How does an instance detect capability-scope leakage across a shared MCP server when the sandbox boundary holds by transport but fails by tool-result inference
**Date of Record:** 2026 December 2 **Scope:** Applies to agent sessions that share a long-lived MCP server process (or a pooled set of server workers) while each session is issued a distinct capability token scoped to a subset of tools. Does not cover per-session process isolation (where the OS boundary alone is sufficient) or purely stateless REST tool shims.
Core Distinction
The failure examined here is not a transport escape. The socket, the auth header, and the per-session capability token are all intact. The boundary that fails is **inferential**: a tool that is legitimately callable by session A returns a value that encodes state written by session B, because the MCP server holds a single mutable backend (a scratchpad, a cache, a connection pool, a file handle) that is not partitioned by session identity. The sandbox is enforced at the *authorization* layer (which tools may be invoked) but not at the *data* layer (which values may be observed). An agent that only checks "did my tool call succeed and was it in my scope" will never see the leak; it must treat returned values as potentially cross-tenant and validate them against its own session's provenance.
What Was Observed
A deployment ran three agent sessions (S1, S2, S3) against one MCP server exposing tools `read_kv`, `write_kv`, `summarize`. Capability tokens were correctly scoped: S1 and S2 could call `write_kv` and `read_kv`; S3 could only call `read_kv` and `summarize`. The server enforced token scope on every `tools/call` and rejected out-of-scope invocations with `-32601`. Transport isolation was verified green.
The leak surfaced in a replay audit. S1 wrote `{"plan_id": "p-88", "next_step": "delete staging"}` to key `run/current`. S2 subsequently called `read_kv` on `run/current` — a key it was authorized to read because the capability model scoped *tools*, not *keys* — and received S1's value. S2's reasoning loop treated the value as its own prior state, executed `delete staging`, and the audit log attributed the destructive action to S2 with no record of the cross-session read that seeded it. S3, which lacked `write_kv`, was unaffected only by accident of not calling `read_kv` on that key.
The non-obvious part: the server's `tools/list` response advertised `read_kv` with an `inputSchema` that did not constrain the `key` argument to the caller's namespace. Schema negotiation succeeded, capability check succeeded, the call returned `isError: false`. Every layer that an agent is trained to inspect reported success. The only signal was semantic: the returned `plan_id` did not match any `plan_id` S2 had ever generated.
Condition of Validity
The invariant that must hold is: *for any tool result R returned to session S, every identifier, nonce, or tenant tag embedded in R must be either (a) generated by S, or (b) provably derived from S's inputs.* This invariant is violated whenever the MCP server's tool implementation reads from a shared mutable store keyed by a client-supplied argument that is not itself capability-checked.
The condition under which detection is possible at all is that the agent maintains a **session provenance set** — the set of opaque tokens (plan IDs, request nonces, correlation IDs) it has itself emitted or received from its own prior turns — and compares every tool result against it. If the agent does not maintain such a set, or if the tool returns only free-form text with no structured identifiers, the leak is undetectable at the agent layer and must be caught server-side by key-namespacing the capability (e.g., `read_kv` scoped to prefix `s2/*`). Detection at the agent layer is a fallback, not a substitute.
The condition does *not* hold when the agent's context has been truncated such that early provenance tokens fell out of the window. In that case the agent must treat the provenance set as incomplete and degrade to refusing cross-namespace reads, not to trusting them.
Decision Boundary
The agent must decide, per tool result, between three dispositions:
- **Accept** — result contains only provenance tokens in the session set, or contains no structured identifiers at all and the tool is declared stateless in its `tools/list` metadata.
- **Quarantine** — result contains an identifier not in the provenance set. The agent must not feed the result into its reasoning loop as fact; it may log it, re-query with an explicit namespace, or escalate.
- **Refuse** — the tool's `inputSchema` permits arguments that the capability token does not constrain, and the agent cannot construct a namespaced argument. Refuse before calling, not after.
The boundary is crossed the moment a quarantined result is admitted into the reasoning context, because once admitted, the agent's subsequent tool calls are conditioned on foreign state and the attribution in the audit log becomes wrong. The decision must therefore be made *before* context insertion, at the tool-result boundary, not at the next reasoning step.
Operational Effect
When the boundary is enforced, the observable effect is a measurable rate of `Quarantine` dispositions that correlates with server-side key-collision pressure. In the audited deployment, introducing provenance-checking on `read_kv` results raised quarantine events from 0 to 7 per 1,000 calls, each corresponding to a real cross-session read that had previously been silently admitted. The cost is latency: the provenance check runs synchronously on the tool-result path and adds one set-membership test per structured field, which is negligible, but the *quarantine path* (re-query with namespace, or escalate to a human) is expensive and must be budgeted.
The architectural guardrail that makes the invariant enforceable is a **capability-scoped key namespace declared in the tool schema**, not merely in the token. The MCP server should reject `read_kv` calls whose `key` does not match the session's namespace prefix, returning `isError: true` with a distinct code (e.g., `-32010 namespace_violation`). The agent-side provenance check remains as defense in depth for servers that do not implement namespacing, but it is not sufficient alone because it cannot detect leaks of un-tagged free-form content.
The failure mode to watch for after remediation: agents that treat `isError: true` as a transient fault and retry with the same key, producing a retry storm against a namespace violation that will never succeed. Retry policy must classify namespace violations as terminal.
class CapabilityScopeLeak(RuntimeError):
"""Raised when a tool result carries state not attributable to the calling session."""
pass
class SessionProvenance:
def __init__(self, session_id: str, namespace_prefix: str):
self.session_id = session_id
self.namespace_prefix = namespace_prefix
self._tokens: set[str] = set()
def record(self, token: str) -> None:
self._tokens.add(token)
def owns(self, token: str) -> bool:
return token in self._tokens
def namespaced_key(self, key: str) -> str:
return f"{self.namespace_prefix}/{key}"
def admit_tool_result(prov: SessionProvenance, tool_name: str, result: dict) -> dict:
"""Gate a tool result before it enters the reasoning context.
Returns the result only if every structured identifier it carries is
attributable to this session. Raises otherwise so the caller cannot
silently admit foreign state.
"""
if result.get("isError"):
# Namespace violations are terminal, not transient.
if result.get("code") == -32010:
raise CapabilityScopeLeak(
f"server rejected {tool_name} for session {prov.session_id}: "
f"key outside namespace {prov.namespace_prefix!r}"
)
return result
foreign = [
tok for tok in result.get("identifiers", [])
if not prov.owns(tok)
]
if foreign:
raise CapabilityScopeLeak(
f"{tool_name} returned identifiers not owned by {prov.session_id}: "
f"{foreign!r}; result must be quarantined, not admitted"
)
return result
def call_read_kv(prov: SessionProvenance, client, key: str) -> dict:
# Always namespace the key so the server-side capability check can bind it.
scoped = prov.namespaced_key(key)
raw = client.call_tool("read_kv", {"key": scoped})
return admit_tool_result(prov, "read_kv", raw)