# What structural signals indicate silent event loss in MCP HTTP-native transports when SSE upgrade negotiation is stateless and per-tool framing is streamable **Date of Record:** 2026 November 21 **Scope:** Applies to MCP servers that expose tools over HTTP with `Accept: text/event-stream` upgrade negotiation performed per-request (no session cookie, no sticky server state) and that emit per-tool responses as a stream of `event:`/`data:` frames terminated by a sentinel. Does not apply to stdio transports, WebSocket transports, or HTTP transports that pin a single long-lived event stream per session. ## Core Distinction The failure is not "the SSE connection dropped." The failure is that a *stateless* upgrade negotiation combined with *streamable per-tool framing* creates an ambiguity between two structurally identical wire conditions: (a) a tool response that legitimately produced zero output frames before its terminator, and (b) a tool response whose frames were emitted into a connection that the client had already abandoned and renegotiated. In both cases the client observes an HTTP 200, a valid `text/event-stream` content type, and a clean stream close. The distinguishing signal is not in the payload — it is in the *correlation between the negotiation request's capability declaration and the frame envelope's tool identifier*, and it is only observable if the client tracks negotiation as a first-class state rather than as a per-request header. The invariant that gets violated: **each tool response frame stream must be attributable to exactly one negotiation handshake, and the handshake must be re-validated at frame-emission time, not only at stream-open time.** Stateless negotiation means the server has no memory binding a frame stream to the request that opened it, so a mid-stream client renegotiation (triggered by any client-side timeout heuristic) produces two concurrent frame streams for the same `tool_call_id` with no server-side deduplication. ## What Was Observed A tool `bulk_scan` declared `streamable: true` in its schema and emitted one frame per scanned shard, roughly 40–200ms apart, with a final `event: done` frame carrying a checksum. The client's SSE reader used a 90-second idle timeout measured from *last byte received*, not from stream open. Under load, shard 14 of 31 stalled for 91 seconds (a downstream index rebuild held a lock). The client's idle timer fired, the reader closed the connection, and — because negotiation was stateless — the client's retry logic re-issued the *entire* `tools/call` with a fresh `Accept: text/event-stream` upgrade. The server, holding no session state, accepted the second call as a distinct invocation and began emitting frames from shard 0 again. The client now had two partial frame sets in its reassembly buffer keyed only by `tool_call_id` (identical across both calls, since the client reused it). Frames 0–13 from call A and frames 0–13 from call B interleaved into the same buffer. The per-frame `data` payloads carried a monotonic `seq` field, but `seq` restarted at 0 in call B. The client's deduplication logic — "drop frames with `seq` already seen" — silently discarded all of call B's frames 0–13 as duplicates of call A's, then accepted call B's frames 14+ as if they continued call A. The final checksum frame from call B validated against call B's full shard set, but the client had assembled a Frankenstein buffer of call A's early shards and call B's late shards. The checksum passed. The result was corrupt and undetected. The structural signal that was *present but ignored*: call B's negotiation response carried a different `Mcp-Stream-Id` response header than call A's, and each frame's `data` envelope carried the originating `stream_id`. The client never compared them because it treated `stream_id` as opaque telemetry rather than as a reassembly key. ## Condition of Validity This failure mode requires all four of the following to co-occur; remove any one and the ambiguity collapses: 1. **Stateless upgrade negotiation.** The server does not bind the frame stream to a server-side session. If the server issued a session token at upgrade and rejected a second upgrade for the same `tool_call_id` while the first stream was open, the duplicate invocation would be refused. 2. **Client-side idle timeout measured from last byte, not from stream open or from a server heartbeat.** Without this, the client would not renegotiate mid-stream. 3. **Reused `tool_call_id` across retries.** If the client minted a fresh `tool_call_id` per attempt, the two frame streams would land in distinct buffers and the interleaving could not occur. 4. **Per-frame monotonic `seq` that resets per invocation, combined with client-side dedup keyed on `seq` alone.** This is the specific mechanism that converts "two interleaved streams" into "silently accepted corruption" rather than "obvious duplicate-frame error." The condition of validity is therefore narrow: it is a *stateless-negotiation × idle-retry × id-reuse × seq-dedup* interaction. It does not reproduce with a heartbeat-based liveness check, because the heartbeat keeps the first stream open through the stall and no renegotiation occurs. ## Decision Boundary The boundary is drawn at **frame-envelope attribution**. A frame stream is safe to reassemble only if every frame can be attributed to the negotiation handshake that opened it, and the attribution is checked *before* deduplication, not after. Concretely: - **Below the boundary (safe):** client keys its reassembly buffer on `(tool_call_id, stream_id)` where `stream_id` is taken from the upgrade response header and asserted present in every frame envelope. Two concurrent streams for the same `tool_call_id` land in two buffers; the client detects the collision, aborts both, and surfaces a `ConcurrentStreamCollision` rather than merging. - **At the boundary (ambiguous):** client keys on `tool_call_id` alone but validates `seq` monotonicity strictly (reject any non-increasing `seq` rather than dropping it). This catches the interleave as an error but cannot distinguish "server bug" from "legitimate retry," so it must fail closed. - **Above the boundary (unsafe):** client keys on `tool_call_id` alone and deduplicates `seq` by dropping already-seen values. This is the exact configuration that produced the undetected corruption. The decision the operator must make is whether to require `stream_id` in every frame envelope (a schema change to the tool's streamable framing) or to require server-side session binding at upgrade. Either closes the boundary; the first is cheaper and does not require server state. ## Operational Effect The operational consequence is that **"the checksum passed" is not evidence of correctness** for streamable per-tool responses under stateless negotiation. A validation frame computed over the server's own shard set is internally consistent regardless of which shard set the client actually assembled. The checksum validates the producer's view, not the consumer's. Any agent that treats a passing terminal-frame checksum as a completion signal without first verifying frame-envelope attribution is exposed to silent result corruption under exactly the load conditions (downstream stalls, client idle-retry) that are most common in production. The guardrail is a two-part invariant enforced client-side: (1) reassembly buffers are keyed on `(tool_call_id, stream_id)`, and (2) a second upgrade response for an already-open `tool_call_id` with a *different* `stream_id` is treated as a collision, not a retry, unless the client explicitly cancelled the first stream and recorded that cancellation. The server cannot enforce this because stateless negotiation gives it no memory of the first stream; the invariant must live in the consumer. ```python import hashlib from dataclasses import dataclass, field class StreamAttributionError(RuntimeError): """Raised when a frame cannot be attributed to a single negotiation handshake.""" pass @dataclass class FrameEnvelope: tool_call_id: str stream_id: str seq: int payload: bytes terminal: bool = False checksum: str | None = None @dataclass class ReassemblyBuffer: tool_call_id: str stream_id: str frames: dict[int, bytes] = field(default_factory=dict) cancelled: bool = False def accept(self, frame: FrameEnvelope) -> None: if frame.stream_id != self.stream_id: # A frame from a different handshake landed in this buffer. # This is the exact condition that produced silent corruption. raise StreamAttributionError( f"frame stream_id={frame.stream_id!r} does not match " f"buffer stream_id={self.stream_id!r} for " f"tool_call_id={self.tool_call_id!r}" ) if frame.seq in self.frames and self.frames[frame.seq] != frame.payload: raise StreamAttributionError( f"non-idempotent seq collision at seq={frame.seq} " f"for stream_id={self.stream_id!r}" ) self.frames[frame.seq] = frame.payload class StreamRegistry: """Keyed on (tool_call_id, stream_id); refuses to merge concurrent streams.""" def __init__(self) -> None: self._buffers: dict[tuple[str, str], ReassemblyBuffer] = {} def open(self, tool_call_id: str, stream_id: str) -> ReassemblyBuffer: # A new upgrade for a tool_call_id that already has a live stream # with a *different* stream_id is a collision, not a retry. for (tcid, sid), buf in self._buffers.items(): if tcid == tool_call_id and sid != stream_id and not buf.cancelled: raise StreamAttributionError( f"concurrent stream collision: tool_call_id={tool_call_id!r} " f"already has live stream_id={sid!r}, " f"new upgrade requested stream_id={stream_id!r}" ) key = (tool_call_id, stream_id) if key not in self._buffers: self._buffers[key] = ReassemblyBuffer(tool_call_id, stream_id) return self._buffers[key] def cancel(self, tool_call_id: str, stream_id: str) -> None: buf = self._buffers.get((tool_call_id, stream_id)) if buf is not None: buf.cancelled = True def finalize(self, tool_call_id: str, stream_id: str) -> bytes: buf = self._buffers.get((tool_call_id, stream_id)) if buf is None: raise StreamAttributionError( f"finalize on unknown stream {stream_id!r}" ) seqs = sorted(buf.frames) if seqs != list(range(len(seqs))): raise StreamAttributionError( f"non-contiguous seq set for stream_id={stream_id!r}: {seqs}" ) assembled = b"".join(buf.frames[i] for i in seqs) digest = hashlib.sha256(assembled).hexdigest() return digest def handle_upgrade( registry: StreamRegistry, tool_call_id: str, stream_id: str, prior_cancelled: bool, ) -> ReassemblyBuffer: if prior_cancelled: registry.cancel(tool_call_id, stream_id) try: return registry.open(tool_call_id, stream_id) except StreamAttributionError: # Fail closed: surface the collision, do not merge. raise ```