Files
reims-agent/internal/mcp/server_test.go
T

323 lines
11 KiB
Go

package mcp
import (
"bytes"
"context"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"errors"
"image"
"image/color"
"image/jpeg"
"strings"
"testing"
"time"
"github.com/reims-go/reims-agent/internal/guest"
)
type hostCall struct {
method string
params any
}
type testHost struct {
calls []hostCall
frames []string
frameIndex int
secretValue string
}
type blockingHost struct{ started chan struct{} }
func (h blockingHost) Call(ctx context.Context, _ string, _ any, _ any) error {
close(h.started)
<-ctx.Done()
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.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,
}
return nil
}
if strings.HasSuffix(method, "typeSecret") {
*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"}
return nil
}
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 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)
}
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 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 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"])
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)
}
}
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)
}
}
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)
}
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" || zoomContent[1].(map[string]any)["text"] != "Crop 1x1" {
t.Fatalf("zoom result missing cropped image: %s", zoom)
}
}
func TestVMUnlockNeverReturnsThePassword(t *testing.T) {
const password = "mcp-password-fixture"
host := &testHost{frames: []string{base64JPEG(t, color.RGBA{G: 120, A: 255})}, secretValue: password}
server := New()
server.BindHost(host)
response := sendRequest(t, server, `{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"vm_unlock","arguments":{"vm":"macos1"}}}`)
if strings.Contains(string(response), password) {
t.Fatalf("vm_unlock leaked password in MCP response: %s", response)
}
if len(host.calls) != 3 {
t.Fatalf("vm_unlock host calls = %d, want typeSecret, key and screenshot", len(host.calls))
}
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])
}
if strings.Contains(string(encoded), password) {
t.Fatal("vm_unlock sent password to the host as a plaintext argument")
}
}
func TestWaitForScreenRecognizesChangedFrame(t *testing.T) {
first := base64JPEG(t, color.RGBA{B: 200, A: 255})
second := base64JPEG(t, color.RGBA{R: 200, A: 255})
baseline := sha256.Sum256([]byte(first))
host := &testHost{frames: []string{first, second}}
server := New()
server.BindHost(host)
payload := `{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"wait_for_screen","arguments":{"vm":"macos1","baseline_sha256":"` + hex.EncodeToString(baseline[:]) + `","timeout_ms":3000}}}`
response := sendRequest(t, server, payload)
content := parseResponse(t, response)["result"].(map[string]any)["content"].([]any)
if content[0].(map[string]any)["type"] != "image" || host.frameIndex < 2 {
t.Fatalf("wait_for_screen did not observe a changed frame: response=%s calls=%d", response, host.frameIndex)
}
}
func TestWaitForScreenAppliesTimeoutToHostCall(t *testing.T) {
server := New()
server.BindHost(deadlineHost{})
started := time.Now()
response := sendRequest(t, server, `{"jsonrpc":"2.0","id":33,"method":"tools/call","params":{"name":"wait_for_screen","arguments":{"vm":"macos1","timeout_ms":100}}}`)
if elapsed := time.Since(started); elapsed > time.Second {
t.Fatalf("wait_for_screen exceeded its timeout: %s", elapsed)
}
result := parseResponse(t, response)["result"].(map[string]any)
if result["isError"] != true || !strings.Contains(result["content"].([]any)[0].(map[string]any)["text"].(string), "Timed out") {
t.Fatalf("wait_for_screen did not report its timeout: %s", response)
}
}
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(), 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")
}
if _, err := server.Handle(context.Background(), json.RawMessage(`{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":31,"reason":"user cancelled"}}`)); err != nil {
t.Fatal(err)
}
select {
case raw := <-result:
response := parseResponse(t, raw)
failure, ok := response["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 TestCancelledDragReleasesMouseButton(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
host := &dragCancellationHost{cancel: cancel}
server := New()
server.BindHost(host)
response, err := server.Handle(ctx, json.RawMessage(`{"jsonrpc":"2.0","id":32,"method":"tools/call","params":{"name":"computer","arguments":{"vm":"macos1","action":"left_click_drag","x":1,"y":1,"x2":20,"y2":20,"width":100,"height":100}}}`))
if err != nil {
t.Fatal(err)
}
if len(host.buttonStates) != 2 || !host.buttonStates[0] || host.buttonStates[1] || host.releaseErr != nil {
t.Fatalf("mouse button states=%v release context error=%v response=%s", host.buttonStates, host.releaseErr, response)
}
}
func parseResponse(t *testing.T, raw json.RawMessage) map[string]any {
t.Helper()
var response map[string]any
if err := json.Unmarshal(raw, &response); err != nil {
t.Fatal(err)
}
return response
}
func sendRequest(t *testing.T, server *Server, raw string) json.RawMessage {
t.Helper()
result, err := server.Handle(context.Background(), json.RawMessage(raw))
if err != nil {
t.Fatal(err)
}
return result
}
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())
}