Skip to main content
Glama
Nagendda

MCP Tool Manager

by Nagendda

MCP 工具管理器

一个基于模型上下文协议(MCP)构建的、面向生产环境加固的 AI 原生工具注册表与代理管理系统。

Node.js License: MIT MCP Security


📖 目录

  1. 这是什么?

  2. 架构概览

  3. 项目结构

  4. 快速开始

  5. 配置参考

  6. API 参考

  7. 实施计划

  8. 安全模型

  9. 监控与可观测性

  10. 路线图

  11. 贡献指南


Related MCP server: AgentsGate

这是什么?

MCP 工具管理器是一个双服务器平台,解决了 AI 集成工具系统中最棘手的运维问题:

问题

解决方案

LLM 在庞大的 API 响应上浪费上下文窗口

每个工具设置字节预算,并带有优雅的截断信号

上游 API 故障级联到 LLM

每个工具配备熔断器(CLOSED → OPEN → HALF-OPEN)

服务器重启后所有数据丢失

自动定期磁盘快照,启动时恢复

对 API 网关的暴力破解 / 注入攻击

10 类威胁检测器 + 分层限流 + IP 自动封禁

无法端到端追踪请求

X-Trace-ID 头跨所有层传播并传递到上游 API

工具/代理仅注册在易失性内存中

文件持久化的调用日志 + 代理 JSON 配置 + 状态快照


架构概览

┌─────────────────────────────────────────────────────────────────────────┐
│                        MCP Tool Manager Platform                        │
│                                                                         │
│  ┌──────────────────────┐        ┌────────────────────────────────────┐ │
│  │   Manager Server      │        │    Hardened MCP Server             │ │
│  │   src/server          │        │    mcp-server-project              │ │
│  │                       │        │                                    │ │
│  │  • REST API (CRUD)    │        │  • MCP Protocol endpoint           │ │
│  │  • JWT + API key auth │        │  • Agent API key auth + expiry     │ │
│  │  • Tool registry      │        │  • Circuit breaker per tool        │ │
│  │  • Agent management   │        │  • Retry + exponential backoff     │ │
│  │  • Credential vault   │        │  • Response cache (TTL per tool)   │ │
│  │  • Audit log          │        │  • Context window limiting         │ │
│  │  • State snapshots    │        │  • File-persisted call log         │ │
│  │  • WebSocket events   │        │  • 10-family threat detection      │ │
│  │  • Response cache     │        │  • Admin /metrics endpoint         │ │
│  └──────────┬───────────┘        └──────────────┬─────────────────────┘ │
│             │                                    │                       │
│  ┌──────────▼───────────┐        ┌──────────────▼─────────────────────┐ │
│  │   React Dashboard     │        │    Claude Desktop / LLM Agent      │ │
│  │   src/dashboard       │        │    (connects via MCP SDK)          │ │
│  └──────────────────────┘        └────────────────────────────────────┘ │
│                                                                         │
│  ┌──────────────────────────────────────────────────────────────────┐   │
│  │  Cross-cutting: X-Trace-ID · Rate Limiting · Helmet CSP ·        │   │
│  │  Structured Logging · Connection Limit · Compression             │   │
│  └──────────────────────────────────────────────────────────────────┘   │
└─────────────────────────────────────────────────────────────────────────┘

项目结构

mcp/
├── .env.example                    # Template — copy to .env and fill in values
├── .gitignore                      # Excludes .env, node_modules, logs, snapshots
├── package.json                    # Root scripts — start both servers, CLI, tests
├── README.md                       # This file
├── REPORT.md                       # Full technical capability report
├── CHANGELOG.md                    # Version history
│
├── src/
│   ├── server/                     # Manager Server (REST API)
│   │   ├── index.js                # Entry point — snapshot restore + server start
│   │   ├── app.js                  # Express app — all middleware wired
│   │   ├── routes/
│   │   │   ├── tools.js            # CRUD + test execution for tools
│   │   │   ├── agents.js           # Agent management + tool discovery
│   │   │   ├── auth.js             # Login, register, API key management
│   │   │   ├── credentials.js      # Encrypted credential vault
│   │   │   └── monitoring.js       # Stats, audit log, cache, snapshot status
│   │   ├── middleware/
│   │   │   ├── auth.js             # JWT + API key auth + RBAC
│   │   │   └── error-handler.js    # Typed errors + global handler
│   │   ├── storage/
│   │   │   ├── in-memory-store.js  # All in-memory Maps + operations
│   │   │   ├── seeder.js           # Initial data (skipped if snapshot exists)
│   │   │   └── state-snapshot.js   # Periodic disk snapshots (JSON files)
│   │   ├── utils/
│   │   │   ├── trace.js            # X-Trace-ID middleware
│   │   │   ├── context-limit.js    # Response byte budget + pagination guard
│   │   │   ├── response-cache.js   # node-cache wrapper + TTL presets
│   │   │   ├── encryption.js       # AES-256-CBC for credential vault
│   │   │   └── logger.js           # Levelled logger (error/warn/info/debug)
│   │   └── websocket.js            # Real-time events via WebSocket
│   │
│   ├── dashboard/                  # React + Vite management UI
│   │   ├── src/
│   │   │   ├── pages/              # Dashboard, Tools, Agents, Monitoring, Settings
│   │   │   ├── components/         # Sidebar, Topbar, ToastContainer
│   │   │   ├── services/api.js     # Axios client for Manager Server
│   │   │   └── styles/             # global.css, sidebar.css
│   │   └── vite.config.js
│   │
│   ├── sdk/
│   │   └── index.js                # Developer SDK — npm-publishable client
│   │
│   └── cli/
│       └── index.js                # Admin CLI (17 commands)
│
├── mcp-server-project/             # Hardened MCP Server
│   ├── package.json
│   ├── src/
│   │   ├── server.js               # Boot sequence — all 7 security layers
│   │   ├── mcp-protocol.js         # MCP spec endpoint (/mcp/tools, /mcp/invoke)
│   │   ├── routes/
│   │   │   ├── invoke.js           # Tool invocation (retry + CB + cache + limit)
│   │   │   ├── info.js             # Tool discovery per agent
│   │   │   └── metrics.js          # Admin monitoring endpoint
│   │   ├── middleware/
│   │   │   ├── auth.js             # Agent auth + expiry + scope + disabled check
│   │   │   ├── trace.js            # X-Trace-ID attachment
│   │   │   └── context-limit.js    # Response byte budget
│   │   ├── state/
│   │   │   ├── call-log.js         # Disk-persisted call log (NDJSON)
│   │   │   ├── circuit-breaker.js  # Per-tool CLOSED/OPEN/HALF state machine
│   │   │   └── response-cache.js   # TTL cache with auto-eviction
│   │   ├── loaders/
│   │   │   ├── registry.js         # Central tool+agent in-memory registry
│   │   │   ├── tool-loader.js      # Loads *.json from /tools/
│   │   │   ├── agent-loader.js     # Loads *.json from /agents/
│   │   │   └── credential-loader.js # Merges .env + JSON credentials
│   │   └── watcher.js              # chokidar hot-reload on /tools/ and /agents/
│   ├── security/
│   │   ├── middleware/
│   │   │   ├── security-headers.js # Strict Helmet CSP + CORS
│   │   │   ├── rate-limiter.js     # 3-tier rate limiting + IP auto-block
│   │   │   └── threat-detector.js  # 10-family injection/attack detector
│   │   └── logger/
│   │       └── security-log.js     # Structured security event log (5 levels)
│   ├── tools/                      # Tool definition JSON files
│   ├── agents/                     # Agent definition JSON files
│   ├── credentials/                # .env and JSON secrets (gitignored)
│   ├── logs/                       # Security log + call log (gitignored)
│   └── security-tests/             # Attack simulation suite + benchmark
│
├── snapshots/                      # Manager server state snapshots (gitignored)
└── examples/                       # Example tool/agent JSON files

快速开始

前置要求

要求

版本

Node.js

≥ 16.0.0

npm

≥ 7.0.0

Git

任意版本

1. 克隆仓库

git clone https://github.com/YOUR_USERNAME/mcp-tool-manager.git
cd mcp-tool-manager

2. 安装依赖

# Root (Manager Server + CLI + SDK)
npm install

# Dashboard
cd src/dashboard && npm install && cd ../..

# MCP Server
cd mcp-server-project && npm install && cd ..

3. 配置

# Manager Server
cp .env.example .env
# Edit .env with your JWT_SECRET, ENCRYPTION_KEY, etc.

# MCP Server
cp mcp-server-project/credentials/.env.example mcp-server-project/credentials/.env
# Edit credentials/.env with your agent keys and tool API keys

4. 运行

# Terminal 1 — Manager Server (port 5000)
npm run dev:server

# Terminal 2 — React Dashboard (port 3000)
npm run dev:dashboard

# Terminal 3 — MCP Server (port 5001 by default)
cd mcp-server-project && npm start

5. 访问

默认登录(管理器)

Email:    admin@mcp-tool-manager.dev
Password: admin123

⚠️ 在生产环境中请立即通过 ADMIN_USERNAME / ADMIN_PASSWORD 环境变量修改此项。


配置参考

管理器服务器(.env)

# Core
NODE_ENV=development
MCP_SERVER_PORT=5000
MCP_SERVER_HOST=localhost
LOG_LEVEL=info

# Auth
JWT_SECRET=your-super-secret-key-min-32-chars
JWT_EXPIRY=24h
ENCRYPTION_KEY=your-encryption-key-exactly-32-ch

# Context Window
MCP_MAX_RESPONSE_BYTES=65536        # 64 KB default response budget
MCP_MAX_PAGE_SIZE=100               # Max items per paginated endpoint

# Scalability
MCP_MAX_CONNECTIONS=500             # TCP connection limit
SNAPSHOT_DIR=./snapshots            # State persistence directory
SNAPSHOT_INTERVAL_SECS=60           # Save state every 60 seconds
SNAPSHOT_RESTORE=true               # Restore state on startup

# Cache TTLs (seconds)
CACHE_TTL_TOOL_LIST=30
CACHE_TTL_TOOL_ITEM=60
CACHE_TTL_AGENT_LIST=30
CACHE_TTL_STATS=10
CACHE_TTL_ACTIVITY=300

# Future (not yet wired — provide connection string to enable)
DATABASE_URL=postgresql://user:password@localhost:5432/mcp_tools
REDIS_URL=redis://localhost:6379

MCP 服务器(mcp-server-project/credentials/.env)

# Agent API Keys (convention: AGENT_<AGENTID_UPPERCASE>_KEY)
AGENT_MY_AGENT_KEY=your-agent-secret-key

# Tool credentials (referenced by credential_ref in tool JSON)
OPENAI_API_KEY=sk-...
WEATHER_API_KEY=...
SLACK_BOT_TOKEN=xoxb-...

# Admin
ADMIN_KEY=your-admin-key-for-metrics-endpoint

# Server
MCP_PORT=5001
MCP_MAX_CONNECTIONS=200
MCP_MAX_RESPONSE_BYTES=32768        # 32 KB default per tool response

工具 JSON 字段(MCP 服务器)

{
  "name": "my_tool",
  "description": "Human-readable description for the LLM",
  "endpoint_url": "https://api.example.com/endpoint",
  "method": "POST",
  "credential_ref": "MY_API_KEY",
  "parameters": {
    "type": "object",
    "properties": {
      "query": { "type": "string", "description": "Search query" }
    },
    "required": ["query"]
  },
  "cache_ttl_seconds": 60,
  "max_response_bytes": 8192,
  "retry_max": 3,
  "timeout_ms": 10000,
  "circuit_failure_threshold": 5,
  "circuit_open_window_ms": 30000
}

代理 JSON 字段(MCP 服务器)

{
  "agent_id": "my-agent",
  "allowed_tools": ["weather_lookup", "send_email"],
  "expires_at": "2027-01-01T00:00:00Z",
  "disabled": false
}

API 参考

管理器服务器(http://localhost:5000)

认证

方法

路径

认证

描述

POST

/api/auth/login

—

获取 JWT 令牌

POST

/api/auth/register

—

创建账户

GET

/api/auth/me

✅

当前用户 + API 密钥

POST

/api/auth/api-keys

✅

生成新的 API 密钥

DELETE

/api/auth/api-keys/:key

✅

撤销 API 密钥

工具

方法

路径

认证

描述

GET

/api/tools

✅

列出工具(分页)

POST

/api/tools

✅

注册新工具

GET

/api/tools/:id

✅

工具详情

PUT

/api/tools/:id

✅

更新工具

DELETE

/api/tools/:id

✅

删除工具

POST

/api/tools/:id/test

✅

测试工具调用

代理

方法

路径

认证

描述

GET

/api/agents

✅

列出代理

POST

/api/agents

✅

注册代理

GET

/api/agents/:id

✅

代理详情

PUT

/api/agents/:id

✅

更新代理

DELETE

/api/agents/:id

✅

删除代理

POST

/api/agents/:id/tools

✅

为代理发现工具

监控

方法

路径

认证

描述

GET

/api/monitoring/health

—

存活探针

GET

/api/monitoring/stats

✅

完整系统统计 + 缓存 + 快照

GET

/api/monitoring/activity

✅

真实逐小时调用时间线(24 小时)

GET

/api/monitoring/top-tools

✅

按调用次数排序的前 N 个工具

GET

/api/monitoring/audit-log

✅

审计条目

GET

/api/monitoring/cache

✅

缓存命中率 + 条目

GET

/api/monitoring/snapshot

✅

上次快照时间戳 + 计数

MCP 服务器(http://localhost:5001)

方法

路径

认证

描述

GET

/health

—

存活探针

GET

/info

AGENT_KEY

列出调用代理可用的工具

GET

/info/all

ADMIN_KEY

所有工具 + 所有代理

GET

/mcp/tools

—

兼容 Claude Desktop 的工具列表

POST

/mcp/invoke/:tool

—

MCP 协议调用

POST

/invoke/:toolName

AGENT_KEY

直接工具调用

GET

/metrics

ADMIN_KEY

完整监控仪表盘

GET

/metrics/health

—

轻量级存活探针

GET

/metrics/calls

ADMIN_KEY

最近的调用历史


实施计划

本节记录了完整的路线图——已完成的内容、正在进行中的内容,以及需要基础设施决策的内容。

阶段 1 — 基础 ✅ 已完成

  • 管理器服务器 REST API(工具、代理、认证、凭据、监控)

  • 带完整 CRUD 操作的内存存储

  • JWT + API 密钥双认证,支持 RBAC

  • AES-256-CBC 凭据保险库

  • React 仪表盘(工具、代理、监控、设置页面)

  • WebSocket 实时事件广播

  • 开发者 SDK(src/sdk/index.js)

  • 包含 17 个命令的管理员 CLI(src/cli/index.js)

  • MCP 协议端点(兼容 Claude Desktop)

  • 基于文件的工具/代理注册表,支持热重载(chokidar)

  • 带滚动环形缓冲区的审计日志

阶段 2 — 安全加固 ✅ 已完成

  • 10 类威胁检测器(SQL/NoSQL/XSS/SSRF/Shell/模板/路径/CMDi/Null/Header 注入)

  • 扫描器用户代理拦截(sqlmap、nikto、nmap、Burp Suite 等 20+ 扫描器)

  • 3 层限流(全局 + 严格 + 速度降级)

  • 暴力破解后自动封禁 IP(20+ 次命中)

  • 结构化安全事件日志,5 个严重级别

  • Helmet 严格 CSP(defaultSrc: 'none')

  • 代理密钥过期 + 禁用标志

  • 作用域强制(requireScope 中间件)

  • 认证失败 + 作用域违规安全日志

  • 安全测试套件 + 基准测试(对比加固与未保护状态)

阶段 3 — 运维能力 ✅ 已完成(本版本)

  • X-Trace-ID — 唯一请求关联器,跨所有层传播并传递到上游 API

  • 熔断器 — 每个工具 CLOSED/OPEN/HALF-OPEN(可配置阈值)

  • 指数退避重试 — 200ms → 400ms → 800ms,跳过 4xx 错误

  • 响应缓存 — 每个工具/数据类型 TTL、命中率跟踪、前缀失效

  • 上下文窗口限制 — 每个工具字节预算,带信号的优雅截断

  • 分页保护 — 全局 ?limit 钳制(默认最多 100 条)

  • 状态快照 — 原子定期写入,启动时恢复(工具/代理/用户重启后保留)

  • 连接数限制保护 — 超过可配置上限时丢弃 TCP 套接字

  • 限流已启用(管理器)— 每 IP 每分钟 300 次全局 + 15 次认证

  • 真实监控 — 基于实际调用数据的活动时间线(移除了 Math.random() 模拟)

  • /metrics 端点(MCP)— 完整管理员仪表盘(调用、缓存、熔断器、内存)

  • node-cache 已启用(管理器)— 每种数据类型 TTL 预设、命中率跟踪

  • /api/monitoring/cache 和 /api/monitoring/snapshot 新端点

阶段 4 — 持久化与分布式 🔲 等待您的输入

这些需要基础设施。pg 和 ioredis 已安装——仅需连接字符串。

  • PostgreSQL — 将 in-memory-store.js 迁移到持久化数据库

    • tools、agents、users、api_keys、credentials、audit_log 表

    • 通过 pg 实现连接池(DATABASE_URL 已在 .env.example 中)

  • Redis — 共享限流 + 会话 + 响应缓存存储

    • 用 ioredis 替换 node-cache 以实现多实例安全

    • 跨所有服务器实例共享 IP 封禁列表

    • (REDIS_URL 已在 .env.example 中)

  • 水平扩展 — 接入 Redis + Postgres 后,在 nginx 后部署 N 个实例

阶段 5 — 开发者体验 🔲 可选

  • OpenAPI/Swagger 规范自动生成(swagger-jsdoc)

  • 启动时 zod 环境变量模式验证(缺少配置时快速失败)

  • JWT 刷新令牌 + 黑名单

  • Prometheus 指标导出(/metrics/prometheus 端点)

  • OpenTelemetry 分布式追踪

  • 工具兼容性矩阵

  • 用于实时熔断器状态的 WebSocket 仪表盘


安全模型

管理器服务器

Request
  │
  ├── X-Trace-ID attachment (Layer 0)
  ├── Helmet strict CSP (Layer 1)
  ├── Global rate limit 300/min (Layer 2a)
  ├── Auth rate limit 15/min on /api/auth (Layer 2b)
  ├── Body size limit 2 MB (Layer 3)
  ├── Context window budget (Layer 4)
  ├── Pagination guard max 100 items (Layer 5)
  ├── JWT / API key verification (per-route)
  └── RBAC role check (per-route)

MCP 服务器

Request
  │
  ├── X-Trace-ID attachment (Layer 0)
  ├── Strict Helmet CSP (Layer 1)
  ├── IP block list check (Layer 2)
  ├── Body size guard (Layer 3)
  ├── Context window budget (Layer 4)
  ├── HTTP method whitelist (Layer 5)
  ├── Scanner user-agent block (Layer 6)
  ├── Global rate limit + speed slow-down (Layer 7)
  ├── 10-family threat detection (Layer 8)
  ├── Agent API key auth + expiry + disabled check (per-route)
  ├── Tool scope enforcement (per-route)
  ├── Circuit breaker check (per-tool)
  ├── Response cache lookup (per-tool)
  └── Retry + context limit on upstream call (per-tool)

监控与可观测性

可用数据

来源

说明

GET /api/monitoring/stats

系统概览、缓存统计、快照信息、上下文限制配置

GET /api/monitoring/activity

24 小时实时调用时间线(成功 + 错误计数)

GET /api/monitoring/top-tools

按调用次数 + 成功率排名的热门工具

GET /api/monitoring/audit-log

所有管理员操作(工具创建/删除、代理添加/移除)

GET /api/monitoring/cache

缓存命中率、条目数、逐出次数

GET /api/monitoring/snapshot

上次快照时间戳 + 记录数

GET /metrics (MCP, admin)

熔断器状态、调用日志、缓存统计、系统内存

GET /metrics/health (MCP, public)

运行时间 + 内存(轻量级探针)

logs/calls.ndjson (MCP)

完整调用历史:追踪 ID、代理、工具、延迟、成功、重试

logs/security.log (MCP)

所有安全事件:AUTH 失败、威胁、速率限制、熔断触发

snapshots/meta.json (Manager)

上次快照:所有数据类型的时间戳 + 计数

X-Trace-ID 流程

Client → [generates or passes X-Trace-ID]
  → Manager/MCP Server [attaches to req.traceId, echoes in X-Trace-ID response header]
    → Security log entries [include traceId]
      → Call log entries [include traceId]
        → Upstream API call [X-Trace-ID forwarded in headers]
          → Response [traceId in JSON body]

路线图

v2.1(下一个)

  • 接入 PostgreSQL 实现持久化存储

  • 接入 Redis 实现分布式限流 + 缓存

  • 启动时使用 zod 进行环境变量模式校验

v2.2

  • JWT 刷新令牌 + 黑名单

  • Prometheus 指标导出

  • 按 API 密钥限流(而非基于 IP)

v3.0

  • 完整的 OpenAPI 规范

  • OpenTelemetry 分布式追踪

  • OAuth2/OIDC 联合代理身份


贡献

有关分支策略、PR 流程和代码风格指南,请参阅 CONTRIBUTING.md。


许可证

MIT © MCP Tool Manager Team


有关完整的技术能力评估,请参阅 REPORT.md。

Maintenance

ActivityStale
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables AI agents to securely call MCP tools with risk scoring, checkpoints, rollback, and approval workflows.
    17 npm
    MIT
  • A
    license
    Not graded
    quality
    B
    maintenance
    Enables AI agents to safely call enterprise tools through a governed MCP gateway with permission enforcement, blast-radius controls, input validation, and a full audit trail for every invocation.
    MIT
  • A
    license
    Not graded
    quality
    A
    maintenance
    Enables organizations to centrally govern agent tool access by exposing authorized MCP tools through a unified endpoint with search and execute functions, while enforcing function-level permissions, credential modes, and auditability.
    MIT