Compare commits

11 Commits
Author SHA1 Message Date
千川白浪 f6bea08c2c Merge pull request #7 from reims-go/feat/mcp-v2
Release plugin package / package (push) Canceled after 0s
refactor(sidecar): serve the MCP channels through pkg/pluginsdk
2026-12-05 17:02:46 +08:00
Nwflower 1b1f02739f refactor(sidecar): serve the MCP channels through pkg/pluginsdk
The transport, the handshake and the Host API calls now come from the shared SDK, so this package only routes channel messages and the host's JSON-RPC error codes reach the MCP tools.
2026-12-05 02:01:04 -07:00
Nwflower f19eef7946 feat(mcp)!: require pluginApi 1.3 for held input, region capture and force stop
The host serves held key transitions, host/console.release, region screenshots and force on host/vm.shutdown, and the plugin relies on all of them, so it declares pluginApi 1.3.
2026-12-05 02:01:04 -07:00
千川白浪andClaude Opus 5.5 d682620fe5 feat(mcp)!: 工具设计范式更新到 0.2.0 (#6)
Serve six computer-use tools on the mcp channel and add the guest,
restore point, clone and test tools on a new mcp-dev channel.

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

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

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-04 23:52:45 -07:00
千川白浪 030fc246a5 Merge pull request #5 from reims-go/fix/mcp-vm-lifecycle
feat(mcp): expose virtual machine suspend and resume
2026-12-04 21:20:56 +08:00
Nwflower 0ad3692acb fix(mcp): retry guest SSH readiness until boot timeout 2026-12-04 06:20:36 -07:00
Nwflower 23d0271c93 fix(mcp): explain a missing login password in vm_unlock
vm_unlock returned the host's raw "secret setting is empty" when a VM had no
saved password, which reads like an internal fault and hides what the user has
to do. Wrap the typeSecret failure with the step that failed and keep the
host's readable explanation, and say in the tool description that the VM (or
an MCP clone's source VM) must have a saved login password.

model: deepseek/deepseek-v4.1-flash
agent: lead (DeepSeek Harness)
2026-12-04 06:16:46 -07:00
Nwflower 6b6a7ff81b feat(mcp): expose virtual machine suspend and resume 2026-12-03 08:32:04 -07:00
bvz rays 1b9e2ad1ec Merge pull request #4 from reims-go/feat/mcp-review-fixes
fix: enforce MCP operation boundaries
2026-12-03 11:41:14 +08:00
bvz rays 40740f7cd0 fix: keep MCP test controls responsive 2026-12-03 02:11:17 +08:00
bvzrays 4c7b4bb052 fix: enforce MCP operation boundaries 2026-12-02 16:58:49 +00:00
16 changed files with 2453 additions and 1776 deletions

No files matched your search

+28 -12
View File
@@ -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`, 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.
+1
View File
@@ -3,6 +3,7 @@ module github.com/reims-go/reims-agent
go 1.26.0
require (
github.com/Nwflower/reims-go v0.2.14
github.com/pkg/sftp v1.13.7
golang.org/x/crypto v0.57.0
)
+2
View File
@@ -1,3 +1,5 @@
github.com/Nwflower/reims-go v0.2.14 h1:0Wpow+DqfHzSUNRO0/S7trDw4+Y4gG5GzqzaIEpwY7o=
github.com/Nwflower/reims-go v0.2.14/go.mod h1:FJVGGa230qMdtPJrSqgQV8lVnXZiBlvPURgysBYhxBU=
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c=
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+1 -3
View File
@@ -186,8 +186,6 @@ func (s *SSH) Exec(ctx context.Context, vm, address, username, command, cwd stri
return ExecResult{}, err
}
defer client.Close()
stopOnContext := closeOnContext(ctx, client)
defer stopOnContext()
session, err := client.NewSession()
if err != nil {
return ExecResult{}, err
@@ -229,7 +227,7 @@ func (s *SSH) Exec(ctx context.Context, vm, address, username, command, cwd stri
if closeErr != nil {
return ExecResult{}, closeErr
}
if err != nil && !timedOut {
if err != nil && !timedOut && !cancelled {
var exitErr *ssh.ExitError
if !errors.As(err, &exitErr) {
return ExecResult{}, err
+436
View File
@@ -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
}
+201
View File
@@ -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 <nil>", "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)
}
}
+298 -395
View File
@@ -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
}
+134 -107
View File
@@ -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")
}
}
+226 -727
View File
File diff suppressed because it is too large. Load diff
+337 -150
View File
@@ -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,10 +23,13 @@ type hostCall struct {
}
type testHost struct {
calls []hostCall
frames []string
frameIndex int
secretValue string
mu sync.Mutex
calls []hostCall
frames []string
frameIndex int
secretErr error
vmPhase string
deleteErr error
}
type blockingHost struct{ started chan struct{} }
@@ -38,66 +40,35 @@ 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") {
if h.secretErr != nil {
return h.secretErr
}
*out.(*hostReply) = hostReply{Characters: 19}
return nil
}
if strings.HasSuffix(method, "vm.get") {
*out.(*map[string]any) = map[string]any{"vm": "driver:macos1", "name": "macos1", "state": "running"}
*out.(*map[string]any) = map[string]any{"vm": "driver:macos1", "name": "macos1", "state": "running", "phase": h.vmPhase}
return nil
}
if strings.HasSuffix(method, "vm.clone") {
*out.(*map[string]any) = map[string]any{"vm": "__agent-test"}
return nil
}
if strings.HasSuffix(method, "vm.delete") && h.deleteErr != nil {
return h.deleteErr
}
if strings.HasSuffix(method, "vm.list") {
*out.(*hostReply) = hostReply{VMs: []any{map[string]any{"vm": "driver:macos1", "name": "macos1"}}}
return nil
@@ -108,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)
@@ -141,107 +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 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 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}}
func TestVMUnlockExplainsMissingPassword(t *testing.T) {
const hostMessage = "secret_missing: 该虚拟机未保存登录密码,无法自动输入。"
host := &testHost{frames: []string{base64JPEG(t, color.RGBA{G: 120, A: 255})}, secretErr: errors.New(hostMessage)}
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)
result := callTool(t, server, "vm_unlock", `{"vm":"macos1"}`)
if result["isError"] != true {
t.Fatalf("vm_unlock should report a tool error, got %v", result)
}
}
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)
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)
}
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")
}
}
}
@@ -251,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 {
@@ -259,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)
}
@@ -274,17 +286,157 @@ func TestCancellationNotificationStopsActiveToolCall(t *testing.T) {
}
}
func TestCancelledDragReleasesMouseButton(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
host := &dragCancellationHost{cancel: cancel}
func TestSessionClosedCancelsOnlyThatSession(t *testing.T) {
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}}}`))
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)
}
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)
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"}
server.BindHost(host)
_, _, err := server.guestAddress(context.Background(), "macos1")
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)
}
if len(host.calls) != 2 || host.calls[0].method != "host/vm.get" || host.calls[1].method != "host/vm.get" {
t.Fatalf("host calls = %+v, want phase checks before side effects", host.calls)
}
}
func TestSessionCreateAlwaysClones(t *testing.T) {
server := New()
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 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{})
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:
case <-time.After(time.Second):
t.Fatal("test_cancel did not cancel its run")
}
}
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()
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)
}
if run.Result["cleanup_error"] != "delete failed" || run.Result["kept_vm"] != "__agent-test" {
t.Fatalf("run result = %+v, want cleanup failure and kept VM", run.Result)
}
}
@@ -297,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))
+174 -90
View File
@@ -55,8 +55,7 @@ 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"`
Steps []testStep `json:"steps"`
@@ -65,6 +64,31 @@ type testConfig struct {
KeepOnFailure bool `json:"keep_on_failure"`
}
const (
defaultGuestWaitTimeout = 240 * time.Second
maxGuestWaitTimeout = 600 * time.Second
)
var (
guestWaitChunkTimeout = 30 * time.Second
guestWaitRetryDelay = 500 * time.Millisecond
waitGuestReadyFn = func(s *Server, ctx context.Context, vm, address, username string, timeout time.Duration) (map[string]any, error) {
return s.guest.WaitReady(ctx, vm, address, username, timeout)
}
)
func resolveGuestWaitTimeout(raw string) (time.Duration, error) {
raw = strings.TrimSpace(raw)
if raw == "" {
return defaultGuestWaitTimeout, nil
}
d, err := time.ParseDuration(raw)
if err != nil || d <= 0 || d > maxGuestWaitTimeout {
return 0, fmt.Errorf("%w: boot_timeout must be a valid duration between 1ms and %s", errInvalidParams, maxGuestWaitTimeout)
}
return d, nil
}
type syncConfig struct {
Dest string `json:"dest"`
Exclude []string `json:"exclude"`
@@ -89,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")
}
@@ -97,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 {
@@ -194,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
@@ -207,14 +221,14 @@ 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)
}
if cfg.Isolation == "" {
cfg.Isolation = "clone"
if _, err := resolveGuestWaitTimeout(cfg.BootTimeout); err != nil {
return nil, err
}
if _, err := s.vmInfo(parent, cfg.VM); err != nil {
return nil, err
}
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
@@ -247,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)
}
@@ -262,7 +276,10 @@ func (s *Server) executeTestRun(ctx context.Context, run *testRun) {
run.mu.Lock()
run.Status = "running"
run.mu.Unlock()
if result, waitErr := s.waitGuest(ctx, run.VM); waitErr != nil {
waitTimeout, timeoutErr := resolveGuestWaitTimeout(run.Config.BootTimeout)
if timeoutErr != nil {
err = timeoutErr
} else if result, waitErr := s.waitGuest(ctx, run.VM, waitTimeout); waitErr != nil {
err = waitErr
} else {
logLine(fmt.Sprintf("guest ready: %v", result))
@@ -306,7 +323,15 @@ func (s *Server) executeTestRun(ctx context.Context, run *testRun) {
}
if err == nil || !keepOnFailure {
if sessionID != "" {
_ = s.disposeSession(context.Background(), sessionID)
if cleanupErr := s.disposeSession(context.Background(), sessionID); cleanupErr != nil {
result["cleanup_error"] = cleanupErr.Error()
result["kept_vm"] = vmName
if status == "passed" {
status = "failed"
result["status"] = status
result["error"] = "temporary VM cleanup failed"
}
}
}
} else {
result["kept_vm"] = vmName
@@ -323,7 +348,7 @@ func (s *Server) executeTestRun(ctx context.Context, run *testRun) {
}
}
func (s *Server) waitGuest(ctx context.Context, vm string) (map[string]any, error) {
func (s *Server) waitGuest(ctx context.Context, vm string, totalTimeout time.Duration) (map[string]any, error) {
var out map[string]any
err := s.host.Call(ctx, "host/vm.get", map[string]any{"vm": vm}, &out)
if err != nil {
@@ -333,26 +358,85 @@ func (s *Server) waitGuest(ctx context.Context, vm string) (map[string]any, erro
return map[string]any{"ready": true}, nil
}
var result map[string]any
if err := s.invokeGuestWait(ctx, vm, &result); err != nil {
if err := s.invokeGuestWait(ctx, vm, totalTimeout, &result); err != nil {
return nil, err
}
return result, nil
}
func (s *Server) invokeGuestWait(ctx context.Context, vm string, out *map[string]any) error {
address, username, err := s.guestAddress(ctx, vm)
if err != nil {
return err
func (s *Server) invokeGuestWait(ctx context.Context, vm string, totalTimeout time.Duration, out *map[string]any) error {
if totalTimeout <= 0 {
totalTimeout = defaultGuestWaitTimeout
}
result, err := s.guest.WaitReady(ctx, vm, address, username, 30*time.Second)
if err != nil {
return err
deadline := time.Now().Add(totalTimeout)
var lastMsg string
for {
if err := ctx.Err(); err != nil {
return err
}
var vmState map[string]any
if err := s.host.Call(ctx, "host/vm.get", map[string]any{"vm": vm}, &vmState); err == nil {
if st, _ := vmState["state"].(string); st != "" {
switch strings.ToLower(strings.TrimSpace(st)) {
case "stopped", "broken", "error", "suspended":
return fmt.Errorf("ssh_unavailable: VM %s entered state %q before guest SSH became ready", vm, st)
}
}
}
remaining := time.Until(deadline)
if remaining < time.Millisecond {
break
}
chunk := guestWaitChunkTimeout
if chunk <= 0 || chunk > 30*time.Second {
chunk = 30 * time.Second
}
if remaining < chunk {
chunk = remaining
}
address, username, err := s.guestAddress(ctx, vm)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
lastMsg = err.Error()
} else {
result, err := waitGuestReadyFn(s, ctx, vm, address, username, chunk)
if err != nil {
if ctx.Err() != nil {
return ctx.Err()
}
lastMsg = err.Error()
} else if ready, _ := result["ready"].(bool); ready {
*out = result
return nil
} else if msg, _ := result["message"].(string); strings.TrimSpace(msg) != "" {
lastMsg = strings.TrimSpace(msg)
}
}
if time.Until(deadline) < time.Millisecond {
break
}
retryDelay := min(guestWaitRetryDelay, time.Until(deadline))
if retryDelay > 0 {
timer := time.NewTimer(retryDelay)
select {
case <-ctx.Done():
timer.Stop()
return ctx.Err()
case <-timer.C:
}
}
}
if ready, _ := result["ready"].(bool); !ready {
return errors.New("ssh_unavailable: guest SSH is not ready")
if lastMsg != "" {
return fmt.Errorf("ssh_unavailable: guest SSH is not ready after %s (%s); ensure Remote Login is persisted in guest (launchctl enable system/com.openssh.sshd)", totalTimeout, lastMsg)
}
*out = result
return nil
return fmt.Errorf("ssh_unavailable: guest SSH is not ready after %s; ensure Remote Login is persisted in guest (launchctl enable system/com.openssh.sshd)", totalTimeout)
}
func (s *Server) syncWorkspace(ctx context.Context, run *testRun) error {
@@ -438,7 +522,10 @@ func (s *Server) executeStep(ctx context.Context, run *testRun, step testStep, l
return err
}
logLine(fmt.Sprintf("step %s exit=%d: %s", step.Name, result.ExitCode, result.Output))
if result.ExitCode != 0 || result.TimedOut || result.Cancelled {
if result.Cancelled {
return context.Canceled
}
if result.ExitCode != 0 || result.TimedOut {
return fmt.Errorf("step %q failed with exit code %d", step.Name, result.ExitCode)
}
return nil
@@ -503,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
@@ -513,48 +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
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
@@ -567,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) {
+145
View File
@@ -0,0 +1,145 @@
package mcp
import (
"context"
"strings"
"testing"
"time"
)
type waitTestHost struct {
state string
sshPort int
}
func (h *waitTestHost) Call(_ context.Context, method string, _ any, out any) error {
if method == "host/vm.get" {
m := out.(*map[string]any)
*m = map[string]any{
"name": "clone-1",
"state": h.state,
"ssh_port": float64(h.sshPort),
"phase": "normal",
}
return nil
}
if method == "host/secret.get" {
m := out.(*map[string]any)
*m = map[string]any{"value": "reims"}
return nil
}
return nil
}
func TestInvokeGuestWaitRetriesUntilReady(t *testing.T) {
origChunk := guestWaitChunkTimeout
origDelay := guestWaitRetryDelay
origFn := waitGuestReadyFn
t.Cleanup(func() {
guestWaitChunkTimeout = origChunk
guestWaitRetryDelay = origDelay
waitGuestReadyFn = origFn
})
guestWaitChunkTimeout = 20 * time.Millisecond
guestWaitRetryDelay = 5 * time.Millisecond
calls := 0
waitGuestReadyFn = func(_ *Server, _ context.Context, _, _, _ string, timeout time.Duration) (map[string]any, error) {
calls++
if timeout > 20*time.Millisecond {
t.Fatalf("chunk timeout = %v, want <= 20ms", timeout)
}
if calls < 3 {
return map[string]any{"ready": false, "message": "connection refused"}, nil
}
return map[string]any{"ready": true}, nil
}
srv := New()
srv.BindHost(&waitTestHost{state: "running", sshPort: 2222})
var out map[string]any
if err := srv.invokeGuestWait(context.Background(), "clone-1", 500*time.Millisecond, &out); err != nil {
t.Fatalf("invokeGuestWait failed: %v", err)
}
if calls != 3 {
t.Fatalf("calls = %d, want 3", calls)
}
if ready, _ := out["ready"].(bool); !ready {
t.Fatalf("out = %+v, want ready=true", out)
}
}
func TestInvokeGuestWaitFailsFastWhenVMStops(t *testing.T) {
origChunk := guestWaitChunkTimeout
origDelay := guestWaitRetryDelay
origFn := waitGuestReadyFn
t.Cleanup(func() {
guestWaitChunkTimeout = origChunk
guestWaitRetryDelay = origDelay
waitGuestReadyFn = origFn
})
guestWaitChunkTimeout = 20 * time.Millisecond
guestWaitRetryDelay = 5 * time.Millisecond
host := &waitTestHost{state: "running", sshPort: 2222}
calls := 0
waitGuestReadyFn = func(_ *Server, _ context.Context, _, _, _ string, _ time.Duration) (map[string]any, error) {
calls++
host.state = "stopped"
return map[string]any{"ready": false, "message": "eof"}, nil
}
srv := New()
srv.BindHost(host)
var out map[string]any
err := srv.invokeGuestWait(context.Background(), "clone-1", 2*time.Second, &out)
if err == nil || !strings.Contains(err.Error(), `entered state "stopped"`) {
t.Fatalf("err = %v, want stopped fail-fast error", err)
}
if calls != 1 {
t.Fatalf("calls = %d, want 1", calls)
}
}
func TestInvokeGuestWaitTimesOutWithActionableHint(t *testing.T) {
origChunk := guestWaitChunkTimeout
origDelay := guestWaitRetryDelay
origFn := waitGuestReadyFn
t.Cleanup(func() {
guestWaitChunkTimeout = origChunk
guestWaitRetryDelay = origDelay
waitGuestReadyFn = origFn
})
guestWaitChunkTimeout = 15 * time.Millisecond
guestWaitRetryDelay = 5 * time.Millisecond
waitGuestReadyFn = func(_ *Server, _ context.Context, _, _, _ string, _ time.Duration) (map[string]any, error) {
return map[string]any{"ready": false, "message": "connection refused"}, nil
}
srv := New()
srv.BindHost(&waitTestHost{state: "running", sshPort: 2222})
var out map[string]any
err := srv.invokeGuestWait(context.Background(), "clone-1", 40*time.Millisecond, &out)
if err == nil || !strings.Contains(err.Error(), "ssh_unavailable") || !strings.Contains(err.Error(), "launchctl enable system/com.openssh.sshd") {
t.Fatalf("err = %v, want actionable ssh_unavailable timeout", err)
}
}
func TestResolveGuestWaitTimeout(t *testing.T) {
if d, err := resolveGuestWaitTimeout(""); err != nil || d != defaultGuestWaitTimeout {
t.Fatalf("empty = (%v, %v), want (%v, nil)", d, err, defaultGuestWaitTimeout)
}
if d, err := resolveGuestWaitTimeout("3m"); err != nil || d != 3*time.Minute {
t.Fatalf("3m = (%v, %v)", d, err)
}
if _, err := resolveGuestWaitTimeout("0s"); err == nil {
t.Fatal("0s must fail")
}
if _, err := resolveGuestWaitTimeout("15m"); err == nil {
t.Fatal("15m above max must fail")
}
}
+239
View File
@@ -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,
},
}
+63 -225
View File
@@ -1,26 +1,32 @@
// Package sidecar serves this plugin's MCP channels over the Reims-Go Sidecar
// protocol. The transport, the handshake and the Host API calls come from
// pkg/pluginsdk, so this package only routes channel messages.
package sidecar
import (
"bufio"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"strconv"
"strings"
"sync"
"sync/atomic"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
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)
}
// HostClient adapts the SDK server to the Call shape the MCP tools use. It
// keeps the JSON-RPC error code the host answered with, so a caller can tell a
// rejected request from a failed one.
type HostClient struct{ Server *Server }
func (c HostClient) Call(ctx context.Context, method string, params any, out any) error {
@@ -30,249 +36,81 @@ func (c HostClient) Call(ctx context.Context, method string, params any, out any
return c.Server.CallHost(ctx, method, params, out)
}
type envelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *rpcError `json:"error,omitempty"`
}
type rpcError struct {
Code int `json:"code"`
Message string `json:"message"`
}
type hostReply struct {
Message string `json:"message"`
}
// Server routes the channels this plugin declares over one Sidecar connection.
type Server struct {
in *bufio.Reader
out io.Writer
sdk *pluginsdk.Server
mcp MCPHandler
mu sync.Mutex
pending map[string]chan envelope
writeMu sync.Mutex
nextID atomic.Uint64
}
// New serves on the process's standard input and output.
func New(handler MCPHandler) *Server {
return &Server{
in: bufio.NewReaderSize(os.Stdin, 64*1024),
out: os.Stdout,
mcp: handler,
pending: make(map[string]chan envelope),
}
return NewWithIO(os.Stdin, os.Stdout, handler)
}
// NewWithIO serves over custom streams, which tests use.
func NewWithIO(r io.Reader, w io.Writer, handler MCPHandler) *Server {
return &Server{
in: bufio.NewReaderSize(r, 64*1024),
out: w,
mcp: handler,
pending: make(map[string]chan envelope),
s := &Server{sdk: pluginsdk.NewWithIO(r, w), mcp: handler}
s.sdk.SetCapability("channels", Channels)
for _, channel := range Channels {
s.sdk.Handle("channel/"+channel+"/message", s.channelMessage(channel))
s.sdk.Handle("channel/"+channel+"/closed", s.channelClosed(channel))
}
return s
}
func (s *Server) Serve(parent context.Context) error {
ctx, cancel := context.WithCancel(parent)
defer cancel()
for {
frame, err := readFrame(s.in)
if err != nil {
if errors.Is(err, io.EOF) {
return nil
}
return err
}
var env envelope
if err := json.Unmarshal(frame, &env); err != nil {
_ = s.writeFrame(envelope{JSONRPC: "2.0", ID: json.RawMessage("null"), Error: &rpcError{Code: -32700, Message: "parse error"}})
continue
}
if env.Method == "plugin/shutdown" {
return nil
}
if env.Method != "" {
go s.dispatch(ctx, env)
continue
}
if len(env.ID) > 0 {
key := strings.TrimSpace(string(env.ID))
s.mu.Lock()
waiter := s.pending[key]
s.mu.Unlock()
if waiter != nil {
select {
case waiter <- env:
default:
}
}
}
}
// Serve runs until the host closes the connection or sends plugin/shutdown.
func (s *Server) Serve(ctx context.Context) error {
return s.sdk.Serve(ctx)
}
func (s *Server) dispatch(ctx context.Context, env envelope) {
var result any
var err error
switch env.Method {
case "plugin/initialize":
result = map[string]any{
"pluginApi": "1.1.0",
"capabilities": map[string]any{"channels": []string{"mcp"}},
}
case "plugin/localeChanged":
return
case "channel/mcp/message":
// CallHost invokes one Host API method on Reims-Go.
func (s *Server) CallHost(ctx context.Context, method string, params, out any) error {
return s.sdk.CallHost(ctx, method, params, out)
}
// InitInfo returns the handshake metadata, including the features the host
// advertised.
func (s *Server) InitInfo() pluginsdk.InitInfo {
return s.sdk.InitInfo()
}
func (s *Server) channelMessage(channel string) pluginsdk.Handler {
return func(ctx context.Context, raw json.RawMessage) (any, error) {
var params struct {
Message json.RawMessage `json:"message"`
Session string `json:"session"`
}
if err = json.Unmarshal(env.Params, &params); err == nil && len(params.Message) == 0 {
err = errors.New("channel message is missing")
if err := json.Unmarshal(raw, &params); err != nil {
return nil, err
}
if err == nil {
var message json.RawMessage
message, err = s.mcp.Handle(ctx, params.Message)
if err == nil {
if len(message) == 0 {
message = json.RawMessage("null")
}
result = map[string]json.RawMessage{"message": message}
}
if len(params.Message) == 0 {
return nil, errors.New("channel message is missing")
}
default:
err = fmt.Errorf("method not found: %s", env.Method)
}
if len(env.ID) == 0 {
return
}
response := envelope{JSONRPC: "2.0", ID: env.ID}
if err != nil {
response.Error = &rpcError{Code: -32000, Message: err.Error()}
} else if result == nil {
response.Result = json.RawMessage("null")
} else {
response.Result, err = json.Marshal(result)
if err != nil {
response.Result = nil
response.Error = &rpcError{Code: -32603, Message: "internal error"}
}
}
_ = s.writeFrame(response)
}
func (s *Server) CallHost(ctx context.Context, method string, params any, out any) error {
if ctx == nil {
ctx = context.Background()
}
id := strconv.FormatUint(s.nextID.Add(1), 10)
var rawParams json.RawMessage
if params != nil {
encoded, err := json.Marshal(params)
if err != nil {
return err
}
rawParams = encoded
}
waiter := make(chan envelope, 1)
s.mu.Lock()
s.pending[id] = waiter
s.mu.Unlock()
defer func() {
s.mu.Lock()
delete(s.pending, id)
s.mu.Unlock()
}()
if err := s.writeFrame(envelope{
JSONRPC: "2.0",
ID: json.RawMessage(id),
Method: method,
Params: rawParams,
}); err != nil {
return err
}
select {
case response := <-waiter:
if response.Error != nil {
return errors.New(response.Error.Message)
}
if out != nil && len(response.Result) > 0 && string(response.Result) != "null" {
return json.Unmarshal(response.Result, out)
}
return nil
case <-ctx.Done():
return ctx.Err()
}
}
func (s *Server) writeFrame(env envelope) error {
frame, err := json.Marshal(env)
if err != nil {
return err
}
if len(frame) > maxFrameBytes {
return errors.New("Sidecar RPC frame exceeds limit")
}
s.writeMu.Lock()
defer s.writeMu.Unlock()
header := []byte(fmt.Sprintf("Content-Length: %d\r\n\r\n", len(frame)))
if err := writeFull(s.out, header); err != nil {
return err
}
return writeFull(s.out, frame)
}
func readFrame(reader *bufio.Reader) ([]byte, error) {
contentLength := -1
headerBytes := 0
for range 64 {
rawLine, err := reader.ReadSlice('\n')
if errors.Is(err, bufio.ErrBufferFull) || len(rawLine)+headerBytes > maxHeaderBytes {
return nil, errors.New("Sidecar RPC header exceeds limit")
if s.mcp == nil {
return nil, errors.New("no MCP handler is bound")
}
message, err := s.mcp.Handle(ctx, channel, params.Session, params.Message)
if err != nil {
return nil, err
}
headerBytes += len(rawLine)
line := strings.TrimRight(string(rawLine), "\r\n")
if line == "" {
break
}
key, value, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(key), "Content-Length") {
if contentLength >= 0 {
return nil, errors.New("duplicate Sidecar RPC Content-Length")
}
length, err := strconv.Atoi(strings.TrimSpace(value))
if err != nil || length < 0 || length > maxFrameBytes {
return nil, errors.New("invalid Sidecar RPC Content-Length")
}
contentLength = length
if len(message) == 0 {
message = json.RawMessage("null")
}
return map[string]json.RawMessage{"message": message}, nil
}
if contentLength < 0 {
return nil, errors.New("Sidecar RPC frame is missing Content-Length")
}
frame := make([]byte, contentLength)
if _, err := io.ReadFull(reader, frame); err != nil {
return nil, err
}
return frame, nil
}
func writeFull(writer io.Writer, data []byte) error {
for len(data) > 0 {
written, err := writer.Write(data)
if err != nil {
return err
func (s *Server) channelClosed(channel string) pluginsdk.Handler {
return func(_ context.Context, raw json.RawMessage) (any, error) {
var params struct {
Session string `json:"session"`
}
if written == 0 {
return io.ErrShortWrite
if err := json.Unmarshal(raw, &params); err != nil {
return nil, err
}
data = data[written:]
if params.Session != "" && s.mcp != nil {
s.mcp.SessionClosed(channel, params.Session)
}
return nil, nil
}
return nil
}
+164 -64
View File
@@ -3,84 +3,184 @@ package sidecar
import (
"bufio"
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"strconv"
"sort"
"strings"
"sync"
"testing"
"time"
"github.com/Nwflower/reims-go/pkg/pluginsdk"
)
func TestReadFrameRejectsInvalidAndOversizedHeaders(t *testing.T) {
tests := []struct {
name string
input string
wantErr string
}{
{
name: "duplicate length",
input: "Content-Length: 2\r\nContent-Length: 2\r\n\r\n{}",
wantErr: "duplicate",
},
{
name: "oversized header",
input: strings.Repeat("X", maxHeaderBytes+1) + "\n\n",
wantErr: "exceeds limit",
},
{
name: "oversized body",
input: "Content-Length: " + strconv.Itoa(maxFrameBytes+1) + "\r\n\r\n",
wantErr: "invalid",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
_, err := readFrame(bufio.NewReaderSize(strings.NewReader(test.input), 64*1024))
if err == nil || !strings.Contains(err.Error(), test.wantErr) {
t.Fatalf("readFrame error = %v, want text %q", err, test.wantErr)
}
})
}
type recordingHandler struct {
mu sync.Mutex
handled []string
closed []string
}
func TestWriteFrameCompletesShortWrites(t *testing.T) {
writer := &shortWriter{maxChunk: 3}
server := NewWithIO(strings.NewReader(""), writer, nil)
if err := server.writeFrame(envelope{JSONRPC: "2.0", ID: json.RawMessage("1"), Result: json.RawMessage(`{"ok":true}`)}); err != nil {
t.Fatal(err)
}
reader := bufio.NewReader(bytes.NewReader(writer.Bytes()))
frame, err := readFrame(reader)
func (h *recordingHandler) Handle(_ context.Context, channel, session string, _ json.RawMessage) (json.RawMessage, error) {
h.mu.Lock()
defer h.mu.Unlock()
h.handled = append(h.handled, channel+"/"+session)
return json.RawMessage(`{"ok":true}`), nil
}
func (h *recordingHandler) SessionClosed(channel, session string) {
h.mu.Lock()
defer h.mu.Unlock()
h.closed = append(h.closed, channel+"/"+session)
}
func (h *recordingHandler) state() ([]string, []string) {
h.mu.Lock()
defer h.mu.Unlock()
return append([]string(nil), h.handled...), append([]string(nil), h.closed...)
}
type rpcEnvelope struct {
JSONRPC string `json:"jsonrpc"`
ID json.RawMessage `json:"id,omitempty"`
Method string `json:"method,omitempty"`
Params json.RawMessage `json:"params,omitempty"`
Result json.RawMessage `json:"result,omitempty"`
Error *struct {
Code int `json:"code"`
Message string `json:"message"`
} `json:"error,omitempty"`
}
func writeFrame(w io.Writer, v any) error {
raw, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
return err
}
var response envelope
if err := json.Unmarshal(frame, &response); err != nil {
t.Fatal(err)
_, err = fmt.Fprintf(w, "Content-Length: %d\r\n\r\n%s", len(raw), raw)
return err
}
func readFrame(r *bufio.Reader) (rpcEnvelope, error) {
length := -1
for {
line, err := r.ReadString('\n')
if err != nil {
return rpcEnvelope{}, err
}
line = strings.TrimRight(line, "\r\n")
if line == "" {
break
}
key, value, ok := strings.Cut(line, ":")
if ok && strings.EqualFold(strings.TrimSpace(key), "Content-Length") {
if _, err := fmt.Sscanf(strings.TrimSpace(value), "%d", &length); err != nil {
return rpcEnvelope{}, err
}
}
}
if string(response.Result) != `{"ok":true}` {
t.Fatalf("response result = %s", response.Result)
if length < 0 {
return rpcEnvelope{}, errors.New("frame is missing Content-Length")
}
frame := make([]byte, length)
if _, err := io.ReadFull(r, frame); err != nil {
return rpcEnvelope{}, err
}
var env rpcEnvelope
return env, json.Unmarshal(frame, &env)
}
func TestChannelsAreRoutedAndUnknownOnesRefused(t *testing.T) {
handler := &recordingHandler{}
inR, inW := io.Pipe()
outR, outW := io.Pipe()
server := NewWithIO(inR, outW, handler)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { _ = server.Serve(ctx) }()
requests := []rpcEnvelope{
{JSONRPC: "2.0", ID: json.RawMessage("1"), Method: "plugin/initialize", Params: json.RawMessage(`{"pluginId":"reims.agent"}`)},
{JSONRPC: "2.0", ID: json.RawMessage("2"), Method: "channel/mcp/message", Params: json.RawMessage(`{"message":{},"session":"a"}`)},
{JSONRPC: "2.0", ID: json.RawMessage("3"), Method: "channel/mcp-dev/message", Params: json.RawMessage(`{"message":{}}`)},
{JSONRPC: "2.0", Method: "channel/mcp/closed", Params: json.RawMessage(`{"session":"a"}`)},
{JSONRPC: "2.0", ID: json.RawMessage("4"), Method: "channel/other/message", Params: json.RawMessage(`{"message":{}}`)},
}
go func() {
for _, req := range requests {
if err := writeFrame(inW, req); err != nil {
return
}
}
}()
reader := bufio.NewReader(outR)
responses := map[string]rpcEnvelope{}
for range 4 {
env, err := readFrame(reader)
if err != nil {
t.Fatalf("read response: %v", err)
}
responses[strings.TrimSpace(string(env.ID))] = env
}
// The SDK dispatches inbound methods concurrently, so the two channel
// messages may be handled in either order.
handled, closed := handler.state()
sort.Strings(handled)
if strings.Join(handled, ",") != "mcp-dev/,mcp/a" || strings.Join(closed, ",") != "mcp/a" {
t.Fatalf("handled=%v closed=%v", handled, closed)
}
if !bytes.Contains(responses["1"].Result, []byte(`"channels":["mcp","mcp-dev"]`)) {
t.Fatalf("initialize = %s", responses["1"].Result)
}
for _, id := range []string{"2", "3"} {
if !bytes.Contains(responses[id].Result, []byte(`"message":{"ok":true}`)) {
t.Fatalf("channel reply %s = %s", id, responses[id].Result)
}
}
if responses["4"].Error == nil {
t.Fatal("a channel this sidecar does not serve must be refused")
}
}
func TestWriteFullStopsOnZeroProgress(t *testing.T) {
if err := writeFull(zeroWriter{}, []byte("payload")); !errors.Is(err, io.ErrShortWrite) {
t.Fatalf("writeFull error = %v, want io.ErrShortWrite", err)
func TestHostCallKeepsTheErrorCode(t *testing.T) {
inR, inW := io.Pipe()
outR, outW := io.Pipe()
server := NewWithIO(inR, outW, nil)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
go func() { _ = server.Serve(ctx) }()
go func() {
reader := bufio.NewReader(outR)
for {
env, err := readFrame(reader)
if err != nil {
return
}
if env.Method == "" || len(env.ID) == 0 {
continue
}
_ = writeFrame(inW, rpcEnvelope{
JSONRPC: "2.0",
ID: env.ID,
Error: &struct {
Code int `json:"code"`
Message string `json:"message"`
}{Code: -32602, Message: "host/console.key: unknown field"},
})
return
}
}()
callCtx, callCancel := context.WithTimeout(ctx, 5*time.Second)
defer callCancel()
err := HostClient{Server: server}.Call(callCtx, "host/console.key", map[string]any{"vm": "a"}, nil)
var sdkErr *pluginsdk.Error
if !errors.As(err, &sdkErr) || sdkErr.Code != pluginsdk.InvalidParams {
t.Fatalf("err = %v, want an SDK error with code %d", err, pluginsdk.InvalidParams)
}
}
type shortWriter struct {
bytes.Buffer
maxChunk int
}
func (w *shortWriter) Write(data []byte) (int, error) {
if len(data) > w.maxChunk {
data = data[:w.maxChunk]
}
return w.Buffer.Write(data)
}
type zeroWriter struct{}
func (zeroWriter) Write([]byte) (int, error) { return 0, nil }
+4 -3
View File
@@ -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"
@@ -14,7 +14,7 @@
"license": "Apache-2.0",
"homepage": "https://github.com/reims-go/reims-agent",
"engines": {
"pluginApi": "^1.1.0"
"pluginApi": "^1.3.0"
},
"platforms": ["windows-x64"],
"entry": {
@@ -58,7 +58,8 @@
},
"contributes": {
"channels": [
{ "id": "mcp", "framing": "jsonl" }
{ "id": "mcp", "framing": "jsonl" },
{ "id": "mcp-dev", "framing": "jsonl" }
]
},
"permissions": [