# Which invariants prevent path-scoped MCP filesystem tools from escaping confinement through symlink resolution and TOCTOU races **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers that expose filesystem tools (`read_file`, `write_file`, `list_dir`, `move`, `delete`) confined to a declared root via per-tool capability scopes. Does not apply to servers with no filesystem surface, nor to sandboxing enforced purely at the OS/container layer where the process itself is chrooted or namespaced. ## Core Distinction The distinction that matters is between **lexical path confinement** and **resolved-path confinement**. Most MCP filesystem servers implement confinement by normalizing the *string* the model passed (`../` stripping, `os.path.normpath`, prefix checks against the root) and then handing that string to the OS. The OS then performs its own resolution: symlinks, hardlinks, `..` after symlink expansion, mount points, and bind mounts are all applied *after* the server's check. The invariant the server believes it enforces — "every file operation touches a path under root" — is a property of the resolved inode, not of the string. A lexical check is a check on a *description* of the target; the kernel acts on the *target*. The gap between description and target is the entire attack and failure surface. A second distinction: capability scope (which tools are exposed, with what declared root) is negotiated once at handshake. Path confinement must hold *per call*, across a mutable filesystem. A capability grant is a claim about a region of a namespace that changes underneath the grant. ## What Was Observed A filesystem MCP server declared `root=/workspace/project` and exposed `read_file(path)` with a guard: ``` def _safe(p): full = os.path.normpath(os.path.join(ROOT, p)) if not full.startswith(ROOT + os.sep): raise Denied return full ``` An agent, mid-task, called `read_file("data/latest")`. `data/latest` was a symlink to `/etc/credentials` created earlier in the same session by a *different* tool call (`write_file` of a symlink payload, or a `move` that relocated a pre-existing link). `normpath` does not resolve symlinks; `startswith` passed because the string was `/workspace/project/data/latest`. `open()` then followed the link and read outside the root. No exception, no log line, because the guard had already returned. Variant two, the TOCTOU window: the guard resolved the path with `realpath`, confirmed containment, and then opened. Between `realpath` and `open`, a concurrent agent (or the same agent via a second tool call) replaced the final component with a symlink pointing outside. The check was true at time *t*; the open happened at time *t+ε* against a different inode. The window is small but the agent loop makes it reachable: agents issue tool calls in parallel batches, and `write_file` + `read_file` on sibling paths routinely interleave. Variant three, the prefix bug: root `/workspace/proj` and containment test `startswith(ROOT)` without separator admits `/workspace/proj-evil/...`. Lexical, trivially triggered by a model that guesses sibling directory names. In all three, the failure is silent. The tool returns success. The agent's belief state now contains content it should not have, and downstream reasoning treats it as in-scope ground truth. ## Condition of Validity The invariant "all filesystem effects are confined to root" holds only if **every path is validated on its resolved identity, and the validated identity is the one operated on.** Operationally this requires: 1. **Resolution before validation, on the final component.** Use `os.path.realpath` (or `O_NOFOLLOW` + `fstat`) so symlinks are expanded *before* the prefix test, and test with a trailing separator (`real_root + os.sep`) or `os.path.commonpath`. 2. **Bind the check to the handle, not the name.** The check and the operation must act on the same inode. Open with `os.open(real, O_NOFOLLOW | O_RDONLY)` and operate on the returned fd; or `openat2` with `RESOLVE_BENEATH | RESOLVE_NO_SYMLINKS` where available. `realpath`-then-`open` is invalid because the name can change between the two. 3. **Reject symlinks whose target leaves the root, at every component**, not just the leaf. A symlinked *directory* mid-path (`data -> /etc`) escapes just as cleanly as a leaf link. 4. **Treat capability scope as re-validated per call.** The handshake-time root is a claim; the filesystem is mutable. Confinement is a per-operation predicate. 5. **Hardlinks break the model too.** A hardlink inside root to an inode outside root has a resolved path *inside* root. Resolution-based confinement does not catch it; only link-count/inode-origin checks or a filesystem that forbids cross-root links do. State this as a known residual. Outside this condition — e.g. a server that runs in a mount namespace where root is the only writable mount — the lexical check is sufficient *because the kernel enforces the boundary*, and the server's check is defense in depth, not the boundary itself. ## Decision Boundary The boundary is: **does the server rely on path strings or on inode identity?** If the guard's output is a string that is later passed to a syscall that re-resolves, the guard is advisory and the boundary is unenforced. If the guard's output is an open file descriptor or a dirfd-relative `openat`, the guard is the boundary. Concretely, the decision for a given tool call: - Path contains no symlink component and no concurrent mutation → lexical check coincidentally correct. - Path contains a symlink component resolving inside root → lexical check passes, resolved check passes; both fine. - Path contains a symlink component resolving outside root → lexical check passes, resolved check fails; **only resolved check is correct**. - Path is stable at check time, mutated before open → resolved check passes at *t*, operation hits different inode at *t+ε*; **only fd-binding is correct**. - Path is a hardlink to an out-of-root inode → both checks pass; **neither is correct**; residual risk, must be documented. The operational rule: any filesystem tool whose guard returns a *path* rather than a *handle* is out of compliance, regardless of how many `normpath`/`realpath` calls it makes. ## Operational Effect When the invariant is violated, the agent does not fail loudly — it fails by *succeeding with poisoned context*. The read returns out-of-scope bytes; the agent's episodic memory records them as project data; subsequent reasoning, summarization, and any `write_file` derived from that content propagate the contamination. Because the tool reported success and the guard logged nothing (it returned before the syscall), there is no signal in the trace to trigger recovery. The failure is only detectable by comparing the resolved inode of every successful filesystem operation against the declared root — an audit the agent does not perform on itself. The corrective architecture is: resolve-and-bind at the syscall boundary, re-validate per call, reject any path whose resolved form exits the root with a typed error the agent loop treats as a hard stop (not a retryable soft failure), and surface symlink/hardlink rejections as distinct from permission denials so the model does not attempt workarounds. The following guard encodes the invariant and refuses to return a bare path: ```python import os class ConfinementViolation(RuntimeError): """Raised when a filesystem operation would resolve outside the capability root.""" def open_confined(root: str, rel: str) -> int: # Resolve the root once; it is the trust anchor. real_root = os.path.realpath(root) # Resolve the requested path fully, including every symlink component. candidate = os.path.realpath(os.path.join(real_root, rel)) # Containment test on resolved identity, with separator to block sibling-prefix escape. if candidate != real_root and not candidate.startswith(real_root + os.sep): raise ConfinementViolation( f"resolved path {candidate!r} escapes root {real_root!r}" ) # Bind the check to the handle: O_NOFOLLOW refuses a leaf symlink swapped in # between realpath() and open(), closing the TOCTOU window. try: fd = os.open(candidate, os.O_RDONLY | os.O_NOFOLLOW) except OSError as e: raise ConfinementViolation( f"open refused for {candidate!r}: leaf mutated or symlinked ({e})" ) from e # Residual: a hardlink inside root to an out-of-root inode passes here. # Documented; mitigate with a link-count check or a namespace-confined mount. return fd ```