JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(mcp): 远程连接器长超时生效并修复 SSE 60s 硬上限与断连崩溃
akko6245f930262d973
diff --git a/jiuwenswarm/common/mcp_call_timeout_patch.py b/jiuwenswarm/common/mcp_call_timeout_patch.pyindex 2ab4a51d55..4f4dbcae05 100644--- a/jiuwenswarm/common/mcp_call_timeout_patch.py+++ b/jiuwenswarm/common/mcp_call_timeout_patch.py@@ -19,23 +19,34 @@ This patch is applied once at process startup (from"Not connected" once ``self._session`` is None) instead of waiting outthe full timeout again.- NB: must use ``anyio.fail_after`` (a cancel scope), *not*- ``asyncio.wait_for``. The MCP SDK runs its streamable-http transport- inside an anyio task group; ``asyncio.wait_for`` runs the wrapped- coroutine in a *different* asyncio Task, which collides with anyio's- cancel-scope/Task invariants and corrupts the session — healthy calls- then start failing with "Not connected". ``anyio.fail_after`` cancels- within the current task, so it stays compatible with the SDK's scopes.+ NB: must use ``anyio.fail_after`` (a cancel scope), *not*+ ``asyncio.wait_for``. The MCP SDK runs its streamable-http transport+ inside an anyio task group; ``asyncio.wait_for`` runs the wrapped+ coroutine in a *different* asyncio Task, which collides with anyio's+ cancel-scope/Task invariants and corrupts the session — healthy calls+ then start failing with "Not connected". ``anyio.fail_after`` cancels+ within the current task, so it stays compatible with the SDK's scopes.+ The resolved timeout is also propagated into the client method's own+ ``timeout`` kwarg, so SseClient's inner ``asyncio.wait_for`` ceiling+ matches the outer scope instead of clamping to its 60s default (which+ corrupts the session's cancel scopes when it fires first).B. Monkeypatch ``ToolMgr._create_client`` so ``config.params["timeout_s"]``(i.e. ``/mcp add ... --timeout_s N``) is stamped onto the client instanceas ``_jws_call_timeout`` and honored by (A). Falls back to``DEFAULT_CALL_TIMEOUT`` when unset.+ C. Wrap the MCP SDK factory functions (``mcp.client.sse.sse_client`` /+ ``mcp.client.streamable_http.streamablehttp_client``) so connections+ created for a client with a stamped ``_jws_call_timeout`` get an+ ``sse_read_timeout`` of at least that value, instead of the SDK's 300s+ default — long tool calls (SSE result stream / held streamable-http+ response) would otherwise be dropped mid-call after 300 idle seconds.Both transforms are idempotent: a module-level ``_PATCHED`` guard makes thewhole function a no-op on repeat calls."""from __future__ import annotations+import contextvarsfrom typing import Anyimport anyio@@ -46,12 +57,137 @@ _PATCHED = False# _PATCHED, so we don't stamp attributes onto function objects (which would# need a mypy ``[attr-defined]`` type-ignore)._wrapped_methods: set[tuple[type, str]] = set()+# (module, name) SDK factory functions already wrapped, and (cls, name)+# client connect methods already wrapped — same idempotency purpose.+_wrapped_factories: set[tuple[object, str]] = set()+_wrapped_connects: set[tuple[type, str]] = set()+#: Set while a client with a stamped ``_jws_call_timeout`` is establishing its+#: transport, so the SDK factory wrappers can lift ``sse_read_timeout`` to the+#: per-connector timeout (see ``_patch_sdk_read_timeouts``).+_pending_sdk_read_timeout: contextvars.ContextVar[float | None] = contextvars.ContextVar(+ "_jws_pending_sdk_read_timeout", default=None+)#: Fallback per-call timeout (seconds) when ``--timeout_s`` is not supplied.DEFAULT_CALL_TIMEOUT = 30.0__all__ = ["apply_mcp_call_timeout_patch", "DEFAULT_CALL_TIMEOUT"]+def _stamp_is_valid(value: Any) -> bool:+ return isinstance(value, (int, float)) and not isinstance(value, bool) and value > 0+++def _patch_sdk_read_timeouts() -> None:+ """Lift the MCP SDK transports' ``sse_read_timeout`` to the connector timeout.++ The SDK builds one httpx client per connection with+ ``httpx.Timeout(timeout, read=sse_read_timeout)`` where ``sse_read_timeout``+ defaults to 300s. A long tool call exceeds it silently: on SSE the result+ is delivered on the event stream, on streamable-http the POST response is+ held until the tool finishes — either way an idle read of more than 300s+ drops the connection mid-call. openjiuwen's clients don't expose the+ parameter, so wrap the module-level factory functions and raise+ ``sse_read_timeout`` to the client's stamped ``_jws_call_timeout`` when one+ is present. The stamp is surfaced to the factories through a ContextVar set+ by wrapping the clients' connect paths (SseClient builds its transport+ inside ``_do_connect`` on the owner task; StreamableHttpClient inside+ ``connect``), which run in the same task that invokes the factory.+ """+ import mcp.client.sse as mcp_sse_module+ import mcp.client.streamable_http as mcp_streamable_http_module+ from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClient+ from openjiuwen.core.foundation.tool.mcp.client.streamable_http_client import (+ StreamableHttpClient,+ )++ for module, factory_name in (+ (mcp_sse_module, "sse_client"),+ (mcp_streamable_http_module, "streamablehttp_client"),+ ):+ if (module, factory_name) in _wrapped_factories:+ continue+ _wrapped_factories.add((module, factory_name))+ orig_factory = getattr(module, factory_name)++ def factory_with_read_timeout(*args: Any, orig=orig_factory, name=factory_name, **kwargs: Any):+ hint = _pending_sdk_read_timeout.get()+ if _stamp_is_valid(hint):+ current = kwargs.get("sse_read_timeout")+ if not _stamp_is_valid(current) or float(current) < float(hint):+ kwargs["sse_read_timeout"] = float(hint)+ logger.info(+ "[mcp-timeout] raised %s sse_read_timeout to %.1fs for this connection",+ name,+ float(hint),+ )+ return orig(*args, **kwargs)++ setattr(module, factory_name, factory_with_read_timeout)++ for cls, method_name in (+ (SseClient, "_do_connect"),+ (StreamableHttpClient, "connect"),+ ):+ if (cls, method_name) in _wrapped_connects:+ continue+ _wrapped_connects.add((cls, method_name))+ orig_method = getattr(cls, method_name)++ async def method_with_read_timeout(self, *args: Any, orig=orig_method, **kwargs: Any):+ hint = getattr(self, "_jws_call_timeout", None)+ token = (+ _pending_sdk_read_timeout.set(float(hint)) if _stamp_is_valid(hint) else None+ )+ try:+ return await orig(self, *args, **kwargs)+ finally:+ if token is not None:+ _pending_sdk_read_timeout.reset(token)++ setattr(cls, method_name, method_with_read_timeout)+++def _patch_sse_disconnect_guard() -> None:+ """Keep ``SseClient.disconnect`` best-effort cleanup.++ openjiuwen's ``_do_disconnect`` wraps the session/transport ``__aexit__``+ calls in ``asyncio.wait_for``, which executes them in a new asyncio Task.+ The contexts were entered on the SSE owner task, so exiting them from+ wait_for's task trips anyio's cancel-scope invariant; the broken teardown+ then surfaces as a ``CancelledError`` raised from ``_submit``'s future —+ a BaseException that sails past the ``except Exception`` handlers around+ discovery cleanup (``_list_remote_mcp_connector_tools``) and the pooled+ worker's exit-stack callback, aborting SSE connector registration outright.+ Disconnect is cleanup: swallow the future-cancel flavor, log it, and+ report failure. A genuine cancellation of the running task (``cancelling``+ count > 0) still propagates.+ """+ import asyncio as _asyncio++ from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClient++ if (SseClient, "disconnect-guard") in _wrapped_connects:+ return+ _wrapped_connects.add((SseClient, "disconnect-guard"))+ orig_disconnect = getattr(SseClient, "disconnect")++ async def disconnect_guarded(self, *args: Any, orig=orig_disconnect, **kwargs: Any):+ try:+ return await orig(self, *args, **kwargs)+ except _asyncio.CancelledError:+ task = _asyncio.current_task()+ cancelling = getattr(task, "cancelling", None)+ if callable(cancelling) and cancelling() > 0:+ raise+ logger.warning(+ "[mcp-timeout] SseClient.disconnect aborted by transport teardown "+ "(pre-existing anyio cancel-scope conflict); treated as failed cleanup",+ )+ return False++ setattr(SseClient, "disconnect", disconnect_guarded)++def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT) -> None:"""Apply the per-call MCP timeout patch. Idempotent per process."""global _PATCHED@@ -84,12 +220,25 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)async def wrapped(self, *args, **kwargs):timeout = _resolve_timeout(self, kwargs.get("timeout"))+ # Run the inner deadline slightly behind the resolved timeout so+ # that, under the pooled worker (whose outer asyncio.wait_for uses+ # exactly ``timeout``), the OUTER deadline always fires first and+ # produces a clean TimeoutError. If the anyio scope below fired at+ # the same instant from inside wait_for's spawned task, its cancel+ # bleeds into the wait_for machinery and surfaces as a+ # CancelledError instead. Direct (non-worker) callers simply get+ # a 5s-later backstop. The resolved timeout is also propagated+ # into the client method's ``timeout`` kwarg so SseClient's inner+ # ``asyncio.wait_for`` ceiling follows the same deadline instead+ # of clamping to its 60s default.+ deadline = timeout + 5.0+ kwargs.setdefault("timeout", deadline)try:# anyio.fail_after (cancel scope) — NOT asyncio.wait_for: the# latter runs the coroutine in a separate asyncio Task, which# breaks anyio's cancel-scope invariants inside the MCP SDK# transport and corrupts the session on healthy calls.- with anyio.fail_after(timeout):+ with anyio.fail_after(deadline):return await orig(self, *args, **kwargs)except TimeoutError:logger.warning(@@ -119,6 +268,9 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)_wrap_with_timeout(cls, "call_tool")_wrap_with_timeout(cls, "list_tools")+ _patch_sdk_read_timeouts()+ _patch_sse_disconnect_guard()+# (B) Thread config.params["timeout_s"] (--timeout_s) onto each client so# (A) can pick it up. NOTE: if the browser-move client patch is applied# *after* this one it rebinds ToolMgr._create_client and would shadow this@@ -154,6 +306,7 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)setattr(ToolMgr, "_create_client", staticmethod(_create_client_with_timeout))logger.info(- "[mcp-timeout] patch applied (default_timeout=%.1fs, covered=StreamableHttpClient,SseClient)",+ "[mcp-timeout] patch applied (default_timeout=%.1fs, covered=StreamableHttpClient,SseClient,"+ "sdk_read_timeouts)",default_timeout,)diff --git a/tests/unit_tests/common/test_mcp_call_timeout_patch.py b/tests/unit_tests/common/test_mcp_call_timeout_patch.pynew file mode 100644index 0000000000..e61bf802bb--- /dev/null+++ b/tests/unit_tests/common/test_mcp_call_timeout_patch.py@@ -0,0 +1,92 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""Unit coverage for the remote-MCP per-call timeout patch.++End-to-end behaviour (long SSE / streamable-http calls under a stamped+``_jws_call_timeout``, SDK ``sse_read_timeout`` lifting, and the SSE teardown+guard) is verified against real delay servers in the vendored harness; these+tests pin the propagation contract that is observable without a live server.+"""++from __future__ import annotations++import asyncio+from typing import Any++import pytest++from jiuwenswarm.common.mcp_call_timeout_patch import (+ DEFAULT_CALL_TIMEOUT,+ apply_mcp_call_timeout_patch,+)+from openjiuwen.core.foundation.tool import McpServerConfig+from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClient+++class _FakeSession:+ def __init__(self) -> None:+ self.calls: list[tuple[str, dict[str, Any]]] = []++ async def call_tool(self, name: str, arguments: dict[str, Any]) -> Any:+ self.calls.append((name, arguments))+ return None+++def _make_sse_client() -> SseClient:+ config = McpServerConfig(+ server_id="timeout-test",+ server_name="timeout-test",+ server_path="http://127.0.0.1:9/sse",+ client_type="sse",+ )+ client = SseClient(config)+ client._session = _FakeSession() # noqa: SLF001 - test seam+ return client+++class TestStampedTimeoutPropagation:+ @pytest.mark.asyncio+ async def test_stamped_timeout_reaches_inner_ceiling_with_margin(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ apply_mcp_call_timeout_patch()+ client = _make_sse_client()+ setattr(client, "_jws_call_timeout", 90.0)++ captured: dict[str, float] = {}+ real_wait_for = asyncio.wait_for++ async def spy_wait_for(coro, timeout=None): # type: ignore[no-untyped-def]+ captured["timeout"] = float(timeout) # type: ignore[arg-type]+ return await real_wait_for(coro, timeout=timeout)++ monkeypatch.setattr(asyncio, "wait_for", spy_wait_for)++ result = await client.call_tool("delay_remote", {"seconds": 0})++ assert result is None+ assert client._session.calls == [("delay_remote", {"seconds": 0})] # type: ignore[attr-defined]+ # The stamped 90s must propagate past SseClient's 60s default ceiling,+ # with the +5s backstop margin so the pooled worker's outer deadline+ # (exactly timeout_s) always fires first.+ assert captured["timeout"] == pytest.approx(95.0)++ @pytest.mark.asyncio+ async def test_unstamped_client_falls_back_to_default_plus_margin(+ self, monkeypatch: pytest.MonkeyPatch+ ) -> None:+ apply_mcp_call_timeout_patch()+ client = _make_sse_client()+ assert not hasattr(client, "_jws_call_timeout")++ captured: dict[str, float] = {}+ real_wait_for = asyncio.wait_for++ async def spy_wait_for(coro, timeout=None): # type: ignore[no-untyped-def]+ captured["timeout"] = float(timeout) # type: ignore[arg-type]+ return await real_wait_for(coro, timeout=timeout)++ monkeypatch.setattr(asyncio, "wait_for", spy_wait_for)++ await client.call_tool("delay_remote", {"seconds": 0})++ assert captured["timeout"] == pytest.approx(DEFAULT_CALL_TIMEOUT + 5.0)