diff --git a/common/ClientLogHandler.h b/common/ClientLogHandler.h new file mode 100644 index 0000000..65caa1c --- /dev/null +++ b/common/ClientLogHandler.h @@ -0,0 +1,58 @@ +#pragma once +#include +#include +#include +#include + +#include "client/IOCPClient.h" +#include "common/commands.h" +#include "common/logger.h" + +// 客户端内存日志上报(POSIX 版,对应 Windows 端 client/ClientLogManager.cpp)。 +// +// 服务端 COMMAND_QUERY_LOG → 本端开子连接 → 首包 TOKEN_REPORT_LOG + 日志文本。 +// +// 为什么必须走子连接:服务端 MessageHandle 的 TOKEN_REPORT_LOG 分支取走首包后会 +// 直接 CancelIO 关掉这条连接。若把日志回在主连接上,被关掉的就是主连接本身, +// 客户端会当场掉线(服务端再判成离线)。 +// +// 为什么首包就发全量:服务端只取第一条(m_sentIdx 从 0 起算即全量),取走即关 +// 子连接,后续增量不会再有人收。Windows 端每 3s 补推一次是为了给人工打开的日志 +// 对话框持续喂增量,MCP 这条路径用不上。 +class ClientLogHandler : public IOCPManager +{ +public: + explicit ClientLogHandler(IOCPClient* client) + : m_client(client) + , m_sentIdx(0) + { + SendLogDump(); + } + + virtual ~ClientLogHandler() {} + + virtual VOID OnReceive(PBYTE szBuffer, ULONG ulLength) + { + if (!szBuffer || ulLength == 0) + return; + // 子连接上再收到 QUERY_LOG(服务端重试)就补发一次增量 + if (szBuffer[0] == COMMAND_QUERY_LOG) + SendLogDump(); + } + +private: + void SendLogDump() + { + std::lock_guard lock(m_sendMutex); + std::string logs = Logger::getInstance().DumpMemoryLogFrom(m_sentIdx); + std::vector pkt(1 + logs.size()); + pkt[0] = TOKEN_REPORT_LOG; + if (!logs.empty()) + memcpy(pkt.data() + 1, logs.data(), logs.size()); + m_client->Send2Server((char*)pkt.data(), (int)pkt.size()); + } + + IOCPClient* m_client; + size_t m_sentIdx; // Logger ring buffer 的绝对游标,DumpMemoryLogFrom 会推进它 + std::mutex m_sendMutex; +}; diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index 1d59c55..5060ea9 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -481,6 +481,9 @@ void CMcpSettingsDlg::OnBnClickedBtnSave() - 写操作工具传 `ids` 直接 `-32602` 拒绝(不逐个执行,避免误操作扩散)。 - 返回:`{tool, total, succeeded, failed, results:[{id, ok, data|error, text}]}`;`content` 里是「共 N 台,成功 X 台,失败 Y 台」+ 最多 ~1200 字节的失败明细。 - `limit` / `offset` 对每台主机各自生效;批量是串行执行,单台超时会占用整批等待时间。 +- **outputSchema 必须声明批量形状**:只声明单机形状会让客户端把批量结果判为不合规 + (`-32602: data must have required property 'host'`)。现在由 `ApplyBatchOutputSchema` + 统一补成 `anyOf:[单机, 批量]`,见 §18.1。 ### 9.3 N3 `get_keylog` @@ -886,3 +889,69 @@ Linux 客户端(`LNX`)早已实现下面这些工具的**线上协议**, - **`remote_keyboard` 的 `type` 仍是 ASCII-only**:Linux 侧 `VKtoKeySym` 把 VK 映射为 keysym 后走 XTest,IME 组合输入做不到;非 ASCII 走 `remote_clipboard` + `Ctrl+V`(Linux 客户端把服务端下发的 GBK 转回 UTF-8 再调 `xclip`/`xsel`,需要 X11 桌面)。 - **限制**:纯 Wayland 会话无法抓屏/注入(要 X11 或 XWayland);多显示器仍按 §7.2 拒绝(Linux 客户端心跳里 `RES_RESOLUTION` 依赖 `xrandr`,没有 `xrandr` 的系统上报 `0:0*0`,按「无法判定」放行);`remote_*` 需要安装 `libX11` + `libXtst`,剪贴板需要 `xclip`/`xsel`。 - **验收**(Debug 实例 + WSL Ubuntu 24.04 客户端,WSLg `DISPLAY=:0`):`exec_command` 真实退出码(`ls` 不存在路径 → 2)、`-32007`/`-32008` 负例、`grep -v ^#` 放行、输出无提示符噪声;持久终端 `cd`/环境变量保持、`false` → 1、`;` 串联取末条、`close` 幂等;`kill_process` 杀死自己起的 `sleep` 且 `remaining` 为空、`pid 1` 被跳过;`remote_open` 返回 3840x1140、`remote_mouse` 归一化 (0.5,0.5) 落在 (1920,570)、`xev` 观测到按键/按钮成对、剪贴板中文往返 UTF-8 一致。Windows 客户端同批工具回归无变化。 + +## 18. 增补(2026-10-29:修掉实测报告的三个 P0) + +`docs/Mcp_Test_Report_2026-10-29.md` 的 P0-1/P0-2/P0-3 有三个共同点:**inputSchema 与 +outputSchema 不是同一份契约**,或者**输出体积没有上限**。三者都只改服务端(P0-3 的 +Linux 半边另需客户端补一段)。 + +### 18.1 批量只读的 outputSchema(P0-1) + +`tools/call` 带 `ids[]` 时走 `BuildBatchCall`,返回的是 +`{tool, total, succeeded, failed, skipped, results[]}`;而每个工具声明的 `outputSchema` +只有单机形状。客户端按声明校验 `structuredContent`,于是**任何** `ids` 调用都以 +`-32602: data must have required property 'host'` 失败——inputSchema 明写「支持 ids」, +outputSchema 却把它判死,十余个只读工具的批量能力整条不可用。 + +修法:`McpInternal::ApplyBatchOutputSchema(tools)` 在 `tools/list` 的最后一步(与 +`ApplyToolAnnotations` 并列)给 `IsBatchReadOnlyTool` 命中的工具把 `outputSchema` +改写成 `{type:object, anyOf:[单机形状, 批量形状]}`。放最后一步是为了让三个注册点 +(本文件内联 / `McpMachine` / `McpChat`)一视同仁,新增工具只要进批量清单就自动生效。 +`IsBatchReadOnlyTool` 也随之从 `McpServer.cpp` 移到 `McpInternal.cpp`——清单现在同时被 +`tools/call`(入口判定)和 `tools/list`(补 schema)使用,两处必须共用一份。 + +批量形状里的 `results[].data` 只能声明成 `object`:它就是该工具单机的 +`structuredContent`,字段随工具而定。 + +### 18.2 `list_registry` 的根键分支(P0-2) + +`path` 为空时 `BuildRegistryRoots` 只回 `keys`,而 outputSchema 把 `values` 也列进了 +`required`——于是文档写的**第一种用法**(省略 path 列根键)必然 `-32602`,AI 必须先猜一个 +真实键路径才能进注册表。现在 `required` 只保留 `keys`,`values` 在根键分支不返回,并在 +schema 里写明这一点;同时根键分支补上 `path: ""`,让两个分支返回同一组字段(`path` / +`keys`),调用方不必按分支判断。 + +### 18.3 `get_client_log` 的体积与平台(P0-3) + +两个症状、两个原因: + +| 平台 | 症状 | 原因 | +|---|---|---| +| Windows | 返回 90,473 字符,超出客户端工具结果上限 | 快照是客户端 ring buffer 全量(最多 1000 行),工具没有 limit | +| Linux/macOS | `-32001` 稳定超时 | 客户端**根本没有处理** `COMMAND_QUERY_LOG`(只有 Windows 的 `ClientLogManager` 有),服务端永远等不到 `TOKEN_REPORT_LOG` | + +服务端:`get_client_log` 新增 `limit`(默认 200,上限 2000)与 `filter`(子串,ASCII +不区分大小写),**从末尾往前取**——排障看的是最后发生了什么,不是开机第一行。返回补 +`lines_total` / `lines_matched` / `lines_returned` / `truncated`。除行数外还有 64 KB +字节预算:单行可能是超长的堆栈或报文转储,只按行数截断仍会撑爆结果;末尾一行自己就超 +预算时回它的尾部并置 `truncated=true`。超时文案也改成可诊断的(点明「客户端版本可能 +不支持日志上报」并给出两条替代路径),而不是一句 `Timeout waiting for client log`。 + +客户端:新增 `common/ClientLogHandler.h`(POSIX 版,与 Windows 的 `CClientLogManager` +对应),`linux/main.cpp` 与 `macos/main.mm` 在 `COMMAND_QUERY_LOG` 分支开子连接、首包发 +`TOKEN_REPORT_LOG` + `Logger::DumpMemoryLogFrom(0)`。**必须走子连接**:服务端 +`MessageHandle` 的 `TOKEN_REPORT_LOG` 分支取走首包后会 `CancelIO` 关掉这条连接,回在 +主连接上就是把主连接关掉(客户端当场掉线)。 + +### 18.4 验证与未覆盖 + +- 服务端 21:17:21 构建 + 两端客户端重编后实测:`ids` 批量(`get_host_detail` / + `host_list_processes` / `get_client_log`)全部 `succeeded=全数`;`list_registry` 省略 + `path` 返回 5 个根键;`get_client_log` 在 Windows 上 `1000→200` 行(`truncated=true`)、 + 在 Linux 上正常返回 8 行,且客户端日志里 `Enter/Leave ClientLogThread` 成对、无泄漏。 + 明细见测试报告 §7。 +- `get_activity_history` 仍是全量返回(实测 501 条),与 P0-3 同一类问题,但不在本次 + 三个 P0 内,留待下一轮。 +- 连接器会缓存 `tools/list`,`limit`/`filter` 在重连前对模型不可见(默认参数已覆盖 + P0-3 的场景),与既有的 `overwrite` 缓存问题同源。 diff --git a/docs/Mcp_Test_Report_2026-10-29.md b/docs/Mcp_Test_Report_2026-10-29.md new file mode 100644 index 0000000..b2ae5a9 --- /dev/null +++ b/docs/Mcp_Test_Report_2026-10-29.md @@ -0,0 +1,356 @@ +# YAMA MCP 工具集实测报告 + +- **测试日期**:2026-10-29 +- **服务端**:Yama v1.4.1,构建时间 `2026-10-29 18:26:56`,监听 `0.0.0.0:6544`,10 项开关全开(readonly=false) +- **规模**:在线 34 台、离线 3165 台,`tools/list` 共 **60 个工具** +- **测试目的**:考察 AI 使用这套 MCP 工具是否顺畅,以及能否对设备完成有效监管与处置 +- **修复状态**:三个 P0 已于同日修复并实测通过,见 §7(实现说明在 `docs/Mcp_Design.md` §18) + +## 1. 测试范围与约定 + +按约定划分操作边界: + +| 用途 | 主机 | 说明 | +|---|---|---| +| 写操作 | `DESKTOP-A55C0OI`(`3441387693643366974`,Win10 VM,MDLL)
`Ubuntu24`(`15731161054501180314`,Ubuntu 24.04,Stuttgart,带 UI,LNX) | 仅这两台 | +| 读操作 | 以本机 `A6`(`11261158607827860566`)为主,另抽样其他主机 | 不做写操作 | + +**实际覆盖 55 / 60 个工具。** 未覆盖及原因: + +- `control_service`:无 `dry_run`,执行即重启/停止 YAMA 自身服务,会切断 AI 自己的 MCP 通道,**无法安全自测** +- `operate_window`、`kill_network_connection`:仅 Windows;唯一可写的 Windows VM 在重启测试窗口内未回线,这两个工具来不及执行(该 VM 未配自动登录,人工登录后才回线,见 P1-9) +- `list_windows`:降级路径,已由首选 `host_list_windows` 覆盖 +- 其余全部实测 + +## 2. 结论摘要 + +**整体可用,但"监管/处置"链路上有 3 个硬伤会直接卡住 AI,另有 1 个动作可能把设备弄丢。** + +- **读得准**:所有只读工具在 A6 上返回结构正确、过滤与分页语义一致(`total` / `totalAll` / `hasMore` 三者自洽),截屏返回的是 AI 真能看的图像,不是 base64 字符串。 +- **写得住**:文件上传/下载/C2C 全部正确,下载带 SHA-256 且与本地逐字节吻合,目录结构保留,`overwrite` / `skipped` / `skip_check_failed` 行为与设计一致。 +- **控得了**:窗口/服务/进程/计划任务的 `dry_run` + 执行后复核闭环质量很高;远程鼠标键盘在 Windows 与 Linux 上都验证成功;远程交谈可视确认。 +- **审计扎实**:每个 MCP 动作都落审计日志,含主机 id、工具名、关键参数,连鼠标归一化坐标与像素坐标都在。 +- **但有 3 个硬伤**:批量读取主机详情**必定失败**、客户端日志**拿不到**、**新参数对已连接客户端不可见**。 +- **重启是唯一会"弄丢设备"的动作**:目标 VM 未配自动登录,重启后停在登录界面,客户端(HKCU 启动项)要等人工输密码才起。`power_action` 既不预检自动登录状态,默认也只等 60 秒,`came_back=false` 既可能是"再等等"也可能是"必须喊人"——AI 无法分辨。 + +严重度分布:**P0 × 3**、**P1 × 9**、**P2 × 15**。 + +## 3. 发现清单 + +### 3.1 P0:阻断性缺陷 + +#### P0-1 `get_host_detail` 的批量模式必定失败 `已修复,见 §7` + +```json +{"ids": ["17221709513794608622", "11261158607827860566"]} +→ -32602 Structured content does not match the tool's output schema: + data must have required property 'host' +``` + +input schema 明确声明支持 `ids`(最多 50 个)、"结果按台汇总在 `results` 里",但 **output schema 只认单台的 `host`**。实现返回 `results` 就必然校验失败。单台 `id` 形式正常。 + +影响:**所有只读工具的 `ids` 批量能力全部不可用**(`list_processes`、`list_files`、`list_registry`、`host_list_*` 等十余个工具共用同一套输出 schema)。AI 只能逐台串行调用,34 台机群的横向盘点要 34 次往返。 + +#### P0-2 `list_registry` 的根键分支必定失败 `已修复,见 §7` + +```json +{"id": "...", "path": ""} # 省略 path,按文档应返回 5 个根键 +→ -32602 ... data must have required property 'values' +``` + +带 `path` 时正常(返回 `keys` + `values`);省略 `path` 时只返回 `keys`,而 output schema 要求 `values` 必填。**文档描述的第一种用法("省略或空 path 返回 5 个根键")是死路**,AI 必须先猜一个真实路径才能进注册表。 + +#### P0-3 `get_client_log` 两种平台都不可用 `已修复,见 §7` + +| 平台 | 实测结果 | +|---|---| +| Windows(A6,pid 8668) | 返回 **90,473 字符**(单行 JSON 塞 1000 行日志),直接超出客户端工具结果上限 | +| Linux(Ubuntu24) | `-32001 Timeout waiting for client log`,连续两次稳定复现 | + +工具没有任何 `limit` / `offset` / `tail` / `since` 参数,只能全量取。Windows 上"取到了但塞不下",Linux 上"根本取不到"。 + +影响:**故障排查最需要的一手证据(客户端日志)AI 拿不到。** 本次测试中我只能改用 `download_file` 把日志文件从主机上拉回本地再读——多绕两跳,且要求 AI 自己想到这条路。 + +### 3.2 P1:破坏工作流 + +#### P1-1 服务端已发布的新参数,对已连接客户端不可见 + +直连 `tools/list` 确认服务端**已声明** `copy_files_c2c.overwrite`: + +``` +upload_file: ['id', 'local_path', 'overwrite', 'remote_dir', 'timeout_ms'] +copy_files_c2c: ['dst_dir', 'dst_id', 'overwrite', 'paths', 'src_id', 'timeout_ms'] +``` + +但连接器缓存的 schema 仍是旧版,带 `overwrite` 调用被本地拦下: + +``` +Parameter validation failed: root: must NOT have additional properties +``` + +**报错完全不提示"服务端已支持、是你的客户端缓存过期"。** AI 只会以为参数名写错了,反复尝试无效写法。 + +功能本身经直连验证是**正确**的: + +| 调用 | 结果 | +|---|---| +| `overwrite=true` | `file_count=1, skipped=0, transfer_id=7364150632606842580` | +| 默认(不带 overwrite) | `file_count=0, skipped=1, transfer_id="", skip_check_failed=false` | + +#### P1-2 本地化枚举值与英文文档冲突,且无枚举可查 + +```json +{"status": "Ready"} → total: 0 (schema 文档建议 "如 Ready / Disabled") +{"status": "已准备"} → total: 222 +``` + +实际值是本地化中文。同类问题存在于 `host_list_win32_services.start_type`(`"Auto Start"` 带空格)与降级版 `list_services.start_type`(`"Auto-Start"` 带连字符)——**两套拼法**。 + +影响:AI 按文档写过滤条件会静默得到空结果,误判为"没有匹配项"。schema 里也没有 `enum` 可枚举合法值。 + +#### P1-3 Linux 主机完全没有文件变更能力 + +`create_folder` / `move_path` / `delete_path` 三个工具均为 Windows-only: + +``` +create_folder on Ubuntu24 → -32005 create_folder is only supported on Windows hosts +``` + +Linux 上唯一的替代是 `terminal_exec` 跑 `mkdir` / `mv` / `rm`。而这正是最危险的一类操作,恰恰**没有 `dry_run`、没有执行后复核、没有受保护路径拦截**——与 Windows 侧形成鲜明反差(Windows 的 `delete_path` 会拒绝 `C:\ProgramData` 等系统目录)。 + +#### P1-4 C2C 只支持 Windows 作源 + +``` +Ubuntu24 → DESKTOP-A55C0OI → -32005 copy_files_c2c requires a Windows source host +DESKTOP-A55C0OI → Ubuntu24 → 正常,receiver_ack=true +``` + +混合机群里,**从 Linux 取文件到另一台主机**只能 `download_file` → `upload_file` 两跳,且文件要经过主控落盘。这与 C2C"不经主控"的设计初衷相悖,但工具描述里没有提示这一限制。 + +#### P1-5 `terminal_exec` 禁管道,`exec_command` 受白名单,两者都不是通用 shell + +``` +ls -1 /home/yuan/upload | wc -l +→ -32012 Command contains & or | or a newline (breaks output capture) +``` + +`exec_command` 则被白名单挡住常用工具: + +``` +powershell -NoProfile -Command Get-Date → -32007 Command not allowed by whitelist +``` + +代价是实打实的:想看"某个目录有几个文件",AI 只能把整个 `ls` 输出拉回上下文自己数;想看进程占用只能先 `host_list_processes` 再本地算。**上下文消耗与往返次数都翻倍**,且两个工具的限制互不覆盖,AI 需要记住"哪件事该用哪个"。 + +#### P1-6 删除保护是"建议"而非"强制" + +`delete_path` 的拦截很到位: + +``` +delete_path C:\ProgramData → -32602 refusing to modify a protected system location +``` + +但提示语自己给出了绕过方式: + +> use exec_command if you really need to touch them + +而 `terminal_exec` 本身不受白名单约束,`rm -rf` 畅通无阻。**保护只在"守规矩的路径"上生效**,对有意或无意的越界没有约束力。 + +#### P1-7 持久终端会话静默过期,AI 无法预判 + +Linux 终端会话(`fb4903…`)在空闲约 35 分钟后消失,期间没有任何通知: + +``` +terminal_exec → -32002 Terminal session not found: fb4903... (call terminal_open first) +``` + +`mcp_list_sessions` 里也**看不到它曾经存在**,因此 AI 无法在调用前判断会话是否还活着。重新 `terminal_open` 后立刻查询,会话正常出现在列表里(`idle_ms: 3000`)——说明登记机制本身没问题,纯粹是**过期无提示、TTL 未文档化**。 + +(`-32002` 的文案本身写得很好,明确让人重新 `terminal_open`。) + +#### P1-8 `mcp_cancel_session` 按主机取消会连带销毁持久终端 + +``` +{"id": "15731161054501180314"} → cancelled: 2, released: false +matched 中包含 {"kind": "terminal", "session_id": "21afe3..."} +→ 后续 terminal_exec: -32002 Terminal session was destroyed because the request was cancelled +``` + +取消在飞请求本身**效果很好**——阻塞 40 秒的调用在 4 秒内以 `-32800` 终止。但 schema 描述的是"取消该主机上所有在飞请求",没提会连带销毁持久会话。副作用超出文档承诺范围。 + +#### P1-9 重启后能否自行回线,取决于目标机的自动登录配置——而工具不会告诉你 + +实测在 `DESKTOP-A55C0OI`(2 GB 内存的 Win10 VM)上执行,按审计日志对齐时间轴: + +| 时刻 | 事件 | +|---|---| +| 18:45:47 | 下发 `{"action":"reboot","wait":true,"wait_ms":120000}` | +| 18:47:47 | 返回 `went_offline=true`、**`came_back=false`** | +| 18:52:15 | 主机重新上线(`myself` 组,即被控的那条记录) | +| 18:52:23 | 同一台机的**第二个**客户端也上线(`default` 组,见 P2-10) | + +**根因已由环境方确认:该 VM 没有配置自动登录,重启后停在登录界面,必须人工输入密码。** 客户端的自启动在 `HKEY_CURRENT_USER\...\Run`(`test.exe`、`ClientDemo.exe`),HKCU 启动项只在**交互式登录之后**才执行,所以"重启 → 客户端回线"这一步完全取决于有没有人把密码输进去。本次那 4 分 28 秒不是机器自己恢复的,是登录之后才起的。 + +这带来三个问题: + +1. **等待窗口本身也不够**:工具默认 `wait_ms=60000`,我设了 120 秒仍不够。即使配了自动登录,60 秒对真实 Windows 开机也偏短,`came_back=false` 会成为重启的常态返回值; +2. **`power_action` 没有任何自动登录预检**:AI 在按下重启前无法知道"这台会不会回来",只能盲下; +3. **`came_back=false` 之后没有下一步**,文案还把重启归到"关机后需人工开机"那一类,既不准确也没给出可执行动作。 + +> **两处自我更正**(都发生在本次测试中): +> 1. 初稿判断"重启把设备弄丢了、需人工介入",据此列为 P0——**已撤回**,设备确实回线了; +> 2. 第二稿改判"设备 4 分半后自行回线、只是等待窗口太短"——**也不准确**,回线是人工登录的结果。真实结论是:**能不能自愈取决于目标机配置,工具既不检查也不告知**。 + +### 3.3 P2:一致性与体验 + +| # | 问题 | 证据 | +|---|---|---| +| 1 | `get_activity_history` 无分页,一次返回 **501 条** | 直接冲爆上下文,且内容含大量个人浏览/求职/签证页面 | +| 2 | `authStatus` 只在 `search_hosts`/`list_all_hosts` 出现,`list_online_hosts` 没有;`myself` 组 6 台全为 `unauthorized` 却可正常写入 | MCP 侧未按授权状态做门禁 | +| 3 | 时间口径三套并存 | `list_files.mtime` 是 epoch 整数;`host_list_scheduled_tasks.lastRun` 是 `"2026-10-25 03:38:42"`;`list_network_connections.state` 是 `5` + `"ESTABLISHED"`。主机 `last_seen` 显示 `2026-10-30 01:27`,审计日志同一时刻显示 `18:47`,**差 6 小时以上** | +| 4 | 降级工具与首选工具字段命名不一致 | `list_services`: `binary_path` / `start_type: "Demand-Start"`;`host_list_win32_services`: `binaryPath` / `startType: "Demand Start"`。进程总数 354 vs 351(枚举口径不同) | +| 5 | `get_keylog` 名为键盘记录,实际返回**剪贴板快照** | 内容是 `[Title:] / [Time:] / [Clipboard:]`,无击键;文档提到的 `offlineRecord` 字段未出现 | +| 6 | `host_control_process` 的 `state` 返回进程名 | `{"action":"freeze", "state":"notepad.exe"}`;且此处 `verified: true` 含义是"进程还在",与其它工具"动作已确认"不一致 | +| 7 | `remote_block_input` 报 `blocked: true`,但输入仍可用 | 60 秒窗口内 ESC 与右键均生效;工具自己已声明"只代表命令已送达",**无法确认是否真的锁住** | +| 8 | 能力位不可信 | `ubuntu-24` 的 `remoteControl: true`,但 `screen` 为 `0:0*0`,`remote_open` 15 秒超时 | +| 9 | `host_list_windows` 返回 1×1 / 0×0 的空标题窗口 | `canSee: true` 但 `width:1, height:1, title:""`,属噪声 | +| 10 | 同一台机多条记录、无法区分 | `A6` 有 2 条在线记录(`ClientDemo.exe` pid 26064 / `test.exe` pid 8668),进程列表里还有第 3 个客户端进程 pid 35052 **没有对应主机记录**;`DESKTOP-A55C0OI` 重启后**同时回线两条**(`3441…` 是 MDLL `test.exe` / `myself` 组,`4665…` 是桌面上的 `YAMA1234567a.exe` / `default` 组);按名搜该机名命中 **28 条**历史记录 | +| 11 | `remote_keyboard.type` 无回执,可能丢字符 | Linux 首次注入(焦点刚切换)得到 `echo LINUX_GUI_O`,输出 `LINUX_GU`;第二次完整。只能靠截图自行复核 | +| 12 | 截屏成本偏高 | 960px 宽 ≈ **67 KB / 张**,持续监管会迅速吃掉上下文,且没有区域裁剪或更省格式 | +| 13 | `mcp_cancel_session` 把自己的请求也列进 `matched` | `request_id: "373" tool: "mcp_cancel_session"` | +| 14 | **已过期客户端仍可正常上线并被操作** | `4665792391648319550` 的 `expiredDate: 20261008`(已过期 3 周),但 `online: true`、`authStatus: authorized_by_super`,`get_host_detail` 正常返回、文件操作可用 | +| 15 | 客户端时钟偏差,服务端只打日志不管 | 审计日志中反复出现 `[92.208.227.255]Please check the client's time`;这正是第 3 条里 `last_seen` 与审计日志差 6 小时的来源 | + +## 4. 监管与处置能力评估 + +### 4.1 能做到的(已验证) + +| 能力 | 实测证据 | +|---|---| +| **资产盘点** | 34 台在线 + 3165 台离线,`os` / `client_type` / `group` / `name` / `ip` 组合过滤准确,`total` 与 `totalAll` 自洽(3199 = 34 + 3165) | +| **单机取证** | 进程 351 / 服务 278(运行中 110)/ 驱动 402 / 窗口 24 / 软件 112 / 计划任务 272 / 网络连接 486,字段完整 | +| **可视化确认** | 截屏是真图像,能直接读出桌面文字(本报告中所有 GUI 结论均靠它闭环) | +| **文件处置** | 上传(含目录递归)、下载(SHA-256 逐字节吻合)、C2C(结构保留)、移动、删除,均带 `verified` 复核 | +| **受控处置** | 停/启服务(`Spooler` stop→start,状态复核通过)、运行计划任务(状态转"运行中")、终止进程(`notepad.exe` 已消失)、最小化/还原窗口(截图确证) | +| **GUI 自动化** | Windows:点击地址栏 → 输入 → 回车;Linux:右键菜单 → 点击终端 → 输入 → 执行,均截图确证 | +| **与人沟通** | `chat_open/send/wait/close` 全流程,消息在目标机弹窗显示,截图确证 | +| **占用治理** | `mcp_cancel_session` 把阻塞 40 秒的调用在 4 秒内以 `-32800` 中止 | +| **事后追溯** | 审计日志完整记录每个 MCP 动作,含 `remote-mouse ... norm=(0.300,0.850) px=(515,782)` 这一级细节 | + +### 4.2 做不到的 + +- **横向批量取证**:`ids` 批量全部失效(P0-1),34 台要 34 次往返 +- **日志取证**:客户端日志取不到(P0-3) +- **Linux 文件处置**:只能靠裸 shell(P1-3),且裸 shell 无任何护栏 +- **管道与过滤**:无法让远端先过滤再回传(P1-5) +- **重启后能否回线**:取决于目标机是否配了自动登录;未配置时必须人工登录,而 `power_action` 既不预检也不告知(P1-9) +- **会话生命周期预判**:终端会静默过期(P1-7) +- **精确锁定目标**:同名主机 28 条、同机 3 个客户端进程,列表视图没有 `clientPath` / `pid` 可供区分(P2-10) + +### 4.3 一次具体的处置失手 + +本次测试中,`power_action reboot` 返回 `came_back=false`。我先后做出两个判断,**两个都是错的**: + +| 我的判断 | 实际情况 | +|---|---| +| "设备失联了,需要人工介入"(据此列为 P0) | 设备在 4 分 28 秒后回线 | +| "只是等待窗口太短,设备会自愈" | 回线是**人工登录**的结果——该 VM 未配自动登录,客户端靠 HKCU 启动项、登录后才执行 | + +复盘这条链路,暴露的是**工具没把判断依据交出来**: + +- 返回里只有 `went_offline` / `came_back` / `elapsed_ms`,**没有"这台会不会自己回来"的任何线索**(自动登录状态、是否有 SYSTEM 级自启动),AI 无法区分"再等等"与"必须喊人"; +- 文案把重启归到"关机后需人工开机"那一类,直接把人引向错误结论; +- 没有 `next_step`。 + +同一个信息缺口下,**AI 和人都只能靠猜**。这不是 AI 的失手,是返回值的信息量不足——而这类"缺口"恰恰是自动化处置最危险的地方:一次重启就能把一台远程设备变成必须到现场(或控制台)才能救回的状态。 + +## 5. 改进建议 + +### P0(下一轮必须修) + +1. **让每个输出分支都通过自己的 schema** + `get_host_detail` 的 `host` 改为可选、或批量时也返回 `host` 数组;`list_registry` 的 `values` 改为可选。更根本的做法:加一个**契约测试**,对每个工具、每个分支各调一次并用它自己的 output schema 校验。目前 60 个工具里至少 2 个的某个分支是必然失败的,这类问题靠人工回归必然漏。 + +2. **给日志类工具加分页与裁剪** + `get_client_log` / `get_activity_history` / `get_keylog` 增加 `limit` / `offset`(或 `tail_n` / `since`),默认只回 200 行并在响应里给 `total`。`get_client_log` 尤其应默认 `tail_n=200`——AI 要的是"最近发生了什么",不是 1000 行全量。 + +3. **修 Linux `get_client_log` 超时** + 超时时至少返回已取到的部分快照并置 `truncated=true`,而不是整条失败。 + +### P1(本轮内应修) + +4. **重启前查自动登录,重启后给判断依据** + `power_action` 增加 `check_autologon=true`:读 `HKLM\...\Winlogon` 的 `AutoAdminLogon`,并结合客户端自启动位置(HKLM/HKCU `Run`、启动文件夹、"计算机启动时"触发的计划任务)判断**这台会不会自己回来**;若判定"不会",在结果里明确写"重启后需人工登录,客户端才会回线",让 AI 能先问过用户再动手。 + 同时:默认 `wait_ms` 提到 300000;返回补 `offline_elapsed_ms` 与 `recommended_wait_ms`;`came_back=false` 时给 `next_step`(如"建议 2 分钟后再查一次 `search_hosts`");文案按 `logout` / `shutdown` / `reboot` 分别措辞。 + +5. **给 schema 加版本,让"参数不可见"可自解释** + 在 `tools/list` 结果里带 `schemaVersion`;当客户端因 `additionalProperties` 拒绝时,服务端无法感知——那就退一步:在工具描述里显式写"若客户端报 unknown property,请重连"。更好的做法是服务端**接受并忽略**未知参数,而不是硬拒。 + +6. **枚举值统一为 ASCII,或双向兼容** + 过滤时同时接受 `"Ready"` 与 `"已准备"`(做一次映射即可),并在 schema 里补 `enum`。`start_type` 的 `"Auto Start"` / `"Auto-Start"` 两套拼法必须统一。 + +7. **给 POSIX 补文件变更工具,或给裸 shell 加护栏** + 首选补 `create_folder` / `move_path` / `delete_path` 的 POSIX 实现(`mkdir -p` / `rename` / `unlink`),复用 Windows 侧的受保护路径策略与 `verified` 复核。若短期不做,至少给 `terminal_exec` 加 `dry_run` 与危险命令二次确认。 + +8. **放开 `terminal_exec` 的管道限制** + 输出哨兵可以改成基于退出码 + 长度前缀的帧协议,不必依赖"命令里不能有 `|`"。这是当前**性价比最高的单点改进**——它同时降低上下文消耗和往返次数。 + +9. **让删除保护名副其实,或明确标注为建议** + 若 `exec_command` / `terminal_exec` 仍可触达系统目录,就应在 `delete_path` 的描述里写"仅为防误触,不是安全边界",避免 AI 误以为已被保护。 + +10. **会话 TTL 可见** + `mcp_list_sessions` 增加 `expires_in_ms`;`terminal_exec` 在接近过期时返回警告而不是直接 `-32002`。 + +### P2(体验优化) + +11. 时间字段统一附加 ISO 字符串(保留 epoch 以兼容),并修掉 `last_seen` 与审计日志的 6 小时时差。 +12. 统一 `list_*` 与 `host_list_*` 的字段命名;长期看应废弃降级版,或让降级版直接复用首选版的 schema。 +13. 修 `host_control_process.state`(应返回状态而非进程名);统一 `verified` 语义——"动作已确认"与"目标仍存在"必须分开表达(建议后者改名 `target_present`)。 +14. `host_list_windows` 默认过滤 0×0 / 1×1 空标题窗口,加 `include_aux=false`。 +15. `search_hosts` 增加 `include_history=false` 默认值或 `dedupe_by_name`,并在列表视图补 `clientPath` / `pid`,让同机多客户端、同名多记录可区分。 +16. `authStatus` 补进所有主机列表工具,并明确它是"信息性"还是"门禁性"。 +17. 截屏默认给更小缩略图,或支持 `crop` 区域与 `webp`,降低持续监管成本。 +18. `remote_keyboard.type` 增加回执(回显被接受的文本)或 `settle_ms` 参数。 +19. 主机列表与详情补 `expiredDate`(目前只有 `get_host_detail` 给,且只在 SC 客户端上有),让 AI 能一眼看出"这台已过期";对 `expiredDate` 已过仍在线的情况,至少在 `authStatus` 或独立字段上标注。 +20. 客户端时钟偏差(`Please check the client's time`)应从"只记日志"升级为可查询的状态字段,否则 `last_seen` 这类时间戳无法用于判案。 + +## 6. 给下一轮的一句话 + +**这套工具"单点很能打,横向很吃力"**——单台机器上的取证、处置、GUI 操作、审计都做得相当扎实,`dry_run` + 复核 + 诚实免责说明的设计水平明显高于同类产品;但一旦要**横向铺开**(批量读、日志取证、Linux 文件操作、重启判定)就立刻撞墙。下一轮优化应把资源集中在这四处,而不是继续加新工具。 + +## 7. 三个 P0 的修复 + +三个 P0 都是**声明与实现不一致**,改动集中在服务端;只有 P0-3 的 Linux/macOS 半边需要 +客户端补一段。实现细节见 `docs/Mcp_Design.md` §18。 + +| 编号 | 修法 | 改动位置 | +|---|---|---| +| P0-1 批量调用必失败 | `tools/list` 收尾时给批量只读工具的 `outputSchema` 补 `anyOf:[单机形状, 批量形状]` | `McpInternal.cpp` 新增 `ApplyBatchOutputSchema`;`IsBatchReadOnlyTool` 从 `McpServer.cpp` 移入 `McpInternal.cpp` | +| P0-2 根键分支必失败 | `required` 去掉 `values`,只留 `keys`;根键分支补 `path:""` 使两分支字段一致 | `BuildListRegistryOutputSchema` / `BuildRegistryRoots` | +| P0-3 日志取不到 | 新增 `limit`(默认 200、上限 2000)与 `filter`,从末尾往前取,另有 64 KB 字节预算;返回 `lines_total`/`lines_matched`/`lines_returned`/`truncated`;Linux/macOS 客户端补 `COMMAND_QUERY_LOG` 处理 | `BuildClientLogInputSchema`(新)、`BuildGetClientLog`、`common/ClientLogHandler.h`(新)、`linux/main.cpp`、`macos/main.mm` | + +**为什么 P0-1 改在收尾阶段**:三个注册点(`McpServer.cpp` 内联 / `McpMachine` / `McpChat`) +各自 `tools.append`,在收尾统一打补丁才能保证以后新增的批量工具不漏。这与既有的 +`ApplyToolAnnotations` 同一位置、同一思路。 + +**P0-3 的两个症状是两个原因**:Windows 是"取到了但塞不下"(无 limit),Linux 是"根本 +取不到"(客户端没有 `COMMAND_QUERY_LOG` 分支,服务端只能等到超时)。只加 limit 不修 +客户端,Linux 上的 `get_client_log` 依旧超时;只修客户端不加 limit,Windows 上依旧超上限。 + +**验证结果(服务端 21:17:21 构建 / 客户端已重编,2026-10-29 21:19–21:21)**: + +| 用例 | 结果 | +|---|---| +| `get_host_detail` + `ids`(A6 两条记录) | **通过** `total=2, succeeded=2`,`results[].data.host` 逐台返回 | +| `host_list_processes` + `ids` + `limit=2` | **通过** `succeeded=2`,两台各回 2 条、`total=348` | +| `get_client_log` + `ids`(Win + Linux 混合) | **通过** `succeeded=2`;Windows 1000 行、Linux 14 行,各自独立裁剪 | +| `list_registry` 省略 `path` | **通过** 返回 5 个根键 + `path:""`,不再 `-32602` | +| `list_registry` 带 `path`(HKLM\...\Run) | **通过** 3 个值,无回归 | +| `get_client_log`(Windows,默认参数) | **通过** `lines_total=1000, lines_returned=200, truncated=true`,不再超上限 | +| `get_client_log`(Windows,`limit=3` + `filter=ConnAuth`) | **通过** `lines_matched=28, lines_returned=3` | +| `get_client_log`(Linux Ubuntu24) | **通过** 返回 8 行;客户端日志里可见 `Received 'QUERY_LOG' command` → `Enter ClientLogThread` → `Leave ClientLogThread`,子连接进出成对、无泄漏 | +| `list_files`(单机,验证 anyOf 包装未影响单机路径) | **通过** 正常分页 | + +**遗留**:连接器仍缓存着旧的 `get_client_log` inputSchema(不含 `limit`/`filter`),模型侧 +直接传这两个参数会被本地校验拦下(`must NOT have additional properties`)。默认参数已经把 +P0-3 解决掉,要显式用 `limit`/`filter` 需重连一次连接器——与 §3.2 P1-1 是同一个缓存问题。 diff --git a/linux/main.cpp b/linux/main.cpp index 4a5d59c..dc82e3d 100644 --- a/linux/main.cpp +++ b/linux/main.cpp @@ -28,6 +28,7 @@ #include "ScreenHandler.h" #include "ScreenPreview.h" #include "SystemManager.h" +#include "common/ClientLogHandler.h" #include "common/FileManager.h" #include "ClipboardHandler.h" #include "common/FileTransferV2.h" @@ -383,6 +384,19 @@ void* FileManagerThread(void* /*param*/) return NULL; } +// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。 +// 服务端取走首包后会关掉这条子连接,所以这里发完就等连接断开即可。 +void* ClientLogThread(void* /*param*/) +{ + RunSubConnThread( + "ClientLogThread", + [](IOCPClient* c) { return std::unique_ptr(new ClientLogHandler(c)); }, + [](IOCPClient* c, ClientLogHandler*) { + Mprintf(">>> ClientLogThread [%p] Send: TOKEN_REPORT_LOG\n", c); + }); + return NULL; +} + // ============== 屏幕预览(对应 Windows 端 COMMAND_SCREEN_PREVIEW_REQ) ============== // 同一时刻只跑一个抓屏任务:列表缩略图是周期性刷新,服务端还可能重发/并发请求, @@ -478,6 +492,11 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) } else if (szBuffer[0] == COMMAND_LIST_DRIVE) { std::thread(FileManagerThread, nullptr).detach(); Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user); + } else if (szBuffer[0] == COMMAND_QUERY_LOG) { + // 与 Windows 端一致:回日志必须开子连接。服务端取走首包后 CancelIO 关的是 + // 子连接;若回在主连接上,被关掉的就是主连接本身。 + std::thread(ClientLogThread, nullptr).detach(); + Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user); } else if (szBuffer[0] == COMMAND_SCREEN_PREVIEW_REQ) { if (ulLength < sizeof(ScreenPreviewReq)) return TRUE; ScreenPreviewReq req; diff --git a/macos/main.mm b/macos/main.mm index aa4c833..7311816 100644 --- a/macos/main.mm +++ b/macos/main.mm @@ -23,6 +23,7 @@ #include "../common/client_auth_state.h" #include "../common/posix_net_helpers.h" #include "../common/sub_conn_thread.h" +#include "../common/ClientLogHandler.h" #import "Permissions.h" #import "ScreenHandler.h" #import "InputHandler.h" @@ -721,6 +722,19 @@ void* FileManagerworkingThread(void* /*param*/) return NULL; } +// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。 +// 服务端取走首包后会关掉这条子连接,发完等连接断开即可。 +void* ClientLogworkingThread(void* /*param*/) +{ + RunSubConnThread( + "ClientLogworkingThread", + [](IOCPClient* c) { return std::unique_ptr(new ClientLogHandler(c)); }, + [](IOCPClient* c, ClientLogHandler*) { + Mprintf(">>> ClientLogworkingThread [%p] Send: TOKEN_REPORT_LOG\n", c); + }); + return NULL; +} + int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) { if (szBuffer == nullptr || ulLength == 0) @@ -747,6 +761,11 @@ int DataProcess(void* user, PBYTE szBuffer, ULONG ulLength) } else if (szBuffer[0] == COMMAND_LIST_DRIVE) { std::thread(FileManagerworkingThread, nullptr).detach(); Mprintf("** [%p] Received 'LIST_DRIVE' command ***\n", user); + } else if (szBuffer[0] == COMMAND_QUERY_LOG) { + // 与 Windows 端一致:回日志必须开子连接(服务端取走首包后 CancelIO 关的是 + // 子连接;若回在主连接上,被关掉的就是主连接本身)。 + std::thread(ClientLogworkingThread, nullptr).detach(); + Mprintf("** [%p] Received 'QUERY_LOG' command ***\n", user); } else if (szBuffer[0] == COMMAND_C2C_PREPARE) { // C2C 准备接收通知 FileTransferV2::HandleC2CPrepare(szBuffer, ulLength, nullptr); diff --git a/server/2015Remote/McpInternal.cpp b/server/2015Remote/McpInternal.cpp index 053fe3c..11499fe 100644 --- a/server/2015Remote/McpInternal.cpp +++ b/server/2015Remote/McpInternal.cpp @@ -480,4 +480,106 @@ void ApplyToolAnnotations(Json::Value& tools) { } } +// ===== 批量只读调用(ids[])===== + +bool IsBatchReadOnlyTool(const std::string& t) { + static const char* kReadOnly[] = { + "get_host_detail", "list_processes", "list_windows", "list_services", + "list_files", "list_registry", "get_client_log", "get_activity_history", + "list_network_connections", + "host_list_processes", "host_list_windows", "host_list_network_state", + "host_list_software", "host_list_browser_history", "host_list_favorites", + "host_list_win32_services", "host_list_driver_services", + "host_list_scheduled_tasks", "host_get_hosts_file", + }; + for (const char* x : kReadOnly) if (t == x) return true; + return false; +} + +namespace { + +// 批量调用的 structuredContent 形状(与 BuildBatchCall 的输出一一对应)。 +Json::Value MakeBatchOutputSchema() { + Json::Value props(Json::objectValue); + + auto strProp = [](const char* desc) { + Json::Value p(Json::objectValue); + p["type"] = "string"; + if (desc) p["description"] = desc; + return p; + }; + auto intProp = [](const char* desc) { + Json::Value p(Json::objectValue); + p["type"] = "integer"; + if (desc) p["description"] = desc; + return p; + }; + auto boolProp = [](const char* desc) { + Json::Value p(Json::objectValue); + p["type"] = "boolean"; + if (desc) p["description"] = desc; + return p; + }; + + props["tool"] = strProp(u8"被批量调用的工具名"); + props["total"] = intProp(u8"请求里的 id 台数"); + props["succeeded"] = intProp(u8"成功的台数"); + props["failed"] = intProp(u8"失败的台数"); + props["skipped"] = intProp(u8"因整体时限用尽而未下发的台数(不是主机侧错误)"); + + // results[]:每台一条。data 就是该工具单机调用时的 structuredContent, + // 所以这里不能给 data 收窄成固定字段,只能声明为 object。 + Json::Value itemProps(Json::objectValue); + itemProps["id"] = strProp(u8"主机 id"); + itemProps["ok"] = boolProp(u8"该台是否成功"); + Json::Value dataProp(Json::objectValue); + dataProp["type"] = "object"; + dataProp["description"] = u8"该台成功时的单机 structuredContent(字段随工具而定)"; + itemProps["data"] = dataProp; + itemProps["text"] = strProp(u8"该台失败时的错误文字"); + Json::Value errProp(Json::objectValue); + errProp["type"] = "object"; + errProp["description"] = u8"该台失败时的错误对象(code / message)"; + itemProps["error"] = errProp; + + Json::Value resultsProp(Json::objectValue); + resultsProp["type"] = "array"; + Json::Value items(Json::objectValue); + items["type"] = "object"; + items["properties"] = itemProps; + resultsProp["items"] = items; + props["results"] = resultsProp; + + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + Json::Value required(Json::arrayValue); + required.append("results"); + schema["required"] = required; + return schema; +} + +} // namespace + +void ApplyBatchOutputSchema(Json::Value& tools) { + if (!tools.isArray()) return; + for (Json::Value& tool : tools) { + if (!tool.isObject()) continue; + if (!tool.isMember("name") || !tool["name"].isString()) continue; + if (!IsBatchReadOnlyTool(tool["name"].asString())) continue; + // 用 isMember 判定,避免 operator[] 往工具对象里插一个 null 成员 + if (!tool.isMember("outputSchema") || !tool["outputSchema"].isObject()) continue; + + Json::Value single = tool["outputSchema"]; + Json::Value anyOf(Json::arrayValue); + anyOf.append(single); + anyOf.append(MakeBatchOutputSchema()); + + Json::Value wrapped(Json::objectValue); + wrapped["type"] = "object"; + wrapped["anyOf"] = anyOf; + tool["outputSchema"] = wrapped; + } +} + } // namespace McpInternal diff --git a/server/2015Remote/McpInternal.h b/server/2015Remote/McpInternal.h index 3c1447e..8a86cb0 100644 --- a/server/2015Remote/McpInternal.h +++ b/server/2015Remote/McpInternal.h @@ -142,6 +142,21 @@ void MakeIdOrIdsRequired(Json::Value& schema); // 统一的提示文字,例如「共 283 个进程,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」 std::string PageSummary(const PageWindow& w, const char* unit); +// ===== 批量只读调用(ids[])===== +// +// 支持批量的只读工具清单(写操作一律不支持,避免一次误操作波及多台主机)。 +// 清单同时被两处使用:tools/call 的入口判定,以及 tools/list 的 outputSchema 补丁。 +bool IsBatchReadOnlyTool(const std::string& toolName); + +// 给 tools/list 里的批量只读工具补第二个 outputSchema 分支。 +// +// 单机调用返回工具自己的字段(如 host / processes / entries),批量调用返回 +// { tool, total, succeeded, failed, skipped, results[] }——两者形状完全不同。 +// 只声明单机形状会让任何 ids 调用在客户端校验 structuredContent 时直接失败 +// (实测 -32602: data must have required property 'host'),而 inputSchema 又 +// 明确写着「支持 ids 批量」,等于把批量能力整条封死。这里统一改成 anyOf 两支。 +void ApplyBatchOutputSchema(Json::Value& tools); + // ===== 工具注解(A3)===== // // 给 tools/list 里的每个工具补 MCP annotations(readOnlyHint / destructiveHint / diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index e763ee7..f002c98 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -770,6 +770,9 @@ std::string BuildRegistryRoots(const Json::Value& id) { Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); + // path 恒为 "":根键这一层没有路径,但补上它能让「列根键」与「列子键」返回同一组 + // 字段(path/keys,子键那次多一个 values),调用方不必按分支判断。 + structuredContent["path"] = ""; structuredContent["keys"] = keys; result["structuredContent"] = structuredContent; @@ -1484,6 +1487,7 @@ Json::Value BuildListRegistryOutputSchema() { Json::Value valsProp(Json::objectValue); valsProp["type"] = "array"; + valsProp["description"] = u8"该键下的值;path 为空(列根键)时不返回本字段"; Json::Value valItems(Json::objectValue); valItems["type"] = "object"; Json::Value valProps(Json::objectValue); @@ -1500,9 +1504,11 @@ Json::Value BuildListRegistryOutputSchema() { Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; + // 只把 keys 标成必填。values 在「列根键」分支里不存在(根键下没有值), + // 早先把它一并 required,导致文档描述的第一种用法(省略 path)必然被 + // 客户端判为不符合 outputSchema(-32602: data must have required property 'values')。 Json::Value required(Json::arrayValue); required.append("keys"); - required.append("values"); schema["required"] = required; return schema; } @@ -1560,14 +1566,62 @@ Json::Value BuildExecCommandOutputSchema() { return schema; } -// get_client_log 的 outputSchema(原始日志文本) +// get_client_log 的 inputSchema:{ id } + limit / filter(+ ids 批量) +// +// 不加 limit 时,一次快照是客户端 ring buffer 的全量(最多 1000 行、实测 90 KB), +// 单条工具结果直接超出客户端上限——取到了却塞不下,等于取不到。默认只回末尾 +// 200 行:故障排查看的是最后发生了什么,不是开机时的第一行。 +Json::Value BuildClientLogInputSchema() { + Json::Value props(Json::objectValue); + + Json::Value idProp(Json::objectValue); + idProp["type"] = "string"; + idProp["description"] = u8"主机 id,取 list_online_hosts / search_hosts 返回的 id 字段;与 ids 二选一"; + props["id"] = idProp; + + Json::Value limitProp(Json::objectValue); + limitProp["type"] = "integer"; + limitProp["description"] = u8"最多返回末尾多少行,默认 200,上限 2000;返回的是最近的日志,不是开头的"; + props["limit"] = limitProp; + + Json::Value filterProp(Json::objectValue); + filterProp["type"] = "string"; + filterProp["description"] = u8"只看包含该子串的行(ASCII 不区分大小写,如 error / TIMEOUT);过滤后再取末尾 limit 行"; + props["filter"] = filterProp; + + AppendBatchIdsProp(props); + + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + MakeIdOrIdsRequired(schema); + return schema; +} + +// get_client_log 的 outputSchema(日志文本 + 行数统计) Json::Value BuildClientLogOutputSchema() { Json::Value props(Json::objectValue); Json::Value logProp(Json::objectValue); logProp["type"] = "string"; + logProp["description"] = u8"日志文本(按行,\\n 分隔);已按 limit/filter 裁剪"; props["log"] = logProp; + auto intProp = [](const char* desc) { + Json::Value p(Json::objectValue); + p["type"] = "integer"; + p["description"] = desc; + return p; + }; + props["lines_total"] = intProp(u8"客户端快照的总行数"); + props["lines_matched"] = intProp(u8"filter 命中后的行数(无 filter 时等于 lines_total)"); + props["lines_returned"] = intProp(u8"本次实际返回的行数"); + + Json::Value truncProp(Json::objectValue); + truncProp["type"] = "boolean"; + truncProp["description"] = u8"true 表示命中行数多于本次返回,log 只是末尾一段"; + props["truncated"] = truncProp; + Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; @@ -1987,9 +2041,9 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "get_client_log"; - tool["description"] = u8"获取指定在线主机 YAMA 客户端的内存运行日志(最近最多 1000 条,含时间戳/源文件/行号)。客户端持续增量上报,本工具取当前时刻的全量快照后即断开。只读。"; + tool["description"] = u8"获取指定在线主机 YAMA 客户端的内存运行日志(客户端 ring buffer,最多 1000 行,含时间戳/源文件/行号)。客户端持续增量上报,本工具取当前时刻的快照后即断开。默认只返回末尾 200 行(故障排查看的是最后发生了什么);可用 limit 调整(上限 2000)、filter 只保留包含某子串的行。返回里的 lines_total / lines_matched / lines_returned / truncated 说明裁剪情况。只读。"; - tool["inputSchema"] = BuildGetHostDetailInputSchema(); // 复用 { id } 必填 schema + tool["inputSchema"] = BuildClientLogInputSchema(); tool["outputSchema"] = BuildClientLogOutputSchema(); tools.append(tool); @@ -2448,6 +2502,12 @@ std::string BuildToolsListResult(const Json::Value& id) { // 以后新增工具只需在 McpInternal.cpp 的 kToolHints 表里登记一行。 ApplyToolAnnotations(tools); + // 22) 批量只读工具补第二个 outputSchema 分支(N2):批量结果的形状是 + // { tool, total, ..., results[] },与单机形状不同;只声明单机形状会让 + // 任何 ids 调用在客户端校验 structuredContent 时以 -32602 失败。 + // 同样放在最后一步,三个注册点一视同仁。 + ApplyBatchOutputSchema(tools); + result["tools"] = tools; return BuildResult(id, result); } @@ -3639,7 +3699,11 @@ std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CM std::vector data; if (!mcp.WaitPending(devId, data, mcp.ToolTimeoutMs())) - return BuildError(id, -32001, "Timeout waiting for client log"); + return BuildError(id, -32001, + u8"Timeout waiting for client log. 客户端在超时内没有回传日志:常见原因是该客户端" + u8"版本尚未实现日志上报(Linux/MAC 需 2026-10-30 之后的客户端),也可能是子连接" + u8"建立失败。可先用 get_host_detail 看 capabilities,或改用 download_file 直接取" + u8"客户端日志文件。"); // data[0]=token,其后为 Logger 内存 ring buffer 的日志文本(无 '\0' 终止)。 // 客户端在子连接建立时 m_sentIdx=0 返回全量,随后每 3s 推增量;MessageHandle 在 @@ -3654,16 +3718,100 @@ std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CM log = ToUtf8(raw.c_str(), cp); } + // 行级裁剪:客户端快照是全量(最多 1000 行、实测 90 KB),直接整段塞进结果会超出 + // 客户端的工具结果上限。默认只回末尾 200 行——排障关心的是最后发生了什么。 + int limit = 200; + if (args.isMember("limit") && args["limit"].isInt()) + limit = args["limit"].asInt(); + if (limit <= 0) limit = 200; + if (limit > 2000) limit = 2000; + const std::string filter = GetStringArg(args, "filter"); + + std::vector lines; + { + size_t b = 0; + while (b < log.size()) { + size_t e = log.find('\n', b); + std::string one = (e == std::string::npos) ? log.substr(b) : log.substr(b, e - b); + if (!one.empty() && one.back() == '\r') one.pop_back(); + lines.push_back(one); + if (e == std::string::npos) break; + b = e + 1; + } + } + const int linesTotal = (int)lines.size(); + + std::vector matched; + matched.reserve(lines.size()); + for (const auto& one : lines) { + if (filter.empty() || ContainsCI(one, filter)) + matched.push_back(one); + } + const int linesMatched = (int)matched.size(); + + // 从末尾往前取:同时受 limit 行数与 64 KB 字节预算约束(单行可能是超长的堆栈或 + // 报文转储,只按行数截断仍可能撑爆结果)。两个约束哪个先到就用哪个。 + const size_t kMaxBytes = 64 * 1024; + std::string shown; + int linesReturned = 0; + bool contentTruncated = false; + { + size_t budget = kMaxBytes; + size_t firstKept = (size_t)linesMatched; // 保留 [firstKept, linesMatched) + while (firstKept > 0 && (int)((size_t)linesMatched - firstKept) < limit) { + const size_t need = matched[firstKept - 1].size() + 1; + if (need > budget) break; + budget -= need; + --firstKept; + } + + if (firstKept == (size_t)linesMatched && linesMatched > 0) { + // 末尾一行自己就超过预算:至少回它的尾部(排障看的是最后发生了什么), + // 而不是回空串让人以为客户端没有日志。 + const std::string& last = matched.back(); + if (last.size() > kMaxBytes) { + shown = last.substr(last.size() - kMaxBytes); + contentTruncated = true; + } else { + shown = last; + } + shown += '\n'; + linesReturned = 1; + } else { + for (size_t i = firstKept; i < (size_t)linesMatched; ++i) { + shown += matched[i]; + shown += '\n'; + } + linesReturned = linesMatched - (int)firstKept; + } + } + Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); - structuredContent["log"] = log; + structuredContent["log"] = shown; + structuredContent["lines_total"] = linesTotal; + structuredContent["lines_matched"] = linesMatched; + structuredContent["lines_returned"] = linesReturned; + structuredContent["truncated"] = (linesMatched > linesReturned) || contentTruncated; result["structuredContent"] = structuredContent; + std::string text; + if (linesTotal == 0) { + text = u8"客户端暂无内存日志。"; + } else { + text = std::string(u8"客户端运行日志:共 ") + std::to_string(linesTotal) + std::string(u8" 行"); + if (!filter.empty()) + text += std::string(u8",匹配 \"") + filter + std::string(u8"\" 的 ") + std::to_string(linesMatched) + std::string(u8" 行"); + text += std::string(u8",返回末尾 ") + std::to_string(linesReturned) + std::string(u8" 行"); + if (linesMatched > linesReturned || contentTruncated) + text += std::string(u8"(还有更多,可调大 limit 或加 filter)"); + text += std::string(u8"。"); + } + Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; - item["text"] = log.empty() ? std::string(u8"客户端暂无内存日志。") - : std::string(u8"客户端运行日志快照如下。"); + item["text"] = text; content.append(item); result["content"] = content; result["isError"] = false; @@ -8550,19 +8698,8 @@ static const size_t kBatchMaxIds = 50; // 所以真实上限约为 50s + 单机超时(20s)。要更紧就得把 deadline 一路传进各工具。 static const long long kBatchDeadlineMs = 50000; -bool IsBatchReadOnlyTool(const std::string& t) { - static const char* kReadOnly[] = { - "get_host_detail", "list_processes", "list_windows", "list_services", - "list_files", "list_registry", "get_client_log", "get_activity_history", - "list_network_connections", - "host_list_processes", "host_list_windows", "host_list_network_state", - "host_list_software", "host_list_browser_history", "host_list_favorites", - "host_list_win32_services", "host_list_driver_services", - "host_list_scheduled_tasks", "host_get_hosts_file", - }; - for (const char* x : kReadOnly) if (t == x) return true; - return false; -} +// IsBatchReadOnlyTool 定义在 McpInternal.cpp:tools/list 要用它补 outputSchema, +// tools/call 要用它做批量入口判定,两处必须共用同一份清单,故不再在此重复定义。 // 单主机分派:批量路径复用它,保证批量与单机走同一套实现。 std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName,