Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions src/mcp/client/stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -158,7 +158,7 @@ async def stdout_reader():

session_message = SessionMessage(message)
await read_stream_writer.send(session_message)
except anyio.ClosedResourceError: # pragma: lax no cover
except (anyio.ClosedResourceError, anyio.BrokenResourceError): # pragma: lax no cover
await anyio.lowlevel.checkpoint()

async def stdin_writer():
Expand All @@ -174,7 +174,7 @@ async def stdin_writer():
errors=server.encoding_error_handler,
)
)
except anyio.ClosedResourceError: # pragma: no cover
except (anyio.ClosedResourceError, anyio.BrokenResourceError): # pragma: no cover
await anyio.lowlevel.checkpoint()

async with anyio.create_task_group() as tg, process:
Expand Down
14 changes: 14 additions & 0 deletions tests/client/test_stdio.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,20 @@ async def test_stdio_client_bad_path():
assert "Connection closed" in exc_info.value.error.message


@pytest.mark.anyio
async def test_stdio_client_exits_immediately_surfaces_connection_closed():
"""Regression test for #1564: process exit should not bubble BrokenResourceError."""
server_params = StdioServerParameters(command=sys.executable, args=["-c", "import sys; sys.exit(0)"])

async with stdio_client(server_params) as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
with pytest.raises(MCPError) as exc_info:
await session.initialize()

assert exc_info.value.error.code == CONNECTION_CLOSED
assert "Connection closed" in exc_info.value.error.message


@pytest.mark.anyio
async def test_stdio_client_nonexistent_command():
"""Test that stdio_client raises an error for non-existent commands."""
Expand Down