Metadata-Version: 2.5
Name: mcp-gateway-guard
Version: 0.1.0
Summary: A local MCP security gateway: semantic tool search, a default-deny policy firewall, human approvals, and an audit log.
Project-URL: Homepage, https://github.com/vinayak533/mcp-gateway
Author: Vinayak
License: MIT
License-File: LICENSE
Keywords: agents,firewall,gateway,llm,mcp,model-context-protocol,security
Classifier: Development Status :: 3 - Alpha
Classifier: Environment :: Console
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: anyio<5,>=4.16
Requires-Dist: fastembed<0.10,>=0.9.1
Requires-Dist: httpx2<3,>=2.16
Requires-Dist: jsonschema<5,>=4.26
Requires-Dist: mcp<3,>=2.3
Requires-Dist: numpy<3,>=2.4
Requires-Dist: pydantic-settings<3,>=2.16
Requires-Dist: pydantic<3,>=2.14
Requires-Dist: pyyaml<7,>=6.0.3
Requires-Dist: regex>=2026.11.19
Requires-Dist: sqlglot<31,>=30.30
Requires-Dist: starlette<2,>=1.10
Requires-Dist: uvicorn<1,>=0.54
Provides-Extra: dev
Requires-Dist: cyclonedx-bom<9,>=8.0; extra == 'dev'
Requires-Dist: hypothesis<7,>=6.170; extra == 'dev'
Requires-Dist: mutmut<4,>=3.8; (sys_platform != 'win32') and extra == 'dev'
Requires-Dist: mypy<3,>=2.4; extra == 'dev'
Requires-Dist: opentelemetry-exporter-otlp-proto-http<2,>=1.45; extra == 'dev'
Requires-Dist: opentelemetry-sdk<2,>=1.45; extra == 'dev'
Requires-Dist: pip-audit<3,>=2.10; extra == 'dev'
Requires-Dist: pre-commit<5,>=4.7; extra == 'dev'
Requires-Dist: pytest-asyncio<2,>=1.4; extra == 'dev'
Requires-Dist: pytest-cov<8,>=7.0; extra == 'dev'
Requires-Dist: pytest<10,>=9.2; extra == 'dev'
Requires-Dist: ruff<0.18,>=0.17.4; extra == 'dev'
Requires-Dist: types-jsonschema>=4.26; extra == 'dev'
Requires-Dist: types-pyyaml>=6.0.12; extra == 'dev'
Requires-Dist: types-regex; extra == 'dev'
Requires-Dist: uv<0.14,>=0.13.7; extra == 'dev'
Provides-Extra: otel
Requires-Dist: opentelemetry-exporter-otlp-proto-http<2,>=1.45; extra == 'otel'
Requires-Dist: opentelemetry-sdk<2,>=1.45; extra == 'otel'
Description-Content-Type: text/markdown

# MCP Security Gateway

[![CI](https://github.com/vinayak533/mcp-gateway/actions/workflows/ci.yml/badge.svg)](https://github.com/vinayak533/mcp-gateway/actions/workflows/ci.yml)
[![OpenSSF Scorecard](https://api.scorecard.dev/projects/github.com/vinayak533/mcp-gateway/badge)](https://scorecard.dev/viewer/?uri=github.com/vinayak533/mcp-gateway)
[![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue.svg)](pyproject.toml)
[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](LICENSE)

A local MCP gateway that sits between an AI agent and your MCP servers.

- **Tool search.** The agent sees two tools instead of hundreds. `search_tools`
  finds the right ones with `BAAI/bge-base-en-v1.5` embeddings (FastEmbed, CPU);
  `call_tool` runs one.
- **Policy firewall.** Every call is checked by deterministic, default-deny
  rules: SQL statement allowlists, path sandboxes, argument limits, rate
  limits. No LLM in the security path.
- **Approvals and audit.** Risky calls wait for a person (in the agent's own UI,
  a terminal, or a localhost page). Every call is logged as JSON, with secrets
  redacted.

```mermaid
flowchart LR
    A["Agent<br/>(Claude Code, Claude Desktop,<br/>LangGraph, ...)"] -- "search_tools<br/>call_tool" --> G
    subgraph G["mcp-gateway"]
        direction TB
        S["semantic search"] --- P["policy firewall<br/>(default deny)"] --- H["human approval"] --- L["audit log"]
    end
    G -- "allowed calls only" --> D1["weather"]
    G --> D2["sqlite"]
    G --> D3["files"]
    G --> D4["...any MCP server"]
```

> **Status: 0.1.0, alpha.** Phases 0 to 14 of [the roadmap](docs/roadmap.md)
> are built and tested (369 tests; 95.6% top-3 search accuracy on the eval set).
> What it does **not** protect against is in [docs/limitations.md](docs/limitations.md).
> It is one security layer: keep least privilege on the servers behind it too.

## Install: one command

```bash
# macOS / Linux
curl -LsSf https://raw.githubusercontent.com/vinayak533/mcp-gateway/main/install.sh | sh
```

```powershell
# Windows (PowerShell)
irm https://raw.githubusercontent.com/vinayak533/mcp-gateway/main/install.ps1 | iex
```

From a clone, run `./install.sh` (or `.\install.ps1`) in it: that installs the
checkout. Either way the installer

1. installs [uv](https://docs.astral.sh/uv/) if you do not have it (uv brings
   its own Python 3.11+ when the system has none);
2. installs `mcp-gateway-guard` in an environment of its own (`uv tool install`), so it
   never clashes with your project's dependencies;
3. downloads the search model (about 200 MB; until it is there, search matches
   keywords);
4. runs `mcp-gateway-guard init`: finds the MCP servers your clients (Claude Desktop,
   Claude Code, Cursor, VS Code, Windsurf, Zed, Cline) already start, moves them
   behind the gateway, writes a starter policy in which **every call needs your
   approval**, and offers to make the gateway the only MCP server in each client.
   Each client file is backed up first; `mcp-gateway-guard undo` puts it back;
5. runs `mcp-gateway-guard doctor`, which starts every server once and checks the setup.

Restart your MCP client and you are done. Options (environment variables, or
arguments after `sh -s --` / `.\install.ps1 -InitArgs`):
`MCP_GATEWAY_GUARD_NO_MODEL=1`, `MCP_GATEWAY_GUARD_NO_INIT=1`, `MCP_GATEWAY_GUARD_NO_MODIFY_PATH=1`,
`MCP_GATEWAY_GUARD_SOURCE=<wheel, folder or git URL>`, `MCP_GATEWAY_GUARD_VERSION=0.1.0`; anything
else is passed to `init` (`--yes`, `--client claude-code`, `--template filesystem`).
Without a terminal (CI) `init` runs with `--yes --no-rewrite`: files are
written, client configs are left alone.

> **Before the first release** the package is not on PyPI and the repository
> is private, so the one-liners above do not work yet: clone the repository and
> run `./install.sh` / `.\install.ps1` in it.

Already have uv? `uv tool install mcp-gateway-guard && mcp-gateway-guard init` is the same thing
by hand, and `uvx mcp-gateway-guard <command>` runs any command without installing.

## Use it in an existing project

Say a project's `.mcp.json` gives Claude Code the official filesystem server:

```json
{ "mcpServers": { "filesystem": { "command": "npx",
  "args": ["-y", "@modelcontextprotocol/server-filesystem", "."] } } }
```

In the project folder:

```bash
mcp-gateway-guard init --template filesystem
```

`init` moves `filesystem` into the gateway's `gateway.yaml`, applies the
built-in `filesystem` policy scoped to this folder, and (when you say yes)
rewrites `.mcp.json` so Claude Code starts only the gateway:

```json
{ "mcpServers": { "mcp-gateway-guard": { "type": "stdio",
  "command": "/home/me/.local/share/uv/tools/mcp-gateway-guard/bin/python",
  "args": ["-m", "mcp_gateway", "--config", "/home/me/.config/mcp-gateway/gateway.yaml"],
  "alwaysLoad": true } } }
```

Ask the agent to "show me src/app.py" and it searches for a tool, finds
`filesystem.read_text_file`, and reads the file. Ask for `.env`, or for a file
outside the project, and the call is refused with the rule that refused it;
ask it to write a file and you are asked first. `policy explain` shows the
same decisions without an agent:

```text
$ mcp-gateway-guard policy explain filesystem.read_text_file path=$PWD/.env
verdict    DENY
reason     '.env' is off-limits (denied name '.env')

$ mcp-gateway-guard policy explain filesystem.write_file path=$PWD/src/new.py content=x
verdict    REQUIRE APPROVAL (a person must say yes to each call)
reason     Changes files in the project.
```

Servers without a template start with every call needing approval. Loosen
them rule by rule in `policies.yaml` ([docs/policies.md](docs/policies.md) has
recipes for SQL, paths, rate limits and argument checks), or let
`mcp-gateway-guard policy suggest` draft rules from what the agent actually called.
To add the gateway to one more client: `mcp-gateway-guard install --client cursor`
(`--print` only shows the snippet). Other clients, LangGraph and HTTP:
[docs/agents.md](docs/agents.md).

A complete `gateway.yaml` can be five lines (with no policy file, every call
asks for approval):

```yaml
version: 1
servers:
  - name: notes
    command: npx
    args: ["-y", "@modelcontextprotocol/server-filesystem", "/home/me/notes"]
```

With no configuration at all the gateway still starts: no downstream servers,
nothing callable, and a message telling the agent to run `init`. It answers
its client at once and connects the servers in the background, so a slow
`npx` download never makes the client give up on it.

## Developing from a clone (about 6 minutes, mostly downloads)

Requires Python 3.11+, [uv](https://docs.astral.sh/uv/), Node 18+ (for the MCP
Inspector), and git.

```bash
git clone https://github.com/vinayak533/mcp-gateway.git && cd mcp-gateway
make setup          # Windows: .\make.ps1 setup
```

`setup` creates `.venv` with `uv sync` (the exact hashed versions in
`uv.lock`), installs the MCP Inspector into `node_modules`, installs
git hooks, and downloads the two BGE models (about 275 MB; bge-small is only
for `make eval-search`) into `.cache/models`. Nothing is installed outside the
folder. A checkout uses `config/gateway.yaml` and `config/policies.yaml`, which
run three example servers.

```bash
make check-config   # validate config/gateway.yaml and config/policies.yaml
make list-tools     # start the three example servers and list their tools
make inspect        # open the gateway in the MCP Inspector
```

In the Inspector, call `search_tools` with `{"query": "read a text file"}`,
then `call_tool` with `{"tool": "files.read_file", "arguments": {"path": "hello.txt"}}`.
Try `{"tool": "sqlite.run_query", "arguments": {"sql": "DELETE FROM notes"}}`
to see the firewall deny it.

Clients, LangGraph and HTTP: [docs/agents.md](docs/agents.md). All setup
commands: [docs/setup.md](docs/setup.md).

## What the agent sees

| Tool | Does |
| --- | --- |
| `search_tools(query, limit)` | returns the best-matching downstream tools (name, description, input schema, whether a call needs approval). Tools the policy denies outright are never shown. |
| `call_tool(tool, arguments)` | validates the arguments against the tool's schema, applies the policy, asks for approval if needed, forwards the call, and returns the result (size-limited, flagged if it looks like a prompt injection). Denials are tool errors that name the rule. |

## Configuration

- `gateway.yaml`: downstream servers (stdio or Streamable HTTP), search,
  approval, audit, limits, how the agent connects. Only `servers` is needed.
  Reference: [docs/configuration.md](docs/configuration.md).
- `policies.yaml` (or a `policies:` section of `gateway.yaml`): the firewall
  rules. Guide: [docs/policies.md](docs/policies.md).

`init` writes both to your config folder (`%APPDATA%\mcp-gateway`,
`~/Library/Application Support/mcp-gateway`, `~/.config/mcp-gateway`); a clone
uses [`config/`](config). Both files carry `version: 1`; `mcp-gateway-guard migrate`
updates older ones.

A bad file stops the gateway with a readable report, never a stack trace:

```text
mcp-gateway-guard: invalid configuration in config/gateway.yaml (2 problems):
  - servers[0] (weather).comand: unknown key (did you mean 'command'?)
  - servers[0] (weather).command: Field required
```

## Measured, not assumed

| | bge-small | **bge-base** (default) |
| --- | --- | --- |
| top-1 / top-3 accuracy | 80.0% / 88.9% | **82.2% / 95.6%** |
| query latency p50 (CPU) | 9.9 ms | 25.6 ms |
| memory (model + index) | 210 MiB | 532 MiB |

45 queries over 35 tools (10 real, 25 realistic distractors), with BGE's query
instruction; full report in [docs/search-eval.md](docs/search-eval.md),
reproduce with `make eval-search`. A regression test keeps top-3 at 90% or more.
Padded with synthetic look-alike tools, bge-base's top-3 is 93.3% at 50 tools,
82.2% at 200 and 75.6% at 1000; a keyword + semantic hybrid did not do better.
(Query latency here is the model alone; a whole `search_tools` call inside the
gateway is below.)

| Performance (CPU, 12 threads, bge-base) | |
| --- | --- |
| cold start, until the MCP handshake is done (3 servers, 10 tools) | 5.9 s |
| `search_tools`, p50 / p95, at 35 / 200 / 1000 tools | 28 / 42, 24 / 31, 22 / 28 ms |
| keyword search (no model yet), p50 at 1000 tools | 1.3 ms |
| index build from scratch, 200 / 1000 tools | 10.1 s / 34.5 s |
| added per call by the gateway (validation, policy, audit flush, result checks), p50 | 4 to 13 ms |
| one policy check: plain rule / SQL / path | 3 µs / 0.4 ms / 0.5 ms |

Full report and method in [docs/benchmarks.md](docs/benchmarks.md); reproduce
with `make bench`.

## Example downstream servers

| Server | Tools | Used for |
| --- | --- | --- |
| `examples/weather_server.py` | `get_weather`, `get_forecast` | basic routing (fake, deterministic data) |
| `examples/sqlite_server.py` | `list_tables`, `describe_table`, `run_query`, `add_note`, `delete_note` | SQL policy; `run_query` runs *any* statement on purpose |
| `examples/file_server.py` | `list_directory`, `read_file`, `write_file` | path policy; confined to its own root |

## Everyday commands

| Task | Linux / macOS | Windows |
| --- | --- | --- |
| Check the whole setup | `mcp-gateway-guard doctor` | `mcp-gateway-guard doctor` |
| Check a policy against sample calls | `mcp-gateway-guard policy test FILE` | `mcp-gateway-guard policy test FILE` |
| See why a call is allowed or denied | `mcp-gateway-guard policy explain TOOL key=value` | `mcp-gateway-guard policy explain TOOL key=value` |
| Draft a policy from the audit log | `mcp-gateway-guard policy suggest -o draft.yaml` | `mcp-gateway-guard policy suggest -o draft.yaml` |
| Check the audit log for tampering | `mcp-gateway-guard audit verify [--expect HASH]` | `mcp-gateway-guard audit verify [--expect HASH]` |
| Lint, type-check, test | `make check` | `.\make.ps1 check` |
| Tests with the coverage gate | `make coverage` | `.\make.ps1 coverage` |
| Dependency vulnerability scan | `make audit-deps` | `.\make.ps1 audit-deps` |
| Long fuzz run (SQL, paths, properties) | `make fuzz` | `.\make.ps1 fuzz` |
| Mutation testing of `policy/` | `make mutate` | WSL, or CI's weekly job |
| Search accuracy report | `make eval-search` | `.\make.ps1 eval-search` |
| Benchmarks | `make bench` | `.\make.ps1 bench` |
| Run the gateway (stdio) | `make run` | `.\make.ps1 run` |
| Open the Inspector | `make inspect` | `.\make.ps1 inspect` |
| Docker image | `make docker` | `.\make.ps1 docker` |
| Re-lock dependencies | `make lock` | `.\make.ps1 lock` |

## Project layout

```text
mcp-gateway/
├── src/mcp_gateway/        # the gateway package
│   ├── server.py           #   MCP server: search_tools / call_tool
│   ├── downstream.py       #   connections to downstream MCP servers
│   ├── index.py            #   semantic tool search (FastEmbed + BGE)
│   ├── policy/             #   default-deny firewall: SQL, paths, args, rate limits
│   ├── approval.py         #   human-in-the-loop approvals (+ approval_web.py)
│   ├── audit.py            #   JSON audit log with secret redaction
│   ├── sanitize.py         #   result size limits and injection flags
│   ├── config.py           #   typed configuration (pydantic)
│   ├── clients.py          #   reading and rewriting MCP client configs
│   ├── wizard.py           #   init / install / undo
│   ├── doctor.py           #   mcp-gateway-guard doctor
│   ├── migrate.py          #   schema versions
│   └── model_cache.py      #   lazy model download with progress
├── config/                 # the checkout's gateway.yaml and policies.yaml (examples)
├── npm/mcp-gateway-guard/           # `npx -y mcp-gateway-guard` launcher
├── install.sh / install.ps1  # the one-command installers
├── examples/               # example downstream servers and client configs
├── tests/                  # unit, integration, end-to-end, property and invariant tests
│   └── fuzz/               #   SQL and path fuzzers with independent oracles
├── bypass-corpus/          # attack payloads with expected verdicts, run on every commit
├── evals/                  # search-accuracy (50 to 1000 tools) and agent-flow evaluations
├── benchmarks/             # cold start, index build, search and per-call overhead
├── scripts/                # model download and venv helpers
├── docs/                   # architecture, configuration, policies, threat model
├── Makefile / make.ps1     # task runners (Linux/macOS / Windows)
└── Dockerfile
```

## Docs

| | |
| --- | --- |
| [architecture.md](docs/architecture.md) | components and the request flow |
| [setup.md](docs/setup.md) | init, install, undo, doctor, migrate, models |
| [configuration.md](docs/configuration.md) | every setting |
| [policies.md](docs/policies.md) | writing rules, with recipes |
| [agents.md](docs/agents.md) | Claude Code, Claude Desktop, LangGraph, HTTP |
| [threat-model.md](docs/threat-model.md) | what is protected, from whom, and how |
| [limitations.md](docs/limitations.md) | what it does not do |
| [testing.md](docs/testing.md) | property tests, fuzzing, bypass corpus, invariants, mutation score |
| [search-eval.md](docs/search-eval.md) | search accuracy at 50 to 1000 tools, latency, memory |
| [benchmarks.md](docs/benchmarks.md) | cold start, index build, search, per-call overhead |
| [roadmap.md](docs/roadmap.md) | the phase-by-phase build plan and its exit checks |

## Contributing and license

Contributing: [CONTRIBUTING.md](CONTRIBUTING.md). Security reports:
[SECURITY.md](SECURITY.md). Changes: [CHANGELOG.md](CHANGELOG.md).

Released under the [MIT License](LICENSE).
