Skip to content

Secure, Fast, and Extensible Sandbox runtime for AI agents.

fix(mcp): do not report a failed connect nobody waits for

Maohao882c29db1d68
diff --git a/sdks/mcp/sandbox/python/src/opensandbox_mcp/server.py b/sdks/mcp/sandbox/python/src/opensandbox_mcp/server.py
index faba365ed..5a0e52ef9 100644
--- a/sdks/mcp/sandbox/python/src/opensandbox_mcp/server.py
+++ b/sdks/mcp/sandbox/python/src/opensandbox_mcp/server.py
@@ -50,7 +50,9 @@ class ServerState:
sandboxes: dict[str, Sandbox] = field(default_factory=dict)
connection_config: ConnectionConfig = field(default_factory=ConnectionConfig)
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
- connecting: dict[str, asyncio.Task[Sandbox]] = field(default_factory=dict)
+ connecting: dict[str, asyncio.Task[Sandbox | Exception]] = field(
+ default_factory=dict
+ )
async def add(self, sandbox: Sandbox) -> None:
async with self.lock:
@@ -66,7 +68,7 @@ class ServerState:
def _discard_connecting(
- state: ServerState, sandbox_id: str, task: asyncio.Task[Sandbox]
+ state: ServerState, sandbox_id: str, task: asyncio.Task[Sandbox | Exception]
) -> None:
# Only pop if this task is still the mapped entry (a stale callback
# must not evict a newer connect).
@@ -125,10 +127,16 @@ def register_tools(
return decorator
- async def _connect_and_register(sandbox_id: str) -> Sandbox:
- sandbox = await Sandbox.connect(
- sandbox_id, connection_config=_borrowed_config(state)
- )
+ async def _connect_and_register(sandbox_id: str) -> Sandbox | Exception:
+ # A failure is returned, not raised: once every caller is cancelled,
+ # asyncio.shield (Python 3.14+) reports a failed task to the loop
+ # exception handler, although nobody waits for it any more.
+ try:
+ sandbox = await Sandbox.connect(
+ sandbox_id, connection_config=_borrowed_config(state)
+ )
+ except Exception as exc:
+ return exc
await state.add(sandbox)
return sandbox
@@ -158,7 +166,10 @@ def register_tools(
)
# Other tool calls may be waiting on the same task, so cancelling this
# call (e.g. the client cancelled the request) must not cancel it.
- return await asyncio.shield(task)
+ result = await asyncio.shield(task)
+ if isinstance(result, Exception):
+ raise result
+ return result
@tool()
async def sandbox_create(
diff --git a/sdks/mcp/sandbox/python/tests/test_server_tools.py b/sdks/mcp/sandbox/python/tests/test_server_tools.py
index 0397449b9..b34e0d630 100644
--- a/sdks/mcp/sandbox/python/tests/test_server_tools.py
+++ b/sdks/mcp/sandbox/python/tests/test_server_tools.py
@@ -324,3 +324,41 @@ async def test_connect_finished_after_its_caller_cancelled_is_registered(
)
assert metrics == "metrics"
assert connect_calls == ["sbx-orphan"]
+
+
+async def test_connect_failure_after_its_caller_cancelled_is_not_logged(
+ server, monkeypatch
+) -> None:
+ """A connect that fails after its only caller was cancelled is not
+ reported to the loop exception handler: no request is waiting for it, and
+ the next call simply connects again."""
+ fake, state = server
+ release = asyncio.Event()
+ entered = asyncio.Event()
+
+ class _FakeServerSandboxModule:
+ @staticmethod
+ async def connect(sandbox_id, connection_config=None, **kwargs):
+ entered.set()
+ await release.wait()
+ raise RuntimeError("transient connect failure")
+
+ monkeypatch.setattr("opensandbox_mcp.server.Sandbox", _FakeServerSandboxModule)
+ loop = asyncio.get_running_loop()
+ reported: list[dict] = []
+ loop.set_exception_handler(lambda _loop, context: reported.append(context))
+
+ cancelled = asyncio.create_task(
+ fake.tools["sandbox_get_metrics"]("sbx-orphan", connect_if_missing=True)
+ )
+ await asyncio.wait_for(entered.wait(), timeout=1)
+ connect_task = state.connecting["sbx-orphan"]
+ cancelled.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await cancelled
+ release.set()
+ await asyncio.wait_for(connect_task, timeout=1)
+ await asyncio.sleep(0)
+
+ assert reported == []