# Which invariants prevent SSE-to-POST upgrade negotiation from silently orphaning a resumable MCP session **Date of Record:** 2026 November 29 **Scope:** Applies to MCP servers and clients using the HTTP-native transport with streamable sessions, where a client may resume an interrupted SSE event stream by replaying the last observed event ID via a POST request. Does not apply to stdio transport, nor to stateless HTTP request/response servers that do not advertise `Last-Event-ID` resumability. ## Core Distinction The failure is not "the connection dropped." Connections drop constantly and the protocol is designed for it. The failure is a **negotiation skew between the two halves of the streamable transport**: the SSE leg (server→client, carrying server-initiated notifications and the response continuation) and the POST leg (client→server, carrying the client's tool-call results and the resume request). A session is resumable only if the server's event log and the client's `Last-Event-ID` cursor agree on a single linear sequence. When the upgrade handshake completes on the POST leg *before* the SSE leg has been re-bound to the same session, the server accepts the resume, replays events into a stream that no longer has a reader, and advances its event log past the client's cursor. The client, meanwhile, believes it is resuming and waits for events that were already flushed to a dead sink. Both sides report success. The session is orphaned: alive on the server, unreachable by the client, and no error is raised on either side. The invariant that must hold is: **at every instant, the server's `last_emitted_event_id` and the client's `last_consumed_event_id` must be monotonic and the gap between them must be replayable from the server's retained log.** The upgrade negotiation is the precise moment this invariant is most fragile, because it is the only point where the two legs are briefly decoupled. ## What Was Observed A streamable-session server (event log retention: 512 events or 5 minutes, whichever is longer) fronted by a load balancer with a 60-second idle timeout on SSE connections. A client agent executed a multi-step tool sequence: `search → fetch → synthesize`. Each step is a POST; each POST returns `202 Accepted` with a `Mcp-Session-Id` header and the actual result arrives as an SSE `event: message` frame on the long-lived GET stream. At step `fetch`, the tool call took 71 seconds (a large document fetch). The load balancer killed the SSE connection at 60 seconds of inactivity—inactivity measured on the *SSE* leg, which had emitted nothing since the POST was issued, even though the POST leg was active. The client's SSE reader saw `ECONNRESET` at T+60s. The client library, correctly, did not treat this as a task failure. It recorded `last_consumed_event_id = 47` and scheduled a resume. The resume logic issued a GET with `Last-Event-ID: 47`. The server re-bound the session, replayed events 48–52 (the `fetch` progress notifications), and the client consumed them. So far, correct. But the `fetch` result itself—event 53—arrived at T+71s, *after* the resume GET had already been established. The server wrote event 53 to the **new** SSE stream. The client consumed it. No loss. The failure appeared on the *second* interruption, at step `synthesize`. This time the client's resume used the **POST** leg: it issued a POST with `Last-Event-ID: 53` and `Mcp-Session-Id` set, expecting the server to attach the response continuation to a fresh SSE stream and replay from 54. The server's HTTP-native handler treated a POST carrying `Last-Event-ID` as a *resume request* and, per its implementation, opened a *new* SSE stream keyed to a *new* internal stream ID, replayed events 54–58 into it, and returned `200 OK` on the POST with a body that was the *first* replayed event only. The client's POST handler read the 200, treated it as the resume acknowledgment, and closed the POST. The new SSE stream, with events 54–58, had no reader. The client's SSE reader was still attached to the *old* stream ID, which the server had already torn down. The client now waited on a dead stream for event 59 (the `synthesize` result). The server had already emitted 59 into the orphaned stream and advanced its log to 59. At T+60s the client's SSE reader timed out again, issued a resume with `Last-Event-ID: 58` (its last consumed). The server replayed 59 into yet another new stream. This time the client's resume used the GET leg (its retry logic alternated), and it consumed 59. The result was delivered—**71 seconds late, after two full idle-timeout cycles, and only because the client's retry logic happened to alternate legs.** Had it consistently used the POST leg, it would have looped forever: each POST resume would spawn an orphaned stream, advance the log, and the client would never see the event. The tell was in the server logs: `session=s-8812 events_emitted=59 streams_opened=4 streams_closed=3 readers_active=1`. Four streams for one session; three closed without a single event consumed. The server's own metrics showed healthy throughput. The client's metrics showed a slow but successful task. Neither showed the orphan. ## Condition of Validity The resume-via-POST path is valid **only if** the server's POST handler, upon receiving `Last-Event-ID`, does one of two things atomically: 1. **Re-binds the existing SSE stream** (same stream ID) to the session and replays the gap into it, returning the replay on the SSE leg and a bare `202` on the POST; or 2. **Rejects the POST resume** with `409 Conflict` and a `Retry-After`, forcing the client to resume via GET, which is the only leg that can carry a server→client replay. If the server instead opens a *new* stream on POST resume and returns replayed events in the POST *response body*, the invariant is violated: the client's SSE reader is bound to a different stream than the one the server is writing to. This is a **transport-leg conflation**: the POST leg is being used to carry server→client data, which it can do only for the single response continuation, not for a multi-event replay. The MCP streamable-session spec permits the POST response to carry a single `event: message` frame (the direct response to that POST), but a *replay* is by definition a sequence, and a sequence cannot be delivered on a one-shot POST response without the client re-issuing POSTs per event—which no client does. The condition of validity is therefore: **`Last-Event-ID` on a POST is only meaningful if the server's response is `202`/`409`, never `200` with a body.** A `200` with a body on a resume POST is the signature of leg conflation. The server must either re-bind (202) or refuse (409). There is no correct `200`. ## Decision Boundary The boundary is between **resume-as-rebind** and **resume-as-replay-into-new-stream**. The former preserves the invariant; the latter breaks it silently. Concretely, the server's resume handler must decide, before touching the event log, whether the incoming request's leg matches the leg the client's reader is attached to. The client's reader is attached to the SSE leg iff the client's last action was a GET that returned `200` with `Content-Type: text/event-stream` and the stream is still open. If the client's last action was a POST, its reader is *not* attached, and a POST resume must be refused. The guardrail is a **leg-affinity token**: the server issues, on every SSE stream open, a `Mcp-Stream-Id` header. The client echoes it on every POST. On a resume POST, the server checks: does `Mcp-Stream-Id` match an *open* stream for this session? If yes, re-bind and replay into it, return `202`. If no (the stream was torn down), return `409` with `Mcp-Resume-Via: GET`. The client, on `409`, must resume via GET with `Last-Event-ID` and no stream ID. This makes the leg explicit and eliminates the ambiguity that lets the server open an orphaned stream. The decision boundary for the *client* is symmetric: it must never treat a `200` on a resume POST as a successful resume. A `200` with a body on a resume POST is either a protocol violation or a direct-response POST (no `Last-Event-ID`), and the client must distinguish them by the presence of `Last-Event-ID` in its own request. If it sent `Last-Event-ID` and got `200`, it must discard the body, close the POST, and re-issue as GET. This is the client-side half of the invariant. ## Operational Effect Without the leg-affinity guardrail, the observable effect is **latency amplification proportional to the number of interruptions, with a silent-success terminal state**. Each POST-leg resume opens one orphaned stream and advances the event log by the number of events the server had queued. The client's cursor does not advance (it never saw those events). The gap between server log head and client cursor grows monotonically. If the client's retry logic consistently chooses POST (e.g., because its HTTP library reuses the POST connection for the resume), the gap never closes and the task hangs until the agent's own token or wall-clock budget expires—at which point the agent reports a *timeout*, not a *transport failure*, and the operator debugs the wrong layer. With the guardrail, the failure mode becomes loud and bounded: a `409` forces the client onto the GET leg, the replay lands in the reader's stream, the cursor advances, and the gap closes in one round trip. The orphaned-stream count stays at zero. The cost is one extra round trip per interruption and a `Mcp-Stream-Id` header on every POST—negligible against the cost of a silently orphaned session. The deeper operational lesson: in a two-leg transport, **resumability is not a property of the session; it is a property of the (session, leg) pair.** A session that is resumable on the GET leg is not thereby resumable on the POST leg. The upgrade negotiation is the point where the two legs are momentarily indistinguishable to a server that keys only on `Mcp-Session-Id`, and that indistinguishability is exactly what the leg-affinity token must eliminate. ```python import time from dataclasses import dataclass, field from typing import Optional class OrphanedStreamError(RuntimeError): """Raised when a resume would write replayed events into a stream with no reader.""" pass class LegConflationError(RuntimeError): """Raised when a resume POST returns 200-with-body, conflating the POST and SSE legs.""" pass @dataclass class SessionState: session_id: str last_emitted_event_id: int = 0 open_streams: dict = field(default_factory=dict) # stream_id -> reader_attached stream_seq: int = 0 def handle_resume_post( session: SessionState, last_event_id: int, echoed_stream_id: Optional[str], now: float, ) -> dict: """ Server-side resume handler. Enforces the leg-affinity invariant: a resume POST may only re-bind an OPEN SSE stream; otherwise it must 409. """ # Invariant check 1: cursor must not be ahead of the log (client bug or replay attack). if last_event_id > session.last_emitted_event_id: raise OrphanedStreamError( f"resume cursor {last_event_id} ahead of log head " f"{session.last_emitted_event_id} for session {session.session_id}" ) # Invariant check 2: leg affinity. The client must echo a stream ID that is # still open AND still has a reader attached. If not, refuse and force GET. if echoed_stream_id is None: return { "status": 409, "headers": {"Mcp-Resume-Via": "GET"}, "reason": "no_stream_id_echoed", } reader_attached = session.open_streams.get(echoed_stream_id) if reader_attached is None: # Stream was torn down. A 200 here would open an orphaned stream. return { "status": 409, "headers": {"Mcp-Resume-Via": "GET"}, "reason": "stream_not_open", } if not reader_attached: # Stream is open but its reader has disconnected. Same hazard. return { "status": 409, "headers": {"Mcp-Resume-Via": "GET"}, "reason": "stream_reader_detached", } # Safe to re-bind: replay the gap into the SAME stream, return bare 202. replay_count = session.last_emitted_event_id - last_event_id return { "status": 202, "headers": {"Mcp-Stream-Id": echoed_stream_id}, "replayed_events": replay_count, "stream_id": echoed_stream_id, } def client_resume( server_response: dict, sent_last_event_id: bool, ) -> str: """ Client-side guard: never trust a 200 on a resume POST. Returns the leg the client must use next. """ status = server_response.get("status") if sent_last_event_id and status == 200 and server_response.get("body"): # Server conflated legs: replayed events into a POST body. Do not read it. raise LegConflationError( "resume POST returned 200-with-body; replayed events are unreachable " "by the SSE reader. Discard body and re-issue as GET." ) if status == 409: return "GET" if status == 202: return "SSE" raise OrphanedStreamError(f"unexpected resume status {status}") def simulate_two_interruptions() -> None: s = SessionState(session_id="s-8812") s.last_emitted_event_id = 53 s.stream_seq = 1 s.open_streams["stream-1"] = True # First interruption: client resumes via POST echoing stream-1 (still open). r1 = handle_resume_post(s, last_event_id=47, echoed_stream_id="stream-1", now=time.time()) assert r1["status"] == 202, r1 # Second interruption: server tore down stream-1 during the idle gap. s.open_streams["stream-1"] = False r2 = handle_resume_post(s, last_event_id=53, echoed_stream_id="stream-1", now=time.time()) # The guardrail refuses the POST resume rather than opening an orphan. if r2["status"] != 409: raise OrphanedStreamError( f"POST resume on torn-down stream {r2.get('stream_id')} would orphan " f"events {53}..{s.last_emitted_event_id}" ) leg = client_resume(r2, sent_last_event_id=True) assert leg == "GET", leg if __name__ == "__main__": simulate_two_interruptions() ```