Files
SimpleRemoter/server/go/mcp/server.go
T
yuanyuanxianganddeepseek-flash 5f764b2425 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
2026-11-27 14:51:15 +01:00

522 lines
21 KiB
Go

package mcp
import (
"bytes"
"context"
"crypto/subtle"
"encoding/json"
"errors"
"io"
"net/http"
"runtime/debug"
"strings"
"sync"
"time"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/devicehistory"
"github.com/yuanyuanxiang/SimpleRemoter/server/go/hub"
"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
// termSweepInterval is how often the reaper looks for sessions a model
// forgot to close. The sweep itself is cheap: one mutex per session.
termSweepInterval = 30 * time.Second
)
// DeviceOwner reports the owner of a device. The web console's DeviceACL
// implements it; declared here as an interface so the MCP package does not
// import the web package.
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.
type deviceOwnerSnapshotter interface {
Owners() map[string]string
}
// ownerChecker returns a predicate for "is this device public?" that borrows a
// single snapshot when the ACL supports it, so scanning thousands of audit
// records does not contend with an in-flight bind's write lock.
func (s *Server) ownerChecker() func(deviceID string) bool {
if s.cfg.DeviceACL == nil {
return nil
}
if snap, ok := s.cfg.DeviceACL.(deviceOwnerSnapshotter); ok {
owners := snap.Owners()
return func(id string) bool { return owners[id] == "" }
}
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 {
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
// Server-side state the local read tools answer from. A nil Hub means the
// endpoint was built without a device registry: the host tools then fail
// with -32000 instead of reporting an empty (and misleading) list.
Hub *hub.Hub
History *devicehistory.Store // nil: no offline history to merge
AuditPath string // "" = audit file disabled (YAMA_AUDIT_LOG=off)
Port int // web/MCP listening port, for get_server_status
Bind string // listening address, for get_server_status
// DeviceACL, when non-nil, hides devices bound to a web user. MCP only
// operates public devices (product decision): a bound device is invisible
// 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
// 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
// locks serialises device operations; sem bounds the global in-flight
// tools/call count. Both are non-blocking: contention is -32003, not a
// queue, so a slow call cannot pile up requests behind it (design §9).
locks *deviceLocks
sem chan struct{}
sessions *sessionTable
previews *previewTable // in-flight get_screenshot requests, keyed by device
files *fileTable // in-flight list_files requests, keyed by device
transfers *transferTable // in-flight read_file V2 transfers, keyed by device
// stop ends the idle reaper and reaperDone reports that it returned;
// closeOnce makes Close idempotent (tests call it both explicitly and from
// Cleanup). reaperDone is nil when no reaper was started (hub-less server).
stop chan struct{}
reaperDone chan struct{}
closeOnce sync.Once
}
// 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()
}
// Version is left exactly as injected: it may be empty in a build without
// git/ldflags. The initialize response substitutes "dev" for such builds;
// get_server_status reports the empty string rather than inventing a
// version (design §3.2).
if cfg.Log == nil {
cfg.Log = logger.New(logger.Config{Level: logger.LevelError})
}
s := &Server{
cfg: cfg,
log: cfg.Log,
tools: buildToolSet(toolsJSON),
handlers: make(map[string]toolFunc),
locks: newDeviceLocks(),
sem: make(chan struct{}, cfg.MaxConcurrency),
previews: newPreviewTable(),
files: newFileTable(),
transfers: newTransferTable(),
stop: make(chan struct{}),
}
if cfg.Hub != nil {
s.sessions = newSessionTable(cfg.Hub)
} else {
s.sessions = newSessionTable(nil)
}
s.registerLocalTools()
s.registerScreenTools()
s.registerFileTools()
s.registerTerminalTools()
if cfg.Hub != nil {
// No hub means no shell can ever be opened, so there is nothing to
// reap; skipping the goroutine keeps hub-less servers inert.
s.reaperDone = make(chan struct{})
go s.sweepLoop()
}
return s
}
// 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 != "" }
// devicePrivate reports whether the device is bound to a web user. MCP only
// operates public devices; bound devices are hidden and unreachable here even
// though the endpoint's static token is effectively an admin credential.
func (s *Server) devicePrivate(deviceID string) bool {
return s.cfg.DeviceACL != nil && s.cfg.DeviceACL.Owner(deviceID) != ""
}
// denyPrivateDevice returns the same error shape as an offline host so a
// private device is indistinguishable from one that does not exist.
func (s *Server) denyPrivateDevice(deviceID string) *rpcError {
if s.devicePrivate(deviceID) {
return errf(CodeOffline, "Host not found or offline: %s", deviceID)
}
return nil
}
// publicDevices filters a device snapshot down to the ones MCP may expose.
func (s *Server) publicDevices(devices []hub.DeviceInfo) []hub.DeviceInfo {
if s.cfg.DeviceACL == nil {
return devices
}
out := make([]hub.DeviceInfo, 0, len(devices))
for _, d := range devices {
if s.cfg.DeviceACL.Owner(d.ID) == "" {
out = append(out, d)
}
}
return out
}
// Close releases resources held by long-lived tool state: the reaper stops and
// every terminal session MCP owns is torn down and the shell told to exit.
func (s *Server) Close() {
s.closeOnce.Do(func() {
close(s.stop)
if s.reaperDone != nil {
<-s.reaperDone
}
s.sessions.closeAll()
})
}
// sweepLoop reclaims terminal sessions nobody closed. The interval shrinks to
// TermIdle when that is shorter, so a test (or a deliberately tiny idle knob)
// sees the sweep fire on schedule instead of up to 30 s late.
func (s *Server) sweepLoop() {
defer close(s.reaperDone)
ticker := time.NewTicker(min(termSweepInterval, s.cfg.TermIdle))
defer ticker.Stop()
for {
select {
case <-s.stop:
return
case now := <-ticker.C:
s.sessions.sweepIdle(now, s.cfg.TermIdle)
}
}
}
// 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 {
// "dev" is a serverInfo-only marker for an unversioned build; the status
// tool keeps the raw (empty) value.
version := s.cfg.Version
if version == "" {
version = "dev"
}
return initializeResult{
ProtocolVersion: protocolVersion,
Capabilities: serverCapabilities{Tools: toolsCapability{ListChanged: false}},
ServerInfo: serverInfo{Name: "yama", Version: version},
Instructions: serverInstructions,
}
}
// callTool parses tools/call, enforces visibility, takes the concurrency and
// device gates, then hands the raw arguments to the handler. Readonly mode
// refuses hidden write tools with -32006 rather than pretending they do not
// exist. Every call that names a tool is audited, including rejected ones.
func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (result any, rerr *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")
}
start := time.Now()
deviceID := ""
if !localReadTools[params.Name] {
deviceID = deviceIDFromArgs(params.Arguments)
}
defer func() {
// Convert a handler panic into -32000 instead of letting net/http drop
// the connection, and make sure the audit record says the call failed:
// without this the zero-valued rerr would be logged as success.
if p := recover(); p != nil {
s.log.Error("panic in MCP tool %s: %v\n%s", params.Name, p, debug.Stack())
result = nil
rerr = errf(CodeInternal, "internal error in tool %s", params.Name)
}
s.auditCall(params.Name, deviceID, params.Arguments, result, rerr, time.Since(start))
}()
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)
}
// A device bound to a web user is invisible to MCP (product policy). Enforce
// it once here for every single-host tool so a new tool cannot forget the
// check; batch id[] spellings are checked by their per-host handler
// (listFilesOne / hostMaps).
if rerr := s.denyPrivateDevice(deviceID); rerr != nil {
return nil, rerr
}
// Global slot first: a call that would be rejected for concurrency must
// not squat on a device lock while it fails.
select {
case s.sem <- struct{}{}:
defer func() { <-s.sem }()
default:
return nil, errf(CodeBusy, "Server busy: too many concurrent MCP calls (limit %d)",
s.cfg.MaxConcurrency)
}
if deviceID != "" && !unlockedTools[params.Name] {
held, acquired := s.locks.tryAcquire(deviceID, params.Name)
if !acquired {
return nil, errf(CodeBusy, "%s", busyMessage(held))
}
defer s.locks.release(deviceID)
}
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 主机不支持该能力(换主机或换工具,改参数无用;老客户端不声明 CLIENT_CAP_V2 时 read_file 也返回 -32005,需升级客户端);-32006 只读模式拒绝(terminal_exec / terminal_close;重试无效,需管理员关掉只读);-32001 多为超时,也可能是工具自身失败或已被取消:工具支持 timeout_ms 时先加大重试一次;子连接/会话没建立或同一主机反复超时通常重试无效(主机卡住、链路断或老客户端不认命令);message 写 Request cancelled 的表示客户端已中止,可直接重试;-32602 参数错误(按 message 修正)。
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) 本实现不维护授权状态与 TLS 标记:list_hosts / get_host_detail 不返回 authStatus/tls;备注(remark)由 Web 控制台维护,设置后会随主机返回,query 也匹配备注。get_server_status 只报版本、在线台数与监听地址,没有 switches/sessions。
8) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。`