production-mcp-server
production-mcp-server
엔터프라이즈 환경에서 AI 에이전트에게 도구를 안전하게 노출하는 방법을 보여주는 프로덕션 등급의 MCP(Model Context Protocol) 서버입니다.
대부분의 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계층 구성
계층 | 기능 | 중요성 |
도구 레지스트리 | 모든 도구에 대해 이름, 설명, 필수 권한, 위험 수준을 저장합니다 | 단일 진실 공급원(Single source of truth) — 등록되지 않은 도구는 실행될 수 없습니다 |
권한 강제 | 실행 전에 호출자 권한이 도구 요구 사항을 충족하는지 확인합니다 | 에이전트는 명시적으로 승인된 도구만 호출할 수 있습니다 |
영향 범위 가드 | HIGH 위험 작업에는 | 에이전트가 파괴적인 작업을 실수로 트리거할 수 없습니다 |
입력 검증 | 경로 탐색(path traversal), 파괴적 SQL 및 기타 공격 패턴을 차단합니다 | 심층 방어(Defense-in-depth) — 핸들러가 실행되기 전에 검증합니다 |
감사 추적 | 모든 호출에 대한 변경 불가능한 추가 전용 로그 | 규정 준수와 디버깅을 위한 완전한 감사 가능성 |
문제점
AI 에이전트가 도구 접근 권한을 얻으면 다음 세 가지 실패 모드가 즉시 나타납니다:
제한 없는 접근 — 에이전트가 호출해서는 안 되는 도구를 호출하여 의도하지 않은 부작용을 유발합니다
감사 추적 부재 — 문제가 발생했을 때 에이전트가 무엇을 했는지 재구성할 수 없습니다
조용한 실패(Silent failures) — 권한 오류가 무시되어 디버깅이 불가능해집니다
이 서버는 이 세 가지를 모두 해결합니다.
아키텍처
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. 영향 범위 제어
HIGH 위험 도구에는 명시적 확인 플래그가 필요합니다 — 에이전트가 파괴적인 작업을 실수로 트리거할 수 없습니다:
# 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.serverMCP 호환 클라이언트(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를 실제 ID 공급자로 교체합니다:
# 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 에이전트 인프라 포트폴리오의 한 부분입니다:
Repo | 내용 |
전체 시스템 설계: 프로덕션 배포에서 수동 온콜 트라이지의 95%를 제거한 이러한 구성 요소들이 어떻게 함께 맞물리는지 보여줍니다 | |
← 현재 위치: MCP 거버넌스 계층 | |
에이전트 품질이 어떻게 측정되고, 출시 전에 회귀가 어떻게 발견되는지 보여줍니다 |
This server cannot be deployed
Maintenance
Related MCP Connectors
- gatewayOAuthai.sealgate
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.
Find, vet, and run MCP tools through a secure audited gateway with prompt-injection risk scoring
Governed app access for AI agents: 1,000+ apps & 12,000+ tools via Code Mode MCP.
Related MCP Servers
AlicenseNot gradedqualityBmaintenanceEnables AI agents to securely call MCP tools with risk scoring, checkpoints, rollback, and approval workflows.17 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