Skip to content

Commit 655ac4f

Browse files
committed
Cancel queued notifications during normal MCP shutdown
Keep foreground closed-session calls terminal while joining pending SDK notification work. Cover discovery-only resource and action-only servers without extra RPCs. Signed-off-by: zlareb1 <lareb.zafar@clickhouse.com>
1 parent 44e9764 commit 655ac4f

2 files changed

Lines changed: 30 additions & 1 deletion

File tree

‎server/clients/mcp_source.py‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -621,6 +621,19 @@ async def _authorize(self) -> None:
621621
await self.validate_access()
622622
self._check_state()
623623

624+
async def _transport_authorize(self) -> None:
625+
try:
626+
await self._authorize()
627+
except MCPSourceError as error:
628+
if (
629+
error.code == "closed"
630+
and self._closing
631+
and asyncio.current_task() is not self._owner_task
632+
):
633+
# Pending SDK notifications stop without poisoning expected shutdown.
634+
raise asyncio.CancelledError from None
635+
raise
636+
624637
async def __aenter__(self) -> MCPSourceClient:
625638
if self._owner_task is not None or self._deadline:
626639
raise MCPSourceError("closed")
@@ -679,7 +692,7 @@ async def _initialize(self, stack: AsyncExitStack) -> None:
679692
self._config,
680693
self.credential,
681694
self._deadline,
682-
self._authorize,
695+
self._transport_authorize,
683696
transport=self._test_transport,
684697
)
685698
self._transport = transport

‎tests/unit/test_mcp_source_client.py‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1222,3 +1222,19 @@ async def reply(request: httpx.Request) -> httpx.Response:
12221222
assert pins == [str(httpx.URL(endpoint))]
12231223
assert requests == []
12241224
assert transport.failure == "denied"
1225+
1226+
1227+
@pytest.mark.asyncio
1228+
@pytest.mark.parametrize("actions_only", [False, True])
1229+
async def test_discovery_without_an_approved_tool_rpc_closes_cleanly(
1230+
monkeypatch: pytest.MonkeyPatch, actions_only: bool
1231+
) -> None:
1232+
async with synthetic_server(monkeypatch, tools=actions_only) as state:
1233+
opened = client()
1234+
async with opened:
1235+
discovered = await opened.discover()
1236+
assert discovered.resources is (not actions_only)
1237+
assert discovered.tools == ()
1238+
assert state["calls"] == []
1239+
assert opened._owner_task is not None and opened._owner_task.done()
1240+
assert opened._transport is not None and opened._transport.failure is None

0 commit comments

Comments
 (0)