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
527 lines
33 KiB
Markdown
527 lines
33 KiB
Markdown
# Go 服务端 MCP 实施计划
|
||
|
||
> 版本:v1(草稿,待评审) 日期:2026-11-12
|
||
>
|
||
> 依据:`docs/Mcp_Go_Minimal_Design.md` v1.0(下称"设计文档")。
|
||
> 本文只回答**怎么施工**:顺序、改动面、完成定义、验证手段、提交边界。
|
||
> 设计取舍一律以设计文档为准,本文不重复论证;与设计文档不一致的地方在 §1 单列。
|
||
>
|
||
> 工作方式:沿用本项目既有节奏——**做一段、验一段、审一段、提交一段**,每段一个可独立
|
||
> 回滚的提交。Go 侧提交前缀用仓库既有约定 `Feature(Go):` / `Fix(Go):`。
|
||
|
||
---
|
||
|
||
## 0. 交付面与总量
|
||
|
||
| 类别 | 内容 | 规模 |
|
||
|---|---|---:|
|
||
| 新包 | `server/go/mcp/`(server / tools / errors / audit / lock / session / term / screen / filemgr / filev2) | ≈2,300 行(含测试 ≈900) |
|
||
| 抽包 | `server/go/auditquery/`(从 `web/audit_query.go` 提出查询器,见 §1.1) | ≈180 行搬移 |
|
||
| 接线 | `web/server.go`(`WithMCP` + 一行路由)、`cmd/main.go`(构造/注入/六个 case/版本变量)、`protocol/commands.go`(常量)、`build.ps1` + `Makefile`(`-X` 注入) | ≈120 行 |
|
||
| 工具校验 | `tools/mcp_tools/verify_tools.py` 增 `--subset` | ≈80 行 |
|
||
| 文档 | `deploy/yama-server.env.example` 补 5 个变量;`docs/Mcp_Go_Minimal_Design.md` 状态改"已实施" | — |
|
||
|
||
**8 个提交,8 个里程碑,预估 62 小时**(明细见 §3 / §7)。`hub` 零改动——这是设计文档
|
||
自审后的结论,本计划沿用;若施工中发现必须改 `hub`,先停下来改设计文档。
|
||
|
||
---
|
||
|
||
## 1. 开工前必须先定的 5 件事
|
||
|
||
这 5 项都会阻塞某个里程碑,且都需要一次性拍板。建议按顺序在本计划评审时定掉。
|
||
|
||
### 1.1 `get_audit_log` 的代码复用方式(阻塞 M2)
|
||
|
||
设计文档 §3.2 要求"复用 `web/audit_query.go` 的查询器",§10 又要求"`mcp` 不 import `web`"。
|
||
两者冲突:查询器 `queryAuditLog` 及其类型/过滤/时间解析全是 `web` 包私有(`web/audit_query.go:158-328`)。
|
||
|
||
| 方案 | 做法 | 代价 |
|
||
|---|---|---|
|
||
| **A(推荐)** | 新增 `server/go/auditquery` 包,把 `queryAuditLog` + `auditQueryRequest/Result` + `auditRecordMatches` / `auditEventFilterMatches` / `auditStringField` / `parseAuditTime` / `clamp*` 整体搬过去并导出(`Scan(path string, q Query) (Result, error)`);`web/audit_query.go` 只留 handler 与回包整形 | 搬移 + `web/audit_query_test.go`(294 行)机械改调用名;依赖方向保持不变 |
|
||
| B | `mcp` 自己实现一个精简扫描器(keyword/type/limit/offset) | 少动 `web`,但审计格式一旦变就有两份实现 |
|
||
| C | `mcp` import `web` | 破环:`web → mcp` 已存在(`WithMCP`),反向成环直接编译失败 |
|
||
|
||
**已确认:采用 A**。M2 的第一步就是搬包,`go test ./web/...` 全绿后再写工具。
|
||
|
||
### 1.2 版本号与提交号注入(阻塞 M2 的 `get_server_status`)
|
||
|
||
`cmd/main.go` 目前没有版本常量(全文件 grep 不到)。**已确认**的做法:
|
||
|
||
- 新增 `server/go/buildinfo`,只放 `var Version, Commit string`(零值空串)+ `Snapshot()`。
|
||
不塞 `main`:`mcp` 不能依赖 `main`,也不该为两个字符串在装配链上多传两层。
|
||
- 注入:`-X github.com/yuanyuanxiang/SimpleRemoter/server/go/buildinfo.Version=…`,同样注入 `.Commit`。
|
||
取值 `Version=$(git describe --tags --always --dirty)`、`Commit=$(git rev-parse --short HEAD)`
|
||
(现在是 `v1.4.2-72-g425d737-dirty` / `425d737`)。
|
||
- `build.ps1`:Debug/Release **都**拼 `-X`(Debug 只是不剥符号);`Makefile` 的 `LDFLAGS`
|
||
用 `$(shell git …)` 同步。
|
||
- 取不到(无 git、源码包构建)就保持空串,`get_server_status` 原样返回空串,**不伪造**。
|
||
- Windows 资源同步:`cmd/winres/winres.json` 里的版本号改成占位,构建前跑
|
||
`go-winres make --in cmd/winres/winres.json --out cmd/rsrc --product-version git-tag --file-version git-tag`
|
||
(实测会把 manifest identity / FileVersion / ProductVersion 三处一起覆盖成 `1.4.2`);
|
||
`go-winres` 不存在时警告并跳过。`server/go/cmd/*.syso` 加进 `.gitignore`,不再出现在
|
||
`git status` 里。文件属性 = 干净 tag,运行时 `version` = `git describe` 全串,各司其职。
|
||
|
||
### 1.3 工具 schema 用哪一份(阻塞 M2/M5/M6/M7)
|
||
|
||
设计文档 §3.2 给的参数集与 `mcp/tools.json`(MFC 现网 schema)**并不完全一致**:
|
||
|
||
| 工具 | 设计文档 §3.2 | `mcp/tools.json` 实际 |
|
||
|---|---|---|
|
||
| `list_hosts` | `group` `name` `online_only` `limit` `offset` | `client_type` `group` `include_offline` `ip` `limit` `name` `offset` `online` `os` `query` |
|
||
| `get_host_detail` | `id` | `id` `ids` |
|
||
| `get_audit_log` | `keyword` `type` `since` `limit` `offset` | `keyword` `limit` `offset` `type` |
|
||
| `get_screenshot` | `id` `max_width` | `id` `max_width` `height` `hwnd` `mode` `monitor` `width` `x` `y` |
|
||
| `terminal_exec` | 一致 | 一致 |
|
||
| `terminal_close` | `session_id` | `id` `session_id` |
|
||
| `list_files` | `id` `path` `limit` | `id` `ids` `limit` `offset` `path` |
|
||
| `read_file` | `id` `path` `offset` `limit` `encoding` | 同 + `max_bytes` |
|
||
|
||
设计文档自称"全部命名、参数、错误码与 MFC 对齐",实际只有 naming 与错误码对齐。
|
||
**已确认:`mcp/tools.json` 是唯一契约**——`name` / `description` / `inputSchema` /
|
||
`outputSchema` 和工具顺序都按它来(`verify_tools.py:12` 的比对口径)。
|
||
|
||
- 9 个工具的这四份字段由 `tools/mcp_tools/gen_go_tools.py` 从 `mcp/tools.json` 抽取(保持相对顺序),
|
||
写到 `server/go/mcp/tools_minimal.json`,Go 侧 `//go:embed` 原样回 `tools/list`;脚本支持
|
||
`--check`(子集与抽取结果不等则非零退出),加一个 Go 单测锁名字与顺序。
|
||
- `tools.json` 里没有 `annotations`,MFC 也不发,Go 不发(M1 的测试相应改为"不带 annotations")。
|
||
- 输出按对应 `outputSchema` 的字段名组装,**不套用设计文档 §3.2 的自造形状**。
|
||
|
||
| 参数 | Go 侧处理 |
|
||
|---|---|
|
||
| `list_hosts` 全部 10 个 | 全部实现(`DeviceInfo` 上做字符串过滤,成本可忽略) |
|
||
| `get_host_detail.ids` | 实现批量(≤50),按 `outputSchema` 的 `{tool,total,succeeded,failed,skipped,results[]}` 汇总 |
|
||
| `get_audit_log` | `keyword` / `type`(映射 `auditquery.Event`)/ `limit` / `offset`;**没有 `since`**(MFC 的 schema 里就没有) |
|
||
| `get_screenshot` 的非整屏参数 | `mode=region/window/monitor` 或 `hwnd/x/y/width/height` 任一出现 → `-32005`,报文点名参数并说明需要 `CLIENT_CAP_SCREEN_REGION` 扩展请求;不静默忽略 |
|
||
| `get_screenshot.max_width` | 钳制 `[64,1920]`(schema 与 `McpServer.cpp:3386` 一致);缺省/0 → Go v1 固定 1024(没有 MFC 的 RTT 自适应档位) |
|
||
| `terminal_close.id` | 必需;用于定位设备,`session_id` 用于匹配会话 |
|
||
| `list_files` 的 `id/ids/path/limit/offset` | 全部实现;`offset` 是服务端在完整列表上做窗口裁剪;批量走 results 汇总 |
|
||
| `read_file` 的语义 | **行语义**:`offset` 起始行(负数=末尾 N 行)、`limit` 行数、`max_bytes` 字节上限;`encoding` 支持 `auto/utf-8/gbk/gb18030/latin1` |
|
||
| 输出字段 | `list_hosts` → `hosts/total/totalAll/limit/offset/hasMore`;`list_files` → `files`(不是 `entries`)/`drives`;`get_host_detail.capabilities` → `screenPreview/screenRegion/windowInfo/fileTransferV2/c2cPaths/registry/remoteControl/platform`;`read_file` → `encoding/eol/lines_total/lines_returned/sha256/size/text/truncated` |
|
||
| hub 没有的字段 | `authStatus/tls/location/install_time/remark` 不伪造、直接不给(`outputSchema` 只强制 `hosts`) |
|
||
|
||
`read_file` 的整文件下载仍受 `YAMA_MCP_READ_MAX`(2 MiB)硬门约束,超过 → `-32602`(schema 描述同款口径)。
|
||
|
||
### 1.4 测试环境与"真机"路径(阻塞 M4 起的全部验收)
|
||
|
||
**已确认并已由 M0 实测**(详见 §4.3):本机真客户端用 **`x64\Debug\ghost.exe`**,
|
||
`TestRun.exe` 不可用(依赖 `ServerDll.dll` 内存加载;Release 版从非安装路径启动会走安装
|
||
流程并自删)。Go 服务端默认 **trial** 签名即可,客户端已上线;屏幕/文件能力是否解锁
|
||
在 M5/M6 实测(`YAMA_LICENSE_DISABLED=1` 的 NoOp 会让客户端拒绝这两类功能,不要用于
|
||
M5 之后的验收)。
|
||
|
||
### 1.5 只读模式下的工具集合(阻塞 M8)
|
||
|
||
`YAMA_MCP_READONLY=1` 时 `tools/list` 只出 7 个。`--subset` 必须支持"期望集合 7 或 9"两种,
|
||
由环境变量或 `--readonly` 参数决定;不能写成硬编码 9。
|
||
|
||
---
|
||
|
||
## 2. 里程碑与提交边界
|
||
|
||
| 里程碑 | 提交标题(建议) | 设计文档 § | 依赖 | 完成定义(可验收) | 预估 |
|
||
|---|---|---|---|---:|
|
||
| M1 | `Feature(Go): MCP endpoint with bearer auth and tools/list` | §4、§3.1 | — | `curl` 打通 initialize/ping/tools/list;错误令牌 401;GET 405;通知 204 | 6h |
|
||
| M2 | `Feature(Go): four local MCP read tools and a shared audit query package` | §3.2、§1.1 | M1 | 4 个工具返回真实数据;`go test ./web/...` 与新增用例全绿 | 10h |
|
||
| M3 | `Feature(Go): per-device locks, concurrency cap and MCP audit trail` | §9、§4.4 | M1 | 并发调用返回 -32003;每次调用一条 `mcp.tool.call` | 4h |
|
||
| M4a | `Feature(Go): MCP terminal sessions with a ring buffer` | §6.1-§6.3 | M3 | 会话表 + 订阅 + 缓冲;浏览器开终端时 MCP 返回 -32003 | 6h |
|
||
| M4b | `Feature(Go): terminal_exec with sentinel cleaning and polling` | §6.4-§6.6 | M4a | 20 条连续命令零失败;超时后轮询取回完整输出 | 8h |
|
||
| M4c | `Feature(Go): terminal_close, idle sweep and legacy-client guard` | §6.2、§6.7 | M4b | 关闭幂等;空闲 180s 回收;非 PTY 返回 -32005 | 2h |
|
||
| M5 | `Feature(Go): get_screenshot over the maintenance-free preview RPC` | §7 | M3 | Windows/Linux 各出一张图;BGRX 分支有单测 | 6h |
|
||
| M6 | `Feature(Go): list_files over the file-manager sub-connection` | §5.3、§8.1 | M3 | 盘符/目录/错误三种路径;老客户端超时有明确 message | 8h |
|
||
| M7 | `Feature(Go): read_file over the V2 stream receiver` | §5.4、§8.2-§8.3 | M6 | `.env` 字节一致且 SHA-256 匹配;路径穿越全部拒收 | 10h |
|
||
| M8 | `Feature(Go): verify_tools --subset and MCP deployment docs` | §10、§4.2 | M1 | 9(或 7)个工具的 schema/description 与 `tools.json` 严格一致 | 3h |
|
||
|
||
M4 拆成三个提交是因为它占全量工作量的 1/4,一次提交无法审查;其余里程碑按设计文档
|
||
§11 的 10 个施工序合并(§11 的 3 并进 M3,4/5/6 并成 M4a/b/c,7 是 M5,8 是 M6,9 是 M7,10 是 M8)。
|
||
|
||
---
|
||
|
||
## 3. 里程碑细则
|
||
|
||
### M1 骨架与鉴权(设计 §4)
|
||
|
||
**新增文件**
|
||
|
||
```
|
||
server/go/mcp/server.go // Config、Server、New、Enabled、Handle、Close
|
||
server/go/mcp/jsonrpc.go // 请求/响应结构、错误对象、批量拒绝
|
||
server/go/mcp/tools.go // //go:embed tools_minimal.json,tools/list 原样返回
|
||
server/go/mcp/tools_minimal.json // gen_go_tools.py 从 mcp/tools.json 抽取的 9 个工具
|
||
server/go/mcp/errors.go // -32001…-32602 常量与 message 模板
|
||
tools/mcp_tools/gen_go_tools.py // 抽取脚本,--check 模式供验收
|
||
```
|
||
|
||
**实现要点**
|
||
|
||
1. `Config` 从环境变量读全(`cmd/main.go` 解析后传入,`mcp` 包不直接读 env):
|
||
`Token` / `Readonly` / `TermIdle` / `MaxConcurrency` / `ReadMax`。
|
||
2. `Handle` 分支表:`POST` 之外一律 `405`(带 `Allow: POST`);无 `id` 的通知 `204`;
|
||
数组入参 `-32600`;未知 `method` `-32601`;`tools/call` 未知工具名 `-32601`。
|
||
3. 鉴权:`subtle.ConstantTimeCompare`,长度不等直接失败;缺令牌 → `401` +
|
||
`WWW-Authenticate: Bearer realm="mcp"`,不带 JSON-RPC 体(规范要求传输层失败)。
|
||
4. 体积:`http.MaxBytesReader(w, r.Body, 8<<20)`,超限 `413`。
|
||
5. `initialize` 回 `protocolVersion=2025-06-18`、`capabilities.tools={listChanged:false}`、
|
||
`serverInfo={name:"yama", version:<build>}`、`instructions=<Go 后端差异说明>`。
|
||
`serverInfo.name` 与 MFC 一致,Go 差异只写 `instructions`——避免客户端按 name 分叉。
|
||
6. 路由注册:`web/server.go` 加 `WithMCP`,`Start()` 里
|
||
`if s.mcp != nil && s.mcp.Enabled() { mux.HandleFunc("/mcp", s.mcp.Handle) }`,
|
||
否则打一行 `MCP endpoint disabled: YAMA_MCP_TOKEN not set`。
|
||
7. `cmd/main.go`:在 `web.New(...)` 之前构造 `mcpSrv`,再 `.WithMCP(mcpSrv)` +
|
||
`handler.mcp = mcpSrv`(`MyHandler` 加字段);`mcp` 只依赖 `hub`/`protocol`/`devicehistory`/`logger`。
|
||
|
||
**测试**(`mcp/server_test.go`,`httptest` + fake hub)
|
||
|
||
- 令牌:正确 / 错误 / 长度不同 / 缺失 → 200 / 401 / 401 / 401。
|
||
- 方法:`initialize`、`ping`、`tools/list`、`notifications/initialized`(204)、未知方法(-32601)。
|
||
- 形态:批量数组 → -32600;GET/DELETE → 405;超大体 → 413。
|
||
- `tools/list`:数目与 `Readonly` 相符;工具定义与 `tools_minimal.json` 逐字一致且顺序不变
|
||
(无 `annotations`,与 MFC 一致)。
|
||
|
||
**验收命令**
|
||
|
||
```bash
|
||
cd server/go
|
||
go build ./... && go test ./mcp/...
|
||
curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \
|
||
-H 'Content-Type: application/json' \
|
||
-d '{"jsonrpc":"2.0","id":1,"method":"tools/list"}'
|
||
```
|
||
|
||
### M2 本机只读四工具(设计 §3.2)
|
||
|
||
**改动**
|
||
|
||
1. 先做 §1.1 的 `auditquery` 抽包:搬移 → `web` 改调用 → `go test ./web/...` 全绿。
|
||
2. 新增 `mcp/tools_local.go`:
|
||
- `list_hosts`:`hub.ListDevices()` + `history.Offline(onlineSet)` 合并;`include_offline`
|
||
决定是否并入历史;`online/ip/os/group/name/client_type/query` 全为过滤(`name`/`query`
|
||
大小写不敏感子串);按 `outputSchema` 返回 `{hosts,total,totalAll,limit,offset,hasMore}`,
|
||
host 字段按 schema 命名组装,hub 没有的(`authStatus/tls/location/install_time/remark`)不伪造。
|
||
- `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`:按 `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`(命中数)、`totalAll`(过滤前)、`hasMore` 三者分离。
|
||
- `get_host_detail` 的能力位:给一个 capability 串(含/不含 `0x0004`)两种。
|
||
- `get_audit_log`:用 `logger.Audit` 写临时文件后查询(`auditquery` 的用例在搬包时一并迁)。
|
||
|
||
### M3 锁、并发与审计(设计 §9、§4.4)
|
||
|
||
**新增** `mcp/lock.go`、`mcp/audit.go`。
|
||
|
||
1. 设备锁:`map[string]*sync.Mutex` + `TryLock`,占用即 `-32003`,message 带占用工具名与
|
||
已持续时长(`since` 记录在持锁结构里)。
|
||
2. 全局信号量:`chan struct{}` 容量 `MaxConcurrency`,`TryAcquire` 失败 `-32003`。
|
||
3. 审计:每次 `tools/call` 一条 `log.Audit("mcp.tool.call", …)`,字段
|
||
`actor=mcp role=admin source=mcp tool device ok code ms args=<首词+长度> result=<体积摘要>`;
|
||
**不记命令全文**(进 debug 日志)。HTTP `r.Context()` 取消同样走 defer 释放锁。
|
||
|
||
**测试**:并发两个同设备调用 → 第二个 -32003;`close(cancel)` 后锁被释放;审计行字段齐全
|
||
(读临时审计文件断言)。
|
||
|
||
### M4a 终端会话(设计 §6.1-§6.3)
|
||
|
||
**新增** `mcp/session.go`(会话表 + 空闲回收)、`mcp/term.go`(环形缓冲 + 哨兵检测骨架)。
|
||
|
||
1. `mcp.Server` 实现 `hub.EventHandler` 全接口(`OnDeviceOnline/Offline/Update`、
|
||
`OnScreenFrame`、`OnResolutionChange`、`OnCursorChange`、`OnClipboardText`、
|
||
`OnTerminalReady/Data/Closed`),只有终端三个方法做事,其余空实现;
|
||
`cmd/main.go` 里 `deviceHub.Subscribe(mcpSrv)`,退出时 `hub.Unsubscribe` + `Close()`。
|
||
2. `OnTerminalData` 在 TCP 读循环上执行,**必须不阻塞**:只做"查会话 → 追加环形缓冲 →
|
||
剥 4 字节 `TRM1` 前缀 → 哨兵扫描 → `sync.Cond` 唤醒",任何长操作都不允许(设计 §6.3)。
|
||
非 MCP 会话的设备直接丢弃(零开销)。
|
||
3. 环形缓冲 256 KiB + `base/total/delivered` 绝对偏移;溢出丢最旧并累计 `droppedBytes`。
|
||
4. 会话表 key 用 `deviceID`;`session_id` 为 `"s-"+6hex`;对外只暴露 `session_id`。
|
||
|
||
**测试**:`hub.PublishTerminalData` 灌 1 MB → 缓冲不涨、`truncated` 语义正确;关闭后释放;
|
||
浏览器(另建一个订阅者 `OpenTerminalSession`)占用时 `OpenSession` 返回 busy。
|
||
|
||
### M4b `terminal_exec` 执行与轮询(设计 §6.4-§6.6)
|
||
|
||
1. 打开:`hub.OpenTerminalSession(deviceID)`;`ErrTerminalBusy` → `-32003`;等
|
||
`OnTerminalReady`(带超时 → `-32001`);非 PTY → `-32005`(M4c 收紧)。
|
||
2. 下发:行尾按 `isPTY`/平台(设计 §6.4 的表);`hub.SendToTerminal`。
|
||
3. 清洗三段**整体移植**:`StripEchoedInput` → `StripAnsi` → `StripSentinelText`
|
||
(对应 MFC `McpServer.cpp:3946-4040`),顺序不可换。Go 侧用表驱动单测锁住行为。
|
||
4. 等待与交付:`done`/`closed`/超时三分支;超时**不销毁会话**,`delivered` 游标支持
|
||
`terminal_exec` 不带 `command` 的轮询;`max_output_bytes` 按行截断(保留换行)并置
|
||
`truncated`(防止把 UTF-8/GBK 多字节字符切坏)。
|
||
5. 返回体:`{session_id, output, exit_code?, done, offset, truncated, is_pty, reused}`。
|
||
|
||
**单测**(表驱动,样例来自 MFC 实测)
|
||
`rem hello`、`cmd /c echo abc`、`type .env`、SPAM 循环、`ping -n 30` 超时后轮询、
|
||
`cmd /\c` 折行回显、退出码 0/1 与非 PTY 单行哨兵。
|
||
|
||
**集成**(假设备,§4.2):模拟 `TOKEN_TERMINAL_START` → 输出 → 哨兵,断言 `exit_code`。
|
||
|
||
### M4c 关闭、回收与老客户端(设计 §6.2、§6.7)
|
||
|
||
1. `terminal_close`:**幂等**(会话不存在也 200);只关 MCP 自己创建的会话(`hub.CloseTerminalSession`
|
||
只有在会话表里有该设备且 `hub.TerminalIsPTY` 一致时才调用,避免误关浏览器会话——实现上
|
||
以"会话表命中"为准)。
|
||
2. 在途命令被 `terminal_close` 撞上:对齐 C++ 的 `waiters` 教训(`McpServer.cpp:12611`)——
|
||
置 `closed` 唤醒等待者交付剩余缓冲,无等待者则立即擦会话并 `CloseTerminalSession`。
|
||
3. 空闲回收 ticker 30s 扫一次,`lastUsed > TermIdle` 关闭;`Close()` 关掉全部会话。
|
||
4. 非 PTY(`TOKEN_SHELL_START`)→ `terminal_exec` 直接 `-32005`,message 写明"该客户端版本
|
||
不支持 PTY 会话"。不支持 shell 的客户端不设能力门,超时文案带一句提示(设计 §6.7)。
|
||
|
||
**测试**:closing 幂等;关闭后立刻重开 <1s;空闲回收(把 `TermIdle` 调成 100ms);
|
||
在途关闭与无等待者两条分支(各一个用例)。
|
||
|
||
### M5 `get_screenshot`(设计 §7)
|
||
|
||
**新增** `mcp/screen.go`;`protocol/commands.go` 加 `CommandScreenPreviewReq=247`、
|
||
`TokenScreenPreviewRsp=248`;`cmd/main.go` `OnReceive` 加两个 case 转 `mcp.OnPacket`。
|
||
|
||
1. 请求表 `map[deviceID]*pendingPreview{reqID uint16; ch chan []byte}`,
|
||
`reqID` 用 `atomic.Uint32` 取低 16 位;**响应 reqID 不匹配直接丢弃**(对齐 MFC
|
||
`TakePreviewResponse`)。
|
||
2. 能力门:缺 `protocol.ClientCapScreenPreview` → `-32005`。
|
||
3. 8 字节请求体;`max_width` 钳制 `[64,1920]`、缺省/0 → 1024;`jpegQuality` 固定 80。
|
||
4. 响应:`status != 0` → 1/2 `-32000`、3 `-32005`、4 `-32602`;`format=0` 直接返回 JPEG,
|
||
`format=3`(BGRX)→ 先 `image.RGBA` 再 `jpeg.Encode`;`bytes != w*h*4` 视为畸形包 `-32000`。
|
||
5. 超时 8s,超时删表项,**不 CancelIO**(主连接 RPC,MFC 同款)。
|
||
6. 返回 `content[]` 一项 `image`(base64 JPEG)+ `structuredContent{width,height,bytes,format,source}`。
|
||
|
||
**测试**:JPEG 魔数(`FF D8 FF`)、BGRX→JPEG 像素抽样、reqID 错包被丢弃、status 映射、
|
||
超时。
|
||
|
||
### M6 `list_files`(设计 §5.3、§8.1)
|
||
|
||
**新增** `mcp/filemgr.go`;`protocol` 加 `CommandListDrive=1`、`CommandListFiles=2`、
|
||
`TokenDriveList=103`、`TokenFileList=104`、`TokenFileListError=171`(**加一个常量唯一性单测**:
|
||
新值不得与既有 `protocol` 常量重复,`103/104` 紧邻 `TOKEN_LOGIN=102`,值写错会吃主连接登录包)。
|
||
|
||
1. 主连接 `hub.SendToDevice(dev, []byte{CommandListDrive})`;等文件子连接:在
|
||
`OnReceive` 顶部(终端 short-circuit 之后)先喂 `mcp.OnPacket(ctx, data)`,`mcp` 按
|
||
`ctx.GetInfo().ClientID` 找到 pending 请求并**记住 ctx**(后续 `COMMAND_LIST_FILES` 要用它)。
|
||
2. `TOKEN_DRIVE_LIST` 到达后**不关子连接**,同一 ctx 下发 `[CommandListFiles][path\0]`;
|
||
`TOKEN_FILE_LIST` / `TOKEN_FILE_LIST_ERROR` 才收尾。
|
||
3. 解析按设计附录 A;`attr & 0x10` 判目录;文件名 `protocol.DecodeClientString(data, capability, "")`。
|
||
4. 错误映射:`win32err ∈ {2,3}` → `-32009`;`5` → `-32010`;其它 → `-32000`。
|
||
老客户端无 `TOKEN_FILE_LIST_ERROR` → 超时;message 提示"路径可能不存在,先列目录确认"。
|
||
5. 收尾:`COMMAND_BYE` → 500ms → `ctx.Close()`(`hub` 同款优雅关闭)。
|
||
|
||
**测试**:盘符/文件/错误三种黄金字节(照 MFC `ParseDriveList`/`ParseFileList` 的样例抓真实包,
|
||
存为 `testdata/*.bin`);`offset/limit` 语义;客户端中途断开 → `-32001` 且 pending 表被清。
|
||
|
||
### M7 `read_file`(设计 §5.4、§8.2-§8.3)
|
||
|
||
**新增** `mcp/filev2.go`;`protocol` 加 `CommandSendFileV2=85`、`CommandFileCompleteV2=91`、
|
||
`CmdDownFilesV2=94`;`cmd/main.go` 加两个 case。
|
||
|
||
1. 流程:列盘(复用 M6 的子连接)→ 同一子连接发 `[CmdDownFilesV2][targetDir\0][path\0][\0]`
|
||
→ 服务端关掉文件子连接 → 客户端建 V2 子连接(`ConnAuth` 已钉 `ClientID`)→
|
||
`COMMAND_SEND_FILE_V2 × N` → `COMMAND_FILE_COMPLETE_V2`。
|
||
2. `targetDir := os.MkdirTemp("", "yama-mcp-read-*")`,`defer os.RemoveAll`。
|
||
3. **大小门**:首个 chunk 的 `fileSize` 超 `ReadMax` → 立即中止、删目录、`-32602`
|
||
(不要先落盘再报错)。
|
||
4. **路径校验**(安全,必须单测):`filepath.Clean(filepath.Join(targetDir, FromSlash(name)))`
|
||
+ `filepath.Rel` 判越界;另拒 NUL / 换行;`name` 允许客户端回填为相对路径。
|
||
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`);
|
||
大小门;SHA 不符;GBK 文件;负 offset;`transferID` 不匹配的迟到 chunk 被丢弃。
|
||
|
||
### M8 校验工具与文档(设计 §10)
|
||
|
||
1. `verify_tools.py --subset <tools.json> [token] [port] [--readonly]`:
|
||
抓 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`;
|
||
设计文档状态改"已实施"。
|
||
|
||
---
|
||
|
||
## 4. 测试与验证
|
||
|
||
### 4.1 三档测试
|
||
|
||
| 档 | 跑什么 | 覆盖 | 何时跑 |
|
||
|---|---|---|---|
|
||
| 1 纯函数单测 | 清洗三段、哨兵、环形缓冲、解析器、路径校验、schema 校验、JSON-RPC | 全部逻辑分支 | 每次提交 |
|
||
| 2 假设备集成(进程内) | 真 `hub` + 假设备 ctx + `httptest` 的 `/mcp` | 九工具端到端、并发、取消、审计 | 每次提交 |
|
||
| 3 真客户端 smoke | `x64\Debug\ghost.exe`(§4.3)或 Linux ghost → 本机 Go 服务端 | 真实 PTY/文件/截屏链路 | 每个里程碑收尾 + 整体验收 |
|
||
|
||
档 2 是主力:不依赖网络、可在 CI 跑,且能精确控制入站包的字节。
|
||
|
||
### 4.2 假设备 harness(`mcp/harness_test.go`)
|
||
|
||
```go
|
||
h := hub.New()
|
||
sent := make(chan []byte, 16) // 出站包,带缓冲 channel 避免数据竞争
|
||
h.SetSender(func(ctx *connection.Context, data []byte) error {
|
||
sent <- append([]byte(nil), data...); return nil
|
||
})
|
||
cfg := logger.DefaultConfig(); cfg.Level = logger.LevelError
|
||
mcpSrv := mcp.New(mcpCfg, h, history, logger.New(cfg))
|
||
unsubscribe := h.Subscribe(mcpSrv) // Subscribe 返回退订闭包(hub 没有 Unsubscribe 方法)
|
||
ts := httptest.NewServer(http.HandlerFunc(mcpSrv.Handle))
|
||
// 假设备:拿到 sent 里的 COMMAND_SHELL 后,模拟回 TOKEN_TERMINAL_START 与输出:
|
||
mcpSrv.OnPacket(devCtx, append([]byte{protocol.TokenTerminalStart}, ...))
|
||
h.PublishTerminalData(devID, []byte("hello\r\n__MCP_DONE_ab12cd__0\r\n"))
|
||
```
|
||
|
||
要点:
|
||
- 造设备:`h.Register(&hub.Device{ID:"dev", PeerIP:"10.0.0.1"}, devCtx)`;
|
||
`devCtx` 的 `Info.ClientID` 按子连接需要设置(模拟 `handleConnAuth` 的钉值)。
|
||
- `sent` 用带缓冲 channel(上面写法),测试里 `select` 带超时地读,不 sleep。
|
||
- 收尾:`defer unsubscribe()` + `defer mcpSrv.Close()`;再断言没有残留会话
|
||
(`mcpSrv.SessionCount()==0`,为此在会话表上留一个只读访问器给测试用)。
|
||
|
||
### 4.3 真客户端 smoke(M0 已实测,2026-11-12)
|
||
|
||
**结论:Windows 真客户端用 `x64\Debug\ghost.exe`,`TestRun.exe` 不可用。**
|
||
|
||
- `test.cpp` 用 `MemoryDllRunner` 加载同目录的 `ServerDll.dll`(`client/test.cpp:448`);
|
||
没有它时静默每 3 秒重试,Go 侧也没有这条内存 DLL 链路。
|
||
- Release `TestRun.exe` 从非安装路径启动时 `RegisterStartup()` 返回 0 → `self_del()`
|
||
自删(`client/test.cpp:323-334`);M0 第一次尝试确实删掉了 `release\TestRun.exe`,
|
||
已用 Release 重建恢复(359936 → 425472 字节)。`-cmd=0` 绕不过安装流程。
|
||
- Release `ghost.exe` 同样会走安装流程(dst = `%ProgramData%\Windows Ghost\WinGhost.exe`),
|
||
因此本机测试统一用 Debug ghost:`RegisterStartup` 在 `_DEBUG` 下直接返回 1(`reg_startup.c:413`)。
|
||
|
||
**M0 实测记录**:
|
||
|
||
- 服务端 `Bin\YamaGo_x64.exe -port 16543 -http-port 18090`(18080 被 python/wslrelay 占用),
|
||
`YAMA_DEVICES_FILE` 指向临时文件;默认签名模式 **TRIAL**(`https://web.just-do-it.icu:8080`)。
|
||
- `x64\Debug\ghost.exe 127.0.0.1 16543` → 10 秒内设备上线:
|
||
`event=device.online computer=A6/default device_id=445427540237756328 os="Windows 11"`,
|
||
`devices.json` 写入 `first_seen/last_seen`,服务端无错误日志。
|
||
- 清理:Debug ghost 的 `SetSelfStart` 会在 `HKCU\...\Run` 写一条哈希名,按运行前快照删除新增项;
|
||
用户既有的 `Client Demo` 计划任务与 `C:\ProgramData\Client Demo\ClientDemo.exe` 未被改动。
|
||
- 待办:trial 签名下客户端是否解锁屏幕/文件能力,要在 M5/M6 端到端确认
|
||
(`YAMA_LICENSE_DISABLED=1` 的 NoOp 已知会被客户端拒绝)。
|
||
|
||
```powershell
|
||
cd C:\github\YAMA
|
||
.\build.ps1 -GoServer -Config Debug
|
||
$msb = "C:\Program Files\Microsoft Visual Studio\18\Insiders\MSBuild\Current\Bin\MSBuild.exe"
|
||
& $msb client\ghost_vs2015.vcxproj -p:Configuration=Debug -p:Platform=x64 -p:SolutionDir=C:/github/YAMA/ -m -v:m
|
||
$env:YAMA_MCP_TOKEN="<32hex>"; $env:YAMA_DEVICES_FILE="$env:TEMP\yama_m0\devices.json"
|
||
Start-Process .\Bin\YamaGo_x64.exe -ArgumentList '-port','16543','-http-port','18090'
|
||
Start-Process .\x64\Debug\ghost.exe -ArgumentList '127.0.0.1','16543'
|
||
curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $env:YAMA_MCP_TOKEN" ...
|
||
```
|
||
|
||
注意:Debug ghost 的 `Mprintf` 走 `TRACE`(`common/logger.h:379`),客户端侧没有日志文件,
|
||
验收以服务端 audit/日志为准。
|
||
|
||
### 4.4 与 MFC 的对照验收
|
||
|
||
同一批命令在两个后端各跑一遍,比对 `exit_code` 与清洗后的文本(不一致就是移植缺陷):
|
||
|
||
```
|
||
sc query AssemblyManager rem hello cmd /c echo abc
|
||
type C:\...\.env ping -n 30 127.0.0.1 for /L %i in (1,1,1000000) do @echo SPAM-%i
|
||
```
|
||
|
||
### 4.5 每个提交前必跑
|
||
|
||
```bash
|
||
cd server/go
|
||
gofmt -l . ; go vet ./... ; go test ./... ; go test -race ./mcp/...
|
||
go build ./cmd
|
||
```
|
||
|
||
MFC 侧测试(`%TEMP%\yama_step1_scripts\*`)本计划不改 C++ 代码,只在 M8 之后回归一次
|
||
`verify_live_6555.py` 确认没被共享常量改动影响(本计划只加常量,理论上无影响)。
|
||
|
||
---
|
||
|
||
## 5. 整体验收(对齐设计 §11)
|
||
|
||
- [ ] 9 个工具全部可调用;`tools/list` 响应 < 24 KB
|
||
- [ ] `terminal_exec` 连续 20 条命令零失败;超时后轮询取回完整输出
|
||
- [ ] 浏览器开着终端时 `terminal_exec` → `-32003`,人的会话不受影响
|
||
- [ ] `read_file` 读 `.env` 字节级一致,SHA-256 与远端 `sha256sum` 相同
|
||
- [ ] `get_screenshot` Windows / Linux 各一张,Linux 走 BGRX→JPEG
|
||
- [ ] 审计每次 `mcp.tool.call` 一条,`device/tool/code/ms` 齐全
|
||
- [ ] `verify_tools.py --subset` 通过(9 个 / 只读 7 个两种模式)
|
||
- [ ] `go test -race ./mcp/...` 无数据竞争
|
||
- [ ] `hub` 零改动(`git diff --stat server/go/hub` 为空)
|
||
|
||
---
|
||
|
||
## 6. 风险(在设计 R1-R8 之上新增)
|
||
|
||
| # | 风险 | 影响 | 处置 |
|
||
|---:|---|---|---|
|
||
| R9 | `OnTerminalData` 在 TCP 读循环上阻塞 | 整个设备通道卡死(浏览器画面/终端一起停) | 只做内存追加与唤醒;缓冲满丢最旧;禁止在回调里调用 `hub` 的会加锁方法 |
|
||
| R10 | 文件子连接 ctx 生命周期 | 客户端中途断开 → 后续发送到已关闭 ctx / pending 表泄漏 | pending 表带超时与 `OnDisconnect` 清理;发送失败即失败收尾 |
|
||
| R11 | `103/104` 常量与主连接 token 相邻 | 值写错会把登录包当文件列表(反之亦然) | 常量唯一性单测 + 解析前校验最小长度 |
|
||
| R12 | Windows 路径与 `filepath.Rel` | 路径穿越(被控端写主控任意位置) | 单测覆盖 `..`/绝对路径/UNC/混合分隔符;拒 NUL 与换行 |
|
||
| R13 | 客户端断开(`r.Context()`)后锁未释放 | 设备永久 `-32003` | `defer` 释放;单测用 cancel 验证 |
|
||
| R14 | 单测 goroutine 泄漏 | `-race` 偶发失败 | `Close()` 幂等;测试里 `defer Close()` |
|
||
| R15 | 真机 smoke 用 Debug ghost,与 Release 客户端有差异 | 安装/许可行为可能在 Release 上不同,本地验收未覆盖 | M0 已确认 Debug ghost 可上线;M5/M6 用 trial 签名验证屏幕/文件能力;交付说明写明该差异 |
|
||
|
||
---
|
||
|
||
## 7. 工时估算
|
||
|
||
| 里程碑 | 编码 | 测试 | 小计 |
|
||
|---|---:|---:|---:|
|
||
| M1 | 3h | 3h | 6h |
|
||
| M2 | 6h | 4h | 10h |
|
||
| M3 | 2h | 2h | 4h |
|
||
| M4a | 4h | 2h | 6h |
|
||
| M4b | 5h | 3h | 8h |
|
||
| M4c | 1h | 1h | 2h |
|
||
| M5 | 4h | 2h | 6h |
|
||
| M6 | 5h | 3h | 8h |
|
||
| M7 | 6h | 4h | 10h |
|
||
| M8 | 2h | 1h | 3h |
|
||
| 整体联调 + 真机验收 | — | — | 6h(含在 §5) |
|
||
| **合计** | **38h** | **25h** | **≈63h ≈ 8 人日** |
|
||
|
||
---
|
||
|
||
## 附录 A:`protocol/commands.go` 新增常量
|
||
|
||
| 常量 | 值 | 方向 | 里程碑 |
|
||
|---|---:|---|---|
|
||
| `CommandListDrive` | 1 | S→C 主连接 | M6 |
|
||
| `CommandListFiles` | 2 | S→C 文件子连接 | M6 |
|
||
| `CommandSendFileV2` | 85 | C→S V2 子连接 | M7 |
|
||
| `CommandFileCompleteV2` | 91 | C→S V2 子连接 | M7 |
|
||
| `CmdDownFilesV2` | 94 | S→C 文件子连接 | M7 |
|
||
| `TokenDriveList` | 103 | C→S 文件子连接 | M6 |
|
||
| `TokenFileList` | 104 | C→S 文件子连接 | M6 |
|
||
| `TokenFileListError` | 171 | C→S 文件子连接 | M6 |
|
||
| `CommandScreenPreviewReq` | 247 | S→C 主连接 | M5 |
|
||
| `TokenScreenPreviewRsp` | 248 | C→S 主连接 | M5 |
|
||
|
||
## 附录 B:环境变量
|
||
|
||
| 变量 | 默认 | 说明 | 引入里程碑 |
|
||
|---|---|---|---|
|
||
| `YAMA_MCP_TOKEN` | 空(端点不注册) | 32 位十六进制静态令牌 | M1 |
|
||
| `YAMA_MCP_READONLY` | 0 | 隐藏 `terminal_exec` / `terminal_close` | M1 |
|
||
| `YAMA_MCP_TERM_IDLE` | 180 | 终端会话空闲回收秒数 | M4c |
|
||
| `YAMA_MCP_MAX_CONCURRENCY` | 16 | 全局并发上限 | M3 |
|
||
| `YAMA_MCP_READ_MAX` | 2097152 | `read_file` 大小门(字节) | M7 |
|
||
|
||
## 附录 C:提交前自检清单(每个里程碑)
|
||
|
||
1. `gofmt -l .` 无输出;`go vet ./...` 干净。
|
||
2. `go test ./...` 与 `go test -race ./mcp/...` 全绿。
|
||
3. 新增的每个错误码都有触发它的单测(错误码不是装饰)。
|
||
4. 新增的每条审计事件都能在临时审计文件里被 `get_audit_log` 查到。
|
||
5. 提交标题用 `Feature(Go):` / `Fix(Go):`,正文说明"为什么",trailer 用当前会话模型名。
|
||
6. 未推送前发现问题用 `--amend`/squash,不堆补丁提交。
|