Build & Leverage MCP Servers in C# for AI-Driven Development

As AI gets to be more pervasive in the software development industry, there is a clear need to bring more contextual intelligence and repeatable confidence to Agentic workflows – Model Context Protocol (MCP) can help. Let’s take a look at how .NET developers can leverage C# to build modern MCP endpoints and utilize them in AI-driven workflows.

The Promise of MCP

It is the age of AI – while AI is evolving most aspects of human interactions, the impact on software is particularly interesting. There is a huge opportunity for developers to infuse apps with solutions powered by generative AI and large/small language models – the end result should be smarter apps and better user experiences. Modern AI is also an opportunity to streamline and automate developer workflows for better productivity – AI can do much of the mundane code writing, freeing up developers to review code and guide architectural decisions. However, despite all the smartness, AI Models struggle with a few foundational challenges – timestamped knowledge, lack of repeatability and missing context are at the top of the list. Modern agentic workflows demand AI Agents perform concrete actions on behalf of developers – context and specialized tools would be key.

Model Context Protocol (MCP) is an industry protocol that standardizes how applications provide context to AI Models/Agents — developers can think of it as a common language for information exchange between AI Models/Agents and custom endpoints with specialized tooling. MCP aims to provide a standardized way to connect AI to different data sources, tools and non-public information. The point is to provide deep contextual information/APIs/data to AI Models/Agents. MCP services also support robust authentication/authorization toward executing specific tasks on behalf of users – security is well thought out. Originally developed by Anthropic, lots of of tech companies and AI stakeholders now participate in further developing the MCP specifications toward global standardization – this is good news for developers looking to extend AI capabilities with reliable and contextual tooling. While early days, there is plenty of excitement around MCP – with a stable yet flexible specification, MCP can play a big role in standardizing information exchange between AI Models/Agents and various data sources for grounded AI usage.

Build MCP Server in C#

For .NET developers excited to start building with MCP, there is great news – the official C# SDK for MCP is here to enable .NET apps, services and libraries to implement/interact with MCP clients and servers. Better still, .NET developers can start building MCP Servers fairly easily using the MCP C# SDK – this is the big benefit bringing in enterprise context and custom tools to AI Agents. Let’s start up a .NET console app and bring in some NuGet dependencies in the .csproj file:

				
					<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>net9.0</TargetFramework>
    <ImplicitUsings>enable</ImplicitUsings>
    <Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
    <PackageReference Include="Microsoft.Extensions.Hosting" Version="9.0.4" />
    <PackageReference Include="ModelContextProtocol" Version="0.1.0-preview.6" />
</ItemGroup>
</Project>
				
			

The ModelContextProtocol package gives developers access to new APIs to create MCP servers, clients that connect to MCP servers and AI helper libraries to integrate with AI Models through Microsoft.Extensions.AI. With an MCP server, developers can expose custom data/APIs or specialized tools that carry out tasks – all within a specific context. Say you want to connect some custom data to AI Agents through an MCP Server – the data could be coming from SQL Server under a table/in the cloud, some entity mapping layer, web services entity or any other custom API. Let’s pretend your custom data/API is JSON Placeholder – the free, fake and reliable API for testing and prototyping. If we look at their /posts API, it represents a random collection of sample fake poats – more importantly, in Latin. If we are to expose this API over MCP, the first step would be write up a class that mimics the data in .NET object form and a PostService class to fire up HTTP calls to fetch the data, before hydrating into a C# collection.

				
					using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;

namespace MyMCP;

public class PostService
{
    private static HttpClient sharedClient = new()
    {
        BaseAddress = new Uri("https://jsonplaceholder.typicode.com"),
    };

    public async Task<List<Post>> GetPosts()
    {
        return await sharedClient.GetFromJsonAsync<List<Post>>("/posts") ?? new List<Post>();
    }
}

public partial class Post
{
    [JsonPropertyName("id")]
    public int ID { get; set; }

    [JsonPropertyName("title")]
    public string? Title { get; set; }

    [JsonPropertyName("body")]
    public string? Body { get; set; }
}
				
			

MCP Servers work by declaring API endpoints or specialized Tools that are exposed up to AI Models/Agents. Here’s a simple Echo tool that relays back a text message – the McpServerToolType attribute makes for the magic glue:

				
					using ModelContextProtocol.Server;
using System.ComponentModel;

[McpServerToolType]
public static class EchoTool
{
    [McpServerTool, Description("Echoes the message back to the client.")]
    public static string Echo(string message) => $"Hello from: {message}";
}
				
			

Next up, let’s wire up an MCP Tool that leverages the PostService to fetch Post data from JSON Placeholder and offer it up as an MCP endpoint, like so:

				
					using System.ComponentModel;
using System.Text.Json;
using ModelContextProtocol.Server;

namespace MyMCP;

[McpServerToolType]
public static class PostDataTool
{
    [McpServerTool, Description("Get a list of sample posts.")]
    public static async Task<string> GetPostSampleData()
    {
        PostService postService = new PostService();
        var posts = await postService.GetPosts();
        if (posts == null || posts.Count == 0 || string.IsNullOrEmpty(posts[0].Title))
        {
            var fallback = new List<Post>
            {
                new Post { ID = 1, Title = "Sample post 1", Body = "This is a fallback sample post." },
                new Post { ID = 2, Title = "Sample post 2", Body = "Another fallback post." }
            };
            return JsonSerializer.Serialize(fallback);
        }

        return JsonSerializer.Serialize(posts);
    }
}
				
			

Lastly, we update the Program.cs in our console app with some scaffolding to create an MCP server, configure standard I/O client-server transport, and ask the MCP server to expose Tools from the running program assembly:

				
					using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using MyMCP;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddSingleton<PostService>();

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

await builder.Build().RunAsync();
				
			

MCP Servers are essentially like API endpoints, and they can work for a folder/workspace/globally. To start, let’s add an mcp.json file in the .vscode folder within the project – this is read by VS Code to find marked tools from the MCP Server. Notice how we name the custom MCP Server and set things up with command/arguments – this one pointing to the local .NET console app executable:

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

Test MCP Server

Once our MCP Server built with C# is all wired up, it is time to test whether things actually work. There is some help before actually offering the MCP Server up to AI – the MCP Inspector is an interactive developer tool for testing and debugging MCP servers. The MCP Inspector is actually a NodeJS app with a React frontend, but it is perfectly good to test our .NET MCP Server. Best thing is, there is nothing to install – we can simply fire up the Inspector and NPX will bring everything down to run:

				
					npx @modelcontextprotocol/inspector
				
			

Once the MCP Inspector is up and running, we can point to our .NET console app that’s now an MCP Server, like so:

Once connected, we can ask the Inspector to find the Tools offered by our MCP Server – notice the discoverability of MCP Tools through the McpServerToolType attribute.

We can send in a parameter and check whether to Echo Tool is working as desired:

And finally, we can invoke the GetPostSampleData tool to make sure it is returning JSON data from our API:

MCP Server for AI

With our MCP Tools working and MCP Server specifications defined in mcp.json, we can now let AI have a crack at it – this is essentially integration of custom data/API/context with AI Agents. For GitHub Copilot, we can open up the chat interface in Agent mode and hit Settings to see the listing of MCP Servers – our custom one shows up in the list along with Tools exposed:

With our custom MCP Server wired up, the Tools can be invoked with corresponding # names in Agentic modes, like so:

We can invoke the #Echo Tool with some parameter and see it working with GitHub Copilot AI Agent running the Tool with user permission:

Next up, let’s use the AI Agent to invoke our #GetPostSampleData Tool – AI permissions can be for each time, for the session or for the whole workspace.

Once run, the MCP Tools makes the HTTP call to the API and pulls back a list of 100 sample posts – GitHub Copilot AI Agent is happy to summarize:

We can get creative in what we want the AI Agent to do with the data – like run the Tool and present the data in tabular format, like so:

Leverage MCP Server in App Building

If the MCP Server and the Tools are global, AI Agents always have access to them – the real benefit of MCP is contextual intelligence for innovative tasks. Let’s say we’re wanting to build a cross-platform .NET app – Uno Platform can take the app to iOS, Android, Windows, macOS, Linux and WebAssembly. We can start from the default template and have a completely blank Uno Platform app – wouldn’t it be nice to have some app UI that shows a list of sample posts from our API? We can hand-code the UI and call the API – or let AI Agents take a stab at code generation.

Turns out, modern AI Agents are smart – based on the structure of the sample Post data, much can be automated including UI creation to show a list of Posts. MainPage is the default first view of our blank Uno Platform app – let’s start with a Prompt for the GitHub Copilot AI Agent:

Granted we’re asking for UI to show a list of Posts, the AI Agent will first invoke the MCP Tool – one can easily envision this being the custom data/API context being surfaced up to AI.

While mileage may vary based on the AI Agent & Models at work, with the data pulled down from MCP Server, you can see the GitHub Copilot Agent trying to analyze the Uno Platform app and figuring out what needs to be done to create the UI to show the list of Posts – most Agents will come up with a plan to execute, with human intervention welcome at any stage.

Next up, the GitHub Copilot Agent creates a Post Model class to mimic data and gets to work creating the list UI – in accordance to what Uno Platform expects.

The GitHub Copilot Agent wires up the UI from code-behind and even includes an event handler to get more info from chosen Post from the list – while experiences vary, quite magical when things work.

Once any issues have been sorted out and the app code builds successfully, we can run the Uno Platform app on chosen mobile/desktop/web form factors – voila, list of Posts powered by custom MCP Server. A simple demo showing a list – but without us having to write any UI code:

One can even click on a sample Post to see the whole details. It is really nice when AI Agents are this productive – all powered by the context exposed by custom MCP Servers and Tools.

Conclusion

Model Context Protocol (MCP) aims to standardize how applications provide context to AI Models and Tools to AI agents. The advent of MCP looks to empower agentic workflows to have secure access to deeply contextual tasks and, in turn, AI workflows that are more predictable and beneficial to everyone. There is plenty of help and inspiration for developers to buid amazing things with MCP – bringing custom data/services/APIs to make AI Agents more contextually intelligent.

Armed with C# SDKs for MCP, .NET developers can easily create MCP Servers and corresponding Tools that surface custom expertise – bring your enterprise data and workflows. And once MCP endpoints are up, AI Agents can invoke MCP Tools as need or when asked for explicitly – with contextual intelligence, AI can do some amazing things.

MCP promises to keep AI Agentic workflows grounded – you coming along for the ride? Cheers developers!

Get Started

With new features like .NET 10 Preview, Visual Studio 2026 support, WebAssembly performance boosts, and Hot Design enhancements, there’s never been a better time to start building with Uno Platform. 

  • Start a new Uno Platform project Follow the Get Started guide 
  • Upgrading from a previous version? Visit the migration guide for steps, breaking changes, and best practices 
  • Want to try the new Hot Design? Test the new features in your own app 

Tags: XAML, WPF, Xamarin, UWP, Silverlight, .NET, Windows, C#, XAML

Related Posts

Uno Platform 5.2 LIVE Webinar – Today at 3 PM EST – Watch