fix(mcp): bound disconnected session cleanup wait (#8378)

* fix(mcp): bound disconnected session cleanup wait

* fix(mcp): use builtin timeout error in cleanup wait

* style(mcp): normalize regression test file ending

* docs(mcp): sync cleanup guidance with upstream

* test(mcp): harden disconnect cleanup regression

* test(mcp): assert owner reaper survives cleanup waiter

* style(mcp): satisfy backend Ruff formatting

* style(mcp): collapse teardown drain call per Ruff

* style(mcp): satisfy Ruff formatting for cleanup regression

* style(mcp): satisfy Ruff formatting for cleanup regression

* style(mcp): wrap teardown drain for Ruff

* style(mcp): satisfy Ruff formatting in disconnect regression

* style(mcp): wrap cleanup owner assertion

* style(mcp): format owner reaper assertion

* style(mcp): respect repository Ruff line length

* style(mcp): apply backend Ruff formatting

* style(mcp): apply Ruff formatting to cleanup regression

* style(mcp): format session cleanup regression test

---------

Co-authored-by: Willem Jiang <willem.jiang@gmail.com>
This commit is contained in:
NanPan 2026-11-22 09:27:53 +08:00 committed by GitHub
parent f95d77f961
commit 7314535539
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 115 additions and 6 deletions

View File

@ -35,6 +35,8 @@ make test-blocking-io
- **`mcp_tasks` is read at startup.** The installed submitter decides whether task
tools are exposed. Editing the config on disk does not change a running process.
- **Disconnect cleanup is bounded.** A transport failure waits at most `SESSION_CLOSE_TIMEOUT` for session cleanup; if the owner is still unwinding, its teardown remains strongly tracked in `_teardown_tasks` while the caller receives the original transport error.
## Credentials
- **Header names are case-insensitive.** Every credential interceptor writes

View File

@ -117,6 +117,8 @@ _MCP_CLOSED_STREAM_ERRORS = (
anyio.EndOfStream,
)
_MCP_DISCONNECT_CLEANUP_TIMEOUT_SECONDS = 5.0
def _is_mcp_transport_disconnect(error: Exception) -> bool:
if isinstance(error, _MCP_CLOSED_STREAM_ERRORS):
@ -124,14 +126,38 @@ def _is_mcp_transport_disconnect(error: Exception) -> bool:
return isinstance(error, McpError) and error.error.code == CONNECTION_CLOSED and error.error.message == "Connection closed"
async def _finish_session_cleanup(cleanup: asyncio.Task[Any], server_name: str) -> bool:
"""Wait for cleanup despite cancellation and report whether it was requested."""
async def _finish_session_cleanup(
cleanup: asyncio.Task[Any],
server_name: str,
*,
timeout_seconds: float,
) -> bool:
"""Wait for cleanup up to a bound despite cancellation and report caller cancellation."""
cancelled = False
loop = asyncio.get_running_loop()
deadline = loop.time() + max(0.0, timeout_seconds)
while not cleanup.done():
remaining = deadline - loop.time()
if remaining <= 0:
logger.warning(
"Timed out waiting for disconnected MCP session cleanup for server '%s' after %.1fs; teardown remains supervised",
server_name,
timeout_seconds,
)
cleanup.cancel()
return cancelled
try:
await asyncio.shield(cleanup)
await asyncio.wait_for(asyncio.shield(cleanup), timeout=remaining)
except asyncio.CancelledError:
cancelled = True
except TimeoutError:
logger.warning(
"Timed out waiting for disconnected MCP session cleanup for server '%s' after %.1fs; teardown remains supervised",
server_name,
timeout_seconds,
)
cleanup.cancel()
return cancelled
except Exception:
logger.warning(
"Failed to close disconnected MCP session for server '%s'",
@ -174,8 +200,12 @@ async def call_pooled_session_tool(
except Exception as error:
if _is_mcp_transport_disconnect(error):
cleanup_call = pool.close_session_if_current(server_name, scope_key, session) if domain == "deployment" else pool.close_session_if_current(server_name, scope_key, session, domain=domain)
cleanup = asyncio.create_task(cleanup_call)
if await _finish_session_cleanup(cleanup, server_name):
cleanup = asyncio.create_task(cleanup_call, name=f"mcp-disconnect-cleanup:{server_name}")
pool._track_owner_teardown(cleanup)
timeout_seconds = getattr(pool, "SESSION_CLOSE_TIMEOUT", None)
if type(timeout_seconds) not in (int, float):
timeout_seconds = _MCP_DISCONNECT_CLEANUP_TIMEOUT_SECONDS
if await _finish_session_cleanup(cleanup, server_name, timeout_seconds=float(timeout_seconds)):
raise asyncio.CancelledError
raise
@ -184,7 +214,7 @@ class MCPSessionPool:
"""Manages persistent MCP sessions scoped by ``(server_name, scope_key, owning_loop, ownership_domain)``."""
MAX_SESSIONS = 256
SESSION_CLOSE_TIMEOUT = 5.0 # seconds to wait when closing a session on a foreign loop
SESSION_CLOSE_TIMEOUT = _MCP_DISCONNECT_CLEANUP_TIMEOUT_SECONDS # disconnect + synchronous foreign-loop close bound
def __init__(self) -> None:
# Each entry: (session, owning_loop, owner_task, close_event).

View File

@ -3184,3 +3184,80 @@ async def test_mcp_tools_routed_to_source_server_with_prefix_overlap():
routing = dict(routed)
assert routing["web_scraper_search"] == "web_scraper", f"tool mis-routed to {routing.get('web_scraper_search')!r}, expected 'web_scraper'"
assert routing["web_open"] == "web"
@pytest.mark.asyncio
async def test_disconnect_cleanup_timeout_preserves_owner_tracking():
"""A stuck owner exit cannot hold a disconnected tool call indefinitely."""
pool = MCPSessionPool()
pool.SESSION_CLOSE_TIMEOUT = 0.01
tracked_teardown_targets = []
track_owner_teardown = pool._track_owner_teardown
def record_owner_teardown(task):
tracked_teardown_targets.append(task)
track_owner_teardown(task)
pool._track_owner_teardown = record_owner_teardown
exit_started = asyncio.Event()
release_exit = asyncio.Event()
session = AsyncMock()
session.initialize = AsyncMock()
session.call_tool = AsyncMock(side_effect=anyio.EndOfStream())
class Cm:
owner: asyncio.Task | None = None
async def __aenter__(self):
self.owner = asyncio.current_task()
return session
async def __aexit__(self, *_args):
assert asyncio.current_task() is self.owner
exit_started.set()
await release_exit.wait()
return False
cm = Cm()
connection = {"transport": "stdio", "command": "x", "args": []}
with patch("langchain_mcp_adapters.sessions.create_session", return_value=cm):
pooled = await pool.get_session("srv", "scope", connection)
call = asyncio.create_task(call_pooled_session_tool(pooled, pool, server_name="srv", scope_key="scope", tool_name="act", arguments={}, call_kwargs={}))
try:
await asyncio.wait_for(exit_started.wait(), timeout=0.5)
# asyncio.wait() observes the deadline without cancelling the caller.
# wait_for(call) would wait for cancellation to propagate and could
# hang here if the cleanup path regressed to an unbounded wait.
done, _pending = await asyncio.wait({call}, timeout=1.0)
assert call in done, "disconnected tool call exceeded the cleanup deadline"
with pytest.raises(anyio.EndOfStream):
await call
# The caller has returned, but __aexit__ is deliberately still blocked.
# Wait for the cleanup waiter itself to finish before checking owner
# tracking; otherwise its own reaper could satisfy a set-nonempty check.
cleanup_waiter = next(
(task for task in tracked_teardown_targets if task.get_name() == "mcp-disconnect-cleanup:srv"),
None,
)
assert cleanup_waiter is not None
await asyncio.wait_for(asyncio.gather(cleanup_waiter, return_exceptions=True), timeout=0.5)
assert cleanup_waiter.done()
# The pool must have handed off this exact owner, and its reaper must
# remain retained until the blocked __aexit__ is released.
assert cm.owner is not None and not cm.owner.done()
assert cm.owner in tracked_teardown_targets
owner_reaper = f"mcp-session-owner-reap:{cm.owner.get_name()}"
assert any(task.get_name() == owner_reaper for task in pool._teardown_tasks)
finally:
# Always release the owner, including when the deadline assertion fails.
release_exit.set()
await asyncio.gather(call, return_exceptions=True)
if cm.owner is not None:
await asyncio.gather(cm.owner, return_exceptions=True)
while pool._teardown_tasks:
await asyncio.gather(*list(pool._teardown_tasks), return_exceptions=True)
assert not pool._teardown_tasks