Flaky streamable-HTTP/SSE tests: TOCTOU port race under pytest -n auto
Initial Checks
- [x] I confirm that I'm using the latest version of MCP Python SDK
- [x] I confirm that I searched for my issue in https://github.com/modelcontextprotocol/python-sdk/issues before opening this issue
Description
Summary
Tests in tests/shared/test_streamable_http.py intermittently fail in CI (non-deterministically, across different Python versions). The failures are not real regressions, they're caused by a time-of-check/time-of-use (TOCTOU) race in how the test server fixtures allocate ports, which collides when tests run in parallel under pytest -n auto.
Evidence
The flakiness is intermittent and non-deterministic: the same commit, re-run across the CI matrix, fails on different tests and different Python versions, while passing locally and on most matrix entries. That pattern, a failure that moves around rather than reproducing on a specific test/version, is the signature of a parallelism race, not a code defect.
Two failure signatures have been observed, and both reduce to "the client connected to the wrong server instance":
- Server can't bind the port (
test_streamable_http_client_session_termination_204)
ERROR: [Errno 98] error while attempting to bind on address ('127.0.0.1', 35105): address already in use
AssertionError: assert 2 == 10
The intended server (10 tools) loses the bind race, so the client reaches a different test's server: len(tools.tools) comes back as 2 (the echo_headers/echo_context server) instead of 10.
- Crossed responses (
test_streamable_http_client_respects_retry_interval)
pydantic_core.ValidationError: 1 validation error for CallToolResult
content
Field required [type=missing, input_value={'tools': [...]}, input_type=dict]
A call_tool request is answered with a ListToolsResult payload ({'tools': [...]}), which fails to validate as CallToolResult. The client is talking to a server/stream that belongs to another test.
Both symptoms are downstream of two servers contending for the same ephemeral port — see Root cause below.
Root cause
The port fixtures pick a port, then close the socket before the real server binds it:
# tests/shared/test_streamable_http.py:474
@pytest.fixture
def basic_server_port() -> int:
with socket.socket() as s:
s.bind(("127.0.0.1", 0)) # OS assigns a free port
return s.getsockname()[1] # ...socket closes here, freeing the port
The server is then started in a separate multiprocessing.Process (run_server, line 435) and binds that port later. In the gap, another xdist worker's fixture can be handed the same port by the OS, so two servers race for it - one fails with Errno 98, and clients can reach the wrong server.
Affected files (same pattern)
- tests/shared/test_streamable_http.py
- tests/shared/test_sse.py
- tests/server/test_sse_security.py
- tests/server/test_streamable_http_security.py
- tests/client/test_http_unicode.py
Proposed fix
Reuse the existing race-free helper run_uvicorn_in_thread in tests/test_helpers.py:15. It binds and listen()s a socket, then hands that same socket to uvicorn (server.run(sockets=[sock])), so there is no window where another worker can claim the port. This pattern is already proven in tests/shared/test_ws.py, and its docstring documents exactly this race.
Migrate the racy fixtures, e.g.:
# before: basic_server_port + basic_server + basic_server_url (3 fixtures, racy)
# after:
@pytest.fixture
def basic_server_url() -> Generator[str, None, None]:
app = create_app()
with run_uvicorn_in_thread(app, limit_concurrency=10, timeout_keep_alive=5, access_log=False) as url:
yield url
This also removes the need for the wait_for_server(port) poll (the helper's pre-listen()ed socket means connections are accepted as soon as the fixture yields).
Considerations
- This converts the test servers from a subprocess to a background thread (as
test_ws.pyalready does). Need to confirm no test relies on subprocess semantics (e.g.proc.kill()); the streamable-HTTP tests appear to test HTTP-level behavior, not process lifecycle. - A subprocess-preserving alternative (pass a pre-bound listening socket into the child via
server.run(sockets=[sock]))is harder cross-platform, Windows spawn can't easily inherit/pickle sockets, so the thread helper is preferred for the CI matrix.
Scope
Primary scope: tests/shared/test_streamable_http.py. The 4 sibling files share the root cause and can be migrated in the same PR or as follow-ups.
Acceptance criteria
- Racy
*_portfixtures +run_server/wait_for_serversubprocess pattern removed from the affected file(s). - Tests pass reliably under
uv run pytest -n autoacross the CI matrix (3.10–3.14, ubuntu + windows).
Example Code
import socket
def pick_free_port() -> int:
# Exact pattern used by basic_server_port / json_server_port / event_server_port
# in tests/shared/test_streamable_http.py
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1] # <- socket closes here, so the port is free again
# A fixture assigns this port to "server A"...
port = pick_free_port()
# ...but server A is started later (in a separate multiprocessing.Process), so the
# port sits free in between. Under `pytest -n auto`, another worker can claim it.
# Simulate that intruder grabbing the port during the window:
intruder = socket.socket()
intruder.bind(("127.0.0.1", port))
intruder.listen()
# Now server A finally tries to bind the port it was handed:
server_a = socket.socket()
server_a.bind(("127.0.0.1", port)) # OSError: [Errno 98] Address already in use
Python & MCP Python SDK
Python: CPython 3.10 and 3.13 (failures captured on ubuntu-latest in CI).
Not version-specific, it's a test-parallelism race, so it can surface anywhere on the 3.10–3.14 matrix.
MCP Python SDK: main branch (the unreleased v2 line) — 1.25.1.dev builds.
This diagnosis lines up with the failure signatures. One extra acceptance check I would add is that the migrated fixture proves the URL is derived from the actual bound socket, not from a separately selected port value.
For the thread-helper path, the useful invariant is:
- the helper binds/listens on port
0 - uvicorn receives that already-bound socket
- the yielded URL is read from
sock.getsockname()after bind
That makes the test immune to xdist worker races and also avoids a weaker refactor where a fixture still calls a pick_free_port() helper before starting uvicorn. If this is done across the sibling SSE/security fixtures, it may be worth adding a short comment near any remaining free-port helper explaining that it must not be used for servers started later in another process or thread.
Thanks for the feedback!
The implementation in this PR (#2705 ) follows this exact pattern. For both the thread-based helper (run_uvicorn_in_thread) and the process-based helper (running_server):
1. The socket is bound and put into a listening state on port 0 (127.0.0.1:0) in the thread/process prior to starting the server.
2. The port is derived directly from that active socket using sock.getsockname()[1].
3. uvicorn is started by passing this pre-bound socket directly via server.run(sockets=[sock]).
Additionally, the old polling helper wait_for_server has been removed and there are no remaining custom pick_free_port helpers left in test_helpers.py that could be mistakenly reused.
test-infrastructure TOCTOU race confirmed. fix is to retire the pick-a-port-then-rebind fixtures and serve through the existing run_uvicorn_in_thread helper in tests/test_helpers.py, which binds + listen()s the socket before handing it to uvicorn so no other xdist worker can grab the port in between. same racy pattern is on origin/v1.x too, so a backport is needed if the fix lands on main only.
both failure signatures the report describes reproduce against origin/main HEAD 616476f. signature 1 — server bind raises [Errno 98] address already in use when something else won the race in the window. signature 2 — the client request lands on a different server than the fixture intended, returning a payload that belongs to another test (the ValidationError: 1 validation error for CallToolResult / Field required is exactly what pydantic produces when a ListToolsResult shape is parsed as CallToolResult).
racy fixtures (5 files):
tests/shared/test_streamable_http.py:474, 482, 512tests/shared/test_sse.pytests/server/test_sse_security.pytests/server/test_streamable_http_security.pytests/client/test_http_unicode.py
repro.py — run with uv run python repro.py
"""Repro for the TOCTOU port race in test fixtures.
Demonstrates that the `pick_free_port`-then-close pattern used in
tests/shared/test_streamable_http.py:474 leaves a window where another
process can claim the port before the real server binds it.
Reproduces both failure signatures the issue describes:
1. EADDRINUSE when the server tries to bind the port.
2. Client reaches the wrong server (crossed responses).
"""
from __future__ import annotations
import multiprocessing
import socket
import time
import urllib.request
def pick_free_port() -> int:
"""Exact pattern from tests/shared/test_streamable_http.py:474."""
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
return s.getsockname()[1]
def serve_simple(port: int, payload: bytes, started_evt: multiprocessing.Event) -> None:
s = socket.socket()
try:
s.bind(("127.0.0.1", port))
except OSError as e:
print(f" [server payload={payload!r}] bind failed: {e}")
started_evt.set()
return
s.listen()
started_evt.set()
conn, _ = s.accept()
conn.recv(4096)
conn.sendall(
b"HTTP/1.1 200 OK\r\nContent-Length: "
+ str(len(payload)).encode()
+ b"\r\n\r\n"
+ payload
)
conn.close()
s.close()
def demo_bind_collision() -> None:
print("=== Signature 1: EADDRINUSE bind race ===")
port = pick_free_port()
print(f" fixture handed out port {port} (socket already closed)")
intruder = socket.socket()
intruder.bind(("127.0.0.1", port))
intruder.listen()
print(f" intruder grabbed {port} in the TOCTOU window")
server_sock = socket.socket()
try:
server_sock.bind(("127.0.0.1", port))
print(" ERROR: expected EADDRINUSE, got success")
except OSError as e:
print(f" real server bind() raised: {e}")
finally:
intruder.close()
server_sock.close()
def demo_crossed_responses() -> None:
print("\n=== Signature 2: client reaches wrong server ===")
ctx = multiprocessing.get_context("spawn")
port_a = pick_free_port()
port_b = pick_free_port()
print(f" fixture A got port {port_a}, fixture B got port {port_b}")
started_b = ctx.Event()
proc_b = ctx.Process(
target=serve_simple,
args=(port_a, b'{"tools":["wrong-server"]}', started_b),
daemon=True,
)
proc_b.start()
started_b.wait(timeout=5)
print(f" server B raced in and bound port {port_a} (the OS reissued it)")
started_a = ctx.Event()
proc_a = ctx.Process(
target=serve_simple,
args=(port_a, b'{"content":[{"type":"text","text":"correct"}]}', started_a),
daemon=True,
)
proc_a.start()
started_a.wait(timeout=5)
time.sleep(0.1)
try:
resp = urllib.request.urlopen(f"http://127.0.0.1:{port_a}/", timeout=2).read()
print(f" client asked port {port_a} (the 'real' server A)")
print(f" client received: {resp.decode()!r}")
if b"wrong-server" in resp:
print(" -> client reached the other test's server (crossed response)")
except Exception as e:
print(f" client got: {e}")
finally:
for p in (proc_a, proc_b):
p.terminate()
p.join(timeout=2)
if __name__ == "__main__":
demo_bind_collision()
demo_crossed_responses()
command and output
$ uv run python repro.py
=== Signature 1: EADDRINUSE bind race ===
fixture handed out port 59237 (socket already closed)
intruder grabbed 59237 in the TOCTOU window
real server bind() raised: [Errno 98] Address already in use
=== Signature 2: client reaches wrong server ===
fixture A got port 46291, fixture B got port 46271
server B raced in and bound port 46291 (the OS reissued it)
[server payload=b'{"content":[...]}'] bind failed: [Errno 98] Address already in use
client asked port 46291 (the 'real' server A)
client received: '{"tools":["wrong-server"]}'
-> client reached the other test's server (crossed response)
suggested fix
per-file pattern (showing tests/shared/test_streamable_http.py; the other four files follow the same shape):
- import multiprocessing
- import traceback
- import uvicorn
- from tests.test_helpers import wait_for_server
+ from tests.test_helpers import run_uvicorn_in_thread
- def run_server(port: int, ...): ... # subprocess entry point
-
- @pytest.fixture
- def basic_server_port() -> int:
- with socket.socket() as s:
- s.bind(("127.0.0.1", 0))
- return s.getsockname()[1]
-
- @pytest.fixture
- def basic_server(basic_server_port: int) -> Generator[None, None, None]:
- proc = multiprocessing.Process(target=run_server, kwargs={"port": basic_server_port}, daemon=True)
- proc.start()
- wait_for_server(basic_server_port)
- yield
- proc.kill(); proc.join(timeout=2)
+ @pytest.fixture
+ def basic_server() -> Generator[str, None, None]:
+ with run_uvicorn_in_thread(create_app()) as url:
+ yield url
+
+ @pytest.fixture
+ def basic_server_url(basic_server: str) -> str:
+ return basic_server
+
+ @pytest.fixture
+ def basic_server_port(basic_server: str) -> int:
+ return int(basic_server.rsplit(":", 1)[1])
each *_server_port fixture is removed and the *_server fixture switches from multiprocessing.Process(target=run_server, port=...) to run_uvicorn_in_thread(make_app()), yielding a URL. derived URL/port fixtures depend on the server fixture so a test asking for the port forces the server to be listening before the port is observed — closing the TOCTOU window. for the two security files the matching change is to retire start_server_process(port, settings) in favour of a start_server(settings) context manager that yields the URL, and update each test to use the URL instead of f"http://127.0.0.1:{server_port}/...".
test to verify: test_basic_server_port_holds_reservation_regression_2704 asserts that a second bind on the port handed back by the fixture fails with EADDRINUSE, which only holds when the fixture is backed by an actually-listening server (post-fix); the old pick-then-close port fixture lets the bind succeed.
full diff across the five files: 5 files changed, 205 insertions(+), 495 deletions(-); the suite (1743 passed, 98 skipped, 1 xfailed) passes locally including under -n auto. fix is for origin/main only; origin/v1.x carries the same pattern and needs the equivalent backport.
Thanks, confirmation matches what #2705 implements. Good call on v1.x: it carries the same pick-a-port-then-rebind pattern (actually in more test files than main), so I'll open a [v1.x] backport PR applying the same fix once #2705 lands.
This looks worth pinning down as a protocol-level regression rather than only an implementation bug.
For flaky streamable HTTP/SSE tests TOCTOU port race, 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.