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

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

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

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

473 lines
13 KiB
Go

package mcp
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"image/jpeg"
"math"
"strings"
"sync"
"time"
)
const (
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 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
last map[string]frameInfo
}
func newScreenCache() *screenCache {
return &screenCache{byHash: make(map[string][]uint8), last: make(map[string]frameInfo)}
}
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)
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[frame.hash]; !exists {
if len(c.order) >= maxFrameCacheEntries {
delete(c.byHash, c.order[0])
c.order = c.order[1:]
}
c.order = append(c.order, frame.hash)
}
c.byHash[frame.hash] = gray
}
c.last[vmKey(vm)] = frame
return frame
}
func (c *screenCache) grayByHash(hash string) []uint8 {
c.mu.Lock()
defer c.mu.Unlock()
return c.byHash[hash]
}
func (c *screenCache) lastFrame(vm string) (frameInfo, bool) {
c.mu.Lock()
defer c.mu.Unlock()
frame, ok := c.last[vmKey(vm)]
return frame, ok && frame.width > 0 && frame.height > 0
}
func vmKey(vm string) string { return strings.ToLower(strings.TrimSpace(vm)) }
func decodeGrayThumb(encoded string) ([]uint8, bool) {
if encoded == "" {
return nil, false
}
raw, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return nil, false
}
img, err := jpeg.Decode(bytes.NewReader(raw))
if err != nil {
return nil, false
}
b := img.Bounds()
srcW, srcH := b.Dx(), b.Dy()
if srcW <= 0 || srcH <= 0 {
return nil, false
}
gray := make([]uint8, thumbW*thumbH)
for y := range thumbH {
sy := b.Min.Y + (y*srcH)/thumbH
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.
gray[y*thumbW+x] = uint8((299*(r>>8) + 587*(g>>8) + 114*(bl>>8)) / 1000)
}
}
return gray, true
}
func frameDiffRatio(a, b []uint8) float64 {
if len(a) == 0 || len(a) != len(b) {
return 1.0
}
diff := 0
for i := range a {
d := int(a[i]) - int(b[i])
if d < 0 {
d = -d
}
if d > pixelDiffThreshold {
diff++
}
}
return float64(diff) / float64(len(a))
}
// 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 a.hash != b.hash
}
func validateScale(scale float64) (float64, error) {
if scale == 0 {
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", 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
}
return *ptr
}
// 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
}
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
}
_, 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})
}
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
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
}
type waitOutcome struct {
observation
hasFrame bool
timedOut bool
until string
lastErr string
}
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
}
if o.timedOut {
fields["timed_out"] = true
fields["until"] = o.until
if o.lastErr != "" {
fields["error"] = o.lastErr
}
}
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 opts, fmt.Errorf("%w: until must be change, stable or change_then_stable", errInvalidParams)
}
if opts.TimeoutMS == 0 {
opts.TimeoutMS = defaultWaitTimeoutMS
}
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()
outcome := waitOutcome{until: opts.Until}
baseline := opts.Baseline
var (
anchor frameInfo
hasAnchor bool
stableSince time.Time
)
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, "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()
}
outcome.timedOut = true
return outcome, nil
}
}
}
func (s *Server) screenTool(ctx context.Context, raw json.RawMessage) (any, error) {
var args struct {
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
}
scale, err := validateScale(args.Scale)
if err != nil {
return nil, err
}
returnImage := boolOrDefault(args.ReturnImage, 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
}
}
var waited *waitOutcome
if args.Wait != nil {
opts, err := s.resolveWait(args.VM, *args.Wait, maxScreenWaitMS, defaultStableMS)
if err != nil {
return nil, err
}
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
}
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 nil, err
}
return newObservation(screen, frame).result(returnImage, nil), nil
}