JiuwenSwarm is an intelligent AI Agent built on openJiuwen. It extends the powerful capabilities of large language models directly to your fingertips through various communication apps you use daily.
Python
fix(common): 修复远程 MCP 跨任务生命周期与取消清理
duhengluckye25009226e38
diff --git a/jiuwenswarm/common/AGENTS.md b/jiuwenswarm/common/AGENTS.mdindex a7d6c2abd8..1523b38325 100644--- a/jiuwenswarm/common/AGENTS.md+++ b/jiuwenswarm/common/AGENTS.md@@ -144,7 +144,7 @@ common/│├── mcp_config.py # MCP 配置→SDK 转换 + 安全准入 + 请求级 worker 池(~2720 行)├── mcp_server_registry.py # 进程内 MCP 注册表 + 全局 worker 池 + remote 周期扫描-├── mcp_call_timeout_patch.py # 上游补丁:调用超时 + 死会话作废重连(wait_for 不变量)+├── mcp_call_timeout_patch.py # 上游补丁:调用超时 + owner 内清理重连(生命周期归属不变量)├── mcp_tool_list_refresh_patch.py # 上游补丁:工具列表中途刷新(修 ToolMgr/ResourceMgr 三缺陷)│├── model_client_extensions.py # 外部模型 client 动态装载(env 白名单 + EXTENSION_DIRS)@@ -228,7 +228,7 @@ common/8. **上游 monkeypatch 唯一装配点 + 幂等**([[S_09]])。两个 MCP patch 只在`server/runtime/agent_adapter/interface_deep.py` 装配;均带 `_PATCHED` 标记防重复;patch 目标属性名集中为常量(上游改名一处可改)。自建 remote MCP client 必须补打- `_jws_call_timeout` 印章——漏打的后果是超时 patch 的内层 300s 兜底先掐断长调用。+ `_jws_call_timeout` 印章——漏打的后果是超时 patch 的进程级默认 30s 兜底先掐断长调用。9. **配置缓存共享引用禁改 + 联动失效**([[S_08]])。`get_config()` 返回的 dict 是缓存共享引用,消费方禁止原地修改;`local_env_config` 的 tip 写入必须联动失效 config 的ns 缓存(已内置,绕过 `set_os_environ` 直写 os.environ 会破坏该联动)。diff --git a/jiuwenswarm/common/docs/AGENTS.md b/jiuwenswarm/common/docs/AGENTS.mdindex 9d32d4a7fe..630a92bdfa 100644--- a/jiuwenswarm/common/docs/AGENTS.md+++ b/jiuwenswarm/common/docs/AGENTS.md@@ -10,8 +10,8 @@|---|---|---|| `specs/` | 模块设计规约:跨子模块的契约、协议、边界、不变量、修改检查单。**长期有效**,描述"系统是什么样、改代码前必须知道什么"。 | 任何**模块设计规约变动**(契约 / 不变量 / 执行路径 / 信封格式 / 注册表结构 / 配额语义变化)都必须同步修订对应 spec;新规约主题 = 新 spec 文件 || `designs/` | 设计叙事文档:面向**理解**的概览与架构说明(特性文档 + 架构文档),描述"系统为什么这样设计、整体如何运转"。含 mermaid 架构图 / 时序图 / 设计决策表 / 术语表。与 specs 的分工:specs 给**改代码的人**(不变量 / 检查单),designs 给**理解系统的人**(概念 / 原理 / 全景)。 | 重大架构变动(新增子包 / 装配链变化 / 设计决策表新增条目)时同步修订;specs 契约变化若影响叙事准确性(数据流 / 分层 / 决策理由),一并刷新 |-| `features/` | 特性变更归档:一次完整设计/重构/新特性的来龙去脉(决策 + 拒绝的方案)。**只增不删**,描述"为什么这么改"。当前暂无;首次特性变更时建立。 | 每次特性更新提交代码前归档 `F_NN_<slug>.md`;归档日期写进文档元信息 |-| `bugfix/` | 缺陷修复归档:一次线上/测试问题的现象、定位证据、根因与修复决策。**只增不删**,描述"为什么会坏、为什么这样修"。当前暂无;首次缺陷归档时建立。 | 根因涉及契约/不变量、或定位过程值得复用的缺陷修复必须归档;契约变了同步修订 spec |+| `features/` | 特性变更归档:一次完整设计/重构/新特性的来龙去脉(决策 + 拒绝的方案)。**只增不删**,描述"为什么这么改"。 | 每次特性更新提交代码前归档 `F_NN_<slug>.md`;归档日期写进文档元信息 |+| `bugfix/` | 缺陷修复归档:一次线上/测试问题的现象、定位证据、根因与修复决策。**只增不删**,描述"为什么会坏、为什么这样修"。 | 根因涉及契约/不变量、或定位过程值得复用的缺陷修复必须归档;契约变了同步修订 spec |`specs/` 是状态快照(描述当前),`features/` 是变更日志(描述过程),`bugfix/` 是故障档案(描述失效),`designs/` 是入门叙事(描述全貌与理由)。当 spec 改了,通常对应一份diff --git a/jiuwenswarm/common/docs/bugfix/B_02_remote-mcp-task-ownership.md b/jiuwenswarm/common/docs/bugfix/B_02_remote-mcp-task-ownership.mdnew file mode 100644index 0000000000..cdc7b7d540--- /dev/null+++ b/jiuwenswarm/common/docs/bugfix/B_02_remote-mcp-task-ownership.md@@ -0,0 +1,70 @@+# 远程 MCP 跨任务退出 AnyIO 上下文导致取消回调持续运行++## 元信息++| 项 | 值 |+|---|---|+| 日期 | 2026-10-28 |+| 严重程度 | 高:后台工具扫描亦可触发,业务结束后仍持续占用 CPU |+| 范围 | mcp_config.py、mcp_call_timeout_patch.py、mcp_server_registry.py |+| 关联 spec | S_09_mcp-integration.md |++## 现象与根因++Streamable HTTP 在 connect 调用任务上进入 transport 和 ClientSession 的 AnyIO+TaskGroup。旧实现仅把 connect 交给 asyncio.wait_for,disconnect 却在调用方执行。+Python 3.11 的 wait_for 创建子任务,因而破坏上下文必须在原任务退出的不变量。+Python 3.12 的正超时实现直接 await 协程,可能掩盖该错误,验证必须覆盖 3.11。++超时补丁另有同构问题:丢弃旧 stack 后,等宿主任务结束再新建任务 aclose。+延迟执行不会转移 AnyIO 上下文归属;SSE 已自行关闭资源,重放旧 stack 还可能重复退出。+因此正常发现、调用超时、重连和后台扫描都需要一起检查。++## 决策++- 发现封装完整生命周期,connect/list 各保留原阶段超时,外层等待整个生命周期。+- 长连接复用原池化 worker,connect 与可重连的调用使用 asyncio.timeout 留在 owner。+ 初始化取消也排干队列,避免首个调用者永远等不到结果。+- ToolMgr 的 HTTP client 没有现成 owner,增加一个仅限该入口的串行任务;SSE 仍用+ SDK owner,不叠加任务;补齐该 owner 在建连取消时的 finally 清理,避免断开排队等+ initialize 的长超时。排队调用者取消不打断其它正在运行的调用。+- SSE public disconnect 在命令返回后还负责停止 owner:将这个完整 API 流程保留到+ 完成,防止等待者取消后只关资源却遗留空闲 owner。此处新增的是 API 等待任务,+ 传输与 session 的 __aexit__ 仍在原 SDK owner 执行。+- 已进入取消处理后,屏蔽等待者的后续取消向 owner 传播,等待同任务清理完成再+ re-raise 原取消。AnyIO shield 仅包等待过程,避免外层取消 scope 反复唤醒等待循环。+- 取消按原异常传播。超时保留 SDK timeout/read timeout 传递,死会话仍最多重试一次。+- disconnect 成功后才重置状态;False 或异常上报,不再延迟 aclose 或丢弃未关资源。+ 同步 force_invalidate 只标记不可复用,实际关闭由 owner 执行。owner 已结束而资源+ 仍未清时,禁止换新 owner 复用 client。+- registry 等待整次发现结束才返回,扫描停止时先等发现 finally,再关闭全局 worker;+ 没启动 scanner 也必须关闭已有 worker。++## 拒绝的方案++不改 AnyIO 私有状态,不全局改 wait_for,不删除超时,不吞取消或断开失败。+不把每个池化连接再包一层通用 owner 框架;只有没有 owner 的 ToolMgr HTTP 入口新增任务。+不修改 agent-core;SSE 内部的资源关闭职责继续由 SDK 承担。++## 验证++`test_mcp_remote_lifecycle.py` 使用真实 SDK 客户端、真实 AnyIO TaskGroup 和内存传输,+不访问外网、不需要凭据。故意跨任务退出的反例放在有界子进程,避免污染 pytest 循环。+成功、initialize 失败/超时、发现超时/取消、worker 退出/重建、ToolMgr 重连/取消、+registry 扫描超时/停止均检查资源子任务已结束,取消回调在若干轮事件循环后不再增长。+修复前的 mcp_config 在 Python 3.11 下运行同一发现回归用例,产生明确的+`Attempted to exit cancel scope in a different task than it was entered in`,并因+进入/退出任务不一致而失败。修复后 Python 3.11 和 3.12 各通过 358 项相关测试,+包含 41 项生命周期用例及既有 MCP timeout/recovery、配置、工具刷新、registry、+request-scoped、retire、schema cache、browser isolation 和 stdio 回归。+继续审查中,先用事件控制的慢清理复现两处遗漏:SSE 断开期间取消留下空闲 owner;+HTTP 调用者第二次取消再次中断 owner 清理。修复后同时覆盖两种 transport 的建连/+调用重复取消,以及 AnyIO 外层超时取消,检查清理未被二次取消且无遗留任务。+新增生命周期测试通过 Ruff;修改模块通过致命语法/未定义名称检查及 git diff --check。++## 已知边界++模拟传输证明已覆盖路径的任务归属及清理,不等价于真实服务和所有 SDK 版本的集成验证。+底层 disconnect 若自行返回 False、抛错或不响应取消,Jiuwenswarm 不能承诺资源全部关闭;+此时会报告失败并保留不可复用状态,不再伪报成功或异步跨任务补关。+模型断流、专家团长耗时未被该证据链证明与本取消忙循环直接相关。diff --git a/jiuwenswarm/common/docs/bugfix/B_03_remote-mcp-cancellation-boundaries.md b/jiuwenswarm/common/docs/bugfix/B_03_remote-mcp-cancellation-boundaries.mdnew file mode 100644index 0000000000..8103174abd--- /dev/null+++ b/jiuwenswarm/common/docs/bugfix/B_03_remote-mcp-cancellation-boundaries.md@@ -0,0 +1,85 @@+# 远程 MCP 内部取消误传给调用者且取消后的清理等待无上限++## 元信息++| 项 | 值 |+|---|---|+| 日期 | 2026-10-28 |+| 严重程度 | 高:单个连接器失败可能中断请求,清理失活可能阻塞取消 |+| 范围 | mcp_config.py、mcp_call_timeout_patch.py |+| 测试基线 | Python 3.11 / 3.12 各 366 项相关测试通过 |+| 关联 spec | S_09_mcp-integration.md,N7 |+| 评审来源 | [PR #9175](https://gitcode.com/openJiuwen/jiuwenswarm/pull/9175/discuss) |++## 现象++worker 初始化被取消时,排队调用者收到 CancelledError,无法区分工具初始化失败和+用户主动取消。发现阶段的内部取消也可跳出连接器隔离边界。SSE public disconnect+自身取消时,shield 向等待者抛出相同异常,原实现把它误判为等待者取消。++清理等待持续屏蔽取消,若 owner 无回执或底层任务不退出,取消流程便无限等待。+本修复延续 B_02 的任务归属约束,补齐异常分类和清理等待的时间边界。++## 根因++- 初始化分支捕获 BaseException 后,直接把原异常写入所有排队请求的 future;+ worker 的生命周期取消因而变成业务调用者的取消。+- discovery 只捕获 Exception,内部 CancelledError 穿过隔离层;SSE 断开等待+ 则没有检查当前等待者是否真的收到 cancel 请求。+- `_finish_mcp_task_after_cancel` 在 task.done 前无限循环 shield,没有截止时间。+ 单纯为外层添加超时不能终止这个吞掉后续取消的等待循环。++## 决策++- worker 初始化中的非 Exception 异常映射为 McpWorkerStoppedError,通知全部排队+ 请求并完成队列记账;worker 自身继续传播原异常。+- discovery 检查当前任务的 cancelling 状态:真实外部取消继续传播,内部取消+ 记录警告并返回空发现结果,仅跳过当前连接器。+- SSE 断开内部取消映射为普通清理失败,并标记连接不可复用;等待者真实取消仍+ 在清理后传播原 CancelledError。+- 清理等待最多 10 秒,超时取消目标后最多再等待 1 秒;后续取消不重置截止时间。+ SSE 从 public disconnect 启动时计时,避免外层超时后额外等待完整清理预算。+ asyncio.wait 只等待任务,不在等待者取消时顺带取消目标。AnyIO shield 仅保护等待。+- 超时报告清理失败并保留不可复用状态;不丢弃资源句柄。仍不响应取消的任务若+ 后续结束,取走异常以免出现未处理任务异常,资源清理仍由原 owner 负责。+- 补充清理失败后恢复的断言:后续 disconnect 成功时允许重连,替换旧 session,+ 清除 needs_reconnect,避免失败状态永久阻止恢复。++## 同构路径检查++| 入口 | 确认结果 |+|---|---|+| 池化 worker 的 `_enter_remote_mcp_session` | HTTP 生命周期在 worker;SSE 使用统一 owner 清理包装,初始化排队失败统一映射 |+| `_list_remote_mcp_connector_tools` | 完整发现生命周期留在同一任务,SSE 使用同一包装,外层区分内部与外部取消 |+| ToolMgr `_create_client` 补丁 | HTTP 独立 owner 与 SSE SDK owner 共用有界清理等待,清理失败标记不可复用 |+| DeepAdapter 安装入口 | `interface_deep.py` 仍统一安装补丁,没有新增绕过路径 |+| registry 扫描、请求级连接器 | 通过既有取消隔离、停止、worker retire 回归,未改变关闭所属任务 |++## 拒绝的方案++不统一吞掉 CancelledError,否则用户取消会失效;不直接向排队调用者重放 worker+取消,否则单个工具失败会被误认为请求取消。不对清理使用无限 shield,也不在超时+后无界 await 被取消的任务。不在其它任务补做 aclose、不修改 AnyIO 私有状态,避免+重新引入 B_02 的跨任务退出问题。++## 验证++先运行内部取消、worker 初始化取消和清理预算回归,在原实现上得到 10 项失败。+修复后生命周期与恢复测试共 71 项通过。扩大到 MCP timeout、配置、工具刷新、+registry、request-scoped、retire、schema cache、browser isolation 和 stdio,+Python 3.11 和 3.12 各 366 项通过。++生命周期测试通过完整 Ruff 检查;修改模块及恢复测试通过致命语法和未定义名称+检查,git diff --check 通过。恢复测试文件完整 Ruff 的 17 项历史告警与 HEAD+一致,本次未新增。++新增测试覆盖双 transport 的 connect/list 内部取消、多个排队请求排干、SSE 内部+断开取消、断开无回执,以及目标忽略 cancel 的有界收尾。既有真实 SDK + 内存 AnyIO+传输用例继续验证真实外部取消、重复取消和 AnyIO 外层取消不破坏 owner 归属。++## 已知遗留++Python 无法强制终止忽略取消的协程;超时后保证等待者能退出并报告失败,不承诺底层+资源已全部释放。不能安全复用的 client 应被替换,不能跨任务强制关闭其上下文。+测试不访问真实远程服务;测试环境对缺失的 openjiuwen_runtime DB 模块使用兼容桩,+MCP 生命周期用例使用本机 agent-core 的真实客户端,结果不代表所有 SDK 版本的集成验证。diff --git a/jiuwenswarm/common/docs/bugfix/B_04_remote-mcp-internal-call-cancellation.md b/jiuwenswarm/common/docs/bugfix/B_04_remote-mcp-internal-call-cancellation.mdnew file mode 100644index 0000000000..0a63df3f4b--- /dev/null+++ b/jiuwenswarm/common/docs/bugfix/B_04_remote-mcp-internal-call-cancellation.md@@ -0,0 +1,47 @@+# MCP 工具调用内部取消被误传为业务请求取消++## 元信息++| 项 | 值 |+|---|---|+| 日期 | 2026-10-28 |+| 严重程度 | 高:工具传输故障可能中断业务请求 |+| 范围 | mcp_call_timeout_patch.py,SSE / Streamable HTTP |+| 测试基线 | Python 3.11 / 3.12 各 380 项相关回归通过 |+| 关联 spec | S_09_mcp-integration.md,N7 |++## 现象与根因++PR #9175 整体复核发现,生命周期修复后 `_invoke_with_cleanup` 无条件传播+CancelledError。底层单次 I/O 自行抛出取消时,没有收到 cancel 请求的业务调用者+也会被取消,绕过 MCPTool.invoke 的普通异常处理。发现阶段和 worker 初始化的+取消隔离没有覆盖这个调用阶段入口。++## 决策++- 单次 I/O 取消时检查当前等待任务的取消计数。真实外部取消仍在所属任务清理后传播。+- 内部取消清理成功后映射为专用 RuntimeError 子类,复用既有一次重连重试分支。+ 第二次内部取消返回普通工具错误,不无限重试;行为仍是 at-least-once。+- 清理失败返回普通清理错误并保留不可复用状态,不重连。清理期间新增的真实取消+ 优先传播,不被内部错误分类覆盖。+- ToolMgr 两种传输、池化 worker 和发现都沿用同一 call_tool/list_tools 类方法补丁;+ 唯一安装入口仍为 interface_deep。未改变 owner 分配、连接及工具调用超时。++## 拒绝的方案++不将所有 CancelledError 都转换为普通异常,否则用户取消和超时会失效;不在清理+失败后强制重连,也不把清理移动到后台任务。使用异常类型区分可重试的内部取消,+避免通过伪造死会话错误文本触发重试。++## 验证++修复前新增及调整的 11 项核心断言失败。修复后新增 14 项测试,覆盖双传输的+call_tool/list_tools 一次及持续内部取消、worker 后续调用恢复、清理失败阻止重连、+内部取消清理期间发生外部取消。既有重复取消、超时、任务归属、后台任务及取消回调+收敛检查继续通过。模拟内存传输使用真实 AnyIO TaskGroup,不依赖外网或凭据。++## 已知遗留++本次只处理整体 review 的 P1;P2(HTTP 建连失败后直接等待 owner,取消可打断清理)+在本次修复中未修改,后续由 B_05_remote-mcp-failed-connect-cleanup.md 修复。+模型断流与专家团长耗时未证明由本问题直接导致。diff --git a/jiuwenswarm/common/docs/bugfix/B_05_remote-mcp-failed-connect-cleanup.md b/jiuwenswarm/common/docs/bugfix/B_05_remote-mcp-failed-connect-cleanup.mdnew file mode 100644index 0000000000..b52a74bef4--- /dev/null+++ b/jiuwenswarm/common/docs/bugfix/B_05_remote-mcp-failed-connect-cleanup.md@@ -0,0 +1,50 @@+# HTTP 建连失败后的等待者取消打断 owner 清理并阻止重连++## 元信息++| 项 | 值 |+|---|---|+| 日期 | 2026-10-29 |+| 严重程度 | 中:清理被打断后客户端无法再次连接 |+| 范围 | mcp_call_timeout_patch.py,ToolMgr Streamable HTTP |+| 测试基线 | Python 3.11 / 3.12 各 386 项相关回归通过 |+| 关联 spec | S_09_mcp-integration.md,N7 |++## 现象与根因++建连超时后,owner 先向调用者的 future 发布异常,再在 finally 中关闭连接。+`_StreamableHttpOwner.submit` 的异常分支直接 await owner;此时调用者被取消,+取消会传入正在执行上下文退出的 owner。owner 结束后残留 session/client 引用,+后续连接被 previous owner cleanup incomplete 检查拒绝。++原有取消处理保护的是等待操作结果的分支,没有保护已经收到操作失败、正在等待+清理结束的分支。单次取消、重复取消以及 AnyIO 外层取消均可复现。++## 决策++- 建连/断开失败后使用 shield 等待既有 owner,不迁移上下文或重新执行关闭。+- 等待者真实取消时,复用有界清理等待,使用进入该异常分支时记录的截止时间;+ 不再次取消正在清理的 owner,清理结束后继续传播调用者取消。+- 预算耗尽后才取消 owner,并有界收尾;失败标记为不可复用并记录日志。+- owner 自身取消不能伪装为调用者取消,保留原操作异常并报告清理失败。+- 同构检查:此分支同时覆盖 connect/disconnect 失败;原有操作中取消分支、SSE+ owner 包装及 pooled worker 不变,共用清理 helper 的预算语义不变。++## 拒绝的方案++不再次 cancel 正在清理的 owner,不跨任务补做 aclose,不清空失败资源句柄以绕过+重连检查;不无限 shield,也不吞掉真实外部取消。++## 验证++新增 6 项回归:无外部取消时保留建连超时;单次、重复、AnyIO 外层取消后原 owner+完成清理,并验证同一客户端重连及工具调用成功;清理预算耗尽后有界返回并拒绝复用;+owner 自身取消保留原操作错误。前三种外部取消场景在修复前失败,修复后通过。++真实 SDK 客户端配合模拟内存传输与真实 AnyIO TaskGroup,检查进入/退出任务一致、+session 及后台任务结束、清理后取消回调不再增长。全部测试离线运行。++## 已知遗留++底层协程拒绝响应取消时,仍只能有界结束等待并报告清理失败,不能强制保证资源释放。+本次不涉及尚未证明与该问题直接相关的模型断流或专家团长耗时。diff --git a/jiuwenswarm/common/docs/bugfix/B_06_mcp-test-patch-isolation.md b/jiuwenswarm/common/docs/bugfix/B_06_mcp-test-patch-isolation.mdnew file mode 100644index 0000000000..9bc7062007--- /dev/null+++ b/jiuwenswarm/common/docs/bugfix/B_06_mcp-test-patch-isolation.md@@ -0,0 +1,51 @@+# 全量 UT 已安装 MCP 补丁时测试重复包装导致锁等待超时++## 元信息++| 项 | 值 |+|---|---|+| 日期 | 2026-10-30 |+| 严重程度 | 中:PR CI 的 33 项 MCP 单测失败 |+| 范围 | MCP timeout、recovery、lifecycle 测试 fixture |+| 测试基线 | Python 3.11 双进程、Python 3.12 各 387 项 MCP 回归通过 |+| 证据 | [PR #9175 UT 报告](https://openjiuwen-ci.obs.cn-north-4.myhuaweicloud.com/jiuwenswarm/ut/9175/unit_test_report.html),2026-10-29 11:17:56 |++## 现象与根因++CI 使用 Python 3.11.5、AnyIO 4.15.1、pytest-xdist,报告 12988 项通过、33 项失败。+失败均位于 test_mcp_call_timeout_patch.py 与 test_mcp_remote_lifecycle.py。+调用栈显示一层超时 wrapper 已持有客户端 I/O 锁,内部另一层 wrapper 再次获取同一锁,+最终超时;重复安装 ToolMgr factory 还可能叠加 owner。++测试 fixture 清空了 `_PATCHED` 和 wrapper 注册集合,但保留了前序 adapter 已安装的+类方法与 factory。重新 apply 因而不是从原始 SDK 开始。recovery fixture 同时存在+只清标记、没有完整恢复 SDK 绑定的问题。独立小范围测试缺少前序补丁安装,未触发故障。++## 决策++- timeout 与 lifecycle fixture 遇到已安装补丁直接复用,不重置 guard 后重复包装。+- recovery fixture 同时快照并还原 SDK 方法、ToolMgr factory、补丁标记与注册集合。+- AbilityManager 模块绑定、Tool invoke 和子类钩子恢复进入测试时的精确状态;不能+ 无条件退回原始 invoke,否则会移除前序已安装的超时桥。+- 增加独立进程回归:收集结束后提前安装生产补丁,交错运行 recovery、timeout 和+ lifecycle 用例,并检查整个测试结束后的方法绑定和 guard 与安装后相同。++## 拒绝的方案++不放宽生产超时、不跳过失败用例、不仅提高测试时间阈值,也不为测试重复安装而改变+生产补丁的生命周期结构。问题在 fixture 的状态隔离,应成对恢复绑定与标记。++## 验证++修复前,提前安装补丁即可稳定复现 SSE、HTTP 正常发现两项失败。修复后,在相同+预安装条件下 Python 3.11 双进程和 Python 3.12 的 387 项 MCP 回归全部通过;新增+子进程回归验证实际安装状态没有被测试污染。公共模块另有 536 项通过。++公共模块全量收集受本机缺失 openjiuwen_runtime.foundation.security 限制,因此+536 项结果排除了 test_link_mtls.py;没有将其计为通过。未重跑远端完整 13062 项+UT,仍需推送后由 CI 确认。静态致命错误检查与 git diff --check 通过。++## 边界++本修复处理 UT 失败,与 P2 清理等待修复一同提交。CLA 由提交者处理;CI 报告另有+开源合规失败,其详情页面公开读取被拦截,本次不宣称该项已解决。diff --git a/jiuwenswarm/common/docs/bugfix/B_07_mcp-wrapper-identity-and-locked-sdk.md b/jiuwenswarm/common/docs/bugfix/B_07_mcp-wrapper-identity-and-locked-sdk.mdnew file mode 100644index 0000000000..92f4114830--- /dev/null+++ b/jiuwenswarm/common/docs/bugfix/B_07_mcp-wrapper-identity-and-locked-sdk.md@@ -0,0 +1,55 @@+# MCP 包装守卫重置后可叠加包装,锁定 SDK 仍存在取消与清理兼容缺口++## 元信息++| 项 | 值 |+|---|---|+| 日期 | 2026-10-30 |+| 范围 | mcp_call_timeout_patch.py,timeout/lifecycle/isolation 测试 |+| 严重程度 | 高:递归 I/O 锁等待及旧 SDK 清理可导致测试或请求挂起 |+| SDK 基线 | uv.lock 中的 agent-core 3460150aa5f319b0b8f84a4ed10eec0a08b0feb1 |+| 关联 spec | S_09_mcp-integration.md,N7 |++## 证据与根因++清空 `_PATCHED` 和注册集合后再次 apply,会在仍有包装的方法/factory 上叠加一层。+新增的连续重装回归在第二次安装即发现函数身份改变;内外层共享不可重入 I/O 锁,+会形成相互等待。fixture 的状态恢复不能替代实际绑定的幂等性检查。++本轮将 SDK 导出到临时目录,用 PYTHONPATH 对齐 uv.lock 中的提交,未修改 SDK 仓库。+同时发现两个独立问题:旧 HTTP connect 捕获 BaseException 并返回 False,吞掉外部+取消和超时取消;旧 SSE `_do_disconnect` 用 wait_for 执行 __aexit__,在 Python 3.11+中跨任务退出 AnyIO scope。仅添加包装标记不足以使锁定 SDK 的生命周期测试通过。++## 决策++- 对 call/list、disconnect、connect read-timeout、传输 factory 和 ToolMgr factory+ 分别设置 `_jws_mcp_wrapper` 标记。重复安装检查当前绑定,注册集合仅记录状态。+ 已包装方法保持原函数身份;已被替换的方法即使注册集合未变,也能正确重新包装。+- 两个 fixture 均取消依赖 `_PATCHED` 的提前返回,继续成对快照与恢复方法和标记。+- 建连返回后检查本次新增的取消请求,恢复旧 SDK 吞掉的取消,保留外层超时语义。+- SSE 沿用 SDK owner 和 AsyncExitStack,在所属任务直接有界 aclose。失败时返回+ False 使 SDK public disconnect 仍完成 owner 停止,外层继续将 False 报错;保留+ 失败标记和资源引用,禁止重复关闭已消费的 stack 或复用失败连接。+- 清理预算测试兼容旧 SDK 在取消后完成整个关闭的情况:有残留资源必须拒绝重连;+ 无残留则验证重连及关闭成功。所有等待有界,不依赖 CPU 百分比或严格耗时断言。++## 拒绝的方案++不只在 fixture 中增加另一个全局布尔守卫,不提高超时或跳过挂起测试,不通过修改+AnyIO 私有状态或升级 SDK 掩盖锁定版本的问题。保留既有 owner 结构,不引入新框架。++## 验证++覆盖连续重装 10 次、原始 SDK 方法被替换后的重装、冷启动/预装补丁两种状态、文件+正序/倒序四种组合,并检查结束后的方法绑定与 guard 精确恢复。生命周期测试继续+检查进入/退出任务相同、后台任务结束、取消回调停止增长,以及失败关闭不会重复执行。++SDK 对齐 uv.lock 后,Python 3.11 双进程和 Python 3.12 的 393 项 MCP 回归均通过。+独立生命周期文件与多文件组合均运行完成。新增测试完整 Ruff、修改模块致命错误检查+及 git diff --check 通过。++## 边界++这修复了已复现的重复包装与锁定 SDK 兼容问题,不代表远端 CI 已重新通过,也不证明+模型断流或专家团长耗时已解决。拒绝响应取消的底层协程仍不能被 Python 强制终止。diff --git a/jiuwenswarm/common/docs/designs/architecture_cn.md b/jiuwenswarm/common/docs/designs/architecture_cn.mdindex e3d4078e6d..797fbef804 100644--- a/jiuwenswarm/common/docs/designs/architecture_cn.md+++ b/jiuwenswarm/common/docs/designs/architecture_cn.md@@ -395,7 +395,7 @@ app_gateway / app_agentserver 启动:| overlay 绑定即 seal | miss 回退 tip 会让任务 A 的配置渗透进任务 B || tip 写入联动失效 config 缓存 | 否则 agent 改了密钥、配置视图还读旧值 || monkeypatch 单装配点 + `_PATCHED` 幂等 | 补丁散落多点会随 SDK 升级成雷区;常量化目标名一处可改 |-| wait_for 而非 anyio.fail_after | 跨 task cancel scope 语义(TC_MCP_CALL_014) |+| remote 生命周期同任务 | 发现协程 / 现有 worker / ToolMgr HTTP owner 持有完整上下文;SSE 复用 SDK owner。生命周期阶段用 asyncio.timeout,禁止跨任务或延迟 aclose || thinking/reasoning 窄白名单 | 前缀宽匹配曾让 GLM-4 误吃 GLM-5 参数 || WS 限额双轨不统一 | 内部链流式事件 vs 浏览器链 base64 文档,载荷形态不同 || 版本总序(stable>pre>类型序) | 字符串比较会把 0.10 排在 0.9 前、pre-release 当 stable |diff --git a/jiuwenswarm/common/docs/specs/S_09_mcp-integration.md b/jiuwenswarm/common/docs/specs/S_09_mcp-integration.mdindex 0ce17d463b..e9f8ca2c92 100644--- a/jiuwenswarm/common/docs/specs/S_09_mcp-integration.md+++ b/jiuwenswarm/common/docs/specs/S_09_mcp-integration.md@@ -7,7 +7,7 @@| 类型 | spec || 编号 / slug | S_09 / mcp-integration || 关联模块 | jiuwenswarm/common/{mcp_config, mcp_server_registry, mcp_call_timeout_patch, mcp_tool_list_refresh_patch}.py |-| 最近一次修订日期 | 2026-10-27 |+| 最近一次修订日期 | 2026-10-29 || 关联 feature | F_01_deepresearch-mcp-delegation.md |## 范围 / 边界@@ -31,7 +31,7 @@ mcp_call_timeout_patch.py ─┐ 两个互相独立的 openjiuwen monkeypatch,mcp_tool_list_refresh_patch.py ┘ 唯一装配点:interface_deep.DeepAdapter.__init__契约耦合:自建 remote client 必须补打 _jws_call_timeout 印章——-漏打则 timeout patch 的内层 300s 兜底会先掐断长调用。+漏打则 timeout patch 的进程级默认 30s 兜底会先掐断长调用。```## 不变量@@ -54,13 +54,32 @@ mcp_tool_list_refresh_patch.py ┘ 唯一装配点:interface_deep.DeepAdapter.- **N6 worker 池判等与 retire**:`config_fingerprint`(sha256)判等,变更即 retire;池 key = server_name(env 含 `OFFICE_CLAW_INVOCATION_ID / CALLBACK_TOKEN` 时附 env指纹)。list 接口凭据一律脱敏(`redact_mcp_config`)。-- **N7 timeout patch 的 wait_for 不变量**:remote transport 必须用- `asyncio.wait_for` 而非 `anyio.fail_after`(跨 task cancel scope 语义,TC_MCP_CALL_014);- monkeypatch `ToolMgr._create_client` 盖 `_jws_call_timeout` 印章;包 SDK 工厂抬- `sse_read_timeout`;AbilityManager 模块级 anyio 代理桥 `fail_after` → `wait_for`- (contextvar `_am_call_timeout`)并包装 Tool / MCPTool / LocalFunction / RestfulApi /- RequestScopedOfficeClawMcpTool.invoke + `__init_subclass__` 钩子;死会话错误标记表- 重连重试一次(at-least-once);`_client_io_lock` 串行共享 client;`_PATCHED` 幂等。+- **N7 remote 生命周期归属**:connect、退出上下文、失败清理和重连必须由同一任务+ 执行。发现用完整生命周期协程;池化连接复用 worker;ToolMgr 的 Streamable HTTP+ 连接由补丁的专用 owner 管理,SSE 保留 SDK owner,建连取消时等待该 owner 的+ finally 清理。SSE public disconnect 的等待者取消时,在 10 秒清理预算内等待完整+ 停止流程;预算内的后续取消不得再次传给 owner。预算耗尽后取消目标任务,并最多+ 再等待 1 秒收尾;仍未结束则报告失败、保留不可复用状态,不无限屏蔽取消。+ ToolMgr HTTP 建连/断开失败后的 owner 等待同样屏蔽调用者取消;取消后使用+ 进入清理等待时的截止时间继续有界收尾,不再次取消正在清理的 owner。+ SSE 清理任务自身取消按清理失败报告,只有等待者真实取消才继续传播原取消。+ worker 初始化取消向排队调用者映射为 McpWorkerStoppedError,worker 本身继续传播+ 原取消;发现阶段的内部取消仅跳过当前连接器,真实外部取消继续传播。+ call_tool/list_tools 的内部取消(等待者无 cancel 请求)在所属任务清理成功后+ 最多重连重试一次;再次内部取消映射为普通工具错误。清理失败不得当作成功重试,+ 调用或清理期间的真实外部取消继续传播。+ 建连/调用用 `asyncio.timeout`+ 保持任务归属;`wait_for` 仅可用于完整生命周期或不持有上下文的单次 I/O。+ 超时/死会话先 await disconnect 再重置状态,禁止延迟跨任务 aclose;False 必须报错。+ owner 结束后若仍有未清资源,禁止换新任务复用该 client。scanner 停止等待发现清理,+ 无论 scanner 是否启动都关闭全局 worker。+ `_jws_call_timeout` 印章、SDK read timeout、AbilityManager 截止桥、共享 client+ 串行和死会话重试一次(at-least-once)保持;外部取消必须传播。+ 包装幂等性以当前方法/factory 的显式标记为准;即使 `_PATCHED` 与注册集合被重置,+ 也不得重复包装或叠加 ToolMgr owner。旧 SDK 建连吞掉新收到的取消并返回 False 时,+ 补丁须恢复该取消,让外层超时及用户取消保持原语义。+ SSE 仍使用 SDK owner,在该任务内直接关闭 SDK 的 AsyncExitStack,避免旧 SDK 的+ wait_for(__aexit__) 跨任务退出;失败保留不可复用状态,不重新关闭已消费的 stack。- **N8 refresh patch 修三缺陷**:`ToolMgr._inner_refresh_mcp_tools`(先 list 后删旧、失败保留旧快照)、`ToolMgr.refresh_tool_server`(`None` = TTL 跳过 vs `[]` = 空刷新)、`ResourceMgr.refresh_mcp_server`(真实现)+ `get_mcp_tool_infos`(刷新后@@ -106,7 +125,8 @@ mcp_tool_list_refresh_patch.py ┘ 唯一装配点:interface_deep.DeepAdapter.| stdio 命令带 `-e` / `-c` | 白名单外拦截 | 准入测试 || remote URL 指向内网 / 元数据地址 | SSRF 屏蔽拒绝 | 准入测试(逃生 env 显式开) || 企业版配置 stdio MCP | 拒绝(N2) | 企业分支测试 |-| remote 调用挂死 | wait_for 超时 + 死会话标记 → 作废重连一次 | `test_mcp_call_timeout_recovery.py` |+| remote 调用挂死 | 保留超时,在 owner 清理;下次调用重连。死会话错误当轮重试一次 | `test_mcp_call_timeout_recovery.py` |+| remote 生命周期取消/退出 | 进入和退出同任务,清理失败报错且禁止换任务复用残留上下文 | `test_mcp_remote_lifecycle.py`(真实 AnyIO TaskGroup + 内存传输) || 共享 client 并发调用 | `_client_io_lock` 串行 | 同上 || 扫描期工具列表失败 | 保留旧快照(N8) | `test_mcp_tool_list_refresh_patch.py` || 配置变更(指纹变) | worker retire 重建 | registry 测试 |diff --git a/jiuwenswarm/common/mcp_call_timeout_patch.py b/jiuwenswarm/common/mcp_call_timeout_patch.pyindex 755676fdaf..4810eab7c9 100644--- a/jiuwenswarm/common/mcp_call_timeout_patch.py+++ b/jiuwenswarm/common/mcp_call_timeout_patch.py@@ -1,77 +1,12 @@# coding: utf-8-"""Inject a per-call timeout + dead-session recovery into openjiuwen 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``.--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 的外层截止先触发。- B. Monkeypatch ``ToolMgr._create_client`` so ``config.params["timeout_s"]``- (i.e. ``/mcp add ... --timeout_s N``) is stamped onto the client instance- as ``_jws_call_timeout`` and honored by (A). Falls back to- ``DEFAULT_CALL_TIMEOUT`` when unset.- C. Wrap the MCP SDK factory functions (``mcp.client.sse.sse_client`` /- ``mcp.client.streamable_http.streamablehttp_client``) so connections- created for a client with a stamped ``_jws_call_timeout`` get an- ``sse_read_timeout`` of at least that value, instead of the SDK's 300s- default — long tool calls (SSE result stream / held streamable-http- response) would otherwise be dropped mid-call after 300 idle seconds.- 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 the-whole function a no-op on repeat calls.+"""Jiuwenswarm 的远程 MCP 超时、生命周期与死会话恢复补丁。++调用保留精确 wait_for 截止和 SDK timeout+5/read timeout 传递;连接、断开及+重连必须在同一个 owner 上执行。池化 client 使用现有 worker,ToolMgr HTTP+client 使用专用任务,SSE 使用 SDK owner。超时先 await 清理再重置,禁止把旧+AsyncExitStack 移到后台任务关闭。断开失败保留不可复用标记并报错,外部取消原样传播。+死会话最多重连重试一次(at-least-once)。ToolMgr timeout 印章、AbilityManager+模块内截止桥和工具 invoke 包装仍在唯一启动入口幂等安装。"""from __future__ import annotations@@ -84,9 +19,7 @@ from typing import Any, Optionalfrom openjiuwen.core.common.logging import logger_PATCHED = False-# (cls, name) pairs already wrapped — idempotency guard independent of-# _PATCHED, so we don't stamp attributes onto function objects (which would-# need a mypy ``[attr-defined]`` type-ignore).+# 注册集合用于记录安装状态;幂等性以实际函数上的标记为准,集合重置不能叠加包装。_wrapped_methods: set[tuple[type, str]] = set()# (module, name) SDK factory functions already wrapped, and (cls, name)# client connect methods already wrapped — same idempotency purpose.@@ -104,6 +37,9 @@ _pending_sdk_read_timeout: contextvars.ContextVar[float | None] = contextvars.Co#: connector discovery/startup may legitimately take longer than this#: process-level fail-fast fallback.DEFAULT_CALL_TIMEOUT = 30.0+# 清理等待与取消收尾分别有界,避免失活 owner 无回执时无限屏蔽调用方取消。+_MCP_CLEANUP_TIMEOUT_S = 10.0+_MCP_CANCEL_DRAIN_TIMEOUT_S = 1.0# AbilityManager 外层曾用 anyio.fail_after 包 tool.invoke;MCP 重连若落在该# cancel scope 内,退出时会抛 cancel scope(TC_MCP_CALL_014 第 3 轮)。@@ -141,98 +77,343 @@ __all__ = []-def _fire_and_forget_aclose_exit_stack(stack: Any) -> None:- """宿主 task 结束后再 best-effort ``aclose`` 旧 AsyncExitStack。+class _McpInternalCancellationError(RuntimeError):+ """单次 I/O 内部取消且清理成功,可走既有的一次重连重试。"""- stack 里的 anyio cancel scope 是在当前 task 上 enter 的。立刻丢到另一个- task 里 ``aclose()`` 会取消这些 scope,宿主 task 收到- ``Cancelled via cancel scope ... by Task-N``,整次聊天被当成用户取消- (0 chunk、无 ``chat.error``),Relay 空等看门狗后变成 OA.05000090。- 因此不在宿主还活着时 aclose。等它结束后再清理:此时 cancel 已是空操作,- 连接泄漏只覆盖这一次请求。无 running loop 时放弃 aclose。+def force_invalidate_mcp_client(client: Any) -> None:+ """只标记连接不可复用;同步函数不能安全关闭或丢弃仍有资源的上下文。"""+ setattr(client, "_jws_needs_reconnect", True)+++def _reset_closed_client(client: Any) -> None:+ """仅在所属任务完成 disconnect 后重置,不再安排后台 aclose。++ SSE 自行退出 session/transport,旧 stack 的回调不能再执行一次。"""- if not isinstance(stack, AsyncExitStack):- return+ for attr in ("_session", "_client", "_read", "_write", "_auth_provider"):+ if hasattr(client, attr):+ setattr(client, attr, None)+ if hasattr(client, "_is_disconnected"):+ setattr(client, "_is_disconnected", True)+ if hasattr(client, "_exit_stack"):+ setattr(client, "_exit_stack", AsyncExitStack())+ force_invalidate_mcp_client(client)- async def _aclose() -> None:- try:- await stack.aclose()- except BaseException as exc:- # 含 CancelledError / 跨 task 退出 scope:清理失败不得再抛- logger.debug(- "[mcp-timeout] background aclose of old AsyncExitStack failed: %r",- exc,- )+async def disconnect_remote_mcp_client(+ client: Any, exc_type: Any = None, exc: BaseException | None = None, tb: Any = None,+) -> None:+ """在 owner 上有界清理;可用作 AsyncExitStack 的 exit,保留外部取消。"""+ if (getattr(client, "_is_disconnected", False)+ and getattr(client, "_session", None) is None+ and getattr(client, "_client", None) is None):+ # SSE connect 失败虽已清理资源,public disconnect 仍需停止它的 owner。+ owner = getattr(client, "_owner_task", None)+ if owner is None or owner.done():+ returntry:- loop = asyncio.get_running_loop()- except RuntimeError:- logger.debug(- "[mcp-timeout] no running loop; skip background aclose of old AsyncExitStack"- )- return+ owner = getattr(client, "_owner_task", None)+ if owner is not None and owner.done() and (+ getattr(client, "_session", None) is not None+ or getattr(client, "_client", None) is not None+ ):+ raise RuntimeError("SSE previous owner cleanup incomplete; replace client")+ async with asyncio.timeout(10.0):+ clean = await client.disconnect(timeout=10.0)+ if clean is False:+ raise RuntimeError("remote MCP disconnect returned false; cleanup incomplete")+ except BaseException as cleanup_error:+ force_invalidate_mcp_client(client)+ logger.warning("[mcp-timeout] remote MCP cleanup failed", exc_info=True)+ if isinstance(exc, asyncio.CancelledError) and isinstance(cleanup_error, Exception):+ return # 已报告清理失败;不能用普通异常替代调用方的取消+ raise+++async def _finish_mcp_task_after_cancel(+ task: asyncio.Task, *, deadline: float | None = None,+) -> Any:+ """在预算内保护 owner 清理,超时后取消并有界收尾;调用处继续传播原取消。++ asyncio.wait 不把等待者的取消转发给目标;AnyIO shield 避免外层已取消+ scope 反复唤醒。预算耗尽后才主动取消目标,不跨任务关闭任何资源。+ """+ import anyio- def _drain_task_result(done: asyncio.Task) -> None:- try:- done.result()- except BaseException:- pass+ loop = asyncio.get_running_loop()+ if deadline is None:+ deadline = loop.time() + _MCP_CLEANUP_TIMEOUT_S++ async def wait_until(end: float) -> None:+ while not task.done():+ remaining = end - loop.time()+ if remaining <= 0:+ return+ try:+ await asyncio.wait({task}, timeout=remaining)+ except asyncio.CancelledError:+ continue # 后续取消只影响等待者,不能重置清理截止时间。++ def consume_result(finished: asyncio.Task) -> None:+ # 超时已报告;仍不响应取消的任务结束时取走异常,资源仍归原 owner。+ with contextlib.suppress(BaseException):+ finished.result()++ with anyio.CancelScope(shield=True):+ await wait_until(deadline)+ if task.done():+ return task.result()+ task.cancel()+ await wait_until(loop.time() + _MCP_CANCEL_DRAIN_TIMEOUT_S)+ if task.done():+ consume_result(task)+ else:+ task.add_done_callback(consume_result)+ raise TimeoutError("MCP cleanup deadline exceeded; cleanup incomplete")- def _schedule_aclose(_done: asyncio.Task | None = None) -> None:- try:- running = asyncio.get_running_loop()- except RuntimeError:- logger.debug(- "[mcp-timeout] loop already closed; skip background aclose of old AsyncExitStack"- )- return- cleanup = running.create_task(_aclose())- cleanup.add_done_callback(_drain_task_result)- host = asyncio.current_task(loop)- if host is None or host.done():- _schedule_aclose()+def manage_sse_owner_cleanup(client: Any) -> None:+ """沿用 SDK 的 SSE owner,在建连被取消时让它自己清理再退出。++ SDK 的 connect 等待队列 future,取消等待者不会自动中断正在 initialize 的+ owner。只停止等待会把 disconnect 排到长时间挂起的 initialize 后面。+ """+ if getattr(client, "_jws_sse_cleanup_managed", False):+ return+ owner_loop = getattr(client, "_owner_loop", None)+ do_disconnect = getattr(client, "_do_disconnect", None)+ if not callable(owner_loop) or not callable(do_disconnect):return- host.add_done_callback(_schedule_aclose)+ connect = client.connect+ disconnect = client.disconnect++ if isinstance(getattr(client, "_exit_stack", None), AsyncExitStack):+ async def do_disconnect(*, timeout: float = -1):+ # 锁文件中的 SDK 用 wait_for 退出上下文,在 Python 3.11 会换任务。+ # 沿用 SDK 的 owner 与 exit stack,只替换退出入口,不能跨任务补关。+ if getattr(client, "_jws_sse_cleanup_failed", False):+ return False+ try:+ async with asyncio.timeout(timeout if timeout > 0 else 10.0):+ await client._exit_stack.aclose()+ except BaseException as exc:+ setattr(client, "_jws_sse_cleanup_failed", True)+ force_invalidate_mcp_client(client)+ if isinstance(exc, Exception):+ # SDK public disconnect 收到 False 后仍会停止 owner;外层将 False 报错。+ logger.warning("[mcp-timeout] SSE owner cleanup failed", exc_info=True)+ return False+ raise+ _reset_closed_client(client)+ return True+ setattr(client, "_do_disconnect", do_disconnect)-def force_invalidate_mcp_client(client: Any) -> None:- """丢弃半死会话状态,换上新的 AsyncExitStack,供后续 ``connect()`` 重连。+ async def owner_with_cleanup():+ try:+ await owner_loop()+ finally:+ if getattr(client, "_session", None) is not None or getattr(client, "_client", None) is not None:+ async with asyncio.timeout(10.0):+ clean = await do_disconnect(timeout=10.0)+ if clean is False:+ force_invalidate_mcp_client(client)+ raise RuntimeError("SSE owner disconnect returned false; cleanup incomplete")+ _reset_closed_client(client)++ async def connect_with_cleanup(*args, **kwargs):+ if getattr(client, "_jws_sse_cleanup_failed", False):+ raise RuntimeError("SSE previous cleanup incomplete; replace client")+ owner = getattr(client, "_owner_task", None)+ if owner is not None and owner.done() and (+ getattr(client, "_session", None) is not None+ or getattr(client, "_client", None) is not None+ ):+ raise RuntimeError("SSE previous owner cleanup incomplete; replace client")+ try:+ return await connect(*args, **kwargs)+ except asyncio.CancelledError:+ owner = getattr(client, "_owner_task", None)+ if owner is not None and not owner.done():+ # SDK 清理可能消费这次 cancel;退出标记仍须让其命令循环结束。+ setattr(client, "_stopping", True)+ if not owner.cancelling():+ owner.cancel()+ try:+ await _finish_mcp_task_after_cancel(owner)+ except asyncio.CancelledError:+ pass # owner 取消已被等待;调用方取消仍在下方传播+ except Exception:+ force_invalidate_mcp_client(client)+ logger.warning("[mcp-timeout] SSE owner cleanup failed", exc_info=True)+ raise++ async def disconnect_with_cleanup(*args, **kwargs):+ # public API 只向 SDK owner 投命令;实际 __aexit__ 始终留在原 owner。+ # 保住整个 public disconnect,才能执行命令完成后的停止 owner / 释放锁步骤。+ deadline = asyncio.get_running_loop().time() + _MCP_CLEANUP_TIMEOUT_S+ closing = asyncio.create_task(+ disconnect(*args, **kwargs), name="mcp-sse-disconnect"+ )+ try:+ return await asyncio.shield(closing)+ except asyncio.CancelledError as exc:+ current = asyncio.current_task()+ if current is None or not current.cancelling():+ # shield 的内部任务取消也会抛 CancelledError,不能伪装成用户取消。+ force_invalidate_mcp_client(client)+ raise RuntimeError("SSE disconnect cancelled internally; cleanup incomplete") from exc+ try:+ await _finish_mcp_task_after_cancel(closing, deadline=deadline)+ except asyncio.CancelledError:+ force_invalidate_mcp_client(client)+ except Exception:+ force_invalidate_mcp_client(client)+ logger.warning("[mcp-timeout] SSE disconnect cleanup failed", exc_info=True)+ raise++ setattr(client, "_owner_loop", owner_with_cleanup)+ setattr(client, "connect", connect_with_cleanup)+ setattr(client, "disconnect", disconnect_with_cleanup)+ setattr(client, "_jws_sse_cleanup_managed", True)- SDK ``StreamableHttpClient.disconnect`` 在 aclose 失败时往往不清 ``_session``,- 且成功 aclose 后旧 stack 也不能再 enter。超时 / Session terminated 路径必须- 无条件调用本函数。- 替换 ``_exit_stack`` 前会取出旧 stack。aclose 推迟到当前 task 结束之后- (scope 是在这个 task 上 enter 的,活着时跨 task aclose 会取消整次聊天)。- 无 running loop 时放弃 aclose。本函数保持同步,不改成 async。+class _StreamableHttpOwner:+ """仅供没有池化 worker 的 ToolMgr HTTP client 使用的生命周期任务。- 同时打上 ``_jws_needs_reconnect``:即便残留对象仍像「已连接」,下次调用也强制- 重连。聊天会话 A/B 共用同一客户端,否则新建会话也会继承半死连接。+ 池化连接已有 _run_mcp_worker,SSE 已有 SDK owner,均不叠加此任务。"""- 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 __init__(self, client: Any) -> None:+ self.client = client+ self.queue: asyncio.Queue = asyncio.Queue()+ self.task: asyncio.Task | None = None+ self.active: asyncio.Future | None = None++ async def submit(self, method: Any, name: str, args: tuple, kwargs: dict) -> Any:+ if asyncio.current_task() is self.task:+ return await method(*args, **kwargs)+ if self.task is not None and self.task.done() and (+ getattr(self.client, "_session", None) is not None+ or getattr(self.client, "_client", None) is not None+ ):+ raise RuntimeError("MCP HTTP previous owner cleanup incomplete; replace client")+ # 已断开的 client 不必创建 owner。+ if name == "disconnect" and (self.task is None or self.task.done()):+ if getattr(self.client, "_is_disconnected", False):+ return True+ if self.task is None or self.task.done():+ self.task = asyncio.create_task(self.run(), name="mcp-streamable-http-owner")+ task = self.task+ future = asyncio.get_running_loop().create_future()+ self.queue.put_nowait((method, name, args, kwargs, future))+ try:+ result = await future+ if name == "disconnect" or (name == "connect" and not result):+ await task+ return result+ except asyncio.CancelledError:+ # 排队者取消不能中断另一个聊天正在执行的命令。+ if self.active is not None and self.active is not future:+ raise+ if not task.cancelling():+ task.cancel()+ try:+ await _finish_mcp_task_after_cancel(task)+ except asyncio.CancelledError:+ pass # owner 的取消已取出;调用方取消在下方继续传播+ except Exception:+ force_invalidate_mcp_client(self.client)+ logger.warning("[mcp-timeout] HTTP owner cleanup failed", exc_info=True)+ raise+ except Exception:+ if name in ("connect", "disconnect"):+ deadline = asyncio.get_running_loop().time() + _MCP_CLEANUP_TIMEOUT_S+ try:+ # 操作已失败,owner 正在 finally 清理;等待者取消不能再打断它。+ await asyncio.shield(task)+ except asyncio.CancelledError:+ current = asyncio.current_task()+ caller_cancelled = current is not None and current.cancelling() > 0+ try:+ await _finish_mcp_task_after_cancel(task, deadline=deadline)+ except asyncio.CancelledError:+ force_invalidate_mcp_client(self.client)+ logger.warning("[mcp-timeout] HTTP owner cancelled during cleanup")+ except Exception:+ force_invalidate_mcp_client(self.client)+ logger.warning("[mcp-timeout] HTTP owner cleanup failed", exc_info=True)+ if caller_cancelled:+ raise+ except Exception:+ force_invalidate_mcp_client(self.client)+ logger.warning("[mcp-timeout] HTTP owner cleanup failed", exc_info=True)+ raise++ async def run(self) -> None:+ failure: BaseException = RuntimeError("MCP HTTP owner stopped")+ disconnect_attempted = False+ try:+ while True:+ method, name, args, kwargs, future = await self.queue.get()+ if future.cancelled():+ continue+ self.active = future+ disconnect_attempted = name == "disconnect"+ try:+ if name in ("connect", "disconnect"):+ timeout = kwargs.get("timeout", -1)+ default = 60.0 if name == "connect" else 10.0+ async with asyncio.timeout(timeout if timeout > 0 else default):+ result = await method(*args, **kwargs)+ else:+ result = await method(*args, **kwargs)+ except BaseException as exc:+ failure = exc+ if not future.done():+ future.set_exception(exc)+ if not isinstance(exc, Exception) or name in ("connect", "disconnect"):+ raise+ else:+ if not future.done():+ future.set_result(result)+ if name == "disconnect" or (name == "connect" and not result):+ break+ finally:+ self.active = None+ except Exception as exc:+ failure = exc+ logger.warning("[mcp-timeout] HTTP owner stopped: %s", exc)+ finally:+ try:+ if not disconnect_attempted:+ await disconnect_remote_mcp_client(self.client)+ finally:+ while not self.queue.empty():+ *_, pending = self.queue.get_nowait()+ if not pending.done():+ # 一个调用者取消不应伪装成其它调用者的用户取消。+ pending.set_exception(+ failure if isinstance(failure, Exception)+ else RuntimeError("MCP HTTP owner stopped during another call")+ )+++def _install_streamable_http_owner(client: Any) -> None:+ owner = _StreamableHttpOwner(client)+ # 包括资源 API:它们也必须和重连/断开串行,不能观察半关闭 session。+ for name in ("connect", "disconnect", "call_tool", "list_tools", "get_tool_info",+ "list_resources", "read_resource"):+ method = getattr(client, name, None)+ if not callable(method):+ continue++ async def routed(*args, _method=method, _name=name, **kwargs):+ return await owner.submit(_method, _name, args, kwargs)++ setattr(client, name, routed)+ setattr(client, "_jws_http_owner", owner)def is_retryable_mcp_dead_session_error(error: BaseException) -> bool:@@ -252,15 +433,6 @@ def is_retryable_mcp_dead_session_error(error: BaseException) -> bool: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 的重连/调用串行锁。@@ -284,39 +456,29 @@ def _client_io_lock(client: Any) -> asyncio.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 结束后再- ``aclose()``,本协程本身不 await 清理。- """- force_invalidate_mcp_client(client)- logger.warning(- "[mcp-timeout] abandoned MCP session without aclose (%s): %s",- context,- getattr(client, "_server_path", "?"),- )+ """由生命周期 owner 完成清理后才允许重连。"""+ await disconnect_remote_mcp_client(client)+ logger.debug("[mcp-timeout] closed MCP session (%s)", context)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)+ if getattr(orig, "_jws_mcp_wrapper", None) == "disconnect":+ returnasync def wrapped(self, *args, **kwargs):- try:- return await orig(self, *args, **kwargs)- finally:- force_invalidate_mcp_client(self)-+ force_invalidate_mcp_client(self)+ result = await orig(self, *args, **kwargs)+ if result is False:+ raise RuntimeError("remote MCP disconnect returned false; cleanup incomplete")+ _reset_closed_client(self)+ return result++ setattr(wrapped, "_jws_mcp_wrapper", "disconnect")setattr(cls, method_name, wrapped)@@ -503,10 +665,10 @@ def _patch_sdk_read_timeouts() -> None:(mcp_sse_module, "sse_client"),(mcp_streamable_http_module, "streamablehttp_client"),):- if (module, factory_name) in _wrapped_factories:- continue_wrapped_factories.add((module, factory_name))orig_factory = getattr(module, factory_name)+ if getattr(orig_factory, "_jws_mcp_wrapper", None) == "transport-read-timeout":+ continuedef factory_with_read_timeout(*args: Any, orig=orig_factory, name=factory_name, **kwargs: Any):hint = _pending_sdk_read_timeout.get()@@ -521,6 +683,7 @@ def _patch_sdk_read_timeouts() -> None:)return orig(*args, **kwargs)+ setattr(factory_with_read_timeout, "_jws_mcp_wrapper", "transport-read-timeout")setattr(module, factory_name, factory_with_read_timeout)connect_targets: list[tuple[type, str]] = [@@ -535,8 +698,6 @@ def _patch_sdk_read_timeouts() -> None: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:- continueif not hasattr(cls, method_name):logger.debug("[mcp-timeout] skip wrapping %s.%s (attribute missing)",@@ -546,62 +707,33 @@ def _patch_sdk_read_timeouts() -> None:continue_wrapped_connects.add((cls, method_name))orig_method = getattr(cls, method_name)+ if getattr(orig_method, "_jws_mcp_wrapper", None) == "connect-read-timeout":+ continueasync def method_with_read_timeout(self, *args: Any, orig=orig_method, **kwargs: Any):hint = getattr(self, "_jws_call_timeout", None)token = (_pending_sdk_read_timeout.set(float(hint)) if _stamp_is_valid(hint) else None)+ current = asyncio.current_task()+ cancelling = current.cancelling() if current is not None else 0try:- return await orig(self, *args, **kwargs)+ connected = await orig(self, *args, **kwargs)+ # 锁文件中的旧 SDK 会捕获 BaseException 并返回 False,不能让它+ # 吞掉本次建连收到的取消(含 asyncio.timeout 发出的取消)。+ if current is not None and current.cancelling() > cancelling:+ raise asyncio.CancelledError+ if connected:+ setattr(self, "_jws_needs_reconnect", False)+ return connectedfinally:if token is not None:_pending_sdk_read_timeout.reset(token)+ setattr(method_with_read_timeout, "_jws_mcp_wrapper", "connect-read-timeout")setattr(cls, method_name, method_with_read_timeout)-def _patch_sse_disconnect_guard() -> None:- """Keep ``SseClient.disconnect`` best-effort cleanup.-- openjiuwen's ``_do_disconnect`` wraps the session/transport ``__aexit__``- calls in ``asyncio.wait_for``, which executes them in a new asyncio Task.- The contexts were entered on the SSE owner task, so exiting them from- wait_for's task trips anyio's cancel-scope invariant; the broken teardown- then surfaces as a ``CancelledError`` raised from ``_submit``'s future —- a BaseException that sails past the ``except Exception`` handlers around- discovery cleanup (``_list_remote_mcp_connector_tools``) and the pooled- worker's exit-stack callback, aborting SSE connector registration outright.- Disconnect is cleanup: swallow the future-cancel flavor, log it, and- report failure. A genuine cancellation of the running task (``cancelling``- count > 0) still propagates.- """- import asyncio as _asyncio-- from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClient-- if (SseClient, "disconnect-guard") in _wrapped_connects:- return- _wrapped_connects.add((SseClient, "disconnect-guard"))- orig_disconnect = getattr(SseClient, "disconnect")-- async def disconnect_guarded(self, *args: Any, orig=orig_disconnect, **kwargs: Any):- try:- return await orig(self, *args, **kwargs)- except _asyncio.CancelledError:- task = _asyncio.current_task()- cancelling = getattr(task, "cancelling", None)- if callable(cancelling) and cancelling() > 0:- raise- logger.warning(- "[mcp-timeout] SseClient.disconnect aborted by transport teardown "- "(pre-existing anyio cancel-scope conflict); treated as failed cleanup",- )- return False-- setattr(SseClient, "disconnect", disconnect_guarded)--def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT) -> None:"""Apply the per-call MCP timeout patch. Idempotent per process."""global _PATCHED@@ -628,13 +760,22 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)async def _connect_fresh(client: Any, *, reason: str) -> None:"""作废旧协议会话后重新 connect(进程级客户端,跨聊天会话共享)。"""- # 超时后勿 aclose:跨 task cancel scope 会污染当前 task(见 _abandon_session)。+ # 调用和重连均由生命周期 owner 执行,先关旧连接再建新连接。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()+ try:+ async with asyncio.timeout(60.0):+ ok = await connect()+ except BaseException:+ try:+ await disconnect_remote_mcp_client(client)+ except Exception:+ logger.warning("[mcp-timeout] reconnect cleanup failed", exc_info=True)+ raiseif not ok:+ await disconnect_remote_mcp_client(client)raise RuntimeError(f"MCP client reconnect failed ({reason}): "f"{getattr(client, '_server_path', '?')}"@@ -670,7 +811,7 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)async def _teardown_after_timeout(client: Any, *, cls_name: str, method: str, timeout: float) -> None:- # 跳过 disconnect/aclose,直接作废(TC_MCP_CALL_014)。+ # 不丢弃仍活着的 AsyncExitStack,由 owner 同步完成清理。await _abandon_session(client,context=f"{cls_name}.{method} after {timeout:g}s timeout",@@ -690,17 +831,11 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)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_wrapped_methods.add((cls, name))orig = getattr(cls, name)+ if getattr(orig, "_jws_mcp_wrapper", None) == "call-timeout":+ returnasync def wrapped(self, *args, **kwargs):timeout = _resolve_timeout(self, kwargs.get("timeout"))@@ -710,11 +845,7 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)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 一致。+ # 这里只执行单次 I/O;会持有上下文的重连/清理在外层 owner 执行。return await asyncio.wait_for(orig(self, *args, **kwargs),timeout=timeout,@@ -732,136 +863,71 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_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)+ async def _invoke_with_cleanup():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", "?"),- )+ except Exception as cleanup_error:+ raise _timeout_error(cls.__name__, name, timeout) from cleanup_errorraise _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 重启场景)+ except asyncio.CancelledError as exc:+ # I/O 自身取消不等于调用者取消;清理仍留在生命周期 owner。+ current = asyncio.current_task()+ outer_cancel = current is not None and current.cancelling() > 0try:- 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():+ await _abandon_session(self, context="call cancelled")+ except asyncio.CancelledError as cleanup_error:+ if outer_cancel or (current is not None and current.cancelling()):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+ raise RuntimeError(+ "MCP internal cancellation cleanup failed"+ ) from cleanup_error+ except Exception as cleanup_error:+ if not outer_cancel and not (current is not None and current.cancelling()):+ # 清理失败不能进入重试,否则会在未关闭的上下文上重连。+ raise RuntimeError(+ "MCP internal cancellation cleanup failed"+ ) from cleanup_error+ logger.warning("[mcp-timeout] cleanup after cancellation failed", exc_info=True)+ if not outer_cancel and not (current is not None and current.cancelling()):+ raise _McpInternalCancellationError(+ f"MCP {cls.__name__}.{name} cancelled internally"+ ) from exc+ raise++ async with _client_io_lock(self):+ await _ensure_connected(self)+ try:+ return await _invoke_with_cleanup()+ except (TimeoutError, asyncio.CancelledError):+ raiseexcept Exception as exc:- # MCP 服务重启后协议会话失效:进程级客户端仍持有旧 session id,- # 新旧聊天会话都会 Session terminated / 404。作废后重连并重试一次。- # 亦覆盖 cancel-scope 清理噪声(超时后首轮偶发)。- if not is_retryable_mcp_dead_session_error(exc):+ if not (+ isinstance(exc, _McpInternalCancellationError)+ or is_retryable_mcp_dead_session_error(exc)+ ):raise- logger.warning(- "[mcp-timeout] %s.%s hit dead session (%s), reconnecting once: %s",- cls.__name__,- name,- exc,- getattr(self, "_server_path", "?"),- )+ # 保留死会话的一次 at-least-once 重试;清理失败不能当成已断开。+ await _connect_fresh(self, reason="dead-session")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+ return await _invoke_with_cleanup()+ except Exception:+ force_invalidate_mcp_client(self)+ raise+ setattr(wrapped, "_jws_mcp_wrapper", "call-timeout")setattr(cls, name, wrapped)# (A) HTTP long-poll transports — same failure mode when the server dies.for cls in (StreamableHttpClient, SseClient):_wrap_with_timeout(cls, "call_tool")_wrap_with_timeout(cls, "list_tools")- # 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,不再全局替换@@ -870,6 +936,10 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)def _create_client_with_timeout(config):client = _orig_create_client(config)+ if isinstance(client, StreamableHttpClient):+ _install_streamable_http_owner(client)+ elif isinstance(client, SseClient):+ manage_sse_owner_cleanup(client)timeout_s = (getattr(config, "params", None) or {}).get("timeout_s")if isinstance(timeout_s, (int, float)) and timeout_s > 0:try:@@ -894,7 +964,9 @@ def apply_mcp_call_timeout_patch(default_timeout: float = DEFAULT_CALL_TIMEOUT)# setattr (not direct assignment): rebinding a staticmethod on the class is# an mypy [assignment] error; setattr keeps the monkeypatch lint-clean# (no type: ignore needed).- setattr(ToolMgr, "_create_client", staticmethod(_create_client_with_timeout))+ if getattr(_orig_create_client, "_jws_mcp_wrapper", None) != "toolmgr-factory":+ setattr(_create_client_with_timeout, "_jws_mcp_wrapper", "toolmgr-factory")+ setattr(ToolMgr, "_create_client", staticmethod(_create_client_with_timeout))# (C) AbilityManager 外层 fail_after → wait_for 桥(不改 agent-core)try:diff --git a/jiuwenswarm/common/mcp_config.py b/jiuwenswarm/common/mcp_config.pyindex eac3fcf627..96786f0037 100644--- a/jiuwenswarm/common/mcp_config.py+++ b/jiuwenswarm/common/mcp_config.py@@ -1032,7 +1032,7 @@ async def _run_mcp_worker(- stdio(默认/缺省):起 ``stdio_client`` + ``ClientSession`` 进程。仅供 OfficeClaw Relay 身份 pin 后的 worker 使用;用户可配连接器入口已切断。- sse / streamable-http:复用 openjiuwen 的 ``SseClient`` / ``StreamableHttpClient``,- connect 后长连接复用(自带 owner-task/cancel-scope/超时/重连 + auth 注入)。+ connect 后长连接复用;HTTP 上下文由本 worker 持有,SSE 由 SDK owner 持有。全程在本 task 内执行,使 stdio 的 anyio task group / cancel scope 不逃逸到外来 task。task 被 cancel(清理)或队列收到 ``None`` 哨兵时退出(关闭 stdio 进程 / 远端连接)。@@ -1048,12 +1048,17 @@ async def _run_mcp_worker(worker.call_timeout_s = call_timeout_sasync with AsyncExitStack() as stack:+ # queue.get 被取消或清理期间新入队,也必须解除等待者;此回调最后执行。+ stack.push_async_callback(+ _drain_queue_with_error, worker,+ McpWorkerStoppedError(f"MCP worker stopped: server={worker.server_name}"),+ )try:if client_type in ("sse", "streamable-http"):session = await _enter_remote_mcp_session(stack, params, client_type)else:session = await _enter_stdio_mcp_session(stack, params)- except Exception as exc:+ except BaseException as exc:# 初始化失败:失败已排队的 caller,退出以便下次 invoke 时 acquire 重建。logger.warning("request-scoped MCP worker init failed: server=%s transport=%s error=%s",@@ -1061,30 +1066,26 @@ async def _run_mcp_worker(client_type,exc,)- await _drain_queue_with_error(worker, exc)+ # worker 自身仍传播取消,但排队 caller 应收到工具失败而非用户取消。+ mapped = exc if isinstance(exc, Exception) else McpWorkerStoppedError(+ f"MCP worker initialization interrupted: server={worker.server_name}"+ )+ await _drain_queue_with_error(worker, mapped)+ if not isinstance(exc, Exception):+ raisereturnwhile True:req = await worker.queue.get()if req is None:breaktry:- # 超时分派:- # - stdio:必须用 anyio.fail_after(cancel scope)。MCP stdio transport 的- # anyio task group / cancel scope 要求进入与退出在同一 task;asyncio.wait_for- # 把协程放到新 Task 跑,会破坏该不变量。- # - remote(sse/streamable-http):相反,必须用 asyncio.wait_for。remote- # transport(尤其 streamable-http)内部自带后台 task + anyio cancel scope;- # 若用 anyio.fail_after 在本 task 套一层 scope,外层 scope 与 transport 后台- # task 的 scope 跨 task 退出会抛 "Attempted to exit a cancel scope that isn't- # the current tasks's current cancel scope"(企查查 streamable-http 实测故障)。- # asyncio.wait_for 在新 Task 里跑协程,scope 隔离,与 SseClient 自身超时- # 机制(同样 asyncio.wait_for)一致,已由百度网盘 SSE 实证可行。+ # remote 的 patch 可能在调用中重连,因此整个调用也留在 owner。try:if client_type in ("sse", "streamable-http"):- result = await asyncio.wait_for(- session.call_tool(req.tool_name, arguments=req.arguments),- timeout=call_timeout_s,- )+ async with asyncio.timeout(call_timeout_s):+ result = await session.call_tool(+ req.tool_name, arguments=req.arguments+ )else:with anyio.fail_after(call_timeout_s):result = await session.call_tool(@@ -1101,13 +1102,7 @@ async def _run_mcp_worker(req.tool_name,call_timeout_s,)- # remote transport(sse/streamable-http):SseClient/StreamableHttpClient- # 的 _submit 把调用转发到其内部 owner_task 串行执行;外层 cancel 只取消- # 等待方的 future,不会取消 owner_task 上正在跑的命令。若 continue 复用- # worker,下次 invoke 投的新命令会排在未完成的旧命令后面,最长阻塞 60s- # (SseClient 内部 asyncio.wait_for 上限)。故超时即退出 worker:AsyncExitStack- # 关闭触发 disconnect(SseClient 内部 cancel owner_task 清掉未完成命令),- # 下次 invoke 的 acquire 发现 worker 已死便重建。+ # 超时后退出 remote worker,在 owner 上关闭连接;下次 acquire 重建。if client_type in ("sse", "streamable-http"):await _drain_queue_with_error(worker, exc)break@@ -1189,10 +1184,11 @@ async def _enter_remote_mcp_session(rebuild_cfg = _build_remote_mcp_config(params.get("server_name") or "", params, client_type)client = client_cls(rebuild_cfg)- # mcp_call_timeout_patch 把 SseClient/StreamableHttpClient 的 call_tool/list_tools- # 包了内层 anyio.fail_after:不经 ToolMgr._create_client 自建的 client 不会被打- # _jws_call_timeout,内层按 300s 默认先掐断,令 params["timeout_s"] 失效。按- # _run_mcp_worker 的口径(下发合法值直接生效)在此补打。+ if client_type == "sse":+ from jiuwenswarm.common.mcp_call_timeout_patch import manage_sse_owner_cleanup++ manage_sse_owner_cleanup(client)+ # 自建 client 不经 ToolMgr._create_client,需补打调用超时印章。call_timeout_s = (_positive_timeout_s(params.get("timeout_s"))or _MCP_CALL_TOOL_TIMEOUT_S@@ -1202,49 +1198,17 @@ async def _enter_remote_mcp_session(_MCP_CONNECTOR_DISCOVERY_TIMEOUT_S,call_timeout_s,)- # remote transport(sse/streamable-http)的 client.connect 内部 enter async- # context manager(streamable-http 尤其用 anyio TaskGroup + cancel scope)。- # connect 失败时 anyio cancel()+uncancel() 本 task,抛出 CancelledError;它是- # BaseException(Py3.8+),外层 ``except Exception`` 抓不住,会一路泄漏杀死流式- # 任务。用 asyncio.wait_for 套住防卡死,再显式 except CancelledError + cancelling()- # 区分:anyio 内部取消(cancelling()==0)→ 当连接失败跳过;外层真取消 → re-raise。- try:- connected = await asyncio.wait_for(- client.connect(timeout=discovery_timeout),- timeout=discovery_timeout,- )- except asyncio.TimeoutError:- raise RuntimeError( # pylint: disable=raise-missing-from- f"remote MCP client connect timed out after {discovery_timeout}s: "- f"{rebuild_cfg.server_path}"- )- except asyncio.CancelledError:- if is_asyncio_outer_cancellation():- raise- logger.warning(- "request-scoped MCP worker init cancelled (anyio internal), "- "isolating as connect failure: server=%s transport=%s path=%s",- rebuild_cfg.server_name,- client_type,- rebuild_cfg.server_path,- )- raise RuntimeError( # pylint: disable=raise-missing-from- f"remote MCP client connect cancelled (anyio internal): "- f"{rebuild_cfg.server_path}"- )+ # worker 就是生命周期 owner;不能只把 connect 移到 wait_for 的子任务。+ from jiuwenswarm.common.mcp_call_timeout_patch import disconnect_remote_mcp_client++ # 提前登记,覆盖 initialize 中断等半连接路径。SDK 已成功关闭时 helper 不重复关闭。+ stack.push_async_exit(lambda *exc: disconnect_remote_mcp_client(client, *exc))+ async with asyncio.timeout(discovery_timeout):+ connected = await client.connect(timeout=discovery_timeout)if not connected:raise RuntimeError(f"remote MCP client connect returned false: {rebuild_cfg.server_path}")- # 把 disconnect 注册进 stack,worker 退出时统一关连接。-- async def _disconnect() -> None:- try:- await client.disconnect(timeout=10.0)- except Exception as exc:- logger.debug("remote MCP client disconnect failed: %s", exc)-- stack.push_async_callback(_disconnect)return _RemoteMcpCallAdapter(client)@@ -1423,9 +1387,7 @@ async def shutdown_pooled_mcp_worker(if task is None:return# Ask the owner loop to exit gracefully, then await (cancel as fallback).- # 用 anyio.fail_after 而非 asyncio.wait_for:后者在新 Task 里跑协程,会破坏- # MCP transport(stdio 的 task group / remote 的 SseClient owner-task)的- # anyio cancel-scope 不变量,与 _run_mcp_worker 内部的超时机制保持一致。+ # 等待既有 owner task 不会改变上下文归属;超时取消后仍等它完成 finally。try:worker.queue.put_nowait(None)except Exception as exc:@@ -2380,6 +2342,10 @@ async def _list_remote_mcp_connector_tools(# _run_mcp_worker 用 connect_params 字段经 _build_remote_mcp_config 重建 client。rebuild_cfg = _build_remote_mcp_config(server_name, connect_params, client_type)client = client_cls(rebuild_cfg)+ if client_type == "sse":+ from jiuwenswarm.common.mcp_call_timeout_patch import manage_sse_owner_cleanup++ manage_sse_owner_cleanup(client)# 同 _enter_remote_mcp_session:自建 client 不经 ToolMgr._create_client,需补打# _jws_call_timeout,否则 mcp_call_timeout_patch 的内层 300s 默认会先掐断长调用。setattr(@@ -2387,91 +2353,42 @@ async def _list_remote_mcp_connector_tools("_jws_call_timeout",_connector_timeout or _MCP_CALL_TOOL_TIMEOUT_S,)- connected = False- try:- try:- # remote transport(sse/streamable-http)的 client.connect 内部会 enter- # async context manager(streamable-http transport 尤其用 anyio cancel- # scope);若用 anyio.fail_after 包,外层 scope 与 transport 的 scope 跨- # task 退出会抛 "Attempted to exit a cancel scope that isn't the current- # tasks's current cancel scope"(实测企查查 streamable-http 即此故障)。- # 改用 asyncio.wait_for:在新 task 里跑协程,scope 隔离,与 SseClient- # 内部超时机制(同样用 asyncio.wait_for)一致。- connected = await asyncio.wait_for(- client.connect(timeout=discovery_timeout),- timeout=discovery_timeout,- )- except (asyncio.TimeoutError, TimeoutError):- logger.warning(- "request-scoped MCP connector '%s' discovery timed out after "- "%.0fs (connect/list_tools hung)",- server_name,- discovery_timeout,- )- return [], {}- except asyncio.CancelledError:- # connect 失败时 anyio TaskGroup cancel()+uncancel() 本 task 抛- # CancelledError(BaseException,Py3.8+);``except Exception`` 在下方- # 抓不住,会泄漏杀死流式任务。cancelling()==0 → anyio 内部取消 → 当- # 该连接器连接失败跳过(返回空);cancelling()>0 → 外层真取消 → re-raise。- if is_asyncio_outer_cancellation():- raise- logger.warning(- "request-scoped MCP connector '%s' connect cancelled (anyio "- "internal), isolating as connect failure: transport=%s path=%s",- server_name,- client_type,- connect_params["server_path"],- )- return [], {}- if not connected:- logger.warning(- "request-scoped MCP connector '%s' (%s) connect failed: %s",- server_name,- client_type,- connect_params["server_path"],- )- return [], {}- try:- # 同理避免 anyio.fail_after 撞 streamable-http transport 的 cancel scope。- # StreamableHttpClient.list_tools 的 timeout 参数当前未生效(直接调- # session.list_tools 无超时),必须靠这层 asyncio.wait_for 兜底防卡死。- tools = await asyncio.wait_for(- client.list_tools(timeout=discovery_timeout),- timeout=discovery_timeout,- )- except (asyncio.TimeoutError, TimeoutError):- logger.warning(- "request-scoped MCP connector '%s' list_tools timed out after %.0fs",- server_name,- discovery_timeout,- )- return [], {}- except asyncio.CancelledError:- # list_tools 与 connect 共用 anyio TaskGroup,失败时同样 cancel() 本- # task 抛 CancelledError。隔离语义同 connect:内部取消跳过该连接器,- # 外层真取消 re-raise。- if is_asyncio_outer_cancellation():- raise- logger.warning(- "request-scoped MCP connector '%s' list_tools cancelled (anyio "- "internal), isolating as discovery failure: transport=%s path=%s",- server_name,- client_type,- connect_params["server_path"],- )- return [], {}- tool_defs = [- {- "name": getattr(t, "name", "") or "",- "description": getattr(t, "description", "") or "",- "input_params": getattr(t, "input_params", None)- or getattr(t, "inputSchema", {})- or {},- }- for t in (tools or [])- ]+ from jiuwenswarm.common.mcp_call_timeout_patch import disconnect_remote_mcp_client++ async def _discover() -> tuple[list[dict[str, Any]], dict[str, Any]]:+ # 两个阶段各自保留 deadline;finally 仍由进入 transport 的任务执行。+ async with AsyncExitStack() as stack:+ stack.push_async_exit(lambda *exc: disconnect_remote_mcp_client(client, *exc))+ async with asyncio.timeout(discovery_timeout):+ connected = await client.connect(timeout=discovery_timeout)+ if not connected:+ raise RuntimeError("remote MCP client connect returned false")+ async with asyncio.timeout(discovery_timeout):+ tools = await client.list_tools(timeout=discovery_timeout)+ tool_defs = [+ {+ "name": getattr(t, "name", "") or "",+ "description": getattr(t, "description", "") or "",+ "input_params": getattr(t, "input_params", None)+ or getattr(t, "inputSchema", {})+ or {},+ }+ for t in (tools or [])+ ]return tool_defs, connect_params++ try:+ # 外层限制包含清理的完整生命周期,不拆分 connect/disconnect 所属任务。+ return await asyncio.wait_for(_discover(), timeout=2 * discovery_timeout + 10.0)+ except asyncio.CancelledError:+ if is_asyncio_outer_cancellation():+ raise+ logger.warning(+ "请求级 MCP 连接器 '%s' (%s) 发现阶段内部取消,跳过当前连接器",+ server_name,+ client_type,+ )+ return [], {}except Exception as exc:logger.warning("request-scoped MCP connector '%s' (%s) tool discovery failed: %s",@@ -2480,16 +2397,6 @@ async def _list_remote_mcp_connector_tools(exc,)return [], {}- finally:- if connected:- try:- await client.disconnect(timeout=10.0)- except Exception as exc:- logger.debug(- "request-scoped MCP connector '%s' discovery disconnect failed: %s",- server_name,- exc,- )def _remote_mcp_client_cls(client_type: str) -> Any | None:diff --git a/jiuwenswarm/common/mcp_server_registry.py b/jiuwenswarm/common/mcp_server_registry.pyindex aa9abfe940..feb3fc3805 100644--- a/jiuwenswarm/common/mcp_server_registry.py+++ b/jiuwenswarm/common/mcp_server_registry.py@@ -728,14 +728,25 @@ class McpServerRegistry:self._scanner_stop.set()task = self._scanner_taskself._scanner_task = None- if task is None:- return- task.cancel()try:- await task- except (asyncio.CancelledError, Exception):- pass- await self.worker_pool.close_all()+ if task is not None:+ task.cancel()+ try:+ # 等待已有 scanner 清理完成;调用 stop 的任务取消时,不再次打断它。+ await asyncio.shield(task)+ except asyncio.CancelledError:+ current = asyncio.current_task()+ if current is not None and current.cancelling():+ try:+ await task+ except asyncio.CancelledError:+ pass # scanner 本身的取消,外部取消在下方继续传播+ raise+ except Exception:+ logger.exception("[McpServerRegistry] scanner shutdown failed")+ finally:+ # 即使 scanner 尚未启动,也可能已经创建了全局 worker。+ await self.worker_pool.close_all()async def scan_once(self) -> None:"""单轮扫描(单测 / 扫描循环复用)。"""diff --git a/tests/unit_tests/agentserver/test_request_scoped_remote_mcp.py b/tests/unit_tests/agentserver/test_request_scoped_remote_mcp.pyindex e089e4660d..5fb1d3e3ec 100644--- a/tests/unit_tests/agentserver/test_request_scoped_remote_mcp.py+++ b/tests/unit_tests/agentserver/test_request_scoped_remote_mcp.py@@ -248,7 +248,7 @@ async def test_sse_discovery_connect_failure_returns_empty(assert tool_defs == []assert params == {}client = _FakeRemoteClient.instances[0]- client.disconnect.assert_not_awaited() # connect returned False → no disconnect+ client.disconnect.assert_awaited_once() # 未报告已关闭,仍须清理半连接资源@pytest.mark.asyncio@@ -306,7 +306,7 @@ async def test_remote_call_result_adapts_to_stdio_invoke_contract(''str' object has no attribute 'content' must stay fixed."""from jiuwenswarm.common.mcp_config import _RemoteMcpCallAdapter- inner = MagicMock()+ inner = MagicMock(_owner_task=None)inner.call_tool = AsyncMock(return_value="bare-string-from-remote")adapter = _RemoteMcpCallAdapter(inner)@@ -325,7 +325,7 @@ async def test_remote_call_result_none_adapts_to_empty_content(stdio's empty CallToolResult — invoke's `if result.content:` then yields None."""from jiuwenswarm.common.mcp_config import _RemoteMcpCallAdapter- inner = MagicMock()+ inner = MagicMock(_owner_task=None)inner.call_tool = AsyncMock(return_value=None)adapter = _RemoteMcpCallAdapter(inner)@@ -345,7 +345,7 @@ async def test_remote_call_result_dict_serialized_as_json() -> None:from jiuwenswarm.common.mcp_config import _RemoteMcpCallAdapterpayload = {"key": "值", "nested": {"n": 1}}- inner = MagicMock()+ inner = MagicMock(_owner_task=None)inner.call_tool = AsyncMock(return_value=payload)adapter = _RemoteMcpCallAdapter(inner)@@ -376,7 +376,7 @@ async def test_remote_call_tool_honors_connector_timeout_s(async def _hang(*a, **kw):await asyncio.sleep(10)- inner = MagicMock()+ inner = MagicMock(_owner_task=None)inner.call_tool = AsyncMock(side_effect=_hang)inner.connect = AsyncMock(return_value=True)inner.disconnect = AsyncMock(return_value=True)@@ -449,7 +449,7 @@ async def test_remote_call_tool_timeout_breaks_worker_and_drains(async def _hang(*a, **kw):await asyncio.sleep(60) # far beyond the shrunken timeout- inner = MagicMock()+ inner = MagicMock(_owner_task=None)inner.call_tool = AsyncMock(side_effect=_hang)inner.connect = AsyncMock(return_value=True)inner.disconnect = AsyncMock(return_value=True)diff --git a/tests/unit_tests/common/test_mcp_call_timeout_patch.py b/tests/unit_tests/common/test_mcp_call_timeout_patch.pyindex e61bf802bb..a19abe5742 100644--- a/tests/unit_tests/common/test_mcp_call_timeout_patch.py+++ b/tests/unit_tests/common/test_mcp_call_timeout_patch.py@@ -13,13 +13,37 @@ import asynciofrom typing import Anyimport pytest+from openjiuwen.core.foundation.tool import McpServerConfig+from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClientfrom jiuwenswarm.common.mcp_call_timeout_patch import (DEFAULT_CALL_TIMEOUT,apply_mcp_call_timeout_patch,)-from openjiuwen.core.foundation.tool import McpServerConfig-from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClient++[email protected](autouse=True)+def _restore_patch_bindings(monkeypatch):+ from mcp.client import sse, streamable_http+ from openjiuwen.core.foundation.tool.mcp.client.streamable_http_client import (+ StreamableHttpClient,+ )+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ from jiuwenswarm.common import mcp_call_timeout_patch as patch++ # 成对恢复绑定与 guard;实际函数标记保证重复 apply 不会叠加包装。+ for cls in (SseClient, StreamableHttpClient, ToolMgr):+ for name in ("connect", "_do_connect", "disconnect", "call_tool", "list_tools", "_create_client"):+ if name in cls.__dict__:+ monkeypatch.setattr(cls, name, cls.__dict__[name])+ for module, name in ((sse, "sse_client"), (streamable_http, "streamablehttp_client")):+ monkeypatch.setattr(module, name, getattr(module, name))+ monkeypatch.setattr(patch, "_PATCHED", False)+ monkeypatch.setattr(patch, "_wrapped_methods", set())+ monkeypatch.setattr(patch, "_wrapped_connects", set())+ monkeypatch.setattr(patch, "_wrapped_factories", set())+ monkeypatch.setattr(patch, "_patch_ability_manager_fail_after", lambda: None)class _FakeSession:@@ -39,7 +63,7 @@ def _make_sse_client() -> SseClient:client_type="sse",)client = SseClient(config)- client._session = _FakeSession() # noqa: SLF001 - test seam+ client._session = _FakeSession()return client@@ -50,7 +74,7 @@ class TestStampedTimeoutPropagation:) -> None:apply_mcp_call_timeout_patch()client = _make_sse_client()- setattr(client, "_jws_call_timeout", 90.0)+ client._jws_call_timeout = 90.0captured: dict[str, float] = {}real_wait_for = asyncio.wait_for@@ -90,3 +114,68 @@ class TestStampedTimeoutPropagation:await client.call_tool("delay_remote", {"seconds": 0})assert captured["timeout"] == pytest.approx(DEFAULT_CALL_TIMEOUT + 5.0)+++async def test_reapply_after_guard_reset_keeps_single_wrapper(monkeypatch):+ from mcp.client import sse, streamable_http+ from openjiuwen.core.foundation.tool.mcp.client.streamable_http_client import (+ StreamableHttpClient,+ )+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ from jiuwenswarm.common import mcp_call_timeout_patch as patch++ monkeypatch.setattr(patch, "_patch_ability_manager_fail_after", lambda: None)+ # 记录 guard 的初始对象,不能把本测试的 reset 泄漏给已预装补丁的进程。+ for name in ("_PATCHED", "_wrapped_methods", "_wrapped_connects", "_wrapped_factories"):+ monkeypatch.setattr(patch, name, getattr(patch, name))+ apply_mcp_call_timeout_patch()+ bindings = [+ (cls, name, getattr(cls, name))+ for cls in (SseClient, StreamableHttpClient)+ for name in ("connect", "disconnect", "call_tool", "list_tools")+ ] + [+ (SseClient, "_do_connect", SseClient._do_connect),+ (ToolMgr, "_create_client", ToolMgr._create_client),+ (sse, "sse_client", sse.sse_client),+ (streamable_http, "streamablehttp_client", streamable_http.streamablehttp_client),+ ]+ for _ in range(10):+ patch._PATCHED = False+ patch._wrapped_methods = set()+ patch._wrapped_connects = set()+ patch._wrapped_factories = set()+ apply_mcp_call_timeout_patch()+ assert all(getattr(target, name) is method for target, name, method in bindings)+ client = _make_sse_client()+ assert await asyncio.wait_for(client.call_tool("echo", {}), 1) is None+ assert client._session.calls == [("echo", {})]+++async def test_legacy_connect_cannot_swallow_timeout_cancellation(monkeypatch):+ from openjiuwen.core.foundation.tool.mcp.client.streamable_http_client import (+ StreamableHttpClient,+ )++ from jiuwenswarm.common import mcp_call_timeout_patch as patch++ apply_mcp_call_timeout_patch()++ async def legacy_connect(self, **kwargs):+ try:+ await asyncio.Event().wait()+ except asyncio.CancelledError:+ return False++ monkeypatch.setattr(StreamableHttpClient, "connect", legacy_connect)+ # 方法被替换而注册集合未变,必须以实际函数为准重新包装。+ patch._patch_sdk_read_timeouts()+ client = StreamableHttpClient(McpServerConfig(+ server_id="test", server_name="test", server_path="http://127.0.0.1:9/mcp",+ client_type="streamable-http",+ ))+ with pytest.raises(TimeoutError):+ async with asyncio.timeout(0.01):+ await client.connect()diff --git a/tests/unit_tests/common/test_mcp_call_timeout_recovery.py b/tests/unit_tests/common/test_mcp_call_timeout_recovery.pyindex 656bc6fca6..82cb3bb4e7 100644--- a/tests/unit_tests/common/test_mcp_call_timeout_recovery.py+++ b/tests/unit_tests/common/test_mcp_call_timeout_recovery.py@@ -22,7 +22,7 @@ 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`` 还原。+ Tool 等类的 invoke 与子类钩子恢复为进入测试时的绑定,保留原有补丁。"""am_mod = Noneorig_am_anyio = None@@ -64,20 +64,27 @@ def _restore_after_mcp_timeout_patch() -> Iterator[None]:passreturn classes+ # 可能已有 adapter 安装的 invoke 包装;退出时恢复进入测试时的精确绑定,+ # 而不是无条件退回原始方法,避免让其它测试失去已安装的 AM 超时桥。+ invoke_bindings = {+ cls: {name: cls.__dict__[name] for name in (+ "invoke", "_jws_orig_invoke", "__init_subclass__",+ "_jws_am_timeout_init_subclass_hooked",+ ) if name in cls.__dict__}+ for cls in _tool_classes_for_invoke_restore()+ }try:yieldfinally: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+ for cls, bindings in invoke_bindings.items():+ for name in ("invoke", "_jws_orig_invoke", "__init_subclass__",+ "_jws_am_timeout_init_subclass_hooked"):+ if name in bindings:+ setattr(cls, name, bindings[name])+ elif name in cls.__dict__:+ delattr(cls, name)# 单测会反复清 _PATCHED;收尾再清一次,避免泄漏到其它文件timeout_patch._PATCHED = Falsetimeout_patch._wrapped_methods.clear()@@ -91,67 +98,26 @@ def restore_mcp_timeout_patch():@pytest.mark.asyncio-async def test_force_invalidate_defers_aclose_until_host_task_finishes() -> None:- """活着的聊天 task 上不得 aclose:跨 task 退 cancel scope 会取消整次请求。"""+async def test_force_invalidate_retains_resources_without_background_aclose() -> None:+ """同步作废只能标记,不能丢弃资源或在另一任务关闭上下文。"""import asyncio+ from unittest.mock import AsyncMock- aclosed = asyncio.Event()-- class _CancellingStack(AsyncExitStack):- def __init__(self, host: asyncio.Task) -> None:- super().__init__()- self._host = host-- async def aclose(self) -> None:- # 复现 anyio:别的 task 退出 scope 时取消进入该 scope 的宿主 task。- self._host.cancel()- aclosed.set()-- async def host() -> None:- current = asyncio.current_task()- assert current is not None- client = SimpleNamespace(- _session=object(),- _exit_stack=_CancellingStack(current),- _is_disconnected=False,- )- force_invalidate_mcp_client(client)- await asyncio.sleep(0)- await asyncio.sleep(0)- assert current.cancelling() == 0- assert not aclosed.is_set()-- # host 必须是独立 task:aclose 挂在 current_task 的 done 回调上。- task = asyncio.create_task(host())- await task+ stack = AsyncExitStack()+ stack.aclose = AsyncMock()+ session = object()+ client = SimpleNamespace(_session=session, _exit_stack=stack, _is_disconnected=False)+ await asyncio.create_task(_mark_invalid(client))for _ in range(10):- if aclosed.is_set():- breakawait asyncio.sleep(0)- assert aclosed.is_set()---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+ assert client._session is session+ assert client._exit_stack is stack+ stack.aclose.assert_not_awaited()+++async def _mark_invalid(client):+ force_invalidate_mcp_client(client)@pytest.mark.parametrize(@@ -246,9 +212,7 @@ def _install_fake_streamable_client(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"- )+ return Trueconnect_count = {"n": 0}@@ -293,15 +257,29 @@ def _install_fake_streamable_client(@pytest.fixture(autouse=True)-def _autouse_restore_mcp_timeout_patch():+def _autouse_restore_mcp_timeout_patch(monkeypatch):"""本文件凡 apply / 改 ability_manager.anyio 的用例结束后还原全局副作用。"""+ from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClient+ from openjiuwen.core.foundation.tool.mcp.client.streamable_http_client import StreamableHttpClient+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ # 本文件有真实 SSE 和假 transport 两种装配。绑定与 guard 必须成对还原,+ # 否则后续生命周期测试会在已有 wrapper 上再包一次,甚至叠加 HTTP owner。+ for cls in (SseClient, StreamableHttpClient, ToolMgr):+ for name in ("connect", "_do_connect", "disconnect", "call_tool", "list_tools", "_create_client"):+ if name in cls.__dict__:+ monkeypatch.setattr(cls, name, cls.__dict__[name])+ monkeypatch.setattr(timeout_patch, "_PATCHED", timeout_patch._PATCHED)+ for name in ("_wrapped_methods", "_wrapped_connects", "_wrapped_factories"):+ monkeypatch.setattr(timeout_patch, name, set(getattr(timeout_patch, name)))+ monkeypatch.setattr(timeout_patch, "_patch_sdk_read_timeouts", lambda: None)with _restore_after_mcp_timeout_patch():yield@pytest.mark.asyncioasync def test_timeout_then_same_session_call_recovers(monkeypatch: pytest.MonkeyPatch) -> None:- """对齐现场:disconnect 因 cancel scope 失败且未清 _session 时,下一轮须重连成功。"""+ """超时在 owner 清理完成后,下一轮须重连成功。"""call_count = {"n": 0}async def fake_call_tool(self, tool_name: str, arguments: dict, *, timeout=-1):@@ -514,89 +492,62 @@ async def test_empty_error_after_half_dead_session_reconnects_once(@pytest.mark.asyncio-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 test_cleanup_failure_blocks_reconnect(monkeypatch: pytest.MonkeyPatch) -> None:+ """不能把失败的 disconnect 静默视为成功并在旧上下文上重连。"""+ healthy = False- 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 call(self, *args, **kwargs):+ if not healthy:+ raise RuntimeError("Session terminated")+ return {"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"- )+ async def disconnect(self, **kwargs):+ return healthyclient, connect_count, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- fake_disconnect=fake_disconnect,- default_timeout=0.05,+ monkeypatch, fake_call_tool=call, fake_disconnect=disconnect,)- 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+ session, stack = client._session, client._exit_stack+ with pytest.raises(RuntimeError, match="disconnect returned false"):+ await client.call_tool("echo", {})+ assert connect_count["n"] == 0+ assert client._session is session+ assert client._exit_stack is stack+ assert client._jws_needs_reconnect is 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+ # 清理恢复后同一个 client 应可重连,不能永久卡在 needs_reconnect。+ healthy = True+ assert await client.call_tool("echo", {}) == {"ok": True}+ assert connect_count["n"] == 1+ assert client._session is not session+ assert client._jws_needs_reconnect is False@pytest.mark.asyncio-async def test_timeout_teardown_cancelled_error_still_reports_timeout(- monkeypatch: pytest.MonkeyPatch,-) -> None:- """超时 teardown 不再 aclose;即使旧 disconnect 会抛 CancelledError,仍报 TimeoutError。"""+async def test_cleanup_cancelled_error_propagates(monkeypatch: pytest.MonkeyPatch) -> None:+ """清理中的取消也必须传播,不可伪装为完整断开。"""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 call(self, *args, **kwargs):+ await asyncio.Event().wait()- async def fake_disconnect(self, *, timeout=-1):- del self, timeout+ async def disconnect(self, **kwargs):raise asyncio.CancelledError()client, _, _ = _install_fake_streamable_client(- monkeypatch,- fake_call_tool=fake_call_tool,- fake_disconnect=fake_disconnect,- default_timeout=0.05,+ monkeypatch, fake_call_tool=call, fake_disconnect=disconnect, default_timeout=0.01,)-- 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+ with pytest.raises(asyncio.CancelledError):+ await client.call_tool("echo", {})+ assert client._session is not None+ assert client._jws_needs_reconnect is True@pytest.mark.asyncio-async def test_spurious_cancelled_error_reconnects_once(+async def test_internal_cancel_reconnects_once_after_cleanup(monkeypatch: pytest.MonkeyPatch,) -> None:- """连接中断冒出的 CancelledError(非外层取消)应重连重试,而非标成用户取消。"""+ """内部取消在原任务清理后重连一次,不取消业务调用者。"""import asynciocall_count = {"n": 0}@@ -614,13 +565,10 @@ async def test_spurious_cancelled_error_reconnects_once(default_timeout=5.0,)- result = await client.call_tool(- "qa_echo",- {"text": "MCP-CALL-sds-90b35bbefb56-after-restart"},- )- assert result["ok"] is True+ assert (await client.call_tool("qa_echo", {}))["ok"] is Trueassert call_count["n"] == 2- assert connect_count["n"] >= 1+ assert connect_count["n"] == 1+ assert client._session is not None@pytest.mark.asyncio@@ -639,7 +587,7 @@ async def test_sse_timeout_reports_timeout_not_cancelled(async def fake_disconnect(self, *, timeout=-1):del self, timeout- raise asyncio.CancelledError()+ return Trueasync def fake_connect(self, *, timeout=-1):del timeout@@ -806,10 +754,10 @@ def test_init_subclass_hook_must_be_classmethod() -> None:@pytest.mark.asyncio-async def test_disconnect_wrap_clears_session_when_aclose_fails(+async def test_disconnect_wrap_retains_resources_when_aclose_fails(monkeypatch: pytest.MonkeyPatch,) -> None:- """disconnect finally 清会话:aclose 失败也不留半死连接。"""+ """清理失败不丢弃仍待 owner 关闭的资源,不假报成功。"""StreamableHttpClient, _, _ = _install_fake_transport_modules(monkeypatch)async def boom_disconnect(self, *, timeout=-1):@@ -834,7 +782,31 @@ async def test_disconnect_wrap_clears_session_when_aclose_fails(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._session is not None+ assert client._client is not None+ assert client._is_disconnected is False+ assert client._jws_needs_reconnect is True++[email protected]("cleanup_cancelled", [False, True])+async def test_internal_cancel_cleanup_failure_does_not_reconnect(monkeypatch, cleanup_cancelled):+ import asyncio++ async def call(self, *args, **kwargs):+ raise asyncio.CancelledError("internal call cancellation")++ async def disconnect(self, **kwargs):+ if cleanup_cancelled:+ raise asyncio.CancelledError("internal cleanup cancellation")+ return False++ client, connects, _ = _install_fake_streamable_client(+ monkeypatch, fake_call_tool=call, fake_disconnect=disconnect,+ )+ session = client._session+ with pytest.raises(RuntimeError, match="internal cancellation cleanup failed"):+ await client.call_tool("echo", {})+ assert connects["n"] == 0+ assert client._session is sessionassert client._jws_needs_reconnect is Truediff --git a/tests/unit_tests/common/test_mcp_patch_test_isolation.py b/tests/unit_tests/common/test_mcp_patch_test_isolation.pynew file mode 100644index 0000000000..6173d8623d--- /dev/null+++ b/tests/unit_tests/common/test_mcp_patch_test_isolation.py@@ -0,0 +1,61 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""模拟全量 UT 已安装生产补丁的顺序,防止测试 fixture 再次包装 SDK。"""++import subprocess+import sys+from pathlib import Path++import pytest++[email protected]("preinstalled", [False, True])[email protected]("reverse", [False, True])+def test_mcp_fixtures_restore_bindings_in_any_order(preinstalled, reverse):+ code = """+import sys+import pytest++class PreinstalledPatch:+ @pytest.hookimpl(trylast=True)+ def pytest_collection_finish(self, session):+ from jiuwenswarm.common import mcp_call_timeout_patch as patch+ from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClient+ from openjiuwen.core.foundation.tool.mcp.client.streamable_http_client import StreamableHttpClient+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr+ from openjiuwen.core.foundation.tool.base import Tool+ if sys.argv[1] == 'True':+ patch.apply_mcp_call_timeout_patch()+ self.patch = patch+ self.installed = patch._PATCHED+ self.bindings = [(cls, name, cls.__dict__[name])+ for cls in (SseClient, StreamableHttpClient, ToolMgr, Tool)+ for name in ('connect', '_do_connect', 'disconnect', 'call_tool',+ 'list_tools', '_create_client', 'invoke', '__init_subclass__')+ if name in cls.__dict__]+ self.guards = {name: set(getattr(patch, name)) for name in+ ('_wrapped_methods', '_wrapped_connects', '_wrapped_factories')}++ def pytest_sessionfinish(self, session):+ assert self.patch._PATCHED == self.installed+ assert all(cls.__dict__[name] is value for cls, name, value in self.bindings)+ assert all(getattr(self.patch, name) == value for name, value in self.guards.items())++files = [+ 'tests/unit_tests/common/test_mcp_call_timeout_recovery.py',+ 'tests/unit_tests/common/test_mcp_call_timeout_patch.py',+ 'tests/unit_tests/common/test_mcp_remote_lifecycle.py',+]+if sys.argv[2] == 'True':+ files.reverse()+raise SystemExit(pytest.main(files + [+ '-k', 'stamped_timeout or unstamped_client or sse_timeout_reports_timeout or '+ 'reapply_after_guard_reset or (test_discovery_lifecycle and normal) or toolmgr_owner_reconnect',+ '-o', 'addopts=', '-o', 'log_cli=false', '-q',+], plugins=[PreinstalledPatch()]))+"""+ result = subprocess.run(+ [sys.executable, "-c", code, str(preinstalled), str(reverse)],+ cwd=Path(__file__).resolve().parents[3],+ capture_output=True, text=True, timeout=60, check=False,+ )+ assert result.returncode == 0, result.stdout + result.stderrdiff --git a/tests/unit_tests/common/test_mcp_remote_lifecycle.py b/tests/unit_tests/common/test_mcp_remote_lifecycle.pynew file mode 100644index 0000000000..0a315405d3--- /dev/null+++ b/tests/unit_tests/common/test_mcp_remote_lifecycle.py@@ -0,0 +1,1080 @@+# Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved.+"""离线验证真实 SDK 客户端 + AnyIO TaskGroup 的生命周期任务归属。"""++from __future__ import annotations++import asyncio+import subprocess+import sys+from collections import Counter+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock++import anyio+import pytest+import pytest_asyncio+from openjiuwen.core.foundation.tool import McpServerConfig+from openjiuwen.core.foundation.tool.mcp.client.sse_client import SseClient+from openjiuwen.core.foundation.tool.mcp.client.streamable_http_client import (+ StreamableHttpClient,+)++from jiuwenswarm.common import mcp_call_timeout_patch as patch+from jiuwenswarm.common import mcp_config+from jiuwenswarm.common.mcp_server_registry import (+ McpRegistrySettings,+ McpServerRegistry,+)+++@pytest_asyncio.fixture+async def transport(monkeypatch):+ import mcp+ from mcp.client import sse, streamable_http+ from openjiuwen.core.runner import Runner++ state = SimpleNamespace(+ phase="normal",+ hold_close=False,+ closing=asyncio.Event(),+ release_close=asyncio.Event(),+ close_cancellations=0,+ entered=asyncio.Event(),+ calls=asyncio.Event(),+ owners=[],+ exits=[],+ children=[],+ sessions=[],+ connects=0,+ callbacks=0,+ release=asyncio.Event(),+ initial_tasks=set(asyncio.all_tasks()),+ )+ loop = asyncio.get_running_loop()+ original_soon = loop.call_soon++ def call_soon(callback, *args, **kwargs):+ if getattr(callback, "__name__", "") == "_deliver_cancellation":+ state.callbacks += 1+ return original_soon(callback, *args, **kwargs)++ monkeypatch.setattr(loop, "call_soon", call_soon)++ async def receive(stream):+ state.children.append(asyncio.current_task())+ async with stream:+ async for _ in stream:+ pass++ @asynccontextmanager+ async def memory_transport(*args, **kwargs):+ state.owners.append(asyncio.current_task())+ send, recv = anyio.create_memory_object_stream(1)+ async with anyio.create_task_group() as group:+ group.start_soon(receive, recv)+ try:+ yield recv, send, None+ finally:+ state.exits.append(asyncio.current_task())+ group.cancel_scope.cancel()+ await send.aclose()++ @asynccontextmanager+ async def sse_transport(*args, **kwargs):+ async with memory_transport() as (read, write, _):+ yield read, write++ class Session:+ def __init__(self, *args, **kwargs):+ self.group = anyio.create_task_group()+ self.owner = None+ self.exited = False+ state.sessions.append(self)++ async def __aenter__(self):+ self.owner = asyncio.current_task()+ await self.group.__aenter__()+ return self++ async def __aexit__(self, *args):+ assert not self.exited, "session closed twice"+ assert asyncio.current_task() is self.owner+ try:+ if state.hold_close:+ state.closing.set()+ await state.release_close.wait()+ except asyncio.CancelledError:+ state.close_cancellations += 1+ raise+ finally:+ self.exited = True+ suppressed = await self.group.__aexit__(*args)+ return suppressed++ async def initialize(self):+ state.connects += 1+ state.entered.set()+ if state.phase == "connect-error":+ raise RuntimeError("initialize failed")+ if state.phase == "connect-hang":+ await asyncio.Event().wait()++ async def list_tools(self):+ state.calls.set()+ if state.phase == "list-hang":+ await asyncio.Event().wait()+ return SimpleNamespace(+ tools=[+ SimpleNamespace(+ name="echo", description="test", inputSchema={"type": "object"}+ )+ ]+ )++ async def call_tool(self, name, arguments):+ from mcp.types import CallToolResult, TextContent++ state.calls.set()+ if state.phase == "call-hang":+ await state.release.wait()+ if state.phase == "dead":+ state.phase = "normal"+ raise RuntimeError("Session terminated")+ return CallToolResult(content=[TextContent(type="text", text="ok")])++ monkeypatch.setattr(mcp, "ClientSession", Session)+ monkeypatch.setattr(streamable_http, "streamablehttp_client", memory_transport)+ monkeypatch.setattr(sse, "sse_client", sse_transport)+ monkeypatch.setattr(+ Runner.callback_framework, "trigger", AsyncMock(return_value=[])+ )+ monkeypatch.setenv("JIUWENSWARM_ALLOW_LOOPBACK_MCP", "1")+ monkeypatch.setattr(mcp_config, "_MCP_CONNECTOR_DISCOVERY_TIMEOUT_S", 0.05)+ monkeypatch.setattr(mcp_config, "_MCP_CALL_TOOL_TIMEOUT_S", 0.05)+ return state+++def patched(monkeypatch):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ # 成对恢复类方法与 guard;已有包装由函数标记识别,不依赖 _PATCHED 跳过。+ for cls, names in (+ (StreamableHttpClient, ("connect", "disconnect", "call_tool", "list_tools")),+ (+ SseClient,+ ("connect", "_do_connect", "disconnect", "call_tool", "list_tools"),+ ),+ (ToolMgr, ("_create_client",)),+ ):+ for name in names:+ if name in cls.__dict__:+ monkeypatch.setattr(cls, name, cls.__dict__[name])+ monkeypatch.setattr(patch, "_PATCHED", False)+ monkeypatch.setattr(patch, "_wrapped_methods", set())+ monkeypatch.setattr(patch, "_wrapped_connects", set())+ monkeypatch.setattr(patch, "_wrapped_factories", set())+ monkeypatch.setattr(patch, "_patch_ability_manager_fail_after", lambda: None)+ patch.apply_mcp_call_timeout_patch(default_timeout=0.05)+++def config(kind):+ return {"type": kind, "url": "http://127.0.0.1:9/mcp"}+++async def settled(state):+ for _ in range(20):+ await asyncio.sleep(0)+ assert Counter(state.owners) == Counter(state.exits)+ assert all(s.exited for s in state.sessions)+ assert all(t.done() for t in state.children)+ assert not (asyncio.all_tasks() - state.initial_tasks - {asyncio.current_task()})+ count = state.callbacks+ for _ in range(20):+ await asyncio.sleep(0)+ assert state.callbacks == count, "cleanup left a cancellation callback loop"+++def test_foreign_task_exit_reproduces_anyio_error():+ # 故意破坏作用域的测试放子进程,不能污染 pytest 的事件循环。+ code = """+import asyncio, anyio, os+async def main():+ ready = asyncio.Event()+ group = anyio.create_task_group()+ async def owner():+ await group.__aenter__()+ ready.set()+ await asyncio.Event().wait()+ asyncio.create_task(owner())+ await ready.wait()+ try:+ await group.__aexit__(None, None, None)+ except RuntimeError as exc:+ assert 'different task' in str(exc), str(exc)+ os._exit(0)+ os._exit(1)+asyncio.run(main())+"""+ result = subprocess.run(+ [sys.executable, "-c", code], timeout=5, capture_output=True, check=False+ )+ assert result.returncode == 0, result.stderr.decode()++[email protected]("kind", ["streamable-http", "sse"])+ "phase", ["normal", "connect-error", "connect-hang", "list-hang"]+)+async def test_discovery_lifecycle(transport, patched, kind, phase):+ transport.phase = phase+ tools, params = await asyncio.wait_for(+ mcp_config.list_request_mcp_server_tools("test", config(kind)), 2+ )+ assert bool(params) == (phase == "normal")+ assert bool(tools) == (phase == "normal")+ await settled(transport)++[email protected]("kind", ["streamable-http", "sse"])[email protected]("phase", ["connect-hang", "list-hang"])+async def test_discovery_external_cancel(transport, patched, monkeypatch, kind, phase):+ monkeypatch.setattr(mcp_config, "_MCP_CONNECTOR_DISCOVERY_TIMEOUT_S", 30.0)+ transport.phase = phase+ task = asyncio.create_task(+ mcp_config.list_request_mcp_server_tools("test", config(kind))+ )+ await asyncio.wait_for(+ transport.entered.wait() if phase == "connect-hang" else transport.calls.wait(),+ 1,+ )+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, 2)+ await settled(transport)++[email protected]("kind", ["streamable-http", "sse"])+async def test_worker_reconnect_and_shutdown(transport, patched, kind):+ params = {+ "_mcp_client_type": kind,+ "server_name": "test",+ "server_path": config(kind)["url"],+ }+ worker = await mcp_config.acquire_request_scoped_mcp_session(+ "lifecycle", kind, params+ )+ try:+ assert (await asyncio.wait_for(worker.call_tool("echo", {}), 1)).content[+ 0+ ].text == "ok"+ transport.phase = "dead"+ assert (await asyncio.wait_for(worker.call_tool("echo", {}), 1)).content[+ 0+ ].text == "ok"+ transport.phase = "call-hang"+ with pytest.raises(TimeoutError):+ await asyncio.wait_for(worker.call_tool("echo", {}), 1)+ await asyncio.wait_for(worker.task, 1)+ transport.phase = "normal"+ rebuilt = await mcp_config.acquire_request_scoped_mcp_session(+ "lifecycle", kind, params+ )+ assert rebuilt is not worker+ assert (await asyncio.wait_for(rebuilt.call_tool("echo", {}), 1)).content[+ 0+ ].text == "ok"+ finally:+ await mcp_config.release_request_scoped_mcp_sessions("lifecycle")+ await settled(transport)++[email protected]("kind", ["streamable-http", "sse"])+async def test_worker_cancel_during_connect_unblocks_callers(transport, patched, kind):+ transport.phase = "connect-hang"+ worker = mcp_config._PooledMcpWorker("test")+ params = {+ "_mcp_client_type": kind,+ "server_name": "test",+ "server_path": config(kind)["url"],+ }+ worker.task = asyncio.create_task(mcp_config._run_mcp_worker(params, worker))+ caller = asyncio.create_task(worker.call_tool("echo", {}))+ await asyncio.wait_for(transport.entered.wait(), 1)+ worker.task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(worker.task, 2)+ with pytest.raises(mcp_config.McpWorkerStoppedError):+ await asyncio.wait_for(caller, 2)+ await settled(transport)+++async def test_toolmgr_owner_reconnect_and_cross_task_disconnect(transport, patched):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(+ McpServerConfig(+ server_id="test",+ server_name="test",+ client_type="streamable-http",+ server_path=config("streamable-http")["url"],+ params={"timeout_s": 0.05},+ )+ )+ assert await asyncio.wait_for(client.connect(), 1)+ transport.phase = "dead"+ assert await asyncio.wait_for(client.call_tool("echo", {}), 1) == "ok"+ transport.phase = "call-hang"+ with pytest.raises(TimeoutError):+ await asyncio.wait_for(client.call_tool("echo", {}), 1)+ transport.phase = "normal"+ assert await asyncio.wait_for(client.call_tool("echo", {}), 1) == "ok"+ assert await asyncio.wait_for(client.disconnect(), 1)+ assert client._jws_http_owner.task.done()+ await settled(transport)+++async def test_discovery_disconnect_false_is_failure(monkeypatch):+ client = SimpleNamespace(+ connect=AsyncMock(return_value=True),+ list_tools=AsyncMock(return_value=[]),+ disconnect=AsyncMock(return_value=False),+ )+ monkeypatch.setattr(+ mcp_config, "_remote_mcp_client_cls", lambda _: lambda cfg: client+ )+ cfg = McpServerConfig(+ server_id="test", server_name="test", server_path="http://example/mcp"+ )+ assert await mcp_config._list_remote_mcp_connector_tools(+ "test", cfg, "streamable-http"+ ) == ([], {})+ client.disconnect.assert_awaited_once()++[email protected]("kind", ["streamable-http", "sse"])+async def test_discovery_without_startup_patch(transport, kind):+ tools, params = await mcp_config.list_request_mcp_server_tools("test", config(kind))+ assert tools and params+ await settled(transport)++[email protected]("phase", ["connect-hang", "call-hang"])+async def test_toolmgr_owner_external_cancel(transport, patched, phase):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(+ McpServerConfig(+ server_id="test",+ server_name="test",+ client_type="streamable-http",+ server_path=config("streamable-http")["url"],+ )+ )+ if phase == "call-hang":+ assert await asyncio.wait_for(client.connect(), 1)+ transport.phase = phase+ task = asyncio.create_task(+ client.connect() if phase == "connect-hang" else client.call_tool("echo", {})+ )+ event = transport.entered if phase == "connect-hang" else transport.calls+ await asyncio.wait_for(event.wait(), 1)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, 1)+ assert client._jws_http_owner.task.done()+ await settled(transport)+++async def test_toolmgr_partial_connect_timeout_and_reconnect(transport, patched):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(+ McpServerConfig(+ server_id="test",+ server_name="test",+ client_type="streamable-http",+ server_path=config("streamable-http")["url"],+ )+ )+ transport.phase = "connect-hang"+ with pytest.raises(TimeoutError):+ await asyncio.wait_for(client.connect(timeout=0.01), 1)+ assert client._jws_http_owner.task.done()+ await settled(transport)+ transport.phase = "normal"+ assert await asyncio.wait_for(client.connect(), 1)+ assert await asyncio.wait_for(client.disconnect(), 1)+ await settled(transport)++[email protected]("kind", ["streamable-http", "sse"])+async def test_registry_scan_timeout_and_shutdown(+ transport, patched, monkeypatch, kind+):+ from jiuwenswarm.common import mcp_server_registry as registry_module++ registry = McpServerRegistry(settings=McpRegistrySettings(scan_interval_s=60))+ assert (await registry.add_servers([{"name": "test", **config(kind)}]))[0]["ok"]+ worker = await registry.acquire_worker("test")+ await asyncio.wait_for(worker.call_tool("echo", {}), 1)+ transport.phase = "list-hang"+ monkeypatch.setattr(registry_module, "_discover_timeout_s", lambda cfg: 0.01)+ await asyncio.wait_for(registry.scan_once(), 1)+ assert registry._cache["test"].last_scan_ok is False+ assert registry._cache["test"].tools # 失败扫描保留旧缓存+ transport.calls.clear()+ registry.start_scanner()+ scanner = registry._scanner_task+ await asyncio.wait_for(transport.calls.wait(), 1)+ await asyncio.wait_for(registry.stop_scanner(), 1)+ assert scanner.done() and worker.task.done()+ await settled(transport)+++async def test_toolmgr_cancel_queued_caller_does_not_cancel_active_call(+ transport, patched+):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(+ McpServerConfig(+ server_id="test",+ server_name="test",+ client_type="streamable-http",+ server_path=config("streamable-http")["url"],+ params={"timeout_s": 1.0},+ )+ )+ assert await asyncio.wait_for(client.connect(), 1)+ transport.phase = "call-hang"+ first = asyncio.create_task(client.call_tool("echo", {}))+ await asyncio.wait_for(transport.calls.wait(), 1)+ queued = asyncio.create_task(client.call_tool("echo", {}))+ await asyncio.sleep(0)+ queued.cancel()+ with pytest.raises(asyncio.CancelledError):+ await queued+ assert not first.done()+ transport.release.set()+ assert await asyncio.wait_for(first, 1) == "ok"+ assert await asyncio.wait_for(client.disconnect(), 1)+ await settled(transport)+++async def test_registry_shutdown_without_scanner_closes_workers(transport, patched):+ registry = McpServerRegistry()+ assert (+ await registry.add_servers([{"name": "test", **config("streamable-http")}])+ )[0]["ok"]+ worker = await registry.acquire_worker("test")+ await asyncio.wait_for(worker.call_tool("echo", {}), 1)+ await asyncio.wait_for(registry.stop_scanner(), 1)+ assert worker.task.done()+ await settled(transport)+++async def test_cleanup_failure_does_not_hide_external_cancel(monkeypatch):+ entered = asyncio.Event()++ async def list_tools(**kwargs):+ entered.set()+ await asyncio.Event().wait()++ client = SimpleNamespace(+ connect=AsyncMock(return_value=True),+ list_tools=list_tools,+ disconnect=AsyncMock(return_value=False),+ )+ monkeypatch.setattr(+ mcp_config, "_remote_mcp_client_cls", lambda _: lambda cfg: client+ )+ cfg = McpServerConfig(+ server_id="test", server_name="test", server_path="http://example/mcp"+ )+ task = asyncio.create_task(+ mcp_config._list_remote_mcp_connector_tools("test", cfg, "streamable-http")+ )+ await asyncio.wait_for(entered.wait(), 1)+ task.cancel()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(task, 1)+ assert client._jws_needs_reconnect+ client.disconnect.assert_awaited_once()+++async def test_toolmgr_does_not_move_failed_cleanup_to_new_owner():+ client = SimpleNamespace(+ _session=None,+ _client=None,+ _is_disconnected=False,+ connect=AsyncMock(return_value=True),+ disconnect=AsyncMock(side_effect=RuntimeError("disconnect returned false")),+ )+ patch._install_streamable_http_owner(client)+ assert await client.connect()+ client._session = object()+ # 模拟 disconnect wrapper 把 False 变成错误后的保留状态。+ with pytest.raises(RuntimeError, match="disconnect returned false"):+ await client.disconnect()+ owner = client._jws_http_owner.task+ assert owner.done()+ with pytest.raises(RuntimeError, match="previous owner cleanup incomplete"):+ await client.connect()+ assert client._jws_http_owner.task is owner++[email protected]("kind", ["streamable-http", "sse"])+async def test_idle_worker_cancel_drains_newly_queued_request(transport, patched, kind):+ worker = mcp_config._PooledMcpWorker("test")+ params = {+ "_mcp_client_type": kind,+ "server_name": "test",+ "server_path": config(kind)["url"],+ }+ worker.task = asyncio.create_task(mcp_config._run_mcp_worker(params, worker))+ await asyncio.wait_for(worker.call_tool("echo", {}), 1)+ request = mcp_config._McpCallRequest("echo", {})+ worker.queue.put_nowait(request)+ worker.task.cancel() # 已唤醒的 queue.get 在获取 request 之前收到取消+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(worker.task, 1)+ with pytest.raises(mcp_config.McpWorkerStoppedError):+ await asyncio.wait_for(request.future, 1)+ await settled(transport)+++async def test_registry_stop_cancellation_waits_for_scanner_cleanup():+ registry = McpServerRegistry()+ started, cleaning, release = asyncio.Event(), asyncio.Event(), asyncio.Event()++ async def scanner():+ started.set()+ try:+ await asyncio.Event().wait()+ finally:+ cleaning.set()+ await release.wait()++ registry._scanner_task = asyncio.create_task(scanner())+ registry.worker_pool.close_all = AsyncMock()+ await started.wait()+ stop = asyncio.create_task(registry.stop_scanner())+ await asyncio.wait_for(cleaning.wait(), 1)+ stop.cancel()+ await asyncio.sleep(0)+ assert not stop.done()+ release.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(stop, 1)+ registry.worker_pool.close_all.assert_awaited_once()+++async def test_sse_failed_owner_is_not_cleaned_from_new_task():+ owner = asyncio.create_task(asyncio.sleep(0))+ await owner+ client = SimpleNamespace(+ _session=object(),+ _client=object(),+ _owner_task=owner,+ _is_disconnected=False,+ disconnect=AsyncMock(return_value=True),+ )+ with pytest.raises(RuntimeError, match="SSE previous owner cleanup incomplete"):+ await patch.disconnect_remote_mcp_client(client)+ client.disconnect.assert_not_awaited()+ assert client._jws_needs_reconnect+++async def test_sse_disconnect_cancel_waits_for_owner_exit(transport, patched):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(+ McpServerConfig(+ server_id="test",+ server_name="test",+ client_type="sse",+ server_path=config("sse")["url"],+ )+ )+ assert await asyncio.wait_for(client.connect(), 1)+ transport.hold_close = True+ disconnect = asyncio.create_task(client.disconnect())+ await asyncio.wait_for(transport.closing.wait(), 1)+ disconnect.cancel()+ await asyncio.sleep(0)+ disconnect.cancel()+ await asyncio.sleep(0)+ transport.release_close.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(disconnect, 1)+ owner = client._owner_task+ # 失败时也主动结束空闲 SDK owner,避免本回归把 pytest 循环弄脏。+ for _ in range(20):+ await asyncio.sleep(0)+ leaked = owner is not None and not owner.done()+ if leaked:+ owner.cancel()+ await owner+ assert not leaked, "cancelled disconnect left an idle SSE owner"+ await settled(transport)++[email protected]("kind", ["streamable-http", "sse"])[email protected]("phase", ["connect-hang", "call-hang"])+async def test_repeated_caller_cancel_does_not_interrupt_owner_cleanup(+ transport, patched, kind, phase+):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(+ McpServerConfig(+ server_id="test",+ server_name="test",+ client_type=kind,+ server_path=config(kind)["url"],+ params={"timeout_s": 1.0},+ )+ )+ if phase == "call-hang":+ assert await asyncio.wait_for(client.connect(), 1)+ transport.phase = phase+ transport.hold_close = True+ call = asyncio.create_task(+ client.connect() if phase == "connect-hang" else client.call_tool("echo", {})+ )+ ready = transport.entered if phase == "connect-hang" else transport.calls+ await asyncio.wait_for(ready.wait(), 1)+ call.cancel()+ await asyncio.wait_for(transport.closing.wait(), 1)+ call.cancel()+ await asyncio.sleep(0)+ transport.release_close.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(call, 1)+ assert transport.close_cancellations == 0+ await settled(transport)++[email protected]("kind", ["streamable-http", "sse"])+async def test_anyio_caller_scope_cancel_allows_owner_cleanup(transport, patched, kind):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(+ McpServerConfig(+ server_id="test",+ server_name="test",+ client_type=kind,+ server_path=config(kind)["url"],+ params={"timeout_s": 1.0},+ )+ )+ assert await asyncio.wait_for(client.connect(), 1)+ transport.phase = "call-hang"+ transport.hold_close = True++ async def release_cleanup():+ await transport.closing.wait()+ for _ in range(20):+ await asyncio.sleep(0)+ transport.release_close.set()++ release = asyncio.create_task(release_cleanup())+ with pytest.raises(TimeoutError):+ with anyio.fail_after(0.01):+ await client.call_tool("echo", {})+ await asyncio.wait_for(release, 1)+ assert transport.close_cancellations == 0+ await settled(transport)+++async def test_worker_init_internal_cancel_is_not_caller_cancel(monkeypatch):+ """worker 初始化的内部取消不能伪装成所有排队请求的用户取消。"""+ monkeypatch.setattr(+ mcp_config, "_enter_remote_mcp_session",+ AsyncMock(side_effect=asyncio.CancelledError()),+ )+ worker = mcp_config._PooledMcpWorker("test")+ requests = [mcp_config._McpCallRequest("echo", {}) for _ in range(2)]+ for request in requests:+ worker.queue.put_nowait(request)+ worker.task = asyncio.create_task(mcp_config._run_mcp_worker(+ {"_mcp_client_type": "sse"}, worker,+ ))+ with pytest.raises(asyncio.CancelledError):+ await worker.task+ results = await asyncio.gather(*(request.future for request in requests), return_exceptions=True)+ assert all(isinstance(result, mcp_config.McpWorkerStoppedError) for result in results)+ await asyncio.wait_for(worker.queue.join(), 1)++[email protected]("kind", ["sse", "streamable-http"])[email protected]("phase", ["connect", "list_tools"])+async def test_discovery_internal_cancel_skips_only_connector(monkeypatch, kind, phase):+ """SDK 内部 CancelledError 只让当前连接器发现失败。"""+ client = SimpleNamespace(+ connect=AsyncMock(return_value=True),+ list_tools=AsyncMock(return_value=[]),+ disconnect=AsyncMock(return_value=True),+ )+ getattr(client, phase).side_effect = asyncio.CancelledError()+ monkeypatch.setattr(mcp_config, "_remote_mcp_client_cls", lambda _: lambda cfg: client)+ cfg = SimpleNamespace(server_name="test", server_path="http://localhost/mcp", params={})+ assert await mcp_config._list_remote_mcp_connector_tools("test", cfg, kind) == ([], {})+ client.disconnect.assert_awaited_once()+++def sse_cleanup_client(disconnect):+ client = SimpleNamespace(+ connect=AsyncMock(return_value=True),+ disconnect=disconnect,+ _owner_loop=AsyncMock(),+ _do_disconnect=AsyncMock(return_value=True),+ )+ patch.manage_sse_owner_cleanup(client)+ return client+++async def test_sse_disconnect_internal_cancel_is_cleanup_failure():+ client = sse_cleanup_client(AsyncMock(side_effect=asyncio.CancelledError()))+ with pytest.raises(RuntimeError, match="cancelled internally"):+ await client.disconnect()+ assert client._jws_needs_reconnect is True+ assert asyncio.current_task().cancelling() == 0+++async def test_sse_cancelled_disconnect_has_bounded_cleanup(monkeypatch):+ """没有 owner 回执时仍须在预算内结束取消流程,不无限 shield。"""+ monkeypatch.setattr(patch, "_MCP_CLEANUP_TIMEOUT_S", 0.02)+ monkeypatch.setattr(patch, "_MCP_CANCEL_DRAIN_TIMEOUT_S", 0.02)+ started, release, stopped = asyncio.Event(), asyncio.Event(), asyncio.Event()++ async def disconnect():+ started.set()+ try:+ await release.wait()+ finally:+ stopped.set()++ client = sse_cleanup_client(disconnect)+ caller = asyncio.create_task(client.disconnect())+ await started.wait()+ caller.cancel()+ done, _ = await asyncio.wait({caller}, timeout=0.2)+ try:+ assert done, "取消后的 SSE disconnect 超过清理预算仍未返回"+ with pytest.raises(asyncio.CancelledError):+ await caller+ assert stopped.is_set()+ assert client._jws_needs_reconnect is True+ finally:+ release.set()+ await asyncio.gather(caller, return_exceptions=True)+++async def test_finish_cleanup_budget_includes_cancel_resistant_task(monkeypatch):+ """目标忽略 cancel 时收尾仍有上限,资源由原任务持有,测试最终显式释放。"""+ monkeypatch.setattr(patch, "_MCP_CLEANUP_TIMEOUT_S", 0.02)+ monkeypatch.setattr(patch, "_MCP_CANCEL_DRAIN_TIMEOUT_S", 0.02)+ started, release = asyncio.Event(), asyncio.Event()++ async def resistant():+ started.set()+ while not release.is_set():+ try:+ await release.wait()+ except asyncio.CancelledError:+ continue++ target = asyncio.create_task(resistant())+ await started.wait()+ waiter = asyncio.create_task(patch._finish_mcp_task_after_cancel(target))+ done, _ = await asyncio.wait({waiter}, timeout=0.2)+ try:+ assert done, "目标忽略取消导致清理等待无上限"+ with pytest.raises(TimeoutError, match="cleanup"):+ await waiter+ assert target.cancelling() > 0+ finally:+ release.set()+ await asyncio.gather(target, waiter, return_exceptions=True)++[email protected]("kind", ["streamable-http", "sse"])[email protected]("method", ["call_tool", "list_tools"])[email protected]("persistent", [False, True])+async def test_internal_io_cancel_retries_once_without_cancelling_caller(+ transport, patched, monkeypatch, kind, method, persistent,+):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(McpServerConfig(+ server_id="test", server_name="test", client_type=kind,+ server_path=config(kind)["url"],+ ))+ assert await client.connect()+ session_cls = type(transport.sessions[-1])+ original = getattr(session_cls, method)+ calls = 0++ async def internally_cancelled(self, *args, **kwargs):+ nonlocal calls+ calls += 1+ if persistent or calls == 1:+ raise asyncio.CancelledError("internal transport cancellation")+ return await original(self, *args, **kwargs)++ monkeypatch.setattr(session_cls, method, internally_cancelled)+ caller = asyncio.create_task(+ client.call_tool("echo", {}) if method == "call_tool" else client.list_tools()+ )+ try:+ if persistent:+ with pytest.raises(RuntimeError, match="cancelled internally"):+ await asyncio.wait_for(caller, 1)+ else:+ assert await asyncio.wait_for(caller, 1)+ assert not caller.cancelled() and caller.cancelling() == 0+ assert calls == 2+ assert transport.connects == 2+ finally:+ await client.disconnect()+ await settled(transport)++[email protected]("kind", ["streamable-http", "sse"])+async def test_worker_internal_call_cancel_is_tool_error(+ transport, patched, monkeypatch, kind,+):+ worker = mcp_config._PooledMcpWorker("test")+ params = {+ "_mcp_client_type": kind, "server_name": "test",+ "server_path": config(kind)["url"],+ }+ worker.task = asyncio.create_task(mcp_config._run_mcp_worker(params, worker))+ try:+ await asyncio.wait_for(worker.call_tool("echo", {}), 1)+ session_cls = type(transport.sessions[-1])+ original = session_cls.call_tool+ monkeypatch.setattr(session_cls, "call_tool", AsyncMock(side_effect=asyncio.CancelledError()))+ with pytest.raises(RuntimeError, match="cancelled internally"):+ await asyncio.wait_for(worker.call_tool("echo", {}), 1)+ assert not worker.task.done()+ monkeypatch.setattr(session_cls, "call_tool", original)+ assert (await asyncio.wait_for(worker.call_tool("echo", {}), 1)).content[0].text == "ok"+ finally:+ await mcp_config.shutdown_pooled_mcp_worker(worker)+ await settled(transport)++[email protected]("kind", ["streamable-http", "sse"])+async def test_external_cancel_during_internal_cancel_cleanup(+ transport, patched, monkeypatch, kind,+):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(McpServerConfig(+ server_id="test", server_name="test", client_type=kind,+ server_path=config(kind)["url"],+ ))+ assert await client.connect()+ monkeypatch.setattr(+ transport.sessions[-1], "call_tool", AsyncMock(side_effect=asyncio.CancelledError()),+ )+ transport.hold_close = True+ caller = asyncio.create_task(client.call_tool("echo", {}))+ try:+ await asyncio.wait_for(transport.closing.wait(), 1)+ caller.cancel()+ await asyncio.sleep(0)+ transport.release_close.set()+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(caller, 1)+ assert transport.connects == 1+ finally:+ transport.release_close.set()+ await asyncio.gather(caller, return_exceptions=True)+ await client.disconnect()+ await settled(transport)++[email protected]("cancel_mode", ["none", "once", "repeated", "anyio"])+async def test_connect_timeout_cleanup_survives_caller_cancel_and_reconnects(+ transport, patched, cancel_mode,+):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(McpServerConfig(+ server_id="test", server_name="test", client_type="streamable-http",+ server_path=config("streamable-http")["url"],+ ))+ transport.phase = "connect-hang"+ transport.hold_close = True+ scope = None+ cancellation_seen = False++ async def connect():+ nonlocal scope, cancellation_seen+ with anyio.CancelScope() as scope:+ try:+ return await client.connect(timeout=0.01)+ except asyncio.CancelledError:+ cancellation_seen = True+ raise++ caller = asyncio.create_task(connect())+ try:+ # owner 先发布建连超时,再进入清理;此时调用者正在等待 owner 退出。+ await asyncio.wait_for(transport.closing.wait(), 1)+ if cancel_mode == "anyio":+ scope.cancel()+ elif cancel_mode != "none":+ caller.cancel()+ await asyncio.sleep(0)+ if cancel_mode == "repeated":+ caller.cancel()+ await asyncio.sleep(0)+ transport.release_close.set()+ if cancel_mode == "none":+ with pytest.raises(TimeoutError):+ await asyncio.wait_for(caller, 1)+ elif cancel_mode == "anyio":+ await asyncio.wait_for(caller, 1)+ assert cancellation_seen+ else:+ with pytest.raises(asyncio.CancelledError):+ await asyncio.wait_for(caller, 1)+ assert transport.close_cancellations == 0+ assert client._jws_http_owner.task.done()+ assert client._session is None+ assert client._client is None+ await settled(transport)+ transport.phase = "normal"+ transport.hold_close = False+ assert await client.connect()+ assert await client.call_tool("echo", {}) == "ok"+ assert await client.disconnect()+ await settled(transport)+ finally:+ transport.release_close.set()+ await asyncio.gather(caller, return_exceptions=True)+++async def test_cancelled_connect_failure_cleanup_has_deadline(transport, patched, monkeypatch):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ monkeypatch.setattr(patch, "_MCP_CLEANUP_TIMEOUT_S", 0.02)+ monkeypatch.setattr(patch, "_MCP_CANCEL_DRAIN_TIMEOUT_S", 0.02)+ client = ToolMgr._create_client(McpServerConfig(+ server_id="test", server_name="test", client_type="streamable-http",+ server_path=config("streamable-http")["url"],+ ))+ transport.phase = "connect-hang"+ transport.hold_close = True+ caller = asyncio.create_task(client.connect(timeout=0.01))+ try:+ await asyncio.wait_for(transport.closing.wait(), 1)+ caller.cancel()+ # 不释放清理事件,必须由清理预算耗尽结束等待,不能无限 shield。+ done, _ = await asyncio.wait({caller}, timeout=1)+ assert done, "取消后的建连失败清理超过预算仍未返回"+ with pytest.raises(asyncio.CancelledError):+ await caller+ assert client._jws_needs_reconnect+ assert client._jws_http_owner.task.done()+ assert transport.close_cancellations == 1 # 只有预算耗尽才取消 owner。+ if client._session is not None or client._client is not None:+ with pytest.raises(RuntimeError, match="previous owner cleanup incomplete"):+ await asyncio.wait_for(client.connect(), 1)+ else:+ # 旧 SDK 可能在取消后完成整个清理;没有残留资源时仍应允许重连。+ transport.phase = "normal"+ transport.hold_close = False+ assert await asyncio.wait_for(client.connect(), 1)+ assert await asyncio.wait_for(client.disconnect(), 1)+ finally:+ transport.release_close.set()+ await asyncio.gather(caller, return_exceptions=True)+ await settled(transport)+++async def test_failed_connect_owner_cancel_preserves_operation_error():+ client = SimpleNamespace(+ connect=AsyncMock(side_effect=ValueError("connect failed")),+ disconnect=AsyncMock(side_effect=asyncio.CancelledError()),+ )+ patch._install_streamable_http_owner(client)+ caller = asyncio.create_task(client.connect())+ with pytest.raises(ValueError, match="connect failed"):+ await asyncio.wait_for(caller, 1)+ assert not caller.cancelled() and caller.cancelling() == 0+ assert client._jws_http_owner.task.done()+ assert client._jws_needs_reconnect+++async def test_sse_failed_stack_close_stops_owner_without_reclosing(transport, patched, monkeypatch):+ from openjiuwen.core.runner.resources_manager.tool_manager import ToolMgr++ client = ToolMgr._create_client(McpServerConfig(+ server_id="test", server_name="test", client_type="sse",+ server_path=config("sse")["url"],+ ))+ assert await client.connect()+ owner = client._owner_task+ session = client._session+ original = client._exit_stack.aclose+ closes = 0++ async def failed_close():+ nonlocal closes+ closes += 1+ await original()+ raise RuntimeError("session cleanup failed")++ monkeypatch.setattr(client._exit_stack, "aclose", failed_close)+ try:+ with pytest.raises(RuntimeError, match="disconnect returned false"):+ await asyncio.wait_for(client.disconnect(), 1)+ assert owner.done()+ assert client._session is session+ assert closes == 1+ with pytest.raises(RuntimeError, match="previous cleanup incomplete"):+ await client.connect()+ finally:+ if not owner.done():+ owner.cancel()+ await asyncio.gather(owner, return_exceptions=True)+ await settled(transport)