Using the Model Context Protocol (MCP) with C#

Information AI .NET MCP C#

With the new MCP C# SDK, developers can efficiently manage communication between AI models and applications. 

Anthropic’s Model Context Protocol (MCP) is currently making waves. It's a standardized protocol designed to streamline communication between applications and models by offering a structured way to exchange context and data between AI models and their clients.

Whether you're developing AI-powered applications or integrating multiple models into a cohesive system, MCP ensures interoperability and scalability. For developers using tools like Visual Studio, MCP servers can now be integrated into your development workflow — making it easier to build and test MCP servers locally.

With the release of the MCP C# SDK, developers can now create both servers and clients that utilize this protocol. The SDK significantly simplifies the implementation process, allowing you to focus on the unique features of your application instead of dealing with the complexities of protocol handling.

In addition, the SDK supports working with MCP servers, enabling developers to build robust client applications that seamlessly interact with them. In a blog post, Microsoft demonstrates how to use the C# SDK to build your own MCP server and client applications.

To get started with building a MCP server, the MCP C# SDK is available as a NuGet package, which you can add to a simple console application:

dotnet new console -n MyFirstAppWithMCP

Next, add some essential NuGet packages for the MCP C# SDK and host the server using Microsoft.Extensions.Hosting:

dotnet add package ModelContextProtocol --prerelease
dotnet add package Microsoft.Extensions.Hosting

The ModelContextProtocol package provides access to new APIs for creating clients that connect to MCP servers, building MCP servers themselves, and integrating LLMs via the Microsoft.Extensions.AI library.


Build a Kernel with OpenAI Chat Completion Example:

// Prepare and build kernel
var builder = Kernel.CreateBuilder();
builder.Services.AddLogging(c => c.AddDebug().SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Trace));
builder.Services.AddOpenAIChatCompletion(
    modelId: config["OpenAI:ChatModelId"] ?? "gpt-4o",
    apiKey: config["OpenAI:ApiKey"]!);
Kernel kernel = builder.Build();