Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

The official C# SDK for Model Context Protocol servers and clients. Maintained in collaboration with Microsoft.

License

NotificationsYou must be signed in to change notification settings

modelcontextprotocol/csharp-sdk

Repository files navigation

NuGet preview version

The official C# SDK for theModel Context Protocol, enabling .NET applications, services, and libraries to implement and interact with MCP clients and servers. Please visit ourAPI 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, theMcpClientFactory.CreateAsync method is used to instantiate and connect anIMcpClientto a server. Once you have anIMcpClient, you can interact with it, such as to enumerate all available tools and invoke tools.

varclientTransport=newStdioClientTransport(newStdioClientTransportOptions{Name="Everything",Command="npx",Arguments=["-y","@modelcontextprotocol/server-everything"],});varclient=awaitMcpClientFactory.CreateAsync(clientTransport);// Print the list of tools available from the server.foreach(vartoolinawaitclient.ListToolsAsync()){Console.WriteLine($"{tool.Name} ({tool.Description})");}// Execute a tool (this would normally be driven by LLM tool invocations).varresult=awaitclient.CallToolAsync("echo",newDictionary<string,object?>(){["message"]="Hello MCP!"},cancellationToken:CancellationToken.None);// echo always returns one and only one text content objectConsole.WriteLine(result.Content.First(c=>c.Type=="text").Text);

You can find samples demonstrating how to use ModelContextProtocol with an LLM SDK in thesamples directory, and also refer to thetests 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 byIChatClients, becauseMcpClientTool inherits fromAIFunction.

// Get available functions.IList<McpClientTool>tools=awaitclient.ListToolsAsync();// Call the chat client using the tools.IChatClientchatClient= ...;varresponse=awaitchatClient.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 ofWithTools examines the current assembly for classes with theMcpServerToolType attribute, and registers all methods with theMcpTool attribute as tools.)

dotnet add package ModelContextProtocol --prereleasedotnet add package Microsoft.Extensions.Hosting
usingMicrosoft.Extensions.DependencyInjection;usingMicrosoft.Extensions.Hosting;usingMicrosoft.Extensions.Logging;usingModelContextProtocol.Server;usingSystem.ComponentModel;varbuilder=Host.CreateApplicationBuilder(args);builder.Logging.AddConsole(consoleLogOptions=>{// Configure all logs to go to stderrconsoleLogOptions.LogToStandardErrorThreshold=LogLevel.Trace;});builder.Services.AddMcpServer().WithStdioServerTransport().WithToolsFromAssembly();awaitbuilder.Build().RunAsync();[McpServerToolType]publicstaticclassEchoTool{[McpServerTool,Description("Echoes the message back to the client.")]publicstaticstringEcho(stringmessage)=>$"hello{message}";}

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

[McpServerTool(Name="SummarizeContentFromUrl"),Description("Summarizes content downloaded from a specific URI")]publicstaticasyncTask<string>SummarizeDownloadedContent(IMcpServerthisServer,HttpClienthttpClient,[Description("The url from which to download the content to summarize")]stringurl,CancellationTokencancellationToken){stringcontent=awaithttpClient.GetStringAsync(url);ChatMessage[]messages=[new(ChatRole.User,"Briefly summarize the following downloaded content:"),new(ChatRole.User,content),];ChatOptionsoptions=new(){MaxOutputTokens=256,Temperature=0.3f,};return$"Summary:{awaitthisServer.AsSamplingChatClient().GetResponseAsync(messages,options,cancellationToken)}";}

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

[McpServerPromptType]publicstaticclassMyPrompts{[McpServerPrompt,Description("Creates a prompt to summarize the provided message.")]publicstaticChatMessageSummarize([Description("The content to summarize")]stringcontent)=>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:

usingModelContextProtocol;usingModelContextProtocol.Protocol;usingModelContextProtocol.Server;usingSystem.Text.Json;McpServerOptionsoptions=new(){ServerInfo=newImplementation{Name="MyServer",Version="1.0.0"},Capabilities=newServerCapabilities{Tools=newToolsCapability{ListToolsHandler=(request,cancellationToken)=>ValueTask.FromResult(newListToolsResult{Tools=[newTool{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",outvarmessage)is nottrue){thrownewMcpException("Missing required argument 'message'");}returnValueTask.FromResult(newCallToolResult{Content=[newTextContentBlock{Text=$"Echo:{message}",Type="text"}]});}thrownewMcpException($"Unknown tool: '{request.Params?.Name}'");},}},};awaitusingIMcpServerserver=McpServerFactory.Create(newStdioServerTransport("MyServer"),options);awaitserver.RunAsync();

Acknowledgements

The starting point for this library was a project calledmcpdotnet, initiated byPeder 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 theMIT License.

About

The official C# SDK for Model Context Protocol servers and clients. Maintained in collaboration with Microsoft.

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp