# Which invariants prevent MCP streamable-HTTP resumption from silently replaying a poisoned chunk after SSE fallback negotiation **Date of Record:** 2026 November 24 **Scope:** Applies to MCP servers and clients using HTTP-native transport where a POST returns a streamable chunked body that may degrade to a resumable SSE stream negotiated via `Last-Event-ID` / `Mcp-Session-Id`. Does not cover pure stdio transport, WebSocket-based MCP bridges, or stateless one-shot JSON responses with no resumption path. ## Core Distinction The failure here is not "the stream dropped." Dropped streams are the expected, benign case that resumption was designed for. The failure is that **resumption and fallback negotiation share a cursor namespace but not a cursor contract**. A streamable chunked response emits ordered frames with an implicit byte/sequence position; the SSE fallback emits frames keyed by an explicit `id:` field that the client echoes as `Last-Event-ID`. When a client transitions from a chunked read to an SSE resume mid-response, the two position models are reconciled by the server, and the reconciliation is where a frame that was already *partially observed and acted upon* by the agent can be re-emitted as if it were new. The distinction that matters operationally: a **replayed tool-result frame** is indistinguishable, at the client's stream parser, from a **fresh tool-result frame** unless an idempotency key exists at a layer above the transport. The transport invariant "resume delivers each frame at least once" is correct and necessary; it is dangerously incomplete without the companion invariant "the agent's action layer deduplicates by frame identity, not by arrival order." ## What Was Observed A tool-calling agent issued `POST /mcp` with `Accept: application/json, text/event-stream`. The server responded `200` with `Transfer-Encoding: chunked` and `Content-Type: text/event-stream` (streamable mode). The first three SSE frames arrived: an `id: 41` `notifications/progress`, an `id: 42` `tools/call` result containing a destructive action descriptor (`fs.delete` on a scratch path), and then the connection was severed by an intermediate proxy at ~90 seconds — a classic idle-timeout kill, not a server fault. The client, on reconnect, sent `GET /mcp` with `Last-Event-ID: 42` plus `Mcp-Session-Id: sess-7f3a`. The server's session store had recorded the highest *acknowledged* event as `40` — because the write of `41`/`42` to the durable event log was committed *after* the chunked socket flush (write-through-to-socket, write-behind-to-log). On resume the server replayed from its log cursor: `41`, `42`, then `43`. The client saw `41` and `42` a second time. Its SSE parser, being a dumb line reader, dispatched both to the agent loop. The agent executed `fs.delete` twice. The second execution failed with `ENOENT` and the agent's error-compounding logic escalated it into a retry storm against a path that no longer existed, consuming 14k tokens of recovery reasoning before the token budget aborted the task. The non-obvious part: **the client had correctly sent `Last-Event-ID: 42`.** The bug was not a missing resume header. It was that the server's durable cursor lagged the wire cursor, and the SSE fallback path trusted the durable cursor as authoritative for replay while the chunked path had trusted the socket as authoritative for delivery. Two transports, two different definitions of "delivered," one shared id space. ## Condition of Validity The at-least-once replay guarantee of SSE resumption is *safe* only under the conjunction of: 1. **Frame identity is stable and content-addressed.** Every frame carries an `id` that is a deterministic function of its payload (or a monotonic server-assigned sequence written to the log *before* the socket flush), so a replayed frame is byte-identical to its first emission and the client can hash it. 2. **The action layer is idempotent by frame id, not by arrival.** The agent maintains an executed-frame set keyed on `(Mcp-Session-Id, event id, payload hash)`. Re-dispatch of a seen key is a no-op, not a re-execution. 3. **The cursor is committed before the frame is observable.** Write-ahead-to-log then flush-to-socket. If the log write can fail after the socket flush, the resume cursor is not a valid replay origin and must be rejected, not clamped. 4. **Fallback negotiation is explicit, not silent.** When a server degrades from streamable chunked to resumable SSE, it must signal the transport change (e.g., a `notifications/message` with a `transport` field, or a distinct `Content-Type` renegotiation) so the client can reset its ordering assumptions and switch to id-keyed dedup before the first replayed frame arrives. The invariant fails — and this is the boundary — when any one of these is violated *and* a destructive or non-idempotent tool call sits between the wire cursor and the durable cursor. Read-only tool calls tolerate the violation invisibly; that is why it survives testing and detonates in production on the first `fs.delete` or `payments.charge`. ## Decision Boundary The operational rule an agent must encode: - **Trust the wire cursor for ordering; never trust it for exactly-once.** The `Last-Event-ID` you send is a *request*, not a *guarantee*. The server may replay from an earlier point. - **Before executing any tool call whose frame arrives via a resumed stream, verify frame novelty.** Compute `hash(session_id || event_id || canonical(payload))` and check against the executed-frame set. If present, drop and log a `replay-suppressed` event; do not re-execute, do not re-reason about it. - **Treat a transport-mode transition as a cursor reset.** If the response `Content-Type` or a transport notification changes between the original stream and the resume, treat all frames on the new stream as *potentially replayed* until one frame's id exceeds the highest id you successfully executed *and* its payload hash is novel. - **Refuse to resume across a destructive boundary without an idempotency token.** If the pending tool call is non-idempotent and the resume cursor is not provably ahead of the last executed frame, the correct action is to abort the resume and surface a `ResumeAmbiguity` to the orchestrator — not to guess. The boundary is precise: the moment a stream is resumed, the agent's certainty about "what has already happened" drops from *exactly-once* to *at-least-once*, and any downstream action that assumed the former must be gated. ## Operational Effect Without these guards, the failure signature is: duplicated side effects on exactly the tool calls that are least safe to duplicate, followed by error-compounding recovery loops that consume disproportionate token budget on a task that was already 90% complete. The agent does not crash; it *thrashes*, which is worse, because the thrash is invisible in success metrics until the side effect is audited. With the guards, a replay is downgraded to a logged no-op, the resume completes, and the only cost is one suppressed-frame log line per replayed event. The architectural takeaway: **at-least-once delivery is a transport property; exactly-once execution is an application invariant that the transport cannot supply and must not be assumed to supply.** The two transports in a fallback pair will always disagree about "delivered" at the margin; the agent's dedup layer is the only place that disagreement can be safely reconciled. ```python import hashlib import json from dataclasses import dataclass, field class ResumeAmbiguity(RuntimeError): """Raised when a resumed stream cannot be proven ahead of the last executed frame.""" class ReplaySuppressed(Exception): """Raised (and caught) when a replayed frame is correctly deduplicated.""" @dataclass class FrameDeduper: session_id: str executed: set = field(default_factory=set) highest_executed_id: int = -1 def _key(self, event_id: int, payload: dict) -> str: canon = json.dumps(payload, sort_keys=True, separators=(",", ":")) return hashlib.sha256( f"{self.session_id}|{event_id}|{canon}".encode() ).hexdigest() def admit(self, event_id: int, payload: dict, *, resumed: bool, destructive: bool, cursor_ahead: bool) -> None: key = self._key(event_id, payload) if key in self.executed: raise ReplaySuppressed(f"replay of event {event_id} suppressed") if resumed and destructive and not cursor_ahead: # Cannot prove this frame is novel relative to side effects. raise ResumeAmbiguity( f"resume cursor not ahead of last executed frame " f"(last={self.highest_executed_id}, incoming={event_id}); " f"refusing to execute destructive call on ambiguous stream" ) self.executed.add(key) self.highest_executed_id = max(self.highest_executed_id, event_id) def handle_resumed_frame(deduper: FrameDeduper, event_id: int, payload: dict, tool_name: str, cursor_ahead: bool) -> str: destructive = tool_name in {"fs.delete", "payments.charge", "db.drop"} try: deduper.admit(event_id, payload, resumed=True, destructive=destructive, cursor_ahead=cursor_ahead) except ReplaySuppressed: return "suppressed" return "executed" ```