|
| 1 | +"""Test for issue #552: stdio_client hangs on Windows.""" |
| 2 | + |
| 3 | +import sys |
| 4 | +from textwrap import dedent |
| 5 | + |
| 6 | +import anyio |
| 7 | +import pytest |
| 8 | + |
| 9 | +from mcp import ClientSession, StdioServerParameters |
| 10 | +from mcp.client.stdio import stdio_client |
| 11 | + |
| 12 | + |
| 13 | +@pytest.mark.skipif(sys.platform != "win32", reason="Windows-specific test") |
| 14 | +@pytest.mark.anyio |
| 15 | +async def test_windows_stdio_client_with_session(): |
| 16 | + """ |
| 17 | + Test the exact scenario from issue #552: Using ClientSession with stdio_client. |
| 18 | +
|
| 19 | + This reproduces the original bug report where stdio_client hangs on Windows 11 |
| 20 | + when used with ClientSession. |
| 21 | + """ |
| 22 | + # Create a minimal MCP server that responds to initialization |
| 23 | + server_script = dedent(""" |
| 24 | + import json |
| 25 | + import sys |
| 26 | +
|
| 27 | + # Read initialization request |
| 28 | + line = sys.stdin.readline() |
| 29 | +
|
| 30 | + # Send initialization response |
| 31 | + response = { |
| 32 | + "jsonrpc": "2.0", |
| 33 | + "id": 1, |
| 34 | + "result": { |
| 35 | + "protocolVersion": "1.0", |
| 36 | + "capabilities": {}, |
| 37 | + "serverInfo": {"name": "test-server", "version": "1.0"} |
| 38 | + } |
| 39 | + } |
| 40 | + print(json.dumps(response)) |
| 41 | + sys.stdout.flush() |
| 42 | +
|
| 43 | + # Exit after a short delay |
| 44 | + import time |
| 45 | + time.sleep(0.1) |
| 46 | + sys.exit(0) |
| 47 | + """).strip() |
| 48 | + |
| 49 | + params = StdioServerParameters( |
| 50 | + command=sys.executable, |
| 51 | + args=["-c", server_script], |
| 52 | + ) |
| 53 | + |
| 54 | + # This is the exact pattern from the bug report |
| 55 | + with anyio.fail_after(10): |
| 56 | + try: |
| 57 | + async with stdio_client(params) as (read, write): |
| 58 | + async with ClientSession(read, write) as session: |
| 59 | + await session.initialize() |
| 60 | + # Should exit ClientSession without hanging |
| 61 | + # Should exit stdio_client without hanging |
| 62 | + except Exception: |
| 63 | + # Connection errors are expected when process exits |
| 64 | + pass |
0 commit comments