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

# 调试

> 调试模型上下文协议（MCP）集成的全面指南

在开发 MCP 服务器或将它们与应用集成时，有效的调试至关重要。本指南涵盖 MCP 生态系统中可用的调试工具和方法。

## 调试工具概览

MCP 提供了若干用于在不同层面进行调试的工具：

1. **[MCP Inspector](/docs/2026-07-28/tools/inspector)**：交互式、与传输无关的测试 UI。连接到 stdio 或 Streamable HTTP 服务器，调用[工具](/specification/latest/server/tools)、[提示](/specification/latest/server/prompts)和[资源](/specification/latest/server/resources)，并观察通知流。这应当是你的第一站。
2. **服务器日志**：结构化日志输出到 stderr（stdio 传输）或通过 [OpenTelemetry](https://opentelemetry.io/)（所有传输）。自协议版本 `2026-07-28` 起，通过协议进行的[日志记录](/specification/2026-07-28/server/utilities/logging)（`notifications/message`）已弃用。
3. **客户端开发者工具**：大多数 MCP 客户端都暴露日志和连接状态。参见下方[在 Claude Desktop 中调试](#在-claude-desktop-中调试)作为一个示例，或查阅你客户端的文档。

## 实现日志记录

### 服务器端日志

在构建使用本地 [stdio 传输](/specification/2026-07-28/basic/transports/stdio)的服务器时，所有记录到 stderr（标准错误）的消息都会被宿主应用自动捕获。

<Warning>
  本地 MCP 服务器不应将消息记录到 stdout（标准输出），因为这会干扰协议运行。
</Warning>

对于使用 [Streamable HTTP 传输](/specification/2026-07-28/basic/transports/streamable-http)的服务器，stderr 不会被客户端捕获。请使用你自己的服务器端日志聚合或 [OpenTelemetry](https://opentelemetry.io/) 来记录日志，并使用标准的 HTTP 工具（curl、浏览器 DevTools Network 面板）来检查请求和 SSE 流。

<Warning>
  下面的 `notifications/message` 机制自协议版本 `2026-07-28` 起已弃用。它在弃用窗口期内仍然可用。
</Warning>

对于所有[传输](/specification/latest/basic/transports)，记录服务器运行时正在做什么：

<CodeGroup>
  ```python Python theme={null}
  import logging

  from mcp.server import MCPServer

  logger = logging.getLogger(__name__)

  mcp = MCPServer("reports")


  @mcp.tool()
  async def fetch_report(report_id: str) -> str:
      """Fetch a report by id."""
      logger.info("Fetching report %s", report_id)
      return f"Report {report_id} is ready."
  ```

  ```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`）。客户端通过在请求的 `_meta` 中设置 [`io.modelcontextprotocol/logLevel`](/specification/2026-07-28/server/utilities/logging#per-request-log-level) 字段，来按请求选择接收日志消息。对于省略该字段的请求，服务器不得发送 `notifications/message`。

需要记录的重要事件：

* 启动步骤
* 资源访问
* 工具执行
* 错误情况
* 性能指标

## 常见问题

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

### 工作目录

当 MCP 客户端启动一个 stdio 服务器时：

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

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

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

而不是像 `./data` 这样的相对路径

### 环境变量

通过 stdio 启动的 MCP 服务器只会自动继承一部分有限的环境变量（确切集合与平台相关）。

要覆盖默认变量或提供你自己的变量，你可以在 `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/2026-07-28/tools/inspector) 独立测试
4. 验证[协议兼容性](/docs/2026-07-28/learn/versioning#negotiation)：调用 [`server/discover`](/specification/2026-07-28/server/discover) 查看服务器支持哪些协议版本。`UnsupportedProtocolVersionError`（`-32022`）会在其 `data` 字段中列出服务器所支持的版本
5. 检查[每请求的 `_meta` 字段](/specification/2026-07-28/basic/index#meta)：每个请求都必须携带 `io.modelcontextprotocol/protocolVersion` 和 `io.modelcontextprotocol/clientCapabilities`，客户端还应包含 `io.modelcontextprotocol/clientInfo`。缺少任一必需字段的请求会以错误 `-32602`（Invalid params）被拒绝，许多其他格式错误的输入也返回相同的代码。如果服务器需要一个请求的 `clientCapabilities` 未声明的能力（例如[征询](/specification/2026-07-28/client/elicitation)），它会返回一个 `MissingRequiredClientCapabilityError`（`-32021`），并指明缺少的能力。检查请求的 `_meta` 和 [`server/discover`](/specification/2026-07-28/server/discover) 响应，以验证双方都声明了你所期望的内容

## 在 Claude Desktop 中调试

Claude Desktop 是众多 MCP 客户端之一。它在 macOS 和 Windows 上可用。

### 检查服务器状态

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

<img src="https://mintcdn.com/mcp-zh-com/fSX9TLdMaDs9iBSP/images/available-mcp-tools.png?fit=max&auto=format&n=fSX9TLdMaDs9iBSP&q=85&s=599cc859dca57fc943135697bf3207ea" alt="可用的 MCP 工具" 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/2026-07-28/tools/inspector) 进行基本测试
   * 实现核心功能
   * 添加日志记录点

2. 集成测试
   * 在你的目标 MCP 客户端中测试
   * 监控日志
   * 检查错误处理

### 测试变更

为高效地测试变更：

* **配置变更**：重启 MCP 客户端
* **服务器代码变更**：重启客户端（对于 Claude Desktop，完全退出并重新打开；仅关闭窗口是不够的）
* **快速迭代**：在开发过程中使用 [Inspector](/docs/2026-07-28/tools/inspector)

## 最佳实践

### 日志策略

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

2. **错误处理**
   * 记录堆栈跟踪
   * 包含错误上下文
   * 跟踪错误模式
   * 监控恢复

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

### 安全考量

在调试时：

1. **敏感数据**
   * 净化日志
   * 保护凭据
   * 屏蔽个人信息

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

有关 MCP 攻击向量和缓解措施的完整论述，参见[安全最佳实践](/docs/2026-07-28/tutorials/security/security_best_practices)。

## 获取帮助

在遇到问题时：

1. **第一步**
   * 检查服务器日志
   * 使用 [Inspector](/docs/2026-07-28/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/2026-07-28/tools/inspector">
    学习使用 MCP Inspector
  </Card>

  <Card title="构建 MCP 服务器" icon="code" href="/docs/2026-07-28/develop/build-server">
    逐步了解如何从零构建一个服务器
  </Card>

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