Skip to content

MCP Inspector

MCP Inspector 是一个强大的调试和测试工具,用于检查、测试和调试 Model Context Protocol (MCP) 服务器。它提供了一个直观的 Web 界面,让开发者能够轻松地与 MCP 服务器交互。

概述

MCP Inspector 是官方提供的调试工具,具有以下特性:

  • 实时连接测试: 连接并测试本地和远程 MCP 服务器
  • 交互式界面: 直观的 Web UI 用于探索服务器功能
  • 协议验证: 验证 MCP 协议实现的正确性
  • 性能监控: 监控请求响应时间和连接状态
  • 日志查看: 实时查看协议消息和错误日志

安装和启动

1. 使用 npx (推荐)

bash
# 直接运行,无需安装
npx @modelcontextprotocol/inspector

2. 全局安装

bash
# 全局安装
npm install -g @modelcontextprotocol/inspector

# 启动 Inspector
mcp-inspector

3. 本地开发安装

bash
# 克隆仓库
git clone https://github.com/modelcontextprotocol/inspector.git
cd inspector

# 安装依赖
npm install

# 启动开发服务器
npm run dev

基本使用

1. 启动 Inspector

bash
npx @modelcontextprotocol/inspector

启动后,Inspector 会在浏览器中打开,默认地址为 http://localhost:3000

2. 连接服务器

连接本地服务器 (stdio)

  1. 在 Inspector 界面中选择 "Local Server"
  2. 输入服务器启动命令,例如:
    bash
    python server.py
  3. 点击 "Connect" 建立连接

连接远程服务器 (SSE)

  1. 选择 "Remote Server (SSE)"
  2. 输入服务器 URL,例如:
    https://api.example.com/mcp/sse
  3. 配置认证信息(如需要)
  4. 点击 "Connect"

连接 WebSocket 服务器

  1. 选择 "WebSocket Server"
  2. 输入 WebSocket URL,例如:
    wss://api.example.com/mcp/ws
  3. 配置连接参数
  4. 点击 "Connect"

界面功能

1. 连接状态面板

显示当前连接状态和服务器信息:

┌─ Connection Status ─────────────────────────┐
│ Status: Connected ✅                        │
│ Protocol Version: 2025-06-18               │
│ Server: WeatherServer v1.0.0               │
│ Transport: stdio                           │
│ Uptime: 00:05:23                          │
└────────────────────────────────────────────┘

2. 工具 (Tools) 面板

列出服务器提供的所有工具:

┌─ Available Tools ──────────────────────────┐
│ 🔧 get_weather                             │
│    Get current weather information         │
│    Parameters: location (string)           │
│                                            │
│ 🔧 calculate                               │
│    Perform mathematical calculations       │
│    Parameters: expression (string)         │
│                                            │
│ 🔧 search_web                              │
│    Search the web for information          │
│    Parameters: query (string), limit (int) │
└────────────────────────────────────────────┘

3. 资源 (Resources) 面板

显示服务器提供的资源:

┌─ Available Resources ──────────────────────┐
│ 📄 file://config.json                      │
│    Configuration file                      │
│                                            │
│ 📄 file://logs/app.log                     │
│    Application logs                        │
│                                            │
│ 🌐 https://api.weather.com/data            │
│    Weather API data                        │
└────────────────────────────────────────────┘

4. 提示词 (Prompts) 面板

列出服务器提供的提示词模板:

┌─ Available Prompts ────────────────────────┐
│ 💬 weather_report                          │
│    Generate a weather report              │
│    Arguments: location, date               │
│                                            │
│ 💬 data_analysis                           │
│    Analyze data and provide insights       │
│    Arguments: data_source, analysis_type   │
└────────────────────────────────────────────┘

测试功能

1. 工具调用测试

在工具面板中点击任意工具进行测试:

json
{
  "tool": "get_weather",
  "arguments": {
    "location": "San Francisco"
  }
}

响应示例:

json
{
  "content": [
    {
      "type": "text",
      "text": "Current weather in San Francisco: Sunny, 72°F (22°C), Light breeze from the west at 5 mph. Humidity: 65%"
    }
  ]
}

2. 资源读取测试

点击资源项目查看内容:

json
{
  "resource": "file://config.json"
}

响应示例:

json
{
  "contents": [
    {
      "uri": "file://config.json",
      "mimeType": "application/json",
      "text": "{\n  \"api_key\": \"***\",\n  \"timeout\": 30,\n  \"retries\": 3\n}"
    }
  ]
}

3. 提示词测试

测试提示词模板:

json
{
  "name": "weather_report",
  "arguments": {
    "location": "New York",
    "date": "2024-01-15"
  }
}

高级功能

1. 协议消息查看器

Inspector 提供实时的协议消息查看功能:

┌─ Protocol Messages ────────────────────────┐
│ [14:30:15] → tools/list                    │
│ {                                          │
│   "jsonrpc": "2.0",                        │
│   "method": "tools/list",                  │
│   "id": 1                                  │
│ }                                          │
│                                            │
│ [14:30:15] ← tools/list response           │
│ {                                          │
│   "jsonrpc": "2.0",                        │
│   "result": {                              │
│     "tools": [...]                         │
│   },                                       │
│   "id": 1                                  │
│ }                                          │
└────────────────────────────────────────────┘

2. 性能监控

监控请求性能和连接质量:

┌─ Performance Metrics ──────────────────────┐
│ Average Response Time: 125ms               │
│ Total Requests: 47                         │
│ Failed Requests: 2                         │
│ Success Rate: 95.7%                        │
│                                            │
│ Recent Requests:                           │
│ tools/call (get_weather): 89ms ✅          │
│ resources/read: 156ms ✅                   │
│ tools/call (calculate): timeout ❌         │
└────────────────────────────────────────────┘

3. 批量测试

执行批量测试脚本:

javascript
// 批量测试脚本示例
const testSuite = [
  {
    name: "Weather Tool Test",
    tool: "get_weather",
    arguments: { location: "London" },
    expect: { type: "text" }
  },
  {
    name: "Calculator Test",
    tool: "calculate",
    arguments: { expression: "2 + 2" },
    expect: { content: "4" }
  }
];

// 运行测试套件
await runTestSuite(testSuite);

配置选项

1. 连接配置

json
{
  "connection": {
    "timeout": 30000,
    "retries": 3,
    "keepAlive": true,
    "reconnect": true
  },
  "logging": {
    "level": "debug",
    "saveToFile": true,
    "maxLogSize": "10MB"
  },
  "ui": {
    "theme": "dark",
    "autoRefresh": true,
    "refreshInterval": 5000
  }
}

2. 环境变量

bash
# 设置 Inspector 端口
export MCP_INSPECTOR_PORT=3000

# 设置日志级别
export MCP_INSPECTOR_LOG_LEVEL=debug

# 设置主题
export MCP_INSPECTOR_THEME=dark

# 启用自动保存
export MCP_INSPECTOR_AUTO_SAVE=true

调试技巧

1. 常见问题诊断

连接失败

❌ Connection failed: ECONNREFUSED

解决方案:

  • 检查服务器是否正在运行
  • 验证端口和地址是否正确
  • 检查防火墙设置

协议版本不匹配

❌ Protocol version mismatch: server=2024-11-05, client=2025-06-18

解决方案:

  • 更新服务器到最新版本
  • 或使用兼容的 Inspector 版本

工具调用超时

❌ Tool call timeout after 30s

解决方案:

  • 增加超时时间设置
  • 检查工具实现是否有性能问题
  • 验证网络连接稳定性

2. 日志分析

启用详细日志记录:

bash
# 启动时启用调试日志
MCP_INSPECTOR_LOG_LEVEL=debug npx @modelcontextprotocol/inspector

查看日志文件:

bash
# 日志文件位置
~/.mcp-inspector/logs/inspector.log

3. 网络调试

使用网络面板查看 HTTP/WebSocket 流量:

┌─ Network Activity ─────────────────────────┐
│ [14:35:22] POST /mcp/tools/call            │
│ Status: 200 OK                             │
│ Duration: 234ms                            │
│ Size: 1.2KB                                │
│                                            │
│ [14:35:25] GET /mcp/events (SSE)           │
│ Status: 200 OK                             │
│ Duration: ongoing                          │
│ Events received: 15                        │
└────────────────────────────────────────────┘

集成到开发流程

1. 自动化测试

创建测试脚本:

javascript
// test-mcp-server.js
const { MCPInspector } = require('@modelcontextprotocol/inspector');

async function testServer() {
  const inspector = new MCPInspector();
  
  try {
    // 连接服务器
    await inspector.connect({
      command: 'python server.py',
      type: 'stdio'
    });
    
    // 测试工具列表
    const tools = await inspector.listTools();
    console.log(`Found ${tools.length} tools`);
    
    // 测试每个工具
    for (const tool of tools) {
      try {
        const result = await inspector.callTool(tool.name, {});
        console.log(`✅ ${tool.name}: OK`);
      } catch (error) {
        console.log(`❌ ${tool.name}: ${error.message}`);
      }
    }
    
  } finally {
    await inspector.disconnect();
  }
}

testServer().catch(console.error);

2. CI/CD 集成

yaml
# .github/workflows/test-mcp.yml
name: Test MCP Server
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      
      - name: Setup Node.js
        uses: actions/setup-node@v3
        with:
          node-version: '18'
          
      - name: Install dependencies
        run: npm install
        
      - name: Test MCP Server
        run: |
          npm install -g @modelcontextprotocol/inspector
          node test-mcp-server.js

扩展和自定义

1. 自定义插件

javascript
// custom-plugin.js
class CustomInspectorPlugin {
  constructor(inspector) {
    this.inspector = inspector;
  }
  
  async onConnect(serverInfo) {
    console.log('Connected to:', serverInfo.name);
    // 自定义连接后逻辑
  }
  
  async onToolCall(toolName, args, result) {
    // 记录工具调用
    this.logToolCall(toolName, args, result);
  }
  
  logToolCall(toolName, args, result) {
    const logEntry = {
      timestamp: new Date().toISOString(),
      tool: toolName,
      arguments: args,
      result: result,
      duration: result.duration
    };
    
    // 保存到自定义日志
    this.saveToCustomLog(logEntry);
  }
}

// 注册插件
inspector.use(new CustomInspectorPlugin(inspector));

2. 自定义主题

css
/* custom-theme.css */
:root {
  --primary-color: #007acc;
  --background-color: #1e1e1e;
  --text-color: #d4d4d4;
  --border-color: #3c3c3c;
}

.inspector-panel {
  background-color: var(--background-color);
  color: var(--text-color);
  border: 1px solid var(--border-color);
}

.tool-item:hover {
  background-color: var(--primary-color);
}

相关资源

🚀 探索模型上下文协议的无限可能 | 连接 AI 与世界的桥梁 | 让智能更智能