Repository navigation
Description
Bug: -32002 Session not found for every request after initialize when USE_STATEFUL_SESSIONS=true
Summary
With USE_STATEFUL_SESSIONS=true, the Streamable HTTP endpoint (POST /mcp) issues a valid Mcp-Session-Id on initialize, but every subsequent request carrying that exact session id is rejected with -32002 "Session not found".
The session marker is never written to session_registry, because no code path under /mcp calls session_registry.add_session(). Only the legacy SSE endpoints do.
Environment
- Image/version: 1.1.0 (also reproduced by reading
mainbranch source — same code) - MCP SDK:
mcp-streamable-httpserverInfo version1.29.0 - Config:
USE_STATEFUL_SESSIONS=true MCPGATEWAY_SESSION_AFFINITY_ENABLED=true CACHE_TYPE=redis REDIS_URL=redis://<redis>:6379/0 - Redis is not in cluster mode;
/healthreportscluster_propagation: redis. - Pod: single pod (
context-forge-97664fbf7-gs69z), so this is not a multi-worker routing issue.
Reproduction (no auth required)
# 1) initialize — succeeds and returns a session id
curl -i -X POST https://<gateway>/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"probe","version":"1"}}}'
# -> HTTP 200, header: mcp-session-id: <SID>
# 2) ping with that exact SID, immediately after
curl -X POST https://<gateway>/mcp \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-H "Mcp-Session-Id: <SID>" \
-d '{"jsonrpc":"2.0","id":2,"method":"ping","params":{}}'
# -> {"jsonrpc":"2.0","error":{"code":-32002,"message":"Session not found","data":{"method":"ping"}},"id":2}Observed results (t < 100ms between the two calls, so TTL is not a factor):
| Step | Request | Result |
|---|---|---|
| 1 | POST /mcp initialize |
200, returns mcp-session-id |
| 2 | POST /mcp notifications/initialized + SID |
202 |
| 3 | POST /mcp ping + SID |
-32002 Session not found |
| 4 | POST /mcp tools/list + SID |
-32002 Session not found |
| 5 | POST /mcp tools/list, no SID |
400 Bad Request: Missing session ID (SDK) |
| 6 | GET /mcp + SID |
405 Method Not Allowed |
| 7 | DELETE /mcp + SID |
200 |
Note the contradiction between rows 3 and 6: GET behaves as if stateful were disabled (405), while POST enforces a stateful-only check.
Root cause analysis
mcpgateway/main.py:11799 runs an unconditional stateful session check (no RBAC bypass):
if settings.use_stateful_sessions and mcp_session_id and method != "initialize":
try:
await _assert_session_owner_or_admin(request, user, mcp_session_id)
except HTTPException as exc:
if exc.status_code == status.HTTP_404_NOT_FOUND:
raise JSONRPCError(-32002, "Session not found", {"method": method}) from excwhich resolves to mcpgateway/cache/session_registry.py:1005-1012:
if self._backend == "redis":
return bool(await self._redis.exists(f"mcp:session:{session_id}"))However, nothing under /mcp writes mcp:session:{sid}. Searching the tree for add_session( yields only:
mcpgateway/main.py:4644— legacy SSE endpoint (/servers/{id}/sse)mcpgateway/main.py:12421— legacy SSE endpoint (/sse)
The Streamable HTTP path performs two different writes instead, neither of which creates the marker:
main.py:10916→session_registry.claim_session_owner(...)— writes the owner key onlymain.py:10937→session_affinity.register_session_owner(...)— writes the affinity mapping only
So session_exists() can never return True for a /mcp session, and -32002 is guaranteed.
Consistency check against main
I fetched mcpgateway/transports/streamablehttp_transport.py from main (7032 lines). The relevant blocks are byte-identical to 1.1.0:
# main branch, ~L1407
session_exists = await session_registry.session_exists(mcp_session_id)
...
if session_exists is False:
return False, HTTP_404_NOT_FOUND, "Session not found"# main branch, ~L6093
if settings.use_stateful_sessions:
if captured_session_id:
session_to_register = captured_session_id
if requester_email:
effective_owner = await _claim_streamable_session_owner(captured_session_id, requester_email)A full-text search of CHANGELOG.md for add_session, session_registry, Session not found, and 32002 returns no matches, so this does not appear to be fixed on main.
1.1.1 entry #7434 ("Persistent MCP sessions with tracing") addresses upstream session reuse (gateway → upstream MCP server), which is a different registry (services/upstream_session_registry.py, in-process). The bug here is in the downstream session registry (cache/session_registry.py).
Expected behaviour
Either:
/mcpshould callsession_registry.add_session(sid, transport)(or write themcp:session:{sid}marker) after the SDK issues a session, so subsequent requests passsession_exists; or- the
-32002check inmain.py:11799should not apply to streamable-HTTP sessions that the gateway itself issued and cannot track.
Impact
USE_STATEFUL_SESSIONS=true makes the Streamable HTTP endpoint completely unusable — the very first post-initialize call fails. This blocks the documented way to enable upstream session reuse (#7434 describes USE_STATEFUL_SESSIONS=true as a prerequisite), so operators must choose between "working gateway" and "session reuse".
Additional note (possibly related, may be separate)
GET /mcp returns 405 with stateful sessions disabled reasoning while USE_STATEFUL_SESSIONS=true, suggesting the flag is not read consistently across the GET vs POST paths.
No workaround found (attempted bypasses)
We tried to seed a session id through the paths main.py:10913 reads, in case that would create the marker. All three attempts fail:
| Attempt | What we sent | Server-issued mcp-session-id |
Subsequent tools/list |
|---|---|---|---|
| Baseline | plain initialize |
81996c8f... |
-32002 Session not found |
| Seed via params | params.session_id = "fixed-probe-sid-abc123" |
1041d99b... (ignored our value) |
-32002 Session not found |
| Seed via query | ?session_id=query-probe-sid-xyz |
13e1ac68... (ignored our value) |
-32002 Session not found |
Two takeaways:
- The gateway ignores a client-supplied
session_idfor the actual MCP session — the id always comes from the SDK'sStreamableHTTPSessionManager. - Even so,
params.session_id/query.session_idis consumed atmain.py:10913and routed tosession_registry.claim_session_owner(...), which writes only the owner record.
So the two ids live in unrelated keys, and session_exists() (which reads the SDK-issued id) can never see what claim_session_owner wrote. No client-side value can close the gap.
Workaround
Set USE_STATEFUL_SESSIONS=false. Upstream session reuse is then unavailable, but the gateway remains functional.
Happy to test a patch against our SIT instance.
Activity