3 Commits
Author SHA1 Message Date
yuanyuanxiang dcb5ae25c6 Fix: Paginate get_activity_history results
The tool was the only list-type tool without pagination. The client keeps
ACTIVITY_HISTORY_MAX=500 records and Dump() prepends the in-progress window,
so a single call returned up to 501 lines of "[time] [title] duration" --
enough to blow up the caller's context, especially since titles carry
personal browsing history.

Records come back newest-first (m_records uses push_front and the current
window is prepended), so the standard limit/offset window applies directly:
offset=0 is the most recent page, no need to read total first and count
backwards. That ordering is now stated in the tool description so the model
can rely on it.

- inputSchema: BuildGetHostDetailInputSchema -> BuildPagedHostListInputSchema
  (adds limit, default 100 / max 1000, and offset)
- outputSchema: append AppendPageOutputProps plus truncated
- implementation: rename the full split to `all`, slice via ResolvePageWindow
  and ApplyPageWindow, write back with WritePageFields
- activityHistory is rebuilt from the window instead of returning the whole
  Dump() text -- otherwise the raw copy would bypass pagination entirely
- 64 KB byte budget (same as get_client_log), trimmed from the end so the
  newest records survive; hasMore is computed as offset+kept < total rather
  than hardcoded true, since a single oversized tail record must not claim
  there is another page

Batch calls need no extra work: the tool is already in IsBatchReadOnlyTool,
and BuildBatchCall forwards limit/offset to each host, so ids + limit means
"the latest N records of every host".

Compiles clean; not yet exercised against a running server (the exe was
locked by the live instance). Verification cases are listed in
docs/Mcp_Test_Report_2026-10-29.md section 8.
2026-10-29 21:37:02 +01:00
yuanyuanxianganddeepseek-flash 56a937fabb Fix: Three blocking defects found by the MCP tool survey
The survey in docs/Mcp_Test_Report_2026-10-29.md turned up three P0s, each
of which stopped a whole capability rather than degrading it. Two of them
were the same mistake: the input schema promised something the output
schema then rejected. The third was an output with no size limit, plus a
client that never implemented the command at all.

Batch calls could never succeed. A call carrying ids[] goes through
BuildBatchCall, which returns {tool, total, succeeded, failed, skipped,
results[]}; every tool declares only the single-host shape. The client
validates structuredContent against that declaration, so any batch call
failed with -32602: data must have required property 'host' - the input
schema advertises ids, the output schema kills it. Tools/call cannot fix
this one call at a time, so ApplyBatchOutputSchema runs at the end of
tools/list, next to ApplyToolAnnotations, and rewrites the schema of every
tool in the batch list to {type: object, anyOf: [single, batch]}. Placing
it at the end is what makes it cover all three registration points
(inline, McpMachine, McpChat) and any tool added later. IsBatchReadOnlyTool
moved from McpServer.cpp to McpInternal.cpp for the same reason: the list
is now read by tools/call and tools/list, and the two must not drift.

list_registry failed whenever path was omitted. The root-key branch
returns keys only, while the output schema listed values in required as
well, so the first usage the documentation describes - omit path, get the
five root keys - could not work. values is no longer required and the
schema says it is absent in that branch. The root branch also returns
path: "" now, so both branches carry the same field set and callers need
not branch.

get_client_log was unusable on both platforms, for two unrelated reasons.
Windows returned the whole 1000-line ring buffer, 90,473 characters, over
the client's result limit: fetched, then not deliverable. Linux and macOS
timed out because their clients never handled COMMAND_QUERY_LOG at all -
only client/ClientLogManager.cpp does - so TOKEN_REPORT_LOG never arrived.
Adding a limit alone would have left Linux broken; fixing the client alone
would have left Windows over the limit.

The server now takes limit (default 200, max 2000) and filter, and reads
backwards from the end: troubleshooting wants the last thing that happened,
not the first line after boot. A 64 KB byte budget sits under the line
count, because one line can be a stack dump; when the final line alone
exceeds it, the tail is returned and truncated says so. Responses carry
lines_total, lines_matched, lines_returned and truncated. The timeout
message now names the likely cause and two ways around it instead of
saying only "Timeout waiting for client log".

The POSIX clients get common/ClientLogHandler.h, a counterpart to the
Windows CClientLogManager, and one line each in linux/main.cpp and
macos/main.mm. It must open a sub-connection: MessageHandle's
TOKEN_REPORT_LOG branch takes the first packet and then calls CancelIO on
that connection, so answering on the main connection would close the main
connection and drop the client offline.

Verified against a server built at 21:17:21 with both clients rebuilt. A
batch get_host_detail over the two A6 records returns succeeded=2 with
per-host data; host_list_processes with ids returns 2 of 2, which exercises
the McpMachine registration point rather than the inline one; a mixed
Windows/Linux batch of get_client_log returns 2 of 2. list_registry with
no path returns the five root keys and path ""; with a path it still
returns its values. get_client_log on Windows goes from 1000 lines to 200
with truncated=true, and limit=3 with filter=ConnAuth yields 28 matched and
3 returned. On Ubuntu 24.04 it returns logs at all, and the client's own
log shows Enter ClientLogThread, TOKEN_REPORT_LOG, then Leave about a
second later when the server cancels the connection - paired, no leak.

The connector still caches an old input schema for get_client_log, so
limit and filter are rejected locally until it reconnects; the defaults
already cover the P0, and this is the same cache problem as the
copy_files_c2c.overwrite entry in the report's P1 list.

docs/Mcp_Design.md section 18 records the implementation and the reasoning;
section 7 of the test report carries the verification table.

Co-Authored-By: deepseek-flash
2026-10-29 21:22:43 +01:00
yuanyuanxianganddeepseek-flash dc4fd792f6 Feature: Implement the Linux screen preview response
The Linux client now answers COMMAND_SCREEN_PREVIEW_REQ, so a host with
an X11 desktop gets a thumbnail when it is double-clicked in the online
list, a frame in the list's Preview column, and an image from the MCP
get_screenshot tool. Previously only Windows clients advertised the
capability and Linux hosts showed "预览不可用" after a four second wait.

The client does not encode JPEG. Stock desktops ship libjpeg.so.8 whose
struct layout is the distribution's ABI (JPEG_LIB_VERSION 80), while the
in-tree jpeglib.h is libjpeg-turbo 3.1.1 (62), and libturbojpeg is not
installed by default; dlopening the system library against that header
fails with "Wrong JPEG library version: library is 80, caller expects
62". Instead the client sends raw pixels in a new screen preview format,
SCREEN_PREVIEW_FMT_BGRX: top-down rows of B,G,R,X with no row padding,
already scaled to the requested width. The server re-encodes to JPEG at
the single ingress point, so the preview popup, the list thumbnail cache
and the MCP tool keep consuming JPEG only.

Capture follows the path ScreenHandler already uses: root window copied
into an offscreen pixmap with an IncludeInferiors GC, then XGetImage,
which avoids BadMatch under compositing window managers. The X11 type
declarations and the dlopen loader moved out of ScreenHandler.h into
linux/X11Loader.h so both users share one dlsym table. The full-size
image is never materialized: a box filter reads straight from the
XImage rows (honouring bytes_per_line) into the output buffer, scales to
maxWidth without upscaling, and clamps the height to 1080 so a portrait
4K desktop cannot produce a 26 MB packet. Rows and columns come out
even, which they are for JPEG anyway.

The capability bit is now honest about the runtime. LOGIN_INFOR grows
DefaultCaps()/SetCaps(), and the client recomputes the bits before every
login and re-login: CLIENT_CAP_SCREEN_PREVIEW is set only when DISPLAY is
present and the X server actually opens. A headless host therefore gets
-32005 "Host does not support screen preview" from MCP instead of a
timeout, and a host whose session appears after boot picks it up on the
next reconnect. Requests are handled on a detached worker thread behind
a single-flight guard (matching the Windows client), so a slow XGetImage
never stalls the receive thread and a burst of requests degrades to "no
preview" rather than queueing. If the worker thread cannot be created,
the guard is released again, so one failure cannot leave every later
request rejected as busy until the client restarts.

The MCP design note claimed the capability was declared by Windows only,
and the get_screenshot tool description said the same; both now say what
the code does (Windows always, Linux when a display is reachable).

Server side, NormalizeScreenPreviewPacket runs in MessageHandle before
the MCP handoff and the PostMessage to the UI thread. It validates that
width/height are within the values the server itself can ask for and
that bytes equals width*height*4, converts with a stack Gdiplus::Bitmap
over the packet's own pixels (no copy, and no DEBUG_NEW trouble), and
rewrites the header to JPEG. The encoder output is read back by seeking
the stream rather than GlobalSize, so the packet carries no heap-block
padding after the EOI marker. Malformed packets are dropped; failure
statuses pass through untouched so the existing code can report them.

Tested against a Debug server with the WSL Ubuntu 24.04 build as the
client. get_screenshot returned valid JPEGs at max_width 480 (480x142,
1.7 KB) and 1920 (1920x570, 17.9 KB), repeatably; the list showed a
thumbnail for the GUI client and N/A for a second copy started without
DISPLAY, which also answered -32005. The box filter and the BGRX to JPEG
conversion were checked separately with quadrant fixtures: the browser
over the synthetic B,G,R,X buffer recovers red/green/blue/white in the
right channels and the downscale averages, handles non-integer ratios
and row padding, and rejects 24bpp and upscaling. The captured frames
come out black under WSLg because Xwayland keeps no root pixmap there;
that is the compositor, not this code, and Xorg sessions capture
normally.

Co-Authored-By: deepseek-flash
2026-10-29 18:12:15 +01:00
18 changed files with 1652 additions and 305 deletions

No files matched your search

+58
View File
@@ -0,0 +1,58 @@
#pragma once
#include <cstring>
#include <mutex>
#include <string>
#include <vector>
#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<std::mutex> lock(m_sendMutex);
std::string logs = Logger::getInstance().DumpMemoryLogFrom(m_sentIdx);
std::vector<BYTE> 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;
};
+26 -5
View File
@@ -465,13 +465,17 @@ static_assert(sizeof(ConnAuthAck) == 256, "ConnAuthAck must be exactly 256 by
// 屏幕预览:服务端按双击在线主机触发,向客户端要一张缩略图(JPEG),与浮窗一起显示。
// 服务端依 ctx 最近心跳 Ping + RES_RESOLUTION 决定 maxWidth/quality 后下发;客户端
// 主屏抓图 → 等比缩放 → JPEG 编码 → 回响应。format 字段 v1 锁 0=JPEG,预留 PNG/WebP。
// 主屏抓图 → 等比缩放 → JPEG 编码 → 回响应。
//
// format 字段:v1 只有 JPEG(0);Windows 客户端走这条路(GDI+ 编码)。Linux 客户端
// 没有可依赖的 JPEG 编码库,改为回 BGRX(3) 原始像素,由服务端在 IO 线程统一编码成
// JPEG——下游(浮窗/列表缩略图/MCP get_screenshot)因此只认 JPEG 一种格式。
#pragma pack(push, 1)
struct ScreenPreviewReq {
uint8_t cmd; // = COMMAND_SCREEN_PREVIEW_REQ
uint16_t reqId; // 请求序号,用于丢弃过期响应
uint16_t maxWidth; // 服务端期望的目标宽度(客户端等比缩放,不强制)
uint8_t jpegQuality; // 1..100
uint8_t jpegQuality; // 1..100(BGRX 客户端不编码,服务端按自己的档位重编)
uint16_t reserved;
}; // 总 8 字节
@@ -486,6 +490,9 @@ enum ScreenPreviewFormat {
SCREEN_PREVIEW_FMT_JPEG = 0,
SCREEN_PREVIEW_FMT_PNG = 1, // 预留
SCREEN_PREVIEW_FMT_WEBP = 2, // 预留
// 原始像素:自上而下逐行、每像素 4 字节 B,G,R,X(X 填充为 0xFF),无行首对齐填充。
// bytes 必须等于 width*height*4;客户端已缩放到 maxWidth 以内,不再二次缩放。
SCREEN_PREVIEW_FMT_BGRX = 3,
};
struct ScreenPreviewRspHeader {
@@ -1107,9 +1114,15 @@ typedef struct LOGIN_INFOR {
{
memset(this, 0, sizeof(LOGIN_INFOR));
bToken = TOKEN_LOGIN;
// 能力位:声明客户端实际实现了的功能。SCREEN_PREVIEW 只在 Windows 客户端
// 实现(依赖 GDI BitBlt + GDI+ JPEG),Linux/macOS 不声明,避免服务端发请求
// 后等 4s 超时显示"预览不可用"。
SetCaps(DefaultCaps());
}
// 本平台的默认能力位:声明客户端实际实现了的功能。
// SCREEN_PREVIEW 依赖抓屏:Windows 恒为真(GDI BitBlt + GDI+ JPEG);Linux 要等
// 运行时确认有可截图的 X11 会话,所以不在这里声明,由 main.cpp 探测后用
// SetCaps(DefaultCaps() | CLIENT_CAP_SCREEN_PREVIEW) 追加。
static unsigned int DefaultCaps()
{
unsigned int caps = CLIENT_CAP_V2 | CLIENT_CAP_UTF8;
#ifdef _WIN32
caps |= CLIENT_CAP_SCREEN_PREVIEW;
@@ -1119,6 +1132,14 @@ typedef struct LOGIN_INFOR {
// macOS 暂未接线(无全局主连接句柄),不声明——服务端就不会为它空等回执。
caps |= CLIENT_CAP_C2C_RECV_ACK;
#endif
return caps;
}
// 覆写能力位。服务端只从 moduleVersion 的 "版本-XXXX" 后缀解析能力位
// (2015RemoteDlg.cpp AddList),因此改能力位必须重写该字段;
// LOGIN_INFOR 是与服务端共享的定长结构,不能再加成员来携带它。
void SetCaps(unsigned int caps)
{
sprintf_s(moduleVersion, "%s-%04X", DLL_VERSION, caps);
}
LOGIN_INFOR& Speed(unsigned long speed)
+116
View File
@@ -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,116 @@ 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` 缓存问题同源。
## 19. 增补(2026-10-29:`get_activity_history` 分页,P2-1)
### 19.1 问题
`get_activity_history` 是全仓库唯一没有分页的列表类工具。客户端 `ACTIVITY_HISTORY_MAX`
= 500,`Dump()` 还会把进行中的当前窗口作为第 1 条,所以一次返回上限约 501 条——实测
正是 501 条。每行含窗口标题(可能很长),501 行直接把上下文冲爆;而报告里那份数据还
混着大量个人浏览、求职、签证页面,属于「不该被整包塞进模型上下文」的典型。
### 19.2 顺序:为什么可以直接用 `limit`/`offset`
`ActivityHistory::Loop()` 用 `m_records.push_front(...)` 维护,`Dump()` 又把当前进行中
的窗口拼在最前面——**返回顺序天然是「新在前」**。于是 `offset=0` 就是最近 `limit` 条,
不必像「新在后」的日志那样先取一次 `total` 再倒算 `offset=total-limit`。这条顺序不是
本次新增的约定,是客户端本来就这样,写进描述是为了让模型敢直接用 `offset=0`。
### 19.3 实现
- `inputSchema` 从 `BuildGetHostDetailInputSchema()` 换成 `BuildPagedHostListInputSchema()`
(`{ id | ids }` + `limit`/`offset`,与 `list_processes` / `list_windows` 同一套);
- `outputSchema` 追加 `AppendPageOutputProps()` 与 `truncated`;
- 实现里把原来的 `records` 改名 `all`(全量拆行结果),再 `ResolvePageWindow` +
`ApplyPageWindow` 切出 `records`,`WritePageFields` 写回 `total`/`totalAll`/`offset`/
`limit`/`hasMore`;
- **`activityHistory` 必须按窗口重建**:它原来是 `Dump()` 的整包原文,如果原样返回,
501 行的正文照样进上下文,等于没分页。现在它是窗口内 `records` 的按行拼接,语义仍是
「同一份数据的纯文本形态」;
- 再加 64 KB 字节预算(与 `get_client_log` 同口径),从窗口**末尾**裁——保留最新的那些。
裁断时 `truncated=true`;`hasMore` 按 `offset + returned < total` 算,而不是一律置 true
(末尾单条自己超预算时不该再报还有下一页)。调用方用 `offset + returned` 继续取;
- 至少保留 1 条:单条超预算时若不保底,`returned=0` 会让调用方在同一个 `offset` 上原地
打转。窗口标题达到 64 KB 几乎不可能,这是纯兜底。
### 19.4 批量
`get_activity_history` 在 `IsBatchReadOnlyTool` 名单里,`BuildBatchCall` 会把 `ids` 摘掉、
其余参数原样透传给单机调用,所以 `ids` + `limit` 等于「每台各取最近 N 条」,不需要额外
处理。P0-1 的 `anyOf:[单机, 批量]` 包装也自动覆盖新增字段。
### 19.5 未做
- 没有 `filter`(按窗口标题子串)。报告没提,且客户端标题是 UTF-8、过滤要按字节子串做,
与 `get_client_log` 的 `filter` 不同源,等有实际需求再加。
- 没有 `since`(按时间起点取)。记录里的时间是 `[YYYY-MM-DD HH:MM:SS]` 文本前缀,做时间
过滤得先解析每行;当前 `limit/offset` 已够用。
+2 -2
View File
@@ -275,7 +275,7 @@ Web 是长连接,子链接可长驻;MCP 是**一次性 request/response**。
- 复用 MFC 预览的 RTT/FRP 自适应参数挑选 `ChooseScreenPreviewParams` + `SendScreenPreviewRequest`,不重复实现 `GetTargetQualityLevel`。
- **可选 `max_width` 参数**:缺省/0 沿用缩略图档位(最大 1024,4K 源屏高档 1280);`max_width`>0 覆盖宽度并钳制到客户端上限 `[64,1920]`(客户端 `CaptureAndEncodePreview` 硬钳制),供 AI 视觉/OCR 场景请求接近原分辨率(1080p 源屏传 1920 即原分辨率,4K 源屏最多 1920)。`jpegQuality` 仍沿用档位自适应值。
- **请求关联**:`ScreenPreviewReq.reqId` 提供关联;MCP 用独立 16 位 reqId 发生器(`NextPreviewReqId`,跳过 0)+ `SetPendingReqId` 登记期望值,`TakePreviewResponse` 只接受「挂起命中 + reqId 一致」的响应,过期/他途(MFC 预览并发)响应原样回落到 MFC 路径。
- 客户端能力位 `CLIENT_CAP_SCREEN_PREVIEW`(0x0004,仅 Windows 客户端声明):非 Windows 主机返回 `-32005`「不支持」。
- 客户端能力位 `CLIENT_CAP_SCREEN_PREVIEW`(0x0004):Windows 客户端恒声明;Linux 客户端在登录时探测到可用 X11 桌面才声明(无 `DISPLAY` 的服务器不声明)。未声明的主机返回 `-32005`「不支持」。
- 返回结构:`content[0] = {type:"image", data: base64(JPEG), mimeType:"image/jpeg"}` + `structuredContent.image = {mimeType,width,height,bytes}`(元数据,不含 base64,避免二次膨胀)。
**`list_files`(文件链路,一次性子链接,模式 A′)**:
@@ -303,7 +303,7 @@ Web 是长连接,子链接可长驻;MCP 是**一次性 request/response**。
**验收 / 实机验证点(待构建后执行)**:
- MFC 双击文件管理弹框仍正常(回归点);MFC 双击预览缩略图仍正常(回归点)。
- MCP `get_screenshot` 返回 JPEG(base64 + 元数据),Windows 主机正常;非 Windows 主机(或未声明 `CLIENT_CAP_SCREEN_PREVIEW`)返回 `-32005`。
- MCP `get_screenshot` 返回 JPEG(base64 + 元数据),Windows 主机正常;带 X11 桌面的 Linux 主机同样正常(客户端回 BGRA,服务端转 JPEG);未声明 `CLIENT_CAP_SCREEN_PREVIEW` 的主机返回 `-32005`。
- MCP `list_files`(无 `path`)返回 `drives[]`;`list_files(path="C:\\")` 返回 `files[]`(含目录/文件/大小/mtime),中文文件名无乱码;条目 >500 时截断为 500。
- 错误路径:缺 `id`/非数字 `id` → `-32602`;未知/离线主机 → `-32002`;同 host 并发 → `-32003`;发送失败 → `-32004`;超时 → `-32001`。
+389
View File
@@ -0,0 +1,389 @@
# 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);P2-1(`get_activity_history` 无分页)已于同日修复,见 §8(实现说明在 `docs/Mcp_Design.md` §19)
## 1. 测试范围与约定
按约定划分操作边界:
| 用途 | 主机 | 说明 |
|---|---|---|
| 写操作 | `DESKTOP-A55C0OI`(`3441387693643366974`,Win10 VM,MDLL)<br>`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 条**~~ **已修复,见 §8** | 直接冲爆上下文,且内容含大量个人浏览/求职/签证页面 |
| 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 是同一个缓存问题。
## 8. 附带修复:`get_activity_history` 分页(P2-1)
P2-1 与 P0-3 是同一类病——**列表类工具没有裁剪,把上下文当垃圾桶**。既然 `get_client_log`
的分页/预算机制已经就位,这里直接复用同一套。实现细节见 `docs/Mcp_Design.md` §19。
| 改动 | 内容 |
|---|---|
| `inputSchema` | 由 `BuildGetHostDetailInputSchema()`(只有 `{id\|ids}`)换成 `BuildPagedHostListInputSchema()`,补 `limit`(默认 100、上限 1000)与 `offset` |
| `outputSchema` | 追加 `AppendPageOutputProps()`(`total`/`totalAll`/`offset`/`limit`/`hasMore`)与 `truncated` |
| 实现 | 全量拆行结果改名 `all`,再 `ResolvePageWindow` + `ApplyPageWindow` 切出 `records`,`WritePageFields` 回填 |
| `activityHistory` | **按窗口重建**(窗口内 `records` 按行拼接)。原来是 `Dump()` 整包原文,原样返回等于没分页 |
| 字节预算 | 64 KB(与 `get_client_log` 同口径),从窗口末尾裁,保留最新的;裁断时 `truncated=true`,`hasMore` 按 `offset+returned < total` 算 |
| 保底 | 至少留 1 条,避免 `returned=0` 让调用方在同一个 `offset` 上原地打转 |
**顺序语义**:客户端 `ActivityHistory::Loop()` 用 `m_records.push_front(...)`,`Dump()` 又把
进行中的当前窗口拼在最前——返回顺序**天然是「新在前」**。所以 `offset=0` 就是最近 `limit` 条,
不需要先取 `total` 再倒算 offset。这条不是新约定,写进工具描述是为了让模型敢直接用 `offset=0`。
**批量**:本工具在 `IsBatchReadOnlyTool` 名单里,`BuildBatchCall` 摘掉 `ids` 后把其余参数原样
透传,所以 `ids` + `limit` 就是「每台各取最近 N 条」,P0-1 的 `anyOf` 包装自动覆盖新字段。
**验证(服务端 21:34 构建,待重启后实测)**:
| 用例 | 期望 |
|---|---|
| 默认参数(不带 `limit`) | `records` 100 条、`total≈501`、`hasMore=true`,结果体积从约 90 KB 降到约 12 KB |
| `limit=5` | 5 条,且是最新的 5 条(第 1 条时间最晚) |
| `offset=500` | 1 条(尾部最老的那条),`hasMore=false` |
| `ids` + `limit=3` | `succeeded=全数`,每台各 3 条,`results[].data.total` 各自独立 |
| `activityHistory` 与 `records` | 行数与内容一致(不再是整包原文) |
| `offset` 超过 `total` | `records=[]`、`returned=0`、`hasMore=false`,不报错 |
+1
View File
@@ -26,6 +26,7 @@ include_directories(../compress)
# 添加可执行文件
set(SOURCES
main.cpp
ScreenPreview.cpp # 屏幕预览(缩略图)抓屏,见 ScreenPreview.h
../client/Buffer.cpp
../client/IOCPClient.cpp
../client/TlsChannelLinux.cpp # Linux 客户端单向 TLS(OpenSSL),见 client/TlsChannel.h
+2
View File
@@ -5,6 +5,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
## 功能特性
- **远程桌面** - 实时屏幕截图传输,支持鼠标/键盘控制,支持多种压缩算法
- **屏幕预览** - 服务端双击主机弹缩略图、在线列表缩略图、MCP `get_screenshot`
- **远程终端** - 基于 PTY 的交互式 Shell
- **文件管理** - 远程文件浏览、上传、下载
- **进程管理** - 查看和管理远程进程
@@ -25,6 +26,7 @@ SimpleRemoter 的 Linux 客户端,支持远程桌面、远程终端、文件
| 系统信息采集 | main.cpp | `LoginServer.cpp` | ✅ 完整 |
| 守护进程 | daemonize() | Windows 服务 | ✅ 完整 |
| 剪贴板同步 | `ClipboardHandler.h` | `ScreenManager.cpp` | ✅ 服务端↔Linux |
| 屏幕预览(缩略图) | `ScreenPreview.cpp` | `client/ScreenPreview.cpp` | ✅ 完整(X11 抓屏 → 缩放 → 原始 BGRA 上报,由服务端统一编码 JPEG;双击预览、列表缩略图、MCP `get_screenshot` 均可用。无 `DISPLAY` 时不声明能力位,服务端不会发请求) |
| V2 文件传输 | `FileTransferV2.h` | `file_upload.h` | ✅ 服务端↔Linux(含 MCP `upload_file`/`download_file`:发送完成包带流式 SHA-256,路径不存在/无权限回 `TOKEN_DOWNLOAD_ERROR`) |
| C2C 文件接收 | `FileTransferV2.h` | `file_upload.h` | ✅ Windows/MCP → Linux(目标目录由服务端 `dst_dir` 指定,落盘后回执) |
| 配置持久化 | `LinuxConfig` | INI 文件 | ✅ 完整 |
+1 -264
View File
@@ -5,6 +5,7 @@
#include "ClipboardHandler.h"
#include "common/FileTransferV2.h"
#include "X264Encoder.h"
#include "X11Loader.h"
#include <dlfcn.h>
#include <sys/stat.h>
#include <thread>
@@ -50,68 +51,6 @@ struct MSG64_LNX {
};
#pragma pack(pop)
// X11 类型前向声明(避免 #include <X11/Xlib.h>)
typedef struct _XDisplay Display;
typedef unsigned long XID;
typedef XID Window;
typedef XID Drawable;
typedef XID Pixmap;
typedef struct _XGC *GC;
struct XImage {
int width, height;
int xoffset;
int format;
char *data;
int byte_order;
int bitmap_unit;
int bitmap_bit_order;
int bitmap_pad;
int depth;
int bytes_per_line;
int bits_per_pixel;
unsigned long red_mask;
unsigned long green_mask;
unsigned long blue_mask;
// 后续字段省略,XDestroyImage 通过函数指针释放
void *obdata;
struct funcs {
void *p[8]; // create_image, destroy_image, ...
} f;
};
// X11 错误处理(防止 BadMatch 等错误导致进程退出)
static int x11_error_handler(Display* dpy, void* evt)
{
// 忽略所有 X11 错误,由调用方检查返回值
return 0;
}
// XCreateGC 需要的 XGCValues 结构体(布局与 Xlib 一致)
struct XGCValues_LNX {
int function;
unsigned long plane_mask;
unsigned long foreground;
unsigned long background;
int line_width;
int line_style;
int cap_style;
int join_style;
int fill_style;
int fill_rule;
int arc_mode;
unsigned long tile; // Pixmap = XID
unsigned long stipple; // Pixmap = XID
int ts_x_origin;
int ts_y_origin;
unsigned long font; // Font = XID
int subwindow_mode;
};
// X11 GC 常量
#define GCSubwindowMode (1L<<15)
#define IncludeInferiors 1
// ============== 屏幕算法常量 ==============
// 常量定义已移至 commands.h: ALGORITHM_GRAY, ALGORITHM_DIFF, ALGORITHM_H264, ALGORITHM_RGB565
@@ -390,208 +329,6 @@ static unsigned long VKtoKeySym(unsigned int vk)
}
}
// XFixes cursor image structure (for cursor type detection)
struct XFixesCursorImage {
short x, y;
unsigned short width, height;
unsigned short xhot, yhot;
unsigned long cursor_serial;
unsigned long* pixels;
// Atom cursor_name; // Only in XFixes 2.0+
};
// X11 函数指针类型
typedef Display* (*fn_XOpenDisplay)(const char*);
typedef int (*fn_XCloseDisplay)(Display*);
typedef XImage* (*fn_XGetImage)(Display*, Drawable, int, int, unsigned int, unsigned int, unsigned long, int);
typedef int (*fn_XDestroyImage)(XImage*);
typedef int (*fn_XSetErrorHandler)(int (*)(Display*, void*));
typedef Pixmap (*fn_XCreatePixmap)(Display*, Drawable, unsigned int, unsigned int, unsigned int);
typedef int (*fn_XFreePixmap)(Display*, Pixmap);
typedef GC (*fn_XCreateGC)(Display*, Drawable, unsigned long, void*);
typedef int (*fn_XFreeGC)(Display*, GC);
typedef int (*fn_XCopyArea)(Display*, Drawable, Drawable, GC, int, int, unsigned int, unsigned int, int, int);
typedef int (*fn_XDefaultDepth)(Display*, int);
typedef int (*fn_XSync)(Display*, int);
typedef unsigned long (*fn_XKeysymToKeycode)(Display*, unsigned long);
typedef int (*fn_XFlush)(Display*);
typedef int (*fn_XClearArea)(Display*, Window, int, int, unsigned int, unsigned int, int);
typedef int (*fn_XQueryPointer)(Display*, Window, Window*, Window*, int*, int*, int*, int*, unsigned int*);
typedef int (*fn_XFree)(void*);
// XTest 扩展函数指针类型(用于模拟鼠标/键盘输入)
typedef int (*fn_XTestFakeMotionEvent)(Display*, int, int, int, unsigned long);
typedef int (*fn_XTestFakeButtonEvent)(Display*, unsigned int, int, unsigned long);
typedef int (*fn_XTestFakeKeyEvent)(Display*, unsigned int, int, unsigned long);
// XFixes 扩展函数指针类型(用于光标类型检测)
typedef int (*fn_XFixesQueryExtension)(Display*, int*, int*);
typedef XFixesCursorImage* (*fn_XFixesGetCursorImage)(Display*);
// X11 动态加载包装
class X11Loader
{
public:
fn_XOpenDisplay pXOpenDisplay;
fn_XCloseDisplay pXCloseDisplay;
fn_XGetImage pXGetImage;
fn_XDestroyImage pXDestroyImage;
// Xlib 宏的替代:通过偏移读取 Display 内部结构
// 这些函数通过 dlsym 获取
typedef int (*fn_XDefaultScreen)(Display*);
typedef int (*fn_XDisplayWidth)(Display*, int);
typedef int (*fn_XDisplayHeight)(Display*, int);
typedef Window (*fn_XRootWindow)(Display*, int);
fn_XDefaultScreen pXDefaultScreen;
fn_XDisplayWidth pXDisplayWidth;
fn_XDisplayHeight pXDisplayHeight;
fn_XRootWindow pXRootWindow;
// Pixmap 相关(解决合成窗口管理器下 XGetImage BadMatch 问题)
fn_XSetErrorHandler pXSetErrorHandler;
fn_XCreatePixmap pXCreatePixmap;
fn_XFreePixmap pXFreePixmap;
fn_XCreateGC pXCreateGC;
fn_XFreeGC pXFreeGC;
fn_XCopyArea pXCopyArea;
fn_XDefaultDepth pXDefaultDepth;
fn_XSync pXSync;
fn_XKeysymToKeycode pXKeysymToKeycode;
fn_XFlush pXFlush;
fn_XClearArea pXClearArea;
fn_XQueryPointer pXQueryPointer;
fn_XFree pXFree;
// XTest 扩展(用于模拟输入)
fn_XTestFakeMotionEvent pXTestFakeMotionEvent;
fn_XTestFakeButtonEvent pXTestFakeButtonEvent;
fn_XTestFakeKeyEvent pXTestFakeKeyEvent;
// XFixes 扩展(用于光标类型检测)
fn_XFixesQueryExtension pXFixesQueryExtension;
fn_XFixesGetCursorImage pXFixesGetCursorImage;
X11Loader() : m_handle(nullptr), m_xtst_handle(nullptr), m_xfixes_handle(nullptr)
{
pXOpenDisplay = nullptr;
pXCloseDisplay = nullptr;
pXGetImage = nullptr;
pXDestroyImage = nullptr;
pXDefaultScreen = nullptr;
pXDisplayWidth = nullptr;
pXDisplayHeight = nullptr;
pXRootWindow = nullptr;
pXSetErrorHandler = nullptr;
pXCreatePixmap = nullptr;
pXFreePixmap = nullptr;
pXCreateGC = nullptr;
pXFreeGC = nullptr;
pXCopyArea = nullptr;
pXDefaultDepth = nullptr;
pXSync = nullptr;
pXKeysymToKeycode = nullptr;
pXFlush = nullptr;
pXClearArea = nullptr;
pXQueryPointer = nullptr;
pXFree = nullptr;
pXTestFakeMotionEvent = nullptr;
pXTestFakeButtonEvent = nullptr;
pXTestFakeKeyEvent = nullptr;
pXFixesQueryExtension = nullptr;
pXFixesGetCursorImage = nullptr;
}
bool Load()
{
m_handle = dlopen("libX11.so.6", RTLD_LAZY);
if (!m_handle) m_handle = dlopen("libX11.so", RTLD_LAZY);
if (!m_handle) return false;
pXOpenDisplay = (fn_XOpenDisplay)dlsym(m_handle, "XOpenDisplay");
pXCloseDisplay = (fn_XCloseDisplay)dlsym(m_handle, "XCloseDisplay");
pXGetImage = (fn_XGetImage)dlsym(m_handle, "XGetImage");
pXDestroyImage = (fn_XDestroyImage)dlsym(m_handle, "XDestroyImage");
pXDefaultScreen = (fn_XDefaultScreen)dlsym(m_handle, "XDefaultScreen");
pXDisplayWidth = (fn_XDisplayWidth)dlsym(m_handle, "XDisplayWidth");
pXDisplayHeight = (fn_XDisplayHeight)dlsym(m_handle, "XDisplayHeight");
pXRootWindow = (fn_XRootWindow)dlsym(m_handle, "XRootWindow");
// Pixmap 相关函数
pXSetErrorHandler = (fn_XSetErrorHandler)dlsym(m_handle, "XSetErrorHandler");
pXCreatePixmap = (fn_XCreatePixmap)dlsym(m_handle, "XCreatePixmap");
pXFreePixmap = (fn_XFreePixmap)dlsym(m_handle, "XFreePixmap");
pXCreateGC = (fn_XCreateGC)dlsym(m_handle, "XCreateGC");
pXFreeGC = (fn_XFreeGC)dlsym(m_handle, "XFreeGC");
pXCopyArea = (fn_XCopyArea)dlsym(m_handle, "XCopyArea");
pXDefaultDepth = (fn_XDefaultDepth)dlsym(m_handle, "XDefaultDepth");
pXSync = (fn_XSync)dlsym(m_handle, "XSync");
pXKeysymToKeycode = (fn_XKeysymToKeycode)dlsym(m_handle, "XKeysymToKeycode");
pXFlush = (fn_XFlush)dlsym(m_handle, "XFlush");
pXClearArea = (fn_XClearArea)dlsym(m_handle, "XClearArea");
pXQueryPointer = (fn_XQueryPointer)dlsym(m_handle, "XQueryPointer");
pXFree = (fn_XFree)dlsym(m_handle, "XFree");
// 加载 XTest 扩展库(用于模拟鼠标/键盘输入)
m_xtst_handle = dlopen("libXtst.so.6", RTLD_LAZY);
if (!m_xtst_handle) m_xtst_handle = dlopen("libXtst.so", RTLD_LAZY);
if (m_xtst_handle) {
pXTestFakeMotionEvent = (fn_XTestFakeMotionEvent)dlsym(m_xtst_handle, "XTestFakeMotionEvent");
pXTestFakeButtonEvent = (fn_XTestFakeButtonEvent)dlsym(m_xtst_handle, "XTestFakeButtonEvent");
pXTestFakeKeyEvent = (fn_XTestFakeKeyEvent)dlsym(m_xtst_handle, "XTestFakeKeyEvent");
}
// 加载 XFixes 扩展库(用于光标类型检测)
m_xfixes_handle = dlopen("libXfixes.so.3", RTLD_LAZY);
if (!m_xfixes_handle) m_xfixes_handle = dlopen("libXfixes.so", RTLD_LAZY);
if (m_xfixes_handle) {
pXFixesQueryExtension = (fn_XFixesQueryExtension)dlsym(m_xfixes_handle, "XFixesQueryExtension");
pXFixesGetCursorImage = (fn_XFixesGetCursorImage)dlsym(m_xfixes_handle, "XFixesGetCursorImage");
}
// 基本 X11 函数必须全部存在;XTest/XFixes 函数可选
return pXOpenDisplay && pXCloseDisplay && pXGetImage && pXDestroyImage &&
pXDefaultScreen && pXDisplayWidth && pXDisplayHeight && pXRootWindow &&
pXSetErrorHandler && pXCreatePixmap && pXFreePixmap &&
pXCreateGC && pXFreeGC && pXCopyArea && pXDefaultDepth && pXSync &&
pXKeysymToKeycode && pXFlush;
}
// 检查 XTest 扩展是否可用
bool HasXTest() const
{
return pXTestFakeMotionEvent && pXTestFakeButtonEvent && pXTestFakeKeyEvent;
}
// 检查 XFixes 扩展是否可用
bool HasXFixes() const
{
return pXFixesGetCursorImage != nullptr;
}
~X11Loader()
{
if (m_xfixes_handle) {
dlclose(m_xfixes_handle);
m_xfixes_handle = nullptr;
}
if (m_xtst_handle) {
dlclose(m_xtst_handle);
m_xtst_handle = nullptr;
}
if (m_handle) {
dlclose(m_handle);
m_handle = nullptr;
}
}
private:
void* m_handle;
void* m_xtst_handle;
void* m_xfixes_handle;
};
class ScreenHandler : public IOCPManager
{
public:
+185
View File
@@ -0,0 +1,185 @@
#include "ScreenPreview.h"
#include "X11Loader.h"
#include "common/commands.h"
#include <cstdlib>
#include <cstring>
namespace {
// 一次抓屏独占一条 X 连接:Xlib 的 Display 不是线程安全的,预览在工作线程里跑,
// 不能复用 ScreenHandler 的那条连接;用完即关,避免长驻连接占着 X server 资源。
struct XSession {
X11Loader x11;
Display* dpy = nullptr;
bool Open()
{
// 没有 DISPLAY 必然是纯命令行/无桌面环境,连库都不必加载
const char* display = getenv("DISPLAY");
if (display == nullptr || display[0] == '\0') {
return false;
}
if (!x11.Load() || !x11.CanCapture()) {
return false;
}
// 与 ScreenHandler 一致:忽略 X11 协议错误,由返回值判断失败
x11.pXSetErrorHandler(x11_error_handler);
dpy = x11.pXOpenDisplay(display);
return dpy != nullptr;
}
~XSession()
{
if (dpy) {
x11.pXCloseDisplay(dpy);
}
}
};
// 盒式滤波缩放,直接从 XImage 读到目标缓冲,不保留整屏中间副本。
// 返回 false 表示像素格式不受支持(非 32bpp)。
bool DownscaleBox(const XImage* img, int tw, int th, std::vector<unsigned char>& out)
{
if (img == nullptr || img->bits_per_pixel != 32 || img->bytes_per_line <= 0) {
return false;
}
const int sw = img->width;
const int sh = img->height;
if (sw <= 0 || sh <= 0 || tw <= 0 || th <= 0 || tw > sw || th > sh) {
return false;
}
out.resize((size_t)tw * th * 4);
const unsigned char* base = (const unsigned char*)img->data;
for (int dy = 0; dy < th; dy++) {
// 目标行覆盖的源行区间 [sy0, sy1),区间非空因为 th <= sh
int sy0 = (int)((long long)dy * sh / th);
int sy1 = (int)((long long)(dy + 1) * sh / th);
if (sy1 <= sy0) sy1 = sy0 + 1;
unsigned char* dst = out.data() + (size_t)dy * tw * 4;
for (int dx = 0; dx < tw; dx++) {
int sx0 = (int)((long long)dx * sw / tw);
int sx1 = (int)((long long)(dx + 1) * sw / tw);
if (sx1 <= sx0) sx1 = sx0 + 1;
unsigned int sb = 0, sg = 0, sr = 0;
unsigned int count = 0;
for (int sy = sy0; sy < sy1; sy++) {
// X11 ZPixmap 32bpp 每像素 4 字节,字节序为 B,G,R,X(X 不用);
// 行尾可能有对齐填充,必须按 bytes_per_line 定位
const unsigned char* row = base + (size_t)sy * img->bytes_per_line;
for (int sx = sx0; sx < sx1; sx++) {
const unsigned char* px = row + (size_t)sx * 4;
sb += px[0];
sg += px[1];
sr += px[2];
count++;
}
}
dst[0] = (unsigned char)(sb / count);
dst[1] = (unsigned char)(sg / count);
dst[2] = (unsigned char)(sr / count);
dst[3] = 0xFF;
dst += 4;
}
}
return true;
}
} // namespace
bool ScreenPreview::IsAvailable()
{
XSession session;
if (!session.Open()) {
return false;
}
int screen = session.x11.pXDefaultScreen(session.dpy);
return session.x11.pXDisplayWidth(session.dpy, screen) > 0 &&
session.x11.pXDisplayHeight(session.dpy, screen) > 0;
}
int ScreenPreview::Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH)
{
outW = 0;
outH = 0;
out.clear();
// 与 Windows 端一致:上限防滥用,下限防止 1 像素宽的退化请求
if (maxWidth < 64) maxWidth = 64;
if (maxWidth > 1920) maxWidth = 1920;
XSession session;
if (!session.Open()) {
return SCREEN_PREVIEW_NOT_SUPPORTED;
}
X11Loader& x11 = session.x11;
Display* dpy = session.dpy;
int screen = x11.pXDefaultScreen(dpy);
int sw = x11.pXDisplayWidth(dpy, screen);
int sh = x11.pXDisplayHeight(dpy, screen);
if (sw <= 0 || sh <= 0) {
return SCREEN_PREVIEW_CAPTURE_FAILED;
}
// 等比缩放到 maxWidth 以内(不放大);再把高度限制在 1080,避免竖屏 4K 这类
// 极端宽高比把 BGRX 包撑到几十 MB(服务端只按宽度提要求,不管比例)
int tw = sw, th = sh;
if (tw > maxWidth) {
th = (int)((long long)sh * maxWidth / sw);
tw = maxWidth;
}
if (th > 1080) {
tw = (int)((long long)tw * 1080 / th);
th = 1080;
}
// 宽高取偶数,便于 JPEG 编码
tw &= ~1;
th &= ~1;
if (tw < 2) tw = 2;
if (th < 2) th = 2;
if (tw > sw) tw = sw;
if (th > sh) th = sh;
// root → 离屏 Pixmap → XGetImage:绕开合成窗口管理器下的 BadMatch
Window root = x11.pXRootWindow(dpy, screen);
int depth = x11.pXDefaultDepth(dpy, screen);
Pixmap pixmap = x11.pXCreatePixmap(dpy, root, (unsigned int)sw, (unsigned int)sh, (unsigned int)depth);
if (pixmap == 0) {
return SCREEN_PREVIEW_CAPTURE_FAILED;
}
XGCValues_LNX gcv;
memset(&gcv, 0, sizeof(gcv));
gcv.subwindow_mode = IncludeInferiors; // 连同子窗口内容一起抓
GC gc = x11.pXCreateGC(dpy, root, GCSubwindowMode, &gcv);
if (gc == nullptr) {
x11.pXFreePixmap(dpy, pixmap);
return SCREEN_PREVIEW_CAPTURE_FAILED;
}
int result = SCREEN_PREVIEW_CAPTURE_FAILED;
x11.pXCopyArea(dpy, root, pixmap, gc, 0, 0, (unsigned int)sw, (unsigned int)sh, 0, 0);
x11.pXSync(dpy, 0); // 等待拷贝完成
// AllPlanes = ~0UL, ZPixmap = 2
XImage* img = x11.pXGetImage(dpy, pixmap, 0, 0, (unsigned int)sw, (unsigned int)sh, ~0UL, 2);
if (img != nullptr) {
if (DownscaleBox(img, tw, th, out)) {
outW = tw;
outH = th;
result = SCREEN_PREVIEW_OK;
} else {
out.clear();
}
x11.pXDestroyImage(img);
}
x11.pXFreeGC(dpy, gc);
x11.pXFreePixmap(dpy, pixmap);
return result;
}
+24
View File
@@ -0,0 +1,24 @@
#pragma once
// 屏幕预览(COMMAND_SCREEN_PREVIEW_REQ)—— Linux 端一次性抓屏
//
// 与 Windows 端 client/ScreenPreview.h 对应,区别只有一处:Linux 没有可依赖的
// JPEG 编码库(桌面版默认只带 libjpeg.so.8,其结构体布局随发行版 ABI 变化,
// 不适合 dlopen 后手搓),所以这里只做 抓屏 → 等比缩放 → BGRA 原始像素,
// 由服务端在 IO 线程统一编码成 JPEG(见 2015RemoteDlg.cpp 的预览包规范化)。
//
// 抓屏路径与 ScreenHandler 相同:root window → 离屏 Pixmap(XCopyArea,
// IncludeInferiors)→ XGetImage,规避合成窗口管理器下的 BadMatch。
#include <vector>
#include <cstdint>
class ScreenPreview
{
public:
// 本机当前能否截图(X11 库可加载 + 能打开 display + 主屏尺寸有效)。
// 服务端按 CLIENT_CAP_SCREEN_PREVIEW 决定要不要下发预览请求,能力位就取自它。
static bool IsAvailable();
// 抓主屏并等比缩放到 maxWidth 以内(不放大、高不超过 1080),返回 ScreenPreviewStatus。
// out 为自上而下逐行、每像素 B,G,R,X 四字节(X=0xFF),无行首填充。
static int Capture(int maxWidth, std::vector<unsigned char>& out, int& outW, int& outH);
};
+279
View File
@@ -0,0 +1,279 @@
#pragma once
// X11 运行时加载(编译期不依赖 X11 开发包,运行时 dlopen libX11.so)
//
// 从 ScreenHandler.h 抽出:远程桌面(ScreenHandler)和屏幕预览(ScreenPreview)
// 都要抓屏,共用这套类型定义与加载器,避免两份 dlsym 表各自漂移。
#include <dlfcn.h>
// X11 类型前向声明(避免 #include <X11/Xlib.h>)
typedef struct _XDisplay Display;
typedef unsigned long XID;
typedef XID Window;
typedef XID Drawable;
typedef XID Pixmap;
typedef struct _XGC *GC;
struct XImage {
int width, height;
int xoffset;
int format;
char *data;
int byte_order;
int bitmap_unit;
int bitmap_bit_order;
int bitmap_pad;
int depth;
int bytes_per_line;
int bits_per_pixel;
unsigned long red_mask;
unsigned long green_mask;
unsigned long blue_mask;
// 后续字段省略,XDestroyImage 通过函数指针释放
void *obdata;
struct funcs {
void *p[8]; // create_image, destroy_image, ...
} f;
};
// X11 错误处理(防止 BadMatch 等错误导致进程退出)
static inline int x11_error_handler(Display* dpy, void* evt)
{
// 忽略所有 X11 错误,由调用方检查返回值
return 0;
}
// XCreateGC 需要的 XGCValues 结构体(布局与 Xlib 一致)
struct XGCValues_LNX {
int function;
unsigned long plane_mask;
unsigned long foreground;
unsigned long background;
int line_width;
int line_style;
int cap_style;
int join_style;
int fill_style;
int fill_rule;
int arc_mode;
unsigned long tile; // Pixmap = XID
unsigned long stipple; // Pixmap = XID
int ts_x_origin;
int ts_y_origin;
unsigned long font; // Font = XID
int subwindow_mode;
};
// X11 GC 常量
#define GCSubwindowMode (1L<<15)
#define IncludeInferiors 1
// XFixes cursor image structure (for cursor type detection)
struct XFixesCursorImage {
short x, y;
unsigned short width, height;
unsigned short xhot, yhot;
unsigned long cursor_serial;
unsigned long* pixels;
// Atom cursor_name; // Only in XFixes 2.0+
};
// X11 函数指针类型
typedef Display* (*fn_XOpenDisplay)(const char*);
typedef int (*fn_XCloseDisplay)(Display*);
typedef XImage* (*fn_XGetImage)(Display*, Drawable, int, int, unsigned int, unsigned int, unsigned long, int);
typedef int (*fn_XDestroyImage)(XImage*);
typedef int (*fn_XSetErrorHandler)(int (*)(Display*, void*));
typedef Pixmap (*fn_XCreatePixmap)(Display*, Drawable, unsigned int, unsigned int, unsigned int);
typedef int (*fn_XFreePixmap)(Display*, Pixmap);
typedef GC (*fn_XCreateGC)(Display*, Drawable, unsigned long, void*);
typedef int (*fn_XFreeGC)(Display*, GC);
typedef int (*fn_XCopyArea)(Display*, Drawable, Drawable, GC, int, int, unsigned int, unsigned int, int, int);
typedef int (*fn_XDefaultDepth)(Display*, int);
typedef int (*fn_XSync)(Display*, int);
typedef unsigned long (*fn_XKeysymToKeycode)(Display*, unsigned long);
typedef int (*fn_XFlush)(Display*);
typedef int (*fn_XClearArea)(Display*, Window, int, int, unsigned int, unsigned int, int);
typedef int (*fn_XQueryPointer)(Display*, Window, Window*, Window*, int*, int*, int*, int*, unsigned int*);
typedef int (*fn_XFree)(void*);
// XTest 扩展函数指针类型(用于模拟鼠标/键盘输入)
typedef int (*fn_XTestFakeMotionEvent)(Display*, int, int, int, unsigned long);
typedef int (*fn_XTestFakeButtonEvent)(Display*, unsigned int, int, unsigned long);
typedef int (*fn_XTestFakeKeyEvent)(Display*, unsigned int, int, unsigned long);
// XFixes 扩展函数指针类型(用于光标类型检测)
typedef int (*fn_XFixesQueryExtension)(Display*, int*, int*);
typedef XFixesCursorImage* (*fn_XFixesGetCursorImage)(Display*);
// X11 动态加载包装
class X11Loader
{
public:
fn_XOpenDisplay pXOpenDisplay;
fn_XCloseDisplay pXCloseDisplay;
fn_XGetImage pXGetImage;
fn_XDestroyImage pXDestroyImage;
// Xlib 宏的替代:通过偏移读取 Display 内部结构
// 这些函数通过 dlsym 获取
typedef int (*fn_XDefaultScreen)(Display*);
typedef int (*fn_XDisplayWidth)(Display*, int);
typedef int (*fn_XDisplayHeight)(Display*, int);
typedef Window (*fn_XRootWindow)(Display*, int);
fn_XDefaultScreen pXDefaultScreen;
fn_XDisplayWidth pXDisplayWidth;
fn_XDisplayHeight pXDisplayHeight;
fn_XRootWindow pXRootWindow;
// Pixmap 相关(解决合成窗口管理器下 XGetImage BadMatch 问题)
fn_XSetErrorHandler pXSetErrorHandler;
fn_XCreatePixmap pXCreatePixmap;
fn_XFreePixmap pXFreePixmap;
fn_XCreateGC pXCreateGC;
fn_XFreeGC pXFreeGC;
fn_XCopyArea pXCopyArea;
fn_XDefaultDepth pXDefaultDepth;
fn_XSync pXSync;
fn_XKeysymToKeycode pXKeysymToKeycode;
fn_XFlush pXFlush;
fn_XClearArea pXClearArea;
fn_XQueryPointer pXQueryPointer;
fn_XFree pXFree;
// XTest 扩展(用于模拟输入)
fn_XTestFakeMotionEvent pXTestFakeMotionEvent;
fn_XTestFakeButtonEvent pXTestFakeButtonEvent;
fn_XTestFakeKeyEvent pXTestFakeKeyEvent;
// XFixes 扩展(用于光标类型检测)
fn_XFixesQueryExtension pXFixesQueryExtension;
fn_XFixesGetCursorImage pXFixesGetCursorImage;
X11Loader() : m_handle(nullptr), m_xtst_handle(nullptr), m_xfixes_handle(nullptr)
{
pXOpenDisplay = nullptr;
pXCloseDisplay = nullptr;
pXGetImage = nullptr;
pXDestroyImage = nullptr;
pXDefaultScreen = nullptr;
pXDisplayWidth = nullptr;
pXDisplayHeight = nullptr;
pXRootWindow = nullptr;
pXSetErrorHandler = nullptr;
pXCreatePixmap = nullptr;
pXFreePixmap = nullptr;
pXCreateGC = nullptr;
pXFreeGC = nullptr;
pXCopyArea = nullptr;
pXDefaultDepth = nullptr;
pXSync = nullptr;
pXKeysymToKeycode = nullptr;
pXFlush = nullptr;
pXClearArea = nullptr;
pXQueryPointer = nullptr;
pXFree = nullptr;
pXTestFakeMotionEvent = nullptr;
pXTestFakeButtonEvent = nullptr;
pXTestFakeKeyEvent = nullptr;
pXFixesQueryExtension = nullptr;
pXFixesGetCursorImage = nullptr;
}
bool Load()
{
m_handle = dlopen("libX11.so.6", RTLD_LAZY);
if (!m_handle) m_handle = dlopen("libX11.so", RTLD_LAZY);
if (!m_handle) return false;
pXOpenDisplay = (fn_XOpenDisplay)dlsym(m_handle, "XOpenDisplay");
pXCloseDisplay = (fn_XCloseDisplay)dlsym(m_handle, "XCloseDisplay");
pXGetImage = (fn_XGetImage)dlsym(m_handle, "XGetImage");
pXDestroyImage = (fn_XDestroyImage)dlsym(m_handle, "XDestroyImage");
pXDefaultScreen = (fn_XDefaultScreen)dlsym(m_handle, "XDefaultScreen");
pXDisplayWidth = (fn_XDisplayWidth)dlsym(m_handle, "XDisplayWidth");
pXDisplayHeight = (fn_XDisplayHeight)dlsym(m_handle, "XDisplayHeight");
pXRootWindow = (fn_XRootWindow)dlsym(m_handle, "XRootWindow");
// Pixmap 相关函数
pXSetErrorHandler = (fn_XSetErrorHandler)dlsym(m_handle, "XSetErrorHandler");
pXCreatePixmap = (fn_XCreatePixmap)dlsym(m_handle, "XCreatePixmap");
pXFreePixmap = (fn_XFreePixmap)dlsym(m_handle, "XFreePixmap");
pXCreateGC = (fn_XCreateGC)dlsym(m_handle, "XCreateGC");
pXFreeGC = (fn_XFreeGC)dlsym(m_handle, "XFreeGC");
pXCopyArea = (fn_XCopyArea)dlsym(m_handle, "XCopyArea");
pXDefaultDepth = (fn_XDefaultDepth)dlsym(m_handle, "XDefaultDepth");
pXSync = (fn_XSync)dlsym(m_handle, "XSync");
pXKeysymToKeycode = (fn_XKeysymToKeycode)dlsym(m_handle, "XKeysymToKeycode");
pXFlush = (fn_XFlush)dlsym(m_handle, "XFlush");
pXClearArea = (fn_XClearArea)dlsym(m_handle, "XClearArea");
pXQueryPointer = (fn_XQueryPointer)dlsym(m_handle, "XQueryPointer");
pXFree = (fn_XFree)dlsym(m_handle, "XFree");
// 加载 XTest 扩展库(用于模拟鼠标/键盘输入)
m_xtst_handle = dlopen("libXtst.so.6", RTLD_LAZY);
if (!m_xtst_handle) m_xtst_handle = dlopen("libXtst.so", RTLD_LAZY);
if (m_xtst_handle) {
pXTestFakeMotionEvent = (fn_XTestFakeMotionEvent)dlsym(m_xtst_handle, "XTestFakeMotionEvent");
pXTestFakeButtonEvent = (fn_XTestFakeButtonEvent)dlsym(m_xtst_handle, "XTestFakeButtonEvent");
pXTestFakeKeyEvent = (fn_XTestFakeKeyEvent)dlsym(m_xtst_handle, "XTestFakeKeyEvent");
}
// 加载 XFixes 扩展库(用于光标类型检测)
m_xfixes_handle = dlopen("libXfixes.so.3", RTLD_LAZY);
if (!m_xfixes_handle) m_xfixes_handle = dlopen("libXfixes.so", RTLD_LAZY);
if (m_xfixes_handle) {
pXFixesQueryExtension = (fn_XFixesQueryExtension)dlsym(m_xfixes_handle, "XFixesQueryExtension");
pXFixesGetCursorImage = (fn_XFixesGetCursorImage)dlsym(m_xfixes_handle, "XFixesGetCursorImage");
}
// 基本 X11 函数必须全部存在;XTest/XFixes 函数可选
return pXOpenDisplay && pXCloseDisplay && pXGetImage && pXDestroyImage &&
pXDefaultScreen && pXDisplayWidth && pXDisplayHeight && pXRootWindow &&
pXSetErrorHandler && pXCreatePixmap && pXFreePixmap &&
pXCreateGC && pXFreeGC && pXCopyArea && pXDefaultDepth && pXSync &&
pXKeysymToKeycode && pXFlush;
}
// 只关心抓屏的那一小部分函数是否齐备(ScreenPreview 用,不要求 XTest/XFixes)
bool CanCapture() const
{
return pXOpenDisplay && pXCloseDisplay && pXGetImage && pXDestroyImage &&
pXDefaultScreen && pXDisplayWidth && pXDisplayHeight && pXRootWindow &&
pXSetErrorHandler && pXCreatePixmap && pXFreePixmap &&
pXCreateGC && pXFreeGC && pXCopyArea && pXDefaultDepth && pXSync;
}
// 检查 XTest 扩展是否可用
bool HasXTest() const
{
return pXTestFakeMotionEvent && pXTestFakeButtonEvent && pXTestFakeKeyEvent;
}
// 检查 XFixes 扩展是否可用
bool HasXFixes() const
{
return pXFixesGetCursorImage != nullptr;
}
~X11Loader()
{
if (m_xfixes_handle) {
dlclose(m_xfixes_handle);
m_xfixes_handle = nullptr;
}
if (m_xtst_handle) {
dlclose(m_xtst_handle);
m_xtst_handle = nullptr;
}
if (m_handle) {
dlclose(m_handle);
m_handle = nullptr;
}
}
private:
void* m_handle;
void* m_xtst_handle;
void* m_xfixes_handle;
};
+98
View File
@@ -26,7 +26,9 @@
#include <map>
#include <cmath>
#include "ScreenHandler.h"
#include "ScreenPreview.h"
#include "SystemManager.h"
#include "common/ClientLogHandler.h"
#include "common/FileManager.h"
#include "ClipboardHandler.h"
#include "common/FileTransferV2.h"
@@ -382,6 +384,66 @@ void* FileManagerThread(void* /*param*/)
return NULL;
}
// 日志上报(对应 Windows 端 CClientLogManager):子连接建立即发首包全量。
// 服务端取走首包后会关掉这条子连接,所以这里发完就等连接断开即可。
void* ClientLogThread(void* /*param*/)
{
RunSubConnThread<ClientLogHandler>(
"ClientLogThread",
[](IOCPClient* c) { return std::unique_ptr<ClientLogHandler>(new ClientLogHandler(c)); },
[](IOCPClient* c, ClientLogHandler*) {
Mprintf(">>> ClientLogThread [%p] Send: TOKEN_REPORT_LOG\n", c);
});
return NULL;
}
// ============== 屏幕预览(对应 Windows 端 COMMAND_SCREEN_PREVIEW_REQ) ==============
// 同一时刻只跑一个抓屏任务:列表缩略图是周期性刷新,服务端还可能重发/并发请求,
// 多余的直接丢弃,让服务端 4s 超时后按"预览不可用"降级(与 Windows 端限流一致)。
static std::atomic<int> g_previewInFlight(0);
static void ScreenPreviewThread(ScreenPreviewReq req)
{
// 抓屏/缩放全程可能在几十毫秒量级,跑在独立线程里,不阻塞接收线程
struct InFlightGuard {
~InFlightGuard() { g_previewInFlight.fetch_sub(1); }
} guard;
std::vector<unsigned char> pixels;
int w = 0, h = 0;
int st = ScreenPreview::Capture(req.maxWidth, pixels, w, h);
bool ok = (st == SCREEN_PREVIEW_OK) && !pixels.empty();
if (!ok) {
pixels.clear();
}
uint32_t bytes = ok ? (uint32_t)pixels.size() : 0;
std::vector<char> pkt(sizeof(ScreenPreviewRspHeader) + bytes);
ScreenPreviewRspHeader* hdr = (ScreenPreviewRspHeader*)pkt.data();
memset(hdr, 0, sizeof(*hdr));
hdr->token = TOKEN_SCREEN_PREVIEW_RSP;
hdr->reqId = req.reqId;
hdr->status = (uint8_t)st;
// 成功时发原始 BGRA,由服务端统一编码成 JPEG(Linux 无可靠的 JPEG 编码库);
// 失败时 format 无意义,填 JPEG 保持包头合法
hdr->format = ok ? SCREEN_PREVIEW_FMT_BGRX : SCREEN_PREVIEW_FMT_JPEG;
hdr->width = (uint16_t)w;
hdr->height = (uint16_t)h;
hdr->bytes = bytes;
if (ok) {
memcpy(pkt.data() + sizeof(*hdr), pixels.data(), pixels.size());
}
// Send2Server 内部持锁,可在工作线程调用;进程退出/断线时不再回包
if (g_pMainClient && g_pMainClient->IsConnected() && g_bExit == S_CLIENT_NORMAL) {
g_pMainClient->Send2Server(pkt.data(), (int)pkt.size());
}
if (!ok) {
Mprintf("** Screen preview capture failed: status=%d ***\n", st);
}
}
// 信任锚已落盘/已删除:热重载 TLS 状态,必要时请求主循环重建连接。
// 只在传输方式真正变化(明文↔TLS)时重连;仅换证书(仍是 TLS)不打断现有会话,
// 新锚从下一条新连接开始生效。
@@ -430,6 +492,27 @@ 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;
memcpy(&req, szBuffer, sizeof(req));
// 抓屏可能耗几十毫秒,必须离开接收线程;超额请求直接丢弃(服务端会超时降级)
if (g_previewInFlight.fetch_add(1) >= 1) {
g_previewInFlight.fetch_sub(1);
return TRUE;
}
try {
std::thread(ScreenPreviewThread, req).detach();
} catch (const std::exception& e) {
// 线程起不来时必须把在途计数还回去,否则后面所有预览请求都会被当成"忙"丢掉
g_previewInFlight.fetch_sub(1);
Mprintf("** Screen preview thread failed: %s ***\n", e.what());
}
} else if (szBuffer[0] == CMD_HEARTBEAT_ACK) {
if (ulLength >= 1 + sizeof(HeartbeatACK)) {
HeartbeatACK* ack = (HeartbeatACK*)(szBuffer + 1);
@@ -1115,6 +1198,18 @@ static void RefreshLoginTls(LOGIN_INFOR& info)
info.szReserved[sizeof(info.szReserved) - 1] = '\0';
}
// 能力位(moduleVersion 的 "-%04X" 后缀)里唯一依赖运行环境的是屏幕预览:
// 只在本机当前真有可抓的 X11 桌面时才声明,无桌面的服务器不该被服务端要求截图。
// 与 RefreshLoginTls 一样只在主线程登录前调用,每次重连都会重新判断。
static void RefreshLoginCaps(LOGIN_INFOR& info)
{
unsigned int caps = LOGIN_INFOR::DefaultCaps();
if (ScreenPreview::IsAvailable()) {
caps |= CLIENT_CAP_SCREEN_PREVIEW;
}
info.SetCaps(caps);
}
// 用法: ./ghost [-d] [IP] [端口]
// -d 后台守护进程模式
// 示例: ./ghost -d 192.168.1.100 6543
@@ -1296,6 +1391,8 @@ int main(int argc, char* argv[])
ClientAuth::OnNewConnection();
// 传输方式可能已被热切换(TLS 启/停),登录上报的 RES_TLS 必须反映本次连接。
RefreshLoginTls(logInfo);
// 屏幕预览能力取决于本机当前是否有可用桌面(daemon 启动时可能还没有 DISPLAY)
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo.Speed(clock() - c));
// 新连接:把 ACK 看门狗喂到当前时间,避免循环刚进来就被误判为超时
@@ -1315,6 +1412,7 @@ int main(int argc, char* argv[])
}
logInfo.szPCName[sizeof(logInfo.szPCName) - 1] = '\0';
RefreshLoginTls(logInfo);
RefreshLoginCaps(logInfo);
ClientObject->SendLoginInfo(logInfo);
Mprintf(">> Resent login info after group change\n");
}
+19
View File
@@ -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<ClientLogHandler>(
"ClientLogworkingThread",
[](IOCPClient* c) { return std::unique_ptr<ClientLogHandler>(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);
+99 -3
View File
@@ -6852,15 +6852,19 @@ VOID CMy2015RemoteDlg::MessageHandle(CONTEXT_OBJECT* ContextObject)
// (IO 线程不接触 UI;clientId 用于循环快照路由到对应窗口)。
// 不用 WPARAM 携带 ID:32 位 Windows 上 WPARAM 是 32 位,会截 64 位 clientID。
if (len < sizeof(ScreenPreviewRspHeader)) break;
// Linux 客户端回的是原始 BGRA,统一在这里转成 JPEG;畸形包直接丢弃
std::vector<BYTE> previewPkt(szBuffer, szBuffer + len);
if (!NormalizeScreenPreviewPacket(previewPkt))
break;
// P2c:MCP 挂起时接管(屏幕预览 = 主连接 RPC,不能 CancelIO)。
// reqId 关联:命中 MCP 的 expectedReqId 才取走,避免误吞 MFC 预览在途响应。
uint64_t previewDevId = ContextObject->GetClientID();
const ScreenPreviewRspHeader* previewHdr = reinterpret_cast<const ScreenPreviewRspHeader*>(szBuffer);
if (McpServer().TakePreviewResponse(previewDevId, previewHdr->reqId, szBuffer, len))
const ScreenPreviewRspHeader* previewHdr = reinterpret_cast<const ScreenPreviewRspHeader*>(previewPkt.data());
if (McpServer().TakePreviewResponse(previewDevId, previewHdr->reqId, previewPkt.data(), (ULONG)previewPkt.size()))
break;
auto* msg = new CMy2015RemoteDlg::PreviewRspMsg{
ContextObject->GetClientID(),
std::vector<BYTE>(szBuffer, szBuffer + len)
std::move(previewPkt)
};
if (!g_2015RemoteDlg->PostMessageA(WM_PREVIEW_RESPONSE, 0, (LPARAM)msg)) {
delete msg;
@@ -9531,6 +9535,98 @@ void CMy2015RemoteDlg::ChooseScreenPreviewParams(context* ctx, WORD& maxWidth, B
jpegQuality = q;
}
namespace {
// GDI+ 的 JPEG 编码器 CLSID(Windows 自带,进程内即可用;与 Bmp2Video 的同名逻辑互不影响)
bool FindJpegEncoderClsid(CLSID& clsid)
{
UINT num = 0, size = 0;
if (Gdiplus::GetImageEncodersSize(&num, &size) != Gdiplus::Ok || size == 0) return false;
std::vector<BYTE> buf(size);
Gdiplus::ImageCodecInfo* info = reinterpret_cast<Gdiplus::ImageCodecInfo*>(buf.data());
if (Gdiplus::GetImageEncoders(num, size, info) != Gdiplus::Ok) return false;
for (UINT i = 0; i < num; ++i) {
if (wcscmp(info[i].MimeType, L"image/jpeg") == 0) {
clsid = info[i].Clsid;
return true;
}
}
return false;
}
} // namespace
// 预览响应规范化:Windows 客户端直接回 JPEG,Linux 客户端没有可靠的 JPEG 编码库,
// 回的是原始 BGRA(SCREEN_PREVIEW_FMT_BGRX)。统一在 IO 线程入口转成 JPEG,下游
// (浮窗 / 列表缩略图 / MCP get_screenshot)就只需要认识 JPEG 一种格式。
// 返回 false 表示这个包畸形、不可用,调用方应直接丢弃。
bool CMy2015RemoteDlg::NormalizeScreenPreviewPacket(std::vector<BYTE>& pkt)
{
if (pkt.size() < sizeof(ScreenPreviewRspHeader)) return false;
ScreenPreviewRspHeader* hdr = reinterpret_cast<ScreenPreviewRspHeader*>(pkt.data());
if (hdr->token != TOKEN_SCREEN_PREVIEW_RSP) return false;
if (hdr->format != SCREEN_PREVIEW_FMT_BGRX) return true; // JPEG / 预留格式:原样放行
// 抓屏失败的响应没有像素可转,原样放行,让下游按 status 报"预览不可用"
if (hdr->status != SCREEN_PREVIEW_OK) return true;
// 尺寸与长度校验:请求侧 maxWidth 已限制在 [64,1920],高度按 16:10 上限放宽到 2160
const int w = hdr->width, h = hdr->height;
if (w < 2 || h < 2 || w > 1920 || h > 2160) return false;
const size_t pixels = (size_t)w * h * 4;
if (hdr->bytes != pixels || pkt.size() < sizeof(*hdr) + pixels) return false;
std::vector<BYTE> jpeg;
{
// Bitmap 直接引用包内像素(不复制),所以编码必须在 pkt 被 resize 之前、且
// 在本作用域内完成析构。用栈对象:本 TU 的 `new` 被 MFC 重定义成 DEBUG_NEW,
// Gdiplus 的 operator new 不接受那种三参形式。
Gdiplus::Bitmap bmp(w, h, w * 4, PixelFormat32bppRGB, pkt.data() + sizeof(*hdr));
if (bmp.GetLastStatus() != Gdiplus::Ok) return false;
CLSID clsid;
if (!FindJpegEncoderClsid(clsid)) return false;
// Linux 端不上报质量(它不编码),这里跟随缩略图默认档 70
Gdiplus::EncoderParameters params;
params.Count = 1;
params.Parameter[0].Guid = Gdiplus::EncoderQuality;
params.Parameter[0].Type = Gdiplus::EncoderParameterValueTypeLong;
params.Parameter[0].NumberOfValues = 1;
ULONG quality = 70;
params.Parameter[0].Value = &quality;
IStream* stream = nullptr;
if (FAILED(::CreateStreamOnHGlobal(NULL, TRUE, &stream))) return false;
if (bmp.Save(stream, &clsid, &params) == Gdiplus::Ok) {
// 取实际写入长度:GlobalSize 按堆块对齐,尾部填充字节不能算进 JPEG
LARGE_INTEGER zero = {};
ULARGE_INTEGER end = {}, start = {};
if (SUCCEEDED(stream->Seek(zero, STREAM_SEEK_END, &end)) &&
end.QuadPart > 0 && end.QuadPart <= 16 * 1024 * 1024 &&
SUCCEEDED(stream->Seek(zero, STREAM_SEEK_SET, &start))) {
jpeg.resize((size_t)end.QuadPart);
ULONG read = 0;
if (FAILED(stream->Read(jpeg.data(), (ULONG)jpeg.size(), &read)) ||
read != jpeg.size()) {
jpeg.clear();
}
}
}
stream->Release();
}
if (jpeg.empty()) return false;
// 用 JPEG 覆盖原像素区;宽高沿用客户端上报值(客户端就是按这两个尺寸缩放的)
pkt.resize(sizeof(*hdr) + jpeg.size());
hdr = reinterpret_cast<ScreenPreviewRspHeader*>(pkt.data()); // resize 后重新取
memcpy(pkt.data() + sizeof(*hdr), jpeg.data(), jpeg.size());
hdr->format = SCREEN_PREVIEW_FMT_JPEG;
hdr->bytes = (uint32_t)jpeg.size();
return true;
}
void CMy2015RemoteDlg::SendScreenPreviewRequest(context* ctx, WORD reqId, WORD maxWidth, BYTE jpegQuality)
{
if (!ctx) return;
+3
View File
@@ -621,6 +621,9 @@ public:
void ChooseScreenPreviewParams(context* ctx, WORD& maxWidth, BYTE& jpegQuality) const;
// 发起预览请求;reqId 应与 m_PreviewReqId 同步
void SendScreenPreviewRequest(context* ctx, WORD reqId, WORD maxWidth, BYTE jpegQuality);
// 预览响应规范化:Linux 客户端回原始 BGRA(SCREEN_PREVIEW_FMT_BGRX),在 IO 线程入口
// 统一转成 JPEG,下游(浮窗/列表缩略图/MCP)只处理 JPEG。返回 false 表示畸形包,应丢弃。
static bool NormalizeScreenPreviewPacket(std::vector<BYTE>& pkt);
// 收到 TOKEN_SCREEN_PREVIEW_RSP(在主线程处理)
afx_msg LRESULT OnPreviewResponse(WPARAM wParam, LPARAM lParam);
afx_msg void OnOnlineUnauthorize();
+102
View File
@@ -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
+15
View File
@@ -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 /
+233 -31
View File
@@ -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;
@@ -1180,7 +1183,7 @@ Json::Value BuildWindowListOutputSchema() {
return schema;
}
// get_activity_history 的 outputSchema(records 数组 + 原始文本)
// get_activity_history 的 outputSchema(records 数组 + 原始文本 + 翻页字段)
Json::Value BuildActivityHistoryOutputSchema() {
Json::Value props(Json::objectValue);
@@ -1189,12 +1192,21 @@ Json::Value BuildActivityHistoryOutputSchema() {
Json::Value items(Json::objectValue);
items["type"] = "string";
recordsProp["items"] = items;
recordsProp["description"] = u8"本次窗口内的记录,每条一行「[时间] [标题] 时长」。新在前。";
props["records"] = recordsProp;
Json::Value rawProp(Json::objectValue);
rawProp["type"] = "string";
rawProp["description"] = u8"与 records 同源的纯文本(records 按行拼接),窗口外的记录不包含。";
props["activityHistory"] = rawProp;
Json::Value truncProp(Json::objectValue);
truncProp["type"] = "boolean";
truncProp["description"] = u8"因 64 KB 字节预算而比 limit 少返回了条目(此时 hasMore 也为 true)。";
props["truncated"] = truncProp;
AppendPageOutputProps(props); // total / totalAll / offset / limit / hasMore
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
@@ -1484,6 +1496,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 +1513,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 +1575,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;
@@ -1939,9 +2002,9 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_activity_history";
tool["description"] = u8"获取指定在线主机的历史活动记录(前台窗口驻留时长,每行一条「[时间] [标题] 时长」)。主连接 RPC、一次性返回。";
tool["description"] = u8"获取指定在线主机的历史活动记录(前台窗口驻留时长,每行一条「[时间] [标题] 时长」)。主连接 RPC。结果按 limit/offset 分页(默认 100 条、上限 1000),新在前:offset=0 就是最近 limit 条,想看更早的再往后翻。total 为本机现有记录总数,hasMore 表示还有更早的记录;客户端只保留最近 500 条,所以 total 最多约 501(含进行中的当前窗口)。";
tool["inputSchema"] = BuildGetHostDetailInputSchema(); // 复用 { id } 必填 schema
tool["inputSchema"] = BuildPagedHostListInputSchema(); // { id | ids } + limit/offset
tool["outputSchema"] = BuildActivityHistoryOutputSchema();
tools.append(tool);
@@ -1951,7 +2014,7 @@ std::string BuildToolsListResult(const Json::Value& id) {
{
Json::Value tool(Json::objectValue);
tool["name"] = "get_screenshot";
tool["description"] = u8"截取指定在线主机的一帧屏幕,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。仅 Windows 客户端支持(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。";
tool["description"] = u8"截取指定在线主机的一帧屏幕,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。";
tool["inputSchema"] = BuildGetScreenshotInputSchema(); // { id } 必填 + max_width 可选
tool["outputSchema"] = BuildScreenshotOutputSchema();
@@ -1987,9 +2050,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 +2511,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);
}
@@ -2906,21 +2975,72 @@ std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& ar
text.assign((const char*)data.data() + 1, data.size() - 1);
// 拆行:每行一条记录,过滤空行(含 Dump 末尾的换行)。
Json::Value records(Json::arrayValue);
// 顺序是「新在前」:客户端 m_records 用 push_front 维护,Dump() 又把进行中的
// 当前窗口放在最前面。所以 offset=0 天然就是“最近 limit 条”,不需要先取
// total 再倒着算 offset——这正是日志类数据最常用的取法。
Json::Value all(Json::arrayValue);
size_t start = 0;
while (start <= text.size()) {
size_t nl = text.find('\n', start);
std::string line = text.substr(start, (nl == std::string::npos ? text.size() : nl) - start);
if (!line.empty()) records.append(line);
if (!line.empty()) all.append(line);
if (nl == std::string::npos) break;
start = nl + 1;
}
int count = (int)records.size();
// 分页:实测一次 501 条会把上下文撑爆(P2-1)。本工具无服务端过滤,
// total == totalAll,ApplyPageWindow 的默认口径即可。
PageWindow page = ResolvePageWindow(args);
Json::Value records(Json::arrayValue);
ApplyPageWindow(all, page, records);
// 字节预算:limit 上限 1000,窗口内若标题很长仍可能过大。从窗口末尾裁
// (保留最新的那些),裁掉的部分由 truncated 与 hasMore 一起表达。
const size_t kMaxBytes = 64 * 1024;
bool byteTrimmed = false;
{
size_t bytes = 0;
int kept = 0;
for (const Json::Value& r : records) {
const std::string s = r.asString();
if (bytes + s.size() + 1 > kMaxBytes) { byteTrimmed = true; break; }
bytes += s.size() + 1;
++kept;
}
if (byteTrimmed) {
// 至少留一条,保证调用方按 offset+returned 前进时不会原地打转
// (单条超过 64 KB 在窗口标题上几乎不可能,这里只是兜底)。
if (kept == 0) {
kept = 1;
Json::Value one(Json::arrayValue);
one.append(records[0]);
records = one;
} else {
Json::Value trimmed(Json::arrayValue);
for (int i = 0; i < kept; ++i) trimmed.append(records[i]);
records = trimmed;
}
page.returned = kept;
// 还有没有更早的记录,按「已返回到的绝对位置」算,而不是一律置 true:
// 末尾那条自己超预算时,offset+kept 已经等于 total,不该再报 hasMore。
page.hasMore = (page.offset + kept < page.total);
}
}
// activityHistory 是同一份数据的纯文本形态:必须按窗口重建,
// 否则整包原文会绕过分页,等于没分页。
std::string shown;
for (const Json::Value& r : records) {
shown += r.asString();
shown += '\n';
}
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["records"] = records;
structuredContent["activityHistory"] = text;
structuredContent["activityHistory"] = shown;
structuredContent["truncated"] = byteTrimmed;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
// 正文外的 JSON 块只放 records:activityHistory 是同一份数据的原文,
@@ -2932,7 +3052,11 @@ std::string BuildGetActivityHistory(const Json::Value& id, const Json::Value& ar
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"共 ") + std::to_string(count) + std::string(u8" 条历史活动记录。");
item["text"] = std::string(u8"共 ") + std::to_string(page.total) + std::string(u8" 条历史活动记录(新在前),本次返回第 ") +
std::to_string(page.offset) + std::string(u8" 条起的 ") + std::to_string(page.returned) + std::string(u8" 条") +
(page.hasMore ? std::string(u8";hasMore=true 表示还有更早的记录,可用 offset=") +
std::to_string(page.offset + page.returned) + std::string(u8" 继续取。")
: std::string(u8"。"));
content.append(item);
result["content"] = content;
result["isError"] = false;
@@ -2951,7 +3075,8 @@ std::string BuildGetScreenshot(const Json::Value& id, const Json::Value& args, C
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 能力位门槛:仅 Windows 客户端声明 CLIENT_CAP_SCREEN_PREVIEW(非 Windows 返回明确错误)
// 能力位门槛:只有能抓屏的客户端才声明 CLIENT_CAP_SCREEN_PREVIEW
// (Windows 恒声明;Linux 仅在登录时探测到可用 X11 桌面才声明),否则返回明确错误
if (!ctx->SupportsScreenPreview())
return BuildError(id, -32005, "Host does not support screen preview");
@@ -3638,7 +3763,11 @@ std::string BuildGetClientLog(const Json::Value& id, const Json::Value& args, CM
std::vector<BYTE> 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 在
@@ -3653,16 +3782,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<std::string> 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<std::string> 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;
@@ -8549,19 +8762,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,