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, ¶ms); 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) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。`