工具门控MCP
用于模型上下文协议(MCP)的智能代理/路由器,使Claude Desktop和其他MCP客户端能够动态发现和使用来自多个MCP服务器的工具,同时保持单个连接点。该系统通过智能地为每个任务选择最相关的工具来防止上下文膨胀。
🎯 问题
像Claude Desktop这样的MCP客户端必须在启动时加载所有服务器,并且不能在对话期间动态添加服务器。使用多个MCP服务器时:
- Exa服务器:7个搜索工具(网络、研究论文、推特、公司等)
- 操纵者:浏览器自动化工具
- 背景7:文档搜索工具
- 桌面指挥官:18+桌面自动化工具
直接加载所有服务器会导致:
- 🚨 上下文膨胀:100多种工具占用了大部分上下文窗口
- 🔒 静态配置:如果不重新启动Claude,则无法添加服务器
- 💸 成本增加:每次请求消耗的令牌更多
- 🎯 工具选择不当:人工智能难以从太多的选项中做出选择
💡 解决方案
工具门控MCP充当智能代理:
- 单个连接:Claude Desktop仅连接到工具门控
- 后端管理:保持与多个MCP服务器的连接
- 智能发现:使用语义搜索在所有服务器上查找相关工具
- 动态预配置:仅在令牌预算内加载所需的工具
- 透明路由:在适当的后端服务器上执行工具
示例:与其用100多个工具配置10个MCP服务器,不如只配置工具门控。然后动态发现并仅使用您需要的2-3个工具。
🚀 特性
- 代理架构:路由到多个后端服务器的单个MCP服务器
- 动态工具发现:无需手动配置即可在所有服务器上查找工具
- 语义搜索:通过自然语言查询找到合适的工具
- 智能资源调配:仅在代币预算内加载相关工具
- 透明执行:将工具调用路由到适当的后端服务器
- 本地MCP服务器:通过mcp代理直接与Claude Desktop集成
- 跨服务器智能:Puppeteer、Exa、Context7等工具的统一视图。
- 令牌优化:与加载所有服务器相比,上下文使用率降低了90%以上
- 零配置:Claude Desktop只需要工具门控配置
📋 先决条件
- Python 3.12+
- 紫外线 包管理器
🔧 安装
- 克隆存储库:
git clone https://github.com/yourusername/tool-gating-mcp.git
cd tool-gating-mcp- 创建并激活虚拟环境:
uv venv
source .venv/bin/activate # On Unix/macOS
# .venv\Scripts\activate # On Windows- 安装依赖项:
uv sync- 在开发模式下安装软件包:
uv pip install -e .🏃 运行服务器
作为HTTP API服务器
# Start the server
tool-gating-mcp
# Or with uvicorn for development
uvicorn tool_gating_mcp.main:app --reload服务器将在上运行 http://localhost:8000
API文件可在以下网址获取:
- Swagger用户界面:
http://localhost:8000/docs - 重新记录:
http://localhost:8000/redoc - MCP端点:
http://localhost:8000/mcp(SSE运输)
作为MCP服务器(推荐)
Tool Gating MCP现在是一个直接与Claude Desktop配合使用的原生MCP服务器:
- 启动服务器:
tool-gating-mcp- 安装mcp代理 (如果尚未安装):
uv tool install mcp-proxy- 添加到克劳德桌面:
编辑 ~/Library/Application Support/Claude/claude_desktop_config.json:
{
"mcpServers": {
"tool-gating": {
"command": "/Users/YOUR_USERNAME/.local/bin/mcp-proxy",
"args": ["http://localhost:8000/mcp"]
}
}
}注:更换 YOUR_USERNAME 使用您的实际用户名。
- 重新启动克劳德桌面
您将在Claude中看到Tool Gating的工具,包括:
discover_tools-根据查询查找相关工具provision_tools-在代币预算内选择工具register_tool-向注册表添加新工具list_mcp_servers-查看已注册的MCP服务器- 还有更多!
看 MCP本机使用指南 详细说明。
🔍 API终点
工具发现
POST /api/tools/discover基于语义搜索发现相关工具。
请求:
{
"query": "I need to perform calculations",
"tags": ["math", "calculation"],
"limit": 5
}答复:
{
"tools": [
{
"tool_id": "calculator",
"name": "Calculator",
"description": "Perform mathematical calculations",
"score": 0.95,
"matched_tags": ["math", "calculation"],
"estimated_tokens": 50
}
],
"query_id": "uuid",
"timestamp": "2024-01-01T00:00:00"
}工具配置
POST /api/tools/provision选择并格式化用于LLM消费的工具,并强制执行代币预算。
请求:
{
"tool_ids": ["calculator", "web-search"],
"max_tools": 3
}答复:
{
"tools": [
{
"name": "Calculator",
"description": "Perform mathematical calculations",
"parameters": { "type": "object", "properties": {...} },
"token_count": 50
}
],
"metadata": {
"total_tokens": 150,
"gating_applied": true
}
}🔄 运作原理
- Claude桌面配置:仅配置工具门控MCP
{
"mcpServers": {
"tool-gating": {
"command": "mcp-proxy",
"args": ["http://localhost:8000/mcp"]
}
}
}- 后端服务器连接:工具门控连接到多个MCP服务器
Tool Gating → puppeteer (browser tools)
→ exa (search tools)
→ context7 (documentation)
→ filesystem (file operations)- 自然语言发现:“我需要搜索研究论文”
Claude → discover_tools → Semantic Search → Returns relevant tools- 实时工具执行:工具按需加载
execute_tool("exa_research_paper_search", {...}) → Validates → Loads → Executes无需配置!工具在使用时会动态加载。
🎯 使用示例
运行演示
# Make sure the server is running first
tool-gating-mcp
# In another terminal, run the interactive demo
python demo.py手动测试
# Test the server endpoints
python test_server.py示例:查找数学工具
import httpx
import asyncio
async def find_math_tools():
async with httpx.AsyncClient() as client:
response = await client.post(
"http://localhost:8000/api/tools/discover",
json={
"query": "I need to solve equations",
"tags": ["math"],
"limit": 3
}
)
tools = response.json()["tools"]
print(f"Found {len(tools)} relevant tools")
for tool in tools:
print(f"- {tool['name']}: {tool['score']:.3f}")
asyncio.run(find_math_tools())🧪 测试
# Run all tests
pytest
# Run with coverage
pytest --cov=tool_gating_mcp
# Run specific test files
pytest tests/test_discovery_service.py -v
# Run integration tests
pytest tests/test_integration.py -v📊 建筑细部
- 工具注册:工具与元数据、标签和令牌估计一起注册
- 语义搜索:使用句子转换器嵌入用户查询
- 相关性评分:工具评分基于:
- 查询与工具嵌入之间的余弦相似性 - 标签匹配(每个匹配标签增加0.2个增益)
- 实时加载:工具在执行过程中按需验证和加载
- MCP格式化:所选工具根据MCP协议进行格式化
🔧 配置
系统使用合理的默认值,但可以配置:
- 最大令牌数:每个请求默认2000个令牌
- Max工具:默认每个请求10个工具
- 嵌入模型:
all-MiniLM-L6-v2(384个维度嵌入)
📖 文档
- 刀具发现系统 -语义搜索和标签如何协同工作
- 添加新的MCP服务器 -集成新服务器的分步指南
- AI集成指南 -AI助手如何自动添加MCP服务器
- 架构概述 -系统设计和组件交互
📁 项目结构
tool-gating-mcp/
├── src/
│ └── tool_gating_mcp/
│ ├── __init__.py
│ ├── main.py # FastAPI application
│ ├── api/
│ │ ├── models.py # Pydantic models
│ │ ├── tools.py # Tool management endpoints
│ │ └── mcp.py # MCP server endpoints
│ ├── models/
│ │ └── tool.py # Domain models
│ └── services/
│ ├── discovery.py # Semantic search
│ ├── gating.py # Tool selection logic
│ └── repository.py # Tool storage
├── tests/
│ ├── test_*.py # Test files
│ └── test_integration.py # Integration tests
├── demo.py # Interactive demo
├── test_server.py # Manual testing script
└── pyproject.toml # Project configuration🔌 与MCP服务器集成
从MCP服务器注册工具
# 1. Clear existing demo tools
DELETE /api/tools/clear
# 2. Register tools from your MCP servers
POST /api/tools/register
{
"id": "exa_research_paper_search",
"name": "research_paper_search",
"description": "Search across 100M+ research papers with full text access",
"tags": ["search", "research", "academic"],
"estimated_tokens": 250,
"server": "exa",
"parameters": {
"type": "object",
"properties": {
"query": {"type": "string"},
"numResults": {"type": "number", "default": 5}
},
"required": ["query"]
}
}与LLM编排一起使用
- LLM接收用户查询:“查找有关量子计算的最新论文”
- 编排器查询工具门控:
POST /api/tools/discover
{"query": "find research papers", "limit": 3}- 系统返回相关工具:只有研究工具,没有文件编辑器
- 编排器配置工具:
POST /api/tools/provision
{"tool_ids": ["exa_research_paper_search"], "max_tokens": 500}- LLM直接与MCP服务器执行:使用配置的工具定义
人工智能辅助服务器注册
AI助手可以自动添加新的MCP服务器:
# User: "Add this Slack MCP server to tool gating"
# AI: Connects to server, discovers tools, and registers everything
POST /api/mcp/ai/register-server
{
"server_name": "slack",
"config": {
"command": "npx",
"args": ["@slack/mcp-server"],
"env": {"SLACK_TOKEN": "xoxb-..."}
},
"tools": [
// AI provides all discovered tools with metadata
]
}
# Result: Slack server + all tools registered and ready for use🧑💻 发展
代码质量
# Format code
black .
# Run linter
ruff check . --fix
# Type checking
mypy .
# Run all checks
black . && ruff check . --fix && mypy . && pytest添加新工具
工具可以添加到存储库中 services/repository.py:
Tool(
id="my-tool",
name="My Tool",
description="Description for semantic search",
tags=["category", "function"],
estimated_tokens=100,
parameters={
"type": "object",
"properties": {...},
"required": [...]
}
)🤝 贡献
- 分叉存储库
- 创建要素分支(
git checkout -b feature/amazing-feature) - 进行更改并添加测试
- 进行质量检查(
black,ruff,mypy,pytest) - 提交您的更改(
git commit -m 'Add amazing feature') - 推到分支(
git push origin feature/amazing-feature) - 打开拉取请求
📄 许可证
此项目根据MIT许可证获得许可-有关详细信息,请参阅许可证文件。
🙏 致谢
- 内置于 快速API
- 语义搜索由 句子转换
- MCP协议集成 fastapi mcp
- 演示UI使用 富有的
