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: fix mcp http issue
huanggawa4c74014e94d3
diff --git a/jiuwenswarm/common/mcp_call_timeout_patch.py b/jiuwenswarm/common/mcp_call_timeout_patch.pynew file mode 100644index 0000000000..2ab4a51d55--- /dev/null+++ b/jiuwenswarm/common/mcp_call_timeout_patch.py@@ -0,0 +1,159 @@+# coding: utf-8+"""Inject a per-call timeout into openjiuwen's MCP HTTP clients.++Why this exists: ``MCPTool.invoke`` calls ``call_tool`` without a ``timeout``,+and the stock ``StreamableHttpClient.call_tool`` / ``list_tools`` await+``self._session.call_tool(...)`` / ``self._session.list_tools()`` with no+``asyncio.wait_for`` around them. When a remote streamable-http MCP server+process is killed mid-session, the underlying SSE read is governed by the MCP+SDK's ``sse_read_timeout`` (default 300s), so the call hangs for minutes —+neither failing nor timing out, which surfaces as an forever-spinning TUI+spinner and the agent repeatedly retrying the tool.++This patch is applied once at process startup (from+``JiuWenSwarmDeepAdapter.__init__``):++ A. Wrap ``call_tool`` / ``list_tools`` on the HTTP transports with+ ``anyio.fail_after``. On timeout we ``disconnect()`` so the dead session+ is torn down and the very next call fails fast (the stock client raises+ "Not connected" once ``self._session`` is None) instead of waiting out+ the 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.+ B. Monkeypatch ``ToolMgr._create_client`` so ``config.params["timeout_s"]``+ (i.e. ``/mcp add ... --timeout_s N``) is stamped onto the client instance+ as ``_jws_call_timeout`` and honored by (A). Falls back to+ ``DEFAULT_CALL_TIMEOUT`` when unset.++Both transforms are idempotent: a module-level ``_PATCHED`` guard makes the+whole function a no-op on repeat calls.+"""+from __future__ import annotations++from typing import Any+import anyio++from openjiuwen.core.common.logging import logger++_PATCHED = False+# (cls, name) pairs already wrapped — idempotency guard independent of+# _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()+#: 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 apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT) -> None:+ """Apply the per-call MCP timeout patch. Idempotent per process."""+ global _PATCHED+ if _PATCHED:+ return+ _PATCHED = True++ from openjiuwen.core.foundation.tool.mcp.client.streamable_http_client import (+ StreamableHttpClient,+ )+ from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClient+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ def _resolve_timeout(client: Any, explicit: Any) -> float:+ # Explicit kwarg wins (currently never passed by invoke, but keeps the+ # signature honest); then the per-instance value stamped by (B); then+ # the module default.+ if isinstance(explicit, (int, float)) and explicit > 0:+ return float(explicit)+ stamped = getattr(client, "_jws_call_timeout", None)+ if isinstance(stamped, (int, float)) and stamped > 0:+ return float(stamped)+ return default_timeout++ def _wrap_with_timeout(cls: type, name: str) -> None:+ if (cls, name) in _wrapped_methods:+ return+ _wrapped_methods.add((cls, name))+ orig = getattr(cls, name)++ async def wrapped(self, *args, **kwargs):+ timeout = _resolve_timeout(self, kwargs.get("timeout"))+ 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):+ return await orig(self, *args, **kwargs)+ except TimeoutError:+ logger.warning(+ "[mcp-timeout] %s.%s timed out after %.1fs, disconnecting client: %s",+ cls.__name__,+ name,+ timeout,+ getattr(self, "_server_path", "?"),+ )+ # Tear down the dead session so the next call fails fast rather+ # than burning another full timeout window on a half-open conn.+ try:+ await self.disconnect()+ except Exception as exc:+ logger.warning(+ "[mcp-timeout] %s.%s disconnect after timeout also failed: %r",+ cls.__name__,+ name,+ exc,+ )+ raise++ setattr(cls, name, wrapped)++ # (A) HTTP long-poll transports — same failure mode when the server dies.+ for cls in (StreamableHttpClient, SseClient):+ _wrap_with_timeout(cls, "call_tool")+ _wrap_with_timeout(cls, "list_tools")++ # (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+ # stamp for streamable-http; the common case (no browser tool) is unaffected.+ _orig_create_client = getattr(ToolMgr, "_create_client")++ def _create_client_with_timeout(config):+ client = _orig_create_client(config)+ timeout_s = (getattr(config, "params", None) or {}).get("timeout_s")+ if isinstance(timeout_s, (int, float)) and timeout_s > 0:+ try:+ # setattr (not attribute assignment): McpClient has no+ # _jws_call_timeout field, so direct assignment is an mypy+ # [attr-defined] error. setattr keeps it dynamic & lint-clean.+ setattr(client, "_jws_call_timeout", float(timeout_s))+ except Exception as exc:+ # Don't silently drop the user's --timeout_s. If this client+ # can't hold the attribute (e.g. __slots__ without the field,+ # or a proxy object), surface it so ops notices the silent+ # fallback to DEFAULT_CALL_TIMEOUT instead of debugging blind.+ logger.warning(+ "[mcp-timeout] failed to apply timeout_s=%.1fs to MCP client "+ "%s: %r — falling back to default timeout",+ float(timeout_s),+ getattr(config, "server_name", "?"),+ exc,+ )+ return client++ # setattr (not direct assignment): rebinding a staticmethod on the class is+ # an mypy [assignment] error; setattr keeps the monkeypatch lint-clean+ # (no type: ignore needed).+ setattr(ToolMgr, "_create_client", staticmethod(_create_client_with_timeout))++ logger.info(+ "[mcp-timeout] patch applied (default_timeout=%.1fs, covered=StreamableHttpClient,SseClient)",+ default_timeout,+ )diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.pyindex 79321ef847..b9789dba23 100644--- a/jiuwenswarm/common/mcp_config.py+++ b/jiuwenswarm/common/mcp_config.py@@ -4,13 +4,18 @@from __future__ import annotations+import asyncioimport hashlibimport jsonimport refrom typing import Any+from urllib.parse import urlparse+from openjiuwen.core.common.logging import loggerfrom openjiuwen.core.foundation.tool import McpServerConfig+_HTTP_MCP_TRANSPORTS = frozenset({"sse", "http", "streamable-http", "streamable_http"})+def extract_enabled_mcp_server_entries(config_base: dict[str, Any]) -> list[dict[str, Any]]:"""Return enabled ``mcp.servers`` entries from a resolved config mapping."""@@ -114,6 +119,55 @@ def build_enabled_mcp_server_configs(return configs+async def preflight_mcp_server_reachable(+ cfg: McpServerConfig, *, timeout: float = 3.0+) -> tuple[bool, str]:+ """Cheap reachability probe for HTTP-based MCP servers.++ Why this exists: when an HTTP MCP server is unreachable, openjiuwen still+ enters the mcp ``streamablehttp_client`` async context (which spins up an+ anyio task group with background request tasks) before failing on+ ``session.initialize()``. Tearing that context back down leaks orphaned+ background tasks and raises noisy ``aclose(): asynchronous generator is+ already running`` / ``Attempted to exit cancel scope in a different task``+ errors. Probing the host:port first lets us skip registration cleanly.++ Returns ``(reachable, reason)``. Non-HTTP transports (stdio/playwright/…)+ report reachable — they are spawned locally and have no cheap probe.+ """+ transport = (getattr(cfg, "client_type", "") or "").strip().lower()+ if transport not in _HTTP_MCP_TRANSPORTS:+ return True, ""++ url = (getattr(cfg, "server_path", "") or "").strip()+ parsed = urlparse(url)+ host = parsed.hostname+ if not host:+ return False, f"invalid url: {url!r}"+ port = parsed.port or (443 if parsed.scheme == "https" else 80)++ try:+ _, writer = await asyncio.wait_for(+ asyncio.open_connection(host, port), timeout=timeout+ )+ except asyncio.TimeoutError:+ return False, f"tcp connect to {host}:{port} timed out after {timeout}s"+ except Exception as exc:+ # Connection refused / DNS failure / etc. — also defensive: the probe+ # itself must never break startup with an unexpected exception type.+ return False, f"tcp connect to {host}:{port} failed: {type(exc).__name__}: {exc}"++ writer.close()+ try:+ await writer.wait_closed()+ except Exception as exc:+ logger.debug(+ "[mcp-preflight] reachability probe socket close failed for %s:%s: %r",+ host, port, exc,+ )+ return True, ""++def _stable_mcp_server_id(scope: str, name: str, payload: dict[str, Any]) -> str:stable_payload = {key: value@@ -141,4 +195,5 @@ __all__ = ["build_enabled_mcp_server_configs","build_mcp_server_config","extract_enabled_mcp_server_entries",+ "preflight_mcp_server_reachable",]diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 9c953ba738..55bf1a1141 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -251,7 +251,9 @@ from jiuwenswarm.common.config import (from jiuwenswarm.common.mcp_config import (build_mcp_server_config,extract_enabled_mcp_server_entries,+ preflight_mcp_server_reachable,)+from jiuwenswarm.common.mcp_call_timeout_patch import apply_mcp_call_timeout_patchfrom jiuwenswarm.common.reasoning_injector import build_reasoning_model_request_kwargsfrom jiuwenswarm.server.runtime.agent_adapter.sysop_builder import (build_filesystem_policy,@@ -564,6 +566,12 @@ class JiuWenSwarmDeepAdapter:"""def __init__(self) -> None:+ # Apply the MCP per-call timeout patch once per process: wraps+ # StreamableHttpClient/SseClient.call_tool & list_tools in+ # asyncio.wait_for and honors config ``timeout_s`` (--timeout_s), so a+ # killed remote MCP server fails fast instead of hanging on the MCP+ # SDK's 300s SSE read timeout. Idempotent (module-level _PATCHED guard).+ apply_mcp_call_timeout_patch()self._instance: DeepAgent | None = Noneself._project_dir: str | None = Noneself._workspace_dir: str = str(get_agent_workspace_dir())@@ -1477,6 +1485,19 @@ class JiuWenSwarmDeepAdapter:async def _register_mcp_server(self, cfg: McpServerConfig, *, tag: str) -> bool:if self._instance is None:return False+ # Pre-flight reachability check for HTTP-based MCP servers. If the host+ # is down we skip registration here instead of entering the mcp+ # streamable-http context — otherwise openjiuwen leaks orphaned anyio+ # background tasks on the failed initialize() and logs noisy+ # ``aclose()``/cancel-scope RuntimeErrors.+ reachable, reason = await preflight_mcp_server_reachable(cfg)+ if not reachable:+ logger.warning(+ "[JiuWenSwarmDeepAdapter] MCP server unreachable, skipping registration: "+ "name=%s transport=%s path=%s reason=%s",+ cfg.server_name, cfg.client_type, cfg.server_path, reason,+ )+ return Falsetry:result = await Runner.resource_mgr.add_mcp_server(cfg, tag=tag)ok = True