package mcp import ( "context" "encoding/json" "fmt" "strconv" "strings" "time" "github.com/yuanyuanxiang/SimpleRemoter/server/go/auditquery" "github.com/yuanyuanxiang/SimpleRemoter/server/go/hub" "github.com/yuanyuanxiang/SimpleRemoter/server/go/protocol" ) // Local read tools: they answer from the server's own state (device hub, // device history, audit file) and never open a channel to a client. The // remote tools (screenshot, files, terminal) live in later milestones. const ( // Page size bounds shared by list_hosts and get_audit_log, matching the // tool descriptions in mcp/tools.json. listDefaultLimit = 100 listMaxLimit = 1000 // batchMaxIDs is the per-call cap for get_host_detail.ids, matching the // Win32 server. batchMaxIDs = 50 ) // toolResult is the MCP tools/call success envelope, byte-compatible with the // Win32 server: one text item plus structuredContent. Failures are JSON-RPC // error objects at the top level, not isError results. type toolResult struct { Content []contentItem `json:"content"` StructuredContent any `json:"structuredContent"` IsError bool `json:"isError"` } // contentItem is one MCP content block. Text tools fill Text; get_screenshot // emits an image block (Data is base64, MimeType image/jpeg), so both the text // and image fields are optional on the wire. type contentItem struct { Type string `json:"type"` Text string `json:"text,omitempty"` Data string `json:"data,omitempty"` MimeType string `json:"mimeType,omitempty"` } func newToolResult(text string, structured any) toolResult { return toolResult{ Content: []contentItem{{Type: "text", Text: text}}, StructuredContent: structured, IsError: false, } } func (s *Server) registerLocalTools() { s.handlers["list_hosts"] = s.callListHosts s.handlers["get_host_detail"] = s.callGetHostDetail s.handlers["get_server_status"] = s.callGetServerStatus s.handlers["get_audit_log"] = s.callGetAuditLog } // decodeArgs unmarshals tools/call arguments into v. An absent/null arguments // object leaves v at its zero value, which is valid for the all-optional tools. func decodeArgs(raw json.RawMessage, v any) *rpcError { if len(raw) == 0 || string(raw) == "null" { return nil } if err := json.Unmarshal(raw, v); err != nil { return errf(CodeInvalidParams, "invalid arguments: %v", err) } return nil } // ----- list_hosts ----------------------------------------------------------- type listHostsArgs struct { ClientType string `json:"client_type"` Group string `json:"group"` IncludeOffline *bool `json:"include_offline"` IP string `json:"ip"` Limit int `json:"limit"` Name string `json:"name"` Offset int `json:"offset"` Online *bool `json:"online"` OS string `json:"os"` Query string `json:"query"` } func (s *Server) callListHosts(_ context.Context, raw json.RawMessage) (any, *rpcError) { if s.cfg.Hub == nil { return nil, errf(CodeInternal, "server device registry is not configured") } var args listHostsArgs if rerr := decodeArgs(raw, &args); rerr != nil { return nil, rerr } // online defaults to true (only online hosts). online=false means "only // offline"; include_offline=true merges history behind the online hosts. online := true if args.Online != nil { online = *args.Online } includeOffline := args.IncludeOffline != nil && *args.IncludeOffline // The offline history must be computed from the FULL online set, not the // ACL-filtered one: otherwise a private device that is currently online // would reappear as an "offline" entry until the outer filter drops it. // Filter once, at the end. onlineAll := s.cfg.Hub.ListDevices() onlineSet := make(map[string]struct{}, len(onlineAll)) for _, d := range onlineAll { onlineSet[d.ID] = struct{}{} } onlineDevices := s.publicDevices(onlineAll) offlineDevices := s.publicDevices(s.offlineDevices(onlineSet)) var pool []hub.DeviceInfo switch { case !online: pool = offlineDevices case includeOffline: pool = make([]hub.DeviceInfo, 0, len(onlineDevices)+len(offlineDevices)) pool = append(pool, onlineDevices...) pool = append(pool, offlineDevices...) default: pool = onlineDevices } totalAll := len(pool) // All filters are optional, ANDed, and substring matches. ASCII case // folding is what the tool description promises; strings.ToLower is a // superset and cannot change an ASCII-only match. q := strings.ToLower(args.Query) nameF := strings.ToLower(args.Name) ipF := strings.ToLower(args.IP) groupF := strings.ToLower(args.Group) osF := strings.ToLower(args.OS) ctF := strings.ToLower(args.ClientType) matched := make([]hub.DeviceInfo, 0, len(pool)) for _, d := range pool { group := d.Group if group == "" { group = "default" } ip := d.IP if ip == "" { ip = d.PeerIP } clientType := "" 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) { continue } if nameF != "" && !strings.Contains(strings.ToLower(d.Name), nameF) { continue } if ipF != "" && !strings.Contains(strings.ToLower(ip), ipF) { continue } if groupF != "" && !strings.Contains(strings.ToLower(group), groupF) { continue } if osF != "" && !strings.Contains(strings.ToLower(d.OS), osF) { continue } if ctF != "" && !strings.Contains(strings.ToLower(clientType), ctF) { continue } matched = append(matched, d) } limit := clampPageLimit(args.Limit) offset := max(args.Offset, 0) total := len(matched) begin := min(offset, total) 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)) } structured := map[string]any{ "hosts": hosts, "total": total, "totalAll": totalAll, "limit": limit, "offset": offset, "hasMore": end < total, } text := pageSummary(total, limit, offset, "台主机") if total != totalAll { text += fmt.Sprintf("过滤前共 %d 台。", totalAll) } text = appendHostRows(text, hosts) return newToolResult(text, structured), nil } // 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 { group := d.Group if group == "" { group = "default" } h := map[string]any{ "id": d.ID, "name": d.Name, "group": group, "online": d.Online, } if d.Version != "" { h["version"] = d.Version } if d.OS != "" { h["os"] = d.OS } ip := d.IP if ip == "" { ip = d.PeerIP } if ip != "" { h["ip"] = ip } if d.Location != "" { h["location"] = d.Location } if d.InstallTime != "" { h["install_time"] = d.InstallTime } if d.Screen != "" { h["screen"] = d.Screen } if d.Online { // RTT 0 means "no heartbeat yet", not "zero latency". if d.RTT > 0 { h["rtt"] = strconv.Itoa(d.RTT) } if d.ActiveWindow != "" { h["activeWindow"] = d.ActiveWindow } if ct := s.clientType(d.ID); ct != "" { h["clientType"] = ct } } else if d.LastSeen > 0 { h["last_seen"] = time.Unix(d.LastSeen, 0).Format("2006-01-02 15:04:05") } return h } // clientType reads the RES_CLIENT_TYPE the client reported at login. It lives // on the main connection's ClientInfo, not on the hub's Device projection. func (s *Server) clientType(deviceID string) string { if s.cfg.Hub == nil { return "" } if ctx := s.cfg.Hub.MainConn(deviceID); ctx != nil { return ctx.GetInfo().ClientType } return "" } // offlineDevices returns history entries that are not currently online. A nil // history store (server started without persistence) yields no entries. func (s *Server) offlineDevices(online map[string]struct{}) []hub.DeviceInfo { if s.cfg.History == nil { return nil } return s.cfg.History.Offline(online) } // ----- get_host_detail ------------------------------------------------------ type getHostDetailArgs struct { ID string `json:"id"` IDs []string `json:"ids"` } func (s *Server) callGetHostDetail(_ context.Context, raw json.RawMessage) (any, *rpcError) { if s.cfg.Hub == nil { return nil, errf(CodeInternal, "server device registry is not configured") } var args getHostDetailArgs if rerr := decodeArgs(raw, &args); rerr != nil { return nil, rerr } if len(args.IDs) > 0 { return s.hostDetailBatch(args.IDs) } if args.ID == "" { return nil, errf(CodeInvalidParams, "Missing required parameter: id or ids") } online, offline := s.hostMaps() host, rerr := s.lookupHost(args.ID, online, offline) if rerr != nil { return nil, rerr } return newToolResult(hostDetailText(host), map[string]any{"host": host}), nil } func (s *Server) hostDetailBatch(ids []string) (any, *rpcError) { if len(ids) > batchMaxIDs { return nil, errf(CodeInvalidParams, "Too many ids: %d (max %d per batch)", len(ids), batchMaxIDs) } online, offline := s.hostMaps() results := make([]map[string]any, 0, len(ids)) succeeded, failed := 0, 0 for _, id := range ids { host, rerr := s.lookupHost(id, online, offline) if rerr != nil { results = append(results, map[string]any{ "id": id, "ok": false, "text": rerr.Message, "error": map[string]any{"code": rerr.Code, "message": rerr.Message}, }) failed++ continue } results = append(results, map[string]any{ "id": id, "ok": true, "text": hostSummary(host), "data": map[string]any{"host": host}, }) succeeded++ } structured := map[string]any{ "tool": "get_host_detail", "total": len(ids), "succeeded": succeeded, "failed": failed, "skipped": 0, // no batch deadline: every id is answered locally "results": results, } text := fmt.Sprintf("批量调用 get_host_detail:共 %d 台,成功 %d 台,失败 %d 台。", len(ids), succeeded, failed) text = appendBatchRows(text, results) return newToolResult(text, structured), nil } // hostMaps indexes the online devices and offline history by ID. Building both // once per call keeps a 50-id batch at one hub snapshot instead of 50. func (s *Server) hostMaps() (online, offline map[string]hub.DeviceInfo) { onlineAll := s.cfg.Hub.ListDevices() onlineSet := make(map[string]struct{}, len(onlineAll)) onlineDevices := s.publicDevices(onlineAll) online = make(map[string]hub.DeviceInfo, len(onlineDevices)) for _, d := range onlineDevices { online[d.ID] = d } // Derive offline entries from the full online set (see callListHosts): // a private online device must not be mistaken for an offline one. for _, d := range onlineAll { onlineSet[d.ID] = struct{}{} } offlineDevices := s.publicDevices(s.offlineDevices(onlineSet)) offline = make(map[string]hub.DeviceInfo, len(offlineDevices)) for _, d := range offlineDevices { offline[d.ID] = d } return online, offline } // 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) { 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["capabilities"] = s.capabilities(d) return h, nil } if d, ok := offline[id]; ok { return s.hostJSON(d), nil } return nil, errf(CodeOffline, "Host not found or offline: %s", id) } // capabilities answers "what can this host do" from the capability hex string // the client reported at login. v2 is deliberately absent: CLIENT_CAP_V2 is // set by every platform, so listing it would only mislead. func (s *Server) capabilities(d hub.DeviceInfo) map[string]any { platform := s.clientType(d.ID) windows := platform != "LNX" && platform != "MAC" && platform != "APK" monitors := monitorCount(d.Screen) // Multi-monitor Windows needs whole-virtual-desktop capture for the // observed and injected coordinate spaces to line up; monitorCount 0 // means the client did not report the "N:W*H" form (legacy) and passes, // matching the Win32 server's remote_open gate. virtualDesktopOK := monitors <= 1 || !windows || protocol.SupportsCap(d.Capability, protocol.ClientCapVirtualDesktop) caps := map[string]any{ "screenPreview": protocol.SupportsCap(d.Capability, protocol.ClientCapScreenPreview), "screenRegion": protocol.SupportsCap(d.Capability, protocol.ClientCapScreenRegion), "windowInfo": protocol.SupportsCap(d.Capability, protocol.ClientCapWindowInfo), "fileTransferV2": protocol.SupportsCap(d.Capability, protocol.ClientCapV2), "c2cPaths": protocol.SupportsCap(d.Capability, protocol.ClientCapC2CPaths), "registry": windows, "remoteControl": (windows || platform == "LNX" || platform == "APK") && virtualDesktopOK, } if platform != "" { caps["platform"] = platform } return caps } // hostSummary is the human-readable text item for one host. func hostSummary(h map[string]any) string { name, _ := h["name"].(string) ip, _ := h["ip"].(string) if online, _ := h["online"].(bool); !online { return fmt.Sprintf("主机 %s (%s) 当前离线,以下为其最后一次登录时的记录。", name, ip) } return fmt.Sprintf("主机 %s (%s) 的详情。", name, ip) } // hostDetailText is the text block for one host: the summary line followed by // the host object as compact JSON. Text-only MCP clients never surface // structuredContent, so without this they would see neither the id nor any // field of the host they just asked about. func hostDetailText(h map[string]any) string { summary := hostSummary(h) b, err := json.Marshal(h) if err != nil { return summary } return summary + "\n" + string(b) } // appendHostRows renders the returned page as a tab-separated table. The host // id comes first because every follow-up tool (read_file, get_host_detail, // terminal_exec, ...) is addressed by it. func appendHostRows(text string, hosts []map[string]any) string { rows := make([][]string, 0, len(hosts)) 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"]), }) } return appendRows(text, []string{"id", "name", "ip", "group", "os", "online", "clientType", "last_seen"}, rows) } // appendBatchRows lists each batch result on its own line: failures carry the // error message, successes the full host JSON. func appendBatchRows(text string, results []map[string]any) string { rows := make([][]string, 0, len(results)) for _, r := range results { ok, _ := r["ok"].(bool) var detail string if ok { if data, _ := r["data"].(map[string]any); data != nil { if b, err := json.Marshal(data["host"]); err == nil { detail = string(b) } } } else { detail, _ = r["text"].(string) } rows = append(rows, []string{tableText(r["id"]), strconv.FormatBool(ok), detail}) } return appendRows(text, []string{"id", "ok", "detail"}, rows) } // ----- get_server_status ---------------------------------------------------- func (s *Server) callGetServerStatus(_ context.Context, _ json.RawMessage) (any, *rpcError) { uptime := max(int64(time.Since(s.cfg.StartedAt).Seconds()), 0) status := map[string]any{ "version": s.cfg.Version, "uptime_sec": uptime, } text := fmt.Sprintf("YAMA Go 服务端已运行 %d 秒", uptime) if s.cfg.Version != "" { text = fmt.Sprintf("YAMA Go 服务端 %s 已运行 %d 秒", s.cfg.Version, uptime) } if s.cfg.Hub != nil { onlineAll := s.cfg.Hub.ListDevices() onlineSet := make(map[string]struct{}, len(onlineAll)) for _, d := range onlineAll { onlineSet[d.ID] = struct{}{} } onlineDevices := s.publicDevices(onlineAll) offline := len(s.publicDevices(s.offlineDevices(onlineSet))) status["hosts"] = map[string]any{"online": len(onlineDevices), "offline": offline} text += fmt.Sprintf(";在线 %d 台,离线 %d 台", len(onlineDevices), offline) } // MCP is mounted on the web server, so its listening address is the web // server's. Port/bind stay absent when the caller did not provide them. if s.cfg.Port > 0 { status["port"] = s.cfg.Port } if s.cfg.Bind != "" { status["bind"] = s.cfg.Bind text += ",监听 " + s.cfg.Bind } // The status fields are flat in structuredContent (the outputSchema has no // "status" wrapper object). return newToolResult(text+"。", status), nil } // ----- get_audit_log -------------------------------------------------------- type getAuditLogArgs struct { Keyword string `json:"keyword"` Limit int `json:"limit"` Offset int `json:"offset"` Type string `json:"type"` } func (s *Server) callGetAuditLog(_ context.Context, raw json.RawMessage) (any, *rpcError) { if s.cfg.AuditPath == "" { return nil, errf(CodeInternal, "audit log file is disabled on this server (YAMA_AUDIT_LOG=off)") } var args getAuditLogArgs if rerr := decodeArgs(raw, &args); rerr != nil { return nil, rerr } q := auditquery.Query{ Keyword: args.Keyword, // The tool's "type" column is a case-insensitive substring of the // event name; the web UI's exact/prefix Event filter does not fit. EventContains: args.Type, } // Audit records name their target device. A device bound to a web user is // invisible to MCP, so its activity must not leak through the log either. q.DeviceAllowed = s.ownerChecker() q.Limit = auditquery.ClampLimit(args.Limit, auditquery.MaxLimit) q.Offset = auditquery.ClampOffset(args.Offset) res, err := auditquery.Scan(s.cfg.AuditPath, q) if err != nil { return nil, errf(CodeInternal, "failed to read audit log: %v", err) } entries := make([]map[string]any, 0, len(res.Events)) for _, rec := range res.Events { entries = append(entries, map[string]any{ "type": auditquery.StringField(rec, "event"), "time": auditquery.StringField(rec, "time"), "msg": auditMessage(rec), }) } // Scan caps Offset at auditquery.MaxOffset, so a page that reaches that // point must not advertise a next page: the follow-up offset would be // clamped back and return the same records forever. reached := q.Offset + len(entries) structured := map[string]any{ "entries": entries, "total": res.Total, "totalAll": res.TotalAll, "limit": q.Limit, "offset": q.Offset, "hasMore": reached < res.Total && reached < auditquery.MaxOffset, } text := pageSummary(res.Total, q.Limit, q.Offset, "条日志") if res.Total != res.TotalAll { text += fmt.Sprintf("过滤前共 %d 条。", res.TotalAll) } if res.Truncated { text += "(审计文件较大,仅扫描最近 32 MB。)" } rows := make([][]string, 0, len(entries)) for _, e := range entries { rows = append(rows, []string{tableText(e["time"]), tableText(e["type"]), tableText(e["msg"])}) } text = appendRows(text, []string{"time", "type", "msg"}, rows) return newToolResult(text, structured), nil } // auditMessage renders the non-envelope fields as compact JSON. The web audit // page shows the raw record; the MCP entry has dedicated type/time columns, so // repeating them inside msg would only add noise. func auditMessage(rec map[string]any) string { rest := make(map[string]any, len(rec)) for k, v := range rec { switch k { case "audit", "level", "time", "event": continue } rest[k] = v } if len(rest) == 0 { return "" } b, err := json.Marshal(rest) if err != nil { return "" } return string(b) } // ----- shared helpers ------------------------------------------------------- func clampPageLimit(n int) int { if n <= 0 { return listDefaultLimit } if n > listMaxLimit { return listMaxLimit } return n } // appendRows appends a tab-separated table to a summary line. The first // column is always the addressable key (host id, file name, ...), because a // text-only client sees only content[].text and needs the key for the next // call. structuredContent remains the authoritative, exact copy. func appendRows(text string, header []string, rows [][]string) string { if len(rows) == 0 { return text } var b strings.Builder b.WriteString(text) b.WriteByte('\n') b.WriteString(strings.Join(header, "\t")) for _, row := range rows { b.WriteByte('\n') for i, cell := range row { if i > 0 { b.WriteByte('\t') } b.WriteString(oneLine(cell)) } } return b.String() } // tableText extracts a string field. An absent field yields "", which oneLine // renders as "-". func tableText(v any) string { s, _ := v.(string) return s } // oneLine keeps a table cell on one line: a tab or newline inside a value // would break the column layout. The exact value stays in structuredContent. func oneLine(s string) string { if s == "" { return "-" } return strings.NewReplacer("\t", " ", "\r", " ", "\n", " ").Replace(s) } // pageSummary mirrors the Win32 server's summary line: // 「共 N 台主机,本次返回第 1-100 条(还有更多,可用 offset 继续取)。」 func pageSummary(total, limit, offset int, unit string) string { out := fmt.Sprintf("共 %d %s", total, unit) if total == 0 { return out + "。" } begin := min(offset, total) if begin >= total { return out + ",offset 超出范围,本次返回 0 条。" } end := min(begin+limit, total) out += fmt.Sprintf(",本次返回第 %d-%d 条", begin+1, end) if end < total { out += "(还有更多,可用 offset 继续取)" } return out + "。" } // isDecimalID reports whether id is a non-empty decimal string. Host IDs are // uint64 rendered in decimal; anything else is a caller mistake. func isDecimalID(id string) bool { if id == "" { return false } for _, r := range id { if r < '0' || r > '9' { return false } } return true } // monitorCount parses the "N:W*H" screen string the client reports. 0 means // "not reported / not in that form". func monitorCount(screen string) int { i := strings.IndexByte(screen, ':') if i <= 0 { return 0 } n, err := strconv.Atoi(strings.TrimSpace(screen[:i])) if err != nil || n < 0 { return 0 } return n }