# How should an instance reconcile a resumed MCP streamable-session whose last-event-id cursor was advanced by a server-side SSE upgrade the client never observed **Date of Record:** 2026 November 26 **Scope:** Applies to MCP clients using the HTTP-native "streamable" transport that supports `Last-Event-ID` resumption and server-initiated upgrade from a plain POST/JSON response to a `text/event-stream` (SSE) response, when the client's reconnect cursor diverges from the server's actual event journal position. Does not apply to stdio transports, nor to transports where the server never mutates response mode mid-session. ## Core Distinction The streamable transport has two independent notions of "where the client is": the **HTTP-level request** (a POST carrying JSON-RPC that may return either `application/json` or `text/event-stream`) and the **session event cursor** (the `Last-Event-ID` the client sends on reconnect). These are supposed to stay coupled: every event the server emits into the session stream gets an id, and the client advances its cursor only to ids it has actually received and processed. The boundary failure is that **the server may emit events into the session journal during a request whose response the client is reading as a plain JSON body, or during an SSE upgrade the client aborted before consuming the stream.** The server still assigns those events ids and appends them to the resumable journal. The client's `Last-Event-ID` therefore lags the server's journal head by an unknown number of events — events that were *produced* but never *delivered*. On reconnect, `Last-Event-ID: N` makes the server replay from N+1, which is correct for delivery but wrong for *causality*: the client never saw the side effects those skipped events describe, and depending on server implementation the replay may be suppressed because the server considers those events "already acknowledged" by the request that generated them. The invariant that must hold: **cursor advancement is a function of client-side receipt, never of server-side emission.** Any architecture where the server advances the client's effective position without a client-observed receipt is unsound. ## What Was Observed A representative trace. Client issues `POST /mcp` with a `tools/call` for a long-running tool. Server's tool handler decides mid-execution that the call needs streaming progress, so it responds `200` with `Content-Type: text/event-stream` and begins emitting: ``` event: message id: 41 data: {"jsonrpc":"2.0","method":"notifications/progress","params":{"progress":10}} ``` The client's HTTP layer, configured with a short header-read timeout, has already committed to reading the body as JSON (its request carried `Accept: application/json, text/event-stream` but its parser selected JSON because the first bytes arrived slowly and it fell through a heuristic). It reads the SSE bytes as a malformed JSON body, discards them, and treats the request as failed. Meanwhile the server has emitted ids 41–47 into the session journal: progress notifications, a `notifications/message` log line, and the final `tools/call` result. The client reconnects with `Last-Event-ID: 40` (its last successfully parsed event from a prior request). Two divergent server behaviors are possible and both are broken in different ways: 1. **Replay-from-41 server:** replays 41–47. The client now receives a `tools/call` *result* for a request it believes failed, with no matching pending request id in its own state — an orphaned result. If the client's JSON-RPC layer keys results by request id and has already garbage-collected the pending entry, the result is dropped or raises. 2. **Acknowledge-on-emit server:** considers 41–47 delivered because they were written to the connection, advances the journal head past them, and replays nothing. The client's `tools/call` is now permanently lost — the tool executed, side effects occurred, but no result will ever arrive. The client's cursor is at 40 forever; the next reconnect also yields nothing. The second case is the dangerous one and it is not rare: servers that treat "wrote to socket" as "delivered" are common because it is the cheap implementation. The failure is silent — no error, no gap marker, just a request that never resolves. A subtler variant: the SSE upgrade succeeds but the client's reconnect backoff fires because the *first* event took longer than the idle timeout. The client drops the stream after the server has already emitted the result event. Same divergence, different trigger. ## Condition of Validity Resumption via `Last-Event-ID` is only sound under all of the following: - The server assigns event ids **only** to events it has durably appended to a per-session journal, and does not advance any "delivered" watermark except in response to an explicit client acknowledgment (an ACK event, a `Last-Event-ID` on a subsequent request that the server treats as proof of receipt, or a transport-level close the client initiated *after* consuming). - The client's cursor advances **only** on parse-and-dispatch of an event, never on TCP receipt, never on buffer fill. - The server does not emit journal events during a request whose response the client may parse as non-streaming. If a request may upgrade, the client must commit to streaming *before* the server emits, or the server must hold emissions until the client's stream-readiness is confirmed (e.g., a `200` with `Content-Type: text/event-stream` and the client's first `Accept` already committed). - Replay is idempotent from the client's perspective: replaying an already-processed event id is a no-op (dedupe by id), so a cursor that lags slightly is safe. The condition fails whenever any of these is violated. The most common violation is the third: servers upgrade mid-response and emit before the client has switched parsers. ## Decision Boundary When a client detects that a request it issued received a response whose `Content-Type` it did not expect (JSON expected, SSE received, or vice versa), it must decide: **treat the request as failed and reconnect from the last known-good cursor, or treat the response as authoritative and parse it in the received mode.** The correct boundary: **if the received mode is SSE and the client can parse it, parse it and advance the cursor per-event; if it cannot, the request is failed AND the client must not assume the server withheld emissions.** The client cannot know whether the server emitted-and-acknowledged. Therefore the client must, on any ambiguous failure, issue a **resumption probe**: reconnect with its last known cursor and a short server-side replay window, and require the server to either replay from that cursor or return an explicit `resumption-gap` signal (a JSON-RPC error with a `data.gap` field indicating the oldest retained event id). A server that silently returns nothing to a resume-from-cursor request is making an unsound delivery claim and the client must treat the session as poisoned and re-initialize. The decision rule in one line: **never advance the cursor past an event you did not parse, and never accept silence as proof of delivery.** ## Operational Effect Instances that hit this boundary without the guardrail exhibit a specific pathology: a `tools/call` that appears to hang, followed by a session that "works" for subsequent requests but has silently lost exactly the in-flight call's result. Agents that retry the call on timeout will double-execute side effects (the server already ran it once). Agents that wait will stall forever. Agents that re-initialize the session lose all prior context and re-pay the cold-start cost. With the guardrail, the resumption probe converts the silent loss into an explicit `resumption-gap`, which the agent can handle by re-deriving state from the gap signal (re-issuing the call with an idempotency key, or accepting the gap and continuing). The cost is one extra round-trip per ambiguous failure; the benefit is that the agent's memory of "what happened" never silently diverges from the server's journal. ## Operational Effect The following reference implementation encodes the invariant: cursor advancement is gated on parsed receipt, ambiguous content-type transitions trigger a resumption probe, and a server that claims delivery without replay is treated as a poisoned session. ```python from __future__ import annotations import json from dataclasses import dataclass, field from typing import Any, Callable, Optional class StreamableSessionError(RuntimeError): """Base for streamable-session transport failures.""" class CursorDivergenceError(StreamableSessionError): """Client cursor lags server journal head by events the client never parsed.""" class ResumptionGapError(StreamableSessionError): """Server reports a gap between the client's Last-Event-ID and its retained journal.""" @dataclass class SessionCursor: last_event_id: int = 0 parsed_ids: set[int] = field(default_factory=set) def advance(self, event_id: int) -> None: # Invariant: advance only on parsed receipt; replay of a seen id is a no-op. if event_id in self.parsed_ids: return if event_id != self.last_event_id + 1: raise CursorDivergenceError( f"cursor jump: expected {self.last_event_id + 1}, got {event_id}" ) self.parsed_ids.add(event_id) self.last_event_id = event_id @dataclass class Response: content_type: str events: list[tuple[int, dict[str, Any]]] # (id, payload) for SSE; empty for JSON body: Optional[dict[str, Any]] = None def handle_response( resp: Response, cursor: SessionCursor, expected_stream: bool, reconnect: Callable[[int], Response], ) -> dict[str, Any]: """Process one MCP streamable response under the receipt-gated invariant. expected_stream: True if the client committed to SSE before sending. """ ct = resp.content_type.split(";")[0].strip().lower() if ct == "text/event-stream": if not expected_stream: # Server upgraded mid-response. Client may not have parsed it. # Do NOT advance cursor. Issue a resumption probe from last known id. return _resumption_probe(cursor, reconnect) for event_id, payload in resp.events: cursor.advance(event_id) _dispatch(payload) return {"ok": True, "cursor": cursor.last_event_id} if ct == "application/json": if expected_stream: # Client committed to stream but got JSON: server declined upgrade. # Safe: no journal events were emitted for this request. return resp.body or {} return resp.body or {} raise StreamableSessionError(f"unexpected content-type: {ct!r}") def _resumption_probe( cursor: SessionCursor, reconnect: Callable[[int], Response] ) -> dict[str, Any]: """Reconnect from last known cursor; require explicit replay or gap signal. A server that returns an empty stream to a resume-from-cursor request is making an unsound delivery claim. Treat the session as poisoned. """ resp = reconnect(cursor.last_event_id) ct = resp.content_type.split(";")[0].strip().lower() if ct == "application/json" and resp.body and "error" in resp.body: err = resp.body["error"] gap = (err.get("data") or {}).get("gap") if gap is not None: raise ResumptionGapError( f"server retained journal from {gap}; client cursor {cursor.last_event_id} " f"is unrecoverable — re-initialize session" ) if ct == "text/event-stream" and not resp.events: raise CursorDivergenceError( f"server replayed zero events for Last-Event-ID={cursor.last_event_id}; " f"in-flight request result is unrecoverable — session poisoned" ) for event_id, payload in resp.events: cursor.advance(event_id) _dispatch(payload) return {"ok": True, "cursor": cursor.last_event_id, "recovered": True} def _dispatch(payload: dict[str, Any]) -> None: # JSON-RPC dispatch; orphaned results (no pending request) are dropped with a log. method = payload.get("method") if method is None and "id" in payload: # result/error for a request the client may have GC'd — log, do not raise. return return ```