Feature: Add MCP cancellation, progress notifications and dry runs

P11 closes the plan's last batch, entirely on the server side: no client
change is required for any of it.

Long-running tools now expose a cancellation flag that every wait loop
checks in 500 ms slices. A cancelled tool returns through the cleanup
branch it already had (late first packets still get absorbed, sub
connections still get closed, pending entries still get deleted), so
there is no second cleanup path to keep in sync, and the host is released
within a second. Three sources set the flag: notifications/cancelled
(matched on the exact JSON-RPC id, with a fallback to the display form so
a request_id copied out of the session list round-trips), mcp_cancel_session
(by request_id, host id or session id), and a failed SSE write when the
client has gone away. The dispatcher rewrites a cancel-induced failure to
-32800 so callers do not mistake it for a host fault.

tools/call requests carrying _meta.progressToken are answered as
text/event-stream on the same POST: the tool runs on its own thread and
both the notifications/progress events and the final JSON-RPC response go
out through one chunked provider. Requests without a token are unchanged.
download_file reports files done vs. expected, upload_file reports bytes
sent vs. total.

Two new local-only tools, mcp_list_sessions and mcp_cancel_session, list
and cancel in-flight sessions (calls, pending one-shots, terminal, remote
control, file transfer, chat). They are deliberately not gated by the
feature switches or readonly mode, since that is the only way out of a
stuck request. The -32003 busy message now names the occupier:
"Device busy: ... (tool=download_file, elapsed=12s)".

power_action gains wait/wait_ms to verify the result against the main
connection's presence (went_offline, came_back, elapsed_ms); not seeing
the transition is reported as ok, not as a failure. kill_process,
operate_window and the four host_control_* tools accept dry_run, which
validates the target against one fresh snapshot and returns what would be
affected without sending anything. Validation rejections now use -32012;
-32008 stays as documented historical alias.

One implementation note worth recording: the per-thread call context uses
FLS, not thread_local. Any static thread_local in this server crashes the
process about a second after start, because some threads come from
shellcode/MemoryModule images that never ran PE TLS initialisation.

Verified against a real Debug server and a real Windows client over MCP:
the smoke test now passes 104 checks with 0 failures, including
cancellation releasing the host in under a second, the cancelled request
returning -32800, notifications/cancelled returning 202, 63 progress
events with exact byte counts for a 64 MB upload, and a cleanly
terminated SSE stream. Not exercised in this pass: power_action's
wait=true path (it would take the test host down) and the -32006
readonly/switch-off section (every switch was on during the run).

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-28 21:25:49 +01:00
1 parent 3d388f8e45
commit 1c832ff7f2
10 files changed
+1855 -107

No files matched your search

+3 -2
View File
@@ -677,15 +677,16 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
| `-32002` | Host offline / not found | 主机 id 不存在、主连接已断、会话 id 不存在或已关闭 | 先 `list_online_hosts` 刷新再选主机 |
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open` | 等前一个结束或先 `*_close` |
| `-32003` | Busy | 该主机已有同类请求在飞(终端/截屏/文件/聊天会话),或同设备重复 `chat_open`。`message` 末尾带 `(tool=..., elapsed=Ns)` 点名占用者 | 用 `mcp_list_sessions` 看全部会话;等前一个结束、先 `*_close`,或 `mcp_cancel_session` 释放 |
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
| `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 |
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
| `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
| `-32008` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符 | 按 `message` 修正参数后重试 |
| `-32012` | Rejected by validation | 只覆盖「参数被校验拒绝、改参数可修」:`exec_command` 含 shell 元字符(Windows `&\|<>^`;Linux `&\|<>;` 与反引号、`$(` `${` `!`)或控制字符(含 `\r\n`);`terminal_exec` 含 `&`/`\|`/换行;路径/参数含非法字符。**`-32008` 是同一语义的历史别名**(早期实现用它,已发布的客户端/文档可能仍在匹配),新代码一律用 `-32012` | 按 `message` 修正参数后重试 |
| `-32009` | Target not found | 远端路径/注册表键不存在(win32 `2`/`3`,由新客户端主动回报);`kill_network_connection` 的四元组在当前连接表里查不到(`dry_run` 传假四元组最常见) | 先用 `list_files`/`list_registry`(或 `host_list_network_state`)确认目标存在 |
| `-32010` | Access denied | 目标存在但权限不足(win32 `5`):非提权客户端的服务枚举(`OpenSCManager`)、受保护目录(如 `System Volume Information`)、受保护注册表键(如 `HKLM\SAM`) | **不要重试**:需客户端提权(管理员运行)或换目标 |
| `-32011` | Destination write failed | 文件传输的**目标端**已收到数据但写盘失败:`copy_files_c2c` / `upload_file` 的目标主机回了回执且 `status != 0`(`message` 带 status、首个 errno、实收文件数) | **不要原样重试**:按文案判断(errno 13/1→权限、2→路径不存在、28→磁盘满),先修目标端目录/权限 |
| `-32800` | Request cancelled | 客户端取消了这次调用:`notifications/cancelled`、`mcp_cancel_session` 或 SSE 流断开(检测到断开会置同一个取消位)。工具在 ≤1s 内退出等待并走既有的超时清理路径,主机占用已释放 | 不是主机故障,可直接重试;终止类命令可能已经执行,重试前先读一次现状 |
- **命令超时会销毁持久会话**(`terminal_exec`):等服务端收集到哨兵超时返回 `-32001`,会话随即被销毁并留 600 秒「墓碑」;对同一 `session_id` 再发命令返回 `-32002`,文案明确写 `Terminal session was destroyed after this command timed out (waited N ms); call terminal_open again`,与「id 写错」(`Terminal session not found: <id>`)区分开。
- **新客户端把失败改成结构化回报**(`TOKEN_SERVICE_ERROR=170` / `TOKEN_FILE_LIST_ERROR=171` / `TOKEN_REG_ERROR=172` / `TOKEN_DOWNLOAD_ERROR=173`,布局 `[token:1][win32 码:4 LE]`):`list_services`(未提权)、`list_files`/`list_registry`(路径/键不存在或拒绝访问)、`download_file`(远端路径全部不存在)都在客户端侧就失败并立即回报,服务端转译成 `-32009`/`-32010`,**亚秒级返回**,不再靠超时猜。老客户端不发这些包,成功路径报文一律不变,因此老客户端/老服务端的行为与改造前完全一致(老服务端把未知 token 走 `default` 丢弃)。
+89 -1
View File
@@ -505,7 +505,7 @@ if (filtered) page.totalAll = (int)all.size(); // 过滤前总数
| **P10-A(优化,先做)** | `instructions`、`capabilities`、`list_*` 过滤、`get_keylog` 离线开关与状态、工具族互指、`kToolHints` 注释、`search_file` 过期描述 | 无 | 服务端 ~450 行 | 冒烟断言 `instructions` 非空;`capabilities` 与平台一致;`list_processes(name=...)` 命中数 < 全量且 `totalAll` 正确;`get_keylog.offlineRecord` 与实际 `kbrecord` 一致 |
| **P10-B** | `delete_path` / `move_path` / `create_folder` + `McpFileWrite` 开关 + 系统目录保护 + §2.3 的三处接线 + `verified` 复核 | 无 | ~700 行 | 冒烟新增:建目录→传文件→改名→删除→删目录→越界拒绝;中文路径 + 超长路径各一条;超时后确认**不弹**文件管理器窗口 |
| **P10-C** | `remote_block_input`(含强制解锁与超时自动解锁) | 无 | ~200 行 | 会话内 block→截图对比→unblock;`remote_close` 后确认已解锁 |
| **P11** | `power_action` 验证、`dry_run` 统一、`-32012`、progress/cancelled、`mcp_list_sessions` | 无 | ~700 行 | 长任务 progress 回调计数 > 0;取消后主机 1s 内释放(`get_server_status` 可查) |
| **P11(已完成 2026-10-28,见附录 D)** | `power_action` 验证、`dry_run` 统一、`-32012`、progress/cancelled、`mcp_list_sessions` | 无 | ~700 行 | 长任务 progress 回调计数 > 0;取消后主机 1s 内释放(`get_server_status` 可查) |
| **P12** | 注册表写、事件日志、进程模块/启动项、`TOKEN_FILE_OP_ERROR`、`DeleteDirectory` 的路径长度防御 | **需要** | 客户端 + 服务端 | 单独设计文档 |
| **独立立项** | 代理隧道、客户端升级、摄像头/语音 | 视方案 | 大 | 单独安全评审 |
@@ -592,3 +592,91 @@ MCP 路径的 `hDlg` 恒为 `NULL`,所以第 2 层一定会命中——这一
配置开关的接线也是三处:读取(`2015RemoteDlg.cpp:2416` 块)、对话框回填(`McpSettingsDlg.cpp:227`)、
落盘(`McpSettingsDlg.cpp:383`)。对话框是**纯代码构建**的(`McpSettingsDlg.cpp:128-186`),
插入一个 checkbox 需要重排其下所有控件的 y 坐标与窗口高度。
---
## 附录 D:P11 施工记录(2026-10-28)
零客户端改动,全部落在服务端(`McpServer.cpp` / `McpServer.h` / `McpMachine.cpp` /
`McpChat.cpp` / `McpInternal.{h,cpp}`)。
### D.1 `power_action` 的结果验证(§5.4)
- 新入参 `wait`(bool,默认 false)与 `wait_ms`(1000–600000,默认 60000),`wait_ms` 是
「等离线」与「等回线」**各自**的时限;`wait=false` 时也会校验 `wait_ms` 的取值范围。
- 输出从 `{ok}` 扩展为 `{ok, sent, went_offline, came_back, elapsed_ms}`:
`sent` 恒为 true(命令写进 socket),`went_offline` / `came_back` 由主连接的出现/消失判定
(`FindMainContext`,200ms 轮询),`elapsed_ms` 为整次调用的耗时。
- **超时不是错误**:`wait=true` 但没等到离线/回线时仍返回 `ok:true` 并在正文里写清「仍在
线」或「已离线但未回线」,让模型据此决定是否再等,而不是把「没等到」当成失败重试。
- `logout` 之后主机不会自动回线(需要人工登录),正文单独提示。
### D.2 破坏性工具统一 `dry_run`(§5.5)
| 工具 | `dry_run=true` 时的行为 |
|---|---|
| `kill_process` | 只取一次进程列表,回 `{ok, dry_run, targets:[{pid,name,path}], missing:[pid...]}`,**不下发终止命令**;一个都匹配不到返回 `-32009` |
| `operate_window` | 只取一次窗口列表,回 `{ok, dry_run, action, window}`;窗口不存在返回 `-32009` |
| `host_control_process` / `_window` / `_service` / `_task` | 只做目标存在性校验,回 `{ok, dry_run, action, target, state, detail}`(detail 是被影响对象的原始字段) |
实现要点:dry run 的挂起项以 `"<tool>/dryrun"` 登记,`OnSystemReady` 只认 `kill_process` /
`operate_window` 两个**精确**工具名,因此不会误发后续写命令;迟到首包仍按既有逻辑吸收。
### D.3 `-32012` 与 `-32008` 别名(§5.6)
- 两个真实站点(`exec_command` 的 shell 元字符、`terminal_exec` 的 `&`/`|`/换行)改为
`McpInternal::kErrValidation = -32012`;`kErrValidationOld = -32008` 保留为历史别名,不再新增使用。
- `initialize.instructions` 的错误码表与 `docs/Mcp_Design.md §12` 同步;`-32800` 一并登记。
### D.4 `notifications/progress` 与 `notifications/cancelled`(§5.9)
**传输**:本服务端原本每个 POST 只回一个 JSON。带 `params._meta.progressToken` 的 `tools/call`
改走 MCP Streamable HTTP 允许的 `text/event-stream`(同一个 POST):
1. 工具在独立线程执行,`McpCallContext` 经 FLS(Fiber Local Storage)暴露给工具实现
——**不能用 `thread_local`**:本工程有 shellcode/MemoryModule 手工映射出来的线程,没有
PE 的 TLS 初始化,加一个静态 `thread_local` 就会让服务端启动约 1s 后跳飞(实测);
2. 进度通知与最终响应都从这个 SSE 流写出(`McpProgressChannel`,背压队列上限 64 条,
满了丢最旧——进度是「最新值有意义」的信号);
3. 不带 token 的请求完全不变(一次性 JSON)。
**进度上报点**(`McpCallProgress`,内部 1s 节流):
| 工具 | 进度含义 |
|---|---|
| `download_file` | `filesDone / (totalFiles - directoryCount)`;总量未知时退回已收字节数 |
| `upload_file` | 已发数据字节 / 待发数据字节总数(在 worker 的分块回调里累加) |
| `copy_files_c2c` | 源端只在最后回一包结果,因此不报中间进度;取消/超时按既有路径收尾 |
| `search_file` | 命中数在客户端,服务端只在收尾时报一次结果(见下) |
| `chat_wait` | 等待期无中间量,取消即时生效 |
**取消**:三条入口共用一个取消位(`McpCallContext::cancelled`)
- `notifications/cancelled`(`params.requestId` 按 JSON-RPC id 精确匹配,字符串与数字不混用);
- `mcp_cancel_session`(按 request_id / host id / session_id);
- SSE 流写失败(客户端已断开)。
所有长等待都改成「≤500ms 一片 + 每片检查取消位」(`WaitWithCancel`),取消后直接落到各函数
**既有的超时/放弃分支**:`MarkLateFirstPacketForTool` 照登、子连接照关、挂起项照删。因此取消
不需要第二套清理逻辑,也满足「取消后主机 1s 内释放」。取消导致的失败结果由分发层统一改写成
`-32800`(已经拿到成功结果则照实返回)。
### D.5 `mcp_list_sessions` / `mcp_cancel_session`(§5.10)
- `mcp_list_sessions`:一次快照列出在飞 `tools/call`(含 JSON-RPC `request_id`)、挂起中的一次性
请求、终端、远程控制、文件传输、远程交谈;字段 `host_id/kind/tool/session_id/request_id/busy/
elapsed_ms/idle_ms`,可选 `kind` 过滤。纯本地,**不受功能开关与只读模式限制**。
- `mcp_cancel_session`:按 `request_id`(精确)或 `id`/`session_id`(条件)取消,返回
`{cancelled, released, waited_ms, matched}`;最多等 2s 让工具线程走完清理,`released` 说明
主机是否真的松开。
- `-32003` 的文案统一追加占用者:`Device busy: another request is pending for this host
(tool=download_file, elapsed=12s)`。`DescribeBusy` 会排除发起本次错误的那个调用自身。
### D.6 已知边界
- SSE 请求会占住 httplib 的一个 worker 线程直到工具结束(线程池 32);单机管理场景足够,
不作为多租户端点使用。
- `search_file` 被取消时返回**已收到的部分结果**(`finished=false`),不是 `-32800`:搜索是只读
累积操作,部分结果对调用方更有用;它同样在 ≤1s 内释放主机。
- `mcp_cancel_session` 找不到匹配项时返回 `cancelled:0`(不是错误)——请求可能已经结束,
或 `request_id` 的 JSON 类型与调用时不一致。
+6 -6
View File
@@ -153,8 +153,8 @@ FindMainContext → -32002 主机不存在/离线
clientType==LNX/MAC → -32005 仅 Windows
command 为空 → -32602
mcp.IsReadonly() → -32006 只读模式默认开,需 McpReadonly=0
含 &|<>^ 五元字符 → -32008 防注入绕过白名单
含控制字符(\r\n 等 <0x20) → -32008 防换行拆分绕过白名单
含 &|<>^ 五元字符 → -32012 防注入绕过白名单(-32008 为历史别名)
含控制字符(\r\n 等 <0x20) → -32012 防换行拆分绕过白名单
白名单前缀校验 → -32007 不在白名单
```
@@ -237,7 +237,7 @@ SweepIdleTerminals(300)
ResolveTerminalSessionHost
session_id 为空 → -32602
command 为空 → -32602
command 含 & 或 | → -32008(正确性门,见 §4.6)
command 含 & 或 | → -32012(正确性门,见 §4.6)
nonce = 随机 8 hex
BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty)
→ false 则 -32002(不存在/不匹配/未就绪/忙碌/已关)
@@ -273,7 +273,7 @@ CloseTermSession(devId, sessionId)
### 4.6 正确性门 `&|`(非安全门)
`terminal_exec` **拒绝含 `&` 或 `|` 的命令**(`find_first_of("&|")`,含 `&&`/`||`/`|`),报 `-32008`。原因:哨兵包装 `cmd 2>&1 && echo ... || echo ...` 假定命令是「扁平」的,命令内含 `&`/`|` 会与包装的控制操作符合流、导致退出码失真/输出归属不清。
`terminal_exec` **拒绝含 `&` 或 `|` 的命令**(`find_first_of("&|")`,含 `&&`/`||`/`|`),报 `-32012`(历史别名 `-32008`)。原因:哨兵包装 `cmd 2>&1 && echo ... || echo ...` 假定命令是「扁平」的,命令内含 `&`/`|` 会与包装的控制操作符合流、导致退出码失真/输出归属不清。
- 这是**正确性限制,不是白名单**——持久终端本就不设白名单。
- 同样拒绝 `<0x20` 的控制字符(`\r`/`\n`):换行会把命令拆成多行、只有末行被哨兵包装,导致退出码与输出归属失真。
@@ -415,7 +415,7 @@ McpServer().SetTerminalEnabled(THIS_CFG.GetInt("settings", "McpTerminal", 0) !=
| `-32005` | 非 Windows | LNX/MAC 客户端 |
| `-32006` | 已禁用/只读 | `IsReadonly()` 或 `!IsTerminalEnabled()` |
| `-32007` | 白名单拒绝 | `IsCommandAllowed` false |
| `-32008` | 含禁用字符 | `exec_command` 的 `&|<>^`;`terminal_exec` 的 `&|` |
| `-32012` | 含禁用字符 | `exec_command` 的 `&|<>^`;`terminal_exec` 的 `&|`(早期版本用 `-32008`,同一语义) |
| `-32602` | 参数非法 | `ParseHostIdArg` 失败、缺 required 参数 |
| `-32700` | JSON 解析错误 | 请求体非合法 JSON-RPC |
@@ -446,7 +446,7 @@ McpServer().SetTerminalEnabled(THIS_CFG.GetInt("settings", "McpTerminal", 0) !=
### 10.5 stdout 里出现命令本身 / 哨兵
- 命令本身回显 = ConPTY 输入回显,已由 `StripEchoedCommand` 服务端剔除(§2.4)。若仍出现,检查是否该行因编码(非 PTY 老管道的 GBK)与 `echoedLine` 字节不一致而 `find` 不到——老管道本应无回显。
- 哨兵 `__MCP_DONE_...` 出现 = 哨兵截断/清洗异常,通常意味着命令含 `&|` 破坏了控制操作符链(持久终端会提前 `-32008` 拒绝,一次性会 `-32008` 拒绝五元字符)。
- 哨兵 `__MCP_DONE_...` 出现 = 哨兵截断/清洗异常,通常意味着命令含 `&|` 破坏了控制操作符链(持久终端会提前 `-32012` 拒绝,一次性会 `-32012` 拒绝五元字符)。
### 10.6 中文/乱码