MCP网关
 ](https://nodejs.org/)   ](https://lobehub.com/mcp/abdullah1854-mcpgateway)
通用MCP聚合服务器,通过具有15层令牌优化的单个端点从多个MCP服务器路由300多个工具(减少95-98%)。适用于Claude Desktop、Claude Code、Cursor、OpenAI Codex和VS Code Copilot。
主要特点
- 多服务器聚合 --通过一个网关端点连接多个MCP服务器(STDIO、HTTP、SSE)
- 15个令牌优化层 --渐进式披露、智能过滤、聚合、代码批处理、增量响应、自动摘要等
- Web仪表板 --通过热重新加载管理工具、后端和服务器生命周期的实时UI
- 沙盒代码执行 --在安全的Node.js虚拟机中执行Types/JavaScript进行批处理操作
- 技能体系 -为零样本任务执行保存和重用代码模式
- 认证 -API密钥和OAuth/JWT支持(带速率限制)
- Docker就绪 --使用Docker/Compose轻松部署
快速安装
git clone https://github.com/abdullah1854/MCPGateway.git
cd MCPGateway
npm install
cp config/servers.example.json config/servers.json
npm run dev连接您的AI客户端
克劳德桌面/光标/VS代码复制品 --添加为远程MCP服务器:
http://localhost:3010/mcp克劳德代码 --添加到设置:
{
"mcpServers": {
"mcp-gateway": {
"type": "url",
"url": "http://localhost:3010/mcp"
}
}
}仪表盘: http://localhost:3010/dashboard
最适合: 在跨多个工具工作时,希望有一个MCP端点、一个浏览器仪表板和激进的令牌节省的团队。
快速链接
3个命令快速入门
npm install
cp config/servers.example.json config/servers.json
npm run dev然后打开 http://localhost:3010/dashboard,连接您的首选客户端,然后继续完整操作 快速开始 下面是服务器配置和生产设置。
支持的MCP客户端
| 客户 | 支持 | 备注 |
|---|---|---|
| 克劳德桌面 | ✅ | 通过网关的HTTP或SSE端点连接 |
| 克劳德代码 | ✅ | 减少大型工具目录的上下文开销 |
| 光标 | ✅ | 使用一个网关公开数百个后端工具 |
| OpenAI Codex✅ | 与网关的标准MCP端点配合使用 | |
| VS代码副本 | ✅ | 跨本地和远程服务器集中化MCP工具 |
______________________________________________________________________
MCP网关如何补充Anthropic的工具搜索
2025年1月:Anthropic发布 工具搜索工具 -用于从大型目录中发现工具的本机服务器端功能 defer_loading 以及正则表达式/BM25搜索。MCP网关和Anthropic的工具搜索解决了不同的问题:
| 问题 | 人工工具搜索 | MCP网关 |
|---|---|---|
| 工具发现 (从100年代开始寻找合适的工具) | ✅ 本土的 defer_loading +搜索 | ✅ 渐进式披露 |
| 结果筛选 (修剪大结果) | ❌ 不可用 | ✅ maxRows, fields, format |
| 自动摘要 (提取见解) | ❌ 不可用 | ✅ 60-90%的代币节省 |
| Delta响应 (仅发送更改) | ❌ 不可用 | ✅ 投票节省90%以上 |
| 聚合 (计数、总和、分组依据) | ❌ 不可用 | ✅ 服务器端分析 |
| 代码批处理 (一次通话中有多个操作) | ❌ 不可用 | ✅ 往返次数减少60-80% |
| 技能 (可重用代码模式) | ❌ 不可用 | ✅ 95%以上的代币节省 |
底线: Anthropic的工具搜索可帮助您 *找到* 正确的工具。MCP网关助您一臂之力 *使用* 通过管理大型结果、批处理操作和提供可重用模式,高效地使用工具。
您可以将两者结合使用-让Anthropic在布线工具的同时处理工具发现 *电话* 通过MCP网关进行结果优化。
______________________________________________________________________
为什么选择MCP网关?
问题: AI代理在使用MCP服务器时面临三个关键挑战:
- 刀具过载 -在任何工作开始之前,加载300多个工具定义会消耗77000多个上下文令牌
- 结果Bloat -大型查询结果(10K行)每次调用可能消耗50000多个令牌
- 重复操作 -同样的工作流程每次都需要向模型重新解释
注: 人类学 工具搜索工具 现在为直接API用户原生地寻址#1。MCP网关对于#2和#3仍然至关重要,并为没有本机工具搜索的MCP客户端提供工具发现。
解决方案: MCP网关聚合您的所有MCP服务器并提供 15层令牌优化:
| Layer | 它做什么 | 令牌节省 | Gateway独有的? |
|---|---|---|---|
| 渐进式披露 | 按需加载工具模式 | 85% | 共享\* |
| 智能过滤 | 自动限制结果大小 | 60-80% | ✅ |
| 聚合 | 服务器端分析 | 90%+ | ✅ |
| 代码批处理 | 一次通话中进行多次操作 | 60%-80% | ✅ |
| 技能 | 零样本任务执行 | 95%+ | ✅ |
| 缓存 | 跳过重复查询 | 100% | ✅ |
| PII标记化 | 删除敏感数据 | 安全性 | ✅ |
| 响应优化 | 去除空值 | 20-40% | ✅ |
| 会话上下文 | 避免在上下文中重新发送数据 | 非常高 | ✅ |
| 架构重复数据删除 | 按哈希引用相同的架构 | 高达90% | ✅ |
| 微模式 | 超紧凑型缩写 | 60-70% | ✅ |
| Delta响应 | 仅发送重复查询的更改 | 90%+ | ✅ |
| 上下文跟踪 | 监控上下文使用情况,防止溢出 | 安全 | ✅ |
| 自动摘要 | 从大结果中提取见解 | 60-90% | ✅ |
| 查询计划 | 检测优化机会 | 30-50% | ✅ |
*\*Anthropic的工具搜索提供本地工具发现;MCP网关为没有本机支持的MCP客户端提供它。*
结果: 一个典型的会话从约500000个令牌下降到约25000个令牌(减少95%)。
305个工具到19个网关工具
Cursor showing gateway tools providing access to 305 MCP tools
*游标连接到MCP网关-19个工具可访问16台服务器上的305个后端工具*
最小化上下文使用
Claude Code context showing only 8.9k tokens for MCP tools
*克劳德代码 /context 视图-所有MCP工具只有8.9万个令牌(4.5%),而原始定义只有20多万个令牌*
新增功能(v1.0.0)
- 网关MCP工具 -所有代码执行功能现在都作为MCP工具公开(
gateway_*)任何客户都可以直接发现和使用 - 热重新加载服务器管理 -在仪表板上添加、编辑和删除MCP服务器,而无需重新启动
- UI状态持久化 -禁用的工具和后端在服务器重新启动时会被记住
- 增强型仪表板 -重新连接失败的后端,查看实时状态,改进错误处理
- 连接测试 -在将服务器连接添加到配置之前测试它们
- 导出/导入配置 -轻松备份和共享服务器配置
- 并行工具执行 -同时执行多个工具调用以获得更好的性能
- 结果过滤和聚合 -通过以下方式减少上下文膨胀
maxRows,fields,format,以及聚合选项
特性
核心网关功能
- 🔀 多服务器聚合 -通过一个网关路由多个MCP服务器
- 🎛️ Web仪表板 -用于管理工具、后端和服务器生命周期的实时UI
- ➕ 热重新加载服务器管理 -在仪表板上添加、编辑、删除MCP服务器,无需重新启动
- 🌐 HTTP流传输 -主要运输,与所有客户合作
- 📡 苏格兰和南方能源公司运输 -对旧客户端的向后兼容性
- 🔐 认证 -API密钥和OAuth/JWT支持
- ⚡ 速率限制 -保护您的后端服务器
- 🐳 Docker就绪 -使用Docker/Compose轻松部署
- 📊 健康检查 -使用详细的诊断程序监控后端状态
- 🔄 自动重启 -服务器在崩溃时自动重启或通过仪表板重启
- 💾 UI状态持久化 -在重启过程中记住禁用的工具/后端
代码执行模式(令牌高效AI)
受启发于 使用MCP执行Anthropic的代码 -达到 代币减少98.7%:
- 🔍 渐进式工具披露 -搜索和延迟加载工具,以减少令牌使用(减少85%)
- 💻 沙盒代码执行 -在安全的Node.js虚拟机中执行Types/JavaScript
- 📉 上下文高效结果 -过滤、聚合和转换工具结果(减少60-80%)
- 🔒 隐私保护操作 -敏感数据的PII标记化
- 📁 技能体系 -保存并重用零样本执行的代码模式(消除提示令牌)
- 🗄️ 状态持久性 -跨会话的代理状态工作区
- 🛠️ 网关MCP工具 -所有代码执行功能都作为MCP工具公开给任何客户端
- 🧹 响应优化 -自动从响应中删除空值(减少20-40%)
- 🧠 会话上下文 -跟踪已发送的数据,以避免在多回合对话中重新发送
- 🔗 架构重复数据删除 -按哈希引用相同的模式(最多减少90%)
- 📐 微模式 -具有缩写类型的超紧凑模式(减少60-70%)
- 🔄 Delta响应 -仅发送重复查询的更改(减少90%以上)
- 📊 上下文跟踪 -监控上下文窗口的使用情况,并在溢出前获得警告
- 📝 自动摘要 -从大结果中提取关键见解(减少60-90%)
- 🔍 查询计划 -分析代码以发现优化机会(30-50%的改进)
监测和可观察性
- 📈 普罗米修斯指标 -工具调用延迟、错误率、缓存性能
- 📊 JSON度量API -通过程序访问网关统计数据
- 💾 结果缓存 -带有TTL的LRU缓存,用于工具结果
- 📝 审计日志 -跟踪敏感操作
截图
仪表板概览
工具管理
添加服务器对话框
快速开始
1.安装依赖项
npm install2.配置后端服务器
复制示例配置并对其进行编辑:
cp config/servers.example.json config/servers.json编辑 config/servers.json 添加您的MCP服务器:
{
"servers": [
{
"id": "filesystem",
"name": "Filesystem",
"enabled": true,
"transport": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"]
},
"toolPrefix": "fs"
}
]
}3.启动网关
# Development
npm run dev
# Production
npm run build
npm start网关将启动 http://localhost:3010 默认情况下。
安全模式
对于本地实验,您可以在没有身份验证的情况下运行:
AUTH_MODE=none
然而, 敏感端点 (/dashboard, /dashboard/api/*, /api/code/*, /metrics/json)默认情况下,当 AUTH_MODE=none。要允许未经身份验证的访问(除了孤立的本地使用外不建议),请明确选择加入:
ALLOW_INSECURE=1
为了安全使用,请选择:
AUTH_MODE=api-key随着API_KEYS=key1,key2- 或
AUTH_MODE=oauth与适当OAUTH_*设置如下所示。
端点
核心终点
| 端点 | 传输 | 用例 |
|---|---|---|
/mcp | HTTP Streamable | 主端点-适用于所有客户端 |
/sse | 服务器发送事件 | 向后兼容性 |
/health | JSON | 健康检查和状态 |
/dashboard | Web UI | 管理工具、后端和重新启动服务器 |
/metrics | Prometheus | Prometheus格式度量 |
/metrics/json | JSON | JSON格式指标 |
代码执行API
| 端点 | 方法 | 描述 |
|---|---|---|
/api/code/tools/search | GET | 带过滤器的搜索工具 |
/api/code/tools/tree | GET | 获取类似文件系统的工具树 |
/api/code/tools/names | GET | 获取所有工具名称(最小令牌) |
/api/code/tools/:name/schema | GET | 延迟加载特定工具架构 |
/api/code/tools/stats | GET | 按后端统计工具 |
/api/code/sdk | GET | 自动生成的TypeScript SDK |
/api/code/execute | POST | 在沙盒中执行代码 |
/api/code/tools/:name/call | POST | 带结果过滤的调用工具 |
/api/code/tools/:name/call/aggregate | POST | 带聚合的调用工具 |
/api/code/tools/parallel | POST | 并行执行多个工具 |
/api/code/skills | GET/POST | 列出或创建技能 |
/api/code/skills/search | GET | 搜索技能 |
/api/code/skills/:name | 获取/删除 | 获取或删除技能 |
/api/code/skills/:name/execute | POST | 执行技能 |
/api/code/workspace/session | GET/POST | 获取或更新会话状态 |
/api/code/cache/stats | GET | 缓存统计信息 |
/api/code/cache/clear | POST | 清除缓存 |
仪表板API
| 端点 | 方法 | 描述 |
|---|---|---|
/dashboard/api/tools | GET | 获取所有处于启用状态的工具 |
/dashboard/api/backends | GET | 获取所有带有状态的后端 |
/dashboard/api/tools/:name/toggle | POST | 启用/禁用切换工具 |
/dashboard/api/backends/:id/toggle | POST | 切换后端启用/禁用 |
/dashboard/api/backends/:id/reconnect | POST | 重新连接失败的后端 |
/dashboard/api/backends | POST | 添加新的后端服务器 |
/dashboard/api/backends/:id | PUT | 更新后端配置 |
/dashboard/api/backends/:id | DELETE | 删除后端服务器 |
/dashboard/api/config/export | GET | 导出服务器配置 |
/dashboard/api/config/import | POST | 导入服务器配置 |
/dashboard/api/restart | POST | 重新启动网关服务器 |
仪表盘
访问web仪表板 http://localhost:3010/dashboard 致:
- 查看所有连接的后端及其实时状态
- 添加新的MCP服务器 具有连接测试(STDIO、HTTP、SSE传输)
- 编辑现有服务器 (修改命令、参数、环境变量)
- 删除服务器 优雅地断开连接
- 启用/禁用单个工具或整个后端
- 跨所有后端的搜索和过滤工具
- 导出/导入配置 用于备份和共享
- 重新连接失败的后端 只需单击一下
- 重新启动整个网关服务器
- 一目了然地查看工具计数和后端运行状况
仪表板在服务器重新启动时保持UI状态(禁用的工具/后端)。
客户端配置
克劳德桌面/克劳德代码
- 打开克劳德桌面→ 设置 → 连接器
- 点击 添加远程MCP服务器
- 请输入您的网关URL:
http://your-gateway-host:3010/mcp- 如果需要,完成身份验证
注: Claude要求通过UI而不是配置文件添加远程服务器。
克劳德桌面通过STDIO代理
如果Claude Desktop不直接支持HTTP/SSE传输,您可以使用附带的STDIO代理脚本:
{
"mcpServers": {
"mcp-gateway": {
"command": "node",
"args": ["/path/to/mcp-gateway/scripts/claude-stdio-proxy.mjs"],
"env": {
"MCP_GATEWAY_URL": "http://localhost:3010/mcp"
}
}
}
}代理(scripts/claude-stdio-proxy.mjs)从stdin读取JSON-RPC消息,将其转发到网关HTTP端点,并将响应写入stdout。它自动管理会话ID。
光标
- 打开的游标→ 设置 → 特性 → 主控程序
- 点击 添加新的MCP服务器
- 选择 类型:
HTTP或SSE - 请输入您的网关URL:
对于HTTP(推荐):
http://your-gateway-host:3010/mcp对于SSE:
http://your-gateway-host:3010/sse或者添加到您的游标设置JSON:
{
"mcpServers": {
"my-gateway": {
"type": "http",
"url": "http://your-gateway-host:3010/mcp"
}
}
}OpenAI 代码专家
选项1:CLI
codex mcp add my-gateway --transport http --url https://your-gateway-host:3010/mcp选项2:配置文件
添加 ~/.codex/config.toml:
[mcp_servers.my_gateway]
type = "http"
url = "https://your-gateway-host:3010/mcp"
# With API key authentication
# headers = { Authorization = "Bearer your-api-key-here" }重要提示: 食品法典委员会要求 超文本传输安全协议 用于远程服务器,仅支持HTTP Streamable(不支持SSE)。
VS代码副本
- 打开命令选项板(
Cmd/Ctrl + Shift + P) - 跑 MCP:添加MCP服务器
- 选择 远程(URL)
- 请输入您的网关URL:
http://your-gateway-host:3010/mcp- 批准信任提示
或者添加到您的VS代码中 settings.json:
{
"mcp.servers": {
"my-gateway": {
"type": "http",
"url": "http://your-gateway-host:3010/mcp"
}
}
}跨IDE配置(.agents/)
MCP网关使用集中式 .agents/ 目录作为所有IDE中AI代理配置的唯一真实来源:
.agents/
├── AGENTS.md # Unified project rules (symlinked to all IDEs)
├── hooks/
│ └── skill-activation.mjs # Auto-activates skills based on prompt keywords
├── skills/ # Single source of truth for all skills
│ ├── code-review/ # Executable: skill.json + index.ts + SKILL.md
│ ├── debugging/ # Protocol-only: SKILL.md only (loaded by AI agent)
│ ├── git-workflow/
│ └── ...
└── rules/ # Additional rule fragments
└── cipher-memory.md运作原理
这 .agents/AGENTS.md 文件符号链接到每个IDE的配置位置:
| IDE | Symlink |
|---|---|
| 光标 | .cursorrules → .agents/AGENTS.md |
| 帆板运动 | .windsurfrules → .agents/AGENTS.md |
| 克劳德代码 | CLAUDE.md → .agents/AGENTS.md |
| 法典 | AGENTS.md → .agents/AGENTS.md |
这意味着:
- 一个文件需要维护 -编辑
.agents/AGENTS.md所有IDE都会得到更新 - 一致性行为 -所有工具都有相同的规则、技能和协议
- 版本受控 -跟踪git中的所有配置
技能自动激活
技能 .agents/skills/ 当您的AI代理在提示中检测到相关关键字时,可以自动激活。设置因IDE而异——请参阅 设置技能自动激活 有关完整说明,请参阅技能系统部分。
内置触发器的快速概述:
| 触发关键字 | 技能加载 |
|---|---|
| “审查代码”、“安全审计”、“发现错误” | code-review |
| “调试”、“修复错误”、“不工作”、“错误” | debugging |
| “提交”、“推送”、“创建PR”、“合并” | git-workflow |
| “构建UI”、“仪表板”、“React”、“前端” | frontend-build |
| “部署”、“docker”、“生产”、“托管” | infra-deploy |
| “SQL优化”、“慢速查询” | sql-analyzer |
设置您的叉子
如果你分叉这个仓库:
- 符号链接已在仓库中配置
- 编辑
.agents/AGENTS.md为您的项目自定义规则 - 在中添加/修改技能
.agents/skills/
______________________________________________________________________
后端服务器配置
网关可以使用不同的传输方式连接到MCP服务器:
STDIO(本地进程)
{
"id": "filesystem",
"name": "Filesystem Server",
"enabled": true,
"transport": {
"type": "stdio",
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/dir"],
"env": {
"SOME_VAR": "${ENV_VAR_NAME}"
}
},
"toolPrefix": "fs",
"timeout": 30000
}HTTP(远程服务器)
{
"id": "remote-server",
"name": "Remote MCP Server",
"enabled": true,
"transport": {
"type": "http",
"url": "https://remote-mcp-server.com/mcp",
"headers": {
"Authorization": "Bearer ${REMOTE_API_KEY}"
}
},
"toolPrefix": "remote",
"timeout": 60000
}工具前缀
使用 toolPrefix 从不同服务器访问命名空间工具:
- 服务器与
toolPrefix: "fs"暴露read_file作为fs_read_file - 防止服务器之间的命名冲突
- 明确哪个服务器处理每个工具
认证
API密钥验证
设置环境变量:
AUTH_MODE=api-key
API_KEYS=key1,key2,key3客户端在Authorization标头中发送密钥:
Authorization: Bearer your-api-keyOAuth身份验证
AUTH_MODE=oauth
OAUTH_ISSUER=https://your-oauth-provider.com
OAUTH_AUDIENCE=mcp-gateway
OAUTH_JWKS_URI=https://your-oauth-provider.com/.well-known/jwks.jsonDocker部署
构建并运行
# Build the image
docker build -t mcp-gateway .
# Run with environment variables
docker run -d \
-p 3010:3010 \
-v $(pwd)/config/servers.json:/app/config/servers.json:ro \
-e AUTH_MODE=api-key \
-e API_KEYS=your-secret-key \
mcp-gatewayDocker Compose
# Start
docker-compose up -d
# View logs
docker-compose logs -f
# Stop
docker-compose down环境变量
核心配置
| 变量 | 默认值 | 描述 |
|---|---|---|
PORT | 3010 | 服务器端口 |
HOST | 0.0.0.0 | 服务器主机 |
LOG_LEVEL | info | 日志级别(调试、信息、警告、错误) |
GATEWAY_NAME | mcp-gateway | MCP响应中的网关名称 |
GATEWAY_LITE_MODE | 1 | 精简模式-减少暴露的网关工具,以降低令牌使用率(推荐) |
AUTH_MODE | none | 身份验证模式(无、api密钥、oauth) |
API_KEYS | - | 以逗号分隔的API密钥 |
OAUTH_ISSUER | - | OAuth令牌颁发者 |
OAUTH_AUDIENCE | - | OAuth受众 |
OAUTH_JWKS_URI | - | OAuth JWKS端点 |
CORS_ORIGINS | http://localhost:3010,http://127.0.0.1:3010 | 允许的CORS来源(* 允许所有) |
HEALTH_REQUIRE_BACKENDS | 0 | 如果 1, /health 回报 503 当所有配置的后端都关闭时 |
ALLOW_INSECURE | 0 | 如果 1,允许在以下情况下对仪表板、代码API和JSON指标进行未经身份验证的访问 AUTH_MODE=none |
RATE_LIMIT_WINDOW_MS | 60000 | 速率限制窗口(ms) |
RATE_LIMIT_MAX_REQUESTS | 100 | 每个窗口的最大请求数 |
可选功能
MCP网关包括以下可选功能 默认情况下禁用 以实现最小的、对公众友好的部署。通过将相应的环境变量设置为 1.
| 变量 | 默认值 | 描述 |
|---|---|---|
ENABLE_SKILLS | 0 | 启用技能系统-可重用的代码模式和技能执行 |
ENABLE_CIPHER | 0 | 启用密码内存-带Qdrant矢量存储的跨IDE持久内存 |
ENABLE_ANTIGRAVITY | 0 | 启用反重力使用-反重力IDE的IDE配额跟踪 |
ENABLE_CLAUDE_USAGE | 0 | 启用Claude使用-API代币消费跟踪 |
当功能被禁用时:
- 相应的仪表板选项卡隐藏
- API终结点返回
404 Feature disabled带有启用说明 - 缺少依赖项(Qdrant、密码服务等)不会出错
用于个人/发展用途,在中启用所需的功能 .env:
# Enable all optional features
ENABLE_SKILLS=1
ENABLE_CIPHER=1
ENABLE_ANTIGRAVITY=1
ENABLE_CLAUDE_USAGE=1
# Disable lite mode to see all gateway tools
GATEWAY_LITE_MODE=0特定功能配置
仅当启用相应功能时才需要这些变量:
| 变量 | 特性 | 默认值 | 描述 |
|---|---|---|---|
CIPHER_API_URL | 密码 | http://localhost:8082 | 密码内存服务URL |
QDRANT_URL | 密码 | - | Qdrant矢量存储URL |
QDRANT_API_KEY | 密码 | - | Qdrant API密钥 |
QDRANT_COLLECTION | 密码 | cipher_knowledge | Qdrant集合名称 |
QDRANT_TIMEOUT_MS | 密码 | 8000 | Qdrant请求超时 |
可选功能指南
本节提供了启用和使用每个可选功能的详细说明。
______________________________________________________________________
技能体系(ENABLE_SKILLS=1)
Skills系统允许您保存和重用代码模式以执行零样本。技能是 最强大的代币保存功能 在MCP网关中,重复任务的令牌使用量减少了95%以上。
什么技能
- 保存成功的代码模式 作为可重用的模板
- 执行复杂的工作流程 使用单个工具调用(约20个令牌)
- 消除快速工程 用于重复任务
- 热重载 当技能文件在磁盘上更改时
赋能技能
# In your .env file
ENABLE_SKILLS=1存储位置
所有技能都位于一个目录中: .agents/skills/
技能有两种:
可执行技能 (有 skill.json + index.ts)--可以通过运行 gateway_execute_skill:
code-review/
├── skill.json # Metadata (name, description, inputs, tags)
├── index.ts # Executable TypeScript code
├── SKILL.md # Human-readable protocol/instructions
├── scripts/ # Optional helper scripts
└── references/ # Optional reference docs仅协议技能 (有 SKILL.md 仅)——由AI代理加载,不能通过网关执行:
debugging/
└── SKILL.md # Protocol/instructions the AI follows仅协议技能出现在 gateway_list_skills 但如果您尝试执行它们,则返回一个有用的错误,指示您阅读SKILL.md。
通过MCP工具创造技能
// Create a new skill
await gateway_create_skill({
name: "daily-report",
description: "Generate daily sales summary by region",
code: `
const sales = await mssql.executeQuery({
query: \`SELECT region, SUM(amount) as total
FROM orders WHERE date = '\${date}' GROUP BY region\`
});
console.log(JSON.stringify(sales));
`,
inputs: [
{ name: "date", type: "string", required: true, description: "Date in YYYY-MM-DD format" }
],
tags: ["reporting", "sales", "daily"]
});执行技能
// Execute with ~20 tokens instead of 500+ for raw code
await gateway_execute_skill({
name: "daily-report",
inputs: { date: "2024-01-15" }
});技能MCP工具
| 工具 | 说明 |
|---|---|
gateway_list_skills | 使用元数据列出所有可用技能 |
gateway_search_skills | 按名称、描述或标签搜索技能 |
gateway_get_skill | 获取完整的技能细节,包括代码 |
gateway_execute_skill | 使用输入参数执行技能 |
gateway_create_skill | 创建新的可重用技能 |
技能REST API
| 端点 | 方法 | 描述 |
|---|---|---|
/api/code/skills | GET | 列出所有技能 |
/api/code/skills | POST | 创建新技能 |
/api/code/skills/search?q=query | GET | 搜索技能 |
/api/code/skills/:name | 获取 | 获取技能详细信息 |
/api/code/skills/:name | DELETE | 删除技能 |
/api/code/skills/:name/execute | POST | 执行技能 |
/api/code/skills/templates | 获取技能模板 | |
/api/code/skills/sync | POST | 将外部技能同步到工作区 |
仪表盘
当启用时,a 技能 选项卡出现在仪表板中(/dashboard)显示:
- 所有可用的搜索/筛选技能
- 技能详情和代码预览
- 直接从UI执行技能
- 从模板创建新技能
添加自己的技能
您可以通过两种方式向网关添加技能:
1.创建可执行技能 (通过以下方式实现自动化 gateway_execute_skill):
mkdir -p .agents/skills/my-skill创建三个文件:
skill.json --元数据:
{
"name": "my-skill",
"description": "What this skill does",
"version": "1.0.0",
"category": "productivity",
"inputs": [
{ "name": "target", "type": "string", "required": true, "description": "Target to process" }
],
"tags": ["automation"]
}index.ts --可执行代码:
const target = inputs?.target || 'default';
const result = await callTool('some_backend_tool', { query: target });
console.log(JSON.stringify(result));SKILL.md --人类可读的指令(可选但推荐)。
2.仅创建协议技能 (适用于AI代理工作流):
只需创建一个 SKILL.md 在技能目录中--否 skill.json 需要:
mkdir -p .agents/skills/my-protocol
cat > .agents/skills/my-protocol/SKILL.md
Claude Code (recommended — fully automatic)
克劳德代码支持 [钩子](https://docs.anthropic.com/en/docs/claude-code/hooks) 它在每个提示下运行。回购包括一个挂钩 `.agents/hooks/skill-activation.mjs` 它检测触发关键字并将技能推荐注入上下文。
**设置:** 将此添加到您的项目 `.claude/settings.local.json` (如果文件不存在,请创建该文件):
{ "hooks": { "UserPromptSubmit": [ { "hooks": [ { "type": "command", "command": "node .agents/hooks/skill-activation.mjs" } ] } ] } }
**它是如何工作的:**
1. 您键入如下提示 _“检查此代码是否存在安全问题”_
1. 挂钩匹配“审核代码”→ `code-review` 技能
1. 克劳德收到: _“加载 `.agents/skills/code-review/SKILL.md` 为了达到最佳效果”_
1. 克劳德阅读技能文件并遵循其协议
**自定义触发器:** 编辑 `SKILLS` 数组in `.agents/hooks/skill-activation.mjs` 添加您自己的关键字→ 技能映射。
Cursor
将此块添加到您的 `.cursorrules` 文件(或 `.cursor/rules/skills.mdc`):
Skills
This project has reusable AI skills at .agents/skills/. When the user's request matches a skill, read its SKILL.md BEFORE responding.
| User says | Read this skill |
|---|---|
| "review code", "security audit", "find bugs" | .agents/skills/code-review/SKILL.md |
| "debug", "fix bug", "not working", "error" | .agents/skills/debugging/SKILL.md |
| "commit", "push", "create PR", "merge" | .agents/skills/git-workflow/SKILL.md |
| "build UI", "dashboard", "React", "frontend" | .agents/skills/frontend-build/SKILL.md |
| "deploy", "docker", "production", "hosting" | .agents/skills/infra-deploy/SKILL.md |
| "SQL optimization", "slow query" | .agents/skills/sql-analyzer/SKILL.md |
To see all available skills: ls .agents/skills/
Windsurf
将与Cursor相同的块添加到您的 `.windsurfrules` 文件。
VS Code Copilot / Codex / Other
将此添加到IDE读取的用于AI指令的任何文件中(例如。, `AGENTS.md`, `.github/copilot-instructions.md`):
Skills
This project has reusable AI skills at .agents/skills/. Each skill directory contains a SKILL.md with instructions the AI should follow.
Before responding to a user request, check if any skill matches:
- List skills:
ls .agents/skills/ - If a skill name matches the task, read
.agents/skills/{name}/SKILL.md - Follow the skill's instructions in your response
Skills with a skill.json + index.ts can also be executed programmatically via the MCP Gateway: gateway_execute_skill({ name: "skill-name", inputs: {...} })
Any IDE — universal prompt snippet
如果以上都不适用,请将其粘贴到您的AI系统提示或项目说明中:
You have access to a skills library at .agents/skills/. Each skill is a directory containing a SKILL.md with step-by-step instructions for specific tasks.
IMPORTANT: Before starting any task, check if a matching skill exists:
- Code review → .agents/skills/code-review/SKILL.md
- Debugging → .agents/skills/debugging/SKILL.md
- Git workflow → .agents/skills/git-workflow/SKILL.md
- Frontend → .agents/skills/frontend-build/SKILL.md
- Deployment → .agents/skills/infra-deploy/SKILL.md
- SQL analysis → .agents/skills/sql-analyzer/SKILL.md
If a skill matches, read its SKILL.md and follow the protocol before responding. For the full list: ls .agents/skills/
______________________________________________________________________
### 密码存储器(`ENABLE_CIPHER=1`)
密码存储器提供 **跨所有IDE的持久AI内存**决策、学习、模式和见解存储在向量数据库中,并在未来的会话中自动调用。
#### 密码的作用是什么
- **跨IDE内存** -记忆在克劳德、光标、风帆、VS代码、Codex中持续存在
- **项目范围上下文** -按项目路径筛选内存
- **语义搜索** -使用自然语言查找相关记忆
- **自动整合** -自动存储会话摘要
#### 先决条件
Cipher需要两个外部服务:
1. **密码存储服务** -内存API(默认值: `http://localhost:8082`)
1. **Qdrant矢量存储** -用于语义记忆存储
#### 启用密码
In your .env file
ENABLE_CIPHER=1
Cipher service URL (if not running on default port)
CIPHER_API_URL=http://localhost:8082
Qdrant configuration (required for memory stats)
QDRANT_URL=https://your-qdrant-instance.cloud QDRANT_API_KEY=your-qdrant-api-key QDRANT_COLLECTION=cipher_knowledge QDRANT_TIMEOUT_MS=8000
#### 通过MCP使用密码
Cipher服务公开 `cipher_ask_cipher` 通过MCP工具:
// Store a decision cipher_ask_cipher({ message: "STORE DECISION: Using PostgreSQL for the user service. Reasoning: Better JSON support.", projectPath: "/path/to/your/project" });
// Recall context cipher_ask_cipher({ message: "Recall context for this project. What do you remember?", projectPath: "/path/to/your/project" });
// Search memories cipher_ask_cipher({ message: "Search memory for: database decisions", projectPath: "/path/to/your/project" });
#### 内存类型
|前缀|用例|示例|
|--------|----------|---------|
| `STORE DECISION:` |架构选择|“存储决策:使用Redis进行缓存”|
| `STORE LEARNING:` |Bug修复,发现|“商店学习:修复了身份验证中的竞争条件”|
| `STORE MILESTONE:` |已完成的功能|“STORE MILESTONE:已完成的用户身份验证系统”|
| `STORE PATTERN:` |代码模式|“存储模式:数据访问的存储库模式”|
| `STORE BLOCKER:` |持续存在的问题|“存储阻塞:ARM构建上的CI失败”|
#### 仪表板API
|端点|方法|描述|
|----------|--------|-------------|
| `/dashboard/api/cipher/sessions` |GET |列出内存会话|
| `/dashboard/api/cipher/sessions/:id/history` |GET |获取会话历史记录|
| `/dashboard/api/cipher/ask` |POST |向Cipher发送消息|
| `/dashboard/api/cipher/search?q=query` |获取|搜索记忆|
| `/dashboard/api/cipher/qdrant-stats` |GET |获取矢量存储统计信息|
| `/dashboard/api/cipher/memory/:id` |GET |按ID获取特定内存|
#### 仪表盘
当启用时,a **记忆** 选项卡显示:
- Qdrant中存储的总内存
- 带有时间戳的最近记忆
- 记忆类别细分(决策、学习等)
- 查找记忆的搜索界面
- 会话历史查看器
______________________________________________________________________
### Claude使用情况跟踪(`ENABLE_CLAUDE_USAGE=1`)
在所有Claude Code会话中跟踪您的Claude API代币消耗和成本。
#### 它的作用
- **汇总使用数据** 来自Claude Code JSONL日志
- **跟踪成本** 按型号(作品、十四行诗、俳句)
- **监控缓存效率** (创建令牌与读取令牌)
- **查看每日/每周/每月趋势**
- **实时会话监控**
#### 先决条件
此功能使用 `ccusage` 用于解析Claude Code对话日志的CLI工具 `~/.claude/projects/`.
The tool is auto-installed via npx when needed
npx ccusage@latest --json
#### 启用Claude使用
In your .env file
ENABLE_CLAUDE_USAGE=1
无需额外配置-服务会自动查找Claude代码日志。
#### 仪表板API
|端点|方法|描述|
|----------|--------|-------------|
| `/dashboard/api/claude-usage` |GET |获取使用情况摘要(缓存5分钟)|
| `/dashboard/api/claude-usage/range?since=YYYY-MM-DD&until=YYYY-MM-DD` |GET |获取日期范围的用法|
| `/dashboard/api/claude-usage/current` |GET |获取实时会话使用情况|
| `/dashboard/api/claude-usage/refresh` |POST |强制刷新缓存数据|
#### 响应格式
{ "totalCost": 45.67, "totalInputTokens": 15000000, "totalOutputTokens": 2500000, "totalCacheCreationTokens": 500000, "totalCacheReadTokens": 12000000, "cacheHitRatio": 96.0, "daysActive": 30, "avgCostPerDay": 1.52, "modelDistribution": [ { "model": "Claude Sonnet", "cost": 40.00, "percentage": 87.5 }, { "model": "Claude Opus", "cost": 5.67, "percentage": 12.5 } ], "topDays": [...], "daily": [...] }
#### 仪表盘
当启用时,a **用法** 选项卡显示:
- 总成本和代币明细
- 按型号列出的成本饼图
- 缓存命中率(更高=更高效)
- 每日使用趋势图
- 最高使用天数
- 实时会话监控
______________________________________________________________________
### 反重力使用跟踪(`ENABLE_ANTIGRAVITY=1`)
跟踪Antigravity IDE(前身为Windsurf/Codeium)帐户的配额和使用情况。
#### 它的作用
- **实时配额监控** 适用于所有模型层
- **多账户支持** (反重力+技术重力账户)
- **对话统计** 来自本地数据
- **大脑/任务跟踪** 用于代理工作流
- **自动检测** 运行语言服务器进程
#### 运作原理
服务内容:
1. 检测正在运行 `language_server_macos` 过程
1. 从进程参数中提取CSRF令牌和端口
1. 查询本地gRPC Web端点以获取配额数据
1. 如果API不可用,则返回到基于文件的统计数据
#### 先决条件
- 反重力IDE已安装并正在运行
- 帐户目录存在于 `~/.gemini/antigravity/` 或 `~/.gemini/techgravity/`
#### 启用反重力功能
In your .env file
ENABLE_ANTIGRAVITY=1
无需额外配置。
#### 仪表板API
|端点|方法|描述|
|----------|--------|-------------|
| `/dashboard/api/antigravity/available` |GET |检查反重力帐户是否存在|
| `/dashboard/api/antigravity/summary` |GET |获取完整的使用情况摘要|
| `/dashboard/api/antigravity/refresh` |POST |强制刷新缓存数据|
#### 响应格式
{ "status": { "isRunning": true, "processId": 12345, "port": 64446, "accounts": [ { "accountId": "antigravity", "accountName": "Antigravity", "accountEmail": "user@example.com", "planName": "Pro", "monthlyPromptCredits": 500, "availablePromptCredits": 450, "models": [ { "modelId": "gemini-3-pro-high", "label": "Gemini 3 Pro (High)", "remainingPercentage": 85, "isExhausted": false, "timeUntilReset": "4h 30m" }, { "modelId": "claude-sonnet-4.5", "label": "Claude Sonnet 4.5", "remainingPercentage": 60, "isExhausted": false } ] } ] }, "conversationStats": { "primary": { "totalConversations": 150, "totalSizeBytes": 25000000, "formattedSize": "23.8 MB", "recentConversations": 25 } }, "brainStats": { "primary": { "totalTasks": 12, "totalSizeBytes": 5000000 } } }
#### 仪表盘
启用后 **反重力** 选项卡显示:
- 运行状态指示灯(绿色=活动)
- 每个模型的每个帐户配额栏
- 带有颜色编码(绿色/黄色/红色)的剩余百分比
- 配额重置前的时间
- 会话和任务统计
- 多账户支持(反重力+技术重力)
______________________________________________________________________
### 启用所有功能
对于个人/开发用途,启用所有功能:
.env file
Core settings
PORT=3010 LOG_LEVEL=info
Enable all optional features
ENABLE_SKILLS=1 ENABLE_CIPHER=1 ENABLE_ANTIGRAVITY=1 ENABLE_CLAUDE_USAGE=1
Show all gateway tools (not just lite mode subset)
GATEWAY_LITE_MODE=0
Cipher/Qdrant settings (if using Cipher)
CIPHER_API_URL=http://localhost:8082 QDRANT_URL=https://your-qdrant.cloud QDRANT_API_KEY=your-api-key QDRANT_COLLECTION=cipher_knowledge
然后重新启动网关:
npm run build && npm start
现在,所有四个选项卡都将出现在仪表板上 `http://localhost:3010/dashboard`.
______________________________________________________________________
## 健康检查
curl http://localhost:3010/health
答复:
{ "status": "ok", "gateway": "mcp-gateway", "backends": { "connected": 2, "total": 3, "details": { "filesystem": { "status": "connected", "toolCount": 5, "resourceCount": 0, "promptCount": 0 } } }, "tools": 10, "resources": 0, "prompts": 0 }
## 建筑
┌─────────────────────────────────────────────────────────────────┐ │ MCP Clients │ │ (Claude Desktop, Cursor, Codex, VS Code) │ └─────────────────────────────────────────────────────────────────┘ │ HTTP Streamable / SSE │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ MCP Gateway │ │ ┌─────────────┐ ┌──────────────┐ ┌────────────────────────┐ │ │ │ Auth │ │ Rate Limit │ │ Protocol Handler │ │ │ │ Middleware │──│ Middleware │──│ (Aggregates Tools) │ │ │ └─────────────┘ └──────────────┘ └────────────────────────┘ │ │ │ │ │ ┌────────────────────┼────────────────┐ │ │ │ │ │ │ │ ▼ ▼ ▼ │ │ ┌──────────────────┐ ┌──────────────────┐ ┌──────┐ │ │ │ STDIO Backend │ │ HTTP Backend │ │ ... │ │ │ │ (Local Process) │ │ (Remote Server) │ │ │ │ │ └──────────────────┘ └──────────────────┘ └──────┘ │ └─────────────────────────────────────────────────────────────────┘ │ │ ▼ ▼ ┌──────────────────┐ ┌──────────────────┐ │ Local MCP │ │ Remote MCP │ │ Server │ │ Server │ └──────────────────┘ └──────────────────┘
## 代码执行模式
代码执行模式允许AI代理编写和执行代码,而不是进行单独的工具调用,实现高达 **代币减少98.7%** 对于复杂的工作流程。
### 为什么是技能?(效率和代币使用)
技能是MCP网关中最强大的令牌保存功能。原因如下:
#### 令牌问题
没有技能,每一项复杂的操作都需要:
1. **输入令牌**:用自然语言描述任务(约200-500个标记)
1. **推理令牌**:模型考虑如何实现它(~100-300个令牌)
1. **输出令牌**:模型生成要执行的代码(约200-1000个令牌)
1. **结果标记**:大型查询结果输入上下文(~500-10000+标记)
**总计:每次操作1000-12000+个令牌**
#### 技能解决方案
有了技能,同样的操作需要:
1. **输入令牌**: `gateway_execute_skill({ name: "daily-report" })` (约20个代币)
1. **结果标记**:预过滤、汇总输出(~50-200个令牌)
**总计:每次操作70-220个令牌→ 95%+ 减少**
#### 主要优势
|好处|描述|代币节省|
|---------|-------------|---------------|
| **零样本执行** |无提示解释 *怎么* 执行任务| 500-2000个令牌/调用|
| **确定性结果** |预测试代码,无LLM幻觉|消除重试|
| **批量操作** |单一技能中的多个工具调用|往返次数减少60-80%|
| **预滤波输出** |返回前处理的结果|在大型数据集上为80-95%|
| **缓存执行** |重复技能调用命中缓存|缓存命中率为100%|
#### 真实世界示例
**没有技能** (传统方法):
User: "Get me the daily sales report grouped by region" Model: [Thinks about SQL, table schema, grouping logic...] Model: [Generates code block with query, filtering, aggregation...] Tool: [Returns 10,000 rows of raw data] Model: [Processes and summarizes...]
Total: ~8,000 tokens, 4 round-trips, 15 seconds
**凭借技能** (基于技能的方法):
User: "Get me the daily sales report grouped by region" Model: gateway_execute_skill({ name: "daily-sales-report", inputs: { date: "today" } }) Tool: [Returns pre-aggregated summary: 5 regions, totals, trends]
Total: ~150 tokens, 1 round-trip, 2 seconds
### 网关MCP工具
所有代码执行功能都作为MCP工具公开,任何客户端都可以直接使用。当连接到网关时,客户端会自动获得这些 **19工具** 而不是300多个原始工具定义:
#### 工具发现(渐进式披露)
|工具|目的|代币影响|
|------|---------|--------------|
| `gateway_list_tool_names` |获取所有带分页的工具名称|~50字节/工具|
| `gateway_search_tools` |按名称、描述、类别、后端搜索|加载前筛选|
| `gateway_get_tool_schema` |延迟加载特定的工具模式|仅在需要时加载|
| `gateway_get_tool_schemas` |批量加载多个架构|使用 `compact: true` |
| `gateway_get_tool_categories` |获取语义类别(数据库、文件系统等)|轻松浏览300多种工具|
| `gateway_get_tool_tree` |获取按后端组织的工具|可视化层次结构|
| `gateway_get_tool_stats` |获取工具统计信息|按后端计数|
#### 执行和筛选
|工具|目的|代币影响|
|------|---------|--------------|
| `gateway_execute_code` |在沙盒中执行Types/JavaScript |批处理多个操作|
| `gateway_call_tool_filtered` |调用任何具有结果过滤功能的工具|结果缩小60-80%|
| `gateway_call_tool_aggregate` |具有聚合功能的调用工具|分析功能缩小90%以上|
| `gateway_call_tools_parallel` |并行执行多个工具|减少往返次数|
#### 技能(最高代币节省)
|工具|目的|代币影响|
|------|---------|--------------|
| `gateway_list_skills` |列出保存的代码模式|发现可用技能|
| `gateway_search_skills` |按姓名/标签搜索技能|快速找到合适的技能|
| `gateway_get_skill` |获取技能细节和代码|执行前检查|
| `gateway_execute_skill` |执行已保存的技能| **每次通话约20个代币** |
| `gateway_create_skill` |节省新的可重复使用技能|一次性投资|
#### 优化与监控
|工具|目的|代币影响|
|------|---------|--------------|
| `gateway_get_optimization_stats` |查看代币节省统计数据|监控效率|
| `gateway_call_tool_delta` |具有增量响应的调用工具-仅更改| **重复查询90%以上** |
| `gateway_get_context_status` |监控上下文窗口的使用情况并获取警告|防止溢出|
| `gateway_call_tool_summarized` |调用工具,自动汇总结果| **60-90%用于大数据** |
| `gateway_analyze_code` |分析代码以寻找优化机会|提高效率|
### 渐进式工具披露
与其预先加载所有工具定义(这可能会消耗300多个工具的过多令牌),不如使用渐进式披露:
Get just tool names (minimal tokens)
curl http://localhost:3010/api/code/tools/names
Search for specific tools
curl "http://localhost:3010/api/code/tools/search?query=database&backend=mssql"
Get filesystem-like tree view
curl http://localhost:3010/api/code/tools/tree
Lazy-load specific tool schema when needed
curl http://localhost:3010/api/code/tools/mssql_execute_query/schema
搜索的详细级别:
- `name_only` -只是工具名称
- `name_description` -带有描述的名称
- `full_schema` -完整的JSON模式
### 沙盒代码执行
在安全的Node.js虚拟机沙箱中执行Types/JavaScript代码:
curl -X POST http://localhost:3010/api/code/execute \ -H "Content-Type: application/json" \ -d '{ "code": "const data = await mssql.executeQuery({ query: \"SELECT * FROM users\" });\nconst active = data.filter(u => u.active);\nconsole.log(Found ${active.length} active users);", "timeout": 30000 }'
沙盒:
- 从MCP工具自动生成TypeScript SDK
- 支持async/await、循环和条件语句
- 仅限退货 `console.log` 输出(非原始数据)
- 具有可配置的超时保护
### 上下文高效结果
减少大型工具结果导致的上下文膨胀:
Call tool with filtering
curl -X POST http://localhost:3010/api/code/tools/mssql_get_table_data/call \ -H "Content-Type: application/json" \ -d '{ "args": { "tableName": "users" }, "options": { "maxRows": 10, "fields": ["id", "name", "email"], "format": "summary" } }'
Call with aggregation
curl -X POST http://localhost:3010/api/code/tools/mssql_get_table_data/call/aggregate \ -H "Content-Type: application/json" \ -d '{ "args": { "tableName": "orders" }, "aggregation": { "operation": "groupBy", "field": "status", "countField": "count" } }'
可用聚合: `count`, `sum`, `avg`, `min`, `max`, `groupBy`, `distinct`
### 隐私保护操作
自动标记PII,使敏感数据永远不会进入模型上下文:
curl -X POST http://localhost:3010/api/code/execute \ -H "Content-Type: application/json" \ -d '{ "code": "const users = await mssql.executeQuery({ query: \"SELECT * FROM users\" });\nconsole.log(users);", "privacy": { "tokenize": true, "patterns": ["email", "phone", "ssn", "credit_card"] } }'
输出显示标记值:
[{ name: "John", email: "[EMAIL_1]", phone: "[PHONE_1]" }]
当数据流向另一个工具时,令牌会自动取消标记。
### 技能体系
将成功的代码模式保存为可重用的技能:
Create a skill
curl -X POST http://localhost:3010/api/code/skills \ -H "Content-Type: application/json" \ -d '{ "name": "export-active-users", "description": "Export active users to CSV", "code": "const users = await mssql.executeQuery({ query: \"SELECT * FROM users WHERE active = 1\" });\nreturn users;", "parameters": { "type": "object", "properties": { "limit": { "type": "number", "default": 100 } } } }'
List all skills
curl http://localhost:3010/api/code/skills
Execute a skill
curl -X POST http://localhost:3010/api/code/skills/export-active-users/execute \ -H "Content-Type: application/json" \ -d '{ "limit": 50 }'
技能存储在 `skills/` 目录,可以通过文件系统探索来发现。
### 会话状态和工作区
跨代理会话保持状态:
Save session state
curl -X POST http://localhost:3010/api/code/workspace/session \ -H "Content-Type: application/json" \ -d '{ "lastQuery": "SELECT * FROM users", "results": { "count": 150 } }'
Retrieve session state
curl http://localhost:3010/api/code/workspace/session
状态存储在 `workspace/` 目录。
## 监控和指标
### 普罗米修斯指标
curl http://localhost:3010/metrics
返回的指标包括:
- `mcp_tool_calls_total` -按后端和工具划分的工具调用总数
- `mcp_tool_call_duration_seconds` -工具调用延迟直方图
- `mcp_tool_errors_total` -后端错误计数
- `mcp_cache_hits_total` / `mcp_cache_misses_total` -缓存性能
- `mcp_active_connections` -活动客户端连接
### JSON度量
curl http://localhost:3010/metrics/json
### 缓存
使用带TTL的LRU缓存缓存工具结果:
View cache statistics
curl http://localhost:3010/api/code/cache/stats
Clear cache
curl -X POST http://localhost:3010/api/code/cache/clear
## 令牌效率架构
MCP网关实现了一种多层方法,以最大限度地减少AI代理交互每个阶段的令牌使用。
### 第1层:渐进式工具披露(减少85%)
传统的MCP客户端预先加载所有工具模式。使用300多个工具,在任何工作开始之前,这可能会消耗77000多个令牌。
Traditional: Load 305 tools → 77,000 tokens in context Gateway: Load 14 gateway tools → 8,900 tokens in context (89% less)
**它是如何工作的:**
// Step 1: Get just tool names (50 bytes each) const names = await gateway_list_tool_names(); // Returns: ["db_query", "db_insert", "fs_read", ...]
// Step 2: Search with minimal detail const tools = await gateway_search_tools({ query: "database", detailLevel: "name_only" // or "name_description" });
// Step 3: Load full schema ONLY when calling const schema = await gateway_get_tool_schema({ toolName: "db_query", compact: true // 40% smaller schemas });
### 第二层:智能结果过滤(减少60-80%)
大型工具结果可能会消耗数千个令牌。智能过滤 **默认启用**.
// Default behavior - auto-applies smart filtering await gateway_call_tool_filtered({ toolName: "database_query", args: { query: "SELECT * FROM users" } }); // Returns: { rowCount: 10000, sample: [...first 20 rows...], truncated: true }
// Explicit filtering for more control await gateway_call_tool_filtered({ toolName: "database_query", args: { query: "SELECT * FROM users" }, filter: { maxRows: 10, // Limit rows maxTokens: 500, // Budget-aware truncation fields: ["id", "name"], // Select columns format: "summary" // Count + sample } });
### 第3层:服务器端聚合
在网关中计算聚合,而不是获取原始数据并在客户端进行处理:
// Without aggregation: Fetch 10,000 orders → 50,000 tokens // With aggregation: Get summary → 200 tokens
await gateway_call_tool_aggregate({ toolName: "orders_table", args: { tableName: "orders" }, aggregation: { operation: "groupBy", groupByField: "status" } }); // Returns: { "completed": 5420, "pending": 3210, "cancelled": 1370 }
**可用操作:** `count`, `sum`, `avg`, `min`, `max`, `groupBy`, `distinct`
### 第4层:代码执行批处理
在一次往返中执行多个操作。结果在服务器端处理;仅 `console.log` 输出返回。
// Without batching: 5 tool calls = 5 round-trips + 5 result payloads // With batching: 1 code execution = 1 round-trip + 1 summarized output
await gateway_execute_code({ code: ` const users = await db.query("SELECT * FROM users WHERE active = 1"); const orders = await db.query("SELECT * FROM orders WHERE user_id IN (...)");
const summary = users.map(u => ({ name: u.name, orderCount: orders.filter(o => o.user_id === u.id).length }));
console.log(JSON.stringify(summary.slice(0, 10))); ` });
### 第5层:技能(95%以上减少)
技能完全消除了重复任务的即时工程:
// Create once await gateway_create_skill({ name: "user-activity-report", description: "Get user activity summary for a date range", code: const users = await db.query(\SELECT * FROM users WHERE last_active BETWEEN '\${startDate}' AND '\${endDate}'\); const grouped = users.reduce((acc, u) => { acc[u.department] = (acc[u.department] || 0) + 1; return acc; }, {}); console.log(JSON.stringify({ total: users.length, byDepartment: grouped })); , inputs: [ { name: "startDate", type: "string", required: true }, { name: "endDate", type: "string", required: true } ] });
// Execute forever (~20 tokens per call) await gateway_execute_skill({ name: "user-activity-report", inputs: { startDate: "2024-01-01", endDate: "2024-01-31" } });
### 第6层:结果缓存
相同的查询会命中LRU缓存,而不是重新执行:
// First call: Executes tool, caches result await gateway_call_tool_filtered({ toolName: "db_query", args: { query: "SELECT COUNT(*) FROM users" } });
// Second call: Returns cached result instantly (0 tool execution tokens) await gateway_call_tool_filtered({ toolName: "db_query", args: { query: "SELECT COUNT(*) FROM users" } });
### 第7层:PII标记化
敏感数据在工具之间流动时,永远不会进入模型上下文:
// Raw data: { email: "john@example.com", ssn: "123-45-6789" } // Model sees: { email: "[EMAIL_1]", ssn: "[SSN_1]" } // Next tool receives: Original values (auto-detokenized)
### 第8层:响应优化(减少20-40%)
自动从所有响应中删除默认值/空值:
// Before optimization (raw response): { name: "John", email: null, phone: "", orders: [], metadata: {} }
// After optimization (stripped): { name: "John" } // Saves 20-40% tokens on typical API responses
条状物: `null`, `undefined`,空字符串 `""`,空数组 `[]`,空对象 `{}`
### 第9层:会话上下文缓存(非常高的缩减)
跟踪会话中已发送的模式和数据,以避免重新发送:
// First call: Full schema sent (~500 tokens) await gateway_get_tool_schema({ toolName: "db_query" });
// Second call in same session: Reference returned (~20 tokens) await gateway_get_tool_schema({ toolName: "db_query" }); // Returns: "[See schema 'db_query' sent earlier in conversation]"
// View savings await gateway_get_optimization_stats(); // Returns: { session: { duplicatesAvoided: 15, tokensSaved: 4500 }, ... }
### 第10层:模式重复数据删除(最多可减少90%)
许多工具共享相同的模式。通过哈希引用而不是复制:
// 10 database tools with same query schema: // Without dedup: 10 × 200 tokens = 2000 tokens // With dedup: 200 tokens (schema) + 10 × 5 tokens (refs) = 250 tokens // Savings: 87.5%
// The gateway automatically identifies duplicate schemas await gateway_get_optimization_stats(); // Returns: { schemaDeduplication: { uniqueSchemas: 45, totalSchemas: 305, duplicateSchemas: 260 } }
### 第11层:微模式(减少60-70%)
使用缩写类型的超紧凑模式表示:
// Full schema (~200 tokens): { type: "object", properties: { query: { type: "string", description: "SQL query" }, limit: { type: "number" } }, required: ["query"] }
// Micro schema (~60 tokens): { p: { query: { t: "s", r: 1 }, limit: { t: "n" } } }
// Use micro mode for maximum savings await gateway_search_tools({ query: "database", detailLevel: "micro_schema" }); await gateway_get_tool_schema({ toolName: "db_query", mode: "micro" });
// Type abbreviations: s=string, n=number, i=integer, b=boolean, a=array, o=object // r=1 means required, e=enum values, d=default value
### 第12层:增量响应(减少90%+)
对于重复查询或轮询,只发送自上次调用以来的更改:
// First call - returns full data await gateway_call_tool_delta({ toolName: "database_query", args: { query: "SELECT * FROM active_users" }, idField: "id" // Optional: use ID for smarter diffing }); // Returns: { isDelta: false, data: [...1000 users...], stateHash: "abc123" }
// Second call - returns only changes await gateway_call_tool_delta({ toolName: "database_query", args: { query: "SELECT * FROM active_users" }, idField: "id" }); // Returns: { isDelta: true, data: { type: "diff", added: [2 new], updated: {"5": {...}}, removed: ["3"] }, stats: { savedPercent: 95 } }
// Perfect for: // - Dashboard refreshes // - Monitoring queries // - Real-time data feeds // - Polling scenarios
### 第13层:上下文窗口跟踪(安全)
监控上下文使用情况以防止溢出并获得优化建议:
// Check current context status await gateway_get_context_status(); // Returns: { // tokensUsed: 45000, // contextLimit: 128000, // percentUsed: 35, // warning: null, // 'low', 'medium', 'high', 'critical' // recommendation: null, // breakdown: { schemas: 8000, results: 32000, code: 5000 }, // recentCalls: [{ tool: "db_query", tokens: 1200, timestamp: ... }] // }
// When context is high (>70%), you'll get warnings: // warning: "medium" // recommendation: "Consider using compact or micro schema modes. Use result filtering."
// When critical (>95%): // warning: "critical" // recommendation: "CRITICAL: Context nearly full. Complete current task or start new session."
### 第14层:自动汇总(减少60-90%)
从大型结果中自动提取见解:
// Instead of returning 10,000 rows... await gateway_call_tool_summarized({ toolName: "database_query", args: { query: "SELECT * FROM orders" }, maxTokens: 300, focusFields: ["status", "amount"] });
// Returns summarized insights: // { // wasSummarized: true, // data: { // count: 10000, // fields: ["id", "status", "amount", "created_at"], // sample: [/* first 5 rows */], // stats: { amount: { min: 10, max: 5000, avg: 250 } }, // distribution: { status: { completed: 7500, pending: 2000, cancelled: 500 } }, // insights: [ // "Total records: 10000", // "status distribution: completed: 7500, pending: 2000, cancelled: 500", // "amount: min=10, max=5000, avg=250" // ] // }, // summary: { originalTokens: 45000, summaryTokens: 280, savedPercent: 99 } // }
### 第15层:查询计划(改进30-50%)
执行前分析代码以检测优化机会:
await gateway_analyze_code({ code: ` const users = await db.query("SELECT * FROM users"); const orders = await db.query("SELECT * FROM orders"); const products = await db.query("SELECT * FROM products");
for (const user of users) { await db.query(\SELECT * FROM logs WHERE user_id = \${user.id}\); } ` });
// Returns optimization plan: // { // toolCalls: [/* detected calls */], // suggestions: [ // { // type: "parallel", // severity: "info", // message: "Sequential awaits on lines 2, 3, 4 could run in parallel with Promise.all()", // suggestedCode: "const [users, orders, products] = await Promise.all([...])", // estimatedSavings: "66% time reduction" // }, // { // type: "batch", // severity: "warning", // message: "Potential N+1 query pattern detected (await inside loop)", // estimatedSavings: "80-95% reduction for large datasets" // }, // { // type: "filter", // severity: "warning", // message: "SELECT * returns all columns. Consider selecting only needed fields.", // estimatedSavings: "30-70% token reduction" // } // ], // warnings: ["High number of tool calls (4). Consider using code batching."], // summary: "Found 4 tool calls. Optimization opportunities: 1 parallel, 1 batch, 1 filter." // }
### 组合代币节省
|图层|功能|典型节省|
|-------|---------|-----------------|
|1|渐进式披露|85%关于工具模式|
|2|智能筛选|结果的60-80%|
|3 |汇总|分析能力超过90%|
|4 |代码批处理|往返次数减少60-80%|
|5 |技能|重复任务95%以上|
|6 |缓存|重复查询时100%缓存|
|7|PII标记化|防止数据泄露|
|8|响应优化|所有响应的20-40%|
|9|会话上下文|多回合时非常高|
|10 |架构重复数据消除|在类似工具上高达90%|
|11 |微模式|模式定义的60-70%|
|12 |增量响应|重复/轮询查询的90%以上|
|13|上下文跟踪|防止上下文溢出|
|14 |自动摘要|大型数据集上的60-90%|
|15|查询计划|30-50%通过优化|
**现实世界影响:** 一个典型的10分钟代理会话,包含50个工具调用,从约500000个令牌下降到约25000个令牌。
## AI代理提示
当将MCP网关与AI代理(Claude、GPT等)一起使用时,请遵循以下最佳实践以高效使用令牌:
### 1.从工具发现开始
// First, get just tool names (minimal tokens) const names = await gateway_list_tool_names();
// Search for specific functionality const dbTools = await gateway_search_tools({ query: "database", detailLevel: "name_description" });
// Only load full schema when you need to call a tool const schema = await gateway_get_tool_schema({ toolName: "mssql_execute_query" });
### 2.对复杂工作流使用代码执行
// Instead of multiple tool calls, batch operations in code await gateway_execute_code({ code: const users = await mssql.executeQuery({ query: "SELECT * FROM users WHERE active = 1" }); const summary = users.reduce((acc, u) => { acc[u.department] = (acc[u.department] || 0) + 1; return acc; }, {}); console.log(JSON.stringify(summary)); });
### 3.过滤大结果
// Reduce context bloat from large datasets await gateway_call_tool_filtered({ toolName: "mssql_get_table_data", args: { tableName: "orders" }, filter: { maxRows: 10, fields: ["id", "status", "total"], format: "summary" } });
// Smart filtering is ON by default (maxRows: 20, format: "summary") // Just call without filter - tokens are minimized automatically await gateway_call_tool_filtered({ toolName: "mssql_get_table_data", args: { tableName: "orders" } });
// Opt-out for raw results when you need full data await gateway_call_tool_filtered({ toolName: "mssql_get_table_data", args: { tableName: "orders" }, smart: false });
### 4.使用聚合
// Get summaries instead of raw data await gateway_call_tool_aggregate({ toolName: "mssql_get_table_data", args: { tableName: "orders" }, aggregation: { operation: "groupBy", groupByField: "status" } });
### 5.将可重用模式保存为技能
// Create a skill for common operations await gateway_create_skill({ name: "daily-sales-report", description: "Generate daily sales summary", code: "const sales = await mssql.executeQuery({...}); console.log(sales);", tags: ["reporting", "sales"] });
// Execute later with different inputs await gateway_execute_skill({ name: "daily-sales-report", inputs: { date: "2024-01-15" } });
## 从任何IDE调用密码
Cipher暴露了 `cipher_ask_cipher` 通过MCP工具。为了确保存储器在IDE和会话之间持久存在, **始终包括 `projectPath` 参数**.
### 工具模式
cipher_ask_cipher({ message: string, // Required: What to store or ask projectPath: string // Recommended: Full project path for cross-IDE filtering })
### 快速参考
|操作|消息格式|
|--------|----------------|
| **回忆上下文** | `"Recall context for this project. What do you remember?"` |
| **店铺决策** | `"STORE DECISION: [description]. Reasoning: [why]"` |
| **商店错误修复** | `"STORE LEARNING: Fixed [bug]. Root cause: [cause]. Solution: [fix]"` |
| **门店里程碑** | `"STORE MILESTONE: Completed [feature]. Key files: [files]"` |
| **店铺格局** | `"STORE PATTERN: [pattern_name]. Usage: [when_to_use]"` |
| **商店拦截器** | `"STORE BLOCKER: [description]. Attempted: [what_tried]"` |
| **搜索记忆** | `"Search memory for: [topic]. What patterns or learnings are relevant?"` |
| **会话结束** | `"Consolidate session. Accomplishments: [list]. Open: [items]"` |
### IDE配置示例
将这些指令添加到IDE的规则文件中,以便AI自动使用Cipher。
Claude Code (~/.claude/CLAUDE.md)
Claude Code可以使用SessionStart钩子进行自动调用。对于手动配置:
Cipher Memory Protocol
At session start, recall context: cipher_ask_cipher({ message: "Recall context for this project. What do you remember?", projectPath: "/path/to/your/project" })
Auto-store important events (decisions, bug fixes, milestones, patterns, blockers) using cipher_ask_cipher with the STORE prefix and always include projectPath.
Cursor (~/.cursorrules)
Cipher Memory Protocol - MANDATORY
Session Start
At the start of EVERY conversation, call: cipher_ask_cipher({ message: "Recall context for this project. What do you remember?", projectPath: "/path/to/your/project" })
Auto-Store Events
| Event | Call |
|---|---|
| Decision | cipher_ask_cipher({ message: "STORE DECISION: ...", projectPath: "..." }) |
| Bug fix | cipher_ask_cipher({ message: "STORE LEARNING: ...", projectPath: "..." }) |
| Feature | cipher_ask_cipher({ message: "STORE MILESTONE: ...", projectPath: "..." }) |
| Pattern | cipher_ask_cipher({ message: "STORE PATTERN: ...", projectPath: "..." }) |
projectPath Rules
- ALWAYS use FULL path: /path/to/your/project
- NEVER use placeholders like {cwd} - use the actual path
- Determine path from workspace folder or open files
Windsurf (~/.windsurfrules)
Cipher Memory Protocol - MANDATORY
Session Start
At the start of EVERY conversation, call: cipher_ask_cipher({ message: "Recall context for this project. What do you remember?", projectPath: "/path/to/your/project" })
Auto-Store Events
Store decisions, bug fixes, milestones, and patterns automatically using cipher_ask_cipher with STORE prefix. Always include full projectPath.
projectPath Rules
- ALWAYS use FULL path - /path/to/your/project
- NEVER use placeholders - determine actual path from context
VS Code / GitHub Copilot (~/.github/copilot-instructions.md)
Cipher Memory Protocol - MANDATORY
Session Start
At the start of EVERY conversation, call: cipher_ask_cipher({ message: "Recall context for this project. What do you remember?", projectPath: "/path/to/your/project" })
Auto-Store Events
When you encounter decisions, bug fixes, completed features, or discovered patterns, store them in Cipher using cipher_ask_cipher with the appropriate STORE prefix.
projectPath is MANDATORY
- Use FULL path like /path/to/your/project
- Never use placeholders or just the project name
Codex CLI (~/.codex/AGENTS.md)
Cipher Memory Protocol - MANDATORY
Session Start
At the start of EVERY conversation, call: cipher_ask_cipher message="Recall context for this project. What do you remember?" projectPath="/path/to/your/project"
Auto-Store Events
| Event | Example Call |
|---|---|
| Decision | cipher_ask_cipher message="STORE DECISION: [desc]" projectPath="/path/to/your/project" |
| Bug fix | cipher_ask_cipher message="STORE LEARNING: Fixed [bug]" projectPath="/path/to/your/project" |
| Feature | cipher_ask_cipher message="STORE MILESTONE: Completed [feature]" projectPath="/path/to/your/project" |
projectPath Rules
- ALWAYS use FULL path - /path/to/your/project
- NEVER use placeholders - look at open files to determine actual path
Google Gemini / Antigravity (~/.gemini/GEMINI.md)
alwaysApply: true
Cipher Memory Protocol - MANDATORY
CRITICAL: Determine Project Path FIRST
Before ANY cipher call, determine the FULL project path from:
- Workspace folder open in the IDE
- File paths in the conversation
Session Start
cipher_ask_cipher({ message: "Recall context for this project. What do you remember?", projectPath: "/path/to/your/project" })
Auto-Store Events
Store decisions, learnings, milestones, and patterns using STORE prefix. Always include projectPath with the FULL path.
projectPath Rules
- ALWAYS use FULL path - /path/to/your/project
- NEVER use {cwd} or {project} placeholders - they don't resolve!
- Determine path from context - workspace name, file paths, or ask user
### 为什么projectPath很重要
这 `projectPath` 参数为 **关键的** 用于:
1. **跨IDE过滤**:内存的作用域是项目,因此从Cursor切换到Claude Code可以保持上下文。
1. **避免污染**:没有projectPath,来自不同项目的记忆会混合在一起。
1. **团队同步**:工作区内存功能依赖于一致的项目路径。
**常见错误**:使用 `{cwd}` 或者只是项目名称。这些问题无法正确解决。始终使用完整的绝对路径,如 `/path/to/your/project`.
## macOS自动启动(LaunchAgent)
要在登录时自动运行网关,请执行以下操作:
1. 复制并自定义示例plist文件:
Copy the example file
cp com.mcp-gateway.plist.example ~/Library/LaunchAgents/com.mcp-gateway.plist
Edit the file to update paths for your installation
nano ~/Library/LaunchAgents/com.mcp-gateway.plist
更新plist文件中的这些路径:
- `/path/to/mcp-gateway` → 您的实际安装路径
- `/usr/local/bin/node` → 你的Node.js路径(运行 `which node` 找到它)
2. 加载LaunchAgent:
Create logs directory
mkdir -p /path/to/mcp-gateway/logs
Load (start) the service
launchctl load ~/Library/LaunchAgents/com.mcp-gateway.plist
Unload (stop) the service
launchctl unload ~/Library/LaunchAgents/com.mcp-gateway.plist
Restart the service
launchctl kickstart -k gui/$(id -u)/com.mcp-gateway
## Windows安装程序
### 运行网关
Install dependencies
npm install
Development mode
npm run dev
Production
npm run build npm start
### Windows自动启动(任务计划程序)
要在Windows启动时自动运行网关,请执行以下操作:
1. 打开 **任务计划程序** (`taskschd.msc`)
1. 点击 **创建任务** (非基本任务)
1. 配置:
- **常规选项卡**:说出它的名字 `MCP Gateway`,检查“用户是否登录运行”
- **触发器选项卡**:添加触发器→ “启动时”
- **操作选项卡**:添加操作:
- 程序: `node` (或全路径式 `C:\Program Files\nodejs\node.exe`)
- 论据: `dist/index.js`
- 开始时间: `C:\path\to\mcp-gateway`
- **设置标签**:选中“允许按需运行任务”
或者,使用 `start.example.sh` 适用于PowerShell的模式:
start-gateway.ps1
$env:NODE_ENV = "production" $env:PORT = "3010"
Set-Location "C:\path\to\mcp-gateway"
while ($true) { Write-Host "Starting MCP Gateway..." node dist/index.js Write-Host "Gateway stopped. Restarting in 5 seconds..." Start-Sleep -Seconds 5 }
### Windows服务(NSSM)
要获得正确的Windows服务,请使用 [国家安全研究备忘录](https://nssm.cc/):
Install NSSM, then:
nssm install MCPGateway "C:\Program Files\nodejs\node.exe" "C:\path\to\mcp-gateway\dist\index.js" nssm set MCPGateway AppDirectory "C:\path\to\mcp-gateway" nssm set MCPGateway AppEnvironmentExtra "NODE_ENV=production" "PORT=3010" nssm start MCPGateway
## 发展
Install dependencies
npm install
Run in development mode (with hot reload)
npm run dev
Type check
npm run typecheck
Lint
npm run lint
Build for production
npm run build
## 许可证
麻省理工学院