From 5f764b2425f786584c7e6f9ee2c8d41ed12f4069 Mon Sep 17 00:00:00 2001 From: yuanyuanxiang <962914132@qq.com> Date: Fri, 27 Nov 2026 14:51:15 +0100 Subject: [PATCH] Feature: return web-console remarks from the Go MCP host tools list_hosts and get_host_detail now include the remark an admin set in the web console, and the name/query filters match it like the Win32 server (name: hostname + remark; query: hostname + remark + IP). The text-only host table gains a remark column, and the MCP instructions stop claiming the Go server keeps no remarks. The remark table is injected through a small Note() interface so the mcp package still does not import web. An optional Notes() snapshot capability is borrowed once per call, so a listing neither takes a read lock per device nor mixes labels across a concurrent save. The design docs are updated to match the new fields and table column. Verified: go build ./..., go vet, gofmt and the full go test ./... pass; new tests cover remark projection, both filters and the snapshot path. Co-Authored-By: deepseek-flash --- docs/Mcp_Go_Minimal_Design.md | 9 ++-- docs/Mcp_Go_Minimal_Implementation_Plan.md | 5 ++- server/go/cmd/main.go | 2 + server/go/mcp/server.go | 36 ++++++++++++++- server/go/mcp/tools_local.go | 51 ++++++++++++++-------- server/go/mcp/tools_local_test.go | 31 +++++++++++-- server/go/web/device_notes.go | 16 +++++++ server/go/web/device_notes_test.go | 14 ++++++ 8 files changed, 136 insertions(+), 28 deletions(-) diff --git a/docs/Mcp_Go_Minimal_Design.md b/docs/Mcp_Go_Minimal_Design.md index 116925e..baf5422 100644 --- a/docs/Mcp_Go_Minimal_Design.md +++ b/docs/Mcp_Go_Minimal_Design.md @@ -141,14 +141,15 @@ { "hosts": [ /* ... */ ], "total": 7, "totalAll": 9, "limit": 100, "offset": 0, "hasMore": false } ``` -`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 只匹配计算机名,`query` 同时匹配 +`client_type/group/ip/os` 为大小写不敏感子串过滤;`name` 匹配计算机名与备注,`query` 匹配 计算机名、备注与 IP;`online=true`(默认)只列在线,`false` 只列历史中存在但当前离线的; `include_offline=true` 时再合并 `devicehistory.Store.Offline(online)`。`total` 是过滤后命中数, `totalAll` 是过滤前总数,`hasMore` 表示同一条件下还有下一页。 `hosts[]` 的字段按 `outputSchema`:`id/name/group/version/clientType/os/ip/rtt/activeWindow/ -screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`;两个服务端都 -没有 `authStatus/tls/remark`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。 +screen/online/last_seen`,以及 hub 或历史记录里确有的 `location/install_time`,和 Go 版 +Web 控制台设置过的 `remark`(`device_notes.json`,未设置时省略);两个服务端都没有 +`authStatus/tls`,不输出。离线历史条目不存 `clientType`,也没有 `rtt/activeWindow`。 #### `get_host_detail` @@ -255,7 +256,7 @@ M5 之前传任一参数都返回 `-32005` 并在 message 里点名。细节见 | 工具 | 汇总行之后 | |---|---| -| `list_hosts` | 表头 `id name ip group os online clientType last_seen`,随后每台一行 | +| `list_hosts` | 表头 `id name remark ip group os online clientType last_seen`,随后每台一行 | | `get_host_detail` | 单台:主机 JSON(compact);批量:`id ok detail`,成功行是主机 JSON,失败行是错误信息 | | `list_files` | 盘符 `drive typeName fileSystem totalMB freeMB`;目录 `name isDir size mtime` | | `get_audit_log` | `time type msg`,`msg` 是去掉信封字段后的 compact JSON | diff --git a/docs/Mcp_Go_Minimal_Implementation_Plan.md b/docs/Mcp_Go_Minimal_Implementation_Plan.md index 735dc09..1cc0913 100644 --- a/docs/Mcp_Go_Minimal_Implementation_Plan.md +++ b/docs/Mcp_Go_Minimal_Implementation_Plan.md @@ -97,7 +97,7 @@ | `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`) | +| hub 没有的字段 | `authStatus/tls/location/install_time` 不伪造、直接不给(`outputSchema` 只强制 `hosts`);`remark` 来自 Web 控制台备注表(`DeviceNotes`),有则填、无则省略 | `read_file` 的整文件下载仍受 `YAMA_MCP_READ_MAX`(2 MiB)硬门约束,超过 → `-32602`(schema 描述同款口径)。 @@ -197,7 +197,8 @@ curl -s -X POST localhost:18090/mcp -H "Authorization: Bearer $YAMA_MCP_TOKEN" \ 决定是否并入历史;`online/ip/os/group/name/client_type/query` 全为过滤(`name`/`query` 大小写不敏感子串);按 `outputSchema` 返回 `{hosts,total,totalAll,limit,offset,hasMore}`, host 字段按 schema 命名组装,hub/历史里确有的 `location/install_time/screen/version` 照填, - 两边都没有的 `authStatus/tls/remark` 不伪造。 + 两边都没有的 `authStatus/tls` 不伪造;`remark` 来自 Web 控制台备注表(`DeviceNotes`, + 有则填、无则省略),沿用 `name`/`query` 的过滤口径。 - `get_host_detail`:`id` 或 `ids`(≤50,批量走 `{tool,total,succeeded,failed,skipped,results[]}`); `capabilities{screenPreview,screenRegion,windowInfo,fileTransferV2,c2cPaths,registry,remoteControl,platform}` (`protocol.SupportsCap` 逐位)——**不含 `v2`**(恒真,列出来误导)。 diff --git a/server/go/cmd/main.go b/server/go/cmd/main.go index eafd624..e6fea4a 100644 --- a/server/go/cmd/main.go +++ b/server/go/cmd/main.go @@ -1292,6 +1292,8 @@ func main() { Bind: bindAddr, // Devices bound to a web user are invisible/unreachable through MCP. DeviceACL: deviceACL, + // Web-console remarks are returned by list_hosts/get_host_detail. + DeviceRemarks: deviceNotes, }) if mcpSrv.Enabled() { // Terminal tools need the hub's shell events (ready/data/closed). diff --git a/server/go/mcp/server.go b/server/go/mcp/server.go index 93f6937..f30dbb9 100644 --- a/server/go/mcp/server.go +++ b/server/go/mcp/server.go @@ -43,6 +43,21 @@ type DeviceOwner interface { Owner(deviceID string) string } +// DeviceRemarks reports the web console's remark for a device ("" when none). +// Implemented by web.DeviceNotes; declared as an interface for the same reason +// as DeviceOwner. A nil table simply leaves the field out of the host JSON. +type DeviceRemarks interface { + Note(deviceID string) string +} + +// deviceRemarkSnapshotter is an optional DeviceRemarks capability: returning +// the whole table lets a host listing take one snapshot instead of a read lock +// per device, so a remark save's fsync cannot stall the call and one listing +// cannot mix pre-edit and post-edit labels. Implemented by web.DeviceNotes. +type deviceRemarkSnapshotter interface { + Notes() map[string]string +} + // deviceOwnerSnapshotter is an optional DeviceOwner capability: returning the // whole binding table lets a long operation (the audit scan) apply the policy // without a read-lock acquisition per record. Implemented by web.DeviceACL. @@ -64,6 +79,21 @@ func (s *Server) ownerChecker() func(deviceID string) bool { return func(id string) bool { return s.cfg.DeviceACL.Owner(id) == "" } } +// remarkLookup returns a per-call remark lookup, or nil when no remark table +// is configured. A table that can snapshot its whole map is read once, so a +// large listing neither takes a read lock per device nor observes a save +// halfway through; other tables fall back to one Note() per device. +func (s *Server) remarkLookup() func(deviceID string) string { + if s.cfg.DeviceRemarks == nil { + return nil + } + if snap, ok := s.cfg.DeviceRemarks.(deviceRemarkSnapshotter); ok { + notes := snap.Notes() + return func(id string) string { return notes[id] } + } + return func(id string) string { return s.cfg.DeviceRemarks.Note(id) } +} + // 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 { @@ -90,6 +120,10 @@ type Config struct { // in list_hosts/get_host_detail and unreachable by ID in every device- // targeted tool, even if its ID is known. DeviceACL DeviceOwner + + // DeviceRemarks, when non-nil, adds the web console's remark to + // list_hosts/get_host_detail and lets the name/query filters match it. + DeviceRemarks DeviceRemarks } // toolFunc implements one tools/call. It returns either a result value or a @@ -483,5 +517,5 @@ const serverInstructions = `这是 YAMA 服务端的 MCP 端点(Go 实现) 4) get_screenshot 只支持 mode=screen(按链路状况自适应缩放,max_width 省略时最大 1024);本实现没有 CLIENT_CAP_SCREEN_REGION 扩展,mode=region/window/monitor 与区域类参数一律返回 -32005。 5) list_files / read_file 走文件传输通道;list_files 支持 ids 批量(最多 50 台、整批 50 秒)。read_file 只接受单个普通文件且整文件不超过 2 MiB,目录用 list_files;本实现没有 download_file / search_file,超限文件只能改用 terminal_exec 分段查看,或连 Windows 主控端的完整服务端。 6) terminal_exec 需要客户端支持终端(CLIENT_CAP_TERMINAL),会在目标主机上创建持久会话;用完调用 terminal_close 释放,闲置会话由服务端回收。调用被取消时返回的 message 里带 session_id,可用它轮询或关闭。 -7) 本实现不维护备注与授权状态:list_hosts / get_host_detail 不返回 remark/authStatus/tls;get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。 +7) 本实现不维护授权状态与 TLS 标记:list_hosts / get_host_detail 不返回 authStatus/tls;备注(remark)由 Web 控制台维护,设置后会随主机返回,query 也匹配备注。get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。 8) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。` diff --git a/server/go/mcp/tools_local.go b/server/go/mcp/tools_local.go index 84b9b59..944e610 100644 --- a/server/go/mcp/tools_local.go +++ b/server/go/mcp/tools_local.go @@ -142,6 +142,7 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp ctF := strings.ToLower(args.ClientType) matched := make([]hub.DeviceInfo, 0, len(pool)) + remarkOf := s.remarkLookup() for _, d := range pool { group := d.Group if group == "" { @@ -155,12 +156,20 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp if d.Online { clientType = s.clientType(d.ID) } - // query matches computer name, remark and IP. The two servers keep no - // remark column, so name+IP is the full set here. - if q != "" && !strings.Contains(strings.ToLower(d.Name), q) && !strings.Contains(strings.ToLower(ip), q) { + remark := "" + if remarkOf != nil { + remark = remarkOf(d.ID) + } + // query matches computer name, remark and IP; name matches computer + // name and remark, like the Win32 server. The remark is the web + // console's label (empty unless an admin set it). + if q != "" && !strings.Contains(strings.ToLower(d.Name), q) && + !strings.Contains(strings.ToLower(ip), q) && + !strings.Contains(strings.ToLower(remark), q) { continue } - if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) { + if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) && + !strings.Contains(strings.ToLower(remark), nameF) { continue } if ipF != "" && !strings.Contains(strings.ToLower(ip), ipF) { @@ -185,7 +194,7 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp end := min(begin+limit, total) hosts := make([]map[string]any, 0, end-begin) for _, d := range matched[begin:end] { - hosts = append(hosts, s.hostJSON(d)) + hosts = append(hosts, s.hostJSON(d, remarkOf)) } structured := map[string]any{ @@ -205,9 +214,11 @@ func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rp } // hostJSON projects a hub device onto the list_hosts/get_host_detail schema. -// Fields the Go server does not know (authStatus, tls, remark, clientType of -// an offline entry) are omitted rather than fabricated. -func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any { +// Fields the Go server does not know (authStatus, tls, clientType of an +// offline entry) are omitted rather than fabricated. remark is included when +// the web console has one for the device; remarkOf is the per-call snapshot +// (nil when no remark table is configured). +func (s *Server) hostJSON(d hub.DeviceInfo, remarkOf func(string) string) map[string]any { group := d.Group if group == "" { group = "default" @@ -218,6 +229,11 @@ func (s *Server) hostJSON(d hub.DeviceInfo) map[string]any { "group": group, "online": d.Online, } + if remarkOf != nil { + if remark := remarkOf(d.ID); remark != "" { + h["remark"] = remark + } + } if d.Version != "" { h["version"] = d.Version } @@ -300,7 +316,7 @@ func (s *Server) callGetHostDetail(_ context.Context, raw json.RawMessage) (any, return nil, errf(CodeInvalidParams, "Missing required parameter: id or ids") } online, offline := s.hostMaps() - host, rerr := s.lookupHost(args.ID, online, offline) + host, rerr := s.lookupHost(args.ID, online, offline, s.remarkLookup()) if rerr != nil { return nil, rerr } @@ -313,10 +329,11 @@ func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) { "Too many ids: %d (max %d per batch)", len(ids), batchMaxIDs) } online, offline := s.hostMaps() + remarkOf := s.remarkLookup() // one snapshot for the whole batch results := make([]map[string]any, 0, len(ids)) succeeded, failed := 0, 0 for _, id := range ids { - host, rerr := s.lookupHost(id, online, offline) + host, rerr := s.lookupHost(id, online, offline, remarkOf) if rerr != nil { results = append(results, map[string]any{ "id": id, @@ -375,17 +392,17 @@ func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) { // lookupHost resolves one host: online first, then the last-known history // record. It mirrors the Win32 server, which answers offline hosts with their // final snapshot instead of an error. -func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo) (map[string]any, *rpcError) { +func (s *Server) lookupHost(id string, online, offline map[string]hub.DeviceInfo, remarkOf func(string) string) (map[string]any, *rpcError) { if !isDecimalID(id) { return nil, errf(CodeInvalidParams, "Invalid id: expected a decimal host id string") } if d, ok := online[id]; ok { - h := s.hostJSON(d) + h := s.hostJSON(d, remarkOf) h["capabilities"] = s.capabilities(d) return h, nil } if d, ok := offline[id]; ok { - return s.hostJSON(d), nil + return s.hostJSON(d, remarkOf), nil } return nil, errf(CodeOffline, "Host not found or offline: %s", id) } @@ -449,13 +466,13 @@ func appendHostRows(text string, hosts []map[string]any) string { for _, h := range hosts { online, _ := h["online"].(bool) rows = append(rows, []string{ - tableText(h["id"]), tableText(h["name"]), tableText(h["ip"]), - tableText(h["group"]), tableText(h["os"]), strconv.FormatBool(online), - tableText(h["clientType"]), tableText(h["last_seen"]), + tableText(h["id"]), tableText(h["name"]), tableText(h["remark"]), + tableText(h["ip"]), tableText(h["group"]), tableText(h["os"]), + strconv.FormatBool(online), tableText(h["clientType"]), tableText(h["last_seen"]), }) } return appendRows(text, - []string{"id", "name", "ip", "group", "os", "online", "clientType", "last_seen"}, + []string{"id", "name", "remark", "ip", "group", "os", "online", "clientType", "last_seen"}, rows) } diff --git a/server/go/mcp/tools_local_test.go b/server/go/mcp/tools_local_test.go index ac5d9d7..ead05f1 100644 --- a/server/go/mcp/tools_local_test.go +++ b/server/go/mcp/tools_local_test.go @@ -213,8 +213,22 @@ func TestAppendRowsSanitizesCells(t *testing.T) { } } +// fakeRemarks stands in for web.DeviceNotes: the map value is the remark. It +// only implements Note, so it exercises the per-device fallback path. +type fakeRemarks map[string]string + +func (f fakeRemarks) Note(deviceID string) string { return f[deviceID] } + +// fakeRemarkSnapshot also implements Notes(), the snapshot capability the +// shipped web.DeviceNotes provides. +type fakeRemarkSnapshot map[string]string + +func (f fakeRemarkSnapshot) Note(deviceID string) string { return f[deviceID] } +func (f fakeRemarkSnapshot) Notes() map[string]string { return f } + func TestListHostsPoolsAndProjection(t *testing.T) { f := newLocalFixture(t) + f.srv.cfg.DeviceRemarks = fakeRemarkSnapshot{"1001": "Reception PC"} text, sc := mustCallLocal(t, f.srv, "list_hosts", `{}`) hosts := hostList(t, sc) @@ -236,11 +250,11 @@ func TestListHostsPoolsAndProjection(t *testing.T) { } // Text-only MCP clients never see structuredContent, so the table in the // text block must carry the id every follow-up call is addressed by. - if !strings.Contains(text, "id\tname\tip\tgroup\tos\tonline\tclientType\tlast_seen") { + if !strings.Contains(text, "id\tname\tremark\tip\tgroup\tos\tonline\tclientType\tlast_seen") { t.Fatalf("text = %q, want host table header", text) } - if !strings.Contains(text, "1001\tALPHA\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") { - t.Fatalf("text = %q, want ALPHA row with id first", text) + if !strings.Contains(text, "1001\tALPHA\tReception PC\t10.0.0.1\tdefault\tWindows 10\ttrue\tEXE\t-") { + t.Fatalf("text = %q, want ALPHA row with id first and remark", text) } alpha := hosts[0] @@ -268,7 +282,13 @@ func TestListHostsPoolsAndProjection(t *testing.T) { if _, ok := alpha["last_seen"]; ok { t.Fatal("online host carries last_seen") } - for _, absent := range []string{"remark", "authStatus", "tls"} { + if got := strField(t, alpha, "remark"); got != "Reception PC" { + t.Fatalf("remark = %q, want the web console's label", got) + } + if _, ok := hosts[1]["remark"]; ok { + t.Fatalf("unset remark present on %v", hosts[1]["id"]) + } + for _, absent := range []string{"authStatus", "tls"} { if _, ok := alpha[absent]; ok { t.Fatalf("%s present but the Go server has no such data", absent) } @@ -306,6 +326,7 @@ func TestListHostsPoolsAndProjection(t *testing.T) { func TestListHostsFilters(t *testing.T) { f := newLocalFixture(t) + f.srv.cfg.DeviceRemarks = fakeRemarks{"1001": "Reception PC"} cases := []struct { name string @@ -313,6 +334,7 @@ func TestListHostsFilters(t *testing.T) { want []string }{ {"name substring", `{"name":"beta"}`, []string{"1002"}}, + {"name matches remark", `{"name":"reception"}`, []string{"1001"}}, {"group substring", `{"group":"office"}`, []string{"1002", "1003"}}, {"os substring case-insensitive", `{"os":"windows"}`, []string{"1001", "1002"}}, {"client type", `{"client_type":"lnx"}`, []string{"1003"}}, @@ -320,6 +342,7 @@ func TestListHostsFilters(t *testing.T) { {"peer ip fallback", `{"ip":"192.168.1.2"}`, []string{"1002"}}, {"query matches name", `{"query":"gamma"}`, []string{"1003"}}, {"query matches ip", `{"query":"10.0.0.1"}`, []string{"1001"}}, + {"query matches remark", `{"query":"reception"}`, []string{"1001"}}, {"filters are ANDed", `{"group":"office","os":"ubuntu"}`, []string{"1003"}}, {"no match", `{"name":"zzz"}`, nil}, } diff --git a/server/go/web/device_notes.go b/server/go/web/device_notes.go index ecab80d..fefd13e 100644 --- a/server/go/web/device_notes.go +++ b/server/go/web/device_notes.go @@ -114,6 +114,22 @@ func (n *DeviceNotes) Note(deviceID string) string { return n.entries[deviceID].Note } +// Notes returns a copy of the deviceID -> remark map. Callers that look up +// many devices in one pass (MCP host listings) take this snapshot instead of a +// read lock per device, so a save's fsync cannot stall the whole listing. +func (n *DeviceNotes) Notes() map[string]string { + if n == nil { + return map[string]string{} + } + n.mu.RLock() + defer n.mu.RUnlock() + out := make(map[string]string, len(n.entries)) + for id, e := range n.entries { + out[id] = e.Note + } + return out +} + // Snapshot returns a copy of the table (for logs and tests). func (n *DeviceNotes) Snapshot() map[string]DeviceNoteEntry { if n == nil { diff --git a/server/go/web/device_notes_test.go b/server/go/web/device_notes_test.go index b7e700c..46a95bb 100644 --- a/server/go/web/device_notes_test.go +++ b/server/go/web/device_notes_test.go @@ -73,6 +73,20 @@ func TestDeviceNotesSetPersistClear(t *testing.T) { if got := notes.Note("dev-2"); got != "" { t.Fatalf("Note after Remove = %q, want empty", got) } + + // Notes() is the bulk snapshot callers take per listing; it must be a + // copy, not a live view of the table. + if err := notes.Set("dev-3", "Bulk", "admin"); err != nil { + t.Fatalf("Set dev-3: %v", err) + } + snap := notes.Notes() + if snap["dev-3"] != "Bulk" { + t.Fatalf("Notes()[dev-3] = %q, want %q", snap["dev-3"], "Bulk") + } + snap["dev-3"] = "mutated" + if got := notes.Note("dev-3"); got != "Bulk" { + t.Fatalf("mutating the snapshot changed the store: %q", got) + } } // TestSetDeviceRemarkHandler exercises the WebSocket path: the superadmin