Files
reims-agent/internal/mcp/server.go
T
千川白浪andClaude Opus 5.5 d682620fe5 feat(mcp)!: 工具设计范式更新到 0.2.0 (#6)
Serve six computer-use tools on the mcp channel and add the guest,
restore point, clone and test tools on a new mcp-dev channel.

- vm_power replaces vm_start, vm_shutdown, vm_suspend and vm_resume and adds
  force_stop.
- screen replaces the screenshot and zoom actions and wait_for_screen: it can
  wait for a change or a stable frame (up to 180 s while booting) and return
  one region at up to source resolution.
- computer_input replaces computer and computer_batch: it checks every step
  before sending input, holds modifiers around pointer actions, stops on a
  wait_screen timeout, and releases held keys and buttons on success, error
  or cancellation.
- Coordinates follow the last full image returned, so scaled screenshots no
  longer misplace clicks; results report the image size and a short sha256
  as compact JSON and structuredContent.
- Calls on one VM run in order instead of all tools sharing one lock;
  request ids and cancellation are scoped per client connection, and a
  closed connection cancels its calls.
- guest_wait_ready returns the plugin public key; logs_read pages guest and
  test logs; test_wait returns the result once finished; sessions and test
  runs always use a clone. Removed the screen resource.
- Tools carry annotations and one-sentence descriptions, and arguments the
  schema does not name are refused.

Requires a Reims-Go host with region screenshots, held-key input,
host/console.release and forced shutdown.

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:52:45 -07:00

646 lines
18 KiB
Go

package mcp
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/reims-go/reims-agent/internal/guest"
)
const (
protocolVersion = "2025-06-18"
serverVersion = "0.2.0"
// ChannelCore serves the computer-use tools; ChannelDev adds guest,
// snapshot and test tools.
ChannelCore = "mcp"
ChannelDev = "mcp-dev"
)
type Host interface {
Call(context.Context, string, any, any) error
}
type Server struct {
host Host
guest *guest.SSH
root string
state *agentState
screens *screenCache
logw io.Writer
callsMu sync.Mutex
calls map[callKey]context.CancelFunc
vmMu sync.Mutex
vmLocks map[string]chan struct{}
}
// callKey scopes a request id to the client connection that sent it, since
// two clients may use the same ids.
type callKey struct {
session string
id string
}
type request struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Method string `json:"method"`
Params json.RawMessage `json:"params"`
}
type response struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id"`
Result any `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type hostReply struct {
Data string `json:"data"`
MIMEType string `json:"mime_type"`
Width int `json:"width"`
Height int `json:"height"`
SourceWidth int `json:"source_width"`
SourceHeight int `json:"source_height"`
Blank bool `json:"blank"`
Region *region `json:"region"`
Characters int `json:"characters"`
VMs []any `json:"vms"`
OK bool `json:"ok"`
}
func New() *Server {
root, err := os.Getwd()
if err != nil {
root = "."
}
root = filepath.Clean(root)
return &Server{
guest: guest.NewSSH(root),
root: root,
state: newAgentState(root),
calls: make(map[callKey]context.CancelFunc),
vmLocks: make(map[string]chan struct{}),
screens: newScreenCache(),
logw: os.Stderr,
}
}
func (s *Server) logToolCall(name string, dur time.Duration, status string) {
w := s.logw
if w == nil {
w = os.Stderr
}
_, _ = fmt.Fprintf(w, "tools/call %s %d %s\n", name, dur.Milliseconds(), status)
}
func (s *Server) BindHost(host Host) { s.host = host }
// Handle answers one MCP message from a client connection.
func (s *Server) Handle(ctx context.Context, channel, session string, raw json.RawMessage) (json.RawMessage, error) {
if channel != ChannelCore && channel != ChannelDev {
return nil, fmt.Errorf("unknown channel %q", channel)
}
dev := channel == ChannelDev
var req request
if err := json.Unmarshal(raw, &req); err != nil {
return nil, err
}
if req.JSONRPC != "2.0" || strings.TrimSpace(req.Method) == "" {
return marshal(response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{Code: -32600, Message: "invalid JSON-RPC request"}})
}
if len(req.ID) == 0 {
if req.Method == "notifications/cancelled" {
var params struct {
RequestID json.RawMessage `json:"requestId"`
}
if json.Unmarshal(req.Params, &params) == nil && validRequestID(params.RequestID) {
s.cancelRequest(callKey{session, string(params.RequestID)})
}
}
return json.RawMessage("null"), nil
}
if !validRequestID(req.ID) {
return marshal(response{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{Code: -32600, Message: "request id must be a string or number"}})
}
if ctx == nil {
ctx = context.Background()
}
if req.Method == "tools/call" {
key := callKey{session, string(req.ID)}
requestCtx, cancel, ok := s.beginRequest(ctx, key)
if !ok {
return marshal(response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{Code: -32600, Message: "request id is already active"}})
}
defer s.finishRequest(key, cancel)
ctx = requestCtx
}
result, err := s.dispatch(ctx, dev, req.Method, req.Params)
if ctx.Err() != nil {
return marshal(response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{Code: -32800, Message: "request cancelled"}})
}
if err != nil {
code := -32000
switch {
case errors.Is(err, errUnknownMethod):
code = -32601
case errors.Is(err, errInvalidParams):
code = -32602
case errors.Is(err, context.Canceled):
code = -32800
}
return marshal(response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{Code: code, Message: err.Error()}})
}
return marshal(response{JSONRPC: "2.0", ID: req.ID, Result: result})
}
// SessionClosed cancels every call still running for a client connection
// that has ended. Each cancelled input call releases what it holds.
func (s *Server) SessionClosed(_ string, session string) {
s.callsMu.Lock()
var cancels []context.CancelFunc
for key, cancel := range s.calls {
if key.session == session {
cancels = append(cancels, cancel)
}
}
s.callsMu.Unlock()
for _, cancel := range cancels {
cancel()
}
}
func validRequestID(raw json.RawMessage) bool {
if len(raw) == 0 {
return false
}
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.UseNumber()
var value any
if err := decoder.Decode(&value); err != nil {
return false
}
switch value.(type) {
case string, json.Number:
return true
default:
return false
}
}
func (s *Server) beginRequest(parent context.Context, key callKey) (context.Context, context.CancelFunc, bool) {
requestCtx, cancel := context.WithCancel(parent)
s.callsMu.Lock()
defer s.callsMu.Unlock()
if _, exists := s.calls[key]; exists {
cancel()
return nil, nil, false
}
s.calls[key] = cancel
return requestCtx, cancel, true
}
func (s *Server) finishRequest(key callKey, cancel context.CancelFunc) {
s.callsMu.Lock()
delete(s.calls, key)
s.callsMu.Unlock()
cancel()
}
func (s *Server) cancelRequest(key callKey) {
s.callsMu.Lock()
cancel := s.calls[key]
s.callsMu.Unlock()
if cancel != nil {
cancel()
}
}
// lockVM serializes display and input work on one VM. Waiting for the lock
// ends when the call is cancelled.
func (s *Server) lockVM(ctx context.Context, vm string) (func(), error) {
key := strings.ToLower(strings.TrimSpace(vm))
s.vmMu.Lock()
sem := s.vmLocks[key]
if sem == nil {
sem = make(chan struct{}, 1)
s.vmLocks[key] = sem
}
s.vmMu.Unlock()
select {
case sem <- struct{}{}:
return func() { <-sem }, nil
case <-ctx.Done():
return nil, ctx.Err()
}
}
var (
errUnknownMethod = errors.New("unknown MCP method")
errInvalidParams = errors.New("invalid MCP parameters")
)
func (s *Server) dispatch(ctx context.Context, dev bool, method string, raw json.RawMessage) (any, error) {
switch method {
case "initialize":
return map[string]any{
"protocolVersion": protocolVersion,
"capabilities": map[string]any{"tools": map[string]any{"listChanged": false}},
"serverInfo": map[string]any{"name": "reims-agent", "version": serverVersion},
}, nil
case "ping":
return map[string]any{}, nil
case "tools/list":
return map[string]any{"tools": toolList(dev)}, nil
case "tools/call":
return s.callTool(ctx, dev, raw)
default:
return nil, fmt.Errorf("%w: %s", errUnknownMethod, method)
}
}
func (s *Server) callTool(ctx context.Context, dev bool, raw json.RawMessage) (any, error) {
var req struct {
Name string `json:"name"`
Arguments json.RawMessage `json:"arguments"`
}
if err := json.Unmarshal(raw, &req); err != nil || strings.TrimSpace(req.Name) == "" {
return nil, fmt.Errorf("%w: tool name is required", errInvalidParams)
}
tool, ok := lookupTool(req.Name, dev)
if !ok {
return toolError(fmt.Sprintf("unknown tool %q", req.Name)), nil
}
if s.host == nil {
s.logToolCall(req.Name, 0, "error")
return toolError("Reims-Go host is unavailable"), nil
}
started := time.Now()
if tool.locksVM {
var target struct {
VM string `json:"vm"`
}
_ = json.Unmarshal(req.Arguments, &target)
if strings.TrimSpace(target.VM) == "" {
return toolError("vm is required"), nil
}
unlock, err := s.lockVM(ctx, target.VM)
if err != nil {
return nil, err
}
defer unlock()
}
result, err := s.invoke(ctx, req.Name, req.Arguments)
dur := time.Since(started)
if err != nil {
if errors.Is(err, context.DeadlineExceeded) {
s.logToolCall(req.Name, dur, "timeout")
} else {
s.logToolCall(req.Name, dur, "error")
}
if errors.Is(err, context.Canceled) {
return nil, err
}
return toolError(err.Error()), nil
}
status := "ok"
if m, ok := result.(map[string]any); ok {
if isErr, _ := m["isError"].(bool); isErr {
status = "error"
} else if info, ok := m["structuredContent"].(map[string]any); ok && info["timed_out"] == true {
status = "timeout"
}
}
s.logToolCall(req.Name, dur, status)
return result, nil
}
func toolError(message string) map[string]any {
return map[string]any{"isError": true, "content": []any{map[string]any{"type": "text", "text": message}}}
}
func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) (any, error) {
switch name {
case "vm_list":
var out hostReply
if err := s.host.Call(ctx, "host/vm.list", nil, &out); err != nil {
return nil, err
}
return textResult(out.VMs), nil
case "vm_get":
var args struct {
VM string `json:"vm"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
var out map[string]any
if err := s.host.Call(ctx, "host/vm.get", args, &out); err != nil {
return nil, err
}
return textResult(out), nil
case "vm_power":
return s.vmPower(ctx, raw)
case "vm_unlock":
return s.vmUnlock(ctx, raw)
case "screen":
return s.screenTool(ctx, raw)
case "computer_input":
return s.computerInput(ctx, raw)
case "guest_wait_ready":
return s.guestWaitReady(ctx, raw)
case "guest_trust_host":
var args struct {
VM string `json:"vm"`
Fingerprint string `json:"fingerprint"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
if args.Fingerprint == "" {
return nil, fmt.Errorf("%w: fingerprint is required", errInvalidParams)
}
address, _, err := s.guestAddress(ctx, args.VM)
if err != nil {
return nil, err
}
if err := s.guest.TrustHostKeyContext(ctx, args.VM, address, args.Fingerprint); err != nil {
return nil, err
}
return textResult(map[string]any{"trusted": true, "fingerprint": args.Fingerprint}), nil
case "guest_exec":
var args struct {
VM string `json:"vm"`
Command string `json:"command"`
CWD string `json:"cwd"`
Env map[string]string `json:"env"`
TimeoutMS int `json:"timeout_ms"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
address, username, err := s.guestAddress(ctx, args.VM)
if err != nil {
return nil, err
}
if args.TimeoutMS == 0 {
args.TimeoutMS = 900000
}
result, err := s.guest.Exec(ctx, args.VM, address, username, args.Command, args.CWD, args.Env, time.Duration(args.TimeoutMS)*time.Millisecond)
if err != nil {
return nil, err
}
return textResult(result), nil
case "guest_put":
var args struct {
VM string `json:"vm"`
LocalPath string `json:"local_path"`
RemotePath string `json:"remote_path"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
address, username, err := s.guestAddress(ctx, args.VM)
if err != nil {
return nil, err
}
result, err := s.guest.Put(ctx, args.VM, address, username, args.LocalPath, args.RemotePath)
if err != nil {
return nil, err
}
return textResult(result), nil
case "guest_get":
var args struct {
VM string `json:"vm"`
RemotePath string `json:"remote_path"`
LocalPath string `json:"local_path"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
address, username, err := s.guestAddress(ctx, args.VM)
if err != nil {
return nil, err
}
result, err := s.guest.Get(ctx, args.VM, address, username, args.RemotePath, args.LocalPath)
if err != nil {
return nil, err
}
return textResult(result), nil
case "session_create":
var args struct {
VM string `json:"vm"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
result, err := s.createSession(ctx, args.VM)
if err != nil {
return nil, err
}
return textResult(result), nil
case "session_dispose":
var args struct {
SessionID string `json:"session_id"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
if strings.TrimSpace(args.SessionID) == "" {
return nil, fmt.Errorf("%w: session_id is required", errInvalidParams)
}
if err := s.disposeSession(ctx, args.SessionID); err != nil {
return nil, err
}
return textResult(map[string]any{"ok": true}), nil
case "snapshot_list", "snapshot_create", "snapshot_restore":
return s.snapshotTool(ctx, name, raw)
case "test_run":
return s.startTestRun(ctx, raw)
case "test_wait":
return s.waitTestRun(ctx, raw)
case "test_cancel":
return s.cancelTestRun(raw)
case "logs_read":
return s.readLogs(raw)
default:
return nil, fmt.Errorf("unknown tool %q", name)
}
}
func (s *Server) guestWaitReady(ctx context.Context, raw json.RawMessage) (any, error) {
var args struct {
VM string `json:"vm"`
TimeoutMS int `json:"timeout_ms"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
if args.TimeoutMS == 0 {
args.TimeoutMS = 10000
}
if args.TimeoutMS < 1 || args.TimeoutMS > 30000 {
return nil, fmt.Errorf("%w: timeout_ms must be between 1 and 30000", errInvalidParams)
}
address, username, err := s.guestAddress(ctx, args.VM)
if err != nil {
return nil, err
}
result, err := s.guest.WaitReady(ctx, args.VM, address, username, time.Duration(args.TimeoutMS)*time.Millisecond)
if err != nil {
return nil, err
}
publicKey, err := s.guest.PublicKey()
if err != nil {
return nil, err
}
result["plugin_public_key"] = strings.TrimSpace(publicKey)
return textResult(result), nil
}
func (s *Server) guestAddress(ctx context.Context, ref string) (string, string, error) {
if strings.TrimSpace(ref) == "" {
return "", "", fmt.Errorf("%w: vm is required", errInvalidParams)
}
vm, err := s.vmInfo(ctx, ref)
if err != nil {
return "", "", err
}
portValue, ok := vm["ssh_port"].(float64)
if !ok || portValue < 1 || portValue > 65535 {
return "", "", errors.New("ssh_unavailable: SSH port forwarding is not enabled for this VM")
}
username, _ := vm["ssh_username"].(string)
return net.JoinHostPort("127.0.0.1", fmt.Sprint(int(portValue))), username, nil
}
func (s *Server) vmInfo(ctx context.Context, ref string) (map[string]any, error) {
var vm map[string]any
if err := s.host.Call(ctx, "host/vm.get", map[string]string{"vm": ref}, &vm); err != nil {
return nil, err
}
phase, _ := vm["phase"].(string)
if phase != "" && !strings.EqualFold(phase, "normal") {
return nil, fmt.Errorf("confirmation_required: VM %q is in %s phase", ref, phase)
}
return vm, nil
}
var powerMethods = map[string]string{
"start": "host/vm.start",
"shutdown": "host/vm.shutdown",
"force_stop": "host/vm.shutdown",
"suspend": "host/vm.suspend",
"resume": "host/vm.resume",
}
func (s *Server) vmPower(ctx context.Context, raw json.RawMessage) (any, error) {
var args struct {
VM string `json:"vm"`
Action string `json:"action"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
method, ok := powerMethods[args.Action]
if !ok {
return nil, fmt.Errorf("%w: action must be start, shutdown, force_stop, suspend or resume", errInvalidParams)
}
params := map[string]any{"vm": args.VM}
if args.Action == "force_stop" {
params["force"] = true
}
var out hostReply
if err := s.host.Call(ctx, method, params, &out); err != nil {
return nil, err
}
return textResult(map[string]any{"ok": true, "action": args.Action}), nil
}
const (
unlockTimeoutMS = 20000
unlockStableMS = 1500
)
func (s *Server) vmUnlock(ctx context.Context, raw json.RawMessage) (any, error) {
var args struct {
VM string `json:"vm"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
// The wait below needs the login screen as its baseline so it can tell
// when the desktop has replaced it.
baseline, ok := s.screens.lastFrame(args.VM)
if !ok {
_, frame, err := s.capture(ctx, args.VM, 1)
if err != nil {
return nil, err
}
baseline = frame
}
var typed hostReply
if err := s.host.Call(ctx, "host/console.typeSecret", map[string]any{"vm": args.VM, "setting": "login_password"}, &typed); err != nil {
return nil, fmt.Errorf("cannot enter the login password: %w", err)
}
var key hostReply
if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": "ret"}, &key); err != nil {
return nil, err
}
out, err := s.waitScreen(ctx, waitOptions{
VM: args.VM,
Baseline: baseline,
Until: "change_then_stable",
TimeoutMS: unlockTimeoutMS,
StableMS: unlockStableMS,
Scale: 1,
})
if err != nil {
return nil, err
}
return out.result(true, nil), nil
}
func decodeArguments(raw json.RawMessage, target any) error {
if len(raw) == 0 {
raw = json.RawMessage(`{}`)
}
// Arguments the schema does not name are refused rather than ignored.
decoder := json.NewDecoder(bytes.NewReader(raw))
decoder.DisallowUnknownFields()
if err := decoder.Decode(target); err != nil {
return fmt.Errorf("%w: %v", errInvalidParams, err)
}
return nil
}
func textResult(value any) map[string]any {
encoded, err := json.Marshal(value)
if err != nil {
return toolError(err.Error())
}
return map[string]any{"content": []any{map[string]any{"type": "text", "text": string(encoded)}}}
}
func marshal(value any) (json.RawMessage, error) {
encoded, err := json.Marshal(value)
return json.RawMessage(encoded), err
}