From a5b633e0a3de3faa1d8a2c7e69a9bb7842a816f0 Mon Sep 17 00:00:00 2001 From: Ling Li Date: Sat, 1 Mar 2025 22:45:59 +0100 Subject: [PATCH] handle BrokenResourceError gracefully --- src/mcp/server/stdio.py | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/src/mcp/server/stdio.py b/src/mcp/server/stdio.py index 0e0e49129..c1aab9b42 100644 --- a/src/mcp/server/stdio.py +++ b/src/mcp/server/stdio.py @@ -67,16 +67,27 @@ async def stdin_reader(): continue await read_stream_writer.send(message) + except anyio.BrokenResourceError as ex: + print(f"BrokenResourceError(reader): {ex}") + pass except anyio.ClosedResourceError: await anyio.lowlevel.checkpoint() + except Exception as ex: + print(f"read error: {ex}") async def stdout_writer(): try: async with write_stream_reader: async for message in write_stream_reader: - json = message.model_dump_json(by_alias=True, exclude_none=True) - await stdout.write(json + "\n") - await stdout.flush() + try: + json = message.model_dump_json(by_alias=True, exclude_none=True) + await stdout.write(json + "\n") + await stdout.flush() + except Exception as ex: + print(f"problem with writer: {ex}") + except anyio.BrokenResourceError as ex: + print(f"BrokenResourceError(writer): {ex}") + pass except anyio.ClosedResourceError: await anyio.lowlevel.checkpoint()