Feature: Add MCP cancellation, progress notifications and dry runs
P11 closes the plan's last batch, entirely on the server side: no client change is required for any of it. Long-running tools now expose a cancellation flag that every wait loop checks in 500 ms slices. A cancelled tool returns through the cleanup branch it already had (late first packets still get absorbed, sub connections still get closed, pending entries still get deleted), so there is no second cleanup path to keep in sync, and the host is released within a second. Three sources set the flag: notifications/cancelled (matched on the exact JSON-RPC id, with a fallback to the display form so a request_id copied out of the session list round-trips), mcp_cancel_session (by request_id, host id or session id), and a failed SSE write when the client has gone away. The dispatcher rewrites a cancel-induced failure to -32800 so callers do not mistake it for a host fault. tools/call requests carrying _meta.progressToken are answered as text/event-stream on the same POST: the tool runs on its own thread and both the notifications/progress events and the final JSON-RPC response go out through one chunked provider. Requests without a token are unchanged. download_file reports files done vs. expected, upload_file reports bytes sent vs. total. Two new local-only tools, mcp_list_sessions and mcp_cancel_session, list and cancel in-flight sessions (calls, pending one-shots, terminal, remote control, file transfer, chat). They are deliberately not gated by the feature switches or readonly mode, since that is the only way out of a stuck request. The -32003 busy message now names the occupier: "Device busy: ... (tool=download_file, elapsed=12s)". power_action gains wait/wait_ms to verify the result against the main connection's presence (went_offline, came_back, elapsed_ms); not seeing the transition is reported as ok, not as a failure. kill_process, operate_window and the four host_control_* tools accept dry_run, which validates the target against one fresh snapshot and returns what would be affected without sending anything. Validation rejections now use -32012; -32008 stays as documented historical alias. One implementation note worth recording: the per-thread call context uses FLS, not thread_local. Any static thread_local in this server crashes the process about a second after start, because some threads come from shellcode/MemoryModule images that never ran PE TLS initialisation. Verified against a real Debug server and a real Windows client over MCP: the smoke test now passes 104 checks with 0 failures, including cancellation releasing the host in under a second, the cancelled request returning -32800, notifications/cancelled returning 202, 63 progress events with exact byte counts for a 64 MB upload, and a cleanly terminated SSE stream. Not exercised in this pass: power_action's wait=true path (it would take the test host down) and the -32006 readonly/switch-off section (every switch was on during the run). Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
3d388f8e45
commit
1c832ff7f2
10 files changed
+1855
-107
No files matched your search
+3
-2
@@ -677,15 +677,16 @@ token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机
|
|||||||
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
|
| `-32602` | Invalid params | 未知工具名、缺必填参数、参数类型/取值非法、批量 `ids` 超过 50 个、`search_file` 过滤参数非法、文本无法转 GBK | 改参数重试,重试同样的请求不会成功 |
|
||||||
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
|
| `-32001` | Timeout | 等客户端就绪/等子连接/等搜索结果超时(`timeout_ms` 内没等到) | 可加大 `timeout_ms` 重试;持续出现看主机是否卡住 |
|
||||||
| `-32002` | Host offline / not found | 主机 id 不存在、主连接已断、会话 id 不存在或已关闭 | 先 `list_online_hosts` 刷新再选主机 |
|
| `-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` 处理 |
|
| `-32004` | Send failed | 命令写入主连接失败(连接刚断) | 重试一次;仍失败按 `-32002` 处理 |
|
||||||
| `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 |
|
| `-32005` | Not supported on this host | 能力限制,改参数也修不好:需要 Windows 的工具用在 LNX/MAC/APK 主机上;`remote_open` 遇到多显示器(阶段一);主机无屏幕预览/控制能力位 | 换主机或换工具;不要改参数重试 |
|
||||||
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
|
| `-32006` | Policy refused | 只读模式 / 对应 `Mcp*` 开关关闭 / 主机不支持该能力(如 V2 文件传输) | **不要重试**:这是配置决定,需管理员改服务端配置 |
|
||||||
| `-32007` | Not in command whitelist | `exec_command` 的命令不在 `McpCmdWhitelist` 里,或词边界不匹配(`dir` 过、`dirx` 拒) | **不要重试**:换成白名单内的命令,或请管理员加白名单项 |
|
| `-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`)确认目标存在 |
|
| `-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`) | **不要重试**:需客户端提权(管理员运行)或换目标 |
|
| `-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→磁盘满),先修目标端目录/权限 |
|
| `-32011` | Destination write failed | 文件传输的**目标端**已收到数据但写盘失败:`copy_files_c2c` / `upload_file` 的目标主机回了回执且 `status != 0`(`message` 带 status、首个 errno、实收文件数) | **不要原样重试**:按文案判断(errno 13/1→权限、2→路径不存在、28→磁盘满),先修目标端目录/权限 |
|
||||||
|
| `-32800` | Request cancelled | 客户端取消了这次调用:`notifications/cancelled`、`mcp_cancel_session` 或 SSE 流断开(检测到断开会置同一个取消位)。工具在 ≤1s 内退出等待并走既有的超时清理路径,主机占用已释放 | 不是主机故障,可直接重试;终止类命令可能已经执行,重试前先读一次现状 |
|
||||||
|
|
||||||
- **命令超时会销毁持久会话**(`terminal_exec`):等服务端收集到哨兵超时返回 `-32001`,会话随即被销毁并留 600 秒「墓碑」;对同一 `session_id` 再发命令返回 `-32002`,文案明确写 `Terminal session was destroyed after this command timed out (waited N ms); call terminal_open again`,与「id 写错」(`Terminal session not found: <id>`)区分开。
|
- **命令超时会销毁持久会话**(`terminal_exec`):等服务端收集到哨兵超时返回 `-32001`,会话随即被销毁并留 600 秒「墓碑」;对同一 `session_id` 再发命令返回 `-32002`,文案明确写 `Terminal session was destroyed after this command timed out (waited N ms); call terminal_open again`,与「id 写错」(`Terminal session not found: <id>`)区分开。
|
||||||
- **新客户端把失败改成结构化回报**(`TOKEN_SERVICE_ERROR=170` / `TOKEN_FILE_LIST_ERROR=171` / `TOKEN_REG_ERROR=172` / `TOKEN_DOWNLOAD_ERROR=173`,布局 `[token:1][win32 码:4 LE]`):`list_services`(未提权)、`list_files`/`list_registry`(路径/键不存在或拒绝访问)、`download_file`(远端路径全部不存在)都在客户端侧就失败并立即回报,服务端转译成 `-32009`/`-32010`,**亚秒级返回**,不再靠超时猜。老客户端不发这些包,成功路径报文一律不变,因此老客户端/老服务端的行为与改造前完全一致(老服务端把未知 token 走 `default` 丢弃)。
|
- **新客户端把失败改成结构化回报**(`TOKEN_SERVICE_ERROR=170` / `TOKEN_FILE_LIST_ERROR=171` / `TOKEN_REG_ERROR=172` / `TOKEN_DOWNLOAD_ERROR=173`,布局 `[token:1][win32 码:4 LE]`):`list_services`(未提权)、`list_files`/`list_registry`(路径/键不存在或拒绝访问)、`download_file`(远端路径全部不存在)都在客户端侧就失败并立即回报,服务端转译成 `-32009`/`-32010`,**亚秒级返回**,不再靠超时猜。老客户端不发这些包,成功路径报文一律不变,因此老客户端/老服务端的行为与改造前完全一致(老服务端把未知 token 走 `default` 丢弃)。
|
||||||
|
|||||||
+89
-1
@@ -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-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-B** | `delete_path` / `move_path` / `create_folder` + `McpFileWrite` 开关 + 系统目录保护 + §2.3 的三处接线 + `verified` 复核 | 无 | ~700 行 | 冒烟新增:建目录→传文件→改名→删除→删目录→越界拒绝;中文路径 + 超长路径各一条;超时后确认**不弹**文件管理器窗口 |
|
||||||
| **P10-C** | `remote_block_input`(含强制解锁与超时自动解锁) | 无 | ~200 行 | 会话内 block→截图对比→unblock;`remote_close` 后确认已解锁 |
|
| **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` 的路径长度防御 | **需要** | 客户端 + 服务端 | 单独设计文档 |
|
| **P12** | 注册表写、事件日志、进程模块/启动项、`TOKEN_FILE_OP_ERROR`、`DeleteDirectory` 的路径长度防御 | **需要** | 客户端 + 服务端 | 单独设计文档 |
|
||||||
| **独立立项** | 代理隧道、客户端升级、摄像头/语音 | 视方案 | 大 | 单独安全评审 |
|
| **独立立项** | 代理隧道、客户端升级、摄像头/语音 | 视方案 | 大 | 单独安全评审 |
|
||||||
|
|
||||||
@@ -592,3 +592,91 @@ MCP 路径的 `hDlg` 恒为 `NULL`,所以第 2 层一定会命中——这一
|
|||||||
配置开关的接线也是三处:读取(`2015RemoteDlg.cpp:2416` 块)、对话框回填(`McpSettingsDlg.cpp:227`)、
|
配置开关的接线也是三处:读取(`2015RemoteDlg.cpp:2416` 块)、对话框回填(`McpSettingsDlg.cpp:227`)、
|
||||||
落盘(`McpSettingsDlg.cpp:383`)。对话框是**纯代码构建**的(`McpSettingsDlg.cpp:128-186`),
|
落盘(`McpSettingsDlg.cpp:383`)。对话框是**纯代码构建**的(`McpSettingsDlg.cpp:128-186`),
|
||||||
插入一个 checkbox 需要重排其下所有控件的 y 坐标与窗口高度。
|
插入一个 checkbox 需要重排其下所有控件的 y 坐标与窗口高度。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 附录 D:P11 施工记录(2026-10-28)
|
||||||
|
|
||||||
|
零客户端改动,全部落在服务端(`McpServer.cpp` / `McpServer.h` / `McpMachine.cpp` /
|
||||||
|
`McpChat.cpp` / `McpInternal.{h,cpp}`)。
|
||||||
|
|
||||||
|
### D.1 `power_action` 的结果验证(§5.4)
|
||||||
|
|
||||||
|
- 新入参 `wait`(bool,默认 false)与 `wait_ms`(1000–600000,默认 60000),`wait_ms` 是
|
||||||
|
「等离线」与「等回线」**各自**的时限;`wait=false` 时也会校验 `wait_ms` 的取值范围。
|
||||||
|
- 输出从 `{ok}` 扩展为 `{ok, sent, went_offline, came_back, elapsed_ms}`:
|
||||||
|
`sent` 恒为 true(命令写进 socket),`went_offline` / `came_back` 由主连接的出现/消失判定
|
||||||
|
(`FindMainContext`,200ms 轮询),`elapsed_ms` 为整次调用的耗时。
|
||||||
|
- **超时不是错误**:`wait=true` 但没等到离线/回线时仍返回 `ok:true` 并在正文里写清「仍在
|
||||||
|
线」或「已离线但未回线」,让模型据此决定是否再等,而不是把「没等到」当成失败重试。
|
||||||
|
- `logout` 之后主机不会自动回线(需要人工登录),正文单独提示。
|
||||||
|
|
||||||
|
### D.2 破坏性工具统一 `dry_run`(§5.5)
|
||||||
|
|
||||||
|
| 工具 | `dry_run=true` 时的行为 |
|
||||||
|
|---|---|
|
||||||
|
| `kill_process` | 只取一次进程列表,回 `{ok, dry_run, targets:[{pid,name,path}], missing:[pid...]}`,**不下发终止命令**;一个都匹配不到返回 `-32009` |
|
||||||
|
| `operate_window` | 只取一次窗口列表,回 `{ok, dry_run, action, window}`;窗口不存在返回 `-32009` |
|
||||||
|
| `host_control_process` / `_window` / `_service` / `_task` | 只做目标存在性校验,回 `{ok, dry_run, action, target, state, detail}`(detail 是被影响对象的原始字段) |
|
||||||
|
|
||||||
|
实现要点:dry run 的挂起项以 `"<tool>/dryrun"` 登记,`OnSystemReady` 只认 `kill_process` /
|
||||||
|
`operate_window` 两个**精确**工具名,因此不会误发后续写命令;迟到首包仍按既有逻辑吸收。
|
||||||
|
|
||||||
|
### D.3 `-32012` 与 `-32008` 别名(§5.6)
|
||||||
|
|
||||||
|
- 两个真实站点(`exec_command` 的 shell 元字符、`terminal_exec` 的 `&`/`|`/换行)改为
|
||||||
|
`McpInternal::kErrValidation = -32012`;`kErrValidationOld = -32008` 保留为历史别名,不再新增使用。
|
||||||
|
- `initialize.instructions` 的错误码表与 `docs/Mcp_Design.md §12` 同步;`-32800` 一并登记。
|
||||||
|
|
||||||
|
### D.4 `notifications/progress` 与 `notifications/cancelled`(§5.9)
|
||||||
|
|
||||||
|
**传输**:本服务端原本每个 POST 只回一个 JSON。带 `params._meta.progressToken` 的 `tools/call`
|
||||||
|
改走 MCP Streamable HTTP 允许的 `text/event-stream`(同一个 POST):
|
||||||
|
|
||||||
|
1. 工具在独立线程执行,`McpCallContext` 经 FLS(Fiber Local Storage)暴露给工具实现
|
||||||
|
——**不能用 `thread_local`**:本工程有 shellcode/MemoryModule 手工映射出来的线程,没有
|
||||||
|
PE 的 TLS 初始化,加一个静态 `thread_local` 就会让服务端启动约 1s 后跳飞(实测);
|
||||||
|
2. 进度通知与最终响应都从这个 SSE 流写出(`McpProgressChannel`,背压队列上限 64 条,
|
||||||
|
满了丢最旧——进度是「最新值有意义」的信号);
|
||||||
|
3. 不带 token 的请求完全不变(一次性 JSON)。
|
||||||
|
|
||||||
|
**进度上报点**(`McpCallProgress`,内部 1s 节流):
|
||||||
|
|
||||||
|
| 工具 | 进度含义 |
|
||||||
|
|---|---|
|
||||||
|
| `download_file` | `filesDone / (totalFiles - directoryCount)`;总量未知时退回已收字节数 |
|
||||||
|
| `upload_file` | 已发数据字节 / 待发数据字节总数(在 worker 的分块回调里累加) |
|
||||||
|
| `copy_files_c2c` | 源端只在最后回一包结果,因此不报中间进度;取消/超时按既有路径收尾 |
|
||||||
|
| `search_file` | 命中数在客户端,服务端只在收尾时报一次结果(见下) |
|
||||||
|
| `chat_wait` | 等待期无中间量,取消即时生效 |
|
||||||
|
|
||||||
|
**取消**:三条入口共用一个取消位(`McpCallContext::cancelled`)
|
||||||
|
|
||||||
|
- `notifications/cancelled`(`params.requestId` 按 JSON-RPC id 精确匹配,字符串与数字不混用);
|
||||||
|
- `mcp_cancel_session`(按 request_id / host id / session_id);
|
||||||
|
- SSE 流写失败(客户端已断开)。
|
||||||
|
|
||||||
|
所有长等待都改成「≤500ms 一片 + 每片检查取消位」(`WaitWithCancel`),取消后直接落到各函数
|
||||||
|
**既有的超时/放弃分支**:`MarkLateFirstPacketForTool` 照登、子连接照关、挂起项照删。因此取消
|
||||||
|
不需要第二套清理逻辑,也满足「取消后主机 1s 内释放」。取消导致的失败结果由分发层统一改写成
|
||||||
|
`-32800`(已经拿到成功结果则照实返回)。
|
||||||
|
|
||||||
|
### D.5 `mcp_list_sessions` / `mcp_cancel_session`(§5.10)
|
||||||
|
|
||||||
|
- `mcp_list_sessions`:一次快照列出在飞 `tools/call`(含 JSON-RPC `request_id`)、挂起中的一次性
|
||||||
|
请求、终端、远程控制、文件传输、远程交谈;字段 `host_id/kind/tool/session_id/request_id/busy/
|
||||||
|
elapsed_ms/idle_ms`,可选 `kind` 过滤。纯本地,**不受功能开关与只读模式限制**。
|
||||||
|
- `mcp_cancel_session`:按 `request_id`(精确)或 `id`/`session_id`(条件)取消,返回
|
||||||
|
`{cancelled, released, waited_ms, matched}`;最多等 2s 让工具线程走完清理,`released` 说明
|
||||||
|
主机是否真的松开。
|
||||||
|
- `-32003` 的文案统一追加占用者:`Device busy: another request is pending for this host
|
||||||
|
(tool=download_file, elapsed=12s)`。`DescribeBusy` 会排除发起本次错误的那个调用自身。
|
||||||
|
|
||||||
|
### D.6 已知边界
|
||||||
|
|
||||||
|
- SSE 请求会占住 httplib 的一个 worker 线程直到工具结束(线程池 32);单机管理场景足够,
|
||||||
|
不作为多租户端点使用。
|
||||||
|
- `search_file` 被取消时返回**已收到的部分结果**(`finished=false`),不是 `-32800`:搜索是只读
|
||||||
|
累积操作,部分结果对调用方更有用;它同样在 ≤1s 内释放主机。
|
||||||
|
- `mcp_cancel_session` 找不到匹配项时返回 `cancelled:0`(不是错误)——请求可能已经结束,
|
||||||
|
或 `request_id` 的 JSON 类型与调用时不一致。
|
||||||
@@ -153,8 +153,8 @@ FindMainContext → -32002 主机不存在/离线
|
|||||||
clientType==LNX/MAC → -32005 仅 Windows
|
clientType==LNX/MAC → -32005 仅 Windows
|
||||||
command 为空 → -32602
|
command 为空 → -32602
|
||||||
mcp.IsReadonly() → -32006 只读模式默认开,需 McpReadonly=0
|
mcp.IsReadonly() → -32006 只读模式默认开,需 McpReadonly=0
|
||||||
含 &|<>^ 五元字符 → -32008 防注入绕过白名单
|
含 &|<>^ 五元字符 → -32012 防注入绕过白名单(-32008 为历史别名)
|
||||||
含控制字符(\r\n 等 <0x20) → -32008 防换行拆分绕过白名单
|
含控制字符(\r\n 等 <0x20) → -32012 防换行拆分绕过白名单
|
||||||
白名单前缀校验 → -32007 不在白名单
|
白名单前缀校验 → -32007 不在白名单
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -237,7 +237,7 @@ SweepIdleTerminals(300)
|
|||||||
ResolveTerminalSessionHost
|
ResolveTerminalSessionHost
|
||||||
session_id 为空 → -32602
|
session_id 为空 → -32602
|
||||||
command 为空 → -32602
|
command 为空 → -32602
|
||||||
command 含 & 或 | → -32008(正确性门,见 §4.6)
|
command 含 & 或 | → -32012(正确性门,见 §4.6)
|
||||||
nonce = 随机 8 hex
|
nonce = 随机 8 hex
|
||||||
BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty)
|
BeginTermCommand(devId, sessionId, command, nonce, subCtx, isPty)
|
||||||
→ false 则 -32002(不存在/不匹配/未就绪/忙碌/已关)
|
→ false 则 -32002(不存在/不匹配/未就绪/忙碌/已关)
|
||||||
@@ -273,7 +273,7 @@ CloseTermSession(devId, sessionId)
|
|||||||
|
|
||||||
### 4.6 正确性门 `&|`(非安全门)
|
### 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`):换行会把命令拆成多行、只有末行被哨兵包装,导致退出码与输出归属失真。
|
- 同样拒绝 `<0x20` 的控制字符(`\r`/`\n`):换行会把命令拆成多行、只有末行被哨兵包装,导致退出码与输出归属失真。
|
||||||
@@ -415,7 +415,7 @@ McpServer().SetTerminalEnabled(THIS_CFG.GetInt("settings", "McpTerminal", 0) !=
|
|||||||
| `-32005` | 非 Windows | LNX/MAC 客户端 |
|
| `-32005` | 非 Windows | LNX/MAC 客户端 |
|
||||||
| `-32006` | 已禁用/只读 | `IsReadonly()` 或 `!IsTerminalEnabled()` |
|
| `-32006` | 已禁用/只读 | `IsReadonly()` 或 `!IsTerminalEnabled()` |
|
||||||
| `-32007` | 白名单拒绝 | `IsCommandAllowed` false |
|
| `-32007` | 白名单拒绝 | `IsCommandAllowed` false |
|
||||||
| `-32008` | 含禁用字符 | `exec_command` 的 `&|<>^`;`terminal_exec` 的 `&|` |
|
| `-32012` | 含禁用字符 | `exec_command` 的 `&|<>^`;`terminal_exec` 的 `&|`(早期版本用 `-32008`,同一语义) |
|
||||||
| `-32602` | 参数非法 | `ParseHostIdArg` 失败、缺 required 参数 |
|
| `-32602` | 参数非法 | `ParseHostIdArg` 失败、缺 required 参数 |
|
||||||
| `-32700` | JSON 解析错误 | 请求体非合法 JSON-RPC |
|
| `-32700` | JSON 解析错误 | 请求体非合法 JSON-RPC |
|
||||||
|
|
||||||
@@ -446,7 +446,7 @@ McpServer().SetTerminalEnabled(THIS_CFG.GetInt("settings", "McpTerminal", 0) !=
|
|||||||
### 10.5 stdout 里出现命令本身 / 哨兵
|
### 10.5 stdout 里出现命令本身 / 哨兵
|
||||||
|
|
||||||
- 命令本身回显 = ConPTY 输入回显,已由 `StripEchoedCommand` 服务端剔除(§2.4)。若仍出现,检查是否该行因编码(非 PTY 老管道的 GBK)与 `echoedLine` 字节不一致而 `find` 不到——老管道本应无回显。
|
- 命令本身回显 = ConPTY 输入回显,已由 `StripEchoedCommand` 服务端剔除(§2.4)。若仍出现,检查是否该行因编码(非 PTY 老管道的 GBK)与 `echoedLine` 字节不一致而 `find` 不到——老管道本应无回显。
|
||||||
- 哨兵 `__MCP_DONE_...` 出现 = 哨兵截断/清洗异常,通常意味着命令含 `&|` 破坏了控制操作符链(持久终端会提前 `-32008` 拒绝,一次性会 `-32008` 拒绝五元字符)。
|
- 哨兵 `__MCP_DONE_...` 出现 = 哨兵截断/清洗异常,通常意味着命令含 `&|` 破坏了控制操作符链(持久终端会提前 `-32012` 拒绝,一次性会 `-32012` 拒绝五元字符)。
|
||||||
|
|
||||||
### 10.6 中文/乱码
|
### 10.6 中文/乱码
|
||||||
|
|
||||||
|
|||||||
@@ -490,6 +490,10 @@ static std::string BuildChatWait(const Json::Value& id, const Json::Value& args,
|
|||||||
case CMcpServer::ChatWaitResult::Busy:
|
case CMcpServer::ChatWaitResult::Busy:
|
||||||
return BuildError(id, kErrBusy,
|
return BuildError(id, kErrBusy,
|
||||||
"Another chat_wait is already pending for this session");
|
"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::Closed:
|
||||||
case CMcpServer::ChatWaitResult::Timeout:
|
case CMcpServer::ChatWaitResult::Timeout:
|
||||||
case CMcpServer::ChatWaitResult::Ok:
|
case CMcpServer::ChatWaitResult::Ok:
|
||||||
@@ -867,10 +871,14 @@ CMcpServer::ChatReadyResult CMcpServer::WaitChatReady(uint64_t device_id,
|
|||||||
if (s->closed) return ChatReadyResult::Closed;
|
if (s->closed) return ChatReadyResult::Closed;
|
||||||
if (s->started && now >= s->readyAt) return ChatReadyResult::Ok;
|
if (s->started && now >= s->readyAt) return ChatReadyResult::Ok;
|
||||||
if (now >= deadline) return ChatReadyResult::Timeout;
|
if (now >= deadline) return ChatReadyResult::Timeout;
|
||||||
|
if (McpCallCancelled()) return ChatReadyResult::Timeout; // P11:取消按超时收尾
|
||||||
|
|
||||||
// 绑定通知到达后只需等到 readyAt,不要一直睡到整个 open 超时。
|
// 绑定通知到达后只需等到 readyAt,不要一直睡到整个 open 超时。
|
||||||
steady_clock::time_point wake = deadline;
|
steady_clock::time_point wake = deadline;
|
||||||
if (s->started && s->readyAt < wake) wake = s->readyAt;
|
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);
|
m_ChatCv.wait_until(lk, wake);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -923,7 +931,11 @@ CMcpServer::ChatWaitResult CMcpServer::WaitChatMessages(
|
|||||||
|
|
||||||
while (s->inbox.empty() && !s->closed) {
|
while (s->inbox.empty() && !s->closed) {
|
||||||
if (timeoutMs <= 0 || steady_clock::now() >= deadline) break;
|
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) {
|
while (!s->inbox.empty() && out.size() < maxMessages) {
|
||||||
@@ -939,6 +951,8 @@ CMcpServer::ChatWaitResult CMcpServer::WaitChatMessages(
|
|||||||
s->waitBusy = false;
|
s->waitBusy = false;
|
||||||
if (!s->closed) s->lastActiveAt = time(nullptr);
|
if (!s->closed) s->lastActiveAt = time(nullptr);
|
||||||
|
|
||||||
|
// 取消优先于「等到超时」:没有消息且是被取消唤醒的,如实回报(会话本身不受影响)。
|
||||||
|
if (out.empty() && McpCallCancelled() && !closed) return ChatWaitResult::Cancelled;
|
||||||
return timedOut ? ChatWaitResult::Timeout : ChatWaitResult::Ok;
|
return timedOut ? ChatWaitResult::Timeout : ChatWaitResult::Ok;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -383,6 +383,10 @@ const ToolHints kToolHints[] = {
|
|||||||
{ "get_activity_history", true, false, true, true },
|
{ "get_activity_history", true, false, true, true },
|
||||||
{ "get_audit_log", true, false, true, false },
|
{ "get_audit_log", true, false, true, false },
|
||||||
{ "get_server_status", 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_processes", true, false, true, true },
|
||||||
{ "list_windows", true, false, true, true },
|
{ "list_windows", true, false, true, true },
|
||||||
|
|||||||
@@ -20,6 +20,18 @@ class context;
|
|||||||
|
|
||||||
namespace McpInternal {
|
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 字符串
|
// Json::Value → 紧凑 JSON 字符串
|
||||||
std::string JsonToString(const Json::Value& v);
|
std::string JsonToString(const Json::Value& v);
|
||||||
|
|
||||||
|
|||||||
@@ -260,6 +260,11 @@ Json::Value ActionOutputSchema() {
|
|||||||
props["state"] = PropStr(u8"复核时观测到的状态");
|
props["state"] = PropStr(u8"复核时观测到的状态");
|
||||||
props["reason"] = PropStr(u8"ok=false 时的原因");
|
props["reason"] = PropStr(u8"ok=false 时的原因");
|
||||||
props["message"] = PropStr(u8"人类可读的说明");
|
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);
|
Json::Value schema(Json::objectValue);
|
||||||
schema["type"] = "object";
|
schema["type"] = "object";
|
||||||
schema["properties"] = props;
|
schema["properties"] = props;
|
||||||
@@ -303,6 +308,24 @@ std::string BuildListResult(const Json::Value& id, const char* arrayKey,
|
|||||||
return BuildStructuredResult(id, sc, text);
|
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,
|
std::string BuildActionResult(const Json::Value& id, bool ok, bool verified, bool changed,
|
||||||
const std::string& action, const std::string& target,
|
const std::string& action, const std::string& target,
|
||||||
const std::string& state, const std::string& reason,
|
const std::string& state, const std::string& reason,
|
||||||
@@ -860,7 +883,7 @@ public:
|
|||||||
: mcp.BeginMachineSession(m_dev, tool, ht.mainCtx);
|
: mcp.BeginMachineSession(m_dev, tool, ht.mainCtx);
|
||||||
if (!began) {
|
if (!began) {
|
||||||
errJson = BuildError(id, kErrBusy,
|
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;
|
return false;
|
||||||
}
|
}
|
||||||
m_open = true;
|
m_open = true;
|
||||||
@@ -1042,8 +1065,13 @@ CMcpServer::KeylogWaitResult CMcpServer::WaitKeylogData(uint64_t device_id, std:
|
|||||||
if (r.closed) return KeylogWaitResult::Closed;
|
if (r.closed) return KeylogWaitResult::Closed;
|
||||||
|
|
||||||
if (deadline > r.deadline) deadline = r.deadline;
|
if (deadline > r.deadline) deadline = r.deadline;
|
||||||
if (std::chrono::steady_clock::now() >= deadline) return KeylogWaitResult::Timeout;
|
const auto now = std::chrono::steady_clock::now();
|
||||||
m_PendingCv.wait_until(lk, deadline);
|
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;
|
if (waitUntil > r.deadline) waitUntil = r.deadline;
|
||||||
auto now = std::chrono::steady_clock::now();
|
auto now = std::chrono::steady_clock::now();
|
||||||
if (now >= waitUntil) return ManagedWaitResult::Timeout;
|
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() + ")");
|
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<BYTE> pkt(5);
|
std::vector<BYTE> pkt(5);
|
||||||
pkt[0] = (action == "freeze") ? (BYTE)COMMAND_PROCESS_FREEZING
|
pkt[0] = (action == "freeze") ? (BYTE)COMMAND_PROCESS_FREEZING
|
||||||
: (BYTE)COMMAND_PROCESS_THAW;
|
: (BYTE)COMMAND_PROCESS_THAW;
|
||||||
@@ -2209,12 +2250,21 @@ static std::string BuildHostControlWindow(const Json::Value& id, const Json::Val
|
|||||||
Json::Value pre;
|
Json::Value pre;
|
||||||
std::string perr;
|
std::string perr;
|
||||||
if (!ParseWindows(data, 936, pre, perr)) return ParseErrorToJson(id, "window list", 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",
|
AuditManageAction(parent, ht.dev, "host_control_window",
|
||||||
action + " hwnd=" + std::to_string(hwnd) + " result=not_found");
|
action + " hwnd=" + std::to_string(hwnd) + " result=not_found");
|
||||||
return NotFoundJson(id, "window hwnd=" + std::to_string(hwnd));
|
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 字节)
|
// [11][hwnd][SW_*] + 零填充到 20 字节(与 MFC 下发格式一致;客户端只读前 9 字节)
|
||||||
std::vector<BYTE> pkt(20, 0);
|
std::vector<BYTE> pkt(20, 0);
|
||||||
pkt[0] = (BYTE)COMMAND_WINDOW_OPERATE;
|
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();
|
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 报成成功。
|
// 客户端只在状态满足时才真正动作:先按同样的规则判断,避免把 no-op 报成成功。
|
||||||
auto stateIs = [](const std::string& s, const char* want) { return EqualsCI(s, want); };
|
auto stateIs = [](const std::string& s, const char* want) { return EqualsCI(s, want); };
|
||||||
if (action == "start" && stateIs(initial, "Running")) {
|
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();
|
std::string folder = hits[0]->get("folder", Json::Value("\\")).asString();
|
||||||
if (folder.empty()) folder = "\\";
|
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;
|
std::string ansiFolder, ansiName;
|
||||||
if (!Utf8ToCpExact(folder, 936, ansiFolder) || !Utf8ToCpExact(taskName, 936, ansiName)) {
|
if (!Utf8ToCpExact(folder, 936, ansiFolder) || !Utf8ToCpExact(taskName, 936, ansiName)) {
|
||||||
return BuildError(id, -32602,
|
return BuildError(id, -32602,
|
||||||
@@ -2837,8 +2905,9 @@ void AppendTools(Json::Value& tools) {
|
|||||||
props["action"] = PropStrEnum(u8"freeze=挂起进程,thaw=恢复进程", { "freeze", "thaw" });
|
props["action"] = PropStrEnum(u8"freeze=挂起进程,thaw=恢复进程", { "freeze", "thaw" });
|
||||||
props["pid"] = PropInt(u8"目标进程 PID");
|
props["pid"] = PropInt(u8"目标进程 PID");
|
||||||
props["name"] = PropStr(u8"可选:校验进程名,防止 PID 被系统复用后误操作");
|
props["name"] = PropStr(u8"可选:校验进程名,防止 PID 被系统复用后误操作");
|
||||||
|
props["dry_run"] = PropBool(u8"true 时只校验 PID/名称存在并返回目标进程,不冻结/解冻,默认 false");
|
||||||
AddTool(tools, "host_control_process",
|
AddTool(tools, "host_control_process",
|
||||||
u8"挂起或恢复在线 Windows 主机上的一个进程(对应主机管理「进程」右键的冻结/解冻)。可能导致目标进程超时或崩溃,故归入危险操作:需要同时开启 McpMachineDangerous。动作没有回执,客户端也不回报结果;工具会在动作后重新拉取进程列表确认目标仍存在。",
|
u8"挂起或恢复在线 Windows 主机上的一个进程(对应主机管理「进程」右键的冻结/解冻)。可能导致目标进程超时或崩溃,故归入危险操作:需要同时开启 McpMachineDangerous。动作没有回执,客户端也不回报结果;工具会在动作后重新拉取进程列表确认目标仍存在。dry_run=true 只核实目标并返回它,不下发动作。",
|
||||||
MakeSchema(props, { "id", "action", "pid" }),
|
MakeSchema(props, { "id", "action", "pid" }),
|
||||||
ActionOutputSchema());
|
ActionOutputSchema());
|
||||||
}
|
}
|
||||||
@@ -2854,8 +2923,9 @@ void AppendTools(Json::Value& tools) {
|
|||||||
hwnd["type"] = types;
|
hwnd["type"] = types;
|
||||||
hwnd["description"] = u8"窗口句柄,取 host_list_windows 的 hwnd;整数或 0x 前缀字符串";
|
hwnd["description"] = u8"窗口句柄,取 host_list_windows 的 hwnd;整数或 0x 前缀字符串";
|
||||||
props["hwnd"] = hwnd;
|
props["hwnd"] = hwnd;
|
||||||
|
props["dry_run"] = PropBool(u8"true 时只校验 hwnd 仍在可见窗口列表里并返回该窗口,不下发操作,默认 false");
|
||||||
AddTool(tools, "host_control_window",
|
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" }),
|
MakeSchema(props, { "id", "action", "hwnd" }),
|
||||||
ActionOutputSchema());
|
ActionOutputSchema());
|
||||||
}
|
}
|
||||||
@@ -2865,8 +2935,9 @@ void AppendTools(Json::Value& tools) {
|
|||||||
props["action"] = PropStrEnum(u8"start/stop/pause/continue/restart",
|
props["action"] = PropStrEnum(u8"start/stop/pause/continue/restart",
|
||||||
{ "start", "stop", "pause", "continue", "restart" });
|
{ "start", "stop", "pause", "continue", "restart" });
|
||||||
props["name"] = PropStr(u8"服务名(ServiceName,不是显示名),取 host_list_*_services 的 name");
|
props["name"] = PropStr(u8"服务名(ServiceName,不是显示名),取 host_list_*_services 的 name");
|
||||||
|
props["dry_run"] = PropBool(u8"true 时只校验服务存在并返回当前状态,不下发控制命令,默认 false");
|
||||||
AddTool(tools, "host_control_service",
|
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" }),
|
MakeSchema(props, { "id", "action", "name" }),
|
||||||
ActionOutputSchema());
|
ActionOutputSchema());
|
||||||
}
|
}
|
||||||
@@ -2876,8 +2947,9 @@ void AppendTools(Json::Value& tools) {
|
|||||||
props["action"] = PropStrEnum(u8"run=立即运行,stop=停止正在运行的任务", { "run", "stop" });
|
props["action"] = PropStrEnum(u8"run=立即运行,stop=停止正在运行的任务", { "run", "stop" });
|
||||||
props["name"] = PropStr(u8"任务名,取 host_list_scheduled_tasks 的 name");
|
props["name"] = PropStr(u8"任务名,取 host_list_scheduled_tasks 的 name");
|
||||||
props["folder"] = PropStr(u8"可选:任务所在文件夹;同名任务存在多个时必填");
|
props["folder"] = PropStr(u8"可选:任务所在文件夹;同名任务存在多个时必填");
|
||||||
|
props["dry_run"] = PropBool(u8"true 时只校验任务存在(含同名歧义检查)并返回当前状态,不下发 run/stop,默认 false");
|
||||||
AddTool(tools, "host_control_task",
|
AddTool(tools, "host_control_task",
|
||||||
u8"运行或停止在线 Windows 主机的计划任务(主机管理「计划任务」右键)。客户端无回执,工具只复核任务仍存在并报告当前状态,不声称任务一定执行成功。不提供创建/删除任务。",
|
u8"运行或停止在线 Windows 主机的计划任务(主机管理「计划任务」右键)。客户端无回执,工具只复核任务仍存在并报告当前状态,不声称任务一定执行成功。不提供创建/删除任务。dry_run=true 只核实任务并返回当前状态。",
|
||||||
MakeSchema(props, { "id", "action", "name" }),
|
MakeSchema(props, { "id", "action", "name" }),
|
||||||
ActionOutputSchema());
|
ActionOutputSchema());
|
||||||
}
|
}
|
||||||
|
|||||||
+1216
-86
File diff suppressed because it is too large.
Load diff
@@ -50,6 +50,55 @@ struct ChatMessage {
|
|||||||
std::string text;
|
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<bool> cancelled{false};
|
||||||
|
|
||||||
|
// 进度通道:hasProgressToken=false 时一切进度调用都是空操作。
|
||||||
|
bool hasProgressToken = false;
|
||||||
|
std::string progressTokenJson; // progressToken 的 JSON 文本(原样回显)
|
||||||
|
std::shared_ptr<McpProgressChannel> 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<McpCallContext> 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 校验。
|
// MCP (Model Context Protocol) 服务端:httplib 封装 + JSON-RPC 2.0 分发 + 静态 token 校验。
|
||||||
// 与 CWebService 平级、互不依赖;默认禁用,经「扩展 → MCP设置」开启后监听
|
// 与 CWebService 平级、互不依赖;默认禁用,经「扩展 → MCP设置」开启后监听
|
||||||
// (默认 127.0.0.1:6544,仅本机回环)。见 docs/Mcp_Design.md。
|
// (默认 127.0.0.1:6544,仅本机回环)。见 docs/Mcp_Design.md。
|
||||||
@@ -531,8 +580,8 @@ public:
|
|||||||
// 工具线程:发送结束(清 sendBusy)。closed 期间发送失败时调用方仍须调用。
|
// 工具线程:发送结束(清 sendBusy)。closed 期间发送失败时调用方仍须调用。
|
||||||
void FinishChatSend(uint64_t device_id, const std::string& sessionId);
|
void FinishChatSend(uint64_t device_id, const std::string& sessionId);
|
||||||
|
|
||||||
// 工具线程:取走最多 maxMessages 条;inbox 为空则等到 deadline / closed。
|
// 工具线程:取走最多 maxMessages 条;inbox 为空则等到 deadline / closed / 取消。
|
||||||
enum class ChatWaitResult { Ok, Timeout, Closed, NotFound, Mismatch, Busy };
|
enum class ChatWaitResult { Ok, Timeout, Closed, NotFound, Mismatch, Busy, Cancelled };
|
||||||
ChatWaitResult WaitChatMessages(uint64_t device_id, const std::string& sessionId,
|
ChatWaitResult WaitChatMessages(uint64_t device_id, const std::string& sessionId,
|
||||||
int timeoutMs, size_t maxMessages,
|
int timeoutMs, size_t maxMessages,
|
||||||
std::vector<ChatMessage>& out, bool& timedOut,
|
std::vector<ChatMessage>& out, bool& timedOut,
|
||||||
@@ -565,6 +614,39 @@ public:
|
|||||||
void GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl,
|
void GetRuntimeCounters(int& pending, int& terminal, int& screenCtrl,
|
||||||
int& fileXfer, int& chat, int& blockedIps);
|
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<McpCallContext> 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<McpCallContext>& 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<SessionSnapshot> ListSessions();
|
||||||
|
|
||||||
|
// -32003 文案后缀:说明该主机正被哪个工具占着、已持续多久;没有占用信息时返回空串。
|
||||||
|
std::string DescribeBusy(uint64_t device_id);
|
||||||
|
|
||||||
private:
|
private:
|
||||||
CMcpServer();
|
CMcpServer();
|
||||||
~CMcpServer();
|
~CMcpServer();
|
||||||
@@ -626,6 +708,8 @@ private:
|
|||||||
struct PendingRequest {
|
struct PendingRequest {
|
||||||
std::string tool;
|
std::string tool;
|
||||||
std::string path; // list_files:目录路径;list_registry:rootToken(1B)+相对子键路径
|
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 = 未设置)
|
uint16_t expectedReqId = 0; // get_screenshot:期望的预览 reqId(0 = 未设置)
|
||||||
std::vector<BYTE> data;
|
std::vector<BYTE> data;
|
||||||
std::vector<BYTE> regPath; // list_registry:TOKEN_REG_PATH 子键包(含 token 字节)
|
std::vector<BYTE> regPath; // list_registry:TOKEN_REG_PATH 子键包(含 token 字节)
|
||||||
@@ -664,6 +748,11 @@ private:
|
|||||||
std::condition_variable m_PendingCv;
|
std::condition_variable m_PendingCv;
|
||||||
std::map<uint64_t, PendingRequest> m_Pending;
|
std::map<uint64_t, PendingRequest> m_Pending;
|
||||||
|
|
||||||
|
// ===== P11:在飞 tools/call 上下文(受 m_CallMutex 保护)=====
|
||||||
|
// 向量足够:同时在飞的调用只有个位数,取消/列举都是全表扫描。
|
||||||
|
std::mutex m_CallMutex;
|
||||||
|
std::vector<std::shared_ptr<McpCallContext>> m_Calls;
|
||||||
|
|
||||||
// ===== P8:子连接路由(受 m_PendingMutex 保护)=====
|
// ===== P8:子连接路由(受 m_PendingMutex 保护)=====
|
||||||
// 已绑定子连接 → device(该子连接的一切包都由 MCP 消费)。
|
// 已绑定子连接 → device(该子连接的一切包都由 MCP 消费)。
|
||||||
std::map<context*, uint64_t> m_SubCtxToDevice;
|
std::map<context*, uint64_t> m_SubCtxToDevice;
|
||||||
@@ -717,6 +806,7 @@ private:
|
|||||||
bool persistent = false;
|
bool persistent = false;
|
||||||
bool busy = false; // 一条命令在飞(terminal_exec 复位→WaitTermCommand 返回)
|
bool busy = false; // 一条命令在飞(terminal_exec 复位→WaitTermCommand 返回)
|
||||||
time_t lastActiveAt = 0; // idle 回收用(秒)
|
time_t lastActiveAt = 0; // idle 回收用(秒)
|
||||||
|
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11
|
||||||
};
|
};
|
||||||
std::mutex m_TermMutex;
|
std::mutex m_TermMutex;
|
||||||
std::condition_variable m_TermCv;
|
std::condition_variable m_TermCv;
|
||||||
@@ -740,6 +830,7 @@ private:
|
|||||||
bool busy = false; // 一条注入在飞(BeginScreenCtrlAction→End 之间)
|
bool busy = false; // 一条注入在飞(BeginScreenCtrlAction→End 之间)
|
||||||
bool closed = false; // 注入期间屏幕子连接已断(由注入线程收尾)
|
bool closed = false; // 注入期间屏幕子连接已断(由注入线程收尾)
|
||||||
time_t lastActiveAt = 0; // idle 回收用(秒)
|
time_t lastActiveAt = 0; // idle 回收用(秒)
|
||||||
|
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11
|
||||||
int screenW = 0; // 物理捕获分辨率(来自 TOKEN_BITMAPINFO)
|
int screenW = 0; // 物理捕获分辨率(来自 TOKEN_BITMAPINFO)
|
||||||
int screenH = 0;
|
int screenH = 0;
|
||||||
// P10-C 键鼠锁定:inputBlocked 是服务端认为的锁定状态(唯一真相,用于强制解锁);
|
// P10-C 键鼠锁定:inputBlocked 是服务端认为的锁定状态(唯一真相,用于强制解锁);
|
||||||
@@ -785,6 +876,9 @@ private:
|
|||||||
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
|
std::set<uint32_t> skipIndexes; // overwrite=false 跳过的 fileIndex
|
||||||
std::vector<FileTransferEntry> skipped; // 跳过的文件(供输出)
|
std::vector<FileTransferEntry> skipped; // 跳过的文件(供输出)
|
||||||
time_t startAt = 0;
|
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)。
|
// 旧实现只能干等满 timeout_ms(默认 600s,整台主机被单飞互斥锁住,评审 P2)。
|
||||||
std::chrono::steady_clock::time_point lastDataAt;
|
std::chrono::steady_clock::time_point lastDataAt;
|
||||||
@@ -810,6 +904,7 @@ private:
|
|||||||
bool waitBusy = false; // 同一会话只允许一个 chat_wait
|
bool waitBusy = false; // 同一会话只允许一个 chat_wait
|
||||||
std::chrono::steady_clock::time_point readyAt; // 建窗等待期满(绑定 + 1000ms)
|
std::chrono::steady_clock::time_point readyAt; // 建窗等待期满(绑定 + 1000ms)
|
||||||
time_t lastActiveAt = 0;
|
time_t lastActiveAt = 0;
|
||||||
|
std::chrono::steady_clock::time_point startedAt = std::chrono::steady_clock::now(); // P11
|
||||||
std::deque<ChatMessage> inbox; // 未投递消息(UTF-8)
|
std::deque<ChatMessage> inbox; // 未投递消息(UTF-8)
|
||||||
size_t inboxBytes = 0;
|
size_t inboxBytes = 0;
|
||||||
uint64_t nextMsgId = 1;
|
uint64_t nextMsgId = 1;
|
||||||
|
|||||||
@@ -9,6 +9,14 @@
|
|||||||
它在那个目录下建一个 mcp_smoke_xxxx 沙箱,走完 create/upload/rename/delete
|
它在那个目录下建一个 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 = '<token>' # 与 service 的 McpToken 一致
|
$env:YAMA_MCP_TOKEN = '<token>' # 与 service 的 McpToken 一致
|
||||||
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1
|
powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1
|
||||||
@@ -44,6 +52,9 @@ param(
|
|||||||
)
|
)
|
||||||
|
|
||||||
$ErrorActionPreference = 'Stop'
|
$ErrorActionPreference = 'Stop'
|
||||||
|
# Start-RpcAsync 用 HttpClient 发并发请求;Windows PowerShell 5.1 默认没加载这个程序集,
|
||||||
|
# 而类型字面量在执行该语句时就要能解析,所以放在脚本开头加载。
|
||||||
|
try { Add-Type -AssemblyName System.Net.Http -ErrorAction Stop } catch { }
|
||||||
$script:pass = 0
|
$script:pass = 0
|
||||||
$script:fail = 0
|
$script:fail = 0
|
||||||
$script:failures = @()
|
$script:failures = @()
|
||||||
@@ -97,6 +108,58 @@ function HasPaging($obj) {
|
|||||||
return $true
|
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 文本块,
|
# 结果外露(docs/Mcp_Design.md §14):content 末尾必须有一个可解析的 JSON 文本块,
|
||||||
# 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。
|
# 内容与 structuredContent 对应。只读 content 的客户端(WorkBuddy)靠它拿到 id。
|
||||||
function HasJsonText($rpc) {
|
function HasJsonText($rpc) {
|
||||||
@@ -147,6 +210,12 @@ $ro = @($tools | Where-Object { $_.annotations.readOnlyHint -eq $true })
|
|||||||
Check '存在只读工具且无只读工具被标为破坏性' ($ro.Count -gt 0 -and
|
Check '存在只读工具且无只读工具被标为破坏性' ($ro.Count -gt 0 -and
|
||||||
(@($ro | Where-Object { $_.annotations.destructiveHint -eq $true }).Count -eq 0)) ("readOnly=" + $ro.Count)
|
(@($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. 协议层错误码 =====
|
# ===== 2b. 协议层错误码 =====
|
||||||
Write-Host "`n[2b] 协议层错误码"
|
Write-Host "`n[2b] 协议层错误码"
|
||||||
$um = Rpc 'bogus/method' @{} $null $null
|
$um = Rpc 'bogus/method' @{} $null $null
|
||||||
@@ -271,6 +340,14 @@ if (-not $SkipHost) {
|
|||||||
($byPid.error -eq $null -and [int]$bp.total -ge 1 -and
|
($byPid.error -eq $null -and [int]$bp.total -ge 1 -and
|
||||||
@($bp.processes | Where-Object { [int]$_.pid -ne $ppid }).Count -eq 0) `
|
@($bp.processes | Where-Object { [int]$_.pid -ne $ppid }).Count -eq 0) `
|
||||||
("pid=" + $ppid + " total=" + $bp.total)
|
("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 }
|
$wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 }
|
||||||
@@ -567,6 +644,261 @@ if ($offGate) {
|
|||||||
Write-Host " 所有功能开关都开着,跳过 -32006 检查(关掉任一开关再跑一次可覆盖)。" -ForegroundColor Yellow
|
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' })
|
Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' })
|
||||||
if ($script:fail -gt 0) {
|
if ($script:fail -gt 0) {
|
||||||
|
|||||||
Reference in new issue
Block a user