Build Your First MCP Server in C#

Build Your First MCP Server in C#

in

The ability to build your own AI tools has been moving just as fast as the AI capabilities and models themselves. Not too long ago LLMs like Claude and ChatGPT could only give you output that you would have to manually do something with outside of the chat application. Or you’d have to paste in any outside data into the chat if you wanted it to use it for any insights. With MCP you can now make the LLMs act on your behalf to read and even write data to your own applications.

In this post, you will learn how to create an MCP server with several tools, how to test them, and use them in Claude. We will be creating an MCP server that uses the Bored API, which gives suggestions of things to do if you’re bored. The full code is on GitHub. This post will assume .NET 11 is used and Node version 24.11.0. It also assumes using Visual Studio 2026 and Claude Desktop.

What is MCP?

MCP, or Model Context Protocol, is a standard protocol to interact with AI applications to expose specific capabilities that the AI application doesn’t have access to. LLMs are powerful, but without using an MCP, they can’t check your email or update a Google doc for you. Some may describe MCP as the “USB-C for AI tools”. Currently, there’s one protocol (USB-C) that can be used for many applications (charging devices, dock connections, etc.). But, before USB-C was standard you may have needed several different cables. A Lightning cable for charging Apple devices, USB Micro and USB Mini for different devices, and HDMI or Display Port for monitors.

Create the Project and MCP Setup

For the MCP server we will begin by creating a new console project and will give it a name of “BoredMCP”.

dotnet new console -n BoredMCP

With that created, we would need to change the directory to the new one to add packages to it.

cd BoredMCP

For the packages, we will add the following:

  • Microsoft.Extensions.Hosting - The main package that handles dependency injection, configuration, and logging.
  • Microsoft.Extensions.Http - Extension package to allow the use of injecting the HttpClient.
  • ModelContextProtocol - Package that enables the use of creating MCP servers.
dotnet add package Microsoft.Extensions.Hosting
dotnet add package Microsoft.Extensions.Http
dotnet add package ModelContextProtocol

With these installed, we can start building our MCP server. The first thing is to update Program.cs by adding the below to create the application builder and run it.

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

var builder = Host.CreateApplicationBuilder(args);

await builder.Build().RunAsync();

With the MCP we can add some services after we instantiate the builder.

  • AddMcpServer adds the MCP SDK server services.
  • WithStdioServerTransport adds the ability to use the standard input/output for communication to the MCP protocol.
  • WithToolsFromAssembly registers all MCP tools from the current assembly.
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

But there’s an additional setting we need to do for our logging. We need to set all logs to go to standard error. This is because the MCP protocol uses standard output for communication and if anything else goes to it, then it won’t know what to do and may crash or just fail to parse messages.

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

Next, since we know we will be calling an API and injecting the HttpClient, we need to add the HTTP client and we can add the base address of our API so we don’t always have to use it during each tool method. This will have a compile error since we haven’t created the RandomActivityTool class yet.

builder.Services.AddHttpClient<RandomActivityTool>(client =>
    client.BaseAddress = new Uri("https://bored-api.appbrewery.com/"));

Our MCP server is now set up. Let’s create our first tool for the Bored API.

Creating the First Tool

The Bored API gives us a couple of endpoints we can use:

  • A random activity - Returns a random single activity.
  • Filtered by type or participants - Returns a collection of activities and takes in a type (education, social, relaxation, etc.) and the number of participants.

The first one we’ll create will be the random activity endpoint at https://bored-api.appbrewery.com/random. If we go to that endpoint we will get something like this response:

{
  "activity": "Organize a bookshelf",
  "availability": 0,
  "type": "busywork",
  "participants": 1,
  "price": 0,
  "accessibility": "Few to no challenges",
  "duration": "minutes",
  "kidFriendly": true,
  "link": "",
  "key": "6098037"
}

This response will tell us how to create our Activity object. However, the activity itself, let’s have it be a bit more descriptive in the property, so we can name it ActivityDescription. For it to deserialize correctly, we can use the JsonPropertyName attribute as activity. We will do the same with the kidFriendly property.

public class Activity
{
    [JsonPropertyName("activity")]
    public required string ActivityDescription { get; set; }
    public float Availability { get; set; }
    public required string Type { get; set; }
    public int Participants { get; set; }
    public float Price { get; set; }
    public string? Accessibility { get; set; }
    public string? Duration { get; set; }
    [JsonPropertyName("kidFriendly")]
    public bool IsKidFriendly { get; set; }
    public string? Link { get; set; }
    public string Key { get; set; }
}

To create the tool for the random activity, we will first create a new file in the project called RandomActivityTool.cs. The MCP SDK uses attributes to find the tools - McpServerToolType for the class and McpServerTool for the method. Each method is a tool, so our first method will be called GetRandomActivityAsync. There’s also the Description attribute added. Not only does this act like a code comment and self-documents what the method does, this is also used for the LLM to determine how it can use the tool.

[McpServerToolType]
public class RandomActivityTool()
{
    [McpServerTool]
    [Description("Returns a random activity")]
    public async Task<Activity> GetRandomActivityAsync()
    {
    }
}

We are using the Bored API so we need a way to call it. We can inject an HttpClient object.

[McpServerToolType]
-public class RandomActivityTool()
+public class RandomActivityTool(HttpClient client)
{
    [McpServerTool]
    [Description("Returns a random activity")]
    public async Task<Activity> GetRandomActivityAsync()
    {
    }
}

Then we can use it like a regular HTTP call by using the GetAsync method to the endpoint, reading the content as a string, and returning the deserialized JSON response as the Activity object.

[McpServerToolType]
public class RandomActivityTool(HttpClient client)
{
    [McpServerTool]
    [Description("Returns a random activity")]
    public async Task<Activity> GetRandomActivityAsync()
    {
+       var response = await client.GetAsync("random");

+       var jsonResponse = await response.Content.ReadAsStringAsync();

+       return JsonSerializer.Deserialize<Activity>(jsonResponse)!;
    }
}

This can now be run and we get the usual output from the server indicating it’s waiting for requests.

MCP Console Output

But how can we test out our MCP? For this we need to use the MCP inspector.

Testing with the MCP Inspector

The MCP inspector is a package from NPM, so we can use npx to execute it for us to use.

npx @modelcontextprotocol/inspector 

Once that downloads (you may need to confirm it to download) it will open up a web page.

MCP Inspector Page

From here we would add a server manually.

MCP Add Server

That pops up a modal to add details of your MCP server. All that is required are:

  • Server ID - The unique key for the inspector to use,
  • Transport - What transport the MCP server uses for communication,
  • Command - The actual command to run your MCP server.

Optionally, this is also where to add any additional arguments to start your MCP server, any environment variables that it needs, and if the working directory is different than the one where the command was started from in the terminal.

Add MCP Details

For our details we will use:

  • bored-mcp as our server ID
  • stdio (standard input/output) as our transport since we’re running a local process
  • The command will be dotnet and we will have the full path to our DLL as the argument. The DLL will be in the bin\Debug\net11.0 folder where the project is in. If you are using .NET 10 it will be in the net10.0 folder instead of net11.0.

MCP Add Server Details

With that added, we can save it and it now shows on the list of MCP servers to connect to. Next, connect to it to make sure it starts up correctly through the inspector.

MCP Connect to Server

If we try to connect to it here it fails. However, if you run the same command - dotnet "C:\Code\BoredMCP\bin\Debug\net11.0\BoredMCP.dll" - in the terminal it starts up. What’s going on here?

MCP Server Startup Error

What’s happening is that if we run the command with quotes around the DLL file in the terminal, the terminal strips away the quotes before executing. The quotes were there since it was copied from the Windows “Copy as Path” menu item. When it’s in the argument for the MCP server there’s no terminal run so it’s running as the quotes are part of the file path it can’t find it. The fix is to simply remove the quotes. This can be done with the Edit button. It should now look like this when trying to reconnect.

MCP Server Connected

Once it’s connected, you’ll see a Tools tab at the top of the screen. Click on that and you’ll be taken to a screen that shows the tools available for the connected MCP servers. Here, you will see the get_random_activity tool we created.

Note that the MCP SDK converts the GetRandomActivityAsync method to get_random_activity.

MCP Inspector Tools

We can now test out our new tool! Click on the tool name and we can execute the tool to see the output. But it seems like we get an error when we execute it.

MCP Tool Error

The error is specific and is about how the API is getting called.

"get_random_activity" threw an unhandled exception.
      System.InvalidOperationException: An invalid request URI was provided. Either the request URI must be an absolute URI or BaseAddress must be set.

To see what is going on, we would need to debug our MCP server.

Debug the MCP Server

You may first think, “how can we debug this if the MCP inspector is executing the DLL or EXE?”. We can actually use an old feature of Visual Studio - Attach to Process. You can find it in the Debug menu item. For JetBrains Rider, there’s a similar feature in the Run menu. For VS Code, you would need to create a launch.json entry.

Attach to Process

From there we need to pick what process is running to attach the debugger to. Since we’re running the dotnet command in the MCP inspector we will attach to that process.

Attach to dotnet

If you run the EXE in the MCP inspector, then you would attach to that process instead.

With the process attached, we can set a breakpoint and execute the tool again. The breakpoint should hit and we can see what the issue is. With the breakpoint hit, we can now look at the client object to see what’s going on there to cause the call to fail.

Null Client

It seems the BaseAddress for the client is null which is causing the failure. But we set it in the Program.cs file when registering the service. The MCP SDK activates tool classes differently. It asks the dependency injection for a bare HttpClient, which resolves the default unnamed client with no BaseAddress. To fix this, we would give it a named HttpClient.

So in the Program.cs file, we would update the HttpClient injection by passing in a name for the client - bored.

-builder.Services.AddHttpClient<RandomActivityTool>(client =>
+builder.Services.AddHttpClient("bored", client =>
    client.BaseAddress = new Uri("https://bored-api.appbrewery.com/"));

And in the RandomActivityTool file, we would update the injection to bring in the IHttpClientFactory type.

-public class RandomActivityTool(HttpClient client)
+public class RandomActivityTool(IHttpClientFactory httpClientFactory)

Then we can use the new httpClientFactory object in the GetRandomActivityAsync method to make the API call. We can also clean up the deserialization by using the GetFromJsonAsync method which will automatically deserialize the JSON response into our Activity object.

-var response = await client.GetAsync("random");

-var jsonResponse = await response.Content.ReadAsStringAsync();

-return JsonSerializer.Deserialize<Activity>(jsonResponse)!;

+var client = httpClientFactory.CreateClient("bored");

+return await client.GetFromJsonAsync<Activity>("random");

With that fix, we can rebuild so the MCP inspector gets the latest changes and will now return a response.

Random Activity Response

If you’re getting the below error make sure the MCP inspector is not running as that can still keep the dotnet process running, even if the server is disconnected.

Unable to copy file "obj\Debug\net11.0\BoredMCP.dll" to "bin\Debug\net11.0\BoredMCP.dll". The process cannot access the file 'C:\Code\BoredMCP\bin\Debug\net11.0\BoredMCP.dll' because it is being used by another process.

With that running, we can now connect it to Claude and see it in action there.

Connect to Claude Desktop

To connect the local MCP server to Claude Desktop, go to the settings page. Then to Desktop app on the left navigation. Then all the way down click on Manage for the Extensions section.

Claude Desktop Settings

From there, click to edit the local MCP servers config. This will open a file browser to the Claude Desktop location. Open the claude_desktop_config.json file in a text editor.

Edit Config

Depending on your Claude Desktop settings it may be a small file or may have a lot in it. If there isn’t yet a top-level mcpServers object, add it in the file.

{
    "mcpServers": {

    }
}

Then in here you can add any local MCP servers. The name of the object is the name of the MCP server that will display in Claude Desktop. For ours, we will use bored.

{
    "mcpServers": {
        "bored": {

        }
    }
}

Next, it needs to have a command key value pair and, if needed, an args string array. It will be the same as we input for the MCP inspector. Our command will be dotnet and our one arg will be the full path of the DLL file. Since our path is in a JSON file it will need to have double back slashes for it to read.

{
    "mcpServers": {
        "bored": {
            "command": "dotnet",
            "args": [
                "C:\\Code\\BoredMCP\\bin\\Debug\\net11.0\\BoredMCP.dll"
            ]
        }
    }
}

In order for Claude Desktop to run this, we would need to fully exit out of Claude. Which means we would need to right click on it from the system tray and click to exit and restart the application. Once that’s done you can see if it’s running by clicking on the + then going to Plugins and our bored plugin should show with the switch on.

Claude Plugins

Now we can see if it’s working. We can give it a prompt “I’m bored, can you recommend me a task to do?”. Claude should automatically notice we have a tool for it and will use it.

Bored Random Activity from Prompt

Similar to the MCP inspector, if you try to build the solution with the tool being used in Claude Desktop, it won’t build since the DLL is being used. You would need to close Claude completely in order to build.

Add a Parameterized Tool

Now that the testing of our MCP server is working correctly, we can add to it. For the next endpoint we can add parameters that the endpoint can use to make the call. The endpoint can take in a specific type of activity, such as education or charity as well as the number of participants that would be involved. For example, we can search on activities with the type of “education” and the number of participants as “1”.

https://bored-api.appbrewery.com/filter?type=education&participants=1
[
    {
        "activity": "Learn Express.js",
        "availability": 0.25,
        "type": "education",
        "participants": 1,
        "price": 0.1,
        "accessibility": "Few to no challenges",
        "duration": "hours",
        "kidFriendly": true,
        "link": "https://expressjs.com/",
        "key": "3943506"
    },
    {
        "activity": "Learn to greet someone in a new language",
        "availability": 0.2,
        "type": "education",
        "participants": 1,
        "price": 0.1,
        "accessibility": "Few to no challenges",
        "duration": "minutes",
        "kidFriendly": true,
        "link": "",
        "key": "4704256"
    },
    {
        "activity": "Learn a new programming language",
        "availability": 0.25,
        "type": "education",
        "participants": 1,
        "price": 0.1,
        "accessibility": "Few to no challenges",
        "duration": "hours",
        "kidFriendly": true,
        "link": "",
        "key": "5881028"
    }
  ]

Adding the new tool is adding a new method under GetRandomActivityAsync which we’ll call GetActivitiesByFilter. This has two arguments, type and participants. The participants argument is marked as optional with the ? and setting a default to null. We use the Description attribute here again, as well.

[McpServerTool]
[Description("Returns a random activity of a specified type and number of participants, if available")]
public async Task<List<Activity>> GetActivitiesByFilter(string type, int? participants = null)
{

}

Now we can do something similar to the previous tool and create the client by name.

var client = httpClientFactory.CreateClient("bored");

Then, we can add on the filter query parameter. Before we do that, though, we make sure the type is escaped correctly. For example, if the user adds a type of “arts & crafts” it could go in as “filter?type=arts” with the “crafts” being left out. This will prevent that and will be sent as “filter?type=arts%20%26%20crafts”.

var escapedType = Uri.EscapeDataString(type);

var apiString = $"filter?type={escapedType}";

If the participants argument is not null, we can use that to add to the API string.

if(participants.HasValue)
{
    apiString += $"&participants={participants.Value}";
}

With that built, we can make the API call.

return await client.GetFromJsonAsync<List<Activity>>(apiString);

We can build this and do a quick test in the MCP inspector.

Filter Activities

And we can also test in Claude Desktop.

Claude Filter Activities


In this post, we went over what MCP servers are and how to create one with C# by creating a few different tools. Then we tested it with the MCP inspector and in Claude Desktop. As an exercise, feel free to add the third endpoint where it returns an activity by a specific key and test it inside of Claude Desktop. In the next post for MCP servers, we will go over how to use resources and prompts in our MCP server.