852 lines
30 KiB
Go
852 lines
30 KiB
Go
package mcp
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"crypto/sha256"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"image"
|
|
"image/jpeg"
|
|
"net"
|
|
"net/url"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"github.com/reims-go/reims-agent/internal/guest"
|
|
)
|
|
|
|
const protocolVersion = "2025-06-18"
|
|
|
|
type Host interface {
|
|
Call(context.Context, string, any, any) error
|
|
}
|
|
|
|
type Server struct {
|
|
host Host
|
|
callMu sync.Mutex
|
|
callsMu sync.Mutex
|
|
calls map[string]context.CancelFunc
|
|
guest *guest.SSH
|
|
}
|
|
|
|
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"`
|
|
Characters int `json:"characters"`
|
|
VMs []any `json:"vms"`
|
|
OK bool `json:"ok"`
|
|
}
|
|
|
|
func New() *Server {
|
|
root, err := os.Getwd()
|
|
if err != nil {
|
|
root = "."
|
|
}
|
|
return &Server{guest: guest.NewSSH(filepath.Clean(root)), calls: make(map[string]context.CancelFunc)}
|
|
}
|
|
|
|
func (s *Server) BindHost(host Host) { s.host = host }
|
|
|
|
func (s *Server) Handle(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) {
|
|
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, ¶ms) == nil && validRequestID(params.RequestID) {
|
|
s.cancelRequest(params.RequestID)
|
|
}
|
|
}
|
|
if req.Method == "notifications/initialized" || strings.HasPrefix(req.Method, "notifications/") {
|
|
return json.RawMessage("null"), nil
|
|
}
|
|
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" || req.Method == "resources/read" {
|
|
requestCtx, cancel, ok := s.beginRequest(ctx, req.ID)
|
|
if !ok {
|
|
return marshal(response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{Code: -32600, Message: "request id is already active"}})
|
|
}
|
|
defer s.finishRequest(req.ID, cancel)
|
|
ctx = requestCtx
|
|
s.callMu.Lock()
|
|
defer s.callMu.Unlock()
|
|
if err := ctx.Err(); err != nil {
|
|
return marshal(response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{Code: -32800, Message: "request cancelled"}})
|
|
}
|
|
}
|
|
result, err := s.dispatch(ctx, 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
|
|
if errors.Is(err, errUnknownMethod) {
|
|
code = -32601
|
|
}
|
|
if errors.Is(err, errInvalidParams) {
|
|
code = -32602
|
|
}
|
|
if 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})
|
|
}
|
|
|
|
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, id json.RawMessage) (context.Context, context.CancelFunc, bool) {
|
|
requestCtx, cancel := context.WithCancel(parent)
|
|
key := string(id)
|
|
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(id json.RawMessage, cancel context.CancelFunc) {
|
|
key := string(id)
|
|
s.callsMu.Lock()
|
|
delete(s.calls, key)
|
|
s.callsMu.Unlock()
|
|
cancel()
|
|
}
|
|
|
|
func (s *Server) cancelRequest(id json.RawMessage) {
|
|
s.callsMu.Lock()
|
|
cancel := s.calls[string(id)]
|
|
s.callsMu.Unlock()
|
|
if cancel != nil {
|
|
cancel()
|
|
}
|
|
}
|
|
|
|
var (
|
|
errUnknownMethod = errors.New("unknown MCP method")
|
|
errInvalidParams = errors.New("invalid MCP parameters")
|
|
)
|
|
|
|
func (s *Server) dispatch(ctx context.Context, 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}, "resources": map[string]any{"subscribe": false, "listChanged": false}},
|
|
"serverInfo": map[string]any{"name": "reims-agent", "version": "0.1.0"},
|
|
}, nil
|
|
case "ping":
|
|
return map[string]any{}, nil
|
|
case "tools/list":
|
|
return map[string]any{"tools": toolCatalog}, nil
|
|
case "resources/list":
|
|
return s.listResources(ctx)
|
|
case "tools/call":
|
|
return s.callTool(ctx, raw)
|
|
case "resources/read":
|
|
return s.readResource(ctx, raw)
|
|
default:
|
|
return nil, fmt.Errorf("%w: %s", errUnknownMethod, method)
|
|
}
|
|
}
|
|
|
|
func (s *Server) callTool(ctx context.Context, 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)
|
|
}
|
|
if s.host == nil {
|
|
return toolError("Reims-Go host is unavailable"), nil
|
|
}
|
|
result, err := s.invoke(ctx, req.Name, req.Arguments)
|
|
if err != nil {
|
|
if errors.Is(err, context.Canceled) {
|
|
return nil, err
|
|
}
|
|
return toolError(err.Error()), nil
|
|
}
|
|
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_start", "vm_shutdown":
|
|
var args struct {
|
|
VM string `json:"vm"`
|
|
}
|
|
if err := decodeArguments(raw, &args); err != nil {
|
|
return nil, err
|
|
}
|
|
method := "host/vm.start"
|
|
if name == "vm_shutdown" {
|
|
method = "host/vm.shutdown"
|
|
}
|
|
var out hostReply
|
|
if err := s.host.Call(ctx, method, args, &out); err != nil {
|
|
return nil, err
|
|
}
|
|
return textResult(map[string]any{"ok": true}), nil
|
|
case "vm_unlock":
|
|
var args struct {
|
|
VM string `json:"vm"`
|
|
}
|
|
if err := decodeArguments(raw, &args); err != nil {
|
|
return nil, err
|
|
}
|
|
if args.VM == "" {
|
|
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
|
|
}
|
|
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, 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
|
|
}
|
|
var screen hostReply
|
|
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"content": []any{
|
|
map[string]any{"type": "image", "data": screen.Data, "mimeType": screen.MIMEType},
|
|
map[string]any{"type": "text", "text": "Login password entered. Current screen attached."},
|
|
}}, nil
|
|
case "computer":
|
|
return s.computer(ctx, raw)
|
|
case "wait_for_screen":
|
|
return s.waitForScreen(ctx, raw)
|
|
case "guest_public_key":
|
|
var args struct {
|
|
VM string `json:"vm"`
|
|
}
|
|
if err := decodeArguments(raw, &args); err != nil {
|
|
return nil, err
|
|
}
|
|
if args.VM == "" {
|
|
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
|
|
}
|
|
key, err := s.guest.PublicKey()
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return textResult(map[string]any{"public_key": strings.TrimSpace(key), "instructions": "Add this key as one line in the guest account's ~/.ssh/authorized_keys. The private key remains in the plugin data directory."}), nil
|
|
case "guest_wait_ready":
|
|
var args struct {
|
|
VM string `json:"vm"`
|
|
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 = 10000
|
|
}
|
|
if args.TimeoutMS < 1 || args.TimeoutMS > 30000 {
|
|
return nil, fmt.Errorf("%w: timeout_ms must be between 1 and 30000", errInvalidParams)
|
|
}
|
|
result, err := s.guest.WaitReady(ctx, args.VM, address, username, time.Duration(args.TimeoutMS)*time.Millisecond)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if result["trust_required"] == true {
|
|
publicKey, keyErr := s.guest.PublicKey()
|
|
if keyErr != nil {
|
|
return nil, keyErr
|
|
}
|
|
result["plugin_public_key"] = strings.TrimSpace(publicKey)
|
|
}
|
|
return textResult(result), nil
|
|
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
|
|
}
|
|
address, _, err := s.guestAddress(ctx, args.VM)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if args.Fingerprint == "" {
|
|
return nil, fmt.Errorf("%w: fingerprint is required", errInvalidParams)
|
|
}
|
|
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 "guest_logs":
|
|
var args struct {
|
|
LogID string `json:"log_id"`
|
|
Offset int64 `json:"offset"`
|
|
Limit int `json:"limit"`
|
|
}
|
|
if err := decodeArguments(raw, &args); err != nil {
|
|
return nil, err
|
|
}
|
|
result, err := s.guest.ReadLog(args.LogID, args.Offset, args.Limit)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return textResult(result), nil
|
|
default:
|
|
return nil, fmt.Errorf("unknown tool %q", name)
|
|
}
|
|
}
|
|
|
|
func (s *Server) guestAddress(ctx context.Context, ref string) (string, string, error) {
|
|
if strings.TrimSpace(ref) == "" {
|
|
return "", "", fmt.Errorf("%w: vm is required", errInvalidParams)
|
|
}
|
|
var vm map[string]any
|
|
if err := s.host.Call(ctx, "host/vm.get", map[string]string{"vm": ref}, &vm); 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) computer(ctx context.Context, raw json.RawMessage) (any, error) {
|
|
var args struct {
|
|
VM string `json:"vm"`
|
|
Action string `json:"action"`
|
|
X int `json:"x"`
|
|
Y int `json:"y"`
|
|
Width int `json:"width"`
|
|
Height int `json:"height"`
|
|
Button string `json:"button"`
|
|
Text string `json:"text"`
|
|
Key string `json:"key"`
|
|
Modifiers []string `json:"modifiers"`
|
|
X2 int `json:"x2"`
|
|
Y2 int `json:"y2"`
|
|
Delta int `json:"delta"`
|
|
Horizontal bool `json:"horizontal"`
|
|
}
|
|
if err := decodeArguments(raw, &args); err != nil {
|
|
return nil, err
|
|
}
|
|
if args.VM == "" {
|
|
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
|
|
}
|
|
action := strings.ToLower(strings.TrimSpace(args.Action))
|
|
if action == "screenshot" {
|
|
var screen hostReply
|
|
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{
|
|
"content": []any{
|
|
map[string]any{"type": "image", "data": screen.Data, "mimeType": screen.MIMEType},
|
|
map[string]any{"type": "text", "text": fmt.Sprintf("Screen %dx%d, framebuffer %dx%d", screen.Width, screen.Height, screen.SourceWidth, screen.SourceHeight)},
|
|
},
|
|
}, nil
|
|
}
|
|
if action == "zoom" {
|
|
var screen hostReply
|
|
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
|
return nil, err
|
|
}
|
|
cropped, width, height, err := cropJPEG(screen.Data, args.X, args.Y, args.Width, args.Height)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"content": []any{map[string]any{"type": "image", "data": cropped, "mimeType": "image/jpeg"}, map[string]any{"type": "text", "text": fmt.Sprintf("Crop %dx%d", width, height)}}}, nil
|
|
}
|
|
if action == "type" {
|
|
var out hostReply
|
|
if err := s.host.Call(ctx, "host/console.type", map[string]any{"vm": args.VM, "text": args.Text}, &out); err != nil {
|
|
return nil, err
|
|
}
|
|
return textResult(map[string]any{"characters": out.Characters}), nil
|
|
}
|
|
if action == "key" {
|
|
var out hostReply
|
|
if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": args.Key, "modifiers": args.Modifiers}, &out); err != nil {
|
|
return nil, err
|
|
}
|
|
return textResult(map[string]any{"ok": true}), nil
|
|
}
|
|
if action == "wait" {
|
|
timeout := time.Duration(args.Delta) * time.Millisecond
|
|
if timeout < 0 || timeout > 30*time.Second {
|
|
return nil, fmt.Errorf("%w: wait delta must be between 0 and 30000 milliseconds", errInvalidParams)
|
|
}
|
|
timer := time.NewTimer(timeout)
|
|
defer timer.Stop()
|
|
select {
|
|
case <-timer.C:
|
|
case <-ctx.Done():
|
|
return nil, ctx.Err()
|
|
}
|
|
return textResult(map[string]any{"waited_ms": timeout.Milliseconds()}), nil
|
|
}
|
|
|
|
button := "left"
|
|
buttonActions := map[string]string{"left_click": "left", "right_click": "right", "middle_click": "middle", "double_click": "left"}
|
|
if mapped, ok := buttonActions[action]; ok {
|
|
button = mapped
|
|
if err := s.movePointer(ctx, args); err != nil {
|
|
return nil, err
|
|
}
|
|
clicks := 1
|
|
if action == "double_click" {
|
|
clicks = 2
|
|
}
|
|
for range clicks {
|
|
var out hostReply
|
|
if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "click", "button": button}, &out); err != nil {
|
|
return nil, err
|
|
}
|
|
}
|
|
return textResult(map[string]any{"ok": true}), nil
|
|
}
|
|
if action == "mouse_move" {
|
|
if err := s.movePointer(ctx, args); err != nil {
|
|
return nil, err
|
|
}
|
|
return textResult(map[string]any{"ok": true}), nil
|
|
}
|
|
if action == "left_click_drag" {
|
|
if err := s.movePointer(ctx, args); err != nil {
|
|
return nil, err
|
|
}
|
|
var out hostReply
|
|
if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "button", "button": "left", "down": true}, &out); err != nil {
|
|
return nil, err
|
|
}
|
|
releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 2*time.Second)
|
|
defer cancel()
|
|
released := false
|
|
release := func() error {
|
|
if released {
|
|
return nil
|
|
}
|
|
err := s.host.Call(releaseCtx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "button", "button": "left", "down": false}, &out)
|
|
if err == nil {
|
|
released = true
|
|
}
|
|
return err
|
|
}
|
|
defer func() { _ = release() }()
|
|
args.X, args.Y = args.X2, args.Y2
|
|
if err := s.movePointer(ctx, args); err != nil {
|
|
return nil, err
|
|
}
|
|
if err := release(); err != nil {
|
|
return nil, err
|
|
}
|
|
return textResult(map[string]any{"ok": true}), nil
|
|
}
|
|
if action == "scroll" {
|
|
if err := s.movePointer(ctx, args); err != nil {
|
|
return nil, err
|
|
}
|
|
var out hostReply
|
|
if err := s.host.Call(ctx, "host/console.pointer", map[string]any{"vm": args.VM, "action": "scroll", "delta": args.Delta, "horizontal": args.Horizontal}, &out); err != nil {
|
|
return nil, err
|
|
}
|
|
return textResult(map[string]any{"ok": true}), nil
|
|
}
|
|
return nil, fmt.Errorf("unknown computer action %q", action)
|
|
}
|
|
|
|
func (s *Server) movePointer(ctx context.Context, args struct {
|
|
VM string `json:"vm"`
|
|
Action string `json:"action"`
|
|
X int `json:"x"`
|
|
Y int `json:"y"`
|
|
Width int `json:"width"`
|
|
Height int `json:"height"`
|
|
Button string `json:"button"`
|
|
Text string `json:"text"`
|
|
Key string `json:"key"`
|
|
Modifiers []string `json:"modifiers"`
|
|
X2 int `json:"x2"`
|
|
Y2 int `json:"y2"`
|
|
Delta int `json:"delta"`
|
|
Horizontal bool `json:"horizontal"`
|
|
}) error {
|
|
if args.Width <= 0 || args.Height <= 0 {
|
|
var screen hostReply
|
|
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
|
return err
|
|
}
|
|
args.Width, args.Height = screen.Width, screen.Height
|
|
}
|
|
var out hostReply
|
|
return s.host.Call(ctx, "host/console.pointer", map[string]any{
|
|
"vm": args.VM, "action": "move", "x": args.X, "y": args.Y, "width": args.Width, "height": args.Height,
|
|
}, &out)
|
|
}
|
|
|
|
func (s *Server) waitForScreen(ctx context.Context, raw json.RawMessage) (any, error) {
|
|
var args struct {
|
|
VM string `json:"vm"`
|
|
Baseline string `json:"baseline_sha256"`
|
|
TimeoutMS int `json:"timeout_ms"`
|
|
StableMS int `json:"stable_ms"`
|
|
}
|
|
if err := decodeArguments(raw, &args); err != nil {
|
|
return nil, err
|
|
}
|
|
if args.VM == "" {
|
|
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
|
|
}
|
|
if args.TimeoutMS <= 0 {
|
|
args.TimeoutMS = 10000
|
|
}
|
|
if args.TimeoutMS > 30000 || args.StableMS < 0 || args.StableMS > args.TimeoutMS {
|
|
return nil, fmt.Errorf("%w: timeout must be <= 30000 ms and stable_ms <= timeout_ms", errInvalidParams)
|
|
}
|
|
waitCtx, cancel := context.WithTimeout(ctx, time.Duration(args.TimeoutMS)*time.Millisecond)
|
|
defer cancel()
|
|
deadline := time.NewTimer(time.Duration(args.TimeoutMS) * time.Millisecond)
|
|
defer deadline.Stop()
|
|
var previous string
|
|
stableSince := time.Time{}
|
|
for {
|
|
var screen hostReply
|
|
if err := s.host.Call(waitCtx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil {
|
|
if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil {
|
|
return toolTimeout(previous), nil
|
|
}
|
|
return nil, err
|
|
}
|
|
if err := waitCtx.Err(); err != nil {
|
|
if ctx.Err() == nil {
|
|
return toolTimeout(previous), nil
|
|
}
|
|
return nil, ctx.Err()
|
|
}
|
|
digest := sha256.Sum256([]byte(screen.Data))
|
|
current := hex.EncodeToString(digest[:])
|
|
if current != previous {
|
|
previous = current
|
|
stableSince = time.Now()
|
|
}
|
|
changed := args.Baseline == "" || current != args.Baseline
|
|
stable := args.StableMS == 0 || time.Since(stableSince) >= time.Duration(args.StableMS)*time.Millisecond
|
|
if changed && stable {
|
|
return map[string]any{"content": []any{
|
|
map[string]any{"type": "image", "data": screen.Data, "mimeType": screen.MIMEType},
|
|
map[string]any{"type": "text", "text": fmt.Sprintf("Screen changed or stable. sha256=%s", current)},
|
|
}}, nil
|
|
}
|
|
timer := time.NewTimer(250 * time.Millisecond)
|
|
select {
|
|
case <-timer.C:
|
|
case <-ctx.Done():
|
|
timer.Stop()
|
|
return nil, ctx.Err()
|
|
case <-deadline.C:
|
|
timer.Stop()
|
|
return toolTimeout(current), nil
|
|
}
|
|
}
|
|
}
|
|
|
|
func toolTimeout(lastHash string) map[string]any {
|
|
return map[string]any{"isError": true, "content": []any{map[string]any{"type": "text", "text": "Timed out waiting for a screen change. Last frame sha256=" + lastHash}}}
|
|
}
|
|
|
|
func (s *Server) readResource(ctx context.Context, raw json.RawMessage) (any, error) {
|
|
if s.host == nil {
|
|
return nil, errors.New("Reims-Go host is unavailable")
|
|
}
|
|
var args struct {
|
|
URI string `json:"uri"`
|
|
}
|
|
if err := decodeArguments(raw, &args); err != nil {
|
|
return nil, err
|
|
}
|
|
if strings.HasPrefix(args.URI, "reims://vm/") && strings.HasSuffix(args.URI, "/screen") {
|
|
vm := strings.TrimSuffix(strings.TrimPrefix(args.URI, "reims://vm/"), "/screen")
|
|
vm, err := url.PathUnescape(vm)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("invalid VM resource URI: %w", err)
|
|
}
|
|
var screen hostReply
|
|
if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": vm}, &screen); err != nil {
|
|
return nil, err
|
|
}
|
|
return map[string]any{"contents": []any{map[string]any{"uri": args.URI, "mimeType": screen.MIMEType, "blob": screen.Data}}}, nil
|
|
}
|
|
return nil, fmt.Errorf("unknown MCP resource %q", args.URI)
|
|
}
|
|
|
|
func (s *Server) listResources(ctx context.Context) (any, error) {
|
|
if s.host == nil {
|
|
return map[string]any{"resources": []any{}}, nil
|
|
}
|
|
var result hostReply
|
|
if err := s.host.Call(ctx, "host/vm.list", nil, &result); err != nil {
|
|
return nil, err
|
|
}
|
|
resources := make([]any, 0, len(result.VMs))
|
|
for _, item := range result.VMs {
|
|
vm, ok := item.(map[string]any)
|
|
if !ok {
|
|
continue
|
|
}
|
|
ref, _ := vm["vm"].(string)
|
|
name, _ := vm["name"].(string)
|
|
if ref == "" {
|
|
continue
|
|
}
|
|
resources = append(resources, map[string]any{
|
|
"uri": "reims://vm/" + url.PathEscape(ref) + "/screen",
|
|
"name": name + " screen",
|
|
"mimeType": "image/jpeg",
|
|
})
|
|
}
|
|
return map[string]any{"resources": resources}, nil
|
|
}
|
|
|
|
func cropJPEG(encoded string, x, y, width, height int) (string, int, int, error) {
|
|
if width <= 0 || height <= 0 || width > 2048 || height > 2048 {
|
|
return "", 0, 0, fmt.Errorf("crop width and height must be between 1 and 2048 pixels")
|
|
}
|
|
data, err := base64.StdEncoding.DecodeString(encoded)
|
|
if err != nil {
|
|
return "", 0, 0, err
|
|
}
|
|
img, err := jpeg.Decode(bytes.NewReader(data))
|
|
if err != nil {
|
|
return "", 0, 0, err
|
|
}
|
|
bounds := img.Bounds()
|
|
area := image.Rect(x, y, x+width, y+height).Intersect(bounds)
|
|
if area.Empty() {
|
|
return "", 0, 0, errors.New("crop rectangle does not intersect the screen")
|
|
}
|
|
var cropped image.Image
|
|
if sub, ok := img.(interface {
|
|
SubImage(image.Rectangle) image.Image
|
|
}); ok {
|
|
cropped = sub.SubImage(area)
|
|
} else {
|
|
return "", 0, 0, errors.New("screen image cannot be cropped")
|
|
}
|
|
var buf bytes.Buffer
|
|
if err := jpeg.Encode(&buf, cropped, &jpeg.Options{Quality: 84}); err != nil {
|
|
return "", 0, 0, err
|
|
}
|
|
return base64.StdEncoding.EncodeToString(buf.Bytes()), area.Dx(), area.Dy(), nil
|
|
}
|
|
|
|
func decodeArguments(raw json.RawMessage, target any) error {
|
|
if len(raw) == 0 {
|
|
raw = json.RawMessage(`{}`)
|
|
}
|
|
if err := json.Unmarshal(raw, target); err != nil {
|
|
return fmt.Errorf("%w: %v", errInvalidParams, err)
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func textResult(value any) map[string]any {
|
|
encoded, err := json.MarshalIndent(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
|
|
}
|
|
|
|
var toolCatalog = []map[string]any{
|
|
{"name": "vm_list", "description": "List virtual machines visible to Reims-Go.", "inputSchema": map[string]any{"type": "object", "properties": map[string]any{}, "additionalProperties": false}},
|
|
{"name": "vm_get", "description": "Read the state and capabilities of one virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
|
{"name": "vm_start", "description": "Start a virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
|
{"name": "vm_shutdown", "description": "Request a normal guest shutdown.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
|
{"name": "vm_unlock", "description": "Enter the host-stored macOS login password and return the current screen.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
|
{"name": "computer", "description": "Capture or interact with a virtual machine display.", "inputSchema": objectSchema(map[string]any{
|
|
"vm": map[string]any{"type": "string"},
|
|
"action": map[string]any{"type": "string", "enum": []string{"screenshot", "left_click", "right_click", "middle_click", "double_click", "mouse_move", "left_click_drag", "scroll", "key", "type", "wait", "zoom"}},
|
|
"x": map[string]any{"type": "integer"}, "y": map[string]any{"type": "integer"},
|
|
"width": map[string]any{"type": "integer"}, "height": map[string]any{"type": "integer"},
|
|
"button": map[string]any{"type": "string", "enum": []string{"left", "right", "middle"}},
|
|
"text": map[string]any{"type": "string"}, "key": map[string]any{"type": "string"},
|
|
"modifiers": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
|
|
"x2": map[string]any{"type": "integer"}, "y2": map[string]any{"type": "integer"},
|
|
"delta": map[string]any{"type": "integer"}, "horizontal": map[string]any{"type": "boolean"},
|
|
}, []string{"vm", "action"})},
|
|
{"name": "wait_for_screen", "description": "Wait for a virtual machine screen frame to change or remain stable.", "inputSchema": objectSchema(map[string]any{
|
|
"vm": map[string]any{"type": "string"}, "baseline_sha256": map[string]any{"type": "string"},
|
|
"timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000},
|
|
"stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000},
|
|
}, []string{"vm"})},
|
|
{"name": "guest_public_key", "description": "Create or return this plugin's SSH public key for explicit guest-side installation.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
|
{"name": "guest_wait_ready", "description": "Wait for guest SSH and report a host fingerprint that must be reviewed before trust.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000}}, []string{"vm"})},
|
|
{"name": "guest_trust_host", "description": "Pin an SSH host fingerprint after verifying it against the live guest connection.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "fingerprint": map[string]any{"type": "string"}}, []string{"vm", "fingerprint"})},
|
|
{"name": "guest_exec", "description": "Run a command over pinned SSH and return its exit code, bounded output, and a paginatable log id.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "command": map[string]any{"type": "string"}, "cwd": map[string]any{"type": "string"}, "env": map[string]any{"type": "object", "additionalProperties": map[string]any{"type": "string"}}, "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 1800000}}, []string{"vm", "command"})},
|
|
{"name": "guest_put", "description": "Upload one file over SFTP to a path inside the guest user's home directory.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "local_path": map[string]any{"type": "string"}, "remote_path": map[string]any{"type": "string"}}, []string{"vm", "local_path", "remote_path"})},
|
|
{"name": "guest_get", "description": "Download one file over SFTP from inside the guest user's home directory.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "remote_path": map[string]any{"type": "string"}, "local_path": map[string]any{"type": "string"}}, []string{"vm", "remote_path", "local_path"})},
|
|
{"name": "guest_logs", "description": "Read a bounded page from the complete output file of a previous guest_exec call.", "inputSchema": objectSchema(map[string]any{"log_id": map[string]any{"type": "string"}, "offset": map[string]any{"type": "integer", "minimum": 0}, "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 65536}}, []string{"log_id"})},
|
|
}
|
|
|
|
func objectSchema(properties map[string]any, required []string) map[string]any {
|
|
return map[string]any{"type": "object", "properties": properties, "required": required, "additionalProperties": false}
|
|
}
|