Files
SimpleRemoter/server/2015Remote/McpInternal.cpp
T
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

586 lines
24 KiB
C++
Raw Permalink 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 "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");
}
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 },
{ "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_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