API网关服务

mcp-gateway是一个独立的MCP兼容API网关,为AI平台提供9种工具(如语义搜索、代码分析、LLM完成等)的访问接口,支持VS Code/Copilot、外部LLM(Claude、GPT、Gemini)和外部租户代理。

  • by kevin-toles
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 kevin-toles/mcp-gateway

使用说明

mcp网关

AI平台的独立MCP-兼容API网关。

将9个平台工具(语义搜索、代码分析、LLM完成、代理执行等)暴露给VS code/Copilot、外部LLM(Claude、GPT、Gemini),并在第3阶段暴露给外部租户代理——所有这些都是通过模型上下文协议(MCP)实现的。

快速开始

# Create virtual environment
python3 -m venv .venv
source .venv/bin/activate

# Install with dev dependencies
pip install -e ".[dev]"

# Run unit tests (no services required)
pytest tests/unit/

# Run integration tests (requires live services + Redis)
INTEGRATION=1 pytest tests/integration/ --no-cov

# Start the gateway
uvicorn src.main:app --host 0.0.0.0 --port 8087

建筑

External Client (VS Code / Claude / GPT)
    │
    ▼
mcp-gateway :8087 — FastMCP SSE/HTTP
    │
    ├── RequestID middleware (UUID v4)
    ├── OIDCAuthMiddleware (JWT RS256/ES256)
    ├── RateLimitMiddleware (Redis token bucket)
    ├── ToolRegistry (YAML-driven, 9 tools)
    ├── Input Validation (Pydantic per tool)
    ├── Injection Prevention (path traversal + Cypher)
    ├── ToolDispatcher (HTTP POST to backends, connection pooling)
    ├── OutputSanitizer (Phase 1: passthrough)
    └── AuditMiddleware (JSONL provenance + :8084 forwarding)
    │
    ▼
Backend Services
    ├── llm-gateway         :8080
    ├── semantic-search      :8081
    ├── ai-agents            :8082
    ├── code-orchestrator    :8083
    └── audit-service        :8084

MCP协议

网关实现 模型上下文协议 通过SSE/HTTP传输 /mcp.

支持的操作:

  • tools/list --返回所有9个已注册的工具及其模式
  • tools/call --验证输入→ 派遣→ 消毒→ 返回结果

从客户端连接:

from fastmcp import Client

async with Client("http://localhost:8087/mcp") as client:
    tools = await client.list_tools()
    result = await client.call_tool("semantic_search", {
        "query": "error handling patterns",
        "collection": "code",
        "top_k": 5,
    })

工具

工具 后端 层 描述
semantic_search 语义搜索:8081 青铜 跨代码、文档、教科书的语义相似性搜索
hybrid_search 语义搜索:8081 青铜色 语义+关键字组合搜索
code_analyze 代码编排器:8083 silver 代码复杂性、依赖性和质量分析
code_pattern_audit 代码编排器:8083 银色 使用双网检测检测反模式
graph_query ai代理:8082 gold Neo4j Cypher查询(只读,注入保护)
llm_complete llm网关:8080 黄金 llm完成,分层回退
run_agent_function ai代理:8082 gold 执行单用途代理功能
run_discussion ai代理商:8082 企业 多LLM厨房大队洽谈
agent_execute ai代理:8082 企业 执行自主代理任务

工具定义从以下位置加载 config/tools.yaml.

配置

所有设置都使用环境变量 MCP_GATEWAY_ 前缀:

变量 默认值 描述
MCP_GATEWAY_HOST 0.0.0.0 绑定地址
MCP_GATEWAY_PORT 8087 绑定端口
MCP_GATEWAY_SERVICE_NAME mcp-gateway 服务标识
MCP_GATEWAY_SERVICE_VERSION 0.1.0 服务版本
MCP_GATEWAY_LLM_GATEWAY_URL http://localhost:8080 LLM网关后端
MCP_GATEWAY_UNIFIED_SEARCH_URL http://localhost:8081 统一搜索后端(Python)
MCP_GATEWAY_UNIFIED_SEARCH_RS_URL http://localhost:8089 统一搜索后端(Rust)
MCP_GATEWAY_AI_AGENTS_URL http://localhost:8082 AI代理后端
MCP_GATEWAY_CODE_ORCHESTRATOR_URL http://localhost:8083 代码编排器后端
MCP_GATEWAY_AUTH_ENABLED false 启用JWT身份验证
MCP_GATEWAY_OIDC_JWKS_URL (空) JWT验证的JWKS端点
MCP_GATEWAY_OIDC_ISSUER (空) 预期JWT发行人
MCP_GATEWAY_OIDC_AUDIENCE ai-platform-tools 预计JWT观众
MCP_GATEWAY_TLS_ENABLED false 启用TLS 1.3
MCP_GATEWAY_TLS_CERT_PATH (空) TLS证书的路径
MCP_GATEWAY_TLS_KEY_PATH (空) TLS私钥的路径
MCP_GATEWAY_REDIS_URL redis://localhost:6379 Redis用于速率限制
MCP_GATEWAY_RATE_LIMIT_RPM 100 每位租户每分钟的请求数
MCP_GATEWAY_AUDIT_LOG_PATH logs/audit.jsonl 本地审核日志路径

安全

认证

  • 通过OIDC进行JWT验证(仅RS256/ES256,无对称算法)
  • 所需索赔: exp, iss, aud, sub, tier
  • 开发模式旁路 AUTH_ENABLED=false

速率限制

  • 每租户Redis令牌桶(INCR+EXPIRE)
  • 可配置RPM X-RateLimit-* 标头
  • Redis不可用时性能下降

输入验证

  • 每个工具的Pydantic模型都有字段验证器
  • OWASP路径遍历保护(CWE-22):双解码、空字节、符号链接检测
  • 防止密码注入:关键字拦截、管理员命令过滤

审计

  • 使用SHA-256输入哈希记录到JSONL的每个非健康请求
  • 转发到8084上的集中审计服务
  • 审计服务不可用时的JSONL回退

测试

# Unit tests (493 tests, 98.64% coverage)
pytest tests/unit/

# Integration tests (requires live services + Redis)
INTEGRATION=1 pytest tests/integration/ --no-cov

# Full suite
INTEGRATION=1 pytest --no-cov

测试结构

tests/
├── unit/                           # 493 tests, no external dependencies
│   ├── core/                       # config, errors
│   ├── models/                     # schemas, budget
│   ├── security/                   # authn, rate_limiter, audit, validators
│   ├── test_main.py               # app startup, middleware chain
│   ├── test_tool_dispatcher.py    # dispatch routing, error handling
│   ├── test_tool_registry.py      # YAML loading, validation
│   └── test_server.py             # MCP server creation
├── integration/                    # 112 tests, requires live services
│   ├── test_tool_dispatch_e2e.py  # 9 tools → live backends
│   ├── test_security_suite.py     # OWASP, JWT, rate limiting, audit
│   ├── test_performance.py        # latency benchmarks
│   └── test_mcp_protocol.py       # FastMCP protocol verification
└── conftest.py

api参考

GET /health

返回服务运行状况。

{
  "service": "mcp-gateway",
  "version": "0.1.0",
  "status": "healthy",
  "uptime_seconds": 123.45
}

GET /mcp/sse (MCP SSE运输)

MCP协议通信的服务器发送事件端点。

发展

# Lint
ruff check src/ tests/

# Type check
mypy src/

# Format
ruff format src/ tests/

许可证

专有——AI平台内部服务。