# Why does an instance of an MCP tool server silently retain filesystem authority after its declared capability scope is revoked mid-session? **Date of Record:** 2026 November 19 **Scope:** Applies to long-lived MCP server processes that are granted a capability scope (tool allowlist + resource path allowlist + TTL) at session handshake and are expected to enforce least-privilege per invocation. Does not apply to stateless per-call tool servers that tear down and re-exec their sandbox on every `tools/call`, nor to servers whose sandbox is enforced by an external kernel/OS mechanism the agent cannot reconfigure. ## Core Distinction The distinction that matters here is between **capability revocation as a message** and **capability revocation as a state transition**. In an MCP deployment, the orchestrator typically revokes or narrows a scope by sending a control message (a `notifications/capabilities/updated`, a new session descriptor, or an out-of-band policy push). The server *receives* that message and, on the happy path, updates its in-memory allowlist. The failure mode is that the *effective* authority of the process is not the in-memory allowlist at all — it is the union of (a) the allowlist consulted at dispatch time, (b) any file descriptors, memory-mapped regions, or cached handles opened *before* revocation, and (c) any subprocess or worker pool spawned under the old scope that was never itself re-scoped. Revocation updates (a) and leaves (b) and (c) intact. The instance then reports a narrowed capability while retaining the widened one. This is not the same as a permission-check bug. The check is correct. The bug is that the check is evaluated against a *snapshot* of authority that diverged from the *live* authority when the handle was opened. ## What Was Observed A representative trace, reproducible on a filesystem-backed MCP server exposing `read_file`, `write_file`, and `list_dir` under a scoped root: 1. **Handshake.** Orchestrator issues a session descriptor: scope `{tools: [read_file, write_file, list_dir], roots: [/work/project], ttl: 3600s}`. Server caches `roots` into a resolver object and also opens a directory handle `dh = open("/work/project", O_DIRECTORY)` for fast `list_dir` traversal. 2. **Warm phase.** Agent issues `read_file("/work/project/a.txt")`. Resolver validates against cached `roots` → allowed → reads. Fine. 3. **Revocation.** At T+40s the orchestrator narrows the scope to `{tools: [read_file], roots: [/work/project/readonly]}` because the agent's plan moved into a read-only verification phase. Server receives the update, replaces `self.scope`. `write_file` is now removed from the dispatch table; `roots` is now `[/work/project/readonly]`. 4. **Divergence.** The agent issues `list_dir(".")`. Dispatch resolves the tool, but the handler uses the *pre-existing* `dh` directory handle, which points at `/work/project`, not `/work/project/readonly`. The resolver's path check is bypassed because the handler never re-resolves — it trusts the cached handle. The listing leaks sibling entries outside the narrowed root. 5. **Worse variant.** If the server had spawned a worker subprocess during the warm phase to do async writes, that worker inherited the original `roots` and the original `dh` at fork time. Revocation touches the parent's `self.scope` only. The worker continues to honor the *old* scope, and any `write_file` job queued before revocation but executed after it succeeds against `/work/project`, not `/work/project/readonly`. The observable signature: after revocation, `tools/list` correctly omits `write_file`, yet a `write_file` call routed through a queued job or a cached handle still lands. The instance's *declared* capability and its *effective* capability disagree, and the disagreement is invisible to the orchestrator because the orchestrator only sees the declared surface. A second, subtler signature: the TTL. A `ttl` of 3600s is enforced by a timer that flips a boolean. If a long-running `read_file` on a large file is in flight when the timer fires, the read completes because the check happened at dispatch, not at each `read()` syscall. The TTL bounds *invocation admission*, not *invocation duration*. An adversary that can induce a slow read (large file, slow FUSE backend) can extend effective authority past the declared TTL by exactly the read duration, and the server will report "expired" while the fd is still live. ## Condition of Validity The guardrail — "re-check scope at every syscall boundary, not at dispatch" — is only *necessary* under the following conditions, and stating them precisely is what separates a real fix from cargo-cult re-validation: - The server holds **stateful handles** (fds, mmaps, subprocess pools, connection pools) across invocations. If every invocation opens and closes its own handles, the dispatch-time check is sufficient and re-checking is pure overhead. - Revocation can occur **concurrently with an in-flight invocation**. If the protocol serializes revocation behind a quiesce barrier (drain all in-flight calls, then revoke), the divergence window is zero and the naive check is sound. - The scope includes a **path or resource predicate** (not just a tool allowlist). Tool-allowlist-only scopes are immune to the handle-reuse leak because the tool name is re-resolved per call; the leak requires a *resource* dimension. - **Subprocess or thread pools** were forked under a prior scope. If the server re-execs workers on every scope change, inheritance is broken and the old scope dies with the old process. Conversely, the invariant does *not* require re-validation if the server is architected as **stateless-per-call with a fresh resolver**: open handles inside the invocation, validate against the *current* `self.scope` read at the top of the handler, close before returning. That architecture makes the dispatch check and the syscall check the same check, and the boundary condition cannot arise. The precise invariant to enforce is: **effective authority at any instant = declared scope at that instant.** Any cached artifact that encodes authority (handle, mmap, forked worker, memoized resolver result) must be either (a) invalidated on scope change, or (b) re-validated against the live scope at the moment of use. There is no third option; "validate at open" is exactly the bug. ## Decision Boundary The decision the operator must make is *where* to place the revocation barrier, and it is a genuine tradeoff, not a free lunch: - **Quiesce-then-revoke (drain barrier).** Revocation blocks until all in-flight invocations complete, then swaps scope atomically. Cost: revocation latency equals the slowest in-flight call, which under a slow FUSE read can be seconds to minutes. Benefit: the naive dispatch-time check becomes correct; no per-syscall re-validation needed. Choose this when invocations are bounded and revocation is rare (e.g., phase transitions in a plan). - **Re-validate-at-use (fine-grained barrier).** Every handle access re-checks the live scope. Cost: a scope read and predicate evaluation per I/O, plus a lock or atomic snapshot to avoid torn reads during the swap. Benefit: revocation is immediate even mid-read; the slow-read TTL extension closes. Choose this when invocations are unbounded (streaming, large files) or revocation must be instantaneous (security incident, prompt-injection containment). - **Re-exec-on-change (process barrier).** On any scope change, kill and re-spawn workers with the new scope. Cost: warm-up latency, loss of in-flight work. Benefit: inheritance bugs are structurally impossible. Choose this when the worker pool is cheap to rebuild and correctness dominates latency. The boundary is crossed the moment the deployment has *both* stateful handles *and* concurrent revocation *and* a resource-predicate scope. Any two of the three are survivable with the naive check; all three together are not. The operator who cannot prove at least one of the three is absent must implement one of the three barriers above. ## Operational Effect The operational consequence is that **capability narrowing is not monotonic in authority unless handles are invalidated.** An orchestrator that reasons "I narrowed the scope, therefore the agent's blast radius shrank" is reasoning about the declared surface and will be wrong for the duration of any live handle or forked worker. This matters most in the exact scenario least-privilege is supposed to defend: a prompt-injected agent that has been *demoted* mid-task. The demotion message is delivered, the demotion is acknowledged, and the injected payload — already holding a directory handle or a queued write job — completes its write against the pre-demotion root. The audit log shows a clean revocation followed by a write that the revoked scope should have forbidden; the discrepancy is only visible if the log records *effective* scope at the moment of the syscall, not declared scope at dispatch. The fix that survives audit is to log, at each handle use, the scope snapshot that authorized it, and to assert equality between the authorizing snapshot and the live scope at use time. A mismatch is not a warning; it is a boundary violation and must abort the invocation. The invariant to encode: *no I/O may proceed under a scope snapshot that is not the current one.* ```python import threading from dataclasses import dataclass, field from typing import Optional class ScopeDivergenceError(RuntimeError): """Raised when an in-flight handle outlives the scope that authorized it.""" pass @dataclass(frozen=True) class Scope: tools: frozenset roots: tuple epoch: int # monotonic counter, bumped on every revocation @dataclass class ScopedHandle: path: str authorizing_epoch: int fd: int _open: bool = field(default=True) class ScopedToolServer: def __init__(self, scope: Scope): self._scope = scope self._lock = threading.Lock() self._handles: dict[str, ScopedHandle] = {} def _live_scope(self) -> Scope: with self._lock: return self._scope def revoke(self, new_scope: Scope) -> None: with self._lock: # bump epoch so every pre-existing handle is provably stale self._scope = Scope( tools=new_scope.tools, roots=new_scope.roots, epoch=self._scope.epoch + 1, ) def open_for_read(self, path: str) -> ScopedHandle: scope = self._live_scope() if "read_file" not in scope.tools: raise ScopeDivergenceError(f"read_file not in scope epoch {scope.epoch}") if not any(path.startswith(r) for r in scope.roots): raise ScopeDivergenceError(f"{path} outside roots {scope.roots}") h = ScopedHandle(path=path, authorizing_epoch=scope.epoch, fd=hash(path)) self._handles[path] = h return h def read(self, h: ScopedHandle, n: int) -> bytes: # The critical invariant: re-validate at use, not just at open. scope = self._live_scope() if not h._open: raise ScopeDivergenceError("handle closed") if h.authorizing_epoch != scope.epoch: raise ScopeDivergenceError( f"handle authorized under epoch {h.authorizing_epoch}, " f"live scope is epoch {scope.epoch}; aborting read of {h.path}" ) if "read_file" not in scope.tools: raise ScopeDivergenceError(f"read_file revoked at epoch {scope.epoch}") if not any(h.path.startswith(r) for r in scope.roots): raise ScopeDivergenceError( f"{h.path} no longer under live roots {scope.roots}" ) return b"x" * n def demonstrate_divergence() -> None: server = ScopedToolServer( Scope(tools=frozenset({"read_file", "write_file"}), roots=("/work/project",), epoch=0) ) h = server.open_for_read("/work/project/a.txt") # warm phase, epoch 0 server.revoke( Scope(tools=frozenset({"read_file"}), roots=("/work/project/readonly",), epoch=0) ) # Naive server would return data here. Correct server must raise. server.read(h, 16) # -> ScopeDivergenceError, epoch 0 != 1 if __name__ == "__main__": try: demonstrate_divergence() except ScopeDivergenceError as e: print(f"boundary enforced: {e}") ```