> ## Documentation Index
> Fetch the complete documentation index at: https://mcp.developerdoc.cn/llms.txt
> Use this file to discover all available pages before exploring further.

# 调试

> 调试 Model Context Protocol (MCP) 集成的完整指南

开发 MCP 服务器或将其集成到应用中时，高效调试非常关键。本指南介绍 MCP 生态中可用的调试工具和方法。

## 调试工具概览

MCP 提供了多个面向不同层级的调试工具：

1. **[MCP Inspector](/docs/tools/inspector)**：交互式、传输无关的测试 UI。它可以连接 stdio 或 Streamable HTTP server，调用 [tools](/specification/latest/server/tools)、[prompts](/specification/latest/server/prompts) 和 [resources](/specification/latest/server/resources)，并查看通知流。这通常应是你的首选调试工具。
2. **服务器日志**：可以将结构化日志写入 stderr（stdio 传输），或通过 [`notifications/message`](/specification/latest/server/utilities/logging#log-message-notifications) 发送（所有传输方式）。
3. **客户端开发者工具**：大多数 MCP client 会暴露日志和连接状态。下面的[在 Claude Desktop 中调试](#debugging-in-claude-desktop)提供了一个示例，也可以查阅你的客户端文档。

## 实现日志

### 服务器端日志

构建使用本地 [stdio transport](/specification/latest/basic/transports#stdio) 的服务器时，所有写入 stderr（standard error）的消息都会被 host 应用自动捕获。

<Warning>
  本地 MCP 服务器不应将日志写入 stdout（standard out），因为这会干扰协议运行。
</Warning>

对于使用 [Streamable HTTP transport](/specification/latest/basic/transports#streamable-http) 的服务器，stderr 不会被客户端捕获。可以使用下面的日志消息通知、你自己的服务器端日志聚合，或标准 HTTP 工具（curl、浏览器 DevTools Network 面板）来检查请求、[`Mcp-Session-Id` headers](/specification/latest/basic/transports#session-management) 和 SSE streams。

对于所有[传输方式](/specification/latest/basic/transports)，也可以通过发送日志消息通知向 client 提供日志：

<CodeGroup>
  ```python Python theme={null}
  @server.tool()
  async def my_tool(ctx: Context) -> str:
      await ctx.session.send_log_message(
          level="info",
          data="Server started successfully",
      )
      return "done"
  ```

  ```typescript TypeScript theme={null}
  await server.sendLoggingMessage({
    level: "info",
    data: "Server started successfully",
  });
  ```
</CodeGroup>

MCP 定义了八个 [RFC 5424 严重级别](/specification/latest/server/utilities/logging#log-levels)（从 `debug` 到 `emergency`）。Client 可以在运行时通过 [`logging/setLevel`](/specification/latest/server/utilities/logging#setting-log-level) 请求调整最低日志级别。

建议记录的重要事件：

* 初始化步骤
* Resource 访问
* Tool 执行
* 错误情况
* 性能指标

## 常见问题

下面的示例使用 Claude Desktop 的 [`claude_desktop_config.json`](/docs/develop/connect-local-servers)；同样的原则适用于任何基于 stdio 的 MCP client。

### 工作目录

当 MCP client 启动 stdio server 时：

* 通过 client 配置启动的服务器，其工作目录可能是未定义的（例如 macOS 上可能是 `/`），因为 client 可能从任意位置启动。
* 始终在配置和 `.env` 文件中使用绝对路径，以确保可靠运行。
* 如果直接通过命令行测试服务器，工作目录就是运行命令的位置。

例如，在 `claude_desktop_config.json` 中使用：

```json theme={null}
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": [
        "-y",
        "@modelcontextprotocol/server-filesystem",
        "/Users/username/data"
      ]
    }
  }
}
```

而不是使用 `./data` 这样的相对路径。

### 环境变量

通过 stdio 启动的 MCP server 只会自动继承有限的一部分环境变量（具体集合取决于平台）。

如果要覆盖默认变量或提供自定义变量，可以在 `claude_desktop_config.json` 中指定 `env` 键：

```json theme={null}
{
  "mcpServers": {
    "myserver": {
      "command": "mcp-server-myapp",
      "env": {
        "MYAPP_API_KEY": "some_key"
      }
    }
  }
}
```

### 服务器初始化

常见初始化问题：

1. **路径问题**
   * 服务器可执行文件路径不正确。
   * 缺少必需文件。
   * 权限问题。
   * 尝试为 `command` 使用绝对路径。

2. **配置错误**
   * JSON 语法无效。
   * 缺少必填字段。
   * 类型不匹配。

3. **环境问题**
   * 缺少环境变量。
   * 变量值不正确。
   * 权限限制。

### 连接问题

当服务器无法连接时：

1. 检查客户端日志。
2. 确认服务器进程正在运行。
3. 使用 [Inspector](/docs/tools/inspector) 独立测试。
4. 验证[协议兼容性](/specification/latest/basic/lifecycle#version-negotiation)。
5. 检查[能力协商](/specification/latest/basic/lifecycle#capability-negotiation)：错误 [`-32602`](/specification/latest/basic/lifecycle#error-handling) 是标准 JSON-RPC `"Invalid params"` 代码，会在多种场景下返回。一个常见原因是 server 向未声明对应能力的 client 发送 [sampling](/specification/latest/client/sampling) 或 [elicitation](/specification/latest/client/elicitation) 请求。请检查 [`initialize` exchange](/specification/latest/basic/lifecycle#initialization)，确认双方声明了你期望的能力。

## 在 Claude Desktop 中调试

Claude Desktop 是众多 MCP client 之一，支持 macOS 和 Windows。

### 检查服务器状态

点击聊天输入框中的 “Add files, connectors, and more” 加号图标，然后悬停在 **Connectors** 菜单上，即可查看已连接服务器和可用 tools。

<img src="https://mintcdn.com/mcp-af858c62/jSqzMzM_desZfWyn/images/available-mcp-tools.png?fit=max&auto=format&n=jSqzMzM_desZfWyn&q=85&s=6bd4fa8c784f3b54987f66089771b2ec" alt="Available MCP tools" width="437" height="244" data-path="images/available-mcp-tools.png" />

### 查看日志

日志文件会写入：

* macOS: `~/Library/Logs/Claude`
* Windows: `%APPDATA%\Claude\logs`

<CodeGroup>
  ```bash macOS theme={null}
  tail -n 20 -F ~/Library/Logs/Claude/mcp*.log
  ```

  ```powershell Windows theme={null}
  type "$env:AppData\Claude\logs\mcp*.log"
  ```
</CodeGroup>

日志会捕获：

* 服务器连接事件
* 配置问题
* 运行时错误
* 消息交换

### 使用 Chrome DevTools

可以在 Claude Desktop 内访问 Chrome 开发者工具，以调查客户端侧错误：

1. 创建 `developer_settings.json` 文件，并将 `allowDevTools` 设为 true：

<CodeGroup>
  ```bash macOS theme={null}
  echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json
  ```

  ```powershell Windows theme={null}
  '{"allowDevTools": true}' | Set-Content "$env:AppData\Claude\developer_settings.json"
  ```
</CodeGroup>

2. 打开 DevTools：`Command-Option-I`（macOS）或 `Ctrl+Alt+I`（Windows）。

注意：你会看到两个 DevTools 窗口：

* 主内容窗口
* 应用标题栏窗口

使用 Console 面板检查客户端侧错误。

使用 Network 面板检查：

* 消息载荷
* 连接时序

## 调试工作流

### 开发周期

1. 初始开发
   * 使用 [Inspector](/docs/tools/inspector) 做基础测试。
   * 实现核心功能。
   * 添加日志点。

2. 集成测试
   * 在目标 MCP client 中测试。
   * 监控日志。
   * 检查错误处理。

### 测试变更

为了高效测试变更：

* **配置变更**：重启 MCP client。
* **服务器代码变更**：重启 client（对于 Claude Desktop，需要完全退出并重新打开；仅关闭窗口不够）。
* **快速迭代**：开发期间使用 [Inspector](/docs/tools/inspector)。

## 最佳实践

### 日志策略

1. **结构化日志**
   * 使用一致格式。
   * 包含上下文。
   * 添加时间戳。
   * 跟踪请求 ID。

2. **错误处理**
   * 记录 stack traces。
   * 包含错误上下文。
   * 跟踪错误模式。
   * 监控恢复过程。

3. **性能跟踪**
   * 记录操作耗时。
   * 监控资源使用。
   * 跟踪消息大小。
   * 测量延迟。

### 安全注意事项

调试时：

1. **敏感数据**
   * 清理日志。
   * 保护凭据。
   * 遮盖个人信息。

2. **访问控制**
   * 验证权限。
   * 检查认证。
   * 监控访问模式。

关于 MCP 攻击向量和缓解措施的完整讨论，请参阅[安全最佳实践](/docs/tutorials/security/security_best_practices)。

## 获取帮助

遇到问题时：

1. **第一步**
   * 检查服务器日志。
   * 使用 [Inspector](/docs/tools/inspector) 测试。
   * 审查配置。
   * 验证环境。

2. **支持渠道**
   * [GitHub issues](https://github.com/modelcontextprotocol/modelcontextprotocol/issues)
   * [GitHub discussions](https://github.com/modelcontextprotocol/modelcontextprotocol/discussions)

3. **提供信息**
   * 日志片段。
   * 配置文件。
   * 复现步骤。
   * 环境详情。

## 后续步骤

<CardGroup cols={2}>
  <Card title="MCP Inspector" icon="magnifying-glass" href="/docs/tools/inspector">
    学习使用 MCP Inspector
  </Card>

  <Card title="构建 MCP 服务器" icon="code" href="/docs/develop/build-server">
    从零开始构建服务器
  </Card>

  <Card title="连接本地服务器" icon="plug" href="/docs/develop/connect-local-servers">
    完整的 claude\_desktop\_config.json 参考和排障说明
  </Card>
</CardGroup>
