LOADING

加载过慢请开启缓存 浏览器默认开启

mcpdotnet使用指南:用C#构建MCP服务器和客户端

Model Context Protocol (MCP) 是一个开放协议,让AI模型能够与外部数据源和工具交互。mcpdotnet是官方C# SDK,让你可以轻松在.NET应用中实现MCP服务器和客户端。

什么是MCP

MCP(Model Context Protocol)是由Anthropic提出的协议,用于标准化AI模型与外部工具的通信。通过MCP,你可以:

  • 为AI助手提供自定义工具(Tools)
  • 暴露数据资源(Resources)给AI模型
  • 定义可重用的提示模板(Prompts)

安装NuGet包

SDK提供三个包,按需选择:

# 完整包(推荐,包含DI和托管扩展)
dotnet add package ModelContextProtocol

# 仅核心包(客户端或底层服务器API,依赖最少)
dotnet add package ModelContextProtocol.Core

# ASP.NET Core集成(HTTP传输)
dotnet add package ModelContextProtocol.AspNetCore

创建MCP服务器

1. 创建控制台项目

dotnet new console -n MyMcpServer
cd MyMcpServer
dotnet add package ModelContextProtocol

2. 定义工具类

使用 [McpServerToolType][McpServerTool] 标记你的工具:

using ModelContextProtocol.Server;
using System.ComponentModel;

[McpServerToolType]
public class CalculatorTools
{
    [McpServerTool, Description("计算两个数的和")]
    public static string Add(double a, double b)
    {
        return (a + b).ToString();
    }

    [McpServerTool, Description("计算两个数的乘积")]
    public static string Multiply(double a, double b)
    {
        return (a * b).ToString();
    }
}

3. 启动服务器(stdio模式)

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddMcpServer(options =>
{
    options.ServerInfo = new() { Name = "MyMcpServer", Version = "1.0.0" };
})
.WithStdioServerTransport()
.WithToolsFromAssembly();

await builder.Build().RunAsync();

4. 注册到Claude Desktop

在Claude Desktop配置文件中添加:

{
  "mcpServers": {
    "my-mcp-server": {
      "command": "dotnet",
      "args": ["run", "--project", "路径/MyMcpServer"]
    }
  }
}

创建MCP客户端

1. 创建控制台客户端

dotnet new console -n MyMcpClient
cd MyMcpClient
dotnet add package ModelContextProtocol
dotnet add package Microsoft.Extensions.AI.OpenAI

2. 连接服务器并调用工具

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

// 通过stdio连接到MCP服务器
var clientTransport = new StdioClientTransport(new()
{
    Name = "MyMcpServer",
    Command = "dotnet",
    Arguments = ["run", "--project", "路径/MyMcpServer"]
});

var client = await McpClientFactory.CreateAsync(clientTransport);

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

// 调用工具
var result = await client.CallToolAsync("Add", new Dictionary<string, object?>
{
    ["a"] = 10,
    ["b"] = 20
});

Console.WriteLine($"结果: {result.Content.First(c => c.Type == "text").Text}");

ASP.NET Core HTTP传输

如果需要HTTP方式暴露MCP服务器:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddMcpServer(options =>
{
    options.ServerInfo = new() { Name = "MyHttpMcpServer", Version = "1.0.0" };
})
.WithHttpTransport()
.WithToolsFromAssembly();

var app = builder.Build();

app.MapMcp();

app.Run();

客户端连接HTTP服务器:

var clientTransport = new HttpClientTransport(new()
{
    Name = "MyHttpMcpServer",
    Endpoint = new Uri("http://localhost:5000")
});

var client = await McpClientFactory.CreateAsync(clientTransport);

资源和提示模板

除了工具,MCP还支持资源(Resources)和提示模板(Prompts):

[McpServerToolType]
public class DataTools
{
    [McpServerTool, Description("获取用户信息")]
    public static async Task<string> GetUser(int userId)
    {
        // 从数据库或API获取数据
        return $"用户 {userId} 的信息";
    }
}

总结

mcpdotnet让C#开发者能够轻松构建MCP生态:

  • 简单:用Attribute标记方法即可创建工具
  • 灵活:支持stdio和HTTP两种传输方式
  • 标准:与Claude Desktop、VS Code等客户端无缝集成
  • DI友好:完美集成.NET依赖注入

项目地址:https://github.com/modelcontextprotocol/csharp-sdk

官方文档:https://csharp.sdk.modelcontextprotocol.io