Merge pull request #3 from reims-go/feat/mcp-runtime-hardening
feat(mcp): add isolated sessions and keep test runs alive
This commit is contained in:
5 files changed
+790
-15
No files matched your search
@@ -0,0 +1,17 @@
|
||||
# Contributing
|
||||
|
||||
This repository targets the official Reims-Go MCP Service release workflow.
|
||||
|
||||
Requirements are Go 1.26 or later and a Reims-Go checkout with plugin API 1.1 support.
|
||||
|
||||
Run the local checks from the repository root.
|
||||
|
||||
```powershell
|
||||
go test ./...
|
||||
go vet ./...
|
||||
go build -o bin/reims-agent.exe ./cmd/reims-agent
|
||||
reims-go plugin doctor .
|
||||
reims-go plugin pack .
|
||||
```
|
||||
|
||||
Use the Reims-Go Plugins page to link this directory in developer mode. A release must be built by the repository workflow from the tagged source. Submit the resulting plugin package and SHA-256 to the market repository only after the GitHub Release is available.
|
||||
@@ -2,19 +2,7 @@
|
||||
|
||||
`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.
|
||||
|
||||
## Development
|
||||
|
||||
Requirements are Go 1.26 or later and a Reims-Go checkout with plugin API 1.1 support.
|
||||
|
||||
```powershell
|
||||
go test ./...
|
||||
go vet ./...
|
||||
go build -o bin/reims-agent.exe ./cmd/reims-agent
|
||||
reims-go plugin doctor .
|
||||
reims-go plugin pack .
|
||||
```
|
||||
|
||||
Use the Reims-Go Plugins page to link this directory in developer mode. 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.
|
||||
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).
|
||||
|
||||
## Current MCP tools
|
||||
|
||||
@@ -23,12 +11,17 @@ Use the Reims-Go Plugins page to link this directory in developer mode. Configur
|
||||
- `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
|
||||
|
||||
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.
|
||||
|
||||
Guest SSH requires port forwarding and a configured username in the host VM settings. Review the fingerprint from `guest_wait_ready` before calling `guest_trust_host`, and add the returned public key to the guest account's `~/.ssh/authorized_keys`. SFTP transfers are limited to the guest user's home directory and 64 MiB per file.
|
||||
|
||||
Enable **Allow AI to access this VM** in the MCP Service settings for each VM before using its desktop or SSH tools. This permission is stored per VM and can be revoked there at any time.
|
||||
|
||||
## Releases
|
||||
|
||||
Tags named `vX.Y.Z` run the Windows CI, tests, vet, build the sidecar, and package the plugin with the Reims-Go CLI. The resulting `reims.agent-X.Y.Z.zip` and its SHA-256 are attached to the GitHub Release. Market registration is maintained separately in [reims-go/plugins](https://github.com/reims-go/plugins).
|
||||
|
||||
+73
-1
@@ -34,6 +34,8 @@ type Server struct {
|
||||
callsMu sync.Mutex
|
||||
calls map[string]context.CancelFunc
|
||||
guest *guest.SSH
|
||||
root string
|
||||
state *agentState
|
||||
}
|
||||
|
||||
type request struct {
|
||||
@@ -72,7 +74,7 @@ func New() *Server {
|
||||
if err != nil {
|
||||
root = "."
|
||||
}
|
||||
return &Server{guest: guest.NewSSH(filepath.Clean(root)), calls: make(map[string]context.CancelFunc)}
|
||||
return &Server{guest: guest.NewSSH(filepath.Clean(root)), root: filepath.Clean(root), state: newAgentState(filepath.Clean(root)), calls: make(map[string]context.CancelFunc)}
|
||||
}
|
||||
|
||||
func (s *Server) BindHost(host Host) { s.host = host }
|
||||
@@ -442,6 +444,48 @@ func (s *Server) invoke(ctx context.Context, name string, raw json.RawMessage) (
|
||||
return nil, err
|
||||
}
|
||||
return textResult(result), nil
|
||||
case "session_create":
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
BaseSnapshot string `json:"base_snapshot"`
|
||||
Isolation string `json:"isolation"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result, err := s.createSession(ctx, args.VM, args.BaseSnapshot, args.Isolation)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(result), nil
|
||||
case "session_dispose":
|
||||
var args struct {
|
||||
SessionID string `json:"session_id"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(args.SessionID) == "" {
|
||||
return nil, fmt.Errorf("%w: session_id is required", errInvalidParams)
|
||||
}
|
||||
if err := s.disposeSession(ctx, args.SessionID); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(map[string]any{"ok": true}), nil
|
||||
case "snapshot_list", "snapshot_create", "snapshot_restore":
|
||||
return s.snapshotTool(ctx, name, raw)
|
||||
case "test_run":
|
||||
return s.startTestRun(ctx, raw)
|
||||
case "test_wait":
|
||||
return s.waitTestRun(ctx, raw)
|
||||
case "test_status":
|
||||
return s.statusTestRun(raw)
|
||||
case "test_logs":
|
||||
return s.logsTestRun(raw)
|
||||
case "test_result":
|
||||
return s.resultTestRun(raw)
|
||||
case "test_cancel":
|
||||
return s.cancelTestRun(raw)
|
||||
default:
|
||||
return nil, fmt.Errorf("unknown tool %q", name)
|
||||
}
|
||||
@@ -820,6 +864,11 @@ var toolCatalog = []map[string]any{
|
||||
{"name": "vm_get", "description": "Read the state and capabilities of one virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "vm_start", "description": "Start a virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "vm_shutdown", "description": "Request a normal guest shutdown.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "snapshot_list", "description": "List restore points for an authorized virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "snapshot_create", "description": "Create a restore point for an authorized virtual machine.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "name": map[string]any{"type": "string"}}, []string{"vm", "name"})},
|
||||
{"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 and return the current screen.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}}, []string{"vm"})},
|
||||
{"name": "computer", "description": "Capture or interact with a virtual machine display.", "inputSchema": objectSchema(map[string]any{
|
||||
"vm": map[string]any{"type": "string"},
|
||||
@@ -844,6 +893,29 @@ var toolCatalog = []map[string]any{
|
||||
{"name": "guest_put", "description": "Upload one file over SFTP to a path inside the guest user's home directory.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "local_path": map[string]any{"type": "string"}, "remote_path": map[string]any{"type": "string"}}, []string{"vm", "local_path", "remote_path"})},
|
||||
{"name": "guest_get", "description": "Download one file over SFTP from inside the guest user's home directory.", "inputSchema": objectSchema(map[string]any{"vm": map[string]any{"type": "string"}, "remote_path": map[string]any{"type": "string"}, "local_path": map[string]any{"type": "string"}}, []string{"vm", "remote_path", "local_path"})},
|
||||
{"name": "guest_logs", "description": "Read a bounded page from the complete output file of a previous guest_exec call.", "inputSchema": objectSchema(map[string]any{"log_id": map[string]any{"type": "string"}, "offset": map[string]any{"type": "integer", "minimum": 0}, "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 65536}}, []string{"log_id"})},
|
||||
{"name": "test_run", "description": "Start a configured test run and return its run id.", "inputSchema": objectSchema(map[string]any{
|
||||
"config": map[string]any{
|
||||
"type": "object",
|
||||
"properties": map[string]any{
|
||||
"vm": map[string]any{"type": "string"},
|
||||
"isolation": map[string]any{"type": "string", "enum": []string{"clone", "live"}},
|
||||
"workspace": map[string]any{"type": "string"},
|
||||
"sync": map[string]any{"type": "object", "properties": map[string]any{"dest": map[string]any{"type": "string"}, "exclude": map[string]any{"type": "array", "items": map[string]any{"type": "string"}}}, "additionalProperties": false},
|
||||
"steps": map[string]any{"type": "array", "minItems": 1, "items": map[string]any{"type": "object", "properties": map[string]any{"name": map[string]any{"type": "string"}, "run": map[string]any{"type": "string"}, "cwd": map[string]any{"type": "string"}, "timeout": map[string]any{"type": "string"}}, "required": []string{"run"}, "additionalProperties": false}},
|
||||
"junit": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
|
||||
"artifacts": map[string]any{"type": "array", "items": map[string]any{"type": "string"}},
|
||||
"keep_on_failure": map[string]any{"type": "boolean"},
|
||||
},
|
||||
"required": []string{"vm", "steps"},
|
||||
"additionalProperties": false,
|
||||
},
|
||||
"workspace": map[string]any{"type": "string"},
|
||||
}, []string{"config"})},
|
||||
{"name": "test_wait", "description": "Wait for a test run to finish or return its current status.", "inputSchema": objectSchema(map[string]any{"run_id": map[string]any{"type": "string"}, "timeout_ms": map[string]any{"type": "integer", "minimum": 1, "maximum": 300000}}, []string{"run_id"})},
|
||||
{"name": "test_status", "description": "Read the current status of a test run.", "inputSchema": objectSchema(map[string]any{"run_id": map[string]any{"type": "string"}}, []string{"run_id"})},
|
||||
{"name": "test_logs", "description": "Read a bounded page from a test run log.", "inputSchema": objectSchema(map[string]any{"run_id": map[string]any{"type": "string"}, "offset": map[string]any{"type": "integer", "minimum": 0}, "limit": map[string]any{"type": "integer", "minimum": 1, "maximum": 65536}}, []string{"run_id"})},
|
||||
{"name": "test_result", "description": "Read the structured result of a test run.", "inputSchema": objectSchema(map[string]any{"run_id": map[string]any{"type": "string"}}, []string{"run_id"})},
|
||||
{"name": "test_cancel", "description": "Cancel an active test run and clean up its temporary VM.", "inputSchema": objectSchema(map[string]any{"run_id": map[string]any{"type": "string"}}, []string{"run_id"})},
|
||||
}
|
||||
|
||||
func objectSchema(properties map[string]any, required []string) map[string]any {
|
||||
|
||||
@@ -0,0 +1,678 @@
|
||||
package mcp
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// agentState keeps test orchestration state in the plugin process. A session
|
||||
// is only ever disposable by the plugin that created it.
|
||||
type agentState struct {
|
||||
mu sync.Mutex
|
||||
root string
|
||||
sessions map[string]*agentSession
|
||||
runs map[string]*testRun
|
||||
}
|
||||
|
||||
type agentSession struct {
|
||||
ID string
|
||||
VM string
|
||||
CloneVM string
|
||||
Owned bool
|
||||
Disposed bool
|
||||
}
|
||||
|
||||
type testRun struct {
|
||||
mu sync.Mutex
|
||||
ID string
|
||||
Status string
|
||||
VM string
|
||||
Session string
|
||||
Started time.Time
|
||||
Finished time.Time
|
||||
Config testConfig
|
||||
Result map[string]any
|
||||
Cancel context.CancelFunc
|
||||
Done chan struct{}
|
||||
LogPath string
|
||||
Files testFiles
|
||||
}
|
||||
|
||||
type testFiles struct {
|
||||
JUnit []map[string]any `json:"junit,omitempty"`
|
||||
Artifacts []map[string]any `json:"artifacts,omitempty"`
|
||||
}
|
||||
|
||||
type testConfig struct {
|
||||
VM string `json:"vm"`
|
||||
Isolation string `json:"isolation"`
|
||||
BaseSnapshot string `json:"base_snapshot"`
|
||||
Workspace string `json:"workspace"`
|
||||
Sync syncConfig `json:"sync"`
|
||||
Steps []testStep `json:"steps"`
|
||||
JUnit []string `json:"junit"`
|
||||
Artifacts []string `json:"artifacts"`
|
||||
KeepOnFailure bool `json:"keep_on_failure"`
|
||||
}
|
||||
|
||||
type syncConfig struct {
|
||||
Dest string `json:"dest"`
|
||||
Exclude []string `json:"exclude"`
|
||||
}
|
||||
|
||||
type testStep struct {
|
||||
Name string `json:"name"`
|
||||
Run string `json:"run"`
|
||||
CWD string `json:"cwd"`
|
||||
Timeout string `json:"timeout"`
|
||||
}
|
||||
|
||||
func newAgentState(root string) *agentState {
|
||||
return &agentState{root: root, sessions: make(map[string]*agentSession), runs: make(map[string]*testRun)}
|
||||
}
|
||||
|
||||
func newOpaqueID(prefix string) string {
|
||||
var raw [8]byte
|
||||
if _, err := rand.Read(raw[:]); err != nil {
|
||||
return fmt.Sprintf("%s-%d", prefix, time.Now().UnixNano())
|
||||
}
|
||||
return fmt.Sprintf("%s-%x", prefix, raw)
|
||||
}
|
||||
|
||||
func (s *Server) createSession(ctx context.Context, vm, baseSnapshot, isolation string) (map[string]any, error) {
|
||||
if s.state == nil {
|
||||
return nil, errors.New("plugin state is unavailable")
|
||||
}
|
||||
vm = strings.TrimSpace(vm)
|
||||
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
|
||||
}
|
||||
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
|
||||
}
|
||||
|
||||
func (s *Server) disposeSession(ctx context.Context, id string) error {
|
||||
s.state.mu.Lock()
|
||||
session := s.state.sessions[id]
|
||||
if session == nil {
|
||||
s.state.mu.Unlock()
|
||||
return errors.New("session not found")
|
||||
}
|
||||
if session.Disposed {
|
||||
s.state.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
session.Disposed = true
|
||||
s.state.mu.Unlock()
|
||||
if !session.Owned {
|
||||
s.state.mu.Lock()
|
||||
delete(s.state.sessions, id)
|
||||
s.state.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
_ = s.host.Call(ctx, "host/vm.shutdown", map[string]any{"vm": session.VM}, &map[string]any{})
|
||||
if err := s.host.Call(ctx, "host/vm.delete", map[string]any{"vm": session.VM}, &map[string]any{}); err != nil {
|
||||
s.state.mu.Lock()
|
||||
session.Disposed = false
|
||||
s.state.mu.Unlock()
|
||||
return err
|
||||
}
|
||||
s.state.mu.Lock()
|
||||
delete(s.state.sessions, id)
|
||||
s.state.mu.Unlock()
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) snapshotTool(ctx context.Context, name string, raw json.RawMessage) (any, error) {
|
||||
var args struct {
|
||||
VM string `json:"vm"`
|
||||
Name string `json:"name"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(args.VM) == "" {
|
||||
return nil, fmt.Errorf("%w: vm is required", errInvalidParams)
|
||||
}
|
||||
var out any
|
||||
method := "host/vm.snapshot.list"
|
||||
switch name {
|
||||
case "snapshot_create":
|
||||
method = "host/vm.snapshot.create"
|
||||
case "snapshot_restore":
|
||||
method = "host/vm.snapshot.restore"
|
||||
}
|
||||
params := map[string]any{"vm": args.VM}
|
||||
if args.Name != "" {
|
||||
params["name"] = args.Name
|
||||
}
|
||||
if err := s.host.Call(ctx, method, params, &out); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return textResult(out), nil
|
||||
}
|
||||
|
||||
func (s *Server) startTestRun(parent context.Context, raw json.RawMessage) (any, error) {
|
||||
if parent == nil {
|
||||
parent = context.Background()
|
||||
}
|
||||
if err := parent.Err(); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var args struct {
|
||||
Config json.RawMessage `json:"config"`
|
||||
Workspace string `json:"workspace"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
var cfg testConfig
|
||||
if len(args.Config) == 0 || string(args.Config) == "null" {
|
||||
return nil, fmt.Errorf("%w: config is required", errInvalidParams)
|
||||
}
|
||||
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"
|
||||
}
|
||||
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
|
||||
// request and is cancelled through test_cancel or when the run finishes.
|
||||
ctx, cancel := context.WithCancel(context.WithoutCancel(parent))
|
||||
run.Cancel = cancel
|
||||
dir := filepath.Join(s.state.root, "runs", run.ID)
|
||||
if err := os.MkdirAll(dir, 0o700); err != nil {
|
||||
cancel()
|
||||
return nil, err
|
||||
}
|
||||
run.LogPath = filepath.Join(dir, "run.log")
|
||||
s.state.mu.Lock()
|
||||
s.state.runs[run.ID] = run
|
||||
s.state.mu.Unlock()
|
||||
go s.executeTestRun(ctx, run)
|
||||
return textResult(map[string]any{"run_id": run.ID, "status": "queued"}), nil
|
||||
}
|
||||
|
||||
func (s *Server) executeTestRun(ctx context.Context, run *testRun) {
|
||||
run.mu.Lock()
|
||||
run.Status, run.Started = "preparing", time.Now()
|
||||
run.mu.Unlock()
|
||||
logFile, _ := os.OpenFile(run.LogPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
|
||||
if logFile != nil {
|
||||
defer logFile.Close()
|
||||
}
|
||||
logLine := func(line string) {
|
||||
if logFile != nil {
|
||||
_, _ = fmt.Fprintln(logFile, time.Now().Format(time.RFC3339)+" "+line)
|
||||
}
|
||||
}
|
||||
session, err := s.createSession(ctx, run.Config.VM, run.Config.BaseSnapshot, run.Config.Isolation)
|
||||
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" {
|
||||
var out map[string]any
|
||||
err = s.host.Call(ctx, "host/vm.start", map[string]any{"vm": run.VM}, &out)
|
||||
}
|
||||
if err == nil {
|
||||
run.mu.Lock()
|
||||
run.Status = "running"
|
||||
run.mu.Unlock()
|
||||
if result, waitErr := s.waitGuest(ctx, run.VM); waitErr != nil {
|
||||
err = waitErr
|
||||
} else {
|
||||
logLine(fmt.Sprintf("guest ready: %v", result))
|
||||
}
|
||||
}
|
||||
if err == nil {
|
||||
err = s.syncWorkspace(ctx, run)
|
||||
}
|
||||
if err == nil {
|
||||
for _, step := range run.Config.Steps {
|
||||
if err = s.executeStep(ctx, run, step, logLine); err != nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
var files testFiles
|
||||
if err == nil {
|
||||
files, err = s.collectTestFiles(ctx, run)
|
||||
}
|
||||
status := "passed"
|
||||
if errors.Is(err, context.Canceled) {
|
||||
status = "cancelled"
|
||||
} else if err != nil {
|
||||
status = "failed"
|
||||
}
|
||||
run.mu.Lock()
|
||||
started := run.Started
|
||||
vmName := run.VM
|
||||
sessionID := run.Session
|
||||
keepOnFailure := run.Config.KeepOnFailure
|
||||
run.mu.Unlock()
|
||||
result := map[string]any{"run_id": run.ID, "status": status, "vm": vmName, "duration_s": int(time.Since(started).Seconds())}
|
||||
if err != nil && !errors.Is(err, context.Canceled) {
|
||||
result["error"] = err.Error()
|
||||
}
|
||||
if len(files.JUnit) > 0 {
|
||||
result["junit"] = files.JUnit
|
||||
}
|
||||
if len(files.Artifacts) > 0 {
|
||||
result["artifacts"] = files.Artifacts
|
||||
}
|
||||
if err == nil || !keepOnFailure {
|
||||
if sessionID != "" {
|
||||
_ = s.disposeSession(context.Background(), sessionID)
|
||||
}
|
||||
} else {
|
||||
result["kept_vm"] = vmName
|
||||
}
|
||||
run.mu.Lock()
|
||||
run.Status, run.Finished, run.Result = status, time.Now(), result
|
||||
run.mu.Unlock()
|
||||
close(run.Done)
|
||||
run.mu.Lock()
|
||||
cancel := run.Cancel
|
||||
run.mu.Unlock()
|
||||
if cancel != nil {
|
||||
cancel()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) waitGuest(ctx context.Context, vm string) (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 {
|
||||
return nil, err
|
||||
}
|
||||
if _, ok := out["ssh_port"]; !ok {
|
||||
return map[string]any{"ready": true}, nil
|
||||
}
|
||||
var result map[string]any
|
||||
if err := s.invokeGuestWait(ctx, vm, &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
|
||||
}
|
||||
result, err := s.guest.WaitReady(ctx, vm, address, username, 30*time.Second)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if ready, _ := result["ready"].(bool); !ready {
|
||||
return errors.New("ssh_unavailable: guest SSH is not ready")
|
||||
}
|
||||
*out = result
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) syncWorkspace(ctx context.Context, run *testRun) error {
|
||||
root := strings.TrimSpace(run.Config.Workspace)
|
||||
if root == "" {
|
||||
return nil
|
||||
}
|
||||
info, err := os.Stat(root)
|
||||
if err != nil || !info.IsDir() {
|
||||
return fmt.Errorf("workspace is unavailable: %s", root)
|
||||
}
|
||||
dest := run.Config.Sync.Dest
|
||||
if dest == "" {
|
||||
dest = "~/work"
|
||||
}
|
||||
return filepath.Walk(root, func(pathName string, info os.FileInfo, walkErr error) error {
|
||||
if walkErr != nil {
|
||||
return walkErr
|
||||
}
|
||||
if info.IsDir() {
|
||||
return nil
|
||||
}
|
||||
rel, err := filepath.Rel(root, pathName)
|
||||
if err != nil || excludedPath(rel, run.Config.Sync.Exclude) {
|
||||
return nil
|
||||
}
|
||||
remote := strings.TrimSuffix(dest, "/") + "/" + filepath.ToSlash(rel)
|
||||
remote = strings.Replace(remote, "~/", "", 1)
|
||||
var out map[string]any
|
||||
return s.hostGuestPut(ctx, run.VM, pathName, remote, &out)
|
||||
})
|
||||
}
|
||||
|
||||
func excludedPath(rel string, patterns []string) bool {
|
||||
rel = filepath.ToSlash(rel)
|
||||
for _, pattern := range patterns {
|
||||
pattern = strings.Trim(strings.ReplaceAll(pattern, "\\", "/"), "/")
|
||||
if pattern == "" {
|
||||
continue
|
||||
}
|
||||
if ok, _ := filepath.Match(pattern, rel); ok || strings.HasPrefix(rel, strings.TrimSuffix(pattern, "/")+"/") {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (s *Server) hostGuestPut(ctx context.Context, vm, local, remote string, out *map[string]any) error {
|
||||
return s.guestPutViaHost(ctx, vm, local, remote, out)
|
||||
}
|
||||
|
||||
func (s *Server) guestPutViaHost(ctx context.Context, vm, local, remote string, out *map[string]any) error {
|
||||
// guest_put is handled by the MCP plugin itself, so call the same SSH path
|
||||
// used by the public tool without exposing a second Host API method.
|
||||
address, username, err := s.guestAddress(ctx, vm)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := s.guest.Put(ctx, vm, address, username, local, remote)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
*out = map[string]any{"bytes": result.Bytes}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) executeStep(ctx context.Context, run *testRun, step testStep, logLine func(string)) error {
|
||||
if strings.TrimSpace(step.Run) == "" {
|
||||
return errors.New("test step command is empty")
|
||||
}
|
||||
timeout := 15 * time.Minute
|
||||
if step.Timeout != "" {
|
||||
if parsed, err := time.ParseDuration(step.Timeout); err == nil {
|
||||
timeout = parsed
|
||||
}
|
||||
}
|
||||
address, username, err := s.guestAddress(ctx, run.VM)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
result, err := s.guest.Exec(ctx, run.VM, address, username, step.Run, step.CWD, nil, timeout)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
logLine(fmt.Sprintf("step %s exit=%d: %s", step.Name, result.ExitCode, result.Output))
|
||||
if result.ExitCode != 0 || result.TimedOut || result.Cancelled {
|
||||
return fmt.Errorf("step %q failed with exit code %d", step.Name, result.ExitCode)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *Server) collectTestFiles(ctx context.Context, run *testRun) (testFiles, error) {
|
||||
var files testFiles
|
||||
if len(run.Config.JUnit) == 0 && len(run.Config.Artifacts) == 0 {
|
||||
return files, nil
|
||||
}
|
||||
dir := filepath.Dir(run.LogPath)
|
||||
seen := make(map[string]struct{}, len(run.Config.JUnit)+len(run.Config.Artifacts))
|
||||
collect := func(remote string, junit bool) error {
|
||||
remote = strings.TrimSpace(remote)
|
||||
if remote == "" {
|
||||
return nil
|
||||
}
|
||||
if _, ok := seen[remote]; ok {
|
||||
return nil
|
||||
}
|
||||
seen[remote] = struct{}{}
|
||||
name := filepath.Base(remote)
|
||||
if name == "." || name == "" || strings.ContainsAny(name, `/\\`) {
|
||||
return fmt.Errorf("invalid collected file path %q", remote)
|
||||
}
|
||||
local := filepath.Join(dir, name)
|
||||
address, username, err := s.guestAddress(ctx, run.VM)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := s.guest.Get(ctx, run.VM, address, username, remote, local); err != nil {
|
||||
return err
|
||||
}
|
||||
entry := map[string]any{"remote_path": remote, "local_path": local}
|
||||
if junit {
|
||||
data, readErr := os.ReadFile(local)
|
||||
if readErr != nil {
|
||||
return readErr
|
||||
}
|
||||
entry["summary"] = parseJUnit(data)
|
||||
files.JUnit = append(files.JUnit, entry)
|
||||
} else {
|
||||
files.Artifacts = append(files.Artifacts, entry)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, remote := range run.Config.JUnit {
|
||||
if err := collect(remote, true); err != nil {
|
||||
return files, err
|
||||
}
|
||||
}
|
||||
for _, remote := range run.Config.Artifacts {
|
||||
if err := collect(remote, false); err != nil {
|
||||
return files, err
|
||||
}
|
||||
}
|
||||
run.mu.Lock()
|
||||
run.Files = files
|
||||
run.mu.Unlock()
|
||||
return files, nil
|
||||
}
|
||||
|
||||
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"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
run := s.lookupRun(args.RunID)
|
||||
if run == nil {
|
||||
return nil, errors.New("run not found")
|
||||
}
|
||||
if args.Timeout <= 0 {
|
||||
args.Timeout = 30000
|
||||
}
|
||||
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()
|
||||
}
|
||||
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) {
|
||||
var args struct {
|
||||
RunID string `json:"run_id"`
|
||||
Offset int64 `json:"offset"`
|
||||
Limit int `json:"limit"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
run := s.lookupRun(args.RunID)
|
||||
if run == nil {
|
||||
return nil, errors.New("run not found")
|
||||
}
|
||||
if args.Offset < 0 {
|
||||
return nil, errors.New("offset must be non-negative")
|
||||
}
|
||||
if args.Limit <= 0 || args.Limit > 65536 {
|
||||
args.Limit = 8192
|
||||
}
|
||||
file, err := os.Open(run.LogPath)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer file.Close()
|
||||
if _, err := file.Seek(args.Offset, io.SeekStart); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, err := io.ReadAll(io.LimitReader(file, int64(args.Limit)))
|
||||
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
|
||||
}
|
||||
|
||||
func (s *Server) cancelTestRun(raw json.RawMessage) (any, error) {
|
||||
run, err := s.runFromRaw(raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
run.mu.Lock()
|
||||
cancel := run.Cancel
|
||||
run.mu.Unlock()
|
||||
if cancel != nil {
|
||||
cancel()
|
||||
}
|
||||
return textResult(map[string]any{"ok": true}), nil
|
||||
}
|
||||
|
||||
func (s *Server) runFromRaw(raw json.RawMessage) (*testRun, error) {
|
||||
var args struct {
|
||||
RunID string `json:"run_id"`
|
||||
}
|
||||
if err := decodeArguments(raw, &args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
run := s.lookupRun(args.RunID)
|
||||
if run == nil {
|
||||
return nil, errors.New("run not found")
|
||||
}
|
||||
return run, nil
|
||||
}
|
||||
|
||||
func (s *Server) lookupRun(id string) *testRun {
|
||||
s.state.mu.Lock()
|
||||
defer s.state.mu.Unlock()
|
||||
return s.state.runs[strings.TrimSpace(id)]
|
||||
}
|
||||
|
||||
func (s *Server) runStatus(run *testRun) map[string]any {
|
||||
run.mu.Lock()
|
||||
defer run.mu.Unlock()
|
||||
status := map[string]any{"run_id": run.ID, "status": run.Status, "vm": run.VM}
|
||||
if !run.Started.IsZero() {
|
||||
end := run.Finished
|
||||
if end.IsZero() {
|
||||
end = time.Now()
|
||||
}
|
||||
status["duration_s"] = int(end.Sub(run.Started).Seconds())
|
||||
}
|
||||
if run.Session != "" {
|
||||
status["session_id"] = run.Session
|
||||
}
|
||||
if len(run.Files.JUnit) > 0 {
|
||||
status["junit"] = run.Files.JUnit
|
||||
}
|
||||
if len(run.Files.Artifacts) > 0 {
|
||||
status["artifacts"] = run.Files.Artifacts
|
||||
}
|
||||
return status
|
||||
}
|
||||
|
||||
// JUnit reports are commonly either a single <testsuite> or a <testsuites>
|
||||
// wrapper. Invalid or non-JUnit XML is treated as an empty summary.
|
||||
type junitSuite struct {
|
||||
Tests int `xml:"tests,attr"`
|
||||
Failures int `xml:"failures,attr"`
|
||||
Skipped int `xml:"skipped,attr"`
|
||||
}
|
||||
|
||||
type junitDocument struct {
|
||||
Tests int `xml:"tests,attr"`
|
||||
Failures int `xml:"failures,attr"`
|
||||
Skipped int `xml:"skipped,attr"`
|
||||
Suites []junitSuite `xml:"testsuite"`
|
||||
}
|
||||
|
||||
func parseJUnit(data []byte) map[string]any {
|
||||
var doc junitDocument
|
||||
if xml.Unmarshal(data, &doc) != nil {
|
||||
return map[string]any{}
|
||||
}
|
||||
tests, failures, skipped := doc.Tests, doc.Failures, doc.Skipped
|
||||
if len(doc.Suites) > 0 {
|
||||
tests, failures, skipped = 0, 0, 0
|
||||
for _, suite := range doc.Suites {
|
||||
tests += suite.Tests
|
||||
failures += suite.Failures
|
||||
skipped += suite.Skipped
|
||||
}
|
||||
}
|
||||
passed := tests - failures - skipped
|
||||
if passed < 0 {
|
||||
passed = 0
|
||||
}
|
||||
return map[string]any{"tests": tests, "passed": passed, "failed": failures, "skipped": skipped}
|
||||
}
|
||||
+16
-1
@@ -24,8 +24,23 @@
|
||||
"title": { "zh-CN": "MCP服务", "en-US": "MCP Service" },
|
||||
"x-scope": "vm",
|
||||
"x-group": "collaboration",
|
||||
"x-order": ["username", "login_password"],
|
||||
"x-order": ["allow_ai_access", "username", "login_password"],
|
||||
"properties": {
|
||||
"allow_ai_access": {
|
||||
"type": "boolean",
|
||||
"title": {
|
||||
"zh-CN": "允许 AI 操作此虚拟机",
|
||||
"en-US": "Allow AI to access this VM"
|
||||
},
|
||||
"description": {
|
||||
"zh-CN": "启用后,MCP 服务可查看屏幕、操作桌面,并通过 SSH 访问此虚拟机。",
|
||||
"en-US": "When enabled, MCP clients can view and control the desktop and use SSH with this VM."
|
||||
},
|
||||
"default": false,
|
||||
"x-scope": "vm",
|
||||
"x-group": "collaboration",
|
||||
"x-effect": "immediate"
|
||||
},
|
||||
"username": {
|
||||
"type": "string",
|
||||
"title": { "zh-CN": "macOS 用户名", "en-US": "macOS username" },
|
||||
|
||||
Reference in new issue
Block a user