社区交流 ·
使用 MCP Inspector 调试
开源教程转载|使用 MCP Inspector 调试。Microsoft 及项目贡献者编写,智链谷平台运营整理。
> 开源教程转载 · 由智链谷平台运营账号整理发布。作者:Microsoft 及项目贡献者。
> [查看原文](https://github.com/microsoft/mcp-for-beginners/blob/2f43408b764326df5fc928984c6dd7db2b8fb63e/translations/zh-CN/03-GettingStarted/13-mcp-inspector/README.md) · MIT 许可,完整声明见文末。
# 使用 MCP Inspector 调试
**MCP Inspector** 是一个必备的调试工具,允许您交互式测试和排查 MCP 服务器问题,而无需完整的 AI 主机应用程序。可以将其视为“MCP 的 Postman”——它提供可视界面发送请求、查看响应,并了解服务器的行为。
## 为什么使用 MCP Inspector?
构建 MCP 服务器时,您经常会遇到以下挑战:
- **“我的服务器运行了吗?”** - Inspector 显示连接状态
- **“我的工具注册正确吗?”** - Inspector 列出所有可用工具
- **“响应格式是什么?”** - Inspector 显示完整 JSON 响应
- **“为什么这个工具不起作用?”** - Inspector 显示详细错误消息
## 前提条件
- 已安装 Node.js 18+
- npm(随 Node.js 一起安装)
- 一个用于测试的 MCP 服务器(参见 [模块 3.1 - 第一个服务器](https://github.com/microsoft/mcp-for-beginners/blob/2f43408b764326df5fc928984c6dd7db2b8fb63e/translations/zh-CN/03-GettingStarted/01-first-server/README.md))
## 安装
### 选项 1:使用 npx 运行(推荐快速测试)
```bash
npx @modelcontextprotocol/inspector
```
### 选项 2:全局安装
```bash
npm install -g @modelcontextprotocol/inspector
mcp-inspector
```
### 选项 3:添加到您的项目
```bash
cd your-mcp-server-project
npm install --save-dev @modelcontextprotocol/inspector
```
添加至 `package.json`:
```json
{
"scripts": {
"inspector": "mcp-inspector"
}
}
```
---
## 连接到您的服务器
### stdio 服务器(本地进程)
对于通过标准输入/输出通信的服务器:
```bash
# Python 服务器
npx @modelcontextprotocol/inspector python -m your_server_module
# Node.js 服务器
npx @modelcontextprotocol/inspector node ./build/index.js
# 使用环境变量
OPENAI_API_KEY=xxx npx @modelcontextprotocol/inspector python server.py
```
### SSE/HTTP 服务器(网络)
对于作为 HTTP 服务运行的服务器:
1. 先启动您的服务器:
```bash
python server.py # 服务器运行在 http://localhost:8080 上
```
2. 启动 Inspector 并连接:
```bash
npx @modelcontextprotocol/inspector --sse http://localhost:8080/sse
```
---
## Inspector 界面概览
启动 Inspector 时,您会看到一个网页界面(通常位于 `http://localhost:5173`):
```
┌─────────────────────────────────────────────────────────────┐
│ MCP Inspector [Connected ✅] │
├─────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │
│ │ 🔧 Tools │ │ 📄 Resources│ │ 💬 Prompts │ │
│ │ (3) │ │ (2) │ │ (1) │ │
│ └─────────────┘ └─────────────┘ └─────────────┘ │
│ │
│ ┌───────────────────────────────────────────────────────┐ │
│ │ 📋 Message Log │ │
│ │ ─────────────────────────────────────────────────── │ │
│ │ → initialize │ │
│ │ ← initialized (server info) │ │
│ │ → tools/list │ │
│ │ ← tools (3 tools) │ │
│ └───────────────────────────────────────────────────────┘ │
│ │
└─────────────────────────────────────────────────────────────┘
```
---
## 测试工具
### 列出可用工具
1. 点击 **Tools** 选项卡
2. Inspector 会自动调用 `tools/list`
3. 您将看到所有已注册的工具,包括:
- 工具名称
- 描述
- 输入参数模式(schema)
### 调用工具
1. 从列表中选择一个工具
2. 在表单中填写所需参数
3. 点击 **Run Tool**
4. 在结果面板查看响应
**示例:测试计算器工具**
```
Tool: add
Parameters:
a: 25
b: 17
Response:
{
"content": [
{
"type": "text",
"text": "42"
}
]
}
```
### 调试工具错误
工具调用失败时,Inspector 显示:
```
Error Response:
{
"error": {
"code": -32602,
"message": "Invalid params: 'b' is required"
}
}
```
常见错误代码:
| 代码 | 含义 |
|---------|-------------------------|
| -32700 | 解析错误(无效的 JSON) |
| -32600 | 无效请求 |
| -32601 | 方法未找到 |
| -32602 | 无效参数 |
| -32603 | 内部错误 |
---
## 测试资源
### 列出资源
1. 点击 **Resources** 选项卡
2. Inspector 调用 `resources/list`
3. 您将看到:
- 资源 URI
- 名称和描述
- MIME 类型
### 读取资源
1. 选择一个资源
2. 点击 **Read Resource**
3. 查看返回的内容
**示例输出:**
```
Resource: file:///config/settings.json
Content-Type: application/json
{
"config": {
"debug": true,
"maxConnections": 10
}
}
```
---
## 测试提示
### 列出提示
1. 点击 **Prompts** 选项卡
2. Inspector 调用 `prompts/list`
3. 查看可用的提示模板
### 获取提示
1. 选择一个提示
2. 填写任何必填参数
3. 点击 **Get Prompt**
4. 查看渲染后的提示消息
---
## 消息日志分析
消息日志显示所有 MCP 协议消息:
```
14:32:01 → {"jsonrpc":"2.0","id":1,"method":"initialize",...}
14:32:01 ← {"jsonrpc":"2.0","id":1,"result":{"protocolVersion":"2025-11-25",...}}
14:32:02 → {"jsonrpc":"2.0","id":2,"method":"tools/list"}
14:32:02 ← {"jsonrpc":"2.0","id":2,"result":{"tools":[...]}}
14:32:05 → {"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add",...}}
14:32:05 ← {"jsonrpc":"2.0","id":3,"result":{"content":[...]}}
```
### 注意事项
- **请求/响应对**:每个 `→` 应该对应一个 `←`
- **错误消息**:查看响应中的 `"error"`
- **时间间隔**:大间隙可能指示性能问题
- **协议版本**:确保服务器和客户端使用相同版本
---
## VS Code 集成
您可以直接在 VS Code 中运行 Inspector:
### 使用 launch.json
添加到 `.vscode/launch.json`:
```json
{
"version": "0.2.0",
"configurations": [
{
"name": "Debug with MCP Inspector",
"type": "node",
"request": "launch",
"runtimeExecutable": "npx",
"runtimeArgs": [
"@modelcontextprotocol/inspector",
"python",
"${workspaceFolder}/server.py"
],
"console": "integratedTerminal"
},
{
"name": "Debug SSE Server with Inspector",
"type": "chrome",
"request": "launch",
"url": "http://localhost:5173",
"preLaunchTask": "Start MCP Inspector"
}
]
}
```
### 使用任务(Tasks)
添加到 `.vscode/tasks.json`:
```json
{
"version": "2.0.0",
"tasks": [
{
"label": "Start MCP Inspector",
"type": "shell",
"command": "npx @modelcontextprotocol/inspector node ${workspaceFolder}/build/index.js",
"isBackground": true,
"problemMatcher": {
"pattern": {
"regexp": "^$"
},
"background": {
"activeOnStart": true,
"beginsPattern": "Inspector",
"endsPattern": "listening"
}
}
}
]
}
```
---
## 常见调试场景
### 场景 1:服务器无法连接
**症状:** Inspector 显示“Disconnected”或卡在“Connecting...”页面
**检查清单:**
1. ✅ 服务器命令是否正确?
2. ✅ 所有依赖是否安装?
3. ✅ 服务器路径是绝对路径还是相对于当前目录?
4. ✅ 必需的环境变量是否设置?
**调试步骤:**
```bash
# 先手动测试服务器
python -c "import your_server_module; print('OK')"
# 检查导入错误
python -m your_server_module 2>&1 | head -20
# 验证是否安装了MCP SDK
pip show mcp
```
### 场景 2:工具列表为空
**症状:** 工具选项卡显示空列表
**可能原因:**
1. 服务器初始化时未注册工具
2. 服务器启动后崩溃
3. `tools/list` 处理器返回空数组
**调试步骤:**
1. 检查消息日志中的 `tools/list` 响应
2. 在工具注册代码中添加日志
3. 确认 `@mcp.tool()` 装饰器是否存在(Python)
### 场景 3:工具返回错误
**症状:** 工具调用返回错误响应
**调试方法:**
1. 仔细阅读错误信息
2. 检查参数类型是否与 schema 匹配
3. 增加 try/catch 并输出详细错误信息
4. 检查服务器日志中的堆栈跟踪
**示例改进的错误处理:**
```python
@mcp.tool()
async def my_tool(param1: str, param2: int) -> str:
try:
# 工具逻辑在这里
result = process(param1, param2)
return str(result)
except ValueError as e:
raise McpError(f"Invalid parameter: {e}")
except Exception as e:
raise McpError(f"Tool failed: {type(e).__name__}: {e}")
```
### 场景 4:资源内容为空
**症状:** 资源成功返回但内容为空或为 null
**检查清单:**
1. ✅ 文件路径或 URI 正确
2. ✅ 服务器有权限读取资源
3. ✅ 资源内容正确返回
---
## Inspector 高级功能
### 自定义头部(SSE)
```bash
npx @modelcontextprotocol/inspector \
--sse http://localhost:8080/sse \
--header "Authorization: Bearer your-token"
```
### 详细日志记录
```bash
DEBUG=mcp* npx @modelcontextprotocol/inspector python server.py
```
### 会话录制
Inspector 可以导出消息日志以供后续分析:
1. 在消息面板点击 **Export Log**
2. 保存 JSON 文件
3. 与团队成员共享调试
---
## 最佳实践
1. **尽早且频繁测试** —— 开发过程中使用 Inspector 而非仅在出错时
2. **从简单开始** —— 先测试基本连通性,再调用复杂工具
3. **验证模式** —— 许多错误源自参数类型不匹配
4. **阅读错误信息** —— MCP 错误通常描述清晰
5. **保持 Inspector 打开** —— 有助于开发时捕捉问题
---
## 接下来
您已完成模块 3:入门!继续学习:
- [模块 4:实用实现](https://github.com/microsoft/mcp-for-beginners/blob/2f43408b764326df5fc928984c6dd7db2b8fb63e/translations/zh-CN/04-PracticalImplementation/README.md)
---
## 额外资源
- [MCP Inspector GitHub 仓库](https://github.com/modelcontextprotocol/inspector)
- [MCP 规范 - 协议消息](https://spec.modelcontextprotocol.io/specification/2025-11-25/)
- [JSON-RPC 2.0 规范](https://www.jsonrpc.org/specification)
---
<!-- CO-OP TRANSLATOR DISCLAIMER START -->
**免责声明**:
本文件由 AI 翻译服务 [Co-op Translator](https://github.com/Azure/co-op-translator) 翻译。虽然我们力求准确,但请注意,自动翻译可能包含错误或不准确之处。应将原始语言版本的文件视为权威来源。对于关键信息,建议使用专业人工翻译。因使用本翻译而产生的任何误解或曲解,本公司概不负责。
<!-- CO-OP TRANSLATOR DISCLAIMER END -->
---
## 版权与许可
```text
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE
```