{"meta":{"title":"将 MCP 服务器与 GitHub Copilot SDK 配合使用","intro":"Copilot SDK 可以与 MCP 服务器（模型上下文协议）集成，以使用外部工具扩展助手的功能。 MCP 服务器作为单独的进程运行，并公开Copilot可在会话期间调用的工具（函数）。","product":"GitHub Copilot","breadcrumbs":[{"href":"/zh/enterprise-cloud@latest/copilot","title":"GitHub Copilot"},{"href":"/zh/enterprise-cloud@latest/copilot/how-tos","title":"操作方法"},{"href":"/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk","title":"Copilot SDK"},{"href":"/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features","title":"功能"},{"href":"/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/mcp","title":"MCP"}],"documentType":"article"},"body":"# 将 MCP 服务器与 GitHub Copilot SDK 配合使用\n\nCopilot SDK 可以与 MCP 服务器（模型上下文协议）集成，以使用外部工具扩展助手的功能。 MCP 服务器作为单独的进程运行，并公开Copilot可在会话期间调用的工具（函数）。\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n> \\[!NOTE]\n> 这是一个不断发展的功能。 有关正在进行的讨论，请参阅[问题 #36](https://github.com/github/copilot-sdk/issues/36)。\n\n## 什么是 MCP？\n\n[模型上下文协议（MCP）](https://modelcontextprotocol.io/) 是将 AI 助手连接到外部工具和数据源的开放标准。 MCP 服务器可以：\n\n* 执行代码或脚本\n* 查询数据库\n* 访问文件系统\n* 调用外部 API\n* 等等\n\n## 服务器类型\n\nSDK 支持两种类型的 MCP 服务器：\n\n| 类型              | Description                  | 用例              |\n| --------------- | ---------------------------- | --------------- |\n| **Local/Stdio** | 作为子进程运行，通过 stdin/stdout 进行通信 | 本地工具、文件访问、自定义脚本 |\n| **HTTP/SSE**    | 通过 HTTP 访问的远程服务器             | 共享服务、云托管工具      |\n\n## Configuration\n\n### Node.js/TypeScript\n\n```typescript\nimport { CopilotClient } from \"@github/copilot-sdk\";\n\nconst client = new CopilotClient();\nconst session = await client.createSession({\n    model: \"gpt-5\",\n    mcpServers: {\n        // Local MCP server (stdio)\n        \"my-local-server\": {\n            type: \"local\",\n            command: \"node\",\n            args: [\"./mcp-server.js\"],\n            env: { DEBUG: \"true\" },\n            cwd: \"./servers\",\n            tools: [\"*\"],  // \"*\" = all tools, [] = none, or list specific tools\n            timeout: 30000,\n        },\n        // Remote MCP server (HTTP)\n        \"github\": {\n            type: \"http\",\n            url: \"https://api.githubcopilot.com/mcp/\",\n            headers: { \"Authorization\": \"Bearer ${TOKEN}\" },\n            tools: [\"*\"],\n        },\n    },\n});\n```\n\n### Python\n\n```python\nimport asyncio\nfrom copilot import CopilotClient\nfrom copilot.session import PermissionHandler\n\nasync def main():\n    client = CopilotClient()\n    await client.start()\n\n    session = await client.create_session(on_permission_request=PermissionHandler.approve_all, model=\"gpt-5\", mcp_servers={\n        # Local MCP server (stdio)\n        \"my-local-server\": {\n            \"type\": \"local\",\n            \"command\": \"python\",\n            \"args\": [\"./mcp_server.py\"],\n            \"env\": {\"DEBUG\": \"true\"},\n            \"cwd\": \"./servers\",\n            \"tools\": [\"*\"],\n            \"timeout\": 30000,\n        },\n        # Remote MCP server (HTTP)\n        \"github\": {\n            \"type\": \"http\",\n            \"url\": \"https://api.githubcopilot.com/mcp/\",\n            \"headers\": {\"Authorization\": \"Bearer ${TOKEN}\"},\n            \"tools\": [\"*\"],\n        },\n    })\n\n    response = await session.send_and_wait(\"List my recent GitHub notifications\")\n    print(response.data.content)\n\n    await client.stop()\n\nasyncio.run(main())\n```\n\n### Go\n\n```golang\npackage main\n\nimport (\n    \"context\"\n    \"log\"\n    copilot \"github.com/github/copilot-sdk/go\"\n)\n\nfunc main() {\n    ctx := context.Background()\n    client := copilot.NewClient(nil)\n    if err := client.Start(ctx); err != nil {\n        log.Fatal(err)\n    }\n    defer client.Stop()\n\n    session, err := client.CreateSession(ctx, &copilot.SessionConfig{\n        Model: \"gpt-5\",\n        MCPServers: map[string]copilot.MCPServerConfig{\n            \"my-local-server\": copilot.MCPStdioServerConfig{\n                Command: \"node\",\n                Args:    []string{\"./mcp-server.js\"},\n                Tools:   []string{\"*\"},\n            },\n        },\n    })\n    if err != nil {\n        log.Fatal(err)\n    }\n    defer session.Disconnect()\n\n    // Use the session...\n}\n```\n\n### .NET\n\n```csharp\nusing GitHub.Copilot;\n\nawait using var client = new CopilotClient();\nawait using var session = await client.CreateSessionAsync(new SessionConfig\n{\n    Model = \"gpt-5\",\n    McpServers = new Dictionary<string, McpServerConfig>\n    {\n        [\"my-local-server\"] = new McpStdioServerConfig\n        {\n            Command = \"node\",\n            Args = new List<string> { \"./mcp-server.js\" },\n            Tools = new List<string> { \"*\" },\n        },\n    },\n});\n```\n\n## 按会话禁用已配置的服务器\n\n将 `disabledMcpServers` 设置为不得在会话中运行的确切 MCP 服务器名称。\n该设置的范围限定为单个创建或恢复请求;它不会修改全局 MCP 设置或服务器配置。\n\n```typescript\nconst session = await client.createSession({\n    mcpServers: {\n        filesystem: { type: \"local\", command: \"npx\", args: [\"-y\", \"@modelcontextprotocol/server-filesystem\", \".\"] },\n        github: { type: \"http\", url: \"https://api.githubcopilot.com/mcp/\" },\n    },\n    disabledMcpServers: [\"github\"],\n});\n```\n\n| SDK     | 配置属性                             |\n| ------- | -------------------------------- |\n| Node.js | `disabledMcpServers`             |\n| Python  | `disabled_mcp_servers`           |\n| Go      | `DisabledMCPServers`             |\n| .NET    | `DisabledMcpServers`             |\n| Java    | `setDisabledMcpServers(...)`     |\n| Rust    | `with_disabled_mcp_servers(...)` |\n\n在创建会话时以及进行**冷**恢复时，已禁用的服务器不会启动，运行时也不会发起对其的身份验证。 常驻恢复无法撤消运行时已经生成的服务器。 名称完全一致。\n\n## 工具配置\n\n可以使用 `tools` 字段控制 MCP 服务器可用的工具。\n\n### 允许使用所有工具\n\n使用 `\"*\"` 来启用 MCP 服务器提供的所有工具：\n\n```typescript\ntools: [\"*\"]\n```\n\n### 允许使用特定工具\n\n提供用于限制访问的工具名称列表：\n\n```typescript\ntools: [\"bash\", \"edit\"]\n```\n\n只有列出的工具可供代理使用。\n\n### 禁用所有工具\n\n使用空数组禁用所有工具：\n\n```typescript\ntools: []\n```\n\n### Notes\n\n* 该 `tools` 字段定义允许的工具。\n* 没有单独的 `allow` 或 `disallow` 配置 - 工具访问直接通过此列表进行控制。\n\n## 快速入门：文件系统 MCP 服务器\n\n下面是使用官方 [`@modelcontextprotocol/server-filesystem`](https://www.npmjs.com/package/@modelcontextprotocol/server-filesystem) MCP 服务器的完整工作示例：\n\n```typescript\nimport { CopilotClient } from \"@github/copilot-sdk\";\n\nasync function main() {\n    const client = new CopilotClient();\n\n    // Create session with filesystem MCP server\n    const session = await client.createSession({\n        mcpServers: {\n            filesystem: {\n                type: \"local\",\n                command: \"npx\",\n                args: [\"-y\", \"@modelcontextprotocol/server-filesystem\", \"/tmp\"],\n                tools: [\"*\"],\n            },\n        },\n    });\n\n    console.log(\"Session created:\", session.sessionId);\n\n    // The model can now use filesystem tools\n    const result = await session.sendAndWait({\n        prompt: \"List the files in the allowed directory\",\n    });\n\n    console.log(\"Response:\", result?.data?.content);\n\n    await session.disconnect();\n    await client.stop();\n}\n\nmain();\n```\n\n**Output:**\n\n```text\nSession created: 18b3482b-bcba-40ba-9f02-ad2ac949a59a\nResponse: The allowed directory is `/tmp`, which contains various files\nand subdirectories including temporary system files, log files, and\ndirectories for different applications.\n```\n\n> \\[!TIP]\n> 可以使用 [MCP 服务器目录中的任何 MCP 服务器](https://github.com/modelcontextprotocol/servers)。 常用选项包括 `@modelcontextprotocol/server-github`、 `@modelcontextprotocol/server-sqlite`和 `@modelcontextprotocol/server-puppeteer`。\n\n## 配置选项\n\n### 本地/stdio 服务器\n\n| 财产                    | 类型         | 必选           | Description                      |\n| --------------------- | ---------- | ------------ | -------------------------------- |\n| `type`                |            |              |                                  |\n| `\"local\"` 或 `\"stdio\"` | 否          | 服务器类型（默认为本地） |                                  |\n| `command`             | `string`   | Yes          | 要执行的命令                           |\n| `args`                | `string[]` | Yes          | 命令参数                             |\n| `env`                 | `object`   | 否            | 环境变量                             |\n| `cwd`                 | `string`   | 否            | 工作目录                             |\n| `tools`               | `string[]` | 否            | 要启用的工具（`[\"*\"]` 表示全部启用，`[]` 都不启用） |\n| `timeout`             | `number`   | 否            | 超时（以毫秒为单位）                       |\n\n### 远程服务器 （HTTP/SSE）\n\n| 财产                 | 类型         | 必选    | Description        |\n| ------------------ | ---------- | ----- | ------------------ |\n| `type`             |            |       |                    |\n| `\"http\"` 或 `\"sse\"` | Yes        | 服务器类型 |                    |\n| `url`              | `string`   | Yes   | 服务器 URL            |\n| `headers`          | `object`   | 否     | HTTP 标头（例如，用于身份验证） |\n| `tools`            | `string[]` | 否     | 要启用的工具             |\n| `timeout`          | `number`   | 否     | 超时（以毫秒为单位）         |\n\n## 故障排除\n\n### 工具未显示或未被调用\n\n1. **验证 MCP 服务器是否正确启动**\n   * 检查命令和参数是否正确\n   * 确保服务器进程在启动时不会崩溃\n   * 在 stderr 中查找错误输出\n\n2. **检查工具配置**\n   * 确保 `tools` 已设置为 `[\"*\"]` 或列出所需的特定工具\n   * 空数组 `[]` 意味着未启用任何工具\n\n3. **验证远程服务器的连接性**\n   * 确保 URL 可访问\n   * 检查身份验证标头是否正确\n\n### 常见问题\n\n| Issue           | 解决方案                   |\n| --------------- | ---------------------- |\n| “找不到 MCP 服务器”   | 验证命令路径是否正确且可执行         |\n| “连接被拒绝”（HTTP）   | 检查 URL 并确保服务器正在运行      |\n| “超时”错误          | 增加`timeout`的值，或检查服务器性能 |\n| 工具虽然在正常运行但没有被调用 | 请确保提示明确指明工具的功能         |\n\n有关详细的调试指南，请参阅 **[MCP 服务器调试指南](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/mcp-debugging)**。\n\n## 相关资源\n\n* [模型上下文协议规范](https://modelcontextprotocol.io/)\n* [MCP 服务器目录](https://github.com/modelcontextprotocol/servers) - 社区 MCP 服务器\n* [GitHub MCP 服务器](https://github.com/github/github-mcp-server) - 官方GitHub MCP 服务器\n* [构建你的第一个由 Copilot 提供支持的应用](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/getting-started) - SDK 基础知识和自定义工具\n* [调试指南](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/debugging) - SDK 范围的调试\n\n## 另见\n\n* [MCP 服务器调试指南](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/mcp-debugging) - 详细的 MCP 故障排除\n* [问题 9](https://github.com/github/copilot-sdk/issues/9) - 原始 MCP 工具使用情况问题\n* [问题 #36](https://github.com/github/copilot-sdk/issues/36) - MCP 文档跟踪问题"}