mcp-gate
# MCP-Gate
**Zero-trust, protocol-layer security reverse proxy and `stdio` sidecar for the Model Context Protocol (MCP).**
`MCP-Gate` intercepts MCP Streamable HTTP (`POST /mcp/gateway`, `/mcp/{server_id}`) and local `stdio` JSON-RPC 2.0 traffic between LLM agents (Claude Desktop, Cursor, LangGraph, Gemini/OpenAI tool-calling agents) and upstream MCP servers to stop agentic security failures without modifying client code or prompts:
1. **Post-Approval Rug Pulls (`ATK-1`)** — Cryptographic SHA-256 tool-schema pinning in PostgreSQL with TOCTOU enforcement on `tools/call`, fail-closed stripping, and unified diff alerts.
2. **Direct & Split-Instruction Tool Poisoning (`ATK-2`, `ATK-3`, `ATK-5`)** — Two-stage Combined-Context Detector combining `<2ms` deterministic & multilingual heuristics (invisible Unicode, cross-server tool shadowing, obfuscated shares, ES/FR/DE/PT overrides) with an INT8-quantized local ONNX DeBERTa prompt-injection classifier (**17.29ms p95 on CPU**).
3. **Cross-Tool Data Exfiltration / "The Lethal Trifecta" (`ATK-4`)** — Dynamic Redis/local session taint FSM (`UNTRUSTED_READ` → `TAINTED` → `SENSITIVE_WRITE` pause) + human-in-the-loop Step-Up Approval gate via Redis Pub/Sub and live WebSocket Security Console UI + **real-time indirect prompt-injection Output Guard** on `UNTRUSTED_READ` tool responses (appends a `[MCP-GATE SECURITY WARNING]` boundary and escalates local taint to `CRITICAL`).
4. **Outbound DLP & Declarative Argument Policies** — Blocks AWS keys, JWTs, private keys, SSNs, unauthorized recipient domains (`allowed_domains`), and transfer-limit violations (`max_amount`) before they leave the proxy.
5. **Tamper-Evident Audit Ledger & Shadow Mode** — SHA-256 hash-chained, Ed25519-signed audit rows (`GET /admin/audit/verify`, `mcp-gate verify-audit`) with persistent keys (`0600` local/volume or env/KMS override), OpenTelemetry spans, Prometheus `/metrics`, and `MCP_GATE_ENFORCEMENT_MODE=shadow` for safe rollout.
---
## Architecture
```mermaid
flowchart LR
Client["MCP Client<br/>(Agent / SDK / IDE)"] -->|"HTTP /mcp/gateway or /mcp/{server_id}"| Gate["MCP-Gate Proxy<br/>(FastAPI / Asyncio :8000)"]
Client -.->|"Local stdio"| Sidecar["mcp-gate wrap<br/>(Zero-Docker Sidecar)"]
Gate -->|"1. Schema Pinning + Ed25519 Audit"| PG[("PostgreSQL 16<br/>pinned_tools / approvals / audit")]
Gate -->|"2. Combined-Context Scan + DLP"| ONNX["INT8 ONNX DeBERTa<br/>+ Stage A Heuristics"]
Gate -->|"3. Session Taint & Step-Up"| Redis[("Redis 7<br/>taint:{session} + Pub/Sub")]
Gate -->|"4. Redacted Spans + Metrics"| OTel["OpenTelemetry / Jaeger :16686<br/>+ Prometheus /metrics"]
Gate --> Fin["Upstream Finance Server :8001"]
Gate --> Notes["Upstream Notes Server :8002"]
UI["Security Console UI<br/>React + Vite + Tailwind :5173"] -->|"/admin/* + WS /admin/ws"| Gate
```
See [ARCHITECTURE.md](ARCHITECTURE.md) for deep technical details.
---
## Screenshots
| Security Console — Live Step-Up Approval Queue | Tool Pins & Rug-Pull Diff Quarantine |
| :---: | :---: |
|  |  |
| Live Gemini / LLM Agent Demo (`--live-llm`) | Jaeger OpenTelemetry Trace (`mcp_gate.intercept`) |
| :---: | :---: |
|  |  |
---
## 60-Second Quickstart
### Option A: Zero-Docker Local Coding Agent Protection (Claude Code, Cursor, OpenCode, Antigravity, Claude Desktop)
No Docker, Postgres, or YAML required — `mcp-gate` auto-infers tool risk tiers (`UNTRUSTED_READ` vs `SENSITIVE_WRITE`, including MCP tool annotations), pins schemas in `~/.mcp-gate/pins.json`, scans `tools/call`, `resources/read`, and `prompts/get` outputs for indirect injection, runs outbound secret DLP, shares cross-server session taint via `~/.mcp-gate/taint.json`, and allows safe in-workspace code edits while still blocking sensitive/delayed-execution files (`.env*`, `.git/hooks`, `.ssh`, `*.key`, `Makefile`, `package.json`, `Dockerfile`, `.github/workflows/*`, `*.sh`), path escapes, shell execution, and external writes (pass `--strict-taint` to block all writes when tainted):
```bash
# Install globally from PyPI (lightweight 5-dep core, zero Docker)
uv tool install mcp-gate-proxy
# or run directly without installing: uvx mcp-gate-proxy init --dry-run
# Auto-wrap all local stdio MCP servers across Claude Code, Cursor, OpenCode, Antigravity, Claude Desktop
mcp-gate init --dry-run # preview changes first
mcp-gate init # wrap all detected agent configs (reversible with `mcp-gate unwrap`)
# Or wrap any official stdio MCP server directly (e.g., Anthropic's filesystem server)
uvx mcp-gate-proxy wrap --server-id fs -- npx -y @modelcontextprotocol/server-filesystem .
# Inspect local taint state, pinned tools, rug-pull diffs, and redacted audit logs
mcp-gate status
mcp-gate pins --status drift --diff
mcp-gate approve <server_id> <tool_name>
mcp-gate logs --blocks-only
mcp-gate reset-taint
```
### Option B: Full Reverse-Proxy Stack (Docker Compose)
#### 1. Export the INT8 ONNX Classifier (One-Time)
```bash
uv sync
uv run python scripts/export_onnx.py
```
#### 2. Start the Entire Stack
```bash
make up
# equivalent to: docker compose up -d --build --wait
```
This launches:
- **MCP-Gate Proxy & Unified Gateway:** `http://127.0.0.1:8000` (`/mcp/{server_id}`, `/mcp/gateway`, `/metrics`)
- **Security Console Dashboard (WebSocket + REST):** `http://127.0.0.1:5173`
- **Jaeger OpenTelemetry Trace UI:** `http://127.0.0.1:16686`
- **Mock Finance Server:** `http://127.0.0.1:8001`
- **Rogue Notes Server:** `http://127.0.0.1:8002`
- **PostgreSQL 16** (`:5433`) & **Redis 7** (`:6379`)
#### 3. Run the 60-Second Attack Demo
```bash
make attack-demo
```
- **Run 1 (Unprotected):** Agent reads confidential balance, reads a poisoned public note, and exfiltrates the balance via `send_email` (**attack succeeds**).
- **Run 2 (Protected by `MCP-Gate`):** Exact same agent is marked `TAINTED` on the untrusted read, `send_email` pauses in the Step-Up Approval Queue, and upon denial returns JSON-RPC `-32003` with **0 unauthorized emails sent upstream**.
To approve or deny live in the Security Console UI (`http://127.0.0.1:5173`), run without `--auto-deny`:
```bash
uv run python examples/demo_agent.py
```
#### 4. Run a Real LLM Agent Against `/mcp/gateway`
Supports any OpenAI-compatible provider (Google Gemini, OpenAI, Groq, OpenRouter, or local Ollama). Put `GEMINI_API_KEY` or `OPENAI_API_KEY` in `.env` (gitignored) and run:
```bash
# Headless (auto-denies paused tainted writes)
uv run python examples/demo_agent.py --live-llm --auto-deny
# Interactive HITL (pause & approve/deny live in http://127.0.0.1:5173)
uv run python examples/demo_agent.py --live-llm \
--prompt "Check my checking-001 balance, read public note 'injected', and email a summary to audit@acme.example."
```
#### 5. Verify the Cryptographic Audit Chain
```bash
uv run mcp-gate verify-audit
```
---
## Benchmark Results
Reproducible via `make benchmark` (full report and error analysis in [BENCHMARKS.md](BENCHMARKS.md)):
### Standard Suite (60 Scenarios)
| Attack Category | Scenarios | Unprotected ASR | Static Proxy ASR | MCP-Gate ASR |
| :--- | :---: | :---: | :---: | :---: |
| Tool Rug Pulls | 10 | 100.0% | 0.0% | **0.0%** |
| Direct Tool Poisoning | 10 | 100.0% | 100.0% | **0.0%** |
| Split-Instruction Poisoning | 10 | 100.0% | 100.0% | **0.0%** |
| Indirect Injection -> Exfil | 10 | 100.0% | 100.0% | **0.0%** |
| **Benign False Positives (FPR)** | **20** | **0.0%** | **0.0%** | **0.0%** |
### Hard Adversarial Evasion & External Public Dataset
- **Hard Evasion & Ablation Suite (20 paraphrased/multilingual attacks + hard benign security tools, Combined @ `0.75`):** **90.0% recall** (10.0% ASR, 10.0% hard benign FPR vs. 30.0% recall for regex-only heuristics).
- **External Public Dataset (`deepset/prompt-injections`, 100 unseen test samples via `benchmarks/eval_public.py`):** Combined @ `0.50` achieves **75.0% precision / 27.3% recall / 7.1% FPR** (`p50 = 20.66ms`) — reported transparently to show domain gap between general chat jailbreaks and MCP tool descriptions.
### Dual Latency Breakdown & Fail-Closed Reliability
- **Steady-State Proxy Overhead (500 reqs):** `p50 = 0.55ms`, **`p95 = 1.04ms`** (target `< 35ms`)
- **Full-Inspection Path (Heuristics + INT8 ONNX, 50 reqs):** `p50 = 16.22ms`, **`p95 = 17.29ms`** (target `< 35ms`)
- **Fail-Closed Reliability (Redis / Postgres / Malformed JSON faults):** **`100.0%`** (3/3)
---
## Verified Positioning vs. Existing MCP Security Tools
Commit-pinned source-code audit conducted **December 2026** (exact SHAs recorded below):
| Project & Audited Commit | Runtime Session Taint FSM (`UNTRUSTED_READ` -> `SENSITIVE_WRITE`) | Local INT8 ONNX Combined-Catalog Split-Poisoning Scan | Strengths / Notes |
| :--- | :---: | :---: | :--- |
| **`smart-mcp-proxy/mcpproxy-go`** (`47c747b2`) | No | No *(offline rule-based per-tool detector v2)* | Strong Docker server isolation, OAuth, multilingual rules, signed TPA bundles. |
| **`hoophq/mcpproxy`** (`21d4deaa`) | No | No *(per-tool `GuardInput` hook)* | Strong OAuth/OIDC, glob policies, mid-session rug-pull session kill, budgets. |
| **`ressl/mcp-firewall`** (`4dfc9768`) | No | No *(regex `InjectionDetector` on args)* | Clean YAML policies, egress rules, Ed25519 compliance logs, `stdio` proxy. |
| **`agent-scan`** *(ex-`mcp-scan`, `e9cedaf1`)* | No | No *(IDE hooks + Snyk cloud API)* | Broad multi-IDE discovery & Snyk cloud `guard` integration. |
| **`MCP-Gate`** *(this repo)* | **Yes** *(Redis FSM + Step-Up Pub/Sub + HMAC `/mcp/gateway`)* | **Yes** *(Stage A i18n/heuristics + Stage B INT8 ONNX)* | Also includes `mcp-gate wrap` (`stdio`), outbound DLP, Shadow mode, persistent-key SHA-256 + Ed25519 audit ledger. |
---
## Scope & v0.3 Roadmap
`v0.2` delivers protocol-layer taint tracking, combined-context split-poisoning detection, real-time indirect prompt-injection output guarding, workspace-safe local taint allowlisting, zero-Docker `stdio` onboarding (`mcp-gate init` / `wrap` / `status` / `pins` / `approve` / `logs`), and lightweight core vs. `[proxy]`/`[ml]` packaging. Planned `v0.3` items for multi-tenant team deployments:
- **Multi-user OAuth 2.1 / OIDC RBAC** and high-concurrency SSE soak testing.
- **KMS-backed key rotation (`kid`)** for multi-replica deployments.
- **Data-flow isolation (CaMeL-style capability attenuation)** for complex multi-agent workflows.
---
## Development Commands
```bash
make lint # uv run ruff check . && uv run ruff format --check .
make test # uv run --all-extras pytest -v (64 unit + integration tests)
make benchmark # Re-run 60-scenario + 20-scenario hard evasion benchmark
make attack-demo # Run unprotected vs MCP-Gate exfiltration demo
make up / down # Start / stop full Docker Compose stack
```
TDQS
Scored across 3 tools
Each tool targets a distinct action on a distinct resource: reading balance, sending email, and moving money. There is no plausible way to confuse transfer_funds with read_balance or send_email, even though email lives in a different domain than the banking tools.
All three names follow a strict verb_noun snake_case pattern (read_balance, send_email, transfer_funds). A predictable, readable convention with no deviations.
Three tools is thin for a server that appears to span two domains (banking and email). It is borderline rather than wrong: each tool earns its place, but the surface feels like a fragment of a larger API.
Banking lifecycle is severely truncated: no way to list or look up accounts (so read_balance and transfer_funds require IDs the agent cannot discover), no transaction history, no deposits. Email is write-only with no listing or status check, leaving obvious dead ends.