Streamable HTTP server silently drops in-flight request when client reuses a JSON-RPC id
Summary
When a client sends two JSON-RPC requests with the same id on the same Streamable HTTP session before the first response is delivered, StreamableHTTPServerTransport overwrites the per-id response stream slot without warning. The first request's caller hangs until its read times out, and the second response is delivered to whichever caller wins the race. The server logs nothing.
The MCP base protocol requires that "the request ID MUST NOT have been previously used by the requestor within the same session," so a duplicate id is a protocol violation by the client. But the server has no way to tell the client (or an operator) that the violation happened, which makes this very hard to diagnose downstream.
Where it happens
In src/mcp/server/streamable_http.py lines 534-536 at v1.27.1:
request_id = str(message.root.id)
self._request_streams[request_id] = anyio.create_memory_object_stream[EventMessage](0)
request_stream_reader = self._request_streams[request_id][1]
The assignment is unconditional. If request_id is already a key in _request_streams, the prior (send, receive) pair is dropped on the floor. The earlier request's writer eventually tries to push a response into a stream nobody is reading, and the earlier request's caller is reading a stream nobody will ever write to.
The router side at lines 1004-1033 uses the same str(id) keying to dispatch responses, so once the slot has been overwritten, response routing is undefined.
Reproduction signature
We hit this through an in-house client that was sending id: 1 for every concurrent tool call on a shared session. Under concurrent load, calls timed out and at least one caller received the wrong tool's response payload.
Proposed Behavior
When a request arrives with an id that already has an in-flight stream registered, the server should reject it with JSON-RPC -32600 Invalid Request and leave the existing in-flight request untouched. This:
- Surfaces the spec violation to the client immediately instead of timing out.
- Preserves the in-flight request that arrived first.
- Gives operators a log line to diagnose against.
A weaker variant (log-only, no error response) would still be a meaningful improvement over silent data loss.
Confirmed at HEAD on v1.x. The unconditional dict assignment is still present at src/mcp/server/streamable_http.py:536 (line 529 on main). When request_id already keys an in-flight stream, the prior (send, receive) pair is dropped on the floor exactly as you described. The earlier handler's request_stream_reader then reads a closed stream, and the response router at line 1006 routes the response to whichever stream happens to be live.
The existing GET_STREAM_KEY in self._request_streams collision check at line 690 is the precedent for the fix shape:
request_id = str(message.root.id)
if request_id in self._request_streams:
response = self._create_error_response(
f"Conflict: request id {request_id!r} is already in flight on this session",
HTTPStatus.CONFLICT,
)
await response(scope, receive, send)
return
self._request_streams[request_id] = anyio.create_memory_object_stream[EventMessage](0)
This matches the GET-stream conflict (409 + _create_error_response) and preserves the in-flight request untouched.
One nuance worth a maintainer call: the existing helper builds the JSONRPCError with id=None. For most callers that's correct (parse errors before id is known), but here the client knows the id. Mirroring the existing helper keeps the diff one-call; threading the offending id through would require either a new helper signature or an inline JSONRPCError construction. I'd lean on the helper for consistency but can go either way.
Happy to send the PR ([v1.x] target, with a regression test that seeds _request_streams[request_id] and POSTs the duplicate) if it's welcome. Targeting v1.x since this is a non-breaking server-side bug fix per AGENTS.md.
reproduced on origin/main (616476f) and origin/v1.x (6213787). client A (slow, id="dup-id-1") and client B (fast, same id) race; B's stream slot overwrites A's at streamable_http.py:529 (main) / :536 (v1.x), B's response is delivered correctly, and A's coroutine then blocks forever on a receive half that nobody will write to. no log line on either side. workaround until the fix lands: clients must not reuse a JSON-RPC id for an in-flight request (the spec already requires this, basic/index.mdx#L47), but the server should surface the violation instead of dropping the stream silently.
the proposed fix shape — collision check + _create_error_response(..., HTTPStatus.CONFLICT) mirroring the existing GET_STREAM_KEY guard at :690 — is the right one. one nit on the earlier comment's draft: _create_error_response builds JSONRPCError with id=None, which is wrong for this case since the offending id is known; threading the id through the error (or constructing JSONRPCError inline here) keeps the JSON-RPC envelope correct. a regression test should seed _request_streams[request_id] and POST a duplicate, asserting 409 + the original stream is untouched.
repro.py
"""Repro for issue #2655.
When the client POSTs two JSON-RPC requests with the same id on the same
StreamableHTTP session, the server unconditionally overwrites the prior
(send, receive) pair in self._request_streams. The earlier request's handler
ends up reading a stream nobody will write to.
Behavior we expect to observe:
- request A (slow, id="dup") is in flight
- request B (fast, id="dup") arrives, overwrites the stream slot
- request A's HTTP read hangs forever (no response written into the new slot
for A's coroutine, and nobody is writing into A's *original* slot)
- request B's response either reaches B, reaches A, or both, depending on
the race in the message router. The issue is that this is silent.
Run:
uv run python repro.py
"""
from __future__ import annotations
import asyncio
import json
import socket
import threading
import time
import httpx
import uvicorn
from starlette.applications import Starlette
from starlette.routing import Mount
from mcp import types
from mcp.server import Server
from mcp.server.streamable_http_manager import StreamableHTTPSessionManager
from mcp.server.transport_security import TransportSecuritySettings
def _create_server() -> Server:
# Support both v1.x decorator API and the newer kwarg-handler API on main.
try:
server = Server("repro-2655")
@server.list_tools() # type: ignore[attr-defined]
async def _list_tools():
return [
types.Tool(
name="sleep_tool",
description="Sleeps for `delay` seconds then echoes `tag`.",
inputSchema={
"type": "object",
"properties": {
"delay": {"type": "number"},
"tag": {"type": "string"},
},
},
)
]
@server.call_tool() # type: ignore[attr-defined]
async def _call_tool(name: str, arguments: dict):
delay = float(arguments.get("delay", 0.0))
tag = str(arguments.get("tag", "?"))
await asyncio.sleep(delay)
return [types.TextContent(type="text", text=f"tag={tag} delay={delay}")]
return server
except AttributeError:
# main branch API
async def _list_tools_handler(ctx, params):
return types.ListToolsResult(
tools=[
types.Tool(
name="sleep_tool",
description="Sleeps for `delay` seconds then echoes `tag`.",
input_schema={
"type": "object",
"properties": {
"delay": {"type": "number"},
"tag": {"type": "string"},
},
},
)
]
)
async def _call_tool_handler(ctx, params):
args = params.arguments or {}
delay = float(args.get("delay", 0.0))
tag = str(args.get("tag", "?"))
await asyncio.sleep(delay)
return types.CallToolResult(
content=[types.TextContent(type="text", text=f"tag={tag} delay={delay}")]
)
return Server(
"repro-2655",
on_list_tools=_list_tools_handler,
on_call_tool=_call_tool_handler,
)
def _create_app() -> Starlette:
server = _create_server()
security = TransportSecuritySettings(
allowed_hosts=["127.0.0.1:*", "localhost:*"],
allowed_origins=["http://127.0.0.1:*", "http://localhost:*"],
)
manager = StreamableHTTPSessionManager(
app=server,
json_response=True,
security_settings=security,
)
return Starlette(
routes=[Mount("/mcp", app=manager.handle_request)],
lifespan=lambda app: manager.run(),
)
def _free_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def _run_server(port: int) -> None:
config = uvicorn.Config(
app=_create_app(),
host="127.0.0.1",
port=port,
log_level="warning",
access_log=False,
)
uvicorn.Server(config=config).run()
def _wait_for(port: int, deadline: float = 5.0) -> None:
start = time.monotonic()
while time.monotonic() - start < deadline:
try:
with socket.create_connection(("127.0.0.1", port), timeout=0.1):
return
except OSError:
time.sleep(0.05)
raise RuntimeError("server did not start")
JSON_HEADERS = {"Accept": "application/json, text/event-stream", "Content-Type": "application/json"}
def _initialize(base: str) -> tuple[str, httpx.Client]:
"""Initialize a session, return (session_id, client)."""
client = httpx.Client(timeout=10.0)
init = {
"jsonrpc": "2.0",
"method": "initialize",
"params": {
"clientInfo": {"name": "repro", "version": "0"},
"protocolVersion": "2025-03-26",
"capabilities": {},
},
"id": "init",
}
r = client.post(base, headers=JSON_HEADERS, json=init)
r.raise_for_status()
session_id = r.headers["mcp-session-id"]
ack = {"jsonrpc": "2.0", "method": "notifications/initialized"}
headers = dict(JSON_HEADERS)
headers["mcp-session-id"] = session_id
headers["mcp-protocol-version"] = "2025-03-26"
client.post(base, headers=headers, json=ack)
return session_id, client
def _post_call(client: httpx.Client, base: str, session_id: str, *, tag: str, delay: float, req_id: str) -> dict:
body = {
"jsonrpc": "2.0",
"method": "tools/call",
"params": {"name": "sleep_tool", "arguments": {"delay": delay, "tag": tag}},
"id": req_id,
}
headers = dict(JSON_HEADERS)
headers["mcp-session-id"] = session_id
headers["mcp-protocol-version"] = "2025-03-26"
r = client.post(base, headers=headers, json=body, timeout=15.0)
return {"status": r.status_code, "body": r.text}
def main() -> None:
port = _free_port()
t = threading.Thread(target=_run_server, args=(port,), daemon=True)
t.start()
_wait_for(port)
base = f"http://127.0.0.1:{port}/mcp/"
session_id, init_client = _initialize(base)
init_client.close()
duplicate_id = "dup-id-1"
results: dict[str, dict] = {}
errors: dict[str, str] = {}
def fire(label: str, delay: float, tag: str, start_after: float) -> None:
time.sleep(start_after)
client = httpx.Client(timeout=15.0)
try:
t0 = time.monotonic()
res = _post_call(
client, base, session_id,
tag=tag, delay=delay, req_id=duplicate_id,
)
res["elapsed"] = round(time.monotonic() - t0, 2)
results[label] = res
except Exception as e:
errors[label] = f"{type(e).__name__}: {e}"
finally:
client.close()
th_a = threading.Thread(target=fire, args=("A", 3.0, "slow-A", 0.0), daemon=True)
th_b = threading.Thread(target=fire, args=("B", 0.5, "fast-B", 0.3), daemon=True)
th_a.start()
th_b.start()
th_a.join(timeout=12.0)
th_b.join(timeout=12.0)
print("=== results ===")
print(json.dumps(results, indent=2))
print("=== errors ===")
print(json.dumps(errors, indent=2))
print("=== thread liveness ===")
print({"A_alive": th_a.is_alive(), "B_alive": th_b.is_alive()})
if __name__ == "__main__":
main()
command + output (origin/main, 616476f)
$ timeout 30 uv run python repro.py
=== results ===
{
"B": {
"status": 200,
"body": "{\"jsonrpc\":\"2.0\",\"id\":\"dup-id-1\",\"result\":{\"content\":[{\"type\":\"text\",\"text\":\"tag=fast-B delay=0.5\"}],\"isError\":false}}",
"elapsed": 0.51
}
}
=== errors ===
{}
=== thread liveness ===
{'A_alive': True, 'B_alive': False}
B (sent ~0.3s after A) returns in ~0.5s with its own payload. A is still stuck inside httpx.post 12+s after submission even though its tool handler completed at t≈3s. same result on origin/v1.x (6213787).
code path
- A arrives,
streamable_http.py:529registers_request_streams["dup-id-1"] = (sendA, recvA); A's coroutine holds a local ref torecvAand awaits it in theasync forat:543. - B arrives,
:529runs again and overwrites the slot with(sendB, recvB);sendAis now unreferenced from the dict,recvAis still held by A's local but nothing can write to it. - B's tool finishes; message router at
:993–:1019finds key"dup-id-1"in_request_streams, sends intosendB. B readsrecvB, returns 200,finallyat:574calls_clean_up_memory_streams("dup-id-1")which closes both halves and pops the key. - A's tool finishes at t≈3s; router looks up
"dup-id-1"again, miss → "Request stream not found" at:1024(debug-level, no operator-visible log). - A's
async for event_message in request_stream_readerat:543never receives anything (no writer left forrecvA) and never sees the stream close, so A's HTTP read times out client-side.
precedent for the fix shape is the GET_STREAM_KEY in self._request_streams collision guard at :690, returning 409 via _create_error_response.
suggested fix
# src/mcp/server/streamable_http.py
@@ _create_error_response signature
def _create_error_response(
self,
error_message: str,
status_code: HTTPStatus,
error_code: int = INVALID_REQUEST,
headers: dict[str, str] | None = None,
+ request_id: RequestId | None = None,
) -> Response:
...
error_response = JSONRPCError(
jsonrpc="2.0",
- id=None,
+ id=request_id,
error=ErrorData(code=error_code, message=error_message),
)
@@ _handle_post_request, just before line 529 stream registration
request_id = str(message.id)
+ if request_id in self._request_streams:
+ response = self._create_error_response(
+ f"Conflict: Request ID {request_id!r} is already in flight on this session",
+ HTTPStatus.CONFLICT,
+ request_id=message.id,
+ )
+ await response(scope, receive, send)
+ return
self._request_streams[request_id] = anyio.create_memory_object_stream[EventMessage](0)
test to verify: posts request A (wait_for_lock_with_notification, in flight) then a second POST reusing A's id with test_tool — asserts the duplicate gets 409 + JSON-RPC error envelope and that A still completes 200 with its original id after the lock releases. full suite (1743 passed, 98 skipped, 1 xfailed) still green.
This looks worth pinning down as a protocol-level regression rather than only an implementation bug.
For Streamable HTTP drops in-flight request on reused JSON-RPC id, the acceptance test I would want is a minimal client/server fixture that records the exact JSON-RPC or HTTP exchange, then asserts both the wire result and the local lifecycle state after the failure path. In MCP deployments, the dangerous failures are often not just wrong return values; they are pending requests, dropped notifications, mismatched session state, or errors that get translated into a generic response and become impossible to diagnose.
A useful fix boundary would preserve three signals: the protocol error sent to the peer, the local exception or cancellation reason available to application code, and a trace/log field that ties the two together. That makes the behavior debuggable for agent hosts without requiring every host to special-case this SDK detail.
Hi, I'm Waseem Mushtaq, a final-year Computer Science undergraduate at Albukhary International University (AIU) in Malaysia on a full scholarship. I'm working on AI engineering, tool calling and agent infrastructure, and this issue is directly in that area.
I reproduced this on main (v2). With a slow tool (3s) and a fast tool (0.5s) sent 0.3s later with the same request id, the second request got its own response in about 0.5s, but the first request was still hanging 12s later, with no error and no log. With unique ids, both requests completed correctly. The same happens in SSE mode.
The cause looks like the unconditional overwrite of the per-id response stream in _handle_post_request, so the first request's response is routed to the second request's stream and the first handler is left waiting.
I saw the earlier PRs #2657, #3063 and #3064 were closed in the backlog sweep, not on the merits, so I wanted to check before doing any work here. @truffle-dev and @ghost, are you still planning to continue with this? And could a maintainer confirm whether the transport-level guard is still the wanted scope, returning 409 with JSON-RPC -32600 when a request id is already in flight, and whether I can be assigned this issue to work on it?
Thanks!
Confirmed on current main (77001c9). I reproduced this with the in-memory transport harness: two concurrent JSON-mode POSTs with id "dup-1" on one session. Both requests are forwarded to the session, the first caller then hangs, and the duplicate receives the first request's response. So the overwrite is still live on v2, in both the JSON-response and SSE branches of _handle_post_request.
Why it matters for my use case: I build MCP clients that fan out concurrent tool calls, and a client that reuses ids (or a retry that replays one) silently loses responses with no log line. A clear rejection would make this diagnosable instead of a hang.
Approach I would take, reviving #2657 on v2: a single guard right after request_id = str(message.id), before both branches and before the priming-event mint, so no per-request state is created for a duplicate. If the id is already in _request_streams, log a warning and return 409 with a JSON-RPC -32600 Invalid Request error, leaving the in-flight request untouched. Regression tests in tests/server/test_streamable_http_router.py covering the guard plus a concurrent duplicate that still lets the first request complete.
If you are happy with that approach, please assign #2655 to me and I will open the PR with the fix and tests.
Disclosure: I worked on the reproduction with AI assistance and have reviewed and tested it myself.