Merge pull request #5 from reims-go/fix/mcp-vm-lifecycle
feat(mcp): expose virtual machine suspend and resume
This commit is contained in:
5 files changed
+310
-19
No files matched your search
@@ -6,7 +6,7 @@ Configure an MCP client to launch `reims-go.exe plugin connect reims.agent mcp`
|
||||
|
||||
## Current MCP tools
|
||||
|
||||
- `vm_list`, `vm_get`, `vm_start`, `vm_shutdown`, and `vm_unlock`
|
||||
- `vm_list`, `vm_get`, `vm_start`, `vm_shutdown`, `vm_suspend`, `vm_resume`, and `vm_unlock`
|
||||
- `computer` for screenshots, zoom, pointer, keyboard, and text input
|
||||
- `wait_for_screen` for changed or stable frames
|
||||
- `guest_public_key`, `guest_wait_ready`, and `guest_trust_host` for explicit SSH setup and host-key pinning
|
||||
|
||||
@@ -318,7 +318,7 @@ func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) (
|
||||
return textResult(out), nil
|
||||
case "vm_start":
|
||||
return s.vmStart(ctx, raw)
|
||||
case "vm_shutdown":
|
||||
case "vm_shutdown", "vm_suspend", "vm_resume":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
}
|
||||
@@ -326,7 +326,8 @@ func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) (
|
||||
return nil, err
|
||||
}
|
||||
var out hostReply
|
||||
if err := s.host.Call(ctx, "host/vm.shutdown", args, &out); err != nil {
|
||||
method := "host/vm." + strings.TrimPrefix(name, "vm_")
|
||||
if err := s.host.Call(ctx, method, args, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"ok": true}), nil
|
||||
@@ -640,7 +641,7 @@ func (s *Server) vmUnlock(ctx context.Context, raw json.RawMessage) (any, error)
|
||||
|
||||
var typed hostReply
|
||||
if err := s.host.Call(ctx, "host/console.typeSecret", map[string]any{"vm": args.VM, "setting": "login_password"}, &typed); err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("cannot enter the login password: %w", err)
|
||||
}
|
||||
var key hostReply
|
||||
if err := s.host.Call(ctx, "host/console.key", map[string]any{"vm": args.VM, "key": "ret"}, &key); err != nil {
|
||||
@@ -1056,7 +1057,9 @@ var toolCatalog = []map[string]any{
|
||||
{"name": "snapshot_restore", "description": "Restore a restore point on an MCP-owned temporary VM.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "name": map[string]any{"type": "string"}}, []string{"vm", "name"})},
|
||||
{"name": "session_create", "description": "Create an isolated CoW VM session for a test run. Restore-point bases are unavailable on the current host.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "isolation": map[string]any{"type": "string", "enum": []string{"clone", "live"}}}, []string{"vm"})},
|
||||
{"name": "session_dispose", "description": "Dispose an MCP-owned temporary VM session.", "inputSchema": objectSchema(map[string]any{"session_id": map[string]any{"type": "string"}}, []string{"session_id"})},
|
||||
{"name": "vm_unlock", "description": "Enter the host-stored macOS login password, wait for the desktop to settle (skipping transitional blank frames), and return the screen.", "inputSchema": objectSchema(map[string]any{
|
||||
{"name": "vm_suspend", "description": "Save a running VM state and stop its process.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string", "description": "VM reference."}}, []string{"vm"})},
|
||||
{"name": "vm_resume", "description": "Restore a suspended VM from its saved state.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string", "description": "VM reference."}}, []string{"vm"})},
|
||||
{"name": "vm_unlock", "description": "Type the macOS login password saved in the Reims-Go MCP Service settings into the VM's login screen, wait for the desktop to settle (skipping transitional blank frames), and return the screen. Requires the VM, or the source VM of an MCP clone, to have a saved login password.", "inputSchema": objectSchema(map[string]any{
|
||||
"vm": map[string]any{"type": "string", "description": "VM reference."},
|
||||
"timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 60000, "description": "Max milliseconds to wait for the unlocked screen to settle (default 20000)."},
|
||||
"stable_ms": map[string]any{"type": "integer", "minimum": 0, "maximum": 30000, "description": "Stability window in milliseconds after leaving the login screen (default 1500)."},
|
||||
|
||||
@@ -28,6 +28,7 @@ type testHost struct {
|
||||
frames []string
|
||||
frameIndex int
|
||||
secretValue string
|
||||
secretErr error
|
||||
vmPhase string
|
||||
deleteErr error
|
||||
}
|
||||
@@ -93,6 +94,9 @@ func (h *testHost) Call(_ context.Context, method string, params any, out any) e
|
||||
return nil
|
||||
}
|
||||
if strings.HasSuffix(method, "typeSecret") {
|
||||
if h.secretErr != nil {
|
||||
return h.secretErr
|
||||
}
|
||||
*out.(*hostReply) = hostReply{Characters: 19}
|
||||
return nil
|
||||
}
|
||||
@@ -163,6 +167,29 @@ func TestReadResourceReportsUnavailableHost(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSuspendAndResumeUseLifecycleHostMethods(t *testing.T) {
|
||||
for tool, method := range map[string]string{"vm_suspend": "host/vm.suspend", "vm_resume": "host/vm.resume"} {
|
||||
t.Run(tool, func(t *testing.T) {
|
||||
server := New()
|
||||
host := &testHost{}
|
||||
server.BindHost(host)
|
||||
request := `{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"` + tool + `","arguments":{"vm":"driver:macos1"}}}`
|
||||
response := parseResponse(t, sendRequest(t, server, request))
|
||||
result, ok := response["result"].(map[string]any)
|
||||
if !ok || result["isError"] == true {
|
||||
t.Fatalf("tool response = %v", response)
|
||||
}
|
||||
if len(host.calls) != 1 || host.calls[0].method != method {
|
||||
t.Fatalf("host calls = %v, want %s", host.calls, method)
|
||||
}
|
||||
args, err := json.Marshal(host.calls[0].params)
|
||||
if err != nil || string(args) != `{"vm":"driver:macos1"}` {
|
||||
t.Fatalf("host arguments = %s, err = %v", args, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGuestToolsAreAdvertisedAndPublicKeyIsAvailable(t *testing.T) {
|
||||
server := New()
|
||||
server.guest = guest.NewSSH(t.TempDir())
|
||||
@@ -225,6 +252,31 @@ func TestVMUnlockNeverReturnsThePassword(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestVMUnlockExplainsMissingPassword(t *testing.T) {
|
||||
const hostMessage = "secret_missing: 该虚拟机未保存登录密码,无法自动输入。"
|
||||
host := &testHost{secretErr: errors.New(hostMessage)}
|
||||
server := New()
|
||||
server.BindHost(host)
|
||||
response := sendRequest(t, server, `{"jsonrpc":"2.0","id":6,"method":"tools/call","params":{"name":"vm_unlock","arguments":{"vm":"macos1"}}}`)
|
||||
result := parseResponse(t, response)["result"].(map[string]any)
|
||||
if isErr, _ := result["isError"].(bool); !isErr {
|
||||
t.Fatalf("vm_unlock should report a tool error, got %s", response)
|
||||
}
|
||||
text := result["content"].([]any)[0].(map[string]any)["text"].(string)
|
||||
if !strings.Contains(text, "cannot enter the login password") {
|
||||
t.Fatalf("vm_unlock did not explain the failure step: %q", text)
|
||||
}
|
||||
if !strings.Contains(text, hostMessage) {
|
||||
t.Fatalf("vm_unlock dropped the host explanation: %q", text)
|
||||
}
|
||||
if strings.Contains(text, "Login password entered") {
|
||||
t.Fatalf("vm_unlock claimed success after a failed secret entry: %q", text)
|
||||
}
|
||||
if host.frameIndex != 0 || len(host.frames) != 0 {
|
||||
t.Fatalf("vm_unlock must not press Return or screenshot after the secret fails")
|
||||
}
|
||||
}
|
||||
|
||||
func TestWaitForScreenRecognizesChangedFrame(t *testing.T) {
|
||||
first := base64JPEG(t, color.RGBA{B: 200, A: 255})
|
||||
second := base64JPEG(t, color.RGBA{R: 200, A: 255})
|
||||
|
||||
+105
-14
@@ -57,6 +57,7 @@ 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 +66,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"`
|
||||
@@ -213,6 +239,9 @@ func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any,
|
||||
if strings.TrimSpace(cfg.VM) == "" || len(cfg.Steps) == 0 {
|
||||
return nil, fmt.Errorf("%w: vm and at least one step are required", errInvalidParams)
|
||||
}
|
||||
if _, err := resolveGuestWaitTimeout(cfg.BootTimeout); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, err := s.vmInfo(parent, cfg.VM); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -265,7 +294,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))
|
||||
@@ -334,7 +366,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 {
|
||||
@@ -344,26 +376,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 {
|
||||
|
||||
@@ -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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user