使用 .NET 创建和连接到最小 MCP 服务器

在本快速入门中,你将使用 适用于 MCP 的 C# SDK 创建最小模型上下文协议(MCP)服务器,并使用 GitHub Copilot 连接到该服务器。 MCP 服务器是通过模型上下文协议(MCP)向客户端公开功能的服务。

先决条件

创建项目

  1. 在终端窗口中,导航到要在其中创建应用的目录,并使用 dotnet new 以下命令创建新的控制台应用:

    dotnet new console -n MinimalMcpServer
    
  2. 导航到 MinimalMcpServer 目录:

    cd MinimalMcpServer
    
  3. 将以下 NuGet 包添加到应用:

    dotnet add package ModelContextProtocol --prerelease
    dotnet add package Microsoft.Extensions.Hosting
    

添加应用代码

Program.cs 的内容替换为以下代码,来实现一个公开简单回显工具的最小 MCP 服务器。 AI 模型根据需要调用这些工具,以生成对用户提示的响应。

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

// Create a generic host builder for
// dependency injection, logging, and configuration.
var builder = Host.CreateApplicationBuilder(args);

// Configure logging for better integration with MCP clients.
builder.Logging.AddConsole(consoleLogOptions =>
{
consoleLogOptions.LogToStandardErrorThreshold = LogLevel.Trace;
});

// Register the MCP server and configure it to use stdio transport.
// Scan the assembly for tool definitions.
builder.Services
    .AddMcpServer()
    .WithStdioServerTransport()
    .WithToolsFromAssembly();

// Build and run the host. This starts the MCP server.
await builder.Build().RunAsync();

// Define a static class to hold MCP tools.
[McpServerToolType]
public static class EchoTool
{
    // Expose a tool that echoes the input message back to the client.
    [McpServerTool, Description("Echoes the message back to the client.")]
    public static string Echo(string message) => $"Hello from C#: {message}";

    // Expose a tool that returns the input message in reverse.
    [McpServerTool, Description("Echoes in reverse the message sent by the client.")]
    public static string ReverseEcho(string message) => new string(message.Reverse().ToArray());
}

前面的代码:

  • 创建用于依赖项注入、日志记录和配置的通用主机生成器。
  • 配置日志记录,以便更好地与 MCP 客户端集成。
  • 注册 MCP 服务器,配置其使用 stdio 传输协议,然后扫描程序集以获取工具定义。
  • 构建并运行启动 MCP 服务器的主机。
  • 定义一个静态类,用于保存两个 MCP 工具,这些工具将值回显回客户端。

在 Visual Studio Code 中配置 MCP 服务器

配置用于 Visual Studio Code 的 GitHub Copilot 以使用自定义 MCP 服务器:

  1. 如果尚未打开,请在 Visual Studio Code 中打开项目文件夹。

  2. 在项目的根目录中创建文件夹 .vscode

  3. mcp.json文件夹中添加一个.vscode文件,内容如下:

    {
      "inputs": [],
      "servers": {
        "MinimalMcpServer": {
          "type": "stdio",
          "command": "dotnet",
          "args": [
            "run",
            "--project",
            "${workspaceFolder}/MinimalMcpServer.csproj"
          ]
        }
      }
    }
    
  4. 保存文件。

测试 MCP 服务器

  1. 在 Visual Studio Code 中打开 GitHub Copilot 并切换到代理模式。

  2. 选择 “选择工具” 图标,验证 MinimalMcpServer 在列出的这两个工具中均可用。

    显示可用 MCP 工具的屏幕截图。

  3. 输入运行 ReverseEcho 工具的提示:

    Reverse the following: "Hello, minimal MCP server!"
    
  4. GitHub Copilot 请求针对提示运行 ReverseEcho 工具的权限。 选择 “继续 ”或使用箭头选择更具体的行为:

    • 当前会话 始终在当前 GitHub Copilot 代理模式会话中运行作。
    • 当前工作区 始终运行当前 Visual Studio Code 工作区的命令。
    • 始终允许 将此操作设置为始终在 GitHub Copilot 代理模式的任何会话或任何 Visual Studio Code 工作区中运行。
  5. 验证服务器是否响应回显的消息:

    !revres PCM laminim ,olleH
    

构建最小 MCP 客户端.NET AI 和模型上下文协议入门