production-mcp-server
production-mcp-server
一个生产级 MCP(模型上下文协议)服务器,演示如何在企业环境中安全地向 AI 代理暴露工具。
大多数 MCP 示例展示的是如何 连接 工具与代理。本仓库展示的是如何 安全地大规模 实现这一目标——通过权限强制、行为护栏、爆炸半径控制,以及每次调用的结构化审计追踪。
问题 → 解决方案 → 影响
问题 | AI 代理需要工具访问权限才能发挥作用——但不受约束的工具访问会导致生产事故。团队要么将代理完全锁定(无用),要么给予完全访问权限(危险)。 |
解决方案 | 一个受治理的 MCP 网关层,位于每个代理和每个工具之间:每次调用都经过权限检查、爆炸半径控制,并完全审计。 |
影响 | 代理凭借企业级授权在生产环境中安全运行。安全团队可以审计每一个操作。开发者无需担心副作用即可发布代理功能。 |
Related MCP server: evav-gateway
系统设计
graph TD
A[🤖 AI Agent<br/>Claude / Any LLM] -->|MCP Protocol| B
subgraph MCP Gateway — Governed Tool Access
B[Request Received] --> C{Layer 1<br/>Permission Check}
C -->|Missing permissions| D[❌ Denied<br/>Audit logged]
C -->|Permitted| E{Layer 2<br/>Blast-Radius Guard}
E -->|HIGH risk, no confirmation| F[❌ Blocked<br/>Audit logged]
E -->|Confirmed or LOW/MED| G{Layer 3<br/>Input Validation}
G -->|Path traversal / SQL injection| H[❌ Blocked<br/>Audit logged]
G -->|Clean inputs| I[✅ Tool Handler Executes]
end
I --> J[(Tool Registry<br/>name · permissions · risk_level)]
I --> K[📋 Audit Trail<br/>every call · permitted or denied]
subgraph Tools
I --> L[📊 Read Metrics]
I --> M[🔍 Query Database]
I --> N[🚀 Trigger Rollback<br/>HIGH RISK — requires confirmed=True]
end分层详解
层级 | 功能 | 重要性 |
工具注册表 | 存储每个工具的名称、描述、所需权限和风险等级 | 单一事实来源——未经注册的工具无法运行 |
权限强制 | 在执行前检查调用者权限是否符合工具要求 | 代理只能调用其被明确授权的工具 |
爆炸半径保护 | 对高风险操作要求 | 代理无法意外触发破坏性操作 |
输入验证 | 阻止路径遍历、破坏性 SQL 及其他攻击模式 | 纵深防御——在任何处理程序运行之前进行验证 |
审计追踪 | 每次调用的不可变、仅追加日志 | 为合规性和调试提供完整可审计性 |
问题
当 AI 代理获得工具访问权限时,三种故障模式会立即显现:
不受限制的访问——代理调用本不该调用的工具,造成意外副作用
没有审计追踪——出问题时无法重建代理的操作
静默失败——权限错误被吞掉,导致调试无法进行
本服务器解决了以上所有三个问题。
架构
Agent (Claude / any LLM)
│
▼ MCP Protocol
┌─────────────────────────────┐
│ MCP Server │
│ ┌──────────────────────┐ │
│ │ Guardrail Layer │ │ ← permission check → blast-radius guard → arg validation
│ └──────────┬───────────┘ │
│ │ │
│ ┌──────────▼───────────┐ │
│ │ Tool Registry │ │ ← name, description, required_permissions, risk_level
│ └──────────┬───────────┘ │
│ │ │
│ ┌──────────▼───────────┐ │
│ │ Tool Handlers │ │ ← plain Python functions, no security logic here
│ └──────────────────────┘ │
│ │ │
│ ┌──────────▼───────────┐ │
│ │ Audit Trail │ │ ← every invocation logged, permitted or denied
│ └──────────────────────┘ │
└─────────────────────────────┘关键模式
1. 受治理的工具访问
每个工具都通过明确的权限要求进行注册:
registry.register(ToolDefinition(
name="trigger_rollback",
description="Initiate a deployment rollback.",
handler=trigger_rollback,
required_permissions={"deployments:write", "deployments:rollback"},
risk_level=RiskLevel.HIGH,
requires_confirmation=True, # blast-radius guard
))2. 权限强制
护栏层在任何处理程序运行之前检查权限:
# Agent tries to trigger rollback but lacks deployments:write
guardrails.invoke(
tool_name="trigger_rollback",
arguments={"deployment_id": "d-123", "reason": "high error rate"},
caller_id="monitoring-agent",
caller_permissions={"deployments:read"}, # missing write permission
)
# → PermissionDeniedError: Caller 'monitoring-agent' lacks permissions
# {'deployments:write', 'deployments:rollback'} for tool 'trigger_rollback'3. 爆炸半径控制
高风险工具需要明确的确认标志——代理无法意外触发破坏性操作:
# Without confirmation — blocked
guardrails.invoke("trigger_rollback", {...}, confirmed=False)
# → GuardrailViolationError: HIGH risk tool requires confirmed=True
# With confirmation — permitted
guardrails.invoke("trigger_rollback", {...}, confirmed=True)4. 输入验证
参数级检查在任何工具处理程序之前运行:
# Path traversal — blocked automatically
guardrails.invoke("read_file", {"path": "../../etc/passwd"}, ...)
# → GuardrailViolationError: Path traversal detected
# Destructive SQL — blocked automatically
guardrails.invoke("query", {"query": "DROP TABLE users"}, ...)
# → GuardrailViolationError: Destructive SQL pattern detected5. 结构化审计追踪
每次调用——无论允许还是拒绝——都会被记录:
# After some invocations
events = audit.get_events()
print(events[0].to_json())
# {
# "tool_name": "read_deployment_status",
# "caller_id": "oncall-agent-v1",
# "arguments": {"deployment_id": "d-abc"},
# "result": "{'status': 'healthy', ...}",
# "permitted": true,
# "timestamp": "2026-08-26T14:30:00+00:00",
# "duration_ms": 12.4
# }
print(f"Denied requests: {audit.denied_count()}")项目结构
production-mcp-server/
├── src/
│ ├── server.py # MCP server entry point — tool registration + FastMCP wiring
│ ├── registry.py # Tool registry — metadata, permissions, risk classification
│ ├── guardrails.py # Guardrail layer — 3-layer enforcement on every invocation
│ ├── audit.py # Structured audit trail — append-only event log
│ └── tools/
│ └── example_tools.py # Example handlers — swap with your real data sources
├── tests/
│ ├── test_guardrails.py # Permission enforcement, blast-radius, input validation
│ └── test_registry.py # Tool registration and lookup
├── examples/
│ └── basic_usage.py # Standalone usage without the MCP server
└── pyproject.toml安装
pip install -e ".[dev]"运行服务器
python -m src.server将任何兼容 MCP 的客户端(如 Claude Desktop、Claude Code 等)连接到服务器。
运行测试
pytest tests/ -v扩展
添加新工具
在
src/tools/中编写处理函数:
def read_config(config_key: str) -> str:
return os.environ.get(config_key, "not_found")使用权限和风险等级注册它:
registry.register(ToolDefinition(
name="read_config",
description="Read a configuration value by key.",
handler=read_config,
required_permissions={"config:read"},
risk_level=RiskLevel.LOW,
))通过 FastMCP 暴露:
@mcp.tool()
def config(config_key: str) -> str:
return guardrails.invoke("read_config", {"config_key": config_key}, ...)护栏层和审计层会自动生效——无需修改。
集成你的认证层
将 server.py 中的静态 CALLER_ID / CALLER_PERMISSIONS 替换为你的真实身份提供方:
# Example: derive permissions from an OAuth token in the MCP session context
def get_caller_context(session) -> tuple[str, set[str]]:
token = session.headers.get("Authorization")
claims = verify_jwt(token)
return claims["sub"], set(claims["permissions"])为什么这很重要
在生产环境中拥有工具访问权限的 AI 代理需要与任何特权服务相同的控制:最小权限授权、输入验证、爆炸半径限制和完整的审计追踪。本仓库是使用 MCP 协议实现这些模式的参考示例。
许可证
MIT
作为代理基础设施栈的一部分
本仓库是生产级 AI 代理基础设施组合中的一部分:
仓库 | 说明 |
完整系统设计:这些组件如何在生产部署中协同工作,消除了 95% 的手动值班分流 | |
← 你在这里:MCP 治理层 | |
如何衡量代理质量,并在发布前捕获回归问题 |
This server cannot be deployed
Maintenance
Related MCP Connectors
MCP gateway with runtime security policy, tool-call-level control, and audit of agent actions.
Zero-secret MCP gateway for AI agents: risk-scored, audited calls with human-in-the-loop approval.
MCP gateway: one connection for your AI apps, with tool policies, PII redaction and audit logs.
Find, vet, and run MCP tools through a secure audited gateway with prompt-injection risk scoring
Related MCP Servers
AlicenseNot gradedqualityCmaintenanceEnables AI agents to securely call MCP tools with risk scoring, checkpoints, rollback, and approval workflows.10 npmMIT
evav-gatewayofficial
AlicenseNot gradedqualityDmaintenanceGoverned MCP gateway that lets AI agents call tools with policy enforcement, prompt-injection screening, a kill-switch, and tamper-evident signed audit logs.Apache 2.0- AlicenseNot gradedqualityBmaintenanceEnables agents to invoke declared API capabilities through a governed MCP surface where each call is risk-tiered — low-risk calls execute immediately, medium-risk writes queue for human approval, and high-risk actions are withheld from the tool list entirely. Every call, decision and denial is recorded in an audit trail, and responses carrying third-party text are scanned for prompt-injection signals before an agent can read them.2MIT
- AlicenseNot gradedqualityBmaintenanceEnables AI agents to securely reach enterprise tools and other agents through a governed gateway with pinned tool definitions, delegated authorization, content inspection, human approval, and signed audit trails.Apache 2.0