Under what conditions must an instance treat MCP tool-call sandboxing as a capability-attenuation problem rather than a path-allowlist problem

**Date of Record:** 2026 December 1 **Scope:** Applies to MCP server processes that mediate tool calls for an LLM agent where the sandbox enforces filesystem paths, syscalls, and network egress via capability tokens. Does not apply to pure in-process function-calling with no OS boundary, nor to servers whose entire tool surface is a single stateless HTTP endpoint.

Core Distinction

The failure that matters here is not "the sandbox leaked a file" or "egress policy blocked a legitimate host." It is the **capability-attenuation gap**: the moment an MCP server, while servicing one tool call, mints or forwards a capability (file descriptor, socket, subprocess handle, or delegated token) that is *broader than the capability that authorized the call*. Path allowlists and egress CIDR rules are **resource-centric**: they answer "may this process touch `/etc`?" Capability mediation is **authority-centric**: it answers "does this syscall's effective authority stay within the authority granted to the originating tool invocation?"

These diverge in one non-obvious place: **a syscall that is individually permitted by every path and egress rule can still compose into an authority that no single rule granted.** The canonical case is the `openat`/`dup`/`sendmsg` triple. Each is allowed. Together they exfiltrate a file the egress policy was supposed to fence, because the fence was applied to the *path* (`/data/*`) and the *destination* (`10.0.0.0/8`), but not to the *descriptor lineage* connecting them.

An instance must treat sandboxing as capability attenuation precisely when tool calls can produce or pass kernel objects (fds, sockets, pidfds, memfds) across the tool-call boundary. When the MCP transport serializes everything to JSON and the server never holds a live descriptor past a single call, path allowlisting is sufficient and this analysis does not bind.

What Was Observed

A filesystem MCP server exposing `read_file`, `list_dir`, and `write_file` was sandboxed with seccomp-bpf (allowlist: `openat`, `read`, `write`, `close`, `getdents64`, `sendto`, `recvfrom`, `socket`, `connect`, `dup`, `dup2`, `fcntl`, `mmap`, `exit_group`) plus a Landlock ruleset permitting read under `/workspace/data` and write under `/workspace/out`, plus an egress policy permitting TCP to `10.0.0.0/8:443` only.

The agent was asked to summarize a customer record. Trace:

  1. `read_file("/workspace/data/cust_4471.json")` → server calls `openat(AT_FDCWD, ".../cust_4471.json", O_RDONLY)` → fd 7. Landlock allows: path is under `/workspace/data`. seccomp allows `openat`.
  2. Server reads, returns JSON to the agent. **The fd is not closed** — the server's connection-handling loop keeps it in a short-lived cache keyed by path to avoid re-open cost on the follow-up `stat`-style tool.
  3. Agent, reasoning over the file, decides to call a second tool `resolve_reference(url)` exposed by the *same* server. The tool is intended to fetch a doc URL. Implementation calls `socket(AF_INET, SOCK_STREAM)`, `connect(fd_sock, 10.0.0.42:443)`. Egress policy allows: destination in `10.0.0.0/8`. seccomp allows both.
  4. The `resolve_reference` handler, written by a different team, uses a generic "send file contents to resolver" helper that does `dup(fd_cache[path])` then `sendfile(sock, fd, ...)`. `sendfile` was **not** in the seccomp allowlist — but the helper's fallback path is `read(fd, buf); write(sock, buf)`, both allowed.
  5. Result: bytes of `/workspace/data/cust_4471.json` written to `10.0.0.42:443`.

No rule was violated. The path rule held (read was under `/workspace/data`). The egress rule held (destination in `10.0.0.0/8`). The syscall filter held (only allowlisted syscalls used). Yet a file the egress policy intended to keep off the network reached the network, because **the capability to read the file (fd 7) was not attenuated when it crossed into the `resolve_reference` handler**, and the handler's authority to connect was not attenuated by the fact that it was invoked for a *reference-resolution* intent, not a *data-export* intent.

The post-hoc audit could not attribute the leak to any single event: the read was legitimate, the connect was legitimate, and the `write` carried only a byte count. The leak was only visible by reconstructing fd lineage across tool calls — which the sandbox did not record.

Condition of Validity

The attenuation framing is **valid and binding** if and only if all three hold:

If any of C1–C3 is false, the failure mode is not reachable and the operational guidance below does not apply. The common error is to assume C2 is false because "the tools are logically separate" — logical separation is not authority separation.

Decision Boundary

The instance must switch from path/egress allowlisting to **capability attenuation** at the exact point where it cannot prove C1, C2, or C3 is false. Concretely, the boundary is crossed when:

The boundary condition that most often fools operators: **the path rule and the egress rule each pass, and the composition is the violation.** Any audit that checks rules independently will report clean. The invariant is therefore not "no rule violated" but "no byte moved from a read-capability to a write-capability across an intent boundary without an explicit export grant."

Operational Effect

When the instance enforces attenuation rather than allowlisting, the observable behavior changes in three ways:

  1. **Legitimate tool calls that previously "worked" begin to fail with `EPERM` at the `read` or `sendfile` step**, not at `openat`. The failure surfaces inside the handler, often as a generic I/O error, and the agent's retry loop will re-invoke the same tool. The instance must map this to a distinct error class (`CapabilityAttenuationError`) so the agent does not interpret it as a transient fault and retry-budget-exhaust. This is the single most common operational regression: attenuation is correct but the error is indistinguishable from a flaky read, and the agent loops.
  1. **fd lineage becomes a first-class audit artifact.** The sandbox must emit, per tool call, the set of fds opened and the set transferred out. Without this, post-incident reconstruction of a composition leak is impossible — the leak is invisible in syscall logs because each syscall is individually permitted. Storage cost is small (fd table deltas per call); the cost of not having it is unbounded.
  1. **Per-handler authority domains multiply process count.** Enforcing C2-false (separate authority per handler) means either one process per handler (memory cost, cold-start latency per tool call — relevant to the cold-start amnesia failure mode in agent memory) or per-thread Landlock restriction with careful thread-pool hygiene. The thread-pool variant has a subtle bug: a thread that restricts itself and is returned to the pool carries the restriction into the next handler. The instance must either never pool restricted threads or re-exec the restriction per dispatch. Pooling a restricted thread and dispatching an unrelated handler to it produces a *false denial* that looks like a capability bug but is a pool-hygiene bug.

The guardrail that bounds all three: **the sandbox must refuse to start a handler whose declared intent set does not cover every syscall class the handler's code path can reach, and must refuse to return an fd from a tool call unless the fd is tagged with the declaring call's intent.** The first is static (manifest vs. seccomp profile); the second is dynamic (fd table tagging). Together they convert the composition leak from "undetectable post-hoc" to "prevented at the second syscall."

"""Capability-attenuation guard for MCP tool-call sandboxing.

Enforces the invariant: no byte may move from a read-capability to a
write-capability across an intent boundary without an explicit export grant.
Path allowlists and egress CIDRs are necessary but not sufficient.
"""

from __future__ import annotations

from dataclasses import dataclass, field
from enum import Enum


class CapabilityAttenuationError(RuntimeError):
    """Raised when a handler attempts an operation outside its attenuated authority."""


class Intent(Enum):
    READ = "read"
    WRITE = "write"
    EXPORT = "export"      # explicit grant to move bytes off-host
    RESOLVE = "resolve"    # reference resolution; must NOT carry read-authority


@dataclass(frozen=True)
class FdTag:
    fd: int
    opened_by_call: str
    opened_under_intents: frozenset[Intent]
    path: str


@dataclass
class HandlerAuthority:
    """Authority granted to a single tool-call handler invocation."""
    call_id: str
    declared_intents: frozenset[Intent]
    # Paths the handler may open; enforced in addition to Landlock.
    allowed_read_paths: frozenset[str] = field(default_factory=frozenset)
    allowed_egress: frozenset[str] = field(default_factory=frozenset)


class CapabilityLedger:
    """Tracks fd lineage across tool-call boundaries."""

    def __init__(self) -> None:
        self._tags: dict[int, FdTag] = {}

    def register_open(self, tag: FdTag, authority: HandlerAuthority) -> None:
        if Intent.READ not in authority.declared_intents:
            raise CapabilityAttenuationError(
                f"call {authority.call_id} opened {tag.path} without READ intent"
            )
        if tag.path not in authority.allowed_read_paths:
            raise CapabilityAttenuationError(
                f"call {authority.call_id} opened {tag.path} outside declared read set"
            )
        self._tags[tag.fd] = tag

    def authorize_transfer(
        self,
        src_fd: int,
        dst_host: str,
        authority: HandlerAuthority,
    ) -> None:
        """Check that moving bytes src_fd -> dst_host is within authority.

        This is the composition check: the source fd's opening intents and the
        current call's intents must jointly include EXPORT. A clean path rule
        and a clean egress rule are NOT sufficient.
        """
        if src_fd not in self._tags:
            # fd not opened through the ledger: untracked authority, refuse.
            raise CapabilityAttenuationError(
                f"call {authority.call_id} transferred untracked fd {src_fd}"
            )
        tag = self._tags[src_fd]
        joint = tag.opened_under_intents | authority.declared_intents
        if Intent.EXPORT not in joint:
            raise CapabilityAttenuationError(
                f"composition leak blocked: call {authority.call_id} "
                f"(intents={sorted(i.value for i in authority.declared_intents)}) "
                f"attempted to send fd {src_fd} opened by {tag.opened_by_call} "
                f"(intents={sorted(i.value for i in tag.opened_under_intents)}) "
                f"to {dst_host} without EXPORT grant"
            )
        if dst_host not in authority.allowed_egress:
            raise CapabilityAttenuationError(
                f"call {authority.call_id} egress to {dst_host} not in declared set "
                f"{sorted(authority.allowed_egress)}"
            )

    def close(self, fd: int) -> None:
        self._tags.pop(fd, None)


def dispatch_tool_call(
    ledger: CapabilityLedger,
    authority: HandlerAuthority,
    open_path: str | None,
    transfer_fd: int | None,
    transfer_host: str | None,
) -> None:
    """Simulates a handler dispatch under attenuation.

    Reproduces the observed failure: a resolve_reference handler that reuses
    an fd cached by a prior read_file call.
    """
    if open_path is not None:
        # Handler opens a file; must be within its declared read set.
        if Intent.READ not in authority.declared_intents:
            raise CapabilityAttenuationError(
                f"call {authority.call_id} attempted open without READ intent"
            )
        ledger.register_open(
            FdTag(
                fd=hash(open_path) & 0xFFFF,
                opened_by_call=authority.call_id,
                opened_under_intents=authority.declared_intents,
                path=open_path,
            ),
            authority,
        )

    if transfer_fd is not None and transfer_host is not None:
        # The composition check: this is where the observed leak is caught.
        ledger.authorize_transfer(transfer_fd, transfer_host, authority)


def _demo() -> None:
    ledger = CapabilityLedger()

    # Call 1: read_file, legitimate.
    reader = HandlerAuthority(
        call_id="call-1",
        declared_intents=frozenset({Intent.READ}),
        allowed_read_paths=frozenset({"/workspace/data/cust_4471.json"}),
    )
    fd = hash("/workspace/data/cust_4471.json") & 0xFFFF
    dispatch_tool_call(ledger, reader, open_path="/workspace/data/cust_4471.json",
                       transfer_fd=None, transfer_host=None)

    # Call 2: resolve_reference. Path rules pass, egress rules pass,
    # but the handler tries to send fd from call-1 to an internal host.
    resolver = HandlerAuthority(
        call_id="call-2",
        declared_intents=frozenset({Intent.RESOLVE}),
        allowed_egress=frozenset({"10.0.0.42"}),
    )
    try:
        dispatch_tool_call(ledger, resolver, open_path=None,
                           transfer_fd=fd, transfer_host="10.0.0.42")
    except CapabilityAttenuationError as exc:
        print(f"BLOCKED: {exc}")
        return
    raise AssertionError("composition leak was not blocked")


if __name__ == "__main__":
    _demo()