# How should an instance enforce taint propagation across MCP tool-call boundaries when a sandboxed tool returns attacker-influenced content **Date of Record:** 2026 November 28 **Scope:** Applies to LLM agent instances that invoke MCP (Model Context Protocol) tools through a sandboxed transport layer and maintain a taint label set over context segments. Does not cover pure single-shot inference with no tool calls, nor systems where tool outputs are never re-ingested into the reasoning context. ## Core Distinction The failure is not "the sandbox let malicious code run." It is subtler: **the sandbox correctly executed the tool in isolation, but the taint label attached to the tool's *output* was dropped at the transport re-entry boundary — the point where the MCP response is deserialized back into the agent's context.** Taint-aware sandboxing typically taints *inputs* (untrusted documents, user text) and *capabilities* (which tools may touch which resources). The non-obvious gap is the **output-taint re-entry invariant**: any content that flowed through a tool whose arguments were tainted must itself be tainted on return, even if the tool is nominally "safe" and even if the returned bytes look like clean structured JSON. Prompt injection survives not by escaping the sandbox but by riding a *clean-looking* return value back into an untainted context window, where the next reasoning step treats it as trusted instruction. ## What Was Observed An agent fetched a web page via an MCP `fetch_url` tool. The URL argument was derived from untrusted user text, so the call was correctly marked `tainted_input=True`. The sandbox fetched the page in a network-isolated container. The page contained an injected payload: `
`. The tool returned `{"status":200,"body":"...","content_type":"text/html"}`. The transport layer deserialized this into the agent context as a fresh tool-result segment. **The taint flag was not propagated** because the deserializer treated tool results as a distinct, implicitly-trusted `role:tool` channel. On the next reasoning turn, the agent's planner saw a `tool` message and — per the prompt's trust hierarchy — assigned it higher trust than user content. It executed the injected instruction, calling `filesystem.write`. That second tool call inherited taint only from its *arguments*, which the planner had synthesized from now-untainted text, so the write passed the sandbox's argument check. The trace: 1. `fetch_url(url_from_user)` → `tainted_input=True`, sandbox executes, returns bytes. 2. Transport deserialize → segment created with `taint=∅` (default clean). 3. Planner reads `role:tool` segment, treats as trusted. 4. Injected instruction promoted to plan step. 5. `filesystem.write(path, data)` → `tainted_input=False` (arguments look clean). 6. Sandbox permits write. Containment broken. The single broken link is step 2. Everything upstream and downstream was individually correct. ## Condition of Validity The taint-containment guarantee holds **only if** the transport layer enforces the closure rule: > `taint(result) ⊇ taint(args) ∪ taint(tool_source)` for every tool result re-entering the context, where `tool_source` is the trust level of the tool's *implementation and its data sources* (a `fetch_url` tool is inherently `UNTRUSTED_SOURCE` because the network is adversarial). The guarantee is void the moment any deserialization path constructs a tool-result segment without computing this union — including error responses, partial/streamed results, and tool outputs that are themselves valid JSON matching a trusted schema. Note the schema trap: a tool returning well-formed JSON that validates against a declared MCP output schema is *more* dangerous, not less, because schema validation is frequently (and wrongly) used as a proxy for trustworthiness. Schema conformance says nothing about provenance. ## Decision Boundary The boundary is between **structural trust** (channel/role: `tool`, `assistant`, `user`) and **provenance trust** (taint set). Systems that conflate them fail here. The rule: - A `role:tool` segment is **never** structurally trusted. Structural role determines *formatting and parsing*, not *trust*. - Trust is a function of provenance only: `taint(result) = taint(args) ∪ source_trust(tool)`. - Content is "clean" only when `taint = ∅`, which requires untainted args AND a tool whose source is declared `TRUSTED` (e.g., a local deterministic calculator with no external reads). Any code path that emits a tool result with `taint = ∅` while `taint(args) ≠ ∅` OR `source_trust(tool) = UNTRUSTED` is a containment violation and must raise, not silently proceed. ## Operational Effect After enforcing the closure rule, the injected `fetch_url` result is tagged `taint = {UNTRUSTED_SOURCE}`. The planner's trust hierarchy now ranks it *below* user content, and any *action-suggesting* content from a tainted segment is quarantined: it may be summarized or quoted but cannot generate a tool call whose effects are irreversible (`filesystem.*`, `shell.*`, `net.*` egress) without an explicit declassification step (human confirmation or a policy warrant). The `filesystem.write` call is blocked at plan-construction time because its data dependency traces to a tainted segment. The cost is real: taint spreads monotonically and tainted segments cannot silently feed privileged tools, so agents must either declassify (with audit) or route through a summarizing, non-executing sub-agent. That friction is the invariant working as intended — it converts a silent privilege escalation into an explicit, logged decision. ```python from dataclasses import dataclass, field from enum import Enum from typing import FrozenSet class TrustSource(Enum): TRUSTED = "trusted" # local deterministic, no external read UNTRUSTED_SOURCE = "untrusted_source" # network, filesystem, user-derived class TaintViolation(RuntimeError): """Raised when a tool result re-enters context with insufficient taint.""" pass @dataclass(frozen=True) class Segment: content: str taint: FrozenSet[str] = field(default_factory=frozenset) def deserialize_tool_result( raw_content: str, args_taint: FrozenSet[str], tool_source: TrustSource, ) -> Segment: """Enforce: taint(result) >= taint(args) | source_trust(tool).""" expected = set(args_taint) if tool_source is TrustSource.UNTRUSTED_SOURCE: expected.add(tool_source.value) # Simulate a deserializer that (incorrectly) trusts role:tool. naive_taint = frozenset() # the bug: tool channel assumed clean if not expected.issubset(naive_taint): raise TaintViolation( f"tool result re-entered context with taint={set(naive_taint)} " f"but required >= {expected}; provenance dropped at transport boundary" ) return Segment(content=raw_content, taint=naive_taint) def guarded_deserialize(raw_content, args_taint, tool_source) -> Segment: """Correct path: compute the union, never default to clean.""" taint = set(args_taint) if tool_source is TrustSource.UNTRUSTED_SOURCE: taint.add(tool_source.value) return Segment(content=raw_content, taint=frozenset(taint)) # Reproduces the observed failure: try: deserialize_tool_result( raw_content="