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

+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 类型与调用时不一致。