Feature(Go): MCP endpoint with bearer auth and tools/list

Add a stateless POST /mcp endpoint to the Go server, mounted by the web
server and built from an environment-driven Config in cmd.

The endpoint gates on YAMA_MCP_TOKEN: without it the route is not
registered and /mcp 404s. Requests use a constant-time bearer compare,
and transport failures stay transport failures (401 with a
WWW-Authenticate challenge, 405 for anything but POST, 413 above 8 MiB,
204 for notifications). Everything after a parsed JSON-RPC request is
HTTP 200, including -32600 for batch arrays and -32601 for unknown
methods or tools.

tools/list returns the nine minimal tools verbatim from an embedded
copy of the canonical schemas. tools/mcp_tools/gen_go_tools.py extracts
them from mcp/tools.json, preserving order and only the four published
fields, and its --check mode detects drift. Readonly mode hides and
refuses terminal_exec/terminal_close (-32006); tools that are listed but
not implemented yet answer -32000 until their milestone lands.

Also sync design §3.2 and the M2/M7/M8 plan text to tools.json, which
is the sole schema contract: files not entries, line-based read_file,
no since, camelCase capabilities, max_width [64,1920] defaulting to
1024, and outputSchema included in the M8 subset comparison.

Co-Authored-By: deepseek-flash
This commit is contained in:
yuanyuanxianganddeepseek-flash committed 2026-11-12 20:35:03 +01:00
1 parent 5f124fcb3a
commit 3f1957a9c9
11 files changed
+2022 -60

No files matched your search

+69 -46
View File
@@ -125,58 +125,72 @@
### 3.2 逐个定义
本节只用于阅读;**参数名与返回字段的唯一契约是 `mcp/tools.json` 的 `inputSchema` /
`outputSchema`**(M1 起 `tools/list` 原样返回这些定义)。Go 取不到的字段省略,不伪造。
#### `list_hosts`
```jsonc
// input
{ "group": "asm", "name": "ASM-", "online_only": true, "limit": 50, "offset": 0 }
// input(全部可选)
{ "client_type": "EXE", "group": "asm", "include_offline": false, "ip": "10.",
"limit": 100, "name": "ASM-", "offset": 0, "online": true, "os": "Windows",
"query": "asm" }
// output.structuredContent
{ "total": 7, "returned": 7, "hosts": [ /* hub.DeviceInfo */ ] }
{ "hosts": [ /* ... */ ], "total": 7, "totalAll": 9, "limit": 100, "offset": 0, "hasMore": false }
```
`hub.DeviceInfo` 已含 `id/name/group/version/capability/os/rtt/activeWindow/ip/peer_ip/screen/connected_at/online/last_seen`,
直接序列化,**不裁剪字段**——模型排障需要的正是这些。`online_only=false` 时合并
`devicehistory.Store.Offline(online)` 的历史条目。
`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 只匹配计算机名,`query` 同时匹配
计算机名、备注与 IP;`online=true`(默认)只列在线,`false` 只列历史中存在但当前离线的;
`include_offline=true` 时再合并 `devicehistory.Store.Offline(online)`。`total` 是过滤后命中数,
`totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。
`group` 与 `name` 都是子串匹配(与 MFC `list_hosts` 一致),`name` 大小写不敏感。
`hosts[]` 的字段按 `outputSchema`:`id/name/group/version/clientType/os/ip/rtt/activeWindow/
screen/online/last_seen`;hub 没有 `authStatus/tls/location/install_time/remark`,不出现。
#### `get_host_detail`
```jsonc
{ "id": "7888521104752806905" }
{ "id": "7888521104752806905" } // 或 { "ids": ["…", "…"] }(≤50 台,批量)
```
返回 `DeviceInfo` + `capabilities: { utf8, screen_preview, screen_region, window_info }`(由
`protocol.SupportsCap` 逐位解出)。**这是 MFC 优化里被验证过的高价值字段**:
模型不用靠 `-32005` 试错就知道这台机器能不能截图。
单台返回 `{ host: {...} }`;批量返回 `{ tool, total, succeeded, failed, skipped, results[] }`。
`host.capabilities` 由 `protocol.SupportsCap` 逐位解出,字段名与 schema 一致:
`screenPreview / screenRegion / windowInfo / fileTransferV2 / c2cPaths / registry /
remoteControl / platform`。
注意**不要把 `v2` 放进 capabilities**:`CLIENT_CAP_V2` 在 `DefaultCaps()` 里全平台恒真
(`common/commands.h:1289`),列出来只会误导模型。
#### `get_server_status`
```jsonc
{} // 无参
```
返回 `{ version, commit, uptime_s, devices_online, devices_offline_known, mcp: { readonly, tools } }`。
`version`/`commit` 取 `-ldflags -X` 注入的构建变量——**Go 侧目前没有这两个变量**
(`cmd/main.go` 里查不到版本常量),需要新增两行 `var version, commit string` 并在
`Makefile` 里注入;拿不到时返回空串,不要伪造。
无参。返回字段按 `outputSchema`:`version / uptime_sec / hosts / sessions / port / bind /
switches / blocked_auth_ips / exe_build_time / app_name`。Go v1 只填能如实取到的:
`version`(buildinfo)、`uptime_sec`、`hosts`(在线/历史计数)、`sessions`(MCP 活动调用,
M3 起)、`port`、`bind`;其余属 MFC 专有,直接不给(schema 的 `required` 为空)。
`version` 取 `-ldflags -X` 注入的 `buildinfo.Version`——**Go 侧目前没有版本变量**
(`cmd/main.go` 里查不到),需要新增 `buildinfo` 包并在 `Makefile` / `build.ps1` 里注入;
拿不到时返回空串,不要伪造。`commit` 只用于日志与排障,不塞进 schema 未定义的返回字段。
#### `get_audit_log`
```jsonc
{ "keyword": "terminal", "type": "mcp", "since": "2026-11-12T00:00:00Z", "limit": 100, "offset": 0 }
{ "keyword": "terminal", "type": "mcp", "limit": 100, "offset": 0 }
```
复用 `web/audit_query.go` 的查询器,返回 `{ total, returned, records[] }`。
复用 `web/audit_query.go` 的查询器(M2 抽成 `auditquery`),返回
`{ entries, total, totalAll, limit, offset, hasMore }`。**没有 `since`**:MFC 的 schema 里就没有。
#### `get_screenshot`
```jsonc
{ "id": "...", "max_width": 1600 }
{ "id": "...", "max_width": 1024 }
// output: content[] 里一项 image(mimeType=image/jpeg, base64 data)
// structuredContent: { width, height, bytes, format, source: "preview" }
// structuredContent: { image: { mimeType, width, height, bytes },
// capture: { mode, x, y, width, height, scale, native } }
```
细节见 §7。
`max_width` 钳制到 `[64,1920]`;缺省/0 时 Go v1 固定 1024(没有 MFC 的 RTT 自适应档位)。
`mode=region/window/monitor` 与 `hwnd/x/y/width/height` 需要 `CLIENT_CAP_SCREEN_REGION` 扩展,
M5 之前传任一参数都返回 `-32005` 并在 message 里点名。细节见 §7。
#### `terminal_exec`
@@ -186,41 +200,48 @@
// 轮询(不带 command)
{ "id": "...", "session_id": "s-3f2a", "timeout_ms": 20000 }
// output
{ "session_id": "s-3f2a", "output": "...", "exit_code": 0, "done": true,
"offset": 1843, "truncated": false, "is_pty": true, "reused": false }
{ "session_id": "s-3f2a", "stdout": "...", "done": true, "exit_code": 0,
"is_pty": true, "reused": false, "truncated": false, "dropped_bytes": 0, "elapsed_ms": 412 }
```
超时未完成时 `done=false`、无 `exit_code`、`output` 是已产生的部分输出,**会话保留**。
超时未完成时 `done=false`、无 `exit_code`;`stdout` 是已产生的部分输出,**会话保留**,
用同一 `session_id` 轮询。`max_output_bytes`(1024..1048576,默认 65536)按行截断并置
`truncated`,剩余内容下次轮询取。
#### `terminal_close`
```jsonc
{ "session_id": "s-3f2a" } // 幂等:会话不存在也返回成功
{ "id": "...", "session_id": "s-3f2a" } // 幂等:会话不存在也返回成功
```
#### `list_files`
```jsonc
{ "id": "...", "path": "C:\\ProgramData\\AssemblyManager", "limit": 200 }
{ "id": "...", "path": "C:\\ProgramData\\AssemblyManager", "limit": 100, "offset": 0 }
// output
{ "path": "...", "total": 42, "returned": 42, "entries": [
{ "name": "settings.ini", "isDir": false, "size": 1204, "mtime": 1699999999 } ] }
{ "files": [ { "name": "settings.ini", "isDir": false, "size": 1204, "mtime": 1699999999 } ],
"total": 42, "totalAll": 42, "limit": 100, "offset": 0, "hasMore": false }
```
`path` 为空或 `"drives"` 时返回盘符列表 `{ drives: [{ drive, typeName, fileSystem, totalMB, freeMB }] }`。
`path` 为空时返回盘符列表 `{ drives: [{ drive, typeName, fileSystem, totalMB, freeMB }] }`。
批量传 `ids` 时结果按台汇总在 `results` 里。注意返回数组字段是 `files`,不是 `entries`。
#### `read_file`
```jsonc
{ "id": "...", "path": "C:\\ProgramData\\AssemblyManager\\.env",
"offset": 0, "limit": 262144, "encoding": "auto" }
"offset": 0, "limit": 2000, "max_bytes": 262144, "encoding": "auto" }
// output
{ "path": "...", "size": 4096, "bytes_read": 4096, "truncated": false,
"encoding": "utf-8", "text": "IR_ENDPOINT=...", "sha256": "..." }
{ "path": "...", "size": 4096, "encoding": "utf-8", "eol": "lf",
"lines_total": 120, "offset": 0, "lines_returned": 120,
"text": "IR_ENDPOINT=...", "sha256": "...", "truncated": false }
```
`encoding`:`auto`(默认,先 UTF-8 严格解码,失败回退 GBK)/ `utf-8` / `gbk` / `latin1`。
`offset` 支持负数表示"从尾部倒数 N 字节"(MFC 同款,读日志尾部最常用)。
**上限 2 MiB**(`YAMA_MCP_READ_MAX`):V2 下载没有区间参数,只能整文件拉,超过就拒绝。
`offset`/`limit` 是下载后的窗口裁剪,绕不过这个门。
**行语义**:`offset` 是起始行(0 基,负数表示末尾 N 行),`limit` 是行数(1..200000,默认
2000),`max_bytes` 是本次返回文本的字节上限(1024..2097152,默认 262144=256KB),
超出按行截断并置 `truncated`。`encoding`:`auto`(BOM → UTF-8 合法性 → GBK 回退)/
`utf-8` / `gbk` / `gb18030` / `latin1`;`eol` 为 `crlf/lf/cr/mixed/none`。
**整文件上限 2 MiB**(`YAMA_MCP_READ_MAX`):V2 下载没有区间参数,只能整文件拉,超过就拒绝
(`-32602`)。`offset`/`limit` 是下载后的窗口裁剪,绕不过这个门。
---
@@ -553,7 +574,7 @@ struct ScreenPreviewRspHeader { // 16 字节
v1 只发 8 字节基础请求(等价于整虚拟桌面),**不发 v2 扩展**——`region/window/monitor`
需要 `CLIENT_CAP_SCREEN_REGION`,属后续增强。
参数映射:`max_width` 默认 1600,钳制到 `[320, 3840]`;`jpegQuality` 固定 80。
参数映射:`max_width` 钳制到 `[64, 1920]`,缺省/0 时 Go v1 固定 1024;`jpegQuality` 固定 80。
### 7.3 BGRX → JPEG
@@ -598,18 +619,19 @@ jpeg.Encode(&buf, img, &jpeg.Options{Quality: 80})
失败回执;老客户端路径不存在时直接不回包,表现为 `-32001` 超时(message 里要提示
"路径可能不存在,先用 list_files 确认")。
`total` 与 `returned` 分开:客户端一次返回全部,服务端做 `limit` 截断并在
`structuredContent` 里如实说明(与 MFC 的分页语义一致)。
`total` 与本次返回条数分开:客户端一次返回全部,服务端做 `limit`/`offset` 窗口裁剪并在
`structuredContent` 里如实给出 `total`/`totalAll`/`hasMore`(与 MFC 的分页语义一致)。
### 8.2 `read_file`
见 §5.4。落盘完成后:
1. 校验 SHA-256(`COMMAND_FILE_COMPLETE_V2` 里带的 32 字节)。
2. 打开临时文件,按 `offset`/`limit` 读取(负 `offset` 从尾部倒数)。
3. 按 `encoding` 解码:`auto` 先试严格 UTF-8(`utf8.Valid`),失败回退 GBK
(`golang.org/x/text/encoding/simplifiedchinese`,go.mod 已有)。
4. 返回 `text` + `size` + `bytes_read` + `truncated` + `sha256`。
2. 按 `encoding` 解码全文(`auto`:BOM → 严格 UTF-8 → GBK 回退;`gb18030`/`latin1` 显式指定)。
3. 按行切分,按 `offset`(0 基,负数=末尾 N 行)/`limit`/`max_bytes` 取窗口;`max_bytes`
按行边界截断,避免切坏 UTF-8/GBK 多字节字符。
4. 返回 `text` + `size` + `encoding` + `eol` + `lines_total` + `offset` + `lines_returned` +
`truncated` + `sha256`。
5. `defer os.RemoveAll(tmpDir)`。
**大小门**:`CMD_DOWN_FILES_V2` **没有区间参数,只能整文件下载**,所以大小门必须卡在
@@ -793,7 +815,8 @@ flags(2) checksum(2) reserved(8)` = 77 字节。
| 20 | §3.2 `get_server_status` 返回 `version`/`commit`,但 Go 侧没有这两个变量 | **补**。`cmd/main.go` 查不到版本常量,需新增 `var version, commit string` + Makefile `-X` 注入;拿不到返回空串 |
| 21 | §3.2 `get_host_detail.capabilities` 里列了 `v2` | **删**。该位全平台恒真(同 #10),列出来误导模型。换成 `utf8`/`screen_preview`/`screen_region`/`window_info` |
| 22 | §5.2 写死 `SendToTerminal(cmd+"\n")`,与 §6.4 的 ConPTY `\r\n` 冲突 | **改** 为按平台分行尾 |
| 23 | §3.2 的输入/输出形状是自造结构,与 `mcp/tools.json` 不一致(`online_only`、`entries`、`since`、`bytes_read`、`output`、capabilities 下划线命名、`max_width` 1600/[320,3840]) | **改**。已确认 `mcp/tools.json` 是唯一契约,§3.2 按 `inputSchema`/`outputSchema` 重写:`list_files` 返回 `files`、`read_file` 为行语义、审计无 `since`、capabilities 用 camelCase、`max_width` 钳制 `[64,1920]` 默认 1024;M1 起 `tools/list` 原样回显该 schema |
**结论**:以上 22 处已全部修入正文,无遗留。v1 对 `server/go` 的改动是
**结论**:以上 23 处已全部修入正文,无遗留。v1 对 `server/go` 的改动是
**新增 `mcp` 包 + `web/server.go` 一行路由 + `web.Server` 一个 `WithMCP` + `cmd/main.go` 六个 case + `protocol` 六个常量 + 两个版本变量**,
`hub` 零改动。
+12 -9
View File
@@ -200,15 +200,17 @@ curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
- `get_host_detail`:`id` 或 `ids`(≤50,批量走 `{tool,total,succeeded,failed,skipped,results[]}`);
`capabilities{screenPreview,screenRegion,windowInfo,fileTransferV2,c2cPaths,registry,remoteControl,platform}`
(`protocol.SupportsCap` 逐位)——**不含 `v2`**(恒真,列出来误导)。
- `get_server_status`:`{version,commit,uptime_s,devices_online,devices_offline_known,
mcp:{readonly,tools}}`;`version`/`commit` 取 `buildinfo`(§1.2),`uptime` 用 `mcp.Config.StartedAt`。
- `get_server_status`:按 `outputSchema` 的字段名组装,Go 只填能如实取到的
`version / uptime_sec / hosts / sessions / port / bind`(其余 MFC 专有字段不给);
`version` 取 `buildinfo`(§1.2),`uptime_sec` 用 `mcp.Config.StartedAt`,`commit`
只进日志,不塞进 schema 未定义的返回字段。
- `get_audit_log`:`auditquery.Scan`;`type` 映射事件过滤;无 `since`。
3. `buildinfo` 包 + `build.ps1` / `Makefile` 的 `-X` + winres 重建(§1.2)。
**测试**(`mcp/tools_local_test.go`)
- `devicehistory.New(t.TempDir()+"/devices.json", 10, log)` + `hub.Register` 造 3 台在线、2 台历史
离线;断言过滤/分页/`total` 与 `returned` 分离。
离线;断言过滤/分页,以及 `total`(命中数)、`totalAll`(过滤前)、`hasMore` 三者分离。
- `get_host_detail` 的能力位:给一个 capability 串(含/不含 `0x0004`)两种。
- `get_audit_log`:用 `logger.Audit` 写临时文件后查询(`auditquery` 的用例在搬包时一并迁)。
@@ -325,9 +327,10 @@ curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
(不要先落盘再报错)。
4. **路径校验**(安全,必须单测):`filepath.Clean(filepath.Join(targetDir, FromSlash(name)))`
+ `filepath.Rel` 判越界;另拒 NUL / 换行;`name` 允许客户端回填为相对路径。
5. SHA-256 校验(完成包 32 字节)→ 读窗口(负 `offset` 从尾部倒数)→ 编码判定
(`utf8.Valid` 优先,失败回退 `simplifiedchinese.GBK`,`latin1` 逐字节)→ 返回
`{path,size,bytes_read,truncated,encoding,text,sha256}`。
5. SHA-256 校验(完成包 32 字节)→ 编码判定(BOM → `utf8.Valid` → 回退
`simplifiedchinese.GBK`,`latin1` 逐字节)→ 按行切分并取
`offset`/`limit`/`max_bytes` 窗口 → 返回
`{path,size,encoding,eol,lines_total,offset,lines_returned,truncated,text,sha256}`。
6. 超时/断流:`-32001`;工具描述写明"超时可能是不支持 V2 的旧客户端"(设计 R3)。
**测试**:路径穿越用例集(`../x`、`..\\..\\x`、绝对路径、UNC、混合分隔符、`a/../../b`);
@@ -336,9 +339,9 @@ curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
### M8 校验工具与文档(设计 §10)
1. `verify_tools.py --subset <tools.json> [token] [port] [--readonly]`:
抓 Go 服务端 `tools/list`,与 `tools.json` 同名工具逐字段比 `description` / `inputSchema`;
**忽略 `outputSchema`**(Go 不做);名字集合必须恰好等于期望的 9(或 7);
多一个少一个都失败。
抓 Go 服务端 `tools/list`,与 `tools.json` 同名工具逐字段比 `description` / `inputSchema` /
`outputSchema`(与 `verify_tools.py` 的 `FIELDS` 口径一致);名字集合必须恰好等于
期望的 9(或 7),多一个少一个都失败。
2. 同批更新:`deploy/yama-server.env.example` 加 `YAMA_MCP_TOKEN` / `YAMA_MCP_READONLY` /
`YAMA_MCP_TERM_IDLE` / `YAMA_MCP_MAX_CONCURRENCY` / `YAMA_MCP_READ_MAX`;
设计文档状态改"已实施"。