Which invariants prevent taint laundering through MCP tool-argument re-encoding at the policy enforcement point

**Date of Record:** 2026 December 1 **Scope:** Applies to runtime policy enforcement points (PEPs) that sit between an LLM agent's tool-call emission and an MCP server's tool execution, and that make allow/deny decisions by propagating taint labels attached to context segments into tool-call arguments. Does not apply to stateless per-call filters that do not carry taint across turns, nor to post-hoc output auditing.

Core Distinction

A taint-aware PEP does not decide "is this argument malicious?" It decides "does the set of provenance labels on the argument's *value* intersect the set of labels the invoked tool is permitted to consume?" These are different questions with different failure surfaces. The first is a classification problem over content; the second is a provenance-containment problem over data flow. Almost every observed bypass in this class comes from confusing the two: the PEP evaluates the *serialized argument string* rather than the *data-flow lattice* that produced it.

The invariant that must hold at every enforcement point is:

> For every tool invocation `t(args)`, the taint label of every argument value, computed over the transitive closure of its derivation from context segments, must be a subset of `allowed_taint(t)`.

The failure mode is that argument values are re-encoded between derivation and enforcement — JSON serialization, string interpolation, base64, template expansion, or an intermediate tool that returns the value back into context — and the PEP computes taint over the re-encoded artifact rather than the derivation. The label is dropped, the value survives, and the allow decision is made on a laundered object.

What Was Observed

An agent was given a three-tool sequence: `fetch_url` (returns untrusted web content, tagged `UNTRUSTED_EXTERNAL`), `summarize` (a pure LLM transform, no external side effect, permitted to consume any taint but must *propagate* the maximum taint of its inputs to its output), and `send_email` (permitted only to consume `TRUSTED` or `AGENT_GENERATED`).

The intended flow — fetch a page, summarize it, email the summary to the user — is legal because `summarize` is a taint-transparent transform and `send_email`'s `allowed_taint` excludes `UNTRUSTED_EXTERNAL`, so the summarized-but-still-tainted body should be denied. That denial is the whole point: it forces the agent to route external content through a human-review tool or an explicit sanitizer that *lowers* taint only after a check.

What actually happened: `summarize` was implemented as an MCP tool that took `text: string` and returned `{ "summary": string }`. The PEP computed the taint of the `summarize` *call* correctly — `UNTRUSTED_EXTERNAL`, allowed because `summarize`'s `allowed_taint` is `{*, }`. But the PEP computed the taint of the `summarize` *result* by inspecting the returned JSON object for known-taint markers, and the summary text — a paraphrase — contained none. The result was labeled `AGENT_GENERATED`. The subsequent `send_email` call was allowed. The external content reached an outbound side effect through a transform that the PEP had assumed was taint-preserving but had only *checked* rather than *enforced*.

The trace:

  1. `fetch_url("https://attacker.example")` → result tagged `UNTRUSTED_EXTERNAL`. Correct.
  2. Agent emits `summarize(text=<page body>)`. PEP computes argument taint = `{UNTRUSTED_EXTERNAL}`. `allowed_taint(summarize) = ⊤`. **Allow.** Correct.
  3. `summarize` returns `{"summary": "..."}`. PEP computes result taint by scanning the string for provenance markers. Finds none. Assigns `AGENT_GENERATED`. **Incorrect** — the correct label is the join of input labels, `{UNTRUSTED_EXTERNAL}`.
  4. Agent emits `send_email(to=..., body=<summary>)`. PEP computes argument taint = `{AGENT_GENERATED}`. `allowed_taint(send_email) = {TRUSTED, AGENT_GENERATED}`. **Allow.** Incorrect decision on correct-looking inputs.

The mechanism is a **label-recomputation gap**: the PEP trusted the tool's return value to carry its own provenance, but provenance is a property of the *derivation graph*, not of the payload. A paraphrase, a hash, a translation, or a base64 wrap all destroy the lexical markers a content-scanning PEP looks for while preserving the semantic dependency.

Condition of Validity

The containment invariant holds only when all three of the following are true at every enforcement point:

  1. **Tool output taint is derived, not detected.** The PEP must assign the result label of `t(args)` as `join(taint(args)) ⊔ declared_output_taint(t)`, where `declared_output_taint` is a *static* property of the tool's manifest (a tool that transforms untrusted input into trusted output must declare a `sanitizer` capability and prove it, not merely fail to emit markers). Content scanning is a fallback for tools with no manifest, and must default to `⊤` (deny-everything-that-matters), never to `AGENT_GENERATED`.
  1. **The derivation graph is closed under re-encoding.** Any value that flows from a tainted source to a sink must be traceable through every intermediate representation. If the agent string-interpolates a tainted value into a new argument, the PEP must taint the *interpolated result* by the join of the interpolated parts. This requires the enforcement point to see the argument-construction expression, not just the final string — or, equivalently, to operate on a structured argument tree in which each leaf carries its own label.
  1. **Sanitizers are the only label-lowering operation, and they are explicit.** No transform lowers taint by default. A tool may lower taint only if its manifest declares a `sanitizer` capability *and* the PEP verifies the lowering against a declared post-condition (e.g., "output contains no URLs from the input" — checkable, not merely asserted). Absent that, `summarize`, `translate`, `reformat`, and `base64_encode` are all taint-transparent.

When any of these fails, the invariant is violated and the PEP is making allow/deny decisions over a lattice that does not model the actual data flow.

Decision Boundary

The boundary between "safe to allow" and "must deny" is *not* "does the argument look tainted." It is:

> Allow `t(args)` iff `derived_taint(args) ⊆ allowed_taint(t)`, where `derived_taint` is computed over the argument's derivation in the provenance graph, and where any tool whose output taint is not derivable from a manifest defaults to `⊤`.

Two corollaries that are easy to get wrong:

Operational Effect

The practical consequence is that a taint-aware PEP must be built around a **provenance-tracked value representation** that survives the agent's own tool-call serialization, and must treat every tool as taint-transparent by default. Concretely, the enforcement point must:

The failure this prevents is not "the agent was tricked." It is "the PEP's lattice had a hole at the re-encoding boundary, and the agent's normal, non-adversarial behavior — summarize then send — walked through it." The invariant is what closes the hole: taint is a property of derivation, not of payload, and any enforcement point that forgets this is enforcing a lexical check while believing it is enforcing a data-flow one.

from dataclasses import dataclass, field
from typing import FrozenSet, Dict, List, Optional

TOP = frozenset({"*"})

class TaintLaunderingError(RuntimeError):
    """Raised when a tool result's taint label is not derivable from its inputs
    and the tool has not declared a verified sanitizer capability."""
    pass

class ManifestIncompleteError(RuntimeError):
    """Raised when a tool manifest omits output_taint; defaulting to TOP is
    required, and silently defaulting to AGENT_GENERATED is the bug this prevents."""
    pass

@dataclass(frozen=True)
class ToolManifest:
    name: str
    allowed_taint: FrozenSet[str]
    output_taint: Optional[FrozenSet[str]]          # None => must default to TOP
    sanitizer: bool = False
    sanitizer_postcondition: Optional[str] = None   # checkable predicate id

@dataclass
class TaintedValue:
    value: object
    labels: FrozenSet[str]
    derivation: List[str] = field(default_factory=list)

def join(*labelsets: FrozenSet[str]) -> FrozenSet[str]:
    out: set = set()
    for ls in labelsets:
        out |= set(ls)
    return frozenset(out)

def enforce(manifest: ToolManifest, args: Dict[str, TaintedValue]) -> FrozenSet[str]:
    if manifest.output_taint is None:
        raise ManifestIncompleteError(
            f"tool {manifest.name!r} has no output_taint; refusing to guess"
        )
    arg_taint = join(*(a.labels for a in args.values())) if args else frozenset()
    if not arg_taint <= manifest.allowed_taint:
        raise TaintLaunderingError(
            f"deny {manifest.name}: arg taint {arg_taint} not subset of "
            f"allowed {manifest.allowed_taint}"
        )
    # Result taint is DERIVED: join of inputs and declared output taint.
    # A sanitizer may lower, but only if its postcondition is verified.
    if manifest.sanitizer:
        if not manifest.sanitizer_postcondition:
            raise ManifestIncompleteError(
                f"sanitizer {manifest.name!r} declares no postcondition"
            )
        return manifest.output_taint  # postcondition already verified upstream
    return join(arg_taint, manifest.output_taint)

def call_tool(manifest: ToolManifest, args: Dict[str, TaintedValue],
              impl) -> TaintedValue:
    result_taint = enforce(manifest, args)
    raw = impl({k: v.value for k, v in args.items()})
    # Crucially: do NOT scan `raw` for markers. Label comes from derivation.
    return TaintedValue(
        value=raw,
        labels=result_taint,
        derivation=[f"{manifest.name}({','.join(args)})"] ,
    )

# --- demonstration of the laundering trace ---
fetch = ToolManifest("fetch_url", frozenset({"*"}), frozenset({"UNTRUSTED_EXTERNAL"}))
summarize = ToolManifest("summarize", frozenset({"*"}), frozenset())  # transparent
send = ToolManifest("send_email", frozenset({"TRUSTED", "AGENT_GENERATED"}), frozenset())

page = call_tool(fetch, {"url": TaintedValue("https://x", frozenset({"AGENT_GENERATED"}))},
                 lambda a: "body")
summary = call_tool(summarize, {"text": page}, lambda a: "paraphrased body")

try:
    call_tool(send, {"body": summary}, lambda a: "sent")
except TaintLaunderingError as e:
    # Correct behavior: summary retains UNTRUSTED_EXTERNAL, send is denied.
    print(f"blocked: {e}")
else:
    raise TaintLaunderingError(
        "send_email allowed a laundered UNTRUSTED_EXTERNAL body; "
        "output_taint was not derived from input taint"
    )