Skip to content
Merged
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
6 changes: 4 additions & 2 deletions examples/mcp_tool_example.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"),
)
Expand Down
29 changes: 27 additions & 2 deletions examples/tests/test_example_scripts.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,11 @@
import sys
from pathlib import Path

import pytest

import dry_run_example
import mcp_tool_example
import one_tool_call
import pytest

_REPO_ROOT = Path(os.path.abspath(dry_run_example.__file__)).parents[1]
_SDK_SRC = _REPO_ROOT / "sdk" / "python" / "src"
Expand Down Expand Up @@ -143,7 +144,7 @@ def test_one_tool_call_runs_without_error(
from importlib import reload

original_env = dict(os.environ)

try:
assert asyncio.run(one_tool_call.main()) == 0
out = capsys.readouterr().out
Expand All @@ -159,3 +160,27 @@ def test_one_tool_call_runs_without_error(
os.environ.update(original_env)
if "app.config" in sys.modules:
reload(sys.modules["app.config"])


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"}]