Mirror of https://github.com/modelcontextprotocol/csharp-sdk — The official C# SDK for Model Context Protocol servers and clients. Maintained in collaboration with Microsoft.
  • C# 99.8%
  • JavaScript 0.2%
Find a file
Repository files (latest commit first)
Filename Latest commit message Latest commit date
Mehran Davoudi 15d1271212
Add ElicitAsync<T> (#630) (#715)
* Add ElicitAsync<T> (#630)

- Refactored `ElicitResult` to a generic class `ElicitResult<T>` for typed content.
- Added `ElicitAsync<T>` method in `McpServerExtensions.cs` to request user input and construct schemas based on type `T`.
- Implemented schema building logic to handle primitive types and enums, ignoring unsupported types.
- Introduced `ElicitationTypedTests.cs` for testing the new elicitation functionality with typed forms.
- Verified naming policies in tests to ensure correct serialization casing.
- Defined `SampleForm` and `CamelForm` classes for expected input shapes, including unsupported properties for schema testing.
- Created JSON serialization contexts for both forms using source generation for improved performance.

* Fix the enum issue. for ElicitAsync<T>.

* Use AIJsonUtilities.CreateJsonSchema to create PrimitiveSchemaDefinition. #630

Renamed `BuildRequestSchemaFor<T>` to `BuildRequestSchema<T>`.
Updated the implementation to use `CreatePrimitiveSchema` and
enhanced type checks for supported primitives with
`AIJsonUtilities.CreateJsonSchema`. Streamlined handling of
unsupported types by consolidating return statements.

* Simplify ElicitAsync for schema validation. #630

Simplified the `ElicitAsync` method in `McpServerExtensions.cs` by removing unnecessary JSON object construction and directly deserializing `raw.Content`. Updated `CreatePrimitiveSchema` to use `JsonTypeInfo` for type checking and adjusted return logic for unsupported types.

In `ElicitationTypedTests.cs`, modified the `Can_Elicit_Typed_Information` test to account for the new `Created` property in `SampleForm`, increasing the expected property count from 5 to 6. Added assertions for the type and format of the `Created` property and included its deserialization in the test setup.

* Add error handling for unsupported elicitation types #630

Introduce exception handling in `McpServerExtensions.cs` for unsupported types. Add a test case in `ElicitationTypedTests.cs` to verify exception throwing for unsupported types. Define a new `UnsupportedForm` class with nested properties and include JSON serialization attributes for proper handling.

* Validate generic types in BuildRequestSchema #630

Introduce validation to ensure only object types are supported for elicitation requests in the `BuildRequestSchema` method. An exception is thrown for non-object types. Update the test suite with a new test case to verify this behavior, ensuring that an exception is raised when eliciting a non-object generic type (e.g., string) and that the elicitation handler is not invoked in this scenario.

* Move nullable types handling logic to ElicitationRequestParams.Coverter. #630

* Add schema validation for elicitation requests

Introduce `TryValidateElicitationPrimitiveSchema` method to validate JSON schemas for elicitation requests. This method checks for object type, verifies the "type" property, and ensures compliance with allowed properties based on primitive types (string, boolean, number). Integrate this validation in the `BuildRequestSchema` method to ensure generated schemas are valid before further processing.

* Refactor nullable type pattern matching. #630

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Update src/ModelContextProtocol.Core/Server/McpServerExtensions.cs

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Add ElicitResultSchemaCache. #630

* Prepopulate elicit schema validation logic. #630

- Introduced `LazyElicitAllowedProperties` to cache allowed property names for primitive types, replacing hardcoded logic.
- Streamlined `TryValidateElicitationPrimitiveSchema` method by consolidating type checks using pattern matching.
- Removed manual addition of allowed properties and now retrieve them directly from the new dictionary.
- Updated handling of "integer" type to be treated as "number" for consistency.

* Use Nullable.GetUnderlyingType to handle nullable types on elicitation. #630

- Update `ElicitRequestParams.cs` to throw a `JsonException` for non-string "type" properties, simplifying error handling.
- Modify `CreatePrimitiveSchema` in `McpServerExtensions.cs` to better handle nullable types and improve error messages.
- Revise `TryValidateElicitationPrimitiveSchema` to accept schema as the first parameter, enhancing clarity in error reporting.
- Simplify validation logic for the "type" keyword by directly retrieving string values, ensuring unsupported "type" arrays are flagged as errors.

* Rename static field.

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Fix static field renamings. #630

* Make BuildRequestSchema non-generic. #630

* Avoid closure allocation for serializerOptions on netcore  #630

Updated the `GetOrAdd` method to use a generic type parameter for .NET, allowing for better handling of `JsonSerializerOptions`. Retained the original implementation for other frameworks to ensure compatibility.

* Refactor ElicitRequestParams and McpServerExtensions. #630

- Simplified "type" property handling in Converter.
- Changed s_lazyElicitAllowedProperties to nullable type.
- Updated ElicitAsync to use static lambda for clarity.
- Refactored CreatePrimitiveSchema to handle nullable types.
- Initialized allowed properties in TryValidateElicitationPrimitiveSchema.
- Updated ElicitationTypedTests for naming conventions and added tests for nullable properties.
- Enforced required properties in SampleForm and introduced NullablePropertyForm.
- Added JSON source generation context for NullablePropertyForm.

* Remove reduntant checks. #630

Refactor JSON schema type handling and add integer support

This commit simplifies the validation logic for the `type` property in the JSON schema by removing unnecessary conditional checks. It directly retrieves the string value from `typeProperty` and assigns it to `typeKeyword`. Additionally, it enhances the `s_lazyElicitAllowedProperties` dictionary to include support for the `integer` type, allowing it to be recognized as a valid type with its corresponding allowed properties.

* Add IsAccepted property and update ElicitAsync return type

- Introduced `IsAccepted` property in `ElicitResult` and `ElicitResult<T>` to indicate if the action was accepted.
- Changed `ElicitAsync<T>` to return `ValueTask<ElicitResult<T>>` instead of `ValueTask<ElicitResult<T?>>`, ensuring non-nullable results.
- Updated return statements in `ElicitAsync<T>` to reflect the new return type, treating `Content` as non-nullable.

* Rename to s_elicitAllowedProperties

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Fix renaming s_elicitAllowedProperties. #630

* Remove unnecessary json attributes. #630

* Improve xml comment

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>

* Remove extra IsAccepted property. #630

* Use IsAccepted for checks.

Co-authored-by: Stephen Toub <stoub@microsoft.com>

* Add IsAccepted to non-generic ElicitResult.

---------

Co-authored-by: Eirik Tsarpalis <eirik.tsarpalis@gmail.com>
Co-authored-by: Stephen Toub <stoub@microsoft.com>
2025-09-15 17:50:50 +03:00
.config Update documentation configuration (#86) 2025-03-25 15:43:14 +00:00
.github/workflows Include docs samples in solution build (#751) 2025-09-03 07:37:01 -05:00
docs Add middleware and authz support for server-side handlers (#733) 2025-09-10 10:07:45 -07:00
samples Add middleware and authz support for server-side handlers (#733) 2025-09-10 10:07:45 -07:00
src Add ElicitAsync<T> (#630) (#715) 2025-09-15 17:50:50 +03:00
tests Add ElicitAsync<T> (#630) (#715) 2025-09-15 17:50:50 +03:00
.editorconfig style: (#746) 2025-09-02 18:34:17 +03:00
.gitattributes Add gitattributes (#98) 2025-03-25 18:57:01 -07:00
.gitignore Bump xunit.v3 to 2.0.0 (#231) 2025-04-07 14:46:24 -04:00
Directory.Build.props Update packages and Infra (#732) 2025-08-26 17:28:35 +03:00
Directory.Packages.props Update packages and Infra (#732) 2025-08-26 17:28:35 +03:00
global.json Convert solution to slnx (#472) 2025-05-30 18:19:55 +03:00
LICENSE Update copyright in LICENSE file and add THIRD-PARTY-NOTICES.txt (#9) 2025-03-20 11:32:16 -04:00
logo.png Add Directory.Build.props, apply CPM, use NB.GitVersioning, update package publishing 2025-03-19 17:27:18 +02:00
Makefile Update documentation configuration (#86) 2025-03-25 15:43:14 +00:00
ModelContextProtocol.slnx Per Session Tools Sample (#724) 2025-09-08 07:34:09 -07:00
nuget.config Fix nuget config 2025-03-19 15:12:55 -04:00
Open.snk Add strong naming (#49) 2025-03-21 17:51:05 +00:00
README.md Styling: remove a few redundant parens from object initializer expressions. (#548) 2025-06-26 16:55:54 +03:00
SECURITY.md Add SECURITY.md (#239) 2025-04-08 11:43:02 -07:00
THIRD-PARTY-NOTICES.txt Add McpServer/ClientResource{Template} and friends (#391) 2025-05-09 18:21:11 -04:00

MCP C# SDK

NuGet preview version

The official C# SDK for the Model Context Protocol, enabling .NET applications, services, and libraries to implement and interact with MCP clients and servers. Please visit our API documentation for more details on available functionality.

Packages

This SDK consists of three main packages:

Note

This project is in preview; 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:

Installation

To get started, install the package from NuGet

dotnet add package ModelContextProtocol --prerelease

Getting Started (Client)

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 clientTransport = new StdioClientTransport(new StdioClientTransportOptions
{
    Name = "Everything",
    Command = "npx",
    Arguments = ["-y", "@modelcontextprotocol/server-everything"],
});

var client = await McpClientFactory.CreateAsync(clientTransport);

// Print the list of tools available from the server.
foreach (var tool in await 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 Dictionary<string, object?>() { ["message"] = "Hello MCP!" },
    cancellationToken: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 easily exposed for immediate use by IChatClients, because McpClientTool inherits from AIFunction.

// Get available functions.
IList<McpClientTool> tools = await client.ListToolsAsync();

// 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 McpServerToolType attribute, and registers all methods with the McpTool attribute as tools.)

dotnet add package ModelContextProtocol --prerelease
dotnet add package Microsoft.Extensions.Hosting
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using ModelContextProtocol.Server;
using System.ComponentModel;

var builder = Host.CreateApplicationBuilder(args);
builder.Logging.AddConsole(consoleLogOptions =>
{
    // Configure all logs to go to stderr
    consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();
await builder.Build().RunAsync();

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

Tools can have the IMcpServer representing the server injected via a parameter to the method, and can use that for interaction with the connected client. Similarly, arguments may be injected via dependency injection. For example, this tool will use the supplied IMcpServer to make sampling requests back to the client in order to summarize content it downloads from the specified url via an HttpClient injected via dependency injection.

[McpServerTool(Name = "SummarizeContentFromUrl"), Description("Summarizes content downloaded from a specific URI")]
public static async Task<string> SummarizeDownloadedContent(
    IMcpServer thisServer,
    HttpClient httpClient,
    [Description("The url from which to download the content to summarize")] string url,
    CancellationToken cancellationToken)
{
    string content = await httpClient.GetStringAsync(url);

    ChatMessage[] messages =
    [
        new(ChatRole.User, "Briefly summarize the following downloaded content:"),
        new(ChatRole.User, content),
    ];
    
    ChatOptions options = new()
    {
        MaxOutputTokens = 256,
        Temperature = 0.3f,
    };

    return $"Summary: {await thisServer.AsSamplingChatClient().GetResponseAsync(messages, options, cancellationToken)}";
}

Prompts can be exposed in a similar manner, using [McpServerPrompt], e.g.

[McpServerPromptType]
public static class MyPrompts
{
    [McpServerPrompt, Description("Creates a prompt to summarize the provided message.")]
    public static ChatMessage Summarize([Description("The content to summarize")] string content) =>
        new(ChatRole.User, $"Please summarize this content into a single sentence: {content}");
}

More control is also available, with fine-grained control over configuring the server and how it should handle client requests. For example:

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

McpServerOptions options = new()
{
    ServerInfo = new Implementation { Name = "MyServer", Version = "1.0.0" },
    Capabilities = new ServerCapabilities
    {
        Tools = new ToolsCapability
        {
            ListToolsHandler = (request, cancellationToken) =>
                ValueTask.FromResult(new ListToolsResult
                {
                    Tools =
                    [
                        new Tool
                        {
                            Name = "echo",
                            Description = "Echoes the input back to the client.",
                            InputSchema = JsonSerializer.Deserialize<JsonElement>("""
                                {
                                    "type": "object",
                                    "properties": {
                                      "message": {
                                        "type": "string",
                                        "description": "The input to echo back"
                                      }
                                    },
                                    "required": ["message"]
                                }
                                """),
                        }
                    ]
                }),

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

                    return ValueTask.FromResult(new CallToolResult
                    {
                        Content = [new TextContentBlock { Text = $"Echo: {message}", Type = "text" }]
                    });
                }

                throw new McpException($"Unknown tool: '{request.Params?.Name}'");
            },
        }
    },
};

await using IMcpServer server = McpServerFactory.Create(new StdioServerTransport("MyServer"), options);
await server.RunAsync();

Acknowledgements

The starting point for this library was a project called mcpdotnet, initiated by Peder Holdgaard Pedersen. We are grateful for the work done by Peder and other contributors to that repository, which created a solid foundation for this library.

License

This project is licensed under the MIT License.