Files
SimpleRemoter/server/2015Remote/McpInternal.cpp
T
yuanyuanxianganddeepseek-flash bb55f52b29 Feature: Add instructions, capability reporting and filters to MCP
P10-A is the first batch of the next MCP phase: the server now tells a model
how it expects to be driven instead of leaving the rules to be inferred from
per-tool descriptions.

initialize carries the instructions field that MCP 2025-06-18 defines, in
five sections: where host ids come from, which switch hides which tool, what
each error code implies for the next action, typical orchestrations, and
safety. Every statement was checked against the implementation rather than
derived from the tool descriptions, and four did not survive: the host_*
family only supports name/pid filters in part (named per tool now), read-only
mode does not hide host_set_remark and host_set_watch_level (they touch only
the local host store and are refused with -32006 when called), -32003 is one
lock keyed by device id rather than one per capability, and there is no
"screen stream" tool to pick instead of get_screenshot. The string is built
from u8 literals because the project compiles with /execution-charset:.936.

get_host_detail returns a capabilities object (platform, screenPreview,
remoteControl, fileTransferV2, c2cPaths, registry), each flag tied to a gate
that already exists in the dispatcher, so a model no longer discovers a
host's limits by calling and reading -32005. remoteControl mirrors the two
conditions remote_* actually applies (Windows or Linux, and not
multi-monitor), not the preview bit. Making the flags honest exposed
list_registry rejecting only LNX and MAC, so an APK host passed and then
waited out the timeout; it now uses the same is-Windows predicate the bit is
computed from. That predicate existed as identical local copies in
McpMachine.cpp and McpChat.cpp and now lives in McpInternal.

list_processes and list_windows take an optional name and pid, filtered on
the server before the page window is applied, with total counting matches
and totalAll still reporting the unfiltered count. The two tools get their
own schema builder so list_services does not advertise a filter it would
silently ignore, and the pid descriptions differ because a pid means the
process itself for one tool and its owner for the other.

get_keylog gains set_offline and clear, the two commands the client already
implements on the keyboard sub-connection but nothing on the MCP side ever
sent, plus offlineRecord from the ready packet's byte 1. Both writes are
gated on McpReadonly=0 and validated before COMMAND_KEYBOARD goes out, so a
refused call cannot leave a running keyboard session behind; the tool's
annotations change from read-only to writable and destructive, and the
server instructions gain the matching sentence.

Four capabilities are exposed twice through two different sub-connection
chains, so each pair's descriptions now say which one to reach for first and
when the other is the only option: the host_* trio carries more fields and
filters on the server, the list_* trio is the McpMachine=0 fallback, and
operate_window is the only one that can close a window. No tool was merged:
the split is what lets McpMachine be switched off on its own. search_file's
description drops the stale MAX_PATH-overflow warning (fixed in 8f718d9) for
the behaviour that remains - the client silently skips any entry whose full
path does not fit, so a drive-root scan misses deep results and reaches the
10000-entry cap sooner.

Verified per commit by building the Debug x64 server, starting it on a spare
port so the running Release instance could not answer instead, and reading
the fields back out of real responses as UTF-8; tools/list shows 54 tools
with the edited descriptions present. Bin/settings.ini was restored
byte-exact and the Release instance was left alone. The smoke test gained
assertions for all four additions: instructions has to parse out of
initialize, capabilities is compared against the reported platform (registry
true exactly for the Windows client types, remoteControl false on macOS and
Android), the filters query a real entry back by name and by pid while
totalAll stays put, and offlineRecord accepts both a boolean and its absence
for old clients. That script ran 28 checks clean against this build, with
the host-scoped assertions exercised against synthetic responses on a
separate harness (12 of 12, including the negative cases).

Co-Authored-By: deepseek-flash
2026-10-28 21:25:44 +01:00

473 lines
19 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 "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 = 只读服务端本机状态(主机列表、审计日志),不触达外部主机
};
// 54 个工具的语义登记表。新增工具必须在此登记(漏登记 → 走默认 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 },
// --- 主机只读 ---
{ "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 },
{ "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 }, // 覆盖对端剪贴板
// --- 文件传输 ---
{ "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;
}
}
} // namespace McpInternal