MCP网关

一个轻量级、生产就绪的MCP(模型上下文协议)网关,为多个MCP服务器提供统一的路由、认证、日志和限流功能。

  • by Zijian-Ni
  • TypeScript
  • 本地部署
  • 2 星标
  • 更新于
在 GitHub 查看 Zijian-Ni/mcp-gateway

使用说明

mcp网关

轻便、可生产 MCP(模型上下文协议)网关 --多个MCP服务器的统一路由、身份验证、日志记录和速率限制。


建筑

┌─────────────────────────────────────────────────────────────────────┐
│                          LLM Agents / Clients                       │
│               (Claude, GPT-4, local agents, scripts)                │
└───────────────┬─────────────────────────────────────────────────────┘
                │  HTTP (POST /call, GET /tools)
                │  Authorization: Bearer <api-key>
                ▼
┌─────────────────────────────────────────────────────────────────────┐
│                          mcp-gateway                                │
│                                                                     │
│  ┌──────────┐  ┌────────────┐  ┌──────────┐  ┌──────────────────┐  │
│  │   Auth   │  │Rate Limiter│  │  Cache   │  │     Logger       │  │
│  │ (API key)│  │(token bucket│  │  (LRU)  │  │   (SQLite)       │  │
│  └──────────┘  └────────────┘  └──────────┘  └──────────────────┘  │
│                                                                     │
│  ┌──────────────────────────────────────────────────────────────┐   │
│  │                          Router                              │   │
│  │           tool_name  →  upstream_server                      │   │
│  └──────────────────────────────────────────────────────────────┘   │
└──────┬───────────────────┬───────────────────┬──────────────────────┘
       │ stdio             │ SSE               │ HTTP
       ▼                   ▼                   ▼
┌────────────┐    ┌────────────────┐    ┌────────────────┐
│MCP Server A│    │  MCP Server B  │    │  MCP Server C  │
│(filesystem)│    │ (github tools) │    │ (remote tools) │
│  [local]   │    │   [local/net]  │    │    [cloud]     │
└────────────┘    └────────────────┘    └────────────────┘

特性

  • 🔀 统一路由 --在单个端点后聚合来自多个MCP服务器的工具。启动时自动发现工具。
  • 🔑 API密钥认证 --按键分配工具和服务器。 Bearer 令牌和 X-API-Key 头部支持。
  • ⚡ 速率限制 -令牌桶算法,可根据API密钥进行配置,支持突发。
  • 💾 响应缓存 --具有TTL的LRU缓存,用于相同的请求。大幅降低上游负荷。
  • 📊 SQLite日志记录 --每个工具调用都记录了时间、成功/失败、截断参数和结果。
  • 🔌 多运输 --通过以下方式连接上游服务器 stdio (本地过程), SSE,或可流式传输 HTTP.
  • 🔧 YAML配置 --友好的YAML配置 ${ENV_VAR:-default} 环境变量分辨率。
  • 🖥️ 命令行界面 — mcpx start, mcpx list-tools, mcpx logs, mcpx config validate.

快速开始

安装

# Global install for CLI use
npm install -g @niclaw/mcp-gateway

# Or as a project dependency
npm install @niclaw/mcp-gateway

配置

cp config.example.yaml config.yaml
# Edit config.yaml with your upstream MCP servers and API keys

跑

# Start the gateway
mcpx start --config ./config.yaml

# List discovered tools
mcpx list-tools

# View logs
mcpx logs --tail 50

# Validate config
mcpx config validate

配置参考

所有配置都在 config.yaml (YAML)。看 config.example.yaml 查看完整的注释示例。

gateway

字段 类型 默认值 描述
port 编号 3000 要侦听的HTTP端口
host 字符串 127.0.0.1 绑定主机
requireAuth 布尔值 true 需要客户端提供API密钥

servers[]

字段 类型 必填 描述
name string ✅ 唯一服务器标识符
transport stdio sse http
command string 仅限stdio 要执行的命令
args string[] 否 命令的参数
env object 否 额外的环境变量
url string 仅限sse/http 服务器URL
timeout 编号 30000 工具调用超时(ms)

apiKeys[]

字段 类型 描述
key string API密钥值(最少8个字符)
name string 人类可读标签
allowedTools string[] 允许的工具名称(空=全部)
allowedServers string[] 允许的服务器名称(空=全部)
rateLimit number 令牌/分钟覆盖

rateLimit

字段 默认值 描述
tokensPerMinute 60 重新填充率
burstSize 10 最大突发容量

cache

字段 默认值 描述
enabled true 启用/禁用缓存
maxSize 1000 缓存条目的最大数量
ttlSeconds 300 缓存条目过期前的秒数

logging

字段 默认值 描述
dbPath ./mcp-gateway.db SQLite数据库路径
maxParamLength 500 截断超过此长度的记录参数

环境变量替换

在配置值中,使用 ${VAR} 或 ${VAR:-default}:

apiKeys:
  - key: "${GATEWAY_API_KEY}"       # Required env var
    name: "${KEY_NAME:-my-agent}"   # With default fallback

CLI参考

mcpx start

启动网关服务器。

mcpx start [options]

Options:
  -c, --config <path>   Path to config file (default: ./config.yaml)
  -h, --help            Display help

mcpx list-tools

发现并列出已配置上游服务器中的所有工具。

mcpx list-tools [options]

Options:
  -c, --config <path>   Path to config file (default: ./config.yaml)
  --json                Output as JSON

mcpx logs

查看SQLite数据库中的请求日志。

mcpx logs [options]

Options:
  -c, --config <path>   Path to config file (default: ./config.yaml)
  -n, --tail <number>   Show last N entries (default: 20)
  --tool <name>         Filter by tool name
  --server <name>       Filter by server name
  --json                Output as JSON

mcpx config validate

在不启动网关的情况下验证配置文件。

mcpx config validate [options]

Options:
  -c, --config <path>   Path to config file (default: ./config.yaml)

HTTP API

一旦网关运行,它就会公开一个简单的HTTP API。

GET /health

健康检查。

{ "status": "ok", "uptime": 12345 }

GET /tools

列出所有可用工具。

标题: Authorization: Bearer <api-key>

{
  "tools": [
    {
      "name": "read_file",
      "description": "Read a file from the filesystem",
      "inputSchema": { "type": "object", "properties": { "path": { "type": "string" } } },
      "serverName": "filesystem"
    }
  ]
}

POST /call

调用工具。

标题: Authorization: Bearer <api-key>, Content-Type: application/json

请求:

{
  "tool": "read_file",
  "params": { "path": "/home/user/notes.txt" }
}

答复:

{
  "result": { "content": [{ "type": "text", "text": "Hello world" }] },
  "durationMs": 45,
  "cached": false
}

GET /stats

网关统计信息。

{
  "uptime": 86400000,
  "totalRequests": 1234,
  "successfulRequests": 1200,
  "failedRequests": 34,
  "servers": [
    { "name": "filesystem", "connected": true, "toolCount": 5 }
  ]
}

程序化使用

import { Gateway } from '@niclaw/mcp-gateway';
import { loadConfig } from '@niclaw/mcp-gateway/config';

const config = loadConfig('./config.yaml');
const gateway = new Gateway(config);

await gateway.start();

// List all tools
const tools = gateway.listTools();
console.log(tools);

// Call a tool directly (bypasses HTTP layer)
const result = await gateway.callTool('read_file', { path: '/etc/hosts' }, {
  apiKey: 'your-api-key',
});

// Get stats
const stats = gateway.getStats();

// Graceful shutdown
await gateway.stop();

路线图

  • [ ] WebSocket传输 --双向流媒体支持
  • [ ] 工具名称间距 — server.toolname 前缀以避免冲突
  • [ ] 健康监测 --上游服务器故障时自动重新连接
  • [ ] 管理用户界面 --用于日志、统计和配置管理的web仪表板
  • [ ] OpenAPI/Swagger --从工具模式自动生成文档
  • [ ] gRPC传输 --高性能二进制协议支持
  • [ ] 指标导出 --Prometheus/OpenTelemetry集成
  • [ ] 聚类 --共享Redis缓存的多实例支持
  • [ ] 插件系统 --自定义中间件挂钩

发展

git clone https://github.com/Zijian-Ni/mcp-gateway.git
cd mcp-gateway
npm install
npm run build
npm test

脚本

命令 描述
npm run build 编译TypeScript
npm test 使用Vitest运行测试
npm run test:coverage 运行覆盖率测试
npm run lint ESLint棉绒
npm run typecheck 不发射的类型检查

贡献

看 贡献.md 作为指导方针。

安全

看 安全.md 我们负责任的披露政策。

行为准则

该项目遵循 贡献者契约v2.1.


作者

倪子甸 — @倪

许可证

麻省理工学院©2026倪子建--见 许可证 了解详情。