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`;
设计文档状态改"已实施"。
+32 -1
View File
@@ -22,6 +22,7 @@ import (
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/licensing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/mcp"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/server"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/web"
@@ -880,6 +881,16 @@ func envInt(name string, def int) int {
return n
}
// envBool parses a boolean env var; accepts 1/true/yes/on (case-insensitive)
// as true and everything else — including unset — as false.
func envBool(name string) bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv(name))) {
case "1", "true", "yes", "on":
return true
}
return false
}
// runIssueToken handles the "issue-token" subcommand. It mints a customer JWT
// signed with the operator's RSA private key and prints it to stdout.
//
@@ -1288,11 +1299,31 @@ func main() {
SSO: ssoDetector,
}
// MCP endpoint: a static bearer token independent of the web login. An
// empty YAMA_MCP_TOKEN leaves /mcp unregistered (404) — there is no
// auto-generated token, because a secret that only appears in a log is not
// a secret. Version wiring arrives with the buildinfo package; until then
// initialize reports "dev".
mcpReadonly := envBool("YAMA_MCP_READONLY")
mcpSrv := mcp.New(mcp.Config{
Token: strings.TrimSpace(os.Getenv("YAMA_MCP_TOKEN")),
Readonly: mcpReadonly,
TermIdle: time.Duration(envInt("YAMA_MCP_TERM_IDLE", 180)) * time.Second,
MaxConcurrency: envInt("YAMA_MCP_MAX_CONCURRENCY", 16),
ReadMax: int64(envInt("YAMA_MCP_READ_MAX", 2<<20)),
StartedAt: time.Now(),
Log: log.WithPrefix("MCP"),
})
if mcpSrv.Enabled() {
log.Info("MCP endpoint enabled on /mcp (readonly=%v)", mcpReadonly)
}
// Start HTTP server for web UI. Hub gives it read-only access to the
// device registry; the authenticator owns user accounts and session tokens.
httpSrv := web.New(*httpPort, log.WithPrefix("Web"), deviceHub, webAuth).
WithDeviceHistory(deviceHistory).
WithConfig(webCfg)
WithConfig(webCfg).
WithMCP(mcpSrv)
if err := httpSrv.Start(); err != nil {
log.Fatal("Failed to start HTTP server: %v", err)
}
+41
View File
@@ -0,0 +1,41 @@
package mcp
import "fmt"
// JSON-RPC 2.0 error codes used by the MCP endpoint. The -320xx range mirrors
// the Win32 server (McpServer.cpp:296-312) so a model sees the same numbers
// regardless of which backend it talks to; reusing them matters more than
// inventing Go-specific ones.
const (
CodeInternal = -32000 // unexpected server-side failure
CodeTimeout = -32001 // sub-connection or device reply did not arrive
CodeOffline = -32002 // host unknown or offline
CodeBusy = -32003 // per-device lock / terminal slot occupied
CodeSendFailed = -32004 // command could not be delivered to the host
CodeUnsupported = -32005 // host lacks the required capability
CodeDenied = -32006 // policy refusal (readonly mode, disabled tool)
CodeNotFound = -32009 // target file/directory does not exist
CodePermission = -32010 // target rejected the operation (access denied)
CodeParseError = -32700 // invalid JSON
CodeInvalidRequest = -32600 // not a valid JSON-RPC request
CodeMethodNotFound = -32601 // unknown method or tool name
CodeInvalidParams = -32602 // schema/argument validation failed
)
// rpcError is the JSON-RPC "error" object. It is returned as a Go error from
// tool handlers, which lets call sites use plain returns instead of carrying
// a response object through every layer.
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
Data any `json:"data,omitempty"`
}
func (e *rpcError) Error() string {
return fmt.Sprintf("mcp error %d: %s", e.Code, e.Message)
}
// errf builds an rpcError with a formatted message.
func errf(code int, format string, args ...any) *rpcError {
return &rpcError{Code: code, Message: fmt.Sprintf(format, args...)}
}
+48
View File
@@ -0,0 +1,48 @@
package mcp
import "encoding/json"
// request is one JSON-RPC 2.0 call. The MCP endpoint is stateless, so there is
// nothing else to track between requests.
type request struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
// isNotification reports whether the caller omitted "id". Such requests get
// no JSON-RPC response at all (MCP uses them for notifications/initialized).
func (r *request) isNotification() bool { return len(r.ID) == 0 }
// response is a single JSON-RPC 2.0 reply. Exactly one of Result/Error is set.
type response struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result any `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
// idOrNull keeps the reply valid when the request id is missing or malformed:
// JSON-RPC allows "id": null on errors that cannot be correlated.
func idOrNull(id json.RawMessage) json.RawMessage {
if len(id) == 0 {
return json.RawMessage("null")
}
return id
}
func resultResponse(id json.RawMessage, result any) *response {
return &response{JSONRPC: "2.0", ID: idOrNull(id), Result: result}
}
func errorResponse(id json.RawMessage, err *rpcError) *response {
return &response{JSONRPC: "2.0", ID: idOrNull(id), Error: err}
}
// toolCallParams is the tools/call payload. Arguments stay raw so each tool
// decodes only the fields it understands (and reports -32602 itself).
type toolCallParams struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
+289
View File
@@ -0,0 +1,289 @@
package mcp
import (
"bytes"
"context"
"crypto/subtle"
"encoding/json"
"errors"
"io"
"net/http"
"strings"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
)
const (
// protocolVersion is the MCP revision this endpoint speaks. It matches the
// Win32 server and mcp/tools.json.
protocolVersion = "2025-06-18"
// maxBodyBytes bounds a single JSON-RPC request. tools/call arguments can
// carry a file payload for uploads, so 8 MiB is generous but finite.
maxBodyBytes = 8 << 20
defaultTermIdle = 180 * time.Second
defaultMaxConcurrency = 16
defaultReadMax = 2 << 20
)
// Config is filled by cmd/main.go from the YAMA_MCP_* environment variables;
// the package itself never reads the environment, so tests are deterministic.
type Config struct {
Token string // static bearer token; empty disables the endpoint
Readonly bool // hide (and refuse) write tools
TermIdle time.Duration // terminal session idle reaping
MaxConcurrency int // global in-flight tools/call cap
ReadMax int64 // read_file whole-file limit
Version string // serverInfo.version
StartedAt time.Time // reported by get_server_status
Log *logger.Logger
}
// toolFunc implements one tools/call. It returns either a result value or a
// JSON-RPC error; the caller wraps whichever it gets.
type toolFunc func(ctx context.Context, args json.RawMessage) (any, *rpcError)
// Server is the stateless MCP endpoint. It owns the embedded tool definitions
// and the tool handler table; per-device sessions arrive in later milestones.
type Server struct {
cfg Config
log *logger.Logger
tools *toolSet
handlers map[string]toolFunc
}
// New builds the endpoint. Zero-valued knobs fall back to the documented
// defaults so a partially-filled Config from cmd is still safe.
func New(cfg Config) *Server {
if cfg.TermIdle <= 0 {
cfg.TermIdle = defaultTermIdle
}
if cfg.MaxConcurrency <= 0 {
cfg.MaxConcurrency = defaultMaxConcurrency
}
if cfg.ReadMax <= 0 {
cfg.ReadMax = defaultReadMax
}
if cfg.StartedAt.IsZero() {
cfg.StartedAt = time.Now()
}
if cfg.Version == "" {
cfg.Version = "dev"
}
if cfg.Log == nil {
cfg.Log = logger.New(logger.Config{Level: logger.LevelError})
}
return &Server{
cfg: cfg,
log: cfg.Log,
tools: buildToolSet(toolsJSON),
handlers: make(map[string]toolFunc),
}
}
// Enabled reports whether /mcp should be registered. An empty token disables
// the endpoint entirely: the route is not mounted, so it 404s like any other
// unknown path.
func (s *Server) Enabled() bool { return s != nil && s.cfg.Token != "" }
// Close releases resources held by long-lived tool state. M1 has none; the
// terminal session table plugs in here in M4.
func (s *Server) Close() {}
// Handle serves POST /mcp. Transport-level failures (405/401/413) are answered
// here; everything after a successfully parsed JSON-RPC request returns HTTP
// 200 and carries the error in the JSON-RPC body.
func (s *Server) Handle(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
w.Header().Set("Allow", http.MethodPost)
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if !s.authorized(r) {
// The MCP transport spec expects a transport-level failure here, not a
// JSON-RPC error object, so the client can distinguish "bad credential"
// from "server rejected the call".
w.Header().Set("WWW-Authenticate", `Bearer realm="mcp"`)
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
body, err := io.ReadAll(http.MaxBytesReader(w, r.Body, maxBodyBytes))
if err != nil {
var tooLarge *http.MaxBytesError
if errors.As(err, &tooLarge) {
http.Error(w, "request body too large", http.StatusRequestEntityTooLarge)
return
}
http.Error(w, "failed to read request body", http.StatusBadRequest)
return
}
s.serveRPC(w, r, body)
}
// serveRPC parses and dispatches one JSON-RPC request, writing the response.
func (s *Server) serveRPC(w http.ResponseWriter, r *http.Request, body []byte) {
body = bytes.TrimSpace(body)
if len(body) == 0 {
writeRPC(w, errorResponse(nil, errf(CodeParseError, "Parse error")))
return
}
// Batch arrays are rejected rather than processed: gating, auditing and
// locking assume one call at a time (design §4.1).
if body[0] == '[' {
writeRPC(w, errorResponse(nil, errf(CodeInvalidRequest, "batch requests are not supported")))
return
}
var req request
if err := json.Unmarshal(body, &req); err != nil {
writeRPC(w, errorResponse(nil, errf(CodeParseError, "Parse error")))
return
}
if req.Method == "" {
writeRPC(w, errorResponse(req.ID, errf(CodeInvalidRequest, "Invalid Request")))
return
}
// Notifications (notifications/initialized, notifications/cancelled, …)
// get no body. The MCP spec allows 202; we use 204 so there is nothing to
// mistake for a result.
if req.isNotification() {
w.WriteHeader(http.StatusNoContent)
return
}
result, rerr := s.dispatch(r.Context(), &req)
if rerr != nil {
writeRPC(w, errorResponse(req.ID, rerr))
return
}
writeRPC(w, resultResponse(req.ID, result))
}
// dispatch routes one method. Unknown methods are -32601; the MCP client is
// expected to treat that as "this server does not support the feature".
func (s *Server) dispatch(ctx context.Context, req *request) (any, *rpcError) {
switch req.Method {
case "initialize":
return s.initializeResult(), nil
case "ping":
return struct{}{}, nil
case "tools/list":
return toolsListResult{Tools: s.tools.visible(s.cfg.Readonly)}, nil
case "tools/call":
return s.callTool(ctx, req.Params)
default:
return nil, errf(CodeMethodNotFound, "Method not found: %s", req.Method)
}
}
type serverInfo struct {
Name string `json:"name"`
Version string `json:"version"`
}
type toolsCapability struct {
ListChanged bool `json:"listChanged"`
}
type serverCapabilities struct {
Tools toolsCapability `json:"tools"`
}
type initializeResult struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities serverCapabilities `json:"capabilities"`
ServerInfo serverInfo `json:"serverInfo"`
Instructions string `json:"instructions"`
}
// initializeResult mirrors the Win32 server: same protocol version, same
// serverInfo.name ("yama") so clients do not special-case the Go backend.
// Differences are stated in instructions, which models read.
func (s *Server) initializeResult() initializeResult {
return initializeResult{
ProtocolVersion: protocolVersion,
Capabilities: serverCapabilities{Tools: toolsCapability{ListChanged: false}},
ServerInfo: serverInfo{Name: "yama", Version: s.cfg.Version},
Instructions: serverInstructions,
}
}
// callTool parses tools/call, enforces visibility, and hands the raw
// arguments to the handler. Readonly mode refuses hidden write tools with
// -32006 rather than pretending they do not exist.
func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (any, *rpcError) {
if len(raw) == 0 || string(raw) == "null" {
return nil, errf(CodeInvalidParams, "tools/call requires params")
}
var params toolCallParams
if err := json.Unmarshal(raw, &params); err != nil {
return nil, errf(CodeInvalidParams, "invalid params: %v", err)
}
if params.Name == "" {
return nil, errf(CodeInvalidParams, "tool name is required")
}
if !s.tools.known(params.Name) {
return nil, errf(CodeMethodNotFound, "unknown tool: %s", params.Name)
}
if s.cfg.Readonly && writeTools[params.Name] {
return nil, errf(CodeDenied, "tool %s is disabled in readonly mode", params.Name)
}
handler, ok := s.handlers[params.Name]
if !ok {
// The tool is listed but this build does not implement it yet. This is
// a temporary state between milestones, not a client mistake.
return nil, errf(CodeInternal, "tool %s is not implemented by this server build", params.Name)
}
return handler(ctx, params.Arguments)
}
// authorized compares the bearer token without leaking its length or content
// through timing. A missing or different-length header fails immediately, but
// no branch reveals how much of the token matched.
func (s *Server) authorized(r *http.Request) bool {
const prefix = "Bearer "
// An empty configured token would otherwise match an empty credential;
// the route is not mounted in that case, but keep the check safe anyway.
if s.cfg.Token == "" {
return false
}
header := r.Header.Get("Authorization")
if !strings.HasPrefix(header, prefix) {
return false
}
got := header[len(prefix):]
if len(got) != len(s.cfg.Token) {
return false
}
return subtle.ConstantTimeCompare([]byte(got), []byte(s.cfg.Token)) == 1
}
// writeRPC writes a single JSON-RPC response. Marshal failures are impossible
// for the value types used here, but are reported rather than dropping the
// connection silently.
func writeRPC(w http.ResponseWriter, resp *response) {
body, err := json.Marshal(resp)
if err != nil {
http.Error(w, "failed to encode response", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(body)
}
// serverInstructions is the Go backend's initialization guide. The Win32 MCP
// server ships a much larger text covering its 54 tools; this one describes
// only what the minimal Go server exposes and where it behaves differently.
const serverInstructions = `这是 YAMA 服务端的 MCP 端点(Go 实现)。工具集比 Windows 主控端小,以下规则优先于各工具的描述。
1) 主机 id 是 64 位无符号十进制字符串,由服务端分配,无法从 IP 或计算机名推算。需要 id 时先用 list_hosts 取得,拿不到就向用户确认,不要猜。
2) tools/list 只返回当前模式允许的工具;只读模式隐藏 terminal_exec / terminal_close,直接调用被隐藏的工具返回 -32006。
3) 错误码与动作:-32002 主机离线或不存在(先刷新列表);-32003 主机忙(同一台主机同一时刻只允许一个操作,重试无效,等前一个结束);-32004 命令未送达(多为链路瞬断,可重试一次);-32005 主机不支持该能力(换主机或换工具,改参数无用);-32006 策略拒绝(重试无效,需管理员改服务端配置);-32001 超时(可加大 timeout_ms 重试一次);-32602 参数错误(按 message 修正)。
4) get_screenshot 的 screen 模式按链路状况自适应缩放,max_width 省略时最大 1024;region/window/monitor 模式需要声明 CLIENT_CAP_SCREEN_REGION 的较新 Windows 客户端,否则返回 -32005。
5) list_files / read_file 走文件传输通道;read_file 只接受单个普通文件且不超过 2 MiB,目录用 list_files,大文件分段读取。
6) terminal_exec 需要客户端支持终端(CLIENT_CAP_TERMINAL),会在目标主机上创建持久会话;用完调用 terminal_close 释放,闲置会话由服务端回收。
7) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。`
+393
View File
@@ -0,0 +1,393 @@
package mcp
import (
"encoding/json"
"net/http"
"net/http/httptest"
"path/filepath"
"reflect"
"strings"
"testing"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/logger"
)
const testToken = "0123456789abcdef0123456789abcdef"
func testServer(t *testing.T, readonly bool) *Server {
t.Helper()
log := logger.New(logger.Config{
Level: logger.LevelError,
File: filepath.Join(t.TempDir(), "mcp-test.log"),
})
return New(Config{
Token: testToken,
Readonly: readonly,
Version: "test-1.0",
Log: log,
})
}
// rpcEnvelope decodes a JSON-RPC response without committing to a result type.
type rpcEnvelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result json.RawMessage `json:"result"`
Error *rpcError `json:"error"`
}
func call(t *testing.T, s *Server, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
s.Handle(rec, req)
return rec
}
func authedCall(t *testing.T, s *Server, body string) *httptest.ResponseRecorder {
t.Helper()
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+testToken)
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
s.Handle(rec, req)
return rec
}
func decodeEnvelope(t *testing.T, rec *httptest.ResponseRecorder) rpcEnvelope {
t.Helper()
var env rpcEnvelope
if err := json.Unmarshal(rec.Body.Bytes(), &env); err != nil {
t.Fatalf("response is not JSON: %v\nbody: %s", err, rec.Body.String())
}
return env
}
func TestEnabledRequiresToken(t *testing.T) {
if New(Config{}).Enabled() {
t.Fatal("endpoint without a token must report disabled")
}
if !testServer(t, false).Enabled() {
t.Fatal("endpoint with a token must report enabled")
}
}
func TestAuth(t *testing.T) {
s := testServer(t, false)
body := `{"jsonrpc":"2.0","id":1,"method":"ping"}`
t.Run("missing", func(t *testing.T) {
rec := call(t, s, body)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", rec.Code)
}
if got := rec.Header().Get("WWW-Authenticate"); !strings.Contains(got, "Bearer") {
t.Fatalf("WWW-Authenticate = %q, want a Bearer challenge", got)
}
if strings.Contains(rec.Body.String(), "jsonrpc") {
t.Fatalf("401 must not carry a JSON-RPC body: %s", rec.Body.String())
}
})
t.Run("wrong same length", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+strings.Repeat("f", len(testToken)))
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", rec.Code)
}
})
t.Run("wrong different length", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Authorization", "Bearer "+testToken+"x")
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", rec.Code)
}
})
t.Run("missing scheme", func(t *testing.T) {
req := httptest.NewRequest(http.MethodPost, "/mcp", strings.NewReader(body))
req.Header.Set("Authorization", testToken)
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", rec.Code)
}
})
t.Run("correct", func(t *testing.T) {
rec := authedCall(t, s, body)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200 (body: %s)", rec.Code, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
t.Fatalf("Content-Type = %q, want application/json", ct)
}
})
}
func TestInitialize(t *testing.T) {
s := testServer(t, false)
rec := authedCall(t, s, `{"jsonrpc":"2.0","id":7,"method":"initialize"}`)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d, want 200", rec.Code)
}
env := decodeEnvelope(t, rec)
if env.Error != nil {
t.Fatalf("unexpected error: %+v", env.Error)
}
if string(env.ID) != "7" {
t.Fatalf("id = %s, want 7", env.ID)
}
var result struct {
ProtocolVersion string `json:"protocolVersion"`
Capabilities struct {
Tools struct {
ListChanged bool `json:"listChanged"`
} `json:"tools"`
} `json:"capabilities"`
ServerInfo struct {
Name string `json:"name"`
Version string `json:"version"`
} `json:"serverInfo"`
Instructions string `json:"instructions"`
}
if err := json.Unmarshal(env.Result, &result); err != nil {
t.Fatalf("decode result: %v", err)
}
if result.ProtocolVersion != protocolVersion {
t.Fatalf("protocolVersion = %q, want %q", result.ProtocolVersion, protocolVersion)
}
if result.Capabilities.Tools.ListChanged {
t.Fatal("tools.listChanged must be false: the list is static")
}
if result.ServerInfo.Name != "yama" {
t.Fatalf("serverInfo.name = %q, want yama", result.ServerInfo.Name)
}
if result.ServerInfo.Version != "test-1.0" {
t.Fatalf("serverInfo.version = %q, want test-1.0", result.ServerInfo.Version)
}
if strings.TrimSpace(result.Instructions) == "" {
t.Fatal("instructions must not be empty")
}
}
func TestPing(t *testing.T) {
s := testServer(t, false)
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":"abc","method":"ping"}`))
if env.Error != nil {
t.Fatalf("unexpected error: %+v", env.Error)
}
if string(env.ID) != `"abc"` {
t.Fatalf("id = %s, want \"abc\" (string ids echo unchanged)", env.ID)
}
var result map[string]any
if err := json.Unmarshal(env.Result, &result); err != nil {
t.Fatalf("decode result: %v", err)
}
if len(result) != 0 {
t.Fatalf("ping result = %v, want empty object", result)
}
}
func listTools(t *testing.T, s *Server) []json.RawMessage {
t.Helper()
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":1,"method":"tools/list"}`))
if env.Error != nil {
t.Fatalf("tools/list error: %+v", env.Error)
}
var result struct {
Tools []json.RawMessage `json:"tools"`
}
if err := json.Unmarshal(env.Result, &result); err != nil {
t.Fatalf("decode result: %v", err)
}
return result.Tools
}
// TestToolsListMatchesEmbedded pins the published definitions to the embedded
// file: same order, same content, no annotations. tools_minimal.json in turn is
// checked against mcp/tools.json by gen_go_tools.py --check.
func TestToolsListMatchesEmbedded(t *testing.T) {
var want []any
if err := json.Unmarshal(toolsJSON, &want); err != nil {
t.Fatalf("embedded tools: %v", err)
}
for _, readonly := range []bool{false, true} {
got := listTools(t, testServer(t, readonly))
if readonly {
if len(got) != 7 {
t.Fatalf("readonly tools = %d, want 7", len(got))
}
} else if len(got) != len(want) {
t.Fatalf("tools = %d, want %d", len(got), len(want))
}
wantIdx := 0
for _, raw := range got {
var tool map[string]any
if err := json.Unmarshal(raw, &tool); err != nil {
t.Fatalf("tool is not an object: %v", err)
}
name, _ := tool["name"].(string)
if _, ok := tool["annotations"]; ok {
t.Fatalf("tool %s must not carry annotations (MFC compatibility)", name)
}
if readonly && (name == "terminal_exec" || name == "terminal_close") {
t.Fatalf("readonly mode must hide %s", name)
}
// Skip over tools the filter removed, keeping the order check.
for wantIdx < len(want) && want[wantIdx].(map[string]any)["name"] != name {
wantIdx++
}
if wantIdx == len(want) {
t.Fatalf("tool %s is not in tools_minimal.json in this order", name)
}
if !reflect.DeepEqual(tool, want[wantIdx]) {
t.Fatalf("tool %s differs from tools_minimal.json", name)
}
wantIdx++
}
if wantIdx != len(want) {
t.Fatalf("filtered list stopped at %d of %d embedded tools", wantIdx, len(want))
}
}
}
func TestNotification(t *testing.T) {
s := testServer(t, false)
rec := authedCall(t, s, `{"jsonrpc":"2.0","method":"notifications/initialized"}`)
if rec.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204", rec.Code)
}
if rec.Body.Len() != 0 {
t.Fatalf("notification response body = %q, want empty", rec.Body.String())
}
}
func TestUnknownMethod(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, testServer(t, false),
`{"jsonrpc":"2.0","id":1,"method":"does/not/exist"}`))
if env.Error == nil || env.Error.Code != CodeMethodNotFound {
t.Fatalf("error = %+v, want code %d", env.Error, CodeMethodNotFound)
}
}
func TestTransportErrors(t *testing.T) {
s := testServer(t, false)
t.Run("get", func(t *testing.T) {
req := httptest.NewRequest(http.MethodGet, "/mcp", nil)
req.Header.Set("Authorization", "Bearer "+testToken)
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusMethodNotAllowed {
t.Fatalf("status = %d, want 405", rec.Code)
}
if got := rec.Header().Get("Allow"); got != http.MethodPost {
t.Fatalf("Allow = %q, want POST", got)
}
})
t.Run("delete", func(t *testing.T) {
req := httptest.NewRequest(http.MethodDelete, "/mcp", nil)
req.Header.Set("Authorization", "Bearer "+testToken)
rec := httptest.NewRecorder()
s.Handle(rec, req)
if rec.Code != http.StatusMethodNotAllowed {
t.Fatalf("status = %d, want 405", rec.Code)
}
})
t.Run("batch", func(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, s,
`[{"jsonrpc":"2.0","id":1,"method":"ping"},{"jsonrpc":"2.0","id":2,"method":"ping"}]`))
if env.Error == nil || env.Error.Code != CodeInvalidRequest {
t.Fatalf("error = %+v, want code %d", env.Error, CodeInvalidRequest)
}
if string(env.ID) != "null" {
t.Fatalf("id = %s, want null", env.ID)
}
})
t.Run("oversize", func(t *testing.T) {
body := `{"jsonrpc":"2.0","id":1,"method":"ping","params":"` +
strings.Repeat("x", maxBodyBytes) + `"}`
rec := authedCall(t, s, body)
if rec.Code != http.StatusRequestEntityTooLarge {
t.Fatalf("status = %d, want 413", rec.Code)
}
})
t.Run("parse error", func(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":`))
if env.Error == nil || env.Error.Code != CodeParseError {
t.Fatalf("error = %+v, want code %d", env.Error, CodeParseError)
}
})
t.Run("missing method", func(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, s, `{"jsonrpc":"2.0","id":1}`))
if env.Error == nil || env.Error.Code != CodeInvalidRequest {
t.Fatalf("error = %+v, want code %d", env.Error, CodeInvalidRequest)
}
})
}
func TestToolsCallGates(t *testing.T) {
s := testServer(t, false)
readonly := testServer(t, true)
cases := []struct {
name string
srv *Server
body string
code int
}{
{
name: "unknown tool",
srv: s,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"nope"}}`,
code: CodeMethodNotFound,
},
{
name: "missing name",
srv: s,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{}}`,
code: CodeInvalidParams,
},
{
name: "missing params",
srv: s,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call"}`,
code: CodeInvalidParams,
},
{
name: "known but not implemented in M1",
srv: s,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"list_hosts"}}`,
code: CodeInternal,
},
{
name: "readonly refuses write tool",
srv: readonly,
body: `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"terminal_exec"}}`,
code: CodeDenied,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
env := decodeEnvelope(t, authedCall(t, tc.srv, tc.body))
if env.Error == nil || env.Error.Code != tc.code {
t.Fatalf("error = %+v, want code %d", env.Error, tc.code)
}
})
}
}
+80
View File
@@ -0,0 +1,80 @@
package mcp
import (
_ "embed"
"encoding/json"
)
// tools_minimal.json is generated from mcp/tools.json by
// tools/mcp_tools/gen_go_tools.py — never edit it by hand. It is embedded so
// tools/list is a compile-time constant: no disk I/O, no drift between the
// schema the model sees and the schema the handlers were written against.
//
//go:embed tools_minimal.json
var toolsJSON []byte
// writeTools are hidden from tools/list in readonly mode and rejected with
// -32006 if called anyway (design §3.1: readonly exposes 7 of 9 tools).
var writeTools = map[string]bool{
"terminal_exec": true,
"terminal_close": true,
}
// toolDef holds one published definition plus its name, so filtering does not
// re-parse the JSON on every tools/list call.
type toolDef struct {
name string
raw json.RawMessage
}
type toolSet struct {
defs []toolDef
names map[string]bool
}
// buildToolSet validates the embedded payload once at startup. A malformed
// file is a build defect, so panic loudly rather than serve a broken list.
func buildToolSet(raw []byte) *toolSet {
var raws []json.RawMessage
if err := json.Unmarshal(raw, &raws); err != nil {
panic("mcp: embedded tools_minimal.json is not a JSON array: " + err.Error())
}
ts := &toolSet{defs: make([]toolDef, 0, len(raws)), names: make(map[string]bool, len(raws))}
for _, r := range raws {
var head struct {
Name string `json:"name"`
}
if err := json.Unmarshal(r, &head); err != nil || head.Name == "" {
panic("mcp: embedded tool definition without a name")
}
if ts.names[head.Name] {
panic("mcp: duplicate embedded tool " + head.Name)
}
ts.names[head.Name] = true
ts.defs = append(ts.defs, toolDef{name: head.Name, raw: r})
}
return ts
}
// visible returns the tool definitions to publish, preserving tools.json
// order. The raw bytes are passed through untouched, so descriptions and
// schemas stay exactly what mcp/tools.json says (no annotations, like MFC).
func (ts *toolSet) visible(readonly bool) []json.RawMessage {
out := make([]json.RawMessage, 0, len(ts.defs))
for _, def := range ts.defs {
if readonly && writeTools[def.name] {
continue
}
out = append(out, def.raw)
}
return out
}
// known reports whether name is a tool this server defines, including tools
// hidden by readonly mode. Unknown names are -32601; hidden ones are -32006.
func (ts *toolSet) known(name string) bool { return ts.names[name] }
// toolsListResult is the MCP tools/list payload.
type toolsListResult struct {
Tools []json.RawMessage `json:"tools"`
}
+922
View File
@@ -0,0 +1,922 @@
[
{
"name": "list_hosts",
"description": "列主机:默认只返回在线主机(含计算机名、IP、操作系统、版本、备注、分组、活动窗口、延迟等实时信息),include_offline=true 时连离线主机(历史连接过、当前未连接,来自主机列表记录)一起返回,在线主机排在最前面。query 子串匹配计算机名/备注/IP;group / os / client_type 为附加过滤条件(均可选、AND 组合、子串匹配、ASCII 不区分大小写);online=false 只看离线主机。过滤在分页之前生效:total 为命中台数,totalAll 为过滤前的主机库台数。结果按 limit/offset 分页(默认 100 条,上限 1000),hasMore 表示还有下一页。离线主机另有 last_seen(最后一次登录时间)、install_time 字段,但没有 rtt/version/activeWindow 等实时字段,也没有 clientType(按平台筛历史主机请用 os),group 恒为 default。authStatus 为主机授权状态(unauthorized/authorized_by_super/authorized_by_admin/forbidden)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。",
"inputSchema": {
"properties": {
"client_type": {
"description": "按客户端类型过滤(子串,不区分大小写,如 EXE、LNX、MAC)。离线主机没有该字段,不会命中。省略则不过滤。",
"type": "string"
},
"group": {
"description": "按分组过滤(子串,不区分大小写)。省略则不过滤。",
"type": "string"
},
"include_offline": {
"description": "是否把离线主机一起返回,默认 false(只给在线);online=false 时无意义。list_all_hosts 别名默认 true。",
"type": "boolean"
},
"ip": {
"description": "只按 IP 过滤(search_hosts 的旧参数);与 query 同时给出时两者都需满足。",
"type": "string"
},
"limit": {
"description": "本次最多返回的条数,默认 100,上限 1000。",
"type": "integer"
},
"name": {
"description": "只按计算机名/备注过滤(search_hosts 的旧参数);与 query 同时给出时两者都需满足。",
"type": "string"
},
"offset": {
"description": "跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。",
"type": "integer"
},
"online": {
"description": "true(默认)返回在线主机;false 只返回离线主机(历史连接过、当前未连接)。",
"type": "boolean"
},
"os": {
"description": "按操作系统过滤(子串,不区分大小写,如 Windows、Linux、Android)。省略则不过滤。",
"type": "string"
},
"query": {
"description": "关键字:子串匹配计算机名、备注或 IP(ASCII 不区分大小写)。省略则不过滤。",
"type": "string"
}
},
"type": "object"
},
"outputSchema": {
"properties": {
"hasMore": {
"type": "boolean"
},
"hosts": {
"items": {
"properties": {
"activeWindow": {
"type": "string"
},
"authStatus": {
"type": "string"
},
"clientType": {
"type": "string"
},
"group": {
"type": "string"
},
"id": {
"type": "string"
},
"install_time": {
"type": "string"
},
"ip": {
"type": "string"
},
"last_seen": {
"type": "string"
},
"location": {
"type": "string"
},
"name": {
"type": "string"
},
"online": {
"type": "boolean"
},
"os": {
"type": "string"
},
"remark": {
"type": "string"
},
"rtt": {
"type": "string"
},
"screen": {
"type": "string"
},
"tls": {
"type": "boolean"
},
"version": {
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"total": {
"type": "integer"
},
"totalAll": {
"type": "integer"
}
},
"required": [
"hosts"
],
"type": "object"
}
},
{
"name": "get_host_detail",
"description": "获取单台在线主机的详细信息(id、计算机名、IP、操作系统、备注、分组、活动窗口、屏幕分辨率、客户端类型等)。tls=true 表示该客户端登录时使用了 TLS 加密传输(登录时上报,老客户端恒为 false)。",
"inputSchema": {
"anyOf": [
{
"required": [
"id"
]
},
{
"required": [
"ids"
]
}
],
"properties": {
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段;与 ids 二选一",
"type": "string"
},
"ids": {
"description": "批量查询:一次传多台主机 id(最多 50 个),结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;limit/offset 对每台主机各自生效。",
"items": {
"type": "string"
},
"type": "array"
}
},
"type": "object"
},
"outputSchema": {
"anyOf": [
{
"properties": {
"host": {
"properties": {
"activeWindow": {
"type": "string"
},
"authStatus": {
"type": "string"
},
"capabilities": {
"properties": {
"c2cPaths": {
"description": "能否按路径清单接收另一台主机的文件(copy_files_c2c 源端的前提)",
"type": "boolean"
},
"fileTransferV2": {
"description": "是否支持 V2 文件传输(download_file / upload_file 的前提)",
"type": "boolean"
},
"platform": {
"description": "客户端形态:EXE/DLL/MEXE/SC/MDLL(Windows)、LNX(Linux)、MAC、APK",
"type": "string"
},
"registry": {
"description": "是否有 Windows 注册表可查(list_registry);仅 Windows 客户端为 true",
"type": "boolean"
},
"remoteControl": {
"description": "能否建立远程控制会话(remote_open/remote_mouse/remote_keyboard 的前提);Android 客户端只支持整屏目标,且需要已授权录屏与无障碍服务;还要求服务端 Web 远程服务已启动(WebSvrPort>0)",
"type": "boolean"
},
"screenPreview": {
"description": "能否截屏(get_screenshot 的前提)",
"type": "boolean"
},
"screenRegion": {
"description": "能否按区域/窗口/显示器原生分辨率截屏(get_screenshot 的 mode=region/window/monitor 前提);仅声明 CLIENT_CAP_SCREEN_REGION 的新 Windows 客户端为 true",
"type": "boolean"
},
"windowInfo": {
"description": "是否支持窗口信息(get_foreground_window、host_inspect 的 windows 项坐标/前后台字段、operate_window/host_control_window 的 activate);仅声明 CLIENT_CAP_WINDOW_INFO 的新客户端为 true",
"type": "boolean"
}
},
"type": "object"
},
"clientType": {
"type": "string"
},
"group": {
"type": "string"
},
"id": {
"type": "string"
},
"install_time": {
"type": "string"
},
"ip": {
"type": "string"
},
"last_seen": {
"type": "string"
},
"location": {
"type": "string"
},
"name": {
"type": "string"
},
"online": {
"type": "boolean"
},
"os": {
"type": "string"
},
"remark": {
"type": "string"
},
"rtt": {
"type": "string"
},
"screen": {
"type": "string"
},
"tls": {
"type": "boolean"
},
"version": {
"type": "string"
}
},
"type": "object"
}
},
"required": [
"host"
],
"type": "object"
},
{
"properties": {
"failed": {
"description": "失败的台数",
"type": "integer"
},
"results": {
"items": {
"properties": {
"data": {
"description": "该台成功时的单机 structuredContent(字段随工具而定)",
"type": "object"
},
"error": {
"description": "该台失败时的错误对象(code / message)",
"type": "object"
},
"id": {
"description": "主机 id",
"type": "string"
},
"ok": {
"description": "该台是否成功",
"type": "boolean"
},
"text": {
"description": "该台失败时的错误文字",
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"skipped": {
"description": "因整体时限用尽而未下发的台数(不是主机侧错误)",
"type": "integer"
},
"succeeded": {
"description": "成功的台数",
"type": "integer"
},
"tool": {
"description": "被批量调用的工具名",
"type": "string"
},
"total": {
"description": "请求里的 id 台数",
"type": "integer"
}
},
"required": [
"results"
],
"type": "object"
}
],
"type": "object"
}
},
{
"name": "get_screenshot",
"description": "截取指定在线主机的一帧画面,返回 base64 编码的 JPEG 图片(image 对象含 mimeType/data/width/height)。支持 Windows 与带 X11 桌面的 Linux 客户端(能力位 CLIENT_CAP_SCREEN_PREVIEW),主连接 RPC、一次性返回。Android 客户端用无障碍服务 takeScreenshot 抓屏(Android 11+ 且开启无障碍服务,此时登录会声明该能力位;只支持 mode=screen)。mode 可选 screen(默认,整虚拟桌面)/region(指定矩形)/window(指定 hwnd)/monitor(指定显示器);后三种默认按源尺寸 1:1 原生分辨率抓取(适合 OCR/视觉读字),需要较新的 Windows 客户端(CLIENT_CAP_SCREEN_REGION,否则 -32005),结果在 structuredContent.capture 里回报实际源矩形与缩放比例。",
"inputSchema": {
"properties": {
"height": {
"description": "region 模式必填:矩形高度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。",
"type": "integer"
},
"hwnd": {
"description": "window 模式必填:窗口句柄(整数或 0x 前缀字符串),取 host_inspect 的 windows 项 / get_foreground_window 返回的 hwnd。窗口最小化时无法抓取(返回错误),先 activate/restore。",
"type": [
"integer",
"string"
]
},
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"max_width": {
"description": "期望图片最大宽度(像素,钳制到 64~1920)。screen 模式省略或传 0 时沿用 RTT 自适应缩略图档位(最大 1024);region/window/monitor 模式省略/传 0 时按源尺寸 1:1 抓取(原生分辨率),显式传入才等比缩小。",
"type": "integer"
},
"mode": {
"description": "抓取范围,默认 screen。screen=整个虚拟桌面(可缩放);region=指定矩形;window=指定窗口;monitor=指定显示器。region/window/monitor 默认按源尺寸 1:1 抓取(原生分辨率,适合 OCR/视觉读字),只有显式传 max_width 才缩放;这三种需要较新的 Windows 客户端(能力位 CLIENT_CAP_SCREEN_REGION),否则返回 -32005。",
"enum": [
"screen",
"region",
"window",
"monitor"
],
"type": "string"
},
"monitor": {
"description": "monitor 模式:显示器序号,0=主显示器(默认),1..N 为其余显示器(按系统枚举顺序)。序号越界返回错误。",
"type": "integer"
},
"width": {
"description": "region 模式必填:矩形宽度(像素,1~8192)。超出虚拟桌面的部分会被裁剪。",
"type": "integer"
},
"x": {
"description": "region 模式:矩形左上角的虚拟桌面 X 坐标(可为负;多显示器时以虚拟桌面左上角为原点)。省略按 0 处理。",
"type": "integer"
},
"y": {
"description": "region 模式:矩形左上角的虚拟桌面 Y 坐标(可为负)。省略按 0 处理。",
"type": "integer"
}
},
"required": [
"id"
],
"type": "object"
},
"outputSchema": {
"properties": {
"capture": {
"properties": {
"height": {
"type": "integer"
},
"mode": {
"type": "string"
},
"native": {
"type": "boolean"
},
"scale": {
"type": "integer"
},
"width": {
"type": "integer"
},
"x": {
"type": "integer"
},
"y": {
"type": "integer"
}
},
"type": "object"
},
"image": {
"properties": {
"bytes": {
"type": "integer"
},
"height": {
"type": "integer"
},
"mimeType": {
"type": "string"
},
"width": {
"type": "integer"
}
},
"type": "object"
}
},
"required": [
"image"
],
"type": "object"
}
},
{
"name": "list_files",
"description": "列举指定在线主机的目录。省略或空 path 返回驱动器列表(drives);给定 path 返回该目录一层内的文件/子目录(files,最多 500 条,含 name/isDir/size/mtime)。只读。",
"inputSchema": {
"anyOf": [
{
"required": [
"id"
]
},
{
"required": [
"ids"
]
}
],
"properties": {
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"ids": {
"description": "批量查询:一次传多台主机 id(最多 50 个),结果按台汇总在 results 里。与 id 二选一,仅只读工具支持;limit/offset 对每台主机各自生效。",
"items": {
"type": "string"
},
"type": "array"
},
"limit": {
"description": "本次最多返回的条数,默认 100,上限 1000。",
"type": "integer"
},
"offset": {
"description": "跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。",
"type": "integer"
},
"path": {
"description": "要列举的目录路径(如 C:\\Windows);省略或传空则返回驱动器列表",
"type": "string"
}
},
"type": "object"
},
"outputSchema": {
"anyOf": [
{
"properties": {
"drives": {
"items": {
"properties": {
"drive": {
"type": "string"
},
"fileSystem": {
"type": "string"
},
"freeMB": {
"type": "integer"
},
"totalMB": {
"type": "integer"
},
"type": {
"type": "integer"
},
"typeName": {
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"files": {
"items": {
"properties": {
"isDir": {
"type": "boolean"
},
"mtime": {
"type": "integer"
},
"name": {
"type": "string"
},
"size": {
"type": "integer"
}
},
"type": "object"
},
"type": "array"
},
"hasMore": {
"type": "boolean"
},
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"total": {
"type": "integer"
},
"totalAll": {
"type": "integer"
}
},
"type": "object"
},
{
"properties": {
"failed": {
"description": "失败的台数",
"type": "integer"
},
"results": {
"items": {
"properties": {
"data": {
"description": "该台成功时的单机 structuredContent(字段随工具而定)",
"type": "object"
},
"error": {
"description": "该台失败时的错误对象(code / message)",
"type": "object"
},
"id": {
"description": "主机 id",
"type": "string"
},
"ok": {
"description": "该台是否成功",
"type": "boolean"
},
"text": {
"description": "该台失败时的错误文字",
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"skipped": {
"description": "因整体时限用尽而未下发的台数(不是主机侧错误)",
"type": "integer"
},
"succeeded": {
"description": "成功的台数",
"type": "integer"
},
"tool": {
"description": "被批量调用的工具名",
"type": "string"
},
"total": {
"description": "请求里的 id 台数",
"type": "integer"
}
},
"required": [
"results"
],
"type": "object"
}
],
"type": "object"
}
},
{
"name": "get_audit_log",
"description": "获取 YAMA 服务端主界面的消息/审计日志(主机上线/下线、操作结果、告警等),按 limit/offset 分页(新在前,服务端只保留最近 1000 条)。可选 type 按类型列做不区分大小写的子串过滤(如 MCP、主机),keyword 按正文字串过滤;过滤在分页之前生效,total 为命中条数、totalAll 为镜像里的全部条数。只读、纯内存。",
"inputSchema": {
"properties": {
"keyword": {
"description": "正文子串过滤,不区分大小写(如 445、timeout)。省略则不过滤。",
"type": "string"
},
"limit": {
"description": "本次最多返回的条数,默认 100,上限 1000。",
"type": "integer"
},
"offset": {
"description": "跳过前 N 条,默认 0;配合返回的 total/hasMore 翻页。",
"type": "integer"
},
"type": {
"description": "类型列的子串过滤,不区分大小写(如 MCP、主机上线)。省略则不过滤。",
"type": "string"
}
},
"required": [],
"type": "object"
},
"outputSchema": {
"properties": {
"entries": {
"items": {
"properties": {
"msg": {
"type": "string"
},
"time": {
"type": "string"
},
"type": {
"type": "string"
}
},
"type": "object"
},
"type": "array"
},
"hasMore": {
"type": "boolean"
},
"limit": {
"type": "integer"
},
"offset": {
"type": "integer"
},
"total": {
"type": "integer"
},
"totalAll": {
"type": "integer"
}
},
"required": [
"entries"
],
"type": "object"
}
},
{
"name": "get_server_status",
"description": "获取 YAMA 服务端自身的状态:程序版本与 exe 构建时间、进程已运行秒数、MCP 监听地址与端口、各功能开关(只读/终端/远程控制/文件传输/管理/主机管理/高风险操作/键盘记录/远程交谈)、在线与离线主机数、各类在飞会话数、当前被封禁的来源 IP 数。只读、纯内存,不返回 token。",
"inputSchema": {
"properties": {},
"required": [],
"type": "object"
},
"outputSchema": {
"properties": {
"app_name": {
"type": "string"
},
"bind": {
"type": "string"
},
"blocked_auth_ips": {
"type": "integer"
},
"exe_build_time": {
"type": "string"
},
"hosts": {
"type": "object"
},
"port": {
"type": "integer"
},
"sessions": {
"type": "object"
},
"switches": {
"type": "object"
},
"uptime_sec": {
"type": "integer"
},
"version": {
"type": "string"
}
},
"required": [],
"type": "object"
}
},
{
"name": "terminal_exec",
"description": "在已打开的持久会话中执行一条命令,或轮询取回正在运行的命令输出。带 command 时执行并在 timeout_ms 内等待;等待超时返回 done:false 与已产生的部分输出,会话不销毁(命令仍在远端运行)。session_id 可省略:自动复用该主机已有的持久会话,没有就隐式打开一个(结果里有 session_id 与 reused),不必先 terminal_open。不带 command、只传 session_id 时进入轮询模式:继续等待并取回增量输出,直到 done:true(此时有 exit_code)。命令不受白名单约束。PTY 会话(新 Windows 客户端 ConPTY / Linux 与新版 Android 的 POSIX PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联,适合「ls -1 | wc -l」这类先过滤再回传的用法;不要用后台执行符 &(POSIX)或换行。老非 PTY Windows 客户端仍不支持 & 与 |,请拆成多条调用。",
"inputSchema": {
"properties": {
"command": {
"description": "要执行的命令(完整 shell,不受白名单约束)。省略时进入轮询模式:不执行新命令,只等待并取回当前会话的增量输出(上一条命令超时后用这个方式继续取)。PTY 会话(Windows ConPTY / Linux PTY)下可用管道 | 与 && / || 串联,退出码取整条管道/串联;不要用后台执行符 &(POSIX)或换行。老非 PTY 客户端仍不支持 & 与 |,请拆成多条调用。Linux 下通过 POSIX shell 执行,可用 ; 串联且退出码取最后一条命令",
"type": "string"
},
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"max_output_bytes": {
"description": "单次返回的原始输出上限(可选,默认 65536,最小 1024,最大 1048576);超出按换行边界截断并置 truncated:true,再轮询一次可取回剩余",
"type": "integer"
},
"session_id": {
"description": "会话 token。带 command 时可省略:自动复用该主机已有的持久会话,没有就在内部打开一个(结果里有 session_id 与 reused)。轮询模式必须提供",
"type": "string"
},
"timeout_ms": {
"description": "本次调用最多等待的毫秒数(可选,默认 20000,上限 600000)。等待超时不算失败:返回 done:false 与已产生的输出,命令仍在远端运行,继续轮询即可",
"type": "integer"
}
},
"required": [
"id"
],
"type": "object"
},
"outputSchema": {
"properties": {
"done": {
"description": "false=命令仍在运行,用同一工具只传 session_id 继续取增量;true=命令已结束,exit_code 有效",
"type": "boolean"
},
"dropped_bytes": {
"description": "因单条命令输出超过 8MB 上限被丢弃的最旧字节数(该命令累计,0 或省略=无丢失)",
"type": "integer"
},
"elapsed_ms": {
"description": "本次调用实际等待的毫秒数",
"type": "integer"
},
"exit_code": {
"description": "退出码(done=true 时提供):PTY 客户端(Windows ConPTY / Linux PTY)为命令的真实退出码;老客户端(非 PTY)仅区分 0/非 0;-1=未知(shell 进程退出)",
"type": "integer"
},
"is_pty": {
"description": "true=PTY(UTF-8)(Windows ConPTY / Linux PTY);false=老 cmd 管道(GBK)",
"type": "boolean"
},
"reused": {
"description": "true=复用了该主机已有的持久会话;false=本次隐式新建(省略 session_id 时)",
"type": "boolean"
},
"session_id": {
"description": "会话 token,原样回传,便于续接轮询",
"type": "string"
},
"stdout": {
"description": "本次新增的输出(已剥哨兵与 ANSI 转义)",
"type": "string"
},
"truncated": {
"description": "true=本次受 max_output_bytes 限制仍有剩余输出,立即再轮询即可取回",
"type": "boolean"
}
},
"required": [
"stdout",
"done",
"session_id"
],
"type": "object"
}
},
{
"name": "terminal_close",
"description": "关闭并释放指定持久会话(幂等:会话已不存在也返回成功)。",
"inputSchema": {
"properties": {
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"session_id": {
"description": "terminal_open 返回的 session_id",
"type": "string"
}
},
"required": [
"id",
"session_id"
],
"type": "object"
},
"outputSchema": {
"properties": {
"closed": {
"description": "恒为 true(关闭幂等)",
"type": "boolean"
}
},
"required": [
"closed"
],
"type": "object"
}
},
{
"name": "read_file",
"description": "按字节读取指定在线主机上的一个文本文件(分页 + 编码识别 + 整文件 SHA-256),只支持单个普通文件。path 为远程绝对路径:Windows 用 D:\\cfg\\app.ini 这类盘符路径,Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。offset 支持负数(-200 = 最后 200 行,看日志尾部);limit 为最多返回的行数(默认 2000);encoding=auto 时按 BOM → UTF-8 合法性 → GBK 回退识别,也可显式传 utf-8 / gbk / latin1;max_bytes 限制本次返回的文本字节数(默认 262144=256KB,超出按 truncated=true 截断)。目录、或大于 2MB 的文件返回 -32602(请改用 download_file)。返回 size/encoding/eol/lines_total/offset/lines_returned/truncated/text/sha256(sha256 是整个文件,不是本次片段)。读配置文件/日志时用它,不要用 exec_command 的 type/Get-Content(GBK 会乱码、行尾会被归一化);看被管业务程序的日志尾部用 offset=-N(如 offset=-200,N 为行数)。",
"inputSchema": {
"properties": {
"encoding": {
"description": "auto(默认,按 BOM → UTF-8 合法性 → GBK 回退)/ utf-8 / gbk / gb18030 / latin1",
"type": "string"
},
"id": {
"description": "主机 id,取 list_hosts 返回的 id 字段",
"type": "string"
},
"limit": {
"description": "最多返回的行数(1..200000,默认 2000)",
"type": "integer"
},
"max_bytes": {
"description": "本次返回文本的字节上限(1024..2097152,默认 262144=256KB),超出按 truncated=true 截断",
"type": "integer"
},
"offset": {
"description": "起始行(0 基)。负数表示从末尾倒数:-200 = 最后 200 行;默认 0",
"type": "integer"
},
"path": {
"description": "远程文件的绝对路径。Windows 用 D:\\cfg\\app.ini 这类盘符路径;Linux/macOS 用 /etc/app.conf 这类 POSIX 路径。必须是单个普通文件(目录或大于 2MB 的文件返回 -32602)",
"type": "string"
}
},
"required": [
"id",
"path"
],
"type": "object"
},
"outputSchema": {
"properties": {
"encoding": {
"description": "实际使用的编码:utf-8 / utf-16le / utf-16be / gbk / gb18030 / latin1",
"type": "string"
},
"eol": {
"description": "行尾风格:crlf / lf / cr / mixed / none",
"type": "string"
},
"lines_returned": {
"description": "本次返回的行数",
"type": "integer"
},
"lines_total": {
"description": "文件总行数(末尾换行不计空行)",
"type": "integer"
},
"offset": {
"description": "本次实际起始行(负数已换算成绝对行号)",
"type": "integer"
},
"path": {
"description": "远程路径(原样回传)",
"type": "string"
},
"sha256": {
"description": "整个文件的 SHA-256(不是本次片段),可与 download_file 的结果比对",
"type": "string"
},
"size": {
"description": "文件总字节数",
"type": "integer"
},
"text": {
"description": "文件内容(UTF-8,行以 \\n 分隔,已去掉 BOM)",
"type": "string"
},
"truncated": {
"description": "true=还有内容没返回(超出 limit / max_bytes),可调整 offset 继续读",
"type": "boolean"
}
},
"required": [
"path",
"size",
"encoding",
"eol",
"lines_total",
"offset",
"lines_returned",
"truncated",
"text",
"sha256"
],
"type": "object"
}
}
]
+32 -4
View File
@@ -36,14 +36,23 @@ type Server struct {
allowedOrigins []string // for WS Origin allowlist; empty = same-origin only
loginIPLimit *wsauth.RateLimiter
loginUserLimit *wsauth.RateLimiter
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
sso SSODetector // nil = SSO disabled
trustForwardedFor bool // honor X-Forwarded-For (behind trusted proxy only)
basePath string // web UI mount prefix (e.g. "/remoter"); "" = domain root
brandName string // white-label title; "" = "SimpleRemoter" (official branding)
sso SSODetector // nil = SSO disabled
mcp mcpEndpoint // nil = no /mcp route
sweepDone chan struct{} // closes to stop the login-limiter sweeper
sweepStopOnce sync.Once
}
// mcpEndpoint is the part of *mcp.Server the web server mounts. Expressed as
// an interface so web does not depend on the mcp package (the endpoint owns
// its own auth and protocol; web only routes to it).
type mcpEndpoint interface {
Handle(http.ResponseWriter, *http.Request)
Enabled() bool
}
// Config tunes the server's exposed-on-public-HTTPS hardening knobs.
// All fields are optional; zero values pick reasonable defaults.
type Config struct {
@@ -109,6 +118,15 @@ func (s *Server) WithConfig(cfg Config) *Server {
return s
}
// WithMCP attaches the MCP endpoint under /mcp (basePath-aware via mount).
// When the endpoint reports itself disabled (no bearer token) the route is not
// registered and /mcp 404s, matching "no token = feature off". Safe to call
// before Start.
func (s *Server) WithMCP(m mcpEndpoint) *Server {
s.mcp = m
return s
}
// Start launches the server in a goroutine and returns immediately.
// If port is 0, returns nil without starting anything.
func (s *Server) Start() error {
@@ -129,6 +147,16 @@ func (s *Server) Start() error {
mux.HandleFunc("/api/devices", s.requireBearer(s.handleDevices))
mux.HandleFunc("/sso", s.handleSSO)
mux.HandleFunc("/ws", s.ws.serve)
// MCP is its own protocol with its own static bearer token; it does not go
// through requireBearer (that validates browser sessions). Mounted inside
// the mux so basePath stripping applies like every other route.
if s.mcp != nil {
if s.mcp.Enabled() {
mux.HandleFunc("/mcp", s.mcp.Handle)
} else {
s.log.Info("MCP endpoint disabled: YAMA_MCP_TOKEN not set")
}
}
mux.HandleFunc("/static/xterm.js", staticHandler(xtermJS, "application/javascript; charset=utf-8"))
mux.HandleFunc("/static/xterm.css", staticHandler(xtermCSS, "text/css; charset=utf-8"))
mux.HandleFunc("/static/xterm-fit.js", staticHandler(xtermFitJS, "application/javascript; charset=utf-8"))
+104
View File
@@ -0,0 +1,104 @@
#!/usr/bin/env python3
"""Generate server/go/mcp/tools_minimal.json from mcp/tools.json.
The Go server embeds its tools/list payload, so the nine tools it exposes must
be a byte-for-byte copy of the canonical schemas. This script extracts them
without hand-editing, preserving tools.json order, and keeps only the four
fields MCP publishes: name / description / inputSchema / outputSchema.
Usage:
python tools/mcp_tools/gen_go_tools.py # rewrite the embedded file
python tools/mcp_tools/gen_go_tools.py --check # exit 1 if it is stale
Run from anywhere; paths are resolved relative to this file.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
# The nine tools of the Go minimal server (design §3.1). Order in the embedded
# file follows mcp/tools.json, not this list.
MINIMAL_TOOLS = (
"list_hosts",
"get_host_detail",
"get_screenshot",
"list_files",
"get_audit_log",
"get_server_status",
"terminal_exec",
"terminal_close",
"read_file",
)
OUTPUT_FIELDS = ("name", "description", "inputSchema", "outputSchema")
REPO_ROOT = Path(__file__).resolve().parents[2]
TOOLS_JSON = REPO_ROOT / "mcp" / "tools.json"
OUTPUT_JSON = REPO_ROOT / "server" / "go" / "mcp" / "tools_minimal.json"
def render() -> str:
with TOOLS_JSON.open(encoding="utf-8") as f:
doc = json.load(f)
tools = doc["tools"] if isinstance(doc, dict) else doc
by_name = {}
for tool in tools:
name = tool.get("name")
if name in by_name:
raise SystemExit(f"duplicate tool name in {TOOLS_JSON}: {name}")
by_name[name] = tool
missing = [n for n in MINIMAL_TOOLS if n not in by_name]
if missing:
raise SystemExit(f"tools missing from {TOOLS_JSON}: {', '.join(missing)}")
minimal = []
for tool in tools:
if tool["name"] not in MINIMAL_TOOLS:
continue
minimal.append({field: tool[field] for field in OUTPUT_FIELDS})
if len(minimal) != len(MINIMAL_TOOLS):
raise SystemExit(
f"expected {len(MINIMAL_TOOLS)} tools, got {len(minimal)}"
)
return json.dumps(minimal, ensure_ascii=False, indent=2) + "\n"
def main(argv: list[str]) -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"--check",
action="store_true",
help="do not write; exit 1 when tools_minimal.json is out of date",
)
args = parser.parse_args(argv)
want = render()
if args.check:
try:
current = OUTPUT_JSON.read_text(encoding="utf-8")
except FileNotFoundError:
print(f"FAIL {OUTPUT_JSON} is missing", file=sys.stderr)
return 1
if current != want:
print(
f"FAIL {OUTPUT_JSON} is stale; run gen_go_tools.py",
file=sys.stderr,
)
return 1
print(f"PASS {OUTPUT_JSON} matches mcp/tools.json")
return 0
OUTPUT_JSON.parent.mkdir(parents=True, exist_ok=True)
OUTPUT_JSON.write_text(want, encoding="utf-8", newline="\n")
print(f"wrote {OUTPUT_JSON} ({len(MINIMAL_TOOLS)} tools)")
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))