Metadata-Version: 2.5
Name: mcp-gate-proxy
Version: 0.2.2
Summary: Zero-trust, protocol-layer security reverse proxy and stdio sidecar for the Model Context Protocol (MCP)
Project-URL: Homepage, https://github.com/suyash-04/mcp-gate
Project-URL: Repository, https://github.com/suyash-04/mcp-gate
Project-URL: Issues, https://github.com/suyash-04/mcp-gate/issues
Author: Suyash Adhikari
License: MIT License
        
        Copyright (c) 2026 Suyash Adhikari
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: ai-agents,claude-code,cursor,firewall,mcp,prompt-injection,security
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Requires-Python: >=3.11
Requires-Dist: httpx>=0.28.0
Requires-Dist: pydantic-settings>=2.7.0
Requires-Dist: pydantic>=2.10.0
Requires-Dist: pyyaml>=6.0.2
Requires-Dist: typer>=0.15.0
Provides-Extra: all
Requires-Dist: asyncpg>=0.30.0; extra == 'all'
Requires-Dist: cryptography>=44.0.0; extra == 'all'
Requires-Dist: fastapi>=0.115.0; extra == 'all'
Requires-Dist: huggingface-hub>=0.29.0; extra == 'all'
Requires-Dist: mcp[cli]>=1.6.0; extra == 'all'
Requires-Dist: numpy>=2.0.0; extra == 'all'
Requires-Dist: onnx>=1.17.0; extra == 'all'
Requires-Dist: onnxruntime>=1.20.0; extra == 'all'
Requires-Dist: opentelemetry-api>=1.30.0; extra == 'all'
Requires-Dist: opentelemetry-exporter-otlp>=1.30.0; extra == 'all'
Requires-Dist: opentelemetry-sdk>=1.30.0; extra == 'all'
Requires-Dist: prometheus-client>=0.21.0; extra == 'all'
Requires-Dist: redis>=5.2.0; extra == 'all'
Requires-Dist: sqlalchemy[asyncio]>=2.0.38; extra == 'all'
Requires-Dist: tokenizers>=0.21.0; extra == 'all'
Requires-Dist: uvicorn[standard]>=0.34.0; extra == 'all'
Provides-Extra: ml
Requires-Dist: huggingface-hub>=0.29.0; extra == 'ml'
Requires-Dist: numpy>=2.0.0; extra == 'ml'
Requires-Dist: onnx>=1.17.0; extra == 'ml'
Requires-Dist: onnxruntime>=1.20.0; extra == 'ml'
Requires-Dist: tokenizers>=0.21.0; extra == 'ml'
Provides-Extra: proxy
Requires-Dist: asyncpg>=0.30.0; extra == 'proxy'
Requires-Dist: cryptography>=44.0.0; extra == 'proxy'
Requires-Dist: fastapi>=0.115.0; extra == 'proxy'
Requires-Dist: mcp[cli]>=1.6.0; extra == 'proxy'
Requires-Dist: opentelemetry-api>=1.30.0; extra == 'proxy'
Requires-Dist: opentelemetry-exporter-otlp>=1.30.0; extra == 'proxy'
Requires-Dist: opentelemetry-sdk>=1.30.0; extra == 'proxy'
Requires-Dist: prometheus-client>=0.21.0; extra == 'proxy'
Requires-Dist: redis>=5.2.0; extra == 'proxy'
Requires-Dist: sqlalchemy[asyncio]>=2.0.38; extra == 'proxy'
Requires-Dist: uvicorn[standard]>=0.34.0; extra == 'proxy'
Description-Content-Type: text/markdown

# 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 |
| :---: | :---: |
| ![Security Console Step-Up Approval Queue](docs/screenshots/step_up_queue.png) | ![Tool Pins & Rug-Pull Diff Quarantine](docs/screenshots/tool_pins_diff.png) |

| Live Gemini / LLM Agent Demo (`--live-llm`) | Jaeger OpenTelemetry Trace (`mcp_gate.intercept`) |
| :---: | :---: |
| ![Live Gemini Flash Lite Agent Demo](docs/screenshots/live_llm_demo.png) | ![Jaeger OpenTelemetry BLOCK_RUG_PULL Trace](docs/screenshots/jaeger_trace.png) |

---

## 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`), pins schemas in `~/.mcp-gate/pins.json`, 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 files (`.env*`, `.git/hooks`, `.ssh`, `*.key`), 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`)

# 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
```
