blog
Ottorino Bruni  

How to Build a Model Context Protocol (MCP) Server in C# and .NET with a Real Example

Introduction to Model Context Protocol (MCP) Server

In the last few years, AI and especially Large Language Models (LLMs) have changed the way we build software.

Many modern tools now include AI features: code suggestions in IDEs, natural language commands, automatic documentation, and more.
But as we integrate more AI into apps and developer tools, we face an important challenge:

How can these tools talk to LLMs in a consistent and reliable way?

Different tools use different formats. Each AI model might expect different input. Without a standard, every integration becomes complex and difficult to maintain.

To solve this, Microsoft introduced the Model Context Protocol (MCP) a simple and open way for tools and AI models to communicate.

With MCP, developers can:

  • Send structured context to a model (like source code or a user prompt)
  • Receive clear and consistent outputs
  • Reuse the same model across different tools and platforms

Whether you’re building a code editor, a chatbot, or a custom AI service, MCP helps you connect models to the context they need in a clean and standardized way.

MCP is an open protocol, currently driven by Microsoft, with official documentation available at modelcontextprotocol.io

Why MCP Matters

Building AI-powered features often means connecting tools with external models. Without a shared protocol, every integration requires custom logic, data formats, and special adapters which slows things down.

MCP solves this by providing a plug-and-play architecture. Once you expose your model through MCP, any compatible tool can use it.

Here’s why it matters:

  • Interoperability
    Any tool that speaks MCP can connect to your model server from editors to chatbots
  • Reusability
    One model server can be used across multiple tools without changes
  • Modularity
    Keep your tool interface and model logic completely separate
  • AI Extensibility
    Build your own intelligent services and run them locally or in the cloud

This makes MCP ideal for real-world projects that need flexible and scalable AI integrations — especially when working with custom models or internal tooling.

Getting Started with the MCP C# SDK

To make it easy for developers to implement MCP servers in .NET, Microsoft provides an official open-source SDK:

GitHub: github.com/modelcontextprotocol/csharp-sdk

This SDK allows you to create an MCP-compliant server using familiar ASP.NET Core concepts, especially minimal APIs.

Status: Is it production-ready?

As of now, the SDK is still in early development. Although it is functional and well-documented, it’s important to note:

  • The NuGet package is currently in beta (MCP.Server 0.x.x)
  • The API surface might change in future versions
  • No official statement guarantees long-term support or stability

If you’re planning to use it in production environments, proceed with caution. For experimentation, prototyping, or internal tooling, however, it’s a great place to start.

What Does the SDK Do?

The SDK provides everything you need to build an MCP-compliant server:

  • Middleware for request routing and response formatting
  • Utilities to parse and handle context and prompt inputs
  • Strong typing for model outputs, metadata, and protocol negotiation
  • Extensions like MapMcpServer<T>() to easily define endpoints

This allows you to focus entirely on your model logic, not on the protocol wiring.

How to Configure the MCP Server

You typically use MapMcpServer<T>() in your Program.cs, where T is your custom model context class.

app.MapMcpServer<StarWarsContext>(
    info: new()
    {
        Id = "starwars-server",
        DisplayName = "Star Wars Movie Title Provider",
        ApiVersion = "1.0"
    },
    onCreateContext: (request, cancellationToken) =>
    {
        return new StarWarsContext(request);
    });

Your context class must implement McpModelContext, and define how to handle the model prompt and generate outputs.

In the next section, we’ll build a working example that responds to simple natural language prompts like
“Give me the 4th Star Wars movie” or “What is Episode VI?”

Ready? Let’s build it.

Example: Building an MCP Server with ASP.NET Core Minimal API

Disclaimer: This example is purely for educational purposes. There are better ways to write code and applications that can optimize this example. Use this as a starting point for learning, but always strive to follow best practices and improve your implementation.

Prerequisites

Before starting, make sure you have the following installed:

  • .NET SDK: Download and install the .NET SDK if you haven’t already.
  • Visual Studio Code (VSCode): Install Visual Studio Code for a lightweight code editor.
  • C# Extension for VSCode: Install the C# extension for VSCode to enable C# support.

Step 1 – Create the Minimal API Project

In your terminal:

dotnet new web -n McpStarWarsServer
cd McpStarWarsServer

This will generate a minimal ASP.NET Core web project with a basic Program.cs.

Step 2 – Add the MCP Server SDK

Add the official MCP SDK NuGet package (latest available version):

dotnet add package ModelContextProtocol --prerelease

Note: The SDK is still in beta. Avoid using it in production environments until a stable release is available.

Step 3 – Create the Model Context Class

In this step, we’ll define the tool that will be exposed by the MCP server. Tools in the MCP C# SDK are declared as static classes, with one or more public methods marked using [McpServerTool].

Create a new file called StarWarsTool.cs and add the following code:

using System.ComponentModel;
using ModelContextProtocol.Server;

[McpServerToolType]
public static class StarWarsTool
{
    private static readonly string[] MovieTitles = {
        "Episode I - The Phantom Menace",
        "Episode II - Attack of the Clones",
        "Episode III - Revenge of the Sith",
        "Episode IV - A New Hope",
        "Episode V - The Empire Strikes Back",
        "Episode VI - Return of the Jedi",
        "Episode VII - The Force Awakens",
        "Episode VIII - The Last Jedi",
        "Episode IX - The Rise of Skywalker"
    };

    [McpServerTool, Description("Returns the Star Wars movie title by episode number")]
    public static string GetMovieTitle(int episodeNumber)
    {
        if (episodeNumber >= 1 && episodeNumber <= MovieTitles.Length)
        {
            return MovieTitles[episodeNumber - 1];
        }
        return "Movie not found.";
    }
}

This tool receives an integer input and returns the matching Star Wars movie title. It will be automatically discovered and made available to any MCP client once the server is up and running.

Step 4 – Configure and Run the MCP Server

Now that the tool is defined, we can configure the MCP server to load it and handle incoming requests using standard input/output.

Open your Program.cs and replace its content with the following:

var builder = Host.CreateApplicationBuilder(args);

builder.Logging.AddConsole(options =>
{
    options.LogToStandardErrorThreshold = LogLevel.Trace;
});

builder.Services.AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

await builder.Build().RunAsync();

This setup:

  • Registers the MCP server
  • Enables communication over stdio, which is ideal for integration with editors or LLMs
  • Automatically discovers all tools decorated with [McpServerToolType] from your project assembly

When you run this project with dotnet run, the server will listen for incoming MCP requests over standard input/output.

Step 5 – How to Test the MCP Tool in VSCode?

Once your MCP server is implemented, you can easily test it in Visual Studio Code using the built-in Chat interface with Agent Mode.

To do this, you need to tell VSCode how to launch your MCP server project. This is done using a local configuration file named mcp.json.

Create the .vscode/mcp.json file

If it doesn’t already exist, create a folder called .vscode in the root of your project:

McpStarWarsServer/
├── McpStarWarsServer.csproj
├── Program.cs
├── StarWarsTool.cs
└── .vscode/
    └── mcp.json

Inside .vscode, create a file named mcp.json with the following content:

{
	"servers": {
		"McpStarWarsServer": {
			"type": "stdio",
			"command": "dotnet",
			"args": ["run", "--project", "McpStarWarsServer/McpStarWarsServer.csproj"]
		}
	},
	"inputs": []
}

This configuration tells VSCode how to launch your MCP server:

  • type: “stdio” means the server communicates via standard input/output
  • command: “dotnet” is the executable used to launch the project
  • args defines the dotnet run –project command relative to your project folder

Add the MCP server to VSCode

  1. Open the Command Palette (Ctrl+Shift+P or ⇧⌘P)
  2. Type MCP: Add Server and select your server from the list (McpStarWarsServer)
  3. You should see a message like Connection state: Running in the output panel

Once the server is active, VSCode will automatically discover your tool and make it available in Agent Mode. If you want more information, look at this link.

Try it out

  1. Open the Chat panel in VSCode
  2. Switch to Agent Mode (via the gear icon or dropdown)
  3. You should see your tool listed (e.g. GetMovieTitle)
  4. Try entering a prompt like:
What is episode 5 of Star Wars?

The response should be:

Episode 5 of Star Wars is titled "The Empire Strikes Back"

Conclusion

In this article, we built a working Model Context Protocol (MCP) server in C# using the official SDK. We explored how to:

  • Define a tool using attributes and simple static methods
  • Configure a server using minimal Program.cs setup
  • Register and test the server directly in Visual Studio Code
  • Interact with the server in Agent Mode, enabling a seamless bridge between developer prompts and actionable model logic

The true potential of MCP lies in its ability to standardize how tools and AI models interact — especially in enterprise environments where information is often fragmented across multiple sources.

Here are just a few ideas of how organizations could use MCP:

Security and compliance support
Expose internal best practices, known vulnerabilities, or approval checklists in a standardized, discoverable way via chat.

Internal documentation access
Connect your MCP server to Confluence, SharePoint, or custom company wikis to provide instant answers to “How do I deploy X?” or “What are our coding standards?”

DevOps integration
Build MCP tools that query your Azure DevOps pipelines, check build statuses, or explain deployment stages directly in the IDE.

Code generation and validation
Combine MCP with internal code templates or AI-assisted scaffolding to generate boilerplate code that follows your internal architecture and conventions.

Team onboarding
Use MCP to build agents that guide new developers through projects, tooling, or domain-specific concepts, using company-specific examples and guidelines.

The beauty of MCP is that it makes AI integration modular, discoverable, and reusable. You don’t need to rewrite plugins or duplicate logic for each tool. Once a tool is defined, any MCP-compatible client can use it whether it’s Visual Studio, VSCode, or a future AI assistant.

Have a great and well-deserved break!

If you think your friends or network would find this article useful, please consider sharing it with them. Your support is greatly appreciated.

Thanks for reading!

Discover CodeSwissKnife Bar, your all-in-one, offline Developer Tools from Your Menu Bar

2 thoughts on “How to Build a Model Context Protocol (MCP) Server in C# and .NET with a Real Example

  1. Konstantin

    Is there no other IDE than VS code? How to run it outside VS Code? How to get access to this server if I just run it manually instead of providing dotnet run sequence (which looks awful outside “garage experiments”)? Why you all copy and paste the same article from MS docs without a second thought?

    1. Ottorino Bruni

      Hi Konstantin,

      I used VS Code in the article because it’s free and simple for everyone to follow.
      The goal was just to make a quick test with the library using a Star Wars–themed example.

      Best,
      Otto

Leave A Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.