Skip to content

Releases: modelcontextprotocol/csharp-sdk

v0.1.0-preview.4

31 Mar 19:39
4c537ef

Choose a tag to compare

v0.1.0-preview.4 Pre-release
Pre-release

This release introduces the ModelContextProtocol.AspNetCore package for hosting MCP servers in ASP.NET Core applications with SSE transport support.

Breaking Changes

Refer to the C# SDK Versioning documentation for details on versioning and breaking change policies.

  1. Add ModelContextProtocol.AspNetCore #160
    • HttpListenerSseServerTransport removed
    • IServerTransport interface removed
    • MapMcpSse renamed to MapMcp and moved to the new ModelContextProtocol.AspNetCore package

What's Changed

Repository Infrastructure Updates

Acknowledgements

Full Changelog: v0.1.0-preview.3...v0.1.0-preview.4

v0.1.0-preview.3

31 Mar 18:30
330e526

Choose a tag to compare

v0.1.0-preview.3 Pre-release
Pre-release

This release overhauls the resource system, refactors transports for graceful shutdown, introduces prompt support with McpServerPrompt and McpClientPrompt, and adds progress reporting and annotation support.

Breaking Changes

Refer to the C# SDK Versioning documentation for details on versioning and breaking change policies.

  1. Add ToolAnnotations support #124
    • McpServerToolAttribute constructor no longer accepts a positional string; must use Name = "..." instead
  2. Overhaul of Resources #125
    • ResourceContents changed to an abstract class; Text and Blob properties removed
    • Must use TextResourceContents or BlobResourceContents subclasses instead
  3. Add [McpServerPrompt] support #126
    • ListPromptsAsync return type changed
    • GetPromptAsync parameter type changed
    • IMcpServerBuilder namespace moved
    • All With*Handler extension methods deleted
  4. Add missing Annotations #138
    • Annotated abstract record base class deleted
    • Annotations property inlined into Content, Resource, and ResourceTemplate
  5. Refactor transports to help enable graceful shutdown #142
    • McpServerHostedService deleted
    • IClientTransport.ConnectAsync now returns ITransport instead of the previous type
    • StartAsync replaced by RunAsync
  6. Improve progress reporting #145
    • OperationNames class deleted; replaced by RequestMethods

What's Changed

Documentation Updates

Repository Infrastructure Updates

Acknowledgements

Full Changelog: v0.1.0-preview.2...v0.1.0-preview.3

v0.1.0-preview.2

27 Mar 22:35
9330774

Choose a tag to compare

v0.1.0-preview.2 Pre-release
Pre-release

This release overhauls tool handling, makes options types fully mutable, adds logging capability, and improves serialization.

Breaking Changes

Refer to the C# SDK Versioning documentation for details on versioning and breaking change policies.

  1. Overhaul tool handling #89
    • McpToolAttribute renamed to McpServerToolAttribute; McpToolTypeAttribute renamed to McpServerToolTypeAttribute
    • WithTools() renamed to WithToolsFromAssembly()
    • ListToolsAsync return type changed from IAsyncEnumerable<Tool> to Task<IList<McpClientTool>>
    • CallToolAsync parameter changed from Dictionary<string, object> to IReadOnlyDictionary<string, object?>
  2. Make options types fully mutable #107
    • McpClientOptions, Implementation, and all capability types changed from record to class
    • init-only setters changed to set; with expressions on these types will no longer compile
  3. Fix enum serialization #61
    • Role, LoggingLevel, and ContextInclusion enums now use JsonStringEnumConverter with [JsonStringEnumMemberName] instead of [JsonPropertyName]
    • This is a serialization format change; any code depending on the previous serialized form needs to be updated
  4. List tools from DI once #115
    • ServerInstructions property removed from McpServer
    • McpServerHostedService is no longer public

What's Changed

Documentation Updates

Test Improvements

Repository Infrastructure Updates

Acknowledgements

Full Changelog: v0.1.0-preview.1.25171.12...v0.1.0-preview.2

v0.1.0-preview.1.25171.12

21 Mar 21:38
4d61007

Choose a tag to compare

Pre-release

MCP C# SDK

https://www.nuget.org/packages/ModelContextProtocol/0.1.0-preview.1.25171.12

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 is a preview release. Breaking changes can be introduced without prior notice.

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:

Getting Started (Client)

To get started writing a client, the McpClientFactory.CreateAsync method is used to instantiate and connect an IMcpClient
to a server, with details about the client and server specified in McpClientOptions and McpServerConfig objects.
Once you have an IMcpClient, you can interact with it, such as to enumerate all available tools and invoke tools.

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

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 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 ModelContextProtocol;
using ModelContextProtocol.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 ModelContextProtocol.Protocol.Transport;
using ModelContextProtocol.Protocol.Types;
using ModelContextProtocol.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);

License

This project is licensed under the MIT License.