3 min to read
Creating an MCP (Model Context Protocol) server with .NET involves several steps, from setting up your project environment to defining tools that expose functionalities to AI clients.
This guide walks you through the complete process of building a robust MCP server using C#, leveraging the official MCP C# SDK, and integrating best practices for development, debugging, and deployment.
The Model Context Protocol (MCP) is a protocol that allows AI models—such as large language models (LLMs)—to interact with external tools and data sources securely and efficiently. An MCP server exposes a set of "tools" (functions or APIs) that AI clients can invoke to perform operations like fetching data, running computations, or accessing external services.
By building an MCP server in .NET, you create a backend service in C# that enables AI assistants to extend their capabilities by invoking tools from your server.
.NET (C#) is a great choice for developing MCP servers thanks to its performance, stability, and mature tooling. The MCP C# SDK is available on NuGet as a prerelease package.
dotnet add package ModelContextProtocol --prerelease
dotnet add package Microsoft.Extensions.Hosting
dotnet add package Microsoft.Extensions.Logging
dotnet new console -n MyMcpServer
cd MyMcpServer
In Program.cs
, set up logging, transport, and tool registration:
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(consoleLogOptions =>
{
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
await builder.Build().RunAsync();
Tools are methods exposed to AI clients. Each tool must be decorated with the appropriate MCP attributes.
using System.ComponentModel;
using ModelContextProtocol.Server;
[McpServerToolType]
public static class EchoTool
{
[McpServerTool, Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"Hello from C#: {message}";
[McpServerTool, Description("Echoes in reverse the message sent by the client.")]
public static string ReverseEcho(string message) => new string(message.Reverse().ToArray());
}
You can implement tools that call external services.
using System.Net.Http;
using System.Threading.Tasks;
using System.ComponentModel;
using ModelContextProtocol.Server;
[McpServerToolType]
public class JokeTool
{
private readonly HttpClient _httpClient;
public JokeTool()
{
_httpClient = new HttpClient
{
BaseAddress = new Uri("https://v2.jokeapi.dev/joke/")
};
}
[McpServerTool, Description("Fetches jokes from a specified category.")]
public async Task<string> GetJoke(
[Description("Category of jokes (e.g., 'Programming', 'Misc', 'Christmas').")] string category,
[Description("Number of jokes to retrieve, default is 10.")] int amountOfJokes = 10)
{
try
{
var response = await _httpClient.GetAsync($"{category}?amount={amountOfJokes}");
return await response.Content.ReadAsStringAsync();
}
catch
{
return "Error fetching jokes.";
}
}
}
dotnet run
Your MCP server will start and communicate via standard input/output (studio).
To expose your MCP server via HTTP:
builder.Services
.AddMcpServer()
.WithHttpServerTransport()
.WithToolsFromAssembly();
Then, map the endpoint:
app.MapMcpSse(); // SSE endpoint for MCP
Add the following to your .csproj
file:
<PublishContainer>true</PublishContainer>
<ContainerImageName>yourdockerhubusername/mcpserver</ContainerImageName>
<ContainerBaseImage>alpine</ContainerBaseImage>
<RuntimeIdentifiers>linux-x64;linux-arm64</RuntimeIdentifiers>
Publish the container:
dotnet publish /t:PublishContainer -p ContainerRegistry=docker.io
[Description]
attributes thoroughly.To build a fully functional MCP server in .NET:
This architecture empowers AI applications to call your server securely and intelligently making your systems more powerful, automated, and AI-ready.
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.