Skip to content

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

fix(mcp): do not cancel a coalesced connect when one caller is cancelled

Maohaoe02bbf75bbb8
diff --git a/sdks/mcp/sandbox/python/src/opensandbox_mcp/server.py b/sdks/mcp/sandbox/python/src/opensandbox_mcp/server.py
index 627f799fc..faba365ed 100644
--- a/sdks/mcp/sandbox/python/src/opensandbox_mcp/server.py
+++ b/sdks/mcp/sandbox/python/src/opensandbox_mcp/server.py
@@ -125,6 +125,13 @@ 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)
+ )
+ await state.add(sandbox)
+ return sandbox
+
async def _get_or_connect_sandbox(
sandbox_id: str,
*,
@@ -144,18 +151,14 @@ def register_tools(
"Sandbox not found in local registry. Call sandbox_connect or "
"set connect_if_missing=True with connection parameters."
)
- task = asyncio.ensure_future(
- Sandbox.connect(
- sandbox_id, connection_config=_borrowed_config(state)
- )
- )
+ task = asyncio.ensure_future(_connect_and_register(sandbox_id))
state.connecting[sandbox_id] = task
task.add_done_callback(
lambda t: _discard_connecting(state, sandbox_id, t)
)
- sandbox = await task
- await state.add(sandbox)
- return sandbox
+ # 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)
@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 b2951bbb7..0397449b9 100644
--- a/sdks/mcp/sandbox/python/tests/test_server_tools.py
+++ b/sdks/mcp/sandbox/python/tests/test_server_tools.py
@@ -235,3 +235,92 @@ async def test_failed_connect_is_not_sticky(server, monkeypatch) -> None:
assert metrics == "metrics"
assert attempts == ["sbx-flaky", "sbx-flaky"]
assert state.connecting == {}
+
+
+async def test_cancelled_caller_does_not_cancel_coalesced_connect(
+ server, monkeypatch
+) -> None:
+ """Cancelling one tool call must not fail others waiting on the same connect.
+
+ MCP cancels a tool call's handler when the client cancels the request.
+ """
+ fake, state = server
+ release = asyncio.Event()
+ entered = asyncio.Event()
+ connect_calls: list[str] = []
+
+ class _MetricsSandbox(_FakeSandbox):
+ async def get_metrics(self):
+ return "metrics"
+
+ class _FakeServerSandboxModule:
+ @staticmethod
+ async def connect(sandbox_id, connection_config=None, **kwargs):
+ connect_calls.append(sandbox_id)
+ entered.set()
+ await release.wait()
+ return _MetricsSandbox(sandbox_id)
+
+ monkeypatch.setattr("opensandbox_mcp.server.Sandbox", _FakeServerSandboxModule)
+
+ cancelled = asyncio.create_task(
+ fake.tools["sandbox_get_metrics"]("sbx-shared", connect_if_missing=True)
+ )
+ await asyncio.wait_for(entered.wait(), timeout=1)
+ waiting = asyncio.create_task(
+ fake.tools["sandbox_get_metrics"]("sbx-shared", connect_if_missing=True)
+ )
+ await asyncio.sleep(0)
+
+ cancelled.cancel()
+ with pytest.raises(asyncio.CancelledError):
+ await cancelled
+ release.set()
+
+ assert await asyncio.wait_for(waiting, timeout=1) == "metrics"
+ assert connect_calls == ["sbx-shared"]
+ assert state.sandboxes["sbx-shared"].id == "sbx-shared"
+
+
+async def test_connect_finished_after_its_caller_cancelled_is_registered(
+ server, monkeypatch
+) -> None:
+ """A connect whose only caller was cancelled still registers the sandbox,
+ so the next call reuses it instead of connecting again."""
+ fake, state = server
+ release = asyncio.Event()
+ entered = asyncio.Event()
+ connect_calls: list[str] = []
+
+ class _MetricsSandbox(_FakeSandbox):
+ async def get_metrics(self):
+ return "metrics"
+
+ class _FakeServerSandboxModule:
+ @staticmethod
+ async def connect(sandbox_id, connection_config=None, **kwargs):
+ connect_calls.append(sandbox_id)
+ entered.set()
+ await release.wait()
+ return _MetricsSandbox(sandbox_id)
+
+ monkeypatch.setattr("opensandbox_mcp.server.Sandbox", _FakeServerSandboxModule)
+
+ 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)
+
+ metrics = await fake.tools["sandbox_get_metrics"](
+ "sbx-orphan", connect_if_missing=True
+ )
+ assert metrics == "metrics"
+ assert connect_calls == ["sbx-orphan"]