Files
SimpleRemoter/tools/mcp_tools/check_platform_table.py
T
yuanyuanxiang 356aa27108 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),关闭只失去提前拦截,不影响任何执行路径。
2026-11-03 16:06:41 +01:00

207 lines
7.6 KiB
Python
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.
"""校验 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())