Skip to content
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 50 additions & 0 deletions docs/design/2026-09-08-pooled-mcp-recovery.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
# Recovering lost MCP connections in active ACP sessions

Issue: https://github.com/QwenLM/qwen-code/issues/11272

## Reproduction and ownership

Baseline `bb79319ce5e0e2bbe64307c50dc3621621afc25c` was exercised through a real loopback `qwen serve` daemon and ACP WebSocket sessions, with a deterministic model endpoint and a counted stdio MCP fixture.

Ordinary cancellation delivered `notifications/cancelled`, left the child alive, and allowed both sessions to continue. A fixture that deliberately exited on cancellation exposed a stale CONNECTED status; a fixture that emitted an invalid JSON-RPC frame triggered `silent_drop`, removed session tool registrations, and left later turns unable to call tools. These are controlled fault injections, not proof of the original reporter's teardown mechanism.

There are three lifetimes:

- A tool invocation owns arguments, an abort signal, and one permission decision. It may already have applied a side effect when its response disappears.
- The pool owns the transport and stdio process, shared by connection fingerprint. Its cleanup owns process and descendant teardown.
- Each live session owns a pool reference and filtered tool/prompt/resource registrations. Removing an entry does not close the session, but previously nothing restored these registrations before its next model send.

The SDK's clean-close callback was not reflected in McpClient status. Separately, the invocation reconnect path could use the shared snapshot's bootstrap Config to spawn a private client while the real sessions retained stale handles.

## Design

1. Reflect unexpected SDK close in the disconnected status path for pool-managed clients. Standalone clients retain their existing health-monitor behavior. An intentional disconnect remains guarded by `isDisconnecting`. Reject a discovery snapshot if the connection closed while any listing was in flight, even when another listing returned data.
2. Record a recovery candidate only when a held connection emits `failed`. Retain its transport fingerprint, not a tool invocation. Explicit disconnect/stop removes that candidate; initial discovery failure does not create one.
3. Before an ACP model send, recover eligible candidates through the pool and refresh declarations. Preserve the normal folder trust, disabled-server, approval, configuration fingerprint, transport authentication and per-tool permission checks. Recheck eligibility after acquisition so a late result cannot override revocation or shutdown.
4. Serialize a session's recovery, discovery and runtime additions. A queued configuration refresh reconciles after either success or failure; stop, removal and explicit disconnect invalidate older work. Reapply current trust and tool filters before accepting a recovered or runtime-added handle, since these fields are excluded from transport identity. Use the pool's existing spawn-in-flight coordination across sessions. Acquisition waits for the previous entry's cleanup; unpooled HTTP/SSE cleanup belongs to the session and transport fingerprint. Shutdown includes evicted entries still being cleaned within its existing deadline. A shared five-second cooldown covers acquisition and session-acceptance failures. Each model send can demand recovery, including tool-loop continuations and scheduled model turns; there are no background reconnect timers or invocation retries. Explicit management discovery is not throttled by this cooldown.
5. Pool-projected tools delegate recovery to their session. They do not invoke the standalone reconnect/replay path, regardless of annotations. Child Agent registries retain their source registry and refresh inherited MCP objects before each model send, after recovering that source. Local overrides keep their own discovery ownership. Replacement copies must pass the child configuration and permission checks; shutdown removes the source link so a late refresh cannot repopulate the registry.
6. Refresh tools and ACP prompt commands after recovery; expose success/failure as an ACP diagnostic. Suppress consecutive identical states per server within a logical turn, while retaining transitions such as success → failure → success. Each send still refreshes registrations after recovery. Child and resource callers leave notices pending for ACP. If a turn is cancelled while waiting for a shared connection, stop waiting without cancelling that connection or executing a tool; retain its notice until the next send or superseding configuration/management action. Recovery errors remain best effort and cannot prevent the ordinary model request from proceeding.

Runtime add and recovery use the same effective transport configuration, including the session cwd for implicit stdio servers. The raw runtime overlay remains unstamped so it can follow a workspace relocation. The synthetic `mcp.serverCommand` name cannot be overwritten by a runtime addition. Retiring a transport settles the SDK's old pending requests and removes its callbacks before reconnecting; a late child-close event cannot clear the SDK's replacement transport. A handle releases only its own session attachment, so an older handle cannot remove its replacement. Resource reads retain failed candidates and demand recovery through the pool; a missing handle never creates a private standalone client in pool mode.

Parent and child registries can share a logical session ID. Pool subscriptions therefore include the ToolRegistry identity, allowing each registry to receive failures and release its own registrations. Releasing the logical session removes all of its registry subscriptions. Children with their own MCP configuration use separate prompt and resource registries, so their cleanup preserves the parent's registrations. An inheriting child routes resource reads through the source registry's manager; after waiting for recovery, it rechecks the source links and each child's current eligibility before reading.

Pool-owned tool failures keep an explicit unknown-outcome/no-replay warning, even though they skip invocation-level reconnect. Preventing the SDK from replaying is insufficient if a bare connection error encourages the model to issue the same operation again. This warning does not prove that arbitrary future model decisions will never duplicate a business operation; the client recovery itself performs no tool calls.

A session-acceptance failure can impose the remaining cooldown on another session even if the pool still has a healthy entry. This conservative bound avoids repeated registration failures and concurrent successful returns erasing a failure record. Partial recovery preserves unrelated workspace budget refusals and clears the recovered server's refusal; budget failures receive budget-specific advice. When pooling is disabled with `QWEN_SERVE_NO_MCP_POOL=1`, legacy per-session recovery remains outside this change.

Runtime removal and failed additions ask the pool to release an unused budget reservation. The pool checks live entries and pending acquisitions of the same server name first, preserving the reservation while another session still owns that server.

## Existing management interfaces and scope

PR #7309 remains open at `b5f111c02300e39c2c1563af7abbf229e8455341` at investigation time. Its workspace runtime management, authentication, approval and restart routes overlap the management surface, not this demand recovery implementation. Current main already owns a workspace MCP pool and the restart route. This change adds no route, chat command, management platform, authentication bypass, or generic retry framework. PR #11145 concerns initial workspace discovery after preheat; recovery here is limited to previously acquired connections.

## Validation contract

Use counted tools and PID logs, not model prose or `end_turn`, to judge success. Cover ordinary cancellation, cancellation plus controlled exit/error, independent child exit, simultaneous sessions, concurrent acquisition and failure cooldown, explicit disable/disconnect, late shutdown/revocation, discovery timeout and permission denial. Keep the cancelled invocation count at one. Distinguish local macOS daemon evidence from untested production DingTalk infrastructure, Windows/Linux process semantics and real OAuth providers.

## Review follow-up

Session projection deliberately clones a discovered tool to disable standalone reconnect; it is not a zero-allocation path. Tests use an unprojected discovery snapshot and verify that the shared snapshot keeps standalone behavior. Cooldown records expire after five seconds even if their configuration is removed. These expiry timers perform bookkeeping, never connection attempts.

Recovery before model send can delay a turn: stdio discovery defaults to 30 seconds (remote discovery to five seconds), in addition to waiting for old-entry cleanup. The five-second retry cooldown is not a turn deadline. Cancellation stops the caller waiting. This change preserves existing discovery timeout configuration rather than adding another timeout policy.
36 changes: 36 additions & 0 deletions docs/design/2026-09-08-pooled-mcp-recovery.zh-CN.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
# 活跃 ACP 会话中的 MCP 连接恢复

对应 [英文设计](./2026-09-08-pooled-mcp-recovery.md);问题:[issue #11272](https://github.com/QwenLM/qwen-code/issues/11272)。

## 复现与责任划分

基线 `bb79319ce5e0e2bbe64307c50dc3621621afc25c` 使用本机 `qwen serve`、ACP WebSocket、确定性模型端点和记录 PID、调用次数的 stdio MCP 服务验证。普通取消会发送 `notifications/cancelled`,子进程存活,两个会话可以继续使用工具。让测试服务收到取消后退出,或输出无效 JSON-RPC 帧,会造成连接状态失真或注册丢失。这些受控故障不能证明原报告中的钉钉环境采用相同的断开机制。

工具调用持有参数、取消信号和一次权限决定;响应丢失时,服务端可能完成了副作用。连接池按传输配置指纹持有 transport 和进程,负责清理进程及其后代。会话持有连接引用,以及按权限和配置过滤的工具、提示词与资源注册。连接池删除条目后,会话仍然存在,因此需要在下一次模型请求前恢复注册。

## 设计

1. 对连接池管理的客户端,把意外 SDK close 转成断线状态;主动 disconnect 受 `isDisconnecting` 保护。非池化客户端保留原有健康监控语义。发现期间发生断线时拒绝部分结果,避免一个成功的列表掩盖另一个列表中的连接关闭。
2. 持有的连接失败后,记录服务名和传输指纹作为恢复候选,不保存或重放工具调用。主动断开、移除和停止清除候选;首次发现失败不创建候选。
3. ACP 和子 Agent 在模型请求前按需恢复。检查工作区信任、禁用状态、待审批状态、传输指纹和工具权限;等待连接返回后复查配置及权限。取消只结束当前调用者的等待,不取消其他会话共享的连接创建。
4. 同一会话的发现、恢复和运行时添加串行执行。排队的配置刷新在前一项成功或失败后执行;停止、移除、主动断开和新的同名添加使旧操作失效。连接池沿用共享创建协调,替代连接等待旧条目清理;非池化 HTTP/SSE 的等待范围为会话与传输指纹。关闭流程在既有期限内包含已移出池的清理任务。
5. 池投影工具禁用调用级重连与重放。子 Agent 注册表保存来源,在模型请求前恢复来源并刷新继承的 MCP 对象;子 Agent 的配置覆盖继续拥有自己的发现过程。继承工具经过子 Agent 的配置和权限检查。停止时移除来源引用,阻止迟到刷新重新填充注册表。
6. 恢复后刷新模型工具声明及 ACP 提示词命令。提示按服务的相邻状态去重,保留“成功→失败→成功”的变化;子 Agent 和资源读取不消费 ACP 提示。取消期间产生的提示保留到后续请求。恢复异常按尽力而为处理,不阻止普通模型请求。

运行时添加与恢复使用相同的有效配置,包括 stdio 的隐式工作目录;配置覆盖保留原始形式,以便跟随工作区迁移。`mcp.serverCommand` 占用的合成名称 `mcp` 不允许运行时添加覆盖。关闭旧 transport 时结束旧 SDK 请求并移除回调,避免迟到的 close 清除新 transport。句柄释放检查自身身份,旧句柄不能删除新的会话注册。

父子注册表可能共享逻辑会话 ID,因此池订阅使用逻辑会话 ID 与 ToolRegistry 身份共同区分。父子注册表各自接收失败通知、释放自己的注册;关闭逻辑会话时清理其全部订阅。声明 MCP 配置的子 Agent 使用独立的提示词与资源注册表,子 Agent 清理不会删除父会话的注册。继承父配置的子 Agent 通过来源注册表的 manager 读取资源;等待恢复后复查来源关系及各层子配置的资格。

资源读取发现坏句柄时保留恢复候选;缺少句柄时通过池恢复,不创建私有客户端。工具收到连接故障时保留“结果未知、没有重放、核实结果后重试”的说明;没有全局状态记录不等于观测到断线。客户端不重放并不能保证模型未来的决策不会产生重复业务操作。

获取失败或会话接纳失败启动共享的五秒冷却;即使另一个会话存在健康池条目,该冷却仍可能延迟其恢复。冷却定时器只清理记录,不发起连接。局部恢复保留其他服务的预算拒绝记录,成功后清除本服务记录;完整发现重新计算拒绝集合。

运行时删除和添加失败通过连接池释放未使用的预算预留。连接池检查同名服务的存活条目和创建任务;其他会话持有同名服务时保留预算,避免健康连接存在但预算被清空。

## 范围与验证

本改动不新增管理路由、命令、鉴权方式或通用重试框架。运行时管理、审批、认证和显式重启沿用现有入口;`QWEN_SERVE_NO_MCP_POOL=1` 关闭池后使用原有单会话恢复。

以工具调用计数、PID、实际资源结果和后续模型请求中的工具声明判断成功。覆盖普通取消、取消后退出、独立进程退出、多会话并发、冷却、禁用与审批、迟到连接、发现超时、运行时添加移除、子 Agent 和关闭清理。被取消的工具调用次数应为一。

恢复会延迟模型请求:stdio 发现默认三十秒,远端默认五秒,另有旧连接清理等待;五秒冷却不是回合期限。保留现有发现超时配置,不增加超时策略。池投影需要创建工具副本,不能宣称零分配。验证证据区分本机 macOS daemon、真实生产钉钉环境、Windows/Linux 进程行为和真实 OAuth 服务商。
12 changes: 11 additions & 1 deletion docs/users/features/mcp.md
Original file line number Diff line number Diff line change
Expand Up @@ -297,12 +297,22 @@ environment. This is kept as an escape hatch for at least one release.

### Connection-loss replay

Qwen Code only reconnects and replays the current MCP tool call when the server has `trust: true`, the workspace is trusted, and the tool explicitly declares either `idempotentHint: true` or a consistent read-only annotation. Read-only annotations conflict with `destructiveHint: true` or `idempotentHint: false` and are not replayed.
For tools outside the workspace MCP pool (including daemon sessions started with `QWEN_SERVE_NO_MCP_POOL=1`), Qwen Code only reconnects and replays the current MCP tool call when the server has `trust: true`, the workspace is trusted, and the tool explicitly declares either `idempotentHint: true` or a consistent read-only annotation. Read-only annotations conflict with `destructiveHint: true` or `idempotentHint: false` and are not replayed.

Calls with missing annotations, conflicting annotations, an untrusted server, or an untrusted workspace are not replayed after a connection failure. Qwen Code reports that the result may be unknown because the server could have completed the operation before the response was lost. Verify the outcome before trying again. This conservative behavior can differ from earlier releases that transparently retried unannotated tools.

Annotations are server-provided behavior hints, not permissions or an authorization boundary. Only configure `trust: true` for servers you control and whose annotations you have verified.

### Shared daemon / ACP connection recovery

When workspace MCP pooling is enabled, daemon sessions (including Channel sessions) share eligible MCP connections, including stdio processes. Cancelling a tool call sends a request cancellation; it does not request a server restart and the cancelled call is never replayed. A server may nevertheless exit or lose its transport while handling cancellation. Disabling the pool retains the legacy per-session connection behavior.

When a previously connected server disconnects unexpectedly, the next model send in each affected session attempts to restore that session's connection, tools and prompt commands. This includes later tool loops and scheduled model turns. Concurrent sessions share a replacement process. Each model send can request recovery; failures impose a shared five-second cooldown, including failures while accepting the acquired connection into a session. All acquisition paths wait for old transport cleanup. There is no background reconnect timer. The session reports success or failure, with identical diagnostics shown once per user turn.

Shared tools do not reconnect or replay a failed invocation themselves, even when annotated read-only or idempotent. A lost response may hide a completed operation: check its outcome before requesting that operation again. Recovery does not execute any tool or reuse a previous permission decision.

Disabled, removed, explicitly disconnected, untrusted, or pending-approval servers are not started by this recovery path. Initial discovery failures and timeouts do not become recovery candidates; correct the configuration and use the existing management controls. Authentication continues through the existing MCP transport and authentication flow.

### OAuth authentication

Qwen Code supports OAuth 2.0 authentication for MCP servers. This is useful when accessing remote servers that require authentication.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,9 @@ describe('Session review-worktree lease sweep', () => {
setSessionPrBoundCallback: vi.fn(),
}),
getToolRegistry: vi.fn().mockReturnValue({
getMcpClientManager: vi.fn().mockReturnValue({
recoverFailedConnections: vi.fn().mockResolvedValue([]),
}),
getTool: vi.fn(),
ensureTool: vi.fn().mockResolvedValue(true),
}),
Expand Down
Loading
Loading