# What structural signals indicate a half-upgraded MCP streamable HTTP session: SSE-to-POST handshake divergence and the orphaned response-stream invariant **Date of Record:** 2026 November 21 **Scope:** Applies to MCP servers exposing the streamable HTTP transport where a client establishes an SSE `GET` stream and then issues `POST` requests correlated to that stream via `Mcp-Session-Id` and a request-id namespace. Does not apply to stdio transports, nor to pure request/response MCP servers with no server-initiated stream channel. ## Core Distinction The failure mode is not "the SSE connection dropped." That is loud and recoverable. The failure mode is **silent half-upgrade divergence**: the server has accepted the `GET` SSE stream and bound a session, the client has issued `POST`s carrying that session id, but the *response-bearing* half of the duplex — the channel over which the server writes the `POST`'s JSON-RPC result — is not the stream the client is actually reading. The two sides each believe the handshake succeeded; neither observes an error; the agent stalls waiting for a response that was written to a socket nobody drains. The structural signal that matters is not the presence of an `Mcp-Session-Id` (both sides will happily echo one). It is the **correlation between the request-id emitted in the `POST` response envelope and the request-id observed on the SSE stream the client holds open**. When those two id-spaces are disjoint, the session is half-upgraded regardless of what the session id says. ## What Was Observed A tool-using agent issues an `initialize`, receives a session id `S`, opens `GET /mcp` with `Accept: text/event-stream` and `Mcp-Session-Id: S`, and begins reading events. It then issues `POST /mcp` with `Mcp-Session-Id: S` and a JSON-RPC body `{"id": 41, "method": "tools/call", ...}`. Three observable states, all of which look "connected" to a health check: 1. **Fully upgraded (invariant holds).** The `POST` returns `202 Accepted` with an empty body; the JSON-RPC result for id `41` arrives as an SSE `message` event on the open `GET` stream. The id `41` on the stream matches the id `41` the client sent. Correlation is exact. 2. **Degenerate non-upgrade (loud).** The `POST` returns `200` with `Content-Type: application/json` and the full result inline; no SSE stream is used for this request. The client that only reads the stream sees nothing, but the response body tells it the truth immediately. Recoverable. 3. **Half-upgrade (silent, the failure of record).** The `POST` returns `202 Accepted`. The server writes the result for id `41` to a *different* SSE stream than the one the client holds — typically because the server minted a per-request stream, or because a load balancer pinned the `GET` and the `POST` to different backend replicas that each opened their own stream, or because the server rotated the stream on a keepalive boundary and the client's read loop is still on the old one. The client's `GET` stream is alive and emitting keepalive comments (`: ping`), so the read loop never errors. The result event for `41` is written to an orphaned stream. The agent blocks on `await result(41)` until its own timeout. The tell is structural, not temporal: the `GET` stream continues to emit `: ping` heartbeats but emits **zero `message` events whose `id` falls in the set of outstanding `POST` request-ids**, for longer than the server's advertised keepalive interval times the number of outstanding requests. Heartbeats prove the TCP path; they prove nothing about response routing. ## Condition of Validity The invariant "a `POST`'s result is delivered on the client-held SSE stream" is only valid under a conjunction the protocol does not itself enforce: - The server must route by `Mcp-Session-Id` to a *single* stream binding, not mint a stream per request. - Any intermediary (LB, sidecar, gateway) must pin the `GET` and the `POST` for a given session id to the same backend, or the backend must share stream state across replicas. - Stream rotation on keepalive/backpressure must be signalled to the client with an event the client can act on, not performed silently. Break any one and the invariant fails while every individual HTTP response remains a 2xx. The condition of validity is therefore *topological*: same-session requests must traverse a path that converges on the same stream-binding authority. A `Mcp-Session-Id` that is merely a cookie-like token, replicated across stateless backends, satisfies the letter of the header contract and violates the stream-binding requirement. ## Decision Boundary The agent must decide, per outstanding request, whether to keep waiting on the held stream or to fail the request and re-establish. The boundary is: - **Wait** while `elapsed < T_keepalive * (outstanding + 1)` *and* at least one `message` event with a matching id has arrived since the `POST` was issued for any *concurrent* request (proving the stream is the response-bearing one). - **Fail and re-establish** the moment either (a) two consecutive keepalive intervals elapse with heartbeats present but no `message` event matching *any* outstanding id, or (b) a `message` event arrives whose `id` is in the outstanding set but was written to a stream the client did not open (detectable only if the server echoes a stream-nonce the client supplied at `GET` time — which is exactly the non-standard field that would make this diagnosable, and which most servers omit). The sharp edge: condition (a) is indistinguishable from "the tool is just slow" unless the agent tracks the *cross-request* correlation signal. A single slow `tools/call` produces heartbeats and no matching id for a long time and is *not* a half-upgrade. The discriminator is whether *other* outstanding requests are being answered on the same stream. If request 40's result arrived on this stream five seconds ago and request 41's has not, the stream is response-bearing and 41 is merely pending. If *nothing* has ever arrived on this stream despite multiple `POST`s, the stream is orphaned. ## Operational Effect An agent that treats heartbeats as liveness will hang for its full per-call timeout on every request in a half-upgraded session, then — if it retries naively by re-`POST`ing with the same session id — reproduce the divergence, since the routing fault is sticky to the session id. The correct recovery is to **abandon the session id and re-initialize**, forcing a fresh `GET`/`POST` pair that may land on a converged path, and to record the divergence so the orchestrator can quarantine the offending backend replica. The operational invariant to enforce: *liveness of the transport is not liveness of the response channel; only id-correlated `message` events prove the channel.* Health checks that assert "SSE connected" are structurally blind to this failure and will report a fully green fleet while every agent on a mispinned replica stalls. ```python import time from dataclasses import dataclass, field class HalfUpgradedSessionError(RuntimeError): """Raised when an MCP streamable-HTTP session is bound but the SSE stream the client holds is not the response-bearing channel for its POSTed request-ids (heartbeats present, zero id-matched messages).""" @dataclass class StreamBinding: session_id: str keepalive_interval_s: float opened_at: float = field(default_factory=time.monotonic) last_heartbeat: float = 0.0 matched_ids: set = field(default_factory=set) # ids answered on THIS stream outstanding_ids: set = field(default_factory=set) # ids POSTed, awaiting result def on_heartbeat(self) -> None: self.last_heartbeat = time.monotonic() def on_message(self, msg_id: int) -> None: self.matched_ids.add(msg_id) self.outstanding_ids.discard(msg_id) def assert_response_bearing(self, now: float | None = None) -> None: """Enforce the invariant: a held stream with outstanding requests must have answered at least one of them, or be young enough to be legitimately pending. Heartbeats alone are NOT evidence of a response-bearing stream.""" now = now or time.monotonic() if not self.outstanding_ids: return age = now - self.opened_at # Grace window: allow one keepalive interval per outstanding request. grace = self.keepalive_interval_s * (len(self.outstanding_ids) + 1) if age > grace and not self.matched_ids: raise HalfUpgradedSessionError( f"session {self.session_id!r}: stream open {age:.1f}s, " f"{len(self.outstanding_ids)} outstanding id(s) " f"{sorted(self.outstanding_ids)}, zero id-matched messages, " f"heartbeats={'alive' if self.last_heartbeat else 'none'} — " f"stream is orphaned; response channel diverged from held GET." ) def post_and_await(binding: StreamBinding, req_id: int, send_post, read_stream) -> dict: binding.outstanding_ids.add(req_id) send_post(req_id) deadline = time.monotonic() + binding.keepalive_interval_s * 30 while time.monotonic() < deadline: event = read_stream(timeout=binding.keepalive_interval_s) if event is None: binding.on_heartbeat() binding.assert_response_bearing() # may raise HalfUpgradedSessionError continue if event.get("type") == "heartbeat": binding.on_heartbeat() binding.assert_response_bearing() continue if event.get("id") == req_id: binding.on_message(req_id) return event["result"] raise HalfUpgradedSessionError( f"session {binding.session_id!r}: request {req_id} timed out with no " f"id-matched message; re-initialize session to force a converged path." ) ```