.NET MCP 文档中心

全面了解 .NET 使用 Model Context Protocol (MCP) 的实现、配置与最佳实践

MCP 核心特性

服务器端实现

了解如何使用 .NET 创建 MCP 服务器,注册工具,并处理客户端请求。详细的配置指南和最佳实践。

客户端实现

探索如何连接到 MCP 服务器,调用工具,并处理返回结果。包括与 Claude 等 LLM 的集成示例。

工具开发

学习如何创建和注册 MCP 工具,处理参数验证,实现异步操作,以及返回复杂结果类型。

LLM 集成

详细指南,教你如何将 MCP 工具与 Claude、GPT 等大型语言模型集成,实现强大的 AI 辅助功能。

Cursor 配置

全面的 Cursor IDE 集成指南,包括 MCP 服务器配置、工具使用方法和高级配置技巧。

实际应用场景

探索 MCP 在文档检索、数据分析、自动化测试等实际场景中的应用,包含完整的代码示例。

快速开始

1. 安装 NuGet 包

dotnet add package ModelContextProtocol --prerelease

2. 创建 MCP 服务器

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using ModelContextProtocol.Server;
using System.ComponentModel;

var builder = Host.CreateApplicationBuilder(args);
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}";
}

3. 连接到 MCP 服务器

using ModelContextProtocol.Client;
using ModelContextProtocol.Protocol.Transport;

var mcpClient = await McpClientFactory.CreateAsync(new()
{
    Id = "demo-server",
    Name = "Demo Server",
    TransportType = TransportTypes.StdIo,
    TransportOptions = new()
    {
        ["command"] = "dotnet",
        ["arguments"] = "run --project ../MyMcpServer/MyMcpServer.csproj",
    }
});

// 列出可用工具
var tools = await mcpClient.ListToolsAsync();
foreach (var tool in tools)
{
    Console.WriteLine($"{tool.Name}: {tool.Description}");
}

// 调用工具
var result = await mcpClient.CallToolAsync(
    "echo",
    new Dictionary() { ["message"] = "Hello MCP!" },
    CancellationToken.None);

Console.WriteLine(result.Content.First(c => c.Type == "text").Text);

.NET MCP 实现项目对比

项目名称 维护状态 特点 GitHub
官方 C# SDK 活跃
  • 官方支持
  • 完整的协议实现
  • 多种传输方式
  • 丰富的示例
modelcontextprotocol/csharp-sdk
MCPSharp 活跃
  • Microsoft.Extensions.AI 集成
  • Semantic Kernel 支持
  • 动态工具注册
  • 基于属性的 API
afrise/MCPSharp
mcpdotnet 已归档
  • 遵循规范的实现
  • 全面的日志支持
  • 兼容 .NET 8.0+
PederHP/mcpdotnet
ModelContextProtocol.NET 开发中
  • 原生 AOT 兼容
  • 标准输入输出通信
  • 工具集成框架
  • 计算器演示实现
salty-flower/ModelContextProtocol.NET

准备好开始了吗?

深入了解 .NET MCP 的实现细节,探索丰富的代码示例,掌握 Cursor 集成技巧。