Files
reims-agent/internal/mcp/input.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

437 lines
13 KiB
Go

package mcp
import (
"context"
"encoding/json"
"errors"
"fmt"
"slices"
"strings"
"time"
"unicode/utf8"
)
const (
maxInputActions = 50
maxTypeRunes = 4000
maxStepWaitMS = 30000
maxHoldMS = 10000
defaultScrollStep = 3
maxScrollAmount = 120
inputStableMS = 500
releaseTimeout = 3 * time.Second
)
type inputAction struct {
Action string `json:"action"`
X *int `json:"x"`
Y *int `json:"y"`
X2 *int `json:"x2"`
Y2 *int `json:"y2"`
Button string `json:"button"`
Modifiers []string `json:"modifiers"`
Key string `json:"key"`
Text string `json:"text"`
Direction string `json:"direction"`
Amount int `json:"amount"`
DurationMS int `json:"duration_ms"`
Until string `json:"until"`
StableMS *int `json:"stable_ms"`
TimeoutMS int `json:"timeout_ms"`
}
// actionFields lists the fields each action accepts besides "action".
var actionFields = map[string][]string{
"click": {"x", "y", "button", "modifiers"},
"double_click": {"x", "y", "button", "modifiers"},
"triple_click": {"x", "y", "button", "modifiers"},
"mouse_move": {"x", "y"},
"mouse_down": {"x", "y", "button"},
"mouse_up": {"x", "y", "button"},
"drag": {"x", "y", "x2", "y2", "button", "modifiers"},
"scroll": {"x", "y", "direction", "amount", "modifiers"},
"key": {"key", "modifiers"},
"hold_key": {"key", "duration_ms"},
"type": {"text"},
"wait": {"duration_ms"},
"wait_screen": {"until", "stable_ms", "timeout_ms"},
}
var actionNames = []string{"click", "double_click", "triple_click", "mouse_move", "mouse_down", "mouse_up", "drag", "scroll", "key", "hold_key", "type", "wait", "wait_screen"}
// parseActions decodes and checks every step before any input is sent, so
// a bad step never leaves the sequence half done.
func parseActions(raw []json.RawMessage, width, height int) ([]inputAction, error) {
if len(raw) == 0 || len(raw) > maxInputActions {
return nil, fmt.Errorf("%w: actions must hold 1 to %d steps", errInvalidParams, maxInputActions)
}
actions := make([]inputAction, len(raw))
for i, item := range raw {
if err := checkAction(item, &actions[i], width, height); err != nil {
return nil, fmt.Errorf("%w: actions[%d]: %v", errInvalidParams, i, err)
}
}
return actions, nil
}
func checkAction(raw json.RawMessage, a *inputAction, width, height int) error {
var fields map[string]json.RawMessage
if err := json.Unmarshal(raw, &fields); err != nil {
return err
}
if err := json.Unmarshal(raw, a); err != nil {
return err
}
allowed, ok := actionFields[a.Action]
if !ok {
return fmt.Errorf("unknown action %q", a.Action)
}
for name := range fields {
if name != "action" && !slices.Contains(allowed, name) {
return fmt.Errorf("%q does not apply to %s", name, a.Action)
}
}
if (a.X == nil) != (a.Y == nil) {
return errors.New("x and y go together")
}
if a.X != nil && (*a.X < 0 || *a.Y < 0 || *a.X >= width || *a.Y >= height) {
return fmt.Errorf("(%d,%d) is outside the %dx%d screen image", *a.X, *a.Y, width, height)
}
if a.X2 != nil && (*a.X2 < 0 || *a.Y2 < 0 || *a.X2 >= width || *a.Y2 >= height) {
return fmt.Errorf("(%d,%d) is outside the %dx%d screen image", *a.X2, *a.Y2, width, height)
}
switch a.Button {
case "":
a.Button = "left"
case "left", "right", "middle":
default:
return errors.New("button must be left, right or middle")
}
switch a.Action {
case "mouse_move":
if a.X == nil {
return errors.New("mouse_move needs x and y")
}
case "drag":
if a.X == nil || a.X2 == nil || a.Y2 == nil {
return errors.New("drag needs x, y, x2 and y2")
}
case "scroll":
switch a.Direction {
case "up", "down", "left", "right":
default:
return errors.New("direction must be up, down, left or right")
}
if a.Amount == 0 {
a.Amount = defaultScrollStep
}
if a.Amount < 1 || a.Amount > maxScrollAmount {
return fmt.Errorf("amount must be between 1 and %d", maxScrollAmount)
}
case "key", "hold_key":
key, mods := splitCombo(a.Key)
if key == "" {
return errors.New("key is required")
}
if a.Action == "hold_key" {
if len(mods) > 0 {
return errors.New("hold_key takes one key")
}
if a.DurationMS < 1 || a.DurationMS > maxHoldMS {
return fmt.Errorf("duration_ms must be between 1 and %d", maxHoldMS)
}
}
a.Key, a.Modifiers = key, append(a.Modifiers, mods...)
case "type":
if a.Text == "" || !utf8.ValidString(a.Text) || utf8.RuneCountInString(a.Text) > maxTypeRunes {
return fmt.Errorf("text must be 1 to %d characters of valid UTF-8", maxTypeRunes)
}
case "wait":
if a.DurationMS < 1 || a.DurationMS > maxStepWaitMS {
return fmt.Errorf("duration_ms must be between 1 and %d", maxStepWaitMS)
}
}
return nil
}
// splitCombo turns "cmd+shift+z" into the key z and its modifiers.
func splitCombo(key string) (string, []string) {
key = strings.TrimSpace(key)
if len(key) <= 1 || !strings.Contains(key, "+") {
return key, nil
}
parts := strings.Split(key, "+")
return parts[len(parts)-1], parts[:len(parts)-1]
}
// inputRun sends one sequence of input to a VM and remembers what it holds,
// so release can lift it whatever way the sequence ends.
type inputRun struct {
s *Server
vm string
width int
height int
keys []string
buttons []string
}
func (r *inputRun) call(ctx context.Context, method string, params map[string]any) error {
params["vm"] = r.vm
var out hostReply
return r.s.host.Call(ctx, method, params, &out)
}
func (r *inputRun) move(ctx context.Context, x, y int) error {
return r.call(ctx, "host/console.pointer", map[string]any{"action": "move", "x": x, "y": y, "width": r.width, "height": r.height})
}
func (r *inputRun) moveTo(ctx context.Context, a inputAction) error {
if a.X == nil {
return nil
}
return r.move(ctx, *a.X, *a.Y)
}
// Held input is recorded before it is sent: a call cut short may still
// have reached the VM.
func (r *inputRun) button(ctx context.Context, button string, down bool) error {
if down {
r.buttons = append(r.buttons, button)
}
err := r.call(ctx, "host/console.pointer", map[string]any{"action": "button", "button": button, "down": down})
if !down && err == nil {
r.buttons = slices.DeleteFunc(r.buttons, func(b string) bool { return b == button })
}
return err
}
func (r *inputRun) keyState(ctx context.Context, key string, down bool) error {
if down {
r.keys = append(r.keys, key)
}
err := r.call(ctx, "host/console.key", map[string]any{"key": key, "down": down})
if !down && err == nil {
r.keys = slices.DeleteFunc(r.keys, func(k string) bool { return k == key })
}
return err
}
// withModifiers holds modifiers around fn, as for cmd+click.
func (r *inputRun) withModifiers(ctx context.Context, mods []string, fn func() error) error {
for _, mod := range mods {
if err := r.keyState(ctx, mod, true); err != nil {
return err
}
}
if err := fn(); err != nil {
return err
}
for _, mod := range slices.Backward(mods) {
if err := r.keyState(ctx, mod, false); err != nil {
return err
}
}
return nil
}
// release lifts anything still held, even after the call was cancelled.
func (r *inputRun) release(ctx context.Context) error {
if len(r.keys) == 0 && len(r.buttons) == 0 {
return nil
}
releaseCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), releaseTimeout)
defer cancel()
err := r.call(releaseCtx, "host/console.release", map[string]any{"keys": r.keys, "buttons": r.buttons})
if err == nil {
r.keys, r.buttons = nil, nil
}
return err
}
func sleepContext(ctx context.Context, d time.Duration) error {
timer := time.NewTimer(d)
defer timer.Stop()
select {
case <-timer.C:
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (r *inputRun) step(ctx context.Context, a inputAction) error {
switch a.Action {
case "click", "double_click", "triple_click":
if err := r.moveTo(ctx, a); err != nil {
return err
}
clicks := map[string]int{"click": 1, "double_click": 2, "triple_click": 3}[a.Action]
return r.withModifiers(ctx, a.Modifiers, func() error {
for range clicks {
if err := r.call(ctx, "host/console.pointer", map[string]any{"action": "click", "button": a.Button}); err != nil {
return err
}
}
return nil
})
case "mouse_move":
return r.moveTo(ctx, a)
case "mouse_down", "mouse_up":
if err := r.moveTo(ctx, a); err != nil {
return err
}
return r.button(ctx, a.Button, a.Action == "mouse_down")
case "drag":
if err := r.moveTo(ctx, a); err != nil {
return err
}
return r.withModifiers(ctx, a.Modifiers, func() error {
if err := r.button(ctx, a.Button, true); err != nil {
return err
}
if err := r.move(ctx, *a.X2, *a.Y2); err != nil {
return err
}
return r.button(ctx, a.Button, false)
})
case "scroll":
if err := r.moveTo(ctx, a); err != nil {
return err
}
// The host scrolls down or right for a positive delta.
delta := a.Amount
if a.Direction == "up" || a.Direction == "left" {
delta = -delta
}
horizontal := a.Direction == "left" || a.Direction == "right"
return r.withModifiers(ctx, a.Modifiers, func() error {
return r.call(ctx, "host/console.pointer", map[string]any{"action": "scroll", "delta": delta, "horizontal": horizontal})
})
case "key":
params := map[string]any{"key": a.Key}
if len(a.Modifiers) > 0 {
params["modifiers"] = a.Modifiers
}
return r.call(ctx, "host/console.key", params)
case "hold_key":
if err := r.keyState(ctx, a.Key, true); err != nil {
return err
}
if err := sleepContext(ctx, time.Duration(a.DurationMS)*time.Millisecond); err != nil {
return err
}
return r.keyState(ctx, a.Key, false)
case "type":
return r.call(ctx, "host/console.type", map[string]any{"text": a.Text})
case "wait":
return sleepContext(ctx, time.Duration(a.DurationMS)*time.Millisecond)
}
return fmt.Errorf("unknown action %q", a.Action)
}
func (s *Server) computerInput(ctx context.Context, raw json.RawMessage) (any, error) {
var args struct {
VM string `json:"vm"`
Actions []json.RawMessage `json:"actions"`
Scale float64 `json:"scale"`
ReturnImage *bool `json:"return_image"`
}
if err := decodeArguments(raw, &args); err != nil {
return nil, err
}
scale, err := validateScale(args.Scale)
if err != nil {
return nil, err
}
returnImage := boolOrDefault(args.ReturnImage, true)
// Coordinates refer to the last image the client was given, whatever
// scale this call asks for its own result.
ref, err := s.referenceFrame(ctx, args.VM)
if err != nil {
return nil, err
}
actions, err := parseActions(args.Actions, ref.width, ref.height)
if err != nil {
return nil, err
}
waits := make([]waitOptions, len(actions))
for i, a := range actions {
if a.Action != "wait_screen" {
continue
}
waits[i], err = s.resolveWait(args.VM, waitArgs{Until: a.Until, StableMS: a.StableMS, TimeoutMS: a.TimeoutMS}, maxStepWaitMS, inputStableMS)
if err != nil {
return nil, fmt.Errorf("actions[%d]: %w", i, err)
}
waits[i].Scale = scale
}
run := &inputRun{s: s, vm: args.VM, width: ref.width, height: ref.height}
var (
executed int
failure error
waited *waitOutcome
)
for i, a := range actions {
waited = nil
if a.Action == "wait_screen" {
// The change is measured from the image the client last saw, or
// from the end of the previous wait in this sequence.
if last, ok := s.screens.lastFrame(args.VM); ok {
waits[i].Baseline = last
}
out, err := s.waitScreen(ctx, waits[i])
if err != nil {
failure = err
break
}
waited = &out
if out.timedOut {
failure = fmt.Errorf("screen did not %s within %dms", strings.ReplaceAll(out.until, "_", " "), waits[i].TimeoutMS)
break
}
} else if err := run.step(ctx, a); err != nil {
failure = err
break
}
executed++
}
releaseErr := run.release(ctx)
if ctx.Err() != nil {
return nil, ctx.Err()
}
if failure == nil && releaseErr != nil {
failure = fmt.Errorf("cannot release held input: %w", releaseErr)
}
extra := map[string]any{"executed": executed}
var obs observation
if waited != nil && waited.hasFrame {
obs = waited.observation
} else if screen, frame, err := s.capture(ctx, args.VM, scale); err == nil {
obs = newObservation(screen, frame)
} else if failure == nil {
return nil, err
}
if failure != nil {
extra["failed_step"] = executed
extra["error"] = failure.Error()
if waited != nil && waited.timedOut {
extra["timed_out"] = true
}
}
var result map[string]any
if obs.info == nil {
text, _ := json.Marshal(extra)
result = map[string]any{"content": []any{map[string]any{"type": "text", "text": string(text)}}, "structuredContent": extra}
} else {
result = obs.result(returnImage, extra)
}
// A wait that times out on the last step only reports it; one that cuts
// the sequence short is an error.
if failure != nil && !(waited != nil && waited.timedOut && executed == len(actions)-1) {
result["isError"] = true
}
return result, nil
}