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
revert(mcp): 回退 !6630 有问题的 MCP 合入
zhangxiangyu52a7fc5214a557
diff --git a/docs/en/SlashCommands.md b/docs/en/SlashCommands.mdindex 40184d2402..559f9d9cc5 100644--- a/docs/en/SlashCommands.md+++ b/docs/en/SlashCommands.md@@ -285,17 +285,19 @@ Working tree changes are obtained via `git diff HEAD` (tracked files only). The- Usage:- `/mcp list`: List all MCP servers (name, transport, enabled status);- `/mcp show [name]`: Show MCP config; without `name` shows enabled items, with `name` shows one server detail;- - `/mcp add --name <name> --transport <sse|http> ...`: Add a remote MCP server;+ - `/mcp add --name <name> --transport <stdio|sse> ...`: Add a new MCP server;- `/mcp update --name <name> ...`: Update MCP server config (transport / params / enabled status);- `/mcp enable <name>`: Enable a specific MCP server;- `/mcp disable <name>`: Disable a specific MCP server;- `/mcp remove <name>`: Remove a specific MCP server.-- Transport parameters (remote only):- - `sse` / `http` (alias of `streamable-http`): requires `--url`; optional `--headers`, `--timeout_s`.+- Transport parameters:+ - `stdio`: requires `--command`; optional `--args`, `--cwd`, `--env`;+ - `sse`: requires `--url`; optional `--headers`, `--timeout_s`.- Examples:- `/mcp list`- `/mcp show`- `/mcp show playwright`+ - `/mcp add --name playwright --transport stdio --command python --args "server.py --transport stdio"`- `/mcp update --name playwright --transport sse --url http://127.0.0.1:9000/sse --headers "Authorization=Bearer xxx"`- `/mcp add --name local-sse --transport sse --url http://127.0.0.1:9000/sse`- `/mcp disable playwright`diff --git "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md" "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"index 67d726a6ec..26de864ad1 100644--- "a/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"+++ "b/docs/zh/Slash\345\221\275\344\273\244\350\241\250.md"@@ -288,17 +288,19 @@- 用法:- `/mcp list`:列出全部 MCP 服务(名称、transport、启用状态);- `/mcp show [name]`:查看 MCP 配置;不带参数时展示当前启用项,带 `name` 时展示单个服务详情;- - `/mcp add --name <name> --transport <sse|http> ...`:新增远程 MCP 服务;+ - `/mcp add --name <name> --transport <stdio|sse> ...`:新增 MCP 服务;- `/mcp update --name <name> ...`:更新指定 MCP 服务配置(支持更新 transport / 参数 / 启用状态);- `/mcp enable <name>`:启用指定 MCP 服务;- `/mcp disable <name>`:禁用指定 MCP 服务;- `/mcp remove <name>`:删除指定 MCP 服务。-- 传输参数(仅远程):- - `sse` / `http`(`streamable-http` 别名):需提供 `--url`,可选 `--headers`、`--timeout_s`。+- 传输参数:+ - `stdio`:需提供 `--command`,可选 `--args`、`--cwd`、`--env`;+ - `sse`:需提供 `--url`,可选 `--headers`、`--timeout_s`。- 示例:- `/mcp list`- `/mcp show`- `/mcp show playwright`+ - `/mcp add --name playwright --transport stdio --command python --args "server.py --transport stdio"`- `/mcp update --name playwright --transport sse --url http://127.0.0.1:9000/sse --headers "Authorization=Bearer xxx"`- `/mcp add --name local-sse --transport sse --url http://127.0.0.1:9000/sse`- `/mcp disable playwright`diff --git "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md" "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"index fb40a2d076..9dfe818c12 100644--- "a/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"+++ "b/docs/zh/TUI\344\275\277\347\224\250\346\214\207\345\215\227.md"@@ -339,7 +339,8 @@ jiuwenswarm-tui --session "$(printf 'a%.0s' {1..200})" # 超 128 → 长度超#### `/mcp`- 子命令:`list`、`show`、`add`、`update`、`enable`、`disable`、`remove`(`delete` 同 `remove`)。-- 仅支持远程传输:`sse` / `http`(`streamable-http`),需 `--url`,可选 `--headers`、`--timeout_s`。+- `stdio`:需 `--command`,可选 `--args`、`--cwd`、`--env`。+- `sse`:需 `--url`,可选 `--headers`、`--timeout_s`。- 详见 [Slash命令表.md](Slash命令表.md) 与 `mcp.ts`。#### `/skills` 与 `/teamskills`diff --git a/jiuwenswarm/agents/harness/common/tools/browser_tools.py b/jiuwenswarm/agents/harness/common/tools/browser_tools.pyindex 809e4e287d..e78bea0b43 100644--- a/jiuwenswarm/agents/harness/common/tools/browser_tools.py+++ b/jiuwenswarm/agents/harness/common/tools/browser_tools.py@@ -450,32 +450,6 @@ def _normalize_client_type(client_type: str) -> str:return value-def _is_browser_runtime_mcp_config(config: McpServerConfig) -> bool:- """仅识别浏览器自己的 MCP,避免劫持企业远程 MCP 客户端。"""- configured_id = (- _browser_env("BROWSER_RUNTIME_MCP_SERVER_ID", "") or _BROWSER_MCP_DEFAULT_ID- ).strip()- configured_name = (- _browser_env("BROWSER_RUNTIME_MCP_SERVER_NAME", "") or _BROWSER_MCP_DEFAULT_NAME- ).strip()- server_id = str(getattr(config, "server_id", "") or "").strip()- server_name = str(getattr(config, "server_name", "") or "").strip()- server_path = str(getattr(config, "server_path", "") or "").strip().lower()- if server_name and server_name in {configured_name, _BROWSER_MCP_DEFAULT_NAME}:- return True- if server_id and server_id in {- configured_id,- _BROWSER_MCP_DEFAULT_ID,- f"{configured_id}_sse",- f"{_BROWSER_MCP_DEFAULT_ID}_sse",- }:- return True- return (- "playwright-runtime-wrapper" in server_path- or "playwright_runtime" in server_path- )--def _ensure_browser_move_client_patch() -> None:global _BROWSER_MOVE_CLIENT_PATCHEDif _BROWSER_MOVE_CLIENT_PATCHED:@@ -529,19 +503,10 @@ def _ensure_browser_move_client_patch() -> None:original_create_client = tool_mgr.ToolMgr._create_clientdef _patched_create_client(config: McpServerConfig):- # 非浏览器 MCP 必须走原 _create_client(含 timeout_s 盖章与 SDK 客户端),- # 否则企业模板的超时恢复 / auth_headers 会整段失效。- if not _is_browser_runtime_mcp_config(config):- return original_create_client(config)normalized = _normalize_client_type(getattr(config, "client_type", ""))if normalized == "sse":if sse_cls is not None:- return sse_cls(- config.server_path,- config.server_name,- config.auth_headers,- config.auth_query_params,- )+ return sse_cls(config.server_path, config.server_name, config.auth_headers, config.auth_query_params)return original_create_client(config)if normalized == "streamable-http":return streamable_http_cls(@@ -554,8 +519,10 @@ def _ensure_browser_move_client_patch() -> None:return stdio_cls(config.server_path, config.server_name, config.params)return original_create_client(config)- # 不再全局替换 ToolMgr.StreamableHttpClient / SseClient / StdioClient:- # registry 与超时补丁依赖 SDK 原类;只按 server 分流 _create_client。+ tool_mgr.StdioClient = stdio_cls+ if sse_cls is not None:+ tool_mgr.SseClient = sse_cls+ tool_mgr.StreamableHttpClient = streamable_http_clstool_mgr.ToolMgr._create_client = staticmethod(_patched_create_client)_BROWSER_MOVE_CLIENT_PATCHED = Truediff --git a/jiuwenswarm/agents/harness/common/tools/mcp_toolkits.py b/jiuwenswarm/agents/harness/common/tools/mcp_toolkits.pyindex 4fb53a48fb..c3712ed709 100644--- a/jiuwenswarm/agents/harness/common/tools/mcp_toolkits.py+++ b/jiuwenswarm/agents/harness/common/tools/mcp_toolkits.py@@ -10,11 +10,16 @@ from jiuwenswarm.agents.harness.common.tools.command_tools import mcp_exec_commafrom jiuwenswarm.agents.harness.common.tools.web_fetch_tools import mcp_fetch_webpagefrom jiuwenswarm.agents.harness.common.tools.web_search import web_searchfrom jiuwenswarm.common.mcp_config import ( # noqa: F401+ _check_dangerous_args,_is_blocked_host,_loopback_mcp_allowed,_normalize_mcp_client_type,+ _normalize_stdio_command_kind,_optional_auth_dict,+ _path_is_under_trusted_root,_pick_mcp_url,+ _trusted_cat_cafe_stdio_roots,+ _validate_cat_cafe_request_scoped_stdio,_validate_request_scoped_remote_mcp,create_mcp_tool,)@@ -31,10 +36,15 @@ __all__ = ["mcp_exec_command","get_mcp_tools","create_mcp_tool",+ "_check_dangerous_args","_is_blocked_host","_loopback_mcp_allowed","_normalize_mcp_client_type",+ "_normalize_stdio_command_kind","_optional_auth_dict",+ "_path_is_under_trusted_root","_pick_mcp_url",+ "_trusted_cat_cafe_stdio_roots",+ "_validate_cat_cafe_request_scoped_stdio","_validate_request_scoped_remote_mcp",]diff --git a/jiuwenswarm/common/mcp_call_timeout_patch.py b/jiuwenswarm/common/mcp_call_timeout_patch.pyindex 961f35bc54..4f4dbcae05 100644--- a/jiuwenswarm/common/mcp_call_timeout_patch.py+++ b/jiuwenswarm/common/mcp_call_timeout_patch.py@@ -1,59 +1,35 @@# coding: utf-8-"""Inject a per-call timeout + dead-session recovery into openjiuwen MCP HTTP clients.+"""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-deadline. When a remote tool is slow or the server dies mid-session, the call-hangs on the MCP SDK's ``sse_read_timeout`` (default 300s).--Additionally, ToolMgr keeps one long-lived MCP client per server for the whole-AgentServer process. Chat sessions A/B share that client. So after a tool-timeout in chat A, a brand-new chat B still uses the same half-dead client and-fails with empty ``execute invoke failed, error=''`` (field sds-037840350c2c)-until we invalidate + reconnect. When the remote Streamable HTTP service-restarts, the protocol session id is stale and calls fail with-``Session terminated`` / HTTP 404 — again including brand-new chat sessions —-until AS rebuilds the MCP connection.--SSE / Streamable HTTP timeout teardown often raises ``asyncio.CancelledError``-(cancel-scope cross-task noise) *after* the real timeout. ``CancelledError`` is-not an ``Exception`` subclass, so ``MCPTool.invoke`` cannot turn it into a tool-error — the agent loop treats it as “user cancel”, skips ``chat.tool_result``,-and replies “工具调用被用户取消”. This patch converts non-outer-``CancelledError`` into ``TimeoutError`` / transport ``RuntimeError``.+``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- ``asyncio.wait_for``. On timeout we tear down the dead session and- **force-invalidate** local state even if ``disconnect()`` raises- (e.g. ``Attempted to exit cancel scope in a different task`` or- ``CancelledError``). The next call auto-reconnects on a fresh- ``AsyncExitStack`` so the same chat session can keep using other tools- (TC_MCP_CALL_014).-- On retryable dead-session errors (``Session terminated``, connection- closed, cancel-scope teardown noise, …) we invalidate, reconnect once,- and retry the same call so both the original chat and a newly created- chat recover after MCP service restart (without requiring AS restart).-- 同 MCP client 的调用经 ``_client_io_lock`` **串行**是刻意取舍(多会话- 共享进程级客户端时避免并发踩坏半死连接);重试语义是- **at-least-once**(超时/死会话后可能已在对端执行过一次)。-- NB: remote(sse / streamable-http)**必须**用 ``asyncio.wait_for``,- **不能**用 ``anyio.fail_after``。transport 自带后台 task + anyio- cancel scope;外层再套 ``fail_after`` 会在跨 task 退出时抛- ``Attempted to exit a cancel scope...``。现场表现:超时后重连成功、- MCP 侧 ``call completed``,但第 3 轮结果仍被该异常盖成失败- (TC_MCP_CALL_014)。与 ``mcp_config._run_mcp_worker`` 对 remote- 的超时策略一致。-- 同时把解析后的超时以 ``timeout + 5`` 写入 client 方法的 ``timeout``- kwarg(内层天花板),外层 ``wait_for`` 仍用精确超时,避免 SseClient- 默认 60s 提前掐断,并保证 pooled worker 的外层截止先触发。+ ``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.+ 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@@ -64,22 +40,15 @@ This patch is applied once at process startup (from``sse_read_timeout`` of at least that value, instead of the SDK's 300sdefault — long tool calls (SSE result stream / held streamable-httpresponse) would otherwise be dropped mid-call after 300 idle seconds.- D. AbilityManager 外层 ``anyio.fail_after`` → 无 cancel scope 的截止时间- + ``tool.invoke`` 用 ``asyncio.wait_for``(不改 agent-core 源码,等价于- 把 AM 超时从 fail_after 换成 wait_for,修复 TC_MCP_CALL_014 第 3 轮)。- E. ``disconnect`` / ``_do_disconnect`` 在 finally 中强制清会话,避免 aclose- 失败留下半死连接。Both transforms are idempotent: a module-level ``_PATCHED`` guard makes thewhole function a no-op on repeat calls."""from __future__ import annotations-import asyncio-import contextlibimport contextvars-from contextlib import AsyncExitStack-from typing import Any, Optional+from typing import Any+import anyiofrom openjiuwen.core.common.logging import logger@@ -101,342 +70,7 @@ _pending_sdk_read_timeout: contextvars.ContextVar[float | None] = contextvars.Co#: Fallback per-call timeout (seconds) when ``--timeout_s`` is not supplied.DEFAULT_CALL_TIMEOUT = 30.0-# AbilityManager 外层曾用 anyio.fail_after 包 tool.invoke;MCP 重连若落在该-# cancel scope 内,退出时会抛 cancel scope(TC_MCP_CALL_014 第 3 轮)。-# 补丁把 fail_after 换成「无 cancel scope + contextvar 截止时间」,再由-# tool.invoke 包装层用 asyncio.wait_for 真正限时——效果等同改 agent-core。-_am_call_timeout: contextvars.ContextVar[Optional[float]] = contextvars.ContextVar(- "jws_ability_manager_call_timeout", default=None-)--# MCP 对端重启 / 半死连接时 SDK 常见报错(对齐 browser-move 补丁口径)。-_RETRYABLE_DEAD_SESSION_MARKERS: tuple[str, ...] = (- "session terminated",- "closedresourceerror",- "brokenresourceerror",- "endofstream",- "stream closed",- "connection closed",- "remoteprotocolerror",- "readerror",- "writeerror",- "not connected",- "broken pipe",- "server error 404",- "404 not found",- # anyio cancel-scope 跨 task 清理噪声(超时/断连后偶发,应重连而非当业务失败)- "cancel scope",- "attempted to exit a cancel scope",-)--__all__ = [- "DEFAULT_CALL_TIMEOUT",- "apply_mcp_call_timeout_patch",- "force_invalidate_mcp_client",- "is_retryable_mcp_dead_session_error",-]---def _fire_and_forget_aclose_exit_stack(stack: Any) -> None:- """后台 best-effort ``aclose`` 旧 AsyncExitStack,避免泄漏;不阻塞调用方。"""- if not isinstance(stack, AsyncExitStack):- return-- async def _aclose() -> None:- try:- await stack.aclose()- except BaseException as exc:- # 含 CancelledError:后台清理失败不得污染当前调用方- logger.debug(- "[mcp-timeout] background aclose of old AsyncExitStack failed: %r",- exc,- )-- try:- loop = asyncio.get_running_loop()- except RuntimeError:- logger.debug(- "[mcp-timeout] no running loop; skip background aclose of old AsyncExitStack"- )- return-- task = loop.create_task(_aclose())-- def _drain_task_result(done: asyncio.Task) -> None:- try:- done.result()- except BaseException:- pass-- task.add_done_callback(_drain_task_result)---def force_invalidate_mcp_client(client: Any) -> None:- """丢弃半死会话状态,换上新的 AsyncExitStack,供后续 ``connect()`` 重连。-- SDK ``StreamableHttpClient.disconnect`` 在 aclose 失败时往往不清 ``_session``,- 且成功 aclose 后旧 stack 也不能再 enter。超时 / Session terminated 路径必须- 无条件调用本函数。-- 替换 ``_exit_stack`` 前会取出旧 stack,用 running loop 的- ``create_task`` fire-and-forget 去 ``aclose()``(后台 best-effort;异常仅- debug 记录。无 running loop 时 debug 后放弃 aclose)。本函数保持同步,- 不改成 async。-- 同时打上 ``_jws_needs_reconnect``:即便残留对象仍像「已连接」,下次调用也强制- 重连。聊天会话 A/B 共用同一客户端,否则新建会话也会继承半死连接。- """- for attr in ("_session", "_client", "_read", "_write"):- if hasattr(client, attr):- setattr(client, attr, None)- if hasattr(client, "_is_disconnected"):- setattr(client, "_is_disconnected", True)- old_stack = None- if hasattr(client, "_exit_stack"):- old_stack = getattr(client, "_exit_stack", None)- setattr(client, "_exit_stack", AsyncExitStack())- if hasattr(client, "_auth_provider"):- setattr(client, "_auth_provider", None)- try:- setattr(client, "_jws_needs_reconnect", True)- except Exception as exc:- # __slots__/代理对象可能拒绝动态属性;标记失败不阻断作废流程- logger.debug(- "[mcp-timeout] failed to set _jws_needs_reconnect on %s: %r",- type(client).__name__,- exc,- )- if old_stack is not None:- _fire_and_forget_aclose_exit_stack(old_stack)---def is_retryable_mcp_dead_session_error(error: BaseException) -> bool:- """对端重启或传输层半死后,值得作废本地会话并重连重试一次的错误。"""- name = error.__class__.__name__.lower()- text = str(error).lower().strip()- # 现场半死 streamable-http 常抛空消息;仅对传输类空异常重试,避开业务 ValueError。- if not text and name in (- "exception",- "runtimeerror",- "oserror",- "connectionerror",- "mcperror",- "error",- ):- return True- return any(marker in name or marker in text for marker in _RETRYABLE_DEAD_SESSION_MARKERS)---def _is_outer_cancellation() -> bool:- """True only for real interrupt / WS-drop cancels (not transport noise).-- 不 import ``mcp_config``:该模块副作用重,超时热路径只需要 ``Task.cancelling()``。- """- current = asyncio.current_task()- return bool(current is not None and current.cancelling())---def _client_io_lock(client: Any) -> asyncio.Lock:- """进程级共享 MCP client 的重连/调用串行锁。-- 串行是刻意取舍:多聊天会话共用同一客户端时,避免并发重连/调用踩坏半死连接。- 超时与死会话路径的重试是 at-least-once(对端可能已执行过一次)。- """- lock = getattr(client, "_jws_io_lock", None)- if isinstance(lock, asyncio.Lock):- return lock- lock = asyncio.Lock()- try:- setattr(client, "_jws_io_lock", lock)- except Exception as exc:- # 挂不上锁时仍返回本次新建的 lock,仅本调用串行;下次再试 setattr- logger.debug(- "[mcp-timeout] failed to attach _jws_io_lock on %s: %r",- type(client).__name__,- exc,- )- return lock---async def _abandon_session(client: Any, *, context: str) -> None:- """超时后直接作废本地会话,不在当前 task 上调用 disconnect()/aclose。-- wait_for 超时在子 task 取消调用;原 AsyncExitStack 里的 anyio cancel scope- 若在父 task 上 aclose,会抛 cancel scope 并污染当前 task 的 scope 栈,- 导致下一轮重连后的成功结果在 AbilityManager 外层退出时仍被盖掉- (TC_MCP_CALL_014 第 3 轮)。-- ``force_invalidate_mcp_client`` 会把旧 stack 丢到后台 task best-effort- ``aclose()``,本协程本身不 await 清理。- """- force_invalidate_mcp_client(client)- logger.warning(- "[mcp-timeout] abandoned MCP session without aclose (%s): %s",- context,- getattr(client, "_server_path", "?"),- )---def _wrap_disconnect_always_invalidate(cls: type, method_name: str) -> None:- """disconnect / _do_disconnect:aclose 失败也清掉半死会话(对齐 agent-core 修复)。"""- if (cls, method_name) in _wrapped_methods:- return- if not hasattr(cls, method_name):- return- _wrapped_methods.add((cls, method_name))- orig = getattr(cls, method_name)-- async def wrapped(self, *args, **kwargs):- try:- return await orig(self, *args, **kwargs)- finally:- force_invalidate_mcp_client(self)-- setattr(cls, method_name, wrapped)---def _wrap_invoke_with_am_timeout(cls: type, method_name: str = "invoke") -> None:- """AbilityManager 路径下用 wait_for 限时,避免外层 fail_after 的 cancel scope。-- 用 ``_jws_orig_<method>`` 记住原始方法;测试反复 ``_PATCHED=False; clear;- apply`` 时先还原再包一层,避免多层 ``wait_for`` 嵌套。-- 必须只看 ``cls.__dict__``:``hasattr``/``getattr`` 会沿 MRO 找到父类已- stash 的 ``_jws_orig_invoke``,把子类自己的 ``invoke`` 覆盖成父类空实现- (返回 None)——CI 里 LocalFunction / RequestScoped 全系挂掉的根因。- """- if method_name not in cls.__dict__:- return- orig_attr = f"_jws_orig_{method_name}"- # 再次包装前先还原,避免嵌套(仅本类自己 stash 的才算)- existing_orig = cls.__dict__.get(orig_attr)- if existing_orig is not None:- orig = existing_orig- else:- orig = cls.__dict__[method_name]- try:- setattr(cls, orig_attr, orig)- except Exception as exc:- logger.debug(- "[mcp-timeout] failed to stash %s on %s: %r",- orig_attr,- cls.__name__,- exc,- )-- _wrapped_methods.add((cls, f"am_timeout:{method_name}"))-- async def wrapped(self, *args, **kwargs):- timeout = _am_call_timeout.get()- if timeout is None:- return await orig(self, *args, **kwargs)- return await asyncio.wait_for(orig(self, *args, **kwargs), timeout=timeout)-- setattr(cls, method_name, wrapped)---def _install_tool_init_subclass_am_timeout_hook(tool_cls: type) -> None:- """Tool 子类若在自身 ``__dict__`` 定义了 ``invoke``,自动套 AM wait_for 包装。"""- if getattr(tool_cls, "_jws_am_timeout_init_subclass_hooked", False):- return- prev = tool_cls.__dict__.get("__init_subclass__")-- def __init_subclass__(cls, **kwargs): # noqa: N807 — 匹配 Python 钩子名- if prev is not None:- prev(cls, **kwargs)- else:- super(tool_cls, cls).__init_subclass__(**kwargs)- if "invoke" in cls.__dict__:- _wrap_invoke_with_am_timeout(cls)-- try:- tool_cls.__init_subclass__ = __init_subclass__ # type: ignore[method-assign]- setattr(tool_cls, "_jws_am_timeout_init_subclass_hooked", True)- except Exception as exc:- logger.warning(- "[mcp-timeout] Tool.__init_subclass__ AM timeout hook skipped: %r",- exc,- )---def _patch_ability_manager_fail_after() -> None:- """只替换 AbilityManager 模块命名空间里的 ``anyio``,不改全局 ``anyio.fail_after``。-- 注意:``am_mod.anyio.fail_after = ...`` 会改到共享的 anyio 模块属性,- ProgressiveToolRail 等其它 ``import anyio`` 也会中招(丢 cancel_called)。- 正确做法:把 ``am_mod.anyio`` 换成代理对象,仅 AbilityManager 内- ``anyio.fail_after`` 走无 cancel-scope 桥接。- """- import anyio as real_anyio- import openjiuwen.core.single_agent.ability_manager as am_mod-- @contextlib.contextmanager- def _fail_after_without_cancel_scope(delay, *args, **kwargs):- del args, kwargs- # anyio.fail_after(None) 原语义:不设截止- if delay is None:- yield- return- try:- timeout = float(delay)- except (TypeError, ValueError):- yield- return- if timeout <= 0:- yield- return- token = _am_call_timeout.set(timeout)- try:- yield- finally:- _am_call_timeout.reset(token)-- class _AbilityManagerAnyioProxy:- """AbilityManager 专用 anyio 视图:fail_after 桥接,其余原样转发。"""-- @staticmethod- def fail_after(*args, **kwargs):- return _fail_after_without_cancel_scope(*args, **kwargs)-- @staticmethod- def __getattr__(name: str) -> Any:- return getattr(real_anyio, name)-- # 只改 ability_manager.anyio 绑定,绝不写 real_anyio.fail_after- am_mod.anyio = _AbilityManagerAnyioProxy() # type: ignore[assignment]-- # invoke 包装:在 AM 截止时间内用 wait_for(覆盖 MCP / 普通 Tool / 请求级工具)- from openjiuwen.core.foundation.tool.base import Tool- from openjiuwen.core.foundation.tool.mcp.base import MCPTool-- _wrap_invoke_with_am_timeout(Tool)- _wrap_invoke_with_am_timeout(MCPTool)- try:- from openjiuwen.core.foundation.tool.function.function import LocalFunction-- _wrap_invoke_with_am_timeout(LocalFunction)- except Exception as exc: # noqa: BLE001 — 可选依赖,缺了就跳过- logger.warning("[mcp-timeout] LocalFunction invoke wrap skipped: %r", exc)- try:- from openjiuwen.core.foundation.tool.service_api.restful_api import RestfulApi-- _wrap_invoke_with_am_timeout(RestfulApi)- except Exception as exc: # noqa: BLE001- logger.warning("[mcp-timeout] RestfulApi invoke wrap skipped: %r", exc)- try:- from jiuwenswarm.common.mcp_config import RequestScopedOfficeClawMcpTool-- _wrap_invoke_with_am_timeout(RequestScopedOfficeClawMcpTool)- except Exception as exc: # noqa: BLE001- logger.warning("[mcp-timeout] RequestScoped invoke wrap skipped: %r", exc)-- # 后续新 Tool 子类若自带 invoke,自动包装,避免再漏- _install_tool_init_subclass_am_timeout_hook(Tool)-- logger.info(- "[mcp-timeout] AbilityManager fail_after → wait_for bridge applied "- "(module-local anyio proxy; global anyio untouched)"- )+__all__ = ["apply_mcp_call_timeout_patch", "DEFAULT_CALL_TIMEOUT"]def _stamp_is_valid(value: Any) -> bool:@@ -490,27 +124,12 @@ def _patch_sdk_read_timeouts() -> None:setattr(module, factory_name, factory_with_read_timeout)- connect_targets: list[tuple[type, str]] = [+ for cls, method_name in (+ (SseClient, "_do_connect"),(StreamableHttpClient, "connect"),- ]- # 真实 SseClient 在 owner-task 的 _do_connect 里建 transport;单测假类可能只有 connect。- if hasattr(SseClient, "_do_connect"):- connect_targets.append((SseClient, "_do_connect"))- elif hasattr(SseClient, "connect"):- connect_targets.append((SseClient, "connect"))- else:- logger.debug("[mcp-timeout] SseClient has neither _do_connect nor connect; skip stamp")-- for cls, method_name in connect_targets:+ ):if (cls, method_name) in _wrapped_connects:continue- if not hasattr(cls, method_name):- logger.debug(- "[mcp-timeout] skip wrapping %s.%s (attribute missing)",- getattr(cls, "__name__", cls),- method_name,- )- continue_wrapped_connects.add((cls, method_name))orig_method = getattr(cls, method_name)@@ -593,76 +212,6 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)return float(stamped)return default_timeout- async def _connect_fresh(client: Any, *, reason: str) -> None:- """作废旧协议会话后重新 connect(进程级客户端,跨聊天会话共享)。"""- # 超时后勿 aclose:跨 task cancel scope 会污染当前 task(见 _abandon_session)。- await _abandon_session(client, context=f"before reconnect ({reason})")- connect = getattr(client, "connect", None)- if not callable(connect):- raise RuntimeError("MCP client has no connect() for session recovery")- ok = await connect()- if not ok:- raise RuntimeError(- f"MCP client reconnect failed ({reason}): "- f"{getattr(client, '_server_path', '?')}"- )- try:- setattr(client, "_jws_needs_reconnect", False)- except Exception as exc:- logger.debug(- "[mcp-timeout] failed to clear _jws_needs_reconnect on %s after "- "reconnect (%s): %r",- type(client).__name__,- reason,- exc,- )- logger.warning(- "[mcp-timeout] MCP client reconnected after %s: %s",- reason,- getattr(client, "_server_path", "?"),- )-- async def _ensure_connected(client: Any) -> None:- """上一轮超时 / 作废后:强制重连(新旧聊天会话共用同一客户端)。"""- needs_reconnect = bool(getattr(client, "_jws_needs_reconnect", False))- session = getattr(client, "_session", None)- disconnected = bool(getattr(client, "_is_disconnected", False))- if not needs_reconnect and session is not None and not disconnected:- return- await _connect_fresh(- client,- reason="forced-reconnect" if needs_reconnect else "missing-session",- )-- async def _teardown_after_timeout(- client: Any, *, cls_name: str, method: str, timeout: float- ) -> None:- # 跳过 disconnect/aclose,直接作废(TC_MCP_CALL_014)。- await _abandon_session(- client,- context=f"{cls_name}.{method} after {timeout:g}s timeout",- )- logger.warning(- "[mcp-timeout] %s.%s session invalidated after %gs timeout "- "(next call will reconnect): %s",- cls_name,- method,- timeout,- getattr(client, "_server_path", "?"),- )-- def _timeout_error(cls_name: str, method: str, timeout: float) -> TimeoutError:- # 空 TimeoutError 会导致 SSE error='';给出可识别文案。- return TimeoutError(- f"MCP {cls_name}.{method} timed out after {timeout:g}s"- )-- def _transport_cancel_error(cls_name: str, method: str) -> RuntimeError:- return RuntimeError(- f"MCP {cls_name}.{method} interrupted by transport/timeout "- "(not user cancel)"- )-def _wrap_with_timeout(cls: type, name: str) -> None:if (cls, name) in _wrapped_methods:return@@ -671,150 +220,46 @@ 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"))- # 内层(如 SseClient 自带 wait_for)用 timeout+5 作天花板,避免仍按- # 默认 60s 提前掐断;外层 wait_for 用精确 timeout,与 pooled worker- # 的外层截止对齐,保证先触发外层 TimeoutError。- kwargs.setdefault("timeout", timeout + 5.0)-- async def _invoke_once():- # remote HTTP transport:用 asyncio.wait_for,不用 anyio.fail_after。- # fail_after 会在本 task 套 cancel scope,与 streamable-http/SSE- # transport 后台 task 的 scope 冲突,表现为超时后重连成功、MCP- # 已 call completed,但返回时仍抛 Attempted to exit a cancel scope- # (TC_MCP_CALL_014 第 3 轮)。与 mcp_config remote worker 一致。- return await asyncio.wait_for(- orig(self, *args, **kwargs),- timeout=timeout,- )-- async def _handle_timeout() -> None:+ # 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(deadline):+ return await orig(self, *args, **kwargs)+ except TimeoutError:logger.warning(- "[mcp-timeout] %s.%s timed out after %gs, disconnecting client: %s",+ "[mcp-timeout] %s.%s timed out after %.1fs, disconnecting client: %s",cls.__name__,name,timeout,getattr(self, "_server_path", "?"),)- await _teardown_after_timeout(- self, cls_name=cls.__name__, method=name, timeout=timeout- )-- async def _handle_spurious_cancel(*, phase: str) -> None:- """Transport / cancel-scope CancelledError → 可捕获的工具错误。"""- logger.warning(- "[mcp-timeout] %s.%s got CancelledError without outer cancel "- "(%s); treating as transport/timeout error: %s",- cls.__name__,- name,- phase,- getattr(self, "_server_path", "?"),- )- await _teardown_after_timeout(- self, cls_name=cls.__name__, method=name, timeout=timeout- )-- async def _reconnect_and_invoke_once(*, reason: str):- """作废重连后立刻再 invoke 一次(spurious-cancel / dead-session 共用)。"""- await _connect_fresh(self, reason=reason)- return await _invoke_once()-- # 进程级共享 client:串行化重连与调用,避免多聊天会话并发踩坏会话。- async with _client_io_lock(self):- # 同会话续聊:上一轮超时后自动恢复连接,避免永久 execute invoke failed。- await _ensure_connected(self)+ # Tear down the dead session so the next call fails fast rather+ # than burning another full timeout window on a half-open conn.try:- return await _invoke_once()- except TimeoutError:- try:- await _handle_timeout()- except asyncio.CancelledError:- # teardown 内偶发 CancelledError 不应冒泡成「用户取消」- if _is_outer_cancellation():- raise- force_invalidate_mcp_client(self)- logger.warning(- "[mcp-timeout] %s.%s teardown raised CancelledError "- "without outer cancel; still reporting timeout: %s",- cls.__name__,- name,- getattr(self, "_server_path", "?"),- )- raise _timeout_error(cls.__name__, name, timeout) from None- except asyncio.CancelledError:- # wait_for / SSE disconnect 可能直接冒出 CancelledError;- # MCPTool.invoke 捕不到 → 误判用户取消且无 tool_result。- if _is_outer_cancellation():- raise- logger.warning(- "[mcp-timeout] %s.%s got CancelledError without outer cancel "- "(invoke); reconnecting once: %s",- cls.__name__,- name,- getattr(self, "_server_path", "?"),- )- # 连接中断类:作废后重连并重试一次(对齐 SSE mock 重启场景)- try:- return await _reconnect_and_invoke_once(reason="spurious-cancel")- except TimeoutError:- try:- await _handle_timeout()- except asyncio.CancelledError:- if _is_outer_cancellation():- raise- force_invalidate_mcp_client(self)- raise _timeout_error(cls.__name__, name, timeout) from None- except asyncio.CancelledError:- if _is_outer_cancellation():- raise- force_invalidate_mcp_client(self)- raise _transport_cancel_error(cls.__name__, name) from None- except Exception as retry_exc:- force_invalidate_mcp_client(self)- logger.warning(- "[mcp-timeout] %s.%s retry after spurious cancel failed: %r",- cls.__name__,- name,- retry_exc,- )- raise _transport_cancel_error(cls.__name__, name) from retry_exc+ await self.disconnect()except Exception as exc:- # MCP 服务重启后协议会话失效:进程级客户端仍持有旧 session id,- # 新旧聊天会话都会 Session terminated / 404。作废后重连并重试一次。- # 亦覆盖 cancel-scope 清理噪声(超时后首轮偶发)。- if not is_retryable_mcp_dead_session_error(exc):- raiselogger.warning(- "[mcp-timeout] %s.%s hit dead session (%s), reconnecting once: %s",+ "[mcp-timeout] %s.%s disconnect after timeout also failed: %r",cls.__name__,name,exc,- getattr(self, "_server_path", "?"),)- try:- await _connect_fresh(self, reason="dead-session")- except asyncio.CancelledError:- if _is_outer_cancellation():- raise- await _handle_spurious_cancel(phase="reconnect")- raise _transport_cancel_error(cls.__name__, name) from None- except Exception as reconnect_exc:- logger.warning(- "[mcp-timeout] %s.%s reconnect after dead session failed: %r",- cls.__name__,- name,- reconnect_exc,- )- raise exc from reconnect_exc- try:- return await _invoke_once()- except TimeoutError:- await _handle_timeout()- raise _timeout_error(cls.__name__, name, timeout) from None- except asyncio.CancelledError:- if _is_outer_cancellation():- raise- await _handle_spurious_cancel(phase="retry")- raise _transport_cancel_error(cls.__name__, name) from None+ raisesetattr(cls, name, wrapped)@@ -822,17 +267,14 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)for cls in (StreamableHttpClient, SseClient):_wrap_with_timeout(cls, "call_tool")_wrap_with_timeout(cls, "list_tools")- # aclose 失败也必须清会话(原 SDK 只在 success 路径清理)- _wrap_disconnect_always_invalidate(cls, "disconnect")- # SseClient 真正清连接在 owner-task 的 _do_disconnect- _wrap_disconnect_always_invalidate(SseClient, "_do_disconnect")_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. Browser-move 仅劫持自身 MCP server,不再全局替换- # _create_client,因此企业远程 MCP 仍会走到本 stamp。+ # (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):@@ -863,17 +305,8 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)# (no type: ignore needed).setattr(ToolMgr, "_create_client", staticmethod(_create_client_with_timeout))- # (C) AbilityManager 外层 fail_after → wait_for 桥(不改 agent-core)- try:- _patch_ability_manager_fail_after()- except Exception as exc: # noqa: BLE001 — 单测假模块环境可能无 AbilityManager- logger.warning(- "[mcp-timeout] AbilityManager fail_after bridge skipped: %r",- exc,- )-logger.info(- "[mcp-timeout] patch applied (default_timeout=%.1fs, "- "covered=StreamableHttpClient,SseClient,AbilityManager,sdk_read_timeouts)",+ "[mcp-timeout] patch applied (default_timeout=%.1fs, covered=StreamableHttpClient,SseClient,"+ "sdk_read_timeouts)",default_timeout,)diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.pyindex 40e9b3c859..e4323857a2 100644--- a/jiuwenswarm/common/mcp_config.py+++ b/jiuwenswarm/common/mcp_config.py@@ -11,6 +11,7 @@ import ipaddressimport jsonimport osimport re+import sysimport threadingimport timeimport weakref@@ -62,36 +63,6 @@ def extract_enabled_mcp_server_entries(return result-def _coerce_str_dict(raw: Any) -> dict[str, str] | None:- """将 JSON 对象规范为 ``dict[str, str]``;非 dict 返回 ``None``。"""- if not isinstance(raw, dict):- return None- return {str(k): str(v) for k, v in raw.items()}---def _resolve_remote_mcp_auth(- entry: dict[str, Any],-) -> tuple[dict[str, str], dict[str, str]]:- """把配置条目里的鉴权字段映射到 SDK ``McpServerConfig`` 顶层字段。-- openjiuwen 的 SSE / Streamable HTTP 客户端只读 ``auth_headers`` /- ``auth_query_params``,不读 ``params.headers``。-- 字段别名(后者为兼容名):- - headers ←→ auth_headers(企业 MCP 模板 / config.yaml 多用 ``headers``)- - query_params ←→ auth_query_params-- 同组两个键都有时,以 SDK 标准名(``auth_*``)为准。- """- auth_headers = _coerce_str_dict(entry.get("auth_headers"))- if not auth_headers:- auth_headers = _coerce_str_dict(entry.get("headers"))- auth_query = _coerce_str_dict(entry.get("auth_query_params"))- if not auth_query:- auth_query = _coerce_str_dict(entry.get("query_params"))- return auth_headers or {}, auth_query or {}--def build_mcp_server_config(entry: dict[str, Any],*,@@ -103,26 +74,12 @@ def build_mcp_server_config(entry: One config entry under ``mcp.servers``.server_id_scope: Optional scope used to derive a stable ``server_id``.When omitted, openjiuwen's default random id behavior is preserved.-- Note:- Remote MCP 的 Bearer 等鉴权必须进 ``auth_headers``(SDK 建连字段),- 不能只塞进 ``params.headers``——否则客户端不带凭证,服务端会 401。"""name = str(entry.get("name", "")).strip()if not name:return None- raw_transport = str(entry.get("transport", "")).strip().lower()- # 用户可配 MCP 仅允许远程 transport;stdio 留给 OfficeClaw Relay / browser-move 内部路径。- if raw_transport not in {- "sse",- "http",- "streamable-http",- "streamable_http",- }:- return None- # 别名归一后再交给 SDK(http → streamable-http),避免 Unsupported MCP client type- transport = _normalize_mcp_client_type(raw_transport)- if transport not in {"sse", "streamable-http"}:+ transport = str(entry.get("transport", "")).strip().lower()+ if transport not in {"stdio", "sse", "http", "streamable-http", "streamable_http"}:return Nonepayload: dict[str, Any] = {@@ -133,21 +90,39 @@ def build_mcp_server_config(if explicit_server_id:payload["server_id"] = explicit_server_id- url = str(entry.get("url", "")).strip()- if not url:- return None- payload["server_path"] = url- auth_headers, auth_query = _resolve_remote_mcp_auth(entry)- if auth_headers:- payload["auth_headers"] = auth_headers- if auth_query:- payload["auth_query_params"] = auth_query- params: dict[str, Any] = {}- timeout_s = entry.get("timeout_s")- if isinstance(timeout_s, (int, float)) and not isinstance(timeout_s, bool) and float(timeout_s) > 0:- params["timeout_s"] = float(timeout_s)- if params:+ if transport == "stdio":+ command = str(entry.get("command", "")).strip()+ if not command:+ return None+ params: dict[str, Any] = {"command": command}+ args = entry.get("args")+ if isinstance(args, list):+ params["args"] = [str(item) for item in args]+ cwd = entry.get("cwd")+ if isinstance(cwd, str) and cwd.strip():+ params["cwd"] = cwd.strip()+ env = entry.get("env")+ if isinstance(env, dict):+ params["env"] = {str(k): str(v) for k, v in env.items()}+ timeout_s = entry.get("timeout_s")+ if isinstance(timeout_s, (int, float)) and int(timeout_s) > 0:+ params["timeout_s"] = int(timeout_s)+ payload["server_path"] = f"stdio://{name}"payload["params"] = params+ else:+ url = str(entry.get("url", "")).strip()+ if not url:+ return None+ payload["server_path"] = url+ params: dict[str, Any] = {}+ headers = entry.get("headers")+ if isinstance(headers, dict):+ params["headers"] = {str(k): str(v) for k, v in headers.items()}+ timeout_s = entry.get("timeout_s")+ if isinstance(timeout_s, (int, float)) and int(timeout_s) > 0:+ params["timeout_s"] = int(timeout_s)+ if params:+ payload["params"] = paramsif server_id_scope and "server_id" not in payload:payload["server_id"] = _stable_mcp_server_id(server_id_scope, name, payload)@@ -256,28 +231,41 @@ def _safe_id_part(value: str, *, default: str) -> str:return (normalized or default)[:48]-def _normalize_mcp_client_type(raw_type: object) -> str:- """归一 MCP transport / client_type 到 SDK 注册名。-- Gateway 模板与 config.yaml 允许别名 ``http`` / ``streamable_http``;- openjiuwen ResourceMgr 只认 ``streamable-http``(见 StreamableHttpClient.__client_name__)。- 未归一时会出现:模板保存成功 → chat 注册报 ``Unsupported MCP client type: http``。+def _normalize_stdio_command_kind(command: str) -> str:+ """将 command 归一化为 'node'、'python'、'npx' 或 'uvx'。- 空 / None 返回空串(不再默认 ``stdio``);显式 ``stdio`` 仍返回 ``stdio``,- 便于上层配置入口拒绝用户可配本地 stdio。+ 支持绝对路径如 /usr/local/bin/node、C:\\Program Files\\node.exe 等。+ npx/uvx为包运行器,参数为包名而非本地脚本路径,安全模型与 node/python 不同。"""+ raw = str(command or "").strip()+ if not raw:+ raise ValueError("工具配置缺少 'command' 字段")++ normalized = raw.replace("\\", "/").rsplit("/", 1)[-1].lower()+ if normalized in ("node", "node.exe"):+ return "node"+ if normalized.startswith("python"):+ return "python"+ if normalized in ("npx", "npx.exe", "npx.cmd", "npx.bat"):+ return "npx"+ if normalized in ("uvx", "uvx.exe"):+ return "uvx"+ raise ValueError(+ f"不支持的 command 类型: '{command}',目前仅支持 node/python/npx/uvx 及其绝对路径"+ )+++def _normalize_mcp_client_type(raw_type: object) -> str:if raw_type is None:- return ""+ return "stdio"s = str(raw_type).strip().lower().replace("_", "-")- if not s:- return ""- if s in {"http", "streamable-http", "streamablehttp"} or "streamable" in s:+ if "streamable" in s:return "streamable-http"if s == "sse":return "sse"if s == "stdio":return "stdio"- return s+ return s if s else "stdio"def _pick_mcp_url(tool_config: dict) -> str:@@ -296,6 +284,151 @@ def _optional_auth_dict(tool_config: dict, key: str) -> dict | None:return dict(raw)+_DANGEROUS_ARGS_PATTERN = frozenset(+ {+ "-e",+ "--eval",+ "-c",+ "--command",+ "-i",+ }+)+++def _check_dangerous_args(tool_name: str, args: list) -> None:+ if not isinstance(args, list):+ return+ for arg in args:+ arg_str = str(arg).strip()+ if arg_str in _DANGEROUS_ARGS_PATTERN:+ raise ValueError(+ f"安全拦截阻断:工具 '{tool_name}' 的 args 包含危险标志 '{arg_str}',"+ "禁止通过参数注入执行任意代码。"+ )+ for dangerous_prefix in ("-e=", "--eval=", "-c=", "--command="):+ if arg_str.lower().startswith(dangerous_prefix):+ raise ValueError(+ f"安全拦截阻断:工具 '{tool_name}' 的 args 包含危险标志 '{arg_str}',"+ "禁止通过参数注入执行任意代码。"+ )+++def _trusted_cat_cafe_stdio_roots() -> list[Path]:+ roots: list[Path] = []+ raw = (os.getenv("CAT_CAFE_MCP_CWD") or "").strip()+ if raw:+ try:+ roots.append(Path(raw).expanduser().resolve())+ except OSError:+ pass+ try:+ roots.append((Path.home() / ".office-claw").resolve())+ except OSError:+ pass+ try:+ roots.append(Path(sys.executable).resolve().parent)+ except OSError:+ pass+ lp = (os.getenv("LOCALAPPDATA") or "").strip()+ if lp:+ inst = Path(lp) / "Programs" / "OfficeClaw"+ try:+ if inst.exists():+ roots.append(inst.resolve())+ except OSError:+ pass+ for env_key in ("ProgramFiles", "ProgramFiles(x86)"):+ base = os.getenv(env_key, "").strip()+ if not base:+ continue+ inst = Path(base) / "OfficeClaw"+ try:+ if inst.exists():+ roots.append(inst.resolve())+ except OSError:+ pass+ seen: set[str] = set()+ out: list[Path] = []+ for r in roots:+ key = os.path.normcase(str(r))+ if key not in seen:+ seen.add(key)+ out.append(r)+ return out+++def _path_is_under_trusted_root(path: Path, roots: list[Path]) -> bool:+ try:+ rp = path.resolve()+ except OSError:+ return False+ for root in roots:+ try:+ rp.relative_to(root)+ return True+ except ValueError:+ continue+ return False+++def _validate_cat_cafe_request_scoped_stdio(params: dict[str, Any]) -> None:+ """限制请求级 stdio:禁止内联代码执行面,脚本路径须在受信根目录下。++ npx/uvx 为包运行器,参数为包名及其参数,不适用本地脚本路径受信根校验+ (代码来源为包仓库而非本地文件,信任决策在于包名而非路径)。+ """+ cmd = str(params.get("command") or "").strip()+ args = params.get("args") or []+ if not isinstance(args, list):+ raise ValueError("stdio MCP 的 args 须为列表")++ kind = _normalize_stdio_command_kind(cmd)+ flat = [str(a) for a in args]+ lowered = [a.strip().lower() for a in flat]+ if any(x == "-c" or x == "--command" for x in lowered):+ raise ValueError("请求级 cat_cafe_mcp 禁止使用 python -c / --command")+ if kind == "node" and any(x in ("-e", "--eval") for x in lowered):+ raise ValueError("请求级 cat_cafe_mcp 禁止使用 node -e / --eval")++ if kind in ("npx", "uvx"):+ return++ cwd_path: Path | None = None+ cwd_raw = params.get("cwd")+ if isinstance(cwd_raw, str) and cwd_raw.strip():+ try:+ cwd_path = Path(cwd_raw).expanduser().resolve()+ except OSError as exc:+ raise ValueError(f"请求级 cat_cafe_mcp cwd 无效: {cwd_raw}") from exc+ if not _path_is_under_trusted_root(cwd_path, _trusted_cat_cafe_stdio_roots()):+ raise ValueError(f"请求级 cat_cafe_mcp cwd 不在受信根目录下: {cwd_path}")++ roots = _trusted_cat_cafe_stdio_roots()+ for a in flat:+ s = a.strip()+ if not s or s.startswith("-"):+ continue+ path_like_suffix = s.lower().endswith((".js", ".mjs", ".cjs", ".py"))+ if "/" not in s and "\\" not in s and not path_like_suffix:+ continue+ candidate = Path(s).expanduser()+ if not candidate.is_absolute() and cwd_path is None:+ raise ValueError(+ "请求级 cat_cafe_mcp 使用相对脚本路径时必须提供位于受信根下的 cwd"+ )+ try:+ if cwd_path is not None and not candidate.is_absolute():+ resolved = (cwd_path / candidate).resolve()+ else:+ resolved = candidate.resolve()+ except OSError:+ continue+ if not _path_is_under_trusted_root(resolved, roots):+ raise ValueError(+ f"请求级 cat_cafe_mcp 参数路径不在受信根目录下: {resolved}"+ )++_REQUEST_REMOTE_BLOCKED_HOSTS = frozenset({"localhost",@@ -387,19 +520,22 @@ def _validate_request_scoped_remote_mcp(tool_name: str, cfg: dict) -> None:def create_mcp_tool(config_str: str) -> McpServerConfig:- """从 JSON 字符串解析并构造远程 ``McpServerConfig``。-- 用户可配连接器仅支持远程类型(sse / streamable-http / playwright / openapi)。- 本地 stdio 不在此入口开放(OfficeClaw Relay 走独立校验路径)。+ """从 JSON 字符串解析并构造 ``McpServerConfig``。Args:- config_str: JSON 格式配置字符串,例如:+ 1.stdio类型:+ config_str: JSON 格式配置字符串,格式为:+ {+ "name": "tool_name",+ "command": "node" | "python" | "npx" | "uvx",+ "args": ["xxx.js"] | ["xxx.py"] | ["-y", "@scope/pkg"] | ["pkg"]+ }- 1.streamable-http类型:+ 2.streamable-http类型:{- "name": "my-http-mcp","type": "streamableHttp","url": "http://127.0.0.1:3002/mcp",+ "env": {},"auth_headers": {"Authorization": "Bearer xxx"},@@ -408,11 +544,12 @@ def create_mcp_tool(config_str: str) -> McpServerConfig:}}- 2.sse类型:+ 3.sse类型:{"name": "my-sse-mcp","type": "sse","url": "http://127.0.0.1:3001/sse",+ "env": {},"auth_headers": {"Authorization": "Bearer xxx"},@@ -420,8 +557,7 @@ def create_mcp_tool(config_str: str) -> McpServerConfig:"token": "yyy"}}-- 3.playwright类型:+ 4.playwright类型:{"name": "my-playwright-mcp","description": "可选说明",@@ -430,18 +566,11 @@ def create_mcp_tool(config_str: str) -> McpServerConfig:"env": {}}- 4.openapi类型:- {- "name": "my-openapi-mcp",- "type": "openapi",- "url": "http://127.0.0.1:3004/openapi.json"- }-Returns:``McpServerConfig``,由调用方通过 ``Runner.resource_mgr.add_mcp_server(..., tag=...)`` 注册。Raises:- ValueError: JSON 解析失败、缺 type、type=stdio,或其它不合法配置时+ ValueError: JSON 解析失败或配置不合法时"""try:config = json.loads(config_str)@@ -462,7 +591,10 @@ def create_mcp_tool(config_str: str) -> McpServerConfig:tool_name = tool_config.get("name")server_id = str(tool_config.get("server_id") or tool_name or "").strip()+ command = tool_config.get("command")+ args = tool_config.get("args", [])env = tool_config.get("env")+ cwd = tool_config.get("cwd")# timeout_s 兼容两种下发形状:顶层(config.yaml 风格)与嵌套 params.timeout_s# (relay buildMcpRequestFields 下发的 {"params": {"timeout_s": N}})。timeout_s = tool_config.get("timeout_s")@@ -488,7 +620,8 @@ def create_mcp_tool(config_str: str) -> McpServerConfig:if client_type == "sse":if not url:raise ValueError(f"工具 '{tool_name}'('{client_type}')需要 url")- headers, query = _resolve_remote_mcp_auth(tool_config)+ headers = _optional_auth_dict(tool_config, "auth_headers")+ query = _optional_auth_dict(tool_config, "auth_query_params")return McpServerConfig(server_id=server_id or tool_name,server_name=tool_name,@@ -502,7 +635,8 @@ def create_mcp_tool(config_str: str) -> McpServerConfig:if client_type == "streamable-http":if not url:raise ValueError(f"工具 '{tool_name}'('{client_type}')需要 url")- headers, query = _resolve_remote_mcp_auth(tool_config)+ headers = _optional_auth_dict(tool_config, "auth_headers")+ query = _optional_auth_dict(tool_config, "auth_query_params")return McpServerConfig(server_id=server_id or tool_name,server_name=tool_name,@@ -535,10 +669,23 @@ def create_mcp_tool(config_str: str) -> McpServerConfig:params=params,)- raise ValueError(- f"工具 '{tool_name}' 不支持 type={client_type or tool_config.get('type')!r};"- "用户可配 MCP 仅支持 sse / streamable-http / playwright / openapi"- "(本地 stdio 已禁用,请使用远程 URL)"+ if not isinstance(args, list):+ raise ValueError(f"工具 '{tool_name}' 的 args 必须是列表类型")++ _check_dangerous_args(tool_name, args)++ normalized_command = str(command or "").strip()+ _normalize_stdio_command_kind(normalized_command)+ params["command"] = normalized_command+ params["args"] = args+ if isinstance(cwd, str) and cwd.strip():+ params["cwd"] = cwd.strip()+ return McpServerConfig(+ server_id=server_id or tool_name,+ server_name=tool_name,+ server_path=f"stdio://{tool_name}",+ client_type="stdio",+ params=params,)@@ -751,7 +898,6 @@ async def _run_mcp_worker(按 ``params["_mcp_client_type"]`` 分派:- stdio(默认/缺省):起 ``stdio_client`` + ``ClientSession`` 进程。- 仅供 OfficeClaw Relay 身份 pin 后的 worker 使用;用户可配连接器入口已切断。- sse / streamable-http:复用 openjiuwen 的 ``SseClient`` / ``StreamableHttpClient``,connect 后长连接复用(自带 owner-task/cancel-scope/超时/重连 + auth 注入)。@@ -1586,13 +1732,13 @@ async def list_request_mcp_server_tools("""发现单个用户连接器的 tool schema。config 是 Relay 的启动载荷(无 tool schema),需起一次服务调 list_tools() 收集,- 对齐 _list_office_claw_mcp_tools_uncached。仅支持远程 sse / streamable-http。+ 对齐 _list_office_claw_mcp_tools_uncached。支持 stdio / sse / streamable-http。返回 (tool_defs, connect_params):connect_params 是经 create_mcp_tool 安全层过滤后的连接描述,带 ``_mcp_client_type`` 字段供 ``_run_mcp_worker`` 按 transport 分派,交给 RequestScopedOfficeClawMcpTool。任意失败返回 ([], {}) 以免单个坏连接器中断注册。"""- # 经 create_mcp_tool 安全层(SSRF 主机屏蔽等),+ # 经 create_mcp_tool 安全层(危险参数过滤/stdio 命令校验/SSRF 主机屏蔽),# 而非 office-claw 身份 pin(validate_office_claw_mcp_config,专用于 Relay 自带 office-claw)。config_with_name = {**dict(config), "name": server_name}try:@@ -1609,13 +1755,73 @@ async def list_request_mcp_server_tools(if client_type == "sse" or client_type == "streamable-http":return await _list_remote_mcp_connector_tools(server_name, server_cfg, client_type)- logger.warning(- "request-scoped MCP connector '%s' transport '%s' not supported "- "(user connectors are remote-only); skipping",- server_name,- client_type or "unknown",- )- return [], {}+ if client_type != "stdio":+ logger.warning(+ "request-scoped MCP connector '%s' transport '%s' not supported; skipping",+ server_name,+ client_type or "unknown",+ )+ return [], {}++ # stdio:起一次进程,list_tools 后关闭。+ from mcp import ClientSession+ from mcp.client.stdio import stdio_client++ params = dict(getattr(server_cfg, "params", {}) or {})+ if "command" not in params or "args" not in params:+ logger.warning(+ "request-scoped MCP connector '%s' stdio params incomplete: %s",+ server_name,+ params,+ )+ return [], {}++ # 发现阶段超时:连接器下发 timeout_s 时取 max(下发值, 300s)——下发值只放宽不收紧+ # (npx 冷启动首次 initialize/list_tools 可远超 300s;下发值过小则仍以 300s 兜底)。+ _discovery_timeout = _MCP_CONNECTOR_DISCOVERY_TIMEOUT_S+ _timeout_raw = params.get("timeout_s")+ if (+ isinstance(_timeout_raw, (int, float))+ and not isinstance(_timeout_raw, bool)+ and _timeout_raw > _discovery_timeout+ ):+ _discovery_timeout = float(_timeout_raw)++ stack = AsyncExitStack()+ try:+ read, write = await stack.enter_async_context(+ stdio_client(_stdio_server_parameters(params))+ )+ session = await stack.enter_async_context(+ ClientSession(read, write, sampling_callback=None)+ )+ # 防护 connector 启动卡死(用户配置的连接器是任意命令,不像可信的 office-claw)。+ # 同样用 anyio.fail_after 而非 asyncio.wait_for(破坏 stdio cancel-scope 不变量)。+ try:+ with anyio.fail_after(_discovery_timeout):+ await session.initialize()+ response = await session.list_tools()+ except TimeoutError:+ logger.warning(+ "request-scoped MCP connector '%s' discovery timed out after "+ "%.0fs (initialize/list_tools hung)",+ server_name,+ _discovery_timeout,+ )+ return [], {}+ tool_defs = _extract_mcp_tool_defs(response)+ # 标记 transport,供 _run_mcp_worker 分派(默认 None 等价 stdio)。+ params["_mcp_client_type"] = "stdio"+ return tool_defs, params+ except Exception as exc:+ logger.warning(+ "request-scoped MCP connector '%s' tool discovery failed: %s",+ server_name,+ exc,+ )+ return [], {}+ finally:+ await stack.aclose()async def _list_remote_mcp_connector_tools(@@ -2023,10 +2229,15 @@ __all__ = ["revoke_live_office_claw_allowlist","unregister_live_office_claw_tool_instance","validate_office_claw_mcp_config",+ "_check_dangerous_args","_is_blocked_host","_loopback_mcp_allowed","_normalize_mcp_client_type",+ "_normalize_stdio_command_kind","_optional_auth_dict",+ "_path_is_under_trusted_root","_pick_mcp_url",+ "_trusted_cat_cafe_stdio_roots",+ "_validate_cat_cafe_request_scoped_stdio","_validate_request_scoped_remote_mcp",]diff --git a/jiuwenswarm/server/handlers/mcp.py b/jiuwenswarm/server/handlers/mcp.pyindex 44a3656fe2..abee3f4f75 100644--- a/jiuwenswarm/server/handlers/mcp.py+++ b/jiuwenswarm/server/handlers/mcp.py@@ -6,6 +6,8 @@ from __future__ import annotationsimport asyncioimport logging+import shutil+from pathlib import Pathfrom typing import Anyfrom jiuwenswarm.common.config import (@@ -28,13 +30,6 @@ _MCP_ENTERPRISE_FORBIDDEN = ("企业版禁止使用本地 /mcp 命令,请在管理端通过 MCP 模板下发与查看。")-_REMOTE_MCP_TRANSPORTS = frozenset({- "sse",- "http",- "streamable-http",- "streamable_http",-})-def _normalize_mcp_payload(params: dict[str, Any], current: dict[str, Any] | None = None@@ -45,23 +40,38 @@ def _normalize_mcp_payload(transport = str(merged.get("transport", "")).strip().lower()if not name:raise ValueError("MCP server name is required")- if transport not in _REMOTE_MCP_TRANSPORTS:- raise ValueError("transport must be one of sse|http")+ if transport not in {"stdio", "sse", "http", "streamable-http", "streamable_http"}:+ raise ValueError("transport must be one of stdio|sse|http")payload: dict[str, Any] = {"name": name,"enabled": bool(merged.get("enabled", True)),"transport": transport,}- url = str(merged.get("url", "")).strip()- if not url:- raise ValueError(f"{transport} transport requires url")- payload["url"] = url- headers = merged.get("headers")- if isinstance(headers, dict):- payload["headers"] = {str(k): str(v) for k, v in headers.items()}- timeout_s = merged.get("timeout_s")- if isinstance(timeout_s, (int, float)) and not isinstance(timeout_s, bool) and float(timeout_s) > 0:- payload["timeout_s"] = float(timeout_s)+ if transport == "stdio":+ command = str(merged.get("command", "")).strip()+ if not command:+ raise ValueError("stdio transport requires command")+ payload["command"] = command+ args = merged.get("args")+ if isinstance(args, list):+ payload["args"] = [str(item) for item in args]+ cwd = merged.get("cwd")+ if isinstance(cwd, str) and cwd.strip():+ payload["cwd"] = cwd.strip()+ env = merged.get("env")+ if isinstance(env, dict):+ payload["env"] = {str(k): str(v) for k, v in env.items()}+ else:+ url = str(merged.get("url", "")).strip()+ if not url:+ raise ValueError(f"{transport} transport requires url")+ payload["url"] = url+ headers = merged.get("headers")+ if isinstance(headers, dict):+ payload["headers"] = {str(k): str(v) for k, v in headers.items()}+ timeout_s = merged.get("timeout_s")+ if isinstance(timeout_s, (int, float)):+ payload["timeout_s"] = int(timeout_s)return payload@@ -95,27 +105,53 @@ async def _pre_check_mcp_server(server_payload: dict[str, Any]) -> tuple[bool, sReturns ``(ok, message)``."""import logging as _logging+ from openjiuwen.core.foundation.tool import McpServerConfigfrom openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr-- from jiuwenswarm.common.mcp_config import build_mcp_server_config-name = server_payload.get("name", "")- transport = str(server_payload.get("transport", "")).strip().lower()-- cfg = build_mcp_server_config(server_payload)- if cfg is None:- return False, f"{name} ({transport}) pre-check failed: invalid mcp config"+ transport = server_payload.get("transport", "")+ # Build McpServerConfig (same logic as _fetch_mcp_tools_from_config)+ payload: dict[str, Any] = {"server_name": name, "client_type": transport}+ if transport == "stdio":+ command = server_payload.get("command", "")+ if not command:+ return True, "skipped: no command"+ # stdio 预检查改为纯静态校验,静态校验零 spawn、零 anyio。+ if not shutil.which(command):+ return False, f"{name} (stdio) pre-check failed: command not found in PATH: {command}"+ raw_args = server_payload.get("args") or []+ if isinstance(raw_args, list):+ for arg in raw_args:+ if not isinstance(arg, str):+ continue+ looks_like_path = (+ arg.startswith(("/", "./", "../", "~"))+ or arg.endswith((".js", ".mjs", ".cjs", ".json", ".py", ".sh"))+ )+ if looks_like_path and not Path(arg).expanduser().exists():+ return False, f"{name} (stdio) pre-check failed: file not found: {arg}"+ return True, f"{name} (stdio) pre-check passed (static)"+ else:+ url = server_payload.get("url", "")+ if not url:+ return True, "skipped: no url"+ payload["server_path"] = url+ params = {}+ if isinstance(server_payload.get("headers"), dict):+ params["headers"] = {str(k): str(v) for k, v in server_payload["headers"].items()}+ if params:+ payload["params"] = params+ cfg = McpServerConfig(**payload)client = ToolMgr._create_client(cfg)_logging.disable(_logging.CRITICAL)try:connected = await asyncio.wait_for(client.connect(), timeout=15.0)if not connected:- return False, f"{name} ({cfg.client_type}) pre-check failed: connection refused"- return True, f"{name} ({cfg.client_type}) pre-check passed"+ return False, f"{name} ({transport}) pre-check failed: connection refused"+ return True, f"{name} ({transport}) pre-check passed"except asyncio.TimeoutError:- return False, f"{name} ({cfg.client_type}) pre-check failed: connection timed out"+ return False, f"{name} ({transport}) pre-check failed: connection timed out"except Exception as exc:- return False, f"{name} ({cfg.client_type}) pre-check failed: {exc}"+ return False, f"{name} ({transport}) pre-check failed: {exc}"finally:_logging.disable(_logging.NOTSET)try:@@ -126,19 +162,41 @@ async def _pre_check_mcp_server(server_payload: dict[str, Any]) -> tuple[bool, sasync def _fetch_mcp_tools_from_config(entry: dict[str, Any]) -> list[dict[str, Any]]:"""Create a temporary MCP connection from config entry and list tools."""+ from openjiuwen.core.foundation.tool import McpServerConfigfrom openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr-- from jiuwenswarm.common.mcp_config import build_mcp_server_config-name = str(entry.get("name", "")).strip()transport = str(entry.get("transport", "")).strip().lower()- if not name or transport not in _REMOTE_MCP_TRANSPORTS:+ if not name or transport not in {"stdio", "sse", "http", "streamable-http", "streamable_http"}:logger.warning("[command.mcp] _fetch skipped: name=%r transport=%r", name, transport)return []- cfg = build_mcp_server_config(entry)- if cfg is None:- logger.warning("[command.mcp] _fetch skipped: invalid config name=%r transport=%r", name, transport)- return []+ # Build McpServerConfig same as interface_deep._build_mcp_server_config+ payload: dict[str, Any] = {"server_name": name, "client_type": transport}+ if transport == "stdio":+ command = str(entry.get("command", "")).strip()+ if not command:+ logger.warning("[command.mcp] _fetch skipped: no command for stdio")+ return []+ params: dict[str, Any] = {"command": command}+ if isinstance(entry.get("args"), list):+ params["args"] = [str(x) for x in entry["args"]]+ if isinstance(entry.get("cwd"), str) and entry["cwd"].strip():+ params["cwd"] = entry["cwd"].strip()+ if isinstance(entry.get("env"), dict):+ params["env"] = {str(k): str(v) for k, v in entry["env"].items()}+ payload["server_path"] = f"stdio://{name}"+ payload["params"] = params+ else:+ url = str(entry.get("url", "")).strip()+ if not url:+ logger.warning("[command.mcp] _fetch skipped: no url for sse")+ return []+ payload["server_path"] = url+ params = {}+ if isinstance(entry.get("headers"), dict):+ params["headers"] = {str(k): str(v) for k, v in entry["headers"].items()}+ if params:+ payload["params"] = params+ cfg = McpServerConfig(**payload)client = ToolMgr._create_client(cfg)try:connected = await client.connect()@@ -267,46 +325,79 @@ async def handle_command_mcp(ctx: RequestContext) -> None:elif action == "add":server_payload = _normalize_mcp_add_payload(ctx, params)- # 远程 MCP:可选连通性预检查失败不阻断写入(历史行为保留为仅记录)。- # 此处不再做本地 stdio 静态预检。- name = server_payload.get("name", "")- old_item = get_mcp_server_config(name) if name else None-- _, created = upsert_mcp_server_in_config(server_payload)- applied = True- error_message = ""-- # 判断是否需要 reload: 新增必然需要;更新时做完整比较,- # 配置完全一致才跳过(dict 比较成本极低,避免漏字段导致改了不生效)。- config_changed = created- if not created and old_item is not None:- config_changed = (dict(old_item) != dict(server_payload))- if not config_changed:- logger.info(- "[command.mcp] add/update skipped reload: '%s' config unchanged", name- )-- if config_changed:- try:- await ctx.services.agent_manager.reload_agents_config(get_config(), None)- except Exception as reload_exc: # noqa: BLE001- applied = False- error_message = str(reload_exc)- logger.warning("[command.mcp] reload after add failed: %s", reload_exc)-- resp_payload: dict[str, Any] = {- "type": "added" if created else "updated",- "name": server_payload["name"],- "applied": applied,- }- if error_message:- resp_payload["error"] = error_message- resp = AgentResponse(- request_id=request.request_id,- channel_id=request.channel_id,- ok=True,- payload=resp_payload,- )+ # Pre-check: only validate when stdio args contain a local file+ # path (e.g. "node /path/to/server.js"). Skip for package+ # managers like npx which may need to download first.+ pre_check_failed = False+ if bool(server_payload.get("enabled", True)):+ _need_pre_check = False+ if server_payload.get("transport") == "stdio":+ _args = server_payload.get("args")+ if isinstance(_args, list):+ _need_pre_check = any(+ isinstance(a, str)+ and (a.startswith(("/", "./", "../"))+ or a.endswith((".js", ".mjs", ".json", ".py")))+ for a in _args+ )+ if _need_pre_check:+ check_ok, check_msg = await _pre_check_mcp_server(server_payload)+ if not check_ok:+ logger.warning("[command.mcp] add pre-check failed: %s", check_msg)+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=False,+ payload={+ "type": "add_failed",+ "name": server_payload["name"],+ "error": check_msg,+ },+ )+ pre_check_failed = True+ else:+ logger.info("[command.mcp] add pre-check ok: %s", check_msg)++ if not pre_check_failed:+ # 对于 update,先读旧配置,判断是否真有变化+ name = server_payload.get("name", "")+ old_item = get_mcp_server_config(name) if name else None++ _, created = upsert_mcp_server_in_config(server_payload)+ applied = True+ error_message = ""++ # 判断是否需要 reload: 新增必然需要;更新时做完整比较,+ # 配置完全一致才跳过(dict 比较成本极低,避免漏字段导致改了不生效)。+ config_changed = created+ if not created and old_item is not None:+ config_changed = (dict(old_item) != dict(server_payload))+ if not config_changed:+ logger.info(+ "[command.mcp] add/update skipped reload: '%s' config unchanged", name+ )++ if config_changed:+ try:+ await ctx.services.agent_manager.reload_agents_config(get_config(), None)+ except Exception as reload_exc: # noqa: BLE001+ applied = False+ error_message = str(reload_exc)+ logger.warning("[command.mcp] reload after add failed: %s", reload_exc)++ resp_payload: dict[str, Any] = {+ "type": "added" if created else "updated",+ "name": server_payload["name"],+ "applied": applied,+ }+ if error_message:+ resp_payload["error"] = error_message+ resp = AgentResponse(+ request_id=request.request_id,+ channel_id=request.channel_id,+ ok=True,+ payload=resp_payload,+ )elif action in {"enable", "disable"}:name = str(params.get("name", "")).strip()if not name:diff --git a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.pyindex 82da83c75a..5de4c93612 100644--- a/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py+++ b/jiuwenswarm/server/runtime/agent_adapter/interface_deep.py@@ -2148,9 +2148,9 @@ class JiuWenSwarmDeepAdapter:) -> 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). On- # timeout the session is force-invalidated so the next call can- # reconnect (TC_MCP_CALL_014). Idempotent (module-level _PATCHED guard).+ # 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()# 绑定交互续轮的 task id 到 TaskPlan 任务,使外层循环收敛。幂等。apply_deepagent_task_plan_binding_patch()diff --git a/jiuwenswarm/server/runtime/enterprise_config/apply_mcp.py b/jiuwenswarm/server/runtime/enterprise_config/apply_mcp.pyindex 29efe311e2..1ae88e39da 100644--- a/jiuwenswarm/server/runtime/enterprise_config/apply_mcp.py+++ b/jiuwenswarm/server/runtime/enterprise_config/apply_mcp.py@@ -73,9 +73,6 @@ def mcp_entity_to_server_entry(entity: dict[str, Any]) -> dict[str, Any] | None:normalized["name"] = nametransport = str(normalized.get("transport", "")).strip().lower()if transport:- # 与 build_mcp_server_config / SDK 对齐:http 是 streamable-http 别名- if transport in {"http", "streamable_http"}:- transport = "streamable-http"normalized["transport"] = transport# 运行时 servers[] 仍需要 enabled 字段;企业侧开关已由模板行决定normalized["enabled"] = Truediff --git a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/template_schemas.py b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/template_schemas.pyindex eb7b8e273c..b1d77ec4c4 100644--- a/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/template_schemas.py+++ b/packages/jiuwenclaw-ee/gateway/extensions/manager_config_receiver/schemas/template_schemas.py@@ -210,29 +210,17 @@ class SkillPrebuiltTemplateCreateRequest(SkillPrebuiltTemplateUpdateRequest):skill_id: str = Field(..., min_length=1, max_length=512)-# 入参可写别名;存盘归一到 SDK 注册名(见 _CANONICAL_MCP_TRANSPORT)。-# 企业模板仅允许远程 MCP;本地 stdio 不在用户可配入口开放。_VALID_MCP_TRANSPORTS = frozenset({+ "stdio","sse","http","streamable-http","streamable_http",})-# http / streamable_http → streamable-http(openjiuwen StreamableHttpClient)-_MCP_TRANSPORT_ALIASES: dict[str, str] = {- "http": "streamable-http",- "streamable_http": "streamable-http",-}-def validate_mcp_entry(entry: dict[str, Any]) -> dict[str, Any]:- """校验 MCP 模板 ``mcp_entry``;丢弃条目级 ``enabled``(开关只认模板行)。-- ``http`` / ``streamable_http`` 作为 Streamable HTTP 别名接受,存盘时写成- ``streamable-http``,避免 Gateway 保存成功、AgentServer 注册报- ``Unsupported MCP client type: http``。- """+ """校验 MCP 模板 ``mcp_entry``;丢弃条目级 ``enabled``(开关只认模板行)。"""if not isinstance(entry, dict):raise ValueError("mcp_entry must be a JSON object")normalized = dict(entry)@@ -246,10 +234,14 @@ def validate_mcp_entry(entry: dict[str, Any]) -> dict[str, Any]:"mcp_entry.transport must be one of: "+ ", ".join(sorted(_VALID_MCP_TRANSPORTS)))- transport = _MCP_TRANSPORT_ALIASES.get(transport, transport)- url = str(normalized.get("url", "")).strip()- if not url:- raise ValueError("mcp_entry.url is required for remote MCP transport")+ if transport == "stdio":+ command = str(normalized.get("command", "")).strip()+ if not command:+ raise ValueError("mcp_entry.command is required for stdio transport")+ else:+ url = str(normalized.get("url", "")).strip()+ if not url:+ raise ValueError("mcp_entry.url is required for remote MCP transport")normalized["name"] = namenormalized["transport"] = transportreturn normalizeddiff --git a/tests/agents/swarm/test_swarm_assembly.py b/tests/agents/swarm/test_swarm_assembly.pyindex 318ed01b65..fe3989d160 100644--- a/tests/agents/swarm/test_swarm_assembly.py+++ b/tests/agents/swarm/test_swarm_assembly.py@@ -1104,20 +1104,21 @@ def test_enrich_team_spec_for_swarm_injects_config_mcp_servers({"name": "local_tool","enabled": True,- "transport": "sse",- "url": "http://127.0.0.1:18013/sse",+ "transport": "stdio",+ "command": "python",+ "args": ["server.py"],+ "cwd": str(tmp_path),},{"name": "disabled_tool","enabled": False,- "transport": "sse",- "url": "http://127.0.0.1:18014/sse",+ "transport": "stdio",+ "command": "python",},{"name": "invalid_tool","enabled": True,"transport": "stdio",- "command": "python",},],},@@ -1136,8 +1137,12 @@ def test_enrich_team_spec_for_swarm_injects_config_mcp_servers(assert [cfg.server_name for cfg in leader_mcps] == ["local_tool"]assert [cfg.server_name for cfg in teammate_mcps] == ["local_tool"]assert leader_mcps[0].server_id == teammate_mcps[0].server_id- assert leader_mcps[0].client_type == "sse"- assert leader_mcps[0].server_path == "http://127.0.0.1:18013/sse"+ assert leader_mcps[0].client_type == "stdio"+ assert leader_mcps[0].params == {+ "command": "python",+ "args": ["server.py"],+ "cwd": str(tmp_path),+ }def test_enrich_skips_absent_roles_gracefully() -> None:diff --git a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py b/tests/unit_tests/agentserver/test_agentserver_cli_commands.pyindex d3aac7fa98..dbdd23064d 100644--- a/tests/unit_tests/agentserver/test_agentserver_cli_commands.py+++ b/tests/unit_tests/agentserver/test_agentserver_cli_commands.py@@ -663,8 +663,9 @@ async def test_handle_command_mcp_add_triggers_reload(server, fake_ws, monkeypatparams={"action": "add","name": "demo",- "transport": "sse",- "url": "http://127.0.0.1:18013/sse",+ "transport": "stdio",+ "command": "python",+ "args": ["server.py"],},)diff --git a/tests/unit_tests/agentserver/test_apply_enterprise_mcp.py b/tests/unit_tests/agentserver/test_apply_enterprise_mcp.pyindex 902decede9..d353522f13 100644--- a/tests/unit_tests/agentserver/test_apply_enterprise_mcp.py+++ b/tests/unit_tests/agentserver/test_apply_enterprise_mcp.py@@ -5,7 +5,6 @@ from __future__ import annotationsfrom unittest.mock import patch-from jiuwenswarm.common.mcp_config import build_mcp_server_configfrom jiuwenswarm.server.runtime.enterprise_config.apply_mcp import (apply_enterprise_mcp_to_config,mcp_entity_to_server_entry,@@ -23,14 +22,14 @@ def test_apply_enterprise_mcp_replaces_local_servers() -> None:"servers": [{"name": "local-only",- "transport": "sse",- "url": "http://127.0.0.1:8000/sse",+ "transport": "stdio",+ "command": "echo","enabled": True,},{"name": "local-demo",- "transport": "http",- "url": "http://127.0.0.1:8001/mcp",+ "transport": "stdio",+ "command": "echo","enabled": True,},]@@ -68,7 +67,7 @@ def test_apply_enterprise_mcp_replaces_local_servers() -> None:by_name = {item["name"]: item for item in servers}assert "local-only" not in by_nameassert by_name["local-demo"]["transport"] == "sse"- assert by_name["remote-tools"]["transport"] == "streamable-http"+ assert by_name["remote-tools"]["transport"] == "http"assert set(by_name) == {"local-demo", "remote-tools"}@@ -79,8 +78,8 @@ def test_apply_enterprise_mcp_clears_local_when_slot_empty() -> None:"servers": [{"name": "local-demo",- "transport": "sse",- "url": "http://127.0.0.1:8000/sse",+ "transport": "stdio",+ "command": "echo","enabled": True,}]@@ -117,7 +116,7 @@ def test_clear_local_mcp_servers() -> None:)merged = clear_local_mcp_servers(- {"mcp": {"servers": [{"name": "x", "transport": "sse", "url": "http://127.0.0.1/sse"}]}}+ {"mcp": {"servers": [{"name": "x", "transport": "stdio", "command": "c"}]}})assert merged["mcp"]["servers"] == []@@ -158,32 +157,9 @@ def test_mcp_entity_ignores_entry_enabled_and_forces_true() -> None:assert entry is not Noneassert entry["name"] == "x"assert entry["enabled"] is True- assert entry["transport"] == "streamable-http"assert "enabled" in entry-def test_http_transport_alias_registers_as_streamable_http() -> None:- """TC_MCP_CALL_005:模板 transport=http 经企业合并后须可被 SDK 注册。"""- entity = {- "template_id": "sds-24af77be869a-mcp",- "enabled": True,- "mcp_entry": {- "name": "qa-streamable-http",- "transport": "http",- "url": "http://192.168.1.96:18016/mcp",- "timeout_s": 10,- },- }- entry = mcp_entity_to_server_entry(entity)- assert entry is not None- assert entry["transport"] == "streamable-http"-- cfg = build_mcp_server_config(entry, server_id_scope="jiuwenswarm")- assert cfg is not None- assert cfg.client_type == "streamable-http"- assert cfg.server_name == "qa-streamable-http"--_WARN = "jiuwenswarm.server.runtime.enterprise_config.apply_mcp.logger.warning"@@ -268,54 +244,3 @@ def test_apply_enterprise_mcp_warns_for_non_dict_entity() -> None:warn.assert_called_once()message = warn.call_args[0][0] % warn.call_args[0][1:]assert "not a dict" in message---def test_enterprise_mcp_template_headers_map_to_sdk_auth_headers() -> None:- """企业模板 ``mcp_entry.headers`` 必须进 SDK ``auth_headers``,否则 AS→MCP 401。-- 对齐现场 TC_MCP_CALL_002:Bearer 写在模板 headers,不放在 chat 请求头。- """- entity = {- "template_id": "sds-8f1d60f974d1-mcp",- "enabled": True,- "mcp_entry": {- "name": "qa-bearer-streamable-http",- "transport": "streamable-http",- "url": "http://192.168.1.96:18016/mcp",- "headers": {- "Authorization": "Bearer sds-dev-mcp-bearer-token",- },- "timeout_s": 10,- },- }- entry = mcp_entity_to_server_entry(entity)- assert entry is not None- assert entry["headers"]["Authorization"] == "Bearer sds-dev-mcp-bearer-token"-- cfg = build_mcp_server_config(entry, server_id_scope="jiuwenswarm")- assert cfg is not None- assert cfg.client_type == "streamable-http"- assert cfg.auth_headers == {- "Authorization": "Bearer sds-dev-mcp-bearer-token",- }- # 不得再只塞进 params.headers(SDK 客户端不读该字段)- assert "headers" not in (cfg.params or {})- assert cfg.params.get("timeout_s") == 10-- enterprise = EffectiveEnterpriseConfig(- routing=RoutingContext(- group_id="sds-8f1d60f974d1-group",- bot_id="sds-8f1d60f974d1-resource",- user_id="sds-8f1d60f974d1-user",- ),- mcp=[entity],- )- merged, applied = apply_enterprise_mcp_to_config({"mcp": {"servers": []}}, enterprise)- assert applied is True- built = build_mcp_server_config(- merged["mcp"]["servers"][0], server_id_scope="jiuwenswarm"- )- assert built is not None- assert built.auth_headers.get("Authorization") == (- "Bearer sds-dev-mcp-bearer-token"- )diff --git a/tests/unit_tests/agentserver/test_request_scoped_remote_mcp.py b/tests/unit_tests/agentserver/test_request_scoped_remote_mcp.pyindex 4429c532e4..0dc5a2f918 100644--- a/tests/unit_tests/agentserver/test_request_scoped_remote_mcp.py+++ b/tests/unit_tests/agentserver/test_request_scoped_remote_mcp.py@@ -9,7 +9,7 @@ Covers:2. ``_run_mcp_worker`` dispatches by ``params["_mcp_client_type"]`` — theremote client's ``call_tool`` is used to drain the request queue, and theregistered ``disconnect`` callback runs on worker exit.-3. User-configured stdio connectors are rejected (remote-only discovery).+3. stdio discovery keeps working and now tags params with ``_mcp_client_type``."""from __future__ import annotations@@ -424,8 +424,47 @@ async def test_run_mcp_worker_init_failure_drains_queue(@pytest.mark.asyncio-async def test_stdio_discovery_is_rejected() -> None:- """用户可配本地 stdio 连接器不再走发现分支,返回空结果。"""+async def test_stdio_discovery_still_marks_client_type(monkeypatch: pytest.MonkeyPatch) -> None:+ """The stdio discovery path must keep working and now tag params with+ _mcp_client_type='stdio' so the worker dispatch is explicit."""+ # Loopback must be allowed for the 127.0.0.1-style commands we simulate.+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "1")++ fake_session = MagicMock()+ fake_session.initialize = AsyncMock()+ fake_session.list_tools = AsyncMock(+ return_value=SimpleNamespace(tools=[_FakeTool("stdio_tool")])+ )++ # mcp.client.stdio.stdio_client is an async context manager; patch it to+ # return dummy read/write streams so no real process is spawned.+ class _StdioCtx:+ async def __aenter__(self):+ return MagicMock(), MagicMock()++ async def __aexit__(self, *exc):+ return False++ monkeypatch.setattr("mcp.client.stdio.stdio_client", lambda _p: _StdioCtx())+ # stdio_server_parameters is evaluated before stdio_client; stub it so no+ # StdioServerParameters (which needs cwd/env) is constructed.+ monkeypatch.setattr(mcp_config, "_stdio_server_parameters", lambda params: None)++ # ClientSession is imported lazily inside the function; patch at the source.+ import mcp as _mcp_mod++ class _SessionCtx:+ def __init__(self, session) -> None:+ self._session = session++ async def __aenter__(self):+ return self._session++ async def __aexit__(self, *exc):+ return False++ monkeypatch.setattr(_mcp_mod, "ClientSession", lambda *a, **k: _SessionCtx(fake_session))+config = {"name": "local-stdio","type": "stdio",@@ -434,19 +473,5 @@ async def test_stdio_discovery_is_rejected() -> None:}tool_defs, params = await list_request_mcp_server_tools("local-stdio", config)- assert tool_defs == []- assert params == {}---async def test_missing_type_command_args_discovery_is_rejected() -> None:- """缺 type 的 command+args 配置同样被 create_mcp_tool 拒绝。"""- config = {- "name": "legacy-stdio",- "command": "npx",- "args": ["-y", "some-mcp"],- }- tool_defs, params = await list_request_mcp_server_tools("legacy-stdio", config)-- assert tool_defs == []- assert params == {}+ assert [t["name"] for t in tool_defs] == ["stdio_tool"]+ assert params["_mcp_client_type"] == "stdio"diff --git a/tests/unit_tests/common/test_mcp_browser_client_isolation.py b/tests/unit_tests/common/test_mcp_browser_client_isolation.pydeleted file mode 100644index 6f3b50b666..0000000000--- a/tests/unit_tests/common/test_mcp_browser_client_isolation.py+++ /dev/null@@ -1,44 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""browser-move 不得劫持企业远程 MCP 的 ToolMgr 客户端。"""--from __future__ import annotations--from openjiuwen.core.foundation.tool import McpServerConfig--from jiuwenswarm.agents.harness.common.tools.browser_tools import (- _BROWSER_MCP_DEFAULT_ID,- _BROWSER_MCP_DEFAULT_NAME,- _is_browser_runtime_mcp_config,-)---def test_browser_runtime_mcp_detected_by_default_id_and_name() -> None:- assert _is_browser_runtime_mcp_config(- McpServerConfig(- server_id=_BROWSER_MCP_DEFAULT_ID,- server_name=_BROWSER_MCP_DEFAULT_NAME,- server_path="stdio://playwright-runtime-wrapper",- client_type="stdio",- )- )- assert _is_browser_runtime_mcp_config(- McpServerConfig(- server_id=f"{_BROWSER_MCP_DEFAULT_ID}_sse",- server_name=_BROWSER_MCP_DEFAULT_NAME,- server_path="http://127.0.0.1:8931/sse",- client_type="sse",- )- )---def test_enterprise_remote_mcp_not_treated_as_browser() -> None:- assert not _is_browser_runtime_mcp_config(- McpServerConfig(- server_id="qa-noauth-streamable-http",- server_name="qa-noauth-streamable-http",- server_path="http://192.168.1.96:18014/mcp",- client_type="streamable-http",- auth_headers={"Authorization": "Bearer token"},- params={"timeout_s": 1.0},- )- )diff --git a/tests/unit_tests/common/test_mcp_call_timeout_recovery.py b/tests/unit_tests/common/test_mcp_call_timeout_recovery.pydeleted file mode 100644index 691885bf12..0000000000--- a/tests/unit_tests/common/test_mcp_call_timeout_recovery.py+++ /dev/null@@ -1,769 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""MCP 超时 / Session terminated 后须能恢复(TC_MCP_CALL_014 与服务重启场景)。"""--from __future__ import annotations--from contextlib import AsyncExitStack, contextmanager-from types import SimpleNamespace-from typing import Iterator--import anyio-import pytest--import jiuwenswarm.common.mcp_call_timeout_patch as timeout_patch-from jiuwenswarm.common.mcp_call_timeout_patch import (- force_invalidate_mcp_client,- is_retryable_mcp_dead_session_error,-)---@contextmanager-def _restore_after_mcp_timeout_patch() -> Iterator[None]:- """还原 apply_mcp_call_timeout_patch 可能改动的全局绑定(anyio / 原始 invoke)。-- 假 transport 模块下主要还原真 SDK 的 ``ability_manager.anyio``;- 若 AM 桥接包装了 Tool 等,用 ``_jws_orig_invoke`` 还原。- """- am_mod = None- orig_am_anyio = None- try:- import openjiuwen.core.single_agent.ability_manager as am_mod-- orig_am_anyio = am_mod.anyio- except Exception:- am_mod = None-- def _tool_classes_for_invoke_restore() -> list[type]:- classes: list[type] = []- try:- from openjiuwen.core.foundation.tool.base import Tool- from openjiuwen.core.foundation.tool.mcp.base import MCPTool-- classes.extend([Tool, MCPTool])- except Exception:- return classes- try:- from openjiuwen.core.foundation.tool.function.function import LocalFunction-- classes.append(LocalFunction)- except Exception:- pass- try:- from openjiuwen.core.foundation.tool.service_api.restful_api import (- RestfulApi,- )-- classes.append(RestfulApi)- except Exception:- pass- try:- from jiuwenswarm.common.mcp_config import RequestScopedOfficeClawMcpTool-- classes.append(RequestScopedOfficeClawMcpTool)- except Exception:- pass- return classes-- try:- yield- finally:- if am_mod is not None and orig_am_anyio is not None:- am_mod.anyio = orig_am_anyio- for cls in _tool_classes_for_invoke_restore():- # 只还原本类 stash,勿用 getattr 沿 MRO 误拿父类 orig- orig = cls.__dict__.get("_jws_orig_invoke")- if orig is not None:- setattr(cls, "invoke", orig)- try:- delattr(cls, "_jws_orig_invoke")- except Exception:- pass- # 单测会反复清 _PATCHED;收尾再清一次,避免泄漏到其它文件- timeout_patch._PATCHED = False- timeout_patch._wrapped_methods.clear()---def restore_mcp_timeout_patch():- """显式还原入口(与模块 autouse 等价;AM 桥接用例可点名依赖以表意)。"""- with _restore_after_mcp_timeout_patch():- yield---def test_force_invalidate_clears_session_and_replaces_exit_stack() -> None:- old_stack = AsyncExitStack()- client = SimpleNamespace(- _session=object(),- _client=object(),- _read=object(),- _write=object(),- _is_disconnected=False,- _exit_stack=old_stack,- _auth_provider=object(),- )- force_invalidate_mcp_client(client)- assert client._session is None- assert client._client is None- assert client._read is None- assert client._write is None- assert client._is_disconnected is True- assert client._auth_provider is None- assert client._exit_stack is not old_stack- assert isinstance(client._exit_stack, AsyncExitStack)- assert client._jws_needs_reconnect is True--- "exc, expect",- [- (RuntimeError("Session terminated"), True),- (Exception("server error 404"), True),- (ConnectionError("Connection closed"), True),- (Exception(""), True), # 现场半死连接:error='' / 空消息- (- RuntimeError(- "Attempted to exit cancel scope in a different task than it was entered in"- ),- True,- ),- (ValueError(""), False), # 空业务错误不应当死会话重试- (ValueError("invalid tool args"), False),- ],-)-def test_is_retryable_mcp_dead_session_error(exc: BaseException, expect: bool) -> None:- assert is_retryable_mcp_dead_session_error(exc) is expect---def _install_fake_transport_modules(monkeypatch: pytest.MonkeyPatch):- """避免拉取 openjiuwen.tool 整包依赖;给超时补丁提供可包装的假客户端类。"""- import sys- from types import ModuleType-- async def _stub_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del self, tool_name, arguments, timeout- raise RuntimeError("stub call_tool not replaced")-- async def _stub_list_tools(self, *, timeout=-1):- del self, timeout- return []-- async def _stub_connect(self, *, timeout=-1):- del self, timeout- return True-- async def _stub_disconnect(self, *, timeout=-1):- del self, timeout- return True-- class StreamableHttpClient:- call_tool = _stub_call_tool- list_tools = _stub_list_tools- connect = _stub_connect- disconnect = _stub_disconnect-- class SseClient:- call_tool = _stub_call_tool- list_tools = _stub_list_tools- connect = _stub_connect- disconnect = _stub_disconnect-- class ToolMgr:- @staticmethod- def _create_client(config):- return object()-- http_mod = ModuleType(- "openjiuwen.core.foundation.tool.mcp.client.streamable_http_client"- )- http_mod.StreamableHttpClient = StreamableHttpClient- sse_mod = ModuleType("openjiuwen.core.foundation.tool.mcp.client.sse_client")- sse_mod.SseClient = SseClient- mgr_mod = ModuleType("openjiuwen.core.runner.resources_manager.tool_manager")- mgr_mod.ToolMgr = ToolMgr-- monkeypatch.setitem(sys.modules, http_mod.__name__, http_mod)- monkeypatch.setitem(sys.modules, sse_mod.__name__, sse_mod)- monkeypatch.setitem(sys.modules, mgr_mod.__name__, mgr_mod)- return StreamableHttpClient, SseClient, ToolMgr---def _install_fake_streamable_client(- monkeypatch: pytest.MonkeyPatch,- *,- fake_call_tool,- fake_disconnect=None,- fake_connect=None,- default_timeout: float = 5.0,-):- StreamableHttpClient, _, _ = _install_fake_transport_modules(monkeypatch)-- async def _default_list_tools(self, *, timeout=-1):- del timeout- if not self._session:- raise RuntimeError("Not connected to streamable-http server")- return []-- async def _default_disconnect(self, *, timeout=-1):- del timeout- raise RuntimeError(- "Attempted to exit cancel scope in a different task than it was entered in"- )-- connect_count = {"n": 0}-- async def _default_connect(self, *, timeout=-1):- del timeout- connect_count["n"] += 1- self._session = object()- self._is_disconnected = False- return True-- monkeypatch.setattr(StreamableHttpClient, "call_tool", fake_call_tool, raising=False)- monkeypatch.setattr(StreamableHttpClient, "list_tools", _default_list_tools, raising=False)- monkeypatch.setattr(- StreamableHttpClient,- "disconnect",- fake_disconnect or _default_disconnect,- raising=False,- )- monkeypatch.setattr(- StreamableHttpClient,- "connect",- fake_connect or _default_connect,- raising=False,- )-- timeout_patch._PATCHED = False- timeout_patch._wrapped_methods.clear()- timeout_patch.apply_mcp_call_timeout_patch(default_timeout=default_timeout)-- client = object.__new__(StreamableHttpClient)- client._server_path = "http://192.168.1.96:18014/mcp"- client._session = object()- client._client = object()- client._read = None- client._write = None- client._is_disconnected = False- client._exit_stack = AsyncExitStack()- client._auth_provider = None- client._jws_call_timeout = default_timeout- client._name = "qa-noauth-streamable-http"- return client, connect_count, StreamableHttpClient--[email protected](autouse=True)-def _autouse_restore_mcp_timeout_patch():- """本文件凡 apply / 改 ability_manager.anyio 的用例结束后还原全局副作用。"""- with _restore_after_mcp_timeout_patch():- yield---async def test_timeout_then_same_session_call_recovers(monkeypatch: pytest.MonkeyPatch) -> None:- """对齐现场:disconnect 因 cancel scope 失败且未清 _session 时,下一轮须重连成功。"""- call_count = {"n": 0}-- async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del timeout- call_count["n"] += 1- if call_count["n"] == 1:- await anyio.sleep(5)- return {"unreachable": True}- return {"tool": tool_name, "arguments": arguments, "ok": True}-- client, connect_count, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- default_timeout=0.05,- )-- with pytest.raises(TimeoutError, match="timed out after"):- await client.call_tool("qa_delay", {"seconds": 5})-- assert client._session is None- assert client._is_disconnected is True-- result = await client.call_tool(- "qa_echo",- {"text": "MCP-CALL-sds-59382e14cf32-after-timeout"},- )- assert result["ok"] is True- assert result["tool"] == "qa_echo"- assert connect_count["n"] >= 1- assert call_count["n"] == 2---async def test_timeout_then_cancel_scope_on_next_call_retries_once(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """TC_MCP_CALL_014 第 3 轮:超时重连后首呼若冒 cancel scope,须同轮重试成功。-- 现场:MCP 已 call completed,但返回路径抛 Attempted to exit a cancel scope,- 导致 after-timeout 的 qa_echo 失败;第 4 轮才恢复。补丁应对该噪声重连重试一次。- """- call_count = {"n": 0}-- async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del timeout- call_count["n"] += 1- if call_count["n"] == 1:- await anyio.sleep(5)- return {"unreachable": True}- if call_count["n"] == 2:- # 模拟:工具其实已跑完,返回时被 cancel-scope 清理异常盖掉- raise RuntimeError(- "Attempted to exit cancel scope in a different task than it was entered in"- )- return {- "tool": tool_name,- "text": arguments.get("text"),- "marker": "SDS-DEV-MCP-OK",- "ok": True,- }-- client, connect_count, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- default_timeout=0.05,- )-- with pytest.raises(TimeoutError, match="timed out after"):- await client.call_tool("qa_delay", {"seconds": 5})-- result = await client.call_tool(- "qa_echo",- {"text": "MCP-CALL-after-timeout-should-ok"},- )- assert result["ok"] is True- assert result["marker"] == "SDS-DEV-MCP-OK"- # 1 超时 + 1 cancel-scope 失败 + 1 重试成功- assert call_count["n"] == 3- assert connect_count["n"] >= 2---async def test_session_terminated_reconnects_and_retries_same_call(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """MCP 服务重启后:进程级客户端遇 Session terminated 应重连并重试成功。-- 新旧聊天会话共用 ToolMgr 里同一 MCP client,故一次恢复即可服务后续会话。- """- call_count = {"n": 0}-- async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del timeout- call_count["n"] += 1- if call_count["n"] == 1:- raise RuntimeError("Session terminated")- return {- "tool": tool_name,- "text": arguments.get("text"),- "marker": "SDS-DEV-MCP-OK",- "ok": True,- }-- client, connect_count, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- default_timeout=5.0,- )-- # 会话 A:服务重启后第一次调用- result_a = await client.call_tool(- "qa_echo",- {"text": "MCP-CALL-sds-c839d94b0b7a-same-after-restart"},- )- assert result_a["ok"] is True- assert result_a["text"] == "MCP-CALL-sds-c839d94b0b7a-same-after-restart"- assert connect_count["n"] >= 1- assert call_count["n"] == 2 # 失败一次 + 重试成功-- # 会话 B:同一 AS 进程级客户端,不应再 Session terminated- result_b = await client.call_tool(- "qa_echo",- {"text": "MCP-CALL-sds-c839d94b0b7a-fresh-after-restart"},- )- assert result_b["ok"] is True- assert result_b["text"] == "MCP-CALL-sds-c839d94b0b7a-fresh-after-restart"- assert call_count["n"] == 3---async def test_timeout_then_fresh_chat_session_on_shared_client_recovers(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """超时后新建聊天会话 B 与 A 共用进程级客户端,也须能 qa_echo。-- 对齐 sds-037840350c2c:A 超时后 B 仅 echo 仍失败(error='')。- """- call_count = {"n": 0}-- async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del timeout- call_count["n"] += 1- if call_count["n"] == 1:- await anyio.sleep(5)- return {"unreachable": True}- return {- "tool": tool_name,- "text": arguments.get("text"),- "ok": True,- }-- client, connect_count, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- default_timeout=0.05,- )-- with pytest.raises(TimeoutError, match="timed out after"):- await client.call_tool("qa_delay", {"seconds": 5})-- assert getattr(client, "_jws_needs_reconnect", False) is True-- # 会话 A 超时后 echo(对照 #4133)- result_a = await client.call_tool(- "qa_echo",- {"text": "MCP-CALL-sds-037840350c2c-after-timeout"},- )- assert result_a["ok"] is True- assert result_a["text"] == "MCP-CALL-sds-037840350c2c-after-timeout"-- # 会话 B:同一 AS Pod / 同一 ToolMgr 客户端,仅 echo- result_b = await client.call_tool(- "qa_echo",- {"text": "MCP-CALL-sds-037840350c2c-fresh-after-timeout"},- )- assert result_b["ok"] is True- assert result_b["text"] == "MCP-CALL-sds-037840350c2c-fresh-after-timeout"- assert connect_count["n"] >= 1- assert call_count["n"] == 3- assert getattr(client, "_jws_needs_reconnect", True) is False---async def test_empty_error_after_half_dead_session_reconnects_once(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """半死连接抛空消息 Exception 时须重连重试(现场 error='')。"""- call_count = {"n": 0}-- async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del timeout- call_count["n"] += 1- if call_count["n"] == 1:- raise Exception("")- return {"tool": tool_name, "text": arguments.get("text"), "ok": True}-- client, connect_count, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- default_timeout=5.0,- )-- result = await client.call_tool(- "qa_echo",- {"text": "MCP-CALL-sds-037840350c2c-fresh-after-timeout"},- )- assert result["ok"] is True- assert call_count["n"] == 2- assert connect_count["n"] >= 1---async def test_sticky_reconnect_flag_forces_reconnect_even_if_session_present(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """disconnect 失败若残留 _session,靠 _jws_needs_reconnect 仍须强制重连。"""- call_count = {"n": 0}- dead_session = object()-- async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del timeout- call_count["n"] += 1- if call_count["n"] == 1:- await anyio.sleep(5)- return {"unreachable": True}- # 若未强制重连,仍拿着超时前的 dead_session- assert self._session is not dead_session- return {"tool": tool_name, "ok": True}-- async def fake_disconnect(self, *, timeout=-1):- del timeout- # 模拟 SDK:aclose 失败且不清 _session- raise RuntimeError(- "Attempted to exit cancel scope in a different task than it was entered in"- )-- client, connect_count, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- fake_disconnect=fake_disconnect,- default_timeout=0.05,- )- client._session = dead_session-- with pytest.raises(TimeoutError, match="timed out after"):- await client.call_tool("qa_delay", {"seconds": 5})-- # 补丁应已清掉并打标;再故意塞回 dead_session 模拟竞态残留- client._session = dead_session- client._is_disconnected = False- client._jws_needs_reconnect = True-- result = await client.call_tool("qa_echo", {"text": "after"})- assert result["ok"] is True- assert connect_count["n"] >= 1- assert call_count["n"] == 2---async def test_timeout_teardown_cancelled_error_still_reports_timeout(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """超时 teardown 不再 aclose;即使旧 disconnect 会抛 CancelledError,仍报 TimeoutError。"""- import asyncio-- async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del self, tool_name, arguments, timeout- await anyio.sleep(5)- return {"unreachable": True}-- async def fake_disconnect(self, *, timeout=-1):- del self, timeout- raise asyncio.CancelledError()-- client, _, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- fake_disconnect=fake_disconnect,- default_timeout=0.05,- )-- with pytest.raises(TimeoutError, match="timed out after") as ei:- await client.call_tool("qa_delay", {"seconds": 5})-- assert not isinstance(ei.value, asyncio.CancelledError)- assert "user cancel" not in str(ei.value).lower()- assert client._session is None- assert client._is_disconnected is True---async def test_spurious_cancelled_error_reconnects_once(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """连接中断冒出的 CancelledError(非外层取消)应重连重试,而非标成用户取消。"""- import asyncio-- call_count = {"n": 0}-- async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del timeout- call_count["n"] += 1- if call_count["n"] == 1:- raise asyncio.CancelledError()- return {"tool": tool_name, "arguments": arguments, "ok": True}-- client, connect_count, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- default_timeout=5.0,- )-- result = await client.call_tool(- "qa_echo",- {"text": "MCP-CALL-sds-90b35bbefb56-after-restart"},- )- assert result["ok"] is True- assert call_count["n"] == 2- assert connect_count["n"] >= 1---async def test_sse_timeout_reports_timeout_not_cancelled(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """SseClient 超时同样须抛 TimeoutError(可被 MCPTool.invoke 捕获成工具错误)。"""- import asyncio-- _, SseClient, _ = _install_fake_transport_modules(monkeypatch)-- async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):- del self, tool_name, arguments, timeout- await anyio.sleep(5)- return {"unreachable": True}-- async def fake_disconnect(self, *, timeout=-1):- del self, timeout- raise asyncio.CancelledError()-- async def fake_connect(self, *, timeout=-1):- del timeout- self._session = object()- self._is_disconnected = False- return True-- async def fake_list_tools(self, *, timeout=-1):- del self, timeout- return []-- monkeypatch.setattr(SseClient, "call_tool", fake_call_tool, raising=False)- monkeypatch.setattr(SseClient, "list_tools", fake_list_tools, raising=False)- monkeypatch.setattr(SseClient, "disconnect", fake_disconnect, raising=False)- monkeypatch.setattr(SseClient, "connect", fake_connect, raising=False)-- timeout_patch._PATCHED = False- timeout_patch._wrapped_methods.clear()- timeout_patch.apply_mcp_call_timeout_patch(default_timeout=0.05)-- client = object.__new__(SseClient)- client._server_path = "http://192.168.1.96:18013/sse"- client._session = object()- client._client = object()- client._read = None- client._write = None- client._is_disconnected = False- client._exit_stack = AsyncExitStack()- client._auth_provider = None- client._jws_call_timeout = 0.05- client._name = "qa-noauth-sse"-- with pytest.raises(TimeoutError, match="timed out after") as ei:- await client.call_tool("qa_delay", {"seconds": 5})-- assert not isinstance(ei.value, asyncio.CancelledError)- assert client._session is None- assert client._is_disconnected is True---async def test_am_fail_after_bridge_does_not_mutate_global_anyio(- monkeypatch: pytest.MonkeyPatch,- restore_mcp_timeout_patch,-) -> None:- """AbilityManager 桥接不得改写共享 anyio.fail_after(否则 ProgressiveRail 丢 cancel_called)。"""- import anyio-- del restore_mcp_timeout_patch # fixture 副作用:结束后还原 am_mod.anyio- _install_fake_transport_modules(monkeypatch)- timeout_patch._PATCHED = False- timeout_patch._wrapped_methods.clear()-- # 预加载真 AbilityManager(若环境无 openjiuwen 则跳过)- try:- import openjiuwen.core.single_agent.ability_manager as am_mod- except Exception as exc: # noqa: BLE001- pytest.skip(f"openjiuwen AbilityManager unavailable: {exc}")-- real_fail_after = anyio.fail_after- timeout_patch.apply_mcp_call_timeout_patch(default_timeout=1.0)-- # 全局 anyio.fail_after 必须仍是原对象- assert anyio.fail_after is real_fail_after- # AbilityManager 模块拿到的是代理- assert am_mod.anyio is not anyio- assert am_mod.anyio.fail_after is not real_fail_after-- # ProgressiveRail 依赖的 cancel_called 仍在- with anyio.fail_after(1.0) as scope:- assert hasattr(scope, "cancel_called")- assert scope.cancel_called is False---async def test_am_invoke_wrap_honors_contextvar_timeout() -> None:- """AbilityManager 桥:contextvar 截止时间经 invoke 包装走 wait_for。"""- import asyncio-- class _SlowTool:- async def invoke(self, *args, **kwargs):- del args, kwargs- await asyncio.sleep(1.0)- return "done"-- # 清 idempotency,避免与其它用例抢同一 (cls, key)- key = (_SlowTool, "am_timeout:invoke")- timeout_patch._wrapped_methods.discard(key)- timeout_patch._wrap_invoke_with_am_timeout(_SlowTool)-- tool = _SlowTool()- token = timeout_patch._am_call_timeout.set(0.05)- try:- with pytest.raises(asyncio.TimeoutError):- await tool.invoke({})- finally:- timeout_patch._am_call_timeout.reset(token)- orig = getattr(_SlowTool, "_jws_orig_invoke", None)- if orig is not None:- setattr(_SlowTool, "invoke", orig)- delattr(_SlowTool, "_jws_orig_invoke")- timeout_patch._wrapped_methods.discard(key)---async def test_am_wrap_does_not_replace_subclass_invoke_with_parent_orig() -> None:- """回归:先包父类再包子类时,不得用父类 _jws_orig_invoke 覆盖子类 invoke。"""-- class _BaseTool:- async def invoke(self, *args, **kwargs):- del args, kwargs- return "base"-- class _ChildTool(_BaseTool):- async def invoke(self, *args, **kwargs):- del args, kwargs- return "child"-- timeout_patch._wrap_invoke_with_am_timeout(_BaseTool)- timeout_patch._wrap_invoke_with_am_timeout(_ChildTool)- try:- assert await _ChildTool().invoke({}) == "child"- assert "_jws_orig_invoke" in _ChildTool.__dict__- assert _ChildTool.__dict__["_jws_orig_invoke"] is not _BaseTool.__dict__.get(- "_jws_orig_invoke"- )- finally:- for cls in (_BaseTool, _ChildTool):- orig = cls.__dict__.get("_jws_orig_invoke")- if orig is not None:- setattr(cls, "invoke", orig)- delattr(cls, "_jws_orig_invoke")- timeout_patch._wrapped_methods.discard((cls, "am_timeout:invoke"))---async def test_disconnect_wrap_clears_session_when_aclose_fails(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """disconnect finally 清会话:aclose 失败也不留半死连接。"""- StreamableHttpClient, _, _ = _install_fake_transport_modules(monkeypatch)-- async def boom_disconnect(self, *, timeout=-1):- del self, timeout- raise RuntimeError("aclose failed")-- monkeypatch.setattr(StreamableHttpClient, "disconnect", boom_disconnect, raising=False)- timeout_patch._PATCHED = False- timeout_patch._wrapped_methods.clear()- timeout_patch.apply_mcp_call_timeout_patch(default_timeout=1.0)-- client = object.__new__(StreamableHttpClient)- client._session = object()- client._client = object()- client._read = object()- client._write = object()- client._is_disconnected = False- client._exit_stack = AsyncExitStack()- client._auth_provider = object()- client._server_path = "http://example/mcp"-- with pytest.raises(RuntimeError, match="aclose failed"):- await client.disconnect()-- assert client._session is None- assert client._client is None- assert client._is_disconnected is True- assert client._jws_needs_reconnect is Truediff --git a/tests/unit_tests/common/test_mcp_config_create_mcp_tool.py b/tests/unit_tests/common/test_mcp_config_create_mcp_tool.pyindex a0105c9e64..7d8db1a4fe 100644--- a/tests/unit_tests/common/test_mcp_config_create_mcp_tool.py+++ b/tests/unit_tests/common/test_mcp_config_create_mcp_tool.py@@ -3,26 +3,33 @@from __future__ import annotationsimport json+from pathlib import Pathimport pytestfrom jiuwenswarm.common.mcp_config import (+ _check_dangerous_args,_is_blocked_host,_loopback_mcp_allowed,_normalize_mcp_client_type,+ _normalize_stdio_command_kind,_optional_auth_dict,+ _path_is_under_trusted_root,_pick_mcp_url,+ _trusted_cat_cafe_stdio_roots,+ _validate_cat_cafe_request_scoped_stdio,_validate_request_scoped_remote_mcp,- build_mcp_server_config,create_mcp_tool,)+from openjiuwen.core.foundation.tool import McpServerConfig+class TestNormalizeMcpClientType:@pytest.mark.parametrize("raw, expected",[- (None, ""),- ("", ""),+ (None, "stdio"),+ ("", "stdio"),("stdio", "stdio"),("STDIO", "stdio"),("sse", "sse"),@@ -31,9 +38,6 @@ class TestNormalizeMcpClientType:("streamable_http", "streamable-http"),("streamable-http", "streamable-http"),("StreamableHTTP", "streamable-http"),- # TC_MCP_CALL_005:模板 transport=http 是 Streamable HTTP 别名- ("http", "streamable-http"),- ("HTTP", "streamable-http"),("playwright", "playwright"),("openapi", "openapi"),],@@ -42,6 +46,47 @@ class TestNormalizeMcpClientType:assert _normalize_mcp_client_type(raw) == expected+class TestNormalizeStdioCommandKind:+ @pytest.mark.parametrize(+ "command, expected",+ [+ ("node", "node"),+ ("node.exe", "node"),+ ("python", "python"),+ ("python3", "python"),+ ("python3.11", "python"),+ ("C:\\Program Files\\node.exe", "node"),+ ("/usr/local/bin/node", "node"),+ ("npx", "npx"),+ ("npx.exe", "npx"),+ ("npx.cmd", "npx"),+ ("/usr/local/bin/npx", "npx"),+ ("uvx", "uvx"),+ ("uvx.exe", "uvx"),+ ("/home/u/.local/bin/uvx", "uvx"),+ ],+ )+ def test_valid_commands(self, command, expected):+ assert _normalize_stdio_command_kind(command) == expected++ def test_empty_command_raises(self):+ with pytest.raises(ValueError, match="缺少"):+ _normalize_stdio_command_kind("")++ def test_whitespace_command_raises(self):+ with pytest.raises(ValueError, match="缺少"):+ _normalize_stdio_command_kind(" ")++ def test_none_command_raises(self):+ with pytest.raises(ValueError, match="缺少"):+ _normalize_stdio_command_kind(None)++ @pytest.mark.parametrize("cmd", ["bash", "sh", "ruby", "cmd", "powershell", "deno"])+ def test_unsupported_command_raises(self, cmd):+ with pytest.raises(ValueError, match="不支持"):+ _normalize_stdio_command_kind(cmd)++class TestPickMcpUrl:def test_valid_url(self):assert _pick_mcp_url({"url": " http://example.com "}) == "http://example.com"@@ -69,6 +114,131 @@ class TestOptionalAuthDict:_optional_auth_dict({"auth_headers": "not-a-dict"}, "auth_headers")+class TestCheckDangerousArgs:+ def test_safe_args_pass(self):+ _check_dangerous_args("t", ["-y", "@scope/pkg", "/tmp"])++ def test_eval_flag_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ _check_dangerous_args("t", ["-e", "code"])++ def test_command_flag_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ _check_dangerous_args("t", ["-c", "print(1)"])++ def test_module_flag_allowed(self):+ _check_dangerous_args("t", ["-m", "os"])++ def test_eval_equals_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ _check_dangerous_args("t", ["--eval=code"])++ def test_command_equals_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ _check_dangerous_args("t", ["-c=print(1)"])++ def test_non_list_args_noop(self):+ _check_dangerous_args("t", "not-a-list")++ def test_empty_args_pass(self):+ _check_dangerous_args("t", [])+++class TestTrustedCatCafeStdioRoots:+ def test_returns_list_of_paths(self):+ roots = _trusted_cat_cafe_stdio_roots()+ assert isinstance(roots, list)+ for r in roots:+ assert isinstance(r, Path)++ def test_no_duplicates(self):+ roots = _trusted_cat_cafe_stdio_roots()+ keys = [str(r) for r in roots]+ assert len(keys) == len(set(keys))+++class TestPathIsUnderTrustedRoot:+ def test_subpath_is_under_root(self, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ child = root / "sub" / "file.py"+ assert _path_is_under_trusted_root(child, [root])++ def test_unrelated_path_is_not_under_root(self, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ other = tmp_path / "other" / "file.py"+ assert not _path_is_under_trusted_root(other, [root])++ def test_root_itself_is_under_root(self, tmp_path):+ root = tmp_path / "root"+ root.mkdir()+ assert _path_is_under_trusted_root(root, [root])+++class TestValidateCatCafeRequestScopedStdio:+ def test_npx_skips_path_check(self):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "npx",+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/etc", "/tmp"],+ })++ def test_uvx_skips_path_check(self):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "uvx",+ "args": ["mcp-server-fetch", "/var/data"],+ })++ def test_npx_untrusted_cwd_allowed(self):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "npx",+ "args": ["-y", "pkg"],+ "cwd": "/untrusted/random/dir",+ })++ def test_npx_dangerous_command_arg_still_blocked(self):+ with pytest.raises(ValueError, match="python -c"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "npx",+ "args": ["-c", "code"],+ })++ def test_uvx_dangerous_command_arg_still_blocked(self):+ with pytest.raises(ValueError, match="python -c"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "uvx",+ "args": ["--command", "code"],+ })++ def test_node_path_check_still_active(self):+ with pytest.raises(ValueError, match="受信根"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "node",+ "args": ["/untrusted/script.js"],+ })++ def test_python_path_check_still_active(self):+ with pytest.raises(ValueError, match="受信根"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "python",+ "args": ["/untrusted/script.py"],+ })++ def test_node_eval_still_blocked(self):+ with pytest.raises(ValueError, match="node -e"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "node",+ "args": ["-e", "console.log(1)"],+ })++ def test_args_not_list_raises(self):+ with pytest.raises(ValueError, match="args 须为列表"):+ _validate_cat_cafe_request_scoped_stdio({+ "command": "npx",+ "args": "not-a-list",+ })++class TestIsBlockedHost:def test_localhost_blocked(self):assert _is_blocked_host("localhost")@@ -203,51 +373,81 @@ class TestValidateRequestScopedRemoteMcp:_validate_request_scoped_remote_mcp("t", {"url": "http://192.168.1.1/mcp"})-class TestCreateMcpToolRejectsStdio:- """用户可配 create_mcp_tool 不再接受本地 stdio / 缺 type。"""-- def test_basic_stdio_rejected(self):+class TestCreateMcpToolStdio:+ def test_basic_stdio(self):cfg = json.dumps({"name": "my-tool", "command": "node", "args": ["server.js"]})- with pytest.raises(ValueError, match="仅支持|stdio|已禁用"):- create_mcp_tool(cfg)+ result = create_mcp_tool(cfg)+ assert isinstance(result, McpServerConfig)+ assert result.client_type == "stdio"+ assert result.server_name == "my-tool"+ assert result.server_path == "stdio://my-tool"+ assert result.params["command"] == "node"+ assert result.params["args"] == ["server.js"]++ def test_stdio_with_python(self):+ cfg = json.dumps({"name": "py-tool", "command": "python", "args": ["-m", "mymod"]})+ result = create_mcp_tool(cfg)+ assert result.client_type == "stdio"+ assert result.params["command"] == "python"- def test_explicit_stdio_type_rejected(self):+ def test_stdio_with_env(self):cfg = json.dumps({- "name": "my-tool",- "type": "stdio",+ "name": "env-tool","command": "node",- "args": ["server.js"],+ "args": ["s.js"],+ "env": {"KEY": "VAL"},})- with pytest.raises(ValueError, match="仅支持|stdio|已禁用"):- create_mcp_tool(cfg)-- def test_stdio_with_python_rejected(self):- cfg = json.dumps({"name": "py-tool", "command": "python", "args": ["-m", "mymod"]})- with pytest.raises(ValueError, match="仅支持|stdio|已禁用"):- create_mcp_tool(cfg)+ result = create_mcp_tool(cfg)+ assert result.params["env"] == {"KEY": "VAL"}- def test_npx_config_rejected(self):+ def test_stdio_with_cwd(self):cfg = json.dumps({- "name": "npx-tool",- "command": "npx",- "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],+ "name": "cwd-tool",+ "command": "node",+ "args": ["s.js"],+ "cwd": "/tmp/work",})- with pytest.raises(ValueError, match="仅支持|stdio|已禁用"):- create_mcp_tool(cfg)+ result = create_mcp_tool(cfg)+ assert result.params["cwd"] == "/tmp/work"- def test_uvx_config_rejected(self):- cfg = json.dumps({"name": "uvx-tool", "command": "uvx", "args": ["mcp-server-fetch"]})- with pytest.raises(ValueError, match="仅支持|stdio|已禁用"):- create_mcp_tool(cfg)+ def test_stdio_with_server_id(self):+ cfg = json.dumps({+ "name": "sid-tool",+ "server_id": "custom-id",+ "command": "node",+ "args": ["s.js"],+ })+ result = create_mcp_tool(cfg)+ assert result.server_id == "custom-id"def test_missing_name_raises(self):with pytest.raises(ValueError, match="缺少 'name'"):create_mcp_tool(json.dumps({"command": "node", "args": ["s.js"]}))- def test_array_stdio_config_rejected(self):+ def test_missing_command_for_stdio_raises(self):+ with pytest.raises(ValueError, match="缺少"):+ create_mcp_tool(json.dumps({"name": "t", "command": "", "args": ["s.js"]}))++ def test_invalid_args_type_raises(self):+ with pytest.raises(ValueError, match="必须是列表"):+ create_mcp_tool(json.dumps({"name": "t", "command": "node", "args": "not-list"}))++ def test_unsupported_command_raises(self):+ with pytest.raises(ValueError, match="不支持"):+ create_mcp_tool(json.dumps({"name": "t", "command": "ruby", "args": ["s.rb"]}))++ def test_dangerous_eval_arg_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ create_mcp_tool(json.dumps({"name": "t", "command": "node", "args": ["-e", "code"]}))++ def test_dangerous_command_arg_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ create_mcp_tool(json.dumps({"name": "t", "command": "python", "args": ["-c", "print(1)"]}))++ def test_array_config(self):cfg = json.dumps([{"name": "arr-tool", "command": "node", "args": ["s.js"]}])- with pytest.raises(ValueError, match="仅支持|stdio|已禁用"):- create_mcp_tool(cfg)+ result = create_mcp_tool(cfg)+ assert result.server_name == "arr-tool"def test_empty_array_raises(self):with pytest.raises(ValueError, match="不能为空"):@@ -258,6 +458,56 @@ class TestCreateMcpToolRejectsStdio:create_mcp_tool("not-json")+class TestCreateMcpToolNpxUvx:+ def test_npx_config(self):+ cfg = json.dumps({+ "name": "npx-tool",+ "command": "npx",+ "args": ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],+ })+ result = create_mcp_tool(cfg)+ assert result.client_type == "stdio"+ assert result.params["command"] == "npx"+ assert result.params["args"] == ["-y", "@modelcontextprotocol/server-filesystem", "/tmp"]++ def test_uvx_config(self):+ cfg = json.dumps({"name": "uvx-tool", "command": "uvx", "args": ["mcp-server-fetch"]})+ result = create_mcp_tool(cfg)+ assert result.client_type == "stdio"+ assert result.params["command"] == "uvx"+ assert result.params["args"] == ["mcp-server-fetch"]++ def test_npx_with_env_and_cwd(self):+ cfg = json.dumps({+ "name": "npx-env",+ "command": "npx",+ "args": ["-y", "@scope/pkg"],+ "env": {"API_KEY": "secret"},+ "cwd": "/some/dir",+ })+ result = create_mcp_tool(cfg)+ assert result.params["env"] == {"API_KEY": "secret"}+ assert result.params["cwd"] == "/some/dir"++ def test_npx_absolute_path(self):+ cfg = json.dumps({"name": "npx-abs", "command": "/usr/local/bin/npx", "args": ["-y", "pkg"]})+ result = create_mcp_tool(cfg)+ assert result.params["command"] == "/usr/local/bin/npx"++ def test_uvx_absolute_path(self):+ cfg = json.dumps({"name": "uvx-abs", "command": r"C:\Users\me\.local\bin\uvx.exe", "args": ["pkg"]})+ result = create_mcp_tool(cfg)+ assert result.params["command"] == r"C:\Users\me\.local\bin\uvx.exe"++ def test_npx_dangerous_eval_arg_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ create_mcp_tool(json.dumps({"name": "t", "command": "npx", "args": ["-e", "code"]}))++ def test_uvx_dangerous_command_arg_blocked(self):+ with pytest.raises(ValueError, match="危险标志"):+ create_mcp_tool(json.dumps({"name": "t", "command": "uvx", "args": ["-c", "print(1)"]}))++class TestCreateMcpToolSse:def test_basic_sse(self):cfg = json.dumps({@@ -282,16 +532,6 @@ class TestCreateMcpToolSse:assert result.auth_headers == {"Authorization": "Bearer xxx"}assert result.auth_query_params == {"token": "yyy"}- def test_sse_headers_alias_maps_to_auth_headers(self):- cfg = json.dumps({- "name": "sse-headers-alias",- "type": "sse",- "url": "http://127.0.0.1:3001/sse",- "headers": {"Authorization": "Bearer from-headers"},- })- result = create_mcp_tool(cfg)- assert result.auth_headers == {"Authorization": "Bearer from-headers"}-def test_sse_missing_url_raises(self):with pytest.raises(ValueError, match="需要 url"):create_mcp_tool(json.dumps({"name": "sse-no-url", "type": "sse"}))@@ -409,6 +649,17 @@ class TestCreateMcpToolOpenapi:class TestCreateMcpToolTimeoutPassthrough:"""前端下发的 timeout_s 必须透传进 params(供 _run_mcp_worker 按连接器超时调用)。"""+ def test_stdio_timeout_s_passthrough(self):+ cfg = json.dumps({+ "name": "slow-stdio",+ "command": "node",+ "args": ["s.js"],+ "timeout_s": 120,+ })+ result = create_mcp_tool(cfg)+ assert result.client_type == "stdio"+ assert result.params["timeout_s"] == 120+def test_sse_timeout_s_passthrough(self):cfg = json.dumps({"name": "slow-sse",@@ -434,125 +685,19 @@ class TestCreateMcpToolTimeoutPassthrough:def test_no_timeout_s_no_param(self):cfg = json.dumps({"name": "no-timeout",- "type": "sse",- "url": "http://127.0.0.1:3001/sse",+ "command": "node",+ "args": ["s.js"],})result = create_mcp_tool(cfg)assert "timeout_s" not in result.paramsclass TestCreateMcpToolDefaultType:- def test_no_type_rejected(self):+ def test_no_type_defaults_to_stdio(self):cfg = json.dumps({"name": "default-tool","command": "node","args": ["s.js"],})- with pytest.raises(ValueError, match="仅支持"):- create_mcp_tool(cfg)---class TestBuildMcpServerConfigRejectsStdio:- def test_stdio_transport_returns_none(self):- cfg = build_mcp_server_config(- {- "name": "local",- "transport": "stdio",- "command": "node",- "args": ["s.js"],- }- )- assert cfg is None---class TestBuildMcpServerConfigAuthHeaders:- """企业模板 headers / 连接器 auth_headers → SDK auth_headers。"""-- def test_enterprise_headers_map_to_auth_headers(self):- cfg = build_mcp_server_config(- {- "name": "qa-bearer-streamable-http",- "transport": "streamable-http",- "url": "http://192.168.1.96:18016/mcp",- "headers": {"Authorization": "Bearer sds-dev-mcp-bearer-token"},- "timeout_s": 10,- "enabled": True,- },- server_id_scope="jiuwenswarm",- )- assert cfg is not None- assert cfg.auth_headers == {- "Authorization": "Bearer sds-dev-mcp-bearer-token",- }- assert "headers" not in (cfg.params or {})- assert cfg.params.get("timeout_s") == 10-- def test_fractional_timeout_s_preserved(self):- cfg = build_mcp_server_config(- {- "name": "frac-timeout",- "transport": "streamable-http",- "url": "http://192.168.1.96:18014/mcp",- "timeout_s": 0.5,- }- )- assert cfg is not None- assert cfg.params.get("timeout_s") == 0.5-- def test_auth_headers_alias_preferred_over_headers(self):- cfg = build_mcp_server_config(- {- "name": "prefer-auth",- "transport": "sse",- "url": "http://192.168.1.96:18015/sse",- "headers": {"Authorization": "Bearer from-headers"},- "auth_headers": {"Authorization": "Bearer from-auth-headers"},- }- )- assert cfg is not None- assert cfg.auth_headers == {- "Authorization": "Bearer from-auth-headers",- }-- def test_query_params_map_to_auth_query_params(self):- cfg = build_mcp_server_config(- {- "name": "qa-query",- "transport": "http",- "url": "http://example.com/mcp",- "query_params": {"token": "abc"},- }- )- assert cfg is not None- # http 别名须归一为 SDK 注册名,否则 ResourceMgr 报 Unsupported MCP client type- assert cfg.client_type == "streamable-http"- assert cfg.auth_query_params == {"token": "abc"}-- def test_http_alias_maps_to_streamable_http(self):- """对齐 TC_MCP_CALL_005:transport=http 不得原样传给 SDK。"""- for alias in ("http", "HTTP", "streamable_http"):- cfg = build_mcp_server_config(- {- "name": "qa-streamable-http",- "transport": alias,- "url": "http://192.168.1.96:18016/mcp",- "timeout_s": 10,- "enabled": True,- },- server_id_scope="jiuwenswarm",- )- assert cfg is not None, alias- assert cfg.client_type == "streamable-http", alias- assert cfg.params.get("timeout_s") == 10-- def test_non_dict_headers_ignored(self):- cfg = build_mcp_server_config(- {- "name": "bad-headers",- "transport": "sse",- "url": "http://example.com/sse",- "headers": "not-a-dict",- }- )- assert cfg is not None- assert cfg.auth_headers == {}+ result = create_mcp_tool(cfg)+ assert result.client_type == "stdio"diff --git a/tests/unit_tests/common/test_mcp_handler_uses_shared_builder.py b/tests/unit_tests/common/test_mcp_handler_uses_shared_builder.pydeleted file mode 100644index c89e57b379..0000000000--- a/tests/unit_tests/common/test_mcp_handler_uses_shared_builder.py+++ /dev/null@@ -1,74 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""/mcp handler 须走 build_mcp_server_config(鉴权与 http 别名)。"""--from __future__ import annotations--import importlib.util-from pathlib import Path-from types import SimpleNamespace--import pytest---def _load_mcp_handler_module():- """绕过 handlers 包 __init__(会拉 harness rails)。"""- path = (- Path(__file__).resolve().parents[3]- / "jiuwenswarm"- / "server"- / "handlers"- / "mcp.py"- )- spec = importlib.util.spec_from_file_location("jws_mcp_handler_isolated", path)- assert spec is not None and spec.loader is not None- module = importlib.util.module_from_spec(spec)- spec.loader.exec_module(module)- return module---async def test_fetch_mcp_tools_maps_headers_and_http_alias(monkeypatch: pytest.MonkeyPatch) -> None:- mcp_handler = _load_mcp_handler_module()- captured: dict = {}-- class FakeClient:- async def connect(self):- return True-- async def list_tools(self):- return [- SimpleNamespace(- id="t1",- name="qa_echo",- description="echo",- input_params={"type": "object"},- )- ]-- async def disconnect(self):- return True-- def fake_create_client(cfg):- captured["cfg"] = cfg- return FakeClient()-- monkeypatch.setattr(- "openjiuwen.core.runner.resources_manager.tool_manager.ToolMgr._create_client",- staticmethod(fake_create_client),- )-- tools = await mcp_handler._fetch_mcp_tools_from_config(- {- "name": "qa-noauth",- "transport": "http",- "url": "http://192.168.1.96:18014/mcp",- "headers": {"Authorization": "Bearer sds-token"},- "timeout_s": 0.5,- }- )- assert len(tools) == 1- cfg = captured["cfg"]- assert cfg.client_type == "streamable-http"- assert cfg.auth_headers == {"Authorization": "Bearer sds-token"}- assert cfg.params.get("timeout_s") == 0.5- assert "headers" not in (cfg.params or {})diff --git a/tests/unit_tests/gateway/test_mcp_template_transport_alias.py b/tests/unit_tests/gateway/test_mcp_template_transport_alias.pydeleted file mode 100644index f6d4b268a0..0000000000--- a/tests/unit_tests/gateway/test_mcp_template_transport_alias.py+++ /dev/null@@ -1,84 +0,0 @@-# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.-"""Gateway MCP 模板 transport 别名与 SDK 对齐(TC_MCP_CALL_005)。"""--from __future__ import annotations--import importlib-import sys-from pathlib import Path-from types import ModuleType-from typing import Any--import pytest---def _import_template_schemas() -> Any:- parent_name = "jiuwenswarm.loaded_extension"- package_name = f"{parent_name}.manager_config_receiver"- extension_root = (- Path(__file__).resolve().parents[3]- / "packages"- / "jiuwenclaw-ee"- / "gateway"- / "extensions"- / "manager_config_receiver"- )- if parent_name not in sys.modules:- parent = ModuleType(parent_name)- parent.__path__ = [] # type: ignore[attr-defined]- sys.modules[parent_name] = parent- if package_name not in sys.modules:- package = ModuleType(package_name)- package.__path__ = [str(extension_root)] # type: ignore[attr-defined]- package.__package__ = package_name- sys.modules[package_name] = package- return importlib.import_module(f"{package_name}.schemas.template_schemas")--- "raw, expected",- [- ("http", "streamable-http"),- ("HTTP", "streamable-http"),- ("streamable_http", "streamable-http"),- ("streamable-http", "streamable-http"),- ("sse", "sse"),- ],-)-def test_validate_mcp_entry_normalizes_http_alias(raw: str, expected: str) -> None:- validate_mcp_entry = _import_template_schemas().validate_mcp_entry- out = validate_mcp_entry(- {- "name": "qa-streamable-http",- "transport": raw,- "url": "http://192.168.1.96:18016/mcp",- "timeout_s": 10,- }- )- assert out["transport"] == expected- assert out["name"] == "qa-streamable-http"---def test_validate_mcp_entry_rejects_unknown_transport() -> None:- validate_mcp_entry = _import_template_schemas().validate_mcp_entry- with pytest.raises(ValueError, match="mcp_entry.transport must be one of"):- validate_mcp_entry(- {- "name": "bad",- "transport": "websocket",- "url": "http://example.com/mcp",- }- )---def test_validate_mcp_entry_rejects_stdio() -> None:- validate_mcp_entry = _import_template_schemas().validate_mcp_entry- with pytest.raises(ValueError, match="mcp_entry.transport must be one of"):- validate_mcp_entry(- {- "name": "local",- "transport": "stdio",- "command": "node",- "args": ["server.js"],- }- )