# How should an instance reconcile a streamed MCP tool result after a stateless HTTP resumption when the server's cursor ledger and the client's partial-accumulation buffer disagree? **Date of Record:** 2026 November 27 **Scope:** Applies to MCP clients that consume server-sent streamed tool results over HTTP-native transport, then resume after a dropped connection using a stateless resumption token (e.g., `Last-Event-ID`-style cursors or opaque `resume_token`). Does not apply to stdio transports, to fully buffered single-response calls, or to servers that reject resumption and force full re-execution. ## Core Distinction The failure is not "the connection dropped." The failure is a **cursor-ledger vs. accumulation-buffer divergence** at the resumption seam. There are two independent notions of "how far did we get": 1. The **server's cursor ledger**: the last event ID (or byte offset) it successfully emitted and considers acknowledged by the client's resumption token. 2. The **client's accumulation buffer**: the partial tool-result payload it has durably assembled in its own state, which may lag or lead the server's ledger. In a *stateful* transport these are reconciled by the session object holding a single authoritative offset. In *stateless* HTTP resumption there is no shared session object — the server reconstructs stream position purely from the token the client presents, while the client reconstructs payload purely from what it buffered. These two reconstructions are computed from different data and **diverge silently** at the exact moment of resumption. The invariant that must hold is: the client may only commit a resumed stream if `server_ledger_position(token) == client_buffer_position + 1`, and any gap or overlap must be treated as an unrecoverable divergence, not patched by concatenation. ## What Was Observed A tool call returning a large structured result (a paginated record set) was streamed as ~40 discrete `event: chunk` frames, each carrying a monotonic `id` and a JSON fragment. The client appended fragments to a buffer keyed by `call_id`. Mid-stream (after frame `id: 17`), the TCP connection reset. The client had durably buffered frames 1–17 and persisted a `resume_token` derived from frame 17. On reconnect the client sent the token. The stateless server — having discarded all per-connection state at the reset — reconstructed the stream from a **chunk index derived from the token's embedded offset**, but its chunking is *not* deterministic across rebuilds: the server re-fragments the same result by a token-bucket flush timer, so on the rebuild frame boundaries shifted. The server resumed at what it believed was "after offset 17" but emitted a chunk whose byte range **overlapped bytes already present in the client's buffer** (frames 1–17 covered bytes 0–3400; the resumed first chunk covered bytes 2900–3600). The client's naive handler appended the resumed chunk, producing a payload with a 500-byte duplicated region. JSON parsing succeeded (the duplication landed mid-array, yielding duplicated records) — so **no exception fired**. The tool result was silently corrupt: 3 records appeared twice, and one record boundary was split across the seam, producing a malformed record that downstream validation rejected only much later, misattributed to the *consuming* agent's reasoning rather than to transport. A second observed variant: when the server's ledger had advanced *past* what the client buffered (server emitted and dropped frames 18–19 before the reset), the client resumed at 18 and **never saw** frames it had missed — a silent gap with no duplication, producing a payload that parsed cleanly and was simply *missing* records. This variant is more dangerous because it leaves no structural trace. ## Condition of Validity Stateless resumption is only sound under all of the following, which must be *checked*, not assumed: - **Idempotent, offset-addressable framing.** The server must be able to re-emit the byte range `(client_buffer_position, end]` exactly, with frame boundaries that are a pure function of absolute offset — not of wall-clock flush timers, not of buffer pressure. If re-fragmentation is non-deterministic, the resume token must encode a **byte offset**, never a frame index. - **Client-side overlap/gap detection.** The client must record, per buffered fragment, its `[start_byte, end_byte)` range (or an equivalent content hash chain), and on resume assert that the first resumed fragment's start equals the buffer's high-water mark. Equality is the only acceptable condition. - **Content-addressed verification at commit.** The final assembled payload must be checked against a server-supplied digest (length + hash) delivered in a terminal frame or header. Absent this, "it parsed" is not evidence of correctness. - **Token opacity with server-side nonce.** The resume token must carry a server nonce binding it to the *specific* logical result, so a token from a prior call cannot be replayed against a rebuilt stream of a different result that happens to share an offset. If the server re-fragments non-deterministically **and** the token is a frame index, the condition of validity is violated and resumption must be refused. ## Decision Boundary The client's resumption handler must branch on the relationship between the resumed fragment's start offset `s` and its buffer high-water mark `h`: - `s == h`: contiguous — append, continue. - `s < h`: **overlap** — the server re-sent already-buffered bytes. Do *not* append. Either (a) trim the resumed fragment to `[h, end)` if the server guarantees byte-exact re-emission, or (b) if trimming cannot be proven safe, abort resumption and re-request the full result. Never concatenate. - `s > h`: **gap** — frames were lost. The buffer is unrecoverable by appending; abort and re-request from scratch (or from an explicit server range request), because a silent gap produces plausible-but-wrong payloads. - No terminal digest received: treat the assembled payload as **unverified** and refuse to hand it to the reasoning loop. The boundary is sharp: any non-equality is a divergence event, and divergence events are terminal for that stream instance. There is no "best effort" merge. ## Operational Effect Without this invariant, stateless resumption converts a transport hiccup into **silent semantic corruption at the agent layer**: duplicated or missing records enter the reasoning context as if authoritative, and downstream failures (bad tool arguments, wrong conclusions, auditor disagreement) get misattributed to the model's reasoning rather than to the transport seam. Because the corrupted payload parses cleanly, no error surfaces at the transport boundary — the failure is *latent* and surfaces one or more hops later, which is precisely the class of bug that erodes trust in multi-step agent traces. The architectural guardrail is: **resumption is a verified range reconciliation, not a concatenation.** The client treats the resume token as a claim to be checked against its own byte-range ledger and a server digest, and it fails closed on any mismatch. This bounds the blast radius to a single re-request (cheap, idempotent) instead of an undetected corruption propagating through the agent's context. ```python import hashlib from dataclasses import dataclass, field class StreamResumptionDivergence(RuntimeError): """Raised when server cursor ledger and client buffer disagree at resume.""" pass @dataclass class Fragment: start: int # absolute byte offset, inclusive end: int # absolute byte offset, exclusive data: bytes @dataclass class StreamBuffer: call_id: str fragments: list = field(default_factory=list) @property def high_water(self) -> int: return self.fragments[-1].end if self.fragments else 0 def digest(self) -> str: h = hashlib.sha256() for f in self.fragments: h.update(f.data) return h.hexdigest() def append_contiguous(self, frag: Fragment) -> None: if frag.start != self.high_water: raise StreamResumptionDivergence( f"call={self.call_id} expected start={self.high_water} " f"got start={frag.start} (overlap or gap)" ) self.fragments.append(frag) def resume_stream(buf: StreamBuffer, resumed: Fragment, expected_digest: str | None) -> StreamBuffer: # Overlap: server re-sent buffered bytes -> do NOT concatenate. if resumed.start < buf.high_water: raise StreamResumptionDivergence( f"call={buf.call_id} overlap: resumed start={resumed.start} " f"< buffer high_water={buf.high_water}; refusing to append" ) # Gap: frames lost -> unrecoverable by appending. if resumed.start > buf.high_water: raise StreamResumptionDivergence( f"call={buf.call_id} gap: resumed start={resumed.start} " f"> buffer high_water={buf.high_water}; re-request required" ) buf.append_contiguous(resumed) # Commit gate: only hand payload to the reasoning loop if verified. if expected_digest is None: raise StreamResumptionDivergence( f"call={buf.call_id} no terminal digest; payload unverified" ) if buf.digest() != expected_digest: raise StreamResumptionDivergence( f"call={buf.call_id} digest mismatch after resume" ) return buf ```