fix: preserve real cancellation in MCP paths

This commit is contained in:
adabarbulescu
2026-07-18 17:36:35 +08:00
committed by Xubin Ren
parent 07ad0bafa8
commit d4f5abe004
5 changed files with 80 additions and 9 deletions
+28
View File
@@ -111,6 +111,34 @@ class TestHandleStop:
class TestDispatch:
@pytest.mark.asyncio
async def test_run_logs_and_continues_after_leaked_cancelled_error(self, monkeypatch):
loop, bus = _make_loop()
loop._connect_mcp = AsyncMock()
loop.close_mcp = AsyncMock()
loop.auto_compact.check_expired = MagicMock()
warnings: list[str] = []
calls = 0
async def consume_once_then_stop():
nonlocal calls
calls += 1
if calls == 1:
raise asyncio.CancelledError()
loop.stop()
raise asyncio.TimeoutError()
monkeypatch.setattr(bus, "consume_inbound", consume_once_then_stop)
monkeypatch.setattr(
"nanobot.agent.loop.logger.warning",
lambda message, *args, **kwargs: warnings.append(message),
)
await loop.run()
assert calls == 2
assert any("Ignoring leaked CancelledError" in warning for warning in warnings)
def test_exec_tool_not_registered_when_disabled(self):
from nanobot.agent.tools.shell import ExecToolConfig
from nanobot.config.schema import ToolsConfig
+29
View File
@@ -144,6 +144,35 @@ def _make_wrapper(session: object, *, timeout: float = 0.1) -> MCPToolWrapper:
return MCPToolWrapper(session, "test", tool_def, tool_timeout=timeout)
@pytest.mark.asyncio
async def test_connect_missing_servers_propagates_external_cancellation(monkeypatch) -> None:
started = asyncio.Event()
async def connect_mcp_servers(_servers: dict, _registry: ToolRegistry) -> dict:
started.set()
await asyncio.sleep(60)
return {}
class State:
pass
state = State()
state._mcp_closing = False
state._mcp_servers = {"test": MCPServerConfig(command="fake")}
state._mcp_stacks = {}
state._mcp_connecting = False
monkeypatch.setattr(mcp_mod, "connect_mcp_servers", connect_mcp_servers)
task = asyncio.create_task(mcp_mod.connect_missing_servers(state, ToolRegistry()))
await asyncio.wait_for(started.wait(), timeout=1.0)
task.cancel()
with pytest.raises(asyncio.CancelledError):
await task
assert state._mcp_connecting is False
def test_wrapper_preserves_non_nullable_unions() -> None:
tool_def = SimpleNamespace(
name="demo",