MCP服务器监控工具

MCP Monitor是一个轻量级的开源可观测性平台,专为Model Context Protocol (MCP)服务器设计,提供实时监控、性能指标、错误跟踪和调试功能。

  • by anyrxo
  • TypeScript
  • 本地部署
  • 1 星标
  • 更新于
在 GitHub 查看 anyrxo/mcp-monitor

使用说明

📊 MCP监视器-MCP服务器的实时可观察性

模型上下文协议(MCP)服务器的生产就绪监控、调试和性能分析

📖 概述

MCP监视器 是一个用于模型上下文协议(MCP)服务器的轻量级开源可观察性平台。它提供实时监控、性能指标、错误跟踪和调试功能——想想MCP服务器的“htop”。

为什么选择MCP Monitor?

随着MCP采用率的增长,服务器可观察性对于以下方面变得至关重要:

  • 生产调试:实时追踪问题
  • 性能优化:识别瓶颈和缓慢的工具
  • 错误监视:捕捉和诊断故障
  • 使用情况分析:了解哪些工具被称为最常用的工具
  • 容量规划:监控请求率和延迟

主要特点

✅ 实时终端仪表板 -美丽的基于祝福的UI,带有实时指标 ✅ HTTP/WebSocket API -通过程序访问指标 ✅ 自动化仪表 -通过拦截器实现零代码集成 ✅ 性能指标 -P50/P95/P99延迟、RPS、错误率 ✅ 工具分析 -每个工具的成功率、呼叫次数、平均持续时间 ✅ 资源跟踪 -监控文件访问,传输的字节数 ✅ 即时监控 -跟踪提示呼叫和令牌使用情况 ✅ 错误记录 -捕获并分类所有错误 ✅ 指标导出 -JSON导出用于分析和存档

🚀 快速开始

安装

# Clone repository
git clone <repository-url>
cd mcp-monitor

# Install dependencies
npm install

# Build TypeScript
npm run build

基本用法

1.交互式仪表板

启动实时终端仪表板:

node dist/cli.js dashboard --name "My MCP Server" --port 3000

按 r 为了重置度量, q 退出。

2.监控服务器

启动HTTP API服务器进行远程监控:

node dist/cli.js server --port 3000

访问指标:

  • API http://localhost:3000/api/metrics
  • 出口: http://localhost:3000/api/export
  • Websocket: ws://localhost:3000

3.检测您的MCP服务器

import { TelemetryCollector, MCPInterceptor } from 'mcp-monitor';

// Your MCP server
const myServer = {
  tools: {
    'read-file': async (params) => { /* ... */ },
    'write-file': async (params) => { /* ... */ }
  }
};

// Create collector
const collector = new TelemetryCollector({
  serverName: 'My MCP Server',
  port: 3000,
  retentionDays: 7,
  enableWebUI: true,
  enableMetricsExport: true
});

// Instrument server (automatic monitoring)
const interceptor = new MCPInterceptor(collector);
const monitoredServer = interceptor.instrument(myServer);

// Use monitoredServer instead of myServer - all calls are now monitored!
await monitoredServer.tools['read-file']({ path: '/tmp/file.txt' });

📊 仪表板预览

╔═══════════════════════════════════════════════════════════╗
║   MCP MONITOR - Real-time Observability for MCP Servers  ║
╚═══════════════════════════════════════════════════════════╝

┌─ 📊 Server Overview ─────────┐  ┌─ 🔧 Tool Metrics ──────────┐
│ Server: My MCP Server        │  │ Tool         Calls  Errors │
│ Uptime: 5m 23s               │  │ read-file    142    3      │
│                              │  │ write-file   89     0      │
│ Requests:                    │  │ list-dir     67     1      │
│   Total: 298                 │  └────────────────────────────┘
│   Success: 294               │
│   Failed: 4                  │  ┌─ ⚡ Latency (ms) ──────────┐
│                              │  │ Avg: 45.2ms                │
│ Performance:                 │  │ P50: 38ms                  │
│   Avg Latency: 45.2ms        │  │ P95: 127ms                 │
│   Error Rate: 1.34%          │  │ P99: 203ms                 │
│   Success Rate: 98.66%       │  └────────────────────────────┘
│                              │
│ Current:                     │  ┌─ ⚠️  Recent Errors ─────────┐
│   Requests/min: 56           │  │ [10:42:15] tool:read-file  │
│   Requests/sec: 0.93         │  │   File not found           │
│                              │  │ [10:41:32] tool:list-dir   │
│ Press 'r' to reset, 'q' quit │  │   Permission denied        │
└──────────────────────────────┘  └────────────────────────────┘

🔧 CLI命令

dashboard

启动带有实时指标的交互式终端仪表板。

node dist/cli.js dashboard [options]

选项:

  • -n, --name <name> -服务器名称(默认:“MCP服务器”)
  • -p, --port <port> -API服务器端口(默认:3000)
  • --no-api -禁用API服务器

键盘快捷键:

  • r -重置所有指标
  • q / Escape / Ctrl+C -退出

server

启动HTTP API服务器,以便对指标进行编程访问。

node dist/cli.js server [options]

选项:

  • -n, --name <name> -服务器名称(默认:“MCP服务器”)
  • -p, --port <port> -服务器端口(默认值:3000)
  • -r, --retention <days> -数据保留天数(默认值:7)

终点:

  • GET /health -健康检查
  • GET /api/metrics -当前指标(JSON)
  • GET /api/export -导出所有指标(下载)
  • POST /api/tool-call -记录工具调用
  • POST /api/resource-access -记录资源访问
  • POST /api/prompt-call -记录提示通话
  • POST /api/reset -重置所有指标
  • WebSocket / -实时指标流

status

从正在运行的监视服务器获取当前状态。

node dist/cli.js status <url> [options]

选项:

  • --json -输出为JSON

例子:

node dist/cli.js status http://localhost:3000

export

将指标从正在运行的监控服务器导出到文件。

node dist/cli.js export <url> [options]

选项:

  • -o, --output <file> -输出文件(默认值: mcp-metrics-{timestamp}.json)

例子:

node dist/cli.js export http://localhost:3000 -o metrics.json

📈 收集的指标

工具指标

  • 呼叫计数 -总调用次数
  • 成功/错误计数 -状态跟踪
  • 平均持续时间 -性能分析
  • 上次通话时间 -时间戳
  • 错误消息 -调试

资源指标

  • 访问计数 -总访问量
  • 成功/错误计数 -状态跟踪
  • 传输的字节数 -数据量
  • 平均持续时间 演出

提示指标

  • 呼叫计数 -总调用次数
  • 成功/错误计数 -状态跟踪
  • 平均持续时间 演出
  • 令牌计数 -使用情况跟踪

性能指标

  • 平均延迟 -平均响应时间
  • P50/P95/P99延迟 -百分位数分析
  • 每秒请求数 -吞吐量
  • 错误率 -可靠性度量
  • 成功率 -质量指标

服务器指标

  • 运行时间 -服务器运行时间
  • 请求总数 -所有时间计数
  • 每分钟请求数 -当前负载
  • 错误日志 -最近发生的带有时间戳的错误

🔌 API集成

HTTP API

记录来自外部MCP服务器的遥测数据:

# Record a tool call
curl -X POST http://localhost:3000/api/tool-call \
  -H "Content-Type: application/json" \
  -d '{
    "toolName": "read-file",
    "params": {"path": "/tmp/test.txt"},
    "status": "success",
    "duration": 123
  }'

# Get current metrics
curl http://localhost:3000/api/metrics

WebSocket实时流

const ws = new WebSocket('ws://localhost:3000');

ws.on('message', (data) => {
  const message = JSON.parse(data);

  if (message.type === 'metrics') {
    console.log('Server metrics:', message.data);
  } else if (message.type === 'tool_call') {
    console.log('Tool called:', message.data.toolName);
  } else if (message.type === 'error') {
    console.error('Error occurred:', message.data);
  }
});

程序化使用

import { TelemetryCollector } from 'mcp-monitor';

const collector = new TelemetryCollector(config);

// Record tool call
collector.recordToolCall({
  toolName: 'read-file',
  params: { path: '/tmp/file.txt' },
  status: 'success',
  duration: 123,
  result: { content: '...' }
});

// Get metrics
const metrics = collector.getMetrics();
console.log(`Total requests: ${metrics.totalRequests}`);
console.log(`Success rate: ${metrics.performance.successRate}%`);

// Export as JSON
const exported = collector.exportMetrics();
fs.writeFileSync('metrics.json', exported);

// Reset metrics
collector.reset();

🧪 测试与验证

运行测试

npm test

测试结果

📊 Test Summary:
   Total: 15
   ✓ Passed: 15
   ✗ Failed: 0
   Pass Rate: 100%

测试内容

  • ✅ 收集器实例化和配置
  • ✅ 工具调用记录和聚合
  • ✅ 资源访问跟踪
  • ✅ 即时呼叫监控
  • ✅ 错误跟踪和记录
  • ✅ 性能指标计算
  • ✅ 成功/错误率计算
  • ✅ 指标导出为JSON
  • ✅ 指标重置功能
  • ✅ 拦截器工具包装
  • ✅ 拦截器错误处理
  • ✅ HTTP服务器启动/停止
  • ✅ 多工具聚合
  • ✅ 正常运行时间跟踪
  • ✅ 多种刀具类型分离

📊 输出示例

JSON导出

{
  "serverName": "Example MCP Server",
  "uptime": 323000,
  "totalRequests": 298,
  "successfulRequests": 294,
  "failedRequests": 4,
  "avgResponseTime": 45.2,
  "requestsPerMinute": 56,
  "tools": [
    {
      "name": "read-file",
      "callCount": 142,
      "successCount": 139,
      "errorCount": 3,
      "avgDuration": 38.7,
      "lastCalled": 1700000000000,
      "errors": ["File not found", "Permission denied"]
    }
  ],
  "performance": {
    "avgLatency": 45.2,
    "p50Latency": 38,
    "p95Latency": 127,
    "p99Latency": 203,
    "requestsPerSecond": 0.93,
    "errorRate": 1.34,
    "successRate": 98.66
  }
}

🏗️ 建筑

┌─────────────────────────────────────────────────────────┐
│                   MCP Server (Your Code)                │
└───────────────────────┬─────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│               MCPInterceptor (Middleware)               │
│         Wraps tools/resources/prompts                   │
└───────────────────────┬─────────────────────────────────┘
                        │
                        ▼
┌─────────────────────────────────────────────────────────┐
│            TelemetryCollector (Core Engine)             │
│  - Collects metrics                                     │
│  - Aggregates statistics                                │
│  - Calculates performance                               │
└──────┬──────────────────────────────────┬───────────────┘
       │                                  │
       ▼                                  ▼
┌─────────────────┐              ┌──────────────────────┐
│  MonitorServer  │              │  MonitorDashboard    │
│  (HTTP/WS API)  │              │  (Terminal UI)       │
└─────────────────┘              └──────────────────────┘

🚦 用例

1.开发调试

在开发过程中监控您的MCP服务器,以便及早发现问题:

node dist/cli.js dashboard --name "Dev Server"

2.生产监控

在MCP服务器旁边部署监控API:

const server = new MonitorServer(collector, config);
await server.start();

// Export metrics every hour
setInterval(() => {
  fs.writeFileSync(
    `metrics-${Date.now()}.json`,
    collector.exportMetrics()
  );
}, 3600000);

3.性能分析

识别慢速工具并优化:

const metrics = collector.getMetrics();

// Find slowest tools
const slowTools = metrics.tools
  .sort((a, b) => b.avgDuration - a.avgDuration)
  .slice(0, 5);

console.log('Slowest tools:', slowTools);

4.CI/CD集成

如果错误率超过阈值,则构建失败:

const metrics = collector.getMetrics();

if (metrics.performance.errorRate > 5) {
  console.error(`Error rate too high: ${metrics.performance.errorRate}%`);
  process.exit(1);
}

🔒 安全

  • 无数据持久性 -所有指标都存储在内存中
  • 无外部依赖关系 用于堆芯监测
  • 默认情况下仅限本地 -绑定到本地主机
  • 可配置的保留 -自动清理旧数据
  • 无需身份验证 -专为可信环境而设计

备注:对于生产使用,请将身份验证中间件添加到HTTP服务器。

📝 配置

const config: MonitorConfig = {
  serverName: 'My MCP Server',    // Server identifier
  port: 3000,                      // API server port
  retentionDays: 7,                // Data retention (auto-cleanup)
  enableWebUI: true,               // Enable web interface
  enableMetricsExport: true,       // Allow metrics export
  alerting: {                      // Optional alerting
    errorRateThreshold: 5,         // Alert if error rate > 5%
    latencyThreshold: 1000         // Alert if latency > 1000ms
  }
};

🤝 贡献

欢迎投稿!请阅读CONTRIBUTING.md了解指南。

📄 许可证

MIT许可证-有关详细信息,请参阅许可证文件

🔗 资源


内置于❤️ 对于MCP社区