test: convert WebSocket tests to in-memory transport#2267
Draft
test: convert WebSocket tests to in-memory transport#2267
Conversation
test_ws.py used the subprocess + TCP port pattern that races under pytest-xdist: a worker allocates a port with socket.bind(0), releases it, then spawns a uvicorn subprocess hoping to rebind. Between release and rebind, another worker can claim the port, causing the WS client to connect to an unrelated server (observed: HTTP 403 Forbidden on the WebSocket upgrade). Three of the four tests here verify transport-agnostic MCP semantics (read_resource happy path, MCPError propagation, session recovery after client-side timeout). These now use the in-memory Client transport — no network, no subprocess, no race. The fourth test (test_ws_client_basic_connection) is kept as a smoke test running the real WS stack end-to-end. It uses a new run_uvicorn_in_thread helper that binds port=0 atomically and reads the actual port back from the server's socket — the OS holds the port from bind to shutdown, eliminating the race window entirely. This test alone provides 100% coverage of src/mcp/client/websocket.py. Also removed dead handler code (list_tools/call_tool were never exercised) and the no-longer-needed pragma: no cover annotations on the read_resource handler (it now runs in-process).
The three tests converted to in-memory transport in the previous commit weren't testing WebSocket behavior anymore — they were sitting in test_ws.py with misleading names. - test_ws_client_happy_request_and_response: deleted. Duplicates tests/client/test_client.py::test_read_resource. - test_ws_client_timeout: deleted. tests/issues/test_88_random_error.py covers the same session-recovery-after-timeout scenario more thoroughly (uses read_timeout_seconds and an anyio.Event to release the slow handler cleanly). - test_ws_client_exception_handling: moved to test_client.py as test_read_resource_error_propagates. This was the only unique behavior — nothing else asserts that a handler-raised MCPError reaches the client with its error code intact. test_ws.py now contains only what it says on the tin.
The previous version polled server.started with time.sleep(0.001) until uvicorn finished binding. We were waiting for uvicorn to tell us the port — but we can just bind the socket ourselves and hand it to uvicorn via server.run(sockets=[sock]). Once sock.listen() returns, the kernel queues incoming connections (up to the backlog). If a client connects before uvicorn's event loop reaches accept(), the connection sits in the accept queue and is picked up as soon as uvicorn is ready. The kernel is the synchronizer — no cross-thread flag needed. The port is now known before the thread starts. No polling, no sleep, no wait at all.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
tests/shared/test_ws.pyused the subprocess + TCP port pattern that races under pytest-xdist: a worker allocates a port withsocket.bind(0), releases it, then spawns a uvicorn subprocess hoping to rebind. Between release and rebind, another worker can claim the port — observed in CI as the WS client connecting to another worker's HTTP/SSE server and getting a403 Forbiddenon the upgrade (job 63414508256).What changed
Three tests → in-memory
Client(server)transport (no network, no subprocess, no race):test_ws_client_happy_request_and_responsetest_ws_client_exception_handlingtest_ws_client_timeoutThese verify transport-agnostic MCP semantics (read_resource happy path,
MCPErrorpropagation, session recovery after client-side timeout). None of them were testing WebSocket framing.One test kept as real-TCP smoke test →
test_ws_client_basic_connectionUses a new
run_uvicorn_in_threadhelper that bindsport=0atomically and reads the actual port back from the server's bound socket — the OS holds the port from bind to shutdown, eliminating the race window. This test alone provides 100% coverage ofsrc/mcp/client/websocket.py.Cleanup
handle_list_tools/handle_call_tool(never exercised by any test)# pragma: no coverfromhandle_read_resource(now runs in-process)anyio.sleep(2.0)withanyio.sleep_forever()for the slow-resource handler — semantically clearer that it blocks until cancellationOverlap with MAX-158
MAX-158 adds the same
run_uvicorn_in_threadhelper to fix the port race across many test files. Whichever PR lands first, the other will have a trivial rebase (the helper implementation is identical). This PR keepswait_for_serverintest_helpers.pysince other test files onmainstill use it.Test Plan
./scripts/test— full suite + 100% coverage ✓pytest tests/shared/test_ws.py -n 4 --flake-finder --flake-runs=5— 20 parallel runs, 0 flakes ✓pyright+ruff✓AI Disclaimer