What happens when an instance resumes an MCP stream after a torn SSE frame: silent tool-call duplication at the resumption boundary
**Date of Record:** 2026 December 1 **Scope:** Applies to MCP servers and clients using HTTP-native streaming transports (SSE over chunked HTTP, `text/event-stream`) with session resumption via `Last-Event-ID` and any form of backpressure (flow-controlled reader, bounded buffer, or write-block on the server). Does not apply to stdio transports, WebSocket transports with application-level acking, or to non-streaming request/response MCP bindings.
Core Distinction
The failure is not "the stream broke." Broken streams are expected and recoverable. The failure is that **the resumption boundary is defined by byte position, but the semantic unit of an MCP stream is the complete JSON-RPC message**, and those two boundaries do not coincide. When a server emits an SSE event and the client disconnects (or the server's write buffer fills and the connection is torn down by a timeout) *after the event bytes have been partially flushed*, the client's `Last-Event-ID` reflects the last *fully received and framed* event, not the last event the server *committed*. On resume, the server replays from its own notion of "last acknowledged," which is either (a) the last event it handed to the transport, or (b) the last event whose id the client echoed. Neither is guaranteed to equal the last event the client actually *processed into its agent state*.
The distinction that matters operationally: **transport-level resumption is at-least-once delivery of events, but agents require exactly-once *effects*.** A resumed stream that redelivers a `tools/call` result is a duplicate observation; a resumed stream that redelivers a `tools/call` *request* (server→client callback, or client→server retry) is a duplicate side effect. The gap between these is where agents corrupt their own state.
What Was Observed
Trace from a production incident, reduced to essentials. An MCP client (an agent runtime) holds a long-lived SSE stream to a tool server. The server pushes `notifications/progress` and, critically, `tools/call` responses carrying side-effecting results (e.g., "order created, id=8841").
- Server writes event `id: 40` (`tools/call` result, order 8841) into the HTTP response body. The write to the socket **partially succeeds**: the kernel accepts the headers and a prefix of the `data:` line, then the client's reader is slow (backpressure — the agent is blocked in a synchronous reasoning step and its event loop is not draining the socket).
- Server's write blocks. Its per-connection write deadline fires (e.g., 30s). The server **closes the connection** and records "last event id written to transport = 40" in its session store. It has *not* received any ack for 40.
- Client's reader eventually drains. It has a **torn frame**: `id: 40\ndata: {"jsonrpc":"2.0","id":"call-7","result":{"order_id":88` — no terminating `\n\n`. Per SSE spec the incomplete event is discarded. Client's last fully-framed event id is `39`. Client reconnects with `Last-Event-ID: 39`.
- Server, on resume, sees `39` and replays from `40`. **Event 40 is re-emitted.** This is correct at-least-once behavior.
- Client receives the *complete* event 40 this time, parses it, and executes the result-handling path: it records "order 8841 created" and, because the agent's tool-call bookkeeping keyed on `call-7` was **not** deduplicated (the first, torn copy never parsed, so no entry existed), it treats this as a fresh completion. If the agent's planner had *also* independently retried `call-7` during the disconnect window (a common pattern: "no response in N seconds → retry the tool call"), the server now has **two orders** (8841 and 8842) and the agent believes **one** completed.
The non-obvious part: the torn frame is *invisible*. The client never sees a parse error, never logs a malformed event, because the SSE parser correctly discards incomplete trailing data. The agent's telemetry shows a clean reconnect and a clean result. The duplication is only visible downstream, in the tool server's side effects, or in a `notifications/progress` sequence that jumps (39 → 40 → 40) if the client logs raw ids.
A second, quieter observation: under sustained backpressure the server's `notifications/progress` events are *coalesced or dropped* by the transport (bounded queue), but `tools/call` results are not, because they share the same stream and the same queue. So the agent's **progress view and its completion view diverge in their delivery guarantees** while sharing one channel. An agent that infers "task done" from progress monotonicity will mis-time; an agent that infers from result presence will double-count.
Condition of Validity
This boundary is *active* — the failure can occur — precisely when all of the following hold:
- **Resumption is id-based and server-authoritative** (`Last-Event-ID` echoed by client, replay decided by server), rather than client-acked with an explicit `notifications/ack` or equivalent application-level watermark.
- **The transport can tear mid-event**, i.e., the server writes events larger than a single `write()` return, or backpressure/timeouts can close the socket between the start and end of an event's bytes. Small events that fit in one flush are *not* immune if the kernel accepts partial writes, but the window is narrower.
- **The client's dedup key is the transport event id, and dedup state is populated only on successful parse.** If dedup is keyed on the JSON-RPC `id` (`call-7`) and the entry is written *before* side effects, the duplicate is caught. If it is keyed on SSE `id: 40` and written after parse, the torn copy leaves no trace and the replayed copy looks new.
- **The agent layer performs its own retry** on "no response within timeout" without coordinating with the transport's replay. Two independent at-least-once mechanisms compose into unbounded duplication.
It is *not* active when: the server uses a strictly monotonic application-level ack (client sends `Last-Event-ID` only after committing the event to durable agent state, and the server replays strictly after that id); or when all side-effecting results are idempotent and keyed on the JSON-RPC request id at the tool server.
Decision Boundary
The operational choice is where to put the **semantic watermark**. Three placements, with distinct failure profiles:
- **Transport watermark (SSE `id`).** Cheap, standard, but the watermark advances on *framing*, not on *commit*. This is the boundary that produces the incident above. Use only if every event is idempotent under replay.
- **Protocol watermark (JSON-RPC `id` dedup table).** Client maintains a set of seen `id`s, writes the entry *before* dispatching the result to agent state, and the entry survives reconnects. Catches transport replay, but **not** the agent's own retry (which uses a *new* JSON-RPC id for the same logical call unless the agent reuses ids). Requires the agent to reuse the request id on retry — a discipline most planners violate.
- **Application watermark (durable "committed through event N" record, advanced only after the side effect is durably recorded).** Most expensive, only correct one for non-idempotent side effects. The server must replay strictly *after* the committed watermark, and the client must not advance the watermark until the effect is persisted.
The decision rule: **if any event on the stream can cause a non-idempotent effect, the transport watermark is insufficient and you must run the application watermark.** If all effects are idempotent under `(jsonrpc_id, replay)`, the protocol watermark suffices. There is no configuration in which the raw SSE `id` alone is safe for side-effecting `tools/call` results.
A corollary boundary on backpressure: **never share one bounded queue between progress notifications and result messages.** Progress is lossy-tolerable; results are not. Separate them into distinct streams (distinct SSE endpoints or distinct event types with independent flow control), or the backpressure that drops a progress event will, under a full queue, drop or delay a result and widen the tear window.
Operational Effect
Concretely, after this boundary is crossed:
- **Duplicate side effects** at the tool server (two orders, two emails, two file writes) with a single logical completion in agent state. The agent's world model and the environment's ground truth diverge by exactly the number of replays.
- **Progress/completion skew**: the agent's `notifications/progress` view may show a task at 60% while the result event has already been delivered and replayed; planners that gate on progress will stall or double-fire.
- **Silent, non-reproducible**: the tear requires a specific interleaving of slow reader, write deadline, and event size. It will not reproduce in a fast local test; it appears under load, under large payloads, and under agent reasoning pauses — i.e., exactly in production.
- **Replay storms under flapping**: if the connection flaps repeatedly, each resume replays from the same watermark, and the duplication count grows with flap count, not with logical work.
The invariant required to bound it: **the client's resumption watermark must be advanced only after the corresponding effect is durably committed, and the server must replay strictly after that watermark; additionally, the agent's own retry path must reuse the JSON-RPC request id so that protocol-level dedup catches the agent's retry, not just the transport's replay.** Absent both, at-least-once transport × at-least-once agent retry = at-least-once-squared effects.
import hashlib
from dataclasses import dataclass, field
class ResumptionInvariantViolation(RuntimeError):
"""Raised when an MCP stream resume would replay an event whose effect
is not durably committed, or when a side-effecting result arrives for a
JSON-RPC id already dispatched without an idempotency key."""
@dataclass
class StreamSession:
# Durable application watermark: last event id whose EFFECT is committed.
committed_through: int = 0
# Protocol dedup: jsonrpc ids whose result has been dispatched.
dispatched: set = field(default_factory=set)
# Side-effect ledger: (jsonrpc_id, idempotency_key) -> effect fingerprint.
effects: dict = field(default_factory=dict)
def on_resume(self, last_event_id_seen: int, server_replay_from: int) -> int:
# Server must replay strictly AFTER the committed watermark, not after
# the last framed event id the client happened to parse.
if server_replay_from <= self.committed_through:
raise ResumptionInvariantViolation(
f"server replay_from={server_replay_from} <= committed_through="
f"{self.committed_through}; replay would re-deliver a committed "
f"effect (torn-frame duplicate)."
)
return server_replay_from
def on_result(self, jsonrpc_id: str, idempotency_key: str | None,
payload: bytes, side_effecting: bool) -> None:
if side_effecting and idempotency_key is None:
raise ResumptionInvariantViolation(
f"side-effecting result for id={jsonrpc_id} has no "
f"idempotency_key; replay cannot be deduplicated."
)
fp = hashlib.sha256(payload).hexdigest()
key = (jsonrpc_id, idempotency_key)
if key in self.effects and self.effects[key] != fp:
raise ResumptionInvariantViolation(
f"conflicting replay for {key}: prior={self.effects[key][:12]} "
f"new={fp[:12]}; non-idempotent effect diverged."
)
if jsonrpc_id in self.dispatched and not side_effecting:
# duplicate observation of a pure result: safe to drop
return
self.effects[key] = fp
self.dispatched.add(jsonrpc_id)
def commit(self, event_id: int) -> None:
# Advance the application watermark ONLY after the effect is durable.
if event_id <= self.committed_through:
raise ResumptionInvariantViolation(
f"non-monotonic commit: {event_id} <= {self.committed_through}"
)
self.committed_through = event_id