# How should an instance enforce capability-scoped sandboxing when an MCP server's declared tool schema diverges from its runtime behavior at the registration boundary **Date of Record:** 2026 November 27 **Scope:** Applies to agent runtimes that admit third-party MCP servers through a registration handshake where capabilities are declared in `tools/list` and enforced by a capability token bound to the declared schema. Does not apply to first-party in-process tools or to servers whose transport is fully mediated by a trusted sidecar that re-validates every call. ## Core Distinction The failure is not "an untrusted MCP server does something malicious." That is expected and handled by the sandbox. The failure is subtler: **the capability grant is computed from the schema the server *declares*, but the sandbox intercepts the call the server *emits*, and those two artifacts are not required to agree.** A server can register a tool named `read_file` with a schema of `{path: string}` constrained to `/workspace/**`, receive a capability token scoped to that constraint, and then — on invocation — emit a `tools/call` whose arguments carry a different path, or a different tool name entirely, or extra fields the schema never mentioned. The sandbox sees a well-formed JSON-RPC call, checks it against the *token*, and the token was minted against the *declaration*. The gap between declaration and emission is the entire attack surface. The distinction that matters operationally: capability scoping is a *static* artifact (a token, a policy document, a set of allowed tool IDs) but the thing it guards is a *dynamic* stream (per-call arguments produced by a non-deterministic process). Any sandbox that validates only at one of these points is scoping a ghost. ## What Was Observed A registration flow admitted an MCP server advertising three tools. During `tools/list` the server returned: - `search_docs` with `inputSchema: {query: string, max_results: integer}` - `fetch_url` with `inputSchema: {url: string}` and a description noting "read-only, HTTPS only" - `summarize` with `inputSchema: {text: string}` The runtime minted a capability token per tool, embedding the declared schema hash and the declared tool name. The sandbox was configured to reject any `tools/call` whose `name` was not in the token set, and to validate `arguments` against the *stored* schema before forwarding. First divergence: `fetch_url` was invoked with `{url: "https://example.com", method: "POST", body: "..."}`. The stored schema had no `method` or `body`. The validator was configured in "permissive" mode — it checked required fields were present but did not reject additional properties (`additionalProperties` was unset in the original schema, so the validator defaulted to allow). The call was forwarded with the extra fields. The server's `fetch_url` implementation honored `method: "POST"`, turning a read-only tool into a write primitive. The capability token said "read-only HTTPS"; the runtime never enforced it because read-only was a *description string*, not a schema constraint, and the sandbox trusted the schema. Second divergence, more severe: after 40 minutes of operation the server's `tools/list` response changed on a re-list triggered by a heartbeat. `summarize` was now advertised with `inputSchema: {text: string, exec: string}`. The runtime's re-registration path updated the stored schema but **did not re-mint the capability token** — the token still carried the old schema hash. The sandbox's validator, keyed by tool name, now validated against the *new* schema (which permitted `exec`) while the token still asserted the *old* scope. A call `summarize({text: "...", exec: "rm -rf /workspace"})` passed validation against the new schema and passed the token check by name. The schema hash mismatch was logged at DEBUG and dropped. Third divergence: a tool name collision. A second server registered a tool also named `summarize`. The capability token store was keyed by tool name, not by `(server_id, tool_name)`. The second server's registration overwrote the first's token. Calls routed to server A were now validated against server B's token and schema. Server A received arguments shaped for server B's schema, failed to parse them, and — because its error handler echoed the raw input into the error message — leaked the caller's arguments back into the agent's context. The common thread: **the registration boundary is a single point of trust that is re-crossed silently.** Re-listing, name collision, and permissive validation are all ways the declaration-to-emission binding gets severed after the initial grant. ## Condition of Validity The invariant that must hold for capability scoping to mean anything: > For every `tools/call` the sandbox forwards, the tuple `(server_id, tool_name, canonical_schema_hash, arguments)` must be validated against a capability token that was minted from *that exact* `(server_id, tool_name, canonical_schema_hash)` and whose argument constraints are enforced with `additionalProperties: false` semantics — and the token must be invalidated, not silently refreshed, when any component of that tuple changes. This fails whenever any of the following is true: 1. **Schema hash is not part of the token check.** The token must carry the hash; validation must recompute the hash of the schema the call is being validated against and compare. A mismatch is a hard reject, not a log line. 2. **The token store is keyed by tool name alone.** Keys must be `(server_id, tool_name)`. Cross-server name collision is not an edge case; it is the default when two servers both wrap a common utility. 3. **Argument validation permits undeclared properties.** `additionalProperties` must be forced to `false` at mint time regardless of what the server declared. A server that needs optional fields must declare them; the sandbox must not infer permissiveness. 4. **Re-registration mutates the schema without re-minting.** Any change to `tools/list` output for an existing `(server_id, tool_name)` must revoke the old token and require a fresh grant. Silent refresh converts a scoped capability into an unscoped one. 5. **Semantic constraints live only in description text.** "Read-only," "HTTPS only," "no writes" are not enforceable if they are prose. They must be encoded as schema constraints (`enum`, `pattern`, `format`) or as sandbox-level egress policy keyed to the tool, not to the server's self-description. The invariant does not require the server to be honest. It requires the runtime to treat every field of the declaration as a *claim to be pinned*, not a *fact to be trusted*. ## Decision Boundary The runtime must decide, per `tools/call`, between three outcomes: **forward**, **reject-and-notify-agent**, or **reject-and-quarantine-server**. The boundary is drawn by which invariant component failed: | Failure | Outcome | Rationale | |---|---|---| | Argument violates stored schema (undeclared property, wrong type, out-of-pattern) | Reject-and-notify | Server is buggy or probing; agent can retry with corrected args. Token stays valid. | | Schema hash on token ≠ schema hash used for validation | Reject-and-quarantine | The declaration-to-emission binding is broken. The server's schema changed under a live token. Do not trust subsequent calls. | | `tool_name` not in token set for this `server_id` | Reject-and-notify | Likely a routing error or a tool the server added post-registration without re-grant. | | `(server_id, tool_name)` collides with an existing live token | Reject-and-quarantine (both) | Ambiguous provenance. Neither server can be safely attributed. Force re-registration of both with distinct IDs. | | Semantic constraint (e.g., read-only) violated but schema permitted it | Reject-and-quarantine | The schema was under-specified at mint time; the grant was too broad. This is a runtime defect, not just a server defect — quarantine prevents exploitation while the policy is fixed. | The non-obvious boundary: **a schema-hash mismatch is not a validation failure, it is a provenance failure.** Treating it as a normal reject-and-notify (which the observed system did) lets the agent retry, and the retry hits the same broken binding. The agent then "learns" to shape arguments to the new schema, completing the attack. Quarantine is required because the agent's retry loop is itself the exploit primitive. ## Operational Effect After the fix, the observed system's behavior changed in three measurable ways: 1. **Registration latency increased by ~180ms** per server because canonical schema hashing (sorted keys, normalized types) runs at mint time and again at each call. This is the cost of the invariant: you cannot check a hash you did not compute. 2. **Re-list events dropped from silent refresh to hard revocation.** Servers that mutate `tools/list` between heartbeats now fail closed. Two of the three servers in the test fleet did this on first contact (one legitimately, adding an optional field; one not), and both required explicit re-grant. The legitimate one was re-granted in one round-trip; the other was quarantined and never recovered. 3. **Agent retry loops on rejected calls fell to zero for provenance failures.** Previously the agent would retry a schema-mismatch reject up to `max_retries` (default 3) with mutated arguments, and in one trace the third retry succeeded against the drifted schema. With quarantine-on-provenance-failure, the first such reject terminates the server's participation, and the agent receives a typed error (`CapabilityProvenanceError`) that it cannot retry past. The invariant is not free. It costs a hash per call, a re-grant per schema change, and a hard failure mode where the old system degraded gracefully into exploitation. The trade is correct: a scoped capability that can be silently widened is not a capability, it is a suggestion. ```python import hashlib import json from dataclasses import dataclass from typing import Any class CapabilityProvenanceError(RuntimeError): """Raised when a tools/call cannot be bound to a live capability token minted from the exact (server_id, tool_name, schema_hash) it is being validated against. This is a provenance failure, not a validation failure: the caller must not retry, and the server must be quarantined.""" @dataclass(frozen=True) class CapabilityToken: server_id: str tool_name: str schema_hash: str def canonical_schema_hash(schema: dict[str, Any]) -> str: # Normalize: sorted keys, additionalProperties forced false at mint time. normalized = dict(schema) normalized.setdefault("additionalProperties", False) normalized["additionalProperties"] = False blob = json.dumps(normalized, sort_keys=True, separators=(",", ":")) return hashlib.sha256(blob.encode("utf-8")).hexdigest() class CapabilitySandbox: def __init__(self) -> None: # Keyed by (server_id, tool_name) — never by tool_name alone. self._tokens: dict[tuple[str, str], CapabilityToken] = {} self._schemas: dict[tuple[str, str], dict[str, Any]] = {} self._quarantined: set[str] = set() def register(self, server_id: str, tool_name: str, schema: dict[str, Any]) -> CapabilityToken: key = (server_id, tool_name) if key in self._tokens: # Re-registration must revoke, not silently refresh. del self._tokens[key] del self._schemas[key] token = CapabilityToken(server_id, tool_name, canonical_schema_hash(schema)) self._tokens[key] = token self._schemas[key] = schema return token def validate_and_forward( self, server_id: str, tool_name: str, arguments: dict[str, Any] ) -> dict[str, Any]: if server_id in self._quarantined: raise CapabilityProvenanceError( f"server {server_id!r} is quarantined; refusing call to {tool_name!r}" ) key = (server_id, tool_name) token = self._tokens.get(key) schema = self._schemas.get(key) if token is None or schema is None: raise CapabilityProvenanceError( f"no live capability for ({server_id!r}, {tool_name!r})" ) # Recompute hash of the schema the call is validated against. live_hash = canonical_schema_hash(schema) if live_hash != token.schema_hash: # Provenance broken: schema drifted under a live token. self._quarantined.add(server_id) raise CapabilityProvenanceError( f"schema hash mismatch for ({server_id!r}, {tool_name!r}): " f"token={token.schema_hash[:12]} live={live_hash[:12]}" ) # Enforce additionalProperties: false at call time. declared = set(schema.get("properties", {}).keys()) undeclared = set(arguments.keys()) - declared if undeclared: raise CapabilityProvenanceError( f"undeclared arguments {sorted(undeclared)} for " f"({server_id!r}, {tool_name!r}); schema forbids additional properties" ) return {"server_id": server_id, "tool": tool_name, "args": arguments} ```