545 lines
20 KiB
Go
545 lines
20 KiB
Go
package main
|
|
|
|
import (
|
|
"bytes"
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"runtime"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/modelcontextprotocol/go-sdk/mcp"
|
|
"github.com/shoemoney/devbox/internal/config"
|
|
"github.com/shoemoney/devbox/internal/control"
|
|
"github.com/shoemoney/devbox/internal/daemon"
|
|
"github.com/shoemoney/devbox/internal/hub"
|
|
"github.com/shoemoney/devbox/internal/hub/blobstore"
|
|
"github.com/shoemoney/devbox/internal/hub/meta"
|
|
"github.com/shoemoney/devbox/internal/identity"
|
|
"github.com/shoemoney/devbox/internal/ignore"
|
|
"github.com/shoemoney/devbox/internal/secret"
|
|
"github.com/shoemoney/devbox/internal/syncer"
|
|
"github.com/shoemoney/devbox/internal/transport"
|
|
"github.com/shoemoney/devbox/pkg/proto"
|
|
)
|
|
|
|
// DEVBOX_MCP_TEST_BINARY reruns these protocol checks against a packaged binary.
|
|
// Otherwise build the actual command with the race detector, not a test shim.
|
|
func TestMCPStdio(t *testing.T) {
|
|
binary := os.Getenv("DEVBOX_MCP_TEST_BINARY")
|
|
if binary == "" {
|
|
binary = filepath.Join(t.TempDir(), "devbox")
|
|
if runtime.GOOS == "windows" {
|
|
binary += ".exe"
|
|
}
|
|
build := exec.Command("go", "build", "-race", "-o", binary, ".")
|
|
if out, err := build.CombinedOutput(); err != nil {
|
|
t.Fatalf("build actual binary: %v\n%s", err, out)
|
|
}
|
|
}
|
|
t.Run("permissions-and-errors", func(t *testing.T) {
|
|
for _, mode := range []struct {
|
|
flags []string
|
|
count int
|
|
}{{nil, 5}, {[]string{"--allow-writes"}, 9}, {[]string{"--allow-writes", "--allow-destructive"}, 12}} {
|
|
t.Run(fmt.Sprint(mode.count), func(t *testing.T) {
|
|
cfg := t.TempDir()
|
|
cs := mcpTestClient(t, binary, cfg, mode.flags...)
|
|
listed, err := cs.ListTools(t.Context(), nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(listed.Tools) != mode.count {
|
|
t.Fatalf("tool count %d, want %d", len(listed.Tools), mode.count)
|
|
}
|
|
names := map[string]bool{}
|
|
for _, tool := range listed.Tools {
|
|
names[tool.Name] = true
|
|
if tool.InputSchema == nil || tool.OutputSchema == nil || tool.Annotations == nil {
|
|
t.Fatalf("missing schema/annotations: %s", tool.Name)
|
|
}
|
|
read := tool.Name == "devbox_status" || tool.Name == "devbox_doctor" || tool.Name == "devbox_conflicts" || tool.Name == "devbox_history" || tool.Name == "devbox_members"
|
|
if tool.Annotations.ReadOnlyHint != read {
|
|
t.Fatalf("wrong read annotation: %s", tool.Name)
|
|
}
|
|
}
|
|
for _, name := range []string{"devbox_status", "devbox_doctor", "devbox_conflicts", "devbox_history", "devbox_members"} {
|
|
if !names[name] {
|
|
t.Fatalf("missing %s", name)
|
|
}
|
|
}
|
|
for _, name := range []string{"devbox_pause", "devbox_resume", "devbox_publish", "devbox_mount"} {
|
|
if names[name] != (mode.count >= 9) {
|
|
t.Fatalf("bad gating %s", name)
|
|
}
|
|
}
|
|
for _, name := range []string{"devbox_restore", "devbox_deploy", "devbox_unmount"} {
|
|
if names[name] != (mode.count == 12) {
|
|
t.Fatalf("bad gating %s", name)
|
|
}
|
|
}
|
|
got := mcpCall(t, cs, "status", nil, false)
|
|
var status statusJSON
|
|
mcpData(t, got, &status)
|
|
if status.Joined {
|
|
t.Fatal("fabricated enrollment")
|
|
}
|
|
doctor := mcpCall(t, cs, "doctor", nil, true)
|
|
var checks []struct{ Name, Status, Detail string }
|
|
mcpData(t, doctor, &checks)
|
|
if doctor.ExitCode == 0 || len(checks) != 1 || checks[0].Name != "identity" || checks[0].Status != "fail" {
|
|
t.Fatalf("lost failed diagnostics: %+v", doctor)
|
|
}
|
|
mcpCall(t, cs, "conflicts", nil, false)
|
|
mcpCall(t, cs, "history", map[string]any{"share": "demo"}, true)
|
|
if mode.count == 5 {
|
|
for _, name := range []string{"pause", "resume", "publish", "mount", "restore", "deploy", "unmount"} {
|
|
_, err := cs.CallTool(t.Context(), &mcp.CallToolParams{Name: "devbox_" + name, Arguments: map[string]any{}})
|
|
if err == nil {
|
|
t.Fatalf("disabled tool callable: %s", name)
|
|
}
|
|
}
|
|
}
|
|
// A command error must leave stdout readable as protocol traffic.
|
|
mcpCall(t, cs, "status", nil, false)
|
|
})
|
|
}
|
|
for _, flags := range [][]string{{"--allow-destructive"}, {"--command-timeout=0s"}, {"--command-timeout=-1s"}} {
|
|
cmd := exec.Command(binary, append([]string{"mcp"}, flags...)...)
|
|
cmd.Env = mcpTestEnv(t.TempDir())
|
|
var stdout, stderr bytes.Buffer
|
|
cmd.Stdout = &stdout
|
|
cmd.Stderr = &stderr
|
|
if err := cmd.Run(); err == nil || stdout.Len() != 0 || stderr.Len() == 0 {
|
|
t.Fatalf("invalid flags accepted or stdout polluted: %v", flags)
|
|
}
|
|
}
|
|
})
|
|
t.Run("input-validation", func(t *testing.T) {
|
|
cs := mcpTestClient(t, binary, t.TempDir(), "--allow-writes", "--allow-destructive")
|
|
for _, tc := range []struct {
|
|
name string
|
|
args any
|
|
}{
|
|
{"status", map[string]any{"command": "whoami"}},
|
|
{"conflicts", map[string]any{"rm": true}},
|
|
{"history", map[string]any{"share": "--help"}},
|
|
{"history", map[string]any{"share": "demo; touch /tmp/unwanted"}},
|
|
{"history", map[string]any{"share": "demo", "limit": 0}},
|
|
{"history", map[string]any{"share": "demo", "limit": 101}},
|
|
{"history", map[string]any{"share": "demo", "limit": 1.5}},
|
|
{"history", map[string]any{"share": "demo", "limit": nil}},
|
|
{"history", map[string]any{}},
|
|
{"history", map[string]any{"share": "demo/sub"}},
|
|
{"mount", map[string]any{"share": "demo/../escape", "local_dir": t.TempDir()}},
|
|
{"mount", map[string]any{"share": "demo", "local_dir": "--help"}},
|
|
{"mount", map[string]any{"share": "demo", "local_dir": t.TempDir(), "read_only": "true"}},
|
|
{"mount", map[string]any{"share": "demo", "local_dir": t.TempDir(), "exclude": []string{"x\n--help"}}},
|
|
{"publish", map[string]any{"share": "demo", "local_dir": "relative"}},
|
|
{"pause", map[string]any{"duration": "-1s"}},
|
|
{"pause", map[string]any{"duration": "1s --help"}},
|
|
{"restore", map[string]any{"share": "demo", "snapshot": "--help"}},
|
|
{"restore", map[string]any{"share": "demo", "snapshot": strings.Repeat("a", 64), "path": "../escape"}},
|
|
{"deploy", map[string]any{"share": "demo", "snapshot": strings.Repeat("a", 64), "path": "file"}},
|
|
{"unmount", map[string]any{"share": "demo\x00evil"}},
|
|
} {
|
|
r := mcpCall(t, cs, tc.name, tc.args, true)
|
|
if r.ExitCode != -1 || r.Stdout != "" || r.Stderr != "" {
|
|
t.Fatalf("invalid input reached child: %s %+v", tc.name, r)
|
|
}
|
|
}
|
|
mcpCall(t, cs, "status", nil, false)
|
|
})
|
|
t.Run("actual-isolated-hub", func(t *testing.T) { mcpTestHub(t, binary) })
|
|
t.Run("cancellation-and-timeout", func(t *testing.T) { mcpTestCancellation(t, binary) })
|
|
t.Run("output-cap", func(t *testing.T) {
|
|
cfg := t.TempDir()
|
|
dir := filepath.Join(cfg, "devbox")
|
|
if _, err := identity.LoadOrCreate(dir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
d := config.Daemon{Hub: "http://127.0.0.1:1", Bearer: "fixture-secret-must-not-appear"}
|
|
for i := 0; i < 10000; i++ {
|
|
d.Mounts = append(d.Mounts, config.Mount{Share: fmt.Sprintf("share%d", i), Local: "/unused/" + strings.Repeat("x", 128)})
|
|
}
|
|
if err := config.SaveDaemon(dir, d); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cs := mcpTestClient(t, binary, cfg)
|
|
r := mcpCall(t, cs, "status", nil, false)
|
|
if !r.Truncated || len(r.Stdout) != mcpOutputLimit || r.Data != nil {
|
|
t.Fatalf("cap not enforced: bytes=%d, truncated=%v", len(r.Stdout), r.Truncated)
|
|
}
|
|
if strings.Contains(r.Stdout, d.Bearer) {
|
|
t.Fatal("bearer leaked")
|
|
}
|
|
mcpCall(t, cs, "history", map[string]any{"share": "demo", "limit": 0}, true)
|
|
})
|
|
}
|
|
|
|
func mcpTestEnv(cfg string) []string {
|
|
env := []string{}
|
|
for _, v := range os.Environ() {
|
|
if !strings.HasPrefix(v, "XDG_CONFIG_HOME=") && !strings.HasPrefix(v, "GORACE=") {
|
|
env = append(env, v)
|
|
}
|
|
}
|
|
return append(env, "XDG_CONFIG_HOME="+cfg, "GORACE=atexit_sleep_ms=0")
|
|
}
|
|
|
|
func mcpTestClient(t *testing.T, binary, cfg string, flags ...string) *mcp.ClientSession {
|
|
t.Helper()
|
|
cmd := exec.Command(binary, append([]string{"mcp"}, flags...)...)
|
|
cmd.Env = mcpTestEnv(cfg)
|
|
var stderr bytes.Buffer
|
|
cmd.Stderr = &stderr
|
|
client := mcp.NewClient(&mcp.Implementation{Name: "devbox-mcp-test", Version: "1"}, nil)
|
|
cs, err := client.Connect(t.Context(), &mcp.CommandTransport{Command: cmd}, nil)
|
|
if err != nil {
|
|
t.Fatalf("stdio initialize: %v; stderr: %s", err, stderr.String())
|
|
}
|
|
t.Cleanup(func() {
|
|
if err := cs.Close(); err != nil {
|
|
t.Errorf("stdio close: %v", err)
|
|
}
|
|
if stderr.Len() != 0 {
|
|
t.Errorf("unexpected server stderr: %s", stderr.String())
|
|
}
|
|
})
|
|
return cs
|
|
}
|
|
|
|
func mcpCall(t *testing.T, cs *mcp.ClientSession, name string, args any, wantError bool) mcpCommandResult {
|
|
t.Helper()
|
|
ctx, cancel := context.WithTimeout(t.Context(), 20*time.Second)
|
|
defer cancel()
|
|
r, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "devbox_" + name, Arguments: args})
|
|
if err != nil {
|
|
t.Fatalf("%s protocol call: %v", name, err)
|
|
}
|
|
if r.IsError != wantError {
|
|
t.Fatalf("%s isError=%v, want %v: %+v", name, r.IsError, wantError, r.Content)
|
|
}
|
|
raw, err := json.Marshal(r.StructuredContent)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var result mcpCommandResult
|
|
if err := json.Unmarshal(raw, &result); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if len(r.Content) != 1 || r.Content[0].(*mcp.TextContent).Text == "" {
|
|
t.Fatalf("missing readable result: %s", name)
|
|
}
|
|
var text mcpCommandResult
|
|
if err := json.Unmarshal([]byte(r.Content[0].(*mcp.TextContent).Text), &text); err != nil || text.Stdout != result.Stdout || text.Error != result.Error {
|
|
t.Fatalf("text/structured mismatch: %s", name)
|
|
}
|
|
return result
|
|
}
|
|
|
|
func mcpData(t *testing.T, r mcpCommandResult, dst any) {
|
|
t.Helper()
|
|
b, err := json.Marshal(r.Data)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := json.Unmarshal(b, dst); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
|
|
func mcpTestHub(t *testing.T, binary string) {
|
|
db, err := meta.Open(filepath.Join(t.TempDir(), "hub.db"))
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer db.Close()
|
|
store, err := blobstore.NewDisk(t.TempDir())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
server := httptest.NewServer(hub.NewServer(db, store).Handler())
|
|
defer server.Close()
|
|
cfg := t.TempDir()
|
|
dir := filepath.Join(cfg, "devbox")
|
|
if err := db.CreateToken(hub.HashToken("isolated-mcp-fixture"), time.Now().Add(time.Hour).Unix()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
joined, err := joinHub(dir, server.URL, "isolated-mcp-fixture")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cs := mcpTestClient(t, binary, cfg, "--allow-writes", "--allow-destructive")
|
|
inspection := mcpTestClient(t, binary, cfg)
|
|
src := t.TempDir()
|
|
content := "MCP fixture first version\n"
|
|
if err := os.WriteFile(filepath.Join(src, "hello.txt"), []byte(content), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mcpCall(t, cs, "publish", map[string]any{"share": "fixture", "local_dir": src}, false)
|
|
client := transport.New(server.URL)
|
|
client.SetBearer(joined.Bearer)
|
|
initial, err := client.Log("fixture")
|
|
if err != nil || len(initial) != 1 {
|
|
t.Fatalf("initial snapshot: %v", err)
|
|
}
|
|
// A second enrolled device exercises actual two-way mount and creates history
|
|
// without racing any daemon or touching the worker's own configuration.
|
|
cfg2 := t.TempDir()
|
|
dir2 := filepath.Join(cfg2, "devbox")
|
|
if err := db.CreateToken(hub.HashToken("second-mcp-fixture"), time.Now().Add(time.Hour).Unix()); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if _, err := joinHub(dir2, server.URL, "second-mcp-fixture"); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
cs2 := mcpTestClient(t, binary, cfg2, "--allow-writes")
|
|
// Shell syntax is a literal directory name; never interpreted or expanded.
|
|
dst := filepath.Join(t.TempDir(), "literal $(echo injected); --help")
|
|
mcpCall(t, cs2, "mount", map[string]any{"share": "fixture", "local_dir": dst, "exclude": []string{"--ro"}}, false)
|
|
got, err := os.ReadFile(filepath.Join(dst, "hello.txt"))
|
|
if err != nil || string(got) != content {
|
|
t.Fatal("mount did not download fixture")
|
|
}
|
|
if err := os.WriteFile(filepath.Join(dst, "hello.txt"), []byte("second version\n"), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mcpCall(t, cs2, "mount", map[string]any{"share": "fixture", "local_dir": dst}, false)
|
|
// Multiple distinct versions prove default and explicit history limits.
|
|
ig, err := syncer.LoadIgnoreWith(dst, nil)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
for i := 0; i < 22; i++ {
|
|
if err := os.WriteFile(filepath.Join(dst, "hello.txt"), []byte(fmt.Sprintf("version %d\n", i)), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
head, err := client.Head("fixture")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := pushFixture(client, dst, ig, head); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
}
|
|
history := mcpCall(t, inspection, "history", map[string]any{"share": "fixture"}, false)
|
|
var snaps []proto.SnapshotInfo
|
|
mcpData(t, history, &snaps)
|
|
if len(snaps) != 20 {
|
|
t.Fatalf("default limit=%d", len(snaps))
|
|
}
|
|
latest := snaps[0].ID
|
|
history = mcpCall(t, inspection, "history", map[string]any{"share": "fixture", "limit": 1}, false)
|
|
mcpData(t, history, &snaps)
|
|
if len(snaps) != 1 || snaps[0].ID != latest {
|
|
t.Fatal("limit/order mismatch")
|
|
}
|
|
mcpCall(t, inspection, "members", map[string]any{"share": "fixture"}, false)
|
|
mcpCall(t, cs, "mount", map[string]any{"share": "fixture", "local_dir": src, "read_only": true}, false)
|
|
mcpCall(t, cs, "deploy", map[string]any{"share": "fixture", "snapshot": initial[0].ID}, false)
|
|
got, err = os.ReadFile(filepath.Join(src, "hello.txt"))
|
|
if err != nil || string(got) != content {
|
|
t.Fatal("deploy did not restore original file")
|
|
}
|
|
d, err := config.LoadDaemon(dir)
|
|
if err != nil || len(d.Mounts) != 1 || !d.Mounts[0].Pinned {
|
|
t.Fatal("deploy pin missing")
|
|
}
|
|
head, err := client.Head("fixture")
|
|
if err != nil || head != latest {
|
|
t.Fatal("deploy changed hub head")
|
|
}
|
|
// Restore requires a read-write mount, so re-mount the second device to pick
|
|
// up the latest head, then opt that MCP process into destructive operations.
|
|
cs2destructive := mcpTestClient(t, binary, cfg2, "--allow-writes", "--allow-destructive")
|
|
mcpCall(t, cs2, "mount", map[string]any{"share": "fixture", "local_dir": dst}, false)
|
|
mcpCall(t, cs2destructive, "restore", map[string]any{"share": "fixture", "snapshot": initial[0].ID, "path": "hello.txt"}, false)
|
|
got, err = os.ReadFile(filepath.Join(dst, "hello.txt"))
|
|
if err != nil || string(got) != content {
|
|
t.Fatal("restore did not restore original file")
|
|
}
|
|
head, err = client.Head("fixture")
|
|
if err != nil || head == latest {
|
|
t.Fatal("restore did not publish new head")
|
|
}
|
|
if err := os.WriteFile(filepath.Join(src, "hello.conflict-fixture-1.txt"), []byte("conflict"), 0600); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
conflicts := mcpCall(t, inspection, "conflicts", nil, false)
|
|
var copies []struct{ Share, Path string }
|
|
mcpData(t, conflicts, &copies)
|
|
if len(copies) != 1 || copies[0].Share != "fixture" {
|
|
t.Fatal("conflict missing")
|
|
}
|
|
// A real control server and daemon instance prove pause/resume IPC without
|
|
// starting a watcher or syncing background data on the shared host.
|
|
if runtime.GOOS != "windows" {
|
|
dmn, err := daemon.New(dir, d, "mcp-fixture", func(string, ...any) {})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
controlCtx, stop := context.WithCancel(t.Context())
|
|
defer stop()
|
|
if _, err := control.Serve(controlCtx, dir, dmn, nil); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
mcpCall(t, cs, "pause", map[string]any{"duration": "1h"}, false)
|
|
status := mcpCall(t, inspection, "status", nil, false)
|
|
var st statusJSON
|
|
mcpData(t, status, &st)
|
|
if !st.Live || !st.Paused {
|
|
t.Fatal("pause not reflected in live status")
|
|
}
|
|
mcpCall(t, cs, "resume", nil, false)
|
|
if dmn.StateSnapshot().Paused {
|
|
t.Fatal("resume did not clear pause")
|
|
}
|
|
}
|
|
mcpCall(t, cs, "unmount", map[string]any{"share": "fixture"}, false)
|
|
if _, err := os.Stat(filepath.Join(src, "hello.txt")); err != nil {
|
|
t.Fatal("unmount removed files")
|
|
}
|
|
d, err = config.LoadDaemon(dir)
|
|
if err != nil || len(d.Mounts) != 0 {
|
|
t.Fatal("unmount retained mount")
|
|
}
|
|
// Inspect result envelopes, including failed commands, for private material.
|
|
for _, result := range []mcpCommandResult{history, conflicts, mcpCall(t, inspection, "doctor", nil, false)} {
|
|
b, _ := json.Marshal(result)
|
|
if strings.Contains(string(b), joined.Bearer) || strings.Contains(string(b), "DEVBOX PRIVATE KEY") {
|
|
t.Fatal("private material in MCP result")
|
|
}
|
|
}
|
|
}
|
|
|
|
func pushFixture(c *transport.Client, dir string, ig *ignore.Matcher, head string) error {
|
|
guard, err := secret.New(nil)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
result, err := syncer.Push(c, dir, "fixture", "", ig, guard, head, nil)
|
|
if err == nil && result.Conflict {
|
|
return fmt.Errorf("fixture push unexpectedly conflicted")
|
|
}
|
|
return err
|
|
}
|
|
|
|
func mcpTestCancellation(t *testing.T, binary string) {
|
|
for _, kind := range []string{"cancel", "timeout"} {
|
|
t.Run(kind, func(t *testing.T) {
|
|
started, ended := make(chan struct{}), make(chan struct{})
|
|
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
if r.URL.Path != proto.PathLog {
|
|
http.NotFound(w, r)
|
|
return
|
|
}
|
|
close(started)
|
|
<-r.Context().Done()
|
|
close(ended)
|
|
}))
|
|
defer func() { server.CloseClientConnections(); server.Close() }()
|
|
cfg := t.TempDir()
|
|
dir := filepath.Join(cfg, "devbox")
|
|
if _, err := identity.LoadOrCreate(dir); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := config.SaveDaemon(dir, config.Daemon{Hub: server.URL, Bearer: "isolated-fake-bearer"}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
flags := []string{}
|
|
if kind == "timeout" {
|
|
flags = append(flags, "--command-timeout=750ms")
|
|
}
|
|
cs := mcpTestClient(t, binary, cfg, flags...)
|
|
ctx, cancel := context.WithCancel(t.Context())
|
|
defer cancel()
|
|
type response struct {
|
|
r *mcp.CallToolResult
|
|
err error
|
|
}
|
|
done := make(chan response, 1)
|
|
go func() {
|
|
r, err := cs.CallTool(ctx, &mcp.CallToolParams{Name: "devbox_history", Arguments: map[string]any{"share": "demo"}})
|
|
done <- response{r, err}
|
|
}()
|
|
select {
|
|
case <-started:
|
|
case <-time.After(10 * time.Second):
|
|
t.Fatal("child did not reach HTTP request")
|
|
}
|
|
if kind == "cancel" {
|
|
cancel()
|
|
}
|
|
select {
|
|
case <-ended:
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("cancellation did not terminate child HTTP connection")
|
|
}
|
|
select {
|
|
case got := <-done:
|
|
if kind == "timeout" {
|
|
if got.err != nil || got.r == nil || !got.r.IsError {
|
|
t.Fatalf("timeout lost tool error: %v", got.err)
|
|
}
|
|
b, _ := json.Marshal(got.r.StructuredContent)
|
|
if !strings.Contains(string(b), "context deadline exceeded") || !strings.Contains(string(b), "not rolled back") {
|
|
t.Fatal("missing timeout/retry explanation")
|
|
}
|
|
} else if got.err == nil && (got.r == nil || !got.r.IsError) {
|
|
t.Fatal("cancelled command reported success")
|
|
}
|
|
case <-time.After(5 * time.Second):
|
|
t.Fatal("call did not finish after cancellation")
|
|
}
|
|
// Completion and a subsequent call prove the gate/stdio session survives.
|
|
mcpCall(t, cs, "status", nil, false)
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestMCPCapture(t *testing.T) {
|
|
for _, limit := range []int{0, 1, 10} {
|
|
b := &mcpCapture{limit: limit}
|
|
for i := 0; i < 3; i++ {
|
|
if n, err := b.Write([]byte("0123456789")); err != nil || n != 10 {
|
|
t.Fatal("writer must drain all bytes")
|
|
}
|
|
}
|
|
if b.buffer.Len() != limit || !b.truncated {
|
|
t.Fatal("capture exceeded bound")
|
|
}
|
|
}
|
|
}
|
|
|
|
// This subprocess exercises both pipe-draining paths and nonzero exit handling;
|
|
// the stdio suite separately exercises the stdout cap on the actual CLI binary.
|
|
func TestMCPCommandCapture(t *testing.T) {
|
|
t.Setenv("DEVBOX_MCP_COMMAND_FIXTURE", "1")
|
|
executable, err := os.Executable()
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second)
|
|
defer cancel()
|
|
got := runMCPCommand(ctx, executable, []string{"-test.run=^TestMCPCommandFixture$", "--"})
|
|
if got.ExitCode != 7 || got.Error == "" || !got.Truncated || len(got.Stdout) != mcpOutputLimit || len(got.Stderr) != mcpStderrLimit || got.Data != nil {
|
|
t.Fatalf("capture failed: exit=%d, error=%q, trunc=%v, stdout=%d, stderr=%d", got.ExitCode, got.Error, got.Truncated, len(got.Stdout), len(got.Stderr))
|
|
}
|
|
}
|
|
|
|
func TestMCPCommandFixture(t *testing.T) {
|
|
if os.Getenv("DEVBOX_MCP_COMMAND_FIXTURE") != "1" {
|
|
return
|
|
}
|
|
_, _ = os.Stdout.Write(bytes.Repeat([]byte("x"), mcpOutputLimit+4096))
|
|
_, _ = os.Stderr.Write(bytes.Repeat([]byte("y"), mcpStderrLimit+4096))
|
|
os.Exit(7)
|
|
}
|