在本快速入门中,你将使用 适用于 MCP 的 C# SDK 创建最小模型上下文协议(MCP)服务器,并使用 GitHub Copilot 连接到该服务器。 MCP 服务器是通过模型上下文协议(MCP)向客户端公开功能的服务。
先决条件
- .NET 8.0 SDK 或更高版本
- Visual Studio Code
- 适用于 Visual Studio Code 的 GitHub Copilot 扩展
创建项目
在终端窗口中,导航到要在其中创建应用的目录,并使用
dotnet new
以下命令创建新的控制台应用:dotnet new console -n MinimalMcpServer
导航到
MinimalMcpServer
目录:cd MinimalMcpServer
将以下 NuGet 包添加到应用:
dotnet add package ModelContextProtocol --prerelease dotnet add package Microsoft.Extensions.Hosting
- ModelContextProtocol 包是用于处理模型上下文协议的官方 C# SDK。
-
Microsoft.Extensions.Hosting 包提供用于日志记录和依赖项注入的通用 .NET
HostBuilder
和服务。
添加应用代码
将 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 服务器:
如果尚未打开,请在 Visual Studio Code 中打开项目文件夹。
在项目的根目录中创建文件夹
.vscode
。在
mcp.json
文件夹中添加一个.vscode
文件,内容如下:{ "inputs": [], "servers": { "MinimalMcpServer": { "type": "stdio", "command": "dotnet", "args": [ "run", "--project", "${workspaceFolder}/MinimalMcpServer.csproj" ] } } }
保存文件。
测试 MCP 服务器
在 Visual Studio Code 中打开 GitHub Copilot 并切换到代理模式。
选择 “选择工具” 图标,验证 MinimalMcpServer 在列出的这两个工具中均可用。
输入运行 ReverseEcho 工具的提示:
Reverse the following: "Hello, minimal MCP server!"
GitHub Copilot 请求针对提示运行 ReverseEcho 工具的权限。 选择 “继续 ”或使用箭头选择更具体的行为:
- 当前会话 始终在当前 GitHub Copilot 代理模式会话中运行作。
- 当前工作区 始终运行当前 Visual Studio Code 工作区的命令。
- 始终允许 将此操作设置为始终在 GitHub Copilot 代理模式的任何会话或任何 Visual Studio Code 工作区中运行。
验证服务器是否响应回显的消息:
!revres PCM laminim ,olleH