diff --git a/docs/Mcp_Design.md b/docs/Mcp_Design.md index cef469f..4d20d1c 100644 --- a/docs/Mcp_Design.md +++ b/docs/Mcp_Design.md @@ -492,3 +492,85 @@ void CMcpSettingsDlg::OnBnClickedBtnSave() - `content` 摘要统一为「共 N <单位>,本次返回第 a-b 条(还有更多,可用 offset 继续取)。」;`hasMore=false` 时不再出现「继续取」的误导提示;`offset` 越界时明确写「offset 超出范围,本次返回 0 条」。 - 实现集中在 `McpInternal.h/.cpp`:`PageWindow` / `ResolvePageWindow` / `ApplyPageWindow` / `WritePageFields` / `AppendPagingProps` / `PageSummary`。 - `list_files` 仍受客户端单次 500 条的硬限制(`total=500` 表示客户端截断,不是服务端分页)。 + +--- + +## 10. 增补(2026-10-25:A 批加固 / B 批非破坏性能力) + +A 批只改服务端传输、元数据与校验,不动任何既有工具语义;B 批新增三个工具(两个写主机库、一个远程搜索)。**客户端零改动。** + +### 10.1 A1/A2 传输层加固(`CMcpServer::Start`) + +httplib 默认值对 MCP 场景不合适,改为显式配置: + +| 项 | 默认 | 现在 | 原因 | +|---|---|---|---| +| 请求体上限 | 不限(`SIZE_MAX`) | 2 MB(超出 413 `RequestEntityTooLarge`) | 只收 JSON 参数,文件内容走子连接分块,绝不进 HTTP body | +| 读超时 | 5s | 15s | 经 frp 隧道上传参数时,单次 recv 不该 5s 就断 | +| 写超时 | 5s | 60s | `get_screenshot` 大图 base64、慢链路下 5s 会写断响应 | +| 线程池 | `max(8, 核数-1)` | 固定 32 | `chat_wait`(最长 55s)与批量只读会长期占线程 | + +读超时是 **socket 空闲读超时**,不是「处理时长上限」:`search_file` 阻塞 20s、`chat_wait` 阻塞 55s 都正常返回(已实测)。 + +### 10.2 A3 工具注解(`McpInternal::ApplyToolAnnotations`) + +- `tools/list` 每个工具都带 `annotations`:`readOnlyHint` / `destructiveHint` / `idempotentHint` / `openWorldHint`,由 `McpInternal.cpp` 的 `kToolHints` 表按名登记,末尾统一补一次。 +- 未登记的工具按规范默认值处理(`destructiveHint=true`),即**新增工具必须显式登记**,漏登记只会更保守,不会误标成只读。 +- 只读工具的 `destructiveHint` 一律 `false`(按规范对只读工具无意义,避免客户端误报「破坏性」)。 +- `openWorldHint=false` 只给「只读服务端本机状态」的工具(`list_online_hosts` / `search_hosts` / `list_all_hosts` / `get_host_detail` / `get_activity_history` / `get_audit_log`),其余都会触达外部主机。 + +### 10.3 A4 `get_host_detail` 字段补全 + +在线主机现在返回:`id` / `name` / `online` / `ip` / `publicIp` / `location` / `group` / `os` / `version` / `exeVersion` / `clientType` / `clientPath` / `systemBits` / `programBits` / `cpuCores` / `memoryGB` / `monitors` / `screen` / `user` / `isAdmin` / `pid` / `installTime` / `activeWindow` / `rtt` / `tls`;离线主机返回 `authStatus` / `last_seen` / `install_time` 等最后记录。 + +注意 `memoryGB` 是 **double**:客户端 `GetMemorySizeGB()` 上报的就是浮点字符串(如 `"27.800000000000001"` 的原始形态),不能按整数解析。服务端按 1 位小数规范化,并给 jsoncpp 写入器设 15 位有效数字,避免输出 17 位噪声。 + +### 10.4 B1 主机库写入:`host_set_remark` / `host_set_watch_level` + +- 写的是服务端本机的 `_ClientList`(`MAP_NOTE` / `MAP_LEVEL`),**只影响主控端自己的展示**:不下发命令、不改远端状态。 +- 门控:`McpReadonly=0` 即可(不要求 `McpManage`);在线/离线(历史记录)主机都能写,id 在主机库中存在即可。 +- `host_set_remark`:`remark` 必填(空串 = 清除),**严格 GBK 转换**(emoji、`ö` 等不可表示字符报 `-32602`),长度上限 63 GBK 字节(主机库列 `char Note[64]`)。 +- `host_set_watch_level`:`level` 0–3。重复写同一值幂等。 +- 写后 `SaveToFile(GetDbPath())` 落库,并用 `LVM_REDRAWITEMS` 让在线列表那一行立刻刷新(MCP 线程不直接碰 `CListCtrl`)。 +- 审计只记「set/cleared + 字节数」与 `level=`,**不记录备注正文**。 + +### 10.5 B2 远程文件搜索:`search_file` + +**链路**(旧文件管理器,不是 SimplePlugins 版): + +``` +主连接 COMMAND_LIST_DRIVE → 客户端建子连接 → 子连接回 TOKEN_DRIVE_LIST + → 服务端 OnDriveList 下发 COMMAND_SEARCH_FILE [根目录 \0][模式 \0](ANSI/GBK 两个 C 串) + → N × TOKEN_SEARCH_FILE_LIST(分片)→ TOKEN_SEARCH_FILE_FINISH +``` + +协议来自 `client/FileManager.cpp`(`COMMAND_LIST_DRIVE` → `LoopFileManager` → `CFileManager`)。客户端工程是 MultiByte,所有字段都是 GBK,服务端用 `Utf8ToCpExact` 严格转换,不可表示即 `-32602`。 + +要点: + +- **模式**:不含 `*` / `?` 时客户端当成 `*pattern*`(不区分大小写的子串),含通配符时走 `WildcardMatch`。 +- **递归**:客户端只有递归搜索(深度 32,最多 10000 条,跳过隐藏/系统目录与重解析点)。`recursive=false` 由**服务端按「父目录 == 根目录」过滤**实现。 +- **路径归一化**:客户端用 `wsprintf("%s\\*.*")` 枚举,根目录带尾部反斜杠会拼成 `C:\\*.*` 导致 `FindFirstFile` 失败、搜索秒回 0 条。服务端统一切成正斜杠→反斜杠并去尾斜杠(`C:\` → `C:`,客户端再拼回 `C:\*.*`)。 +- **超时**:`timeout_ms` 默认 20000(1000–120000)。到点先下发 `COMMAND_FILES_SEARCH_STOP`,再等 5s 收尾;收不到 `FINISH` 也返回已收到的部分结果,`finished=false`。 +- **收集上限**:5000 条 / 4 MB 原始包,超出即让客户端停搜并置 `truncated=true`(保护服务端内存,整盘搜索能命中几十万条)。 +- **子连接身份校验**:`TOKEN_SEARCH_FILE_LIST` / `TOKEN_SEARCH_FILE_FINISH` 都按 `context*` 比对当前 pending 的子链接,旧搜索(已放弃)的尾包一律不受理,避免迟到的 FINISH 终止新搜索。 +- **已知风险(客户端既有缺陷,未修)**:`client/FileManager.cpp` 的 `SearchFilesRecursive` 用无界 `wsprintf` 往 `char[MAX_PATH]` 里拼路径(`strPath` 第 562 行、`szFullPath` 第 578 行),全程没有长度检查。目录一深(累计路径超过 260)就栈溢出:Debug 客户端弹 `Run-Time Check Failure #2 - Stack around the variable 'strPath' was corrupted` 并挂住搜索线程,Release 客户端静默破坏栈。MFC 文件管理器的「搜索」走同一函数,**与 MCP 无关**(本工具只是让它更容易被触发)。规避:只搜具体的中浅层目录,别从盘符根开始深搜。 +- **无头路由**:MFC 对话框存在时搜索结果走 `OnReceiveComplete`;只有无头子连接(MCP 调用)才会进 `MessageHandle`,所以这两条 case 只影响 MCP。`TOKEN_SEARCH_FILE_LIST` 分支**绝不 CancelIO**(后面还有 FINISH 与剩余分片)。 +- 输出:`{files:[{path,name,dir,size,modified}], finished, truncated, total, totalAll, offset, limit, hasMore}`。 + +### 10.6 A5 冒烟测试脚本 + +`tools/mcp_smoke.ps1`:只调只读工具(列表/详情/搜索 + 传输层负例),断言分页字段、注解、401/413、批量汇总。 + +```powershell +$env:YAMA_MCP_TOKEN = '' +powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 # 默认 6544(Release) +powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 -Base http://127.0.0.1:6545/mcp +``` + +token 只从 `-Token` / env 读取,不落仓库、不打印;无在线主机时加 `-SkipHost`。退出码 0/1,可接 CI。 + +### 10.7 明确不做的两项 + +- `get_clipboard`:剪贴板常含口令/令牌/私钥,属"读即泄密",且客户端没有"只读不覆盖"的现成链路;已有 `remote_clipboard` 覆盖写。需要时用 `get_screenshot` + 人工确认。 +- `close_window`:`operate_window` 的 `close` 动作已覆盖(同一 `COMMAND_WINDOW_CONTROL` 链路),不重复造工具。 diff --git a/server/2015Remote/2015RemoteDlg.cpp b/server/2015Remote/2015RemoteDlg.cpp index 7aeb05c..e0ba8d2 100644 --- a/server/2015Remote/2015RemoteDlg.cpp +++ b/server/2015Remote/2015RemoteDlg.cpp @@ -6867,6 +6867,25 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject) ContextObject->CancelIO(); // 无论是否命中,用完即关(无 MFC 对话框接管此子链接) break; } + case TOKEN_SEARCH_FILE_LIST: { // 搜索结果【B2:仅 MCP 无头搜索会到达】 + // 有挂起的 search_file 且是本连接发的 → 收下这一包;否则是已被放弃的旧搜索 + // (工具线程已超时返回部分结果)的尾包,原地丢弃即可。 + // 注意:这里绝不能 CancelIO。客户端搜索线程持有 CFileManager 的 this 指针, + // 且关连接后 ~CFileManager(client/FileManager.cpp)只会 m_bSearching=false 并 + // 最多等 5s;线程若正在 FindFirstFile 里就会继续跑。子连接统一等 + // TOKEN_SEARCH_FILE_FINISH 再关——那时客户端搜索线程已经退出。 + uint64_t devId = ContextObject->GetClientID(); + McpServer().OnSearchFileRecords(devId, ContextObject, szBuffer, len); + break; + } + case TOKEN_SEARCH_FILE_FINISH: { // 搜索结束【B2】 + // 客户端是「先停搜索线程、再发 FINISH」(自然结束或收到 COMMAND_FILES_SEARCH_STOP + // 后下一轮循环退出),所以 FINISH 到达时关子连接是安全的。挂起命中则同时唤醒工具线程。 + uint64_t devId = ContextObject->GetClientID(); + McpServer().FinishSearchFile(devId, ContextObject); + ContextObject->CancelIO(); + break; + } case TOKEN_TALK_START: { // 发送消息【x】 g_2015RemoteDlg->SendMessage(WM_OPENTALKDIALOG, 0, (LPARAM)ContextObject); break; diff --git a/server/2015Remote/McpInternal.cpp b/server/2015Remote/McpInternal.cpp index 5b1297f..03e5937 100644 --- a/server/2015Remote/McpInternal.cpp +++ b/server/2015Remote/McpInternal.cpp @@ -23,6 +23,10 @@ namespace McpInternal { std::string JsonToString(const Json::Value& v) { Json::StreamWriterBuilder b; b["indentation"] = ""; + // jsoncpp 默认按 17 位有效数字输出 double,27.8 会写成 27.800000000000001。 + // 我们只有 memoryGB 一个浮点字段(1 位小数),15 位足够且输出干净。 + b["precision"] = 15; + b["precisionType"] = "significant"; return Json::writeString(b, v); } @@ -307,4 +311,109 @@ std::string PageSummary(const PageWindow& w, const char* unit) { return s + std::string(u8"。"); } +// ===== 工具注解(A3)===== + +namespace { + +struct ToolHints { + const char* name; + bool readOnly; + bool destructive; + bool idempotent; + bool openWorld; // false = 只读服务端本机状态(主机列表、审计日志),不触达外部主机 +}; + +// 52 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。 +const ToolHints kToolHints[] = { + // --- 服务端本机只读 --- + { "list_online_hosts", true, false, true, false }, + { "search_hosts", true, false, true, false }, + { "list_all_hosts", true, false, true, false }, + { "get_host_detail", true, false, true, false }, + { "get_activity_history", true, false, true, false }, + { "get_audit_log", true, false, true, false }, + // --- 主机只读 --- + { "list_processes", true, false, true, true }, + { "list_windows", true, false, true, true }, + { "list_files", true, false, true, true }, + { "list_services", true, false, true, true }, + { "get_client_log", true, false, true, true }, + { "get_keylog", true, false, true, true }, + { "get_screenshot", true, false, true, true }, + { "list_registry", true, false, true, true }, + { "download_file", true, false, true, true }, // 只读主机(写的是主控本机目录) + { "search_file", true, false, true, true }, + { "list_network_connections", true, false, true, true }, + { "host_list_processes", true, false, true, true }, + { "host_list_windows", true, false, true, true }, + { "host_list_network_state", true, false, true, true }, + { "host_list_software", true, false, true, true }, + { "host_list_browser_history", true, false, true, true }, + { "host_list_favorites", true, false, true, true }, + { "host_list_win32_services", true, false, true, true }, + { "host_list_driver_services", true, false, true, true }, + { "host_list_scheduled_tasks", true, false, true, true }, + { "host_get_hosts_file", true, false, true, true }, + // --- 终端 --- + { "terminal_open", false, false, true, true }, + { "terminal_exec", false, true, false, true }, // 任意命令,后果由命令决定 + { "exec_command", false, true, false, true }, + { "terminal_close", false, false, true, true }, + // --- 远程控制 --- + { "remote_open", false, false, true, true }, + { "remote_close", false, false, true, true }, + { "remote_keyboard", false, false, false, true }, + { "remote_mouse", false, false, false, true }, + { "remote_clipboard", false, false, false, true }, // 覆盖对端剪贴板 + // --- 文件传输 --- + { "upload_file", false, true, false, true }, // 覆盖/新增远端文件 + // --- 设备管理(McpManage)--- + { "kill_process", false, true, false, true }, + { "operate_window", false, true, false, true }, + { "control_service", false, true, true, true }, // start/stop/set_* 重复执行同一状态 + { "power_action", false, true, false, true }, + // --- 主机管理 / 连接管理(McpMachine)--- + { "kill_network_connection", false, true, false, true }, + { "host_control_process", false, true, false, true }, + { "host_control_window", false, true, false, true }, + { "host_control_service", false, true, true, true }, + { "host_control_task", false, true, false, true }, + { "host_set_remark", false, false, true, false }, // 只写服务端主机库 + { "host_set_watch_level", false, false, true, false }, + // --- 远程交谈(McpChat)--- + { "chat_open", false, false, false, true }, + { "chat_send", false, false, false, true }, + { "chat_wait", false, false, false, true }, // 会取走 inbox 消息,不是纯读 + { "chat_close", false, false, true, true }, +}; + +} // namespace + +void ApplyToolAnnotations(Json::Value& tools) { + if (!tools.isArray()) return; + for (Json::Value& tool : tools) { + if (!tool.isObject() || !tool["name"].isString()) continue; + const std::string name = tool["name"].asString(); + + bool readOnly = false, destructive = true, idempotent = false, openWorld = true; + for (const auto& h : kToolHints) { + if (name == h.name) { + readOnly = h.readOnly; + destructive = h.destructive; + idempotent = h.idempotent; + openWorld = h.openWorld; + break; + } + } + + Json::Value ann(Json::objectValue); + ann["readOnlyHint"] = readOnly; + // 只读工具的 destructiveHint 按规范无意义,统一置 false,免得客户端误报「破坏性」。 + ann["destructiveHint"] = readOnly ? false : destructive; + ann["idempotentHint"] = idempotent; + ann["openWorldHint"] = openWorld; + tool["annotations"] = ann; + } +} + } // namespace McpInternal diff --git a/server/2015Remote/McpInternal.h b/server/2015Remote/McpInternal.h index cd0bdaf..e55a28f 100644 --- a/server/2015Remote/McpInternal.h +++ b/server/2015Remote/McpInternal.h @@ -104,4 +104,12 @@ void MakeIdOrIdsRequired(Json::Value& schema); // 统一的提示文字,例如「共 283 个进程,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」 std::string PageSummary(const PageWindow& w, const char* unit); +// ===== 工具注解(A3)===== +// +// 给 tools/list 里的每个工具补 MCP annotations(readOnlyHint / destructiveHint / +// idempotentHint / openWorldHint),让 MCP 客户端能按语义分组审批、默认折叠只读工具。 +// 名称未在注解表里的工具按 schema 规范的默认值处理(destructiveHint=true), +// 即「新增工具必须显式登记」,漏登记只会更保守,不会误标成只读。 +void ApplyToolAnnotations(Json::Value& tools); + } // namespace McpInternal diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 705cbe9..14359ab 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -1310,6 +1310,19 @@ std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, C std::string BuildControlService(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); +// ===== B1 前置声明(主机库元数据,定义见「tools/call 分派」前)===== +Json::Value BuildHostSetRemarkInputSchema(); +Json::Value BuildHostSetRemarkOutputSchema(); +Json::Value BuildHostSetWatchLevelInputSchema(); +Json::Value BuildHostSetWatchLevelOutputSchema(); +std::string BuildHostSetRemark(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); +std::string BuildHostSetWatchLevel(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); + +// ===== B2 前置声明(search_file,定义见「tools/call 分派」前)===== +Json::Value BuildSearchFileInputSchema(); +Json::Value BuildSearchFileOutputSchema(); +std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent); + // tools/list std::string BuildToolsListResult(const Json::Value& id) { Json::Value result(Json::objectValue); @@ -1686,6 +1699,36 @@ std::string BuildToolsListResult(const Json::Value& id) { } } + // 18b) 主机库元数据(B1:host_set_remark / host_set_watch_level)。 + // 只写服务端本地的备注/关注等级,不触达客户端,因此只受 McpReadonly 约束。 + { + Json::Value tool(Json::objectValue); + tool["name"] = "host_set_remark"; + tool["description"] = u8"给主机设置备注(在线或离线历史记录都可)。只写入服务端本地主机库,不向客户端下发任何命令;remark 传空字符串表示清除备注,GBK 编码后最长 63 字节。"; + tool["inputSchema"] = BuildHostSetRemarkInputSchema(); + tool["outputSchema"] = BuildHostSetRemarkOutputSchema(); + tools.append(tool); + } + { + Json::Value tool(Json::objectValue); + tool["name"] = "host_set_watch_level"; + tool["description"] = u8"设置主机在服务端在线列表里的关注等级:0=无、1=蓝字、2=红字、3=红底。只影响主控端本机显示,重复设置同一等级幂等。"; + tool["inputSchema"] = BuildHostSetWatchLevelInputSchema(); + tool["outputSchema"] = BuildHostSetWatchLevelOutputSchema(); + tools.append(tool); + } + + // 18c) 远程文件搜索(B2:search_file)。只读、仅 Windows 客户端, + // 故与其它只读工具一样始终登记,调用时按 McpReadonly / 客户端平台复核。 + { + Json::Value tool(Json::objectValue); + tool["name"] = "search_file"; + tool["description"] = u8"在指定主机(仅 Windows)的某个目录下按文件名搜索文件(不区分大小写;pattern 不含通配符时按子串匹配,含 * / ? 时按通配符匹配)。客户端始终递归子目录(深度 32、最多 10000 条,跳过隐藏+系统目录与符号链接),结果边搜边收集、按 limit/offset 分页;finished=false 表示到达 timeout_ms 时限、返回的是部分结果(服务端已通知客户端停止搜索)。单次最多收集 5000 条 / 4 MB,超出时 truncated=true。注意:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,整盘/深目录搜索会栈溢出(Debug 客户端弹 Run-Time Check Failure #2 并挂住搜索线程,Release 静默破坏栈)——请只搜具体的中浅层目录,不要从盘符根开始扫。"; + tool["inputSchema"] = BuildSearchFileInputSchema(); + tool["outputSchema"] = BuildSearchFileOutputSchema(); + tools.append(tool); + } + // 19) 连接管理 / 主机管理(P8:list_network_connections / kill_network_connection / // host_* 共 16 个工具)。开关在 McpMachine.cpp 内部按 McpMachine / // McpMachineDangerous / McpReadonly 逐项判断,关闭时不追加任何工具。 @@ -1695,6 +1738,11 @@ std::string BuildToolsListResult(const Json::Value& id) { // 独立开关 McpChat(默认关),与 McpReadonly 无关;关闭时不追加任何工具。 McpChat::AppendTools(tools); + // 21) 统一补 annotations(A3):只读/破坏性/幂等/开放世界四类提示。 + // 放在最后一步,三个注册点(本文件内联、McpMachine、McpChat)一视同仁, + // 以后新增工具只需在 McpInternal.cpp 的 kToolHints 表里登记一行。 + ApplyToolAnnotations(tools); + result["tools"] = tools; return BuildResult(id, result); } @@ -1812,6 +1860,69 @@ std::string BuildSearchHosts(const Json::Value& id, const Json::Value& args, CMy } // tools/call:get_host_detail +// +// 登录时上报的 RES_* 技术字段(CPU 核数/内存/系统位数/账号/安装时间/分辨率…)只在 +// get_host_detail 里补充,不改 BuildHostJson —— 那是 Web UI 与 list_online_hosts 共用的 +// 序列化函数,动它会改变已有调用方的输出形状。 +std::string ResFieldUtf8(context* ctx, UINT cp, int idx) { + CString v = ctx->GetAdditionalData(idx); + if (v.IsEmpty()) return ""; + return ToUtf8(v.GetString(), cp); +} + +int DigitsOrZero(const std::string& s) { + return IsDigits(s) ? atoi(s.c_str()) : 0; +} + +void AppendHostTechnicalDetail(CMy2015RemoteDlg* parent, uint64_t devId, Json::Value& host) { + context* ctx = FindMainContext(parent, devId); + if (!ctx) return; + const UINT cp = GetClientEncoding(ctx); + + int cpu = DigitsOrZero(ResFieldUtf8(ctx, cp, RES_SYSTEM_CPU)); + if (cpu > 0) host["cpuCores"] = cpu; + // 内存是 double 上报(client/LoginServer.cpp 的 GetMemorySizeGB → to_string), + // 例如 "15.903053";不能按整数解析,否则整段被丢掉。保留 1 位小数。 + std::string memStr = ResFieldUtf8(ctx, cp, RES_SYSTEM_MEM); + if (!memStr.empty() && memStr[0] >= '0' && memStr[0] <= '9') { + double mem = atof(memStr.c_str()); + if (mem > 0) host["memoryGB"] = (double)((long long)(mem * 10.0 + 0.5)) / 10.0; + } + + std::string bits = ResFieldUtf8(ctx, cp, RES_SYSTEM_BITS); + if (!bits.empty()) host["systemBits"] = bits; // "64" / "32" + std::string progBits = ResFieldUtf8(ctx, cp, RES_PROGRAM_BITS); + if (!progBits.empty()) host["programBits"] = progBits; + + std::string user = ResFieldUtf8(ctx, cp, RES_USERNAME); + if (!user.empty()) host["user"] = user; + std::string admin = ResFieldUtf8(ctx, cp, RES_ISADMIN); + if (!admin.empty()) host["isAdmin"] = (admin == "1"); + + std::string install = ResFieldUtf8(ctx, cp, RES_INSTALL_TIME); + if (!install.empty()) host["installTime"] = install; + std::string expired = ResFieldUtf8(ctx, cp, RES_EXPIRED_DATE); + if (!expired.empty()) host["expiredDate"] = expired; + + // 心跳格式 "N:W*H":N=显示器数。多显示器时 remote_open/remote_* 会拒(-32008), + // 把 N 直接给出,AI 不必自己拆 screen 字符串。 + std::string res = ResFieldUtf8(ctx, cp, RES_RESOLUTION); + size_t colon = res.find(':'); + if (colon != std::string::npos) { + int monitors = DigitsOrZero(res.substr(0, colon)); + if (monitors > 0) host["monitors"] = monitors; + } + + std::string exeVer = ResFieldUtf8(ctx, cp, RES_EXE_VERSION); + if (!exeVer.empty()) host["exeVersion"] = exeVer; + std::string exePath = ResFieldUtf8(ctx, cp, RES_FILE_PATH); + if (!exePath.empty()) host["clientPath"] = exePath; + std::string pid = ResFieldUtf8(ctx, cp, RES_PID); + if (!pid.empty()) host["pid"] = pid; + std::string pubIp = ResFieldUtf8(ctx, cp, RES_CLIENT_PUBIP); + if (!pubIp.empty()) host["publicIp"] = pubIp; +} + std::string BuildGetHostDetail(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { std::string sid = GetStringArg(args, "id"); if (sid.empty()) { @@ -1826,16 +1937,21 @@ std::string BuildGetHostDetail(const Json::Value& id, const Json::Value& args, C for (unsigned int i = 0; i < all.size(); ++i) { const Json::Value& h = all[i]; if (JsonStrField(h, "id") == sid) { + // 复制后再补充技术字段:all[] 里的是本次调用内的临时对象,补字段不影响 + // BuildHostJson 本身(list_online_hosts 用同一份序列化,输出形状不变)。 + Json::Value host = h; + AppendHostTechnicalDetail(parent, strtoull(sid.c_str(), nullptr, 10), host); + Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); - structuredContent["host"] = h; + structuredContent["host"] = host; result["structuredContent"] = structuredContent; Json::Value content(Json::arrayValue); Json::Value item(Json::objectValue); item["type"] = "text"; - std::string name = JsonStrField(h, "name"); - std::string ip = JsonStrField(h, "ip"); + std::string name = JsonStrField(host, "name"); + std::string ip = JsonStrField(host, "ip"); item["text"] = std::string(u8"主机 ") + name + " (" + ip + ")" + u8" 的详情。"; content.append(item); result["content"] = content; @@ -4818,6 +4934,145 @@ std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy return BuildResult(id, result); } +// ===== B1:主机库元数据(备注 / 关注等级)===== +// +// 写的是服务端本机的 _ClientList(MAP_NOTE / MAP_LEVEL),只影响主控端自己的展示: +// 不向客户端下发任何命令,也不改远端状态。所以门控只要 McpReadonly=0(这不是对设备的 +// 操作,不要求 McpManage),审计仍走 AuditManageAction(只记字节数,绝不记备注内容)。 +// 在线与离线(历史记录)主机都能写:id 在主机库里存在即可。 +static bool HostStoreHas(CMy2015RemoteDlg* parent, uint64_t devId) { + if (!parent || !parent->m_ClientMap) return false; + EnterCriticalSection(&parent->m_cs); + bool exists = parent->m_ClientMap->Exists(devId); + LeaveCriticalSection(&parent->m_cs); + return exists; +} + +// 备注/关注等级改完,UI 行要重绘才能立刻看到。MCP 线程不能直接碰 CListCtrl, +// 用 LVM_REDRAWITEMS 投递到列表控件(回到 UI 线程处理,触发 LVN_GETDISPINFO 重取文本)。 +static void PostRepaintHostRow(CMy2015RemoteDlg* parent, uint64_t devId) { + if (!parent || !parent->m_CList_Online.GetSafeHwnd()) return; + int row = -1; + EnterCriticalSection(&parent->m_cs); + auto it = parent->m_ClientIndex.find(devId); + if (it != parent->m_ClientIndex.end()) { + for (size_t fi = 0; fi < parent->m_FilteredIndices.size(); ++fi) { + if (parent->m_FilteredIndices[fi] == it->second) { row = (int)fi; break; } + } + } + LeaveCriticalSection(&parent->m_cs); + if (row >= 0) + parent->m_CList_Online.PostMessage(LVM_REDRAWITEMS, (WPARAM)row, (LPARAM)row); +} + +std::string BuildHostSetRemark(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { + uint64_t devId = 0; + std::string err; + if (!ParseHostIdArg(args, devId, err)) + return BuildError(id, -32602, err); + + if (!args.isMember("remark") || !args["remark"].isString()) + return BuildError(id, -32602, + "Missing required parameter: remark (string; empty string clears the remark)"); + const std::string remarkU8 = args["remark"].asString(); + + CMcpServer& mcp = CMcpServer::Instance(); + if (mcp.IsReadonly()) + return BuildError(id, -32006, + "host_set_remark is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); + + if (!HostStoreHas(parent, devId)) + return BuildError(id, -32002, "Unknown host id (not in host store): " + std::to_string(devId)); + + // 主机库的备注列是 char Note[64](_ClientValue),存的是 GBK。严格转换:不可表示 + // 的字符(emoji、ö 等)直接报错,而不是静默变成 '?';长度按 GBK 字节算,留 1 字节 NUL。 + std::string remarkGbk; + if (!Utf8ToCpExact(remarkU8, 936, remarkGbk)) + return BuildError(id, -32602, + "Remark contains characters that GBK (client ANSI) cannot represent"); + if (remarkGbk.size() >= 64) + return BuildError(id, -32602, + "Remark too long: " + std::to_string(remarkGbk.size()) + + " GBK bytes (max 63)"); + + EnterCriticalSection(&parent->m_cs); + parent->m_ClientMap->SetClientMapData(devId, MAP_NOTE, remarkGbk.c_str()); + parent->m_ClientMap->SaveToFile(GetDbPath()); + LeaveCriticalSection(&parent->m_cs); + + PostRepaintHostRow(parent, devId); + AuditManageAction(parent, devId, "host_set_remark", + std::string("remark ") + (remarkGbk.empty() ? "cleared" : "set") + + " bytes=" + std::to_string(remarkGbk.size())); + + Json::Value result(Json::objectValue); + Json::Value structuredContent(Json::objectValue); + structuredContent["id"] = std::to_string(devId); + structuredContent["remark"] = remarkU8; + result["structuredContent"] = structuredContent; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = remarkGbk.empty() + ? std::string(u8"已清除该主机的备注。") + : std::string(u8"已更新该主机的备注(") + + std::to_string(remarkGbk.size()) + std::string(u8" 字节)。"); + content.append(item); + result["content"] = content; + result["isError"] = false; + + return BuildResult(id, result); +} + +std::string BuildHostSetWatchLevel(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { + uint64_t devId = 0; + std::string err; + if (!ParseHostIdArg(args, devId, err)) + return BuildError(id, -32602, err); + + int level = -1; + if (!GetIntArg(args, "level", level)) + return BuildError(id, -32602, "Missing required parameter: level (integer 0-3)"); + if (level < 0 || level > 3) + return BuildError(id, -32602, + "Invalid level: " + std::to_string(level) + " (expect 0-3)"); + + CMcpServer& mcp = CMcpServer::Instance(); + if (mcp.IsReadonly()) + return BuildError(id, -32006, + "host_set_watch_level is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)"); + + if (!HostStoreHas(parent, devId)) + return BuildError(id, -32002, "Unknown host id (not in host store): " + std::to_string(devId)); + + EnterCriticalSection(&parent->m_cs); + parent->m_ClientMap->SetClientMapInteger(devId, MAP_LEVEL, level); + parent->m_ClientMap->SaveToFile(GetDbPath()); + LeaveCriticalSection(&parent->m_cs); + + PostRepaintHostRow(parent, devId); + AuditManageAction(parent, devId, "host_set_watch_level", + "level=" + std::to_string(level)); + + Json::Value result(Json::objectValue); + Json::Value structuredContent(Json::objectValue); + structuredContent["id"] = std::to_string(devId); + structuredContent["level"] = level; + result["structuredContent"] = structuredContent; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = std::string(u8"关注等级已设为 ") + std::to_string(level) + + std::string(u8"(0=无、1=蓝字、2=红字、3=红底)。"); + content.append(item); + result["content"] = content; + result["isError"] = false; + + return BuildResult(id, result); +} + // ===== N3:get_keylog ===== // // 复用客户端既有键盘记录链路:主连接下发 COMMAND_KEYBOARD → 客户端新建子连接并回 @@ -4965,12 +5220,398 @@ std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy20 return BuildResult(id, result); } +// ===== B2:search_file(远程文件搜索,仅 Windows)===== +// +// 链路:主连接 COMMAND_LIST_DRIVE → 子连接回 TOKEN_DRIVE_LIST(OnDriveList 转下发) +// → 子连接 COMMAND_SEARCH_FILE → N×TOKEN_SEARCH_FILE_LIST → TOKEN_SEARCH_FILE_FINISH。 +// +// 协议来自 client/FileManager.cpp(COMMAND_LIST_DRIVE → LoopFileManager → 这个 CFileManager), +// 不是 client/file/FileManager.cpp(那是 SimplePlugins 版,走 COMMAND_FILE_MANAGER_PLUGIN, +// MCP 的 list_files 不走那条链路)。客户端工程是 MultiByte,全部字段都是 ANSI(GBK): +// * 请求 = [COMMAND_SEARCH_FILE][根目录 \0][模式 \0](两个 NUL 结尾的字符串,无定长结构)。 +// 模式里没有 * / ? 时客户端自动包成 "*模式*",即「子串、不区分大小写」; +// 含通配符则按通配符匹配(WildcardMatch)。 +// * 结果 = [TOKEN_SEARCH_FILE_LIST]{ [attr:1][全路径 \0][sizeHi:4][sizeLo:4][FILETIME:8] }*, +// 一个包里可以有多条(客户端按 64KB 批量发),attr = dwFileAttributes & 0x10 → 0 或 16。 +// * 客户端行为:总是递归(深度 32、最多 10000 条),跳过隐藏+系统目录与重解析点; +// COMMAND_FILES_SEARCH_STOP 只置 m_bSearching=false,搜索线程随后自然结束并发 FINISH。 +// ~CFileManager 会 m_bSearching=false + WaitForSingleObject(5000) 再离开,所以即使连接 +// 在搜索中途断开,旧版这个管理器也不会 UAF;我们仍然只在 FINISH 后关连接,保持保守。 +// +// 协议上限约束:客户端用 char[MAX_PATH] 缓冲拼路径(ExpandEnvironmentStrings/wsprintf), +// 服务端把 path/pattern 限在 200 字节 GBK 内,给客户端留余量(见 kSearchMaxPathBytes)。 +namespace { + +// 客户端 SearchFilesRecursive 的 strPath[MAX_PATH]/szFullPath[MAX_PATH] 都要再拼子路径。 +const size_t kSearchMaxPathBytes = 200; +const size_t kSearchMaxPatternBytes = 200; + +// 去掉末尾的 '\' 或 '/'("C:\" 保留成 "C:",比较时再容忍这种差异)。 +std::string StripTrailingSlashes(std::string s) { + while (s.size() > 2 && (s.back() == '\\' || s.back() == '/')) s.pop_back(); + if (s.size() == 3 && s[1] == ':' && (s[2] == '\\' || s[2] == '/')) s.pop_back(); // "C:\" → "C:" + return s; +} + +// Windows 路径比较:ASCII 不区分大小写(GBK 双字节按原字节比,中文本就无大小写)。 +bool EqualsPathNoCase(const std::string& a, const std::string& b) { + if (a.size() != b.size()) return false; + for (size_t i = 0; i < a.size(); ++i) { + char ca = a[i], cb = b[i]; + if (ca >= 'A' && ca <= 'Z') ca = (char)(ca - 'A' + 'a'); + if (cb >= 'A' && cb <= 'Z') cb = (char)(cb - 'A' + 'a'); + if (ca != cb) return false; + } + return true; +} + +std::string FormatFileTimeLocal(const FILETIME& ftIn) { + if (ftIn.dwLowDateTime == 0 && ftIn.dwHighDateTime == 0) return ""; + FILETIME local; + if (!FileTimeToLocalFileTime(&ftIn, &local)) return ""; + SYSTEMTIME st; + if (!FileTimeToSystemTime(&local, &st)) return ""; + char buf[32]; + _snprintf_s(buf, sizeof(buf), _TRUNCATE, "%04d-%02d-%02d %02d:%02d:%02d", + st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond); + return buf; +} + +// 一个 TOKEN_SEARCH_FILE_LIST 包里有多条记录(客户端按 64KB 批量发)。 +// 客户端用 LocalReAlloc(LMEM_ZEROINIT) 扩缓冲,包尾可能带 0 填充;读到空路径即视为结束。 +void AppendSearchRecords(const std::vector& pkt, Json::Value& out) { + if (pkt.size() < 2) return; + const size_t len = pkt.size(); + size_t off = 1; // 跳过 token 字节 + while (off + 1 <= len) { + const BYTE attr = pkt[off]; + ++off; + + std::string path; // GBK 原始字节 + bool terminated = false; + while (off < len) { + const char ch = (char)pkt[off++]; + if (ch == 0) { terminated = true; break; } + path.push_back(ch); + } + if (!terminated || off + 16 > len) return; // 尾部截断/零填充 + if (path.empty()) return; // LocalSize 的零填充 + + DWORD sizeHi = 0, sizeLo = 0; + memcpy(&sizeHi, pkt.data() + off, 4); + memcpy(&sizeLo, pkt.data() + off + 4, 4); + off += 8; + FILETIME ft; + memcpy(&ft, pkt.data() + off, sizeof(ft)); + off += 8; + + size_t slash = path.find_last_of("\\/"); + const std::string name = (slash == std::string::npos) ? path : path.substr(slash + 1); + + Json::Value rec(Json::objectValue); + rec["path"] = ToUtf8(path.c_str(), 936); + rec["name"] = ToUtf8(name.c_str(), 936); + rec["dir"] = (attr & FILE_ATTRIBUTE_DIRECTORY) != 0; + rec["size"] = (Json::UInt64)(((uint64_t)sizeHi << 32) | sizeLo); + std::string modified = FormatFileTimeLocal(ft); + if (!modified.empty()) rec["modified"] = modified; + out.append(rec); + } +} + +} // namespace + +Json::Value BuildSearchFileInputSchema() { + Json::Value props(Json::objectValue); + Json::Value idProp(Json::objectValue); + idProp["type"] = "string"; + idProp["description"] = u8"主机 id(Windows 客户端)。"; + props["id"] = idProp; + + Json::Value pathProp(Json::objectValue); + pathProp["type"] = "string"; + pathProp["description"] = u8"搜索的根目录,例如 C:\\Users 或 D:\\Data(必须是完整路径)。"; + props["path"] = pathProp; + + Json::Value patProp(Json::objectValue); + patProp["type"] = "string"; + patProp["description"] = u8"文件名匹配串(不区分大小写),例如 report、.log、setup.exe;不含通配符时按子串匹配,含 * 或 ? 时按通配符匹配(如 *.log)。"; + props["pattern"] = patProp; + + Json::Value recProp(Json::objectValue); + recProp["type"] = "boolean"; + recProp["description"] = u8"是否包含子目录,默认 true。客户端只支持递归搜索,传 false 时由服务端过滤出根目录下的直接子项(搜索耗时不变)。"; + props["recursive"] = recProp; + + Json::Value toProp(Json::objectValue); + toProp["type"] = "integer"; + toProp["description"] = u8"搜索时限(毫秒),默认 20000,范围 1000-120000。到时限会通知客户端停止搜索,返回已收到的部分结果(finished=false)。"; + props["timeout_ms"] = toProp; + + AppendPagingProps(props); + + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + Json::Value required(Json::arrayValue); + required.append("id"); + required.append("path"); + required.append("pattern"); + schema["required"] = required; + return schema; +} + +Json::Value BuildSearchFileOutputSchema() { + Json::Value props(Json::objectValue); + Json::Value filesProp(Json::objectValue); + filesProp["type"] = "array"; + Json::Value items(Json::objectValue); + items["type"] = "object"; + filesProp["items"] = items; + props["files"] = filesProp; + Json::Value finProp(Json::objectValue); + finProp["type"] = "boolean"; + props["finished"] = finProp; + Json::Value truncProp(Json::objectValue); + truncProp["type"] = "boolean"; + props["truncated"] = truncProp; + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + return schema; +} + +std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { + uint64_t devId = 0; + std::string err; + if (!ParseHostIdArg(args, devId, err)) + return BuildError(id, -32602, err); + + context* ctx = FindMainContext(parent, devId); + if (!ctx) + return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); + + // 该协议只在 Windows 客户端的 CFileManager 里实现(请求体是两个 GBK C 串)。 + CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); + if (clientType == "LNX" || clientType == "MAC" || clientType == "APK") + return BuildError(id, -32005, "search_file is only supported on Windows hosts"); + + std::string path = Trim(GetStringArg(args, "path")); + std::string pattern = Trim(GetStringArg(args, "pattern")); + if (path.empty()) + return BuildError(id, -32602, "Missing required parameter: path (e.g. C:\\\\Users)"); + if (pattern.empty()) + return BuildError(id, -32602, "Missing required parameter: pattern (file name substring)"); + + // 客户端枚举用的是 wsprintf("%s\\*.*"):根目录带尾部反斜杠会拼成 "C:\\*.*", + // FindFirstFile 直接失败,搜索秒回 0 条。统一去尾斜杠("C:\" → "C:",客户端拼回 "C:\*.*"), + // 顺便把分隔符统一成反斜杠(记录里的全路径也是反斜杠拼的)。 + for (char& c : path) if (c == '/') c = '\\'; + path = StripTrailingSlashes(path); + if (path.empty() || path == "\\") + return BuildError(id, -32602, + "Invalid path: expected a directory such as C:\\ or C:\\Users"); + + bool recursive = true; + if (args.isMember("recursive") && args["recursive"].isBool()) + recursive = args["recursive"].asBool(); + + int timeoutMs = 20000; + int v = 0; + if (GetIntArg(args, "timeout_ms", v)) { + if (v < 1000) v = 1000; + if (v > 120000) v = 120000; + timeoutMs = v; + } + + std::string ansiPath, ansiPattern; + if (!Utf8ToCpExact(path, 936, ansiPath)) + return BuildError(id, -32602, + "path cannot be encoded in the client's ANSI code page (GBK); use ASCII-safe paths"); + if (!Utf8ToCpExact(pattern, 936, ansiPattern)) + return BuildError(id, -32602, + "pattern cannot be encoded in the client's ANSI code page (GBK)"); + if (ansiPath.size() > kSearchMaxPathBytes) + return BuildError(id, -32602, + "path too long (max " + std::to_string(kSearchMaxPathBytes) + " bytes in GBK)"); + if (ansiPattern.size() > kSearchMaxPatternBytes) + return BuildError(id, -32602, + "pattern too long (max " + std::to_string(kSearchMaxPatternBytes) + " bytes in GBK)"); + + // 请求体 = [根目录 \0][模式 \0](OnDriveList 前面再加 COMMAND_SEARCH_FILE)。 + std::string payload; + payload.reserve(ansiPath.size() + ansiPattern.size() + 2); + payload.append(ansiPath); + payload.push_back('\0'); + payload.append(ansiPattern); + payload.push_back('\0'); + + CMcpServer& mcp = CMcpServer::Instance(); + if (!mcp.BeginPending(devId, "search_file", payload)) + return BuildError(id, -32003, "Device busy: another request is pending for this host"); + + BYTE cmd = COMMAND_LIST_DRIVE; + if (!ctx->Send2Client(&cmd, 1)) { + mcp.ClearPending(devId); + return BuildError(id, -32004, "Failed to send command to host"); + } + + std::vector> packets; + bool finished = false, truncated = false; + context* subCtx = nullptr; + if (!mcp.WaitSearchFile(devId, packets, finished, truncated, subCtx, timeoutMs)) { + mcp.ClearPending(devId); + return BuildError(id, -32001, "Timeout waiting for the file manager session"); + } + + if (!finished) { + if (!subCtx) { + // 客户端连文件管理器子连接都没建起来(离线/拒绝/过载),不是「搜索慢」。 + mcp.ClearPending(devId); + return BuildError(id, -32001, "Timeout waiting for the file manager session"); + } + // 到时限:让客户端停搜(客户端搜索线程下一次循环即退出,随后回 FINISH),再给 5s 收尾。 + // 收不到 FINISH 也照样返回部分结果;子连接留给 FINISH 分支关闭。 + mcp.StopSearchFile(devId); + std::vector> more; + bool finished2 = false, truncated2 = truncated; + context* subCtx2 = nullptr; + if (mcp.WaitSearchFile(devId, more, finished2, truncated2, subCtx2, 5000)) { + packets.insert(packets.end(), more.begin(), more.end()); + finished = finished2; + truncated = truncated || truncated2; + } + } + mcp.ClearPending(devId); + + Json::Value all(Json::arrayValue); + for (const auto& pkt : packets) AppendSearchRecords(pkt, all); + + // 客户端只有递归搜索(深度 32),非递归请求在这里按「父目录 == 根目录」服务端过滤。 + if (!recursive) { + Json::Value filtered(Json::arrayValue); + const std::string root = StripTrailingSlashes(path); + for (const Json::Value& rec : all) { + std::string p = rec["path"].asString(); + size_t slash = p.find_last_of("\\/"); + if (slash == std::string::npos) continue; + if (EqualsPathNoCase(StripTrailingSlashes(p.substr(0, slash)), root)) + filtered.append(rec); + } + all = filtered; + } + + PageWindow page = ResolvePageWindow(args); + Json::Value pageItems; + ApplyPageWindow(all, page, pageItems); + + Json::Value result(Json::objectValue); + Json::Value structuredContent(Json::objectValue); + structuredContent["files"] = pageItems; + structuredContent["finished"] = finished; + structuredContent["truncated"] = truncated; + WritePageFields(structuredContent, page); + result["structuredContent"] = structuredContent; + + std::string text = PageSummary(page, u8"个匹配项"); + if (!finished) + text += u8" 搜索在时限内未完成,以上为已收到的部分结果(可加大 timeout_ms 重试)。"; + if (truncated) + text += u8" 命中数超过服务端收集上限(5000 条 / 4 MB),后续匹配已停止收集,请缩小 path 或 pattern 再搜。"; + + Json::Value content(Json::arrayValue); + Json::Value item(Json::objectValue); + item["type"] = "text"; + item["text"] = text; + content.append(item); + result["content"] = content; + result["isError"] = false; + + return BuildResult(id, result); +} + +// ===== B1:主机库元数据 schema ===== +Json::Value BuildHostSetRemarkInputSchema() { + Json::Value props(Json::objectValue); + Json::Value idProp(Json::objectValue); + idProp["type"] = "string"; + idProp["description"] = u8"主机 id(list_online_hosts / list_all_hosts 返回的十进制字符串)。"; + props["id"] = idProp; + Json::Value remarkProp(Json::objectValue); + remarkProp["type"] = "string"; + remarkProp["description"] = u8"备注文本(UTF-8);空字符串表示清除备注;GBK 编码后最长 63 字节。"; + props["remark"] = remarkProp; + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + Json::Value required(Json::arrayValue); + required.append("id"); + required.append("remark"); + schema["required"] = required; + return schema; +} + +Json::Value BuildHostSetRemarkOutputSchema() { + Json::Value props(Json::objectValue); + Json::Value idProp(Json::objectValue); + idProp["type"] = "string"; + props["id"] = idProp; + Json::Value remarkProp(Json::objectValue); + remarkProp["type"] = "string"; + props["remark"] = remarkProp; + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + return schema; +} + +Json::Value BuildHostSetWatchLevelInputSchema() { + Json::Value props(Json::objectValue); + Json::Value idProp(Json::objectValue); + idProp["type"] = "string"; + idProp["description"] = u8"主机 id(在线或离线历史记录均可)。"; + props["id"] = idProp; + Json::Value levelProp(Json::objectValue); + levelProp["type"] = "integer"; + levelProp["minimum"] = 0; + levelProp["maximum"] = 3; + levelProp["description"] = u8"关注等级:0=无、1=蓝字、2=红字、3=红底(服务端在线列表现色)。"; + props["level"] = levelProp; + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + Json::Value required(Json::arrayValue); + required.append("id"); + required.append("level"); + schema["required"] = required; + return schema; +} + +Json::Value BuildHostSetWatchLevelOutputSchema() { + Json::Value props(Json::objectValue); + Json::Value idProp(Json::objectValue); + idProp["type"] = "string"; + props["id"] = idProp; + Json::Value levelProp(Json::objectValue); + levelProp["type"] = "integer"; + props["level"] = levelProp; + Json::Value schema(Json::objectValue); + schema["type"] = "object"; + schema["properties"] = props; + return schema; +} + // ===== N2:批量只读调用(ids[]) ===== // // 只读工具支持一次传多个主机 id(args.ids),服务端逐个调用单机实现并把结果汇总到 // structuredContent.results。写操作工具一律不支持批量(避免一次误操作波及多台)。 // 每个 id 的单机结果仍带各自的 limit/offset/total/hasMore —— 分页是「每台主机各自的」。 static const size_t kBatchMaxIds = 50; +// 批量整体时限:50 台 × 单机 20s 最坏能拖到 1000s,远超 MCP 客户端自身的工具超时。 +// 到了时限就不再对剩余 id 下发(标 skipped),保证响应在客户端放弃之前返回。 +// 注意:时限只在「下一台开始前」检查,正在跑的那一台仍会跑完它自己的超时, +// 所以真实上限约为 50s + 单机超时(20s)。要更紧就得把 deadline 一路传进各工具。 +static const long long kBatchDeadlineMs = 50000; bool IsBatchReadOnlyTool(const std::string& t) { static const char* kReadOnly[] = { @@ -5001,6 +5642,16 @@ Json::Value MakeBatchErrorEntry(const std::string& hostId, int code, const std:: return entry; } +// 批量整体时限用尽后,剩余 id 的占位结果:明确标 skipped(未下发), +// 与「试过但失败」区分开,避免调用方误以为这些都是主机侧错误。 +Json::Value MakeBatchSkippedEntry(const std::string& hostId) { + Json::Value entry = MakeBatchErrorEntry(hostId, -32001, + "Batch deadline exceeded (" + std::to_string(kBatchDeadlineMs / 1000) + + " s): not attempted"); + entry["skipped"] = true; + return entry; +} + std::string BuildBatchCall(const Json::Value& id, const std::string& toolName, const Json::Value& args, CMy2015RemoteDlg* parent) { const Json::Value& ids = args["ids"]; @@ -5011,8 +5662,11 @@ std::string BuildBatchCall(const Json::Value& id, const std::string& toolName, } Json::Value results(Json::arrayValue); - int okCount = 0, failCount = 0; + int okCount = 0, failCount = 0, skipCount = 0; std::string failLines; + const auto batchDeadline = + std::chrono::steady_clock::now() + std::chrono::milliseconds(kBatchDeadlineMs); + bool deadlineHit = false; for (const Json::Value& v : ids) { std::string hostId; @@ -5029,6 +5683,14 @@ std::string BuildBatchCall(const Json::Value& id, const std::string& toolName, continue; } + // 整体时限:一旦命中,后面所有 id 都不再下发(只记 skipped,不等待)。 + if (deadlineHit || std::chrono::steady_clock::now() >= batchDeadline) { + deadlineHit = true; + results.append(MakeBatchSkippedEntry(hostId)); + ++skipCount; + continue; + } + Json::Value oneArgs = args; oneArgs.removeMember("ids"); oneArgs["id"] = hostId; @@ -5082,6 +5744,7 @@ std::string BuildBatchCall(const Json::Value& id, const std::string& toolName, structuredContent["total"] = (int)ids.size(); structuredContent["succeeded"] = okCount; structuredContent["failed"] = failCount; + structuredContent["skipped"] = skipCount; structuredContent["results"] = results; Json::Value result(Json::objectValue); @@ -5093,7 +5756,11 @@ std::string BuildBatchCall(const Json::Value& id, const std::string& toolName, item["text"] = std::string(u8"批量调用 ") + toolName + std::string(u8":共 ") + std::to_string(ids.size()) + std::string(u8" 台,成功 ") + std::to_string(okCount) + std::string(u8" 台,失败 ") + - std::to_string(failCount) + std::string(u8" 台。") + failLines; + std::to_string(failCount) + std::string(u8" 台") + + (skipCount > 0 + ? std::string(u8",超时跳过 ") + std::to_string(skipCount) + std::string(u8" 台") + : std::string()) + + std::string(u8"。") + failLines; content.append(item); result["content"] = content; result["isError"] = false; @@ -5163,6 +5830,9 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too if (toolName == "operate_window") return BuildOperateWindow(id, args, parent); if (toolName == "control_service") return BuildControlService(id, args, parent); if (toolName == "power_action") return BuildPowerAction(id, args, parent); + if (toolName == "host_set_remark") return BuildHostSetRemark(id, args, parent); + if (toolName == "host_set_watch_level") return BuildHostSetWatchLevel(id, args, parent); + if (toolName == "search_file") return BuildSearchFile(id, args, parent); return BuildError(id, -32602, "Unknown tool: " + (toolName.empty() ? std::string("(empty)") : toolName)); @@ -5596,6 +6266,19 @@ CMcpServer::~CMcpServer() { bool CMcpServer::Start(const std::string& bind, int port) { if (m_running.load()) return true; // 已在运行 + // ===== 传输层加固(A1)===== + // httplib 默认:请求体不限长(SIZE_MAX)、读写超时各 5s、线程池 max(8, 核数-1)。 + // 1) 请求体上限 2 MB:本服务只收 JSON-RPC 参数(文件内容走子连接分块,不进 HTTP body), + // 2 MB 足够 chat_send(4 KB)/remote_clipboard 文本,又能挡住超大 body 打爆内存。 + // 2) 读超时 15s:经 frp 隧道上传参数时单次 recv 不至于 5s 就被掐断。 + // 3) 写超时 60s:get_screenshot 的大图 base64 或慢链路下,5s 会把半个响应写断。 + // 4) 线程池显式 32:chat_wait(最长 55s)/批量只读会长时间占线程,默认 8~15 个不够; + // 每个线程约 1 MB 栈,32 个约 32 MB,可接受。 + m_server.set_payload_max_length(2 * 1024 * 1024); + m_server.set_read_timeout(15, 0); + m_server.set_write_timeout(60, 0); + m_server.new_task_queue = []() { return new httplib::ThreadPool(32); }; + m_thread = std::thread([this, bind, port]() { m_server.listen(bind, port); }); @@ -5957,20 +6640,38 @@ bool CMcpServer::TakePreviewResponse(uint64_t device_id, uint16_t reqId, const B bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len) { std::string path; bool listDrives = true; + bool searchFile = false; { std::lock_guard lk(m_PendingMutex); auto it = m_Pending.find(device_id); if (it == m_Pending.end()) return true; // 已超时清理 → 调用方 CancelIO 收尾 path = it->second.path; - listDrives = path.empty() || path == "." || path == "/" || path == "\\"; - if (listDrives) { - it->second.data.assign(buf, buf + len); - it->second.done = true; - m_PendingCv.notify_one(); - return true; // 只列盘 → 调用方用完即关 + if (it->second.tool == "search_file") { + // B2:path 里装的是 [根目录 \0][模式 \0](含 NUL,不能用 C 字符串接口处理)。 + searchFile = true; + it->second.subCtx = subCtx; // 超时停搜 / 收尾要用 + } else { + listDrives = path.empty() || path == "." || path == "/" || path == "\\"; + if (listDrives) { + it->second.data.assign(buf, buf + len); + it->second.done = true; + m_PendingCv.notify_one(); + return true; // 只列盘 → 调用方用完即关 + } } } + if (searchFile) { + // 文件搜索:子链接已就绪,下发 COMMAND_SEARCH_FILE + FILESEARCH 结构体。 + // 与 MFC 文件管理器 OnBtnSearch 的打包方式一致(命令字节后紧跟整个结构体)。 + std::vector pkt; + pkt.reserve(1 + path.size()); + pkt.push_back((BYTE)COMMAND_SEARCH_FILE); + pkt.insert(pkt.end(), path.begin(), path.end()); + subCtx->Send2Client(pkt.data(), (ULONG)pkt.size()); + return false; // 保持子链接,等 N 个结果包 + FINISH + } + // 列目录:锁外下发 COMMAND_LIST_FILES + path,子链接保持,等 TOKEN_FILE_LIST。 // path 已在 BuildListFiles 按客户端 ANSI 转好(OnDriveList 无需再转),结尾 '\0' // 与 FileManagerDlg 的 PacketSize=len+2 一致。 @@ -5983,6 +6684,85 @@ bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* bu return false; // 继续等 TOKEN_FILE_LIST,调用方不 CancelIO } +// ===== B2:search_file ===== + +namespace { +// 收集上限:单次搜索最多记住 5000 条 / 4 MB 原始包,超过就让客户端停搜。 +// 这是保护服务端内存(整盘搜索能命中几十万条),不是业务上限。 +const size_t kSearchMaxRecords = 5000; +const size_t kSearchMaxBytes = 4 * 1024 * 1024; +} + +bool CMcpServer::OnSearchFileRecords(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len) { + bool needStop = false; + { + std::lock_guard lk(m_PendingMutex); + auto it = m_Pending.find(device_id); + if (it == m_Pending.end() || it->second.tool != "search_file") return false; + PendingRequest& p = it->second; + // 身份校验:只认登记过的那条子连接。旧搜索(已放弃)的尾包一律不受理, + // 由调用方原地丢弃——但调用方绝不能因此关连接(见 2015RemoteDlg.cpp 的注释)。 + if (p.subCtx != subCtx) return false; + + if (p.searchRecords.size() >= kSearchMaxRecords || + p.searchBytes + len > kSearchMaxBytes) { + p.searchTruncated = true; + if (!p.searchStopSent) { p.searchStopSent = true; needStop = true; } + } else { + p.searchRecords.emplace_back(buf, buf + len); + p.searchBytes += len; + } + } + if (needStop && subCtx) { + BYTE stop = (BYTE)COMMAND_FILES_SEARCH_STOP; + subCtx->Send2Client(&stop, 1); + } + return true; // 命中挂起 → 本包由 MCP 消费(不论是否因超限被丢弃) +} + +void CMcpServer::FinishSearchFile(uint64_t device_id, context* subCtx) { + std::lock_guard lk(m_PendingMutex); + auto it = m_Pending.find(device_id); + if (it == m_Pending.end() || it->second.tool != "search_file") return; + if (it->second.subCtx != subCtx) return; // 别的子连接的 FINISH,与当前搜索无关 + it->second.searchFinished = true; + m_PendingCv.notify_all(); +} + +bool CMcpServer::WaitSearchFile(uint64_t device_id, std::vector>& records, + bool& finished, bool& truncated, context*& subCtx, int timeoutMs) { + std::unique_lock lk(m_PendingMutex); + auto it = m_Pending.find(device_id); + if (it == m_Pending.end() || it->second.tool != "search_file") return false; + + m_PendingCv.wait_for(lk, std::chrono::milliseconds(timeoutMs), + [&] { return it->second.searchFinished; }); + + records.swap(it->second.searchRecords); + it->second.searchRecords.clear(); + it->second.searchBytes = 0; + finished = it->second.searchFinished; + truncated = it->second.searchTruncated; + subCtx = it->second.subCtx; + return true; +} + +void CMcpServer::StopSearchFile(uint64_t device_id) { + context* subCtx = nullptr; + { + std::lock_guard lk(m_PendingMutex); + auto it = m_Pending.find(device_id); + if (it == m_Pending.end() || it->second.tool != "search_file") return; + if (it->second.searchStopSent) return; + it->second.searchStopSent = true; + subCtx = it->second.subCtx; + } + if (subCtx) { + BYTE stop = (BYTE)COMMAND_FILES_SEARCH_STOP; + subCtx->Send2Client(&stop, 1); + } +} + // ===== P3:list_registry 扩展 ===== bool CMcpServer::OnRegeditReady(uint64_t device_id, context* subCtx) { diff --git a/server/2015Remote/McpServer.h b/server/2015Remote/McpServer.h index bfa98e8..68cdaa3 100644 --- a/server/2015Remote/McpServer.h +++ b/server/2015Remote/McpServer.h @@ -104,6 +104,31 @@ public: // 等 TOKEN_FILE_LIST(调用方不关子链接)。 bool OnDriveList(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len); + // ===== B2:search_file(文件搜索,COMMAND_SEARCH_FILE → N×TOKEN_SEARCH_FILE_LIST + // + TOKEN_SEARCH_FILE_FINISH)===== + // + // 搜索结果是「流式多包」:客户端边搜边发,最后单独发一个 FINISH。子连接在 FINISH + // 之前绝不能关——客户端 CFileManager 的搜索线程持有 this 指针,连接在内搜索未停时 + // 断开会让它访问已析构对象(客户端既有缺陷)。 + // + // MessageHandle(TOKEN_SEARCH_FILE_LIST) 调用:挂起命中且为 search_file 则收下这一包。 + // 超过收集上限时自行下发 COMMAND_FILES_SEARCH_STOP 并标记 truncated。 + // 只接受来自登记过的那条子连接(pending.subCtx)的包:被放弃的旧搜索在设备重开后 + // 仍可能吐尾包,按 context 身份区分,避免把旧搜索的结果/结束信号算到新搜索头上。 + bool OnSearchFileRecords(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len); + + // MessageHandle(TOKEN_SEARCH_FILE_FINISH) 调用:置 finished 并唤醒等待者。 + // 同样只认 pending.subCtx 发来的 FINISH;其它子连接的 FINISH 只关它自己,不影响挂起。 + void FinishSearchFile(uint64_t device_id, context* subCtx); + + // 工具线程:等待搜索结束(或超时)。取走已收集的原始包;finished=false 表示还在搜。 + bool WaitSearchFile(uint64_t device_id, std::vector>& records, + bool& finished, bool& truncated, context*& subCtx, int timeoutMs); + + // 工具线程:让客户端停止搜索(COMMAND_FILES_SEARCH_STOP,客户端会等搜索线程退出 + // 后回 FINISH)。幂等。 + void StopSearchFile(uint64_t device_id); + // ===== P3:list_registry(注册表查询,三阶段:COMMAND_REGEDIT → TOKEN_REGEDIT → // COMMAND_REG_FIND → TOKEN_REG_PATH + TOKEN_REG_KEY)===== @@ -460,6 +485,12 @@ private: // ===== N3:键盘记录(kind = Keylog 时有效)===== std::string keylogBuf; // 累积的原始击键字节(客户端编码,未含 token) bool keylogTruncated = false; // 已到字节上限,后续数据被丢弃 + // ===== B2:search_file(tool == "search_file" 时有效)===== + std::vector> searchRecords; // 已收集的 TOKEN_SEARCH_FILE_LIST 原始包 + size_t searchBytes = 0; + bool searchFinished = false; // 已收到 TOKEN_SEARCH_FILE_FINISH + bool searchStopSent = false; // 已下发 COMMAND_FILES_SEARCH_STOP + bool searchTruncated = false; // 命中收集上限,后续匹配被丢弃 }; std::mutex m_PendingMutex; std::condition_variable m_PendingCv; diff --git a/tools/mcp_smoke.ps1 b/tools/mcp_smoke.ps1 new file mode 100644 index 0000000..386fb90 --- /dev/null +++ b/tools/mcp_smoke.ps1 @@ -0,0 +1,204 @@ +<# + 服务端 MCP 只读冒烟测试。 + + 只调用「不会改变任何状态」的工具(列表/详情类),断言结构化字段齐全、 + 分页字段正确、鉴权与请求体上限生效。可在发布前对着任一台在线主机跑一遍, + 确认 MCP 链路与改动前相比没有回归。 + + 用法: + $env:YAMA_MCP_TOKEN = '' # 与 service 的 McpToken 一致 + powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 + powershell -ExecutionPolicy Bypass -File tools\mcp_smoke.ps1 -Base http://127.0.0.1:6545/mcp + + 参数: + -Base MCP 端点,默认 http://127.0.0.1:6544/mcp(Release 实例) + -Token 覆盖 env YAMA_MCP_TOKEN + -HostId 指定在线主机 id;缺省取 list_online_hosts 的第一台 + -SkipHost 只测服务端本机工具,不触达远程主机(无在线主机时用) + -SearchPath 可选,跑 search_file 测试的搜索根目录(如 C:\Windows\Fonts)。 + 不指定就跳过:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲, + 深目录会栈溢出(Debug 客户端弹 Run-Time Check Failure #2)。 + + 退出码:0 全部通过;1 有失败项。token 不会被打印。 +#> +param( + [string]$Base = 'http://127.0.0.1:6544/mcp', + [string]$Token = $env:YAMA_MCP_TOKEN, + [string]$HostId = '', + [switch]$SkipHost, + [string]$SearchPath = '' +) + +$ErrorActionPreference = 'Stop' +$script:pass = 0 +$script:fail = 0 +$script:failures = @() + +function Check([string]$name, [bool]$ok, [string]$detail = '') { + if ($ok) { + $script:pass++ + Write-Host (" [PASS] " + $name) -ForegroundColor Green + } else { + $script:fail++ + $script:failures += $name + $(if ($detail) { " -- $detail" } else { "" }) + Write-Host (" [FAIL] " + $name + $(if ($detail) { " -- " + $detail } else { "" })) -ForegroundColor Red + } +} + +function Send-Raw([string]$json, [string]$auth) { + # 返回 @{ Status = ; Body = };非 2xx 不抛异常。 + $bytes = [System.Text.Encoding]::UTF8.GetBytes($json) + $headers = @{} + if ($auth) { $headers['Authorization'] = 'Bearer ' + $auth } + try { + $resp = Invoke-WebRequest -Uri $Base -Method Post -Body $bytes ` + -ContentType 'application/json' -Headers $headers -TimeoutSec 180 -UseBasicParsing + return @{ Status = [int]$resp.StatusCode; Body = $resp.Content } + } catch { + $r = $_.Exception.Response + if ($r) { return @{ Status = [int]$r.StatusCode; Body = '' } } + return @{ Status = 0; Body = $_.Exception.Message } + } +} + +function Rpc([string]$method, $params, [string]$toolName, $toolArgs) { + # tools/call 用 toolName+args,其余方法用 method+params。 + if ($toolName) { + $payload = @{ jsonrpc = '2.0'; id = 1; method = 'tools/call'; + params = @{ name = $toolName; arguments = $toolArgs } } + } else { + $payload = @{ jsonrpc = '2.0'; id = 1; method = $method; params = $params } + } + $json = $payload | ConvertTo-Json -Depth 12 -Compress + $raw = Send-Raw $json $Token + if ($raw.Status -ne 200) { throw "HTTP $($raw.Status) calling $method$toolName" } + return ($raw.Body | ConvertFrom-Json) +} + +function HasPaging($obj) { + if ($null -eq $obj) { return $false } + foreach ($k in @('total', 'totalAll', 'offset', 'limit', 'hasMore')) { + if (-not ($obj.PSObject.Properties.Name -contains $k)) { return $false } + } + return $true +} + +Write-Host "MCP smoke test -> $Base" +if (-not $Token) { + Write-Host "缺少 token:请设置环境变量 YAMA_MCP_TOKEN 或传 -Token。" -ForegroundColor Red + exit 1 +} + +# ===== 1. 传输层 ===== +Write-Host "`n[1] 传输层" +$bad = Send-Raw '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}' 'wrong-token-for-smoke-test' +Check '未授权 token 返回 401' ($bad.Status -eq 401) ("status=" + $bad.Status) + +$big = '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_online_hosts","arguments":{"pad":"' + + ('x' * (2 * 1024 * 1024 + 1024)) + '"}}}' +$o = Send-Raw $big $Token +Check '请求体超过 2 MB 返回 413' ($o.Status -eq 413) ("status=" + $o.Status) + +# ===== 2. 协议层 ===== +Write-Host "`n[2] 协议层" +$init = Rpc 'initialize' @{ protocolVersion = '2025-06-18'; capabilities = @{}; clientInfo = @{ name = 'smoke'; version = '1' } } $null $null +Check 'initialize 返回 serverInfo' ($null -ne $init.result.serverInfo) + +$tl = Rpc 'tools/list' @{} $null $null +$tools = @($tl.result.tools) +Check 'tools/list 至少 40 个工具' ($tools.Count -ge 40) ("count=" + $tools.Count) +$annotated = @($tools | Where-Object { + $a = $_.annotations + $a -and ($a.PSObject.Properties.Name -contains 'readOnlyHint') -and + ($a.PSObject.Properties.Name -contains 'destructiveHint') -and + ($a.PSObject.Properties.Name -contains 'idempotentHint') -and + ($a.PSObject.Properties.Name -contains 'openWorldHint') +}) +Check '每个工具都带 annotations 四元组' ($annotated.Count -eq $tools.Count) ("annotated=" + $annotated.Count + "/" + $tools.Count) +$ro = @($tools | Where-Object { $_.annotations.readOnlyHint -eq $true }) +Check '存在只读工具且无只读工具被标为破坏性' ($ro.Count -gt 0 -and + (@($ro | Where-Object { $_.annotations.destructiveHint -eq $true }).Count -eq 0)) ("readOnly=" + $ro.Count) + +# ===== 3. 服务端本机只读工具 ===== +Write-Host "`n[3] 服务端本机工具" +$online = Rpc '' $null 'list_online_hosts' @{ limit = 100 } +$sc = $online.result.structuredContent +Check 'list_online_hosts 带分页字段' (HasPaging $sc) +Check 'list_online_hosts 每条都有 id/online' (@($sc.hosts | Where-Object { -not $_.id -or $_.online -ne $true }).Count -eq 0) + +$all = Rpc '' $null 'list_all_hosts' @{ limit = 5 } +Check 'list_all_hosts 带分页字段' (HasPaging $all.result.structuredContent) + +$found = Rpc '' $null 'search_hosts' @{ query = ''; limit = 5 } +Check 'search_hosts 正常返回' ($found.error -eq $null -and (HasPaging $found.result.structuredContent)) + +$audit = Rpc '' $null 'get_audit_log' @{ limit = 5 } +Check 'get_audit_log 正常返回' ($audit.error -eq $null) + +if (-not $HostId) { + $first = @($sc.hosts)[0] + if ($first) { $HostId = [string]$first.id } +} +if (-not $HostId) { + Write-Host "`n 没有在线主机,跳过主机类工具。" -ForegroundColor Yellow + $SkipHost = $true +} + +# ===== 4. 主机只读工具 ===== +if (-not $SkipHost) { + Write-Host "`n[4] 主机工具 (id=$HostId)" + + $det = Rpc '' $null 'get_host_detail' @{ id = $HostId } + $h = $det.result.structuredContent.host + Check 'get_host_detail id 回显正确' (([string]$h.id) -eq $HostId) + Check 'get_host_detail 含 os/version/online' ($h.os -and $h.version -and ($null -ne $h.online)) + + $procs = Rpc '' $null 'list_processes' @{ id = $HostId; limit = 3 } + $ps = $procs.result.structuredContent + Check 'list_processes 分页字段' (HasPaging $ps) + Check 'list_processes 条数不超过 limit' (@($ps.processes).Count -le 3) + Check 'list_processes 总数为正' ([int]$ps.total -gt 0) + + $wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 } + Check 'list_windows 正常返回' ($wins.error -eq $null -and (HasPaging $wins.result.structuredContent)) + + $drv = Rpc '' $null 'list_files' @{ id = $HostId } + $ds = $drv.result.structuredContent + Check 'list_files 无 path 时返回驱动器列表' (@($ds.drives).Count -gt 0 -and (HasPaging $ds)) + + $drive = '' + if (@($ds.drives).Count -gt 0) { $drive = [string](@($ds.drives)[0].drive) } + if ($drive) { + $dir = Rpc '' $null 'list_files' @{ id = $HostId; path = $drive; limit = 5 } + Check ("list_files 目录列举 (" + $drive + ")") ($dir.error -eq $null -and (HasPaging $dir.result.structuredContent)) + + # search_file:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,深目录会栈溢出 + # (Debug 客户端弹 Run-Time Check Failure #2 并挂住搜索线程)。所以默认不跑, + # 需要时用 -SearchPath 指定一个中浅层目录(如 C:\Windows\Fonts)。 + if ($SearchPath) { + $search = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe'; limit = 3; timeout_ms = 5000 } + $ss = $search.result.structuredContent + if ($search.error) { + Check 'search_file 正常返回' $false $search.error.message + } else { + Check 'search_file 带 finished/truncated 字段' (($null -ne $ss.finished) -and ($null -ne $ss.truncated)) + Check 'search_file 命中项字段完整' (@($ss.files | Where-Object { -not $_.path -or $null -eq $_.size }).Count -eq 0) + } + } else { + Write-Host " 未指定 -SearchPath,跳过 search_file 测试(深目录会触发客户端已知的 MAX_PATH 栈溢出)。" -ForegroundColor Yellow + } + } + + # 批量入口:一台真实主机 + 一台不存在的主机,验证 results 汇总 + $batch = Rpc '' $null 'list_processes' @{ ids = @($HostId, '999999999999999'); limit = 1 } + $bs = $batch.result.structuredContent + Check '批量 results 覆盖全部 id' (@($bs.results).Count -eq 2 -and [int]$bs.succeeded -eq 1 -and [int]$bs.failed -eq 1) +} + +# ===== 汇总 ===== +Write-Host ("`n通过 " + $script:pass + " 项,失败 " + $script:fail + " 项。") -ForegroundColor $(if ($script:fail -eq 0) { 'Green' } else { 'Red' }) +if ($script:fail -gt 0) { + $script:failures | ForEach-Object { Write-Host (" - " + $_) -ForegroundColor Red } + exit 1 +} +exit 0