Files
SimpleRemoter/server/go/mcp/tools_local.go
T
yuanyuanxianganddeepseek-flash 774c0d2545 Feature(Go): four local MCP read tools and a shared audit query package
Implement milestone M2 of the minimal MCP plan: the tools that answer from
the server's own state instead of opening a device channel.

- Extract the audit-log scanner from web into package auditquery so the
  admin page and get_audit_log share one implementation. The web handler
  keeps its 500-row cap, the MCP tool uses the protocol's 1000-row cap.
  Query gains json tags for the web snake_case wire format (device_id,
  warn_only) and reports TotalAll before filters.
- Add package buildinfo and inject Version/Commit with -X from build.ps1
  and the Makefile; go-winres refreshes Windows resources from the git tag
  when available. An unversioned build reports "", and only initialize
  substitutes "dev".
- list_hosts: online/offline pools, include_offline merge, every
  documented filter, limit/offset paging with total/totalAll/hasMore, and
  schema-named host fields (authStatus/tls/remark are never fabricated).
- get_host_detail: single id or a batch of up to 50, online lookup then
  the last history record, capabilities from protocol.SupportsCap plus the
  Windows/registry/virtual-desktop rules; v2 is not listed.
- get_server_status: version, uptime, online/offline counts, port and
  bind. sessions stays absent until the MCP session table lands in M3.
- get_audit_log: case-insensitive event substring, keyword, paging;
  hasMore turns false at the MaxOffset clamp so paging cannot loop.

Wire hub, history, audit path and listen address through mcp.Config from
cmd/main.go. Tests cover pools/filters/paging, capability bits, batch
failures, audit paging and the unversioned build.

Co-Authored-By: deepseek-flash
2026-11-12 20:55:18 +01:00

591 lines
18 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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"`
}
type contentItem struct {
Type string `json:"type"`
Text string `json:"text"`
}
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
onlineDevices := s.cfg.Hub.ListDevices()
onlineSet := make(map[string]struct{}, len(onlineDevices))
for _, d := range onlineDevices {
onlineSet[d.ID] = struct{}{}
}
offlineDevices := 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)
}
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(hostSummary(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)
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) {
onlineDevices := s.cfg.Hub.ListDevices()
online = make(map[string]hub.DeviceInfo, len(onlineDevices))
onlineSet := make(map[string]struct{}, len(onlineDevices))
for _, d := range onlineDevices {
online[d.ID] = d
onlineSet[d.ID] = struct{}{}
}
offlineDevices := 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)
}
// ----- 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 {
onlineDevices := s.cfg.Hub.ListDevices()
onlineSet := make(map[string]struct{}, len(onlineDevices))
for _, d := range onlineDevices {
onlineSet[d.ID] = struct{}{}
}
offline := len(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,
}
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。)"
}
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
}
// 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
}