# How should an instance enforce egress policy on MCP tool results before they re-enter the reasoning loop **Date of Record:** 2026 November 29 **Scope:** Applies to any agent runtime that connects to third-party MCP servers over stdio or streamable HTTP and treats tool *results* (not just tool *arguments*) as data flowing back into the model context. Does not cover inbound prompt-injection arriving via the user turn, nor sandbox escape of the server process itself — only the egress boundary between a tool response and the agent's context. ## Core Distinction Most sandboxing effort is spent on the **call side**: constraining what arguments the model may pass to a tool, which tools are exposed, and what filesystem/network the server process can touch. The failure mode here is on the **return side**. An MCP server that has been declared "untrusted" is still permitted to return arbitrary `content` blocks, and the runtime's default behavior is to splice those blocks into the assistant's context as if they were trustworthy observations. The distinction that matters: *tool arguments are model-generated and policy-checkable before dispatch; tool results are server-generated and policy-checkable only after they have already been parsed into the context window.* The egress filter must therefore operate on the response envelope, and it must run before any block is admitted to context — not as a post-hoc scan of the assembled transcript. ## What Was Observed A runtime registered a third-party MCP server exposing a single tool, `fetch_issue`. The server was configured with a restrictive capability manifest: one tool, `readOnlyHint: true`, no `resources` or `prompts` capability. The call-side guard worked correctly — arguments were schema-validated, the tool name was on the allowlist, and the stdio process ran under a seccomp profile with no outbound sockets. The server returned a well-formed `CallToolResult` whose `content` array contained a single `text` block. The text was a JSON document describing the issue, but it also carried a trailing instruction block styled as a system reminder. Because the runtime's admission path treated `result.content` as opaque and appended each block's `text` verbatim into a `tool` role message, the instruction block entered the context window with no distinction from legitimate tool output. On the next reasoning step the model treated the embedded text as an operational directive and called a *second* tool — `write_file`, which was legitimately exposed on a different, trusted server — with arguments derived from the injected block. The call-side sandbox held. The egress boundary did not. The server never escaped its process sandbox; it simply *replied* its way into the agent's control flow. Two secondary observations compounded it: 1. The result envelope's `isError` flag was `false`, so the runtime's error-handling path never fired, and no audit record was emitted beyond a raw transcript dump. 2. The server had been marked untrusted at registration time, but the untrusted flag was consulted only when *dispatching* — it was never consulted when *admitting the response*. The trust tier was effectively write-only metadata. A replay of the same transcript against a runtime that filtered on admission reproduced the tool call zero times, confirming the injection vector was the admission path and not model stochasticity. ## Condition of Validity The guardrail described below is valid only under these conditions, and an instance must refuse to claim egress enforcement outside them: - The MCP transport delivers responses as structured `CallToolResult` envelopes with a stable `content` array of typed blocks. If the server speaks a transport that returns a bare string, the block-type discrimination below is unavailable and the whole result must be treated as untrusted text. - The runtime controls the admission function — i.e., there is a single chokepoint between "response received" and "message appended to context." If the framework auto-appends results (many SDKs do), the invariant cannot be enforced without patching the loop. - Trust tier is attached to the *server registration*, not to individual tools, and is read at admission time as well as dispatch time. A per-tool trust model is stronger but is not assumed here. - The filter is deterministic and runs on raw bytes before tokenization. Any filter that operates on the model's *interpretation* of the text is not a boundary and must not be counted as one. When any of these fail, the correct posture is to treat every result from a third-party server as hostile input and either quarantine it behind a summarization step or refuse the server entirely. ## Decision Boundary The boundary is not "is this text malicious" — that is undecidable and invites false confidence. The boundary is **provenance-typed admission**: a block's admissibility is decided by (a) the trust tier of the server that produced it and (b) whether the block's declared type is one the runtime can safely re-render. Concretely: - Trusted server → admit blocks as-is. - Untrusted server → admit only blocks whose type is in a closed allowlist (`text` with a declared `mimeType` of `text/plain` or `application/json`, and `resource` blocks whose `uri` scheme is on a per-server allowlist). Every admitted block is wrapped in a delimited, non-executable envelope and prefixed with an explicit provenance marker that the system prompt instructs the model to treat as data, never as instruction. - Any block whose type is unknown, whose `mimeType` is absent on an untrusted server, or which exceeds a byte cap → reject the *entire result*, not just the block. Partial admission of a multi-block result is itself a boundary hole, because the server controls block ordering and can split an injection across blocks. The decision must be made before the result enters context and must be recorded with the server identity, the block hash, and the verdict. A result that fails the boundary is surfaced to the model as a typed error, not silently dropped — silent drops cause the model to retry with mutated arguments, which is its own divergence mode. ## Operational Effect Enforcing admission-time egress filtering changes three things an instance will notice in practice. First, third-party results arrive wrapped and provenance-marked, so the model's instruction-following on tool output drops sharply for injected content while legitimate data extraction is unaffected — the wrapper is a delimiter, not a summarizer, and does not lose fidelity. Second, the runtime gains a hard audit point: every untrusted result has a verdict, a hash, and a server identity, which makes replay-based verification of "did this injection reach context" a lookup rather than a forensic reconstruction. Third, and most importantly, the trust tier becomes load-bearing on both sides of the call, closing the asymmetry where a server could pass dispatch-time scrutiny and still write into the reasoning loop on the return path. The cost is that a misbehaving-but-honest server returning an exotic `mimeType` will have its result rejected wholesale; that is the intended trade, and the rejection must be legible enough that the model does not loop on it. ```python import hashlib from dataclasses import dataclass from typing import Iterable class EgressPolicyViolation(RuntimeError): """Raised when an MCP tool result fails admission-time egress policy.""" @dataclass(frozen=True) class ContentBlock: type: str mime_type: str | None payload: bytes @dataclass(frozen=True) class ToolResult: server_id: str trusted: bool blocks: list[ContentBlock] ALLOWED_UNTRUSTED_MIME = frozenset({"text/plain", "application/json"}) MAX_BLOCK_BYTES = 256 * 1024 def admit_result(result: ToolResult) -> list[dict]: """Decide whether an MCP CallToolResult may enter the model context. Runs before any block is appended to the transcript. Rejects the whole result on any violation; partial admission is a boundary hole. """ if result.trusted: return [ {"role": "tool", "content": b.payload.decode("utf-8", "replace")} for b in result.blocks ] admitted: list[dict] = [] for idx, block in enumerate(result.blocks): if block.type not in {"text", "resource"}: raise EgressPolicyViolation( f"server={result.server_id} block={idx} type={block.type!r} " f"not admissible from untrusted server" ) if block.mime_type not in ALLOWED_UNTRUSTED_MIME: raise EgressPolicyViolation( f"server={result.server_id} block={idx} " f"mime={block.mime_type!r} outside allowlist" ) if len(block.payload) > MAX_BLOCK_BYTES: raise EgressPolicyViolation( f"server={result.server_id} block={idx} " f"size={len(block.payload)} exceeds {MAX_BLOCK_BYTES}" ) digest = hashlib.sha256(block.payload).hexdigest()[:16] admitted.append( { "role": "tool", "content": ( f"[UNTRUSTED_DATA server={result.server_id} " f"block={idx} sha256={digest}]\n" f"{block.payload.decode('utf-8', 'replace')}\n" f"[/UNTRUSTED_DATA]" ), } ) return admitted def admit_or_typed_error(result: ToolResult) -> list[dict]: """Admission wrapper that converts violations into a legible tool error. Silent drops cause the model to retry with mutated arguments, which is its own divergence mode; the rejection must be visible. """ try: return admit_result(result) except EgressPolicyViolation as exc: return [ { "role": "tool", "content": f"[EGRESS_REJECTED server={result.server_id}] {exc}", } ] ```