Feature: Reject MCP tool calls the target client cannot handle

tools/list 不带参数,无法按目标设备过滤工具列表。60 个工具里有 33 个只在
Windows 客户端上有实现,模型无从得知,只能下发命令后白等超时。

DispatchSingleHostTool 开头按 kToolPlatforms 表核对目标主机平台,不匹配立刻
返回 -32005;批量路径经由同一函数自动覆盖。主机不存在或离线时放行,把 -32002
留给工具自己报,避免同一个问题出现两种错误码。

支持面是刻意设计的阶梯:win 60/60、lnx 27、mac 16、apk 10。60 个工具全部含
win,所以 Windows 客户端永远不会被这道门禁拒绝,行为与改动前完全一致。

平台表按服务端实际放行来标,不按客户端能力标。两处会分叉的地方:

- exec_command / terminal_* / kill_process:macOS 客户端有实现(main.mm:753 的
  ShellworkingThread、SystemManager 的 KILLPROCESS),但服务端刻意拦着
  (McpServer.cpp:3652「macOS 本轮不开放」、6870),故标 win+lnx。
- list_windows:Linux/macOS 的 SystemManager 都有 COMMAND_WSLIST 分支,但
  BuildListWindows 把命令发在主连接上,而这两个平台的主循环只处理 COMMAND_SYSTEM
  (起子连接),WSLIST 只在子连接里才被处理,走不到。实测 Linux 上直接超时
  -32001。那两个 case 是给 SystemDlg 用的,故标 win。

copy_files_c2c 是唯一的非对称工具(源端必须 Windows,目标端可 win/lnx/mac,
反向不支持),用 roles 按参数名分别声明,C++ 侧 CollectTargetReqs 对应处理。

配套 mcp/tools.json(60 个工具,version 2)与 tools/mcp_tools/ 下的抓取、生成、
比对、校验脚本。check_platform_table.py 校验 C++ 表、tools.json、instructions
三方一致,并把「Windows 全量」做成不变式。

已在 A6(Windows 11)与 Ubuntu24(Linux)上实测:Windows 侧 14/14 通过且无误拒,
Linux 侧 11 项拒绝全部命中门禁,copy_files_c2c win->lnx 成功、lnx->win 被拒。

开关 McpPlatformGuard(默认 1),关闭只失去提前拦截,不影响任何执行路径。
This commit is contained in:
yuanyuanxiang committed 2026-11-03 16:06:41 +01:00
1 parent 8c0351b45b
commit 356aa27108
10 files changed
+7085 -1

No files matched your search

+6
View File
@@ -97,3 +97,9 @@ server/go/devices.json
server/go/build/
server/go/.claude/settings.json
android/app/.cxx/
# MCP 工具清单的中间产物(dump_tools.py 的默认输出)
tools_raw.json
# AI 助手的本地工作记忆(含个人上下文,与 .claude/settings.json 同理)
.workbuddy-ai/
+5845
View File
File diff suppressed because it is too large. Load diff
+4
View File
@@ -2549,6 +2549,10 @@ BOOL CMy2015RemoteDlg::OnInitDialog()
McpServer().SetChatEnabled(THIS_CFG.GetInt("settings", "McpChat", 0) != 0);
// N3 键盘记录(get_keylog):独立开关默认关,与只读开关无关。
McpServer().SetKeylogEnabled(THIS_CFG.GetInt("settings", "McpKeylog", 0) != 0);
// 平台门禁:默认开。调用前拦掉目标客户端根本没实现的工具(立刻 -32005),
// 否则会照常下发命令然后白等超时。关掉它只影响这道拦截,不改任何工具的执行路径。
McpServer().SetPlatformGuardEnabled(
THIS_CFG.GetInt("settings", "McpPlatformGuard", 1) != 0);
// 工具默认等待超时(ini-only 键,无设置界面):默认 20000ms,clamp 在 SetToolTimeoutMs 内。
McpServer().SetToolTimeoutMs(THIS_CFG.GetInt("settings", "McpToolTimeoutMs", 20000));
// HTTPS(native TLS):McpHttps=1 时对外端口说 TLS,httplib 退到回环内部端口。
+239 -1
View File
@@ -325,7 +325,31 @@ const char* kServerInstructions =
u8"客户端无管理员权限时 Windows 会让 BlockInput 静默失败,成功只代表命令已送达)。\n"
u8"命令执行:exec_command 一次性取输出;需要保持 cd 或环境变量时用 terminal_open + terminal_exec,用毕 terminal_close。\n"
u8"\n"
u8"5) 安全约定\n"
u8"5) 客户端平台差异\n"
u8"工具能否执行取决于目标主机的平台,这与服务端开关无关,两者是叠加关系。调用前用 "
u8"list_online_hosts / get_host_detail 的 capabilities.platform 确认,宁可先查一次,不要先试后错。\n"
u8"支持面从宽到窄依次是 win > lnx > mac ≈ apk:Windows 是唯一全量支持的平台,Linux 次之,"
u8"macOS 与 Android 只覆盖一部分。拿不准时按这个顺序假设。\n"
u8"win(EXE / DLL / MEXE / SC / MDLL):全部工具可用。\n"
u8"lnx(LNX):不支持服务、注册表、键日志、活动历史、文件搜索/删除/移动/建目录、"
u8"窗口列表(list_windows)、网络连接列表与断开"
u8"(list_network_connections / kill_network_connection)、"
u8"块输入、host_* 全族、chat_* 全族、operate_window、power_action。远程控制与截屏要求目标机"
u8"有 X11/Xorg(或 XWayland)桌面,纯 Wayland 或无桌面的服务器不行。\n"
u8"mac(MAC):在 lnx 的基础上,还不支持远程控制全族(remote_open / remote_close / "
u8"remote_mouse / remote_keyboard / remote_clipboard)、get_screenshot、"
u8"exec_command、terminal_open / terminal_exec / terminal_close"
u8"(客户端有 PTY 实现,但服务端本轮未开放)、kill_process;"
u8"文件传输、进程列表、日志可用。\n"
u8"apk(APK):只支持主机列表(list_online_hosts / list_all_hosts)/ 详情 / 搜索 / "
u8"审计日志 / 服务状态 / 会话管理,以及 "
u8"host_set_remark / host_set_watch_level 这两个只改服务端本地数据的工具。其余一律不支持"
u8"(客户端未实现 SYSTEM 与 SHELL)。\n"
u8"copy_files_c2c 是唯一有方向性的工具:源端 src_id 必须是 win,目标端 dst_id 可以是 "
u8"win / lnx / mac。Linux 和 macOS 只能当接收方,不能当发送方(反向不支持)。\n"
u8"这些不支持的组合会立刻返回 -32005,不会白等超时;反之,遇到超时不要当成平台不支持。\n"
u8"\n"
u8"6) 安全约定\n"
u8"写操作前先读一次现状,动作后再用读工具复核;删改类工具的 ok 只表示命令已送达客户端,不代表成功。"
u8"涉及删除、重启、结束进程、关机等不可逆操作时,先把目标和影响范围讲给用户,得到确认再执行。"
u8"主机上可能有人正在办公,注入输入、截屏、关机都是会被察觉的动作。";
@@ -8765,6 +8789,213 @@ static const long long kBatchDeadlineMs = 50000;
// IsBatchReadOnlyTool 定义在 McpInternal.cpp:tools/list 要用它补 outputSchema,
// tools/call 要用它做批量入口判定,两处必须共用同一份清单,故不再在此重复定义。
// ===== 平台门禁:调用前拦掉「该客户端根本没实现」的组合 =====
//
// 判据来自各平台客户端对相应 COMMAND_ 的处理实现,不能看「是否引用了常量」:
// - android/.../main.cpp:534-540 的 COMMAND_SYSTEM / COMMAND_SHELL 都是空实现
// - macOS 能处理 SEND_FILE_V2,但 DefaultCaps() 不给 SCREEN_PREVIEW,截屏仍不可用
// 表内容与 mcp/tools.json 的 platforms 字段一一对应,
// tools/mcp_tools/check_platform_table.py 会校验两边一致。
//
// 这里只做平台级粗筛。能力位门槛(SCREEN_PREVIEW / V2 / C2C_PATHS)仍留在各工具内部,
// 因为像「Linux 这台机器有没有 X11 桌面」只有运行时才知道。
enum : uint8_t {
kPlatWin = 1,
kPlatLnx = 2,
kPlatMac = 4,
kPlatApk = 8,
};
struct ToolPlatform {
const char* name;
uint8_t mask;
};
// mask 为 0 或表里查不到 = 不限制。新增工具忘了登记时按放行处理(宁可漏拦,不可误拒),
// 遗漏由 check_platform_table.py 的工具数比对发现。
const ToolPlatform kToolPlatforms[] = {
// ---- win+lnx+mac+apk ---- 只读写服务端本地数据,与客户端平台无关
{ "list_online_hosts", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "search_hosts", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "list_all_hosts", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "get_host_detail", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "get_audit_log", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "get_server_status", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "mcp_list_sessions", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "mcp_cancel_session", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "host_set_remark", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
{ "host_set_watch_level", kPlatWin|kPlatLnx|kPlatMac|kPlatApk },
// ---- win+lnx+mac ---- SYSTEM / LIST_DRIVE / QUERY_LOG / V2 文件传输
{ "list_processes", kPlatWin|kPlatLnx|kPlatMac },
{ "list_files", kPlatWin|kPlatLnx|kPlatMac },
{ "get_client_log", kPlatWin|kPlatLnx|kPlatMac },
{ "download_file", kPlatWin|kPlatLnx|kPlatMac },
{ "upload_file", kPlatWin|kPlatLnx|kPlatMac },
// ---- win+lnx ---- 远程控制全族 + 需 SCREEN_PREVIEW 的截屏 + macOS 未开放项
{ "get_screenshot", kPlatWin|kPlatLnx },
{ "remote_open", kPlatWin|kPlatLnx },
{ "remote_close", kPlatWin|kPlatLnx },
{ "remote_keyboard", kPlatWin|kPlatLnx },
{ "remote_mouse", kPlatWin|kPlatLnx },
{ "remote_clipboard", kPlatWin|kPlatLnx },
// macOS 客户端有 PTY 实现(macos/main.mm:753),但服务端刻意不开放
// (McpServer.cpp:3652「macOS 本轮不开放」),故实际不可用
{ "exec_command", kPlatWin|kPlatLnx },
{ "terminal_open", kPlatWin|kPlatLnx },
{ "terminal_exec", kPlatWin|kPlatLnx },
{ "terminal_close", kPlatWin|kPlatLnx },
// macOS 客户端有 COMMAND_KILLPROCESS 分支,服务端同样拦着(McpServer.cpp:6870)
{ "kill_process", kPlatWin|kPlatLnx },
// ---- win ---- 服务 / 注册表 / 键日志 / 文件写 / host_* / chat_* / power_action
// list_windows 单列:BuildListWindows 把 COMMAND_WSLIST 发在**主连接**上
// (McpServer.cpp:2931 的 Send2Client),而 Linux/macOS 主循环只处理 COMMAND_SYSTEM
// (起 SystemManager 子连接),WSLIST 只在子连接里处理 —— 走不到,实测 Linux 上
// 直接超时 -32001。Windows 是在主循环里处理的(client/KernelManager.cpp:1491)。
// 注意别被 linux/SystemManager.h:38 和 macos/SystemManager.mm:39 的 case 骗到,
// 那是给 SystemDlg 窗口管理用的,不是 MCP 这条路径。
{ "list_windows", kPlatWin },
{ "get_activity_history", kPlatWin },
{ "list_services", kPlatWin },
{ "get_keylog", kPlatWin },
{ "list_registry", kPlatWin },
{ "remote_block_input", kPlatWin },
// 两端并集。方向性差异由 CollectTargetReqs 精确处理:源端必须 win,目标端 win/lnx/mac
{ "copy_files_c2c", kPlatWin|kPlatLnx|kPlatMac },
{ "operate_window", kPlatWin },
{ "control_service", kPlatWin },
{ "power_action", kPlatWin },
{ "search_file", kPlatWin },
{ "delete_path", kPlatWin },
{ "move_path", kPlatWin },
{ "create_folder", kPlatWin },
{ "list_network_connections", kPlatWin },
{ "kill_network_connection", kPlatWin },
{ "host_list_processes", kPlatWin },
{ "host_list_windows", kPlatWin },
{ "host_list_network_state", kPlatWin },
{ "host_list_software", kPlatWin },
{ "host_list_browser_history", kPlatWin },
{ "host_list_favorites", kPlatWin },
{ "host_list_win32_services", kPlatWin },
{ "host_list_driver_services", kPlatWin },
{ "host_list_scheduled_tasks", kPlatWin },
{ "host_get_hosts_file", kPlatWin },
{ "host_control_process", kPlatWin },
{ "host_control_window", kPlatWin },
{ "host_control_service", kPlatWin },
{ "host_control_task", kPlatWin },
{ "chat_open", kPlatWin },
{ "chat_send", kPlatWin },
{ "chat_wait", kPlatWin },
{ "chat_close", kPlatWin },
};
// 未知的 clientType 一律按 Windows:EXE/DLL/MEXE/SC/MDLL 都走这个分支,
// 将来新增平台在没有明确登记前也不会被误拦。
uint8_t CurrentClientPlatform(context* ctx) {
CString t = ctx->GetAdditionalData(RES_CLIENT_TYPE);
if (t == "LNX") return kPlatLnx;
if (t == "MAC") return kPlatMac;
if (t == "APK") return kPlatApk;
return kPlatWin;
}
const char* PlatformName(uint8_t p) {
switch (p) {
case kPlatLnx: return "lnx";
case kPlatMac: return "mac";
case kPlatApk: return "apk";
default: return "win";
}
}
std::string PlatformNames(uint8_t mask) {
std::string s;
if (mask & kPlatWin) s += "win ";
if (mask & kPlatLnx) s += "lnx ";
if (mask & kPlatMac) s += "mac ";
if (mask & kPlatApk) s += "apk ";
if (!s.empty()) s.pop_back();
return s;
}
// 一台主机 + 它在这个工具里被允许的平台集合。
struct TargetReq {
uint64_t id;
uint8_t mask;
};
bool AddIdReq(const Json::Value& args, const char* key, uint8_t mask,
std::vector<TargetReq>& reqs) {
if (!args[key].isString()) return false;
const std::string sid = args[key].asString();
if (sid.empty() || sid.find_first_not_of("0123456789") != std::string::npos) return false;
reqs.push_back({ strtoull(sid.c_str(), nullptr, 10), mask });
return true;
}
// 取出这个工具真正要操作的主机,以及每台主机各自的平台要求。
// 绝大多数工具只有一个目标、用统一的 defaultMask;copy_files_c2c 是唯一的
// 非对称工具,源端和目标端的平台要求不同,必须分开查:
// src_id —— 只有 Windows 实现了 C2C 发送逻辑(client/KernelManager.cpp)
// dst_id —— 只需 CLIENT_CAP_V2 收包,Windows / Linux / macOS 都行
// 反过来 Linux → Windows 不支持:POSIX 客户端没有 C2C_PATHS 发送实现。
// 返回 false = 这个工具不针对某台主机(服务端本地工具),不需要门禁。
bool CollectTargetReqs(const std::string& toolName, const Json::Value& args,
uint8_t defaultMask, std::vector<TargetReq>& reqs) {
// 多主机工具必须先判断:它的 schema 里没有 "id",但调用方可以多塞一个 id 进来。
// 若先走 ParseHostIdArg,就只会检查那一台主机,真正的 src_id / dst_id 反而漏过去。
if (toolName == "copy_files_c2c") {
AddIdReq(args, "src_id", kPlatWin, reqs);
AddIdReq(args, "dst_id", kPlatWin|kPlatLnx|kPlatMac, reqs);
return !reqs.empty();
}
uint64_t devId = 0;
std::string err;
if (!ParseHostIdArg(args, devId, err)) return false; // 无 id:服务端本地工具
reqs.push_back({ devId, defaultMask });
return true;
}
// 返回空串 = 放行;非空 = 可直接作为 tools/call 结果返回的错误 JSON。
// 主机不存在/离线时跳过该 id,把 -32002 留给工具自己报,避免同一问题出现两种错误码。
std::string CheckToolPlatform(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent) {
if (!CMcpServer::Instance().IsPlatformGuardEnabled()) return "";
uint8_t mask = 0;
for (const ToolPlatform& e : kToolPlatforms) {
if (toolName == e.name) { mask = e.mask; break; }
}
if (mask == 0) return "";
std::vector<TargetReq> reqs;
if (!CollectTargetReqs(toolName, args, mask, reqs)) return ""; // 无 id:服务端本地工具
for (const TargetReq& req : reqs) {
context* ctx = FindMainContext(parent, req.id);
if (!ctx) continue;
const uint8_t cur = CurrentClientPlatform(ctx);
if (req.mask & cur) continue;
CString ct = ctx->GetAdditionalData(RES_CLIENT_TYPE);
std::string msg;
msg += std::string(u8"该主机平台是 ");
msg += PlatformName(cur);
msg += std::string(u8"(clientType=");
msg += std::string((LPCSTR)ct);
msg += std::string(u8"),");
msg += toolName;
msg += std::string(u8" 在此主机上仅支持 ");
msg += PlatformNames(req.mask);
msg += std::string(u8"。按 instructions 第 5 节换用该平台支持的等价工具。");
return BuildError(id, -32005, msg);
}
return "";
}
// 单主机分派:批量路径复用它,保证批量与单机走同一套实现。
std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent);
@@ -8933,6 +9164,13 @@ std::string BuildToolsCall(const Json::Value& root, CMy2015RemoteDlg* parent) {
std::string DispatchSingleHostTool(const Json::Value& id, const std::string& toolName,
const Json::Value& args, CMy2015RemoteDlg* parent) {
// 平台门禁:放在所有分派之前,批量路径也会经过这里(BuildBatchCall 循环调用本函数),
// 所以不需要在批量入口重复一次。主机不存在/离线时放行,让各工具自己报 -32002。
{
std::string platErr = CheckToolPlatform(id, toolName, args, parent);
if (!platErr.empty()) return platErr;
}
// P8:连接管理 / 主机管理工具族(独立分发;门控在 McpMachine::Call 内复核)。
if (McpMachine::Handles(toolName)) return McpMachine::Call(id, toolName, args, parent);
+9
View File
@@ -605,6 +605,11 @@ public:
bool IsReadonly() const { return m_readonly; }
const std::string& GetCmdWhitelist() const { return m_cmdWhitelist; }
// 平台门禁开关:默认开。关闭只影响「错误平台上的调用是否被提前拦住」,
// 不影响任何工具的正常执行路径,可作为出问题时的应急回退手段。
void SetPlatformGuardEnabled(bool enabled) { m_platformGuard = enabled; }
bool IsPlatformGuardEnabled() const { return m_platformGuard; }
// 监听地址/端口(Start 时记录,供 get_server_status 报告)。
const std::string& GetBind() const { return m_bind; }
int GetPort() const { return m_port; }
@@ -938,6 +943,10 @@ private:
bool m_machineEnabled = false; // P8 主机管理族总开关(默认关;16 个 host_* 工具)
bool m_machineDangerousEnabled = false; // P8 高风险子集(冻结/解冻进程、停止/重启服务)
bool m_keylogEnabled = false; // N3 键盘记录开关(默认关;get_keylog)
// 平台门禁(默认开):调用前拦掉「该客户端根本没实现」的工具,立刻返回 -32005。
// 关闭后这类调用会照常下发命令,通常表现为白等超时。判据表见 McpServer.cpp 的
// kToolPlatforms,与 mcp/tools.json 的 platforms 字段对应。
bool m_platformGuard = true;
int m_toolTimeoutMs = 20000; // 工具默认等待超时(McpToolTimeoutMs,见 SetToolTimeoutMs)
};
+205
View File
@@ -0,0 +1,205 @@
# MCP 工具清单维护
`mcp/tools.json` 是 MCP 全部 60 个工具的**单一来源候选**:工具名、描述、
inputSchema、outputSchema,以及运行时不可见的开关元信息(`gate` / `write` / `manage`)。
它的用途不限于给 Go 服务端复用。当前 26KB 的工具描述埋在 11k 行 C++ 里,
没有人能整体 review 一遍;抽成一份 JSON 后可以 diff、可以搜索、可以一眼看出
哪些工具描述含糊或功能重叠。
## 文件
| 路径 | 作用 |
|---|---|
| `mcp/tools.json` | 工具清单本体(生成产物,勿手工编辑) |
| `tools/mcp_tools/dump_tools.py` | 从运行中的服务端抓 `tools/list` |
| `tools/mcp_tools/make_tools_json.py` | 把抓取结果转成 `tools.json`(含 gate / platforms 表) |
| `tools/mcp_tools/verify_tools.py` | 校验 `tools.json` 与服务端是否一致 |
| `tools/mcp_tools/check_platform_table.py` | 校验 `tools.json` 的 `platforms` 与 C++ `kToolPlatforms` 一致 |
## 更新流程
改动 C++ 里的工具定义(`McpServer.cpp` / `McpMachine.cpp` / `McpChat.cpp`)之后:
```bash
# 0. 先重编并启动主控端,确保服务端跑的是新代码
cd C:/github/YAMA
# 1. 抓取(token 自动从注册表读;端口自动探测 6545/6544)
python tools/mcp_tools/dump_tools.py "" /tmp/tools_raw.json
# 2. 生成
python tools/mcp_tools/make_tools_json.py /tmp/tools_raw.json mcp/tools.json
# 3. 校验
python tools/mcp_tools/verify_tools.py --live mcp/tools.json
```
第 3 步输出 `PASS: 60 个工具完全一致` 才算成功。
### 如果工具数量变了
`make_tools_json.py` 里的 `GATE` 和 `PLATFORMS` 两张表是**手工维护**的,新增工具会直接报错退出:
```
!! GATE 表缺少 1 个工具: ['new_tool']
!! PLATFORMS 表缺少 1 个工具: ['new_tool']
```
这是有意为之——`gate` / `write` / `manage` 三项在运行时不可见,只能从 C++
注册点的 `if` 条件读出来,必须人工确认。补表时对照:
- `McpServer.cpp:BuildToolsListResult` —— 内联的 40 个
- `McpMachine.cpp:AppendTools` —— 16 个(总开关 `IsMachineEnabled` 用 early return)
- `McpChat.cpp:AppendTools` —— 4 个(总开关 `IsChatEnabled` 用 early return)
`PLATFORMS` 还要额外核对各平台客户端有没有实现对应命令,见下节。
## 字段说明
| 字段 | 含义 |
|---|---|
| `gate` | 该工具出现所需的开关(`null` = 无条件)。取值:`machine` / `chat` / `terminal` / `remote_control` / `file_transfer` / `file_write` / `keylog` / `manage` |
| `write` | 需要 `!McpReadonly` |
| `manage` | 额外需要 `McpManage`(仅 `kill_network_connection` 用到) |
| `platforms` | 该工具涉及的**任一主机**都必须落在此集合内:`win` / `lnx` / `mac` / `apk` |
| `roles` | 仅多主机工具才有。按参数名细分平台,表达 `platforms` 说不清的方向性能力 |
| `impl` | 已实现该工具的服务端:`mfc` / `go` / `both` |
`gate` / `write` / `manage` 只描述**可见性**,不描述行为。像
「`McpMachine` 开启时 `host_list_processes` 优先、关闭时退回 `list_processes`」
这类互斥/降级关系属于逻辑,仍然留在代码里。
## platforms 怎么判定
**只看各平台客户端有没有实现对应命令,不能看「是否引用了 COMMAND_ 常量」。**
两个真实的反例:
- `android/.../main.cpp` 里 `COMMAND_SYSTEM` 和 `COMMAND_SHELL` 都有 `case` 分支,
但内容是 `LOGI("... (not implemented)")` —— 引用 ≠ 实现。
- `macos/` 能处理 `COMMAND_SEND_FILE_V2`,但 `DefaultCaps()` 在 macOS 上只给
`V2|UTF8`,没有 `SCREEN_PREVIEW`,所以 `get_screenshot` 在 macOS 上仍不可用。
判定时要同时看**命令实现**和**能力位**:
| 依据 | 位置 |
|---|---|
| 命令分支 | `client/`、`linux/main.cpp`、`macos/main.mm`、`android/app/src/main/cpp/main.cpp` |
| 能力位 | `common/commands.h` 的 `LOGIN_INFOR::DefaultCaps()`;Linux 另在 `linux/main.cpp:RefreshLoginCaps` 追加 `SCREEN_PREVIEW` |
当前分布(60 个工具):
| platforms | 数量 | 典型工具 |
|---|---|---|
| `win+lnx+mac+apk` | 10 | 只读写服务端本地数据:`list_online_hosts` / `get_audit_log` / `mcp_*` |
| `win+lnx+mac` | 6 | 进程列表、文件列取、日志、V2 文件传输、`copy_files_c2c` |
| `win+lnx` | 11 | `remote_*` 全族、`get_screenshot`、`exec_command` / `terminal_*` / `kill_process` |
| `win` | 33 | 服务 / 注册表 / 键日志 / 文件写 / **`list_windows`** / `host_*` / `chat_*` / `power_action` |
**注意 `exec_command` / `terminal_*` / `kill_process` 不在 `win+lnx+mac` 组**:
macOS 客户端其实有对应实现(`macos/main.mm:753` 的 `ShellworkingThread` 跑 PTY,
`SystemManager.mm` 有 `COMMAND_KILLPROCESS` 分支),但服务端刻意拦着
(`McpServer.cpp:3652` 注释「macOS 本轮不开放」、`6870`)。**平台表按实际行为标,
不按客户端能力标**。
**`list_windows` 只有 Windows 可用**,这个坑很隐蔽:Linux 的
`SystemManager.h:38` 和 macOS 的 `SystemManager.mm:39` 都有 `COMMAND_WSLIST`
的 `case` 分支,看起来是支持的。但 `BuildListWindows` 把命令发在**主连接**上
(`McpServer.cpp:2931`),而这两个平台的主循环只处理 `COMMAND_SYSTEM`
(起 SystemManager 子连接),`WSLIST` 在子连接里才被处理——走不到。实测 Linux
上直接超时 `-32001`。那两个 `case` 是给 SystemDlg 窗口管理用的,不是 MCP 这条路径。
Windows 是在主循环里处理的(`client/KernelManager.cpp:1491`),所以正常。
### 平台优先级(产品定位)
支持面是**刻意设计的阶梯**,不是历史遗留:
| 平台 | 覆盖 | 定位 |
|---|---|---|
| **win** | **60 / 60 (100%)** | 唯一全量支持的平台,所有工具都以它为准 |
| lnx | 27 / 60 (45%) | 第二梯队,桌面场景基本可用 |
| mac | 16 / 60 (27%) | 第三梯队 |
| apk | 10 / 60 (17%) | 第三梯队,仅服务端本地类工具 |
`check_platform_table.py` 把「Windows 全量」做成了**不变式**:任何工具缺 `win`
直接报错,同时检查 `win >= lnx >= mac/apk` 的阶梯不倒挂。新增工具时若只标了
`lnx`,脚本会拦下。
判断平台归属时**以 Windows 为基线**:先确认它在 Windows 上成立,再逐级确认
Linux、macOS、Android。反过来做(从 Android 往上推)容易把「客户端有实现」
误当成「服务端放行」——`exec_command` 在 macOS 上就是这种情况。
**注意 `exec_command` / `terminal_*` / `kill_process` 不在 `win+lnx+mac` 组**:
macOS 客户端其实有对应实现(`macos/main.mm:753` 的 `ShellworkingThread` 跑 PTY,
`SystemManager.mm` 有 `COMMAND_KILLPROCESS` 分支),但服务端刻意拦着
(`McpServer.cpp:3652` 注释「macOS 本轮不开放」、`6870`)。**平台表按实际行为标,
不按客户端能力标**——将来开放这几项时,要同时改表、`roles` 无关、和 instructions。
`make_tools_json.py` 会做一致性检查:描述里声称「仅 Windows」但 `platforms` 含
其他平台时直接报错,防止描述与事实再次漂移。
### 方向性能力(roles)
`platforms` 是**无序集合**,只能表达「任一参与端都落在这个集合内」。
`copy_files_c2c` 两端的要求不同,单靠它表达不了:
```json
"platforms": ["win", "lnx", "mac"],
"roles": {
"src_id": ["win"],
"dst_id": ["win", "lnx", "mac"]
}
```
依据是 `McpServer.cpp:6591-6609`:
- 源端只有 Windows 实现了 C2C 发送逻辑(`client/KernelManager.cpp`),
代码对 `LNX` / `MAC` 直接返回 `-32005`
- 目标端只需 `CLIENT_CAP_V2` 收包,`posixDst` 分支专门处理 LNX/MAC 的路径形态
(接收端把 `\` 归一化成 `/` 后按绝对路径落盘)
**Linux / macOS 只能当接收方,不能当发送方。** 这是当前唯一的非对称工具。
新增同类工具时,`platforms` 填两端并集,方向性写进 `roles`,并在 C++ 的
`CollectTargetReqs` 里同步一份 `AddIdReq` —— `check_platform_table.py` 会校验
`tools.json` / C++ / 脚本三方一致。
## 与 instructions 的对应
`server/2015Remote/McpServer.cpp` 的 `kServerInstructions` 第 5 节(客户端平台差异)
是这份矩阵的**面向模型的摘要**。改 `PLATFORMS` 时同步改那一节,否则模型看到的
说明会和数据不一致。
## 运行时门禁
`platforms` 不只是文档,它还被编进 `McpServer.cpp` 的 `kToolPlatforms` 表,
由 `DispatchSingleHostTool` 开头的 `CheckToolPlatform` 执行硬校验:
平台不匹配时直接返回 `-32005`,不会下发命令也不会白等超时。
批量调用走 `BuildBatchCall` → `DispatchSingleHostTool`,自动被覆盖。
门禁需要从入参里拿到目标主机 id 才能判断平台。绝大多数工具用 `id`,
`copy_files_c2c` 用 `src_id` / `dst_id`(两端都查)——这是目前唯一的例外,
由 C++ 的 `CollectTargetIds` 处理。**新增受限平台的工具时,如果入参里没有 `id`,
必须在 `CollectTargetIds` 和 `check_platform_table.py` 的 `ID_ALIASES` 两处同时登记**,
否则门禁会静默放行。`check_platform_table.py` 会检查这件事。
总开关:`McpPlatformGuard`(默认 1),关掉后 `CheckToolPlatform` 直接返回放行。
```bash
python tools/mcp_tools/check_platform_table.py
# PASS: 60 个工具的 platforms 两边完全一致,且门禁都能拿到主机 id
```
## 与 Go 服务端的关系
`impl` 字段就是给 Go 端裁剪用的:标 `mfc` 的工具表示 Go 端还没有对应能力。
Go 端补齐某个工具的底层命令后,把它改成 `both`。
注意 Go 端目前只有 5 类客户端命令(`SCREEN_SPY` / `NEXT` / `SCREEN_CONTROL` /
`BYE` / `SHELL`),所以短期内 `impl: both` 的工具不会多。
## 前置条件
- 服务端在运行(`McpEnabled=1`)
- Release 版读注册表 `HKCU\Software\YAMA\settings`,Debug 版读 `<exe目录>\settings.ini`
—— 抓不到工具时先确认跑的是哪个构建
- 抓取时所有开关都应为开,否则拿到的是子集而非全集
+206
View File
@@ -0,0 +1,206 @@
"""校验 C++ 的 kToolPlatforms 表与 mcp/tools.json 的 platforms 字段是否一致。
C++ 侧不读 JSON(当前架构如此),两边是双份维护。这个脚本负责让它们不漂移:
- 工具集合必须完全相同(漏登记 / 多登记都报错)
- 每个工具的掩码必须对应同一组平台
- 受限平台的工具必须让门禁拿得到主机 id(否则 CheckToolPlatform 会静默放行)
用法:
python check_platform_table.py [mcp/tools.json] [McpServer.cpp]
"""
import json
import re
import sys
JSON_PATH = sys.argv[1] if len(sys.argv) > 1 else "mcp/tools.json"
CPP_PATH = sys.argv[2] if len(sys.argv) > 2 else "server/2015Remote/McpServer.cpp"
BIT = {"kPlatWin": "win", "kPlatLnx": "lnx", "kPlatMac": "mac", "kPlatApk": "apk"}
ORDER = ["win", "lnx", "mac", "apk"]
def plats_of(expr, where):
out = []
for token in re.findall(r"kPlat\w+", expr):
if token not in BIT:
sys.exit(f"未知的平台常量 {token}({where})")
out.append(BIT[token])
# 保持与 tools.json 相同的顺序约定:win, lnx, mac, apk
return [p for p in ORDER if p in out]
def parse_cpp(path):
src = open(path, encoding="utf-8", errors="replace").read()
start = src.find("const ToolPlatform kToolPlatforms[]")
if start < 0:
sys.exit("找不到 kToolPlatforms 表")
end = src.find("};", start)
if end < 0:
sys.exit("kToolPlatforms 表没有闭合")
body = src[start:end]
table = {}
for line in body.splitlines():
m = re.search(r'\{\s*"([a-z_0-9]+)"\s*,\s*([^}]+)\}', line)
if not m:
continue
table[m.group(1)] = plats_of(m.group(2), f"工具 {m.group(1)}")
return table, src
def parse_cpp_roles(src):
"""从 CollectTargetReqs 里提取 AddIdReq(args, "<key>", <mask>, reqs) 三元组。"""
i = src.find("bool CollectTargetReqs(")
if i < 0:
return None
j = src.find("\n}", i)
fn_body = src[i:j] if j > i else ""
roles = {}
for m in re.finditer(r'AddIdReq\(\s*args\s*,\s*"(\w+)"\s*,\s*([^,]+),', fn_body):
roles[m.group(1)] = plats_of(m.group(2), f"CollectTargetReqs 的 {m.group(1)}")
return roles
def check_coverage(tools, src):
"""两件事:
1. 受限平台的工具若拿不到主机 id,CheckToolPlatform 会直接放行,等于没拦。
2. 多主机工具的方向性要求(roles)必须三方一致:tools.json / C++ / 本脚本。
"""
problems = 0
cpp_roles = parse_cpp_roles(src)
if cpp_roles is None:
print("!! 找不到 CollectTargetReqs(门禁实现可能被改名或删除)")
return 1
for t in tools:
name = t["name"]
props = t["inputSchema"].get("properties", {})
roles = t.get("roles")
if roles:
outer = set(t["platforms"])
for key, plats in roles.items():
if key not in props:
problems += 1
print(f"!! {name}.roles.{key}: 不在 inputSchema 里")
extra = set(plats) - outer
if extra:
problems += 1
print(f"!! {name}.roles.{key}: 超出 platforms 范围 {sorted(extra)}")
got = cpp_roles.get(key)
if got is None:
problems += 1
print(f"!! {name}.roles.{key}: C++ CollectTargetReqs 未处理")
elif got != list(plats):
problems += 1
print(f"!! {name}.roles.{key}: tools.json={plats} C++={got}")
continue
if len(t["platforms"]) >= 4:
continue # 全平台可用,不需要判断主机
if "id" in props:
continue # 标准路径,ParseHostIdArg 能取到
problems += 1
print(f"!! {name}: platforms={t['platforms']} 但入参无 id,门禁拿不到主机")
return problems
def check_win_baseline(tools):
"""Windows 是唯一全量支持的平台,这是产品定位,不是数据巧合。
任何工具都不该缺 win:缺了要么是标注出错,要么是这个工具根本不该注册。
支持面从宽到窄依次是 win > lnx > mac ≈ apk,这条阶梯也在这里顺带核对,
倒挂说明某一档标反了。
"""
problems = 0
for t in tools:
if "win" not in t["platforms"]:
problems += 1
print(f"!! {t['name']}: platforms={t['platforms']} 不含 win,但 Windows 应全量支持")
def covered(p):
return sum(1 for t in tools if p in t["platforms"])
win, lnx, mac, apk = covered("win"), covered("lnx"), covered("mac"), covered("apk")
if not (win >= lnx >= mac and win >= apk):
problems += 1
print(f"!! 支持面阶梯倒挂: win={win} lnx={lnx} mac={mac} apk={apk}"
f"(应为 win >= lnx >= mac/apk)")
print(f"支持面: win={win} lnx={lnx} mac={mac} apk={apk}")
return problems
def check_instructions(src, tools):
"""instructions 第 5 节是平台矩阵的摘要,模型只读它不读表。
mac 段是逐个点名列出 win+lnx 组工具的,漏一个模型就会误以为 macOS 支持它
(实际发生过:remote_close 漏了)。这里做一次点名核对。
"""
i = src.find('u8"5) 客户端平台差异')
if i < 0:
print("!! 找不到 instructions 第 5 节(客户端平台差异)")
return 1
j = src.find('u8"6) 安全约定', i)
if j < 0:
print("!! 找不到 instructions 第 6 节,无法确定第 5 节的边界")
return 1
# 把这一节里所有 u8"..." 拼成连续文本,再按平台段落切开
text = "".join(re.findall(r'u8"((?:[^"\\]|\\.)*)"', src[i:j]))
mac_at, apk_at = text.find("mac(MAC)"), text.find("apk(APK)")
if mac_at < 0 or apk_at < mac_at:
print("!! instructions 第 5 节里找不到 mac / apk 段落")
return 1
mac_seg = text[mac_at:apk_at]
problems = 0
for t in tools:
if t["platforms"] == ["win", "lnx"] and t["name"] not in mac_seg:
problems += 1
print(f"!! {t['name']} 不支持 mac,但 instructions 的 mac 段没点名")
return problems
def main():
doc = json.load(open(JSON_PATH, encoding="utf-8"))
tools = doc["tools"]
json_table = {t["name"]: list(t["platforms"]) for t in tools}
cpp_table, cpp_src = parse_cpp(CPP_PATH)
print(f"{JSON_PATH}: {len(json_table)} 个工具")
print(f"{CPP_PATH}: {len(cpp_table)} 项")
problems = 0
only_json = sorted(set(json_table) - set(cpp_table))
only_cpp = sorted(set(cpp_table) - set(json_table))
if only_json:
problems += len(only_json)
print(f"!! 只在 tools.json 里(C++ 表漏登记): {only_json}")
if only_cpp:
problems += len(only_cpp)
print(f"!! 只在 C++ 表里(tools.json 已无此工具): {only_cpp}")
for name in sorted(set(json_table) & set(cpp_table)):
a, b = json_table[name], cpp_table[name]
if a != b:
problems += 1
print(f"!! {name}: tools.json={a} C++={b}")
problems += check_coverage(tools, cpp_src)
problems += check_win_baseline(tools)
problems += check_instructions(cpp_src, tools)
if problems == 0:
print(f"\nPASS: {len(json_table)} 个工具的 platforms 两边完全一致,"
f"Windows 全量覆盖,多主机工具的方向性要求三方一致,"
f"门禁都能拿到主机 id,instructions 第 5 节无漏项")
return 0
print(f"\nFAIL: {problems} 处不一致")
return 1
if __name__ == "__main__":
sys.exit(main())
+90
View File
@@ -0,0 +1,90 @@
"""抓取运行中 MCP 服务端的 tools/list 原始响应,作为黄金样本。
token 来源(按优先级):命令行参数 > 环境变量 YAMA_MCP_TOKEN > 注册表
HKCU\\Software\\YAMA\\settings 的 McpToken
注意:Release 版读注册表,Debug 版读 <exe目录>\\settings.ini,两者可能不同。
端口自动探测:
6545 = McpHttps=1 时 httplib 的明文后端(只绑回环,首选)
6544 = TLS 前端(McpTlsProxy,需跳过证书校验)
用法:
python dump_tools.py [token] [out.json]
"""
import http.client
import json
import os
import ssl
import sys
def resolve_token(argv_token=""):
if argv_token:
return argv_token
env = os.environ.get("YAMA_MCP_TOKEN", "")
if env:
return env
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\YAMA\settings")
val, _ = winreg.QueryValueEx(key, "McpToken")
return val
except Exception:
return ""
def call(port, token, method="tools/list", use_tls=False):
body = json.dumps({
"jsonrpc": "2.0", "id": 1, "method": method, "params": {},
}, ensure_ascii=False).encode("utf-8")
if use_tls:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
conn = http.client.HTTPSConnection("127.0.0.1", port, timeout=30, context=ctx)
else:
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=30)
conn.request("POST", "/mcp", body, {
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
})
resp = conn.getresponse()
raw = resp.read()
conn.close()
return resp.status, raw
def main():
token = resolve_token(sys.argv[1] if len(sys.argv) > 1 else "")
out = sys.argv[2] if len(sys.argv) > 2 else "tools_raw.json"
if not token:
sys.exit("未找到 McpToken(参数 / YAMA_MCP_TOKEN / 注册表 均无)")
last = None
raw = None
for port, tls in ((6545, False), (6544, True)):
try:
status, raw = call(port, token, use_tls=tls)
except Exception as e:
last = f"{port}: {e}"
continue
if status == 200:
print(f"连接 127.0.0.1:{port} ({'TLS' if tls else 'plain'}), {len(raw)} bytes")
break
last = f"{port}: HTTP {status} {raw[:200].decode('utf-8', 'replace')}"
else:
sys.exit(f"两个端口都失败 -> {last}")
doc = json.loads(raw.decode("utf-8"))
tools = doc.get("result", {}).get("tools", [])
print(f"工具数: {len(tools)}")
with open(out, "w", encoding="utf-8", newline="\n") as f:
json.dump(doc, f, ensure_ascii=False, indent=2)
f.write("\n")
print(f"已写入 {out}")
if __name__ == "__main__":
main()
+320
View File
@@ -0,0 +1,320 @@
"""从 tools/list 黄金样本生成 tools.json。
黄金样本来自运行中的 MFC 服务端(全部开关打开,因此是工具全集)。
本脚本只做两件事:
1. 原样保留 name / description / inputSchema / outputSchema(零信息损失)
2. 补充运行时不可见的元信息:gate / write / manage / impl
—— 这些是从 C++ 注册点(BuildToolsListResult / McpMachine::AppendTools /
McpChat::AppendTools)的 if 条件解析出来的,见 GATE 表。
"""
import json
import sys
if len(sys.argv) < 3:
sys.exit("用法: python make_tools_json.py <tools_raw.json> <mcp/tools.json>")
SRC = sys.argv[1]
DST = sys.argv[2]
# gate: 该工具要求哪个服务端开关为开(null = 无条件出现)
# write: 需要 !McpReadonly
# manage: 额外需要 McpManage(仅 McpMachine 族的两处用到)
GATE = {
# ---- McpServer.cpp:BuildToolsListResult 无条件段 ----
"list_online_hosts": (None, False, False),
"search_hosts": (None, False, False),
"list_all_hosts": (None, False, False),
"get_host_detail": (None, False, False),
"list_processes": (None, False, False),
"list_windows": (None, False, False),
"get_activity_history": (None, False, False),
"get_screenshot": (None, False, False),
"list_files": (None, False, False),
"list_services": (None, False, False),
"get_client_log": (None, False, False),
"get_audit_log": (None, False, False),
"get_server_status": (None, False, False),
"mcp_list_sessions": (None, False, False),
"mcp_cancel_session": (None, False, False),
"list_registry": (None, False, False),
# ---- 单开关 ----
"get_keylog": ("keylog", False, False),
# ---- 写操作(无专属开关,只受 readonly 约束)----
"exec_command": (None, True, False),
"host_set_remark": (None, True, False),
"host_set_watch_level": (None, True, False),
"search_file": (None, True, False),
# ---- terminal ----
"terminal_open": ("terminal", True, False),
"terminal_exec": ("terminal", True, False),
"terminal_close": ("terminal", True, False),
# ---- remote_control ----
"remote_open": ("remote_control", True, False),
"remote_close": ("remote_control", True, False),
"remote_keyboard": ("remote_control", True, False),
"remote_mouse": ("remote_control", True, False),
"remote_clipboard": ("remote_control", True, False),
"remote_block_input": ("remote_control", True, False),
# ---- file_transfer ----
"download_file": ("file_transfer", True, False),
"upload_file": ("file_transfer", True, False),
"copy_files_c2c": ("file_transfer", True, False),
# ---- manage(McpServer 侧的危险操作)----
"kill_process": ("manage", True, False),
"operate_window": ("manage", True, False),
"control_service": ("manage", True, False),
"power_action": ("manage", True, False),
# ---- file_write ----
"delete_path": ("file_write", True, False),
"move_path": ("file_write", True, False),
"create_folder": ("file_write", True, False),
# ---- McpMachine 族:总开关 McpMachine ----
"list_network_connections": ("machine", False, False),
"host_list_processes": ("machine", False, False),
"host_list_windows": ("machine", False, False),
"host_list_network_state": ("machine", False, False),
"host_list_software": ("machine", False, False),
"host_list_browser_history": ("machine", False, False),
"host_list_favorites": ("machine", False, False),
"host_list_win32_services": ("machine", False, False),
"host_list_driver_services": ("machine", False, False),
"host_list_scheduled_tasks": ("machine", False, False),
"host_get_hosts_file": ("machine", False, False),
"kill_network_connection": ("machine", True, True), # writable && IsManageEnabled()
"host_control_process": ("machine", True, False), # writable
"host_control_window": ("machine", True, False),
"host_control_service": ("machine", True, False),
"host_control_task": ("machine", True, False),
# ---- McpChat 族:独立开关 McpChat,与 readonly 无关 ----
"chat_open": ("chat", False, False),
"chat_send": ("chat", False, False),
"chat_wait": ("chat", False, False),
"chat_close": ("chat", False, False),
}
# platforms: 该工具涉及的任一主机都必须落在此集合内。
#
# 判定依据是**服务端实际放行**,不是客户端有没有实现。两者在 macOS 上会分叉:
# exec_command / terminal_* / kill_process 的客户端实现是有的,但服务端刻意拦着
# (McpServer.cpp:3652「macOS 本轮不开放」、6870),所以标 win/lnx。
#
# 分组依据(全部经代码核对):
# 全平台 —— 只读写服务端本地数据,与客户端平台无关
# win/lnx/mac —— client/、linux/、macos/ 都有该命令的处理分支,且服务端不拦
# win/lnx —— 远程控制只实现于 Windows/Linux(McpServer.cpp:2728);
# 以及 macOS 客户端有实现但服务端未开放的 exec_command / terminal_* / kill_process
# 仅 win —— 服务/注册表/键日志/活动历史/文件写/块输入/host_* /chat_* /power_action
# (power_action 实际走 TOKEN_MACHINE_MANAGE,不是通用电源命令)
#
# 支持面是产品定位的阶梯:win 100% > lnx 46% > mac 28% ≈ apk 16%。
# Windows 是唯一全量支持的平台,check_platform_table.py 会把这条做成不变式。
#
# apk 现状:COMMAND_SYSTEM 与 COMMAND_SHELL 在 android/.../main.cpp:534-540 明确
# 标注 not implemented,且客户端未声明 SCREEN_PREVIEW,故除服务端本地类外几乎全不支持。
_APK = ["win", "lnx", "mac", "apk"]
_TRIO = ["win", "lnx", "mac"]
_WL = ["win", "lnx"]
_WIN = ["win"]
PLATFORMS = {
# 服务端本地数据,与客户端平台无关
"list_online_hosts": _APK,
"search_hosts": _APK,
"list_all_hosts": _APK,
"get_host_detail": _APK,
"get_audit_log": _APK,
"get_server_status": _APK,
"mcp_list_sessions": _APK,
"mcp_cancel_session": _APK,
"host_set_remark": _APK,
"host_set_watch_level": _APK,
# SYSTEM / LIST_DRIVE / QUERY_LOG:三个桌面平台都实现了
"list_processes": _TRIO,
"list_files": _TRIO,
"get_client_log": _TRIO,
# list_windows 只有 Windows:服务端把 COMMAND_WSLIST 发在主连接上,Linux/macOS
# 主循环只处理 COMMAND_SYSTEM,WSLIST 只在 SystemManager 子连接里处理 —— 走不到,
# 实测 Linux 直接超时 -32001。别被 SystemManager 里的 case 骗到,那是 SystemDlg 用的。
"list_windows": _WIN,
# macOS 客户端有 PTY 实现(macos/main.mm:753 起 ShellworkingThread),但服务端
# 本轮刻意不开放(McpServer.cpp:3652 注释「macOS 本轮不开放」),故实际不可用。
"terminal_open": _WL,
"terminal_exec": _WL,
"terminal_close": _WL,
"exec_command": _WL,
# macOS 客户端有 COMMAND_KILLPROCESS 分支,但服务端同样拦着(McpServer.cpp:6870)
"kill_process": _WL,
# 需要 CLIENT_CAP_V2;三个桌面平台的 DefaultCaps() 都含 V2
"download_file": _TRIO,
"upload_file": _TRIO,
# 远程控制:注释明确只实现于 Windows / Linux
"remote_open": _WL,
"remote_close": _WL,
"remote_keyboard": _WL,
"remote_mouse": _WL,
"remote_clipboard": _WL,
# 需要 CLIENT_CAP_SCREEN_PREVIEW:Windows 恒有,Linux 仅在探测到 X11 桌面时声明
"get_screenshot": _WL,
# ---- 仅 Windows ----
"list_services": _WIN,
"control_service": _WIN,
"list_registry": _WIN,
"get_keylog": _WIN,
"get_activity_history": _WIN,
"search_file": _WIN,
"delete_path": _WIN,
"move_path": _WIN,
"create_folder": _WIN,
"copy_files_c2c": _TRIO, # 两端并集:源端仅 win,目标端 win/lnx/mac,见 ROLES
"remote_block_input": _WIN,
"operate_window": _WIN, # WSLIST 能列窗口,但窗口操作仅 Windows 实现
"power_action": _WIN, # 实际走 TOKEN_MACHINE_MANAGE
# McpMachine 族(COMMAND_MACHINE_MANAGE 仅 Windows 实现)
"list_network_connections": _WIN,
"kill_network_connection": _WIN,
"host_list_processes": _WIN,
"host_list_windows": _WIN,
"host_list_network_state": _WIN,
"host_list_software": _WIN,
"host_list_browser_history": _WIN,
"host_list_favorites": _WIN,
"host_list_win32_services": _WIN,
"host_list_driver_services": _WIN,
"host_list_scheduled_tasks": _WIN,
"host_get_hosts_file": _WIN,
"host_control_process": _WIN,
"host_control_window": _WIN,
"host_control_service": _WIN,
"host_control_task": _WIN,
# McpChat 族(COMMAND_TALK 仅 Windows,代码里另有 requireWindows_ 硬校验)
"chat_open": _WIN,
"chat_send": _WIN,
"chat_wait": _WIN,
"chat_close": _WIN,
}
# roles: 多主机工具的方向性要求。
# platforms 只能表达「任一参与端都必须落在这个集合内」,表达不了「源端必须是 A、
# 目标端可以是 B」。copy_files_c2c 就是这种非对称能力:
# src_id —— 只有 Windows 实现了发送逻辑(client/KernelManager.cpp;
# McpServer.cpp:6591 对 LNX/MAC 直接返回 -32005)
# dst_id —— 只要求 CLIENT_CAP_V2 收包,Windows / Linux / macOS 都行
# (McpServer.cpp:6601-6604 的 posixDst 分支专门处理 LNX/MAC 的路径形态)
# 反过来 Linux → Windows 不支持:POSIX 客户端没有 C2C_PATHS 发送实现。
# 必须与 C++ 的 CollectTargetReqs 保持一致,check_platform_table.py 会校验。
ROLES = {
"copy_files_c2c": {
"src_id": _WIN,
"dst_id": _TRIO,
},
}
raw = json.load(open(SRC, encoding="utf-8"))
tools_in = raw["result"]["tools"]
missing = [t["name"] for t in tools_in if t["name"] not in GATE]
if missing:
print(f"!! GATE 表缺少 {len(missing)} 个工具: {missing}", file=sys.stderr)
sys.exit(1)
missing_p = [t["name"] for t in tools_in if t["name"] not in PLATFORMS]
if missing_p:
print(f"!! PLATFORMS 表缺少 {len(missing_p)} 个工具: {missing_p}", file=sys.stderr)
sys.exit(1)
# 一致性检查:描述里声称「仅 Windows」但 platforms 含非 win 项,说明两者已经漂移。
# 这类矛盾靠人工 review 抓不住(60 个工具、26KB 描述),必须由脚本拦。
import re
ONLY_WIN = re.compile(r"仅\s*Windows\s*(客户端)?(支持)?|only\s+Windows", re.I)
drift = []
for t in tools_in:
name = t["name"]
plats = PLATFORMS[name]
if ONLY_WIN.search(t.get("description", "")) and any(p != "win" for p in plats):
drift.append((name, plats))
if drift:
print("!! 描述声称「仅 Windows」但 platforms 含其他平台:", file=sys.stderr)
for n, p in drift:
print(f" {n}: {p}", file=sys.stderr)
sys.exit(1)
# roles 是 platforms 的细分,不能超出 platforms 的范围
for name, roles in ROLES.items():
outer = set(PLATFORMS[name])
for arg, plats in roles.items():
extra = set(plats) - outer
if extra:
print(f"!! {name}.roles.{arg} 含 platforms 之外的值 {sorted(extra)}", file=sys.stderr)
sys.exit(1)
tools_out = []
for t in tools_in:
name = t["name"]
gate, write, manage = GATE[name]
entry = {"name": name, "description": t.get("description", "")}
entry["gate"] = gate
if write:
entry["write"] = True
if manage:
entry["manage"] = True
entry["platforms"] = PLATFORMS[name]
if name in ROLES:
entry["roles"] = ROLES[name]
entry["impl"] = "mfc"
entry["inputSchema"] = t.get("inputSchema", {})
entry["outputSchema"] = t.get("outputSchema", {})
tools_out.append(entry)
doc = {
"_readme": [
"YAMA MCP 工具清单(单一来源候选)。",
"description / inputSchema / outputSchema 与运行中服务端的 tools/list 逐字节一致,",
"由 tools/mcp_tools/dump_tools.py 抓取、make_tools_json.py 生成,勿手工编辑。",
"gate: 该工具出现的开关条件(null = 无条件);write: 需 !McpReadonly;",
"manage: 额外需 McpManage。这三项从 C++ 注册点的 if 条件解析而来,运行时不可见。",
"platforms: 该工具涉及的任一主机都必须落在此集合内(win/lnx/mac/apk),依据各平台",
"客户端对相应 COMMAND_ 的处理实现。apk 上 COMMAND_SYSTEM 与 COMMAND_SHELL 均为空实现。",
"roles: 仅多主机工具才有。按参数名细分平台,表达 platforms 说不清的方向性能力",
"(copy_files_c2c:src_id 必须 Windows,dst_id 可 win/lnx/mac,反向不支持)。",
"impl: 已实现该工具的服务端(mfc / go / both)。",
"version 2 起 platforms 语义为「任一参与端都落在此集合内」,并新增 roles 字段;",
"version 1 的 platforms 表示「该工具能在哪些客户端上执行」,两者对单主机工具等价。",
],
"version": 2,
"protocolVersion": "2025-06-18",
"toolCount": len(tools_out),
"tools": tools_out,
}
with open(DST, "w", encoding="utf-8", newline="\n") as f:
json.dump(doc, f, ensure_ascii=False, indent=2)
f.write("\n")
import collections
dist = collections.Counter(tuple(t["platforms"]) for t in tools_out)
print(f"写入 {DST}: {len(tools_out)} 个工具")
print(f" 有 gate 的: {sum(1 for t in tools_out if t['gate'])}")
print(f" 写操作: {sum(1 for t in tools_out if t.get('write'))}")
print(f" 需 manage: {sum(1 for t in tools_out if t.get('manage'))}")
print(" 平台分布:")
for plats, n in sorted(dist.items(), key=lambda x: -len(x[0])):
print(f" {'+'.join(plats):20s} {n}")
+161
View File
@@ -0,0 +1,161 @@
"""校验 tools.json 与 MCP 服务端的 tools/list 是否一致。
两种模式:
python verify_tools.py --offline mcp/tools.json tools_raw.json
对比 tools.json 与已保存的黄金样本(不联网)
python verify_tools.py --live mcp/tools.json [token] [port]
抓取运行中服务端的 tools/list 再对比(回归测试用)
token 省略时依次取环境变量 YAMA_MCP_TOKEN、注册表 McpToken;
port 省略时自动探测 6545(明文后端)/ 6544(TLS 前端)
比对内容:name / description / inputSchema / outputSchema,逐字段深度比较,
外加工具顺序。gate / write / manage / impl 是 tools.json 独有的元信息,不参与比对。
"""
import http.client
import json
import os
import ssl
import sys
def normalize(obj):
"""规范化:键排序后序列化,消除 JSON object 的键序差异。"""
return json.dumps(obj, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
def resolve_token(argv_token=""):
if argv_token:
return argv_token
env = os.environ.get("YAMA_MCP_TOKEN", "")
if env:
return env
try:
import winreg
key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r"Software\YAMA\settings")
val, _ = winreg.QueryValueEx(key, "McpToken")
return val
except Exception:
return ""
def fetch_live(token, port=None):
body = json.dumps({
"jsonrpc": "2.0", "id": 1, "method": "tools/list", "params": {},
}, ensure_ascii=False).encode("utf-8")
if port is not None:
candidates = [(port, port == 6544)]
else:
candidates = [(6545, False), (6544, True)]
last = None
for p, tls in candidates:
try:
if tls:
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE
conn = http.client.HTTPSConnection("127.0.0.1", p, timeout=30, context=ctx)
else:
conn = http.client.HTTPConnection("127.0.0.1", p, timeout=30)
conn.request("POST", "/mcp", body, {
"Authorization": "Bearer " + token,
"Content-Type": "application/json",
"Accept": "application/json, text/event-stream",
})
resp = conn.getresponse()
raw = resp.read()
conn.close()
if resp.status == 200:
print(f"连接 127.0.0.1:{p} ({'TLS' if tls else 'plain'})")
return json.loads(raw.decode("utf-8"))["result"]["tools"]
last = f"{p}: HTTP {resp.status} {raw[:200].decode('utf-8', 'replace')}"
except Exception as e:
last = f"{p}: {e}"
sys.exit(f"连接失败 -> {last}")
def main():
args = sys.argv[1:]
if not args:
sys.exit(__doc__)
if args[0] == "--offline":
if len(args) < 3:
sys.exit("用法: python verify_tools.py --offline <tools.json> <黄金样本.json>")
path, sample = args[1], args[2]
tools_live = json.load(open(sample, encoding="utf-8"))["result"]["tools"]
print(f"黄金样本: {sample}")
elif args[0] == "--live":
if len(args) < 2:
sys.exit("用法: python verify_tools.py --live <tools.json> [token] [port]")
path = args[1]
token = resolve_token(args[2] if len(args) > 2 else "")
port = int(args[3]) if len(args) > 3 else None
if not token:
sys.exit("未找到 McpToken(参数 / YAMA_MCP_TOKEN / 注册表 均无)")
tools_live = fetch_live(token, port)
print(f"活服务: 127.0.0.1:{port if port else 'auto'}")
else:
sys.exit(__doc__)
doc = json.load(open(path, encoding="utf-8"))
tools_json = doc["tools"]
print(f"tools.json: {path} ({len(tools_json)} 个工具)")
print(f"服务端: {len(tools_live)} 个工具")
if len(tools_json) != len(tools_live):
print(f"!! 数量不一致: {len(tools_json)} vs {len(tools_live)}")
live_by_name = {t["name"]: t for t in tools_live}
json_by_name = {t["name"]: t for t in tools_json}
only_live = sorted(set(live_by_name) - set(json_by_name))
only_json = sorted(set(json_by_name) - set(live_by_name))
if only_live:
print(f"!! 仅服务端有: {only_live}")
if only_json:
print(f"!! 仅 json 有: {only_json}")
FIELDS = ("description", "inputSchema", "outputSchema")
diffs = 0
for name in sorted(set(live_by_name) & set(json_by_name)):
a, b = live_by_name[name], json_by_name[name]
for f in FIELDS:
va, vb = normalize(a.get(f)), normalize(b.get(f))
if va != vb:
diffs += 1
print(f"!! {name}.{f} 不一致")
for i, (ca, cb) in enumerate(zip(va, vb)):
if ca != cb:
print(f" @{i}")
print(f" 服务端: ...{va[max(0,i-60):i+80]}...")
print(f" json : ...{vb[max(0,i-60):i+80]}...")
break
else:
print(f" 长度不同: {len(va)} vs {len(vb)}")
break # 一个工具报一次即可
# 顺序一致性:tools/list 的数组顺序会影响模型的选择倾向
order_live = [t["name"] for t in tools_live]
order_json = [t["name"] for t in tools_json]
if order_live != order_json:
print("!! 工具顺序不一致")
for i, (x, y) in enumerate(zip(order_live, order_json)):
if x != y:
print(f" 首个差异 @{i}: 服务端={x} json={y}")
break
diffs += 1
else:
print("工具顺序: 一致")
if diffs == 0 and not only_live and not only_json:
print(f"\nPASS: {len(tools_json)} 个工具完全一致")
return 0
print(f"\nFAIL: {diffs} 处差异")
return 1
if __name__ == "__main__":
sys.exit(main())