diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index 575f375..1d59c55 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -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: `)区分开。 - **新客户端把失败改成结构化回报**(`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` 丢弃)。 diff --git a/docs/Mcp_Next_Plan.md b/docs/Mcp_Next_Plan.md index a1d1c8c..82715a7 100644 --- a/docs/Mcp_Next_Plan.md +++ b/docs/Mcp_Next_Plan.md @@ -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 的挂起项以 `"/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 类型与调用时不一致。 diff --git a/docs/Mcp_Terminal_Design.md b/docs/Mcp_Terminal_Design.md index c6be08e..e47d7ce 100644 --- a/docs/Mcp_Terminal_Design.md +++ b/docs/Mcp_Terminal_Design.md @@ -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 中文/乱码 diff --git a/server/2015Remote/McpChat.cpp b/server/2015Remote/McpChat.cpp index fbe073a..bc0107c 100644 --- a/server/2015Remote/McpChat.cpp +++ b/server/2015Remote/McpChat.cpp @@ -490,6 +490,10 @@ static std::string BuildChatWait(const Json::Value& id, const Json::Value& args, case CMcpServer::ChatWaitResult::Busy: return BuildError(id, kErrBusy, "Another chat_wait is already pending for this session"); + case CMcpServer::ChatWaitResult::Cancelled: + // 会话本身仍然有效;回 -32800 让调用方知道是自己取消了等待。 + return BuildError(id, kErrCancelled, + "Waiting cancelled by client; the chat session is still open"); case CMcpServer::ChatWaitResult::Closed: case CMcpServer::ChatWaitResult::Timeout: case CMcpServer::ChatWaitResult::Ok: @@ -867,10 +871,14 @@ CMcpServer::ChatReadyResult CMcpServer::WaitChatReady(uint64_t device_id, if (s->closed) return ChatReadyResult::Closed; if (s->started && now >= s->readyAt) return ChatReadyResult::Ok; if (now >= deadline) return ChatReadyResult::Timeout; + if (McpCallCancelled()) return ChatReadyResult::Timeout; // P11:取消按超时收尾 // 绑定通知到达后只需等到 readyAt,不要一直睡到整个 open 超时。 steady_clock::time_point wake = deadline; if (s->started && s->readyAt < wake) wake = s->readyAt; + // 500ms 上限:唤醒即可响应取消。 + const steady_clock::time_point slice = now + std::chrono::milliseconds(500); + if (slice < wake) wake = slice; m_ChatCv.wait_until(lk, wake); } } @@ -923,7 +931,11 @@ CMcpServer::ChatWaitResult CMcpServer::WaitChatMessages( while (s->inbox.empty() && !s->closed) { if (timeoutMs <= 0 || steady_clock::now() >= deadline) break; - m_ChatCv.wait_until(lk, deadline); + if (McpCallCancelled()) break; // P11:≤500ms 内响应取消 + // 500ms 一片:允许取消及时生效;无取消时与整段等待等价。 + auto until = steady_clock::now() + std::chrono::milliseconds(500); + if (until > deadline) until = deadline; + m_ChatCv.wait_until(lk, until); } while (!s->inbox.empty() && out.size() < maxMessages) { @@ -939,6 +951,8 @@ CMcpServer::ChatWaitResult CMcpServer::WaitChatMessages( s->waitBusy = false; if (!s->closed) s->lastActiveAt = time(nullptr); + // 取消优先于「等到超时」:没有消息且是被取消唤醒的,如实回报(会话本身不受影响)。 + if (out.empty() && McpCallCancelled() && !closed) return ChatWaitResult::Cancelled; return timedOut ? ChatWaitResult::Timeout : ChatWaitResult::Ok; } diff --git a/server/2015Remote/McpInternal.cpp b/server/2015Remote/McpInternal.cpp index 15097d9..053fe3c 100644 --- a/server/2015Remote/McpInternal.cpp +++ b/server/2015Remote/McpInternal.cpp @@ -383,6 +383,10 @@ const ToolHints kToolHints[] = { { "get_activity_history", true, false, true, true }, { "get_audit_log", true, false, true, false }, { "get_server_status", true, false, true, false }, + // P11:在飞会话的观测与取消。取消只改服务端自己的等待状态(被取消的请求立即走既有 + // 清理路径),不改主机数据;按 request_id/session_id 取消天然幂等,故非破坏且幂等。 + { "mcp_list_sessions", true, false, true, false }, + { "mcp_cancel_session", false, false, true, false }, // --- 主机只读 --- { "list_processes", true, false, true, true }, { "list_windows", true, false, true, true }, diff --git a/server/2015Remote/McpInternal.h b/server/2015Remote/McpInternal.h index 8d72c96..3c1447e 100644 --- a/server/2015Remote/McpInternal.h +++ b/server/2015Remote/McpInternal.h @@ -20,6 +20,18 @@ class context; namespace McpInternal { +// ===== 错误码(-32000 系列,见 docs/Mcp_Design.md §12)===== +// +// -32012 参数被校验拒绝:参数内容非法、按 message 改正后重试即可(shell 元字符、 +// 控制字符之类)。-32008 是同一语义的历史别名:早期实现用它,已发布的文档与客户端 +// 可能仍在匹配,故保留不改;新代码一律用 -32012。 +const int kErrValidation = -32012; +const int kErrValidationOld = -32008; // 历史别名,勿新增使用 + +// -32800 请求被客户端取消:收到 notifications/cancelled 或 mcp_cancel_session 后, +// 在飞的工具提前退出(走各自的超时清理路径),结果统一以这个码回报。 +const int kErrCancelled = -32800; + // Json::Value → 紧凑 JSON 字符串 std::string JsonToString(const Json::Value& v); diff --git a/server/2015Remote/McpMachine.cpp b/server/2015Remote/McpMachine.cpp index ca3486b..f5f8e7e 100644 --- a/server/2015Remote/McpMachine.cpp +++ b/server/2015Remote/McpMachine.cpp @@ -260,6 +260,11 @@ Json::Value ActionOutputSchema() { props["state"] = PropStr(u8"复核时观测到的状态"); props["reason"] = PropStr(u8"ok=false 时的原因"); props["message"] = PropStr(u8"人类可读的说明"); + props["dry_run"] = PropBool(u8"true 表示只是试运行,没有下发动作"); + Json::Value detail(Json::objectValue); + detail["type"] = "object"; + detail["description"] = u8"dry_run 时目标对象的完整字段"; + props["detail"] = detail; Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; @@ -303,6 +308,24 @@ std::string BuildListResult(const Json::Value& id, const char* arrayKey, return BuildStructuredResult(id, sc, text); } +// dry_run 的公共结果(§5.5):目标已在最新快照里校验存在,但没有下发任何动作。 +// 字段与 ActionOutputSchema 一致(ok/dry_run/action/target/state/detail), +// changed/verified 不适用故省略。 +std::string BuildDryRunResult(const Json::Value& id, const std::string& action, + const std::string& target, const std::string& state, + const Json::Value& detail) { + Json::Value sc(Json::objectValue); + sc["ok"] = true; + sc["dry_run"] = true; + sc["action"] = action; + sc["target"] = target; + sc["state"] = state; + sc["detail"] = detail; + std::string text = std::string(u8"试运行:目标已确认存在(") + target + + u8"),未下发任何动作;当前状态 state=" + state; + return BuildStructuredResult(id, sc, text); +} + std::string BuildActionResult(const Json::Value& id, bool ok, bool verified, bool changed, const std::string& action, const std::string& target, const std::string& state, const std::string& reason, @@ -860,7 +883,7 @@ public: : mcp.BeginMachineSession(m_dev, tool, ht.mainCtx); if (!began) { errJson = BuildError(id, kErrBusy, - "Device busy: another MCP request is pending for this host"); + BusyMessage("Device busy: another MCP request is pending for this host", m_dev)); return false; } m_open = true; @@ -1042,8 +1065,13 @@ CMcpServer::KeylogWaitResult CMcpServer::WaitKeylogData(uint64_t device_id, std: if (r.closed) return KeylogWaitResult::Closed; if (deadline > r.deadline) deadline = r.deadline; - if (std::chrono::steady_clock::now() >= deadline) return KeylogWaitResult::Timeout; - m_PendingCv.wait_until(lk, deadline); + const auto now = std::chrono::steady_clock::now(); + if (now >= deadline) return KeylogWaitResult::Timeout; + if (McpCallCancelled()) return KeylogWaitResult::Timeout; // P11:取消按超时收尾 + // 500ms 一片:取消后才能及时回到调用方的清理分支。 + auto until = now + std::chrono::milliseconds(500); + if (until > deadline) until = deadline; + m_PendingCv.wait_until(lk, until); } } @@ -1099,7 +1127,11 @@ CMcpServer::ManagedWaitResult CMcpServer::WaitManagedPacket(uint64_t device_id, if (waitUntil > r.deadline) waitUntil = r.deadline; auto now = std::chrono::steady_clock::now(); if (now >= waitUntil) return ManagedWaitResult::Timeout; - m_PendingCv.wait_until(lk, waitUntil); + if (McpCallCancelled()) return ManagedWaitResult::Timeout; // P11:取消按超时收尾 + // 500ms 一片:取消后才能及时回到调用方的清理分支。 + auto until = now + std::chrono::milliseconds(500); + if (until > waitUntil) until = waitUntil; + m_PendingCv.wait_until(lk, until); } } @@ -2141,6 +2173,15 @@ static std::string BuildHostControlProcess(const Json::Value& id, const Json::Va proc->get("name", Json::Value("")).asString() + ")"); } + // dry_run(§5.5):目标已在最新进程列表里核实,就此返回,不下发冻结/解冻。 + if (GetBoolArg(args, "dry_run", false)) { + session.Finish(); + AuditManageAction(parent, ht.dev, "host_control_process", + action + " pid=" + std::to_string(pidFilter) + " result=dry_run"); + return BuildDryRunResult(id, action, "pid=" + std::to_string(pidFilter), + proc->get("name", Json::Value("")).asString(), *proc); + } + std::vector pkt(5); pkt[0] = (action == "freeze") ? (BYTE)COMMAND_PROCESS_FREEZING : (BYTE)COMMAND_PROCESS_THAW; @@ -2209,12 +2250,21 @@ static std::string BuildHostControlWindow(const Json::Value& id, const Json::Val Json::Value pre; std::string perr; if (!ParseWindows(data, 936, pre, perr)) return ParseErrorToJson(id, "window list", perr); - if (!FindWindow(pre, hwnd)) { + const Json::Value* win = FindWindow(pre, hwnd); + if (!win) { AuditManageAction(parent, ht.dev, "host_control_window", action + " hwnd=" + std::to_string(hwnd) + " result=not_found"); return NotFoundJson(id, "window hwnd=" + std::to_string(hwnd)); } + // dry_run(§5.5):hwnd 在最新可见窗口列表里,就此返回,不下发窗口操作。 + if (GetBoolArg(args, "dry_run", false)) { + session.Finish(); + AuditManageAction(parent, ht.dev, "host_control_window", + action + " hwnd=" + std::to_string(hwnd) + " result=dry_run"); + return BuildDryRunResult(id, action, "hwnd=" + std::to_string(hwnd), "visible", *win); + } + // [11][hwnd][SW_*] + 零填充到 20 字节(与 MFC 下发格式一致;客户端只读前 9 字节) std::vector pkt(20, 0); pkt[0] = (BYTE)COMMAND_WINDOW_OPERATE; @@ -2304,6 +2354,15 @@ static std::string BuildHostControlService(const Json::Value& id, const Json::Va std::string initial = svc->get("state", Json::Value("")).asString(); + // dry_run(§5.5):服务已在最新列表里核实,返回当前状态后收手(不判断是否 no-op, + // 由调用方看到 state 自行决定)。 + if (GetBoolArg(args, "dry_run", false)) { + session.Finish(); + AuditManageAction(parent, ht.dev, "host_control_service", + action + " " + serviceName + " result=dry_run"); + return BuildDryRunResult(id, action, serviceName, initial, *svc); + } + // 客户端只在状态满足时才真正动作:先按同样的规则判断,避免把 no-op 报成成功。 auto stateIs = [](const std::string& s, const char* want) { return EqualsCI(s, want); }; if (action == "start" && stateIs(initial, "Running")) { @@ -2459,6 +2518,15 @@ static std::string BuildHostControlTask(const Json::Value& id, const Json::Value std::string folder = hits[0]->get("folder", Json::Value("\\")).asString(); if (folder.empty()) folder = "\\"; + // dry_run(§5.5):任务已在最新列表里核实(含同名歧义检查),返回当前状态后收手。 + if (GetBoolArg(args, "dry_run", false)) { + session.Finish(); + AuditManageAction(parent, ht.dev, "host_control_task", + action + " " + taskName + " result=dry_run"); + return BuildDryRunResult(id, action, taskName + " folder=" + folder, + hits[0]->get("status", Json::Value("")).asString(), *hits[0]); + } + std::string ansiFolder, ansiName; if (!Utf8ToCpExact(folder, 936, ansiFolder) || !Utf8ToCpExact(taskName, 936, ansiName)) { return BuildError(id, -32602, @@ -2837,8 +2905,9 @@ void AppendTools(Json::Value& tools) { props["action"] = PropStrEnum(u8"freeze=挂起进程,thaw=恢复进程", { "freeze", "thaw" }); props["pid"] = PropInt(u8"目标进程 PID"); props["name"] = PropStr(u8"可选:校验进程名,防止 PID 被系统复用后误操作"); + props["dry_run"] = PropBool(u8"true 时只校验 PID/名称存在并返回目标进程,不冻结/解冻,默认 false"); AddTool(tools, "host_control_process", - u8"挂起或恢复在线 Windows 主机上的一个进程(对应主机管理「进程」右键的冻结/解冻)。可能导致目标进程超时或崩溃,故归入危险操作:需要同时开启 McpMachineDangerous。动作没有回执,客户端也不回报结果;工具会在动作后重新拉取进程列表确认目标仍存在。", + u8"挂起或恢复在线 Windows 主机上的一个进程(对应主机管理「进程」右键的冻结/解冻)。可能导致目标进程超时或崩溃,故归入危险操作:需要同时开启 McpMachineDangerous。动作没有回执,客户端也不回报结果;工具会在动作后重新拉取进程列表确认目标仍存在。dry_run=true 只核实目标并返回它,不下发动作。", MakeSchema(props, { "id", "action", "pid" }), ActionOutputSchema()); } @@ -2854,8 +2923,9 @@ void AppendTools(Json::Value& tools) { hwnd["type"] = types; hwnd["description"] = u8"窗口句柄,取 host_list_windows 的 hwnd;整数或 0x 前缀字符串"; props["hwnd"] = hwnd; + props["dry_run"] = PropBool(u8"true 时只校验 hwnd 仍在可见窗口列表里并返回该窗口,不下发操作,默认 false"); AddTool(tools, "host_control_window", - u8"对在线 Windows 主机的窗口执行可恢复操作:restore(还原)/hide(隐藏)/maximize(最大化)/minimize(最小化)。hwnd 取 host_list_windows 或 list_windows 返回的 hwnd。动作后重新枚举可见窗口复核:hide 后 hwnd 应消失,其余动作后仍应存在。不提供关闭窗口——需要 close / show 时改用 operate_window。", + u8"对在线 Windows 主机的窗口执行可恢复操作:restore(还原)/hide(隐藏)/maximize(最大化)/minimize(最小化)。hwnd 取 host_list_windows 或 list_windows 返回的 hwnd。动作后重新枚举可见窗口复核:hide 后 hwnd 应消失,其余动作后仍应存在。不提供关闭窗口——需要 close / show 时改用 operate_window。dry_run=true 只核实 hwnd 并返回窗口信息。", MakeSchema(props, { "id", "action", "hwnd" }), ActionOutputSchema()); } @@ -2865,8 +2935,9 @@ void AppendTools(Json::Value& tools) { props["action"] = PropStrEnum(u8"start/stop/pause/continue/restart", { "start", "stop", "pause", "continue", "restart" }); props["name"] = PropStr(u8"服务名(ServiceName,不是显示名),取 host_list_*_services 的 name"); + props["dry_run"] = PropBool(u8"true 时只校验服务存在并返回当前状态,不下发控制命令,默认 false"); AddTool(tools, "host_control_service", - u8"控制在线 Windows 主机的服务:start/stop/pause/continue/restart。客户端对每次控制都会自动回一份刷新后的服务列表,工具据此复核状态并如实返回 ok;stop 与 restart 归入危险操作,需要同时开启 McpMachineDangerous。restart 先 stop 再 start。不提供删除服务。", + u8"控制在线 Windows 主机的服务:start/stop/pause/continue/restart。客户端对每次控制都会自动回一份刷新后的服务列表,工具据此复核状态并如实返回 ok;stop 与 restart 归入危险操作,需要同时开启 McpMachineDangerous。restart 先 stop 再 start。不提供删除服务。dry_run=true 只核实服务并返回当前状态,不下发命令(是否已是目标状态由你按 state 判断)。", MakeSchema(props, { "id", "action", "name" }), ActionOutputSchema()); } @@ -2876,8 +2947,9 @@ void AppendTools(Json::Value& tools) { props["action"] = PropStrEnum(u8"run=立即运行,stop=停止正在运行的任务", { "run", "stop" }); props["name"] = PropStr(u8"任务名,取 host_list_scheduled_tasks 的 name"); props["folder"] = PropStr(u8"可选:任务所在文件夹;同名任务存在多个时必填"); + props["dry_run"] = PropBool(u8"true 时只校验任务存在(含同名歧义检查)并返回当前状态,不下发 run/stop,默认 false"); AddTool(tools, "host_control_task", - u8"运行或停止在线 Windows 主机的计划任务(主机管理「计划任务」右键)。客户端无回执,工具只复核任务仍存在并报告当前状态,不声称任务一定执行成功。不提供创建/删除任务。", + u8"运行或停止在线 Windows 主机的计划任务(主机管理「计划任务」右键)。客户端无回执,工具只复核任务仍存在并报告当前状态,不声称任务一定执行成功。不提供创建/删除任务。dry_run=true 只核实任务并返回当前状态。", MakeSchema(props, { "id", "action", "name" }), ActionOutputSchema()); } diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 1cd8b78..85144a1 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -39,6 +39,231 @@ using namespace McpInternal; namespace { +// JSON-RPC id 的「展示文本」:字符串 id 取原文、整数 id 取十进制数字。 +// 与紧凑序列化(字符串带引号)相对:mcp_list_sessions 输出的是文本,调用方原样 +// 回传给 mcp_cancel_session / notifications/cancelled 也能命中。 +std::string McpRequestIdText(const Json::Value& v) { + if (v.isString()) return v.asString(); + if (v.isInt64()) return std::to_string(v.asInt64()); + if (v.isUInt64()) return std::to_string(v.asUInt64()); + return JsonToString(v); // 其余类型(null / 浮点)不会出现在 tools/call 的 id 上 +} + +} // namespace + +// ============================================================================ +// P11:progress / cancelled —— 在飞调用上下文与 SSE 进度通道 +// ============================================================================ +// +// 传输层事实:本服务端每个 POST 只回一个 JSON 响应,没有 SSE。MCP Streamable HTTP +// 允许(并要求客户端接受)POST 的响应是 text/event-stream——带 _meta.progressToken +// 的 tools/call 就走这条路径:工具在独立线程执行,进度通知与最终响应都从同一个 +// chunked 流写出。不需要额外的 GET 流,也不影响不带 token 的请求(仍是一次性 JSON)。 +namespace { + +// 客户端读得慢时最多积压的进度通知条数:进度是「最新值有意义」的信号,丢最旧的。 +const size_t kProgressQueueMax = 64; + +std::string SseMessage(const std::string& json) { + return "event: message\ndata: " + json + "\n\n"; +} + +// 进度数值:本服务端的进度都是整数(字节/文件数/条数)。%g 只有 6 位有效数字, +// 67108864 会被写成 6.71089e+07 —— 客户端拿它算百分比就偏了,故整数值按十进制整数 +// 输出;非整数(理论上的比例值)才退回 %g。 +std::string FormatProgressNum(double v) { + char buf[64]; + if (v >= -9.0e15 && v <= 9.0e15 && v == (double)(long long)v) + _snprintf_s(buf, sizeof(buf), _TRUNCATE, "%lld", (long long)v); + else + _snprintf_s(buf, sizeof(buf), _TRUNCATE, "%g", v); + return buf; +} + +} // namespace + +// 一次 SSE 请求的写出队列。工具线程 Push,httplib 的 content provider 线程 Pump。 +struct McpProgressChannel { + std::mutex mu; + std::condition_variable cv; + std::deque events; + bool finished = false; + std::string finalBody; + // 反向引用用 weak_ptr:McpCallContext 持有 channel,不能形成循环。 + std::weak_ptr call; + + void Push(std::string ev) { + std::lock_guard lk(mu); + if (events.size() >= kProgressQueueMax) events.pop_front(); + events.push_back(std::move(ev)); + cv.notify_one(); + } + + void Finish(std::string body) { + { + std::lock_guard lk(mu); + finalBody = std::move(body); + finished = true; + } + cv.notify_one(); + } + + // 由 httplib 反复调用:有事件就写一条,收尾时写最终响应并结束流。 + // 客户端提前断开(write 失败)→ 置取消位,让仍在跑的工具尽快停下并清理。 + bool Pump(httplib::DataSink& sink) { + std::unique_lock lk(mu); + while (events.empty() && !finished) + cv.wait_for(lk, std::chrono::milliseconds(500)); + + if (!events.empty()) { + std::string ev = std::move(events.front()); + events.pop_front(); + lk.unlock(); + if (!sink.write(ev.data(), ev.size())) { + if (auto c = call.lock()) c->cancelled.store(true); + return false; + } + return true; + } + + std::string body = std::move(finalBody); + lk.unlock(); + std::string ev = SseMessage(body); + sink.write(ev.data(), ev.size()); // 写失败也要收尾(客户端已走,done 自己会跳过) + // 必须显式收尾:httplib 的 chunked provider 在返回 false 时不会补终止块 + // (write_content_chunked 直接返回 Canceled),客户端会看到「传输被截断」 + // —— curl 报 18,.NET 报 "Unable to read data from the transport connection"。 + // done() 会写出 0\r\n\r\n 并把 data_available 置 false,因此这里返回 true, + // 让 provider 循环按正常结束退出。 + sink.done(); + return true; + } +}; + +void McpCallContext::EmitProgress(double current, double total, bool hasTotal) { + if (!hasProgressToken || !channel) return; + { + std::lock_guard lk(progressMu); + const auto now = std::chrono::steady_clock::now(); + if (lastProgressAt.time_since_epoch().count() != 0 && + now - lastProgressAt < std::chrono::milliseconds(1000)) + return; + lastProgressAt = now; + } + std::string json = "{\"jsonrpc\":\"2.0\",\"method\":\"notifications/progress\",\"params\":{\"progressToken\":"; + json += progressTokenJson; + json += ",\"progress\":"; + json += FormatProgressNum(current); + if (hasTotal) { + json += ",\"total\":"; + json += FormatProgressNum(total); + } + json += "}}"; + channel->Push(SseMessage(json)); +} + +// 「当前线程正在跑的 MCP 调用」上下文。工具实现(含 McpMachine.cpp / McpChat.cpp)在 +// 工具线程上直接取它,MFC 的 IO/UI 线程永远是空的。 +// +// 这里刻意不用 C++ 的 thread_local:本工程有一部分代码跑在 shellcode / MemoryModule +// 手工映射出来的线程上(见 common/SafeString.h 的同类告警),实测给服务端加一个静态 +// thread_local(哪怕只是一个 int)就会让进程启动约 1s 后跳飞。改用 FLS(Fiber Local +// Storage):纯 Win32 的每线程槽,不依赖 PE 的 TLS 目录,线程退出时由系统回调释放。 +namespace { + +DWORD g_mcpCallSlot = FLS_OUT_OF_INDEXES; + +using McpCallSlotPtr = std::shared_ptr*; + +void NTAPI McpCallSlotDetach(void* p) { delete static_cast(p); } + +// 静态构造时取槽位:FlsAlloc 只为整个进程分配一个索引,与线程数无关。 +struct McpCallSlotInit { + McpCallSlotInit() { g_mcpCallSlot = FlsAlloc(McpCallSlotDetach); } +} g_mcpCallSlotInit; + +inline McpCallSlotPtr LoadCallSlot() { + if (g_mcpCallSlot == FLS_OUT_OF_INDEXES) return nullptr; + return static_cast(FlsGetValue(g_mcpCallSlot)); +} + +} // namespace + +std::shared_ptr CurrentMcpCall() { + McpCallSlotPtr p = LoadCallSlot(); + return p ? *p : std::shared_ptr(); +} + +bool McpCallCancelled() { + McpCallSlotPtr p = LoadCallSlot(); + return p && *p && (*p)->IsCancelled(); +} + +void McpCallProgress(double current) { + McpCallSlotPtr p = LoadCallSlot(); + if (p && *p) (*p)->EmitProgress(current, 0, false); +} + +void McpCallProgress(double current, double total) { + McpCallSlotPtr p = LoadCallSlot(); + if (p && *p) (*p)->EmitProgress(current, total, true); +} + +namespace { +// 作用域内把当前线程的在飞上下文设为 call,离开时恢复上一层(普通路径与 SSE 工具线程共用)。 +// 所有权:槽里保存的是堆上那份 shared_ptr 副本,离开时 delete 掉(释放本层引用); +// 上一层指针仍由外层 McpCallScope 拥有,这里只把槽位恢复回去。 +struct McpCallScope { + explicit McpCallScope(std::shared_ptr c) { + prev_ = LoadCallSlot(); + auto slot = new std::shared_ptr(std::move(c)); + if (g_mcpCallSlot == FLS_OUT_OF_INDEXES || !FlsSetValue(g_mcpCallSlot, slot)) { + delete slot; // 取不到槽位时退化为「本线程没有在飞调用」,工具照常执行 + return; + } + set_ = true; + } + ~McpCallScope() { + if (!set_) return; + delete LoadCallSlot(); // 释放本层持有的引用(槽位里的那份) + FlsSetValue(g_mcpCallSlot, prev_); + } + McpCallScope(const McpCallScope&) = delete; + McpCallScope& operator=(const McpCallScope&) = delete; + +private: + McpCallSlotPtr prev_ = nullptr; + bool set_ = false; +}; + +// 切片上限:取消后工具层最多再等这么久就回到自己的超时清理分支。 +const int kWaitCancelSliceMs = 500; + +std::chrono::steady_clock::time_point DeadlineAfter(int timeoutMs) { + return std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); +} + +// 带取消的有限期等待:把一次长等待切成 ≤500ms 的片,每片之间检查取消位。 +// 返回 pred 是否满足;超时与取消都返回 false —— 调用方按各自既有的超时分支清理, +// 取消本身不需要另写一条清理路径(失败结果由分发层统一改写成 -32800)。 +template +bool WaitWithCancel(std::unique_lock& lk, std::condition_variable& cv, + std::chrono::steady_clock::time_point deadline, Pred pred) { + for (;;) { + if (pred()) return true; + if (McpCallCancelled()) return false; + const auto now = std::chrono::steady_clock::now(); + if (now >= deadline) return false; + auto slice = deadline - now; + if (slice > std::chrono::milliseconds(kWaitCancelSliceMs)) + slice = std::chrono::milliseconds(kWaitCancelSliceMs); + cv.wait_for(lk, slice); + } +} +} // namespace + +namespace { + // P2b 工具等待响应的超时(ms)改为运行期可配:CMcpServer::ToolTimeoutMs(),默认 20000, // 由 settings.ini 的 [settings] McpToolTimeoutMs 覆盖(见 2015RemoteDlg 的 MCP 初始化块)。 @@ -69,14 +294,18 @@ const char* kServerInstructions = u8"3) 错误码与动作\n" u8"-32002 主机离线或不存在:先刷新主机列表再选,不要拿旧快照反复重试。\n" u8"-32003 主机忙:同一台主机同一时刻只允许一个请求在飞(列表、截屏、文件、管理动作共用这一道锁," - u8"文件传输会话另有一道互斥),并发重试只会继续被拒;等前一个结束,或先关闭相关会话。\n" + u8"文件传输会话另有一道互斥),并发重试只会继续被拒;message 末尾会点名占用者与已持续时长," + u8"用 mcp_list_sessions 可看全部会话,确需打断(例如上一条请求已无意义)用 mcp_cancel_session 释放。\n" u8"-32004 命令未能送达主机:多半是链路瞬断,可重试一次。\n" u8"-32005 该主机不支持这项能力:换主机或换工具,改参数没有用。\n" u8"-32006 策略拒绝:开关未开或只读模式,重试无效,需要管理员改服务端配置。\n" u8"-32007 不在命令白名单:换成白名单内的命令,重试无效。\n" - u8"-32008 参数被校验拒绝(shell 元字符、控制字符、多显示器等):按 message 修正参数后重试。\n" + u8"-32012 参数被校验拒绝(命令里的 shell 元字符、控制字符等):按 message 修正参数后重试。" + u8"历史版本用 -32008 表示同一语义,遇到时按同样方式处理。\n" u8"-32009 目标不存在(文件/目录等):先列一次确认目标,再重试。\n" u8"-32001 超时:可加大 timeout_ms 重试一次;持续超时说明主机卡住。\n" + u8"-32800 请求被取消:这是客户端自己取消(notifications/cancelled / mcp_cancel_session / 连接断开)" + u8"导致的中止,不是主机故障;主机占用已释放,可以直接重试。\n" u8"-32602 参数错误:按 message 修正后重试。\n" u8"\n" u8"4) 典型编排\n" @@ -1047,6 +1276,11 @@ Json::Value BuildKillProcessInputSchema() { pidsProp["description"] = u8"要终止的进程 PID 列表(至少 1 个)"; props["pids"] = pidsProp; + Json::Value dryRunProp(Json::objectValue); + dryRunProp["type"] = "boolean"; + dryRunProp["description"] = u8"true 时只校验 PID 是否还存在并返回将被影响的对象,不发送任何终止命令(默认 false)"; + props["dry_run"] = dryRunProp; + return FinalizeIdSchema(props, { "pids" }); } @@ -1060,6 +1294,21 @@ Json::Value BuildKillProcessOutputSchema() { remProp["description"] = u8"杀完后仍在运行的 PID(含权限不足未能终止的)"; props["remaining"] = remProp; + Json::Value dryProp(Json::objectValue); + dryProp["type"] = "boolean"; + dryProp["description"] = u8"true 表示本次只是试运行(dry_run),没有发送终止命令"; + props["dry_run"] = dryProp; + + Json::Value targetsProp(Json::objectValue); + targetsProp["type"] = "array"; + targetsProp["description"] = u8"dry_run 时将被终止的进程(pid/name/path)"; + props["targets"] = targetsProp; + + Json::Value missingProp(Json::objectValue); + missingProp["type"] = "array"; + missingProp["description"] = u8"dry_run 时已不存在的 PID"; + props["missing"] = missingProp; + Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; @@ -1080,11 +1329,39 @@ Json::Value BuildOperateWindowInputSchema() { actionProp["description"] = u8"操作:close(关闭) | show(显示) | hide(隐藏) | minimize(最小化) | maximize(最大化) | restore(还原)"; props["action"] = actionProp; + Json::Value dryRunProp(Json::objectValue); + dryRunProp["type"] = "boolean"; + dryRunProp["description"] = u8"true 时只校验窗口是否还存在并返回将被影响的对象,不发送任何窗口命令(默认 false)"; + props["dry_run"] = dryRunProp; + return FinalizeIdSchema(props, { "hwnd", "action" }); } Json::Value BuildOperateWindowOutputSchema() { - return BuildOkOutputSchema(); + Json::Value props(Json::objectValue); + Json::Value ok(Json::objectValue); + ok["type"] = "boolean"; + ok["description"] = u8"命令已下发(不代表窗口已按预期变化)"; + props["ok"] = ok; + + Json::Value dryProp(Json::objectValue); + dryProp["type"] = "boolean"; + dryProp["description"] = u8"true 表示本次只是试运行(dry_run),没有发送窗口命令"; + props["dry_run"] = dryProp; + + Json::Value actionProp(Json::objectValue); + actionProp["type"] = "string"; + props["action"] = actionProp; + + Json::Value windowProp(Json::objectValue); + windowProp["type"] = "object"; + windowProp["description"] = u8"dry_run 时的目标窗口(hwnd/title/status/pid)"; + props["window"] = windowProp; + + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + return schema; } Json::Value BuildControlServiceInputSchema() { @@ -1117,11 +1394,54 @@ Json::Value BuildPowerActionInputSchema() { actionProp["description"] = u8"操作:logout(注销) | shutdown(关机) | reboot(重启)"; props["action"] = actionProp; + Json::Value waitProp(Json::objectValue); + waitProp["type"] = "boolean"; + waitProp["description"] = u8"true 时先等主机下线、再等它重新上线(默认 false,发完即返回)。超时不算失败,看返回的 went_offline / came_back。"; + props["wait"] = waitProp; + + Json::Value waitMsProp(Json::objectValue); + waitMsProp["type"] = "integer"; + waitMsProp["minimum"] = 1000; + waitMsProp["maximum"] = 600000; + waitMsProp["description"] = u8"等离线与等回线各自的时限(毫秒,默认 60000);一次调用最长约为 2×wait_ms"; + props["wait_ms"] = waitMsProp; + return FinalizeIdSchema(props, { "action" }); } +// power_action 的输出:sent 只代表命令写进了 socket(电源命令没有回执)。 +// wait=true 时用主连接在线状态验证:went_offline / came_back / elapsed_ms。 Json::Value BuildPowerActionOutputSchema() { - return BuildOkOutputSchema(); + Json::Value props(Json::objectValue); + Json::Value ok(Json::objectValue); + ok["type"] = "boolean"; + ok["description"] = u8"命令已下发(不代表已经关机/重启)"; + props["ok"] = ok; + + Json::Value sent(Json::objectValue); + sent["type"] = "boolean"; + sent["description"] = u8"命令已送达主机"; + props["sent"] = sent; + + Json::Value off(Json::objectValue); + off["type"] = "boolean"; + off["description"] = u8"主机是否真的下线了(wait=true 时观察到的;wait=false 恒为 false)"; + props["went_offline"] = off; + + Json::Value back(Json::objectValue); + back["type"] = "boolean"; + back["description"] = u8"主机下线后是否重新上线(logout 一般不会自动回来)"; + props["came_back"] = back; + + Json::Value elapsed(Json::objectValue); + elapsed["type"] = "integer"; + elapsed["description"] = u8"本次等待实际耗时(毫秒)"; + props["elapsed_ms"] = elapsed; + + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + return schema; } // list_registry 的 inputSchema(id 必填,path 可选;path 缺省/空 = 列根键) @@ -1788,6 +2108,93 @@ std::string BuildToolsListResult(const Json::Value& id) { tools.append(tool); } + // 11c) mcp_list_sessions / mcp_cancel_session(P11:服务端自身在飞会话的观测与取消) + // 纯本地:不向主机发报文,因此不受功能开关与只读模式影响(只读模式下也要能放开卡住的请求)。 + { + Json::Value tool(Json::objectValue); + tool["name"] = "mcp_list_sessions"; + tool["description"] = u8"列出服务端当前的会话:在飞 tools/call(kind=call,含 JSON-RPC request_id)、挂起中的一次性请求(pending)、持久终端、远程控制、文件传输、远程交谈。每项给出 host_id、tool、session_id/request_id、busy、已持续 elapsed_ms,长连接会话还给出距最后一次活动的 idle_ms。主机报 -32003「忙」时用它查是谁占着;要放开占用用 mcp_cancel_session。只读、纯内存。"; + + Json::Value inputSchema(Json::objectValue); + inputSchema["type"] = "object"; + Json::Value props(Json::objectValue); + Json::Value kindProp(Json::objectValue); + kindProp["type"] = "string"; + kindProp["enum"] = Json::Value(Json::arrayValue); + for (const char* k : { "call", "pending", "terminal", "remote_control", "file_transfer", "chat" }) + kindProp["enum"].append(k); + kindProp["description"] = u8"只列某一类会话;省略则全部列出。"; + props["kind"] = kindProp; + inputSchema["properties"] = props; + inputSchema["required"] = Json::Value(Json::arrayValue); + tool["inputSchema"] = inputSchema; + + Json::Value outProps(Json::objectValue); + Json::Value sessionsProp(Json::objectValue); + sessionsProp["type"] = "array"; + sessionsProp["description"] = u8"会话列表,每项含 host_id/kind/tool/session_id/request_id/busy/elapsed_ms/idle_ms"; + outProps["sessions"] = sessionsProp; + Json::Value countProp(Json::objectValue); + countProp["type"] = "integer"; + outProps["count"] = countProp; + Json::Value out(Json::objectValue); + out["type"] = "object"; + out["properties"] = outProps; + tool["outputSchema"] = out; + + tools.append(tool); + } + { + Json::Value tool(Json::objectValue); + tool["name"] = "mcp_cancel_session"; + tool["description"] = u8"取消在飞请求并尽快释放主机占用。给 request_id(tools/call 的 JSON-RPC id,类型要与调用时一致)精确取消一次调用,或按 id(主机)与 session_id 取消匹配的调用(两个都给则必须同时匹配)。工具层的等待在 ≤500ms 内退出并走既有清理路径;本工具最多等 2s,返回 cancelled(取消个数)、released(是否已释放占用)、waited_ms 与 matched(匹配到的会话)。被取消的请求以 -32800 结束。等价于对 SSE 流发 notifications/cancelled。"; + + Json::Value inputSchema(Json::objectValue); + inputSchema["type"] = "object"; + Json::Value props(Json::objectValue); + Json::Value reqProp(Json::objectValue); + Json::Value reqTypes(Json::arrayValue); + reqTypes.append("string"); + reqTypes.append("integer"); + reqProp["type"] = reqTypes; + reqProp["description"] = u8"要取消的那次 tools/call 的 JSON-RPC id(字符串或整数,类型必须与调用时一致)"; + props["request_id"] = reqProp; + Json::Value idProp(Json::objectValue); + idProp["type"] = "string"; + idProp["description"] = u8"主机 id:取消该主机上所有在飞请求"; + props["id"] = idProp; + Json::Value sidProp(Json::objectValue); + sidProp["type"] = "string"; + sidProp["description"] = u8"会话 id(terminal/remote_control/chat 的 session_id):只取消该会话上的在飞请求"; + props["session_id"] = sidProp; + inputSchema["properties"] = props; + inputSchema["required"] = Json::Value(Json::arrayValue); + tool["inputSchema"] = inputSchema; + + Json::Value outProps(Json::objectValue); + Json::Value cancelledProp(Json::objectValue); + cancelledProp["type"] = "integer"; + cancelledProp["description"] = u8"被取消的在飞调用个数"; + outProps["cancelled"] = cancelledProp; + Json::Value releasedProp(Json::objectValue); + releasedProp["type"] = "boolean"; + releasedProp["description"] = u8"2s 内匹配的会话是否已从服务端表中消失(主机已松开)"; + outProps["released"] = releasedProp; + Json::Value waitedProp(Json::objectValue); + waitedProp["type"] = "integer"; + outProps["waited_ms"] = waitedProp; + Json::Value matchedProp(Json::objectValue); + matchedProp["type"] = "array"; + matchedProp["description"] = u8"取消前匹配到的会话快照(同 mcp_list_sessions 的字段)"; + outProps["matched"] = matchedProp; + Json::Value out(Json::objectValue); + out["type"] = "object"; + out["properties"] = outProps; + tool["outputSchema"] = out; + + tools.append(tool); + } + // 12) list_registry(P3:注册表查询,列根键/列子键+值,仅 Windows,一次性子链接) { Json::Value tool(Json::objectValue); @@ -1936,7 +2343,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "kill_process"; - tool["description"] = u8"终止指定在线 Windows 或 Linux 主机上的一个或多个进程(Windows 用 TerminateProcess,Linux 用 SIGKILL 强制结束,不保存进程状态,可能造成数据丢失;Linux 会忽略 pid<=1)。返回 remaining(杀完后仍在运行的 PID)。不可撤销,请谨慎确认 PID。"; + tool["description"] = u8"终止指定在线 Windows 或 Linux 主机上的一个或多个进程(Windows 用 TerminateProcess,Linux 用 SIGKILL 强制结束,不保存进程状态,可能造成数据丢失;Linux 会忽略 pid<=1)。返回 remaining(杀完后仍在运行的 PID)。不可撤销,请谨慎确认 PID。dry_run=true 只取一次进程列表校验 PID 是否存在,返回将被影响的进程(targets)与已不存在的 PID(missing),不发送终止命令——执行前可先用它把清单交给用户确认。"; tool["inputSchema"] = BuildKillProcessInputSchema(); tool["outputSchema"] = BuildKillProcessOutputSchema(); tools.append(tool); @@ -1944,7 +2351,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "operate_window"; - tool["description"] = u8"对指定在线 Windows 主机的窗口执行操作:close(关闭)/show(显示)/hide(隐藏)/minimize(最小化)/maximize(最大化)/restore(还原)。hwnd 取 list_windows 或 host_list_windows 返回的 hwnd。ok 仅表示已下发(窗口句柄可能已失效)。关闭窗口只有本工具能做,host_control_window 不提供 close,且它会重新枚举可见窗口复核结果。"; + tool["description"] = u8"对指定在线 Windows 主机的窗口执行操作:close(关闭)/show(显示)/hide(隐藏)/minimize(最小化)/maximize(最大化)/restore(还原)。hwnd 取 list_windows 或 host_list_windows 返回的 hwnd。ok 仅表示已下发(窗口句柄可能已失效)。关闭窗口只有本工具能做,host_control_window 不提供 close,且它会重新枚举可见窗口复核结果。dry_run=true 只校验 hwnd 是否还在可见窗口列表里并返回该窗口信息,不发送任何命令。"; tool["inputSchema"] = BuildOperateWindowInputSchema(); tool["outputSchema"] = BuildOperateWindowOutputSchema(); tools.append(tool); @@ -1960,7 +2367,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "power_action"; - tool["description"] = u8"对指定在线 Windows 主机执行电源操作:logout(注销)/shutdown(关机)/reboot(重启)。不可撤销,主机将立即下线;需客户端管理员权限。"; + tool["description"] = u8"对指定在线 Windows 主机执行电源操作:logout(注销)/shutdown(关机)/reboot(重启)。不可撤销,主机将立即下线;需客户端管理员权限。ok/sent 只代表命令已送达,不代表真的关了机:要验证就给 wait=true,工具会等主机从在线列表消失(went_offline)、再等它重新上线(came_back),并返回 elapsed_ms;每个阶段最多等 wait_ms(默认 60000),等不到不算失败。注销后客户端一般不会自动回线。"; tool["inputSchema"] = BuildPowerActionInputSchema(); tool["outputSchema"] = BuildPowerActionOutputSchema(); tools.append(tool); @@ -2370,7 +2777,7 @@ std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, C CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_processes")) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_SYSTEM; if (!ctx->Send2Client(&cmd, 1)) { @@ -2427,7 +2834,7 @@ std::string BuildListWindows(const Json::Value& id, const Json::Value& args, CMy CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_windows")) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_WSLIST; if (!ctx->Send2Client(&cmd, 1)) { @@ -2480,7 +2887,7 @@ std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& ar CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "get_activity_history")) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_QUERY_ACTIVITY; if (!ctx->Send2Client(&cmd, 1)) { @@ -2550,7 +2957,7 @@ std::string BuildGetScreenshot(const Json::Value& id, const Json::Value& args, C CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "get_screenshot")) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); uint16_t reqId = mcp.NextPreviewReqId(); mcp.SetPendingReqId(devId, reqId); @@ -2662,7 +3069,7 @@ std::string BuildListFiles(const Json::Value& id, const Json::Value& args, CMy20 CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_files", ansiPath)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { @@ -2729,7 +3136,7 @@ std::string BuildListServices(const Json::Value& id, const Json::Value& args, CM CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_services")) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_SERVICES; if (!ctx->Send2Client(&cmd, 1)) { @@ -2811,7 +3218,7 @@ std::string BuildListRegistry(const Json::Value& id, const Json::Value& args, CM CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "list_registry", rootAndPath)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_REGEDIT; if (!ctx->Send2Client(&cmd, 1)) { @@ -3120,7 +3527,7 @@ std::string BuildExecCommand(const Json::Value& id, const Json::Value& args, CMy const bool badMeta = posix ? ContainsForbiddenPosixShellChars(command) : (command.find_first_of("&|<>^") != std::string::npos); if (badMeta || ContainsControlChar(command)) - return BuildError(id, -32008, "Command contains forbidden shell characters: " + command); + return BuildError(id, kErrValidation, "Command contains forbidden shell characters: " + command); // 安全门 3:命令白名单前缀校验(显式配置优先;否则按平台用内置默认表)。 std::string whitelist = mcp.GetCmdWhitelist(); @@ -3221,7 +3628,7 @@ std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CM CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "get_client_log")) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_QUERY_LOG; if (!ctx->Send2Client(&cmd, 1)) { @@ -3420,6 +3827,176 @@ std::string BuildGetServerStatus(const Json::Value& id, CMy2015RemoteDlg* parent return BuildResult(id, result); } +// ===== P11:mcp_list_sessions / mcp_cancel_session ===== +// +// 这两个工具只看/只改服务端自己的会话表,不向任何主机发报文,因此不受功能开关与 +// 只读模式限制——它们回答的是「谁占着这台主机、怎么把占用放开」,包括只读模式下 +// 卡住的长请求。取消是异步的:工具线程在 ≤500ms 的等待切片内退出并走既有清理路径, +// 这里再轮询同等条件最多 2s,好让返回的 released 反映「主机是否真的松开了」。 + +namespace { +const int kCancelWaitMs = 2000; // mcp_cancel_session 等「主机松开」的上限 +} + +static std::string BuildMcpListSessions(const Json::Value& id, const Json::Value& args) { + const std::string kindFilter = ToLowerAscii(GetStringArg(args, "kind")); + static const char* kKinds[] = { "call", "pending", "terminal", "remote_control", + "file_transfer", "chat" }; + if (!kindFilter.empty()) { + bool known = false; + for (const char* k : kKinds) if (kindFilter == k) { known = true; break; } + if (!known) + return BuildError(id, -32602, + "kind must be one of call/pending/terminal/remote_control/" + "file_transfer/chat"); + } + + const auto all = CMcpServer::Instance().ListSessions(); + Json::Value arr(Json::arrayValue); + std::string text; + int shown = 0; + for (const auto& s : all) { + if (!kindFilter.empty() && s.kind != kindFilter) continue; + Json::Value o(Json::objectValue); + if (s.device != 0) o["host_id"] = std::to_string(s.device); + o["kind"] = s.kind; + o["tool"] = s.tool; + if (!s.sessionId.empty()) o["session_id"] = s.sessionId; + if (!s.requestId.empty()) o["request_id"] = s.requestId; + o["busy"] = s.busy; + if (s.elapsedMs >= 0) o["elapsed_ms"] = (Json::Int64)s.elapsedMs; + if (s.idleMs >= 0) o["idle_ms"] = (Json::Int64)s.idleMs; + arr.append(o); + + if (shown < 20) { // 正文只列前 20 条,完整内容在 structuredContent + if (!text.empty()) text += u8";"; + if (s.device != 0) text += std::string(u8"主机 ") + std::to_string(s.device) + u8" "; + text += s.kind + "/" + s.tool; + if (s.elapsedMs >= 0) + text += std::string(u8"(已 ") + std::to_string(s.elapsedMs / 1000) + u8"s)"; + ++shown; + } + } + + Json::Value sc(Json::objectValue); + sc["sessions"] = arr; + sc["count"] = (int)arr.size(); + + if (arr.empty()) { + text = u8"当前没有在飞请求或长连接会话,主机都空闲。"; + } else { + text = std::string(u8"共 ") + std::to_string((int)arr.size()) + u8" 个会话:" + text; + if ((int)arr.size() > shown) + text += std::string(u8"…(正文只列前 ") + std::to_string(shown) + u8" 个)"; + } + + Json::Value result(Json::objectValue); + result["structuredContent"] = sc; + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = text; + content.append(item); + result["content"] = content; + result["isError"] = false; + return BuildResult(id, result); +} + +static std::string BuildMcpCancelSession(const Json::Value& id, const Json::Value& args) { + // request_id:按 JSON-RPC id 精确取消一次 tools/call(与 notifications/cancelled 等价)。 + // 同时接受紧凑写法与 mcp_list_sessions 里给出的文本写法(见 CancelCallById)。 + std::string reqIdKey; + std::string reqIdText; + if (args.isObject() && args.isMember("request_id")) { + const Json::Value& v = args["request_id"]; + if (!(v.isString() || v.isInt() || v.isUInt() || v.isInt64() || v.isUInt64())) + return BuildError(id, -32602, + "request_id must be a string or integer: the JSON-RPC id of a tools/call"); + reqIdKey = JsonToString(v); + reqIdText = McpRequestIdText(v); + } + + uint64_t devId = 0; + const bool hasDev = args.isObject() && args.isMember("id"); + if (hasDev && !ReadUInt64Arg(args, "id", devId)) + return BuildError(id, -32602, "id must be a decimal host id string"); + const std::string sessionId = GetStringArg(args, "session_id"); + + if (reqIdKey.empty() && !hasDev && sessionId.empty()) + return BuildError(id, -32602, + "Provide at least one of request_id (a tools/call id), id (host id), " + "or session_id"); + + // 条件匹配函数:request_id 优先,其余条件按「都给就必须都满足」。 + auto matches = [&](const CMcpServer::SessionSnapshot& s) { + if (!reqIdKey.empty()) return s.idKey == reqIdKey || s.requestId == reqIdText; + if (hasDev && devId != 0 && s.device != devId) return false; + if (!sessionId.empty() && s.sessionId != sessionId) return false; + return true; + }; + + CMcpServer& srv = CMcpServer::Instance(); + Json::Value matched(Json::arrayValue); + for (const auto& s : srv.ListSessions()) { + if (!matches(s)) continue; + Json::Value o(Json::objectValue); + if (s.device != 0) o["host_id"] = std::to_string(s.device); + o["kind"] = s.kind; + o["tool"] = s.tool; + if (!s.sessionId.empty()) o["session_id"] = s.sessionId; + if (!s.requestId.empty()) o["request_id"] = s.requestId; + matched.append(o); + } + + int cancelled = 0; + if (!reqIdKey.empty()) cancelled = srv.CancelCallById(reqIdKey, reqIdText) ? 1 : 0; + else cancelled = srv.CancelCalls(devId, sessionId); + + // 等主机松开(最多 2s):调用还在表里就说明工具线程还没走完清理。 + int waitedMs = 0; + bool released = false; + if (cancelled > 0) { + while (waitedMs < kCancelWaitMs) { + bool stillThere = false; + for (const auto& s : srv.ListSessions()) { + if (matches(s)) { stillThere = true; break; } + } + if (!stillThere) { released = true; break; } + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + waitedMs += 100; + } + } + + Json::Value sc(Json::objectValue); + sc["cancelled"] = cancelled; + sc["released"] = released; + sc["waited_ms"] = waitedMs; + sc["matched"] = matched; + + std::string text; + if (cancelled == 0) { + text = u8"没有匹配的在飞请求:可能已经结束,或 request_id 与列表里的值不一致。"; + } else if (released) { + text = std::string(u8"已取消 ") + std::to_string(cancelled) + u8" 个在飞请求," + + std::to_string(waitedMs) + u8" ms 内已释放占用;被取消的请求会收到 -32800。"; + } else { + text = std::string(u8"已取消 ") + std::to_string(cancelled) + u8" 个在飞请求,但 " + + std::to_string(kCancelWaitMs) + u8" ms 内仍在收尾(主机可能要等到客户端回包或超时);" + u8"稍后用 mcp_list_sessions 复查。"; + } + + Json::Value result(Json::objectValue); + result["structuredContent"] = sc; + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = text; + content.append(item); + result["content"] = content; + result["isError"] = false; + return BuildResult(id, result); +} + // ===== P4:持久远程终端(terminal_open / terminal_exec / terminal_close)===== static const int kTermIdleTimeoutSec = 300; // 持久终端 idle 回收超时(秒) @@ -3685,7 +4262,7 @@ std::string BuildTerminalExec(const Json::Value& id, const Json::Value& args, CM // 正确性门(非安全门):& 与 | 会破坏哨兵控制操作符链、导致退出码失真;拆成多条调用即可。 // \r\n 会把命令拆成多行、只有末行被哨兵包装,同样破坏退出码捕获,一并拒绝。 if (command.find_first_of("&|") != std::string::npos || ContainsControlChar(command)) - return BuildError(id, -32008, + return BuildError(id, kErrValidation, "Command contains & or | or a newline (breaks output capture); run chained/piped commands as separate terminal_exec calls"); int timeoutMs = CMcpServer::Instance().ToolTimeoutMs(); @@ -3935,7 +4512,7 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2 // 多显示器门(§7.2 / §12.1):Observe 抓主屏,Act 注入在虚拟桌面空间,两者仅单显示器时 // 重合。客户端心跳 RES_RESOLUTION = "N:W*H"(N=显示器数);N>1 时归一化坐标会系统性 - // 偏移,阶段一直接拒绝。这是能力限制(改参数也修不好),故报 -32005 而非参数校验错误 -32008。 + // 偏移,阶段一直接拒绝。这是能力限制(改参数也修不好),故报 -32005 而非参数校验错误 -32012。 // 无冒号(老客户端格式)则无法判定,放行不拦。 { CString res = ctx->GetAdditionalData(RES_RESOLUTION); @@ -3989,6 +4566,7 @@ std::string BuildRemoteOpen(const Json::Value& id, const Json::Value& args, CMy2 ready = (subCtx != nullptr); break; } + if (McpCallCancelled()) break; // 按「没就绪」走下面的清理与超时分支 std::this_thread::sleep_for(std::chrono::milliseconds(50)); } @@ -5105,7 +5683,7 @@ std::string BuildDownloadFile(const Json::Value& id, const Json::Value& args, CM CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginFileTransferPending(devId, "download_file", localDirAnsi, remotePathAnsi, overwrite)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { @@ -5239,12 +5817,21 @@ struct UploadCallbackData { DWORD deadline = 0; // 整体传输截止(GetTickCount 毫秒;0=不限) bool timedOut = false; bool failed = false; // 任一 Send2Client 失败或客户端离线 + // P11:进度与取消(worker 的每次分块回调都会经过这里) + uint64_t totalBytes = 0; // 待发送的数据字节总数(进度分母) + uint64_t bytesSent = 0; // 已发出的数据字节数(进度分子) + bool cancelled = false; // 调用被取消 → 中止发送(worker 以非 0 返回) }; // upload_file 无头发送回调(镜像 GUI SendFileChunkToClientV2,去掉 dlg 进度)。 static bool UploadSendChunkHeadless(void* user, FileChunkPacketV2* chunk, unsigned char* data, int size) { UploadCallbackData* cb = (UploadCallbackData*)user; if (!cb || !cb->parent) return false; + if (McpCallCancelled()) { // P11:取消 → 停止发送 + cb->cancelled = true; + cb->failed = true; + return false; + } if (cb->deadline && (int)(GetTickCount() - cb->deadline) >= 0) { // 整体超时(DWORD 回绕安全) cb->timedOut = true; cb->failed = true; @@ -5254,6 +5841,12 @@ static bool UploadSendChunkHeadless(void* user, FileChunkPacketV2* chunk, unsign if (!ctx) { cb->failed = true; return false; } BOOL sent = ctx->Send2Client(data, size); if (!sent) cb->failed = true; + else if (chunk && chunk->dataLength) { + cb->bytesSent += chunk->dataLength; + // 进度按 1s 节流(EmitProgress 内部),大文件每片都会回调到这里。 + if (cb->totalBytes > 0) McpCallProgress((double)cb->bytesSent, (double)cb->totalBytes); + else McpCallProgress((double)cb->bytesSent); + } return sent != FALSE; } @@ -5498,7 +6091,7 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginFileUpload(devId, opts.transferID)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); std::string hash = GetPwdHash(); std::string hmac = GetHMAC(100); @@ -5508,6 +6101,14 @@ std::string BuildUploadFile(const Json::Value& id, const Json::Value& args, CMy2 cbData.clientID = devId; cbData.deadline = GetTickCount() + (DWORD)timeoutMs; // DWORD 回绕由回调的 (int) 差值判断吸收 + // 进度分母:待发送文件的数据字节总数(目录项不计)。取不到属性时保持 0 → 只报已发字节数。 + for (const std::string& f : sendFiles) { + WIN32_FILE_ATTRIBUTE_DATA fad; + if (GetFileAttributesExA(f.c_str(), GetFileExInfoStandard, &fad) && + !(fad.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) + cbData.totalBytes += (((uint64_t)fad.nFileSizeHigh << 32) | fad.nFileSizeLow); + } + // 空文件:worker 对 0 字节文件不发数据块,只发 COMMAND_FILE_COMPLETE_V2,而完成包没有路径字段, // POSIX 接收端无从创建文件(会「回执成功但文件不存在」)。这里替 POSIX 目标端补一个长度 0 的 // 收尾块(名字拼法与 worker 一致),接收端据此建空文件;随后 worker 的完成包只会被去重。 @@ -5986,8 +6587,80 @@ std::string BuildKillProcess(const Json::Value& id, const Json::Value& args, CMy followUp.push_back((BYTE)((d >> 24) & 0xFF)); } + // ===== dry_run(§5.5):只取一次进程列表校验目标,不下发任何终止命令 ===== + // MFC 侧不弹窗:挂起用「非写工具」的名称登记,TOKEN_PSLIST 首包会让 OnSystemReady + // 返回 false,由 TakeMainResponse + CancelIO 收走子链接。目标全部不存在时按 -32009 报错, + // 与 kill_network_connection 的 dry_run 口径一致。 + bool dryRun = false; + if (args.isMember("dry_run")) { + if (!args["dry_run"].isBool()) + return BuildError(id, -32602, "dry_run must be a boolean"); + dryRun = args["dry_run"].asBool(); + } + if (dryRun) { + if (!mcp.BeginPending(devId, "kill_process/dryrun")) + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); + + BYTE cmd = COMMAND_SYSTEM; + if (!ctx->Send2Client(&cmd, 1)) { + mcp.ClearPending(devId); + return BuildError(id, -32004, "Failed to send command to host"); + } + + std::vector data; + if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) + return BuildError(id, -32001, "Timeout waiting for process list (dry run)"); + + UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936; + Json::Value procs = ParseProcessList(data, cp); + + Json::Value targets(Json::arrayValue); + Json::Value missing(Json::arrayValue); + for (size_t i = 0; i < pidList.size(); ++i) { + bool found = false; + for (unsigned int j = 0; j < procs.size(); ++j) { + if (procs[j]["pid"].asUInt64() == pidList[i]) { + Json::Value t(Json::objectValue); + t["pid"] = (Json::UInt64)pidList[i]; + t["name"] = procs[j]["name"]; + t["path"] = procs[j]["path"]; + targets.append(t); + found = true; + break; + } + } + if (!found) missing.append((Json::UInt64)pidList[i]); + } + + AuditManageAction(parent, devId, "kill_process", + "pids=" + std::to_string(pidList.size()) + " result=dry_run"); + if (targets.empty()) + return BuildError(id, -32009, "No matching process for any requested pid (dry run)"); + + Json::Value result(Json::objectValue); + Json::Value structuredContent(Json::objectValue); + structuredContent["ok"] = true; + structuredContent["dry_run"] = true; + structuredContent["targets"] = targets; + structuredContent["missing"] = missing; + result["structuredContent"] = structuredContent; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = std::string(u8"试运行:将终止 ") + std::to_string(targets.size()) + + u8" 个进程(未发送任何命令)" + + (missing.empty() ? std::string() + : std::string(u8";") + std::to_string(missing.size()) + + u8" 个 PID 已不存在,已列入 missing") ; + content.append(item); + result["content"] = content; + result["isError"] = false; + return BuildResult(id, result); + } + if (!mcp.BeginPendingFollowUp(devId, "kill_process", followUp)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_SYSTEM; if (!ctx->Send2Client(&cmd, 1)) { @@ -6083,8 +6756,63 @@ std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, C } std::vector followUp(lpMsgBuf, lpMsgBuf + sizeof(lpMsgBuf)); + + // ===== dry_run(§5.5):只取一次窗口列表校验 hwnd,不下发任何窗口命令 ===== + // 与 kill_process 的 dry_run 同构:用非写工具名登记,首包直接由 TakeMainResponse 收走。 + bool dryRun = false; + if (args.isMember("dry_run")) { + if (!args["dry_run"].isBool()) + return BuildError(id, -32602, "dry_run must be a boolean"); + dryRun = args["dry_run"].asBool(); + } + if (dryRun) { + if (!mcp.BeginPending(devId, "operate_window/dryrun")) + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); + + BYTE cmd = COMMAND_WSLIST; + if (!ctx->Send2Client(&cmd, 1)) { + mcp.ClearPending(devId); + return BuildError(id, -32004, "Failed to send command to host"); + } + + std::vector data; + if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) + return BuildError(id, -32001, "Timeout waiting for window list (dry run)"); + + // 窗口标题编码由客户端能力位决定(新客户端 UTF-8,老客户端 CP_ACP),与 list_windows 同口径。 + Json::Value windows = ParseWindowList(data, GetClientEncoding(ctx)); + Json::Value target(Json::objectValue); + for (unsigned int i = 0; i < windows.size(); ++i) { + if (windows[i]["hwnd"].asUInt64() == hwnd) { target = windows[i]; break; } + } + + AuditManageAction(parent, devId, "operate_window", + "action=" + action + " hwnd=" + std::to_string(hwnd) + " result=dry_run"); + if (target.isNull() || !target.isObject()) + return BuildError(id, -32009, "Window hwnd=" + std::to_string(hwnd) + + " is not in the current visible window list (dry run)"); + + Json::Value result(Json::objectValue); + Json::Value structuredContent(Json::objectValue); + structuredContent["ok"] = true; + structuredContent["dry_run"] = true; + structuredContent["action"] = action; + structuredContent["window"] = target; + result["structuredContent"] = structuredContent; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = std::string(u8"试运行:将对窗口「") + target["title"].asString() + + u8"」执行 " + action + u8"(未发送任何命令)"; + content.append(item); + result["content"] = content; + result["isError"] = false; + return BuildResult(id, result); + } + if (!mcp.BeginPendingFollowUp(devId, "operate_window", followUp)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_WSLIST; if (!ctx->Send2Client(&cmd, 1)) { @@ -6161,7 +6889,7 @@ std::string BuildControlService(const Json::Value& id, const Json::Value& args, followUp.push_back(0); if (!mcp.BeginPendingFollowUp(devId, "control_service", followUp)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_SERVICES; if (!ctx->Send2Client(&cmd, 1)) { @@ -6193,6 +6921,21 @@ std::string BuildControlService(const Json::Value& id, const Json::Value& args, } // power_action:主连接 TOKEN_MACHINE_MANAGE,发完即走(无响应);主机立即离线。 +// power_action 的结果验证(§5.4):电源命令是「发完即走、无响应」,服务端唯一能观察到的 +// 事实是主连接在不在线。wait=true 时先等主机下线(连接消失),再等它重新上线(重启后客户端 +// 用同一个 id 重连)。两个阶段各自以 wait_ms 为上界;等不到不是错误,交给调用方判断。 +static bool WaitHostOnlineState(CMy2015RemoteDlg* parent, uint64_t devId, bool wantOnline, + int timeoutMs) { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(timeoutMs); + while (true) { + if ((FindMainContext(parent, devId) != nullptr) == wantOnline) return true; + if (McpCallCancelled()) return false; // 取消后按「没等到」返回,由调用方如实回报 + const auto now = std::chrono::steady_clock::now(); + if (now >= deadline) return false; + std::this_thread::sleep_for(std::chrono::milliseconds(200)); + } +} + std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; std::string err; @@ -6221,22 +6964,80 @@ std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy else return BuildError(id, -32602, "Invalid action: " + action + " (expect logout|shutdown|reboot)"); + // 结果验证参数(§5.4):wait 默认 false(保持「发完即走」的旧行为与旧耗时)。 + // wait_ms 即使 wait=false 也校验,避免调用方以为传了有效值、实际被静默忽略。 + bool wait = false; + if (args.isMember("wait")) { + if (!args["wait"].isBool()) + return BuildError(id, -32602, "wait must be a boolean"); + wait = args["wait"].asBool(); + } + int waitMs = 60000; + if (args.isMember("wait_ms")) { + int v = 0; + if (!GetIntArg(args, "wait_ms", v) || v < 1000 || v > 600000) + return BuildError(id, -32602, "wait_ms must be in range 1000..600000"); + waitMs = v; + } + // 主连接、发完即走、无响应(客户端 KernelManager 只校验 ulLength>1 并读 szBuffer[1])。 BYTE token[2] = { (BYTE)TOKEN_MACHINE_MANAGE, type }; if (!ctx->Send2Client(token, 2)) return BuildError(id, -32004, "Failed to send command to host"); - AuditManageAction(parent, devId, "power_action", "action=" + action); + bool wentOffline = false; + bool cameBack = false; + long long elapsedMs = 0; + if (wait) { + const auto t0 = std::chrono::steady_clock::now(); + wentOffline = WaitHostOnlineState(parent, devId, false, waitMs); + if (wentOffline) cameBack = WaitHostOnlineState(parent, devId, true, waitMs); + elapsedMs = (long long)std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0).count(); + } + + AuditManageAction(parent, devId, "power_action", + "action=" + action + (wait ? " wait=1" : "") + + (wait ? (wentOffline ? (cameBack ? " went_offline=1 came_back=1" + : " went_offline=1 came_back=0") + : " went_offline=0") : "")); + + // 取消优先于「没等到」:命令已经发出去了,不能伪装成「主机没反应」。用 -32800 说明是 + // 调用方自己取消了等待,正文里点明命令可能已生效(重试前先读一次在线列表)。 + // 已经看到下线的(wentOffline)继续按成功回报——那是真实发生的事实。 + if (wait && !wentOffline && McpCallCancelled()) + return BuildError(id, kErrCancelled, + "Cancelled while waiting for the host to go offline; the power command " + "was already sent, so check the host list before retrying"); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); structuredContent["ok"] = true; + structuredContent["sent"] = true; + structuredContent["went_offline"] = wentOffline; + structuredContent["came_back"] = cameBack; + structuredContent["elapsed_ms"] = (Json::Int64)elapsedMs; result["structuredContent"] = structuredContent; + std::string text = std::string(u8"已下发电源操作:") + action; + if (!wait) { + text += u8"(未等待结果;要确认主机真的下线/回线请传 wait=true)"; + } else if (!wentOffline) { + text += std::string(u8";在 ") + std::to_string(waitMs) + + u8" ms 内主机仍在在线列表里——命令可能没有生效" + u8"(客户端无管理员权限时关机/重启会被拒绝),也可能还在关机流程中。"; + } else if (!cameBack) { + text += std::string(u8";主机已下线(") + std::to_string(elapsedMs) + + std::string(u8" ms),但未在 ") + std::to_string(waitMs) + + u8" ms 内重新上线(注销不会自动回线;关机后需人工开机)。"; + } else { + text += std::string(u8";主机已下线并重新上线,共耗时 ") + std::to_string(elapsedMs) + u8" ms。"; + } + Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; - item["text"] = std::string(u8"已下发电源操作:") + action; + item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; @@ -6438,7 +7239,7 @@ std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy20 return BuildError(id, -32005, "get_keylog is only supported on Windows hosts"); if (!mcp.BeginKeylogSession(devId, "get_keylog", ctx)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_KEYBOARD; if (!ctx->Send2Client(&cmd, 1)) { @@ -6889,7 +7690,7 @@ std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2 CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPending(devId, "search_file", payload)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { @@ -7271,7 +8072,7 @@ std::string RunFileOp(const Json::Value& id, const std::string& tool, context* c FileOpWait& out) { CMcpServer& mcp = CMcpServer::Instance(); if (!mcp.BeginPendingFileOp(devId, tool, followUp, verifyPathAnsi)) - return BuildError(id, -32003, "Device busy: another request is pending for this host"); + return BuildError(id, -32003, BusyMessage("Device busy: another request is pending for this host", devId)); BYTE cmd = COMMAND_LIST_DRIVE; if (!ctx->Send2Client(&cmd, 1)) { @@ -7874,6 +8675,9 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too if (toolName == "get_keylog") return BuildGetKeylog(id, args, parent); if (toolName == "get_audit_log") return BuildGetAuditLog(id, args, parent); if (toolName == "get_server_status") return BuildGetServerStatus(id, parent); + // P11:服务端自身会话的观测 / 取消(无主机、纯本地;不受功能开关与只读限制)。 + if (toolName == "mcp_list_sessions") return BuildMcpListSessions(id, args); + if (toolName == "mcp_cancel_session") return BuildMcpCancelSession(id, args); if (toolName == "list_registry") return BuildListRegistry(id, args, parent); if (toolName == "exec_command") return BuildExecCommand(id, args, parent); if (toolName == "terminal_open") return BuildTerminalOpen(id, args, parent); @@ -8027,12 +8831,12 @@ bool CMcpServer::WaitTerminalReady(uint64_t device_id, context*& subCtx, bool& i auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) return false; - bool signaled = m_TermCv.wait_for(lk, std::chrono::milliseconds(timeoutMs), - [&] { return it->second.started; }); + bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs), + [&] { return it->second.started; }); if (!signaled) { // 放弃:迟到的 shell 子连接就绪包(TOKEN_SHELL_START/TOKEN_TERMINAL_START)不能弹终端窗口。 MarkLateFirstPacket(device_id, { (BYTE)TOKEN_SHELL_START, (BYTE)TOKEN_TERMINAL_START }); - m_TermSessions.erase(it); // 超时 → 清理 + m_TermSessions.erase(it); // 超时/取消 → 清理 return false; } subCtx = it->second.subCtx; @@ -8046,10 +8850,10 @@ bool CMcpServer::WaitTerminalDone(uint64_t device_id, std::vector& out, auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) return false; - bool signaled = m_TermCv.wait_for(lk, std::chrono::milliseconds(timeoutMs), - [&] { return it->second.done || it->second.closed; }); + bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs), + [&] { return it->second.done || it->second.closed; }); - if (!signaled) { // 超时 → 清理(含路由表) + if (!signaled) { // 超时/取消 → 清理(含路由表) m_TermContextToDevice.erase(it->second.subCtx); m_TermSessions.erase(it); return false; @@ -8148,14 +8952,17 @@ bool CMcpServer::WaitTermCommand(uint64_t device_id, std::vector& out, auto it = m_TermSessions.find(device_id); if (it == m_TermSessions.end()) return false; - bool signaled = m_TermCv.wait_for(lk, std::chrono::milliseconds(timeoutMs), - [&] { return it->second.done || it->second.closed; }); + bool signaled = WaitWithCancel(lk, m_TermCv, DeadlineAfter(timeoutMs), + [&] { return it->second.done || it->second.closed; }); - if (!signaled) { // 超时 → 清理会话+路由(调用方负责 CancelIO) + if (!signaled) { // 超时/取消 → 清理会话+路由(调用方负责 CancelIO) context* subCtx = it->second.subCtx; MarkTermDestroyedLocked(device_id, it->second.sessionId, - "Terminal session was destroyed after this command timed out (waited " - + std::to_string(timeoutMs) + " ms); call terminal_open again"); + McpCallCancelled() + ? std::string("Terminal session was destroyed because the request was cancelled; " + "call terminal_open again") + : "Terminal session was destroyed after this command timed out (waited " + + std::to_string(timeoutMs) + " ms); call terminal_open again"); m_TermContextToDevice.erase(subCtx); m_TermSessions.erase(it); return false; @@ -8563,7 +9370,10 @@ bool CMcpServer::Start(const std::string& bind, int port) { } void CMcpServer::Stop() { - // 先停看门狗:它会对屏幕子连接发报文,必须在后端服务拆除之前停止。 + // P11:先取消所有在飞调用——长任务(下载 / 搜索 / 挂起等待)的等待循环会在 ≤1s + // 内退出并走超时清理路径,不给 Stop 留下还在用连接、还在改表的工具线程。 + CancelCalls(0, std::string()); + // 再停看门狗:它会对屏幕子连接发报文,必须在后端服务拆除之前停止。 m_blockStop.store(true); if (m_blockThread.joinable()) m_blockThread.join(); // 再停前端:不再接入新连接,再停后端。Stop 内部会 join 前端线程。 @@ -8607,8 +9417,222 @@ void CMcpServer::GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl } } -// ===== 鉴权加固(N4)===== +// ===== P11:在飞调用登记 / 取消 / 会话快照 ===== // +// 三张表各自持锁、只读遍历,绝不嵌套(与 GetRuntimeCounters 同一约定):调用方拿到的 +// 是「大致同一时刻」的快照,仅用于观测与取消,不用来同步。 + +namespace { +long long ElapsedMsSince(std::chrono::steady_clock::time_point tp) { + if (tp.time_since_epoch().count() == 0) return -1; + return (long long)std::chrono::duration_cast( + std::chrono::steady_clock::now() - tp).count(); +} +long long IdleMsSince(time_t t) { + if (t <= 0) return -1; + return (long long)(time(NULL) - t) * 1000; +} +} // namespace + +std::shared_ptr CMcpServer::BeginCall(const std::string& idKey, const std::string& idText, + const std::string& tool, + uint64_t device, const std::string& sessionId) { + auto call = std::make_shared(); + call->idKey = idKey; + call->idText = idText; + call->tool = tool; + call->device = device; + call->sessionId = sessionId; + call->startedAt = std::chrono::steady_clock::now(); + std::lock_guard lk(m_CallMutex); + m_Calls.push_back(call); + return call; +} + +void CMcpServer::EndCall(const std::shared_ptr& call) { + if (!call) return; + std::lock_guard lk(m_CallMutex); + for (auto it = m_Calls.begin(); it != m_Calls.end(); ++it) { + if (*it == call) { m_Calls.erase(it); return; } + } +} + +bool CMcpServer::CancelCallById(const std::string& idKey, const std::string& idText) { + std::lock_guard lk(m_CallMutex); + // 先按精确写法找:"41"(字符串)与 41(数字)是两个不同的 id,不能混。 + for (const auto& c : m_Calls) { + if (c->idKey == idKey) { c->cancelled.store(true); return true; } + } + // 再退回展示文本:调用方常把列表里的 request_id 当字符串原样传回来, + // 而原调用用的是数字 id —— 这是同一意图,容忍。 + if (!idText.empty()) { + for (const auto& c : m_Calls) { + if (c->idText == idText) { c->cancelled.store(true); return true; } + } + } + return false; +} + +int CMcpServer::CancelCalls(uint64_t device, const std::string& sessionId) { + int n = 0; + std::lock_guard lk(m_CallMutex); + for (const auto& c : m_Calls) { + if (device != 0 && c->device != device) continue; + if (!sessionId.empty() && c->sessionId != sessionId) continue; + c->cancelled.store(true); + ++n; + } + return n; +} + +std::vector CMcpServer::ListSessions() { + std::vector out; + { + std::lock_guard lk(m_CallMutex); + for (const auto& c : m_Calls) { + SessionSnapshot s; + s.device = c->device; + s.kind = "call"; + s.tool = c->tool; + s.sessionId = c->sessionId; + s.idKey = c->idKey; + s.requestId = c->idText; + s.busy = true; + s.elapsedMs = ElapsedMsSince(c->startedAt); + out.push_back(s); + } + } + { + std::lock_guard lk(m_PendingMutex); + for (const auto& kv : m_Pending) { + SessionSnapshot s; + s.device = kv.first; + s.kind = "pending"; + s.tool = kv.second.tool; + s.busy = true; + s.elapsedMs = ElapsedMsSince(kv.second.startedAt); + out.push_back(s); + } + } + { + std::lock_guard lk(m_TermMutex); + for (const auto& kv : m_TermSessions) { + const TermSession& t = kv.second; + SessionSnapshot s; + s.device = kv.first; + s.kind = "terminal"; + s.tool = t.persistent ? "terminal" : "exec_command"; + s.sessionId = t.sessionId; + s.busy = t.busy || !t.started; + s.elapsedMs = ElapsedMsSince(t.startedAt); + s.idleMs = IdleMsSince(t.lastActiveAt); + out.push_back(s); + } + } + { + std::lock_guard lk(m_ScreenCtrlMutex); + for (const auto& kv : m_ScreenCtrlSessions) { + const ScreenCtrlSession& c = kv.second; + SessionSnapshot s; + s.device = kv.first; + s.kind = "remote_control"; + s.tool = "remote_control"; + s.sessionId = c.sessionId; + s.busy = c.busy || !c.started; + s.elapsedMs = ElapsedMsSince(c.startedAt); + s.idleMs = IdleMsSince(c.lastActiveAt); + out.push_back(s); + } + } + { + std::lock_guard lk(m_FileXferMutex); + for (const auto& kv : m_FileXferSessions) { + const FileTransferSession& f = kv.second; + SessionSnapshot s; + s.device = kv.first; + s.kind = "file_transfer"; + s.tool = f.tool; + s.busy = true; // 文件传输会话在表里就是「在飞」,结束时删除 + s.elapsedMs = ElapsedMsSince(f.startedAt); + s.idleMs = ElapsedMsSince(f.lastDataAt); + out.push_back(s); + } + } + { + std::lock_guard lk(m_ChatMutex); + for (const auto& kv : m_ChatSessions) { + const ChatSession& c = *kv.second; + SessionSnapshot s; + s.device = kv.first; + s.kind = "chat"; + s.tool = "chat"; + s.sessionId = c.sessionId; + s.busy = c.sendBusy || c.waitBusy || !c.started; + s.elapsedMs = ElapsedMsSince(c.startedAt); + s.idleMs = IdleMsSince(c.lastActiveAt); + out.push_back(s); + } + } + return out; +} + +// -32003 文案后缀:优先报「正在跑的长任务」(调用 / 挂起 / 文件传输),其次报持久会话。 +std::string CMcpServer::DescribeBusy(uint64_t device_id) { + auto describe = [](const std::string& tool, long long ms) { + std::string s = " (tool=" + (tool.empty() ? std::string("?") : tool); + if (ms >= 0) s += ", elapsed=" + std::to_string(ms / 1000) + "s"; + return s + ")"; + }; + { + std::lock_guard lk(m_CallMutex); + const McpCallContext* self = CurrentMcpCall().get(); + for (const auto& c : m_Calls) { + if (c.get() == self) continue; // 发起 -32003 的就是这次调用,不能算「占用者」 + if (c->device == device_id) + return describe(c->tool + (c->sessionId.empty() ? "" : " session_id=" + c->sessionId), + ElapsedMsSince(c->startedAt)); + } + } + { + std::lock_guard lk(m_PendingMutex); + auto it = m_Pending.find(device_id); + if (it != m_Pending.end()) return describe(it->second.tool, ElapsedMsSince(it->second.startedAt)); + } + { + std::lock_guard lk(m_FileXferMutex); + auto it = m_FileXferSessions.find(device_id); + if (it != m_FileXferSessions.end()) + return describe(it->second.tool, ElapsedMsSince(it->second.startedAt)); + } + { + std::lock_guard lk(m_TermMutex); + auto it = m_TermSessions.find(device_id); + if (it != m_TermSessions.end() && it->second.busy) + return describe(it->second.sessionId.empty() ? "exec_command" : "terminal", + ElapsedMsSince(it->second.startedAt)); + } + { + std::lock_guard lk(m_ScreenCtrlMutex); + auto it = m_ScreenCtrlSessions.find(device_id); + if (it != m_ScreenCtrlSessions.end() && it->second.busy) + return describe("remote_control", ElapsedMsSince(it->second.startedAt)); + } + { + std::lock_guard lk(m_ChatMutex); + auto it = m_ChatSessions.find(device_id); + if (it != m_ChatSessions.end() && (it->second->sendBusy || it->second->waitBusy)) + return describe("chat", ElapsedMsSince(it->second->startedAt)); + } + return std::string(); +} + +// -32003 的正文:通用句 + 「谁占着这台主机、已持续多久」。McpMachine.cpp 也用它。 +std::string BusyMessage(const std::string& base, uint64_t devId) { + const std::string who = CMcpServer::Instance().DescribeBusy(devId); + return who.empty() ? base : base + who; +} + +// ===== 鉴权加固(N4)===== // 两件事: // 1) 同一 IP 在 60 s 内鉴权失败 10 次 → 封禁 15 min(封禁期内直接 429,不比对 token)。 // 正常客户端只有在 token 配错时才会连续 401,10 次足够覆盖改配置重试;爆破工具一分钟 @@ -8745,7 +9769,8 @@ void CMcpServer::ClearAuthFailures(const std::string& ip) { } void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res) { - res.set_header("Content-Type", "application/json"); + // 注意:这里不预置 Content-Type —— set_content / set_chunked_content_provider 各自 + // 会写,预置会让 SSE 响应带上两个 Content-Type(application/json 在前)。 const std::string clientIp = req.remote_addr; // 环回来源(本机 / frp 隧道)不参与封禁,理由见 IsProxySourceAddress。 @@ -8799,6 +9824,20 @@ void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res) // 通知(无 id)→ 不返回 JSON-RPC 响应(如 notifications/initialized) if (!root.isMember("id")) { + // P11:notifications/cancelled → 置对应在飞调用的取消位。工具层的等待循环会在 + // ≤1s 内退出并走既有的超时清理路径(不发多余报文、不留下悬空挂起项), + // 该请求自己的 SSE 流(若有)随即以 -32800 结束。 + const Json::Value& m = root["method"]; + if (m.isString() && m.asString() == "notifications/cancelled") { + const Json::Value& params = root["params"]; + if (params.isObject() && params.isMember("requestId")) { + const Json::Value& rid = params["requestId"]; + const bool hit = CancelCallById(JsonToString(rid), McpRequestIdText(rid)); + AuditMcpEvent("NOTIFY_CANCEL", clientIp, + "requestId=" + SanitizeHeaderValue(McpRequestIdText(rid), 64) + + " hit=" + (hit ? "1" : "0")); + } + } res.status = 202; res.set_content("", "application/json"); return; @@ -8825,51 +9864,125 @@ void CMcpServer::HandleMcp(const httplib::Request& req, httplib::Response& res) return; } if (method == "tools/call") { + const Json::Value params = + root.isMember("params") ? root["params"] : Json::Value(Json::objectValue); + std::string toolName; - if (root.isMember("params") && root["params"].isObject() && - root["params"].isMember("name") && root["params"]["name"].isString()) - toolName = root["params"]["name"].asString(); + if (params.isObject() && params.isMember("name") && params["name"].isString()) + toolName = params["name"].asString(); - auto t0 = std::chrono::steady_clock::now(); - std::string resp = BuildToolsCall(root, m_parent); - long long ms = (long long)std::chrono::duration_cast( - std::chrono::steady_clock::now() - t0).count(); + // 登记在飞调用:devId / session_id 只用于观测与 mcp_cancel_session, + // 解析不出来(非主机工具、参数非法)就按 0 / 空处理,不影响工具自身的行为。 + const Json::Value args = GetCallArguments(params); + uint64_t devId = 0; + std::string ignored; + ParseHostIdArg(args, devId, ignored); + std::string sessionId; + if (args.isObject() && args.isMember("session_id") && args["session_id"].isString()) + sessionId = args["session_id"].asString(); - // 成败以返回体顶层是否有 "error" 成员为准(解析一次,避免正文里出现 "error" 字样时误判) - bool failed = false; - int errCode = 0; - std::string errMsg; - { + auto call = BeginCall(JsonToString(root["id"]), McpRequestIdText(root["id"]), + toolName, devId, sessionId); + // _meta.progressToken(MCP 2025-06-18):字符串或整数,原样回显。 + if (params.isObject() && params.isMember("_meta") && params["_meta"].isObject() && + params["_meta"].isMember("progressToken")) { + const Json::Value& tok = params["_meta"]["progressToken"]; + if (tok.isString() || tok.isInt() || tok.isUInt() || tok.isInt64() || tok.isUInt64()) { + call->hasProgressToken = true; + call->progressTokenJson = JsonToString(tok); + } + } + + // 审计一条 tools/call 结果(SSE 路径的工具线程与普通路径共用同一份判定)。 + auto auditResult = [this, clientIp, toolName](const std::string& resp, long long ms) { + // 成败以返回体顶层是否有 "error" 成员为准(解析一次,避免正文里出现 "error" 字样时误判) + bool failed = false; + int errCode = 0; + std::string errMsg; + { + Json::Value parsed; + Json::CharReaderBuilder rb; + std::string perrs; + std::istringstream pis(resp); + if (Json::parseFromStream(rb, pis, &parsed, &perrs) && + parsed.isObject() && parsed.isMember("error")) { + failed = true; + const Json::Value& err = parsed["error"]; + if (err.isObject()) { + if (err["code"].isInt()) errCode = err["code"].asInt(); + if (err["message"].isString()) errMsg = err["message"].asString(); + } + } + } + // 单行不变量:工具名来自请求参数,控制字符一律换成空格,避免伪造出额外审计行 + auto oneLine = [](std::string v) { + for (char& c : v) + if ((unsigned char)c < 0x20) c = ' '; + return v; + }; + const std::string toolTag = + "tool=" + oneLine(toolName.empty() ? std::string("(empty)") : toolName); + AuditMcpEvent(failed ? "CALL_FAIL" : "CALL_OK", clientIp, + toolTag + " ms=" + std::to_string(ms) + " bytes=" + std::to_string(resp.size())); + + // 策略拒绝(-32006:只读模式、功能开关关闭、主机不支持)另记一条 CALL_DENIED, + // 事后才分得清「没人调用」和「被策略拦下」。reason 全是固定的英文句式,不含 + // 调用参数或用户输入,可以直接落盘。 + if (errCode == -32006) + AuditMcpEvent("CALL_DENIED", clientIp, toolTag + " reason=" + oneLine(errMsg)); + }; + + // 取消后的收尾:工具因取消而失败时,把错误统一改写成 -32800,让调用方知道 + // 「这是自己取消的」而不是主机故障;已经拿到成功结果就照实返回。 + auto finalize = [id = root["id"], call](std::string resp) { + if (!call->IsCancelled()) return resp; Json::Value parsed; Json::CharReaderBuilder rb; std::string perrs; std::istringstream pis(resp); - if (Json::parseFromStream(rb, pis, &parsed, &perrs) && - parsed.isObject() && parsed.isMember("error")) { - failed = true; - const Json::Value& err = parsed["error"]; - if (err.isObject()) { - if (err["code"].isInt()) errCode = err["code"].asInt(); - if (err["message"].isString()) errMsg = err["message"].asString(); - } - } - } - // 单行不变量:工具名来自请求参数,控制字符一律换成空格,避免伪造出额外审计行 - auto oneLine = [](std::string v) { - for (char& c : v) - if ((unsigned char)c < 0x20) c = ' '; - return v; + if (!Json::parseFromStream(rb, pis, &parsed, &perrs) || !parsed.isObject() || + !parsed.isMember("error")) + return resp; + return BuildError(id, kErrCancelled, + "Request cancelled: the in-flight work was aborted and cleaned up"); }; - const std::string toolTag = - "tool=" + oneLine(toolName.empty() ? std::string("(empty)") : toolName); - AuditMcpEvent(failed ? "CALL_FAIL" : "CALL_OK", clientIp, - toolTag + " ms=" + std::to_string(ms) + " bytes=" + std::to_string(resp.size())); - // 策略拒绝(-32006:只读模式、功能开关关闭、主机不支持)另记一条 CALL_DENIED, - // 事后才分得清「没人调用」和「被策略拦下」。reason 全是固定的英文句式,不含 - // 调用参数或用户输入,可以直接落盘。 - if (errCode == -32006) - AuditMcpEvent("CALL_DENIED", clientIp, toolTag + " reason=" + oneLine(errMsg)); + if (call->hasProgressToken) { + // 带 _meta.progressToken:按 MCP Streamable HTTP 的要求以 text/event-stream + // 回应同一个 POST。工具在独立线程执行,进度通知与最终响应都从这个流写出。 + auto ch = std::make_shared(); + ch->call = call; + call->channel = ch; + const Json::Value rootCopy = root; // 请求体在栈上,工具线程必须持有副本 + std::thread([this, rootCopy, call, ch, clientIp, toolName, auditResult, finalize]() { + McpCallScope scope(call); + auto t0 = std::chrono::steady_clock::now(); + std::string resp = finalize(BuildToolsCall(rootCopy, m_parent)); + const long long ms = (long long)std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0).count(); + auditResult(resp, ms); + EndCall(call); + ch->Finish(resp); // 最后一步:置 finished 并唤醒 provider 线程写出最终响应 + }).detach(); + + res.status = 200; + res.set_chunked_content_provider( + "text/event-stream", + [ch](size_t, httplib::DataSink& sink) { return ch->Pump(sink); }); + return; + } + + auto t0 = std::chrono::steady_clock::now(); + std::string resp; + { + McpCallScope scope(call); // 让工具实现里的 McpCallCancelled() 生效 + resp = BuildToolsCall(root, m_parent); + } + const long long ms = (long long)std::chrono::duration_cast( + std::chrono::steady_clock::now() - t0).count(); + resp = finalize(std::move(resp)); + EndCall(call); + auditResult(resp, ms); res.set_content(resp, "application/json"); return; @@ -8975,7 +10088,8 @@ bool CMcpServer::WaitPending(uint64_t device_id, std::vector& out, int tim auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return false; - bool signaled = m_PendingCv.wait_for(lk, std::chrono::milliseconds(timeoutMs), + // 500ms 一片地等:取消后最多一个切片就落到下面的超时分支,仍由本线程清理 map。 + const bool signaled = WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs), [&] { return it->second.done; }); if (!signaled || it->second.data.empty()) { // 放弃:客户端可能在我们返回后才把应答首包发上来,登记吸收,别让它弹 MFC 窗口。 @@ -9194,8 +10308,9 @@ bool CMcpServer::WaitSearchFile(uint64_t device_id, std::vectorsecond.tool != "search_file") return false; - m_PendingCv.wait_for(lk, std::chrono::milliseconds(timeoutMs), - [&] { return it->second.searchFinished; }); + // 取消(search_file 120s 上限)后仍然把已收记录带出去:调用方会去停搜并返回部分结果。 + WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs), + [&] { return it->second.searchFinished; }); records.swap(it->second.searchRecords); it->second.searchRecords.clear(); @@ -9302,11 +10417,11 @@ bool CMcpServer::WaitPendingRegistry(uint64_t device_id, std::vector& subk auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return false; - bool signaled = m_PendingCv.wait_for(lk, std::chrono::milliseconds(timeoutMs), - [&] { return it->second.done; }); + bool signaled = WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs), + [&] { return it->second.done; }); if (!signaled) { MarkLateFirstPacketForTool(device_id, it->second.tool); // 放弃后的 TOKEN_REGEDIT 不弹注册表窗口 - m_Pending.erase(it); // 超时 → 清理 + m_Pending.erase(it); // 超时/取消 → 清理 return false; } subkeys = std::move(it->second.regPath); @@ -9392,8 +10507,8 @@ bool CMcpServer::WaitPendingWrite(uint64_t device_id, std::vector& out, in } if (phaseOut) *phaseOut = it->second.phase; - bool signaled = m_PendingCv.wait_for(lk, std::chrono::milliseconds(timeoutMs), - [&] { return it->second.done; }); + bool signaled = WaitWithCancel(lk, m_PendingCv, DeadlineAfter(timeoutMs), + [&] { return it->second.done; }); // 超时/空数据时把「放弃那一刻所处的阶段」带出去:P10-B 的 phase 1 表示完成包已到、 // 只是复核列目录没回来(命令已送达),与 phase 0 的「连回包都没有」不是一回事。 if (phaseOut) *phaseOut = it->second.phase; @@ -9594,6 +10709,7 @@ bool CMcpServer::WaitC2CDone(uint64_t src_id, int timeoutMs, C2CResult& out) { signaled = true; break; } + if (McpCallCancelled()) break; // P11:取消按「未收到结果」收尾 } FileTransferSession& s = it->second; @@ -9619,6 +10735,7 @@ bool CMcpServer::WaitC2CReceiver(uint64_t src_id, int timeoutMs, C2CResult& out) if (now + slice > deadline) slice = std::chrono::duration_cast(deadline - now); if (slice.count() <= 0) break; // 超时:老客户端/Windows 目标根本不回执 m_FileXferCv.wait_for(lk, slice); + if (McpCallCancelled()) break; } FileTransferSession& s = it->second; @@ -9675,6 +10792,7 @@ void CMcpServer::OnFileChunkV2(uint64_t device_id, context* streamSubCtx, const if (s.tool != "download_file") return; if (s.done) return; // 已出错/完成,丢弃迟到包 s.lastDataAt = std::chrono::steady_clock::now(); // 停滞看门狗:有包就续命 + s.bytesReceived += pkt->dataLength; // P11:进度通知的兜底量(文件数未知时用) if (s.streamSubCtx == nullptr) { s.streamSubCtx = streamSubCtx; @@ -9822,6 +10940,18 @@ bool CMcpServer::WaitFileTransferDone(uint64_t device_id, int timeoutMs, signaled = true; break; } + // 进度:已落盘文件数 / 期望文件数(总量未知时退回已收字节数)。 + // EmitProgress 内部按 1s 节流,这里每片(500ms)报一次不会把流刷爆。 + { + const uint32_t expectedNow = + (it->second.totalFiles > it->second.directoryCount) + ? (it->second.totalFiles - it->second.directoryCount) : 0; + if (expectedNow > 0) + McpCallProgress((double)it->second.filesDone, (double)expectedNow); + else + McpCallProgress((double)it->second.bytesReceived); + } + if (McpCallCancelled()) break; // 取消 → 下面按超时(1002)收尾 if (std::chrono::steady_clock::now() - it->second.lastDataAt >= std::chrono::milliseconds(kFileXferStallMs)) { it->second.error = 1004; // 停滞 diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index d487f73..8a90c3e 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -50,6 +50,55 @@ struct ChatMessage { std::string text; }; +// ===== P11:tools/call 的在飞上下文(progress / cancelled / 会话观测)===== +// +// 每一次 tools/call 都在服务端登记一个 McpCallContext(见 CMcpServer::BeginCall), +// 工具实现通过 CurrentMcpCall() 拿到它(实现是 FLS 每线程槽,不是 thread_local: +// 本工程有 shellcode 线程,thread_local 会让服务端启动即崩,原因见 McpServer.cpp): +// - 长任务在等待循环里调用 McpCallProgress(),按 1s 节流把 +// notifications/progress 推给带 _meta.progressToken 的请求; +// - 等待循环用 McpCallCancelled() 尽早返回(notifications/cancelled 或 +// mcp_cancel_session 置位后 ≤1 个等待切片退出,走既有的超时清理路径); +// - mcp_list_sessions 用它回答「谁占着这台主机」。 +// channel 只在 SSE 请求上非空:进度通知随该请求自己的流下发,不需要额外的 GET 流。 +struct McpProgressChannel; // 定义见 McpServer.cpp + +struct McpCallContext { + std::string idKey; // JSON-RPC id 的紧凑序列化(字符串带引号;"41" 与 41 不混同) + std::string idText; // 同一 id 的展示文本(字符串取原文、整数取十进制), + // 与 mcp_list_sessions 的 request_id 一致,可按它回传取消 + std::string tool; + uint64_t device = 0; // 参数里的 id(没有则为 0) + std::string sessionId; // 参数里的 session_id(没有则空) + std::chrono::steady_clock::time_point startedAt; + + // 取消位:取消后工具层的等待按超时返回,服务端把最终错误统一改写成 -32800。 + std::atomic cancelled{false}; + + // 进度通道:hasProgressToken=false 时一切进度调用都是空操作。 + bool hasProgressToken = false; + std::string progressTokenJson; // progressToken 的 JSON 文本(原样回显) + std::shared_ptr channel; + std::mutex progressMu; + std::chrono::steady_clock::time_point lastProgressAt{}; + + // 节流(约 1s)后投递一条 progress 通知;没有 token/通道时直接返回。 + void EmitProgress(double current, double total, bool hasTotal); + bool IsCancelled() const { return cancelled.load(std::memory_order_relaxed); } +}; + +// 当前工具调用的上下文(每线程槽;非 MCP 工具线程返回 nullptr)。 +std::shared_ptr CurrentMcpCall(); +// 当前调用是否已被取消(没有上下文时为 false)。 +bool McpCallCancelled(); +// 报告进度:McpCallProgress(n) 表示「进度 n、无总量」;带 total 的重载给出总量。 +void McpCallProgress(double current); +void McpCallProgress(double current, double total); + +// -32003 的正文:在通用句后附上「谁占着这台主机、已持续多久」(没有占用信息时原样返回 +// base)。占着主机的是别的一次调用——当前这次 tools/call 自己会被排除。 +std::string BusyMessage(const std::string& base, uint64_t devId); + // MCP (Model Context Protocol) 服务端:httplib 封装 + JSON-RPC 2.0 分发 + 静态 token 校验。 // 与 CWebService 平级、互不依赖;默认禁用,经「扩展 → MCP设置」开启后监听 // (默认 127.0.0.1:6544,仅本机回环)。见 docs/Mcp_Design.md。 @@ -531,8 +580,8 @@ public: // 工具线程:发送结束(清 sendBusy)。closed 期间发送失败时调用方仍须调用。 void FinishChatSend(uint64_t device_id, const std::string& sessionId); - // 工具线程:取走最多 maxMessages 条;inbox 为空则等到 deadline / closed。 - enum class ChatWaitResult { Ok, Timeout, Closed, NotFound, Mismatch, Busy }; + // 工具线程:取走最多 maxMessages 条;inbox 为空则等到 deadline / closed / 取消。 + enum class ChatWaitResult { Ok, Timeout, Closed, NotFound, Mismatch, Busy, Cancelled }; ChatWaitResult WaitChatMessages(uint64_t device_id, const std::string& sessionId, int timeoutMs, size_t maxMessages, std::vector& out, bool& timedOut, @@ -565,6 +614,39 @@ public: void GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl, int& fileXfer, int& chat, int& blockedIps); + // ===== P11:在飞调用登记(progress / cancelled / mcp_list_sessions)===== + // 每次 tools/call 登记一个上下文;EndCall 必须在工具返回后调用(幂等)。 + // idKey / idText 是同一个 JSON-RPC id 的两种写法(紧凑 JSON / 展示文本), + // 匹配一律先按 idKey 精确比(区分 "41" 与 41),再退回 idText。 + std::shared_ptr BeginCall(const std::string& idKey, const std::string& idText, + const std::string& tool, + uint64_t device, const std::string& sessionId); + void EndCall(const std::shared_ptr& call); + + // notifications/cancelled:按 JSON-RPC id 匹配在飞调用,置取消位。返回是否命中。 + bool CancelCallById(const std::string& idKey, const std::string& idText); + + // mcp_cancel_session:按主机(device=0 表示任意)与会话 id(空表示任意)匹配在飞调用。 + // 返回被取消的数量;工具层的等待会在 ≤1s 内退出并走既有清理路径。 + int CancelCalls(uint64_t device, const std::string& sessionId); + + // mcp_list_sessions 的快照条目(一把锁一次拷贝,不跨表保持一致性)。 + struct SessionSnapshot { + uint64_t device = 0; + std::string kind; // pending / call / terminal / remote_control / file_transfer / chat + std::string tool; + std::string sessionId; + std::string idKey; // kind=call:JSON-RPC id 的紧凑序列化(匹配用,"41" 与 41 不同) + std::string requestId; // kind=call:同一 id 的展示文本(列表输出用,可直接回传 request_id) + bool busy = false; + long long elapsedMs = -1; // 会话已持续(<0 未知) + long long idleMs = -1; // 距最后一次活动(<0 未知) + }; + std::vector ListSessions(); + + // -32003 文案后缀:说明该主机正被哪个工具占着、已持续多久;没有占用信息时返回空串。 + std::string DescribeBusy(uint64_t device_id); + private: CMcpServer(); ~CMcpServer(); @@ -626,6 +708,8 @@ private: struct PendingRequest { std::string tool; std::string path; // list_files:目录路径;list_registry:rootToken(1B)+相对子键路径 + // P11:mcp_list_sessions 展示用。默认取构造时刻,所有 Begin* 都不必显式设置。 + std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); uint16_t expectedReqId = 0; // get_screenshot:期望的预览 reqId(0 = 未设置) std::vector data; std::vector regPath; // list_registry:TOKEN_REG_PATH 子键包(含 token 字节) @@ -664,6 +748,11 @@ private: std::condition_variable m_PendingCv; std::map m_Pending; + // ===== P11:在飞 tools/call 上下文(受 m_CallMutex 保护)===== + // 向量足够:同时在飞的调用只有个位数,取消/列举都是全表扫描。 + std::mutex m_CallMutex; + std::vector> m_Calls; + // ===== P8:子连接路由(受 m_PendingMutex 保护)===== // 已绑定子连接 → device(该子连接的一切包都由 MCP 消费)。 std::map m_SubCtxToDevice; @@ -717,6 +806,7 @@ private: bool persistent = false; bool busy = false; // 一条命令在飞(terminal_exec 复位→WaitTermCommand 返回) time_t lastActiveAt = 0; // idle 回收用(秒) + std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11 }; std::mutex m_TermMutex; std::condition_variable m_TermCv; @@ -740,6 +830,7 @@ private: bool busy = false; // 一条注入在飞(BeginScreenCtrlAction→End 之间) bool closed = false; // 注入期间屏幕子连接已断(由注入线程收尾) time_t lastActiveAt = 0; // idle 回收用(秒) + std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11 int screenW = 0; // 物理捕获分辨率(来自 TOKEN_BITMAPINFO) int screenH = 0; // P10-C 键鼠锁定:inputBlocked 是服务端认为的锁定状态(唯一真相,用于强制解锁); @@ -785,6 +876,9 @@ private: std::set skipIndexes; // overwrite=false 跳过的 fileIndex std::vector skipped; // 跳过的文件(供输出) time_t startAt = 0; + std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11 + // P11:已收到的数据字节数(进度通知用;download 按 chunk 累加) + uint64_t bytesReceived = 0; // 停滞看门狗:最后一次收到数据的时间。远程路径不存在时客户端一个包都不发, // 旧实现只能干等满 timeout_ms(默认 600s,整台主机被单飞互斥锁住,评审 P2)。 std::chrono::steady_clock::time_point lastDataAt; @@ -810,6 +904,7 @@ private: bool waitBusy = false; // 同一会话只允许一个 chat_wait std::chrono::steady_clock::time_point readyAt; // 建窗等待期满(绑定 + 1000ms) time_t lastActiveAt = 0; + std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11 std::deque inbox; // 未投递消息(UTF-8) size_t inboxBytes = 0; uint64_t nextMsgId = 1; diff --git a/tools/mcp_smoke.ps1 b/tools/mcp_smoke.ps1 index c64bca4..94fb6bf 100644 --- a/tools/mcp_smoke.ps1 +++ b/tools/mcp_smoke.ps1 @@ -9,6 +9,14 @@ 它在那个目录下建一个 mcp_smoke_xxxx 沙箱,走完 create/upload/rename/delete 后整棵删掉,不碰沙箱以外的任何东西。 + [6] 是 P11 的验收:-32012(校验拒绝,历史别名 -32008 不再出现)、dry_run + 只校验不下发、mcp_list_sessions / mcp_cancel_session 与 notifications/cancelled + 的取消路径(取消后 1s 内释放主机、被取消的请求回 -32800)、以及 SSE 进度通知。 + 其中「真实取消」会起一条能在目标机跑够 ~25s 的无副作用命令(Windows 上是 + ping -n 25 127.0.0.1,没有 exec_command 时退回 get_keylog 20s),1s 后取消; + 命令本身会在目标机上自己跑完,不影响结果。SSE 进度一节同样要求 -FileWriteDir, + 会往那个目录上传一个 4 MB 临时文件并在结束时删掉。 + 用法: $env:YAMA_MCP_TOKEN = '' # 与 service 的 McpToken 一致 powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 @@ -44,6 +52,9 @@ param( ) $ErrorActionPreference = 'Stop' +# Start-RpcAsync 用 HttpClient 发并发请求;Windows PowerShell 5.1 默认没加载这个程序集, +# 而类型字面量在执行该语句时就要能解析,所以放在脚本开头加载。 +try { Add-Type -AssemblyName System.Net.Http -ErrorAction Stop } catch { } $script:pass = 0 $script:fail = 0 $script:failures = @() @@ -97,6 +108,58 @@ function HasPaging($obj) { return $true } +# 工具是否出现在 tools/list 里:不可见多半是开关关着(正常配置),相关断言跳过而不是报失败。 +function HasTool([string]$name) { + return (@($tools | Where-Object { $_.name -eq $name }).Count -gt 0) +} + +# 并发发起一个 tools/call:取消测试要在请求还在飞的时候去查表、去取消, +# 单线程的 Invoke-WebRequest 做不到。返回句柄交给 Receive-RpcAsync 收尾。 +# +# 用 HttpClient.SendAsync(真异步,立即返回 Task)。别用 HttpWebRequest + BeginGetResponse: +# 实测 EndGetResponse 之前 BeginGetResponse 自己就会阻塞到响应头到达(服务端在工具跑完 +# 才写响应头),于是「异步」调用其实是同步的,被测的长调用根本没在飞。 +$script:HttpClient = $null +function Get-SmokeHttpClient() { + if (-not $script:HttpClient) { + $c = New-Object System.Net.Http.HttpClient + $c.Timeout = [TimeSpan]::FromSeconds(180) + $script:HttpClient = $c + } + return $script:HttpClient +} +function Start-RpcAsync([string]$json) { + $req = New-Object System.Net.Http.HttpRequestMessage([System.Net.Http.HttpMethod]::Post, $Base) + $req.Content = New-Object System.Net.Http.StringContent($json, [System.Text.Encoding]::UTF8, 'application/json') + $req.Headers.Add('Authorization', 'Bearer ' + $Token) + $req.Headers.Add('Accept', 'application/json, text/event-stream') + return @{ Request = $req; Task = (Get-SmokeHttpClient).SendAsync($req) } +} + +function Receive-RpcAsync($handle) { + $resp = $null + try { + $resp = $handle.Task.GetAwaiter().GetResult() # 非 2xx 不抛异常(没调 EnsureSuccessStatusCode) + return $resp.Content.ReadAsStringAsync().GetAwaiter().GetResult() + } catch { + return '' + } finally { + if ($resp) { $resp.Dispose() } + $handle.Request.Dispose() + } +} + +# 带 Accept: text/event-stream 的请求:带 _meta.progressToken 的 tools/call 会以 +# chunked SSE 回应,Invoke-WebRequest 读完整条流后一次性返回正文。 +function Send-Sse([string]$json, [string]$auth) { + $bytes = [System.Text.Encoding]::UTF8.GetBytes($json) + $headers = @{ Authorization = 'Bearer ' + $auth; Accept = 'application/json, text/event-stream' } + $resp = Invoke-WebRequest -Uri $Base -Method Post -Body $bytes -ContentType 'application/json' ` + -Headers $headers -TimeoutSec 300 -UseBasicParsing + return @{ Status = [int]$resp.StatusCode; Body = [string]$resp.Content + ContentType = [string]$resp.Headers['Content-Type'] } +} + # 结果外露(docs/Mcp_Design.md §14):content 末尾必须有一个可解析的 JSON 文本块, # 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。 function HasJsonText($rpc) { @@ -147,6 +210,12 @@ $ro = @($tools | Where-Object { $_.annotations.readOnlyHint -eq $true }) Check '存在只读工具且无只读工具被标为破坏性' ($ro.Count -gt 0 -and (@($ro | Where-Object { $_.annotations.destructiveHint -eq $true }).Count -eq 0)) ("readOnly=" + $ro.Count) +# P11:在飞会话的观测 / 取消入口必须一直可见——它是卡住请求的唯一出路, +# 因此不受功能开关与只读模式限制(只读时也在列表里)。 +foreach ($n in @('mcp_list_sessions', 'mcp_cancel_session')) { + Check ('tools/list 含 ' + $n) (@($tools | Where-Object { $_.name -eq $n }).Count -eq 1) +} + # ===== 2b. 协议层错误码 ===== Write-Host "`n[2b] 协议层错误码" $um = Rpc 'bogus/method' @{} $null $null @@ -271,6 +340,14 @@ if (-not $SkipHost) { ($byPid.error -eq $null -and [int]$bp.total -ge 1 -and @($bp.processes | Where-Object { [int]$_.pid -ne $ppid }).Count -eq 0) ` ("pid=" + $ppid + " total=" + $bp.total) + + # 6b 的 dry_run 断言要拿一个真能操作的进程:pid 0 是内核伪进程([System Process]), + # kill_process 按约定拒绝非零以外的 PID,host_control_process 也认不出它。 + $sample = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 50 } + if ($null -eq $sample.error) { + $realProc = @($sample.result.structuredContent.processes | Where-Object { [int]$_.pid -gt 4 })[0] + if ($realProc) { $ppid = [int]$realProc.pid } + } } $wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 } @@ -567,6 +644,261 @@ if ($offGate) { Write-Host " 所有功能开关都开着,跳过 -32006 检查(关掉任一开关再跑一次可覆盖)。" -ForegroundColor Yellow } +# ===== 6. P11:校验码 / dry_run / 在飞会话观测与取消 / SSE 进度 ===== +# 每条都对应 P11 的一条验收: +# 6a -32012(校验拒绝)取代历史别名 -32008; +# 6b dry_run 统一「只校验目标、不下发动作」; +# 6c mcp_list_sessions 快照 + mcp_cancel_session 与 notifications/cancelled 的取消, +# 以及「取消后主机 1s 内释放」(用 get_server_status.sessions.pending 复核); +# 6d 带 _meta.progressToken 的 tools/call 走 text/event-stream,长任务的进度通知计数 > 0。 +Write-Host "`n[6] P11 校验码、dry_run 与中断" + +# 取消测试要同时挂着长请求、还要再发短请求,需要比 .NET 默认(每主机 2 条)更多的连接。 +[System.Net.ServicePointManager]::DefaultConnectionLimit = 16 +$p11Host = (-not $SkipHost) -and [bool]$HostId +$isWindowsHost = ($null -eq $caps) -or (@('DLL', 'EXE', 'MEXE', 'SC', 'MDLL') -contains [string]$caps.platform) + +# 6a. -32012:命令里的 shell 元字符属于「参数被校验拒绝」,不是白名单拒绝(-32007) +if ($p11Host -and (HasTool 'exec_command')) { + $badCmd = Rpc '' $null 'exec_command' @{ id = $HostId; command = 'dir & whoami' } + Check 'exec_command 含 shell 元字符返回 -32012' ((ErrCode $badCmd) -eq -32012) (Detail $badCmd) + Check '校验拒绝不再使用历史别名 -32008' ((ErrCode $badCmd) -ne -32008) (Detail $badCmd) +} else { + Write-Host " exec_command 不可用,跳过 -32012 检查。" -ForegroundColor Yellow +} + +# 6b. dry_run:只取一次快照校验目标存在,结构化结果带 dry_run=true, +# 且不能出现「动作后才有」的字段(remaining / changed)——那意味着动作真的下发了。 +if ($p11Host -and (HasTool 'kill_process')) { + $drBad = Rpc '' $null 'kill_process' @{ id = $HostId; pids = @(4); dry_run = 'yes' } + Check 'kill_process dry_run 非布尔返回 -32602' ((ErrCode $drBad) -eq -32602) (Detail $drBad) + if ($null -ne $ppid) { + $dr = Rpc '' $null 'kill_process' @{ id = $HostId; pids = @($ppid); dry_run = $true } + $drs = $dr.result.structuredContent + Check 'kill_process dry_run=true 只校验(targets/missing,无 remaining)' ` + (($null -eq $dr.error) -and ($drs.dry_run -eq $true) -and + (@($drs.targets).Count -ge 1) -and + ($drs.PSObject.Properties.Name -contains 'missing') -and + -not ($drs.PSObject.Properties.Name -contains 'remaining')) (Detail $dr) + } +} else { + Write-Host " kill_process 不可用,跳过该 dry_run 检查。" -ForegroundColor Yellow +} + +$win0 = $null +if ($null -ne $wins -and $null -ne $wins.result) { $win0 = @($wins.result.structuredContent.windows)[0] } +if ($p11Host -and (HasTool 'operate_window') -and $win0 -and $null -ne $win0.hwnd) { + $owBad = Rpc '' $null 'operate_window' @{ id = $HostId; hwnd = $win0.hwnd; action = 'restore'; dry_run = 'yes' } + Check 'operate_window dry_run 非布尔返回 -32602' ((ErrCode $owBad) -eq -32602) (Detail $owBad) + $ow = Rpc '' $null 'operate_window' @{ id = $HostId; hwnd = $win0.hwnd; action = 'restore'; dry_run = $true } + $ows = $ow.result.structuredContent + Check 'operate_window dry_run=true 只校验(window 有值、无 changed)' ` + (($null -eq $ow.error) -and ($ows.dry_run -eq $true) -and ($null -ne $ows.window) -and + -not ($ows.PSObject.Properties.Name -contains 'changed')) (Detail $ow) +} else { + Write-Host " operate_window 不可用(或没有可见窗口),跳过该 dry_run 检查。" -ForegroundColor Yellow +} + +if ($p11Host -and (HasTool 'host_control_process') -and $null -ne $ppid) { + $hc = Rpc '' $null 'host_control_process' @{ id = $HostId; action = 'freeze'; pid = $ppid; dry_run = $true } + $hcs = $hc.result.structuredContent + Check 'host_control_process dry_run=true 只校验(state/detail,无 changed)' ` + (($null -eq $hc.error) -and ($hcs.dry_run -eq $true) -and ([string]$hcs.target -ne '') -and + -not ($hcs.PSObject.Properties.Name -contains 'changed')) (Detail $hc) +} else { + Write-Host " host_control_process 不可用,跳过该 dry_run 检查。" -ForegroundColor Yellow +} + +# 6c. 观测与取消。参数拒绝 / 空命中先测(不依赖主机),真实取消再单独跑。 +$ls0 = Rpc '' $null 'mcp_list_sessions' @{} +Check 'mcp_list_sessions 返回 sessions/count' ` + (($null -eq $ls0.error) -and ($null -ne $ls0.result.structuredContent.sessions) -and + ([int]$ls0.result.structuredContent.count -eq @($ls0.result.structuredContent.sessions).Count)) (Detail $ls0) +$lsBad = Rpc '' $null 'mcp_list_sessions' @{ kind = 'zzz-no-such-kind' } +Check 'mcp_list_sessions 非法 kind 返回 -32602' ((ErrCode $lsBad) -eq -32602) (Detail $lsBad) +$cnBad = Rpc '' $null 'mcp_cancel_session' @{} +Check 'mcp_cancel_session 缺参数返回 -32602' ((ErrCode $cnBad) -eq -32602) (Detail $cnBad) +$cnNone = Rpc '' $null 'mcp_cancel_session' @{ request_id = 'zzz-no-such-request' } +Check 'mcp_cancel_session 未命中返回 cancelled=0' ` + (($null -eq $cnNone.error) -and ([int]$cnNone.result.structuredContent.cancelled -eq 0)) (Detail $cnNone) + +# 真实取消:起一个确定会跑够 20s+ 的无副作用调用,等它进了在飞表再取消。 +# Windows 主机用 exec_command 跑 ping(白名单内、不需要管理员),其他平台退回 get_keylog。 +$longCall = $null +if ($p11Host) { + if ((HasTool 'exec_command') -and $isWindowsHost) { + $longCall = @{ tool = 'exec_command' + args = @{ id = $HostId; command = 'ping -n 25 127.0.0.1'; timeout_ms = 60000 } } + } elseif (HasTool 'get_keylog') { + $longCall = @{ tool = 'get_keylog'; args = @{ id = $HostId; duration_ms = 20000; max_bytes = 4096 } } + } +} + +function Wait-Session([string]$rid, [int]$tries = 40) { + # 轮询 mcp_list_sessions 直到出现这次调用(或超时),返回快照项。 + for ($i = 0; $i -lt $tries; $i++) { + Start-Sleep -Milliseconds 100 + $snap = Rpc '' $null 'mcp_list_sessions' @{ kind = 'call' } + if ($null -eq $snap.error) { + $hit = @($snap.result.structuredContent.sessions | Where-Object { [string]$_.request_id -eq $rid })[0] + if ($hit) { return $hit } + } + } + return $null +} + +if (-not $longCall) { + Write-Host " 没有能跑长的工具(exec_command/get_keylog),跳过取消与 SSE 进度检查。" -ForegroundColor Yellow +} else { + $rid = 'p11-cancel-' + (Get-Random -Minimum 1000 -Maximum 9999) + $payload = @{ jsonrpc = '2.0'; id = $rid; method = 'tools/call' + params = @{ name = $longCall.tool; arguments = $longCall.args } } | + ConvertTo-Json -Depth 8 -Compress + $h = Start-RpcAsync $payload + $seen = Wait-Session $rid + Check '在飞调用出现在 mcp_list_sessions 里' ($null -ne $seen) ("request_id=" + $rid) + if (-not $seen) { + $null = Receive-RpcAsync $h + Check '取消测试的前置条件(长调用进入在飞表)' $false '长任务没有进入在飞表,取消路径未验证' + } else { + Check '会话快照字段齐全(host_id/kind/tool/elapsed_ms)' ` + ((([string]$seen.host_id) -eq $HostId) -and ([string]$seen.kind -eq 'call') -and + ([string]$seen.tool -eq $longCall.tool) -and ($null -ne $seen.elapsed_ms)) ` + ("host_id=" + $seen.host_id + " kind=" + $seen.kind + " tool=" + $seen.tool) + + # -32003 的正文要点名占用者(P11 之前只有一句通用话)。它来自「同一主机的一次性 + # 待响应请求单飞行」:exec_command 走的是终端子连接,与 list_processes 这类请求 + # 并不互斥,所以占用者要用「并发打同一台主机」来制造,而不是拿长调用去当占用者。 + if (HasTool 'list_processes') { + $raceHandles = @() + for ($i = 0; $i -lt 8; $i++) { + $raceHandles += Start-RpcAsync (@{ jsonrpc = '2.0'; id = ('race-' + $i); method = 'tools/call' + params = @{ name = 'list_processes' + arguments = @{ id = $HostId; limit = 5 } } } | + ConvertTo-Json -Depth 8 -Compress) + } + $raceErrs = @() + foreach ($rh in $raceHandles) { + $rb = [string](Receive-RpcAsync $rh) + $rj = $null + try { $rj = $rb | ConvertFrom-Json } catch { continue } + if ($null -ne $rj.error) { $raceErrs += $rj } + } + $busy = @($raceErrs | Where-Object { [int]$_.error.code -eq -32003 })[0] + Check '并发请求同一主机时被拒的返回 -32003 且点名占用者' ` + (($null -ne $busy) -and ([string]$busy.error.message).Contains('tool=')) ` + (($raceErrs | ForEach-Object { [string]$_.error.message }) -join ' | ') + } + + $cn = Rpc '' $null 'mcp_cancel_session' @{ request_id = $rid } + $cns = $cn.result.structuredContent + Check 'mcp_cancel_session 按 request_id 取消' ` + (($null -eq $cn.error) -and ([int]$cns.cancelled -eq 1)) (Detail $cn) + Check '取消后主机 1s 内释放' ` + (($cns.released -eq $true) -and ([int]$cns.waited_ms -le 1000)) ` + ("released=" + $cns.released + " waited_ms=" + $cns.waited_ms) + + $body = [string](Receive-RpcAsync $h) + $jr = $null + try { $jr = $body | ConvertFrom-Json } catch { } + if ($body.Length -gt 160) { $body = $body.Substring(0, 160) } + Check '被取消的请求回 -32800' (($null -ne $jr) -and ($null -ne $jr.error) -and + ([int]$jr.error.code -eq -32800)) $body + + # 交叉核对:get_server_status 的 sessions.pending 应回到 0,主机能再次正常调用 + $st2 = (Rpc '' $null 'get_server_status' @{}).result.structuredContent.status + Check '取消后 get_server_status 无挂起(sessions.pending=0)' ` + ([int]$st2.sessions.pending -eq 0) ("pending=" + $st2.sessions.pending) + if (HasTool 'list_processes') { + $again = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 1 } + Check '取消后主机可再次正常调用' ($null -eq $again.error) (Detail $again) + } + + # notifications/cancelled:与 mcp_cancel_session 等价的通知路径(202 无响应体) + $rid2 = 'p11-notify-' + (Get-Random -Minimum 1000 -Maximum 9999) + $payload2 = @{ jsonrpc = '2.0'; id = $rid2; method = 'tools/call' + params = @{ name = $longCall.tool; arguments = $longCall.args } } | + ConvertTo-Json -Depth 8 -Compress + $h2 = Start-RpcAsync $payload2 + $seen2 = Wait-Session $rid2 + if (-not $seen2) { + $null = Receive-RpcAsync $h2 + Check '第二个长调用进入在飞表(通知取消前置)' $false '长任务没有进入在飞表' + } else { + $note = '{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":"' + + $rid2 + '","reason":"smoke"}}' + $nr = Send-Raw $note $Token + Check 'notifications/cancelled 返回 202' ($nr.Status -eq 202) ("status=" + $nr.Status) + $body2 = [string](Receive-RpcAsync $h2) + $jr2 = $null + try { $jr2 = $body2 | ConvertFrom-Json } catch { } + if ($body2.Length -gt 160) { $body2 = $body2.Substring(0, 160) } + Check '通知取消后请求回 -32800' (($null -ne $jr2) -and ($null -ne $jr2.error) -and + ([int]$jr2.error.code -eq -32800)) $body2 + # 通知路径没有「等释放」的返回值,只能自己轮询(≤2s) + $freed = $false + for ($i = 0; $i -lt 20 -and -not $freed; $i++) { + $snap3 = Rpc '' $null 'mcp_list_sessions' @{ kind = 'call' } + if (@($snap3.result.structuredContent.sessions | + Where-Object { [string]$_.request_id -eq $rid2 }).Count -eq 0) { $freed = $true } + else { Start-Sleep -Milliseconds 100 } + } + Check '通知取消后 2s 内从在飞表消失' $freed + } + } +} + +# 6d. SSE:带 _meta.progressToken 的 tools/call 以 text/event-stream 回应。 +# 先用一个立即返回的工具验证传输与收尾(进度天然为 0 条),再用一次真实上传验证进度。 +$probe = '{"jsonrpc":"2.0","id":7001,"method":"tools/call","params":{"name":"get_server_status","arguments":{},"_meta":{"progressToken":"smoke-probe"}}}' +$sse = Send-Sse $probe $Token +Check 'SSE:Content-Type 是 text/event-stream' ($sse.ContentType -like 'text/event-stream*') $sse.ContentType +$sseProbeLast = $null +foreach ($line in ($sse.Body -split "`n")) { + if ($line.StartsWith('data: ')) { try { $sseProbeLast = ($line.Substring(6) | ConvertFrom-Json) } catch { } } +} +Check 'SSE:流末尾是完整 JSON-RPC 响应' ` + (($null -ne $sseProbeLast) -and ([string]$sseProbeLast.id -eq '7001') -and + ($null -ne $sseProbeLast.result) -and ($null -eq $sseProbeLast.error)) + +if (-not $p11Host -or -not $FileWriteDir -or -not (HasTool 'upload_file') -or -not (HasTool 'delete_path')) { + Write-Host " 未给 -FileWriteDir 或文件写入工具不可见,跳过 SSE 进度检查(进度 > 0 需一次真实长任务)。" -ForegroundColor Yellow +} else { + # 4 MB 分 64 KB 一片:即使局域网很快也能产生多个进度回调(首个回调不受 1s 节流限制)。 + $progLocal = Join-Path $env:TEMP ('mcp_smoke_prog_' + (Get-Random -Minimum 1000 -Maximum 9999) + '.bin') + $fs = [System.IO.File]::Create($progLocal) + $chunk = New-Object byte[] (64 * 1024) + for ($i = 0; $i -lt 64; $i++) { $fs.Write($chunk, 0, $chunk.Length) } + $fs.Close() + $progName = [System.IO.Path]::GetFileName($progLocal) + # 注意:PowerShell 变量名大小写不敏感,别用 $tok —— 会覆盖掉 bearer token $Token。 + $progToken = 'smoke-progress-' + (Get-Random -Minimum 1000 -Maximum 9999) + $sseBody = @{ jsonrpc = '2.0'; id = 7002; method = 'tools/call' + params = @{ name = 'upload_file' + arguments = @{ id = $HostId; local_path = $progLocal; remote_dir = $FileWriteDir } + _meta = @{ progressToken = $progToken } } } | + ConvertTo-Json -Depth 10 -Compress + try { + $up = Send-Sse $sseBody $Token + $progCount = ([regex]::Matches($up.Body, [regex]::Escape('notifications/progress'))).Count + Check 'SSE:长任务收到 notifications/progress(计数 > 0)' ($progCount -gt 0) ("count=" + $progCount) + Check 'SSE:进度通知回显 progressToken 且带 progress' ` + (($up.Body -match ('"progressToken":"' + [regex]::Escape($progToken) + '"')) -and + ($up.Body -match '"progress":')) + $upLast = $null + foreach ($line in ($up.Body -split "`n")) { + if ($line.StartsWith('data: ')) { try { $upLast = ($line.Substring(6) | ConvertFrom-Json) } catch { } } + } + Check 'SSE:流末尾是 upload_file 的最终响应(未取消)' ` + (($null -ne $upLast) -and ([string]$upLast.id -eq '7002') -and + ($null -ne $upLast.result) -and ($null -eq $upLast.error)) + Check 'SSE 进度测试上传的文件已落盘' ((ListingNames $FileWriteDir) -contains $progName) + } finally { + $null = Rpc '' $null 'delete_path' @{ id = $HostId; path = ($FileWriteDir.TrimEnd('\') + '\' + $progName) } + Remove-Item -LiteralPath $progLocal -Force -ErrorAction SilentlyContinue + } +} + # ===== 汇总 ===== Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' }) if ($script:fail -gt 0) {