3 min to read
Creating a Model Context Protocol (MCP) server in C# enables seamless integration between AI systems and applications by standardizing communication. This guide walks you through everything from initial setup to advanced tool implementation using the official C# SDK.
Model Context Protocol (MCP) is an open standard designed to support context-aware communication between AI models and external systems. Its modular architecture allows developers to:
Since its release by Anthropic in 2024, MCP has gained rapid adoption, with Microsoft integrating it into their AI toolchain and releasing the official ModelContextProtocol C# SDK.
Before you begin building your MCP server, ensure you have the following:
dotnet add package ModelContextProtocol --prerelease
dotnet add package Microsoft.Extensions.Hosting
Create and initialize a new console application:
dotnet new console -n McpDemoServer
cd McpDemoServer
Configure the project file (McpDemoServer.csproj
) with appropriate settings:
<PropertyGroup>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<LangVersion>latest</LangVersion>
</PropertyGroup>
Edit Program.cs
to set up the base MCP server:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;
var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(options =>
options.LogToStandardErrorThreshold = LogLevel.Trace);
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
AddMcpServer()
: Initializes the MCP server infrastructureWithStdioServerTransport()
: Enables communication via standard I/OWithToolsFromAssembly()
: Automatically registers tools from the assemblyCreate a new file Tools/ExampleTools.cs
:
using ModelContextProtocol.Server;
using System.ComponentModel;
[McpServerToolType]
public static class DemoOperations
{
[McpServerTool(Description = "Converts text to uppercase")]
public static string Uppercase(string input)
=> input.ToUpperInvariant();
[McpServerTool(Description = "Generates Fibonacci sequence")]
public static IEnumerable<long> Fibonacci(int count)
{
long a = 0, b = 1;
for (int i = 0; i < count; i++)
{
yield return a;
(a, b) = (b, a + b);
}
}
}
For HTTP-based communication and database integration:
builder.Services.AddMcpServer()
.WithHttpServerTransport("https://localhost:5000/mcp")
.WithJwtAuthentication();
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlServer(configuration.GetConnectionString("Default")));
[McpServerTool]
public class UserTools(AppDbContext context)
{
[Description("Gets user by ID")]
public User? GetUser(Guid id)
=> context.Users.Find(id);
}
var client = new McpClient(new HttpTransport("http://localhost:5000/mcp"));
var response = await client.InvokeMethodAsync(
"Uppercase", new { input = "test message" });
Console.WriteLine(response); // Output: TEST MESSAGE
curl -X POST http://localhost:5000/mcp/tools/Uppercase \
-H "Content-Type: application/json" \
-d '{"input":"hello world"}'
[Fact]
public async Task Uppercase_ReturnsCapitalizedString()
{
using var host = await StartTestServer();
var client = host.GetMcpClient();
var result = await client.InvokeMethodAsync("Uppercase", new { input = "test" });
Assert.Equal("TEST", result);
}
services.AddMcpServer()
.WithOptimizedBinaryTransport()
.WithConnectionPooling(100);
Problem | Solution |
---|---|
Tools not appearing | Ensure [McpServerToolType] is on the parent class |
Serialization errors | Use record types for complex data |
Connection timeouts | Check port/firewall rules |
Version conflicts | Pin the ModelContextProtocol package version |
services.AddMcpServer()
.WithVersioning(v =>
{
v.AddEndpoint("v1", api => api.WithToolsFromAssembly());
v.AddEndpoint("v2", api => api.WithNewFeatures());
});
.WithHttpServerTransport("http://*:5000")
.WithGrpcServerTransport("http://*:5001")
var kernel = Kernel.CreateBuilder()
.AddMcpPlugin("http://localhost:5000/mcp")
.Build();
Building an MCP server in C# provides a solid foundation for scalable, secure AI integration. With the ModelContextProtocol SDK, you can expose AI tools, handle large request volumes, and ensure long-term maintainability.
Whether you're building internal tools or customer-facing AI solutions, MCP is a powerful protocol to include in your stack.
Connect with top remote developers instantly. No commitment, no risk.
Tags
Discover our most popular articles and guides
Running Android emulators on low-end PCs—especially those without Virtualization Technology (VT) or a dedicated graphics card—can be a challenge. Many popular emulators rely on hardware acceleration and virtualization to deliver smooth performance.
The demand for Android emulation has soared as users and developers seek flexible ways to run Android apps and games without a physical device. Online Android emulators, accessible directly through a web browser.
Discover the best free iPhone emulators that work online without downloads. Test iOS apps and games directly in your browser.
Top Android emulators optimized for gaming performance. Run mobile games smoothly on PC with these powerful emulators.
The rapid evolution of large language models (LLMs) has brought forth a new generation of open-source AI models that are more powerful, efficient, and versatile than ever.
ApkOnline is a cloud-based Android emulator that allows users to run Android apps and APK files directly from their web browsers, eliminating the need for physical devices or complex software installations.
Choosing the right Android emulator can transform your experience—whether you're a gamer, developer, or just want to run your favorite mobile apps on a bigger screen.
The rapid evolution of large language models (LLMs) has brought forth a new generation of open-source AI models that are more powerful, efficient, and versatile than ever.