摘要:一个.NET实现的模型上下文协议(MCP),使.NET应用程序能够连接到并与MCP客户端和服务器进行交互。
一个.NET实现的模型上下文协议(MCP),使.NET应用程序能够连接到并与MCP客户端和服务器进行交互。
什么是MCP
模型上下文协议(MCP)是一种开放协议,它规范了应用程序如何为大型语言模型(LLM)提供上下文。它实现了大型语言模型与各种数据源和工具之间的安全集成。
.net相关的包
mcpdotnet: .NET的核心MCP实现
McpDotNet.Extensions.AI:与 Microsoft.Extensions.AI 的集成
设计目标
这个库旨在提供一个干净、符合规范的MCP协议实现,尽量减少额外的抽象。虽然传输实现必然包含额外的代码,但它们尽可能遵循官方SDK所确立的模式。
特点
.NET应用程序的MCP实现
支持stdio和SSE传输(客户端)
支持stdio传输(服务器)
支持所有MCP功能:工具、资源、提示、采样、根
支持补全实用功能
支持服务器指令、分页和通知
全程采用异步/等待模式
全面的日志记录支持
兼容.NET 8.0及更高版本
代码示例:
1.客户端
首先安装mcpdotnet:
dotnet add package mcpdotnet然后创建一个客户端,并开始使用您配置的服务器上的工具或其他功能:
var options = new McpClientOptions { ClientInfo = new { Name = "TestClient", Version = "1.0.0" } };var config = new McpServerConfig { Id = "everything", Name = "Everything", TransportType = TransportTypes.StdIo, TransportOptions = new Dictionary { ["command"] = "npx", ["arguments"] = "-y @modelcontextprotocol/server-everything", } };var factory = new McpClientFactory( [config], options, LoggerFactory.Instance );var client = await factory.GetClientAsync("everything");// Get the list of tools, for passing to an LLMvar tools = await client.ListToolsAsync;// Execute a tool, in practice this would normally be driven by LLM tool invocationsvar result = await client.CallToolAsync( "echo", new Dictionary { ["message"] = "Hello MCP!" }, CancellationToken.None );// echo always returns one and only one text content objectConsole.WriteLine(result.Content.FirstOrDefault(c => c.Type == "text").Text);请注意,您应该根据您的使用场景传递适合的CancellationToken对象,以便实现适当的错误处理、超时等功能。强烈建议您在工厂构造函数中传递一个适当的LoggerFactory实例,以便记录MCP客户端的操作日志。请记住,您可以连接到任何MCP服务器,而不仅限于使用mcpdotnet创建的服务器。该协议设计为与服务器无关,因此您可以使用此库连接到任何符合规范的服务器。
2.服务端
以下是一个如何创建MCP服务器并注册当前应用程序中的所有工具的示例。
var builder = Host.CreateApplicationBuilder(args);builder.Services.AddMcpServer .WithStdioServerTransport .WithToolsvar app = builder.Build;await app.RunAsync;EchoTool类是一个工具实现的简单示例:
[McpToolType]public static class EchoTool{ [McpTool(Description = "Echoes the input back to the client.")] public static string Echo([McpParameter(true)] string message) { return "hello " + message; }}以下是一个如何手动创建一个包含单个工具的MCP服务器的示例。
McpServerOptions options = new McpServerOptions{ ServerInfo = new Implementation { Name = "MyServer", Version = "1.0.0" }, Capabilities = new ServerCapabilities { Tools = new }};McpServerFactory factory = new McpServerFactory(new StdioServerTransport("MyServer", loggerFactory), options, loggerFactory);IMcpServer server = factory.CreateServer;server.ListToolsHandler = (request, cancellationToken) =>{ return Task.FromResult(new ListToolsResult { Tools = [ new Tool { Name = "echo", Description = "Echoes the input back to the client.", InputSchema = new JsonSchema { Type = "object", Properties = new Dictionary { ["message"] = new JsonSchemaProperty { Type = "string", Description = "The input to echo back." } } }, } ] });};server.CallToolHandler = async (request, cancellationToken) =>{ if (request.Name == "echo") { if (request.Arguments is || !request.Arguments.TryGetValue("message", out var message)) { throw new McpServerException("Missing required argument 'message'"); } return new CallToolResponse { Content = [new Content { Text = "Echo: " + message.ToString, Type = "text" }] }; } else { throw new McpServerException($"Unknown tool: {request.Name}"); }};await server.StartAsync;// Run until process is stopped by the client (parent process)while (true){ await Task.Delay(1000);}路线图:
扩展文档,提供以下方面的详细指南:
1.高级场景(采样、资源、提示)
2.传输配置
3.错误处理和恢复
增加测试覆盖率
添加更多示例和样本
性能优化
SSE服务器支持
身份验证
来源:opendotnet