Files
SimpleRemoter/server/go/mcp/server.go
T
yuanyuanxianganddeepseek-flash 9ce1a58bc3 Feature(Go): read_file over the V2 stream receiver
read_file reuses the list_files handshake: COMMAND_LIST_DRIVE opens the
file-manager sub-conn, which then gets
[CMD_DOWN_FILES_V2][targetDir\0][path\0][\0] and streams
COMMAND_SEND_FILE_V2 chunks plus a COMMAND_FILE_COMPLETE_V2 carrying the
whole-file SHA-256. Windows clients open a fresh authenticated sub-conn
for the chunks; POSIX clients stream on the file-manager conn itself, so
that conn is retired when the call ends rather than right after the
request. TOKEN_DOWNLOAD_ERROR on the file-manager conn maps to -32009 /
-32010 / -32000 like the Win32 server.

Bytes land only in a per-call os.MkdirTemp dir; the client name is
checked against the target dir (separator-normalised, path.Clean, so
..\.., absolute, UNC and mixed separators are refused) as
defence-in-depth, never used as a path. First chunk enforces the size
gate (ReadMax) and rejects multi-file batches, so an expanded directory
fails with -32602 instead of returning its first file. Chunks from a
sub-conn opened for an earlier call are dropped by connection ID, data
sub-conns are closed when the call ends, and a closed sub-conn fails the
call fast instead of waiting for the stall watchdog.

Text windowing, encoding detection (BOM / UTF-8 / GBK / explicit /
latin1) and EOL handling mirror McpServer.cpp. Verified with the Debug
ghost on Windows 11 and the WSL Ubuntu ghost: .env text plus newline is
byte-identical, sha256 equals SHA-256 over the file, windows/GBK/empty/
max_bytes/directory/size-gate/missing-path/POSIX-path cases all pass.

Co-Authored-By: deepseek-flash
2026-11-12 23:04:35 +01:00

416 lines
16 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 (
"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
)
// 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
}
// 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 != "" }
// 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)
}
// 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 主机不支持该能力(换主机或换工具,改参数无用);-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) 列表与详情都是调用时刻的快照,主机可能在操作期间掉线;写操作前先读一次现状,动作后再复核。`