{"meta":{"title":"MCP 服务器调试指南","intro":"本指南介绍在使用 Copilot SDK 时特定于 MCP（模型上下文协议）服务器的调试技术。","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/troubleshooting","title":"故障排除"},{"href":"/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/mcp-debugging","title":"MCP 调试"}],"documentType":"article"},"body":"# MCP 服务器调试指南\n\n本指南介绍在使用 Copilot SDK 时特定于 MCP（模型上下文协议）服务器的调试技术。\n\n<!-- markdownlint-disable GHD046 GHD005 -->\n\n<!-- Suppressed: GHD046 (outdated release terminology), GHD005 (hardcoded data variable) -->\n\n## 目录\n\n* [快速诊断](#quick-diagnostics)\n* [独立测试 MCP 服务器](#testing-mcp-servers-independently)\n* [常见问题](#common-issues)\n* [特定平台问题](#platform-specific-issues)\n* [高级调试](#advanced-debugging)\n\n## 快速诊断\n\n### 清单\n\n在深入潜水之前，请验证以下基础知识：\n\n* [ ] MCP 服务器可执行文件存在且可运行\n* [ ] 命令路径正确（怀疑时使用绝对路径）\n* [ ] 工具已启用（`tools: [\"*\"]` 或特定工具名称）\n* [ ] 服务器正确实现 MCP 协议（响应 `initialize`）\n* [ ] 没有防火墙/防病毒阻止进程（Windows）\n\n### 启用 MCP 调试日志记录\n\n将环境变量添加到 MCP 服务器配置：\n\n```typescript\nmcpServers: {\n  \"my-server\": {\n    type: \"local\",\n    command: \"/path/to/server\",\n    args: [],\n    env: {\n      MCP_DEBUG: \"1\",\n      DEBUG: \"*\",\n      NODE_DEBUG: \"mcp\",  // For Node.js MCP servers\n    },\n  },\n}\n```\n\n## 独立测试 MCP 服务器\n\n始终先在 SDK 外部测试 MCP 服务器。\n\n### 手动协议测试\n\n通过标准输入发送 `initialize` 请求：\n\n```bash\n# Unix/macOS\necho '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"test\",\"version\":\"1.0\"}}}' | /path/to/your/mcp-server\n\n# Windows (PowerShell)\n'{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"test\",\"version\":\"1.0\"}}}' | C:\\path\\to\\your\\mcp-server.exe\n```\n\n**预期响应：**\n\n```json\n{\"jsonrpc\":\"2.0\",\"id\":1,\"result\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{\"tools\":{}},\"serverInfo\":{\"name\":\"your-server\",\"version\":\"1.0\"}}}\n```\n\n### 测试工具列表\n\n初始化后，请求工具列表：\n\n```bash\necho '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}' | /path/to/your/mcp-server\n```\n\n**预期响应：**\n\n```json\n{\"jsonrpc\":\"2.0\",\"id\":2,\"result\":{\"tools\":[{\"name\":\"my_tool\",\"description\":\"Does something\",\"inputSchema\":{...}}]}}\n```\n\n### 交互式测试脚本\n\n创建测试脚本以交互方式调试 MCP 服务器：\n\n```bash\n#!/bin/bash\n# test-mcp.sh\n\nSERVER=\"$1\"\n\n# Initialize\necho '{\"jsonrpc\":\"2.0\",\"id\":1,\"method\":\"initialize\",\"params\":{\"protocolVersion\":\"2024-11-05\",\"capabilities\":{},\"clientInfo\":{\"name\":\"test\",\"version\":\"1.0\"}}}'\n\n# Send initialized notification\necho '{\"jsonrpc\":\"2.0\",\"method\":\"notifications/initialized\"}'\n\n# List tools\necho '{\"jsonrpc\":\"2.0\",\"id\":2,\"method\":\"tools/list\",\"params\":{}}'\n\n# Keep stdin open\ncat\n```\n\n用法：\n\n```bash\n./test-mcp.sh | /path/to/mcp-server\n```\n\n## 常见问题\n\n### 服务器未启动\n\n**症状：** 没有显示任何工具，日志中没有错误。\n\n**原因和解决方案：**\n\n| 原因                           | 解决方案                            |\n| ---------------------------- | ------------------------------- |\n| 命令路径错误                       | 使用绝对路径： `/usr/local/bin/server` |\n| 缺少可执行权限                      |                                 |\n| `chmod +x /path/to/server`运行 |                                 |\n| 缺少依赖项                        | 使用 `ldd` (Linux) 检查或手动运行        |\n| 工作目录问题                       | 在配置中设置`cwd`                     |\n\n**通过手动运行进行调试：**\n\n```bash\n# Run exactly what the SDK would run\ncd /expected/working/dir\n/path/to/command arg1 arg2\n```\n\n### 服务器启动但工具未显示\n\n**症状：** 服务器进程运行，但没有可用的工具。\n\n**原因和解决方案：**\n\n1. **配置中未启用的工具：**\n\n   ```typescript\n   mcpServers: {\n     \"server\": {\n       // ...\n       tools: [\"*\"],  // Must be \"*\" or list of tool names\n     },\n   }\n   ```\n\n2. **服务器不公开工具：**\n   * 使用`tools/list`请求手动测试\n   * 检查服务器是否实现了 `tools/list` 方法\n\n3. **初始化握手失败：**\n   * 服务器必须正确响应 `initialize`\n   * 服务器必须处理 `notifications/initialized`\n\n### 列出但从未调用过的工具\n\n**症状：** 工具显示在调试日志中，但模型不使用它们。\n\n**原因和解决方案：**\n\n1. **提示显然不需要该工具：**\n\n   ```typescript\n   // Too vague\n   await session.sendAndWait({ prompt: \"What's the weather?\" });\n\n   // Better - explicitly mentions capability\n   await session.sendAndWait({ \n     prompt: \"Use the weather tool to get the current temperature in Seattle\" \n   });\n   ```\n\n2. **工具说明不清楚：**\n\n   ```typescript\n   // Bad - model doesn't know when to use it\n   { name: \"do_thing\", description: \"Does a thing\" }\n\n   // Good - clear purpose\n   { name: \"get_weather\", description: \"Get current weather conditions for a city. Returns temperature, humidity, and conditions.\" }\n   ```\n\n3. **工具架构问题：**\n   * 确保 `inputSchema` 有效 JSON 架构\n   * 必填字段必须位于数组中`required`\n\n### 系统超时错误\n\n**症状：**`MCP tool call timed out` 错误。\n\n**解决方案：**\n\n1. **增加超时时间：**\n\n   ```typescript\n   mcpServers: {\n     \"slow-server\": {\n       // ...\n       timeout: 300000,  // 5 minutes\n     },\n   }\n   ```\n\n2. **优化服务器性能：**\n   * 添加进度日志记录以识别瓶颈\n   * 考虑异步操作\n   * 检查是否存在阻塞式 I/O\n\n3. **对于长时间运行的工具**，请考虑流式处理响应（如果受支持）。\n\n### JSON-RPC 错误\n\n**症状：** 解析错误，无效请求错误。\n\n**常见原因：**\n\n1. **服务器错误地写入 stdout：**\n   * 调试输出被发送到 stdout 而不是 stderr\n   * 额外的换行符或空格\n   ```typescript\n   // Wrong - pollutes stdout\n   console.log(\"Debug info\");\n\n   // Correct - use stderr for debug\n   console.error(\"Debug info\");\n   ```\n\n2. **编码问题：**\n   * 确保 UTF-8 编码\n   * 无 BOM （字节顺序标记）\n\n3. **消息框架：**\n   * 每个消息必须是完整的 JSON 对象\n   * 以换行符分隔（每行一条消息）\n\n## 特定于平台的问题\n\n### Windows操作系统\n\n#### .NET控制台应用/工具\n\n```csharp\n// Correct configuration for .NET exe\n[\"my-dotnet-server\"] = new McpStdioServerConfig\n{\n    Command = @\"C:\\Tools\\MyServer\\MyServer.exe\",  // Full path with .exe\n    Args = new List<string>(),\n    WorkingDirectory = @\"C:\\Tools\\MyServer\",  // Set working directory\n    Tools = new List<string> { \"*\" },\n}\n\n// For dotnet tool (DLL)\n[\"my-dotnet-tool\"] = new McpStdioServerConfig\n{\n    Command = \"dotnet\",\n    Args = new List<string> { @\"C:\\Tools\\MyTool\\MyTool.dll\" },\n    WorkingDirectory = @\"C:\\Tools\\MyTool\",\n    Tools = new List<string> { \"*\" },\n}\n```\n\n#### npx 命令\n\n```csharp\n// Windows needs cmd /c for npx\n[\"filesystem\"] = new McpStdioServerConfig\n{\n    Command = \"cmd\",\n    Args = new List<string> { \"/c\", \"npx\", \"-y\", \"@modelcontextprotocol/server-filesystem\", \"C:\\\\allowed\\\\path\" },\n    Tools = new List<string> { \"*\" },\n}\n```\n\n#### 路径问题\n\n* 使用原始字符串 （`@\"C:\\path\"`） 或正斜杠 （`\"C:/path\"`）\n* 尽可能避免路径中的空格\n* 如果需要空格，请确保正确引用\n\n#### 防病毒/防火墙\n\nWindows Defender或其他 AV 可能会阻止：\n\n* 新的可执行文件\n* 通过 stdin/stdout 进行通信的过程\n\n**解决 方案：** 为 MCP 服务器可执行文件添加排除项。\n\n### macOS\n\n#### Gatekeeper 阻止\n\n```bash\n# If the server is blocked\nxattr -d com.apple.quarantine /path/to/mcp-server\n```\n\n#### Homebrew 路径\n\n```typescript\n// GUI apps may not have /opt/homebrew in PATH\nmcpServers: {\n  \"my-server\": {\n    command: \"/opt/homebrew/bin/node\",  // Full path\n    args: [\"/path/to/server.js\"],\n  },\n}\n```\n\n### Linux\n\n#### 权限问题\n\n```bash\nchmod +x /path/to/mcp-server\n```\n\n#### 缺少共享库\n\n```bash\n# Check dependencies\nldd /path/to/mcp-server\n\n# Install missing libraries\napt install libfoo  # Debian/Ubuntu\nyum install libfoo  # RHEL/CentOS\n```\n\n## 高级调试\n\n### 捕获所有 MCP 流量\n\n创建包装器脚本以记录所有通信：\n\n```bash\n#!/bin/bash\n# mcp-debug-wrapper.sh\n\nLOG=\"./mcp-debug-$(date +%s).log\"\nACTUAL_SERVER=\"$1\"\nshift\n\necho \"=== MCP Debug Session ===\" >> \"$LOG\"\necho \"Server: $ACTUAL_SERVER\" >> \"$LOG\"\necho \"Args: $@\" >> \"$LOG\"\necho \"=========================\" >> \"$LOG\"\n\n# Tee stdin/stdout to log file\ntee -a \"$LOG\" | \"$ACTUAL_SERVER\" \"$@\" 2>> \"$LOG\" | tee -a \"$LOG\"\n```\n\n使用它：\n\n```typescript\nmcpServers: {\n  \"debug-server\": {\n    command: \"/path/to/mcp-debug-wrapper.sh\",\n    args: [\"/actual/server/path\", \"arg1\", \"arg2\"],\n  },\n}\n```\n\n### 使用 MCP 检查器进行检查\n\n使用官方 MCP 检查器工具：\n\n```bash\nnpx @modelcontextprotocol/inspector /path/to/your/mcp-server\n```\n\n这提供了一个 Web 用户界面，用于：\n\n* 发送测试请求\n* 查看响应\n* 检查工具架构\n\n### 协议版本不匹配\n\n检查服务器是否支持 SDK 使用的协议版本：\n\n```json\n// In initialize response, check protocolVersion\n{\"result\":{\"protocolVersion\":\"2024-11-05\",...}}\n```\n\n如果版本不匹配，请更新 MCP 服务器库。\n\n## 调试清单\n\n提交问题或寻求帮助时，请收集：\n\n* [ ] SDK 语言和版本\n* [ ] CLI 版本 （`copilot --version`）\n* [ ] MCP 服务器类型（Node.js、Python、.NET、Go、Rust 等）\n* [ ] 完整的 MCP 服务器配置（隐去机密信息）\n* [ ] 手动 `initialize` 测试的结果\n* [ ] 手动 `tools/list` 测试的结果\n* [ ] SDK 调试日志\n* [ ] 任何错误消息\n\n## 另见\n\n* [将 MCP 服务器与 GitHub Copilot SDK 配合使用](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/features/mcp) - 配置和设置\n* [调试指南](/zh/enterprise-cloud@latest/copilot/how-tos/copilot-sdk/troubleshooting/debugging) - SDK 范围的调试\n* [MCP 规范](https://modelcontextprotocol.io/) - 官方协议文档"}