diff --git a/pkgs/mcpx/internal/config/config.go b/pkgs/mcpx/internal/config/config.go index 47f4089203..cc369fe107 100644 --- a/pkgs/mcpx/internal/config/config.go +++ b/pkgs/mcpx/internal/config/config.go @@ -110,9 +110,15 @@ type Extras struct { // Supervised runs a stdio server under a per-server supervisor // process (#1385, Phase 1 of #1384): the supervisor owns the child's // pipes for the child's whole life and daemons attach to it, so the - // child survives a daemon restart. Default false - the direct spawn - // path is unchanged. - Supervised bool `json:"supervised,omitempty"` + // child survives a daemon restart. Since Phase 3 (#9963) supervised + // is the default for stdio servers in any config loaded from a + // file: parse materializes true when the key is absent, an explicit + // false opts the server back into the legacy direct-spawn path, + // and an explicit true is the Phase 1 opt-in, unchanged. A nil here + // means no file load has defaulted it (a programmatically built + // config) and reads as not supervised. Read it through + // SupervisedEnabled, never directly. + Supervised *bool `json:"supervised,omitempty"` // Logging overrides the global settings for records about this server, so // a single misbehaving server can be made verbose without drowning in the // rest. Nested rather than flat, because "logging.level" reads as one @@ -198,6 +204,16 @@ type Extras struct { Preconditions map[string]Precondition `json:"preconditions,omitempty"` } +// SupervisedEnabled reports whether this server's resolved config +// runs its stdio child under a supervisor: the explicit value, with +// the Phase 3 default (true) already materialized by parse for +// file-loaded configs (#9963). Nil Extras or a nil field (a config +// built in code, never parsed from a file) reads as false, the +// Phase 1 behaviour. +func (e *Extras) SupervisedEnabled() bool { + return e != nil && e.Supervised != nil && *e.Supervised +} + // ToolView is one declared view of a tool (#1933 slices 1-3). A view // is either a renamed view of an aliased server's tool (From), a // script-backed tool that runs a declared local command (Command), or @@ -864,6 +880,20 @@ func (c *Config) Resolve(name string) (*Resolved, error) { merged.Name = name merged.AliasOf = s.AliasOf merged.Mcpx = s.Mcpx + // Only the supervised bit is inherited from the target: an + // alias is a view of the target's process, so how that + // process is spawned follows the target, but the rest of the + // alias's extras are its own view (hiding is per view, and + // the target's excludeTools must not leak into the alias). + if target.Mcpx != nil && target.Mcpx.Supervised != nil { + if merged.Mcpx == nil { + merged.Mcpx = &Extras{Supervised: target.Mcpx.Supervised} + } else if merged.Mcpx.Supervised == nil { + cp := *merged.Mcpx + cp.Supervised = target.Mcpx.Supervised + merged.Mcpx = &cp + } + } s = &merged } // A per-server protocol overrides upstream.protocol, so it is read @@ -1485,6 +1515,9 @@ func mergeExtras(near, far Extras) Extras { // survive into the nearer config, and a key both files use // composes with allOf rather than being replaced. near.ArgumentRules = mergeArgumentRules(near.ArgumentRules, far.ArgumentRules) + if near.Supervised == nil { + near.Supervised = far.Supervised + } return near } @@ -1555,6 +1588,20 @@ func parse(b []byte) (*Config, error) { if s.URL != "" && s.Transport == "" { s.Transport = "http" } + // Phase 3 of #1384 (#9963): supervised stdio is the default. + // Materialize it here, at file load, so every consumer of a + // parsed config (daemon, CLI, settings views) sees the same + // resolved value and an explicit "supervised": false remains + // the one opt-out into the legacy direct-spawn path. + if s.Command != "" { + if s.Mcpx == nil { + s.Mcpx = &Extras{} + } + if s.Mcpx.Supervised == nil { + tr := true + s.Mcpx.Supervised = &tr + } + } } return c, nil } diff --git a/pkgs/mcpx/internal/config/supervised_default_test.go b/pkgs/mcpx/internal/config/supervised_default_test.go new file mode 100644 index 0000000000..b7fb62c7b3 --- /dev/null +++ b/pkgs/mcpx/internal/config/supervised_default_test.go @@ -0,0 +1,45 @@ +package config_test + +import ( + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/config" +) + +// Phase 3 of #1384 (#9963): a config loaded from a file defaults its +// stdio servers to supervised; "supervised": false is the opt-out +// into the legacy direct-spawn path, and HTTP servers are untouched. +func TestSupervisedDefaultsOnForStdioFromFile(t *testing.T) { + dir := t.TempDir() + p := write(t, dir, "c.json", `{ + "mcpServers": { + "plain": { "command": "x" }, + "optout": { "command": "x", "mcpx": { "supervised": false } }, + "optin": { "command": "x", "mcpx": { "supervised": true } }, + "web": { "url": "https://example.com/mcp" } + } + }`) + c, err := config.Load(p) + if err != nil { + t.Fatal(err) + } + if !c.MCPServers["plain"].Mcpx.SupervisedEnabled() { + t.Fatal("a stdio server with no supervised key should default to supervised after a file load") + } + if c.MCPServers["optout"].Mcpx.SupervisedEnabled() { + t.Fatal("supervised:false should opt out of the default") + } + if !c.MCPServers["optin"].Mcpx.SupervisedEnabled() { + t.Fatal("supervised:true should stay supervised") + } + if c.MCPServers["web"].Mcpx != nil && c.MCPServers["web"].Mcpx.SupervisedEnabled() { + t.Fatal("an HTTP server should not be defaulted to supervised") + } + r, err := c.Resolve("plain") + if err != nil { + t.Fatal(err) + } + if !r.Mcpx.SupervisedEnabled() { + t.Fatal("the resolved config should carry the supervised default to the pool") + } +} diff --git a/pkgs/mcpx/internal/daemon/main_test.go b/pkgs/mcpx/internal/daemon/main_test.go index 689cdda350..5aefa91478 100644 --- a/pkgs/mcpx/internal/daemon/main_test.go +++ b/pkgs/mcpx/internal/daemon/main_test.go @@ -12,5 +12,6 @@ import ( // removed when the run ends; a process still executing from one of them // fails the run. func TestMain(m *testing.M) { + testsupport.SuperviseReExec() os.Exit(testsupport.MainWithSweep(m)) } diff --git a/pkgs/mcpx/internal/daemon/registry_handoff.go b/pkgs/mcpx/internal/daemon/registry_handoff.go index 9ab3eac721..355422eab2 100644 --- a/pkgs/mcpx/internal/daemon/registry_handoff.go +++ b/pkgs/mcpx/internal/daemon/registry_handoff.go @@ -7,6 +7,7 @@ import ( "time" "github.com/developing-today/code/pkgs/mcpx/internal/defaults" + "github.com/developing-today/code/pkgs/mcpx/internal/mcpclient" "github.com/developing-today/code/pkgs/mcpx/internal/pool" ) @@ -213,3 +214,21 @@ func (r *Registry) AdoptSupervised(ctx context.Context) { p.AdoptRunningSupervised(ctx) } } + +// ReapOrphanedSupervisors runs the reap half of the #9963 +// adopt-or-reap scan at daemon startup: a supervisor socket no +// configured supervised server maps to belongs to a server that +// left the config (or opted out), so its supervisor and child are +// terminated and the reap logged; a socket whose supervisor refuses +// (a daemon attached, a protocol-version mismatch) and stale socket +// files are logged and left or removed accordingly. See +// mcpclient.ScanSupervisorSockets. +func (r *Registry) ReapOrphanedSupervisors() { + var configured []string + for _, name := range r.Names() { + if v, ok := r.View(name); ok && v.Stdio() && v.Mcpx.SupervisedEnabled() { + configured = append(configured, name) + } + } + mcpclient.ScanSupervisorSockets(mcpclient.StateDir(), configured, r.logf) +} diff --git a/pkgs/mcpx/internal/daemon/server.go b/pkgs/mcpx/internal/daemon/server.go index d0aa75a832..56d6630227 100644 --- a/pkgs/mcpx/internal/daemon/server.go +++ b/pkgs/mcpx/internal/daemon/server.go @@ -397,6 +397,9 @@ func (s *Server) Listen(tcpPort int) error { // Adopt supervised instances a previous daemon left running // (#9962): their supervisors outlive the daemon by design. s.reg.AdoptSupervised(context.Background()) + // Reap the supervisors no configured server claims anymore + // (#9963, the other half of the adopt-or-reap scan). + s.reg.ReapOrphanedSupervisors() return s.publish() } diff --git a/pkgs/mcpx/internal/mcpclient/supervised.go b/pkgs/mcpx/internal/mcpclient/supervised.go index 94296fd3e5..fd9e238d92 100644 --- a/pkgs/mcpx/internal/mcpclient/supervised.go +++ b/pkgs/mcpx/internal/mcpclient/supervised.go @@ -117,6 +117,12 @@ func (w *connWriter) closeAfterFlush() { type supervisorHandshake struct { Version int `json:"version"` + // Action is "" or "attach" for the ordinary attach handshake. + // "restart" asks the supervisor to restart its child first and + // then attach the requester to the new child; "terminate" asks + // it to kill the child and exit (the reap half of the #9963 + // adopt-or-reap scan) and is answered without attaching. + Action string `json:"action,omitempty"` } type supervisorReply struct { @@ -230,6 +236,12 @@ type supervisor struct { attached *connWriter attachedEver bool reported bool + // generation increments on every supervisor-side child restart + // (#9963): the per-child watcher goroutines capture their + // generation and a stale generation's finishWhenDone returns + // without closing the listener, because the supervisor lives on + // with the new child. + generation int buf *tailBuffer exited bool exitErr error @@ -284,17 +296,7 @@ func RunSupervisor(opts SupervisorOptions) error { return err } s.ln = ln - go s.pumpStdout() - go func() { - err := s.child.Wait() - s.mu.Lock() - s.exitErr = err - s.exited = true - s.mu.Unlock() - s.signal() - close(s.waitDone) - }() - go s.finishWhenDone() + s.launchWatchers(0, s.pumpDone, s.waitDone) for { conn, err := ln.Accept() @@ -308,6 +310,29 @@ func RunSupervisor(opts SupervisorOptions) error { } } +// launchWatchers starts the per-child goroutines for one child +// generation: the stdout pump, the wait reporter, and the finisher. +// They take their channels and generation as parameters so a +// supervisor-side restart (#9963) can launch a fresh set for the new +// child while the old set is still draining. +func (s *supervisor) launchWatchers(gen int, pumpDone, waitDone chan struct{}) { + child := s.child + outR := s.stdoutR + go s.pumpStdout(outR, pumpDone) + go func() { + err := child.Wait() + s.mu.Lock() + if gen == s.generation { + s.exitErr = err + s.exited = true + } + s.mu.Unlock() + s.signal() + close(waitDone) + }() + go s.finishWhenDone(gen, pumpDone, waitDone) +} + // spawnChild mirrors NewStdio's process semantics: own process group, // plain os.Pipes, stderr into a 64 KiB ring. func (s *supervisor) spawnChild() error { @@ -383,11 +408,11 @@ func (s *supervisor) spawnChild() error { // deadline, so a stalled daemon can block this pump for at most // AttachedWriteTimeout — never the supervisor's state, and never // forever. -func (s *supervisor) pumpStdout() { - defer close(s.pumpDone) +func (s *supervisor) pumpStdout(outR *os.File, pumpDone chan struct{}) { + defer close(pumpDone) chunk := make([]byte, 32<<10) for { - n, err := s.stdoutR.Read(chunk) + n, err := outR.Read(chunk) if n > 0 { data := chunk[:n] // The unattached decision and the tail-buffer append @@ -488,6 +513,24 @@ func (s *supervisor) handleAttach(conn net.Conn) { _ = conn.Close() return } + switch hs.Action { + case "", "attach": + // The ordinary path, below. + case "terminate": + s.handleTerminate(conn) + return + case "restart": + if err := s.restartChild(); err != nil { + _ = writeReply(conn, supervisorReply{Error: "restart: " + err.Error()}) + _ = conn.Close() + return + } + // Fall through: the requester attaches to the new child. + default: + _ = writeReply(conn, supervisorReply{Error: "unknown supervisor action " + hs.Action}) + _ = conn.Close() + return + } s.mu.Lock() if s.attached != nil { @@ -551,6 +594,104 @@ func (s *supervisor) handleAttach(conn net.Conn) { }() } +// handleTerminate answers a terminate handshake (#9963): it refuses +// while a daemon is attached (that supervisor is in use, not an +// orphan), otherwise it replies, then kills the child and closes the +// listener so RunSupervisor returns and removes the socket. It is +// the reap mechanism of the adopt-or-reap scan: the scan only sends +// it to supervisors no configured server maps to. +func (s *supervisor) handleTerminate(conn net.Conn) { + s.mu.Lock() + attached := s.attached != nil + pid := 0 + if s.child != nil && s.child.Process != nil { + pid = s.child.Process.Pid + } + s.mu.Unlock() + if attached { + _ = writeReply(conn, supervisorReply{Error: "supervisor in use: a daemon is attached"}) + _ = conn.Close() + return + } + _ = writeReply(conn, supervisorReply{Version: SupervisorProtocolVersion, PID: pid}) + _ = conn.Close() + go func() { + s.mu.Lock() + waitDone := s.waitDone + s.mu.Unlock() + s.killChild(syscall.SIGTERM, 2*time.Second, waitDone) + if s.ln != nil { + _ = s.ln.Close() + } + }() +} + +// killChild signals the current child's process group and escalates +// to SIGKILL if the child has not exited within grace. waitDone is +// the channel the child's wait goroutine closes — passed explicitly +// because a restart replaces the struct's channels before it kills +// the old child. +func (s *supervisor) killChild(sig syscall.Signal, grace time.Duration, waitDone chan struct{}) { + s.mu.Lock() + child := s.child + exited := s.exited + s.mu.Unlock() + if child == nil || child.Process == nil || exited { + return + } + _ = syscall.Kill(-child.Process.Pid, sig) + select { + case <-waitDone: + case <-time.After(grace): + _ = syscall.Kill(-child.Process.Pid, syscall.SIGKILL) + <-waitDone + } +} + +// restartChild replaces the supervisor's child with a fresh spawn of +// the same command (#9963): `mcpx restart` operates through the +// supervisor, so the supervisor — not the daemon — owns the restart, +// and the socket, the state directory entry, and the supervisor +// process itself all survive it. It refuses while a daemon is +// attached (the pool detaches first, as it does for any restart). +// A child that already exited is simply revived. +func (s *supervisor) restartChild() error { + s.mu.Lock() + if s.attached != nil { + s.mu.Unlock() + return errors.New("already attached") + } + oldStdin := s.stdin + oldPumpDone := s.pumpDone + oldWaitDone := s.waitDone + s.generation++ + gen := s.generation + s.exited = false + s.exitErr = nil + s.reported = false + s.pumpDone = make(chan struct{}) + s.waitDone = make(chan struct{}) + pumpDone, waitDone := s.pumpDone, s.waitDone + s.mu.Unlock() + + s.killChild(syscall.SIGTERM, 2*time.Second, oldWaitDone) + // The old pump exits once the dead child's stdout closes; bound + // the wait so a wedged pump cannot wedge the restart. + select { + case <-oldPumpDone: + case <-time.After(2 * time.Second): + } + if oldStdin != nil { + _ = oldStdin.Close() + } + s.buf.Drain() + if err := s.spawnChild(); err != nil { + return err + } + s.launchWatchers(gen, pumpDone, waitDone) + return nil +} + func (s *supervisor) detach(w *connWriter) { s.mu.Lock() if s.attached == w { @@ -585,9 +726,18 @@ func writeReply(conn net.Conn, reply supervisorReply) error { // the supervisor waits a bounded grace for that first, reporting // attach; with nobody attached after that there is nobody to report // to, so it exits (no lingering supervisors for dead children). -func (s *supervisor) finishWhenDone() { - <-s.waitDone - <-s.pumpDone +func (s *supervisor) finishWhenDone(gen int, pumpDone, waitDone chan struct{}) { + <-waitDone + <-pumpDone + s.mu.Lock() + if gen != s.generation { + // A supervisor-side restart replaced this child (#9963): + // the supervisor lives on with the new generation, so this + // finisher must not close the listener or the socket. + s.mu.Unlock() + return + } + s.mu.Unlock() grace := time.NewTimer(10 * time.Second) defer grace.Stop() for { @@ -707,7 +857,36 @@ func AttachSupervised(opts SupervisedOptions) (*SupervisedTransport, error) { if opts.StateDir == "" { opts.StateDir = StateDir() } - return attachSupervisor(SupervisorSocketPath(opts.StateDir, opts.Name), opts) + return attachSupervisor(SupervisorSocketPath(opts.StateDir, opts.Name), opts, "") +} + +// RestartSupervised attaches to the server's supervisor and has it +// restart its child first (#9963): the returned transport speaks to +// the NEW child, whose PID differs from the previous one. It never +// spawns a supervisor — no live supervisor is an error, exactly as +// for AttachSupervised — and a supervisor with a daemon attached +// refuses, so callers detach before restarting. +func RestartSupervised(opts SupervisedOptions) (*SupervisedTransport, error) { + if opts.StateDir == "" { + opts.StateDir = StateDir() + } + return attachSupervisor(SupervisorSocketPath(opts.StateDir, opts.Name), opts, "restart") +} + +// IsSupervisorRefusal reports whether err is a live supervisor's +// explicit refusal (already attached, version mismatch, in use): +// the socket is alive, so spawning a replacement would be wrong. +func IsSupervisorRefusal(err error) bool { + var refusal *supervisorRefusal + return errors.As(err, &refusal) +} + +// IsProtocolRefusal reports whether err is a supervisor's +// protocol-version refusal — the failure #9963 requires status to +// name rather than silently work around. +func IsProtocolRefusal(err error) bool { + return IsSupervisorRefusal(err) && + strings.Contains(err.Error(), "protocol version mismatch") } // spawnFunc starts a supervisor for the socket; nil means re-exec. @@ -725,7 +904,7 @@ func newSupervised(opts SupervisedOptions, spawn spawnFunc) (*SupervisedTranspor } sock := SupervisorSocketPath(opts.StateDir, opts.Name) - tr, err := attachSupervisor(sock, opts) + tr, err := attachSupervisor(sock, opts, "") if err == nil { return tr, nil } @@ -775,7 +954,7 @@ func newSupervised(opts SupervisedOptions, spawn spawnFunc) (*SupervisedTranspor deadline := time.Now().Add(opts.SpawnTimeout) var lastErr error for time.Now().Before(deadline) { - tr, err := attachSupervisor(sock, opts) + tr, err := attachSupervisor(sock, opts, "") if err == nil { return tr, nil } @@ -785,13 +964,13 @@ func newSupervised(opts SupervisedOptions, spawn spawnFunc) (*SupervisedTranspor return nil, fmt.Errorf("supervised transport for %s: supervisor did not attach within %s: %v", opts.Name, opts.SpawnTimeout, lastErr) } -func attachSupervisor(sock string, opts SupervisedOptions) (*SupervisedTransport, error) { +func attachSupervisor(sock string, opts SupervisedOptions, action string) (*SupervisedTransport, error) { conn, err := net.DialTimeout("unix", sock, 2*time.Second) if err != nil { return nil, err } r := bufio.NewReaderSize(conn, 1<<20) - hs, _ := json.Marshal(supervisorHandshake{Version: SupervisorProtocolVersion}) + hs, _ := json.Marshal(supervisorHandshake{Version: SupervisorProtocolVersion, Action: action}) if _, err := conn.Write(append(hs, '\n')); err != nil { _ = conn.Close() return nil, err @@ -814,8 +993,9 @@ func attachSupervisor(sock string, opts SupervisedOptions) (*SupervisedTransport } if reply.Version != SupervisorProtocolVersion { _ = conn.Close() - return nil, fmt.Errorf("supervisor protocol version mismatch: supervisor sent %d, daemon speaks %d", - reply.Version, SupervisorProtocolVersion) + return nil, &supervisorRefusal{msg: fmt.Sprintf( + "supervisor protocol version mismatch: supervisor sent %d, daemon speaks %d", + reply.Version, SupervisorProtocolVersion)} } tr := &SupervisedTransport{ conn: conn, diff --git a/pkgs/mcpx/internal/mcpclient/supervised_phase3_test.go b/pkgs/mcpx/internal/mcpclient/supervised_phase3_test.go new file mode 100644 index 0000000000..9729d424d5 --- /dev/null +++ b/pkgs/mcpx/internal/mcpclient/supervised_phase3_test.go @@ -0,0 +1,274 @@ +package mcpclient_test + +import ( + "context" + "fmt" + "net" + "os" + "strings" + "syscall" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/mcpclient" +) + +// Phase 3 of #1384 (issue #9963): restart through the supervisor, +// terminate (the reap mechanism), the adopt-or-reap scan, and the +// protocol-refusal classification status relies on. + +func phase3Opts(dir, name string, child ...string) mcpclient.SupervisedOptions { + return mcpclient.SupervisedOptions{ + Name: name, + StateDir: dir, + Command: child[0], + Args: child[1:], + InheritEnv: true, + } +} + +// waitAttachFree polls until the supervisor's attach slot is free +// (a Close clears it asynchronously) and leaves the transport +// detached again. +func waitAttachFree(t *testing.T, opts mcpclient.SupervisedOptions) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for { + tr, err := mcpclient.AttachSupervised(opts) + if err == nil { + _ = tr.Close() + time.Sleep(50 * time.Millisecond) + return + } + if time.Now().After(deadline) { + t.Fatalf("attach slot never freed: %v", err) + } + time.Sleep(10 * time.Millisecond) + } +} + +func pidAlive(pid int) bool { + return pid > 0 && syscall.Kill(pid, 0) == nil +} + +func waitPIDDead(t *testing.T, pid int) { + t.Helper() + deadline := time.Now().Add(10 * time.Second) + for pidAlive(pid) { + if time.Now().After(deadline) { + t.Fatalf("pid %d still alive", pid) + } + time.Sleep(20 * time.Millisecond) + } +} + +// A restart dial has the supervisor replace its child: the new +// transport speaks to a new PID, and the supervisor (and its socket) +// survives — the daemon never respawns either. +func TestSupervisedRestartThroughSupervisor(t *testing.T) { + dir := t.TempDir() + opts := phase3Opts(dir, "echo", "cat") + sock := mcpclient.SupervisorSocketPath(dir, "echo") + + tr1, err := mcpclient.NewSupervised(opts) + if err != nil { + t.Fatalf("attach 1: %v", err) + } + pid1 := tr1.PID() + defer killChild(t, tr1) + if err := tr1.Close(); err != nil { + t.Fatalf("detach: %v", err) + } + waitAttachFree(t, opts) + + var tr2 *mcpclient.SupervisedTransport + deadline := time.Now().Add(10 * time.Second) + for { + tr2, err = mcpclient.RestartSupervised(opts) + if err == nil { + break + } + if !strings.Contains(err.Error(), "already attached") || time.Now().After(deadline) { + t.Fatalf("restart: %v", err) + } + time.Sleep(10 * time.Millisecond) + } + defer func() { _ = tr2.Close() }() + defer killChild(t, tr2) + if tr2.PID() == pid1 { + t.Fatalf("restart kept the old child pid %d", pid1) + } + waitPIDDead(t, pid1) + + ctx := context.Background() + frame := []byte(`{"jsonrpc":"2.0","id":1,"method":"ping"}`) + if err := tr2.Send(ctx, frame); err != nil { + t.Fatalf("send to restarted child: %v", err) + } + got, err := tr2.Recv() + if err != nil || string(got) != string(frame) { + t.Fatalf("recv from restarted child: %q, %v", got, err) + } + if _, err := os.Stat(sock); err != nil { + t.Fatalf("supervisor socket did not survive the restart: %v", err) + } +} + +// Terminate is the reap: the supervisor kills its child and exits, +// removing its socket. +func TestSupervisedTerminateReapsChild(t *testing.T) { + dir := t.TempDir() + opts := phase3Opts(dir, "echo", "cat") + sock := mcpclient.SupervisorSocketPath(dir, "echo") + + tr, err := mcpclient.NewSupervised(opts) + if err != nil { + t.Fatalf("attach: %v", err) + } + pid := tr.PID() + defer killChild(t, tr) + if err := tr.Close(); err != nil { + t.Fatalf("detach: %v", err) + } + waitAttachFree(t, opts) + + if err := mcpclient.TerminateSupervisorSocket(sock); err != nil { + t.Fatalf("terminate: %v", err) + } + waitPIDDead(t, pid) + deadline := time.Now().Add(10 * time.Second) + for { + if _, err := os.Stat(sock); os.IsNotExist(err) { + break + } + if time.Now().After(deadline) { + t.Fatalf("supervisor socket %s not removed after terminate", sock) + } + time.Sleep(20 * time.Millisecond) + } +} + +// The adopt-or-reap scan, both branches plus the stale file: a +// configured supervisor is left in place and remains adoptable, an +// unconfigured one is reaped (child killed, reap logged), and a +// socket file with nobody listening is removed. +func TestScanSupervisorSocketsAdoptAndReap(t *testing.T) { + dir := t.TempDir() + keptOpts := phase3Opts(dir, "kept", "cat") + orphanOpts := phase3Opts(dir, "orphan", "cat") + + keptTr, err := mcpclient.NewSupervised(keptOpts) + if err != nil { + t.Fatalf("start kept: %v", err) + } + defer killChild(t, keptTr) + orphanTr, err := mcpclient.NewSupervised(orphanOpts) + if err != nil { + t.Fatalf("start orphan: %v", err) + } + orphanPID := orphanTr.PID() + defer killChild(t, orphanTr) + _ = keptTr.Close() + _ = orphanTr.Close() + waitAttachFree(t, keptOpts) + waitAttachFree(t, orphanOpts) + + staleSock := mcpclient.SupervisorSocketPath(dir, "gone") + if err := os.WriteFile(staleSock, []byte("not a socket"), 0o600); err != nil { + t.Fatal(err) + } + + var logs []string + logf := func(format string, args ...any) { + logs = append(logs, fmt.Sprintf(format, args...)) + } + var outcomes []mcpclient.SupervisorScanOutcome + deadline := time.Now().Add(15 * time.Second) + for { + outcomes = mcpclient.ScanSupervisorSockets(dir, []string{"kept"}, logf) + byAction := map[string]string{} + for _, o := range outcomes { + byAction[o.Socket] = o.Action + } + if byAction[mcpclient.SupervisorSocketPath(dir, "orphan")] == "reaped" { + break + } + if time.Now().After(deadline) { + t.Fatalf("orphan never reaped; outcomes = %+v, logs = %v", outcomes, logs) + } + time.Sleep(50 * time.Millisecond) + } + byAction := map[string]string{} + for _, o := range outcomes { + byAction[o.Socket] = o.Action + } + if got := byAction[mcpclient.SupervisorSocketPath(dir, "kept")]; got != "configured" { + t.Fatalf("kept supervisor action = %q, want configured (outcomes %+v)", got, outcomes) + } + if got := byAction[staleSock]; got != "stale-removed" { + t.Fatalf("stale socket action = %q, want stale-removed (outcomes %+v)", got, outcomes) + } + if _, err := os.Stat(staleSock); !os.IsNotExist(err) { + t.Fatalf("stale socket still present: %v", err) + } + waitPIDDead(t, orphanPID) + joined := strings.Join(logs, "\n") + if !strings.Contains(joined, "reaped orphaned supervisor") { + t.Fatalf("reap not logged; logs = %v", logs) + } + + // The adopt branch: the configured supervisor is still there to + // be adopted by attach, with its original child. + adopted, err := mcpclient.AttachSupervised(keptOpts) + if err != nil { + t.Fatalf("adopt kept supervisor after scan: %v", err) + } + if adopted.PID() != keptTr.PID() { + t.Fatalf("adopted child pid = %d, want the kept child %d", adopted.PID(), keptTr.PID()) + } + _ = adopted.Close() + waitAttachFree(t, keptOpts) + if err := mcpclient.TerminateSupervisorSocket(mcpclient.SupervisorSocketPath(dir, "kept")); err != nil { + t.Fatalf("cleanup terminate kept: %v", err) + } +} + +// A supervisor that answers with a different protocol version +// refuses, and the refusal is classified so status can name it +// (#9963) instead of the failure looking like a dead socket. +func TestSupervisorProtocolRefusalIsClassified(t *testing.T) { + dir := t.TempDir() + sock := mcpclient.SupervisorSocketPath(dir, "future") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + defer func() { _ = ln.Close() }() + go func() { + conn, err := ln.Accept() + if err != nil { + return + } + defer func() { _ = conn.Close() }() + buf := make([]byte, 4096) + _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) + if _, err := conn.Read(buf); err != nil { + return + } + _, _ = conn.Write([]byte("{\"version\":999,\"pid\":4242}\n")) + }() + + _, err = mcpclient.AttachSupervised(phase3Opts(dir, "future", "cat")) + if err == nil { + t.Fatal("attach to a version-999 supervisor succeeded") + } + if !mcpclient.IsSupervisorRefusal(err) { + t.Fatalf("error is not a supervisor refusal: %v", err) + } + if !mcpclient.IsProtocolRefusal(err) { + t.Fatalf("error is not classified as a protocol refusal: %v", err) + } + if !strings.Contains(err.Error(), "protocol version mismatch") { + t.Fatalf("error does not name the version mismatch: %v", err) + } +} diff --git a/pkgs/mcpx/internal/mcpclient/supervised_scan.go b/pkgs/mcpx/internal/mcpclient/supervised_scan.go new file mode 100644 index 0000000000..a5b943bdbd --- /dev/null +++ b/pkgs/mcpx/internal/mcpclient/supervised_scan.go @@ -0,0 +1,137 @@ +package mcpclient + +import ( + "bufio" + "encoding/json" + "fmt" + "net" + "os" + "path/filepath" + "sort" + "strings" + "time" +) + +// Adopt-or-reap scan — Phase 3 of #1384 (issue #9963). +// +// On daemon start the state directory holds one supervisor socket +// per supervised server that has ever run. Sockets fall into three +// classes: +// +// - configured: the server is in the daemon's current config and +// supervised — the pool's adoption scan (Phase 2, #9962) attaches +// to it; the scan here leaves it alone. +// - orphaned: no configured supervised server maps to the socket — +// the server left the config (or opted out of supervision), so +// nobody will ever attach again. The scan reaps it: it asks the +// supervisor to terminate (which kills the child) and logs the +// reap. A supervisor that answers with a refusal — a daemon is +// attached, or a protocol-version mismatch — is NOT reaped: it +// is live and owned, and the refusal is logged instead. +// - stale: the socket file remains but no supervisor listens +// (dial refused). The file is removed and the removal logged. + +// SupervisorScanOutcome is one socket's scan result. +type SupervisorScanOutcome struct { + Socket string + // Action is one of: configured, reaped, stale-removed, refused, + // terminate-failed. + Action string + Detail string +} + +// ScanSupervisorSockets performs the reap/stale half of the +// adopt-or-reap scan over stateDir and returns one outcome per +// supervisor socket found, in filename order. configured lists the +// server names the daemon expects supervisors for. logf may be nil. +func ScanSupervisorSockets(stateDir string, configured []string, logf func(string, ...any)) []SupervisorScanOutcome { + if logf == nil { + logf = func(string, ...any) {} + } + expected := map[string]string{} + for _, name := range configured { + expected[SupervisorSocketPath(stateDir, name)] = name + } + matches, _ := filepath.Glob(filepath.Join(stateDir, "sup-*.sock")) + sort.Strings(matches) + var out []SupervisorScanOutcome + for _, sock := range matches { + if name, ok := expected[sock]; ok { + out = append(out, SupervisorScanOutcome{Socket: sock, Action: "configured", Detail: name}) + continue + } + err := TerminateSupervisorSocket(sock) + switch { + case err == nil: + logf("mcpx: reaped orphaned supervisor %s (server no longer configured as supervised)", sock) + out = append(out, SupervisorScanOutcome{Socket: sock, Action: "reaped"}) + case IsSupervisorRefusal(err): + logf("mcpx: orphan scan left supervisor %s in place: %v", sock, err) + out = append(out, SupervisorScanOutcome{Socket: sock, Action: "refused", Detail: err.Error()}) + case isStaleSocketErr(err): + _ = os.Remove(sock) + logf("mcpx: removed stale supervisor socket %s", sock) + out = append(out, SupervisorScanOutcome{Socket: sock, Action: "stale-removed", Detail: err.Error()}) + default: + logf("mcpx: orphan scan could not terminate supervisor %s: %v", sock, err) + out = append(out, SupervisorScanOutcome{Socket: sock, Action: "terminate-failed", Detail: err.Error()}) + } + } + return out +} + +// isStaleSocketErr reports whether err means nobody is listening on +// the socket: the file is stale and safe to remove. +func isStaleSocketErr(err error) bool { + if err == nil { + return false + } + if os.IsNotExist(err) { + return true + } + return strings.Contains(err.Error(), "connection refused") || + strings.Contains(err.Error(), "no such file") +} + +// TerminateSupervisorSocket asks the supervisor listening on sock to +// terminate: it kills its child and exits. It is the reap half of +// the adopt-or-reap scan. A live supervisor that refuses (a daemon +// is attached, a protocol-version mismatch) returns a +// *supervisorRefusal; a dead socket returns the dial error. +func TerminateSupervisorSocket(sock string) error { + _, err := supervisorControl(sock, "terminate") + return err +} + +// supervisorControl sends one control handshake (restart/terminate) +// to the supervisor on sock and returns its reply. Control +// handshakes never become the attached daemon. +func supervisorControl(sock, action string) (supervisorReply, error) { + conn, err := net.DialTimeout("unix", sock, 2*time.Second) + if err != nil { + return supervisorReply{}, err + } + defer func() { _ = conn.Close() }() + hs, _ := json.Marshal(supervisorHandshake{Version: SupervisorProtocolVersion, Action: action}) + if _, err := conn.Write(append(hs, '\n')); err != nil { + return supervisorReply{}, err + } + _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) + line, err := bufio.NewReader(conn).ReadBytes('\n') + if err != nil { + return supervisorReply{}, fmt.Errorf("supervisor %s: %w", action, err) + } + var reply supervisorReply + if err := json.Unmarshal(line, &reply); err != nil { + return supervisorReply{}, fmt.Errorf("supervisor %s: %w", action, err) + } + if reply.Error != "" { + return reply, &supervisorRefusal{msg: reply.Error} + } + if reply.Version != SupervisorProtocolVersion { + return reply, &supervisorRefusal{msg: fmt.Sprintf( + "supervisor protocol version mismatch: supervisor sent %d, daemon speaks %d", + reply.Version, SupervisorProtocolVersion)} + } + return reply, nil +} diff --git a/pkgs/mcpx/internal/pool/handoff.go b/pkgs/mcpx/internal/pool/handoff.go index e91b440311..275ba7470d 100644 --- a/pkgs/mcpx/internal/pool/handoff.go +++ b/pkgs/mcpx/internal/pool/handoff.go @@ -469,7 +469,7 @@ func (p *Pool) ExecIdentity() string { // a pool that already serves the default lane are all quiet no-ops: // the ordinary spawn path (attach-or-spawn) covers them on first use. func (p *Pool) AdoptRunningSupervised(ctx context.Context) bool { - if p.cfg == nil || !p.cfg.Stdio() || p.cfg.Mcpx == nil || !p.cfg.Mcpx.Supervised { + if p.cfg == nil || !p.cfg.Stdio() || !p.cfg.Mcpx.SupervisedEnabled() { return false } rs := p.cfg.Scope.Resolve(config.CallContext{}) @@ -481,11 +481,21 @@ func (p *Pool) AdoptRunningSupervised(ctx context.Context) bool { p.starting++ p.mu.Unlock() - in, err := p.startLaneMode(ctx, false, rs, true) + in, err := p.startLaneMode(ctx, false, rs, dialAttachOnly) p.mu.Lock() p.starting-- if err != nil { + // A supervisor protocol-version refusal is the one adoption + // failure status must name (#9963): record it as the pool's + // last error instead of silently working around the + // supervisor, so `mcpx status` shows why this server is not + // running. Other adoption failures (no supervisor yet, + // another daemon attached) stay quiet no-ops: the ordinary + // spawn path covers them on first use. + if mcpclient.IsProtocolRefusal(err) { + p.lastErr = err + } p.cond.Broadcast() p.mu.Unlock() return false diff --git a/pkgs/mcpx/internal/pool/main_test.go b/pkgs/mcpx/internal/pool/main_test.go index fd2d8fa150..e97f561ffa 100644 --- a/pkgs/mcpx/internal/pool/main_test.go +++ b/pkgs/mcpx/internal/pool/main_test.go @@ -12,5 +12,6 @@ import ( // removed when the run ends; a process still executing from one of them // fails the run. func TestMain(m *testing.M) { + testsupport.SuperviseReExec() os.Exit(testsupport.MainWithSweep(m)) } diff --git a/pkgs/mcpx/internal/pool/pool.go b/pkgs/mcpx/internal/pool/pool.go index 980ac5e144..5c5c3709a1 100644 --- a/pkgs/mcpx/internal/pool/pool.go +++ b/pkgs/mcpx/internal/pool/pool.go @@ -629,13 +629,14 @@ func (p *Pool) subscribeServerEvents(cl *mcpclient.Client) { // serves: its root is stored on the instance at creation and read back // for every restart, never re-resolved (decision 0004 §2). func (p *Pool) startLane(ctx context.Context, legacy bool, rs config.ResolvedScope) (*Instance, error) { - return p.startLaneMode(ctx, legacy, rs, false) + return p.startLaneMode(ctx, legacy, rs, dialSpawn) } -// startLaneMode is startLane with the dial mode threaded through: with -// attachOnly set, a supervised server is adopted from its running -// supervisor or not started at all (#9962). -func (p *Pool) startLaneMode(ctx context.Context, legacy bool, rs config.ResolvedScope, attachOnly bool) (*Instance, error) { +// startLaneMode is startLane with the dial kind threaded through: +// dialAttachOnly adopts a supervised server from its running +// supervisor or does not start it at all (#9962); dialRestart +// restarts its child through the supervisor (#9963). +func (p *Pool) startLaneMode(ctx context.Context, legacy bool, rs config.ResolvedScope, kind dialKind) (*Instance, error) { sctx, cancel := context.WithTimeout(ctx, p.cfg.StartTimeout) defer cancel() launched := time.Now() @@ -657,7 +658,7 @@ func (p *Pool) startLaneMode(ctx context.Context, legacy bool, rs config.Resolve } execStamp, execIdentity, _ := eff.ExecStateAt(spawnCwd) - tr, err := p.dialMode(sctx, eff, rs.Root, attachOnly) + tr, err := p.dialMode(sctx, eff, rs.Root, kind) if err != nil { return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err) } @@ -701,7 +702,7 @@ func (p *Pool) startLaneMode(ctx context.Context, legacy bool, rs config.Resolve // transport; going straight there saves the two refused POSTs. if cl, tr, err = p.connectSSE(sctx, tr, opts); err == nil { source = mcpclient.SourceCache - } else if tr, err = p.dialMode(sctx, eff, rs.Root, attachOnly); err != nil { + } else if tr, err = p.dialMode(sctx, eff, rs.Root, kind); err != nil { return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err) } } @@ -746,7 +747,7 @@ func (p *Pool) startLaneMode(ctx context.Context, legacy bool, rs config.Resolve // that hears initialize first -- and the cache is what keeps this // from happening on every start. _ = tr.Close() - if tr, err = p.dialMode(sctx, eff, rs.Root, attachOnly); err != nil { + if tr, err = p.dialMode(sctx, eff, rs.Root, kind); err != nil { return nil, fmt.Errorf("server %q: %w", p.cfg.Name, err) } opts.Preference, opts.Cached = mcpclient.ForceLegacy, "" @@ -1001,6 +1002,21 @@ func SpawnCwd(configCwd, root string) (cwd, source string) { } } +// dialKind selects how a supervised server's transport is obtained. +type dialKind int + +const ( + // dialSpawn attaches to the server's supervisor, spawning it when + // it is not live (the ordinary start). + dialSpawn dialKind = iota + // dialAttachOnly attaches to an already-running supervisor or + // fails — it never spawns one (#9962 adoption scan). + dialAttachOnly + // dialRestart has the supervisor restart its child and attaches + // to the new child (#9963 restart-through-supervisor). + dialRestart +) + // dial creates the transport for one instance. ctx is the caller's // startup context: it bounds any nix: program-spec resolution at spawn, // so a slow build cannot outlive the startup budget that owns it. root @@ -1010,20 +1026,19 @@ func SpawnCwd(configCwd, root string) (cwd, source string) { // callers with no instance being spawned (HTTP session adoption) it is // simply the pool's stored config. func (p *Pool) dial(ctx context.Context, eff *config.Resolved, root string) (mcpclient.Transport, error) { - return p.dialMode(ctx, eff, root, false) + return p.dialMode(ctx, eff, root, dialSpawn) } -// dialMode is dial with one variation: with attachOnly set, a supervised -// server attaches to its already-running supervisor or fails — it never -// spawns a supervisor (#9962 adoption scan). Unsupervised paths ignore -// the flag. -func (p *Pool) dialMode(ctx context.Context, eff *config.Resolved, root string, attachOnly bool) (mcpclient.Transport, error) { +// dialMode is dial with the supervised variation selected by kind: +// dialAttachOnly never spawns a supervisor, dialRestart restarts the +// child through its supervisor. Unsupervised paths ignore the kind. +func (p *Pool) dialMode(ctx context.Context, eff *config.Resolved, root string, kind dialKind) (mcpclient.Transport, error) { spawnCwd, _ := SpawnCwd(eff.Cwd, root) auth, err := p.resolveAuth() if err != nil { return nil, err } - if eff.Stdio() && eff.Mcpx != nil && eff.Mcpx.Supervised { + if eff.Stdio() && eff.Mcpx.SupervisedEnabled() { opts := mcpclient.SupervisedOptions{ Name: eff.Name, Command: eff.Command, @@ -1033,10 +1048,14 @@ func (p *Pool) dialMode(ctx context.Context, eff *config.Resolved, root string, InheritEnv: true, Context: ctx, } - if attachOnly { + switch kind { + case dialAttachOnly: return mcpclient.AttachSupervised(opts) + case dialRestart: + return mcpclient.RestartSupervised(opts) + default: + return mcpclient.NewSupervised(opts) } - return mcpclient.NewSupervised(opts) } if eff.Stdio() { return mcpclient.NewStdio(mcpclient.StdioOptions{ @@ -1895,6 +1914,51 @@ func (p *Pool) Restart(ctx context.Context, lazy bool) RestartResult { } keys = []string{"global"} } + // Supervised servers restart THROUGH their supervisor (#9963): + // the instances above were retired (a supervised close is a + // detach), and each lane now restarts with a restart dial, so + // the supervisor kills and respawns the child instead of the + // pool reattaching to the very child it was asked to restart. + // Busy instances keep the generic path below: their calls drain + // on the old child first, as for any restart. + if p.cfg.Stdio() && p.cfg.Mcpx.SupervisedEnabled() && busy == 0 { + for _, key := range keys { + switch { + case strings.HasPrefix(key, "call:"): + res.Skipped = append(res.Skipped, RestartFailure{Key: key, Error: "per-call instance; its call is over"}) + continue + case p.cfg.Scope.WatchesPID() && !keyPIDAlive(key): + res.Skipped = append(res.Skipped, RestartFailure{Key: key, Error: "owning process has exited"}) + continue + } + rs := config.ResolvedScope{Key: key, Root: roots[key], Cwd: cwds[key]} + p.mu.Lock() + p.starting++ + p.mu.Unlock() + in, err := p.startLaneMode(ctx, false, rs, dialRestart) + p.mu.Lock() + p.starting-- + if err != nil { + p.cond.Broadcast() + p.mu.Unlock() + res.Failed = append(res.Failed, RestartFailure{Key: key, Error: err.Error()}) + continue + } + if p.closed || p.findLaneLocked(key, false) != nil { + p.cond.Broadcast() + p.mu.Unlock() + go func() { _ = in.Client.Close() }() + continue + } + in.key = key + in.lastUsed = time.Now() + p.instances = append(p.instances, in) + p.cond.Broadcast() + p.mu.Unlock() + res.Started = append(res.Started, in.ID) + } + return res + } for _, key := range keys { switch { case strings.HasPrefix(key, "call:"): diff --git a/pkgs/mcpx/internal/pool/supervised_default_test.go b/pkgs/mcpx/internal/pool/supervised_default_test.go new file mode 100644 index 0000000000..1dd9ecadaa --- /dev/null +++ b/pkgs/mcpx/internal/pool/supervised_default_test.go @@ -0,0 +1,127 @@ +package pool_test + +import ( + "context" + "net" + "os" + "path/filepath" + "strings" + "syscall" + "testing" + "time" + + "github.com/developing-today/code/pkgs/mcpx/internal/config" + "github.com/developing-today/code/pkgs/mcpx/internal/mcpclient" + "github.com/developing-today/code/pkgs/mcpx/internal/pool" + "github.com/developing-today/code/pkgs/mcpx/internal/testsupport" +) + +// Phase 3 of #1384 (#9963), the headline acceptance: a fresh daemon +// start with a default config — loaded from a file, no supervised +// key anywhere — runs its stdio servers supervised. The pool is what +// a daemon start builds from the resolved config, so the proof is: +// load, resolve, acquire, and a supervisor socket exists with the +// instance's child behind it. +func TestDefaultConfigStdioRunsSupervised(t *testing.T) { + stateDir := t.TempDir() + t.Setenv("MCPX_STATE_DIR", stateDir) + bin := testsupport.EraMCPBinary(t) + log := filepath.Join(t.TempDir(), "frames") + cfgPath := filepath.Join(t.TempDir(), "mcpx.json") + body := `{"mcpServers": {"era": {"command": "` + bin + `", "env": {"ERAMCP_MODE": "modern", "ERAMCP_LOG": "` + log + `"}}}}` + if err := os.WriteFile(cfgPath, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + cfg, err := config.Load(cfgPath) + if err != nil { + t.Fatal(err) + } + r, err := cfg.Resolve("era") + if err != nil { + t.Fatal(err) + } + if !r.Mcpx.SupervisedEnabled() { + t.Fatal("default config should resolve to supervised") + } + p := pool.New(r) + defer p.Close() + ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) + defer cancel() + lease, err := p.Acquire(ctx, config.ResolvedScope{}) + if err != nil { + t.Fatalf("acquire: %v", err) + } + sock := mcpclient.SupervisorSocketPath(stateDir, "era") + if _, err := os.Stat(sock); err != nil { + t.Fatalf("no supervisor socket at %s: %v", sock, err) + } + st := p.Status() + if len(st.Instances) != 1 || st.Instances[0].PID <= 0 { + t.Fatalf("status instances = %+v, want one with a child pid", st.Instances) + } + childPID := st.Instances[0].PID + lease.Release() + p.Close() + // The child survives the pool (that is the point of supervised); + // reap it through the scan so the test leaves nothing behind. + // The reap is acknowledged before the supervisor finishes the + // kill, so wait for the child to actually exit. + mcpclient.ScanSupervisorSockets(stateDir, nil, nil) + deadline := time.Now().Add(10 * time.Second) + for syscall.Kill(childPID, 0) == nil { + if time.Now().After(deadline) { + t.Fatalf("supervised child %d still alive after the reap", childPID) + } + time.Sleep(20 * time.Millisecond) + } +} + +// The other #9963 status acceptance: when the adoption scan meets a +// supervisor speaking a different protocol version, the refusal is +// recorded as the pool's last error — what `mcpx status` prints — +// instead of being silently worked around. +func TestAdoptProtocolRefusalSurfacesInStatus(t *testing.T) { + stateDir := t.TempDir() + t.Setenv("MCPX_STATE_DIR", stateDir) + sock := mcpclient.SupervisorSocketPath(stateDir, "era") + ln, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + defer func() { _ = ln.Close() }() + go func() { + for { + conn, err := ln.Accept() + if err != nil { + return + } + go func(conn net.Conn) { + defer func() { _ = conn.Close() }() + buf := make([]byte, 4096) + _ = conn.SetReadDeadline(time.Now().Add(5 * time.Second)) + if _, err := conn.Read(buf); err != nil { + return + } + _, _ = conn.Write([]byte("{\"version\":999,\"pid\":4242}\n")) + }(conn) + } + }() + + tr := true + cfg := &config.Config{MCPServers: map[string]*config.Server{ + "era": {Name: "era", Command: "cat", Mcpx: &config.Extras{Supervised: &tr}}, + }} + r, err := cfg.Resolve("era") + if err != nil { + t.Fatal(err) + } + p := pool.New(r) + defer p.Close() + if p.AdoptRunningSupervised(context.Background()) { + t.Fatal("adoption should refuse a version-mismatched supervisor") + } + st := p.Status() + if !strings.Contains(st.LastError, "protocol version mismatch") { + t.Fatalf("status lastError = %q, want it to name the protocol version mismatch", st.LastError) + } +} diff --git a/pkgs/mcpx/internal/testsupport/supervise.go b/pkgs/mcpx/internal/testsupport/supervise.go new file mode 100644 index 0000000000..1241bf6be4 --- /dev/null +++ b/pkgs/mcpx/internal/testsupport/supervise.go @@ -0,0 +1,57 @@ +package testsupport + +import ( + "fmt" + "os" + + "github.com/developing-today/code/pkgs/mcpx/internal/mcpclient" +) + +// SuperviseReExec handles the supervised transport re-execing the +// test binary (#9963, Phase 3 of #1384). Supervised stdio is the +// default now, so a suite whose pools dial stdio servers spawns +// supervisors by re-execing os.Executable() as +// `supervise --socket -- ` — the same re-exec the real +// binary serves via `mcpx supervise`. A test binary is not the mcpx +// binary: without this, the re-exec would run the whole suite again +// as the "supervisor", recursively. Call it first in TestMain; it +// exits the process when the binary was re-execed as a supervisor +// and returns at once otherwise. +func SuperviseReExec() { + if len(os.Args) < 2 || os.Args[1] != "supervise" { + return + } + os.Exit(runSupervise(os.Args[2:])) +} + +func runSupervise(args []string) int { + var socket string + var child []string + for i := 0; i < len(args); i++ { + switch { + case args[i] == "--socket" && i+1 < len(args): + socket = args[i+1] + i++ + case args[i] == "--": + child = args[i+1:] + i = len(args) + default: + fmt.Fprintln(os.Stderr, "supervise: unexpected argument", args[i]) + return 2 + } + } + if socket == "" || len(child) == 0 { + fmt.Fprintln(os.Stderr, "supervise: want --socket -- [args...]") + return 2 + } + if err := mcpclient.RunSupervisor(mcpclient.SupervisorOptions{ + SocketPath: socket, + Command: child[0], + Args: child[1:], + InheritEnv: true, + }); err != nil { + fmt.Fprintln(os.Stderr, "supervise:", err) + return 1 + } + return 0 +}