← 全部新手教程

实操 05 · 英文原文 · 授权全文收录

MCP 官方排错:启动、路径、环境变量与连接

完整收录协议维护者的调试指南,包括 Inspector、服务器日志、常见错误和 Claude Desktop 排查示例。原文为英文。

原作者:
Model Context Protocol 项目贡献者
原文:
Debugging ↗
核对日期:
2026 年 10 月 17 日
转载许可:
CC BY 4.0 · 作者许可声明

核验范围

已读取 2026-07-28 版本全文,核对常见错误、日志位置与重启说明;与 TRAE 日志原教程交叉核对客户端入口差异。已确认文档 CC BY 4.0 许可。

本次仅核对文档,未启动 Inspector、构造故障或改动客户端设置。协议版本相关说明以原文适用版本为准,不能照搬到所有旧版服务。

完整原教程

以下保留作者原文,不改写为本站自拟步骤。 排版与相对链接已转换,未执行原文中的代码;交叉核验补充另列。转载与译文遵循 CC BY 4.0,不代表原作者为本站背书。

Debugging

A comprehensive guide to debugging Model Context Protocol (MCP) integrations

Effective debugging is essential when developing MCP servers or integrating them with applications. This guide covers the debugging tools and approaches available in the MCP ecosystem.

Debugging tools overview

MCP provides several tools for debugging at different levels:

  1. MCP Inspector: interactive, transport-agnostic testing UI. Connect to stdio or Streamable HTTP servers, invoke tools, prompts, and resources, and watch the notification stream. This should be your first stop.
  2. Server logging: structured logs to stderr (stdio transport) or via OpenTelemetry (all transports). Logging over the protocol (notifications/message) is deprecated as of protocol version 2026-07-28.
  3. Client developer tools: most MCP clients expose logs and connection state. See Debugging in Claude Desktop below for one example, or consult your client's documentation.

Implementing logging

Server-side logging

When building a server that uses the local stdio transport, all messages logged to stderr (standard error) will be captured by the host application automatically.

Local MCP servers should not log messages to stdout (standard out), as this will interfere with protocol operation.

For servers using the Streamable HTTP transport, stderr is not captured by the client. Use your own server-side log aggregation or OpenTelemetry for logs, and standard HTTP tooling (curl, browser DevTools Network panel) to inspect requests and SSE streams.

The notifications/message mechanism below is deprecated as of protocol version 2026-07-28. It remains available during the deprecation window.

For all transports, record what the server is doing as it runs:

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."
await server.sendLoggingMessage({
  level: "info",
  data: "Server started successfully",
});

MCP defines eight RFC 5424 severity levels (debug through emergency). Clients opt in to log messages per request by setting the io.modelcontextprotocol/logLevel field in the request's _meta. Servers must not send notifications/message for requests that omit this field.

Important events to log:

  • Startup steps
  • Resource access
  • Tool execution
  • Error conditions
  • Performance metrics

Common issues

The examples below use Claude Desktop's claude_desktop_config.json; the same principles apply to any stdio-based MCP client.

Working directory

When an MCP client launches a stdio server:

  • The working directory for servers launched via the client's config may be undefined (like / on macOS) since the client could be started from anywhere
  • Always use absolute paths in your configuration and .env files to ensure reliable operation
  • For testing servers directly via command line, the working directory will be where you run the command

For example in claude_desktop_config.json, use:

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

Instead of relative paths like ./data

Environment variables

MCP servers launched over stdio inherit only a limited subset of environment variables automatically (the exact set is platform-dependent).

To override the default variables or provide your own, you can specify an env key in claude_desktop_config.json:

{
  "mcpServers": {
    "myserver": {
      "command": "mcp-server-myapp",
      "env": {
        "MYAPP_API_KEY": "some_key"
      }
    }
  }
}

Server startup

Common startup problems:

  1. Path Issues

    • Incorrect server executable path
    • Missing required files
    • Permission problems
    • Try using an absolute path for command
  2. Configuration Errors

    • Invalid JSON syntax
    • Missing required fields
    • Type mismatches
  3. Environment Problems

    • Missing environment variables
    • Incorrect variable values
    • Permission restrictions

Connection problems

When servers fail to connect:

  1. Check client logs
  2. Verify server process is running
  3. Test standalone with Inspector
  4. Verify protocol compatibility: call server/discover to see which protocol versions the server supports. An UnsupportedProtocolVersionError (-32022) lists the server's supported versions in its data field
  5. Check the per-request _meta fields: every request must carry io.modelcontextprotocol/protocolVersion and io.modelcontextprotocol/clientCapabilities, and clients should also include io.modelcontextprotocol/clientInfo. A request missing either required field is rejected with error -32602 (Invalid params), the same code returned for many other malformed inputs. If the server needs a capability the request's clientCapabilities did not declare, such as elicitation, it returns a MissingRequiredClientCapabilityError (-32021) naming the missing capabilities. Inspect the request's _meta and the server/discover response to verify both sides declared what you expect

Debugging in Claude Desktop

Claude Desktop is one of many MCP clients. It is available on macOS, Windows, and Linux.

Checking server status

Click the "Add files, connectors, and more" plus icon in the chat input, then hover over the Connectors menu to see connected servers and available tools.

Available MCP tools

Viewing logs

Log files are written to:

  • macOS: ~/Library/Logs/Claude
  • Windows: %APPDATA%\Claude\logs
tail -n 20 -F ~/Library/Logs/Claude/mcp*.log
type "$env:AppData\Claude\logs\mcp*.log"

The logs capture:

  • Server connection events
  • Configuration issues
  • Runtime errors
  • Message exchanges

Using Chrome DevTools

Access Chrome's developer tools inside Claude Desktop to investigate client-side errors:

  1. Create a developer_settings.json file with allowDevTools set to true:
echo '{"allowDevTools": true}' > ~/Library/Application\ Support/Claude/developer_settings.json
'{"allowDevTools": true}' | Set-Content "$env:AppData\Claude\developer_settings.json"
  1. Open DevTools: Command-Option-I (macOS) or Ctrl+Alt+I (Windows)

Note: You'll see two DevTools windows:

  • Main content window
  • App title bar window

Use the Console panel to inspect client-side errors.

Use the Network panel to inspect:

  • Message payloads
  • Connection timing

Debugging workflow

Development cycle

  1. Initial Development

    • Use Inspector for basic testing
    • Implement core functionality
    • Add logging points
  2. Integration Testing

    • Test in your target MCP client
    • Monitor logs
    • Check error handling

Testing changes

To test changes efficiently:

  • Configuration changes: Restart the MCP client
  • Server code changes: Restart the client (for Claude Desktop, fully quit and reopen; closing the window is not enough)
  • Quick iteration: Use Inspector during development

Best practices

Logging strategy

  1. Structured Logging

    • Use consistent formats
    • Include context
    • Add timestamps
    • Track request IDs
  2. Error Handling

    • Log stack traces
    • Include error context
    • Track error patterns
    • Monitor recovery
  3. Performance Tracking

    • Log operation timing
    • Monitor resource usage
    • Track message sizes
    • Measure latency

Security considerations

When debugging:

  1. Sensitive Data

    • Sanitize logs
    • Protect credentials
    • Mask personal information
  2. Access Control

    • Verify permissions
    • Check authentication
    • Monitor access patterns

For a full treatment of MCP attack vectors and mitigations, see Security Best Practices.

Getting help

When encountering issues:

  1. First Steps

    • Check server logs
    • Test with Inspector
    • Review configuration
    • Verify environment
  2. Support Channels

  3. Providing Information

    • Log excerpts
    • Configuration files
    • Steps to reproduce
    • Environment details

Next steps

MCP Inspector

Learn to use the MCP Inspector

Build an MCP server

Walk through building a server from scratch

Connect local servers

Full claude_desktop_config.json reference and troubleshooting

原文快照 SHA-256:b93e9e2857915eab1745198d64d67a9fa7d504b68d928e5576550cf21bab098a

交叉核验补充

以下为本站核对说明,与上方原教程区分展示。

普通使用者先看常见问题

Common issues 依次解释工作目录、环境变量、启动与连接问题。客户端启动服务时,环境和工作目录可能与手动运行终端不同;原文建议配置绝对路径,并检查 JSON 与必要环境变量。不要因为终端能运行,就认定客户端一定能启动。

日志入口由客户端决定

Claude Desktop 示例在 Windows 使用 %APPDATA%\Claude\logs,在 macOS 使用 ~/Library/Logs/Claude;TRAE 则通过输出面板的 MCP Server Host 查看。原文还说明 stdio 服务的普通日志应写入 stderr,写入 stdout 会干扰协议;这部分主要供服务器开发者阅读。

进一步定位与求助

客户端日志不足时,原文提供 Inspector 独立测试、版本兼容检查和 DevTools 等方法。修改配置后要重启客户端;Claude Desktop 需完全退出,关闭窗口不够。向维护者求助时提供复现步骤、环境与经脱敏的日志,隐藏密钥和个人信息。