# MCP proxy

`aiguard mcp` sits between an MCP client (Claude Code, Codex CLI, Cursor, ...) and an MCP
server and checks every JSON-RPC message with the same detectors and policy as the gateway:

- **to the server** (tool arguments, answers to sampling/elicitation): protected data is
  removed or replaced before it leaves; a block never reaches the server;
- **to the model** (tool results, resources, prompts, tool descriptions, server requests,
  notifications): cleaned before they enter the model context.

Verified with Claude Code 2.1 and Codex CLI 0.155 (`dataplane/tests/test_mcp_live.py`), and
with the official reference servers (everything, filesystem, memory) and the official Python
SDK 2.3 as the client, over stdio and Streamable HTTP, with both the 2025 handshake and the
2026-07-28 protocol (`make mcp-real-e2e`, 2026-10-30). Overhead measured there: 3–6 ms per tool
call for short texts.

## What you need

A running data plane and a key with the `inspect` scope (a dedicated key per user or team;
Q-047). The key is read from an environment variable, never from an argument:

```sh
export AIGUARD_KEY=aig_...
export AIGUARD_GATEWAY_URL=https://aiguard.internal.example.com
```

`https` is required (plain `http` only for localhost or with `--allow-http`).

## stdio servers

Replace the server command `npx some-server --flag` by:

```sh
aiguard mcp stdio -- npx some-server --flag
```

Claude Code (`.mcp.json`):

```json
{"mcpServers": {"notes": {"command": "aiguard",
  "args": ["mcp", "stdio", "--", "npx", "some-server", "--flag"],
  "env": {"AIGUARD_KEY": "aig_...", "AIGUARD_GATEWAY_URL": "https://..."}}}}
```

Codex CLI (`~/.codex/config.toml`):

```toml
[mcp_servers.notes]
command = "aiguard"
args = ["mcp", "stdio", "--", "npx", "some-server", "--flag"]
env_vars = ["AIGUARD_KEY", "AIGUARD_GATEWAY_URL"]
```

Options: `--client NAME` (client assignment), `--repo-dir DIR` (apply `.aiguard.yaml` rules),
`--lang pl|de|en` (language of block messages).

For a whole organization, prefer the central gateway with single sign-on
([mcp-gateway.md](https://grodmir.com/dokumentacja/zrodla/mcp-gateway.md)): no local proxy and every audit entry names the user.

## Streamable HTTP servers

```sh
aiguard mcp http --upstream https://mcp.example.com/mcp \
    --upstream-header Authorization=MCP_TOKEN_ENV --port 8765
```

Point the client at `http://127.0.0.1:8765/mcp`. The upstream is fixed by the operator; the
proxy binds to loopback, refuses foreign `Origin` headers (DNS rebinding) and checks JSON and
SSE responses event by event (LF, CRLF and lone-CR line endings; an event whose JSON spans
several `data:` lines reaches the client as the same text that was checked). The server's own
token stays in the proxy's environment. The proxy has no client authentication, so `--host`
other than loopback is refused unless `--allow-remote` is given (only for an address that is
protected otherwise, such as a private container network).

### Remote servers that need a sign-in (OAuth)

Most SaaS MCP servers (issue trackers, wikis, code hosting) ask the user to sign in with OAuth.
The proxy signs in for the user, so the coding agent never holds the token:

```sh
aiguard mcp login --upstream https://mcp.example.com/mcp      # once; opens the browser
aiguard mcp http --upstream https://mcp.example.com/mcp --oauth --port 8765
```

`login` finds the server's authorization server, registers itself (or uses `--client-id` and
`--client-secret-env` from the vendor), signs the user in with PKCE and asks for a token bound
to that server. With a client secret, `--issuer` (the vendor's authorization server) is
required, so the secret never goes elsewhere. It refuses metadata that names another server or
issuer (or a different one than `--issuer`), URLs in metadata that point to internal addresses
when the server itself is public, an authorization
server without PKCE S256, plain http, and a sign-in answer with a wrong `iss`. An answer with
another `state` (a stale tab, or any local process calling the loopback port) is ignored and
the sign-in keeps waiting for its own answer. The
token is stored in the operating system's keychain (macOS Keychain, Windows Credential Locker,
Linux Secret Service); where there is none, in a 0600 file under `~/.config/aiguard/mcp-auth/`
(`AIGUARD_MCP_AUTH_DIR` overrides, `AIGUARD_MCP_TOKEN_STORE=file` forces the file). The proxy
refreshes it (once for several calls refused at the same moment, so a rotating refresh token
is never presented twice; `expires_in` may be a number or a numeric string); when it can no
longer be refreshed, the agent gets a
message to run `aiguard mcp login` again. `aiguard mcp logout --upstream URL` forgets it. The
client's own `Authorization` header is never forwarded in this mode (Q-060).

Tested against the official MCP SDK's authorization server (dynamic registration, PKCE,
resource-bound tokens, 4-second tokens refreshed through the proxy; `make mcp-real-e2e`). Not
yet tested against a commercial vendor's server.

## Isolation and a pinned catalog

A stdio server runs with the user's rights: it can read their files and reach the network.
Run it in a locked-down container instead:

```sh
aiguard mcp stdio --server notes --sandbox docker \
    --image registry.example.com/mcp/notes@sha256:... --require-digest \
    --mount ~/notes:/data -- notes-server /data
```

The container has no network (`--network none` unless another network is named, never
`host`), a read-only root with a private 64 MB `/tmp`, no Linux capabilities, no privilege
escalation, user 65534, and limits of 512 MB, one CPU and 256 processes. It sees only the paths
given with `--mount`, read-only unless they end in `:rw`. It gets no environment from the
proxy, so never the Grodmir key, only the variables named with `--env`. Podman works the same
(`--sandbox podman`). Tested with Docker: the server works through the proxy, and a process in
the sandbox has no network and cannot write to its root.

In the approved list for `aiguard mcp allowlist`, pin what runs instead of naming a command:

```json
{"mcpServers": {
  "fs":    {"package": "npm:@modelcontextprotocol/server-filesystem@2.1.0", "args": ["/srv"]},
  "fetch": {"package": "pypi:mcp-server-fetch==2025.4.7"},
  "notes": {"image": "registry.example.com/mcp/notes@sha256:...",
            "sandbox": {"network": "none", "mounts": ["/srv/notes:/data"]}}}}
```

Exact versions only: `latest`, ranges and tags are refused. npm and PyPI never reuse a published
version number. A container image needs a digest, and it always runs sandboxed. Together with
tool pins this means what runs and what it offers the model are both fixed.

## Tool permissions, pins and confirmation

Name each server with `--server NAME` (the allow-list generator does it). The signed
organization policy then decides per tool; lower policy layers can only tighten:

```yaml
policy:
  mcp_tools:
    - {id: no-delete, server: jira, tools: ["delete_*"], action: block}
    - {id: confirm-writes, server: "*", tools: ["create_*", "update_*", "send_*"], action: require_approval}
  mcp_pins:            # aiguard mcp pin --server jira -- <command>   prints this block
    jira:
      search_issues: sha256:...
      get_issue: sha256:...
```

- `block`: the model does not see the tool and a call to it is refused.
- `require_approval`: the user confirms each call in the MCP client before it leaves (2025
  clients over stdio: an elicitation; 2026-07-28 clients: `input_required`, bound by an HMAC to
  that exact method and parameters). Modern approval state has a random challenge, expires
  after five minutes and is consumed on the first answer, including decline or an invalid
  answer. A retry can use a new JSON-RPC ID, but cannot reuse an accepted state. Each proxy
  Guard holds at most 1024 pending challenges and refuses further requests until space is
  available. A client that cannot ask gets a refusal that says so.
- Pins: a server with pins shows the model only the pinned tools, and only while each tool's
  definition (name, title, description, schemas, annotations) still has the approved sha256.
  A changed definition (rug pull) or a new tool disappears until it is pinned again; a call to
  an unpinned tool is refused. Review the definitions before pinning them. `aiguard mcp pin`
  skips non-JSON lines a server logs to stdout, and refuses an error answer, an empty list
  (it would block every tool) and a tool listed twice with different definitions.
- Entries of a `tools/list` result that are not named tools are removed, never a reason to
  skip the filter. A `tools/call` without a non-empty string `name` is refused
  (`mcp.tool_blocked`). An `X-AIGuard-MCP-Server` header that is not a valid name is refused
  (HTTP 400) instead of falling back to `default`.
- Audit entries name the server, method, tool, the tool action, whether the user confirmed and
  how many tools were hidden (identifiers only).

## Behaviour to know

- **Fail closed**: any error, timeout or unexpected answer from the data plane blocks the
  message. The client gets a JSON-RPC error (code -32001, text in PL/DE/EN); a blocked server
  request is answered with an error towards the server and is never shown to the client.
- Inside tool arguments and results, object keys and long integers are checked too
  (`{"Client Ltd": {...}}`, a PESEL stored as a JSON number); a transformed number becomes a
  string. Panel dictionaries match without Polish letters, with Cyrillic look-alikes, with
  every word inflected, and in file names and URLs (`projekt_feniks.pdf`, `Projekt%20Feniks`).
  Not caught: `ProjektFeniks` (camelCase), base64 or other encodings (Q-085).
- **Tables and files (Q-086).** In a CSV, a range pasted from Excel, a Markdown table or JSON
  rows, every cell is read with its column header or key as context, so `NIP`, `REGON` or
  `Nazwisko` in the header protects the whole column; amounts, statuses and row structure stay.
  With `defaults.attachment_inspection: text`, a workbook, document or PDF returned by a server
  (`resources/read`, embedded resource) reaches the model as its text (sheets as tab-separated
  rows), pseudonymised; macros, pictures and comments are not delivered. With inspection `off`
  such files stay blocked (`unknown_attachment`).
- Names that select a tool or prompt, and protocol fields such as types, MIME types and the
  server's own name and title, are inspected but cannot be rewritten: a message that carries
  an identifier, secret, e-mail address or dictionary term there is refused
  (`field_needs_transformation`). The statistical name model does not decide in such fields
  (a server called "Everything Server" is not a person).
- One value keeps one placeholder for the whole proxy session: `[EMAIL_1]` in a later tool
  result is the same address as before, and another address gets another number. The proxy
  keeps only salted digests for this, never a value. A new proxy process starts counting again.
- Pseudonyms in a tool result are not restored when the model uses them later (Q-044). A
  message that would send a placeholder this session put into the model's context back to a
  server is refused (Q-059): otherwise an agent that rewrites a whole file would replace the
  real values with placeholders. Tools that change only the lines they name (`edit_file`)
  keep working.
- Binary content (images, blobs) is blocked unless the policy allows it; batches are refused
  (Q-045). To allow images for one server only: give that server's proxy its own key, granted
  only a client context (for example `mcp-images`, defined in the signed policy as a
  `scope: client` policy) and started with `--client mcp-images`; then add an approved
  organization exception scoped to that client with `categories: [unknown_attachment]` (exactly
  that name) and `action_override: allow`. It expires like every exception, and text from that
  server is still checked. `make mcp-real-e2e` shows the full setup.
- The server process is started without the Grodmir key variable, so a third-party server
  cannot use the key (with `--sandbox`, `--env` refuses that variable, also a custom
  `--key-env`). Only the first `--` separates Grodmir's options from the server command; a
  later `--` is passed to the server.
- An unexpected error inside the proxy blocks the message like any other failure; a stdio
  client line longer than 64 MiB is discarded and answered with `too_large`. A server answer
  the proxy has to drop (unparseable) leaves the call pending, so the client still gets
  `server_exited` if the server dies. A 2025 stdio confirmation is valid for five minutes.
- MCP 2026-07-28 over HTTP copies parts of the body into `Mcp-Method`, `Mcp-Name` and
  `Mcp-Param-*` headers. The proxy rebuilds them from the checked body, so a replaced value is
  never sent in a header; a `Mcp-Param-*` header that matches no argument is dropped.
- A server that is not launched through the proxy is not protected. Find such servers with
  `aiguard mcp scan` and prevent them with managed client settings (below; Q-046).
- Nothing is logged but types, counts and positions; the audit entries carry the fields
  `mcp.to_server` and `mcp.to_model`.

## Finding and preventing unproxied servers

`aiguard mcp scan` reads the MCP configuration of Claude Code (`managed-mcp.json`,
`~/.claude.json` user and local scopes, `.mcp.json`), Codex CLI (`$CODEX_HOME/config.toml`)
and Cursor (`~/.cursor/mcp.json`, `.cursor/mcp.json`) on this machine and lists every server
with a status:

| Status | Meaning |
|---|---|
| `covered` | launched as `aiguard mcp stdio -- ...` (directly, via `uvx`, or via `uv run` with only `--project`/`--directory`/`--frozen`/`--locked`/`--offline`/`--quiet`/`--no-sync`; `--from`, `--with` and other options can run another package's `aiguard` and are `not_covered`) |
| `loopback_unverified` | a `http://127.0.0.1`/`localhost` URL: covered only if that port is `aiguard mcp http`; the scan cannot tell |
| `not_covered` | anything else, including servers started through a shell or script |
| `unreadable` | the configuration file cannot be parsed; nothing can be concluded |

```sh
aiguard mcp scan --project ~/src/app       # repeat --project; default: current directory
aiguard mcp scan --json --strict           # exit 1 also for loopback_unverified
aiguard mcp scan --report                  # also send the counts per agent to the panel
```

The panel ("MCP servers") shows per server and tool how many messages were cleaned, blocked,
asked to confirm and confirmed, how many tools were hidden (changed or unapproved), and the
latest scan counts per key and agent; counts only.

Exit code 1 when any server is `not_covered` or `unreadable`, so the command fits a device
management compliance script. It is read-only, sends nothing anywhere, and prints only client,
scope, server name, file and status (never commands, arguments, URLs, headers or `env`).

The scan finds; managed settings prevent. Generate them for all three agents from one list of
approved servers (the `.mcp.json` shape, with each server's own command; an HTTP server must be
the local `aiguard mcp http` URL):

```sh
aiguard mcp allowlist --servers approved.json --gateway-url https://aiguard.example.com \
    --out aiguard-mcp-allowlist
```

| Agent | File | How it enforces | Verified |
|---|---|---|---|
| Claude Code | `claude-code/managed-mcp.json` (fixed set) or `managed-settings-mcp.json` (allow list) | Users cannot add other servers; `serverCommand` must match the whole wrapped command | against [the managed-MCP docs](https://code.claude.com/docs/en/managed-mcp) |
| Codex CLI | `codex/requirements.toml` to `/etc/codex/requirements.toml`, `%ProgramData%\OpenAI\Codex\requirements.toml` or MDM `com.openai.codex:requirements_toml_base64`; `codex/config.toml` for users | A server runs only if its name, executable and every argument match; others are disabled | Codex CLI 0.155.1 (`make mcp-real-e2e`): an unproxied, renamed or swapped server and a direct remote URL are disabled |
| Cursor | `cursor/hooks.json` to the enterprise hooks path (`/Library/Application Support/Cursor/hooks.json`, `/etc/cursor/hooks.json`, `C:\ProgramData\Cursor\hooks.json`); `cursor/mcp.json` for users | `beforeMCPExecution` runs `aiguard mcp cursor-hook`, which denies every tool call to a server not launched through the proxy (fail closed); a user hook cannot override a deny | hook contract from [Cursor's hooks docs](https://cursor.com/docs/agent/hooks); not run in a real Cursor |
| Cursor Enterprise | `cursor/dashboard-allowlist.txt` | Paste into Team Settings > MCP Configuration | entry format from vendor guides only |

The files hold no key (they refer to `AIGUARD_KEY`). Limits: anything listening on an allowed
loopback port is admitted, so run the HTTP proxy as a managed service on a fixed port. The
Cursor hook checks tool calls; resources a user attaches by hand are not hooked.

Every JSON-RPC message, including ping and empty results, now requires gateway inspection
and audit; `_meta` is not a bypass. Unavailable inspection blocks both directions. Server
stderr is discarded, while its exit code is preserved. Only Grodmir's metadata diagnostics
appear on the proxy's stderr. In enforce mode a matching model-routing rule is refused: this
proxy cannot send the message to that model destination or claim its trusted status.
