Metadata-Version: 2.4
Name: onewolf-mcp-guard
Version: 0.15.0
Summary: OneWolf AI Security - MCP stdio proxy (enforced security for any MCP server)
Author: OneWolf Team
License: MIT
Project-URL: Homepage, https://github.com/onewolf-ai/onewolf-guard
Project-URL: Repository, https://github.com/onewolf-ai/onewolf-guard
Project-URL: Issues, https://github.com/onewolf-ai/onewolf-guard/issues
Keywords: ai-security,mcp,model-context-protocol,llm-guard,proxy
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Topic :: Security
Requires-Python: >=3.10
Description-Content-Type: text/markdown
Requires-Dist: httpx>=0.25.0
Requires-Dist: anyio>=4.0.0
Provides-Extra: dev
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Requires-Dist: respx>=0.21; extra == "dev"
Requires-Dist: keyring>=24.0; extra == "dev"
Requires-Dist: keyrings.alt>=4.0; extra == "dev"
Requires-Dist: mcp<3,>=2.0; extra == "dev"
Provides-Extra: keyring
Requires-Dist: keyring>=24.0; extra == "keyring"
Provides-Extra: mitm
Requires-Dist: mitmproxy>=10.0; extra == "mitm"
Provides-Extra: metrics
Requires-Dist: prometheus_client>=0.17.0; extra == "metrics"

# OneWolf MCP Guard

Transparent security proxy for MCP servers. Sits between any MCP client (Cursor, Claude Desktop, MCP Inspector) and any MCP server, intercepting `tools/call` traffic and running OneWolf security checks **automatically** — no code changes needed in the wrapped server.

## What it does

```
MCP client → onewolf-mcp-guard (proxy) → real MCP server
              ↕
         OneWolf API (analyze + filter-output)
```

For every `tools/call`:
1. **Before forwarding:** sends tool name + arguments to OneWolf `/api/v1/analyze`. If prompt injection / exfiltration is detected, the call is **blocked** (JSON-RPC error returned to client, never reaches the wrapped server).
2. **After response:** sends the response text to OneWolf `/api/v1/extension/filter-output`. If PII / credentials / secrets are detected, the response is **sanitized** before reaching the client.

For every `tools/list` response (anti tool-poisoning):
- Each advertised tool (name + description + inputSchema) is analyzed via OneWolf `/api/v1/analyze`. In **enforce** mode a tool whose description carries injected instructions is **removed from the listing** before it reaches the host; in **monitor** mode the full listing passes through and the tool is only logged (`tools_list_would_remove`). Verdicts are cached per listing (SHA-256) so identical re-lists skip the backend.

A `tools/call` is intercepted **with or without `id`**: a notification-shaped
call (no `id`) is executed normally by MCP servers, so it goes through the same
gates. JSON-RPC 2.0 forbids answering a notification, so a refusal there is a
silent **drop** (audited as `notification_dropped`) instead of an error frame.
A `tools/call` carrying an explicit `"id": null` is a request (the key is
there, so it gets an answer) but is **refused**: the id is what correlates a
response to its call, so a null id would mean the response came back
unfiltered. The guard never forwards a call whose response it cannot inspect.

Everything else (initialize, other notifications, ping) passes through unchanged.

## Installation

```bash
pip install onewolf-mcp-guard
```

For secure API key storage in the OS keyring (`--use-keyring`):

```bash
pip install "onewolf-mcp-guard[keyring]"
```

Or, from a checkout of this repository, for development:

```bash
pip install -e ".[dev]"
```

Python 3.10+ required.

## Configuration

### Core

| Variable | Required | Default | Description |
|---|---|---|---|
| `ONEWOLF_API_KEY` | yes* | — | Your OneWolf API key (*not required when `ONEWOLF_USE_KEYRING=1`) |
| `ONEWOLF_USE_KEYRING` | no | — | When exactly `"1"`, read the API key from the OS keyring instead of `ONEWOLF_API_KEY` (see [Enterprise / Fleet install](#enterprise--fleet-install)) |
| `ONEWOLF_URL` | no | `http://localhost:8001` | Backend API URL |
| `ONEWOLF_TIMEOUT` | no | `30` | Legacy global timeout (used for HTTP client setup) |
| `ONEWOLF_GUARD_MODE` | no | `enforce` | **Emergency kill-switch only** (card #3865). `enforce` (block on threat) or `monitor` (log only, does not block the request; see the response-side exceptions under Modes). Setting it by hand is logged locally as `local_posture_override` and shipped as `metadata.kill_switch` — the org's enforcement posture comes from the backend, not from this variable |
| `ONEWOLF_MCP_SERVER_NAME` | no | _(derived)_ | Registry **identity** of the wrapped server. Written by the installer from the `mcpServers` key; when absent it is derived from the wrapped command. It grants nothing — a name the org has not registered gets the backend's `not_registered` verdict |

### Hardening (A2)

| Variable | Default | Description |
|---|---|---|
| `ONEWOLF_GUARD_TIMEOUT_ANALYZE` | `10` | Per-call timeout (seconds) for `/api/v1/analyze` — kept short so a slow API doesn't slow down tool calls |
| `ONEWOLF_GUARD_TIMEOUT_FILTER` | `5` | Per-call timeout for `/api/v1/extension/filter-output` |
| `ONEWOLF_GUARD_BREAKER_THRESHOLD` | `5` | Consecutive errors that open the circuit breaker (fail-fast without network until cooldown) |
| `ONEWOLF_GUARD_BREAKER_COOLDOWN` | `30` | Seconds the breaker stays open before transitioning to half-open (single probe call) |
| `ONEWOLF_GUARD_TOOL_ALLOWLIST` | _(unset)_ | **RETIRED (card #3865) — no effect.** Kept only to warn: setting it prints a stderr notice, logs `local_posture_override`, and ships `metadata.legacy_tool_allowlist`. Which tools may run is decided exclusively by your org's Tool Policy |
| `ONEWOLF_GUARD_MAX_CONCURRENT` | `10` | Max in-flight `tools/call` requests being analyzed/filtered in parallel |
| `ONEWOLF_GUARD_PENDING_TTL` | `300` | Seconds after which an unanswered `tools/call` is dropped from the pending map (memory leak prevention) |
| `ONEWOLF_MCP_MAX_TOOL_IMAGES_PER_SESSION` | `50` | Card #6199: distinct images (by sha256) returned by `tools/call` that one session may send to the Document Shield. `0` blocks every tool image; invalid or outside 0-1000 falls back to `50` |

## Installer 1-clique

Instead of hand-editing the client config, let the guard write the entry for you:

```bash
# Cursor (~/.cursor/mcp.json)
onewolf-mcp-guard install \
  --target cursor \
  --wrap "python -m my_mcp_server" \
  --server-name my-server-guarded \
  --api-key your-api-key

# Claude Desktop (auto-detected per OS)
onewolf-mcp-guard install \
  --target claude \
  --wrap "python -m my_mcp_server" \
  --server-name my-server-guarded \
  --api-key your-api-key
```

The installer detects the config location, reads the existing JSON, inserts (or
overwrites) the `--server-name` entry under `mcpServers`, and writes it back
**atomically** — other servers and other top-level keys are preserved, and a
failed write can never corrupt an existing config. Re-running with the same
`--server-name` is idempotent (it overwrites in place, never duplicates).

| Flag | Required | Description |
|---|---|---|
| `--target` | yes | `cursor`, `claude`, `windsurf`, `cline` or `claude-code` |
| `--wrap` | yes | Command to wrap, e.g. `"python -m my_mcp_server"` |
| `--server-name` | yes | Name of the `mcpServers` entry to insert/overwrite |
| `--api-key` | yes | OneWolf API key (stored in plaintext unless `--use-keyring` — see warning below) |
| `--use-keyring` | no | Store the API key in the OS keyring and write only `ONEWOLF_USE_KEYRING=1` to the config (no plaintext) — see [Enterprise / Fleet install](#enterprise--fleet-install) |
| `--url` | no | Sets `ONEWOLF_URL` in the entry's `env` |
| `--mode` | no | **DEPRECATED (card #3865) — no effect.** Prints a notice and writes nothing; the enforcement posture is not stored in the client config |
| `--config-path` | no | Override the auto-detected config path |

**Config path detection**

| Target | Path |
|---|---|
| `cursor` | `~/.cursor/mcp.json` |
| `claude` (macOS) | `~/Library/Application Support/Claude/claude_desktop_config.json` |
| `claude` (Windows) | `%APPDATA%\Claude\claude_desktop_config.json` |
| `claude` (Linux) | **unsupported** — Claude Desktop has no official Linux build; the installer aborts with exit 1 rather than write a useless path. Use `--target cursor` or `--config-path`. |
| `windsurf` | `~/.codeium/windsurf/mcp_config.json` |
| `cline` | `<app>/User/globalStorage/saoudrizwan.claude-dev/settings/cline_mcp_settings.json` for each of Code, Code - Insiders, Cursor, Windsurf, VSCodium (`%APPDATA%\<app>` / `~/Library/Application Support/<app>` / `~/.config/<app>`), plus `~/.cline/mcp_settings.json` |
| `claude-code` | `~/.claude.json` (top-level **and** `projects.<dir>.mcpServers`) and `~/.claude/mcp.json`; both inside `$CLAUDE_CONFIG_DIR` when it is set. A project's `.mcp.json` (in the repository) is never written. |

`windsurf`, `cline` and `claude-code` are written **only when the file already
exists** — the guard never creates the config of an app that is not installed
(`install --target <one of them>` fails unless `--config-path` is given).

Every rewrite (card #5427) refuses a config that is a symlink / reparse point,
has extra hard links or is owned by another user; keeps a one-time
`<file>.onewolf.bak`; aborts if the client changed the file meanwhile; and
changes only `command` / `args` / `env` of a wrapped entry (keys such as
Cline's `disabled` / `autoApprove` are kept). `onewolf-mcp-guard teardown
[--targets ...]` undoes `setup`.

The generated entry runs the exact runtime form the proxy expects
(`onewolf-mcp-guard --wrap "..."`), so the installer only *writes* config — it
never changes how the proxy launches.

> ⚠️ **Plaintext API key.** By default the `--api-key` value is stored **in
> plaintext** inside the config file (`env.ONEWOLF_API_KEY`), exactly as it
> would be if you edited the file by hand. Treat the config file as a secret and
> set filesystem permissions accordingly — **or** pass `--use-keyring` to keep
> the key out of the file entirely (see
> [Enterprise / Fleet install](#enterprise--fleet-install)).

Empty/missing `--api-key`, `--wrap`, or `--server-name`, and an invalid/missing
`--target`, all abort with exit 1 **before any file is touched** (fail-closed).
A pre-existing config whose JSON is malformed, or whose root is not an object,
also aborts with exit 1 and is left untouched.

## Enterprise / Fleet install

Shipping the same `mcp.json` across a fleet of machines means shipping the API
key in plaintext — where secret scanners (truffleHog, git-secrets), config
repos, and support screenshots all pick it up. Pass `--use-keyring` to store the
key in the **OS keyring** (macOS Keychain, GNOME Keyring / KWallet, Windows
Credential Store) and write only a flag to the config:

```bash
pip install "onewolf-mcp-guard[keyring]"

onewolf-mcp-guard install \
  --use-keyring \
  --target cursor \
  --wrap "python -m my_mcp_server" \
  --server-name my-server-guarded \
  --api-key your-api-key
```

The generated entry contains **no** `ONEWOLF_API_KEY` — only
`"ONEWOLF_USE_KEYRING": "1"`:

```json
{
  "mcpServers": {
    "my-server-guarded": {
      "command": "onewolf-mcp-guard",
      "args": ["--wrap", "python -m my_mcp_server"],
      "env": {
        "ONEWOLF_USE_KEYRING": "1"
      }
    }
  }
}
```

At runtime, when `ONEWOLF_USE_KEYRING=1` the proxy reads the key from the
keyring instead of `ONEWOLF_API_KEY`. The behaviour is **strict and
fail-closed**:

- The mode engages **only** when the value is exactly `"1"`; any other value
  (`"0"`, `"true"`, empty, absent) uses the plaintext `ONEWOLF_API_KEY` path.
- With keyring mode on, `ONEWOLF_API_KEY` is **ignored** — it is never a silent
  fallback.
- If the keyring has no key (or the `keyring` lib is not installed), the proxy
  **does not start**: it exits 1 with a readable message. No silent bypass.
- `install --use-keyring` also fails closed: an empty `--api-key`, a missing
  `keyring` lib, or an unavailable (headless) keyring backend aborts with exit 1
  and **nothing is written** — not to the config file, not to the keyring.

The key is stored under service `onewolf-mcp-guard`, account `api-key`.
Re-running the installer overwrites the same entry (idempotent). To rotate or
remove the key, re-run the installer or delete the keyring entry directly:

```bash
python -c "import keyring; print(keyring.get_password('onewolf-mcp-guard','api-key'))"
python -c "import keyring; keyring.delete_password('onewolf-mcp-guard','api-key')"
```

> **Note.** Migrating an existing plaintext config is manual: re-run the
> installer with `--use-keyring` (it overwrites the entry and drops the
> plaintext key).

## Setup — Cursor (manual)

Edit `.cursor/mcp.json`:

```json
{
  "mcpServers": {
    "my-server-guarded": {
      "command": "onewolf-mcp-guard",
      "args": ["--wrap", "python -m some_mcp_server"],
      "env": {
        "ONEWOLF_API_KEY": "your-api-key",
        "ONEWOLF_URL": "http://localhost:8001"
      }
    }
  }
}
```

Toggle the server off/on in Cursor Settings → MCP to load. The wrapped server's tools appear normally — the guard is transparent.

## Setup — wrapping the OneWolf MCP server

```json
{
  "mcpServers": {
    "onewolf-guarded": {
      "command": "onewolf-mcp-guard",
      "args": ["--wrap", "python -m onewolf_mcp"],
      "env": {
        "ONEWOLF_API_KEY": "your-api-key",
        "ONEWOLF_URL": "http://localhost:8001"
      }
    }
  }
}
```

## Modes

**enforce** (default):
- Blocks malicious requests
- Fail-closed when OneWolf API is unreachable (request and response both blocked)
- Fail-closed on oversized payloads (>100k chars cannot be analyzed safely)
- Fail-closed when the circuit breaker is open
- Blocks a tool your organization's Tool Policy denies, and a server the org's registry has not marked trusted (`not_registered`, `disabled`, `blocked`, `untrusted`)

**monitor**: logs decisions and does not block the *request*. Useful for measuring impact before going to enforce in production. Fail-open in this mode (including breaker-open and registry/Tool Policy denials — all forwarded with `request_would_block` log entries). Exceptions on the response side, which apply in both modes: a `redact` verdict on a `tools/call` response masks it (the data has already left the server, so Monitor never hands the client an unmasked `tools/call` leaf); a secret in a response blocks (#1371); a `tools/call` response that cannot be masked leaf by leaf (`leaf_rewrite_unsafe`, #5424) is refused (JSON-RPC `-32600`); and an exception raised by the `tools/call` response handler itself is refused the same way (#5482). A backend that is unreachable or returns an error in this mode follows the degraded posture (`degraded_block`), it is not refused unconditionally. Since card #3865 the mode is an emergency kill-switch rather than a configuration knob: it still works, but every backend consultation carries `metadata.kill_switch` so the organization can see which machines opted out.

### Monitor mode — deploy prerequisite for the would-block gate

Before enabling enforce in production we run the guard in **monitor mode** to measure the **would-block rate** — the fraction of (assumed-mostly-benign) MCP traffic that *would* have been blocked. The gate to graduate to enforce is a sustained **would-block rate < 0.5%** over 1–2 weeks. Set the mode **explicitly** on the wrapped server — an invalid value falls back to `enforce` (with a stderr warning), which would start blocking real traffic:

```json
{
  "mcpServers": {
    "my-server-guarded": {
      "command": "onewolf-mcp-guard",
      "args": ["--wrap", "python -m some_mcp_server"],
      "env": {
        "ONEWOLF_API_KEY": "your-api-key",
        "ONEWOLF_URL": "http://localhost:8001",
        "ONEWOLF_GUARD_MODE": "monitor"
      }
    }
  }
}
```

In this mode the proxy **does not block requests** — every `tools/call` is forwarded, and would-be blocks are recorded as `request_would_block` log lines. The response-side exceptions listed under **monitor** above (redact, secret, `leaf_rewrite_unsafe`, filter failure) still apply. **Enforce stays OFF in this phase**; the toggle to enforce is a separate, deliberate operational change made only after the gate is met.

**Telemetry behind the gate.** Each `tools/call` the proxy analyzes is tagged at the backend with `source="mcp_guard"`:

- Non-allowed events land in `guard_logs` with `source='mcp_guard'` for qualitative inspection of what *would* have been blocked.
- The backend Prometheus counter `guard_intercept_total{source="mcp_guard", action=...}` increments on **every** analysis — `allowed` included — so the would-block rate has both a numerator (`action="blocked"`) and a denominator (all actions). The Grafana dashboard **OneWolf – Security → MCP Guard – Monitor Mode** renders the total and the `blocked / total` would-block rate. (`guard_logs` alone can't supply the denominator — it never persists `allowed` events.)

## Circuit breaker

After `ONEWOLF_GUARD_BREAKER_THRESHOLD` consecutive errors hitting the OneWolf API, the breaker **opens** and every subsequent call fails fast without touching the network until `ONEWOLF_GUARD_BREAKER_COOLDOWN` seconds elapse. The breaker then transitions to **half-open** — the next call is a probe. Success closes the breaker; failure reopens it with a fresh cooldown.

**Auth errors (401) do NOT trip the breaker** — they signal a config problem, not API health. Retries wouldn't help.

## Retries

The guard performs **one retry on `ConnectError`** with a 500ms backoff. Timeouts and HTTP error responses are **not** retried — retrying a timeout would double the worst-case latency budget, and the backend is the authority on HTTP errors.

## Who decides: the organization, not the machine (card #3865)

The client applies; the backend decides. Two decisions used to live on the user's machine and no longer do.

**The local tool allowlist is retired.** `ONEWOLF_GUARD_TOOL_ALLOWLIST` short-circuited a `tools/call` *before* the backend was ever asked, so it could both refuse a tool the organization allows and wave through a tool the organization forbids — invisibly, from a variable any user of the machine can edit. It was also fail-open by construction: an empty list meant "everything allowed". Which tools may run is now answered only by `POST /api/v1/tool-policies/check`, which is **deny-by-default** — no policy for a tool means the tool is denied, never allowed.

Setting the variable today changes no decision. It prints one stderr notice at boot, emits a `local_posture_override` log line, and tags every `/analyze` call with `metadata.legacy_tool_allowlist`. The same applies to a hand-set `ONEWOLF_GUARD_MODE`, which still works as an emergency kill-switch (card #3617) but no longer does so invisibly.

**The server registry is always consulted.** `POST /api/v1/mcp/check` used to run only when `ONEWOLF_MCP_SERVER_NAME` or `ONEWOLF_MCP_SERVER_ID` was set — leaving a variable unset opted a machine's MCP servers out of the organization's registry entirely, and the org never learned the server existed. The identity now always resolves: the installer writes the `mcpServers` key as `ONEWOLF_MCP_SERVER_NAME`, and when it is absent one is derived from the wrapped command. Every `tools/call` asks the registry, and the backend's verdict travels verbatim:

- `enforce` → a server the org marked `disabled`, `blocked` or `untrusted` is refused, with the backend's own `reason`;
- `monitor` → the call is forwarded and the verdict recorded as `request_would_block`;
- `not_registered` is a deny in `enforce` too, for every identity: `POST /api/v1/mcp/report` (card #3867) reports the wrapped server on every start, so an unregistered server is one the admin can see in the Shadow-MCP inventory and enrol — not one the guard has to wave through.

**How a derived identity is built, and why it looks like that.** It is `<stem of argv[0]>-<32 hex of sha256 of the whole argv>` — for example `npx-3f2a…`. Deliberately not prettier:

- *Only `argv[0]` contributes readable text.* An earlier design walked the arguments to produce `server-filesystem` instead of `npx`, rejecting credential-shaped tokens. That cannot be made safe: MCP servers take secrets as plain flag values (`npx --auth-token ghp_…`, `uvx --password … pkg`), and an opaque token is shaped exactly like a package name. The identity is written to stderr and shipped to `/mcp/check`, `/mcp/report` and `metadata.mcp_server` on every call, so a leak there would reach the SaaS on every install.
- *The digest covers the whole argv.* Without it a derived name could equal a name an administrator registered — and the backend matches names exactly and answers `trusted` on a hit, with nothing binding that name to the command actually running. `npx -y @evil/server-filesystem` would have inherited the ALLOW of the legitimate `server-filesystem`. 128 bits keeps a targeted second preimage out of reach once orgs start enrolling derived identities.
- *Consequence:* a server whose argv changes between launches (a per-session port, token or temp path) derives a different identity every start and cannot be enrolled. Give those an explicit `ONEWOLF_MCP_SERVER_NAME` — which is what the installer writes anyway. The resolved identity is printed at boot as `server_identity_resolved`, so an admin can copy it straight into the registry.

**`tools/list` verdicts expire.** The anti-poisoning verdict cache had no TTL: a listing scanned once stayed "clean" for the life of the process, so a server that poisoned a description afterwards kept its stale approval until the IDE restarted. Entries now expire (300s ceiling), the organization can shorten that with `cache_ttl_seconds`, and a change of `policy_version` drops the cache wholesale.

### Known gaps — stated, not hidden

**An unregistered server is denied — every identity, no grace.** An earlier revision of this card forwarded `not_registered` as a would-block whenever the identity was *derived*, because the only automatic enrolment path was `POST /api/v1/mcp/report` and that route did not exist: a hard deny would have refused 100% of tool calls with nothing the user or the org could do. Card #3867 shipped the route (`backend/app/api/mcp_servers.py::report_mcp_server`, authenticated with the very org credential the guard already carries), and the guard already POSTs to it on every start. With enrolment alive the grace had nothing left to wait for, and keeping it would have been a plain fail-open in a blocking layer — an unregistered MCP server is the exact shape of the shadow server this gate exists to stop.

| Situation | Verdict |
|---|---|
| `blocked` / `untrusted` / `disabled` / `not_registered` | hard deny in `enforce`, `request_would_block` in `monitor` |
| registry error, timeout, breaker open, no identity at all | fail-closed deny in `enforce` |
| registry feature off (503) or `/mcp/check` absent (404) | skip — a control the server does not expose cannot be enforced by the client |


**The posture signals are not persisted yet.** `metadata.kill_switch` and `metadata.legacy_tool_allowlist` are sent on every `/analyze` call, but the backend's metadata allowlist (`_mcp_context_extra` in `backend/app/api/guard_analyze.py`) currently emits only `mcp_context`, `mcp_tool_name`, `mcp_server` and `mcp_mode`, so they are dropped on arrival. Until the backend card widens that allowlist, the guard's own `local_posture_override` log line is where an operator can see the override.

**The org owns what happens when a gate has no verdict.** `POST /api/v1/tool-policies/check` — the call the guard already makes on every `tools/call` — now carries the org's posture in an additive `defaults` block, built by the same `build_defaults_payload` that serves the extension (`GET /org-policy-map/defaults`) and the endpoint agent (`GET /endpoint/domains`). One source, three surfaces, so they cannot diverge inside one organization.

The guard applies `degraded_action` at all **five** degraded points — `/analyze`, `filter-output`, `tools/list`, a registry check that produced no verdict, and a tool-policy check that produced no verdict — from a single resolution (`posture.resolve`), so the org's choice cannot be honoured on one path and ignored on another. `on_expired` and `valid_until` retire a posture the guard can no longer vouch for.

The boundary is "no verdict", not "a verdict I dislike": an **explicit** deny — the org's Tool Policy, or a registry `blocked` / `untrusted` / `disabled` / `not_registered` — is never softened by `degraded_action`. Letting the posture govern both would let `degraded_action=allow` repeal the Tool Policy.

Three rules, mirroring `onewolf_endpoint/enforcement.py`:

- *no contract yet* → the pre-card behaviour byte for byte (fail-closed in `enforce`, forward in `monitor`), so no installed fleet changes because of this code;
- *with a contract* → the only thing left on the machine is the emergency kill-switch of card #3617 (`ONEWOLF_GUARD_MODE`), which still disarms the guard and is reported to the SaaS on every call so the override is visible rather than silent;
- *where the contract is silent* → fail **closed**. `allow` exists only because an admin wrote `allow`, and the guard matches the vocabulary by exact equality, exactly as the backend and its `CHECK` constraint do.

### Known gaps — stated, not hidden

**Enrolment is visible, not automatic.** `POST /api/v1/mcp/report` writes to `mcp_discovered_servers` — the Shadow-MCP inventory behind `GET /api/v1/mcp/discovered` — not to the registry `check_server` reads. It makes an unregistered server *visible* to the admin, who then registers it. So on the first start after this wheel, an organization in `enforce` whose servers were never registered by hand denies every `tools/call` until an admin acts. That is fail-**closed** and it is what `enforce` means, but it is a rollout step, not a silent upgrade: check `/mcp/discovered` and register before rolling the wheel to a fleet.

**The org-level `mode` / `dry_run` is still local.** The contract carries `degraded_action`, `default_action`, `unknown_action`, `on_expired`, `on_never_received`, `ttl_seconds`, `valid_until` and `policy_version` — measured against `build_defaults_payload`, which emits exactly those nine keys — but no `mode` and no `dry_run`. So enforce-vs-monitor is still the local `ONEWOLF_GUARD_MODE`, defaulting to `enforce`. That default is the strict side, so nothing fails open while the backend card that adds org-level mode lands; wiring `mode` to today's `default_action` would be worse than the gap, since its conservative value is `monitor` and every existing org would silently disarm.

**Timeouts, breaker thresholds and `mcp_methods`.** `ONEWOLF_GUARD_TIMEOUT_*` and `ONEWOLF_GUARD_BREAKER_*` remain local knobs: the contract has no field for them (`grep -rn 'mcp_methods' backend/app` returns nothing). They tune latency, not permission — none of them can turn a deny into an allow.

## Concurrency

Each `tools/call` is processed in its own task, capped by `ONEWOLF_GUARD_MAX_CONCURRENT` via a semaphore. Without this cap, a flood of concurrent calls could overwhelm the OneWolf API. Writes to the wrapped server's stdin are serialized through a lock so NDJSON frames can't interleave on the wire.

## Pending TTL

If the wrapped server crashes mid-call or hangs, an entry in the internal `_pending` map would stay forever, leaking memory. A background task scans every `min(60, ttl/4)` seconds and drops entries older than `ONEWOLF_GUARD_PENDING_TTL` with a `pending_expired` log line.

## `structuredContent` redaction

MCP 2025-03-26 added an optional `structuredContent` field on tools/call results — arbitrary JSON that can carry the same data as `content[]` (often in raw form). The guard:

1. Concatenates the JSON serialization of `structuredContent` into the text analyzed by `/api/v1/extension/filter-output`, so PII in the structured payload reaches the detector.
2. On redaction, **rewrites leaf by leaf** (card #5424): each `content[i].text` and each string inside `structuredContent` is sent to the filter on its own and receives its own mask. Clean leaves stay byte-identical, non-string values (numbers, booleans, null) keep their type, and the rewritten result is checked once more as a whole. Card #5481: when the backend returns UTF-16 `spans` with the redaction, each span is mapped back to its leaf from the single analysis call (1 request per response, no leaf cap); a span that does not fall entirely inside one leaf (dict key, number, separator) is refused. Without usable spans the per-leaf rewrite above is the fallback (capped at 64 leaves).
3. If any leaf cannot be masked safely (no verdict, `block`, `redact` with no text, nothing changed leaf by leaf, more than 64 leaves, depth above 32, or residue after the rewrite), the response is **refused with a JSON-RPC error**. Partial or original content is never delivered.

**Embedded resources and off-contract shapes (card #5476).** A `content[]` block of type `resource` contributes `resource.text` to the analysis and, on redaction, is masked in place (`uri`/`mimeType` untouched). The rest of the block (`uri`, `mimeType`, `_meta`, `annotations`, extra keys; everything except `type` and `resource.text`/`resource.blob`) is analyzed too: `block` blocks, and text to mask there refuses the response (not a maskable leaf). `resource.blob` is not analyzed: a `redact` verdict on a response carrying a blob is refused with a JSON-RPC error. Off-contract shapes (`content` not a list, raw items in `content[]`, non-string `text`, non-object `resource`) are analyzed as their JSON serialization: `allow` forwards them unchanged, `block` blocks, `redact` is refused (no leaf to mask). A `resource_link` block is analyzed whole (minus `type`): `name`/`title`/`description` are masked in place, while text to mask in `uri` or an extra key refuses the response. A non-object `result` is analyzed too, on `tools/call` and on the guarded methods (`resources/read`, `prompts/get`, ...): `redact` is refused; a non-object `tools/list` result is refused in `enforce` and forwarded in `monitor` (`null` is forwarded as before). Applies in `enforce` and `monitor`.

Closes a bypass equivalent in severity to the multi-text-block bypass already covered.

## Limits

Payloads larger than **100,000 characters** (after JSON serialization of arguments, or in response text) are **refused** to prevent silent truncation bypass. In enforce mode, oversized requests are blocked; oversized responses are blocked (fail-closed). In monitor mode, both are forwarded with a log entry.

## Images returned by tools (card #6199)

Since **0.11.0**, every `image` block in a `tools/call` result (a computer-use screenshot, a browser capture) goes to the Document Shield before the text filter, in both transports. Only an `allow` verdict forwards the response; any other verdict, a Shield outage, invalid base64 or more than 16 images refuses the **whole** response (`tool_image_blocked`), like `resources/read`. Each session may send at most `ONEWOLF_MCP_MAX_TOOL_IMAGES_PER_SESSION` distinct images; a new image above that is refused. HTTP clients without `mcp-session-id` share one budget per token, reset 1 h after its first image.

**Release note:** there is no image-specific switch. A client that upgrades to 0.11.0 in `enforce` gets tool images inspected (and refused when not clean) immediately; the escape hatch is `ONEWOLF_GUARD_MODE=monitor` (whole guard) or pinning 0.10.x.

## Structured logging

The guard writes JSON log lines to stderr (one event per line):

```json
{"event":"proxy_started","executable":"C:\\Program Files\\nodejs\\npx.CMD","pid":18248}
{"event":"request_allowed","request_id":9,"tool_name":"analyze_prompt","threat_score":0.0,"time_ms":45}
{"event":"response_allowed","request_id":9,"tool_name":"analyze_prompt","time_ms":14}
{"event":"request_blocked","request_id":11,"tool_name":"scan_document","threat_score":1.0,"threats":2,"time_ms":202}
{"event":"response_modified","request_id":15,"tool_name":"get_user_data","time_ms":18}
```

Events: `proxy_started`, `request_allowed`, `request_blocked`, `request_forwarded`, `request_would_block`, `request_invalid_params`, `request_handler_error`, `response_allowed`, `response_modified`, `response_forwarded`, `response_blocked`, `pending_expired`, `proxy_shutdown`.

## Latency overhead

Measured against a healthy local backend (warm):

- **Per allowed `tools/call`:** ~60ms overhead (analyze ~45ms + filter ~15ms)
- **Per blocked `tools/call`:** ~200ms (analyze only — request never forwarded)

The original `tools/call` round-trip to the wrapped server is unchanged.

### Concurrency (A2)

Load test against a mocked backend with 50ms response time, **N=20 concurrent `check_request` calls through the interceptor**:

| Metric | Value |
|---|---|
| Wallclock for all 20 | 79 ms |
| Serial equivalent | 1000 ms (12× speedup) |
| Per-call p50 | 60 ms |
| Per-call p95 | 76 ms |

With `ONEWOLF_GUARD_MAX_CONCURRENT=3` and 10 concurrent dispatch calls, the semaphore caps in-flight at 3 (verified, max_observed = 3) — 248 ms vs 500 ms serial.

No response mixing observed across concurrent calls (each task receives the response tagged with its own `request_id`).

## Testing

```bash
pytest tests/
```

**107 unit + load tests** covering:
- NDJSON framing
- Config validation (including A2 env vars)
- Circuit breaker state transitions
- Interceptor (allow/block/error/breaker/retry paths)
- Proxy message routing (registry gate, retired allowlist no-op, pending TTL, multi-block PII bypass, structuredContent bypass)
- Load: N=20 concurrent calls (no mix, no deadlock, p95 measured)
- Load: semaphore cap enforcement (max in-flight ≤ configured limit)

CI runs the suite on **Linux, macOS, and Windows** to catch platform-specific stdio/buffering regressions.

## License

MIT
