mcpdotnet 1.2.0.1

dotnet add package mcpdotnet --version 1.2.0.1                
NuGet\Install-Package mcpdotnet -Version 1.2.0.1                
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="mcpdotnet" Version="1.2.0.1" />                
For projects that support PackageReference, copy this XML node into the project file to reference the package.
paket add mcpdotnet --version 1.2.0.1                
#r "nuget: mcpdotnet, 1.2.0.1"                
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
// Install mcpdotnet as a Cake Addin
#addin nuget:?package=mcpdotnet&version=1.2.0.1

// Install mcpdotnet as a Cake Tool
#tool nuget:?package=mcpdotnet&version=1.2.0.1                

⚠️ REPOSITORY MOVED ⚠️

This repository has been adopted as the foundations of the official C# SDK for the Model Context Protocol and moved to https://github.com/modelcontextprotocol/csharp-sdk.

Please use the official repository for all new issues, pull requests, and development. This repository is kept for historical purposes but is no longer actively maintained.


mcpdotnet

NuGet version Build License

Maintainability Rating Reliability Rating Security Rating Bugs Vulnerabilities Coverage

A .NET implementation of the Model Context Protocol (MCP), enabling .NET applications to connect to and interact with MCP clients and servers.

About MCP

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:

Available Packages

Package Description Documentation
mcpdotnet Core MCP implementation for .NET README
McpDotNet.Extensions.AI Integration with Microsoft.Extensions.AI README

Design Goals

This library aims to provide a clean, specification-compliant implementation of the MCP protocol, with minimal additional abstraction. While transport implementations necessarily include additional code, they follow patterns established by the official SDKs where possible.

Features

  • MCP implementation for .NET applications
  • Support for stdio and SSE transports (Clients)
  • Support for stdio transport (Servers)
  • Support for all MCP capabilities: Tool, Resource, Prompt, Sampling, Roots
  • Support for the Completion utility capability
  • Support for server instructions, pagination and notifications
  • Async/await pattern throughout
  • Comprehensive logging support
  • Compatible with .NET 8.0 and later

Getting Started (Client)

To use mcpdotnet, first install it via NuGet:

dotnet add package mcpdotnet

Then create a client and start using tools, or other capabilities, from the servers you configure:

McpClientOptions options = new()
{
    ClientInfo = new() { Name = "TestClient", Version = "1.0.0" }
};
	
McpServerConfig config = new()
{
    Id = "everything",
    Name = "Everything",
    TransportType = TransportTypes.StdIo,
    TransportOptions = new()
    {
        ["command"] = "npx",
        ["arguments"] = "-y @modelcontextprotocol/server-everything",
    }
};
		
var client = await McpClientFactory.CreateAsync(config, options);

// 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);

Note that you should pass CancellationToken objects suitable for your use case, to enable proper error handling, timeouts, etc. This example also does not paginate the tools list, which may be necessary for large tool sets. See the IntegrationTests project for an example of pagination, as well as examples of how to handle Prompts and Resources.

It is also highly recommended that you pass a proper LoggerFactory instance to the factory constructor, to enable logging of MCP client operations.

You can find samples demonstrating how to use mcpdotnet with an LLM SDK in the samples directory, and also refer to the IntegrationTests project for more examples.

Additional examples and documentation will be added as in the near future.

Remember you can connect to any MCP server, not just ones created using mcpdotnet. 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 IChatClients.

// 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],
    });

Getting Started (Server)

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.)

using McpDotNet;
using McpDotNet.Server;
using Microsoft.Extensions.Hosting;
using System.ComponentModel;

var builder = Host.CreateEmptyApplicationBuilder(settings: null);
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithTools();
await builder.Build().RunAsync();

[McpToolType]
public static class EchoTool
{
    [McpTool, 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:

using McpDotNet.Protocol.Transport;
using McpDotNet.Protocol.Types;
using McpDotNet.Server;
using Microsoft.Extensions.Logging.Abstractions;

McpServerOptions options = new()
{
    ServerInfo = new() { Name = "MyServer", Version = "1.0.0" },
    Capabilities = new() 
    {
        Tools = new()
        {
            ListToolsHandler = async (request, cancellationToken) =>
            {
                return new ListToolsResult()
                {
                    Tools =
                    [
                        new Tool()
                        {
                            Name = "echo",
                            Description = "Echoes the input back to the client.",
                            InputSchema = new JsonSchema()
                            {
                                Type = "object",
                                Properties = new Dictionary<string, JsonSchemaProperty>()
                                {
                                    ["message"] = new JsonSchemaProperty() { Type = "string", Description = "The input to echo back." }
                                }
                            },
                        }
                    ]
                };
            },

            CallToolHandler = async (request, cancellationToken) =>
            {
                if (request.Params?.Name == "echo")
                {
                    if (request.Params.Arguments?.TryGetValue("message", out var message) is not true)
                    {
                        throw new McpServerException("Missing required argument 'message'");
                    }

                    return new CallToolResponse()
                    {
                        Content = [new Content() { Text = $"Echo: {message}", Type = "text" }]
                    };
                }

                throw new McpServerException($"Unknown tool: '{request.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);

Roadmap

  • Expand documentation with detailed guides for:
    • Advanced scenarios (Sampling, Resources, Prompts)
    • Transport configuration
    • Error handling and recovery
  • Increase test coverage
  • Add additional samples and examples
  • Performance optimization
  • SSE server support
  • Authentication

License

This project is licensed under the MIT License - see the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net5.0 was computed.  net5.0-windows was computed.  net6.0 was computed.  net6.0-android was computed.  net6.0-ios was computed.  net6.0-maccatalyst was computed.  net6.0-macos was computed.  net6.0-tvos was computed.  net6.0-windows was computed.  net7.0 was computed.  net7.0-android was computed.  net7.0-ios was computed.  net7.0-maccatalyst was computed.  net7.0-macos was computed.  net7.0-tvos was computed.  net7.0-windows was computed.  net8.0 is compatible.  net8.0-android was computed.  net8.0-browser was computed.  net8.0-ios was computed.  net8.0-maccatalyst was computed.  net8.0-macos was computed.  net8.0-tvos was computed.  net8.0-windows was computed.  net9.0 was computed.  net9.0-android was computed.  net9.0-browser was computed.  net9.0-ios was computed.  net9.0-maccatalyst was computed.  net9.0-macos was computed.  net9.0-tvos was computed.  net9.0-windows was computed. 
.NET Core netcoreapp2.0 was computed.  netcoreapp2.1 was computed.  netcoreapp2.2 was computed.  netcoreapp3.0 was computed.  netcoreapp3.1 was computed. 
.NET Standard netstandard2.0 is compatible.  netstandard2.1 was computed. 
.NET Framework net461 was computed.  net462 was computed.  net463 was computed.  net47 was computed.  net471 was computed.  net472 was computed.  net48 was computed.  net481 was computed. 
MonoAndroid monoandroid was computed. 
MonoMac monomac was computed. 
MonoTouch monotouch was computed. 
Tizen tizen40 was computed.  tizen60 was computed. 
Xamarin.iOS xamarinios was computed. 
Xamarin.Mac xamarinmac was computed. 
Xamarin.TVOS xamarintvos was computed. 
Xamarin.WatchOS xamarinwatchos was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages (3)

Showing the top 3 NuGet packages that depend on mcpdotnet:

Package Downloads
OllamaSharp.ModelContextProtocol

Use tools from model context protocol (MCP) servers with Ollama

McpDotNet.Extensions.AI

Microsoft.Extensions.AI integration for the Model Context Protocol (MCP). Enables seamless use of MCP tools as AI functions in any IChatClient implementation.

McpDotNet.Extensions.SemanticKernel

Microsoft SemanticKernel integration for the Model Context Protocol (MCP). Enables seamless use of MCP tools as AI functions.

GitHub repositories (2)

Showing the top 2 popular GitHub repositories that depend on mcpdotnet:

Repository Stars
microsoft/semantic-kernel
Integrate cutting-edge LLM technology quickly and easily into your apps
awaescher/OllamaSharp
The easiest way to use the Ollama API in .NET
Version Downloads Last updated
1.2.0.1 139 4 days ago
1.1.0.1 609 13 days ago
1.0.1.3 7,489 a month ago
1.0.1.1 153 a month ago
1.0.0.1 111 2 months ago
0.10.0.1 95 2 months ago
0.9.0.1 109 2 months ago
0.8.0.1 86 2 months ago
0.7.0.1 85 2 months ago
0.6.0.1 91 2 months ago
0.5.0.1 82 3 months ago
0.3.0.2 114 3 months ago
0.3.0.1 134 3 months ago
0.2.0-alpha1 91 3 months ago
0.1.0-alpha1 105 3 months ago