Files
SimpleRemoter/server/2015Remote/McpInternal.cpp
T
yuanyuanxianganddeepseek-flash fd1b085279 Feature: Add remote lock screen for Android hosts
Implement the Ctrl+Alt+Del path on Android as a system lock screen.
Android has no secure attention sequence, so COMMAND_SCREEN_CTRL_ALT_DEL
is mapped in the client to GLOBAL_ACTION_LOCK_SCREEN and the server
exposes it as the new MCP tool remote_lock_screen.

The Android client resolves ControlService.lockScreen()/canLockScreen()
in nativeInit and dispatches the command from the screen sub-connection
through the usual attach/detach JNI path. The lock action is posted to
the accessibility service handler because performGlobalAction must not
run on the receiver thread.

Login advertises the new CLIENT_CAP_LOCK_SCREEN bit only when the
accessibility service is bound and the API level is 28+, so the server
can reject old APKs and Windows/Linux hosts up front instead of
reporting a lock that never happened. There is no receipt: a successful
call only means the command was delivered, and the tool description
tells the caller to confirm with get_screenshot.

Server side adds the schema and handler next to remote_clipboard, audits
the call, and gates it on client type plus the capability bit. Since it
is the only APK-only tool, check_platform_table.py gains a documented
exemption from the Windows baseline invariant, and make_tools_json.py
learns an APK-only platform set. tools.json is regenerated from the live
server and the plan document now counts 62 tools.

Co-Authored-By: deepseek-flash
2026-11-11 20:59:10 +01:00

693 lines
28 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "stdafx.h"
#include "McpInternal.h"
#include "context.h" // context 接口(GetClientID/IsLogin)
#include "McpServer.h" // 窗口信息 RPC 复用主连接的挂起/等待机制
#include "2015RemoteDlg.h" // CMy2015RemoteDlg 成员(m_HostList/m_cs)+ WM_SHOWERRORMSG
#include "LangManager.h" // _TR
#ifndef _WIN64
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncppd.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp.lib")
#endif
#else
#ifdef _DEBUG
#pragma comment(lib, "jsoncpp/jsoncpp_x64d.lib")
#else
#pragma comment(lib, "jsoncpp/jsoncpp_x64.lib")
#endif
#endif
namespace McpInternal {
std::string JsonToString(const Json::Value& v) {
Json::StreamWriterBuilder b;
b["indentation"] = "";
// jsoncpp 默认按 17 位有效数字输出 double,27.8 会写成 27.800000000000001。
// 我们只有 memoryGB 一个浮点字段(1 位小数),15 位足够且输出干净。
b["precision"] = 15;
b["precisionType"] = "significant";
return Json::writeString(b, v);
}
// 结果外露控制键:SetStructuredTextPayload 写入,BuildResult 消费后移除,
// 不会出现在响应里。'$' 前缀确保与任何业务字段不冲突。
static const char kStructuredTextPayloadKey[] = "$structuredTextPayload";
void AppendStructuredText(Json::Value& result, const Json::Value& payload) {
if (!payload.isObject() && !payload.isArray())
return; // null/标量载荷没有可外露的结构
if (payload.empty())
return; // 动作类结果(remote_mouse 等的 {})无内容可补
Json::Value content = result.isMember("content") ? result["content"]
: Json::Value(Json::arrayValue);
if (!content.isArray())
content = Json::Value(Json::arrayValue);
Json::Value item(Json::objectValue);
item["type"] = "text";
item["text"] = JsonToString(payload); // 紧凑 JSON,可被模型原样解析
content.append(item);
result["content"] = content;
}
void AppendStructuredText(Json::Value& result) {
if (!result.isMember("structuredContent"))
return;
AppendStructuredText(result, result["structuredContent"]);
}
void SetStructuredTextPayload(Json::Value& result, const Json::Value& payload) {
result[kStructuredTextPayloadKey] = payload;
}
std::string BuildResult(const Json::Value& id, const Json::Value& result) {
Json::Value resp(Json::objectValue);
resp["jsonrpc"] = "2.0";
resp["id"] = id;
resp["result"] = result;
// resp["result"] 本来就是深拷贝,直接在上面补文本块,不多拷一次。
Json::Value& out = resp["result"];
if (out.isMember(kStructuredTextPayloadKey)) {
Json::Value payload = out[kStructuredTextPayloadKey];
out.removeMember(kStructuredTextPayloadKey);
AppendStructuredText(out, payload);
} else {
AppendStructuredText(out);
}
return JsonToString(resp);
}
std::string BuildError(const Json::Value& id, int code, const std::string& msg) {
Json::Value resp(Json::objectValue);
resp["jsonrpc"] = "2.0";
resp["id"] = id;
Json::Value err(Json::objectValue);
err["code"] = code;
err["message"] = msg;
resp["error"] = err;
return JsonToString(resp);
}
std::string ToLowerAscii(const std::string& s) {
std::string r = s;
for (char& c : r) if (c >= 'A' && c <= 'Z') c = (char)(c - 'A' + 'a');
return r;
}
bool ContainsCI(const std::string& haystack, const std::string& needle) {
if (needle.empty()) return true;
return ToLowerAscii(haystack).find(ToLowerAscii(needle)) != std::string::npos;
}
std::string JsonStrField(const Json::Value& v, const char* key) {
if (v.isObject() && v.isMember(key) && v[key].isString())
return v[key].asString();
return "";
}
bool IsDigits(const std::string& s) {
if (s.empty()) return false;
for (char c : s) if (c < '0' || c > '9') return false;
return true;
}
std::string GetStringArg(const Json::Value& args, const char* key) {
return JsonStrField(args, key);
}
bool GetIntArg(const Json::Value& args, const char* key, int& out) {
if (!args.isMember(key)) return false;
const Json::Value& v = args[key];
if (v.isNumeric()) { out = v.asInt(); return true; }
if (v.isString()) {
const std::string s = v.asString();
if (IsDigits(s) || (!s.empty() && s[0] == '-' && IsDigits(s.substr(1)))) {
out = atoi(s.c_str());
return true;
}
}
return false;
}
bool ReadUInt64(const Json::Value& v, uint64_t& out) {
if (v.isNumeric()) { out = v.asUInt64(); return true; }
if (v.isString()) {
std::string s = v.asString();
if (IsDigits(s)) { out = strtoull(s.c_str(), nullptr, 10); return true; }
}
return false;
}
bool ReadUInt64Arg(const Json::Value& args, const char* key, uint64_t& out) {
if (!args.isMember(key)) return false;
return ReadUInt64(args[key], out);
}
bool ParseHostIdArg(const Json::Value& args, uint64_t& out, std::string& err) {
std::string sid = GetStringArg(args, "id");
if (sid.empty()) {
err = "Missing required parameter: id";
return false;
}
if (!IsDigits(sid)) {
err = "Invalid id: expected a decimal host id string";
return false;
}
out = strtoull(sid.c_str(), nullptr, 10);
return true;
}
context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id) {
if (!parent) return nullptr;
context* found = nullptr;
EnterCriticalSection(&parent->m_cs);
for (context* ctx : parent->m_HostList) {
if (ctx && ctx->GetClientID() == id && ctx->IsLogin()) {
found = ctx;
break;
}
}
LeaveCriticalSection(&parent->m_cs);
return found;
}
bool IsWindowsClient(context* ctx) {
if (!ctx) return false;
CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE);
return !(t == "LNX" || t == "MAC" || t == "APK");
}
// ===== 窗口信息 RPC =====
Json::Value WindowEntryToJson(const WindowEntry& e) {
Json::Value item(Json::objectValue);
item["hwnd"] = (Json::UInt)e.hwnd;
item["pid"] = (Json::UInt)e.pid;
item["title"] = e.title;
item["left"] = e.left;
item["top"] = e.top;
item["right"] = e.right;
item["bottom"] = e.bottom;
item["width"] = e.right - e.left;
item["height"] = e.bottom - e.top;
item["visible"] = (e.flags & WINDOWINFO_VISIBLE) != 0;
item["minimized"] = (e.flags & WINDOWINFO_MINIMIZED) != 0;
item["maximized"] = (e.flags & WINDOWINFO_MAXIMIZED) != 0;
item["isForeground"] = (e.flags & WINDOWINFO_FOREGROUND) != 0;
item["zOrder"] = e.zorder;
return item;
}
int FetchWindowInfo(context* ctx, uint64_t devId, const char* tool, int timeoutMs,
std::vector<WindowEntry>& out, std::string& errMsg, bool* truncated,
WindowDesktopRect* desktop) {
out.clear();
errMsg.clear();
if (truncated) *truncated = false;
if (desktop) *desktop = WindowDesktopRect();
if (!ctx) {
errMsg = "host context unavailable";
return 2;
}
if (!ctx->SupportsWindowInfo()) {
errMsg = "host client does not support window info (old client)";
return 4;
}
CMcpServer& mcp = McpServer();
if (!mcp.BeginPending(devId, tool ? tool : "window_info")) {
errMsg = "device busy: another request is pending for this host";
return 1;
}
BYTE req[2] = { (BYTE)COMMAND_MCP_WINDOW_INFO, 0 }; // mode 0 = 可见顶层窗口
if (!ctx->Send2Client(req, sizeof(req))) {
mcp.ClearPending(devId);
errMsg = "failed to send window info request";
return 2;
}
std::vector<BYTE> data;
if (!mcp.WaitPending(devId, data, timeoutMs > 0 ? timeoutMs : mcp.ToolTimeoutMs())) {
errMsg = "timeout waiting for window info";
return 2;
}
if (data.size() < 4 || data[0] != (BYTE)TOKEN_MCP_WINDOW_INFO) {
errMsg = "invalid window info response";
return 3;
}
// 模式字节最高位 = 客户端枚举到的可见窗口超过单包上限,返回的 count 条不完整。
if (truncated) *truncated = (data[1] & 0x80) != 0;
const size_t count = (size_t)data[2] | ((size_t)data[3] << 8);
if (data.size() < 4 + count * sizeof(WINDOWINFO_MCP)) {
errMsg = "truncated window info response";
return 3;
}
out.reserve(count);
for (size_t i = 0; i < count; ++i) {
WINDOWINFO_MCP rec;
memcpy(&rec, data.data() + 4 + i * sizeof(WINDOWINFO_MCP), sizeof(rec));
WindowEntry e;
e.hwnd = rec.hwnd;
e.pid = rec.pid;
e.left = rec.left;
e.top = rec.top;
e.right = rec.right;
e.bottom = rec.bottom;
e.flags = rec.flags;
e.zorder = rec.zorder;
char title[sizeof(rec.title) + 1] = { 0 };
memcpy(title, rec.title, sizeof(rec.title)); // 客户端保证 NUL 填充;再兜底截断
e.title = title;
out.push_back(std::move(e));
}
// 可选尾块:虚拟桌面矩形(新客户端才回;老客户端包长正好到 count 条记录为止)。
if (desktop && data.size() >= 4 + count * sizeof(WINDOWINFO_MCP) + sizeof(WINDOWINFO_MCP_DESKTOP)) {
WINDOWINFO_MCP_DESKTOP d;
memcpy(&d, data.data() + 4 + count * sizeof(WINDOWINFO_MCP), sizeof(d));
if (d.magic == WINDOWINFO_DESKTOP_MAGIC && d.width > 0 && d.height > 0) {
desktop->left = d.left;
desktop->top = d.top;
desktop->width = d.width;
desktop->height = d.height;
desktop->valid = true;
}
}
return 0;
}
size_t BoundedStrlen(const char* p, size_t avail) {
size_t n = 0;
while (n < avail && p[n]) ++n;
return n;
}
std::string ToUtf8(const char* s, UINT cp) {
if (!s || !*s) return "";
int wlen = MultiByteToWideChar(cp, 0, s, -1, NULL, 0);
if (wlen <= 0) return "";
std::wstring w(wlen - 1, L'\0');
MultiByteToWideChar(cp, 0, s, -1, &w[0], wlen);
int u8len = WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, NULL, 0, NULL, NULL);
if (u8len <= 0) return "";
std::string out(u8len - 1, '\0');
WideCharToMultiByte(CP_UTF8, 0, w.c_str(), -1, &out[0], u8len, NULL, NULL);
return out;
}
std::string ToAnsi(const std::string& utf8, UINT cp) {
if (utf8.empty()) return "";
int wlen = MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.size(), NULL, 0);
if (wlen <= 0) return utf8;
std::wstring w(wlen, L'\0');
MultiByteToWideChar(CP_UTF8, 0, utf8.c_str(), (int)utf8.size(), &w[0], wlen);
int alen = WideCharToMultiByte(cp, 0, w.c_str(), wlen, NULL, 0, NULL, NULL);
if (alen <= 0) return utf8;
std::string out(alen, '\0');
WideCharToMultiByte(cp, 0, w.c_str(), wlen, &out[0], alen, NULL, NULL);
return out;
}
bool Utf8ToCpExact(const std::string& utf8, UINT cp, std::string& out) {
out.clear();
if (utf8.empty()) return true;
int wlen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.c_str(), (int)utf8.size(), NULL, 0);
if (wlen <= 0) return false;
std::wstring w(wlen, L'\0');
if (MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, utf8.c_str(), (int)utf8.size(),
&w[0], wlen) != wlen)
return false;
BOOL usedDefault = FALSE;
int alen = WideCharToMultiByte(cp, WC_NO_BEST_FIT_CHARS, w.c_str(), wlen, NULL, 0, NULL, &usedDefault);
if (alen <= 0 || usedDefault) return false;
out.assign(alen, '\0');
usedDefault = FALSE;
if (WideCharToMultiByte(cp, WC_NO_BEST_FIT_CHARS, w.c_str(), wlen, &out[0], alen,
NULL, &usedDefault) != alen || usedDefault) {
out.clear();
return false;
}
return true;
}
bool IsValidUtf8(const char* s, size_t n) {
if (!s || n == 0) return true;
int wlen = MultiByteToWideChar(CP_UTF8, MB_ERR_INVALID_CHARS, s, (int)n, NULL, 0);
return wlen > 0;
}
void AuditManageAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail) {
if (!parent) return;
std::string text = "host " + std::to_string(devId) + " " + tool + ": " + detail;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP管理操作")));
}
void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail) {
if (!parent) return;
std::string text = "host " + std::to_string(devId) + " " + tool + ": " + detail;
parent->PostMessageA(WM_SHOWERRORMSG,
(WPARAM)new CString(ToAnsi(text, 936).c_str()),
(LPARAM)new CString(_TR("MCP远程交谈")));
}
// ===== 列表输出治理 =====
PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit, int maxLimit) {
PageWindow w;
w.limit = defaultLimit;
if (args.isObject()) {
if (args.isMember("limit") && args["limit"].isInt()) {
int v = args["limit"].asInt();
if (v > 0) w.limit = v; // 0/负数视为未指定,用默认值
}
if (args.isMember("offset") && args["offset"].isInt()) {
int v = args["offset"].asInt();
if (v > 0) w.offset = v;
}
}
if (w.limit > maxLimit) w.limit = maxLimit;
return w;
}
void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out) {
out = Json::Value(Json::arrayValue);
w.total = all.isArray() ? (int)all.size() : 0;
w.totalAll = w.total;
int begin = w.offset < w.total ? w.offset : w.total;
int end = (begin + w.limit < w.total) ? begin + w.limit : w.total;
for (int i = begin; i < end; ++i) out.append(all[i]);
w.returned = end > begin ? end - begin : 0;
w.hasMore = end < w.total;
}
void WritePageFields(Json::Value& structuredContent, const PageWindow& w) {
structuredContent["total"] = w.total;
structuredContent["totalAll"] = w.totalAll;
structuredContent["offset"] = w.offset;
structuredContent["limit"] = w.limit;
structuredContent["hasMore"] = w.hasMore;
}
void AppendPagingProps(Json::Value& props, int defaultLimit, int maxLimit) {
Json::Value limitProp(Json::objectValue);
limitProp["type"] = "integer";
limitProp["description"] = std::string(u8"本次最多返回的条数,默认 ") +
std::to_string(defaultLimit) + std::string(u8",上限 ") +
std::to_string(maxLimit) + std::string(u8"。");
props["limit"] = limitProp;
Json::Value offsetProp(Json::objectValue);
offsetProp["type"] = "integer";
offsetProp["description"] = u8"跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。";
props["offset"] = offsetProp;
}
void AppendBatchIdsProp(Json::Value& props) {
Json::Value idsProp(Json::objectValue);
idsProp["type"] = "array";
Json::Value items(Json::objectValue);
items["type"] = "string";
idsProp["items"] = items;
idsProp["description"] = std::string(u8"批量查询:一次传多台主机 id(最多 50 个),"
u8"结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;"
u8"limit/offset 对每台主机各自生效。");
props["ids"] = idsProp;
}
void MakeIdOrIdsRequired(Json::Value& schema) {
// 调用方可能先按单机 schema 生成了 required:["id"]:留着它会让「只传 ids」违反 schema
// (required 与 anyOf 同时生效)。这里只清理这一个精确形态,别的 required 不动。
if (schema.isMember("required") && schema["required"].isArray() &&
schema["required"].size() == 1 && schema["required"][0].isString() &&
schema["required"][0].asString() == "id") {
schema.removeMember("required");
}
Json::Value anyOf(Json::arrayValue);
for (const char* key : { "id", "ids" }) {
Json::Value alt(Json::objectValue);
Json::Value req(Json::arrayValue);
req.append(key);
alt["required"] = req;
anyOf.append(alt);
}
schema["anyOf"] = anyOf;
}
std::string PageSummary(const PageWindow& w, const char* unit) {
std::string s = std::string(u8"共 ") + std::to_string(w.total) + std::string(u8" ") + unit;
if (w.total == 0) return s + std::string(u8"。");
int begin = w.offset < w.total ? w.offset : w.total;
if (begin >= w.total) {
s += std::string(u8",offset 超出范围,本次返回 0 条。");
return s;
}
int end = (begin + w.limit < w.total) ? begin + w.limit : w.total;
s += std::string(u8",本次返回第 ") + std::to_string(begin + 1) + "-" +
std::to_string(end) + std::string(u8" 条");
if (w.hasMore) s += std::string(u8"(还有更多,可用 offset 继续取)");
return s + std::string(u8"。");
}
// ===== 工具注解(A3)=====
namespace {
struct ToolHints {
const char* name;
bool readOnly;
bool destructive;
bool idempotent;
bool openWorld; // false = 只读服务端本机状态(主机列表、审计日志),不触达外部主机
};
// 工具的语义登记表(全部工具,含开关门控后才会出现的)。新增工具必须在此登记
// (漏登记 → 走默认 destructiveHint=true)。
const ToolHints kToolHints[] = {
// --- 服务端本机只读 ---
{ "list_online_hosts", true, false, true, false },
{ "search_hosts", true, false, true, false },
{ "list_all_hosts", true, false, true, false },
{ "get_host_detail", true, false, true, false },
// get_activity_history 虽不含主机 id 之外的写操作,但要经主连接向目标主机发
// COMMAND_QUERY_ACTIVITY 取数据(McpServer.cpp:2249),属触达外部主机 → openWorld=true。
{ "get_activity_history", true, false, true, true },
{ "get_audit_log", true, false, true, false },
{ "get_server_status", true, false, true, false },
// P11:在飞会话的观测与取消。取消只改服务端自己的等待状态(被取消的请求立即走既有
// 清理路径),不改主机数据;按 request_id/session_id 取消天然幂等,故非破坏且幂等。
{ "mcp_list_sessions", true, false, true, false },
{ "mcp_cancel_session", false, false, true, false },
// --- 主机只读 ---
{ "list_processes", true, false, true, true },
{ "list_windows", true, false, true, true },
{ "list_files", true, false, true, true },
{ "list_services", true, false, true, true },
{ "get_client_log", true, false, true, true },
// get_keylog 默认只读;clear / set_offline 两个入参会改客户端状态(clear 还会删掉
// 已落盘的记录),故按「可写、可破坏」登记。
{ "get_keylog", false, true, false, true },
{ "get_screenshot", true, false, true, true },
{ "get_foreground_window", true, false, true, true },
{ "list_registry", true, false, true, true },
{ "download_file", true, false, true, true }, // 只读主机(写的是主控本机目录)
{ "search_file", true, false, true, true },
// --- 文件系统写操作(McpFileWrite)---
{ "delete_path", false, true, false, true },
{ "move_path", false, true, false, true },
{ "create_folder", false, false, true, true }, // 已存在时同样成功
{ "list_network_connections", true, false, true, true },
{ "host_list_processes", true, false, true, true },
{ "host_list_windows", true, false, true, true },
{ "host_list_network_state", true, false, true, true },
{ "host_list_software", true, false, true, true },
{ "host_list_browser_history", true, false, true, true },
{ "host_list_favorites", true, false, true, true },
{ "host_list_win32_services", true, false, true, true },
{ "host_list_driver_services", true, false, true, true },
{ "host_list_scheduled_tasks", true, false, true, true },
{ "host_get_hosts_file", true, false, true, true },
// --- 终端 ---
{ "terminal_open", false, false, true, true },
{ "terminal_exec", false, true, false, true }, // 任意命令,后果由命令决定
{ "exec_command", false, true, false, true },
{ "terminal_close", false, false, true, true },
// --- 远程控制 ---
{ "remote_open", false, false, true, true },
{ "remote_close", false, false, true, true },
{ "remote_keyboard", false, false, false, true },
{ "remote_mouse", false, false, false, true },
{ "remote_clipboard", false, false, false, true }, // 覆盖对端剪贴板
// 锁屏:改了远端设备状态(把人挡在锁屏界面外),重复调用结果相同 → 幂等。
{ "remote_lock_screen", false, true, true, true },
// 锁定对端键鼠:不破坏数据,但会把真人挡在电脑外,按「可破坏且非幂等」登记。
{ "remote_block_input", false, true, false, true },
// --- 文件传输 ---
{ "upload_file", false, true, false, true }, // 覆盖/新增远端文件
{ "copy_files_c2c", false, true, false, true }, // 覆盖/新增目标主机文件
// --- 设备管理(McpManage)---
{ "kill_process", false, true, false, true },
{ "operate_window", false, true, false, true },
{ "control_service", false, true, true, true }, // start/stop/set_* 重复执行同一状态
{ "power_action", false, true, false, true },
// --- 主机管理 / 连接管理(McpMachine)---
{ "kill_network_connection", false, true, false, true },
{ "host_control_process", false, true, false, true },
{ "host_control_window", false, true, false, true },
{ "host_control_service", false, true, true, true },
{ "host_control_task", false, true, false, true },
{ "host_set_remark", false, false, true, false }, // 只写服务端主机库
{ "host_set_watch_level", false, false, true, false },
// --- 远程交谈(McpChat)---
{ "chat_open", false, false, false, true },
{ "chat_send", false, false, false, true },
{ "chat_wait", false, false, false, true }, // 会取走 inbox 消息,不是纯读
{ "chat_close", false, false, true, true },
};
} // namespace
void ApplyToolAnnotations(Json::Value& tools) {
if (!tools.isArray()) return;
for (Json::Value& tool : tools) {
if (!tool.isObject() || !tool["name"].isString()) continue;
const std::string name = tool["name"].asString();
bool readOnly = false, destructive = true, idempotent = false, openWorld = true;
for (const auto& h : kToolHints) {
if (name == h.name) {
readOnly = h.readOnly;
destructive = h.destructive;
idempotent = h.idempotent;
openWorld = h.openWorld;
break;
}
}
Json::Value ann(Json::objectValue);
ann["readOnlyHint"] = readOnly;
// 只读工具的 destructiveHint 按规范无意义,统一置 false,免得客户端误报「破坏性」。
ann["destructiveHint"] = readOnly ? false : destructive;
ann["idempotentHint"] = idempotent;
ann["openWorldHint"] = openWorld;
tool["annotations"] = ann;
}
}
// ===== 批量只读调用(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