Feature(Go): verify_tools --subset and MCP deployment docs
Add a third mode to verify_tools.py that validates the Go server end to end: it fetches /mcp tools/list and requires the name set to equal the nine implemented tools exactly (seven in readonly mode), compares description / inputSchema / outputSchema field by field against mcp/tools.json, and also checks the published order. Unlike --live, extra or missing tools are failures, not notes. The field-comparison loop is factored into report_field_diffs so --offline / --live and --subset share one comparison, diff printer and FIELDS tuple. Document and deploy the endpoint: the systemd env example gains YAMA_MCP_TOKEN / READONLY / TERM_IDLE / MAX_CONCURRENCY / READ_MAX, the design doc moves to implemented and its section 10 now matches the code (embedded tools_minimal.json, the three packet dispatch groups). The tools README explains gen_go_tools.py --check and --subset. Verified against a freshly built debug Go server on 16543/18090: read-write mode passes with 9 tools, YAMA_MCP_READONLY=1 passes with 7, and both mismatch directions (extra tools, missing tools) fail with exit 1. gen_go_tools.py --check stays clean; no Go code changed. Co-Authored-By: deepseek-flash
This commit is contained in:
1 parent
9ce1a58bc3
commit
d4f10db1f2
4 files changed
+192
-39
No files matched your search
@@ -1,6 +1,8 @@
|
||||
# Go 服务端 MCP 最小工具集设计
|
||||
|
||||
> 版本:v1.0(定稿) 状态:**已自审(22 项问题全部修入正文),可施工** 日期:2026-11-12
|
||||
> 版本:v1.0(定稿) 状态:**已实施(M0–M8 全部落地,2026-11-12)** 日期:2026-11-12
|
||||
>
|
||||
> 实施计划与各里程碑验收口径见 `Mcp_Go_Minimal_Implementation_Plan.md`。
|
||||
>
|
||||
> 前置文档:`Mcp_Tool_Optimization_Plan.md`(MFC 侧工具优化,已全部落地)、
|
||||
> `Mcp_FileTransfer_Design.md`(V2 文件传输协议与无头接收端)、
|
||||
@@ -424,10 +426,12 @@ MCP: 读临时文件 → 返回 → 删临时目录
|
||||
- **路径校验是硬性安全要求**:`filename` 由客户端提供,必须校验它落在 `targetDir` 之内
|
||||
(**用 `filepath.Rel` 判越界,不能用字符串前缀比较**,见 §8.3),否则拒收并中止传输。
|
||||
没有这一步,被控端可以把任意文件写到主控磁盘任意位置。
|
||||
- **没有可用的能力门**。`CLIENT_CAP_V2` 在 `common/commands.h:1289` 的
|
||||
`DefaultCaps()` 里被**所有平台无条件声明**,拿它做门等于没门。MFC 侧的 V2 是
|
||||
**服务端开关**(`2015RemoteDlg.cpp:2822` 的 `EnableFileV2`,默认关),不是客户端能力。
|
||||
Go 侧不设这个开关,恒用 V2。
|
||||
- **能力检查只作诊断兜底**。`CLIENT_CAP_V2` 在 `common/commands.h:1289` 的
|
||||
`DefaultCaps()` 里被**所有现代客户端无条件声明**,拿它做真门等于没门。Go 侧保留
|
||||
`SupportsCap(…, CLIENT_CAP_V2)` 检查的唯一作用,是让"能力串为空"的极老客户端直接
|
||||
得到 `-32005`,而不是等到 94 号命令静默超时(见下一条)。MFC 侧的 V2 是**服务端
|
||||
开关**(`2015RemoteDlg.cpp:2822` 的 `EnableFileV2`,默认关),不是客户端能力;
|
||||
Go 侧不搬这个开关,恒用 V2。
|
||||
- 真正的失败模式是**老客户端不认识 94 号命令**:它收到 `CMD_DOWN_FILES_V2` 后
|
||||
不建子连接、不回任何包,表现为 `-32001` 超时。工具描述里要写明这条,
|
||||
避免模型反复重试。
|
||||
@@ -686,12 +690,16 @@ if err != nil || rel == ".." || strings.HasPrefix(rel, ".."+string(os.PathSepara
|
||||
```
|
||||
server/go/mcp/
|
||||
server.go # /mcp handler、JSON-RPC 分发、鉴权、tools/list
|
||||
tools.go # 9 个工具的定义表(name/description/inputSchema)
|
||||
tools.go # //go:embed tools_minimal.json;只读过滤、工具表
|
||||
tools_minimal.json # gen_go_tools.py 从 mcp/tools.json 抽取的 9 个工具(勿手改)
|
||||
tools_local.go # list_hosts / get_host_detail / get_server_status / get_audit_log
|
||||
tools_term.go # terminal_exec / terminal_close
|
||||
errors.go # 错误码 + JSON-RPC 错误映射
|
||||
audit.go # mcp.tool.call 审计
|
||||
lock.go # 设备锁 + 全局信号量
|
||||
session.go # 终端会话表、空闲回收
|
||||
term.go # 哨兵、环形缓冲、输出清洗
|
||||
term.go # 哨兵、环形缓冲
|
||||
clean.go # 终端输出清洗(逐字节移植 MFC 的 CleanTerminalOutput)
|
||||
screen.go # 主连接预览 RPC
|
||||
filemgr.go # 文件管理器子连接(list_files)
|
||||
filev2.go # V2 流式接收端(read_file)
|
||||
@@ -710,16 +718,21 @@ cmd/main.go ──▶ web ──▶ mcp ──▶ hub ──▶ connection / pro
|
||||
`web.New(...).WithMCP(mcpSrv)`(沿用 `WithDeviceHistory` / `WithConfig` 的链式风格,
|
||||
`web/server.go:94`),以及 `MyHandler.mcp = mcpSrv`(TCP 分派侧)。
|
||||
这样 `web` 和 `cmd` 都只依赖 `mcp`,不存在 `mcp → web` 的反向依赖。
|
||||
- TCP 侧的分派(`cmd/main.go` 的 `OnReceive`)新增六个 case:
|
||||
`TokenScreenPreviewRsp(248)` / `TokenDriveList(103)` / `TokenFileList(104)` /
|
||||
`TokenFileListError(171)` / `CommandSendFileV2(85)` / `CommandFileCompleteV2(91)`,
|
||||
统一转给 `mcp.Server.OnPacket(ctx, data)`,未命中在途请求就丢弃。
|
||||
- TCP 侧的分派(`cmd/main.go` 的 `OnReceive`)按到达的连接分成三组,未命中在途请求就丢弃:
|
||||
- `mcp.Server.OnPacket`:`TokenScreenPreviewRsp(248)`(主连接上的截图 RPC 回包)
|
||||
- `mcp.Server.OnFilePacket`:`TokenDriveList(103)` / `TokenFileList(104)` /
|
||||
`TokenFileListError(171)`(文件管理器子连接)
|
||||
- `mcp.Server.OnTransferPacket`:`CommandSendFileV2(85)` / `CommandFileCompleteV2(91)`
|
||||
(独立数据子连接或 POSIX 的文件管理器子连接)与 `TokenDownloadError(173)`
|
||||
|
||||
**为什么工具定义手写在 Go 里、不 embed `mcp/tools.json`**:9 个工具的 schema 手写约
|
||||
300 行,而 embed 需要跨语言目录同步(`mcp/tools.json` 在仓库根,`//go:embed` 不能
|
||||
引用父目录),要么加 Makefile 同步步骤、要么提交一份副本。手写 + 校验脚本更简单。
|
||||
防漂移靠 `tools/mcp_tools/verify_tools.py` 增加 `--subset` 模式:把 Go 的
|
||||
`tools/list` 抓下来,与 `mcp/tools.json` 里同名的工具逐字段比对,多一个少一个都报错。
|
||||
**为什么 embed 一份生成的 `tools_minimal.json`、而不是手写或直接引用 `mcp/tools.json`**:
|
||||
`mcp/tools.json` 在仓库根,`//go:embed` 不能引用父目录;手写 9 个 schema 又无法证明
|
||||
与 MFC 的 JSON 一致。所以由 `tools/mcp_tools/gen_go_tools.py` 从 `mcp/tools.json` 原样
|
||||
抽取(保持顺序,只留 name/description/inputSchema/outputSchema)生成 go 包内的副本并
|
||||
嵌入二进制——改工具定义必须改 `mcp/tools.json` 再重新生成,不存在两份手写文字漂移的余地。
|
||||
两道防漂移检查:`gen_go_tools.py --check`(生成副本是否为最新)与
|
||||
`verify_tools.py --subset`(线上 `tools/list` 是否与 `mcp/tools.json` 同名工具逐字段
|
||||
一致、名字集合是否恰好 9 个/只读 7 个)。
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -33,6 +33,25 @@ YAMA_WEB_TRUST_PROXY=1
|
||||
# WebSocket Origin 白名单(逗号分隔)。空 = 仅允许同源
|
||||
#YAMA_WEB_ALLOWED_ORIGINS=https://你的域名
|
||||
|
||||
# ---------- MCP 端点(可选)----------
|
||||
# 设计见 docs/Mcp_Go_Minimal_Design.md;启用后挂在同一个 Web 端口的 /mcp。
|
||||
|
||||
# 静态 Bearer Token(客户端填同一个值)。空 = 不注册 /mcp(404)。
|
||||
# 不会自动生成:只出现在日志里的秘密不算秘密
|
||||
#YAMA_MCP_TOKEN=
|
||||
|
||||
# "1" = 只读模式:隐藏并拒收 terminal_exec / terminal_close(会创建/关闭会话)
|
||||
#YAMA_MCP_READONLY=1
|
||||
|
||||
# 终端会话空闲回收(秒,默认 180)
|
||||
#YAMA_MCP_TERM_IDLE=180
|
||||
|
||||
# 全球在途 tools/call 上限(默认 16,超出返回 -32003)
|
||||
#YAMA_MCP_MAX_CONCURRENCY=16
|
||||
|
||||
# read_file 单文件上限(字节,默认 2 MiB;超限提示改用 download_file)
|
||||
#YAMA_MCP_READ_MAX=2097152
|
||||
|
||||
# ---------- SSO(单点登录,可选)----------
|
||||
|
||||
# 共享的 HS256 签名密钥。设置后启用 SSO:YAMA 校验父域名(如 FMS 网关)下发的
|
||||
|
||||
@@ -14,7 +14,8 @@ inputSchema、outputSchema,以及运行时不可见的开关元信息(`gate`
|
||||
| `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/verify_tools.py` | 校验 `tools.json` 与服务端是否一致(含 Go 端 `--subset`) |
|
||||
| `tools/mcp_tools/gen_go_tools.py` | 从 `tools.json` 抽取 Go 端 9 个工具,生成 `server/go/mcp/tools_minimal.json` |
|
||||
| `tools/mcp_tools/check_platform_table.py` | 校验 `tools.json` 的 `platforms` 与 C++ `kToolPlatforms` 一致 |
|
||||
|
||||
## 更新流程
|
||||
@@ -191,11 +192,26 @@ python tools/mcp_tools/check_platform_table.py
|
||||
|
||||
## 与 Go 服务端的关系
|
||||
|
||||
`impl` 字段就是给 Go 端裁剪用的:标 `mfc` 的工具表示 Go 端还没有对应能力。
|
||||
Go 端补齐某个工具的底层命令后,把它改成 `both`。
|
||||
Go 最小服务端(`server/go`,设计见 `docs/Mcp_Go_Minimal_Design.md`)实现 9 个工具。
|
||||
它的 `tools/list` **不是手写的**:`gen_go_tools.py` 从 `tools.json` 原样抽取这 9 个工具
|
||||
生成 `server/go/mcp/tools_minimal.json`,再由 `//go:embed` 编进二进制。
|
||||
|
||||
注意 Go 端目前只有 5 类客户端命令(`SCREEN_SPY` / `NEXT` / `SCREEN_CONTROL` /
|
||||
`BYE` / `SHELL`),所以短期内 `impl: both` 的工具不会多。
|
||||
改完 `tools.json` 之后:
|
||||
|
||||
```bash
|
||||
# 重新生成嵌入副本(--check 只检查是否为最新,CI 友好)
|
||||
python tools/mcp_tools/gen_go_tools.py
|
||||
python tools/mcp_tools/gen_go_tools.py --check
|
||||
|
||||
# 抓 Go 端线上 tools/list,与 tools.json 逐字段比对
|
||||
# 读写模式恰好 9 个;YAMA_MCP_READONLY=1 时恰好 7 个(隐藏 terminal_*)
|
||||
python tools/mcp_tools/verify_tools.py --subset mcp/tools.json <token> <port>
|
||||
python tools/mcp_tools/verify_tools.py --subset mcp/tools.json <token> <port> --readonly
|
||||
```
|
||||
|
||||
`--subset` 与 `--live` 的差别:前者**名字集合必须恰好等于** 9(或 7),多一个少一个
|
||||
都失败;后者只报双方差异。`impl` 字段的 `mfc` / `go` / `both` 目前仍是人工维护的
|
||||
元信息,脚本不据此推断。
|
||||
|
||||
## 前置条件
|
||||
|
||||
|
||||
+123
-18
@@ -1,6 +1,6 @@
|
||||
"""校验 tools.json 与 MCP 服务端的 tools/list 是否一致。
|
||||
|
||||
两种模式:
|
||||
三种模式:
|
||||
python verify_tools.py --offline mcp/tools.json tools_raw.json
|
||||
对比 tools.json 与已保存的黄金样本(不联网)
|
||||
|
||||
@@ -9,6 +9,12 @@
|
||||
token 省略时依次取环境变量 YAMA_MCP_TOKEN、注册表 McpToken;
|
||||
port 省略时自动探测 6545(明文后端)/ 6544(TLS 前端)
|
||||
|
||||
python verify_tools.py --subset mcp/tools.json [token] [port] [--readonly]
|
||||
校验 Go 服务端(server/go)的 MCP 端点:名字集合必须恰好是它实现的那
|
||||
9 个工具(只读模式 7 个),且 description / inputSchema / outputSchema
|
||||
与 tools.json 里的同名工具逐字段一致。Go 端把 tools_minimal.json 内嵌
|
||||
进二进制,这一模式检查的就是线上真正发布的字节。
|
||||
|
||||
比对内容:name / description / inputSchema / outputSchema,逐字段深度比较,
|
||||
外加工具顺序。gate / write / manage / impl 是 tools.json 独有的元信息,不参与比对;
|
||||
例外是 gate == "!machine" 的降级工具——它们只在 McpMachine=0 时出现,不进本次比对。
|
||||
@@ -19,6 +25,24 @@ import os
|
||||
import ssl
|
||||
import sys
|
||||
|
||||
# Go 最小服务端实现的 9 个工具(docs/Mcp_Go_Minimal_Design.md §3.1)。
|
||||
# tools/list 恰好是这些,多一个少一个都算失败。
|
||||
GO_MINIMAL_TOOLS = (
|
||||
"list_hosts",
|
||||
"get_host_detail",
|
||||
"get_screenshot",
|
||||
"list_files",
|
||||
"get_audit_log",
|
||||
"get_server_status",
|
||||
"terminal_exec",
|
||||
"terminal_close",
|
||||
"read_file",
|
||||
)
|
||||
# YAMA_MCP_READONLY=1 时 Go 端隐藏的写工具(terminal_* 会创建/关闭会话)。
|
||||
GO_READONLY_HIDDEN = ("terminal_exec", "terminal_close")
|
||||
|
||||
FIELDS = ("description", "inputSchema", "outputSchema")
|
||||
|
||||
|
||||
def normalize(obj):
|
||||
"""规范化:键排序后序列化,消除 JSON object 的键序差异。"""
|
||||
@@ -91,11 +115,107 @@ def fetch_live(token, port=None):
|
||||
sys.exit(f"连接失败 -> {last}")
|
||||
|
||||
|
||||
def report_field_diffs(live_by_name, golden_by_name, names):
|
||||
"""逐字段比较同名工具,返回差异处数;一个工具最多报一处。"""
|
||||
diffs = 0
|
||||
for name in names:
|
||||
a, b = live_by_name[name], golden_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
|
||||
return diffs
|
||||
|
||||
|
||||
def verify_subset(path, token, port, readonly):
|
||||
"""Go 最小服务端:名字集合恰好是 GO_MINIMAL_TOOLS,schema 与 tools.json 一致。"""
|
||||
expected = [n for n in GO_MINIMAL_TOOLS
|
||||
if not (readonly and n in GO_READONLY_HIDDEN)]
|
||||
tools_live, live_stats = fetch_live(token, port)
|
||||
print(f"tools.json: {path}")
|
||||
print(f"模式: {'只读(隐藏 ' + ' / '.join(GO_READONLY_HIDDEN) + ')' if readonly else '读写'}")
|
||||
print(f"期望: {len(expected)} 个工具 / 服务端: {len(tools_live)} 个")
|
||||
|
||||
live_names = [t["name"] for t in tools_live]
|
||||
expected_set, live_set = set(expected), set(live_names)
|
||||
diffs = 0
|
||||
extra = sorted(live_set - expected_set)
|
||||
missing = [n for n in expected if n not in live_set]
|
||||
if extra:
|
||||
diffs += len(extra)
|
||||
print(f"!! 服务端多出: {extra}")
|
||||
if missing:
|
||||
diffs += len(missing)
|
||||
print(f"!! 服务端缺少: {missing}")
|
||||
dupes = sorted({n for n in live_names if live_names.count(n) > 1})
|
||||
if dupes:
|
||||
diffs += len(dupes)
|
||||
print(f"!! 服务端重复: {dupes}")
|
||||
|
||||
# 顺序一致性:tools/list 的数组顺序会影响模型的选择倾向
|
||||
if not extra and not missing and not dupes:
|
||||
order = [n for n in live_names if n in expected_set]
|
||||
if order != expected:
|
||||
diffs += 1
|
||||
print("!! 工具顺序与 tools.json 不一致")
|
||||
for i, (x, y) in enumerate(zip(order, expected)):
|
||||
if x != y:
|
||||
print(f" 首个差异 @{i}: 服务端={x} 期望={y}")
|
||||
break
|
||||
else:
|
||||
print("工具顺序: 一致")
|
||||
|
||||
doc = json.load(open(path, encoding="utf-8"))
|
||||
tools_json = doc["tools"] if isinstance(doc, dict) else doc
|
||||
golden_by_name = {t["name"]: t for t in tools_json}
|
||||
live_by_name = {t["name"]: t for t in tools_live}
|
||||
|
||||
comparable = []
|
||||
for name in expected:
|
||||
if name not in golden_by_name:
|
||||
diffs += 1
|
||||
print(f"!! tools.json 缺少工具 {name}")
|
||||
elif name in live_by_name:
|
||||
comparable.append(name)
|
||||
diffs += report_field_diffs(live_by_name, golden_by_name, comparable)
|
||||
|
||||
print(f" 体积: 响应 {live_stats['response_bytes']} B / tools 数组 "
|
||||
f"{live_stats['tools_array_bytes']} B")
|
||||
if diffs == 0:
|
||||
print(f"\nPASS: Go 服务端 {len(expected)} 个工具与 tools.json 完全一致")
|
||||
return 0
|
||||
print(f"\nFAIL: {diffs} 处差异")
|
||||
return 1
|
||||
|
||||
|
||||
def main():
|
||||
args = sys.argv[1:]
|
||||
if not args:
|
||||
sys.exit(__doc__)
|
||||
|
||||
if args[0] == "--subset":
|
||||
argv = [a for a in args[1:]]
|
||||
readonly = "--readonly" in argv
|
||||
argv = [a for a in argv if a != "--readonly"]
|
||||
if not argv:
|
||||
sys.exit("用法: python verify_tools.py --subset <tools.json> [token] [port] [--readonly]")
|
||||
path = argv[0]
|
||||
token = resolve_token(argv[1] if len(argv) > 1 else "")
|
||||
port = int(argv[2]) if len(argv) > 2 else None
|
||||
if not token:
|
||||
sys.exit("未找到 McpToken(参数 / YAMA_MCP_TOKEN / 注册表 均无)")
|
||||
return verify_subset(path, token, port, readonly)
|
||||
|
||||
if args[0] == "--offline":
|
||||
if len(args) < 3:
|
||||
sys.exit("用法: python verify_tools.py --offline <tools.json> <黄金样本.json>")
|
||||
@@ -142,24 +262,9 @@ def main():
|
||||
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 # 一个工具报一次即可
|
||||
FIELDS_SHARED = sorted(set(live_by_name) & set(json_by_name))
|
||||
diffs += report_field_diffs(live_by_name, json_by_name, FIELDS_SHARED)
|
||||
|
||||
# 顺序一致性:tools/list 的数组顺序会影响模型的选择倾向
|
||||
order_live = [t["name"] for t in tools_live]
|
||||
|
||||
Reference in new issue
Block a user