From 311e30879723ac02d7c7529e5c65929837f217aa Mon Sep 17 00:00:00 2001 From: CS Date: Wed, 11 Nov 2026 17:49:05 -0800 Subject: [PATCH] fix(examples): mcp_tool_example --serve awaits serve_async (#359) main_serve() runs under asyncio.run() and called the synchronous b2a_sdk.mcp.serve(), which calls asyncio.run() again, so --serve exited 1 with "asyncio.run() cannot be called from a running event loop". Await serve_async() instead. Fixes #359 Co-Authored-By: Claude Opus 5.5 Signed-off-by: CS --- examples/mcp_tool_example.py | 6 ++++-- examples/tests/test_example_scripts.py | 24 ++++++++++++++++++++++++ 2 files changed, 28 insertions(+), 2 deletions(-) diff --git a/examples/mcp_tool_example.py b/examples/mcp_tool_example.py index 5eb79f084..8cbd4d3a0 100644 --- a/examples/mcp_tool_example.py +++ b/examples/mcp_tool_example.py @@ -203,9 +203,11 @@ async def main_generate(): async def main_serve(): """Run standalone MCP server.""" - from b2a_sdk.mcp import serve + from b2a_sdk.mcp import serve_async - serve( + # main_serve already runs inside asyncio.run(), so await the async server. + # The sync serve() wrapper would start a second event loop and fail. + await serve_async( transport="stdio", api_url=os.getenv("B2A_API_URL", "http://localhost:8000"), ) diff --git a/examples/tests/test_example_scripts.py b/examples/tests/test_example_scripts.py index dff4d8f78..2e0353950 100644 --- a/examples/tests/test_example_scripts.py +++ b/examples/tests/test_example_scripts.py @@ -131,3 +131,27 @@ async def fake(_api_key: str, _key: str) -> dict: monkeypatch.setenv("AGENT_API_KEY", "local-test-key") monkeypatch.setattr(call_with_retry, "call_once", fake) assert asyncio.run(call_with_retry.main()) == 1 + + +def test_serve_awaits_the_async_server_inside_the_running_loop( + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Issue #359: --serve runs under asyncio.run, so it must not call asyncio.run again.""" + import b2a_sdk.mcp + + calls: list[dict[str, object]] = [] + + async def fake_serve_async(**kwargs: object) -> None: + asyncio.get_running_loop() + calls.append(kwargs) + + def nested_serve(**kwargs: object) -> None: + asyncio.run(fake_serve_async(**kwargs)) + + monkeypatch.setenv("B2A_API_URL", "http://127.0.0.1:9") + monkeypatch.setattr(b2a_sdk.mcp, "serve_async", fake_serve_async) + monkeypatch.setattr(b2a_sdk.mcp, "serve", nested_serve) + + asyncio.run(mcp_tool_example.main_serve()) + + assert calls == [{"transport": "stdio", "api_url": "http://127.0.0.1:9"}]