GeezerVison is showing github.com — feat(mcpx): cli.Run in-process entrypoint, slim main (#1980 stage 1) by dezren39 · Pull Request #2714 · developing-today/code
feat(mcpx): cli.Run in-process entrypoint, slim main (#1980 stage 1)
#2714
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
57b844d
feat(mcpx): cli.Run in-process entrypoint, slim main (#1980 stage 1)
dezren39 Oct 30, 2026
0e6fd16
fix(mcpx): return script exit status from handlers; scope paths-confi…
dezren39 Oct 30, 2026
3d014df
test(mcpx): regression tests for in-process Run fixes (#1980 stage 1,…
dezren39 Oct 30, 2026
acec1d7
mcpx(cli): scope the plumbing source to the Run invocation (#1980)
dezren39 Oct 30, 2026
f9877ba
mcpx(cli): batch the flag-reach probe to one invocation per command (…
Nov 3, 2026
3f5ae56
fix(mcpx): use current module path in ported cli.Run code (#1980)
Nov 11, 2026
df9be39
test(mcpx): hold GlobalFlags against cli.Run after the stage-1 move (…
Nov 11, 2026
357c3fc
fix(mcpx): alias rounds in flag-reach probe; Stdio.In doc; bare-comma…
Nov 11, 2026
File filter
Filter by extension
.go
(7)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -3,17 +3,11 @@ package main
import (
"context"
"errors"
"flag"
"fmt"
"os"
"os/signal"
"strings"
"syscall"
"github.com/developing-today/code/pkgs/mcpx/internal/cli"
"github.com/developing-today/code/pkgs/mcpx/internal/config"
"github.com/developing-today/code/pkgs/mcpx/internal/daemon"
)
// version is overridden at build time with -ldflags "-X main.version=...".
Expand All
@@ -23,180 +17,13 @@ import (
// instead of impersonating one.
var version = "0.0.0-dev"
// 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.AddPathsConfigSeed(splitList(args[1]))
args = args[2:]
case strings.HasPrefix(args[0], "--paths-config="):
config.AddPathsConfigSeed(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}))
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -70,6 +70,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
}
Expand Down
Expand Up
@@ -1199,7 +1204,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
}
Expand Down
Expand Up
@@ -1239,7 +1244,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
}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -384,7 +384,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
}
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -86,35 +86,93 @@ func TestEverySettingFlagReachesTheResolvedValue(t *testing.T) {
continue
}
cmdName := cmd
// Every (command, flag) pair used to get its own handler
// invocation, each rebuilding the whole settings schema twice
// (bindFlags, then Settings). That is O(commands x flags)
// schema builds and made this test the package's top duration
// contributor under the stress repetition (#2859). Batch instead:
// one invocation carrying every canonical flag, one carrying
// every alias, with the same per-setting origin assertion the
// per-flag loop made. If a batched invocation fails for a reason
// other than the hook, fall back to per-flag invocations for
// that command so the diagnosis stays exact.
type flagCase struct {
path string
arg string
}
var canonical []flagCase
var aliasRounds [][]flagCase
for _, s := range sch.ForCommand(cmdName) {
val := nonDefault(s)
if val == "" {
continue
}
for _, name := range append([]string{s.FlagName()}, s.FlagAliases...) {
if !handFlagsMeaningOther[cmd][s.FlagName()] {
canonical = append(canonical, flagCase{s.Path, "--" + s.FlagName() + "=" + val})
}
// Aliases go in rounds -- round i carries the i-th alias
// of every setting -- so a setting with several aliases
// appears at most once per batch invocation and one
// alias's folding can never mask or overwrite another's.
for i, name := range s.FlagAliases {
if handFlagsMeaningOther[cmd][name] {
continue
}
a := &App{ConfigPath: cfg}
err := a.Handlers()[cmd](ctx, []string{"--" + name + "=" + val})
if err != nil && !errors.Is(err, errStopAfterFlags) {
// A requirement refusing the value proves it arrived.
if v, ok := a.Settings().Value(s.Path); ok && v.Origin.Layer == settings.LayerFlag {
checked++
continue
}
t.Errorf("%s --%s=%s: %v", cmd, name, val, err)
continue
for len(aliasRounds) <= i {
aliasRounds = append(aliasRounds, nil)
}
aliasRounds[i] = append(aliasRounds[i], flagCase{s.Path, "--" + name + "=" + val})
}
}
checkSingle := func(path, arg string) {
a := &App{ConfigPath: cfg}
err := a.Handlers()[cmd](ctx, []string{arg})
if err != nil && !errors.Is(err, errStopAfterFlags) {
// A requirement refusing the value proves it arrived.
if v, ok := a.Settings().Value(path); ok && v.Origin.Layer == settings.LayerFlag {
checked++
return
}
v, ok := a.Settings().Value(s.Path)
t.Errorf("%s %s: %v", cmd, arg, err)
return
}
v, ok := a.Settings().Value(path)
if !ok || v.Origin.Layer != settings.LayerFlag {
t.Errorf("%s %s parsed but %s did not take it (origin %v)",
cmd, arg, path, v)
return
}
checked++
}
checkBatch := func(cases []flagCase) {
if len(cases) == 0 {
return
}
args := make([]string, 0, len(cases))
for _, c := range cases {
args = append(args, c.arg)
}
a := &App{ConfigPath: cfg}
// The error is deliberately ignored here: a flag the
// requirements refuse still arrives (its origin is the flag
// layer), and a flag the batch aborts before folding simply
// is not there. Either way the origins below sort them out.
_ = a.Handlers()[cmd](ctx, args)
for _, c := range cases {
v, ok := a.Settings().Value(c.path)
if !ok || v.Origin.Layer != settings.LayerFlag {
t.Errorf("%s --%s=%s parsed but %s did not take it (origin %v)",
cmd, name, val, s.Path, v)
// Only the flags the batch did not carry home get
// their own invocation, with the per-flag assertions.
checkSingle(c.path, c.arg)
continue
}
checked++
}
}
checkBatch(canonical)
for _, round := range aliasRounds {
checkBatch(round)
}
}
if checked < 100 {
t.Fatalf("only %d (command, flag) pairs checked; the probe is not reaching the commands", checked)
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -81,17 +81,19 @@ func TestManualMarkdownCoversEverySurface(t *testing.T) {
}
// TestGlobalFlagsAreDeclaredInMain holds GlobalFlags() against the
// switch in cmd/mcpx/main.go: a flag main() accepts must be on the
// list, and a flag on the list must be one main() accepts.
// switch in cli.Run (run.go): since #1980 stage 1 the entrypoint's
// global-flag switch lives in Run, not cmd/mcpx/main.go -- a flag Run
// accepts must be on the list, and a flag on the list must be one Run
// accepts.
func TestGlobalFlagsAreDeclaredInMain(t *testing.T) {
b, err := os.ReadFile("../../cmd/mcpx/main .go")
b, err := os.ReadFile("run .go")
if err != nil {
t.Fatal(err)
}
src := string(b)
for _, f := range cli.GlobalFlags() {
if !strings.Contains(src, "\"--"+f.Name+"\"") && !strings.Contains(src, "\"-"+f.Name+"\"") {
t.Errorf("global flag --%s is declared in GlobalFlags but main.go never switches on it", f.Name)
t.Errorf("global flag --%s is declared in GlobalFlags but cli.Run never switches on it", f.Name)
}
}
}
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.