Feature: Harden the MCP transport and add non-destructive host tools

Cap MCP request bodies at 2 MB, set a 15 s idle read timeout and a 60 s
write timeout, and give httplib an explicit 32-thread pool: long tools
such as chat_wait hold a worker for up to 55 s, and the default pool of
8 to 15 left other callers queued.

Every tool returned by tools/list now carries readOnlyHint,
destructiveHint, idempotentHint and openWorldHint. The table is
per-tool; anything not registered defaults to destructive so a new
write tool cannot silently look harmless. Read-only tools are forced
to destructiveHint=false.

get_host_detail appends the technical fields the host store already
holds (cpuCores, memoryGB, systemBits, programBits, user, isAdmin,
installTime, expiredDate, monitors, exeVersion, clientPath, pid,
publicIp). The JSON writer is pinned to 15 significant digits so
memoryGB renders as 27.8 instead of 27.800000000000001. list hosts
output is unchanged.

Add host_set_remark and host_set_watch_level. Both validate the host
against the store, are refused in readonly mode, repaint the affected
row, and are audited without recording the value written.

Add search_file, which drives the client file-manager search channel
and returns paged results. The root path is normalized before sending:
the client enumerates with wsprintf("%s\*.*"), so a trailing
backslash produced C:\*.* and FindFirstFile failed, returning zero
hits instantly. The client only searches recursively, so non-recursive
requests are filtered server-side by comparing the parent directory.
Collection stops at 5000 records or 4 MB and the client is told to
stop; on timeout the partial results are returned. Search result
packets are never closed early: the sub-connection stays open until
TOKEN_SEARCH_FILE_FINISH, because the client's search thread holds a
pointer into the file manager object.

Batch reads report a skipped counter and are bounded to 50 ids and a
50 s deadline.

Add tools/mcp_smoke.ps1, a read-only end-to-end smoke test that asserts
auth rejection, the payload limit, annotation coverage, paging fields
and the main read tools. It takes the token from the environment and
never prints it.

Document all of the above in docs/Mcp_Design.md section 10, including
the client-side MAX_PATH stack overflow that a deep search_file call
can trigger, together with the workaround of searching shallow
directories.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-10-25 13:59:17 +01:00
1 parent ac5b174b5f
commit abe7e99a77
7 files changed
+1244 -11

No files matched your search

+791 -11
View File
@@ -1310,6 +1310,19 @@ std::string BuildOperateWindow(const Json::Value& id, const Json::Value& args, C
std::string BuildControlService(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// ===== B1 前置声明(主机库元数据,定义见「tools/call 分派」前)=====
Json::Value BuildHostSetRemarkInputSchema();
Json::Value BuildHostSetRemarkOutputSchema();
Json::Value BuildHostSetWatchLevelInputSchema();
Json::Value BuildHostSetWatchLevelOutputSchema();
std::string BuildHostSetRemark(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
std::string BuildHostSetWatchLevel(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// ===== B2 前置声明(search_file,定义见「tools/call 分派」前)=====
Json::Value BuildSearchFileInputSchema();
Json::Value BuildSearchFileOutputSchema();
std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent);
// tools/list
std::string BuildToolsListResult(const Json::Value& id) {
Json::Value result(Json::objectValue);
@@ -1686,6 +1699,36 @@ std::string BuildToolsListResult(const Json::Value& id) {
}
}
// 18b) 主机库元数据(B1:host_set_remark / host_set_watch_level)。
// 只写服务端本地的备注/关注等级,不触达客户端,因此只受 McpReadonly 约束。
{
Json::Value tool(Json::objectValue);
tool["name"] = "host_set_remark";
tool["description"] = u8"给主机设置备注(在线或离线历史记录都可)。只写入服务端本地主机库,不向客户端下发任何命令;remark 传空字符串表示清除备注,GBK 编码后最长 63 字节。";
tool["inputSchema"] = BuildHostSetRemarkInputSchema();
tool["outputSchema"] = BuildHostSetRemarkOutputSchema();
tools.append(tool);
}
{
Json::Value tool(Json::objectValue);
tool["name"] = "host_set_watch_level";
tool["description"] = u8"设置主机在服务端在线列表里的关注等级:0=无、1=蓝字、2=红字、3=红底。只影响主控端本机显示,重复设置同一等级幂等。";
tool["inputSchema"] = BuildHostSetWatchLevelInputSchema();
tool["outputSchema"] = BuildHostSetWatchLevelOutputSchema();
tools.append(tool);
}
// 18c) 远程文件搜索(B2:search_file)。只读、仅 Windows 客户端,
// 故与其它只读工具一样始终登记,调用时按 McpReadonly / 客户端平台复核。
{
Json::Value tool(Json::objectValue);
tool["name"] = "search_file";
tool["description"] = u8"在指定主机(仅 Windows)的某个目录下按文件名搜索文件(不区分大小写;pattern 不含通配符时按子串匹配,含 * / ? 时按通配符匹配)。客户端始终递归子目录(深度 32、最多 10000 条,跳过隐藏+系统目录与符号链接),结果边搜边收集、按 limit/offset 分页;finished=false 表示到达 timeout_ms 时限、返回的是部分结果(服务端已通知客户端停止搜索)。单次最多收集 5000 条 / 4 MB,超出时 truncated=true。注意:客户端递归用无界 wsprintf 拼 MAX_PATH 缓冲,整盘/深目录搜索会栈溢出(Debug 客户端弹 Run-Time Check Failure #2 并挂住搜索线程,Release 静默破坏栈)——请只搜具体的中浅层目录,不要从盘符根开始扫。";
tool["inputSchema"] = BuildSearchFileInputSchema();
tool["outputSchema"] = BuildSearchFileOutputSchema();
tools.append(tool);
}
// 19) 连接管理 / 主机管理(P8:list_network_connections / kill_network_connection /
// host_* 共 16 个工具)。开关在 McpMachine.cpp 内部按 McpMachine /
// McpMachineDangerous / McpReadonly 逐项判断,关闭时不追加任何工具。
@@ -1695,6 +1738,11 @@ std::string BuildToolsListResult(const Json::Value& id) {
// 独立开关 McpChat(默认关),与 McpReadonly 无关;关闭时不追加任何工具。
McpChat::AppendTools(tools);
// 21) 统一补 annotations(A3):只读/破坏性/幂等/开放世界四类提示。
// 放在最后一步,三个注册点(本文件内联、McpMachine、McpChat)一视同仁,
// 以后新增工具只需在 McpInternal.cpp 的 kToolHints 表里登记一行。
ApplyToolAnnotations(tools);
result["tools"] = tools;
return BuildResult(id, result);
}
@@ -1812,6 +1860,69 @@ std::string BuildSearchHosts(const Json::Value& id, const Json::Value& args, CMy
}
// tools/call:get_host_detail
//
// 登录时上报的 RES_* 技术字段(CPU 核数/内存/系统位数/账号/安装时间/分辨率…)只在
// get_host_detail 里补充,不改 BuildHostJson —— 那是 Web UI 与 list_online_hosts 共用的
// 序列化函数,动它会改变已有调用方的输出形状。
std::string ResFieldUtf8(context* ctx, UINT cp, int idx) {
CString v = ctx->GetAdditionalData(idx);
if (v.IsEmpty()) return "";
return ToUtf8(v.GetString(), cp);
}
int DigitsOrZero(const std::string& s) {
return IsDigits(s) ? atoi(s.c_str()) : 0;
}
void AppendHostTechnicalDetail(CMy2015RemoteDlg* parent, uint64_t devId, Json::Value& host) {
context* ctx = FindMainContext(parent, devId);
if (!ctx) return;
const UINT cp = GetClientEncoding(ctx);
int cpu = DigitsOrZero(ResFieldUtf8(ctx, cp, RES_SYSTEM_CPU));
if (cpu > 0) host["cpuCores"] = cpu;
// 内存是 double 上报(client/LoginServer.cpp 的 GetMemorySizeGB → to_string),
// 例如 "15.903053";不能按整数解析,否则整段被丢掉。保留 1 位小数。
std::string memStr = ResFieldUtf8(ctx, cp, RES_SYSTEM_MEM);
if (!memStr.empty() && memStr[0] >= '0' && memStr[0] <= '9') {
double mem = atof(memStr.c_str());
if (mem > 0) host["memoryGB"] = (double)((long long)(mem * 10.0 + 0.5)) / 10.0;
}
std::string bits = ResFieldUtf8(ctx, cp, RES_SYSTEM_BITS);
if (!bits.empty()) host["systemBits"] = bits; // "64" / "32"
std::string progBits = ResFieldUtf8(ctx, cp, RES_PROGRAM_BITS);
if (!progBits.empty()) host["programBits"] = progBits;
std::string user = ResFieldUtf8(ctx, cp, RES_USERNAME);
if (!user.empty()) host["user"] = user;
std::string admin = ResFieldUtf8(ctx, cp, RES_ISADMIN);
if (!admin.empty()) host["isAdmin"] = (admin == "1");
std::string install = ResFieldUtf8(ctx, cp, RES_INSTALL_TIME);
if (!install.empty()) host["installTime"] = install;
std::string expired = ResFieldUtf8(ctx, cp, RES_EXPIRED_DATE);
if (!expired.empty()) host["expiredDate"] = expired;
// 心跳格式 "N:W*H":N=显示器数。多显示器时 remote_open/remote_* 会拒(-32008),
// 把 N 直接给出,AI 不必自己拆 screen 字符串。
std::string res = ResFieldUtf8(ctx, cp, RES_RESOLUTION);
size_t colon = res.find(':');
if (colon != std::string::npos) {
int monitors = DigitsOrZero(res.substr(0, colon));
if (monitors > 0) host["monitors"] = monitors;
}
std::string exeVer = ResFieldUtf8(ctx, cp, RES_EXE_VERSION);
if (!exeVer.empty()) host["exeVersion"] = exeVer;
std::string exePath = ResFieldUtf8(ctx, cp, RES_FILE_PATH);
if (!exePath.empty()) host["clientPath"] = exePath;
std::string pid = ResFieldUtf8(ctx, cp, RES_PID);
if (!pid.empty()) host["pid"] = pid;
std::string pubIp = ResFieldUtf8(ctx, cp, RES_CLIENT_PUBIP);
if (!pubIp.empty()) host["publicIp"] = pubIp;
}
std::string BuildGetHostDetail(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
std::string sid = GetStringArg(args, "id");
if (sid.empty()) {
@@ -1826,16 +1937,21 @@ std::string BuildGetHostDetail(const Json::Value& id, const Json::Value& args, C
for (unsigned int i = 0; i < all.size(); ++i) {
const Json::Value& h = all[i];
if (JsonStrField(h, "id") == sid) {
// 复制后再补充技术字段:all[] 里的是本次调用内的临时对象,补字段不影响
// BuildHostJson 本身(list_online_hosts 用同一份序列化,输出形状不变)。
Json::Value host = h;
AppendHostTechnicalDetail(parent, strtoull(sid.c_str(), nullptr, 10), host);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["host"] = h;
structuredContent["host"] = host;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
std::string name = JsonStrField(h, "name");
std::string ip = JsonStrField(h, "ip");
std::string name = JsonStrField(host, "name");
std::string ip = JsonStrField(host, "ip");
item["text"] = std::string(u8"主机 ") + name + " (" + ip + ")" + u8" 的详情。";
content.append(item);
result["content"] = content;
@@ -4818,6 +4934,145 @@ std::string BuildPowerAction(const Json::Value& id, const Json::Value& args, CMy
return BuildResult(id, result);
}
// ===== B1:主机库元数据(备注 / 关注等级)=====
//
// 写的是服务端本机的 _ClientList(MAP_NOTE / MAP_LEVEL),只影响主控端自己的展示:
// 不向客户端下发任何命令,也不改远端状态。所以门控只要 McpReadonly=0(这不是对设备的
// 操作,不要求 McpManage),审计仍走 AuditManageAction(只记字节数,绝不记备注内容)。
// 在线与离线(历史记录)主机都能写:id 在主机库里存在即可。
static bool HostStoreHas(CMy2015RemoteDlg* parent, uint64_t devId) {
if (!parent || !parent->m_ClientMap) return false;
EnterCriticalSection(&parent->m_cs);
bool exists = parent->m_ClientMap->Exists(devId);
LeaveCriticalSection(&parent->m_cs);
return exists;
}
// 备注/关注等级改完,UI 行要重绘才能立刻看到。MCP 线程不能直接碰 CListCtrl,
// 用 LVM_REDRAWITEMS 投递到列表控件(回到 UI 线程处理,触发 LVN_GETDISPINFO 重取文本)。
static void PostRepaintHostRow(CMy2015RemoteDlg* parent, uint64_t devId) {
if (!parent || !parent->m_CList_Online.GetSafeHwnd()) return;
int row = -1;
EnterCriticalSection(&parent->m_cs);
auto it = parent->m_ClientIndex.find(devId);
if (it != parent->m_ClientIndex.end()) {
for (size_t fi = 0; fi < parent->m_FilteredIndices.size(); ++fi) {
if (parent->m_FilteredIndices[fi] == it->second) { row = (int)fi; break; }
}
}
LeaveCriticalSection(&parent->m_cs);
if (row >= 0)
parent->m_CList_Online.PostMessage(LVM_REDRAWITEMS, (WPARAM)row, (LPARAM)row);
}
std::string BuildHostSetRemark(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
if (!args.isMember("remark") || !args["remark"].isString())
return BuildError(id, -32602,
"Missing required parameter: remark (string; empty string clears the remark)");
const std::string remarkU8 = args["remark"].asString();
CMcpServer& mcp = CMcpServer::Instance();
if (mcp.IsReadonly())
return BuildError(id, -32006,
"host_set_remark is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
if (!HostStoreHas(parent, devId))
return BuildError(id, -32002, "Unknown host id (not in host store): " + std::to_string(devId));
// 主机库的备注列是 char Note[64](_ClientValue),存的是 GBK。严格转换:不可表示
// 的字符(emoji、ö 等)直接报错,而不是静默变成 '?';长度按 GBK 字节算,留 1 字节 NUL。
std::string remarkGbk;
if (!Utf8ToCpExact(remarkU8, 936, remarkGbk))
return BuildError(id, -32602,
"Remark contains characters that GBK (client ANSI) cannot represent");
if (remarkGbk.size() >= 64)
return BuildError(id, -32602,
"Remark too long: " + std::to_string(remarkGbk.size()) +
" GBK bytes (max 63)");
EnterCriticalSection(&parent->m_cs);
parent->m_ClientMap->SetClientMapData(devId, MAP_NOTE, remarkGbk.c_str());
parent->m_ClientMap->SaveToFile(GetDbPath());
LeaveCriticalSection(&parent->m_cs);
PostRepaintHostRow(parent, devId);
AuditManageAction(parent, devId, "host_set_remark",
std::string("remark ") + (remarkGbk.empty() ? "cleared" : "set") +
" bytes=" + std::to_string(remarkGbk.size()));
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["id"] = std::to_string(devId);
structuredContent["remark"] = remarkU8;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = remarkGbk.empty()
? std::string(u8"已清除该主机的备注。")
: std::string(u8"已更新该主机的备注(") +
std::to_string(remarkGbk.size()) + std::string(u8" 字节)。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
std::string BuildHostSetWatchLevel(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
int level = -1;
if (!GetIntArg(args, "level", level))
return BuildError(id, -32602, "Missing required parameter: level (integer 0-3)");
if (level < 0 || level > 3)
return BuildError(id, -32602,
"Invalid level: " + std::to_string(level) + " (expect 0-3)");
CMcpServer& mcp = CMcpServer::Instance();
if (mcp.IsReadonly())
return BuildError(id, -32006,
"host_set_watch_level is disabled: MCP is in read-only mode (set McpReadonly=0 to enable)");
if (!HostStoreHas(parent, devId))
return BuildError(id, -32002, "Unknown host id (not in host store): " + std::to_string(devId));
EnterCriticalSection(&parent->m_cs);
parent->m_ClientMap->SetClientMapInteger(devId, MAP_LEVEL, level);
parent->m_ClientMap->SaveToFile(GetDbPath());
LeaveCriticalSection(&parent->m_cs);
PostRepaintHostRow(parent, devId);
AuditManageAction(parent, devId, "host_set_watch_level",
"level=" + std::to_string(level));
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["id"] = std::to_string(devId);
structuredContent["level"] = level;
result["structuredContent"] = structuredContent;
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = std::string(u8"关注等级已设为 ") + std::to_string(level) +
std::string(u8"(0=无、1=蓝字、2=红字、3=红底)。");
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== N3:get_keylog =====
//
// 复用客户端既有键盘记录链路:主连接下发 COMMAND_KEYBOARD → 客户端新建子连接并回
@@ -4965,12 +5220,398 @@ std::string BuildGetKeylog(const Json::Value& id, const Json::Value& args, CMy20
return BuildResult(id, result);
}
// ===== B2:search_file(远程文件搜索,仅 Windows)=====
//
// 链路:主连接 COMMAND_LIST_DRIVE → 子连接回 TOKEN_DRIVE_LIST(OnDriveList 转下发)
// → 子连接 COMMAND_SEARCH_FILE → N×TOKEN_SEARCH_FILE_LIST → TOKEN_SEARCH_FILE_FINISH。
//
// 协议来自 client/FileManager.cpp(COMMAND_LIST_DRIVE → LoopFileManager → 这个 CFileManager),
// 不是 client/file/FileManager.cpp(那是 SimplePlugins 版,走 COMMAND_FILE_MANAGER_PLUGIN,
// MCP 的 list_files 不走那条链路)。客户端工程是 MultiByte,全部字段都是 ANSI(GBK):
// * 请求 = [COMMAND_SEARCH_FILE][根目录 \0][模式 \0](两个 NUL 结尾的字符串,无定长结构)。
// 模式里没有 * / ? 时客户端自动包成 "*模式*",即「子串、不区分大小写」;
// 含通配符则按通配符匹配(WildcardMatch)。
// * 结果 = [TOKEN_SEARCH_FILE_LIST]{ [attr:1][全路径 \0][sizeHi:4][sizeLo:4][FILETIME:8] }*,
// 一个包里可以有多条(客户端按 64KB 批量发),attr = dwFileAttributes & 0x10 → 0 或 16。
// * 客户端行为:总是递归(深度 32、最多 10000 条),跳过隐藏+系统目录与重解析点;
// COMMAND_FILES_SEARCH_STOP 只置 m_bSearching=false,搜索线程随后自然结束并发 FINISH。
// ~CFileManager 会 m_bSearching=false + WaitForSingleObject(5000) 再离开,所以即使连接
// 在搜索中途断开,旧版这个管理器也不会 UAF;我们仍然只在 FINISH 后关连接,保持保守。
//
// 协议上限约束:客户端用 char[MAX_PATH] 缓冲拼路径(ExpandEnvironmentStrings/wsprintf),
// 服务端把 path/pattern 限在 200 字节 GBK 内,给客户端留余量(见 kSearchMaxPathBytes)。
namespace {
// 客户端 SearchFilesRecursive 的 strPath[MAX_PATH]/szFullPath[MAX_PATH] 都要再拼子路径。
const size_t kSearchMaxPathBytes = 200;
const size_t kSearchMaxPatternBytes = 200;
// 去掉末尾的 '\' 或 '/'("C:\" 保留成 "C:",比较时再容忍这种差异)。
std::string StripTrailingSlashes(std::string s) {
while (s.size() > 2 && (s.back() == '\\' || s.back() == '/')) s.pop_back();
if (s.size() == 3 && s[1] == ':' && (s[2] == '\\' || s[2] == '/')) s.pop_back(); // "C:\" → "C:"
return s;
}
// Windows 路径比较:ASCII 不区分大小写(GBK 双字节按原字节比,中文本就无大小写)。
bool EqualsPathNoCase(const std::string& a, const std::string& b) {
if (a.size() != b.size()) return false;
for (size_t i = 0; i < a.size(); ++i) {
char ca = a[i], cb = b[i];
if (ca >= 'A' && ca <= 'Z') ca = (char)(ca - 'A' + 'a');
if (cb >= 'A' && cb <= 'Z') cb = (char)(cb - 'A' + 'a');
if (ca != cb) return false;
}
return true;
}
std::string FormatFileTimeLocal(const FILETIME& ftIn) {
if (ftIn.dwLowDateTime == 0 && ftIn.dwHighDateTime == 0) return "";
FILETIME local;
if (!FileTimeToLocalFileTime(&ftIn, &local)) return "";
SYSTEMTIME st;
if (!FileTimeToSystemTime(&local, &st)) return "";
char buf[32];
_snprintf_s(buf, sizeof(buf), _TRUNCATE, "%04d-%02d-%02d %02d:%02d:%02d",
st.wYear, st.wMonth, st.wDay, st.wHour, st.wMinute, st.wSecond);
return buf;
}
// 一个 TOKEN_SEARCH_FILE_LIST 包里有多条记录(客户端按 64KB 批量发)。
// 客户端用 LocalReAlloc(LMEM_ZEROINIT) 扩缓冲,包尾可能带 0 填充;读到空路径即视为结束。
void AppendSearchRecords(const std::vector<BYTE>& pkt, Json::Value& out) {
if (pkt.size() < 2) return;
const size_t len = pkt.size();
size_t off = 1; // 跳过 token 字节
while (off + 1 <= len) {
const BYTE attr = pkt[off];
++off;
std::string path; // GBK 原始字节
bool terminated = false;
while (off < len) {
const char ch = (char)pkt[off++];
if (ch == 0) { terminated = true; break; }
path.push_back(ch);
}
if (!terminated || off + 16 > len) return; // 尾部截断/零填充
if (path.empty()) return; // LocalSize 的零填充
DWORD sizeHi = 0, sizeLo = 0;
memcpy(&sizeHi, pkt.data() + off, 4);
memcpy(&sizeLo, pkt.data() + off + 4, 4);
off += 8;
FILETIME ft;
memcpy(&ft, pkt.data() + off, sizeof(ft));
off += 8;
size_t slash = path.find_last_of("\\/");
const std::string name = (slash == std::string::npos) ? path : path.substr(slash + 1);
Json::Value rec(Json::objectValue);
rec["path"] = ToUtf8(path.c_str(), 936);
rec["name"] = ToUtf8(name.c_str(), 936);
rec["dir"] = (attr & FILE_ATTRIBUTE_DIRECTORY) != 0;
rec["size"] = (Json::UInt64)(((uint64_t)sizeHi << 32) | sizeLo);
std::string modified = FormatFileTimeLocal(ft);
if (!modified.empty()) rec["modified"] = modified;
out.append(rec);
}
}
} // namespace
Json::Value BuildSearchFileInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id(Windows 客户端)。";
props["id"] = idProp;
Json::Value pathProp(Json::objectValue);
pathProp["type"] = "string";
pathProp["description"] = u8"搜索的根目录,例如 C:\\Users 或 D:\\Data(必须是完整路径)。";
props["path"] = pathProp;
Json::Value patProp(Json::objectValue);
patProp["type"] = "string";
patProp["description"] = u8"文件名匹配串(不区分大小写),例如 report、.log、setup.exe;不含通配符时按子串匹配,含 * 或 ? 时按通配符匹配(如 *.log)。";
props["pattern"] = patProp;
Json::Value recProp(Json::objectValue);
recProp["type"] = "boolean";
recProp["description"] = u8"是否包含子目录,默认 true。客户端只支持递归搜索,传 false 时由服务端过滤出根目录下的直接子项(搜索耗时不变)。";
props["recursive"] = recProp;
Json::Value toProp(Json::objectValue);
toProp["type"] = "integer";
toProp["description"] = u8"搜索时限(毫秒),默认 20000,范围 1000-120000。到时限会通知客户端停止搜索,返回已收到的部分结果(finished=false)。";
props["timeout_ms"] = toProp;
AppendPagingProps(props);
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("path");
required.append("pattern");
schema["required"] = required;
return schema;
}
Json::Value BuildSearchFileOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value filesProp(Json::objectValue);
filesProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "object";
filesProp["items"] = items;
props["files"] = filesProp;
Json::Value finProp(Json::objectValue);
finProp["type"] = "boolean";
props["finished"] = finProp;
Json::Value truncProp(Json::objectValue);
truncProp["type"] = "boolean";
props["truncated"] = truncProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
std::string BuildSearchFile(const Json::Value& id, const Json::Value& args, CMy2015RemoteDlg* parent) {
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err))
return BuildError(id, -32602, err);
context* ctx = FindMainContext(parent, devId);
if (!ctx)
return BuildError(id, -32002, "Host not found or offline: " + std::to_string(devId));
// 该协议只在 Windows 客户端的 CFileManager 里实现(请求体是两个 GBK C 串)。
CString clientType = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (clientType == "LNX" || clientType == "MAC" || clientType == "APK")
return BuildError(id, -32005, "search_file is only supported on Windows hosts");
std::string path = Trim(GetStringArg(args, "path"));
std::string pattern = Trim(GetStringArg(args, "pattern"));
if (path.empty())
return BuildError(id, -32602, "Missing required parameter: path (e.g. C:\\\\Users)");
if (pattern.empty())
return BuildError(id, -32602, "Missing required parameter: pattern (file name substring)");
// 客户端枚举用的是 wsprintf("%s\\*.*"):根目录带尾部反斜杠会拼成 "C:\\*.*",
// FindFirstFile 直接失败,搜索秒回 0 条。统一去尾斜杠("C:\" → "C:",客户端拼回 "C:\*.*"),
// 顺便把分隔符统一成反斜杠(记录里的全路径也是反斜杠拼的)。
for (char& c : path) if (c == '/') c = '\\';
path = StripTrailingSlashes(path);
if (path.empty() || path == "\\")
return BuildError(id, -32602,
"Invalid path: expected a directory such as C:\\ or C:\\Users");
bool recursive = true;
if (args.isMember("recursive") && args["recursive"].isBool())
recursive = args["recursive"].asBool();
int timeoutMs = 20000;
int v = 0;
if (GetIntArg(args, "timeout_ms", v)) {
if (v < 1000) v = 1000;
if (v > 120000) v = 120000;
timeoutMs = v;
}
std::string ansiPath, ansiPattern;
if (!Utf8ToCpExact(path, 936, ansiPath))
return BuildError(id, -32602,
"path cannot be encoded in the client's ANSI code page (GBK); use ASCII-safe paths");
if (!Utf8ToCpExact(pattern, 936, ansiPattern))
return BuildError(id, -32602,
"pattern cannot be encoded in the client's ANSI code page (GBK)");
if (ansiPath.size() > kSearchMaxPathBytes)
return BuildError(id, -32602,
"path too long (max " + std::to_string(kSearchMaxPathBytes) + " bytes in GBK)");
if (ansiPattern.size() > kSearchMaxPatternBytes)
return BuildError(id, -32602,
"pattern too long (max " + std::to_string(kSearchMaxPatternBytes) + " bytes in GBK)");
// 请求体 = [根目录 \0][模式 \0](OnDriveList 前面再加 COMMAND_SEARCH_FILE)。
std::string payload;
payload.reserve(ansiPath.size() + ansiPattern.size() + 2);
payload.append(ansiPath);
payload.push_back('\0');
payload.append(ansiPattern);
payload.push_back('\0');
CMcpServer& mcp = CMcpServer::Instance();
if (!mcp.BeginPending(devId, "search_file", payload))
return BuildError(id, -32003, "Device busy: another request is pending for this host");
BYTE cmd = COMMAND_LIST_DRIVE;
if (!ctx->Send2Client(&cmd, 1)) {
mcp.ClearPending(devId);
return BuildError(id, -32004, "Failed to send command to host");
}
std::vector<std::vector<BYTE>> packets;
bool finished = false, truncated = false;
context* subCtx = nullptr;
if (!mcp.WaitSearchFile(devId, packets, finished, truncated, subCtx, timeoutMs)) {
mcp.ClearPending(devId);
return BuildError(id, -32001, "Timeout waiting for the file manager session");
}
if (!finished) {
if (!subCtx) {
// 客户端连文件管理器子连接都没建起来(离线/拒绝/过载),不是「搜索慢」。
mcp.ClearPending(devId);
return BuildError(id, -32001, "Timeout waiting for the file manager session");
}
// 到时限:让客户端停搜(客户端搜索线程下一次循环即退出,随后回 FINISH),再给 5s 收尾。
// 收不到 FINISH 也照样返回部分结果;子连接留给 FINISH 分支关闭。
mcp.StopSearchFile(devId);
std::vector<std::vector<BYTE>> more;
bool finished2 = false, truncated2 = truncated;
context* subCtx2 = nullptr;
if (mcp.WaitSearchFile(devId, more, finished2, truncated2, subCtx2, 5000)) {
packets.insert(packets.end(), more.begin(), more.end());
finished = finished2;
truncated = truncated || truncated2;
}
}
mcp.ClearPending(devId);
Json::Value all(Json::arrayValue);
for (const auto& pkt : packets) AppendSearchRecords(pkt, all);
// 客户端只有递归搜索(深度 32),非递归请求在这里按「父目录 == 根目录」服务端过滤。
if (!recursive) {
Json::Value filtered(Json::arrayValue);
const std::string root = StripTrailingSlashes(path);
for (const Json::Value& rec : all) {
std::string p = rec["path"].asString();
size_t slash = p.find_last_of("\\/");
if (slash == std::string::npos) continue;
if (EqualsPathNoCase(StripTrailingSlashes(p.substr(0, slash)), root))
filtered.append(rec);
}
all = filtered;
}
PageWindow page = ResolvePageWindow(args);
Json::Value pageItems;
ApplyPageWindow(all, page, pageItems);
Json::Value result(Json::objectValue);
Json::Value structuredContent(Json::objectValue);
structuredContent["files"] = pageItems;
structuredContent["finished"] = finished;
structuredContent["truncated"] = truncated;
WritePageFields(structuredContent, page);
result["structuredContent"] = structuredContent;
std::string text = PageSummary(page, u8"个匹配项");
if (!finished)
text += u8" 搜索在时限内未完成,以上为已收到的部分结果(可加大 timeout_ms 重试)。";
if (truncated)
text += u8" 命中数超过服务端收集上限(5000 条 / 4 MB),后续匹配已停止收集,请缩小 path 或 pattern 再搜。";
Json::Value content(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = text;
content.append(item);
result["content"] = content;
result["isError"] = false;
return BuildResult(id, result);
}
// ===== B1:主机库元数据 schema =====
Json::Value BuildHostSetRemarkInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id(list_online_hosts / list_all_hosts 返回的十进制字符串)。";
props["id"] = idProp;
Json::Value remarkProp(Json::objectValue);
remarkProp["type"] = "string";
remarkProp["description"] = u8"备注文本(UTF-8);空字符串表示清除备注;GBK 编码后最长 63 字节。";
props["remark"] = remarkProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("remark");
schema["required"] = required;
return schema;
}
Json::Value BuildHostSetRemarkOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
props["id"] = idProp;
Json::Value remarkProp(Json::objectValue);
remarkProp["type"] = "string";
props["remark"] = remarkProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
Json::Value BuildHostSetWatchLevelInputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
idProp["description"] = u8"主机 id(在线或离线历史记录均可)。";
props["id"] = idProp;
Json::Value levelProp(Json::objectValue);
levelProp["type"] = "integer";
levelProp["minimum"] = 0;
levelProp["maximum"] = 3;
levelProp["description"] = u8"关注等级:0=无、1=蓝字、2=红字、3=红底(服务端在线列表现色)。";
props["level"] = levelProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
Json::Value required(Json::arrayValue);
required.append("id");
required.append("level");
schema["required"] = required;
return schema;
}
Json::Value BuildHostSetWatchLevelOutputSchema() {
Json::Value props(Json::objectValue);
Json::Value idProp(Json::objectValue);
idProp["type"] = "string";
props["id"] = idProp;
Json::Value levelProp(Json::objectValue);
levelProp["type"] = "integer";
props["level"] = levelProp;
Json::Value schema(Json::objectValue);
schema["type"] = "object";
schema["properties"] = props;
return schema;
}
// ===== N2:批量只读调用(ids[]) =====
//
// 只读工具支持一次传多个主机 id(args.ids),服务端逐个调用单机实现并把结果汇总到
// structuredContent.results。写操作工具一律不支持批量(避免一次误操作波及多台)。
// 每个 id 的单机结果仍带各自的 limit/offset/total/hasMore —— 分页是「每台主机各自的」。
static const size_t kBatchMaxIds = 50;
// 批量整体时限:50 台 × 单机 20s 最坏能拖到 1000s,远超 MCP 客户端自身的工具超时。
// 到了时限就不再对剩余 id 下发(标 skipped),保证响应在客户端放弃之前返回。
// 注意:时限只在「下一台开始前」检查,正在跑的那一台仍会跑完它自己的超时,
// 所以真实上限约为 50s + 单机超时(20s)。要更紧就得把 deadline 一路传进各工具。
static const long long kBatchDeadlineMs = 50000;
bool IsBatchReadOnlyTool(const std::string& t) {
static const char* kReadOnly[] = {
@@ -5001,6 +5642,16 @@ Json::Value MakeBatchErrorEntry(const std::string& hostId, int code, const std::
return entry;
}
// 批量整体时限用尽后,剩余 id 的占位结果:明确标 skipped(未下发),
// 与「试过但失败」区分开,避免调用方误以为这些都是主机侧错误。
Json::Value MakeBatchSkippedEntry(const std::string& hostId) {
Json::Value entry = MakeBatchErrorEntry(hostId, -32001,
"Batch deadline exceeded (" + std::to_string(kBatchDeadlineMs / 1000) +
" s): not attempted");
entry["skipped"] = true;
return entry;
}
std::string BuildBatchCall(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent) {
const Json::Value& ids = args["ids"];
@@ -5011,8 +5662,11 @@ std::string BuildBatchCall(const Json::Value& id, const std::string& toolName,
}
Json::Value results(Json::arrayValue);
int okCount = 0, failCount = 0;
int okCount = 0, failCount = 0, skipCount = 0;
std::string failLines;
const auto batchDeadline =
std::chrono::steady_clock::now() + std::chrono::milliseconds(kBatchDeadlineMs);
bool deadlineHit = false;
for (const Json::Value& v : ids) {
std::string hostId;
@@ -5029,6 +5683,14 @@ std::string BuildBatchCall(const Json::Value& id, const std::string& toolName,
continue;
}
// 整体时限:一旦命中,后面所有 id 都不再下发(只记 skipped,不等待)。
if (deadlineHit || std::chrono::steady_clock::now() >= batchDeadline) {
deadlineHit = true;
results.append(MakeBatchSkippedEntry(hostId));
++skipCount;
continue;
}
Json::Value oneArgs = args;
oneArgs.removeMember("ids");
oneArgs["id"] = hostId;
@@ -5082,6 +5744,7 @@ std::string BuildBatchCall(const Json::Value& id, const std::string& toolName,
structuredContent["total"] = (int)ids.size();
structuredContent["succeeded"] = okCount;
structuredContent["failed"] = failCount;
structuredContent["skipped"] = skipCount;
structuredContent["results"] = results;
Json::Value result(Json::objectValue);
@@ -5093,7 +5756,11 @@ std::string BuildBatchCall(const Json::Value& id, const std::string& toolName,
item["text"] = std::string(u8"批量调用 ") + toolName + std::string(u8":共 ") +
std::to_string(ids.size()) + std::string(u8" 台,成功 ") +
std::to_string(okCount) + std::string(u8" 台,失败 ") +
std::to_string(failCount) + std::string(u8" 台。") + failLines;
std::to_string(failCount) + std::string(u8" 台") +
(skipCount > 0
? std::string(u8",超时跳过 ") + std::to_string(skipCount) + std::string(u8" 台")
: std::string()) +
std::string(u8"。") + failLines;
content.append(item);
result["content"] = content;
result["isError"] = false;
@@ -5163,6 +5830,9 @@ std::string DispatchSingleHostTool(const Json::Value& id, const std::string& too
if (toolName == "operate_window") return BuildOperateWindow(id, args, parent);
if (toolName == "control_service") return BuildControlService(id, args, parent);
if (toolName == "power_action") return BuildPowerAction(id, args, parent);
if (toolName == "host_set_remark") return BuildHostSetRemark(id, args, parent);
if (toolName == "host_set_watch_level") return BuildHostSetWatchLevel(id, args, parent);
if (toolName == "search_file") return BuildSearchFile(id, args, parent);
return BuildError(id, -32602,
"Unknown tool: " + (toolName.empty() ? std::string("(empty)") : toolName));
@@ -5596,6 +6266,19 @@ CMcpServer::~CMcpServer() {
bool CMcpServer::Start(const std::string& bind, int port) {
if (m_running.load()) return true; // 已在运行
// ===== 传输层加固(A1)=====
// httplib 默认:请求体不限长(SIZE_MAX)、读写超时各 5s、线程池 max(8, 核数-1)。
// 1) 请求体上限 2 MB:本服务只收 JSON-RPC 参数(文件内容走子连接分块,不进 HTTP body),
// 2 MB 足够 chat_send(4 KB)/remote_clipboard 文本,又能挡住超大 body 打爆内存。
// 2) 读超时 15s:经 frp 隧道上传参数时单次 recv 不至于 5s 就被掐断。
// 3) 写超时 60s:get_screenshot 的大图 base64 或慢链路下,5s 会把半个响应写断。
// 4) 线程池显式 32:chat_wait(最长 55s)/批量只读会长时间占线程,默认 8~15 个不够;
// 每个线程约 1 MB 栈,32 个约 32 MB,可接受。
m_server.set_payload_max_length(2 * 1024 * 1024);
m_server.set_read_timeout(15, 0);
m_server.set_write_timeout(60, 0);
m_server.new_task_queue = []() { return new httplib::ThreadPool(32); };
m_thread = std::thread([this, bind, port]() {
m_server.listen(bind, port);
});
@@ -5957,20 +6640,38 @@ bool CMcpServer::TakePreviewResponse(uint64_t device_id, uint16_t reqId, const B
bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len) {
std::string path;
bool listDrives = true;
bool searchFile = false;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end()) return true; // 已超时清理 → 调用方 CancelIO 收尾
path = it->second.path;
listDrives = path.empty() || path == "." || path == "/" || path == "\\";
if (listDrives) {
it->second.data.assign(buf, buf + len);
it->second.done = true;
m_PendingCv.notify_one();
return true; // 只列盘 → 调用方用完即关
if (it->second.tool == "search_file") {
// B2:path 里装的是 [根目录 \0][模式 \0](含 NUL,不能用 C 字符串接口处理)。
searchFile = true;
it->second.subCtx = subCtx; // 超时停搜 / 收尾要用
} else {
listDrives = path.empty() || path == "." || path == "/" || path == "\\";
if (listDrives) {
it->second.data.assign(buf, buf + len);
it->second.done = true;
m_PendingCv.notify_one();
return true; // 只列盘 → 调用方用完即关
}
}
}
if (searchFile) {
// 文件搜索:子链接已就绪,下发 COMMAND_SEARCH_FILE + FILESEARCH 结构体。
// 与 MFC 文件管理器 OnBtnSearch 的打包方式一致(命令字节后紧跟整个结构体)。
std::vector<BYTE> pkt;
pkt.reserve(1 + path.size());
pkt.push_back((BYTE)COMMAND_SEARCH_FILE);
pkt.insert(pkt.end(), path.begin(), path.end());
subCtx->Send2Client(pkt.data(), (ULONG)pkt.size());
return false; // 保持子链接,等 N 个结果包 + FINISH
}
// 列目录:锁外下发 COMMAND_LIST_FILES + path,子链接保持,等 TOKEN_FILE_LIST。
// path 已在 BuildListFiles 按客户端 ANSI 转好(OnDriveList 无需再转),结尾 '\0'
// 与 FileManagerDlg 的 PacketSize=len+2 一致。
@@ -5983,6 +6684,85 @@ bool CMcpServer::OnDriveList(uint64_t device_id, context* subCtx, const BYTE* bu
return false; // 继续等 TOKEN_FILE_LIST,调用方不 CancelIO
}
// ===== B2:search_file =====
namespace {
// 收集上限:单次搜索最多记住 5000 条 / 4 MB 原始包,超过就让客户端停搜。
// 这是保护服务端内存(整盘搜索能命中几十万条),不是业务上限。
const size_t kSearchMaxRecords = 5000;
const size_t kSearchMaxBytes = 4 * 1024 * 1024;
}
bool CMcpServer::OnSearchFileRecords(uint64_t device_id, context* subCtx, const BYTE* buf, ULONG len) {
bool needStop = false;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end() || it->second.tool != "search_file") return false;
PendingRequest& p = it->second;
// 身份校验:只认登记过的那条子连接。旧搜索(已放弃)的尾包一律不受理,
// 由调用方原地丢弃——但调用方绝不能因此关连接(见 2015RemoteDlg.cpp 的注释)。
if (p.subCtx != subCtx) return false;
if (p.searchRecords.size() >= kSearchMaxRecords ||
p.searchBytes + len > kSearchMaxBytes) {
p.searchTruncated = true;
if (!p.searchStopSent) { p.searchStopSent = true; needStop = true; }
} else {
p.searchRecords.emplace_back(buf, buf + len);
p.searchBytes += len;
}
}
if (needStop && subCtx) {
BYTE stop = (BYTE)COMMAND_FILES_SEARCH_STOP;
subCtx->Send2Client(&stop, 1);
}
return true; // 命中挂起 → 本包由 MCP 消费(不论是否因超限被丢弃)
}
void CMcpServer::FinishSearchFile(uint64_t device_id, context* subCtx) {
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end() || it->second.tool != "search_file") return;
if (it->second.subCtx != subCtx) return; // 别的子连接的 FINISH,与当前搜索无关
it->second.searchFinished = true;
m_PendingCv.notify_all();
}
bool CMcpServer::WaitSearchFile(uint64_t device_id, std::vector<std::vector<BYTE>>& records,
bool& finished, bool& truncated, context*& subCtx, int timeoutMs) {
std::unique_lock<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end() || it->second.tool != "search_file") return false;
m_PendingCv.wait_for(lk, std::chrono::milliseconds(timeoutMs),
[&] { return it->second.searchFinished; });
records.swap(it->second.searchRecords);
it->second.searchRecords.clear();
it->second.searchBytes = 0;
finished = it->second.searchFinished;
truncated = it->second.searchTruncated;
subCtx = it->second.subCtx;
return true;
}
void CMcpServer::StopSearchFile(uint64_t device_id) {
context* subCtx = nullptr;
{
std::lock_guard<std::mutex> lk(m_PendingMutex);
auto it = m_Pending.find(device_id);
if (it == m_Pending.end() || it->second.tool != "search_file") return;
if (it->second.searchStopSent) return;
it->second.searchStopSent = true;
subCtx = it->second.subCtx;
}
if (subCtx) {
BYTE stop = (BYTE)COMMAND_FILES_SEARCH_STOP;
subCtx->Send2Client(&stop, 1);
}
}
// ===== P3:list_registry 扩展 =====
bool CMcpServer::OnRegeditReady(uint64_t device_id, context* subCtx) {