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

169 lines
8.8 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.
#pragma once
// MCP 工具实现共享的内部辅助函数。
//
// 这些函数原先都定义在 McpServer.cpp 的匿名命名空间里;主机管理 / 连接管理
// 工具族(McpMachine.cpp)需要复用同一套 JSON、host id 解析与编码转换逻辑,
// 故抽出到独立编译单元,由 McpServer.cpp 与 McpMachine.cpp 共同引用。
//
// 约定:函数语义与实现与抽取前完全一致(McpServer.cpp 通过 using-directive
// 引入,调用点不变),不做行为改动。
#include <Windows.h>
#include "jsoncpp/json.h"
#include <string>
#include <cstdint>
class CMy2015RemoteDlg;
class context;
namespace McpInternal {
// ===== 错误码(-32000 系列,见 docs/Mcp_Design.md §12)=====
//
// -32012 参数被校验拒绝:参数内容非法、按 message 改正后重试即可(shell 元字符、
// 控制字符之类)。-32008 是同一语义的历史别名:早期实现用它,已发布的文档与客户端
// 可能仍在匹配,故保留不改;新代码一律用 -32012。
const int kErrValidation = -32012;
const int kErrValidationOld = -32008; // 历史别名,勿新增使用
// -32800 请求被客户端取消:收到 notifications/cancelled 或 mcp_cancel_session 后,
// 在飞的工具提前退出(走各自的超时清理路径),结果统一以这个码回报。
const int kErrCancelled = -32800;
// Json::Value → 紧凑 JSON 字符串
std::string JsonToString(const Json::Value& v);
// JSON-RPC 2.0 成功 / 错误响应
std::string BuildResult(const Json::Value& id, const Json::Value& result);
std::string BuildError(const Json::Value& id, int code, const std::string& msg);
// ===== 结果外露(content 文本块)=====
//
// MCP 规范(Tools > Structured Content)要求:返回 structuredContent 的工具,
// 应同时把序列化后的 JSON 放进一个 TextContent 块。有些客户端(如 WorkBuddy)
// 只把 content 交给模型、完全忽略 structuredContent——不补这一块,模型就拿不到
// id / session_id / pid 这类串联下一跳的关键字段,只能看到「共 N 台主机匹配」。
//
// 因此 BuildResult 默认给每个带非空 structuredContent 的结果追加一个文本块
// (紧凑 JSON)。工具的正文已经承载同一份载荷时,用 SetStructuredTextPayload
// 指定只外露哪部分,避免同一份内容在上下文里出现两三次:
//
// exec_command / terminal_exec → {"exit_code":N} (stdout 已在正文里)
// get_keylog → 行数/字节数等元数据(行已在正文里)
// get_activity_history → {"records":[…]}
// host_get_hosts_file → 去掉 content 的 sc (原文已在 lines 里)
void AppendStructuredText(Json::Value& result, const Json::Value& payload); // 内部用
void AppendStructuredText(Json::Value& result); // 内部用
// 本次结果只外露 payload(BuildResult 消费后移除,不出现在响应里)。
// payload 为空对象/空数组时本次不追加文本块。
void SetStructuredTextPayload(Json::Value& result, const Json::Value& payload);
// 仅 ASCII 小写化;不区分大小写的子串匹配
std::string ToLowerAscii(const std::string& s);
bool ContainsCI(const std::string& haystack, const std::string& needle);
// 入参读取
std::string JsonStrField(const Json::Value& v, const char* key);
bool IsDigits(const std::string& s);
std::string GetStringArg(const Json::Value& args, const char* key);
bool GetIntArg(const Json::Value& args, const char* key, int& out);
bool ReadUInt64(const Json::Value& v, uint64_t& out);
bool ReadUInt64Arg(const Json::Value& args, const char* key, uint64_t& out);
// 解析 id 入参(必填、纯数字)为 uint64;非法返回 false 并写 err。
bool ParseHostIdArg(const Json::Value& args, uint64_t& out, std::string& err);
// 在 m_HostList 中按 clientID 找在线主 context(锁内遍历 m_cs)。
context* FindMainContext(CMy2015RemoteDlg* parent, uint64_t id);
// 客户端是否为 Windows 形态(EXE/DLL/MEXE/SC/MDLL);LNX / MAC / APK 返回 false。
// 用于「只有 Windows 客户端实现了这个能力」的判断(注册表、窗口、服务等)。
bool IsWindowsClient(context* ctx);
// 有界 strlen:p 最多可读 avail 字节,返回 n < avail 表示遇到 '\0'。
size_t BoundedStrlen(const char* p, size_t avail);
// 编码转换:任意代码页 → UTF-8(输出 JSON 用);UTF-8 → 目标代码页(下发客户端用)。
std::string ToUtf8(const char* s, UINT cp);
std::string ToAnsi(const std::string& utf8, UINT cp);
// 严格 UTF-8 → 目标代码页:任一字符无法表示即失败(不用 '?' 顶替)。
// UTF-8 本身非法也失败。聊天消息用它拒绝 GBK 不可表示的字符(emoji 等)。
bool Utf8ToCpExact(const std::string& utf8, UINT cp, std::string& out);
// 校验字节串是否为合法 UTF-8(n=0 视为合法)。
bool IsValidUtf8(const char* s, size_t n);
// 写操作审计:PostMessageA(WM_SHOWERRORMSG) 落到服务端消息/审计日志(不可关闭)。
void AuditManageAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail);
// 远程交谈审计:与 AuditManageAction 同落地方式,标题区分(MCP远程交谈)。
// 只记录会话 id / 字节数,绝不记录消息正文。
void AuditChatAction(CMy2015RemoteDlg* parent, uint64_t devId,
const std::string& tool, const std::string& detail);
// ===== 列表输出治理 =====
//
// 列表类工具统一走 limit/offset:默认 limit=100,硬上限 1000,offset 默认 0。
// structuredContent 里同时给出 total/totalAll/offset/limit/hasMore,与
// McpMachine.cpp 的 host_list_*/list_network_connections 保持同一套字段,
// 调用方据此翻页,而不是让一次返回把上下文撑爆。
struct PageWindow {
int offset = 0;
int limit = 100;
int total = 0; // ApplyPageWindow 填入:切片前的总条数(本工具无二次过滤,故等于 totalAll)
int totalAll = 0;
int returned = 0; // 本次实际返回条数
bool hasMore = false; // 窗口之后还有条目(供调用方判断是否继续翻页)
};
// 读 args 里的 limit/offset(缺省/非法/非正数按默认值,limit 超上限截断到上限)。
PageWindow ResolvePageWindow(const Json::Value& args, int defaultLimit = 100, int maxLimit = 1000);
// 按窗口切片:out = all[offset, offset+limit),并回填 w.total/totalAll/returned/hasMore。
void ApplyPageWindow(const Json::Value& all, PageWindow& w, Json::Value& out);
// 把 total/totalAll/offset/limit/hasMore 写进 structuredContent。
void WritePageFields(Json::Value& structuredContent, const PageWindow& w);
// 往 inputSchema 的 properties 追加 limit / offset 两个字段。
void AppendPagingProps(Json::Value& props, int defaultLimit = 100, int maxLimit = 1000);
// 往 inputSchema 的 properties 追加 ids(只读工具的批量入口,最多 50 个 id)。
void AppendBatchIdsProp(Json::Value& props);
// 把 inputSchema 的必填约束改成「id 或 ids 二选一」。
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 /
// idempotentHint / openWorldHint),让 MCP 客户端能按语义分组审批、默认折叠只读工具。
// 名称未在注解表里的工具按 schema 规范的默认值处理(destructiveHint=true),
// 即「新增工具必须显式登记」,漏登记只会更保守,不会误标成只读。
void ApplyToolAnnotations(Json::Value& tools);
} // namespace McpInternal