The official C# SDK for the Model Context Protocol, enabling .NET applications, services, and libraries to implement and interact with MCP clients and servers.
Note
This repo is still in preview, breaking changes can be introduced without prior notice.
The Model Context Protocol (MCP) is an open protocol that standardizes how applications provide context to Large Language Models (LLMs). It enables secure integration between LLMs and various data sources and tools.
For more information about MCP:
To get started writing a client, the McpClientFactory.CreateAsync
method is used to instantiate and connect an IMcpClient
to a server. Once you have an IMcpClient
, you can interact with it, such as to enumerate all available tools and invoke tools.
var client = await McpClientFactory.CreateAsync(new()
{
Id = "everything",
Name = "Everything",
TransportType = TransportTypes.StdIo,
TransportOptions = new()
{
["command"] = "npx",
["arguments"] = "-y @modelcontextprotocol/server-everything",
}
});
// Print the list of tools available from the server.
await foreach (var tool in client.ListToolsAsync())
{
Console.WriteLine($"{tool.Name} ({tool.Description})");
}
// Execute a tool (this would normally be driven by LLM tool invocations).
var result = await client.CallToolAsync(
"echo",
new() { ["message"] = "Hello MCP!" },
CancellationToken.None);
// echo always returns one and only one text content object
Console.WriteLine(result.Content.First(c => c.Type == "text").Text);
You can find samples demonstrating how to use ModelContextProtocol with an LLM SDK in the samples directory, and also refer to the tests project for more examples. Additional examples and documentation will be added as in the near future.
Clients can connect to any MCP server, not just ones created using this library. The protocol is designed to be server-agnostic, so you can use this library to connect to any compliant server.
Tools can be exposed easily as AIFunction
instances so that they are immediately usable with IChatClient
s.
// Get available functions.
IList<AIFunction> tools = await client.GetAIFunctionsAsync();
// Call the chat client using the tools.
IChatClient chatClient = ...;
var response = await chatClient.GetResponseAsync(
"your prompt here",
new()
{
Tools = [.. tools],
});
Here is an example of how to create an MCP server and register all tools from the current application.
It includes a simple echo tool as an example (this is included in the same file here for easy of copy and paste, but it needn't be in the same file...
the employed overload of WithTools
examines the current assembly for classes with the McpToolType
attribute, and registers all methods with the
McpTool
attribute as tools.)
Starting with a new dotnet console application, add the Microsoft.Extensions.Hosting
and prelease ModelContextProtocol
NuGet packages:
dotnet add package Microsoft.Extensions.Hosting
dotnet add package ModelContextProtocol --prerelease
Then, the replace the code in the Program.cs
file with the following:
using ModelContextProtocol;
using ModelContextProtocol.Server;
using Microsoft.Extensions.Hosting;
using System.ComponentModel;
var builder = Host.CreateEmptyApplicationBuilder(settings: null);
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithTools<EchoTool>();
await builder.Build().RunAsync();
[McpServerToolType]
public class EchoTool
{
[McpServerTool, Description("Echoes the message back to the client.")]
public static string Echo(string message) => $"hello {message}";
}
More control is also available, with fine-grained control over configuring the server and how it should handle client requests.
For example, instead of the code above, you could create a server with the following code in the Program.cs
file:
using ModelContextProtocol.Protocol.Transport;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.Server;
using System.Text.Json;
using System.Text.Json.Nodes;
McpServerOptions options = new()
{
ServerInfo = new() { Name = "MyServer", Version = "1.0.0" },
Capabilities = new()
{
Tools = new()
{
ListToolsHandler = (request, cancellationToken) =>
{
return Task.FromResult(new ListToolsResult()
{
Tools =
[
new Tool()
{
Name = "echo",
Description = "Echoes the input back to the client.",
InputSchema = new JsonObject
{
["type"] = "object",
["properties"] = new JsonObject
{
["message"] = new JsonObject {
["type"] = "string",
["description"] = "The input to echo back."
},
},
["required"] = new JsonArray { "message" }
}.AsValue().GetValue<JsonElement>(),
}
]
});
},
CallToolHandler = (context, cancellationToken) =>
{
if (context.Params?.Name == "echo")
{
if (context.Params.Arguments?.TryGetValue("message", out var message) is not true)
{
throw new McpServerException("Missing required argument 'message'");
}
return Task.FromResult(new CallToolResponse()
{
Content = [new Content() { Text = $"Echo: {message}", Type = "text" }]
});
}
throw new McpServerException($"Unknown tool: '{context.Params?.Name}'");
},
}
},
};
await using IMcpServer server = McpServerFactory.Create(new StdioServerTransport("MyServer"), options);
await server.StartAsync();
// Run until process is stopped by the client (parent process)
await Task.Delay(Timeout.Infinite);
The starting point for this library was a project called mcpdotnet, initiated by Peder Holdgaard Pederson. We are grateful for the work done by Peder and other contributors to that repository, which created a solid foundation for this library.
This project is licensed under the MIT License.