diff --git a/README.md b/README.md index 17c3183..3fa95ac 100644 --- a/README.md +++ b/README.md @@ -1,20 +1,36 @@ # Reims-Go MCP Service -`reims.agent` is the official Reims-Go L3 plugin that exposes host-authorized virtual machine information and desktop controls to MCP clients. The host retains QMP access and permission checks. The plugin communicates with the host through `reims-go plugin connect reims.agent mcp`; it does not open a network listener. +`reims.agent` is the official Reims-Go L3 plugin that exposes host-authorized virtual machine information and desktop controls to MCP clients. The host retains QMP access and permission checks. The plugin communicates with the host through `reims-go plugin connect`; it does not open a network listener. -Configure an MCP client to launch `reims-go.exe plugin connect reims.agent mcp` over stdio. Grant the plugin permissions in Reims-Go before calling VM tools. Source builds and package checks are documented in [CONTRIBUTING.md](CONTRIBUTING.md). +Configure an MCP client to launch one of these commands over stdio. Grant the plugin permissions in Reims-Go before calling VM tools. Source builds and package checks are documented in [CONTRIBUTING.md](CONTRIBUTING.md). -## Current MCP tools +| Command | Tools | +| --- | --- | +| `reims-go.exe plugin connect reims.agent mcp` | The six computer-use tools | +| `reims-go.exe plugin connect reims.agent mcp-dev` | The computer-use tools plus guest SSH, restore point, clone and test tools | -- `vm_list`, `vm_get`, `vm_start`, `vm_shutdown`, `vm_suspend`, `vm_resume`, and `vm_unlock` -- `computer` for screenshots, zoom, pointer, keyboard, and text input -- `wait_for_screen` for changed or stable frames -- `guest_public_key`, `guest_wait_ready`, and `guest_trust_host` for explicit SSH setup and host-key pinning -- `guest_exec`, `guest_put`, `guest_get`, and `guest_logs` for SSH commands, bounded SFTP transfers, and paged command output -- `snapshot_list`, `snapshot_create`, and `snapshot_restore` for restore points. Restore is limited to temporary sessions created by this plugin. -- `session_create` and `session_dispose` for process-owned CoW sessions. -- `test_run`, `test_wait`, `test_status`, `test_logs`, `test_result`, and `test_cancel` for guest test runs with optional workspace sync, JUnit summaries, and artifact collection. -- `reims://vm/{ref}/screen` image resource +## Computer-use tools + +- `vm_list` and `vm_get` read the VMs this plugin may use. +- `vm_power` starts, shuts down, force-stops, suspends or resumes a VM. +- `vm_unlock` types the saved login password and returns the screen once it settles. +- `screen` returns the display. It can first wait for the display to change or settle, for up to 180 seconds while a VM boots, and it can return one region at up to source resolution. +- `computer_input` runs up to 50 mouse and keyboard actions in order and returns the screen after the last one. A `wait_screen` step waits for the UI to respond, and a timeout stops the sequence. + +Version 0.2 needs a Reims-Go build whose Host API provides region screenshots, held-key input, input release and forced shutdown. + +Every x and y is a pixel of the last full screen image the plugin returned, whatever its scale. Each result reports that image's width, height and a 16-digit `sha256` that later waits can use as a baseline. `computer_input` checks every step before it sends any input, and it releases held keys and buttons when it finishes, fails, or is cancelled. Calls on one VM run one at a time; calls on different VMs and the guest and test tools run independently. + +## Development tools + +These tools are only served on the `mcp-dev` channel. + +- `guest_wait_ready` and `guest_trust_host` set up SSH. `guest_wait_ready` returns the host fingerprint to review and the plugin public key to add to the guest. +- `guest_exec`, `guest_put` and `guest_get` run commands and copy files over SSH. +- `snapshot_list`, `snapshot_create` and `snapshot_restore` manage restore points. Restore works only on temporary clones created by this plugin. +- `session_create` and `session_dispose` create and delete temporary clones. +- `test_run`, `test_wait` and `test_cancel` run guest tests on a temporary clone with optional workspace sync, JUnit summaries and artifact collection. +- `logs_read` pages through the output of a `guest_exec` call or a test run. Screenshots are returned to the MCP client and are not retained by the plugin. The plugin package contains a native Windows sidecar and therefore runs with the current Windows account's permissions. Reims-Go presents the declared capabilities and requires approval before enabling them. diff --git a/internal/mcp/input.go b/internal/mcp/input.go new file mode 100644 index 0000000..edb43f7 --- /dev/null +++ b/internal/mcp/input.go @@ -0,0 +1,436 @@ +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 +} diff --git a/internal/mcp/input_test.go b/internal/mcp/input_test.go new file mode 100644 index 0000000..7f20a00 --- /dev/null +++ b/internal/mcp/input_test.go @@ -0,0 +1,201 @@ +package mcp + +import ( + "context" + "encoding/json" + "errors" + "fmt" + "image/color" + "strings" + "testing" + "time" +) + +// inputServer returns a server whose VM last showed a 640x360 image. +func inputServer(t *testing.T) (*Server, *scriptedHost) { + t.Helper() + host := &scriptedHost{screens: []scriptedScreen{ + {data: makeFrame(t, 64, 36, color.RGBA{R: 30, A: 255}, false), w: 640, h: 360}, + }} + server := New() + server.BindHost(host) + callTool(t, server, "screen", `{"vm":"macos1","scale":0.5}`) + return server, host +} + +// inputTrace lists the input calls after the initial screen call, one line +// each, in a form the tests can compare. +func inputTrace(host *scriptedHost) []string { + host.mu.Lock() + defer host.mu.Unlock() + var trace []string + for _, call := range host.calls[1:] { + args, _ := call.params.(map[string]any) + switch call.method { + case "host/console.pointer": + switch args["action"] { + case "move": + trace = append(trace, fmt.Sprintf("move %v,%v in %vx%v", args["x"], args["y"], args["width"], args["height"])) + case "button": + trace = append(trace, fmt.Sprintf("button %v %v", args["button"], args["down"])) + case "click": + trace = append(trace, fmt.Sprintf("click %v", args["button"])) + case "scroll": + trace = append(trace, fmt.Sprintf("scroll %v %v", args["delta"], args["horizontal"])) + } + case "host/console.key": + if down, ok := args["down"]; ok { + trace = append(trace, fmt.Sprintf("key %v %v", args["key"], down)) + } else { + trace = append(trace, fmt.Sprintf("key %v %v", args["key"], args["modifiers"])) + } + case "host/console.type": + trace = append(trace, "type "+args["text"].(string)) + case "host/console.release": + trace = append(trace, fmt.Sprintf("release %v %v", args["keys"], args["buttons"])) + case "host/console.screenshot": + trace = append(trace, "screenshot") + } + } + return trace +} + +func expectTrace(t *testing.T, host *scriptedHost, want ...string) { + t.Helper() + got := inputTrace(host) + if strings.Join(got, "\n") != strings.Join(want, "\n") { + t.Fatalf("input calls:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n")) + } +} + +func TestComputerInputUsesTheLastImageAsCoordinateSpace(t *testing.T) { + server, host := inputServer(t) + result := callTool(t, server, "computer_input", `{"vm":"macos1","actions":[{"action":"click","x":100,"y":200},{"action":"type","text":"hi"},{"action":"key","key":"cmd+c"}]}`) + if result["isError"] == true { + t.Fatalf("computer_input = %v", result) + } + expectTrace(t, host, + "move 100,200 in 640x360", "click left", "type hi", "key c [cmd]", "screenshot") + if info := structured(t, result); info["executed"] != float64(3) || info["width"] != float64(640) { + t.Fatalf("result info = %v", info) + } +} + +func TestComputerInputChecksEveryStepBeforeSendingAny(t *testing.T) { + cases := map[string]string{ + "field of another action": `[{"action":"click","x":1,"y":1},{"action":"type","text":"a","x":3}]`, + "outside the image": `[{"action":"click","x":1,"y":1},{"action":"click","x":640,"y":10}]`, + "half a coordinate": `[{"action":"click","x":1}]`, + "unknown action": `[{"action":"left_click","x":1,"y":1}]`, + "drag without an end": `[{"action":"drag","x":1,"y":1}]`, + "scroll without a way": `[{"action":"scroll"}]`, + "empty text": `[{"action":"type","text":""}]`, + } + for name, actions := range cases { + server, host := inputServer(t) + result := callTool(t, server, "computer_input", `{"vm":"macos1","actions":`+actions+`}`) + if result["isError"] != true { + t.Errorf("%s: expected an error, got %v", name, result) + } + if trace := inputTrace(host); len(trace) != 0 { + t.Errorf("%s: input was sent before the sequence was checked: %v", name, trace) + } + } +} + +func TestComputerInputHoldsModifiersAroundPointerActions(t *testing.T) { + server, host := inputServer(t) + callTool(t, server, "computer_input", `{"vm":"macos1","actions":[{"action":"click","x":5,"y":6,"modifiers":["cmd","shift"]},{"action":"scroll","direction":"up"},{"action":"scroll","direction":"right","amount":5}]}`) + expectTrace(t, host, + "move 5,6 in 640x360", "key cmd true", "key shift true", "click left", "key shift false", "key cmd false", + "scroll -3 false", "scroll 5 true", "screenshot") +} + +func TestComputerInputDragAndHeldInputAreReleased(t *testing.T) { + server, host := inputServer(t) + callTool(t, server, "computer_input", `{"vm":"macos1","actions":[{"action":"drag","x":1,"y":2,"x2":30,"y2":40},{"action":"mouse_down","button":"right"}]}`) + expectTrace(t, host, + "move 1,2 in 640x360", "button left true", "move 30,40 in 640x360", "button left false", + "button right true", "release [] [right]", "screenshot") +} + +func TestComputerInputReleasesHeldInputWhenAStepFails(t *testing.T) { + server, host := inputServer(t) + host.failOn = func(method string, args map[string]any) error { + if method == "host/console.pointer" && args["action"] == "click" { + return errors.New("console busy") + } + return nil + } + result := callTool(t, server, "computer_input", `{"vm":"macos1","actions":[{"action":"key","key":"a"},{"action":"click","x":1,"y":1,"modifiers":["alt"]},{"action":"type","text":"never"}]}`) + info := structured(t, result) + if result["isError"] != true || info["failed_step"] != float64(1) || info["executed"] != float64(1) || !strings.Contains(info["error"].(string), "console busy") { + t.Fatalf("failure info = %v", info) + } + expectTrace(t, host, "key a ", "move 1,1 in 640x360", "key alt true", "click left", "release [alt] []", "screenshot") +} + +func TestComputerInputWaitScreenTimeoutStopsTheSequence(t *testing.T) { + server, host := inputServer(t) + result := callTool(t, server, "computer_input", `{"vm":"macos1","actions":[{"action":"wait_screen","until":"change","timeout_ms":300},{"action":"key","key":"return"}]}`) + info := structured(t, result) + if result["isError"] != true || info["timed_out"] != true || info["failed_step"] != float64(0) { + t.Fatalf("a wait that times out mid-sequence should stop it: %v", info) + } + for _, line := range inputTrace(host) { + if strings.HasPrefix(line, "key") { + t.Fatal("steps after a timed-out wait must not run") + } + } + // On the last step a timeout is reported, not treated as an error. + result = callTool(t, server, "computer_input", `{"vm":"macos1","actions":[{"action":"key","key":"a"},{"action":"wait_screen","until":"change","timeout_ms":300}]}`) + if info := structured(t, result); result["isError"] == true || info["timed_out"] != true || info["executed"] != float64(1) { + t.Fatalf("a final wait timeout should only be reported: %v", info) + } +} + +func TestComputerInputWaitScreenEndsOnTheChangedFrame(t *testing.T) { + server, host := inputServer(t) + host.mu.Lock() + host.screens = append(host.screens, scriptedScreen{data: makeFrame(t, 64, 36, color.RGBA{B: 220, A: 255}, false), w: 640, h: 360}) + host.mu.Unlock() + result := callTool(t, server, "computer_input", `{"vm":"macos1","actions":[{"action":"key","key":"return"},{"action":"wait_screen","stable_ms":0}]}`) + if info := structured(t, result); result["isError"] == true || info["timed_out"] != nil { + t.Fatalf("wait_screen should see the change: %v", info) + } + // The frame from the wait is returned without another capture. + trace := inputTrace(host) + if trace[len(trace)-1] != "screenshot" || len(trace) != 2 { + t.Fatalf("input calls = %v", trace) + } +} + +func TestCancelledInputReleasesWhatItHolds(t *testing.T) { + server, host := inputServer(t) + result := make(chan json.RawMessage, 1) + go func() { + raw, _ := server.Handle(context.Background(), ChannelCore, "client-a", json.RawMessage( + `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"computer_input","arguments":{"vm":"macos1","actions":[{"action":"mouse_down","x":3,"y":4},{"action":"wait","duration_ms":10000}]}}}`)) + result <- raw + }() + deadline := time.Now().Add(time.Second) + for len(host.callsTo("host/console.pointer")) < 2 { + if time.Now().After(deadline) { + t.Fatal("the button was never pressed") + } + time.Sleep(5 * time.Millisecond) + } + server.SessionClosed(ChannelCore, "client-a") + select { + case raw := <-result: + if failure, _ := parseResponse(t, raw)["error"].(map[string]any); failure["code"] != float64(-32800) { + t.Fatalf("response = %s", raw) + } + case <-time.After(2 * time.Second): + t.Fatal("closing the session did not stop the input") + } + releases := host.callsTo("host/console.release") + if len(releases) != 1 || fmt.Sprint(releases[0]["buttons"]) != "[left]" { + t.Fatalf("the held button was not released: %v", releases) + } +} diff --git a/internal/mcp/screen.go b/internal/mcp/screen.go index 6a74038..37349c9 100644 --- a/internal/mcp/screen.go +++ b/internal/mcp/screen.go @@ -7,9 +7,7 @@ import ( "encoding/base64" "encoding/hex" "encoding/json" - "errors" "fmt" - "image" "image/jpeg" "math" "strings" @@ -18,96 +16,99 @@ import ( ) const ( - thumbW = 160 - thumbH = 90 - pixelDiffThreshold = 16 - defaultTolerance = 0.002 // 0.2% - maxFrameCacheEntries = 64 - defaultWaitPollPeriod = 250 * time.Millisecond + thumbW = 160 + thumbH = 90 + pixelDiffThreshold = 16 + changeTolerance = 0.002 // share of thumbnail pixels that must differ + maxFrameCacheEntries = 64 + waitPollPeriod = 250 * time.Millisecond + + // defaultImageWidth is the width of a full screen image at scale 1. + defaultImageWidth = 1280 + hashHexLength = 16 + + defaultWaitTimeoutMS = 10000 + maxScreenWaitMS = 180000 + defaultStableMS = 1000 ) -type cachedFrame struct { - hash string - gray []uint8 - width int - height int - blank bool +type region struct { + X int `json:"x"` + Y int `json:"y"` + Width int `json:"width"` + Height int `json:"height"` +} + +// frameInfo describes a full screen image. Its width and height are the +// coordinate space of every x/y the client sends next. +type frameInfo struct { + hash string + gray []uint8 + width int + height int + sourceWidth int + sourceHeight int + blank bool } type screenCache struct { - mu sync.Mutex - byHash map[string][]uint8 - order []string - vmSize map[string][2]int - vmFrame map[string]cachedFrame + mu sync.Mutex + byHash map[string][]uint8 + order []string + last map[string]frameInfo } func newScreenCache() *screenCache { - return &screenCache{ - byHash: make(map[string][]uint8), - vmSize: make(map[string][2]int), - vmFrame: make(map[string]cachedFrame), - } + return &screenCache{byHash: make(map[string][]uint8), last: make(map[string]frameInfo)} } -func (c *screenCache) record(vm string, screen hostReply) cachedFrame { - digest := sha256.Sum256([]byte(screen.Data)) - hash := hex.EncodeToString(digest[:]) +func frameHash(data string) string { + digest := sha256.Sum256([]byte(data)) + return hex.EncodeToString(digest[:])[:hashHexLength] +} + +// record stores a full screen image as the VM's latest frame. +func (c *screenCache) record(vm string, screen hostReply) frameInfo { gray, _ := decodeGrayThumb(screen.Data) - cf := cachedFrame{ - hash: hash, - gray: gray, - width: screen.Width, - height: screen.Height, - blank: screen.Blank, + frame := frameInfo{ + hash: frameHash(screen.Data), + gray: gray, + width: screen.Width, + height: screen.Height, + sourceWidth: screen.SourceWidth, + sourceHeight: screen.SourceHeight, + blank: screen.Blank, } c.mu.Lock() defer c.mu.Unlock() if gray != nil { - if _, exists := c.byHash[hash]; !exists { + if _, exists := c.byHash[frame.hash]; !exists { if len(c.order) >= maxFrameCacheEntries { - oldest := c.order[0] + delete(c.byHash, c.order[0]) c.order = c.order[1:] - delete(c.byHash, oldest) } - c.order = append(c.order, hash) + c.order = append(c.order, frame.hash) } - c.byHash[hash] = gray + c.byHash[frame.hash] = gray } - if vm != "" { - if screen.Width > 0 && screen.Height > 0 { - c.vmSize[vm] = [2]int{screen.Width, screen.Height} - } - c.vmFrame[vm] = cf - } - return cf + c.last[vmKey(vm)] = frame + return frame } func (c *screenCache) grayByHash(hash string) []uint8 { - if hash == "" { - return nil - } c.mu.Lock() defer c.mu.Unlock() return c.byHash[hash] } -func (c *screenCache) sizeForVM(vm string) (int, int, bool) { +func (c *screenCache) lastFrame(vm string) (frameInfo, bool) { c.mu.Lock() defer c.mu.Unlock() - sz, ok := c.vmSize[vm] - if !ok || sz[0] <= 0 || sz[1] <= 0 { - return 0, 0, false - } - return sz[0], sz[1], true + frame, ok := c.last[vmKey(vm)] + return frame, ok && frame.width > 0 && frame.height > 0 } -func (c *screenCache) lastFrameForVM(vm string) (cachedFrame, bool) { - c.mu.Lock() - defer c.mu.Unlock() - cf, ok := c.vmFrame[vm] - return cf, ok -} +func vmKey(vm string) string { return strings.ToLower(strings.TrimSpace(vm)) } func decodeGrayThumb(encoded string) ([]uint8, bool) { if encoded == "" { @@ -129,13 +130,11 @@ func decodeGrayThumb(encoded string) ([]uint8, bool) { gray := make([]uint8, thumbW*thumbH) for y := range thumbH { sy := b.Min.Y + (y*srcH)/thumbH - rowOff := y * thumbW for x := range thumbW { sx := b.Min.X + (x*srcW)/thumbW r, g, bl, _ := img.At(sx, sy).RGBA() // Rec.601 luma from 16-bit channels to 8-bit. - luma := (299*(r>>8) + 587*(g>>8) + 114*(bl>>8)) / 1000 - gray[rowOff+x] = uint8(luma) + gray[y*thumbW+x] = uint8((299*(r>>8) + 587*(g>>8) + 114*(bl>>8)) / 1000) } } return gray, true @@ -158,42 +157,12 @@ func frameDiffRatio(a, b []uint8) float64 { return float64(diff) / float64(len(a)) } -func framesDifferent(hashA string, grayA []uint8, hashB string, grayB []uint8, tolerance float64) bool { - if grayA != nil && grayB != nil { - return frameDiffRatio(grayA, grayB) >= tolerance +// framesDiffer ignores small changes such as a blinking caret. +func framesDiffer(a, b frameInfo) bool { + if a.gray != nil && b.gray != nil { + return frameDiffRatio(a.gray, b.gray) >= changeTolerance } - return hashA != hashB -} - -func scaleJPEG(encoded string, scale float64) (string, int, int, error) { - if scale <= 0 || scale >= 1 { - return encoded, 0, 0, nil - } - raw, err := base64.StdEncoding.DecodeString(encoded) - if err != nil { - return "", 0, 0, err - } - img, err := jpeg.Decode(bytes.NewReader(raw)) - if err != nil { - return "", 0, 0, err - } - b := img.Bounds() - srcW, srcH := b.Dx(), b.Dy() - dstW := max(1, int(math.Round(float64(srcW)*scale))) - dstH := max(1, int(math.Round(float64(srcH)*scale))) - dst := image.NewRGBA(image.Rect(0, 0, dstW, dstH)) - for y := range dstH { - sy := b.Min.Y + (y*srcH)/dstH - for x := range dstW { - sx := b.Min.X + (x*srcW)/dstW - dst.Set(x, y, img.At(sx, sy)) - } - } - var buf bytes.Buffer - if err := jpeg.Encode(&buf, dst, &jpeg.Options{Quality: 80}); err != nil { - return "", 0, 0, err - } - return base64.StdEncoding.EncodeToString(buf.Bytes()), dstW, dstH, nil + return a.hash != b.hash } func validateScale(scale float64) (float64, error) { @@ -201,11 +170,15 @@ func validateScale(scale float64) (float64, error) { return 1.0, nil } if math.IsNaN(scale) || math.IsInf(scale, 0) || scale < 0.25 || scale > 1.0 { - return 0, fmt.Errorf("%w: scale must be between 0.25 and 1.0", errInvalidParams) + return 0, fmt.Errorf("%w: scale must be between 0.25 and 1", errInvalidParams) } return scale, nil } +func maxWidthFor(scale float64) int { + return int(math.Round(defaultImageWidth * scale)) +} + func boolOrDefault(ptr *bool, fallback bool) bool { if ptr == nil { return fallback @@ -213,357 +186,287 @@ func boolOrDefault(ptr *bool, fallback bool) bool { return *ptr } -func formatScreenResult(screen hostReply, hash string, summary string, scale float64, returnImage bool) (map[string]any, error) { - text := fmt.Sprintf("%s sha256=%s blank=%t", summary, hash, screen.Blank) - if !returnImage || screen.Data == "" { - return map[string]any{"content": []any{ - map[string]any{"type": "text", "text": text}, - }}, nil +// capture takes a full screen image and makes it the VM's coordinate space. +func (s *Server) capture(ctx context.Context, vm string, scale float64) (hostReply, frameInfo, error) { + var screen hostReply + if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": vm, "max_width": maxWidthFor(scale)}, &screen); err != nil { + return hostReply{}, frameInfo{}, err } - data := screen.Data - mime := screen.MIMEType - if mime == "" { - mime = "image/jpeg" + return screen, s.screens.record(vm, screen), nil +} + +// referenceFrame returns the image the client's coordinates refer to, +// capturing one at the default size when none has been returned yet. +func (s *Server) referenceFrame(ctx context.Context, vm string) (frameInfo, error) { + if frame, ok := s.screens.lastFrame(vm); ok { + return frame, nil } - if scale > 0 && scale < 1.0 { - scaled, _, _, err := scaleJPEG(data, scale) - if err == nil && scaled != "" { - data = scaled + _, frame, err := s.capture(ctx, vm, 1) + return frame, err +} + +// captureRegion returns part of the screen at up to source resolution. The +// region is given in the coordinate space of the reference frame. +func (s *Server) captureRegion(ctx context.Context, vm string, area region, ref frameInfo, scale float64) (hostReply, error) { + if area.Width <= 0 || area.Height <= 0 || area.X < 0 || area.Y < 0 { + return hostReply{}, fmt.Errorf("%w: region needs x, y >= 0 and width, height > 0", errInvalidParams) + } + if area.X >= ref.width || area.Y >= ref.height { + return hostReply{}, fmt.Errorf("%w: region starts outside the %dx%d image", errInvalidParams, ref.width, ref.height) + } + var screen hostReply + err := s.host.Call(ctx, "host/console.screenshot", map[string]any{ + "vm": vm, "region": area, "width": ref.width, "height": ref.height, "max_width": maxWidthFor(scale), + }, &screen) + return screen, err +} + +// observation is a screen image ready to return to the client. +type observation struct { + screen hostReply + frame frameInfo + info map[string]any +} + +func newObservation(screen hostReply, frame frameInfo) observation { + return observation{screen: screen, frame: frame, info: map[string]any{ + "width": screen.Width, "height": screen.Height, + "source_width": screen.SourceWidth, "source_height": screen.SourceHeight, + "sha256": frame.hash, "blank": screen.Blank, + }} +} + +func regionObservation(screen hostReply) observation { + info := map[string]any{"width": screen.Width, "height": screen.Height, "blank": screen.Blank} + if screen.Region != nil { + info["region"] = screen.Region + } + return observation{screen: screen, info: info} +} + +// result renders the observation as MCP content. extra fields are added to +// both the text and the structured result. +func (o observation) result(returnImage bool, extra map[string]any) map[string]any { + info := make(map[string]any, len(o.info)+len(extra)) + for k, v := range o.info { + info[k] = v + } + for k, v := range extra { + info[k] = v + } + text, err := json.Marshal(info) + if err != nil { + return toolError(err.Error()) + } + content := make([]any, 0, 2) + if returnImage && o.screen.Data != "" { + mime := o.screen.MIMEType + if mime == "" { mime = "image/jpeg" } + content = append(content, map[string]any{"type": "image", "data": o.screen.Data, "mimeType": mime}) } - return map[string]any{"content": []any{ - map[string]any{"type": "image", "data": data, "mimeType": mime}, - map[string]any{"type": "text", "text": text}, - }}, nil + content = append(content, map[string]any{"type": "text", "text": string(text)}) + return map[string]any{"content": content, "structuredContent": info} +} + +type waitArgs struct { + Until string `json:"until"` + Baseline string `json:"baseline"` + StableMS *int `json:"stable_ms"` + TimeoutMS int `json:"timeout_ms"` + AcceptBlank bool `json:"accept_blank"` } type waitOptions struct { - VM string - BaselineHash string - BaselineGray []uint8 - Mode string // "stable", "change", "change_then_stable" - TimeoutMS int - MaxTimeoutMS int - StableMS int - Tolerance float64 - AcceptBlank bool - RetryHostErr bool // true during vm_start boot waiting + VM string + Baseline frameInfo // the frame a change is measured from + Until string // change, stable or change_then_stable + TimeoutMS int + StableMS int + AcceptBlank bool + // RetryHostErr keeps polling through capture errors, as while a VM boots. + RetryHostErr bool Scale float64 - ReturnImage bool } type waitOutcome struct { - screen hostReply - frame cachedFrame + observation hasFrame bool timedOut bool - mode string + until string + lastErr string } -func (s *Server) waitScreenInternal(ctx context.Context, opts waitOptions) (waitOutcome, error) { - if opts.VM == "" { - return waitOutcome{}, fmt.Errorf("%w: vm is required", errInvalidParams) +func (o waitOutcome) result(returnImage bool, extra map[string]any) map[string]any { + fields := map[string]any{} + for k, v := range extra { + fields[k] = v } - maxTimeout := opts.MaxTimeoutMS - if maxTimeout <= 0 { - maxTimeout = 30000 - } - if opts.TimeoutMS <= 0 { - opts.TimeoutMS = 10000 - } - if opts.TimeoutMS > maxTimeout || opts.StableMS < 0 || opts.StableMS > opts.TimeoutMS { - return waitOutcome{}, fmt.Errorf("%w: timeout_ms must be between 1 and %d and stable_ms <= timeout_ms", errInvalidParams, maxTimeout) - } - mode := strings.ToLower(strings.TrimSpace(opts.Mode)) - if mode == "" { - if opts.BaselineHash != "" { - mode = "change_then_stable" - } else { - mode = "stable" + if o.timedOut { + fields["timed_out"] = true + fields["until"] = o.until + if o.lastErr != "" { + fields["error"] = o.lastErr } } - switch mode { - case "stable", "change", "change_then_stable": + if !o.hasFrame { + text, _ := json.Marshal(fields) + return map[string]any{"content": []any{map[string]any{"type": "text", "text": string(text)}}, "structuredContent": fields} + } + return o.observation.result(returnImage, fields) +} + +// resolveWait checks the client's wait arguments and fills in defaults. +func (s *Server) resolveWait(vm string, args waitArgs, maxTimeoutMS int, defaultStable int) (waitOptions, error) { + opts := waitOptions{VM: vm, Until: args.Until, TimeoutMS: args.TimeoutMS, AcceptBlank: args.AcceptBlank} + if opts.Until == "" { + opts.Until = "change_then_stable" + } + switch opts.Until { + case "change", "stable", "change_then_stable": default: - return waitOutcome{}, fmt.Errorf("%w: mode must be stable, change, or change_then_stable", errInvalidParams) + return opts, fmt.Errorf("%w: until must be change, stable or change_then_stable", errInvalidParams) } - tol := opts.Tolerance - if tol == 0 { - tol = defaultTolerance + if opts.TimeoutMS == 0 { + opts.TimeoutMS = defaultWaitTimeoutMS } - if math.IsNaN(tol) || math.IsInf(tol, 0) || tol < 0 || tol > 1 { - return waitOutcome{}, fmt.Errorf("%w: tolerance must be between 0 and 1", errInvalidParams) - } - - baselineHash := opts.BaselineHash - baselineGray := opts.BaselineGray - if baselineGray == nil && baselineHash != "" { - baselineGray = s.screens.grayByHash(baselineHash) + if opts.TimeoutMS < 1 || opts.TimeoutMS > maxTimeoutMS { + return opts, fmt.Errorf("%w: timeout_ms must be between 1 and %d", errInvalidParams, maxTimeoutMS) } + opts.StableMS = min(defaultStable, opts.TimeoutMS) + if args.StableMS != nil { + opts.StableMS = *args.StableMS + } + if opts.StableMS < 0 || opts.StableMS > opts.TimeoutMS { + return opts, fmt.Errorf("%w: stable_ms must be between 0 and timeout_ms", errInvalidParams) + } + if args.Baseline != "" { + gray := s.screens.grayByHash(args.Baseline) + if gray == nil { + return opts, fmt.Errorf("%w: baseline %q is not a recent sha256", errInvalidParams, args.Baseline) + } + opts.Baseline = frameInfo{hash: args.Baseline, gray: gray} + } else if last, ok := s.screens.lastFrame(vm); ok { + opts.Baseline = last + } + return opts, nil +} +// waitScreen polls full frames until the screen changes from the baseline, +// settles, or both. A timeout is not an error: the outcome carries the last +// frame and timedOut. +func (s *Server) waitScreen(ctx context.Context, opts waitOptions) (waitOutcome, error) { waitCtx, cancel := context.WithTimeout(ctx, time.Duration(opts.TimeoutMS)*time.Millisecond) defer cancel() - deadline := time.NewTimer(time.Duration(opts.TimeoutMS) * time.Millisecond) - defer deadline.Stop() - + outcome := waitOutcome{until: opts.Until} + baseline := opts.Baseline var ( - lastScreen hostReply - lastFrame cachedFrame - hasLast bool - anchor cachedFrame + anchor frameInfo hasAnchor bool stableSince time.Time ) - - makeTimeout := func() waitOutcome { - return waitOutcome{ - screen: lastScreen, - frame: lastFrame, - hasFrame: hasLast, - timedOut: true, - mode: mode, - } - } - + stableFor := time.Duration(opts.StableMS) * time.Millisecond for { var screen hostReply - err := s.host.Call(waitCtx, "host/console.screenshot", map[string]any{"vm": opts.VM}, &screen) - if err != nil { - if errors.Is(err, context.DeadlineExceeded) && ctx.Err() == nil { - return makeTimeout(), nil + err := s.host.Call(waitCtx, "host/console.screenshot", map[string]any{"vm": opts.VM, "max_width": maxWidthFor(opts.Scale)}, &screen) + switch { + case ctx.Err() != nil: + return waitOutcome{}, ctx.Err() + case waitCtx.Err() != nil: + outcome.timedOut = true + return outcome, nil + case err != nil && !opts.RetryHostErr: + return waitOutcome{}, err + case err != nil: + outcome.lastErr = err.Error() + default: + outcome.lastErr = "" + frame := s.screens.record(opts.VM, screen) + outcome.observation, outcome.hasFrame = newObservation(screen, frame), true + if !screen.Blank || opts.AcceptBlank { + if baseline.hash == "" { + // Nothing was seen before: the first usable frame is the + // one a change is measured from. + baseline = frame + } + if !hasAnchor || framesDiffer(anchor, frame) { + anchor, hasAnchor, stableSince = frame, true, time.Now() + } + changed := opts.Until == "stable" || framesDiffer(baseline, frame) + settled := opts.Until == "change" || time.Since(stableSince) >= stableFor + if changed && settled { + return outcome, nil + } } + } + timer := time.NewTimer(waitPollPeriod) + select { + case <-timer.C: + case <-waitCtx.Done(): + timer.Stop() if ctx.Err() != nil { return waitOutcome{}, ctx.Err() } - if !opts.RetryHostErr { - return waitOutcome{}, err - } - } else { - if waitCtx.Err() != nil { - if ctx.Err() == nil { - return makeTimeout(), nil - } - return waitOutcome{}, ctx.Err() - } - cf := s.screens.record(opts.VM, screen) - lastScreen, lastFrame, hasLast = screen, cf, true - - if !screen.Blank || opts.AcceptBlank { - if !hasAnchor { - anchor = cf - hasAnchor = true - stableSince = time.Now() - if baselineHash == "" && (mode == "change" || mode == "change_then_stable") { - baselineHash = cf.hash - baselineGray = cf.gray - } - } else if framesDifferent(anchor.hash, anchor.gray, cf.hash, cf.gray, tol) { - anchor = cf - stableSince = time.Now() - } - - changed := true - if mode == "change" || mode == "change_then_stable" { - changed = framesDifferent(baselineHash, baselineGray, cf.hash, cf.gray, tol) - } - settled := true - if mode == "stable" || mode == "change_then_stable" { - settled = opts.StableMS == 0 || time.Since(stableSince) >= time.Duration(opts.StableMS)*time.Millisecond - } - if changed && settled { - return waitOutcome{ - screen: screen, - frame: cf, - hasFrame: true, - timedOut: false, - mode: mode, - }, nil - } - } - } - - timer := time.NewTimer(defaultWaitPollPeriod) - select { - case <-timer.C: - case <-ctx.Done(): - timer.Stop() - return waitOutcome{}, ctx.Err() - case <-deadline.C: - timer.Stop() - return makeTimeout(), nil + outcome.timedOut = true + return outcome, nil } } } -func formatWaitOutcome(out waitOutcome, timeoutMS int, scale float64, returnImage bool) (map[string]any, error) { - if out.timedOut { - var reason string - switch out.mode { - case "stable": - reason = fmt.Sprintf("Screen did not settle within %dms.", timeoutMS) - case "change": - reason = fmt.Sprintf("Screen did not change within %dms.", timeoutMS) - default: - reason = fmt.Sprintf("Screen did not change and settle within %dms.", timeoutMS) - } - summary := fmt.Sprintf("%s timed_out=true mode=%s", reason, out.mode) - if !out.hasFrame { - return map[string]any{"content": []any{ - map[string]any{"type": "text", "text": summary + " sha256= blank=false"}, - }}, nil - } - return formatScreenResult(out.screen, out.frame.hash, summary, scale, returnImage) - } - summary := fmt.Sprintf("Screen ready. mode=%s", out.mode) - return formatScreenResult(out.screen, out.frame.hash, summary, scale, returnImage) -} - -type computerActionArgs 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"` - DurationMS int `json:"duration_ms"` - Horizontal bool `json:"horizontal"` - SettleMS int `json:"settle_ms"` - TimeoutMS int `json:"timeout_ms"` - StableMS int `json:"stable_ms"` - Baseline string `json:"baseline_sha256"` - Mode string `json:"mode"` - Tolerance float64 `json:"tolerance"` - AcceptBlank bool `json:"accept_blank"` - Scale float64 `json:"scale"` - ReturnImage *bool `json:"return_image"` -} - -func (s *Server) computerBatch(ctx context.Context, raw json.RawMessage) (any, error) { +func (s *Server) screenTool(ctx context.Context, raw json.RawMessage) (any, error) { var args struct { - VM string `json:"vm"` - Actions []computerActionArgs `json:"actions"` - Scale float64 `json:"scale"` - ReturnImage *bool `json:"return_image"` + VM string `json:"vm"` + Region *region `json:"region"` + Wait *waitArgs `json:"wait"` + Scale float64 `json:"scale"` + ReturnImage *bool `json:"return_image"` } if err := decodeArguments(raw, &args); err != nil { return nil, err } - if strings.TrimSpace(args.VM) == "" { - return nil, fmt.Errorf("%w: vm is required", errInvalidParams) - } - if len(args.Actions) == 0 { - return nil, fmt.Errorf("%w: actions must not be empty", errInvalidParams) - } scale, err := validateScale(args.Scale) if err != nil { return nil, err } returnImage := boolOrDefault(args.ReturnImage, true) - - var ( - executed int - lastScreen hostReply - lastFrame cachedFrame - hasScreen bool - ) - - for i, step := range args.Actions { - step.VM = args.VM - if step.Scale == 0 { - step.Scale = scale - } - act := strings.ToLower(strings.TrimSpace(step.Action)) - if act == "wait_stable" { - baseHash := step.Baseline - var baseGray []uint8 - if baseHash == "" { - if hasScreen { - baseHash = lastFrame.hash - baseGray = lastFrame.gray - } else if prev, ok := s.screens.lastFrameForVM(args.VM); ok { - baseHash = prev.hash - baseGray = prev.gray - } - } - out, waitErr := s.waitScreenInternal(ctx, waitOptions{ - VM: args.VM, - BaselineHash: baseHash, - BaselineGray: baseGray, - Mode: step.Mode, - TimeoutMS: step.TimeoutMS, - StableMS: step.StableMS, - Tolerance: step.Tolerance, - AcceptBlank: step.AcceptBlank, - Scale: step.Scale, - ReturnImage: false, - }) - if waitErr != nil { - return s.batchErrorResult(args.VM, executed, i+1, len(args.Actions), waitErr, lastScreen, lastFrame, hasScreen, scale, returnImage), nil - } - if out.hasFrame { - lastScreen, lastFrame, hasScreen = out.screen, out.frame, true - } - executed++ - continue - } - - // Execute single computer action. - res, screenOut, frameOut, gotScreen, stepErr := s.executeComputerAction(ctx, step) - _ = res - if stepErr != nil { - return s.batchErrorResult(args.VM, executed, i+1, len(args.Actions), stepErr, lastScreen, lastFrame, hasScreen, scale, returnImage), nil - } - if gotScreen { - lastScreen, lastFrame, hasScreen = screenOut, frameOut, true - } - executed++ - } - - if !hasScreen { - var screen hostReply - if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err == nil { - lastScreen = screen - lastFrame = s.screens.record(args.VM, screen) - hasScreen = true + // A region is measured in the image the client saw before this call. + var ref frameInfo + if args.Region != nil { + if ref, err = s.referenceFrame(ctx, args.VM); err != nil { + return nil, err } } - summary := fmt.Sprintf("Batch completed (%d/%d actions).", executed, len(args.Actions)) - if !hasScreen { - return map[string]any{"content": []any{ - map[string]any{"type": "text", "text": summary + " sha256= blank=false"}, - }}, nil - } - return formatScreenResult(lastScreen, lastFrame.hash, summary, scale, returnImage) -} - -func (s *Server) batchErrorResult(vm string, executed, failedStep, total int, stepErr error, lastScreen hostReply, lastFrame cachedFrame, hasScreen bool, scale float64, returnImage bool) map[string]any { - if !hasScreen { - var screen hostReply - if err := s.host.Call(context.Background(), "host/console.screenshot", map[string]any{"vm": vm}, &screen); err == nil { - lastScreen = screen - lastFrame = s.screens.record(vm, screen) - hasScreen = true + var waited *waitOutcome + if args.Wait != nil { + opts, err := s.resolveWait(args.VM, *args.Wait, maxScreenWaitMS, defaultStableMS) + if err != nil { + return nil, err } - } - summary := fmt.Sprintf("Batch failed at step %d/%d (executed=%d): %v", failedStep, total, executed, stepErr) - if !hasScreen { - return map[string]any{ - "isError": true, - "content": []any{map[string]any{"type": "text", "text": summary + " sha256= blank=false"}}, + opts.RetryHostErr, opts.Scale = true, scale + out, err := s.waitScreen(ctx, opts) + if err != nil { + return nil, err } + if args.Region == nil || out.timedOut { + return out.result(returnImage, nil), nil + } + waited = &out } - res, err := formatScreenResult(lastScreen, lastFrame.hash, summary, scale, returnImage) + if args.Region != nil { + screen, err := s.captureRegion(ctx, args.VM, *args.Region, ref, scale) + if err != nil { + return nil, err + } + extra := map[string]any{} + if waited != nil { + extra["sha256"] = waited.frame.hash + } + return regionObservation(screen).result(returnImage, extra), nil + } + screen, frame, err := s.capture(ctx, args.VM, scale) if err != nil { - return toolError(summary) + return nil, err } - res["isError"] = true - return res + return newObservation(screen, frame).result(returnImage, nil), nil } diff --git a/internal/mcp/screen_test.go b/internal/mcp/screen_test.go index 48c0d66..bb4459e 100644 --- a/internal/mcp/screen_test.go +++ b/internal/mcp/screen_test.go @@ -4,10 +4,13 @@ import ( "bytes" "context" "encoding/base64" + "encoding/json" + "errors" "image" "image/color" "image/jpeg" "strings" + "sync" "testing" ) @@ -15,39 +18,66 @@ type scriptedScreen struct { data string blank bool w, h int + err error } +// scriptedHost plays screens in order, repeating the last one, and accepts +// every other call. type scriptedHost struct { + mu sync.Mutex calls []hostCall screens []scriptedScreen idx int + failOn func(method string, params map[string]any) error } func (h *scriptedHost) Call(_ context.Context, method string, params any, out any) error { + h.mu.Lock() + defer h.mu.Unlock() h.calls = append(h.calls, hostCall{method: method, params: params}) - if method == "host/console.screenshot" { - i := h.idx - if i >= len(h.screens) { - i = len(h.screens) - 1 - } else { - h.idx++ + args, _ := params.(map[string]any) + if h.failOn != nil { + if err := h.failOn(method, args); err != nil { + return err } - sc := h.screens[i] - w, hgt := sc.w, sc.h - if w == 0 { - w, hgt = 320, 180 - } - *out.(*hostReply) = hostReply{ - Data: sc.data, MIMEType: "image/jpeg", Width: w, Height: hgt, SourceWidth: w * 2, SourceHeight: hgt * 2, Blank: sc.blank, + } + if method != "host/console.screenshot" { + if r, ok := out.(*hostReply); ok { + *r = hostReply{OK: true, Characters: 5} } return nil } - if r, ok := out.(*hostReply); ok { - *r = hostReply{OK: true, Characters: 5} + sc := h.screens[min(h.idx, len(h.screens)-1)] + h.idx++ + if sc.err != nil { + return sc.err } + w, hgt := sc.w, sc.h + if w == 0 { + w, hgt = 320, 180 + } + reply := hostReply{Data: sc.data, MIMEType: "image/jpeg", Width: w, Height: hgt, SourceWidth: w * 2, SourceHeight: hgt * 2, Blank: sc.blank} + if area, ok := args["region"].(region); ok { + reply.Region = &area + reply.Width, reply.Height = area.Width, area.Height + } + *out.(*hostReply) = reply return nil } +func (h *scriptedHost) callsTo(method string) []map[string]any { + h.mu.Lock() + defer h.mu.Unlock() + var found []map[string]any + for _, call := range h.calls { + if call.method == method { + args, _ := call.params.(map[string]any) + found = append(found, args) + } + } + return found +} + func makeFrame(t *testing.T, w, h int, bg color.RGBA, cursorOn bool) string { t.Helper() img := image.NewRGBA(image.Rect(0, 0, w, h)) @@ -70,132 +100,129 @@ func makeFrame(t *testing.T, w, h int, bg color.RGBA, cursorOn bool) string { return base64.StdEncoding.EncodeToString(buf.Bytes()) } -func TestWaitForScreenIgnoresBlinkingCursorAndSkipsBlank(t *testing.T) { +func structured(t *testing.T, result map[string]any) map[string]any { + t.Helper() + info, ok := result["structuredContent"].(map[string]any) + if !ok { + t.Fatalf("result has no structuredContent: %v", result) + } + var fromText map[string]any + if err := json.Unmarshal([]byte(resultText(t, result)), &fromText); err != nil || len(fromText) != len(info) { + t.Fatalf("text should be the structured result as compact JSON: %q", resultText(t, result)) + } + return info +} + +func TestScreenReportsImageSizeAndShortHash(t *testing.T) { + host := &scriptedHost{screens: []scriptedScreen{{data: makeFrame(t, 64, 36, color.RGBA{R: 40, A: 255}, false), w: 640, h: 360}}} + server := New() + server.BindHost(host) + result := callTool(t, server, "screen", `{"vm":"macos1","scale":0.5}`) + info := structured(t, result) + if info["width"] != float64(640) || info["height"] != float64(360) || info["source_width"] != float64(1280) || len(info["sha256"].(string)) != hashHexLength { + t.Fatalf("screen info = %v", info) + } + if result["content"].([]any)[0].(map[string]any)["type"] != "image" { + t.Fatal("screen should attach the image by default") + } + if got := host.callsTo("host/console.screenshot")[0]["max_width"]; got != 640 { + t.Fatalf("scale 0.5 should ask the host for 640 px, got %v", got) + } + if result := callTool(t, server, "screen", `{"vm":"macos1","return_image":false}`); len(result["content"].([]any)) != 1 { + t.Fatal("return_image false should leave only the text") + } +} + +func TestScreenRegionIsMeasuredInTheLastImage(t *testing.T) { + host := &scriptedHost{screens: []scriptedScreen{{data: makeFrame(t, 64, 36, color.RGBA{G: 90, A: 255}, false), w: 640, h: 360}}} + server := New() + server.BindHost(host) + callTool(t, server, "screen", `{"vm":"macos1","scale":0.5}`) + info := structured(t, callTool(t, server, "screen", `{"vm":"macos1","region":{"x":10,"y":20,"width":100,"height":50}}`)) + shots := host.callsTo("host/console.screenshot") + last := shots[len(shots)-1] + if last["region"] != (region{X: 10, Y: 20, Width: 100, Height: 50}) || last["width"] != 640 || last["height"] != 360 { + t.Fatalf("region request = %v", last) + } + if info["region"] == nil { + t.Fatalf("region result should report the source region: %v", info) + } + // A region is a detail view; it does not change the coordinate space. + if frame, _ := server.screens.lastFrame("macos1"); frame.width != 640 { + t.Fatalf("region capture replaced the reference image: %+v", frame) + } + if result := callTool(t, server, "screen", `{"vm":"macos1","region":{"x":700,"y":0,"width":10,"height":10}}`); result["isError"] != true { + t.Fatal("a region starting outside the image must fail") + } +} + +func TestScreenWaitIgnoresBlinkingCursorAndSkipsBlank(t *testing.T) { cursorOff := makeFrame(t, 320, 180, color.RGBA{R: 30, G: 40, B: 50, A: 255}, false) cursorOn := makeFrame(t, 320, 180, color.RGBA{R: 30, G: 40, B: 50, A: 255}, true) - blankFrame := makeFrame(t, 320, 180, color.RGBA{R: 0, G: 0, B: 0, A: 255}, false) - - host := &scriptedHost{ - screens: []scriptedScreen{ - {data: blankFrame, blank: true}, - {data: cursorOff, blank: false}, - {data: cursorOn, blank: false}, - {data: cursorOff, blank: false}, - {data: cursorOn, blank: false}, - }, - } + blankFrame := makeFrame(t, 320, 180, color.RGBA{A: 255}, false) + host := &scriptedHost{screens: []scriptedScreen{ + {data: blankFrame, blank: true}, {data: cursorOff}, {data: cursorOn}, {data: cursorOff}, {data: cursorOn}, + }} server := New() var logBuf bytes.Buffer server.logw = &logBuf server.BindHost(host) - - resp := sendRequest(t, server, `{"jsonrpc":"2.0","id":101,"method":"tools/call","params":{"name":"wait_for_screen","arguments":{"vm":"macos1","stable_ms":500,"timeout_ms":3000}}}`) - res := parseResponse(t, resp)["result"].(map[string]any) - if res["isError"] == true { - t.Fatalf("unexpected error: %s", resp) + info := structured(t, callTool(t, server, "screen", `{"vm":"macos1","wait":{"until":"stable","stable_ms":500,"timeout_ms":3000}}`)) + if info["timed_out"] != nil || info["blank"] != false { + t.Fatalf("expected a settled non-blank frame despite the blinking cursor: %v", info) } - text := res["content"].([]any)[1].(map[string]any)["text"].(string) - if strings.Contains(text, "timed_out=true") || !strings.Contains(text, "sha256=") || !strings.Contains(text, "blank=false") { - t.Fatalf("expected settled non-blank frame despite blinking cursor, got: %s", text) - } - if !strings.Contains(logBuf.String(), "tools/call wait_for_screen ") || !strings.Contains(logBuf.String(), " ok\n") { + if !strings.Contains(logBuf.String(), "tools/call screen ") || !strings.Contains(logBuf.String(), " ok\n") { t.Fatalf("expected tools/call log line, got: %q", logBuf.String()) } } -func TestWaitForScreenTimeoutReturnsLastFrameNotError(t *testing.T) { +func TestScreenWaitTimeoutReturnsLastFrameNotError(t *testing.T) { f1 := makeFrame(t, 320, 180, color.RGBA{R: 20, G: 20, B: 20, A: 255}, false) f2 := makeFrame(t, 320, 180, color.RGBA{R: 220, G: 220, B: 220, A: 255}, false) - host := &scriptedHost{screens: []scriptedScreen{{data: f1}, {data: f2}, {data: f1}, {data: f2}}} + host := &scriptedHost{screens: []scriptedScreen{{data: f1}, {data: f2}, {data: f1}, {data: f2}, {data: f1}, {data: f2}}} server := New() var logBuf bytes.Buffer server.logw = &logBuf server.BindHost(host) - - resp := sendRequest(t, server, `{"jsonrpc":"2.0","id":102,"method":"tools/call","params":{"name":"wait_for_screen","arguments":{"vm":"macos1","mode":"stable","stable_ms":600,"timeout_ms":600}}}`) - res := parseResponse(t, resp)["result"].(map[string]any) - if res["isError"] == true { - t.Fatalf("timeout should not set isError: %s", resp) + result := callTool(t, server, "screen", `{"vm":"macos1","wait":{"until":"stable","stable_ms":600,"timeout_ms":600}}`) + if result["isError"] == true || result["content"].([]any)[0].(map[string]any)["type"] != "image" { + t.Fatalf("a timeout should return the last frame without an error: %v", result) } - content := res["content"].([]any) - if len(content) != 2 || content[0].(map[string]any)["type"] != "image" { - t.Fatalf("expected last frame image on timeout: %s", resp) - } - text := content[1].(map[string]any)["text"].(string) - if !strings.Contains(text, "Screen did not settle within 600ms") || !strings.Contains(text, "timed_out=true mode=stable") { - t.Fatalf("unexpected timeout text: %s", text) + if info := structured(t, result); info["timed_out"] != true || info["until"] != "stable" { + t.Fatalf("timeout info = %v", info) } if !strings.Contains(logBuf.String(), " timeout\n") { t.Fatalf("expected timeout status in log, got: %q", logBuf.String()) } } -func TestClickReusesCachedSizeAndSupportsSettleObservation(t *testing.T) { +func TestScreenWaitForChangeStartsFromTheLastImage(t *testing.T) { before := makeFrame(t, 320, 180, color.RGBA{R: 10, G: 20, B: 30, A: 255}, false) after := makeFrame(t, 320, 180, color.RGBA{R: 200, G: 210, B: 220, A: 255}, false) - host := &scriptedHost{ - screens: []scriptedScreen{ - {data: before, w: 1280, h: 720}, - {data: after, w: 1280, h: 720}, - {data: after, w: 1280, h: 720}, - }, - } + host := &scriptedHost{screens: []scriptedScreen{{data: before}, {data: after}}} server := New() server.BindHost(host) - - // 1) Initial screenshot populates cache. - shot := sendRequest(t, server, `{"jsonrpc":"2.0","id":103,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"screenshot","scale":0.5}}}`) - shotText := parseResponse(t, shot)["result"].(map[string]any)["content"].([]any)[1].(map[string]any)["text"].(string) - if !strings.Contains(shotText, "sha256=") || !strings.Contains(shotText, "blank=false") { - t.Fatalf("screenshot missing sha256/blank: %s", shotText) + first := structured(t, callTool(t, server, "screen", `{"vm":"macos1"}`)) + // The screen changed between calls; the wait must still notice. + info := structured(t, callTool(t, server, "screen", `{"vm":"macos1","wait":{"until":"change","timeout_ms":2000}}`)) + if info["timed_out"] != nil || info["sha256"] == first["sha256"] { + t.Fatalf("wait for change should end on the new frame: first=%v now=%v", first, info) } - - // 2) Click without width/height must NOT call screenshot to discover size. - preCalls := len(host.calls) - _ = sendRequest(t, server, `{"jsonrpc":"2.0","id":104,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"left_click","x":100,"y":200}}}`) - for _, c := range host.calls[preCalls:] { - if c.method == "host/console.screenshot" { - t.Fatalf("left_click should reuse cached VM size without taking screenshot") - } - } - - // 3) Click with settle_ms waits for change and returns observation. - settled := sendRequest(t, server, `{"jsonrpc":"2.0","id":105,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"key","key":"return","settle_ms":200,"timeout_ms":2000,"return_image":false}}}`) - res := parseResponse(t, settled)["result"].(map[string]any) - content := res["content"].([]any) - if len(content) != 1 || content[0].(map[string]any)["type"] != "text" || !strings.Contains(content[0].(map[string]any)["text"].(string), "sha256=") { - t.Fatalf("expected text-only settled observation when return_image=false: %s", settled) + if result := callTool(t, server, "screen", `{"vm":"macos1","wait":{"baseline":"0000000000000000"}}`); result["isError"] != true { + t.Fatal("an unknown baseline must fail rather than wait against nothing") } } -func TestComputerBatchAndVMStartWaitUntil(t *testing.T) { - f1 := makeFrame(t, 320, 180, color.RGBA{R: 50, G: 50, B: 50, A: 255}, false) - f2 := makeFrame(t, 320, 180, color.RGBA{R: 150, G: 180, B: 200, A: 255}, false) - host := &scriptedHost{ - screens: []scriptedScreen{ - {data: f1, blank: true}, - {data: f1, blank: false}, - {data: f2, blank: false}, - }, - } +func TestScreenWaitRetriesHostErrorsWhileBooting(t *testing.T) { + ready := makeFrame(t, 320, 180, color.RGBA{R: 120, G: 140, B: 160, A: 255}, false) + host := &scriptedHost{screens: []scriptedScreen{{err: errors.New("vm is not running")}, {err: errors.New("vm is not running")}, {data: ready}}} server := New() server.BindHost(host) - - // vm_start with wait_until=screen skips blank and returns first non-blank frame. - startResp := sendRequest(t, server, `{"jsonrpc":"2.0","id":106,"method":"tools/call","params":{"name":"vm_start","arguments":{"vm":"macos1","wait_until":"screen","timeout_ms":3000}}}`) - startContent := parseResponse(t, startResp)["result"].(map[string]any)["content"].([]any) - if len(startContent) != 2 || !strings.Contains(startContent[1].(map[string]any)["text"].(string), "blank=false") { - t.Fatalf("vm_start wait_until=screen failed: %s", startResp) + info := structured(t, callTool(t, server, "screen", `{"vm":"macos1","wait":{"until":"stable","stable_ms":0,"timeout_ms":5000}}`)) + if info["timed_out"] != nil || info["blank"] != false { + t.Fatalf("wait should ride out capture errors during boot: %v", info) } - - // computer_batch runs click + type + key + wait_stable in one call. - batchResp := sendRequest(t, server, `{"jsonrpc":"2.0","id":107,"method":"tools/call","params":{"name":"computer_batch","arguments":{"vm":"macos1","actions":[{"action":"left_click","x":10,"y":10},{"action":"type","text":"hello"},{"action":"key","key":"return"},{"action":"wait_stable","stable_ms":100,"timeout_ms":2000}]}}}`) - batchRes := parseResponse(t, batchResp)["result"].(map[string]any) - if batchRes["isError"] == true { - t.Fatalf("computer_batch failed: %s", batchResp) - } - batchText := batchRes["content"].([]any)[1].(map[string]any)["text"].(string) - if !strings.Contains(batchText, "Batch completed (4/4 actions)") || !strings.Contains(batchText, "sha256=") { - t.Fatalf("unexpected batch summary: %s", batchText) + if result := callTool(t, server, "screen", `{"vm":"macos1","wait":{"timeout_ms":180001}}`); result["isError"] != true { + t.Fatal("timeout_ms above 180000 must fail") } } diff --git a/internal/mcp/server.go b/internal/mcp/server.go index 697e5d3..e118f12 100644 --- a/internal/mcp/server.go +++ b/internal/mcp/server.go @@ -3,15 +3,11 @@ package mcp import ( "bytes" "context" - "encoding/base64" "encoding/json" "errors" "fmt" - "image" - "image/jpeg" "io" "net" - "net/url" "os" "path/filepath" "strings" @@ -21,7 +17,15 @@ import ( "github.com/reims-go/reims-agent/internal/guest" ) -const protocolVersion = "2025-06-18" +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 @@ -29,14 +33,24 @@ type Host interface { type Server struct { host Host - callMu sync.Mutex - callsMu sync.Mutex - calls map[string]context.CancelFunc 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 { @@ -59,16 +73,17 @@ type rpcError struct { } 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"` - Characters int `json:"characters"` - VMs []any `json:"vms"` - OK bool `json:"ok"` + 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 { @@ -76,11 +91,13 @@ func New() *Server { if err != nil { root = "." } + root = filepath.Clean(root) return &Server{ - guest: guest.NewSSH(filepath.Clean(root)), - root: filepath.Clean(root), - state: newAgentState(filepath.Clean(root)), - calls: make(map[string]context.CancelFunc), + 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, } @@ -96,7 +113,12 @@ func (s *Server) logToolCall(name string, dur time.Duration, status string) { func (s *Server) BindHost(host Host) { s.host = host } -func (s *Server) Handle(ctx context.Context, raw json.RawMessage) (json.RawMessage, error) { +// 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 @@ -110,12 +132,9 @@ func (s *Server) Handle(ctx context.Context, raw json.RawMessage) (json.RawMessa RequestID json.RawMessage `json:"requestId"` } if json.Unmarshal(req.Params, ¶ms) == nil && validRequestID(params.RequestID) { - s.cancelRequest(params.RequestID) + s.cancelRequest(callKey{session, string(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) { @@ -124,46 +143,27 @@ func (s *Server) Handle(ctx context.Context, raw json.RawMessage) (json.RawMessa if ctx == nil { ctx = context.Background() } - if req.Method == "tools/call" || req.Method == "resources/read" { - requestCtx, cancel, ok := s.beginRequest(ctx, req.ID) + 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(req.ID, cancel) + defer s.finishRequest(key, cancel) ctx = requestCtx - serialized := true - if req.Method == "tools/call" { - var tool struct { - Name string `json:"name"` - } - if json.Unmarshal(req.Params, &tool) == nil { - switch tool.Name { - case "test_wait", "test_status", "test_logs", "test_result", "test_cancel": - serialized = false - } - } - } - if serialized { - 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) + 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 - if errors.Is(err, errUnknownMethod) { + switch { + case errors.Is(err, errUnknownMethod): code = -32601 - } - if errors.Is(err, errInvalidParams) { + case errors.Is(err, errInvalidParams): code = -32602 - } - if errors.Is(err, context.Canceled) { + case errors.Is(err, context.Canceled): code = -32800 } return marshal(response{JSONRPC: "2.0", ID: req.ID, Error: &rpcError{Code: code, Message: err.Error()}}) @@ -171,6 +171,22 @@ func (s *Server) Handle(ctx context.Context, raw json.RawMessage) (json.RawMessa 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 @@ -189,9 +205,8 @@ func validRequestID(raw json.RawMessage) bool { } } -func (s *Server) beginRequest(parent context.Context, id json.RawMessage) (context.Context, context.CancelFunc, bool) { +func (s *Server) beginRequest(parent context.Context, key callKey) (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 { @@ -202,52 +217,66 @@ func (s *Server) beginRequest(parent context.Context, id json.RawMessage) (conte return requestCtx, cancel, true } -func (s *Server) finishRequest(id json.RawMessage, cancel context.CancelFunc) { - key := string(id) +func (s *Server) finishRequest(key callKey, cancel context.CancelFunc) { s.callsMu.Lock() delete(s.calls, key) s.callsMu.Unlock() cancel() } -func (s *Server) cancelRequest(id json.RawMessage) { +func (s *Server) cancelRequest(key callKey) { s.callsMu.Lock() - cancel := s.calls[string(id)] + 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, method string, raw json.RawMessage) (any, error) { +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}, "resources": map[string]any{"subscribe": false, "listChanged": false}}, - "serverInfo": map[string]any{"name": "reims-agent", "version": "0.1.0"}, + "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": toolCatalog}, nil - case "resources/list": - return s.listResources(ctx) + return map[string]any{"tools": toolList(dev)}, nil case "tools/call": - return s.callTool(ctx, raw) - case "resources/read": - return s.readResource(ctx, raw) + return s.callTool(ctx, dev, raw) default: return nil, fmt.Errorf("%w: %s", errUnknownMethod, method) } } -func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (any, error) { +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"` @@ -255,11 +284,29 @@ func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (any, error) 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 { @@ -277,15 +324,8 @@ func (s *Server) callTool(ctx context.Context, raw json.RawMessage) (any, error) if m, ok := result.(map[string]any); ok { if isErr, _ := m["isError"].(bool); isErr { status = "error" - } - if items, ok := m["content"].([]any); ok { - for _, it := range items { - if entry, ok := it.(map[string]any); ok { - if txt, _ := entry["text"].(string); strings.Contains(txt, "timed_out=true") { - status = "timeout" - } - } - } + } else if info, ok := m["structuredContent"].(map[string]any); ok && info["timed_out"] == true { + status = "timeout" } } s.logToolCall(req.Name, dur, status) @@ -316,74 +356,16 @@ func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) ( return nil, err } return textResult(out), nil - case "vm_start": - return s.vmStart(ctx, raw) - case "vm_shutdown", "vm_suspend", "vm_resume": - var args struct { - VM string `json:"vm"` - } - if err := decodeArguments(raw, &args); err != nil { - return nil, err - } - var out hostReply - method := "host/vm." + strings.TrimPrefix(name, "vm_") - if err := s.host.Call(ctx, method, args, &out); err != nil { - return nil, err - } - return textResult(map[string]any{"ok": true}), nil + case "vm_power": + return s.vmPower(ctx, raw) case "vm_unlock": return s.vmUnlock(ctx, raw) - case "computer": - return s.computer(ctx, raw) - case "computer_batch": - return s.computerBatch(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 "screen": + return s.screenTool(ctx, raw) + case "computer_input": + return s.computerInput(ctx, raw) 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 + return s.guestWaitReady(ctx, raw) case "guest_trust_host": var args struct { VM string `json:"vm"` @@ -392,13 +374,13 @@ func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) ( 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 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 } @@ -462,30 +444,14 @@ func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) ( 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 case "session_create": var args struct { - VM string `json:"vm"` - BaseSnapshot string `json:"base_snapshot"` - Isolation string `json:"isolation"` + VM string `json:"vm"` } if err := decodeArguments(raw, &args); err != nil { return nil, err } - result, err := s.createSession(ctx, args.VM, args.BaseSnapshot, args.Isolation) + result, err := s.createSession(ctx, args.VM) if err != nil { return nil, err } @@ -510,19 +476,45 @@ func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) ( return s.startTestRun(ctx, raw) case "test_wait": return s.waitTestRun(ctx, raw) - case "test_status": - return s.statusTestRun(raw) - case "test_logs": - return s.logsTestRun(raw) - case "test_result": - return s.resultTestRun(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) @@ -551,94 +543,59 @@ func (s *Server) vmInfo(ctx context.Context, ref string) (map[string]any, error) return vm, nil } -func (s *Server) vmStart(ctx context.Context, raw json.RawMessage) (any, error) { +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"` - WaitUntil string `json:"wait_until"` - TimeoutMS int `json:"timeout_ms"` - StableMS int `json:"stable_ms"` - Scale float64 `json:"scale"` - ReturnImage *bool `json:"return_image"` + VM string `json:"vm"` + Action string `json:"action"` } if err := decodeArguments(raw, &args); err != nil { return nil, err } - waitUntil := strings.ToLower(strings.TrimSpace(args.WaitUntil)) - if waitUntil == "" { - waitUntil = "none" + method, ok := powerMethods[args.Action] + if !ok { + return nil, fmt.Errorf("%w: action must be start, shutdown, force_stop, suspend or resume", errInvalidParams) } - switch waitUntil { - case "none", "screen", "stable": - default: - return nil, fmt.Errorf("%w: wait_until must be none, screen, or stable", errInvalidParams) - } - scale, err := validateScale(args.Scale) - if err != nil { - return nil, err + params := map[string]any{"vm": args.VM} + if args.Action == "force_stop" { + params["force"] = true } var out hostReply - if err := s.host.Call(ctx, "host/vm.start", map[string]any{"vm": args.VM}, &out); err != nil { + if err := s.host.Call(ctx, method, params, &out); err != nil { return nil, err } - if waitUntil == "none" { - return textResult(map[string]any{"ok": true}), nil - } - timeoutMS := args.TimeoutMS - if timeoutMS <= 0 { - timeoutMS = 120000 - } - stableMS := args.StableMS - if waitUntil == "screen" { - stableMS = 0 - } else if stableMS <= 0 { - stableMS = 2000 - } - waitRes, err := s.waitScreenInternal(ctx, waitOptions{ - VM: args.VM, - Mode: "stable", - TimeoutMS: timeoutMS, - MaxTimeoutMS: 180000, - StableMS: stableMS, - AcceptBlank: false, - RetryHostErr: true, - Scale: scale, - ReturnImage: boolOrDefault(args.ReturnImage, true), - }) - if err != nil { - return nil, err - } - return formatWaitOutcome(waitRes, timeoutMS, scale, boolOrDefault(args.ReturnImage, true)) + 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"` - TimeoutMS int `json:"timeout_ms"` - StableMS int `json:"stable_ms"` - Scale float64 `json:"scale"` - ReturnImage *bool `json:"return_image"` + 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) + // 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 } - scale, err := validateScale(args.Scale) - if err != nil { - return nil, err - } - returnImage := boolOrDefault(args.ReturnImage, true) - - // Capture or reuse baseline frame before pressing Return so we wait until - // the display leaves the login screen and skips transitional blank frames. - var baseHash string - var baseGray []uint8 - if prev, ok := s.screens.lastFrameForVM(args.VM); ok && !prev.blank { - baseHash = prev.hash - baseGray = prev.gray - } - 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) @@ -647,388 +604,35 @@ func (s *Server) vmUnlock(ctx context.Context, raw json.RawMessage) (any, error) if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": "ret"}, &key); err != nil { return nil, err } - - timeoutMS := args.TimeoutMS - if timeoutMS <= 0 { - timeoutMS = 20000 - } - stableMS := args.StableMS - if stableMS < 0 { - return nil, fmt.Errorf("%w: stable_ms must be >= 0", errInvalidParams) - } - if args.StableMS == 0 && args.TimeoutMS == 0 { - stableMS = 1500 - } - mode := "change_then_stable" - if baseHash == "" { - mode = "stable" - } - waitRes, err := s.waitScreenInternal(ctx, waitOptions{ - VM: args.VM, - BaselineHash: baseHash, - BaselineGray: baseGray, - Mode: mode, - TimeoutMS: timeoutMS, - MaxTimeoutMS: 60000, - StableMS: stableMS, - AcceptBlank: false, - Scale: scale, - ReturnImage: returnImage, + 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 } - if waitRes.timedOut { - return formatWaitOutcome(waitRes, timeoutMS, scale, returnImage) - } - return formatScreenResult(waitRes.screen, waitRes.frame.hash, "Login password entered. Current screen attached.", scale, returnImage) -} - -func (s *Server) computer(ctx context.Context, raw json.RawMessage) (any, error) { - var args computerActionArgs - if err := decodeArguments(raw, &args); err != nil { - return nil, err - } - res, _, _, _, err := s.executeComputerAction(ctx, args) - return res, err -} - -func (s *Server) executeComputerAction(ctx context.Context, args computerActionArgs) (any, hostReply, cachedFrame, bool, error) { - if args.VM == "" { - return nil, hostReply{}, cachedFrame{}, false, fmt.Errorf("%w: vm is required", errInvalidParams) - } - scale, err := validateScale(args.Scale) - if err != nil { - return nil, hostReply{}, cachedFrame{}, false, err - } - returnImage := boolOrDefault(args.ReturnImage, true) - if args.SettleMS < 0 || args.SettleMS > 30000 { - return nil, hostReply{}, cachedFrame{}, false, fmt.Errorf("%w: settle_ms must be between 0 and 30000", 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, hostReply{}, cachedFrame{}, false, err - } - cf := s.screens.record(args.VM, screen) - summary := fmt.Sprintf("Screen %dx%d, framebuffer %dx%d", screen.Width, screen.Height, screen.SourceWidth, screen.SourceHeight) - res, err := formatScreenResult(screen, cf.hash, summary, scale, returnImage) - return res, screen, cf, true, err - } - 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, hostReply{}, cachedFrame{}, false, err - } - cf := s.screens.record(args.VM, screen) - cropped, width, height, err := cropJPEG(screen.Data, args.X, args.Y, args.Width, args.Height) - if err != nil { - return nil, hostReply{}, cachedFrame{}, false, err - } - text := fmt.Sprintf("Crop %dx%d sha256=%s blank=%t", width, height, cf.hash, screen.Blank) - if !returnImage { - return map[string]any{"content": []any{map[string]any{"type": "text", "text": text}}}, screen, cf, true, nil - } - return map[string]any{"content": []any{ - map[string]any{"type": "image", "data": cropped, "mimeType": "image/jpeg"}, - map[string]any{"type": "text", "text": text}, - }}, screen, cf, true, nil - } - if action == "wait" { - waitMS := args.DurationMS - if waitMS == 0 { - waitMS = args.Delta - } - timeout := time.Duration(waitMS) * time.Millisecond - if timeout < 0 || timeout > 30*time.Second { - return nil, hostReply{}, cachedFrame{}, false, fmt.Errorf("%w: wait duration_ms/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, hostReply{}, cachedFrame{}, false, ctx.Err() - } - return textResult(map[string]any{"waited_ms": timeout.Milliseconds()}), hostReply{}, cachedFrame{}, false, nil - } - - var preFrame cachedFrame - var hasPreFrame bool - if args.SettleMS > 0 { - preFrame, hasPreFrame = s.screens.lastFrameForVM(args.VM) - } - - var baseResult any - switch action { - case "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, hostReply{}, cachedFrame{}, false, err - } - baseResult = textResult(map[string]any{"characters": out.Characters}) - case "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, hostReply{}, cachedFrame{}, false, err - } - baseResult = textResult(map[string]any{"ok": true}) - case "left_click", "right_click", "middle_click", "double_click": - buttonActions := map[string]string{"left_click": "left", "right_click": "right", "middle_click": "middle", "double_click": "left"} - button := buttonActions[action] - if err := s.movePointer(ctx, args); err != nil { - return nil, hostReply{}, cachedFrame{}, false, 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, hostReply{}, cachedFrame{}, false, err - } - } - baseResult = textResult(map[string]any{"ok": true}) - case "mouse_move": - if err := s.movePointer(ctx, args); err != nil { - return nil, hostReply{}, cachedFrame{}, false, err - } - baseResult = textResult(map[string]any{"ok": true}) - case "left_click_drag": - if err := s.movePointer(ctx, args); err != nil { - return nil, hostReply{}, cachedFrame{}, false, 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, hostReply{}, cachedFrame{}, false, 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() }() - dragEnd := args - dragEnd.X, dragEnd.Y = args.X2, args.Y2 - if err := s.movePointer(ctx, dragEnd); err != nil { - return nil, hostReply{}, cachedFrame{}, false, err - } - if err := release(); err != nil { - return nil, hostReply{}, cachedFrame{}, false, err - } - baseResult = textResult(map[string]any{"ok": true}) - case "scroll": - if err := s.movePointer(ctx, args); err != nil { - return nil, hostReply{}, cachedFrame{}, false, 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, hostReply{}, cachedFrame{}, false, err - } - baseResult = textResult(map[string]any{"ok": true}) - default: - return nil, hostReply{}, cachedFrame{}, false, fmt.Errorf("unknown computer action %q", action) - } - - if args.SettleMS > 0 { - timeoutMS := args.TimeoutMS - if timeoutMS <= 0 { - timeoutMS = min(30000, max(args.SettleMS+5000, 10000)) - } - waitOpts := waitOptions{ - VM: args.VM, - Mode: "change_then_stable", - TimeoutMS: timeoutMS, - StableMS: args.SettleMS, - Tolerance: args.Tolerance, - AcceptBlank: args.AcceptBlank, - Scale: scale, - ReturnImage: returnImage, - } - if hasPreFrame { - waitOpts.BaselineHash = preFrame.hash - waitOpts.BaselineGray = preFrame.gray - } else { - waitOpts.Mode = "stable" - } - waitRes, waitErr := s.waitScreenInternal(ctx, waitOpts) - if waitErr != nil { - return nil, hostReply{}, cachedFrame{}, false, waitErr - } - res, fmtErr := formatWaitOutcome(waitRes, timeoutMS, scale, returnImage) - return res, waitRes.screen, waitRes.frame, waitRes.hasFrame, fmtErr - } - - return baseResult, hostReply{}, cachedFrame{}, false, nil -} - -func (s *Server) movePointer(ctx context.Context, args computerActionArgs) error { - if args.Width <= 0 || args.Height <= 0 { - if w, h, ok := s.screens.sizeForVM(args.VM); ok { - args.Width, args.Height = w, h - } else { - var screen hostReply - if err := s.host.Call(ctx, "host/console.screenshot", map[string]any{"vm": args.VM}, &screen); err != nil { - return err - } - s.screens.record(args.VM, screen) - 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"` - Mode string `json:"mode"` - TimeoutMS int `json:"timeout_ms"` - StableMS int `json:"stable_ms"` - Tolerance float64 `json:"tolerance"` - AcceptBlank bool `json:"accept_blank"` - 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 - } - timeoutMS := args.TimeoutMS - if timeoutMS <= 0 { - timeoutMS = 10000 - } - out, err := s.waitScreenInternal(ctx, waitOptions{ - VM: args.VM, - BaselineHash: args.Baseline, - Mode: args.Mode, - TimeoutMS: timeoutMS, - StableMS: args.StableMS, - Tolerance: args.Tolerance, - AcceptBlank: args.AcceptBlank, - Scale: scale, - ReturnImage: boolOrDefault(args.ReturnImage, true), - }) - if err != nil { - return nil, err - } - return formatWaitOutcome(out, timeoutMS, scale, boolOrDefault(args.ReturnImage, true)) -} - -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 + return out.result(true, nil), nil } func decodeArguments(raw json.RawMessage, target any) error { if len(raw) == 0 { raw = json.RawMessage(`{}`) } - if err := json.Unmarshal(raw, target); err != nil { + // 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.MarshalIndent(value, "", " ") + encoded, err := json.Marshal(value) if err != nil { return toolError(err.Error()) } @@ -1039,137 +643,3 @@ 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 and optionally wait until a non-blank screen appears or settles.", "inputSchema": objectSchema(map[string]any{ - "vm": map[string]any{"type": "string", "description": "VM reference (name or driver_id:name)."}, - "wait_until": map[string]any{"type": "string", "enum": []string{"none", "screen", "stable"}, "description": "Optional post-start wait: none (default), screen (first non-blank frame), or stable (non-blank frame settled for stable_ms)."}, - "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 180000, "description": "Wait timeout in milliseconds when wait_until != none (default 120000, max 180000)."}, - "stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "Required stability duration in milliseconds when wait_until is stable (default 2000)."}, - "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0) to reduce payload size."}, - "return_image": map[string]any{"type": "boolean", "description": "Whether to include the screenshot image (default true). Set false to return only sha256 and metadata."}, - }, []string{"vm"})}, - {"name": "vm_shutdown", "description": "Request a normal guest shutdown.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string", "description": "VM reference."}}, []string{"vm"})}, - {"name": "snapshot_list", "description": "List restore points for an authorized virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})}, - {"name": "snapshot_create", "description": "Create a restore point for an authorized virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "name": map[string]any{"type": "string"}}, []string{"vm", "name"})}, - {"name": "snapshot_restore", "description": "Restore a restore point on an MCP-owned temporary VM.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "name": map[string]any{"type": "string"}}, []string{"vm", "name"})}, - {"name": "session_create", "description": "Create an isolated CoW VM session for a test run. Restore-point bases are unavailable on the current host.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "isolation": map[string]any{"type": "string", "enum": []string{"clone", "live"}}}, []string{"vm"})}, - {"name": "session_dispose", "description": "Dispose an MCP-owned temporary VM session.", "inputSchema": objectSchema(map[string]any{"session_id": map[string]any{"type": "string"}}, []string{"session_id"})}, - {"name": "vm_suspend", "description": "Save a running VM state and stop its process.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string", "description": "VM reference."}}, []string{"vm"})}, - {"name": "vm_resume", "description": "Restore a suspended VM from its saved state.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string", "description": "VM reference."}}, []string{"vm"})}, - {"name": "vm_unlock", "description": "Type the macOS login password saved in the Reims-Go MCP Service settings into the VM's login screen, wait for the desktop to settle (skipping transitional blank frames), and return the screen. Requires the VM, or the source VM of an MCP clone, to have a saved login password.", "inputSchema": objectSchema(map[string]any{ - "vm": map[string]any{"type": "string", "description": "VM reference."}, - "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 60000, "description": "Max milliseconds to wait for the unlocked screen to settle (default 20000)."}, - "stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "Stability window in milliseconds after leaving the login screen (default 1500)."}, - "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0)."}, - "return_image": map[string]any{"type": "boolean", "description": "Whether to attach the resulting screen image (default true)."}, - }, []string{"vm"})}, - {"name": "computer", "description": "Capture or interact with a virtual machine display. Coordinates are based on the most recent screenshot size; width and height may be omitted.", "inputSchema": objectSchema(map[string]any{ - "vm": map[string]any{"type": "string", "description": "VM reference."}, - "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"}, "description": "Action to perform on the VM display."}, - "x": map[string]any{"type": "integer", "description": "X coordinate in the most recent screenshot pixel space."}, - "y": map[string]any{"type": "integer", "description": "Y coordinate in the most recent screenshot pixel space."}, - "width": map[string]any{"type": "integer", "description": "Reference width (optional for clicks/moves/scroll; defaults to the cached last screenshot width; required for zoom)."}, - "height": map[string]any{"type": "integer", "description": "Reference height (optional for clicks/moves/scroll; defaults to the cached last screenshot height; required for zoom)."}, - "button": map[string]any{"type": "string", "enum": []string{"left", "right", "middle"}, "description": "Mouse button name."}, - "text": map[string]any{"type": "string", "description": "UTF-8 text to type for action=type."}, - "key": map[string]any{"type": "string", "description": "Key name for action=key (e.g. return, esc, tab, space, up, down, left, right, page_up, page_down, a-z, 0-9)."}, - "modifiers": map[string]any{"type": "array", "items": map[string]any{"type": "string"}, "description": "Modifier keys for action=key (cmd/command, ctrl/control, alt/option, shift)."}, - "x2": map[string]any{"type": "integer", "description": "Drag destination X coordinate for action=left_click_drag."}, - "y2": map[string]any{"type": "integer", "description": "Drag destination Y coordinate for action=left_click_drag."}, - "duration_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "Wait duration in milliseconds for action=wait (preferred over delta)."}, - "delta": map[string]any{"type": "integer", "description": "Scroll amount for action=scroll, or legacy wait duration in milliseconds for action=wait."}, - "horizontal": map[string]any{"type": "boolean", "description": "Scroll horizontally when true for action=scroll."}, - "settle_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "When >0 on input actions, wait for the screen to change and settle for settle_ms and return the resulting screenshot and sha256."}, - "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000, "description": "Optional timeout in milliseconds when settle_ms > 0."}, - "tolerance": map[string]any{"type": "number", "minimum": 0, "maximum": 1, "description": "Pixel-diff ratio tolerance (default 0.002 = 0.2%) used with settle_ms."}, - "accept_blank": map[string]any{"type": "boolean", "description": "Whether blank frames satisfy settle_ms (default false)."}, - "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0)."}, - "return_image": map[string]any{"type": "boolean", "description": "Whether to attach the screenshot image (default true)."}, - }, []string{"vm", "action"})}, - {"name": "computer_batch", "description": "Run a sequence of computer actions (plus wait_stable) in one round-trip, stopping on first error and returning the final frame and sha256.", "inputSchema": objectSchema(map[string]any{ - "vm": map[string]any{"type": "string", "description": "VM reference."}, - "actions": map[string]any{ - "type": "array", - "minItems": 1, - "description": "Ordered list of computer actions or wait_stable steps.", - "items": map[string]any{ - "type": "object", - "properties": map[string]any{ - "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", "wait_stable"}, "description": "Step action name."}, - "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"}, - "duration_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000}, - "delta": map[string]any{"type": "integer"}, - "horizontal": map[string]any{"type": "boolean"}, - "settle_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000}, - "baseline_sha256": map[string]any{"type": "string"}, - "mode": map[string]any{"type": "string", "enum": []string{"stable", "change", "change_then_stable"}}, - "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000}, - "stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000}, - "tolerance": map[string]any{"type": "number", "minimum": 0, "maximum": 1}, - "accept_blank": map[string]any{"type": "boolean"}, - }, - "required": []string{"action"}, - "additionalProperties": false, - }, - }, - "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0) for the final frame."}, - "return_image": map[string]any{"type": "boolean", "description": "Whether to attach the final screenshot image (default true)."}, - }, []string{"vm", "actions"})}, - {"name": "wait_for_screen", "description": "Wait for a virtual machine screen frame to change or settle (ignoring blinking cursor noise). On timeout, returns the last frame with timed_out=true instead of an error.", "inputSchema": objectSchema(map[string]any{ - "vm": map[string]any{"type": "string", "description": "VM reference."}, - "baseline_sha256": map[string]any{"type": "string", "description": "Previous frame sha256 to compare against."}, - "mode": map[string]any{"type": "string", "enum": []string{"stable", "change", "change_then_stable"}, "description": "Wait mode: defaults to stable when baseline_sha256 is omitted, or change_then_stable when baseline_sha256 is provided."}, - "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 30000, "description": "Maximum wait duration in milliseconds (default 10000, max 30000)."}, - "stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "Required stability duration in milliseconds."}, - "tolerance": map[string]any{"type": "number", "minimum": 0, "maximum": 1, "description": "Fraction of 160x90 luma pixels differing by >16 to count as changed (default 0.002 = 0.2%)."}, - "accept_blank": map[string]any{"type": "boolean", "description": "When true, blank frames may satisfy the wait (default false)."}, - "scale": map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Optional image downscale factor (0.25 to 1.0)."}, - "return_image": map[string]any{"type": "boolean", "description": "Whether to attach the final screenshot image (default true)."}, - }, []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"})}, - {"name": "test_run", "description": "Start a configured test run and return its run id.", "inputSchema": objectSchema(map[string]any{ - "config": map[string]any{ - "type": "object", - "properties": map[string]any{ - "vm": map[string]any{"type": "string"}, - "isolation": map[string]any{"type": "string", "enum": []string{"clone", "live"}}, - "workspace": map[string]any{"type": "string"}, - "sync": map[string]any{"type": "object", "properties": map[string]any{"dest": map[string]any{"type": "string"}, "exclude": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}}, "additionalProperties": false}, - "steps": map[string]any{"type": "array", "minItems": 1, "items": map[string]any{"type": "object", "properties": map[string]any{"name": map[string]any{"type": "string"}, "run": map[string]any{"type": "string"}, "cwd": map[string]any{"type": "string"}, "timeout": map[string]any{"type": "string"}}, "required": []string{"run"}, "additionalProperties": false}}, - "junit": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, - "artifacts": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}, - "keep_on_failure": map[string]any{"type": "boolean"}, - }, - "required": []string{"vm", "steps"}, - "additionalProperties": false, - }, - "workspace": map[string]any{"type": "string"}, - }, []string{"config"})}, - {"name": "test_wait", "description": "Wait for a test run to finish or return its current status.", "inputSchema": objectSchema(map[string]any{"run_id": map[string]any{"type": "string"}, "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 300000}}, []string{"run_id"})}, - {"name": "test_status", "description": "Read the current status of a test run.", "inputSchema": objectSchema(map[string]any{"run_id": map[string]any{"type": "string"}}, []string{"run_id"})}, - {"name": "test_logs", "description": "Read a bounded page from a test run log.", "inputSchema": objectSchema(map[string]any{"run_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{"run_id"})}, - {"name": "test_result", "description": "Read the structured result of a test run.", "inputSchema": objectSchema(map[string]any{"run_id": map[string]any{"type": "string"}}, []string{"run_id"})}, - {"name": "test_cancel", "description": "Cancel an active test run and clean up its temporary VM.", "inputSchema": objectSchema(map[string]any{"run_id": map[string]any{"type": "string"}}, []string{"run_id"})}, -} - -func objectSchema(properties map[string]any, required []string) map[string]any { - return map[string]any{"type": "object", "properties": properties, "required": required, "additionalProperties": false} -} diff --git a/internal/mcp/server_test.go b/internal/mcp/server_test.go index 1c67025..f4f457e 100644 --- a/internal/mcp/server_test.go +++ b/internal/mcp/server_test.go @@ -3,19 +3,18 @@ package mcp import ( "bytes" "context" - "crypto/sha256" "encoding/base64" - "encoding/hex" "encoding/json" "errors" "image" "image/color" "image/jpeg" + "os" + "path/filepath" "strings" + "sync" "testing" "time" - - "github.com/reims-go/reims-agent/internal/guest" ) type hostCall struct { @@ -24,13 +23,13 @@ type hostCall struct { } type testHost struct { - calls []hostCall - frames []string - frameIndex int - secretValue string - secretErr error - vmPhase string - deleteErr error + mu sync.Mutex + calls []hostCall + frames []string + frameIndex int + secretErr error + vmPhase string + deleteErr error } type blockingHost struct{ started chan struct{} } @@ -41,56 +40,15 @@ func (h blockingHost) Call(ctx context.Context, _ string, _ any, _ any) error { return nil } -type deadlineHost struct{} - -func (deadlineHost) Call(ctx context.Context, _ string, _ any, _ any) error { - <-ctx.Done() - return ctx.Err() -} - -type dragCancellationHost struct { - cancel context.CancelFunc - moves int - buttonStates []bool - releaseErr error -} - -func (h *dragCancellationHost) Call(ctx context.Context, method string, params any, out any) error { - if method != "host/console.pointer" { - return errors.New("unexpected host method") - } - args := params.(map[string]any) - switch args["action"] { - case "button": - down := args["down"].(bool) - h.buttonStates = append(h.buttonStates, down) - if !down { - h.releaseErr = ctx.Err() - } - case "move": - h.moves++ - if h.moves == 2 { - h.cancel() - return ctx.Err() - } - default: - return errors.New("unexpected pointer action") - } - *out.(*hostReply) = hostReply{OK: true} - return nil -} - func (h *testHost) Call(_ context.Context, method string, params any, out any) error { + h.mu.Lock() + defer h.mu.Unlock() h.calls = append(h.calls, hostCall{method: method, params: params}) if strings.HasSuffix(method, "screenshot") { - frame := h.frames[0] - if h.frameIndex < len(h.frames) { - frame = h.frames[h.frameIndex] - h.frameIndex++ - } - *out.(*hostReply) = hostReply{ - Data: frame, MIMEType: "image/jpeg", Width: 2, Height: 2, SourceWidth: 2, SourceHeight: 2, - } + // Frames play in order and the last one repeats. + frame := h.frames[min(h.frameIndex, len(h.frames)-1)] + h.frameIndex++ + *out.(*hostReply) = hostReply{Data: frame, MIMEType: "image/jpeg", Width: 2, Height: 2, SourceWidth: 2, SourceHeight: 2} return nil } if strings.HasSuffix(method, "typeSecret") { @@ -121,18 +79,30 @@ func (h *testHost) Call(_ context.Context, method string, params any, out any) e return nil } +func (h *testHost) methods() []string { + h.mu.Lock() + defer h.mu.Unlock() + names := make([]string, len(h.calls)) + for i, call := range h.calls { + names[i] = call.method + } + return names +} + func TestMCPInitializeAndVMGet(t *testing.T) { host := &testHost{} server := New() server.BindHost(host) - initialized := sendRequest(t, server, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`) - if !strings.Contains(string(initialized), protocolVersion) { - t.Fatalf("initialize response missing protocol version: %s", initialized) + initialized := parseResponse(t, sendRequest(t, server, `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`))["result"].(map[string]any) + if initialized["protocolVersion"] != protocolVersion || initialized["serverInfo"].(map[string]any)["version"] != serverVersion { + t.Fatalf("initialize = %+v", initialized) } - response := sendRequest(t, server, `{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"vm_get","arguments":{"vm":"macos1"}}}`) - content := parseResponse(t, response)["result"].(map[string]any)["content"].([]any) - if !strings.Contains(content[0].(map[string]any)["text"].(string), `"name": "macos1"`) { - t.Fatalf("vm_get response missing VM detail: %s", response) + if _, ok := initialized["capabilities"].(map[string]any)["resources"]; ok { + t.Fatal("the screen resource was removed; resources must not be advertised") + } + result := callTool(t, server, "vm_get", `{"vm":"macos1"}`) + if text := resultText(t, result); !strings.Contains(text, `"name":"macos1"`) { + t.Fatalf("vm_get should return compact JSON: %s", text) } if len(host.calls) != 1 || host.calls[0].method != "host/vm.get" { t.Fatalf("VM call route = %+v", host.calls) @@ -154,155 +124,128 @@ func TestMCPRejectsInvalidRequestIDs(t *testing.T) { } } -func TestReadResourceReportsUnavailableHost(t *testing.T) { - server := New() - response := sendRequest(t, server, `{"jsonrpc":"2.0","id":34,"method":"resources/read","params":{"uri":"reims://vm/macos1/screen"}}`) - failure, ok := parseResponse(t, response)["error"].(map[string]any) - message := "" - if ok { - message, _ = failure["message"].(string) - } - if !ok || failure["code"] != float64(-32000) || !strings.Contains(message, "unavailable") { - t.Fatalf("resources/read response = %s", response) - } -} - -func TestSuspendAndResumeUseLifecycleHostMethods(t *testing.T) { - for tool, method := range map[string]string{"vm_suspend": "host/vm.suspend", "vm_resume": "host/vm.resume"} { - t.Run(tool, func(t *testing.T) { - server := New() - host := &testHost{} - server.BindHost(host) - request := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"` + tool + `","arguments":{"vm":"driver:macos1"}}}` - response := parseResponse(t, sendRequest(t, server, request)) - result, ok := response["result"].(map[string]any) - if !ok || result["isError"] == true { - t.Fatalf("tool response = %v", response) - } - if len(host.calls) != 1 || host.calls[0].method != method { - t.Fatalf("host calls = %v, want %s", host.calls, method) - } - args, err := json.Marshal(host.calls[0].params) - if err != nil || string(args) != `{"vm":"driver:macos1"}` { - t.Fatalf("host arguments = %s, err = %v", args, err) - } - }) - } -} - -func TestGuestToolsAreAdvertisedAndPublicKeyIsAvailable(t *testing.T) { - server := New() - server.guest = guest.NewSSH(t.TempDir()) - server.BindHost(&testHost{}) - response := sendRequest(t, server, `{"jsonrpc":"2.0","id":7,"method":"tools/list","params":{}}`) - encoded, err := json.Marshal(parseResponse(t, response)["result"].(map[string]any)["tools"]) +func listedTools(t *testing.T, server *Server, channel string) map[string]map[string]any { + t.Helper() + raw, err := server.Handle(context.Background(), channel, "", json.RawMessage(`{"jsonrpc":"2.0","id":7,"method":"tools/list","params":{}}`)) if err != nil { t.Fatal(err) } - for _, name := range []string{"guest_public_key", "guest_wait_ready", "guest_trust_host", "guest_exec", "guest_put", "guest_get", "guest_logs"} { - if !strings.Contains(string(encoded), `"name":"`+name+`"`) { - t.Errorf("MCP tool list is missing %s", name) + listed := map[string]map[string]any{} + for _, item := range parseResponse(t, raw)["result"].(map[string]any)["tools"].([]any) { + entry := item.(map[string]any) + listed[entry["name"].(string)] = entry + } + return listed +} + +func TestChannelsServeCoreAndDevToolsets(t *testing.T) { + server := New() + server.BindHost(&testHost{}) + core := listedTools(t, server, ChannelCore) + dev := listedTools(t, server, ChannelDev) + wantCore := []string{"vm_list", "vm_get", "vm_power", "vm_unlock", "screen", "computer_input"} + if len(core) != len(wantCore) { + t.Fatalf("core toolset = %d tools, want %d", len(core), len(wantCore)) + } + for _, name := range wantCore { + if core[name] == nil || dev[name] == nil { + t.Errorf("%s must be served on both channels", name) } } - key := sendRequest(t, server, `{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"guest_public_key","arguments":{"vm":"macos1"}}}`) - content := parseResponse(t, key)["result"].(map[string]any)["content"].([]any) - text := content[0].(map[string]any)["text"].(string) - if !strings.Contains(text, "ssh-ed25519 ") || strings.Contains(text, "PRIVATE KEY") { - t.Fatalf("guest public key response is invalid or exposes private material: %s", key) + if len(dev) != 20 { + t.Fatalf("dev toolset = %d tools, want 20", len(dev)) + } + for name, entry := range dev { + description, _ := entry["description"].(string) + if description == "" || strings.Count(description, ". ") > 0 || len(description) > 200 { + t.Errorf("%s description should be one short sentence: %q", name, description) + } + if _, ok := entry["annotations"].(map[string]any)["readOnlyHint"]; !ok { + t.Errorf("%s has no annotations", name) + } + } + for _, removed := range []string{"computer", "computer_batch", "wait_for_screen", "vm_start", "guest_public_key", "guest_logs", "test_status", "test_logs", "test_result"} { + if dev[removed] != nil { + t.Errorf("%s should be gone", removed) + } + } + raw, err := server.Handle(context.Background(), ChannelCore, "", json.RawMessage(`{"jsonrpc":"2.0","id":8,"method":"tools/call","params":{"name":"guest_exec","arguments":{"vm":"macos1","command":"true"}}}`)) + if err != nil { + t.Fatal(err) + } + if result := parseResponse(t, raw)["result"].(map[string]any); result["isError"] != true { + t.Fatalf("dev tools must not run on the core channel: %s", raw) + } + if _, err := server.Handle(context.Background(), "other", "", json.RawMessage(`{"jsonrpc":"2.0","id":9,"method":"ping"}`)); err == nil { + t.Fatal("an unknown channel must be refused") } } -func TestScreenshotAndZoomReturnImages(t *testing.T) { - frame := base64JPEG(t, color.RGBA{R: 180, A: 255}) - host := &testHost{frames: []string{frame}} - server := New() - server.BindHost(host) - shot := sendRequest(t, server, `{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"screenshot"}}}`) - shotContent := parseResponse(t, shot)["result"].(map[string]any)["content"].([]any) - if shotContent[0].(map[string]any)["type"] != "image" || shotContent[0].(map[string]any)["mimeType"] != "image/jpeg" { - t.Fatalf("screenshot result missing image content: %s", shot) +func TestVMPowerRoutesEachAction(t *testing.T) { + cases := map[string]string{ + "start": `{"vm":"macos1"}`, "shutdown": `{"vm":"macos1"}`, "force_stop": `{"force":true,"vm":"macos1"}`, + "suspend": `{"vm":"macos1"}`, "resume": `{"vm":"macos1"}`, } - zoom := sendRequest(t, server, `{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"zoom","x":0,"y":0,"width":1,"height":1}}}`) - zoomContent := parseResponse(t, zoom)["result"].(map[string]any)["content"].([]any) - if zoomContent[0].(map[string]any)["type"] != "image" || !strings.HasPrefix(zoomContent[1].(map[string]any)["text"].(string), "Crop 1x1 sha256=") { - t.Fatalf("zoom result missing cropped image or sha256: %s", zoom) + for action, wantParams := range cases { + host := &testHost{} + server := New() + server.BindHost(host) + result := callTool(t, server, "vm_power", `{"vm":"macos1","action":"`+action+`"}`) + if result["isError"] == true { + t.Fatalf("%s: %v", action, result) + } + params, _ := json.Marshal(host.calls[0].params) + if host.calls[0].method != powerMethods[action] || string(params) != wantParams { + t.Errorf("%s sent %s %s", action, host.calls[0].method, params) + } + } + server := New() + server.BindHost(&testHost{}) + if result := callTool(t, server, "vm_power", `{"vm":"macos1","action":"reboot"}`); result["isError"] != true { + t.Fatal("an unknown power action must fail") } } func TestVMUnlockNeverReturnsThePassword(t *testing.T) { const password = "mcp-password-fixture" - host := &testHost{frames: []string{base64JPEG(t, color.RGBA{G: 120, A: 255})}, secretValue: password} + host := &testHost{frames: []string{base64JPEG(t, color.RGBA{G: 120, A: 255}), base64JPEG(t, color.RGBA{B: 200, A: 255})}} server := New() server.BindHost(host) - response := sendRequest(t, server, `{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"vm_unlock","arguments":{"vm":"macos1","timeout_ms":500,"stable_ms":0}}}`) - if strings.Contains(string(response), password) { - t.Fatalf("vm_unlock leaked password in MCP response: %s", response) + raw := sendRequest(t, server, `{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"vm_unlock","arguments":{"vm":"macos1"}}}`) + if strings.Contains(string(raw), password) { + t.Fatalf("vm_unlock leaked password: %s", raw) } - if len(host.calls) < 3 { - t.Fatalf("vm_unlock host calls = %d, want at least typeSecret, key and screenshot", len(host.calls)) + methods := host.methods() + if len(methods) < 4 || methods[0] != "host/console.screenshot" || methods[1] != "host/console.typeSecret" || methods[2] != "host/console.key" { + t.Fatalf("vm_unlock should capture a baseline, type the secret, press Return, then watch: %v", methods) } - var secretParams map[string]any - encoded, _ := json.Marshal(host.calls[0].params) - _ = json.Unmarshal(encoded, &secretParams) - if host.calls[0].method != "host/console.typeSecret" || secretParams["setting"] != "login_password" { - t.Fatalf("vm_unlock sent unexpected secret call: %+v", host.calls[0]) + encoded, _ := json.Marshal(host.calls[1].params) + if !strings.Contains(string(encoded), `"setting":"login_password"`) || strings.Contains(string(encoded), password) { + t.Fatalf("vm_unlock sent unexpected secret call: %s", encoded) } - if strings.Contains(string(encoded), password) { - t.Fatal("vm_unlock sent password to the host as a plaintext argument") + result := parseResponse(t, raw)["result"].(map[string]any) + if result["content"].([]any)[0].(map[string]any)["type"] != "image" { + t.Fatalf("vm_unlock should return the unlocked screen: %s", raw) } } func TestVMUnlockExplainsMissingPassword(t *testing.T) { const hostMessage = "secret_missing: 该虚拟机未保存登录密码,无法自动输入。" - host := &testHost{secretErr: errors.New(hostMessage)} + host := &testHost{frames: []string{base64JPEG(t, color.RGBA{G: 120, A: 255})}, secretErr: errors.New(hostMessage)} server := New() server.BindHost(host) - response := sendRequest(t, server, `{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"vm_unlock","arguments":{"vm":"macos1"}}}`) - result := parseResponse(t, response)["result"].(map[string]any) - if isErr, _ := result["isError"].(bool); !isErr { - t.Fatalf("vm_unlock should report a tool error, got %s", response) + result := callTool(t, server, "vm_unlock", `{"vm":"macos1"}`) + if result["isError"] != true { + t.Fatalf("vm_unlock should report a tool error, got %v", result) } - text := result["content"].([]any)[0].(map[string]any)["text"].(string) - if !strings.Contains(text, "cannot enter the login password") { - t.Fatalf("vm_unlock did not explain the failure step: %q", text) + text := resultText(t, result) + if !strings.Contains(text, "cannot enter the login password") || !strings.Contains(text, hostMessage) { + t.Fatalf("vm_unlock did not explain the failure: %q", text) } - if !strings.Contains(text, hostMessage) { - t.Fatalf("vm_unlock dropped the host explanation: %q", text) - } - if strings.Contains(text, "Login password entered") { - t.Fatalf("vm_unlock claimed success after a failed secret entry: %q", text) - } - if host.frameIndex != 0 || len(host.frames) != 0 { - t.Fatalf("vm_unlock must not press Return or screenshot after the secret fails") - } -} - -func TestWaitForScreenRecognizesChangedFrame(t *testing.T) { - first := base64JPEG(t, color.RGBA{B: 200, A: 255}) - second := base64JPEG(t, color.RGBA{R: 200, A: 255}) - baseline := sha256.Sum256([]byte(first)) - host := &testHost{frames: []string{first, second}} - server := New() - server.BindHost(host) - payload := `{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"wait_for_screen","arguments":{"vm":"macos1","baseline_sha256":"` + hex.EncodeToString(baseline[:]) + `","timeout_ms":3000}}}` - response := sendRequest(t, server, payload) - content := parseResponse(t, response)["result"].(map[string]any)["content"].([]any) - if content[0].(map[string]any)["type"] != "image" || host.frameIndex < 2 { - t.Fatalf("wait_for_screen did not observe a changed frame: response=%s calls=%d", response, host.frameIndex) - } -} - -func TestWaitForScreenAppliesTimeoutToHostCall(t *testing.T) { - server := New() - server.BindHost(deadlineHost{}) - started := time.Now() - response := sendRequest(t, server, `{"jsonrpc":"2.0","id":33,"method":"tools/call","params":{"name":"wait_for_screen","arguments":{"vm":"macos1","timeout_ms":100}}}`) - if elapsed := time.Since(started); elapsed > time.Second { - t.Fatalf("wait_for_screen exceeded its timeout: %s", elapsed) - } - result := parseResponse(t, response)["result"].(map[string]any) - if result["isError"] == true || !strings.Contains(result["content"].([]any)[0].(map[string]any)["text"].(string), "timed_out=true") { - t.Fatalf("wait_for_screen timeout must return non-error timed_out=true: %s", response) + for _, method := range host.methods() { + if method == "host/console.key" { + t.Fatal("vm_unlock must not press Return after the secret fails") + } } } @@ -312,7 +255,7 @@ func TestCancellationNotificationStopsActiveToolCall(t *testing.T) { server.BindHost(blockingHost{started: started}) result := make(chan json.RawMessage, 1) go func() { - response, _ := server.Handle(context.Background(), json.RawMessage(`{"jsonrpc":"2.0","id":31,"method":"tools/call","params":{"name":"vm_list","arguments":{}}}`)) + response, _ := server.Handle(context.Background(), ChannelCore, "s1", json.RawMessage(`{"jsonrpc":"2.0","id":31,"method":"tools/call","params":{"name":"vm_list","arguments":{}}}`)) result <- response }() select { @@ -320,13 +263,21 @@ func TestCancellationNotificationStopsActiveToolCall(t *testing.T) { case <-time.After(time.Second): t.Fatal("tool call did not reach the host") } - if _, err := server.Handle(context.Background(), json.RawMessage(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":31,"reason":"user cancelled"}}`)); err != nil { + // The same request id from another client connection is a different call. + if _, err := server.Handle(context.Background(), ChannelCore, "s2", json.RawMessage(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":31}}`)); err != nil { t.Fatal(err) } select { case raw := <-result: - response := parseResponse(t, raw) - failure, ok := response["error"].(map[string]any) + t.Fatalf("another session cancelled the call: %s", raw) + case <-time.After(50 * time.Millisecond): + } + if _, err := server.Handle(context.Background(), ChannelCore, "s1", json.RawMessage(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":31,"reason":"user cancelled"}}`)); err != nil { + t.Fatal(err) + } + select { + case raw := <-result: + failure, ok := parseResponse(t, raw)["error"].(map[string]any) if !ok || failure["code"] != float64(-32800) { t.Fatalf("cancelled tool response = %s", raw) } @@ -335,6 +286,67 @@ func TestCancellationNotificationStopsActiveToolCall(t *testing.T) { } } +func TestSessionClosedCancelsOnlyThatSession(t *testing.T) { + server := New() + started := make(chan struct{}) + server.BindHost(blockingHost{started: started}) + result := make(chan json.RawMessage, 1) + go func() { + response, _ := server.Handle(context.Background(), ChannelCore, "gone", json.RawMessage(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"vm_list","arguments":{}}}`)) + result <- response + }() + <-started + server.SessionClosed(ChannelCore, "other") + select { + case <-result: + t.Fatal("closing another session cancelled this call") + case <-time.After(50 * time.Millisecond): + } + server.SessionClosed(ChannelCore, "gone") + select { + case raw := <-result: + if failure, _ := parseResponse(t, raw)["error"].(map[string]any); failure["code"] != float64(-32800) { + t.Fatalf("response after session closed = %s", raw) + } + case <-time.After(time.Second): + t.Fatal("closing the session did not cancel its call") + } +} + +func TestVMLockSerializesOnlyTheSameVM(t *testing.T) { + server := New() + server.BindHost(&testHost{frames: []string{base64JPEG(t, color.RGBA{R: 90, A: 255})}}) + server.state.runs["run-test"] = &testRun{ID: "run-test", Status: "running", Done: make(chan struct{})} + unlock, err := server.lockVM(context.Background(), "macos1") + if err != nil { + t.Fatal(err) + } + done := make(chan string, 3) + go func() { callTool(t, server, "screen", `{"vm":"macos2","return_image":false}`); done <- "screen" }() + go func() { callTool(t, server, "test_wait", `{"run_id":"run-test","timeout_ms":0}`); done <- "test_wait" }() + go func() { callTool(t, server, "vm_get", `{"vm":"macos1"}`); done <- "vm_get" }() + for range 3 { + select { + case <-done: + case <-time.After(time.Second): + t.Fatal("a call waited for another VM's lock or for a lock it does not need") + } + } + blocked := make(chan struct{}) + go func() { callTool(t, server, "screen", `{"vm":"macos1"}`); close(blocked) }() + select { + case <-blocked: + t.Fatal("screen on a locked VM did not wait") + case <-time.After(50 * time.Millisecond): + } + unlock() + select { + case <-blocked: + case <-time.After(time.Second): + t.Fatal("screen did not run once the VM was unlocked") + } +} + func TestGuestAccessRejectsNonNormalVMPhase(t *testing.T) { server := New() host := &testHost{vmPhase: "installer"} @@ -343,7 +355,6 @@ func TestGuestAccessRejectsNonNormalVMPhase(t *testing.T) { if err == nil || !strings.Contains(err.Error(), "confirmation_required") { t.Fatalf("guestAddress error = %v, want confirmation_required", err) } - _, err = server.startTestRun(context.Background(), json.RawMessage(`{"config":{"vm":"macos1","steps":[{"run":"true"}]}}`)) if err == nil || !strings.Contains(err.Error(), "confirmation_required") { t.Fatalf("startTestRun error = %v, want confirmation_required", err) @@ -353,57 +364,44 @@ func TestGuestAccessRejectsNonNormalVMPhase(t *testing.T) { } } -func TestTestWaitDoesNotBlockBehindSerializedToolCall(t *testing.T) { +func TestSessionCreateAlwaysClones(t *testing.T) { server := New() - run := &testRun{ID: "run-test", Status: "running", Done: make(chan struct{})} - server.state.runs[run.ID] = run - server.callMu.Lock() - result := make(chan json.RawMessage, 1) - go func() { - response, _ := server.Handle(context.Background(), json.RawMessage(`{"jsonrpc":"2.0","id":45,"method":"tools/call","params":{"name":"test_wait","arguments":{"run_id":"run-test","timeout_ms":20}}}`)) - result <- response - }() - select { - case raw := <-result: - server.callMu.Unlock() - if response := parseResponse(t, raw); response["error"] != nil { - t.Fatalf("test_wait response = %s", raw) - } - case <-time.After(time.Second): - server.callMu.Unlock() - t.Fatal("test_wait blocked behind another tool call") + host := &testHost{} + server.BindHost(host) + text := resultText(t, callTool(t, server, "session_create", `{"vm":"macos1"}`)) + if host.calls[0].method != "host/vm.clone" || !strings.Contains(text, `"vm":"__agent-test"`) { + t.Fatalf("session_create = %s via %v", text, host.methods()) + } + if result := callTool(t, server, "session_create", `{"vm":"macos1","isolation":"live"}`); result["isError"] != true { + t.Fatal("live sessions were removed; isolation must be refused") } } -func TestTestCancelDoesNotBlockBehindSerializedToolCall(t *testing.T) { +func TestTestWaitReturnsResultOnceFinished(t *testing.T) { + server := New() + server.BindHost(&testHost{}) + running := &testRun{ID: "run-a", Status: "running", Done: make(chan struct{})} + finished := &testRun{ID: "run-b", Status: "passed", Done: make(chan struct{}), Result: map[string]any{"run_id": "run-b", "status": "passed", "junit": []any{}}} + close(finished.Done) + server.state.runs[running.ID], server.state.runs[finished.ID] = running, finished + + started := time.Now() + text := resultText(t, callTool(t, server, "test_wait", `{"run_id":"run-a","timeout_ms":0}`)) + if time.Since(started) > 200*time.Millisecond || !strings.Contains(text, `"status":"running"`) { + t.Fatalf("timeout_ms 0 should return the status at once: %s", text) + } + if text := resultText(t, callTool(t, server, "test_wait", `{"run_id":"run-b"}`)); !strings.Contains(text, `"junit"`) { + t.Fatalf("a finished run should return its result: %s", text) + } +} + +func TestTestCancelCancelsRun(t *testing.T) { server := New() server.BindHost(&testHost{}) cancelled := make(chan struct{}) - run := &testRun{ID: "run-cancel", Status: "running", Done: make(chan struct{}), Cancel: func() { close(cancelled) }} - server.state.mu.Lock() - server.state.runs[run.ID] = run - server.state.mu.Unlock() - server.callMu.Lock() - result := make(chan json.RawMessage, 1) - go func() { - response, _ := server.Handle(context.Background(), json.RawMessage(`{"jsonrpc":"2.0","id":46,"method":"tools/call","params":{"name":"test_cancel","arguments":{"run_id":"run-cancel"}}}`)) - result <- response - }() - select { - case raw := <-result: - server.callMu.Unlock() - response := parseResponse(t, raw) - if response["error"] != nil { - t.Fatalf("test_cancel response = %s", raw) - } - result := response["result"].(map[string]any) - content := result["content"].([]any)[0].(map[string]any)["text"].(string) - if result["isError"] == true { - t.Fatalf("test_cancel returned tool error: %s", content) - } - case <-time.After(time.Second): - server.callMu.Unlock() - t.Fatal("test_cancel blocked behind another tool call") + server.state.runs["run-cancel"] = &testRun{ID: "run-cancel", Status: "running", Done: make(chan struct{}), Cancel: func() { close(cancelled) }} + if result := callTool(t, server, "test_cancel", `{"run_id":"run-cancel"}`); result["isError"] == true { + t.Fatalf("test_cancel = %v", result) } select { case <-cancelled: @@ -412,13 +410,27 @@ func TestTestCancelDoesNotBlockBehindSerializedToolCall(t *testing.T) { } } +func TestLogsReadPagesRunLog(t *testing.T) { + server := New() + server.BindHost(&testHost{}) + logPath := filepath.Join(t.TempDir(), "run.log") + if err := os.WriteFile(logPath, []byte("0123456789"), 0o600); err != nil { + t.Fatal(err) + } + server.state.runs["r-1"] = &testRun{ID: "r-1", LogPath: logPath, Done: make(chan struct{})} + text := resultText(t, callTool(t, server, "logs_read", `{"id":"r-1","offset":2,"limit":4}`)) + if !strings.Contains(text, `"text":"2345"`) || !strings.Contains(text, `"next_offset":6`) { + t.Fatalf("logs_read = %s", text) + } + if result := callTool(t, server, "logs_read", `{"id":"../escape"}`); result["isError"] != true { + t.Fatal("an id that is neither a run nor a guest log must fail") + } +} + func TestTestRunReportsTemporaryVMCleanupFailure(t *testing.T) { server := New() - host := &testHost{deleteErr: errors.New("delete failed")} - server.BindHost(host) - run := &testRun{ - ID: "run-cleanup", VM: "macos1", Config: testConfig{VM: "macos1", Isolation: "clone"}, Done: make(chan struct{}), - } + server.BindHost(&testHost{deleteErr: errors.New("delete failed")}) + run := &testRun{ID: "run-cleanup", VM: "macos1", Config: testConfig{VM: "macos1"}, Done: make(chan struct{})} server.executeTestRun(context.Background(), run) if run.Status != "failed" { t.Fatalf("run status = %q, want failed", run.Status) @@ -428,20 +440,6 @@ func TestTestRunReportsTemporaryVMCleanupFailure(t *testing.T) { } } -func TestCancelledDragReleasesMouseButton(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - host := &dragCancellationHost{cancel: cancel} - server := New() - server.BindHost(host) - response, err := server.Handle(ctx, json.RawMessage(`{"jsonrpc":"2.0","id":32,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"left_click_drag","x":1,"y":1,"x2":20,"y2":20,"width":100,"height":100}}}`)) - if err != nil { - t.Fatal(err) - } - if len(host.buttonStates) != 2 || !host.buttonStates[0] || host.buttonStates[1] || host.releaseErr != nil { - t.Fatalf("mouse button states=%v release context error=%v response=%s", host.buttonStates, host.releaseErr, response) - } -} - func parseResponse(t *testing.T, raw json.RawMessage) map[string]any { t.Helper() var response map[string]any @@ -451,15 +449,50 @@ func parseResponse(t *testing.T, raw json.RawMessage) map[string]any { return response } +// sendRequest sends one message on the dev channel, which serves every tool. func sendRequest(t *testing.T, server *Server, raw string) json.RawMessage { t.Helper() - result, err := server.Handle(context.Background(), json.RawMessage(raw)) + result, err := server.Handle(context.Background(), ChannelDev, "", json.RawMessage(raw)) if err != nil { t.Fatal(err) } return result } +var nextTestID struct { + sync.Mutex + n int +} + +// callTool runs a tool on the dev channel and returns its result object. +func callTool(t *testing.T, server *Server, name, arguments string) map[string]any { + t.Helper() + nextTestID.Lock() + nextTestID.n++ + id := nextTestID.n + nextTestID.Unlock() + params, _ := json.Marshal(map[string]any{"name": name, "arguments": json.RawMessage(arguments)}) + request, _ := json.Marshal(map[string]any{"jsonrpc": "2.0", "id": id, "method": "tools/call", "params": json.RawMessage(params)}) + response := parseResponse(t, sendRequest(t, server, string(request))) + result, ok := response["result"].(map[string]any) + if !ok { + t.Fatalf("%s returned no result: %v", name, response) + } + return result +} + +// resultText returns the text item of a tool result. +func resultText(t *testing.T, result map[string]any) string { + t.Helper() + for _, item := range result["content"].([]any) { + if entry := item.(map[string]any); entry["type"] == "text" { + return entry["text"].(string) + } + } + t.Fatalf("result has no text: %v", result) + return "" +} + func base64JPEG(t *testing.T, fill color.Color) string { t.Helper() img := image.NewRGBA(image.Rect(0, 0, 2, 2)) diff --git a/internal/mcp/test_runs.go b/internal/mcp/test_runs.go index 482db49..c75bcd7 100644 --- a/internal/mcp/test_runs.go +++ b/internal/mcp/test_runs.go @@ -55,8 +55,6 @@ type testFiles struct { type testConfig struct { VM string `json:"vm"` - Isolation string `json:"isolation"` - BaseSnapshot string `json:"base_snapshot"` BootTimeout string `json:"boot_timeout,omitempty"` Workspace string `json:"workspace"` Sync syncConfig `json:"sync"` @@ -115,7 +113,9 @@ func newOpaqueID(prefix string) string { return fmt.Sprintf("%s-%x", prefix, raw) } -func (s *Server) createSession(ctx context.Context, vm, baseSnapshot, isolation string) (map[string]any, error) { +// createSession clones vm into a temporary VM that only this plugin may +// delete. +func (s *Server) createSession(ctx context.Context, vm string) (map[string]any, error) { if s.state == nil { return nil, errors.New("plugin state is unavailable") } @@ -123,32 +123,21 @@ func (s *Server) createSession(ctx context.Context, vm, baseSnapshot, isolation if vm == "" { return nil, fmt.Errorf("%w: vm is required", errInvalidParams) } - if isolation == "" { - isolation = "clone" - } - if isolation != "clone" && isolation != "live" { - return nil, fmt.Errorf("%w: isolation must be clone or live", errInvalidParams) - } - if strings.TrimSpace(baseSnapshot) != "" { - return nil, errors.New("base_snapshot is not supported by the current host API") - } session := &agentSession{ID: newOpaqueID("s"), VM: vm} - if isolation == "clone" { - cloneName := "__agent-" + strings.TrimPrefix(session.ID, "s-") - var cloned map[string]any - if err := s.host.Call(ctx, "host/vm.clone", map[string]any{"vm": vm, "clone_name": cloneName}, &cloned); err != nil { - return nil, err - } - cloneVM, _ := cloned["vm"].(string) - if cloneVM == "" { - cloneVM = cloneName - } - session.CloneVM, session.VM, session.Owned = cloneVM, cloneVM, true + cloneName := "__agent-" + strings.TrimPrefix(session.ID, "s-") + var cloned map[string]any + if err := s.host.Call(ctx, "host/vm.clone", map[string]any{"vm": vm, "clone_name": cloneName}, &cloned); err != nil { + return nil, err } + cloneVM, _ := cloned["vm"].(string) + if cloneVM == "" { + cloneVM = cloneName + } + session.CloneVM, session.VM, session.Owned = cloneVM, cloneVM, true s.state.mu.Lock() s.state.sessions[session.ID] = session s.state.mu.Unlock() - return map[string]any{"session_id": session.ID, "vm": session.VM, "owned": session.Owned, "base_snapshot": strings.TrimSpace(baseSnapshot)}, nil + return map[string]any{"session_id": session.ID, "vm": session.VM}, nil } func (s *Server) disposeSession(ctx context.Context, id string) error { @@ -220,8 +209,7 @@ func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any, return nil, err } var args struct { - Config json.RawMessage `json:"config"` - Workspace string `json:"workspace"` + Config json.RawMessage `json:"config"` } if err := decodeArguments(raw, &args); err != nil { return nil, err @@ -233,9 +221,6 @@ func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any, if err := json.Unmarshal(args.Config, &cfg); err != nil { return nil, fmt.Errorf("%w: invalid test config: %v", errInvalidParams, err) } - if cfg.Workspace == "" { - cfg.Workspace = args.Workspace - } if strings.TrimSpace(cfg.VM) == "" || len(cfg.Steps) == 0 { return nil, fmt.Errorf("%w: vm and at least one step are required", errInvalidParams) } @@ -245,9 +230,6 @@ func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any, if _, err := s.vmInfo(parent, cfg.VM); err != nil { return nil, err } - if cfg.Isolation == "" { - cfg.Isolation = "clone" - } run := &testRun{ID: newOpaqueID("r"), Status: "queued", VM: cfg.VM, Config: cfg, Done: make(chan struct{})} // The request context ends when this tool returns. A test run outlives that // request and is cancelled through test_cancel or when the run finishes. @@ -279,14 +261,14 @@ func (s *Server) executeTestRun(ctx context.Context, run *testRun) { _, _ = fmt.Fprintln(logFile, time.Now().Format(time.RFC3339)+" "+line) } } - session, err := s.createSession(ctx, run.Config.VM, run.Config.BaseSnapshot, run.Config.Isolation) + session, err := s.createSession(ctx, run.Config.VM) if err == nil { run.mu.Lock() run.Session, _ = session["session_id"].(string) run.VM, _ = session["vm"].(string) run.mu.Unlock() } - if err == nil && run.Config.Isolation == "clone" { + if err == nil { var out map[string]any err = s.host.Call(ctx, "host/vm.start", map[string]any{"vm": run.VM}, &out) } @@ -608,8 +590,8 @@ func (s *Server) collectTestFiles(ctx context.Context, run *testRun) (testFiles, func (s *Server) waitTestRun(ctx context.Context, raw json.RawMessage) (any, error) { var args struct { - RunID string `json:"run_id"` - Timeout int `json:"timeout_ms"` + RunID string `json:"run_id"` + TimeoutMS *int `json:"timeout_ms"` } if err := decodeArguments(raw, &args); err != nil { return nil, err @@ -618,50 +600,59 @@ func (s *Server) waitTestRun(ctx context.Context, raw json.RawMessage) (any, err if run == nil { return nil, errors.New("run not found") } - if args.Timeout <= 0 { - args.Timeout = 30000 - } else if args.Timeout > 300000 { - args.Timeout = 300000 + timeout := 30000 + if args.TimeoutMS != nil { + timeout = *args.TimeoutMS } - timer := time.NewTimer(time.Duration(args.Timeout) * time.Millisecond) - defer timer.Stop() - select { - case <-run.Done: - case <-timer.C: - return textResult(s.runStatus(run)), nil - case <-ctx.Done(): - return nil, ctx.Err() + if timeout < 0 || timeout > 300000 { + return nil, fmt.Errorf("%w: timeout_ms must be between 0 and 300000", errInvalidParams) + } + if timeout > 0 { + timer := time.NewTimer(time.Duration(timeout) * time.Millisecond) + defer timer.Stop() + select { + case <-run.Done: + case <-timer.C: + case <-ctx.Done(): + return nil, ctx.Err() + } + } + run.mu.Lock() + result := run.Result + run.mu.Unlock() + if result != nil { + return textResult(result), nil } return textResult(s.runStatus(run)), nil } -func (s *Server) statusTestRun(raw json.RawMessage) (any, error) { - run, err := s.runFromRaw(raw) - if err != nil { - return nil, err - } - return textResult(s.runStatus(run)), nil -} - -func (s *Server) logsTestRun(raw json.RawMessage) (any, error) { +// readLogs pages through a test run log or a guest_exec log. +func (s *Server) readLogs(raw json.RawMessage) (any, error) { var args struct { - RunID string `json:"run_id"` + ID string `json:"id"` Offset int64 `json:"offset"` Limit int `json:"limit"` } if err := decodeArguments(raw, &args); err != nil { return nil, err } - run := s.lookupRun(args.RunID) + run := s.lookupRun(args.ID) if run == nil { - return nil, errors.New("run not found") + result, err := s.guest.ReadLog(args.ID, args.Offset, args.Limit) + if err != nil { + return nil, err + } + return textResult(result), nil } if args.Offset < 0 { - return nil, errors.New("offset must be non-negative") + return nil, fmt.Errorf("%w: offset must be non-negative", errInvalidParams) } - if args.Limit <= 0 || args.Limit > 65536 { + if args.Limit == 0 { args.Limit = 8192 } + if args.Limit < 0 || args.Limit > 65536 { + return nil, fmt.Errorf("%w: limit must be between 1 and 65536", errInvalidParams) + } file, err := os.Open(run.LogPath) if err != nil { return nil, err @@ -674,21 +665,7 @@ func (s *Server) logsTestRun(raw json.RawMessage) (any, error) { if err != nil { return nil, err } - return textResult(map[string]any{"run_id": run.ID, "offset": args.Offset, "next_offset": args.Offset + int64(len(data)), "text": string(data), "eof": len(data) < args.Limit}), nil -} - -func (s *Server) resultTestRun(raw json.RawMessage) (any, error) { - run, err := s.runFromRaw(raw) - if err != nil { - return nil, err - } - run.mu.Lock() - result := run.Result - run.mu.Unlock() - if result == nil { - return textResult(s.runStatus(run)), nil - } - return textResult(result), nil + return textResult(map[string]any{"id": run.ID, "offset": args.Offset, "next_offset": args.Offset + int64(len(data)), "text": string(data), "eof": len(data) < args.Limit}), nil } func (s *Server) cancelTestRun(raw json.RawMessage) (any, error) { diff --git a/internal/mcp/tools.go b/internal/mcp/tools.go new file mode 100644 index 0000000..c646859 --- /dev/null +++ b/internal/mcp/tools.go @@ -0,0 +1,239 @@ +package mcp + +// tool describes one MCP tool. Core tools are served on both channels; dev +// tools only on ChannelDev. +type tool struct { + name string + description string + schema map[string]any + dev bool + // locksVM serializes the tool with other display and input work on the + // same VM. + locksVM bool + readOnly bool + destructive bool + idempotent bool +} + +func (t tool) listing() map[string]any { + annotations := map[string]any{"readOnlyHint": t.readOnly, "idempotentHint": t.idempotent} + if !t.readOnly { + annotations["destructiveHint"] = t.destructive + } + return map[string]any{"name": t.name, "description": t.description, "inputSchema": t.schema, "annotations": annotations} +} + +func toolList(dev bool) []map[string]any { + list := make([]map[string]any, 0, len(tools)) + for _, t := range tools { + if dev || !t.dev { + list = append(list, t.listing()) + } + } + return list +} + +func lookupTool(name string, dev bool) (tool, bool) { + for _, t := range tools { + if t.name == name && (dev || !t.dev) { + return t, true + } + } + return tool{}, false +} + +func objectSchema(properties map[string]any, required ...string) map[string]any { + schema := map[string]any{"type": "object", "properties": properties, "additionalProperties": false} + if len(required) > 0 { + schema["required"] = required + } + return schema +} + +func intRange(lo, hi int) map[string]any { + return map[string]any{"type": "integer", "minimum": lo, "maximum": hi} +} + +func described(schema map[string]any, description string) map[string]any { + schema["description"] = description + return schema +} + +var ( + vmProp = map[string]any{"type": "string", "description": "VM name or reference from vm_list."} + stringProp = map[string]any{"type": "string"} + coordProp = map[string]any{"type": "integer", "minimum": 0} + scaleProp = map[string]any{"type": "number", "minimum": 0.25, "maximum": 1, "description": "Result image width as a share of 1280 px; default 1."} + imageProp = map[string]any{"type": "boolean", "description": "Attach the image; default true."} + untilProp = map[string]any{"type": "string", "enum": []string{"change", "stable", "change_then_stable"}, "description": "Default change_then_stable."} +) + +var tools = []tool{ + { + name: "vm_list", description: "List the virtual machines this plugin may use.", + schema: objectSchema(map[string]any{}), + readOnly: true, idempotent: true, + }, + { + name: "vm_get", description: "Read one virtual machine's state, display and SSH settings.", + schema: objectSchema(map[string]any{"vm": vmProp}, "vm"), + readOnly: true, idempotent: true, + }, + { + name: "vm_power", description: "Start, shut down, force-stop, suspend or resume a virtual machine; follow a boot with screen and wait.", + schema: objectSchema(map[string]any{ + "vm": vmProp, + "action": map[string]any{"type": "string", "enum": []string{"start", "shutdown", "force_stop", "suspend", "resume"}}, + }, "vm", "action"), + locksVM: true, destructive: true, + }, + { + name: "vm_unlock", description: "Type the saved login password, press Return and return the screen once it settles.", + schema: objectSchema(map[string]any{"vm": vmProp}, "vm"), + locksVM: true, + }, + { + name: "screen", description: "Return the display, optionally after waiting for it to change or settle, or one region of it in more detail; x/y everywhere are pixels of the last full screen image.", + schema: objectSchema(map[string]any{ + "vm": vmProp, + "region": described(objectSchema(map[string]any{ + "x": coordProp, "y": coordProp, "width": intRange(1, 10000), "height": intRange(1, 10000), + }, "x", "y", "width", "height"), "Area of the last full image to return at up to source resolution."), + "wait": objectSchema(map[string]any{ + "until": untilProp, + "baseline": described(map[string]any{"type": "string"}, "sha256 to measure change from; default the last image."), + "stable_ms": described(intRange(0, maxScreenWaitMS), "Default 1000."), + "timeout_ms": described(intRange(1, maxScreenWaitMS), "Default 10000; a timeout returns the last frame with timed_out."), + "accept_blank": described(map[string]any{"type": "boolean"}, "Let a blank frame end the wait."), + }), + "scale": scaleProp, + "return_image": imageProp, + }, "vm"), + locksVM: true, readOnly: true, + }, + { + name: "computer_input", description: "Send mouse and keyboard actions in order and return the screen after the last one; end with wait_screen when the UI needs time to respond.", + schema: objectSchema(map[string]any{ + "vm": vmProp, + "actions": map[string]any{ + "type": "array", "minItems": 1, "maxItems": maxInputActions, + "items": objectSchema(map[string]any{ + "action": map[string]any{"type": "string", "enum": actionNames}, + "x": coordProp, + "y": coordProp, + "x2": described(map[string]any{"type": "integer", "minimum": 0}, "Drag end x."), + "y2": described(map[string]any{"type": "integer", "minimum": 0}, "Drag end y."), + "button": map[string]any{"type": "string", "enum": []string{"left", "right", "middle"}}, + "modifiers": map[string]any{"type": "array", "items": map[string]any{"type": "string", "enum": []string{"cmd", "ctrl", "alt", "shift"}}}, + "key": described(map[string]any{"type": "string"}, "Key name such as return, esc, tab, space, backspace, delete, up, f5 or a; combos like cmd+c."), + "text": described(map[string]any{"type": "string"}, "Text to type; non-ASCII needs Guest Tools in the guest."), + "direction": map[string]any{"type": "string", "enum": []string{"up", "down", "left", "right"}}, + "amount": described(intRange(1, maxScrollAmount), "Scroll steps; default 3."), + "duration_ms": described(intRange(1, maxStepWaitMS), "For wait and hold_key."), + "until": untilProp, + "stable_ms": intRange(0, maxStepWaitMS), + "timeout_ms": described(intRange(1, maxStepWaitMS), "Default 10000; a timeout stops the sequence."), + }, "action"), + }, + "scale": scaleProp, + "return_image": imageProp, + }, "vm", "actions"), + locksVM: true, destructive: true, + }, + + { + name: "guest_wait_ready", description: "Wait for guest SSH and return the host fingerprint to pin and the plugin public key to authorize.", + schema: objectSchema(map[string]any{"vm": vmProp, "timeout_ms": described(intRange(1, 30000), "Default 10000.")}, "vm"), + dev: true, readOnly: true, + }, + { + name: "guest_trust_host", description: "Pin the guest SSH host fingerprint after checking it against the live connection.", + schema: objectSchema(map[string]any{"vm": vmProp, "fingerprint": stringProp}, "vm", "fingerprint"), + dev: true, idempotent: true, + }, + { + name: "guest_exec", description: "Run a shell command in the guest over SSH and return its exit code, bounded output and log_id.", + schema: objectSchema(map[string]any{ + "vm": vmProp, "command": stringProp, "cwd": stringProp, + "env": map[string]any{"type": "object", "additionalProperties": stringProp}, + "timeout_ms": described(intRange(1, 1800000), "Default 900000."), + }, "vm", "command"), + dev: true, destructive: true, + }, + { + name: "guest_put", description: "Upload a host file to a path in the guest user's home directory.", + schema: objectSchema(map[string]any{"vm": vmProp, "local_path": stringProp, "remote_path": stringProp}, "vm", "local_path", "remote_path"), + dev: true, destructive: true, idempotent: true, + }, + { + name: "guest_get", description: "Download a file from the guest user's home directory to a host path.", + schema: objectSchema(map[string]any{"vm": vmProp, "remote_path": stringProp, "local_path": stringProp}, "vm", "remote_path", "local_path"), + dev: true, destructive: true, idempotent: true, + }, + { + name: "snapshot_list", description: "List a virtual machine's restore points.", + schema: objectSchema(map[string]any{"vm": vmProp}, "vm"), + dev: true, readOnly: true, idempotent: true, + }, + { + name: "snapshot_create", description: "Create a restore point.", + schema: objectSchema(map[string]any{"vm": vmProp, "name": stringProp}, "vm", "name"), + dev: true, locksVM: true, + }, + { + name: "snapshot_restore", description: "Restore a restore point on a temporary clone made by session_create.", + schema: objectSchema(map[string]any{"vm": vmProp, "name": stringProp}, "vm", "name"), + dev: true, locksVM: true, destructive: true, + }, + { + name: "session_create", description: "Clone a virtual machine into a temporary copy owned by this plugin.", + schema: objectSchema(map[string]any{"vm": vmProp}, "vm"), + dev: true, + }, + { + name: "session_dispose", description: "Stop and delete a temporary copy made by session_create.", + schema: objectSchema(map[string]any{"session_id": stringProp}, "session_id"), + dev: true, destructive: true, idempotent: true, + }, + { + name: "test_run", description: "Start a test run on a temporary clone and return its run_id.", + schema: objectSchema(map[string]any{ + "config": objectSchema(map[string]any{ + "vm": stringProp, + "workspace": described(map[string]any{"type": "string"}, "Host folder copied into the guest before the steps."), + "boot_timeout": described(map[string]any{"type": "string"}, "Go duration to wait for guest SSH; default 4m."), + "sync": objectSchema(map[string]any{ + "dest": stringProp, + "exclude": map[string]any{"type": "array", "items": stringProp}, + }), + "steps": map[string]any{"type": "array", "minItems": 1, "items": objectSchema(map[string]any{ + "name": stringProp, "run": stringProp, "cwd": stringProp, + "timeout": described(map[string]any{"type": "string"}, "Go duration; default 15m."), + }, "run")}, + "junit": map[string]any{"type": "array", "items": stringProp}, + "artifacts": map[string]any{"type": "array", "items": stringProp}, + "keep_on_failure": map[string]any{"type": "boolean"}, + }, "vm", "steps"), + }, "config"), + dev: true, + }, + { + name: "test_wait", description: "Wait for a test run and return its status, with the result once it has finished.", + schema: objectSchema(map[string]any{"run_id": stringProp, "timeout_ms": described(intRange(0, 300000), "Default 30000; 0 returns at once.")}, "run_id"), + dev: true, readOnly: true, + }, + { + name: "test_cancel", description: "Cancel a test run and delete its temporary clone.", + schema: objectSchema(map[string]any{"run_id": stringProp}, "run_id"), + dev: true, destructive: true, idempotent: true, + }, + { + name: "logs_read", description: "Read a page of a guest_exec log_id or a test run_id log.", + schema: objectSchema(map[string]any{ + "id": stringProp, + "offset": map[string]any{"type": "integer", "minimum": 0}, + "limit": described(intRange(1, 65536), "Default 8192."), + }, "id"), + dev: true, readOnly: true, idempotent: true, + }, +} diff --git a/internal/sidecar/rpc.go b/internal/sidecar/rpc.go index 2651d91..9244a3d 100644 --- a/internal/sidecar/rpc.go +++ b/internal/sidecar/rpc.go @@ -17,8 +17,15 @@ import ( const maxFrameBytes = 8 << 20 const maxHeaderBytes = 16 << 10 +// Channels lists the channels this sidecar serves. "mcp" carries the core +// computer-use tools and "mcp-dev" adds guest, snapshot and test tools. +var Channels = []string{"mcp", "mcp-dev"} + +// MCPHandler answers MCP messages. session identifies one client connection; +// SessionClosed is called once that connection has ended. type MCPHandler interface { - Handle(context.Context, json.RawMessage) (json.RawMessage, error) + Handle(ctx context.Context, channel, session string, message json.RawMessage) (json.RawMessage, error) + SessionClosed(channel, session string) } type HostClient struct{ Server *Server } @@ -118,24 +125,26 @@ func (s *Server) Serve(parent context.Context) error { func (s *Server) dispatch(ctx context.Context, env envelope) { var result any var err error - switch env.Method { - case "plugin/initialize": + channel, event := channelMethod(env.Method) + switch { + case env.Method == "plugin/initialize": result = map[string]any{ "pluginApi": "1.1.0", - "capabilities": map[string]any{"channels": []string{"mcp"}}, + "capabilities": map[string]any{"channels": Channels}, } - case "plugin/localeChanged": + case env.Method == "plugin/localeChanged": return - case "channel/mcp/message": + case event == "message": var params struct { Message json.RawMessage `json:"message"` + Session string `json:"session"` } if err = json.Unmarshal(env.Params, ¶ms); err == nil && len(params.Message) == 0 { err = errors.New("channel message is missing") } if err == nil { var message json.RawMessage - message, err = s.mcp.Handle(ctx, params.Message) + message, err = s.mcp.Handle(ctx, channel, params.Session, params.Message) if err == nil { if len(message) == 0 { message = json.RawMessage("null") @@ -143,6 +152,13 @@ func (s *Server) dispatch(ctx context.Context, env envelope) { result = map[string]json.RawMessage{"message": message} } } + case event == "closed": + var params struct { + Session string `json:"session"` + } + if err = json.Unmarshal(env.Params, ¶ms); err == nil && params.Session != "" { + s.mcp.SessionClosed(channel, params.Session) + } default: err = fmt.Errorf("method not found: %s", env.Method) } @@ -164,6 +180,25 @@ func (s *Server) dispatch(ctx context.Context, env envelope) { _ = s.writeFrame(response) } +// channelMethod splits "channel//" for a channel this sidecar +// serves. It returns empty strings for any other method. +func channelMethod(method string) (string, string) { + rest, ok := strings.CutPrefix(method, "channel/") + if !ok { + return "", "" + } + channel, event, ok := strings.Cut(rest, "/") + if !ok { + return "", "" + } + for _, served := range Channels { + if channel == served { + return channel, event + } + } + return "", "" +} + func (s *Server) CallHost(ctx context.Context, method string, params any, out any) error { if ctx == nil { ctx = context.Background() diff --git a/internal/sidecar/rpc_test.go b/internal/sidecar/rpc_test.go index 3d1b543..d106fe1 100644 --- a/internal/sidecar/rpc_test.go +++ b/internal/sidecar/rpc_test.go @@ -3,6 +3,7 @@ package sidecar import ( "bufio" "bytes" + "context" "encoding/json" "errors" "io" @@ -69,6 +70,58 @@ func TestWriteFullStopsOnZeroProgress(t *testing.T) { } } +type recordingHandler struct { + handled []string + closed []string +} + +func (h *recordingHandler) Handle(_ context.Context, channel, session string, _ json.RawMessage) (json.RawMessage, error) { + h.handled = append(h.handled, channel+"/"+session) + return json.RawMessage(`{"ok":true}`), nil +} + +func (h *recordingHandler) SessionClosed(channel, session string) { + h.closed = append(h.closed, channel+"/"+session) +} + +func TestDispatchRoutesBothChannelsWithSessions(t *testing.T) { + handler := &recordingHandler{} + var out bytes.Buffer + server := NewWithIO(strings.NewReader(""), &out, handler) + ctx := context.Background() + server.dispatch(ctx, envelope{JSONRPC: "2.0", ID: json.RawMessage("1"), Method: "plugin/initialize"}) + server.dispatch(ctx, envelope{JSONRPC: "2.0", ID: json.RawMessage("2"), Method: "channel/mcp/message", Params: json.RawMessage(`{"message":{},"session":"a"}`)}) + server.dispatch(ctx, envelope{JSONRPC: "2.0", ID: json.RawMessage("3"), Method: "channel/mcp-dev/message", Params: json.RawMessage(`{"message":{}}`)}) + server.dispatch(ctx, envelope{JSONRPC: "2.0", Method: "channel/mcp/closed", Params: json.RawMessage(`{"session":"a"}`)}) + server.dispatch(ctx, envelope{JSONRPC: "2.0", ID: json.RawMessage("4"), Method: "channel/other/message", Params: json.RawMessage(`{"message":{}}`)}) + + if strings.Join(handler.handled, ",") != "mcp/a,mcp-dev/" || strings.Join(handler.closed, ",") != "mcp/a" { + t.Fatalf("handled=%v closed=%v", handler.handled, handler.closed) + } + reader := bufio.NewReader(&out) + var responses []envelope + for { + frame, err := readFrame(reader) + if err != nil { + break + } + var response envelope + if err := json.Unmarshal(frame, &response); err != nil { + t.Fatal(err) + } + responses = append(responses, response) + } + if len(responses) != 4 { + t.Fatalf("got %d responses, want 4 (the closed notification has none)", len(responses)) + } + if !strings.Contains(string(responses[0].Result), `"channels":["mcp","mcp-dev"]`) { + t.Fatalf("initialize = %s", responses[0].Result) + } + if responses[3].Error == nil { + t.Fatal("a channel this sidecar does not serve must be refused") + } +} + type shortWriter struct { bytes.Buffer maxChunk int diff --git a/plugin.json b/plugin.json index aceb258..47eff7f 100644 --- a/plugin.json +++ b/plugin.json @@ -1,7 +1,7 @@ { "schema": 1, "id": "reims.agent", - "version": "0.1.0", + "version": "0.2.0", "name": { "zh-CN": "MCP服务", "en-US": "MCP Service" @@ -58,7 +58,8 @@ }, "contributes": { "channels": [ - { "id": "mcp", "framing": "jsonl" } + { "id": "mcp", "framing": "jsonl" }, + { "id": "mcp-dev", "framing": "jsonl" } ] }, "permissions": [