From fc78fd32dbcad0c57971313817d151de890ff591 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 06:32:47 -0500 Subject: [PATCH 1/4] feat(mcpx): cli.Run in-process entrypoint, slim main (#1980 stage 1) --- pkgs/mcpx/cmd/mcpx/main.go | 183 +------------------ pkgs/mcpx/internal/cli/commands.go | 5 + pkgs/mcpx/internal/cli/run.go | 270 +++++++++++++++++++++++++++++ pkgs/mcpx/internal/cli/run_test.go | 107 ++++++++++++ 4 files changed, 387 insertions(+), 178 deletions(-) create mode 100644 pkgs/mcpx/internal/cli/run.go create mode 100644 pkgs/mcpx/internal/cli/run_test.go diff --git a/pkgs/mcpx/cmd/mcpx/main.go b/pkgs/mcpx/cmd/mcpx/main.go index a9a810d667..de7e22c89c 100644 --- a/pkgs/mcpx/cmd/mcpx/main.go +++ b/pkgs/mcpx/cmd/mcpx/main.go @@ -3,196 +3,23 @@ package main import ( "context" - "errors" - "flag" - "fmt" "os" "os/signal" - "strings" "syscall" "github.com/dezren39/mcpx/internal/cli" - "github.com/dezren39/mcpx/internal/config" - "github.com/dezren39/mcpx/internal/daemon" ) // version is overridden at build time with -ldflags "-X main.version=...". var version = "0.1.0" -// splitList accepts comma or space separated values. -func splitList(s string) []string { - return strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ' ' }) -} - -// looksRunnable reports whether a bare first argument should be run, and as -// what. It is deliberately conservative: a bare word that is not a file is -// left to fail as an unknown command, because guessing that `mcpx serach` was -// a snippet would replace a clear error with a baffling one. -func looksRunnable(arg string) string { - if arg == "" || strings.HasPrefix(arg, "-") { - return "" - } - for _, ext := range []string{".ts", ".js", ".mts", ".mjs"} { - if strings.HasSuffix(arg, ext) { - return "file" - } - } - // Deliberately narrow. An "=" alone is not evidence of source -- a - // mistyped flag has one -- and treating it as such would run a typo as a - // program. These markers do not occur in a command name. - if strings.ContainsAny(arg, "(){};") || strings.Contains(arg, "await ") || - strings.Contains(arg, "console.") || strings.Contains(arg, "tools.") || - strings.Contains(arg, "=>") { - return "source" - } - if st, err := os.Stat(arg); err == nil && !st.IsDir() { - return "file" - } - return "" -} - +// main is only signal setup plus the in-process entrypoint (#1980, +// stage 1): everything it used to do inline -- global flags, dispatch, +// exit codes -- lives in cli.Run, where a test can drive it. func main() { ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGINT, syscall.SIGTERM) defer stop() - app := &cli.App{Version: version, Paths: daemon.ResolvePaths()} - // Script resolution is reached from places that do not carry an App, so - // it is told once where to read settings from. - cli.SetPlumbingSource(app) - - args := os.Args[1:] - // Global flags may appear before the subcommand. - for len(args) > 0 && strings.HasPrefix(args[0], "-") { - switch { - case args[0] == "--json": - app.JSON = true - args = args[1:] - case args[0] == "--tui": - // A global flag as well as a subcommand, because it is as likely - // to be reached for mid-command ("...actually, show me") as - // chosen up front. - if err := app.CmdTUI(ctx, nil); err != nil { - fmt.Fprintln(os.Stderr, "mcpx:", err) - os.Exit(1) - } - return - case args[0] == "--profile" && len(args) > 1: - app.Profile.Names = append(app.Profile.Names, splitList(args[1])...) - args = args[2:] - case strings.HasPrefix(args[0], "--profile="): - app.Profile.Names = append(app.Profile.Names, splitList(strings.TrimPrefix(args[0], "--profile="))...) - args = args[1:] - case args[0] == "--skip-default": - app.Profile.SkipDefault = true - args = args[1:] - case args[0] == "--all-profiles": - app.Profile.All = true - args = args[1:] - case args[0] == "--config" && len(args) > 1: - app.ConfigPath = args[1] - args = args[2:] - case strings.HasPrefix(args[0], "--config="): - app.ConfigPath = strings.TrimPrefix(args[0], "--config=") - args = args[1:] - case args[0] == "--paths-config" && len(args) > 1: - // A bootstrap flag like --config: it decides which files - // the settings are read from, so it is captured here, - // before any settings exist (issue #1842). - config.SetPathsConfigSeed(splitList(args[1])) - args = args[2:] - case strings.HasPrefix(args[0], "--paths-config="): - config.SetPathsConfigSeed(splitList(strings.TrimPrefix(args[0], "--paths-config="))) - args = args[1:] - case args[0] == "--version" || args[0] == "-v": - fmt.Println("mcpx", version) - return - case args[0] == "--help" || args[0] == "-h": - _ = app.CmdHelp(ctx, nil) - return - default: - // Any setting every command accepts is also a global flag, so - // `mcpx --plumbing-strict-unknown-keys ls` means what - // `mcpx ls --plumbing-strict-unknown-keys` does. - rest, err := app.ApplyGlobalSettingFlags(args) - if err != nil { - fmt.Fprintln(os.Stderr, "mcpx:", err) - os.Exit(2) - } - if len(rest) < len(args) { - args = rest - continue - } - fmt.Fprintf(os.Stderr, "unknown global flag %q\n", args[0]) - os.Exit(2) - } - } - - if len(args) == 0 { - // Bare `mcpx` opens the browser when there is a terminal to draw on, - // and prints help when there is not. Help was the old behaviour and - // is still the right answer for a pipe; for a person at a prompt, - // a wall of usage is a worse first impression than the thing itself. - if err := app.CmdTUI(ctx, nil); err != nil { - _ = app.CmdHelp(ctx, nil) - } - return - } - - cmd, rest := args[0], args[1:] - // The table lives in the cli package, beside Commands(), so a test can - // hold the two together; here it drifted from the declared list by seven. - handlers := app.Handlers() - - h, ok := handlers[cmd] - if !ok { - // An argument that is obviously a script or a snippet runs, rather - // than being refused for not being a subcommand. The alternative -- - // insisting on `mcpx run` -- rejects the most natural thing to type - // in order to protect a namespace that has no collisions in it. - if kind := looksRunnable(cmd); kind != "" { - if kind == "file" { - h, rest = app.CmdRun, args - } else { - h, rest = app.CmdExec, args - } - } else { - fmt.Fprintf(os.Stderr, "unknown command %q\n\n", cmd) - _ = app.CmdHelp(ctx, nil) - os.Exit(2) - } - } - - // Settings are resolved before dispatch, so a contradiction in a config - // file is reported once, up front, rather than by whichever command - // happens to read the offending value first. - if err := app.SettingsErr(); err != nil { - fmt.Fprintln(os.Stderr, "mcpx:", err) - os.Exit(2) - } - - // An in-process daemon lives exactly as long as this command. Stopped on - // every exit path, including an error, or its servers would outlive the - // process that owns them. - defer app.CloseInline() - - if err := h(ctx, rest); err != nil { - // Help was asked for and already printed; it is not a failure. - // Commands reached without the dispatch table (a script file named - // on the command line) can still return this directly. - if errors.Is(err, flag.ErrHelp) { - return - } - var ec cli.ExitCoder - if errors.As(err, &ec) { - fmt.Fprintln(os.Stderr, "mcpx:", err) - app.CloseInline() - os.Exit(ec.ExitCode()) - } - if errors.Is(err, cli.ErrNoDaemon) { - fmt.Fprintln(os.Stderr, "mcpx: daemon is not running and could not be started") - } else { - fmt.Fprintln(os.Stderr, "mcpx:", err) - } - os.Exit(1) - } + cli.Version = version + os.Exit(cli.Run(ctx, os.Args[1:], cli.Env(os.Environ()), cli.Stdio{In: os.Stdin, Out: os.Stdout, Err: os.Stderr})) } diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index 6c853cff8a..b03e59170e 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -68,6 +68,11 @@ type App struct { // Used by the MCP server, which must return what a script produced // rather than write it to a stream the host is parsing as protocol. stdoutOverride interface{ Write([]byte) (int, error) } + // environ is the environment Run was invoked with, recorded at the + // entrypoint for stage 2 of #1980 (threading it through ResolvePaths, + // settings.Environ and the plumbing source). Nil when the App was + // built directly; Environ() then falls back to os.Environ(). + environ Env settingsState } diff --git a/pkgs/mcpx/internal/cli/run.go b/pkgs/mcpx/internal/cli/run.go new file mode 100644 index 0000000000..e5e21472f1 --- /dev/null +++ b/pkgs/mcpx/internal/cli/run.go @@ -0,0 +1,270 @@ +package cli + +import ( + "context" + "errors" + "flag" + "fmt" + "io" + "os" + "strings" + + "github.com/dezren39/mcpx/internal/config" + "github.com/dezren39/mcpx/internal/daemon" +) + +// Version is the build version Run reports. cmd/mcpx sets it from its +// -ldflags-overridden var before calling Run, so the shipped binary and +// an in-process caller stamp the same string. +var Version = "0.1.0" + +// Env is a process environment as "key=value" entries, the shape +// os.Environ() returns. Run takes it explicitly so an in-process caller +// states the environment it means instead of inheriting whatever the +// host process happens to carry. +// +// Stage 1 of #1980: Run records the Env on the App (see App.Environ), +// but the internals still read os.Getenv, so in-process tests set values +// with t.Setenv and must not use t.Parallel. Stage 2 threads this Env +// through ResolvePaths, settings.Environ and the plumbing source. +type Env []string + +// Get returns the value for key, or "" when it is absent. +func (e Env) Get(key string) string { + v, _ := e.Lookup(key) + return v +} + +// Lookup returns the value for key and whether it was present. The first +// entry wins, matching os.Getenv. +func (e Env) Lookup(key string) (string, bool) { + prefix := key + "=" + for _, kv := range e { + if strings.HasPrefix(kv, prefix) { + return strings.TrimPrefix(kv, prefix), true + } + } + return "", false +} + +// Stdio is the streams a Run invocation reads and writes. A nil field +// falls back to the matching os stream, so the zero value behaves +// exactly like the binary. Stage 1: Run's own dispatch-level output +// (version, unknown command/flag, handler errors) goes to these +// streams; commands still write to the os streams directly until the +// threading in stage 2 lands. +type Stdio struct { + In io.Reader + Out io.Writer + Err io.Writer +} + +func (s Stdio) out() io.Writer { + if s.Out != nil { + return s.Out + } + return os.Stdout +} + +func (s Stdio) err() io.Writer { + if s.Err != nil { + return s.Err + } + return os.Stderr +} + +// Environ returns the environment this App was invoked with: the Env +// Run was given, or os.Environ() when the App was built directly. +func (a *App) Environ() Env { + if a.environ != nil { + return a.environ + } + return Env(os.Environ()) +} + +// splitList accepts comma or space separated values. +func splitList(s string) []string { + return strings.FieldsFunc(s, func(r rune) bool { return r == ',' || r == ' ' }) +} + +// looksRunnable reports whether a bare first argument should be run, and as +// what. It is deliberately conservative: a bare word that is not a file is +// left to fail as an unknown command, because guessing that `mcpx serach` was +// a snippet would replace a clear error with a baffling one. +func looksRunnable(arg string) string { + if arg == "" || strings.HasPrefix(arg, "-") { + return "" + } + for _, ext := range []string{".ts", ".js", ".mts", ".mjs"} { + if strings.HasSuffix(arg, ext) { + return "file" + } + } + // Deliberately narrow. An "=" alone is not evidence of source -- a + // mistyped flag has one -- and treating it as such would run a typo as a + // program. These markers do not occur in a command name. + if strings.ContainsAny(arg, "(){};") || strings.Contains(arg, "await ") || + strings.Contains(arg, "console.") || strings.Contains(arg, "tools.") || + strings.Contains(arg, "=>") { + return "source" + } + if st, err := os.Stat(arg); err == nil && !st.IsDir() { + return "file" + } + return "" +} + +// Run is the in-process entrypoint for the whole CLI (#1980, approach C, +// stage 1). It owns everything main() used to do inline -- global-flag +// parsing, building the App, dispatch through the Handlers table, and +// turning handler errors into exit codes -- and returns the exit code +// instead of calling os.Exit, so a test can drive the same code path a +// user takes. cmd/mcpx is now only signal setup plus +// os.Exit(cli.Run(...)). +// +// The binary suite remains the superset: signals, real exit codes as a +// process boundary, and argv as the shell delivers it only exist there. +func Run(ctx context.Context, args []string, env Env, stdio Stdio) int { + app := &App{Version: Version, Paths: daemon.ResolvePaths(), environ: env} + // Script resolution is reached from places that do not carry an App, so + // it is told once where to read settings from. + SetPlumbingSource(app) + + // An in-process daemon lives exactly as long as this command. Stopped on + // every exit path, including an error, or its servers would outlive the + // invocation that owns them. (In main() this only guarded the dispatch + // path, because the process was exiting anyway; in-process it must + // guard every return.) + defer app.CloseInline() + + // Global flags may appear before the subcommand. + for len(args) > 0 && strings.HasPrefix(args[0], "-") { + switch { + case args[0] == "--json": + app.JSON = true + args = args[1:] + case args[0] == "--tui": + // A global flag as well as a subcommand, because it is as likely + // to be reached for mid-command ("...actually, show me") as + // chosen up front. + if err := app.CmdTUI(ctx, nil); err != nil { + fmt.Fprintln(stdio.err(), "mcpx:", err) + return 1 + } + return 0 + case args[0] == "--profile" && len(args) > 1: + app.Profile.Names = append(app.Profile.Names, splitList(args[1])...) + args = args[2:] + case strings.HasPrefix(args[0], "--profile="): + app.Profile.Names = append(app.Profile.Names, splitList(strings.TrimPrefix(args[0], "--profile="))...) + args = args[1:] + case args[0] == "--skip-default": + app.Profile.SkipDefault = true + args = args[1:] + case args[0] == "--all-profiles": + app.Profile.All = true + args = args[1:] + case args[0] == "--config" && len(args) > 1: + app.ConfigPath = args[1] + args = args[2:] + case strings.HasPrefix(args[0], "--config="): + app.ConfigPath = strings.TrimPrefix(args[0], "--config=") + args = args[1:] + case args[0] == "--paths-config" && len(args) > 1: + // A bootstrap flag like --config: it decides which files + // the settings are read from, so it is captured here, + // before any settings exist (issue #1842). + config.SetPathsConfigSeed(splitList(args[1])) + args = args[2:] + case strings.HasPrefix(args[0], "--paths-config="): + config.SetPathsConfigSeed(splitList(strings.TrimPrefix(args[0], "--paths-config="))) + args = args[1:] + case args[0] == "--version" || args[0] == "-v": + fmt.Fprintln(stdio.out(), "mcpx", Version) + return 0 + case args[0] == "--help" || args[0] == "-h": + _ = app.CmdHelp(ctx, nil) + return 0 + default: + // Any setting every command accepts is also a global flag, so + // `mcpx --plumbing-strict-unknown-keys ls` means what + // `mcpx ls --plumbing-strict-unknown-keys` does. + rest, err := app.ApplyGlobalSettingFlags(args) + if err != nil { + fmt.Fprintln(stdio.err(), "mcpx:", err) + return 2 + } + if len(rest) < len(args) { + args = rest + continue + } + fmt.Fprintf(stdio.err(), "unknown global flag %q\n", args[0]) + return 2 + } + } + + if len(args) == 0 { + // Bare `mcpx` opens the browser when there is a terminal to draw on, + // and prints help when there is not. Help was the old behaviour and + // is still the right answer for a pipe; for a person at a prompt, + // a wall of usage is a worse first impression than the thing itself. + if err := app.CmdTUI(ctx, nil); err != nil { + _ = app.CmdHelp(ctx, nil) + } + return 0 + } + + cmd, rest := args[0], args[1:] + // The table lives in this package, beside Commands(), so a test can + // hold the two together; in main it drifted from the declared list + // by seven. + handlers := app.Handlers() + + h, ok := handlers[cmd] + if !ok { + // An argument that is obviously a script or a snippet runs, rather + // than being refused for not being a subcommand. The alternative -- + // insisting on `mcpx run` -- rejects the most natural thing to type + // in order to protect a namespace that has no collisions in it. + if kind := looksRunnable(cmd); kind != "" { + if kind == "file" { + h, rest = app.CmdRun, args + } else { + h, rest = app.CmdExec, args + } + } else { + fmt.Fprintf(stdio.err(), "unknown command %q\n\n", cmd) + _ = app.CmdHelp(ctx, nil) + return 2 + } + } + + // Settings are resolved before dispatch, so a contradiction in a config + // file is reported once, up front, rather than by whichever command + // happens to read the offending value first. + if err := app.SettingsErr(); err != nil { + fmt.Fprintln(stdio.err(), "mcpx:", err) + return 2 + } + + if err := h(ctx, rest); err != nil { + // Help was asked for and already printed; it is not a failure. + // Commands reached without the dispatch table (a script file named + // on the command line) can still return this directly. + if errors.Is(err, flag.ErrHelp) { + return 0 + } + var ec ExitCoder + if errors.As(err, &ec) { + fmt.Fprintln(stdio.err(), "mcpx:", err) + return ec.ExitCode() + } + if errors.Is(err, ErrNoDaemon) { + fmt.Fprintln(stdio.err(), "mcpx: daemon is not running and could not be started") + } else { + fmt.Fprintln(stdio.err(), "mcpx:", err) + } + return 1 + } + return 0 +} diff --git a/pkgs/mcpx/internal/cli/run_test.go b/pkgs/mcpx/internal/cli/run_test.go new file mode 100644 index 0000000000..b4517564fd --- /dev/null +++ b/pkgs/mcpx/internal/cli/run_test.go @@ -0,0 +1,107 @@ +package cli + +import ( + "bytes" + "context" + "strings" + "testing" +) + +// Stage 1 of #1980: Run is the dispatch main() used to own, reachable +// in-process. These tests pin the exit-code contract the binary suite +// asserts through a process boundary; they deliberately avoid commands +// that need a daemon or a terminal. + +func TestRunVersion(t *testing.T) { + var out, errOut bytes.Buffer + code := Run(context.Background(), []string{"--version"}, Env{}, Stdio{Out: &out, Err: &errOut}) + if code != 0 { + t.Fatalf("exit code = %d, want 0 (stderr: %s)", code, errOut.String()) + } + if got, want := out.String(), "mcpx "+Version+"\n"; got != want { + t.Fatalf("stdout = %q, want %q", got, want) + } +} + +func TestRunGlobalFlagThenVersion(t *testing.T) { + var out, errOut bytes.Buffer + code := Run(context.Background(), []string{"--json", "--version"}, Env{}, Stdio{Out: &out, Err: &errOut}) + if code != 0 { + t.Fatalf("exit code = %d, want 0 (stderr: %s)", code, errOut.String()) + } + if !strings.HasPrefix(out.String(), "mcpx ") { + t.Fatalf("stdout = %q, want the version line", out.String()) + } +} + +func TestRunUnknownGlobalFlag(t *testing.T) { + var out, errOut bytes.Buffer + code := Run(context.Background(), []string{"--no-such-flag"}, Env{}, Stdio{Out: &out, Err: &errOut}) + if code != 2 { + t.Fatalf("exit code = %d, want 2", code) + } + if !strings.Contains(errOut.String(), `unknown global flag "--no-such-flag"`) { + t.Fatalf("stderr = %q, want the unknown-flag message", errOut.String()) + } +} + +func TestRunUnknownCommand(t *testing.T) { + var errOut bytes.Buffer + var code int + // CmdHelp still writes to os.Stdout in stage 1; capture it so the + // help text does not land in the test output. + _, err := captureStdout(t, func() error { + code = Run(context.Background(), []string{"frobnicate-xyz"}, Env{}, Stdio{Err: &errOut}) + return nil + }) + if err != nil { + t.Fatal(err) + } + if code != 2 { + t.Fatalf("exit code = %d, want 2", code) + } + if !strings.Contains(errOut.String(), `unknown command "frobnicate-xyz"`) { + t.Fatalf("stderr = %q, want the unknown-command message", errOut.String()) + } +} + +func TestRunHelpCommandDispatches(t *testing.T) { + var code int + out, err := captureStdout(t, func() error { + code = Run(context.Background(), []string{"help"}, Env{}, Stdio{}) + return nil + }) + if err != nil { + t.Fatal(err) + } + if code != 0 { + t.Fatalf("exit code = %d, want 0", code) + } + if out == "" { + t.Fatal("help command printed nothing") + } +} + +func TestEnvLookup(t *testing.T) { + env := Env{"A=1", "B=2=3", "A=9"} + if got := env.Get("A"); got != "1" { + t.Fatalf("Get(A) = %q, want the first entry %q", got, "1") + } + if got, ok := env.Lookup("B"); !ok || got != "2=3" { + t.Fatalf("Lookup(B) = %q, %v; want %q, true", got, ok, "2=3") + } + if _, ok := env.Lookup("MISSING"); ok { + t.Fatal("Lookup(MISSING) reported present") + } +} + +func TestAppEnvironFallsBackToOS(t *testing.T) { + t.Setenv("MCPX_RUN_TEST_SENTINEL", "present") + if got := (&App{}).Environ().Get("MCPX_RUN_TEST_SENTINEL"); got != "present" { + t.Fatalf("Environ().Get(sentinel) = %q, want the os environment", got) + } + given := (&App{environ: Env{"MCPX_RUN_TEST_SENTINEL=from-run"}}).Environ() + if got := given.Get("MCPX_RUN_TEST_SENTINEL"); got != "from-run" { + t.Fatalf("Environ().Get(sentinel) = %q, want the Run-supplied env", got) + } +} From 01ea0cb1207e111bfbe0d8f7d74ed418db654fd9 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 07:09:43 -0500 Subject: [PATCH 2/4] fix(mcpx): return script exit status from handlers; scope paths-config seed per Run (#1980 stage 1, Codex) Codex P1: commands.go/exec.go script paths called os.Exit on a nonzero script status, terminating an in-process caller of cli.Run and skipping its deferred CloseInline. They now return exitStatusError, an ExitCoder Run already translates into the process exit code; Run does not prefix it with mcpx: since the run already reported itself. Codex P2: config.SetPathsConfigSeed is a package global; Run now clears it on entry and defers clearing it on exit, so a --paths-config seed cannot leak between sequential in-process invocations. --- pkgs/mcpx/internal/cli/commands.go | 4 ++-- pkgs/mcpx/internal/cli/exec.go | 2 +- pkgs/mcpx/internal/cli/run.go | 26 +++++++++++++++++++++++++- 3 files changed, 28 insertions(+), 4 deletions(-) diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index b03e59170e..479a7f1383 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -1128,7 +1128,7 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error { return err } if res.ExitCode != 0 { - os.Exit(res.ExitCode) + return &exitStatusError{code: res.ExitCode} } return nil } @@ -1168,7 +1168,7 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error { a.reportArtifacts(res) } if res.ExitCode != 0 { - os.Exit(res.ExitCode) + return &exitStatusError{code: res.ExitCode} } return nil } diff --git a/pkgs/mcpx/internal/cli/exec.go b/pkgs/mcpx/internal/cli/exec.go index 145db88a4a..b616d99282 100644 --- a/pkgs/mcpx/internal/cli/exec.go +++ b/pkgs/mcpx/internal/cli/exec.go @@ -349,7 +349,7 @@ func (a *App) renderExecResult(res *execsvc.Result, eo execOptions) error { if res.Error != "" { fmt.Fprintln(os.Stderr, "mcpx:", res.Error) } - os.Exit(res.ExitCode) + return &exitStatusError{code: res.ExitCode} } return nil } diff --git a/pkgs/mcpx/internal/cli/run.go b/pkgs/mcpx/internal/cli/run.go index e5e21472f1..94ef15a732 100644 --- a/pkgs/mcpx/internal/cli/run.go +++ b/pkgs/mcpx/internal/cli/run.go @@ -130,6 +130,14 @@ func Run(ctx context.Context, args []string, env Env, stdio Stdio) int { // it is told once where to read settings from. SetPlumbingSource(app) + // The --paths-config seed is a package global in config (it has to + // be captured before any settings exist), so an in-process caller + // would otherwise inherit the previous invocation's seed. Scope it + // to this invocation: clear on entry, and clear again on the way + // out so nothing leaks into the next call. + config.SetPathsConfigSeed(nil) + defer config.SetPathsConfigSeed(nil) + // An in-process daemon lives exactly as long as this command. Stopped on // every exit path, including an error, or its servers would outlive the // invocation that owns them. (In main() this only guarded the dispatch @@ -256,7 +264,13 @@ func Run(ctx context.Context, args []string, env Env, stdio Stdio) int { } var ec ExitCoder if errors.As(err, &ec) { - fmt.Fprintln(stdio.err(), "mcpx:", err) + // A script's exit status is not a failure of mcpx itself: + // the run already reported itself, so there is nothing to + // prefix with "mcpx:" -- only the status carries over. + var se *exitStatusError + if !errors.As(err, &se) { + fmt.Fprintln(stdio.err(), "mcpx:", err) + } return ec.ExitCode() } if errors.Is(err, ErrNoDaemon) { @@ -268,3 +282,13 @@ func Run(ctx context.Context, args []string, env Env, stdio Stdio) int { } return 0 } + +// exitStatusError carries a script run's exit status back to Run as an +// error, so a handler never has to os.Exit to report it: in-process, an +// os.Exit would terminate the embedding application or test runner (and +// skip Run's deferred CloseInline); as a returned ExitCoder, Run turns +// it into the same process exit code at the one place that owns it. +type exitStatusError struct{ code int } + +func (e *exitStatusError) Error() string { return fmt.Sprintf("exit status %d", e.code) } +func (e *exitStatusError) ExitCode() int { return e.code } From 5ed1369f25743d80aa23adda48ba5d5a4e6e4863 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 08:49:26 -0500 Subject: [PATCH 3/4] test(mcpx): regression tests for in-process Run fixes (#1980 stage 1, Codex P1) Codex round 2 (PR #2714): the stage-1 tests would still pass with either round-1 bug restored. Add failing-first regressions: a script exiting 3 through cli.Run returns 3 in both the local text and local JSON paths (mutation-checked: restoring os.Exit in the JSON branch kills the test binary with exit status 3); renderExecResult returns an ExitCoder for a nonzero daemon-side result in text and JSON shapes (remote path); sequential Run calls do not inherit a --paths-config seed (seed visible via config.ResolveChainFrom before, absent after flagless and flagged Runs). --- pkgs/mcpx/internal/cli/run_test.go | 204 +++++++++++++++++++++++++++++ 1 file changed, 204 insertions(+) diff --git a/pkgs/mcpx/internal/cli/run_test.go b/pkgs/mcpx/internal/cli/run_test.go index b4517564fd..6856283469 100644 --- a/pkgs/mcpx/internal/cli/run_test.go +++ b/pkgs/mcpx/internal/cli/run_test.go @@ -3,8 +3,18 @@ package cli import ( "bytes" "context" + "encoding/json" + "errors" + "io" + "os" + osexec "os/exec" + "path/filepath" "strings" "testing" + + "github.com/dezren39/mcpx/internal/config" + "github.com/dezren39/mcpx/internal/execsvc" + "github.com/dezren39/mcpx/internal/testsupport" ) // Stage 1 of #1980: Run is the dispatch main() used to own, reachable @@ -105,3 +115,197 @@ func TestAppEnvironFallsBackToOS(t *testing.T) { t.Fatalf("Environ().Get(sentinel) = %q, want the Run-supplied env", got) } } + +// ---- Regression tests for the Codex findings on PR #2714 ---- +// +// The first Codex round found two bugs the stage-1 tests could not see: +// script handlers called os.Exit on a nonzero script status (terminating +// an in-process caller of Run), and the --paths-config seed leaked +// between sequential Run calls. The tests below execute both bugs' exact +// shapes: if either os.Exit comes back, this test binary dies instead of +// failing cleanly, and if the seed scoping comes out, the chain +// resolution after a Run still reports the previous invocation's seed. + +// runTestConfig gives a Run invocation a hermetic home: a temp HOME whose +// only config declares no servers, so the in-process daemon answers at +// once and nothing outside the temp tree is read or written. +func runTestConfig(t *testing.T) string { + t.Helper() + root := testsupport.TempDir(t) + t.Setenv("HOME", root) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "xdg")) + t.Setenv("XDG_STATE_HOME", filepath.Join(root, "state")) + t.Setenv("XDG_CACHE_HOME", filepath.Join(root, "cache")) + t.Setenv("MCPX_CONFIG", "") + t.Setenv("MCPX_PATHS_CONFIG", "") + t.Setenv("MCPX_STATE_DIR", "") + // No daemon binary exists beside a test binary to spawn, and none + // should be: the in-process daemon is the one a Run caller gets. + t.Setenv("MCPX_DAEMON_AUTOSTART", "false") + t.Setenv("MCPX_DAEMON_INLINE", "true") + cfg := filepath.Join(root, "mcpx.json") + if err := os.WriteFile(cfg, []byte(`{"mcpServers":{}}`), 0o600); err != nil { + t.Fatal(err) + } + return cfg +} + +// scriptRuntime picks the first JS runtime this machine has, in the +// order the e2e runtime tests exercise them. A machine with none skips: +// the binary suite on a runner that has one remains the coverage. +func scriptRuntime(t *testing.T) string { + t.Helper() + for _, rt := range []string{"node", "deno", "bun"} { + if _, err := osexec.LookPath(rt); err == nil { + return rt + } + } + t.Skip("no JS runtime (node, deno, or bun) on PATH") + return "" +} + +// exitThree is a snippet that ends its run with status 3 on every +// runtime: the launcher gives bun and node the Deno global deno has +// natively (the same shape TestDenoExitWorksOnEveryRuntime runs through +// the binary). +const exitThree = `console.log("before-exit"); (globalThis as any).Deno.exit(3); console.log("after-exit");` + +func TestRunScriptFailureReturnsStatusText(t *testing.T) { + cfg := runTestConfig(t) + rt := scriptRuntime(t) + var code int + out, err := captureStdout(t, func() error { + code = Run(context.Background(), + []string{"--config", cfg, "exec", "--runtime", rt, exitThree}, + Env{}, Stdio{Err: io.Discard}) + return nil + }) + if err != nil { + t.Fatal(err) + } + if code != 3 { + t.Fatalf("Run(exec, script exits 3) = %d, want 3 (stdout: %s)", code, out) + } + if !strings.Contains(out, "before-exit") || strings.Contains(out, "after-exit") { + t.Fatalf("the script did not stop where it exited:\n%s", out) + } +} + +func TestRunScriptFailureReturnsStatusJSON(t *testing.T) { + cfg := runTestConfig(t) + rt := scriptRuntime(t) + var code int + out, err := captureStdout(t, func() error { + code = Run(context.Background(), + []string{"--json", "--config", cfg, "exec", "--runtime", rt, exitThree}, + Env{}, Stdio{Err: io.Discard}) + return nil + }) + if err != nil { + t.Fatal(err) + } + if code != 3 { + t.Fatalf("Run(--json exec, script exits 3) = %d, want 3 (stdout: %s)", code, out) + } + var doc struct { + OK bool `json:"ok"` + ExitCode int `json:"exitCode"` + } + if jerr := json.Unmarshal([]byte(jsonLineOf(t, out)), &doc); jerr != nil { + t.Fatalf("the JSON envelope should survive a failing script: %v\n%s", jerr, out) + } + if doc.OK || doc.ExitCode != 3 { + t.Fatalf("envelope = %+v, want ok=false exitCode=3", doc) + } +} + +// jsonLineOf returns the first line of out that parses as a JSON object, +// so a test can find the envelope among anything else a run printed. +func jsonLineOf(t *testing.T, out string) string { + t.Helper() + for _, line := range strings.Split(out, "\n") { + line = strings.TrimSpace(line) + if strings.HasPrefix(line, "{") { + var v map[string]any + if json.Unmarshal([]byte(line), &v) == nil { + return line + } + } + } + // The envelope is pretty-printed by App.out, so it spans lines; fall + // back to the whole capture and let the caller's unmarshal judge it. + return out +} + +func TestRenderExecResultReturnsStatusNotExit(t *testing.T) { + // The remote path (execRemote -> renderExecResult): a daemon-side + // script failure arrives as a Result with a nonzero ExitCode and must + // come back as an ExitCoder error, in both render shapes. + for _, tc := range []struct { + name string + app *App + }{ + {"text", &App{}}, + {"json", &App{JSON: true}}, + } { + t.Run(tc.name, func(t *testing.T) { + res := &execsvc.Result{ExitCode: 7, Stdout: "remote-out\n"} + var err error + out, cerr := captureStdout(t, func() error { + err = tc.app.renderExecResult(res, execOptions{}) + return nil + }) + if cerr != nil { + t.Fatal(cerr) + } + var ec ExitCoder + if !errors.As(err, &ec) || ec.ExitCode() != 7 { + t.Fatalf("renderExecResult(ExitCode 7) err = %v, want an ExitCoder with code 7", err) + } + if !strings.Contains(out, "remote-out") { + t.Fatalf("the result's stdout was not rendered:\n%s", out) + } + }) + } +} + +func TestRunPathsConfigSeedDoesNotLeak(t *testing.T) { + root := filepath.Dir(runTestConfig(t)) + seed := filepath.Join(root, "seed.json") + if err := os.WriteFile(seed, []byte(`{"paths":{"config":[]}}`), 0o600); err != nil { + t.Fatal(err) + } + seeded := func() []string { + _, info, err := config.ResolveChainFrom(root) + if err != nil { + t.Fatal(err) + } + return info.Seeded + } + // Sanity: the probe can see a seed when one is set, so an empty + // result below means the seed is gone, not that the probe is blind. + config.SetPathsConfigSeed([]string{seed}) + if got := seeded(); len(got) != 1 || got[0] != seed { + t.Fatalf("with a seed set, Seeded = %v, want [%s]", got, seed) + } + // A Run that never mentions --paths-config must clear a seed it + // inherited (entry scoping), and leave none behind (exit scoping). + var out, errOut bytes.Buffer + if code := Run(context.Background(), []string{"--version"}, Env{}, Stdio{Out: &out, Err: &errOut}); code != 0 { + t.Fatalf("Run(--version) = %d, want 0 (stderr: %s)", code, errOut.String()) + } + if got := seeded(); len(got) != 0 { + t.Fatalf("after a Run without --paths-config, Seeded = %v, want none", got) + } + // A Run that takes the flag uses it for that invocation only: the + // next flagless invocation must not inherit it. + out.Reset() + errOut.Reset() + if code := Run(context.Background(), []string{"--paths-config", seed, "--version"}, Env{}, Stdio{Out: &out, Err: &errOut}); code != 0 { + t.Fatalf("Run(--paths-config seed --version) = %d, want 0 (stderr: %s)", code, errOut.String()) + } + if got := seeded(); len(got) != 0 { + t.Fatalf("after a Run with --paths-config, Seeded = %v, want none (the seed leaked into the next invocation)", got) + } + t.Cleanup(func() { config.SetPathsConfigSeed(nil) }) +} From 61a3d0f8e946233fcd1667f6d62dca5c09d97dc3 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 17:51:36 -0500 Subject: [PATCH 4/4] mcpx(cli): scope the plumbing source to the Run invocation (#1980) --- pkgs/mcpx/internal/cli/run.go | 10 +++++++++- pkgs/mcpx/internal/cli/run_test.go | 18 ++++++++++++++++++ 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/pkgs/mcpx/internal/cli/run.go b/pkgs/mcpx/internal/cli/run.go index 94ef15a732..4dc03a1d35 100644 --- a/pkgs/mcpx/internal/cli/run.go +++ b/pkgs/mcpx/internal/cli/run.go @@ -127,8 +127,16 @@ func looksRunnable(arg string) string { func Run(ctx context.Context, args []string, env Env, stdio Stdio) int { app := &App{Version: Version, Paths: daemon.ResolvePaths(), environ: env} // Script resolution is reached from places that do not carry an App, so - // it is told once where to read settings from. + // it is told once where to read settings from. The plumbing source is a + // package global (clientSettings consults it too), so scope it to this + // invocation like the paths-config seed below: an in-process caller + // would otherwise leak its settings -- its env layer included -- into + // every later client built in the same process. That leak is what the + // stress suite caught: a Run test setting MCPX_DAEMON_AUTOSTART=false + // left later EnsureDaemon tests reading autostart as off. + prevPlumbing := plumbingApp SetPlumbingSource(app) + defer SetPlumbingSource(prevPlumbing) // The --paths-config seed is a package global in config (it has to // be captured before any settings exist), so an in-process caller diff --git a/pkgs/mcpx/internal/cli/run_test.go b/pkgs/mcpx/internal/cli/run_test.go index 6856283469..f5678447c6 100644 --- a/pkgs/mcpx/internal/cli/run_test.go +++ b/pkgs/mcpx/internal/cli/run_test.go @@ -309,3 +309,21 @@ func TestRunPathsConfigSeedDoesNotLeak(t *testing.T) { } t.Cleanup(func() { config.SetPathsConfigSeed(nil) }) } + +// Regression (stress suite, PR #2714): Run installed its App as the +// package plumbing source and never restored it, so every later +// in-process client inherited the Run invocation's settings -- a Run +// test whose env set MCPX_DAEMON_AUTOSTART=false left subsequent +// EnsureDaemon tests reading daemon.autostart as off. The plumbing +// source is scoped to the invocation, like the paths-config seed. +func TestRunRestoresPlumbingSource(t *testing.T) { + before := plumbingApp + var out, errOut bytes.Buffer + code := Run(context.Background(), []string{"--version"}, Env{}, Stdio{Out: &out, Err: &errOut}) + if code != 0 { + t.Fatalf("exit code = %d, want 0 (stderr: %s)", code, errOut.String()) + } + if plumbingApp != before { + t.Fatal("Run left its App installed as the plumbing source; later in-process clients would inherit its settings") + } +}