chandanCoding/mcp-tool-gateway
GitHub: chandanCoding/mcp-tool-gateway
面向 Agentic AI 的安全 MCP 工具执行网关,提供 JWT 身份验证、scope 授权、限流和 prompt-injection 检测,从 OpenAPI 自动接入下游 API。
Stars: 0 | Forks: 0
# 🔐 mcp-tool-gateway
一个**面向 Agentic AI 的安全工具执行平面** —— 一个 MCP 风格的工具服务器前端,
由 gateway 负责**身份验证(JWT + scopes)、配额控制(token-bucket rate
limiting)和安全防护(prompt-injection 检测)**,从 **OpenAPI** 接入下游 API,
并写入结构化的 **audit log**。纯 Python 编写,零依赖。
## 请求生命周期
```
agent tool call ─▶ ┌──────────────────────── SecureToolGateway ───────────────────────┐
(+ JWT) │ 1 authenticate (HS256 verify, exp) │
│ 2 rate limit (per-principal token bucket) │
│ 3 authorize (tool.required_scope ∈ principal.scopes) │
│ 4 inspect IN (prompt-injection / exfiltration / cmd-injection) │
│ 5 execute (MCP server: tools/list · tools/call) │
│ 6 inspect OUT + audit log │
└──────────────────────────────────────────────────────────────────┘
```
## 核心组件
| 模块 | 职责 |
|--------|----------------|
| `jwt_auth` | HS256 JWT 编码/验证(从零实现),`exp` 检查,包含 scope 辅助函数的 `Principal` |
| `rate_limit` | `TokenBucket` + 基于 principal 的 `RateLimiter` |
| `inspection` | 基于规则的 `Inspector`(instruction-override、exfiltration、command-injection、role-spoofing),支持基于严重程度的拦截 |
| `mcp` | 通过 JSON-RPC 实现 `tools/list` 和 `tools/call` 的 `MCPServer` |
| `openapi` | `tools_from_openapi` —— 将下游 API 操作自动注册为 MCP 工具 |
| `audit` | 只追加(Append-only)的结构化 `AuditLog` |
| `gateway` | `SecureToolGateway`,串联起 auth → quota → authz → inspection → execute → audit 流程 |
## 快速开始
```
python examples/run_gateway.py
```
输出演示了:一次授权调用、一次因 **missing-scope** 导致的拒绝、一次被拦截的
**prompt-injection** payload、一个 **invalid token**,以及生成的完整 audit 记录。
```
from mcp_gateway import MCPServer, MCPTool, SecureToolGateway, encode
server = MCPServer()
server.register(MCPTool("get_trade_status", "...", schema,
handler=lambda trade_id: "ACK", required_scope="trades:read"))
gw = SecureToolGateway(server=server, secret="...")
token = encode({"sub": "agent-1", "scopes": ["trades:read"]}, "...")
gw.handle({"id": 1, "method": "tools/call",
"params": {"name": "get_trade_status", "arguments": {"trade_id": "T-1"}}}, token)
```
## 安全特性
- **默认拒绝(Fail-closed)**:缺少 scope、签名错误、token 过期或检测到高严重级别的
结果,都会在工具执行前被拒绝。
- **纵深防御(Defense in depth)**:对输入*和*输出均进行检测;对所有操作进行审计。
- **最小权限(Least privilege)**:基于工具粒度的 `required_scope`,基于 principal 粒度的配额。
## 测试
```
pip install pytest && pytest -q
```
覆盖了 JWT 往返测试 + 篡改检测、scope 强制校验、injection 拦截、
rate limiting 以及 inspector 严重程度判定。
## 技术
Python 3.10+ · 仅依赖标准库(可选:`pytest`)
标签:AI网关, DLL 劫持, JWT认证, MCP, Python, 大语言模型, 无后门, 逆向工具, 限流