# What happens when an instance upgrades an MCP SSE session to streamable HTTP mid-tool-call and the OAuth 2.1 resource indicator no longer matches the negotiated capability **Date of Record:** 2026 December 3 **Scope:** Applies to MCP clients that negotiate an HTTP-native transport by starting on legacy SSE (`text/event-stream`) and upgrading to streamable HTTP while a tool call is in flight, with per-tool OAuth 2.1 resource indicators (`resource` parameter, RFC 8707) bound to the tool's canonical URI. Does not apply to stdio transports, to sessions that never upgrade, or to servers issuing a single session-wide token without per-tool audience scoping. ## Core Distinction The failure is not "the token expired" and it is not "the connection dropped." It is a **resource-indicator rebinding gap**: the upgrade from SSE to streamable HTTP changes the effective request target (scheme, host, path, and — critically — the `resource` URI the server will validate the bearer token against), but the OAuth 2.1 token minted at SSE-negotiation time was audience-bound to the *pre-upgrade* resource identifier. The streamable-HTTP endpoint validates the same token against a *post-upgrade* resource identifier. When those two strings differ — even by a trailing slash, a port, a `/sse` → `/mcp` path segment, or an `http` → `https` scheme promotion behind a TLS-terminating proxy — the server rejects the `initialize` or the resumed request with `401 invalid_token` even though the token is cryptographically valid, unexpired, and correctly scoped for the *original* transport. This is a boundary condition specific to the HTTP-native MCP transport because the upgrade is a **transport-layer state transition that silently mutates the authorization audience**. The agent's reasoning layer sees a valid token and a live session; the server sees a resource mismatch. Neither side is "wrong" under its own model, which is exactly why the failure is non-obvious and why agents retry it into a loop. ## What Was Observed A representative trace, observed on an MCP client resuming a long-running `search_index` tool call: 1. Client opens `GET https://mcp.example.com/sse`. Server responds `200`, holds the stream open, and emits an `endpoint` event pointing at `https://mcp.example.com/messages?session_id=sess_7f3a`. The client's OAuth flow requested a token with `resource=https://mcp.example.com/sse` (the resource it was told to authorize against at discovery time). Token `T1` is issued, `aud=https://mcp.example.com/sse`. 2. Client issues `POST /messages?session_id=sess_7f3a` with `Authorization: Bearer T1`, invoking `tools/call` for `search_index`. Server accepts, begins streaming partial results over the SSE channel, and the tool call is *in flight* — the server has committed side effects (index shard locked, cursor allocated). 3. Mid-stream, the server advertises streamable-HTTP capability in a `notifications/capabilities` style frame and the negotiated transport flips. The client is instructed to resume at `https://mcp.example.com/mcp` (streamable HTTP endpoint). The resource indicator the server now validates against is `https://mcp.example.com/mcp`. 4. Client sends `POST /mcp` with `Authorization: Bearer T1` and `Last-Event-ID: 42` to resume. Server's resource-indicator check compares `aud` (`.../sse`) to the endpoint's canonical resource (`.../mcp`). Mismatch → `401 {"error":"invalid_token","error_description":"resource indicator mismatch"}`. 5. Client's retry logic sees `401`, treats it as "token stale," and re-runs the OAuth flow. The re-mint *also* requests `resource=https://mcp.example.com/sse` because the client's cached discovery document still points at the SSE endpoint. The new token `T2` has the same wrong audience. Retry loop. Meanwhile the server's in-flight tool call for `sess_7f3a` is orphaned: the shard lock is held, the cursor is allocated, and the SSE stream times out server-side after the configured idle window, releasing the lock but discarding partial results. The observable signature is: `401 invalid_token` with a `resource` mismatch description, immediately after a successful transport upgrade, on a token that `introspect` reports as `active: true`. The agent interprets `401` as an auth failure; the actual fault is an audience rebinding that the upgrade introduced. ## Condition of Validity The failure requires all of the following to hold simultaneously, which is why it is intermittent and hard to reproduce: - The transport upgrade is **in-band and mid-call** (SSE → streamable HTTP) rather than at session establishment. If the client re-negotiates before any tool call is dispatched, the client re-runs discovery and mints a fresh token against the new resource — no in-flight state to lose. - The server enforces **per-tool resource indicators** (RFC 8707 `resource` parameter) and validates `aud` against the *endpoint's* canonical URI, not against a wildcard or a stable session-level audience. - The pre-upgrade and post-upgrade resource identifiers **differ as strings** but refer to the same logical server. Common triggers: `/sse` vs `/mcp` path, `https` vs `http` behind a proxy that terminates TLS, `:443` explicit vs implicit, or a hostname alias (`mcp.example.com` vs `mcp-internal.example.com`). - The tool call is **sufficiently long-lived** that the upgrade lands while it is in flight (streaming tool, multi-shard query, a tool that itself awaits a downstream model). If the resource identifiers are canonicalized to a single stable value across both transports, the failure does not occur. That canonicalization is the invariant the rest of this record is about. ## Decision Boundary The agent must distinguish three superficially identical `401` outcomes at the upgrade boundary, because the correct recovery differs: | Signal | Diagnosis | Correct action | |---|---|---| | `401` + `resource indicator mismatch` + token `introspect.active == true` | Audience rebinding from upgrade | Re-mint token with `resource` = **post-upgrade** endpoint URI; do **not** replay the in-flight call until resume is confirmed | | `401` + `invalid_token` + `introspect.active == false` | Genuine expiry/revocation | Standard re-auth, then resume from `Last-Event-ID` | | `401` + `insufficient_scope` | Token valid, scope too narrow for tool | Step-up authorization; do not re-mint blindly | The boundary is crossed when the agent's auth layer keys its "which resource do I request" decision on the **discovery document cached at session start** rather than on the **currently negotiated transport's advertised resource**. Caching discovery across a transport upgrade is the root cause; the `401` is only the symptom. An agent that re-reads the resource indicator from the live `initialize`/capabilities frame after upgrade, and re-mints against *that*, never enters the loop. The second boundary is resume safety: a `401` at the streamable-HTTP endpoint does **not** mean the in-flight tool call was rolled back. The server may still hold the shard lock and cursor. The agent must not treat the `401` as "call failed, safe to re-dispatch," or it will double-invoke a side-effecting tool and contend for the same lock. ## Operational Effect The practical consequence is a **silent orphan plus a retry storm**. The orphaned tool call holds server-side resources until the idle timeout; the client's retry loop burns token-mint requests and, because each retry re-requests the stale resource, never converges. Downstream, the agent's episodic memory records the tool call as `failed:auth`, which is the wrong semantic label — the call was *dispatched and partially executed* — so later distillation misattributes the failure to credentials rather than transport rebinding, and the agent learns a bad recovery policy (re-auth harder) instead of the right one (re-read resource indicator, then resume). The guardrail is a **resource-indicator stability invariant**: at every transport transition, the client must (a) invalidate its cached discovery document, (b) re-derive the resource URI from the live negotiated endpoint, (c) re-mint if the derived URI differs from the current token's `aud`, and (d) resume — never re-dispatch — using the preserved `Last-Event-ID` and session id. The server side must ensure the upgrade response carries the canonical post-upgrade resource URI explicitly, so the client is not left to infer it from the URL. ```python import hashlib from dataclasses import dataclass, field from typing import Optional class ResourceIndicatorRebindingError(RuntimeError): """Raised when an MCP transport upgrade changes the canonical resource URI such that the bearer token's audience no longer matches the live endpoint.""" pass class OrphanedToolCallError(RuntimeError): """Raised when a resume is attempted against a session whose in-flight tool call may still hold server-side resources; re-dispatch is unsafe.""" pass @dataclass class Token: value: str audience: str # the `resource` indicator this token was minted for active: bool = True @dataclass class Session: session_id: str transport: str # "sse" | "streamable_http" canonical_resource: str # live endpoint's canonical URI last_event_id: int = 0 in_flight_tool_call: Optional[str] = None token: Optional[Token] = None discovery_cache: dict = field(default_factory=dict) def _canonicalize(uri: str) -> str: # Collapse scheme/port/trailing-slash/path-alias differences that are the # actual trigger for the rebinding gap. u = uri.strip() u = u.replace("http://", "https://", 1) u = u.rstrip("/") for alias in ("/sse", "/messages"): if u.endswith(alias): u = u[: -len(alias)] + "/mcp" return u def resume_after_upgrade(session: Session, new_endpoint: str) -> Token: # (a) invalidate stale discovery cache from the pre-upgrade transport session.discovery_cache.clear() # (b) re-derive the live resource from the negotiated endpoint live_resource = _canonicalize(new_endpoint) session.canonical_resource = live_resource session.transport = "streamable_http" # (c) detect the rebinding gap before touching the network if session.token is None: raise ResourceIndicatorRebindingError( f"session {session.session_id}: no token present at upgrade" ) if _canonicalize(session.token.audience) != live_resource: # The token is cryptographically fine but audience-bound to the old # transport. This is NOT an expiry; do not label it as one. raise ResourceIndicatorRebindingError( f"session {session.session_id}: token aud={session.token.audience!r} " f"does not match live resource {live_resource!r} after upgrade; " f"re-mint with resource={live_resource!r} (introspect.active=" f"{session.token.active})" ) # (d) resume, never re-dispatch. If a tool call is still in flight on the # server, replaying it would double-invoke a side-effecting tool. if session.in_flight_tool_call is not None and session.last_event_id == 0: raise OrphanedToolCallError( f"session {session.session_id}: tool {session.in_flight_tool_call!r} " f"in flight but no Last-Event-ID to resume from; refusing to " f"re-dispatch (lock/cursor may still be held server-side)" ) return session.token def handle_upgrade_response(session: Session, resp: dict) -> Token: endpoint = resp.get("endpoint") if not endpoint: raise ResourceIndicatorRebindingError( f"session {session.session_id}: upgrade response omitted canonical " f"resource; client cannot infer audience safely" ) return resume_after_upgrade(session, endpoint) ```