MOFAKH.COM
← Back to profile
MCP Servers

Your first MCP server in C#

Nov 28, 202621 min readWritten

Building HelloMcp, a two-tool MCP server, with the official C# SDK: why that 'SDK' is really just a set of packages, how NuGet picks the right build for your .NET version, what each package is for, how three attributes turn an ordinary method into a tool the model can call, why the description is the most important line in the file, how to connect it to VS Code, and how to prove an answer really came from your code. It ends by opening up the exact JSON the model receives.

Parts 1 and 2 were all vocabulary and flow. This part is all keyboard. By the end you will have a working MCP server on your machine, an AI assistant calling it, and a clear picture of how your C# code turns into the tool list the model reads.

The server is deliberately trivial. It has two tools: one greets a person by name, one rolls a die. There is no data and no security yet. Two tools rather than one, so that you can watch the model choose between them.

What you need

  • The .NET SDK. Anything from .NET 8 up works; the SDK targets .NET 8, 9 and 10. Check with dotnet --version.
  • VS Code with GitHub Copilot Chat, and its Agent mode available. Any other MCP-capable host works too, but the connection steps below are for VS Code.

Step 1: create the project

An MCP server that talks over stdio (Part 4 explains exactly what that means) is just a console app: the host starts it as a program and talks to it through its input and output. So the project starts as a plain console app, created outside any other repository so experiments never end up in a commit:

powershell
mkdir C:\projects\mcp-playground
cd C:\projects\mcp-playground
dotnet new console -n HelloMcp
cd HelloMcp
dotnet add package ModelContextProtocol --version 2.2.0
dotnet add package Microsoft.Extensions.Hosting

If a package command fails with a 401, your machine probably has a private NuGet feed configured that wants a login. Add --source https://api.nuget.org/v3/index.json to the command to fetch from the public feed directly.

Two things called "SDK"

The two dotnet add package lines raise an obvious question. The .NET SDK is already installed, with its compiler. Why is "the MCP C# SDK" needed as well? Is it a second compiler?

No. The word SDK is doing two different jobs:

The .NET SDKThe MCP C# SDK
What it really isA toolkit installed on your machineA library: code someone else wrote, shipped as NuGet packages
What is insideThe dotnet command, the Roslyn compiler, MSBuild, project templates, the .NET runtimeCompiled C# (.dll files) that implements the MCP protocol
How you get itInstalled once per machineAdded per project with dotnet add package
What it doesBuilds and runs any .NET appDoes one job: speaks MCP

A library is a package of code you call. An SDK, software development kit, is the official kit for building on some platform or protocol: usually several libraries plus documentation and samples, maintained as "the" way to do it. The MCP project publishes official SDKs for many languages (TypeScript, Python, Java, C# and more), and each is simply the MCP kit for that language. Microsoft names its Azure client libraries the same way: the "Azure SDK for .NET" is also just a collection of NuGet packages. So "the MCP C# SDK" means a set of packages someone else wrote, which your project uses. Nothing more.

A kitchen is a good picture of it. The .NET SDK is your kitchen: the oven (the compiler), the knives (the dotnet command), the recipe cards (dotnet new console). A package is a ready-made sauce someone else prepared. You still cook in your own kitchen; you just do not make that sauce from scratch.

What the package does for you

Without it, HelloMcp would need hundreds of lines of your own code to:

  1. read lines of JSON from standard input;
  2. parse each JSON-RPC message and match every reply to its request;
  3. answer the greeting a host sends first, and cope with different protocol versions;
  4. build the tool list by inspecting your methods, their parameters and their descriptions;
  5. turn incoming arguments such as "sides": 20 into a call to RollDice(20);
  6. wrap your return value, or your exception, into the reply format;
  7. write the reply to standard output.

The package does all of it, and you write only the tools. It is also why [McpServerTool], [McpServerToolType] and McpException exist at all: they are classes defined inside the package. Remove the package reference and the build fails with "the type or namespace could not be found", because the compiler has never heard of them.

What does not need a package: everything in the base class library that ships with .NET itself, such as Console, Random, HttpClient and collections. Anything beyond that, from MCP to Entity Framework, arrives as a package.

The packages in the kit

The official C# SDK is split into a few packages:

PackageWhat it gives you
ModelContextProtocol.CoreThe protocol itself, for clients and low-level servers, with minimal dependencies
ModelContextProtocolEverything for a server like this one: the attributes, automatic tool discovery, the stdio transport, and hooks into the .NET host. This is the one to start with.
ModelContextProtocol.AspNetCoreA server reached over HTTP, inside an ASP.NET Core app

What happens when you add a package

dotnet add package does three things:

  1. It adds one line to the project file:

    xml
    <PackageReference Include="ModelContextProtocol" Version="2.2.0" />
  2. On the next build, a step called restore downloads the package from nuget.org, the public package store, into a cache in your user folder.

  3. The compiler references the package's .dll files while building your code.

You can look inside that cache. On Windows it is under your user profile, in .nuget\packages:

modelcontextprotocol\2.2.0\lib\
    net8.0\
    net9.0\
    net10.0\           ModelContextProtocol.dll        (about 90 KB)
    netstandard2.0\
modelcontextprotocol.core\2.2.0\lib\net10.0\
                       ModelContextProtocol.Core.dll   (about 1.3 MB)

Two things stand out. First, the package that was added is small, and the real protocol work lives in Core, which was never asked for. NuGet fetched it automatically because the main package depends on it; that is a transitive dependency. Second, one package contains several builds, one per .NET version. That is the key to the next question.

Which build does your project get?

Three version numbers are in play, and mixing them up is the usual source of confusion:

NumberWhere it livesWhat it means
10.0.400 (for example)the .NET SDK on your machineThe toolkit's version. It must be new enough to build your target.
net10.0TargetFramework in the project fileWhich .NET your app runs on
2.2.0the PackageReferenceThe library's own version, unrelated to .NET's numbers

NuGet matches a package to your target framework, not to your installed SDK. HelloMcp targets net10.0, so it got the net10.0 folder. A project targeting net8.0 gets the net8.0 folder from the very same package. When there is no exact match, NuGet picks the closest older build that is compatible:

Project targetsThe package shipsNuGet uses
net8.0net8.0, net9.0, net10.0net8.0
net10.0net8.0, net9.0, net10.0net10.0
net11.0net8.0, net9.0, net10.0net10.0, the closest older one

That last row works because newer .NET runs code built for older .NET; Microsoft keeps that backward compatibility carefully. So moving an app to a newer .NET version rarely breaks its packages, and package authors usually add a build for the new version in a later release anyway.

The other direction is where the risk is. If a future package version ships only for net10.0 and newer, a project still on net8.0 cannot use it: the restore fails with a "not compatible" error, and that project is stuck on the last version that still supported it. Packages tend to drop a .NET version once Microsoft stops supporting it, and .NET 8 and 9 both reached end of support on 10 November 2026. Staying current with .NET is what keeps the newest library versions open to you.

Note to self
The MCP specification has its own version too, written as a date such as 2026-07-28. It moves independently of both .NET and the package: a new specification revision usually brings a new major version of the SDK (version 2 implements the 2026-07-28 revision), while a new .NET version does not force a new SDK version at all.

To check whether a package fits your project, look at the supported frameworks on its NuGet page, or at the folders under lib in your local cache. In the end, dotnet build is the judge: it fails clearly when no compatible build exists.

Why pin a version?

Version 2 of the SDK implements the latest revision of the MCP specification, so prefer it over any tutorial written for version 1. This part pins 2.2.0, the version the project was built with; at the time of writing, NuGet already lists 2.4.0. Pinning is a general good habit rather than anything MCP-specific: without a version, dotnet add package installs whatever is newest today, so two people following the same steps a month apart can end up with different behaviour. Pick a version on purpose, and upgrade on purpose.

Why the Hosting package?

The MCP SDK does not run on its own. It plugs into the .NET Generic Host, the same machinery that sits under every ASP.NET Core app. The host gives the server three things it relies on:

The host providesWhy the MCP server needs it
Dependency injectionThe MCP server registers itself in the service container, and tool classes can receive services through their constructors
LifetimeRunAsync keeps the program alive, listening, until the host application closes it, then shuts down cleanly. Without it, the program would end as soon as Main returned.
Logging and configurationSettings from appsettings.json and environment variables, and loggers you can point wherever you like

The MCP package only depends on the host's abstractions. The ready-made builder, Host.CreateApplicationBuilder, lives in Microsoft.Extensions.Hosting, so a console app adds it explicitly. An ASP.NET Core app would not need to: WebApplication.CreateBuilder already is a host, with a web server attached.

Step 2: Program.cs

Replace the template's Program.cs with:

csharp
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
 
var builder = Host.CreateApplicationBuilder(args);
 
// stdout carries the MCP messages, so every log line must go to stderr instead.
builder.Logging.AddConsole(options => options.LogToStandardErrorThreshold = LogLevel.Trace);
 
builder.Services
    .AddMcpServer()                 // register the MCP server in DI
    .WithStdioServerTransport()     // talk over stdin/stdout
    .WithToolsFromAssembly();       // find every [McpServerToolType] class
 
await builder.Build().RunAsync();

Line by line:

  • Host.CreateApplicationBuilder(args) creates the host builder: services, logging and configuration, all with sensible defaults.
  • The logging line is the first MCP gotcha, and an important one. With stdio, the server's standard output is the channel the MCP messages travel on. A log line written there would land in the middle of the protocol and corrupt it. Setting the threshold to Trace sends every log level to standard error instead. Part 4 explains the two channels properly.
  • AddMcpServer() registers the MCP server in dependency injection.
  • WithStdioServerTransport() chooses how hosts reach it: through standard input and output.
  • WithToolsFromAssembly() tells the SDK to scan this project for tool classes and build the tool list from them. You never write the list by hand.
  • RunAsync() starts everything and keeps it running.

Step 3: the tools

Add a file HelloTools.cs:

csharp
using System.ComponentModel;
using ModelContextProtocol;
using ModelContextProtocol.Server;
 
namespace HelloMcp;
 
[McpServerToolType]
public sealed class HelloTools
{
    [McpServerTool(Name = "say_hello", ReadOnly = true)]
    [Description("Greets a person by name. Use this when the user asks you to say hello to someone.")]
    public static string SayHello(
        [Description("The person's first name, e.g. 'Sam'.")] string name)
        => $"Hello, {name}! This answer came from your own MCP server.";
 
    [McpServerTool(Name = "roll_dice", ReadOnly = true)]
    [Description("Rolls one die and returns the number it lands on. Use this when the user asks for a dice roll.")]
    public static int RollDice(
        [Description("Number of sides on the die, from 2 to 100. Defaults to 6.")] int sides = 6)
    {
        if (sides is < 2 or > 100)
        {
            throw new McpException("sides must be between 2 and 100.");
        }
 
        return Random.Shared.Next(1, sides + 1);
    }
}

A tool is an ordinary C# method with labels on it:

AttributeGoes onTells the SDK
[McpServerToolType]the class"This class contains tools; include it when scanning"
[McpServerTool(Name = ...)]the method"This method is a tool, and this is its name in the tool list"
[Description(...)]the method and each parameterThe text the model reads to decide when to call the tool and what to pass

The parameters become the input schema. string name becomes a required text input called name. int sides = 6 becomes an optional whole number with a default of 6. You will see exactly that in the JSON at the end of this part.

The descriptions are the most important lines in the file. Remember from Part 1: the model never sees your code, only the name and the descriptions. So they say what the tool does, when to use it, and what each parameter means, with an example. You write them; the model reads them. Treat them like an API's documentation, because for the model that is exactly what they are.

A few smaller things worth noticing:

  • Static methods are fine for tools that need nothing else. A tool that needs a service, say a database client, can instead be an instance method, and the class gets that service through its constructor from dependency injection, just like a controller would.
  • throw new McpException(...) sends the message back to the model as a tool error, so it can read why the call failed and react: retry with a valid value, or explain the problem. Use it for bad input the model can fix.
  • sides is < 2 or > 100 is C# pattern matching: a shorter way of writing sides < 2 || sides > 100.
  • ReadOnly = true marks the tool as one that changes nothing. It becomes a hint in the tool list that a host may use, for instance to skip asking the user for permission. It is a hint, not a security control: it protects nothing by itself.

Check that it compiles:

powershell
dotnet build

Step 4: connect VS Code

Open the mcp-playground folder in VS Code and create .vscode/mcp.json:

json
{
  "servers": {
    "hello-mcp": {
      "type": "stdio",
      "command": "dotnet",
      "args": ["run", "--project", "${workspaceFolder}/HelloMcp/HelloMcp.csproj", "--verbosity", "quiet"]
    }
  }
}

This tells VS Code: there is a server called hello-mcp; it speaks stdio; to start it, run this command.

Why --verbosity quiet? Without it, dotnet run can print build messages to standard output before your program even starts, and VS Code would try to read them as MCP messages. It is the same gotcha as the logging line, from the other direction: nothing but MCP messages may reach standard output.

Now start the server. In mcp.json, a small Start link appears above the server's name; alternatively, open the Command Palette and run MCP: List Servers. If the list only shows servers that are already running, look for an entry that shows the locally configured ones.

Three things commonly go wrong here:

  • "Cannot start an MCP server before the session runtime has been created. Send a message first." In recent VS Code versions, a fresh window needs a chat session before it will start MCP servers. Open the chat, send any message, then start the server.
  • Use Agent mode. Only the agent mode passes tools to the model. In a plain chat mode, your tools are simply never offered.
  • Start a new chat after starting the server. A chat that was opened before the server was running can keep an out-of-date tool list. Either start a new chat or open the chat's tools picker and make sure the server's tools are ticked.

Step 5: try it

In a new chat, in Agent mode, try:

  1. "Say hello to Sam"
  2. "Roll a 20-sided die"
  3. "Roll a 500-sided die"

The first should call say_hello, the second roll_dice. The third is the interesting one: your tool throws, the model receives "sides must be between 2 and 100.", and it reacts, usually by explaining the limit or rolling a 100-sided die instead. That is the loop from Part 2 handling a failure.

Notice that you did not pick any agent. The default agent ran, and it was offered every running server's tools, including yours.

Proving the answer came from your server

When it works, it is fair to wonder whether the model just made the answer up. Four ways to check:

  1. The text is yours. "This answer came from your own MCP server" is the exact string your SayHello method returns. The model did not invent it.
  2. Expand the steps. The chat shows something like "Completed 2 steps"; expanding it shows the say_hello call, its input, and your server's output.
  3. Read the server's log. Open the Output panel and choose the server's channel (MCP: hello-mcp). You will see the host start the server, ask for its tools (tools/list), and then call one (tools/call). VS Code labels all of these as warnings, only because they arrive on standard error; they are ordinary information messages.
  4. Switch it off. Stop the server, start a new chat, and ask the same question. Without the tool, the model answers by itself, and your sentence is gone.

Under the hood: the tool list

When the host asks for the tool list, this is what your server sends back (shortened):

json
{
  "tools": [
    {
      "name": "say_hello",
      "description": "Greets a person by name. Use this when the user asks you to say hello to someone.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "name": { "type": "string", "description": "The person's first name, e.g. 'Sam'." }
        },
        "required": ["name"]
      },
      "annotations": { "readOnlyHint": true }
    },
    {
      "name": "roll_dice",
      "description": "Rolls one die and returns the number it lands on. Use this when the user asks for a dice roll.",
      "inputSchema": {
        "type": "object",
        "properties": {
          "sides": { "type": "integer", "default": 6, "description": "Number of sides on the die, from 2 to 100. Defaults to 6." }
        }
      },
      "annotations": { "readOnlyHint": true }
    }
  ]
}

Put it next to the C#:

In your codeIn the tool list
Name = "say_hello""name": "say_hello"
[Description] on the method"description"
string name, no defaulta string property, listed under "required"
int sides = 6an integer property with "default": 6, not required
[Description] on a parameterthat property's "description"
ReadOnly = true"readOnlyHint": true

This JSON, together with your prompt, is what the host sends the model in step 1 of the loop. You wrote ordinary C#, and the SDK turned it into this.

Common questions

The .NET SDK with its compiler is already installed. Why is another SDK needed? You don't need another compiler. "The MCP C# SDK" is a set of NuGet packages: code someone else wrote that speaks the MCP protocol, which your code calls. "SDK" is just the name for an official kit of libraries for a platform or protocol.

Is adding a package about finding one that matches the installed .NET SDK? Not quite. NuGet matches a package to your project's target framework (such as net10.0), picking the package's build for that version or the closest older one. Your installed SDK only has to be new enough to build that target.

After a move to a newer .NET, will the MCP packages still work? Almost always: a newer .NET can use a package's builds for older versions, and authors add builds for new versions over time. The risk runs the other way: staying on an old .NET version means eventually being stuck on old package versions, once new releases drop it.

Why pin the SDK version at all? So the build is repeatable. Without a version you get whatever is newest on the day you run the command, and the behaviour can change underneath you. Upgrade on purpose instead.

Why does a console app need the Hosting package? Because the MCP server plugs into the .NET host for dependency injection, lifetime and logging. The ready-made host builder lives in that package. A web app gets the host built in.

There is no Start button. Where is the server? Run MCP: List Servers from the Command Palette and look for the locally configured servers. If starting fails with "send a message first", open a chat and send any message, then start it again.

No agent was selected. How did the tool get used? The default agent is offered the tools of every running server. You only pick a custom agent when you want different instructions or a narrower set of tools.

Does ReadOnly = true stop a tool from changing anything? No. It is a hint to the host about how careful to be. If a tool must never change data, its code must not change data.

What happens when a tool throws? An McpException goes back to the model as a tool error with your message, and the model decides what to do next. That is why the message should say what was wrong and what would be valid.

Sources