correctover-mcp-gateway
v1.1.7
Published
MCP security gateway for any MCP client — Claude Code, Cursor, Cline, Windsurf and more. CCS runtime verification at the tool-call boundary: tools/list baseline, schema consistency, declaration drift, response-stamp, field-order hash. Zero runtime depende
Maintainers
Readme
correctover-mcp-gateway
Production-grade MCP Security Gateway — CCS runtime verification, bidirectional request/response scanning, Ed25519-signed receipts, policy engine, rate limiting, circuit breaker, protocol-metadata verification, Prometheus metrics, structured logging, zero runtime dependencies.
- License: Apache-2.0 OR LicenseRef-Commercial (dual: community core + commercial premium features)
- Node.js: >= 18.0.0
- Runtime dependencies: 0
Why
Model Context Protocol (MCP) lets AI agents call external tools. Every tools/call is a potential injection, exfiltration, or policy violation vector. Most MCP security proxies only inspect inbound requests — they don't scan what the tool returns to the model.
This gateway enforces security on both sides:
- Inbound scanning — blocks shell injection, SSRF, credential exfiltration, path traversal, SQLi, command execution, and prompt injection before the request reaches the upstream MCP server.
- Outbound scanning — blocks secrets, PII, and sensitive filesystem content in tool responses before they reach the model.
- Protocol-metadata verification — verifies that a server's declared
tools/listschema matches its actual behavior (the "lying MCP server" defense).
Every verdict produces a tamper-evident CCS receipt (Ed25519-signed), aligned with draft-correctover-ccs-04.
Quick Start
Install
npm install correctover-mcp-gatewayRun as a standalone gateway (HTTP proxy mode)
npx mcp-gateway \
--http --target http://your-mcp-server:8000/sse \
--port 3000 \
--api-key your-secret-key \
--policy ./policy.json \
--sign-receipts \
--enable-metricsPoint your MCP client at the gateway's /mcp endpoint. All traffic is scanned, policy-enforced, and receipt-logged.
Run as stdio sidecar
npx mcp-gateway --stdio -- python server.py --sign-receiptsUse as an in-process SDK
import { MCPGateway } from 'correctover-mcp-gateway';
const gateway = new MCPGateway({
mode: 'http',
target: { url: 'http://your-mcp-server:8000/sse' },
policy: {
default_tool_action: 'allow',
tools: {},
callers: {},
scan_output: true,
sign_receipts: true,
},
api_keys: { 'sk-live-xxx': 'app-prod' },
enable_metrics: true,
});
await gateway.start();🇨🇳 免费网关之外 · 支付宝 SkillPay
社区版网关可免费部署使用。如果你需要人工深度审计或正式合规凭证,可以在支付宝 SkillPay 货架获取:
- 货架首页:https://skillpay.alipay.com/public/correctover
- 也可以在支持「支付宝 AI 付」的智能体对话里直接输入对应服务名唤起购买:
- MCP配置安全体检:
请通过 SkillPay 购买并安装 Skill「MCP配置安全体检」 - CCS收据批量审计:
请通过 SkillPay 购买并安装 Skill「CCS收据批量审计」 - CCS收据验签:
请通过 SkillPay 购买并安装 Skill「CCS收据验签」
- MCP配置安全体检:
Beyond the free gateway: human-led deep audits and compliance evidence are available on the Alipay SkillPay shelf — open the link above, or type the service name (e.g. MCP配置安全体检) in an agent with Alipay AI Pay enabled.
Architecture
Client ──▶ Gateway ──▶ Upstream MCP Server
Gateway pipeline:
1. Auth (API key / Bearer token)
2. Rate limit (token bucket)
3. Circuit breaker (upstream health)
4. Policy engine (ACL + arg rules)
5. Input verification (8 rules)
6. Protocol pre-check (baseline/schema)
7. Proxy to upstream
8. Output scan + protocol post-check
9. Ed25519 receipt signing
10. Metrics + structured logging
Side outputs: /metrics, /admin/*, receipts/*.jsonlSecurity Rules (16 total)
Input Rules (8 — request direction)
| ID | Rule | Severity | Blocks | |----|------|----------|--------| | SEC-001 | Shell Injection | block | Shell metacharacter chains and command substitution | | SEC-002 | SSRF / Internal IP | block | Link-local, loopback, and private ranges | | SEC-003 | Cloud Credential Exfiltration | block | Cloud secret values in arguments | | SEC-004 | Path Traversal | block | Parent-directory traversal sequences | | SEC-005 | SQL Injection | critical | Common SQLi patterns in inputs | | SEC-006 | Command Execution | block | Eval/exec/system/spawn patterns | | SEC-007 | Prompt Injection — Role Override | critical | Attempts to override system/developer instructions | | SEC-008 | Prompt Injection — Jailbreak | critical | DAN-style jailbreak patterns |
Output Rules (8 — response direction)
| ID | Rule | Severity | Blocks | |----|------|----------|--------| | OUT-001 | AWS Key Leak | critical | AWS access key ID patterns in tool output | | OUT-002 | Private Key Leak | block | RSA/OpenSSH private key material in output | | OUT-003 | GitHub Token Leak | critical | GitHub token patterns | | OUT-004 | Generic API Key Leak | critical | High-entropy API key patterns | | OUT-005 | PII — Email Address | warning | Email addresses in response content | | OUT-006 | PII — SSN / ID Card | critical | US SSN and China Resident ID patterns | | OUT-007 | PII — Credit Card | critical | Major credit card numbers (Luhn-validated) | | OUT-008 | Password File Content | block | System password file content pattern |
Protocol-Metadata Verification Layer
The gateway also verifies the declared contract of the upstream server:
| Check | Behavior |
|-------|----------|
| tools/list baseline | Captures a trust baseline of declared tools and schemas |
| Undeclared tool invocation | Blocked before upstream execution |
| Input schema mismatch | Blocked before upstream execution |
| Missing baseline | Blocked when require_input_schema is enabled (default) |
| Output schema mismatch | Blocked after response is received |
| Declaration drift | Warns on first changes, blocks after repeated unverified drift |
| Response stamp | Requires a valid server-signed response stamp when enabled |
| Field-order hash | Warns or blocks when output field order changes |
Fail-Closed Design
术语说明:MRTR 是 Multi Round-Trip Requests(多轮交互请求),不是 stamp/receipt。本包统一使用 “response stamp” 表示服务端签名的响应戳。
When verification fails, the gateway returns a structured JSON-RPC error and never proxies the request. When output scanning fails, the response is blocked and the model receives an error instead of leaked data.
Empty or absent carrier fields return INDETERMINATE disposition (aligned with the CCS absence principle) rather than a false ALLOW.
Configuration
CLI Options
| Flag | Env | Default | Description |
|------|-----|---------|-------------|
| --http | — | false | Use Streamable HTTP transport |
| --stdio | — | false | Use stdio transport |
| --target <url> | MCP_GATEWAY_UPSTREAM | — | Upstream MCP server URL (HTTP mode) |
| --port <n> | MCP_GATEWAY_PORT | 3100 | HTTP listen port |
| --host <addr> | MCP_GATEWAY_HOST | loopback interface | Listen address |
| --api-key <key> | MCP_GATEWAY_API_KEY | — | Client API key (Bearer or X-API-Key) |
| --admin-key <key> | MCP_GATEWAY_ADMIN_KEY | — | Admin API key |
| --policy <path> | MCP_GATEWAY_POLICY | — | Policy JSON file path |
| --sign-receipts | MCP_GATEWAY_SIGN | false | Enable Ed25519 receipt signing |
| --receipt-dir <dir> | MCP_GATEWAY_RECEIPTS_DIR | ./receipts | Receipt storage directory |
| --enable-metrics | MCP_GATEWAY_METRICS | false | Enable Prometheus metrics endpoint |
| --log-level <level> | MCP_GATEWAY_LOG_LEVEL | info | debug/info/warn/error |
| --log-format <fmt> | MCP_GATEWAY_LOG_FORMAT | text | json or text |
| --rate-limit <n> | MCP_GATEWAY_RATE_LIMIT | — | Global requests per minute |
| --max-concurrency <n> | MCP_GATEWAY_MAX_CONCURRENCY | — | Max simultaneous upstream calls |
| --max-body <bytes> | MCP_GATEWAY_MAX_PAYLOAD | 1048576 | Max request body size |
| --timeout <ms> | — | 120000 | Upstream timeout |
| --circuit-threshold <n> | — | 5 | Failures before opening circuit |
| --circuit-reset <ms> | — | 30000 | Ms before half-open probe |
| --retention <days> | — | 90 | Receipt retention in days |
| --no-verify | — | — | Disable CCS verification |
| --no-output-scan | — | — | Disable output scanning |
| --no-protocol-verify | — | — | Disable protocol-metadata verification |
| --require-response-stamp | MCP_GATEWAY_REQUIRE_RESPONSE_STAMP | false | Require signed server response stamps |
| --server-public-key <file> | — | — | Server public key PEM for response stamps |
| --response-key-id <id> | MCP_GATEWAY_RESPONSE_KEY_ID | — | Expected response stamp keyId |
| --field-order <mode> | — | warn | warn or block for field-order changes |
Policy File
The policy file uses the same schema as PolicyConfig:
{
"default_tool_action": "allow",
"tools": {
"search": {
"action": "allow",
"rate_limit_rpm": 60,
"allowed_args": ["query"],
"denied_args": ["password"]
},
"execute_command": {
"action": "deny"
}
},
"callers": {
"trusted-agent": {
"id": "trusted-agent",
"allowed_tools": ["search", "read_file"],
"rate_limit_rpm": 120,
"max_concurrency": 10
}
},
"global_rate_limit_rpm": 1000,
"global_max_concurrency": 50,
"max_body_size_bytes": 1048576,
"scan_output": true,
"sign_receipts": false,
"receipt_retention_days": 90
}Policy changes are hot-reloaded via fs.watch — no restart required.
API Key Authentication
When --api-key is set, all /mcp endpoints require either:
Authorization: Bearer your-secret-key
# or
X-API-Key: your-secret-keyAdmin endpoints (/admin/*) require the separate --admin-key.
Commercial License Gate
Protocol-metadata verification can be sold as a premium capability while keeping the base CCS gateway usable in community mode.
mcp-gateway --http --target http://your-mcp-server:8000 \
--require-license \
--license-key "v1.<payload>.<signature>" \
--license-public-key ./license-public.pem- When
--require-licenseis enabled and the license is valid, protocol-metadata verification stays on. - When the license is missing/expired/invalid, the gateway logs the reason and runs in community mode (scanner-only); base CCS scanning remains available.
- License format:
v1.<base64url(payload)>.<base64url(RSA-SHA256 signature)>.
The license issuance side is available for Correctover's own license server via issueLicense() / generateLicenseKeyPair() (exported from the SDK).
HTTP Endpoints
| Method | Path | Auth | Description |
|--------|------|------|-------------|
| POST | /mcp | API key | MCP JSON-RPC endpoint (Streamable HTTP) |
| GET | /mcp | API key | SSE stream for server-initiated messages |
| GET | /health | None | Health check |
| GET | /metrics | Admin key | Prometheus text exposition format |
| GET | /admin/stats | Admin key | Gateway statistics snapshot |
| GET | /admin/policy | Admin key | Current policy configuration |
| POST | /admin/policy/reload | Admin key | Force policy reload from disk |
| POST | /admin/circuit/reset | Admin key | Manually reset circuit breaker |
| GET | /admin/receipts | Admin key | List recent receipts |
JSON-RPC Error Codes
| Code | Constant | Meaning |
|------|----------|---------|
| -32001 | CCS_BLOCKED | Input verification failed — request blocked |
| -32002 | CCS_INDETERMINATE | Verification inconclusive (carrier absence) |
| -32003 | CCS_OUTPUT_BLOCKED | Response output scan blocked |
| -32004 | RATE_LIMITED | Rate limit exceeded |
| -32005 | CIRCUIT_OPEN | Circuit breaker is open |
| -32006 | AUTH_REQUIRED | Missing or invalid API key |
| -32007 | TOOL_DENIED | Tool denied by policy |
| -32008 | PAYLOAD_TOO_LARGE | Request body exceeds limit |
Receipts
Every verified call produces a CCS receipt in JSONL format under --receipt-dir. The signature covers canonicalized JSON (sorted keys, no whitespace) using Ed25519. The public key is stored under the receipt key directory.
Performance
Measured on Node.js v22.23.2, 10,000 samples, built-in verifier (gateway mode):
| Configuration | P50 | P95 | P99 | Throughput | |--------------|-----|-----|-----|------------| | No signing | 2.8 μs | 5.7 μs | 14.4 μs | ~159K calls/sec | | Ed25519 signing | 2.3 μs | — | 9.2 μs | ~340K calls/sec |
Microsecond overhead means the gateway adds negligible latency to MCP call chains.
Docker
docker build -f examples/Dockerfile -t mcp-gateway .
docker run -p 3000:3000 \
-e MCP_GATEWAY_API_KEY=your-key \
-e MCP_GATEWAY_UPSTREAM=http://your-mcp-server:8000/sse \
-v $(pwd)/policy.json:/app/policy.json:ro \
mcp-gatewayOr use docker-compose:
docker compose -f examples/docker-compose.yml up -dFramework Integration
- CrewAI: See
examples/crewai-integration.md - LangGraph / LangChain: See
examples/langgraph-integration.md - Any MCP-compatible client: Point your MCP client's server URL at the gateway's
/mcpendpoint with theAuthorizationheader.
Programmatic API
import {
MCPGateway,
BuiltinVerifier,
RateLimiter,
CircuitBreaker,
Metrics,
Logger,
loadPolicy,
generateKeyPair,
signReceipt,
verifyReceiptSignature,
ProtocolMetadataVerifier,
LicenseGate,
verifyLicense,
VERSION,
} from 'correctover-mcp-gateway';Testing
# Build
npm run build
# Run all 103 unit tests
npm test
# Run E2E tests (starts real HTTP server on port 3199)
npm run e2e
# Performance benchmark (10,000 samples)
npm run benchTest coverage:
- 77 gateway / core unit tests
- 19 protocol-metadata verifier tests
- 7 license gate tests
- 20 E2E checks
See QUALITY_GATE.md for the 3+9 release gate and VC due-diligence checklist.
Standards Alignment
- CCS 7 dimensions: Structure / Schema / Latency / Cost / Identity / Integrity / Security
- Receipt format: Aligned with draft-correctover-ccs-04
- Transport: MCP Streamable HTTP (2025-03-26 spec)
- Signature: Ed25519 (RFC 8032)
- Metrics: Prometheus text exposition format
Zero Runtime Dependencies
Every feature — Ed25519 signing, rate limiting, circuit breaker, Prometheus metrics, JSON logging, policy engine, license verification — is implemented using only Node.js built-in modules. No third-party runtime dependencies means zero supply-chain attack surface from the gateway itself.
License
Dual-licensed:
- Community core: Apache License 2.0
- Premium protocol-metadata verification / License Gate: commercial license required
See QUALITY_GATE.md for commercial gate details.
