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

510 lines
18 KiB
Go

package mcp
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"errors"
"image"
"image/color"
"image/jpeg"
"os"
"path/filepath"
"strings"
"sync"
"testing"
"time"
)
type hostCall struct {
method string
params any
}
type testHost struct {
mu sync.Mutex
calls []hostCall
frames []string
frameIndex int
secretErr error
vmPhase string
deleteErr error
}
type blockingHost struct{ started chan struct{} }
func (h blockingHost) Call(ctx context.Context, _ string, _ any, _ any) error {
close(h.started)
<-ctx.Done()
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") {
// 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", "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
}
if result, ok := out.(*hostReply); ok {
*result = hostReply{OK: true}
}
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 := 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)
}
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)
}
}
func TestMCPRejectsInvalidRequestIDs(t *testing.T) {
server := New()
for _, raw := range []string{
`{"jsonrpc":"2.0","id":null,"method":"ping"}`,
`{"jsonrpc":"2.0","id":[1],"method":"ping"}`,
`{"jsonrpc":"2.0","id":true,"method":"ping"}`,
} {
response := parseResponse(t, sendRequest(t, server, raw))
failure, ok := response["error"].(map[string]any)
if !ok || failure["code"] != float64(-32600) || response["id"] != nil {
t.Fatalf("invalid request ID response = %+v", response)
}
}
}
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)
}
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)
}
}
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 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"}`,
}
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}), base64JPEG(t, color.RGBA{B: 200, A: 255})}}
server := New()
server.BindHost(host)
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)
}
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)
}
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)
}
result := parseResponse(t, raw)["result"].(map[string]any)
if result["content"].([]any)[0].(map[string]any)["type"] != "image" {
t.Fatalf("vm_unlock should return the unlocked screen: %s", raw)
}
}
func TestVMUnlockExplainsMissingPassword(t *testing.T) {
const hostMessage = "secret_missing: 该虚拟机未保存登录密码,无法自动输入。"
host := &testHost{frames: []string{base64JPEG(t, color.RGBA{G: 120, A: 255})}, secretErr: errors.New(hostMessage)}
server := New()
server.BindHost(host)
result := callTool(t, server, "vm_unlock", `{"vm":"macos1"}`)
if result["isError"] != true {
t.Fatalf("vm_unlock should report a tool error, got %v", result)
}
text := 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)
}
for _, method := range host.methods() {
if method == "host/console.key" {
t.Fatal("vm_unlock must not press Return after the secret fails")
}
}
}
func TestCancellationNotificationStopsActiveToolCall(t *testing.T) {
server := New()
started := make(chan struct{})
server.BindHost(blockingHost{started: started})
result := make(chan json.RawMessage, 1)
go func() {
response, _ := server.Handle(context.Background(), ChannelCore, "s1", json.RawMessage(`{"jsonrpc":"2.0","id":31,"method":"tools/call","params":{"name":"vm_list","arguments":{}}}`))
result <- response
}()
select {
case <-started:
case <-time.After(time.Second):
t.Fatal("tool call did not reach the host")
}
// 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:
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)
}
case <-time.After(time.Second):
t.Fatal("cancelled tool call did not return")
}
}
func TestSessionClosedCancelsOnlyThatSession(t *testing.T) {
server := New()
started := make(chan struct{})
server.BindHost(blockingHost{started: started})
result := make(chan json.RawMessage, 1)
go func() {
response, _ := server.Handle(context.Background(), ChannelCore, "gone", json.RawMessage(`{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"vm_list","arguments":{}}}`))
result <- response
}()
<-started
server.SessionClosed(ChannelCore, "other")
select {
case <-result:
t.Fatal("closing another session cancelled this call")
case <-time.After(50 * time.Millisecond):
}
server.SessionClosed(ChannelCore, "gone")
select {
case raw := <-result:
if failure, _ := parseResponse(t, raw)["error"].(map[string]any); failure["code"] != float64(-32800) {
t.Fatalf("response after session closed = %s", raw)
}
case <-time.After(time.Second):
t.Fatal("closing the session did not cancel its call")
}
}
func TestVMLockSerializesOnlyTheSameVM(t *testing.T) {
server := New()
server.BindHost(&testHost{frames: []string{base64JPEG(t, color.RGBA{R: 90, A: 255})}})
server.state.runs["run-test"] = &testRun{ID: "run-test", Status: "running", Done: make(chan struct{})}
unlock, err := server.lockVM(context.Background(), "macos1")
if err != nil {
t.Fatal(err)
}
done := make(chan string, 3)
go func() { callTool(t, server, "screen", `{"vm":"macos2","return_image":false}`); done <- "screen" }()
go func() { callTool(t, server, "test_wait", `{"run_id":"run-test","timeout_ms":0}`); done <- "test_wait" }()
go func() { callTool(t, server, "vm_get", `{"vm":"macos1"}`); done <- "vm_get" }()
for range 3 {
select {
case <-done:
case <-time.After(time.Second):
t.Fatal("a call waited for another VM's lock or for a lock it does not need")
}
}
blocked := make(chan struct{})
go func() { callTool(t, server, "screen", `{"vm":"macos1"}`); close(blocked) }()
select {
case <-blocked:
t.Fatal("screen on a locked VM did not wait")
case <-time.After(50 * time.Millisecond):
}
unlock()
select {
case <-blocked:
case <-time.After(time.Second):
t.Fatal("screen did not run once the VM was unlocked")
}
}
func TestGuestAccessRejectsNonNormalVMPhase(t *testing.T) {
server := New()
host := &testHost{vmPhase: "installer"}
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)
}
}
func parseResponse(t *testing.T, raw json.RawMessage) map[string]any {
t.Helper()
var response map[string]any
if err := json.Unmarshal(raw, &response); err != nil {
t.Fatal(err)
}
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(), 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))
for y := range 2 {
for x := range 2 {
img.Set(x, y, fill)
}
}
var buf bytes.Buffer
if err := jpeg.Encode(&buf, img, &jpeg.Options{Quality: 100}); err != nil {
t.Fatal(err)
}
return base64.StdEncoding.EncodeToString(buf.Bytes())
}