# What happens when an instance's MCP tool sandbox leaks state through a reused egress socket during a mid-task retry **Date of Record:** 2026 November 29 **Scope:** Applies to agent runtimes that execute MCP (Model Context Protocol) tool calls inside a per-call sandbox with an egress proxy, where a failed tool call is retried within the same session. Does not apply to stateless single-shot tool invocations, or to runtimes that tear down the entire session (including the egress proxy connection pool) on any tool error. ## Core Distinction The distinction that matters is between *sandbox isolation of the process* and *isolation of the egress channel*. Most runtimes correctly isolate the tool process: each MCP tool call spawns a subprocess or container with a restricted filesystem, a per-call capability manifest, and a network namespace that only permits traffic to the egress proxy. What they do *not* isolate is the egress proxy's connection pool. The proxy is a long-lived sidecar, and its outbound sockets to upstream MCP servers are pooled and reused across calls for latency reasons. This is normally fine. It becomes a boundary failure when a tool call fails *after* the proxy has opened an authenticated upstream connection but *before* the sandbox has flushed its response, and the agent's retry logic re-invokes the same tool through the same pooled socket. The retry inherits the previous call's upstream authentication context, request-scoped headers, and any server-side session state bound to that TCP connection. The sandbox boundary held; the egress boundary did not. The retry is not a fresh call — it is a resumption wearing the costume of a fresh call. ## What Was Observed A tool call to a remote MCP server (`records.lookup`) timed out at the sandbox's 8s wall clock while the upstream server was still processing. The sandbox killed the tool process and returned a `ToolTimeout` to the agent loop. The agent's retry policy — standard exponential backoff, three attempts — reissued the identical `tools/call` 400ms later. The retry succeeded in 120ms. That is the anomaly: the original request had exceeded 8s of server-side work, and the retry returned in 120ms with a *populated* result. The result was correct for the original request, not the retry. The upstream server had completed the first request's work after the sandbox abandoned it, written the response to the still-open socket, and the proxy had buffered it. When the retry arrived on the same pooled connection, the proxy read the buffered response, matched it to the retry's request ID (the proxy rewrote the ID on reuse), and returned it. The retry never reached the upstream server at all. The failure is not that the answer was wrong. The failure is that the agent's *retry semantics* were violated: a retry is supposed to be a new attempt with independent failure probability, and instead it was a replay of an abandoned attempt's tail. Downstream, the agent recorded a successful tool call with a latency of 120ms and used that latency in a budget calculation, concluding the tool was fast and safe to call in a tight loop. It was not. The second-order observation: the same mechanism caused a *stale read* on a different tool. A `records.update` call timed out, was retried, and the retry's response was actually the buffered response to a `records.read` issued two calls earlier on the same pooled socket, because the proxy's response-to-request matching relied on sequential ordering rather than request ID, and the abandoned call's response had shifted the sequence by one. The agent believed an update succeeded and read back the pre-update value, then proceeded on the assumption that the write had been a no-op. ## Condition of Validity The failure requires four conditions to co-occur: 1. **The egress proxy pools upstream connections across tool calls.** If each tool call gets a fresh upstream connection (no pooling), the abandoned response has nowhere to land. 2. **The sandbox aborts the tool process without closing the proxy's upstream socket.** A timeout that kills the client but not the connection is the canonical trigger. So is a sandbox OOM, a capability-manifest revocation mid-call, or an agent-side cancellation. 3. **The upstream server continues processing after the client disconnects** (or the proxy continues to read the socket). Many MCP servers do not abort on client disconnect. 4. **The retry reuses the same pooled connection** and the proxy matches responses to requests by order or by a rewritten ID rather than by an end-to-end correlation token the sandbox controls. Remove any one condition and the failure does not occur. This is why it is non-obvious: it is invisible in single-call tests, invisible under low latency, and only appears when a call times out *and* the retry lands on the same pooled socket *and* the upstream completes the abandoned work in the window between. ## Decision Boundary The architectural invariant required is: **a tool-call retry must not share an egress connection with the attempt it is retrying.** Concretely, the runtime must enforce one of: - **Connection-per-attempt on retry:** the proxy marks a connection "poisoned" when the sandbox aborts a call that had an in-flight upstream request, and refuses to reuse it for any subsequent call in the same session. The connection is drained and closed, not returned to the pool. - **End-to-end correlation tokens:** the sandbox generates a per-attempt nonce, embeds it in the MCP request metadata, and the proxy discards any upstream response whose nonce does not match the currently active attempt. This requires the proxy to *not* rewrite request IDs and the upstream to echo the nonce. - **Drain-before-retry:** the retry policy waits for the proxy to confirm the abandoned connection is fully drained (no buffered bytes, upstream request acknowledged as cancelled or completed) before issuing the retry. This trades latency for correctness and is the safest option when the upstream does not support cancellation. The decision boundary is: if the proxy cannot prove the abandoned attempt's response has been consumed or discarded, the retry must open a new connection. "Prove" means a nonce match or a confirmed drain, not a heuristic timeout. ## Operational Effect Without this invariant, an agent's retry policy becomes a *replay policy* with unbounded, invisible consequences. The agent's error-handling logic — backoff, attempt counting, latency budgeting — operates on a model of independent attempts that the transport layer silently violates. The observable symptoms are: - Retries that succeed faster than the original call could possibly have, which the agent misreads as evidence of tool reliability. - Stale reads after timed-out writes, producing agents that act on pre-update state while believing the update committed. - Sequence-shifted responses when multiple calls share a pooled socket, where call N's response is delivered to call N+1. - Latency budgets that under-provision because fast "retries" are counted as normal calls. The guardrail is to make the egress boundary as strict as the sandbox boundary: an aborted attempt poisons its connection, and the retry is provably a new attempt or it does not run. The runtime should fail closed — if it cannot establish a clean connection for the retry, it should surface a `RetryUnsafeError` to the agent loop rather than silently reusing a tainted channel. ```python class EgressReuseViolation(RuntimeError): """Raised when a tool-call retry would reuse an egress connection that still carries state from an aborted attempt.""" pass class EgressProxy: def __init__(self): # connection_id -> {"nonce": str | None, "poisoned": bool, "drained": bool} self._conns = {} def mark_aborted(self, connection_id: str, attempt_nonce: str) -> None: conn = self._conns.setdefault(connection_id, {"nonce": None, "poisoned": False, "drained": False}) # The attempt was killed mid-flight; any buffered upstream response # belongs to this nonce and must never be delivered to another attempt. conn["poisoned"] = True conn["drained"] = False conn["nonce"] = attempt_nonce def confirm_drained(self, connection_id: str) -> None: conn = self._conns.get(connection_id) if conn is None: raise EgressReuseViolation(f"unknown connection {connection_id}") conn["drained"] = True conn["poisoned"] = False conn["nonce"] = None def acquire_for_retry(self, connection_id: str, retry_nonce: str) -> str: conn = self._conns.get(connection_id) if conn is None: # Fresh connection; safe. self._conns[connection_id] = {"nonce": retry_nonce, "poisoned": False, "drained": True} return connection_id if conn["poisoned"] and not conn["drained"]: # Invariant: a retry must not share a channel with the attempt # it is retrying. Fail closed rather than replay a stale response. raise EgressReuseViolation( f"refusing retry on connection {connection_id}: " f"aborted attempt nonce={conn['nonce']} not drained; " f"retry nonce={retry_nonce} would inherit buffered state" ) if conn["nonce"] is not None and conn["nonce"] != retry_nonce: raise EgressReuseViolation( f"nonce mismatch on {connection_id}: expected {conn['nonce']}, got {retry_nonce}" ) conn["nonce"] = retry_nonce return connection_id def issue_retry(proxy: EgressProxy, connection_id: str, retry_nonce: str) -> str: try: return proxy.acquire_for_retry(connection_id, retry_nonce) except EgressReuseViolation: # Surface to the agent loop as a hard failure; do not silently # open a new socket without recording why the old one was tainted. raise EgressReuseViolation( f"retry on {connection_id} blocked; agent must either " f"drain the aborted attempt or open a fresh connection" ) ```