MCP C# SDK:让 .NET 应用像使用 USB 一样,接入AI大模型



欢迎来到 Dotnet 工具箱!在这里,你可以发现各种令人惊喜的开源项目!
MCP C# SDK,为 .NET 生态提供了一套官方、规范的实现方案,用于构建和集成 MCP Client 与 Server。

MCP C# SDK 的整体结构
当前 MCP 官方为 .NET 提供了完整的 SDK 体系,整体采用模块化设计,主要由以下三个 NuGet 包组成:
1️⃣ ModelContextProtocol(核心推荐)
提供 MCP Server / Client 的核心实现
集成 Hosting 与依赖注入(DI)
适用于大多数 .NET 应用与服务
这是绝大部分项目的首选包。
2️⃣ ModelContextProtocol.AspNetCore
面向 HTTP 的 MCP Server 实现
适合 Web API、微服务场景
对多语言客户端更加友好
3️⃣ ModelContextProtocol.Core
最小依赖版本
适合只需要 Client 或底层 Server API 的场景
偏向框架或基础设施层使用
快速开始
创建 MCP Client
在 MCP 的架构中,Client 的职责是连接 MCP Server,并发现、调用其暴露的能力。
安装 sdk
dotnet add package ModelContextProtocol
通过 Stdio 连接 MCP Server
var clientTransport = new StdioClientTransport(new()
{
Name = "Everything",
Command = "npx",
Arguments = ["-y", "@modelcontextprotocol/server-everything"],
});
var client = await McpClient.CreateAsync(clientTransport);
这里体现了 MCP 的一个核心优势:
Server 可以由 Node / Python / Go / Rust 实现
Client 与 Server 完全解耦
通信基于标准协议,而非语言绑定。
枚举并调用工具
foreach (var tool in await client.ListToolsAsync())
{
Console.WriteLine($"{tool.Name} - {tool.Description}");
}
var result = await client.CallToolAsync(
"echo",
new Dictionary<string, object?> { ["message"] = "Hello MCP!" }
);
Console.WriteLine(
result.Content.OfType<TextContentBlock>().First().Text
);
到这里,你已经完成了一次跨语言、跨进程的 MCP 工具调用。
与 LLM 无缝集成:MCP + ChatClient
MCP 的设计天然适配 LLM 的 Tool / Function Calling 能力。
IList<McpClientTool> tools = await client.ListToolsAsync();
var response = await chatClient.GetResponseAsync(
"你的提示词",
new() { Tools = [.. tools] }
);
McpClientTool 继承自 AIFunction
可直接作为工具传递给 ChatClient
由 LLM 自主决定是否、以及如何调用工具.
创建 MCP Server
在 .NET 中创建 MCP Server 非常自然,完全融入 Host + DI 体系。
builder.Services
.AddMcpServer()
.WithStdioServerTransport()
.WithToolsFromAssembly();
定义一个 Echo 工具
[McpServerToolType]
public static class EchoTool
{
[McpServerTool]
public static string Echo(string message)
=> $"hello {message}";
}
只需添加特性,即可将普通方法暴露为 AI 可调用能力。
对 .NET 开发者来说,MCP C# SDK 最大的好处就是, 不用换思路,不用推翻架构,直接在你熟悉的 Host、DI、Attribute 体系里,就能把工具、Prompt、资源一步步“交给 AI”。
往期推荐:
项目地址
https://modelcontextprotocol.github.io/csharp-sdk/

分享

点收藏

点点赞

点在看
更多推荐
所有评论(0)