From cf21abca65443967f97d319f3428fe0416edea7b Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 02:05:41 -0500 Subject: [PATCH 01/14] mcpx: shebang-first interpreter dispatch + script.interpreter + script.cwd (#2167) Dispatch order: (1) a #! shebang in the source or file, verbatim; (2) script.interpreter, a new settings-registry entry (command line, --interpreter/--shell aliases, reaching CLI, env, config, /v1/settings and MCP through the registry); (3) script.language / extension -- reserved for #1917, nothing diverts there yet; (4) the configured TypeScript runtime, unchanged when everything is unset. Dispatched runs get the harness posture without the harness: MCPX_ENDPOINT/MCPX_SESSION/MCPX_SOCKET via the existing env path, MCPX_RUNTIME naming the interpreter, MCPX_DISPATCH recording the choice, caller args after the script path, and the same stdout/stderr/exit/timeout machinery through runner and execsvc -- locally and via /v1/exec. The absence of the generated client, and that script.permissions profiles are JavaScript-runtime flags a shell interpreter cannot enforce, is stated once per run (Result.Notice and a line on stderr). script.cwd (caller|script|config|workdir, default caller) resolves the working directory for both dispatched and runtime runs. Open questions answered on #2167: a shebang beats script.runtime (it is an instruction inside the program); a snippet is written verbatim -- no Prelude, no .ts suffix -- to a temp file the interpreter runs; script.permissions does not apply to non-JS interpreters and the run says so. --- pkgs/mcpx/docs/configuration.md | 2 + pkgs/mcpx/docs/environment.md | 3 +- pkgs/mcpx/internal/cli/commands.go | 12 + pkgs/mcpx/internal/cli/exec.go | 5 + pkgs/mcpx/internal/daemon/routes_exec.go | 2 + pkgs/mcpx/internal/execsvc/execsvc.go | 16 +- pkgs/mcpx/internal/execsvc/execsvc_test.go | 32 ++ pkgs/mcpx/internal/runner/dispatch.go | 388 +++++++++++++++++++++ pkgs/mcpx/internal/runner/dispatch_test.go | 194 +++++++++++ pkgs/mcpx/internal/runner/runner.go | 40 ++- pkgs/mcpx/internal/settings/registry.go | 25 ++ pkgs/mcpx/internal/settings/scriptenv.go | 9 +- 12 files changed, 720 insertions(+), 8 deletions(-) create mode 100644 pkgs/mcpx/internal/runner/dispatch.go create mode 100644 pkgs/mcpx/internal/runner/dispatch_test.go diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index 63d87dc005..4a71427cd7 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -583,7 +583,9 @@ and a switch to turn the report off would have kept it quiet. | --- | --- | --- | --- | --- | --- | --- | --- | | `script.before` | source | *(empty)* | client | no | `--script-before` | `MCPX_SCRIPT_BEFORE` | runs first, ahead of the globals being installed | | `script.captureConsole` | bool | `true` | client | no | `--script-capture-console` | `MCPX_SCRIPT_CAPTURE_CONSOLE` | route console calls into the log | +| `script.cwd` | enum | `caller` | client | no | `--script-cwd` | `MCPX_SCRIPT_CWD` | where a script runs: caller, script, config or workdir | | `script.env` | list | *(empty)* | client | no | `--script-env`, `--env` | `MCPX_SCRIPT_ENV` | KEY=VALUE pairs added to the script's environment | +| `script.interpreter` | string | *(empty)* | client | no | `--script-interpreter`, `--interpreter`, `--shell` | `MCPX_SCRIPT_INTERPRETER` | command line that runs scripts instead of a JavaScript runtime | | `script.launcher` | source | *(empty)* | client | no | `--script-launcher` | `MCPX_SCRIPT_LAUNCHER` | replace the generated launcher entirely | | `script.onError` | source | *(empty)* | client | no | `--script-on-error` | `MCPX_SCRIPT_ON_ERROR` | runs when the script throws; the error still propagates | | `script.onSuccess` | source | *(empty)* | client | no | `--script-on-success` | `MCPX_SCRIPT_ON_SUCCESS` | runs when the script returns without throwing | diff --git a/pkgs/mcpx/docs/environment.md b/pkgs/mcpx/docs/environment.md index f15c597766..80d155d591 100644 --- a/pkgs/mcpx/docs/environment.md +++ b/pkgs/mcpx/docs/environment.md @@ -111,7 +111,8 @@ and read by name for that reason. | `MCPX_CONFIG_PATH` | `mcpx exec` / `mcpx run` | always | the nearest configuration file in effect, empty when there is none | the generated client (paths.config) | | `MCPX_SCRIPT_DIRS` | `mcpx exec` / `mcpx run` | always | the directories searched for named scripts, nearest first, colon-separated | the generated client (paths.scriptDirs) | | `MCPX_API_DECLARATION_SHA256` | `mcpx exec` / `mcpx run` | always | the fingerprint of a declared API's declaration, set on the child a declared API launches: PoolID hashes the environment, so editing the declaration replaces the pool instead of keeping a child started for the old one | the pool, as a pool identity input (api serve: PoolID hashes the server environment) | -| `MCPX_RUNTIME` | the runner, for every script | always | deno, bun or node | the generated client | +| `MCPX_RUNTIME` | the runner, for every script | always | deno, bun or node; on a dispatched run, the interpreter's name (sh, python3) | the generated client | +| `MCPX_DISPATCH` | the runner, for every script | only on a dispatched (non-JavaScript) run | how the interpreter was chosen: shebang or interpreter (script.interpreter) | the script itself, and anyone reading its environment | | `MCPX_ALLOW_READ` | the runner, for every script | only when the permissions allow reading files | 1: the client's file helpers may read. Without it they refuse, naming the permission, rather than leaving it to the sandbox | the generated client | | `MCPX_LOG_LEVEL` | `mcpx exec` / `mcpx run` | always | the lowest level the script's log keeps | the generated client; `mcpx` run inside the script or shell reads it as logging.level; also the setting `logging.level` | | `MCPX_LOG_SOURCE` | `mcpx exec` / `mcpx run` | always | which levels record a call site: a level name for that level and above, 0 for none | the generated client | diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index 116297f857..f60b1ec97c 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -935,6 +935,15 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error { if a.Settings().Given("script.permissions") { setPerms = a.Settings().String("script.permissions") } + // script.interpreter and script.cwd come from the resolved set like + // every other script.* value: flag aliases (--interpreter/--shell), + // env and config files all fold into the same two strings. + interpreterPref := set.String("script.interpreter") + cwdPolicy := set.String("script.cwd") + configDir := "" + if cp := configPathOf(cfg); cp != "" { + configDir = filepath.Dir(cp) + } opts := runner.Options{ // Set when something other than a terminal is collecting the output: // the MCP server, which has to return it rather than print it. @@ -943,6 +952,9 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error { GlobalsSource: globalsSrc, CaptureConsole: shape.captureConsole, Runtime: runtimePref, + Interpreter: interpreterPref, + CwdPolicy: cwdPolicy, + ConfigDir: configDir, Setup: rtSetup, Timeout: *timeout, Prelude: prelude, diff --git a/pkgs/mcpx/internal/cli/exec.go b/pkgs/mcpx/internal/cli/exec.go index 6474162531..842ef1f7bb 100644 --- a/pkgs/mcpx/internal/cli/exec.go +++ b/pkgs/mcpx/internal/cli/exec.go @@ -175,6 +175,8 @@ func (a *App) localStore() (*artifacts.Store, error) { func (a *App) localService(store *artifacts.Store, socket string) *execsvc.Service { set := a.Settings() lim := execsvc.DefaultLimits() + lim.Interpreter = set.String("script.interpreter") + lim.CwdPolicy = set.String("script.cwd") lim.Delivery = set.String("artifacts.delivery") lim.InlineMaxBytes = set.Bytes("artifacts.inlineMaxBytes") lim.ChunkBytes = set.Bytes("artifacts.chunkBytes") @@ -536,6 +538,9 @@ func (a *App) execOnDaemon(ctx context.Context, c *Client, fs *flag.FlagSet, inl opts := execsvc.Options{ Runtime: rf.runtime, Permissions: rf.permissions, + // From the resolved set, so --interpreter/--shell, the env and + // config files reach local and remote exec the same way. + Interpreter: a.Settings().String("script.interpreter"), Session: session, // The caller's context, not the daemon's. A remote daemon has a // different working directory and a different environment, and a diff --git a/pkgs/mcpx/internal/daemon/routes_exec.go b/pkgs/mcpx/internal/daemon/routes_exec.go index 754a4cb189..c7bf374e27 100644 --- a/pkgs/mcpx/internal/daemon/routes_exec.go +++ b/pkgs/mcpx/internal/daemon/routes_exec.go @@ -173,6 +173,8 @@ func (s *Server) ExecService() *execsvc.Service { lim.Timeout = set.Duration("exec.timeout") lim.Runtime = set.String("script.runtime") lim.Permissions = set.String("script.permissions") + lim.Interpreter = set.String("script.interpreter") + lim.CwdPolicy = set.String("script.cwd") // A malformed definition is reported by the run that needs it, rather // than failing every other route that builds a service. lim.Setup, lim.SetupErr = runner.ParseSetup(set.String("script.runtimes"), diff --git a/pkgs/mcpx/internal/execsvc/execsvc.go b/pkgs/mcpx/internal/execsvc/execsvc.go index 78a1c6116a..9c982d41fe 100644 --- a/pkgs/mcpx/internal/execsvc/execsvc.go +++ b/pkgs/mcpx/internal/execsvc/execsvc.go @@ -100,7 +100,11 @@ type TaskOptions struct { // caller declaring what it can receive is the thing that makes the script // identical everywhere. type Options struct { - Runtime string `json:"runtime,omitempty"` + Runtime string `json:"runtime,omitempty"` + // Interpreter is the script.interpreter command line for this run; + // empty takes the service's configured one. A shebang in the source + // or file beats it, as it beats every configuration surface. + Interpreter string `json:"interpreter,omitempty"` Timeout string `json:"timeout,omitempty"` Permissions string `json:"permissions,omitempty"` Placeholders map[string]any `json:"placeholders,omitempty"` @@ -261,6 +265,10 @@ type Limits struct { Timeout time.Duration Runtime string Permissions string + // Interpreter is the configured script.interpreter command line. + Interpreter string + // CwdPolicy is the configured script.cwd policy. + CwdPolicy string // Setup holds declared runtimes, the auto order and user profiles. Setup runner.Setup // SetupErr is why Setup could not be read; every run reports it. @@ -304,6 +312,9 @@ type Service struct { Local bool // Limits are the resolved settings. Limits Limits + // ConfigDir is the directory holding the configuration in force, + // for the script.cwd "config" policy on runs through this service. + ConfigDir string // WorkDir holds the generated client between runs, so the runtime's // module cache stays warm. Empty means a temporary directory per run. WorkDir string @@ -373,6 +384,9 @@ func (s *Service) Run(ctx context.Context, req Request, sink Sink) (*Result, err WorkDir: s.WorkDir, WorkRoot: s.WorkRoot, Runtime: firstNonEmpty(opts.Runtime, s.Limits.Runtime), + Interpreter: firstNonEmpty(opts.Interpreter, s.Limits.Interpreter), + CwdPolicy: s.Limits.CwdPolicy, + ConfigDir: s.ConfigDir, Setup: s.Limits.Setup, Timeout: timeout, Permissions: firstNonEmpty(opts.Permissions, s.Limits.Permissions), diff --git a/pkgs/mcpx/internal/execsvc/execsvc_test.go b/pkgs/mcpx/internal/execsvc/execsvc_test.go index 08ec50316d..bc0ba41c1a 100644 --- a/pkgs/mcpx/internal/execsvc/execsvc_test.go +++ b/pkgs/mcpx/internal/execsvc/execsvc_test.go @@ -470,3 +470,35 @@ for (let i = 0; i < 200; i++) { console.log("out " + i); emit({ i }); } t.Fatalf("the sink was entered concurrently %d times", n) } } + +// A shebang file runs through the shared service entry point -- the one +// /v1/exec and the CLI both pass through -- under its own interpreter, +// with output and exit code propagating (#2167). No JavaScript runtime +// is involved, so this test never skips for one. +func TestRunWithShebangFile(t *testing.T) { + svc := service(t, store(t)) + dir := t.TempDir() + path := filepath.Join(dir, "greet.sh") + if err := os.WriteFile(path, []byte("#!/bin/sh\necho execsvc-shebang-$MCPX_RUNTIME\nexit 5\n"), 0o755); err != nil { + t.Fatal(err) + } + var frames []execsvc.Frame + res, err := svc.RunWith(context.Background(), runner.Options{ + File: path, Permissions: "all", + }, execsvc.Options{}, func(f execsvc.Frame) error { + frames = append(frames, f) + return nil + }) + if err != nil { + t.Fatalf("RunWith: %v", err) + } + if res.ExitCode != 5 { + t.Errorf("ExitCode = %d, want 5", res.ExitCode) + } + if !strings.Contains(res.Stdout, "execsvc-shebang-sh") { + t.Errorf("Stdout = %q, want the script's output with MCPX_RUNTIME=sh", res.Stdout) + } + if res.Runtime != "sh" { + t.Errorf("Runtime = %q, want sh", res.Runtime) + } +} diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go new file mode 100644 index 0000000000..c530afab38 --- /dev/null +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -0,0 +1,388 @@ +// Interpreter dispatch for non-TypeScript scripts (#2167, parts 1-3 of +// #1919). +// +// Dispatch order, first match wins: +// +// 1. The source or file starts with a shebang (#!): that interpreter, +// verbatim. A shebang is an instruction inside the program itself, so +// it beats every configuration surface -- including script.runtime: +// a file that names its own interpreter is not overridden by a +// machine-wide preference for a different one. +// 2. script.interpreter: a configured command line, with the script +// path appended. +// 3. script.language / file extension: RESERVED for #1917. Nothing +// diverts here yet, by design -- the rank exists so the order does +// not change when it lands. +// 4. The configured TypeScript runtime: today's behaviour, unchanged +// when everything above is unset. +// +// A dispatched (non-JavaScript) run gets the harness posture, not the +// harness: MCPX_ENDPOINT / MCPX_SESSION / MCPX_SOCKET arrive through +// Options.Env exactly as they do for a TypeScript run, MCPX_RUNTIME +// names the interpreter, MCPX_ENTRY names the script, the caller's args +// follow the script path, and stdout/stderr/exit/timeout handling is the +// same machinery. What it does not get is the generated client -- there +// is no TypeScript module a shell script could import -- and that +// absence is stated once per run (Result.Notice, and a line on stderr), +// not left for the script to discover. script.permissions profiles are +// JavaScript-runtime flags; no shell interpreter can enforce them, so +// they are not applied to a dispatched run and the notice says so. +package runner + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "os" + "os/exec" + "path/filepath" + "strings" + "syscall" + "time" + + "github.com/dezren39/mcpx/internal/defaults" + "github.com/dezren39/mcpx/internal/logging" +) + +// CwdPolicies are the script.cwd values, in the order the setting +// documents them. +var CwdPolicies = []string{"caller", "script", "config", "workdir"} + +// ResolveCwd applies a script.cwd policy. callerDir is Options.Dir (the +// caller's explicit directory, empty meaning inherit), scriptPath the +// final entry script, configDir the directory holding the mcpx +// configuration in force, and workDir the runner's working directory +// for the run (where a snippet and the generated client live). +func ResolveCwd(policy, callerDir, scriptPath, configDir, workDir string) (string, error) { + switch policy { + case "", "caller": + return callerDir, nil + case "script": + if scriptPath == "" { + return "", errors.New("script.cwd=script but the run has no script file") + } + return filepath.Dir(scriptPath), nil + case "config": + if configDir == "" { + return "", errors.New("script.cwd=config but no configuration directory is known for this run") + } + return configDir, nil + case "workdir": + if workDir == "" { + return "", errors.New("script.cwd=workdir but the run has no working directory") + } + return workDir, nil + } + return "", fmt.Errorf("script.cwd %q is not one of %s", policy, strings.Join(CwdPolicies, ", ")) +} + +// dispatch is a resolved non-JavaScript interpreter invocation: the +// binary, the arguments that precede the script path, and where the +// decision came from. +type dispatch struct { + bin string + args []string + name string // interpreter name reported as the run's runtime + source string // "shebang" or "interpreter" +} + +// ParseShebang splits a #! line into the interpreter command it names. +// The /usr/bin/env form is unwrapped the way the kernel cannot: env's +// own flags (-S, -i) and VAR=value assignments are consumed, and what +// remains is the command. ok is false when the line is not a shebang. +func ParseShebang(line string) (tokens []string, ok bool) { + line = strings.TrimRight(line, "\r\n") + if !strings.HasPrefix(line, "#!") { + return nil, false + } + fields := strings.Fields(strings.TrimSpace(line[2:])) + if len(fields) == 0 { + return nil, true + } + if filepath.Base(fields[0]) == "env" { + fields = fields[1:] + for len(fields) > 0 { + f := fields[0] + if strings.HasPrefix(f, "-") || (strings.Contains(f, "=") && !strings.Contains(f, "/")) { + fields = fields[1:] + continue + } + break + } + } + return fields, true +} + +// SplitCommandLine splits a configured command line (script.interpreter) +// into words, honouring single and double quotes and backslash escapes. +// It is deliberately small: an interpreter command line is a handful of +// words, and anything fancier belongs in a script of its own. +func SplitCommandLine(s string) ([]string, error) { + var out []string + var word strings.Builder + quoted := byte(0) + escaped := false + started := false + flush := func() { + if started { + out = append(out, word.String()) + word.Reset() + started = false + } + } + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case escaped: + word.WriteByte(c) + escaped = false + started = true + case c == '\\' && quoted != '\'': + escaped = true + case quoted != 0: + if c == quoted { + quoted = 0 + } else { + word.WriteByte(c) + } + started = true + case c == '\'' || c == '"': + quoted = c + started = true + case c == ' ' || c == '\t': + flush() + default: + word.WriteByte(c) + started = true + } + } + if quoted != 0 { + return nil, fmt.Errorf("unterminated %q in command line %q", string(quoted), s) + } + flush() + return out, nil +} + +func firstLineOf(s string) string { + if i := strings.IndexByte(s, '\n'); i >= 0 { + return s[:i] + } + return s +} + +func fileFirstLine(path string) (string, error) { + f, err := os.Open(path) + if err != nil { + return "", err + } + defer f.Close() + line, err := bufio.NewReader(io.LimitReader(f, 8192)).ReadString('\n') + if err != nil && line == "" { + return "", err + } + return line, nil +} + +// decideDispatch applies ranks 1 and 2 of the dispatch order. A nil +// dispatch means the run falls through to the TypeScript runtime. +func decideDispatch(opts Options) (*dispatch, error) { + first := "" + if opts.Source != "" { + first = firstLineOf(opts.Source) + } else if opts.File != "" { + // A read error here is not fatal to the decision: the normal + // path surfaces it with better context when it opens the file + // for real. Only a shebang that IS readable diverts the run. + if l, err := fileFirstLine(opts.File); err == nil { + first = l + } + } + if tokens, ok := ParseShebang(first); ok { + if len(tokens) == 0 { + return nil, errors.New("runner: the script's shebang line (#!) names no interpreter") + } + return dispatchFromTokens("shebang", tokens) + } + if strings.TrimSpace(opts.Interpreter) != "" { + tokens, err := SplitCommandLine(opts.Interpreter) + if err != nil { + return nil, fmt.Errorf("runner: script.interpreter: %w", err) + } + if len(tokens) == 0 { + return nil, errors.New("runner: script.interpreter is set but names no command") + } + return dispatchFromTokens("interpreter", tokens) + } + return nil, nil +} + +func dispatchFromTokens(source string, tokens []string) (*dispatch, error) { + bin := tokens[0] + resolved := bin + if !strings.Contains(bin, "/") { + p, err := exec.LookPath(bin) + if err != nil { + return nil, fmt.Errorf("runner: %s interpreter %q not found on PATH: %w", source, bin, err) + } + resolved = p + } + return &dispatch{ + bin: resolved, + args: append([]string{}, tokens[1:]...), + name: filepath.Base(bin), + source: source, + }, nil +} + +// runDispatched executes a script under a non-JavaScript interpreter. +// The process machinery mirrors Run's: own process group, structured +// stderr streaming when a log writer is set, SIGTERM-then-SIGKILL on +// timeout, exit codes reported rather than errored. +func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, error) { + scriptPath := opts.File + workDir := opts.WorkDir + cleanup := func() {} + if scriptPath != "" { + abs, err := filepath.Abs(scriptPath) + if err != nil { + return nil, err + } + scriptPath = abs + } else { + // A snippet runs from a file of its own: no Prelude (that is + // TypeScript for the generated client) and no .ts suffix (the + // interpreter, not the name, decides what it is). + if workDir == "" { + wd, err := os.MkdirTemp("", "mcpx-run-") + if err != nil { + return nil, err + } + workDir = wd + cleanup = func() { _ = os.RemoveAll(wd) } + } else if err := os.MkdirAll(workDir, 0o700); err != nil { + return nil, err + } + sum := sha256sum([]byte(opts.Source)) + scriptPath = filepath.Join(workDir, "script-"+sum[:16]) + if err := writeIfChanged(scriptPath, opts.Source); err != nil { + cleanup() + return nil, err + } + } + defer cleanup() + if workDir == "" { + workDir = filepath.Dir(scriptPath) + } + + dir, err := ResolveCwd(opts.CwdPolicy, opts.Dir, scriptPath, opts.ConfigDir, workDir) + if err != nil { + return nil, err + } + + notice := fmt.Sprintf("mcpx: running under %s (%s dispatch): no generated mcpx client is "+ + "available to a non-JavaScript script, and script.permissions profiles are not enforced "+ + "for this interpreter; MCPX_ENDPOINT, MCPX_SESSION and MCPX_SOCKET are in the environment", + d.name, d.source) + + runCtx := ctx + var cancel context.CancelFunc + if opts.Timeout > 0 { + runCtx, cancel = context.WithTimeout(ctx, opts.Timeout) + defer cancel() + } + + args := append(append([]string{}, d.args...), scriptPath) + args = append(args, opts.Args...) + cmd := exec.Command(d.bin, args...) + cmd.Dir = dir + cmd.Env = append(os.Environ(), "MCPX_RUNTIME="+d.name, "MCPX_ENTRY="+scriptPath, "MCPX_DISPATCH="+d.source) + for k, v := range opts.Env { + cmd.Env = append(cmd.Env, k+"="+v) + } + if opts.Stdout != nil { + cmd.Stdout = opts.Stdout + } else { + cmd.Stdout = os.Stdout + } + var stderrDone chan struct{} + if opts.Log != nil { + pr, pw, perr := os.Pipe() + if perr != nil { + return nil, perr + } + cmd.Stderr = pw + passthrough := opts.Stderr + if passthrough == nil { + passthrough = os.Stderr + } + stderrDone = make(chan struct{}) + go func() { + defer close(stderrDone) + defer pr.Close() + _ = logging.Stream(pr, opts.Log, logging.StreamOptions{ + Enrich: opts.Enrich, + Passthrough: passthrough, + Collect: opts.CollectLogs, + Result: opts.OnResult, + Artifact: opts.OnArtifact, + }) + }() + // The notice rides the same stream as the script's own stderr, + // ahead of anything the script prints. + fmt.Fprintln(pw, notice) + defer func() { + pw.Close() + <-stderrDone + }() + } else if opts.Stderr != nil { + cmd.Stderr = opts.Stderr + fmt.Fprintln(opts.Stderr, notice) + } else { + cmd.Stderr = os.Stderr + fmt.Fprintln(os.Stderr, notice) + } + if opts.Stdin != nil { + cmd.Stdin = opts.Stdin + } else { + cmd.Stdin = os.Stdin + } + cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true} + + start := time.Now() + if err := cmd.Start(); err != nil { + return nil, fmt.Errorf("start %s: %w", d.name, err) + } + waitCh := make(chan error, 1) + go func() { waitCh <- cmd.Wait() }() + + res := &Result{Runtime: d.name, Script: scriptPath, Notice: notice} + select { + case <-runCtx.Done(): + res.TimedOut = true + if cmd.Process != nil { + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGTERM) + select { + case <-waitCh: + case <-time.After(defaults.ShutdownGrace): + _ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL) + <-waitCh + } + } + res.Duration = time.Since(start) + res.ExitCode = 124 + return res, fmt.Errorf("script timed out after %s", opts.Timeout) + case err := <-waitCh: + res.Duration = time.Since(start) + if err != nil { + var ee *exec.ExitError + if errors.As(err, &ee) { + res.ExitCode = ee.ExitCode() + return res, nil + } + return res, err + } + return res, nil + } +} diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go new file mode 100644 index 0000000000..aa18f7ae64 --- /dev/null +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -0,0 +1,194 @@ +package runner + +import ( + "bytes" + "context" + "os" + "path/filepath" + "strings" + "testing" +) + +func TestParseShebang(t *testing.T) { + for _, tc := range []struct { + line string + want []string + ok bool + }{ + {"#!/bin/sh", []string{"/bin/sh"}, true}, + {"#!/usr/bin/env python3", []string{"python3"}, true}, + {"#!/usr/bin/env -S python3 -u", []string{"python3", "-u"}, true}, + {"#!/usr/bin/env FOO=1 python3", []string{"python3"}, true}, + {"#!/bin/sh -e", []string{"/bin/sh", "-e"}, true}, + {"#!", nil, true}, + {"# just a comment", nil, false}, + {"echo hi", nil, false}, + {"", nil, false}, + } { + got, ok := ParseShebang(tc.line) + if ok != tc.ok || strings.Join(got, " ") != strings.Join(tc.want, " ") { + t.Errorf("ParseShebang(%q) = %v, %v; want %v, %v", tc.line, got, ok, tc.want, tc.ok) + } + } +} + +func TestSplitCommandLine(t *testing.T) { + got, err := SplitCommandLine(`python3 -u`) + if err != nil || strings.Join(got, " ") != "python3 -u" { + t.Errorf("plain: %v, %v", got, err) + } + got, err = SplitCommandLine(`"/opt/my dir/python" -x 'a b'`) + if err != nil || len(got) != 3 || got[0] != "/opt/my dir/python" || got[2] != "a b" { + t.Errorf("quoted: %v, %v", got, err) + } + if _, err := SplitCommandLine(`"unterminated`); err == nil { + t.Error("unterminated quote: want an error") + } +} + +func TestResolveCwdPolicies(t *testing.T) { + script := filepath.Join("/proj", "scripts", "a.sh") + for _, tc := range []struct { + policy, want string + wantErr bool + }{ + {"", "/caller", false}, + {"caller", "/caller", false}, + {"script", "/proj/scripts", false}, + {"config", "/cfg", false}, + {"workdir", "/work", false}, + {"bogus", "", true}, + } { + got, err := ResolveCwd(tc.policy, "/caller", script, "/cfg", "/work") + if tc.wantErr { + if err == nil { + t.Errorf("policy %q: want an error", tc.policy) + } + continue + } + if err != nil || got != tc.want { + t.Errorf("policy %q = %q, %v; want %q", tc.policy, got, err, tc.want) + } + } + if _, err := ResolveCwd("config", "/caller", script, "", "/work"); err == nil { + t.Error("config with no config directory: want an explicit error") + } +} + +func writeScript(t *testing.T, dir, name, body string) string { + t.Helper() + p := filepath.Join(dir, name) + if err := os.WriteFile(p, []byte(body), 0o755); err != nil { + t.Fatal(err) + } + return p +} + +func TestRunShebangFileRunsUnderItsInterpreter(t *testing.T) { + dir := t.TempDir() + f := writeScript(t, dir, "hello.sh", + "#!/bin/sh\necho \"out-$MCPX_RUNTIME-$1\"\necho \"client=[$MCPX_CLIENT]\"\necho \"ep=$MCPX_ENDPOINT\"\nexit 3\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: f, Args: []string{"hello"}, + Env: map[string]string{"MCPX_ENDPOINT": "http://example.invalid:9999"}, + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("Run: %v", err) + } + if res.ExitCode != 3 { + t.Errorf("ExitCode = %d, want 3 (propagated, not errored)", res.ExitCode) + } + if res.Runtime != "sh" || res.Client != "" { + t.Errorf("Result = %+v, want Runtime sh and no client", res) + } + out := stdout.String() + for _, want := range []string{"out-sh-hello", "client=[]", "ep=http://example.invalid:9999"} { + if !strings.Contains(out, want) { + t.Errorf("stdout %q missing %q", out, want) + } + } + if res.Notice == "" || !strings.Contains(stderr.String(), "no generated mcpx client") { + t.Errorf("the missing client must be stated once: Notice=%q stderr=%q", res.Notice, stderr.String()) + } +} + +func TestRunShebangSnippet(t *testing.T) { + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + Source: "#!/bin/sh\necho snippet-ok\n", + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("Run: %v", err) + } + if res.ExitCode != 0 || !strings.Contains(stdout.String(), "snippet-ok") { + t.Errorf("res=%+v stdout=%q", res, stdout.String()) + } +} + +func TestDispatchPrecedenceShebangBeatsInterpreterBeatsRuntime(t *testing.T) { + dir := t.TempDir() + // A bogus configured interpreter would fail resolution if it were + // consulted; the shebang must win without consulting it. + f := writeScript(t, dir, "wins.sh", "#!/bin/sh\necho shebang-won\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: f, Interpreter: "mcpx-no-such-interpreter-3201", + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil || !strings.Contains(stdout.String(), "shebang-won") { + t.Fatalf("shebang precedence: res=%+v err=%v stdout=%q", res, err, stdout.String()) + } + // No shebang: the configured interpreter runs the file. + g := writeScript(t, dir, "plain.txt", "echo interpreter-won\n") + stdout.Reset() + res, err = Run(context.Background(), Options{ + File: g, Interpreter: "sh", + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil || !strings.Contains(stdout.String(), "interpreter-won") || res.Runtime != "sh" { + t.Fatalf("interpreter dispatch: res=%+v err=%v stdout=%q", res, err, stdout.String()) + } +} + +func TestRunInterpreterSnippetWithoutShebang(t *testing.T) { + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + Source: "echo via-interpreter\n", Interpreter: "sh", + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil || res.ExitCode != 0 || !strings.Contains(stdout.String(), "via-interpreter") { + t.Fatalf("res=%+v err=%v stdout=%q", res, err, stdout.String()) + } +} + +func TestRunCwdPolicyScript(t *testing.T) { + base := t.TempDir() + scriptDir := filepath.Join(base, "scripts") + if err := os.MkdirAll(scriptDir, 0o755); err != nil { + t.Fatal(err) + } + f := writeScript(t, scriptDir, "where.sh", "#!/bin/sh\npwd\n") + run := func(policy string) string { + var stdout, stderr bytes.Buffer + _, err := Run(context.Background(), Options{ + File: f, Dir: base, CwdPolicy: policy, + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("policy %s: %v", policy, err) + } + got, _ := filepath.EvalSymlinks(strings.TrimSpace(stdout.String())) + return got + } + wantScript, _ := filepath.EvalSymlinks(scriptDir) + wantBase, _ := filepath.EvalSymlinks(base) + if got := run("script"); got != wantScript { + t.Errorf("script.cwd=script: pwd = %q, want %q", got, wantScript) + } + if got := run("caller"); got != wantBase { + t.Errorf("script.cwd=caller: pwd = %q, want %q", got, wantBase) + } +} diff --git a/pkgs/mcpx/internal/runner/runner.go b/pkgs/mcpx/internal/runner/runner.go index 49293bd419..5a200d0069 100644 --- a/pkgs/mcpx/internal/runner/runner.go +++ b/pkgs/mcpx/internal/runner/runner.go @@ -85,6 +85,17 @@ type Options struct { Export string // Permissions is the sandbox setting; empty means wide open. Permissions string + // Interpreter is the script.interpreter setting: a command line that + // runs the script instead of a JavaScript runtime, when the script + // does not name its own interpreter with a shebang. See dispatch.go + // for the full order. + Interpreter string + // CwdPolicy is the script.cwd setting: caller, script, config or + // workdir. Empty means caller. + CwdPolicy string + // ConfigDir is the directory holding the configuration in force, + // for CwdPolicy "config". Empty makes that policy an explicit error. + ConfigDir string // GlobalsSource is the ambient declaration file written beside the client. GlobalsSource string // CaptureConsole mirrors console output into the record stream. @@ -148,6 +159,10 @@ type Result struct { Script string Client string TimedOut bool + // Notice is set on a dispatched (non-JavaScript) run: the one + // statement of what the run does not have (a generated client, + // enforced permission profiles). See dispatch.go. + Notice string // Stdout is captured only when Options.Stdout is nil. Stdout string } @@ -159,6 +174,15 @@ func Run(ctx context.Context, opts Options) (*Result, error) { if opts.Source == "" && opts.File == "" { return nil, errors.New("runner: need Source or File") } + // Dispatch ranks 1-2 (#2167): a shebang or a configured interpreter + // runs the script under that interpreter, before any JavaScript + // runtime is considered. Rank 3 (language/extension) is reserved + // for #1917; rank 4 is everything below, unchanged. + if d, derr := decideDispatch(opts); derr != nil { + return nil, derr + } else if d != nil { + return runDispatched(ctx, opts, d) + } rt, err := Resolve(opts.Runtime, opts.Permissions, opts.Setup) if err != nil { return nil, err @@ -291,11 +315,17 @@ func Run(ctx context.Context, opts Options) (*Result, error) { args := append(rt.Args(scriptPath), opts.Args...) cmd := exec.Command(rt.Bin, args...) - // Inherit the caller's working directory rather than the script's. A - // relative path in a script should mean what it means on the command line; - // the client import still resolves against the script file, because ESM - // resolves relative specifiers against the importing module. - cmd.Dir = opts.Dir + // The script.cwd policy decides the working directory. The default, + // caller, inherits the caller's directory rather than the script's: + // a relative path in a script should mean what it means on the + // command line; the client import still resolves against the script + // file, because ESM resolves relative specifiers against the + // importing module. + dir, derr := ResolveCwd(opts.CwdPolicy, opts.Dir, scriptPath, opts.ConfigDir, workDir) + if derr != nil { + return nil, derr + } + cmd.Dir = dir // The kind, not the configured name: a script branching on its runtime // cares whether it is under Deno, not what somebody called the binary. cmd.Env = append(os.Environ(), "MCPX_RUNTIME="+rt.Kind) diff --git a/pkgs/mcpx/internal/settings/registry.go b/pkgs/mcpx/internal/settings/registry.go index 24ce4c611a..d978342b27 100644 --- a/pkgs/mcpx/internal/settings/registry.go +++ b/pkgs/mcpx/internal/settings/registry.go @@ -259,6 +259,31 @@ func scriptSettings() []Setting { "introduces flags passed through verbatim and takes the rest of the " + "value. The default is wide open because the scripts are yours.", }, + { + Path: "script.interpreter", Commands: runCommands, Kind: KindString, Default: "", + Scope: ScopeClient, + FlagAliases: []string{"interpreter", "shell"}, + Name: "Interpreter", Short: "command line that runs scripts instead of a JavaScript runtime", + Long: "Dispatch order for a script: a #! shebang in the source or file wins, " + + "then this command line (the script path is appended), then the configured " + + "TypeScript runtime (script.runtime). A non-JavaScript interpreter gets " + + "MCPX_ENDPOINT, MCPX_SESSION and MCPX_SOCKET in its environment and the " + + "same output, exit-code and timeout handling, but no generated client, " + + "and script.permissions profiles -- JavaScript runtime flags -- are not " + + "enforced for it. --shell and --interpreter are aliases of this one " + + "setting; there is no per-language flag family.", + }, + { + Path: "script.cwd", Commands: runCommands, Kind: KindEnum, Default: "caller", + Scope: ScopeClient, + Enum: []string{"caller", "script", "config", "workdir"}, + Name: "Script working directory", Short: "where a script runs: caller, script, config or workdir", + Long: "caller: the directory the caller runs in (Options.Dir, or inherited) -- " + + "the historical behaviour. script: the directory holding the script file. " + + "config: the directory holding the mcpx configuration in force. workdir: " + + "the runner's working directory for the run, where snippets and the " + + "generated client live.", + }, { Path: "script.profiles", Commands: runCommands, Kind: KindString, Default: "", Scope: ScopeClient, diff --git a/pkgs/mcpx/internal/settings/scriptenv.go b/pkgs/mcpx/internal/settings/scriptenv.go index 452cfbd3a5..d5a0bf7be3 100644 --- a/pkgs/mcpx/internal/settings/scriptenv.go +++ b/pkgs/mcpx/internal/settings/scriptenv.go @@ -250,9 +250,16 @@ func ScriptEnv() []EnvVar { { Name: "MCPX_RUNTIME", SetBy: []Setter{SetByRunner}, - Meaning: "deno, bun or node", + Meaning: "deno, bun or node; on a dispatched run, the interpreter's name (sh, python3)", ReadBy: client, }, + { + Name: "MCPX_DISPATCH", + SetBy: []Setter{SetByRunner}, + When: "only on a dispatched (non-JavaScript) run", + Meaning: "how the interpreter was chosen: shebang or interpreter (script.interpreter)", + ReadBy: "the script itself, and anyone reading its environment", + }, { Name: "MCPX_ALLOW_READ", SetBy: []Setter{SetByRunner}, From 2cd05515aca2a24153d28f0627f52edca6977b24 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 02:36:45 -0500 Subject: [PATCH 02/14] fix(mcpx): address Codex findings on the shebang dispatch PR (#2167) Four P2 findings on cf21abca, one commit each in spirit: (1) env shebang assignments (#!/usr/bin/env -S MODE=prod sh) were discarded by ParseShebang; ParseShebangEnv now returns them and the dispatch carries them into the child environment ahead of the MCPX_* variables. (2) The daemon ExecService never populated Service.ConfigDir, so script.cwd=config failed every /v1/exec run; it now takes the directory of the config the daemon loaded. (3) Remote CLI exec dropped the caller script.cwd policy; execsvc.Options gains a request-level cwdPolicy, Service.Run prefers it over the service policy, and execOnDaemon forwards the caller resolved value. (4) A shebang naming a JavaScript runtime bypassed the generated launcher, so a default-export script never ran its entry point; a plain JS-runtime shebang (no extra arguments) now goes through the harness with that runtime as the preference, while a JS shebang with extra arguments keeps raw dispatch. Tests: ParseShebangEnv cases, an env-assignment end-to-end run, decideDispatch routing, and a node .mjs default-export harness run. --- pkgs/mcpx/internal/cli/exec.go | 7 +- pkgs/mcpx/internal/daemon/routes_exec.go | 18 +++- pkgs/mcpx/internal/execsvc/execsvc.go | 10 +- pkgs/mcpx/internal/runner/dispatch.go | 104 +++++++++++++++++---- pkgs/mcpx/internal/runner/dispatch_test.go | 85 +++++++++++++++++ pkgs/mcpx/internal/runner/runner.go | 6 +- 6 files changed, 203 insertions(+), 27 deletions(-) diff --git a/pkgs/mcpx/internal/cli/exec.go b/pkgs/mcpx/internal/cli/exec.go index 842ef1f7bb..bf2af5ee45 100644 --- a/pkgs/mcpx/internal/cli/exec.go +++ b/pkgs/mcpx/internal/cli/exec.go @@ -541,7 +541,12 @@ func (a *App) execOnDaemon(ctx context.Context, c *Client, fs *flag.FlagSet, inl // From the resolved set, so --interpreter/--shell, the env and // config files reach local and remote exec the same way. Interpreter: a.Settings().String("script.interpreter"), - Session: session, + // The caller's script.cwd policy travels with the request; the + // daemon's own policy is only the fallback for callers that send + // none. Without this a caller's --script-cwd (or env/config + // value) was silently ignored by remote runs. + CwdPolicy: a.Settings().String("script.cwd"), + Session: session, // The caller's context, not the daemon's. A remote daemon has a // different working directory and a different environment, and a // script that reads either should see the one belonging to whoever diff --git a/pkgs/mcpx/internal/daemon/routes_exec.go b/pkgs/mcpx/internal/daemon/routes_exec.go index c7bf374e27..84bfa2d833 100644 --- a/pkgs/mcpx/internal/daemon/routes_exec.go +++ b/pkgs/mcpx/internal/daemon/routes_exec.go @@ -186,11 +186,21 @@ func (s *Server) ExecService() *execsvc.Service { lim.ChunkBytes = set.Bytes("artifacts.chunkBytes") lim.InterceptImages = set.Bool("artifacts.interceptImages") + // script.cwd=config resolves against the directory holding the + // configuration this daemon loaded -- the same cfg.Path the info + // file and the resolve route report. Without it every /v1/exec run + // under that policy fails in ResolveCwd before the script starts. + configDir := "" + if cfg := s.currentConfig(); cfg != nil && cfg.Path != "" { + configDir = filepath.Dir(cfg.Path) + } + return &execsvc.Service{ - Src: registrySource{reg: s.reg, endpoint: s.endpoint}, - Store: store, - Endpoint: s.endpoint, - Socket: s.paths.Socket, + Src: registrySource{reg: s.reg, endpoint: s.endpoint}, + Store: store, + Endpoint: s.endpoint, + Socket: s.paths.Socket, + ConfigDir: configDir, // The script the daemon runs is on the daemon's machine by // definition, so a path it hands to artifact() is a path the store // can link rather than read. diff --git a/pkgs/mcpx/internal/execsvc/execsvc.go b/pkgs/mcpx/internal/execsvc/execsvc.go index 9c982d41fe..6aeae88728 100644 --- a/pkgs/mcpx/internal/execsvc/execsvc.go +++ b/pkgs/mcpx/internal/execsvc/execsvc.go @@ -104,7 +104,13 @@ type Options struct { // Interpreter is the script.interpreter command line for this run; // empty takes the service's configured one. A shebang in the source // or file beats it, as it beats every configuration surface. - Interpreter string `json:"interpreter,omitempty"` + Interpreter string `json:"interpreter,omitempty"` + // CwdPolicy is the caller's script.cwd policy for this run; empty + // takes the service's configured one. The CLI resolves its own set + // (flag aliases, env, config) and forwards the result, so a remote + // run honours the caller's policy instead of silently substituting + // the daemon's. + CwdPolicy string `json:"cwdPolicy,omitempty"` Timeout string `json:"timeout,omitempty"` Permissions string `json:"permissions,omitempty"` Placeholders map[string]any `json:"placeholders,omitempty"` @@ -385,7 +391,7 @@ func (s *Service) Run(ctx context.Context, req Request, sink Sink) (*Result, err WorkRoot: s.WorkRoot, Runtime: firstNonEmpty(opts.Runtime, s.Limits.Runtime), Interpreter: firstNonEmpty(opts.Interpreter, s.Limits.Interpreter), - CwdPolicy: s.Limits.CwdPolicy, + CwdPolicy: firstNonEmpty(opts.CwdPolicy, s.Limits.CwdPolicy), ConfigDir: s.ConfigDir, Setup: s.Limits.Setup, Timeout: timeout, diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index c530afab38..49de380233 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -7,7 +7,12 @@ // verbatim. A shebang is an instruction inside the program itself, so // it beats every configuration surface -- including script.runtime: // a file that names its own interpreter is not overridden by a -// machine-wide preference for a different one. +// machine-wide preference for a different one. One exception: a +// shebang naming a JavaScript runtime (deno, bun, node, or a +// declared runtime) with no extra arguments goes through the +// harness with that runtime, because raw dispatch would skip the +// generated launcher and the script's default export would never +// be called. // 2. script.interpreter: a configured command line, with the script // path appended. // 3. script.language / file extension: RESERVED for #1917. Nothing @@ -84,35 +89,68 @@ func ResolveCwd(policy, callerDir, scriptPath, configDir, workDir string) (strin type dispatch struct { bin string args []string - name string // interpreter name reported as the run's runtime - source string // "shebang" or "interpreter" + env []string // VAR=value assignments an env shebang carried + name string // interpreter name reported as the run's runtime + source string // "shebang" or "interpreter" } // ParseShebang splits a #! line into the interpreter command it names. // The /usr/bin/env form is unwrapped the way the kernel cannot: env's -// own flags (-S, -i) and VAR=value assignments are consumed, and what -// remains is the command. ok is false when the line is not a shebang. +// own flags (-S, -i) are consumed, and what remains is the command. ok +// is false when the line is not a shebang. func ParseShebang(line string) (tokens []string, ok bool) { + tokens, _, ok = ParseShebangEnv(line) + return tokens, ok +} + +// ParseShebangEnv is ParseShebang that also returns the VAR=value +// assignments an env shebang carried (#!/usr/bin/env MODE=prod sh). +// env(1) would set them for the command it runs; dropping them would +// run the script under a different environment than its own first line +// specifies, silently, so the dispatch carries them into the child +// environment instead. +func ParseShebangEnv(line string) (tokens []string, env []string, ok bool) { line = strings.TrimRight(line, "\r\n") if !strings.HasPrefix(line, "#!") { - return nil, false + return nil, nil, false } fields := strings.Fields(strings.TrimSpace(line[2:])) if len(fields) == 0 { - return nil, true + return nil, nil, true } if filepath.Base(fields[0]) == "env" { fields = fields[1:] for len(fields) > 0 { f := fields[0] - if strings.HasPrefix(f, "-") || (strings.Contains(f, "=") && !strings.Contains(f, "/")) { + if strings.HasPrefix(f, "-") { + fields = fields[1:] + continue + } + if strings.Contains(f, "=") && !strings.Contains(f, "/") { + env = append(env, f) fields = fields[1:] continue } break } } - return fields, true + return fields, env, true +} + +// isJSRuntimeName reports whether a shebang's command names a +// JavaScript runtime mcpx can drive through the harness: a known kind +// (deno, bun, node), by name or by path, or a name declared under +// script.runtimes. +func isJSRuntimeName(setup Setup, name string) bool { + if _, ok := setup.Runtimes[name]; ok { + return true + } + base := filepath.Base(name) + if _, ok := setup.Runtimes[base]; ok { + return true + } + stem := strings.TrimSuffix(base, filepath.Ext(base)) + return knownKind(strings.ToLower(stem)) } // SplitCommandLine splits a configured command line (script.interpreter) @@ -186,8 +224,20 @@ func fileFirstLine(path string) (string, error) { } // decideDispatch applies ranks 1 and 2 of the dispatch order. A nil -// dispatch means the run falls through to the TypeScript runtime. -func decideDispatch(opts Options) (*dispatch, error) { +// dispatch means the run falls through to the TypeScript runtime; the +// second return value then names the runtime a JavaScript shebang +// chose, so the harness honours the shebang's choice instead of the +// configured preference. +// +// A shebang naming a JavaScript runtime, with no extra arguments, is +// that exception: raw dispatch would bypass the generated launcher, so +// a script whose default export is the program would run without its +// entry point ever being called (the pkgs/mcpx/AGENTS.md script +// contract). The harness path below keeps the contract and takes the +// shebang's runtime as its preference. A JavaScript shebang WITH extra +// arguments keeps raw dispatch: the arguments are part of the command +// the file names, and the harness has nowhere to put them. +func decideDispatch(opts Options) (*dispatch, string, error) { first := "" if opts.Source != "" { first = firstLineOf(opts.Source) @@ -199,23 +249,35 @@ func decideDispatch(opts Options) (*dispatch, error) { first = l } } - if tokens, ok := ParseShebang(first); ok { + if tokens, env, ok := ParseShebangEnv(first); ok { if len(tokens) == 0 { - return nil, errors.New("runner: the script's shebang line (#!) names no interpreter") + return nil, "", errors.New("runner: the script's shebang line (#!) names no interpreter") } - return dispatchFromTokens("shebang", tokens) + if len(tokens) == 1 && isJSRuntimeName(opts.Setup, tokens[0]) { + return nil, tokens[0], nil + } + d, err := dispatchFromTokens("shebang", tokens) + if err != nil { + return nil, "", err + } + d.env = env + return d, "", nil } if strings.TrimSpace(opts.Interpreter) != "" { tokens, err := SplitCommandLine(opts.Interpreter) if err != nil { - return nil, fmt.Errorf("runner: script.interpreter: %w", err) + return nil, "", fmt.Errorf("runner: script.interpreter: %w", err) } if len(tokens) == 0 { - return nil, errors.New("runner: script.interpreter is set but names no command") + return nil, "", errors.New("runner: script.interpreter is set but names no command") + } + d, err := dispatchFromTokens("interpreter", tokens) + if err != nil { + return nil, "", err } - return dispatchFromTokens("interpreter", tokens) + return d, "", nil } - return nil, nil + return nil, "", nil } func dispatchFromTokens(source string, tokens []string) (*dispatch, error) { @@ -297,7 +359,11 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err args = append(args, opts.Args...) cmd := exec.Command(d.bin, args...) cmd.Dir = dir - cmd.Env = append(os.Environ(), "MCPX_RUNTIME="+d.name, "MCPX_ENTRY="+scriptPath, "MCPX_DISPATCH="+d.source) + // The shebang's own VAR=value assignments come first of the + // additions: env(1) would have set them, and the MCPX_* variables + // after them win any collision, as the run's own contract should. + cmd.Env = append(os.Environ(), d.env...) + cmd.Env = append(cmd.Env, "MCPX_RUNTIME="+d.name, "MCPX_ENTRY="+scriptPath, "MCPX_DISPATCH="+d.source) for k, v := range opts.Env { cmd.Env = append(cmd.Env, k+"="+v) } diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index aa18f7ae64..57bef5dbef 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -4,6 +4,9 @@ import ( "bytes" "context" "os" + "os/exec" + + "github.com/dezren39/mcpx/internal/codegen" "path/filepath" "strings" "testing" @@ -32,6 +35,88 @@ func TestParseShebang(t *testing.T) { } } +func TestParseShebangEnvAssignments(t *testing.T) { + tokens, env, ok := ParseShebangEnv("#!/usr/bin/env -S MODE=prod sh") + if !ok || strings.Join(tokens, " ") != "sh" || strings.Join(env, " ") != "MODE=prod" { + t.Errorf("ParseShebangEnv = %v, %v, %v; want [sh], [MODE=prod], true", tokens, env, ok) + } + tokens, env, ok = ParseShebangEnv("#!/usr/bin/env FOO=1 BAR=two python3 -u") + if !ok || strings.Join(tokens, " ") != "python3 -u" || strings.Join(env, " ") != "FOO=1 BAR=two" { + t.Errorf("ParseShebangEnv = %v, %v, %v; want [python3 -u], [FOO=1 BAR=two], true", tokens, env, ok) + } + // A non-env shebang has no assignments to preserve. + _, env, _ = ParseShebangEnv("#!/bin/sh") + if len(env) != 0 { + t.Errorf("env = %v, want none", env) + } +} + +func TestRunEnvShebangAssignmentsReachTheScript(t *testing.T) { + dir := t.TempDir() + f := writeScript(t, dir, "mode.sh", + "#!/usr/bin/env -S MODE=prod sh\necho \"mode=$MODE\"\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: f, Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("Run: %v", err) + } + if res.ExitCode != 0 || !strings.Contains(stdout.String(), "mode=prod") { + t.Errorf("res=%+v stdout=%q; the shebang's MODE=prod assignment must reach the script", res, stdout.String()) + } +} + +func TestDecideDispatchJSRuntimeShebang(t *testing.T) { + // A plain JavaScript-runtime shebang must NOT divert to raw + // dispatch: the harness runs it, under the shebang's runtime. + d, jsRuntime, err := decideDispatch(Options{Source: "#!/usr/bin/env node\nexport default () => 1\n"}) + if err != nil || d != nil || jsRuntime != "node" { + t.Errorf("decideDispatch(node shebang) = %v, %q, %v; want nil, \"node\", nil", d, jsRuntime, err) + } + // A JavaScript shebang with extra arguments keeps raw dispatch: + // the arguments are part of the named command. + d, jsRuntime, err = decideDispatch(Options{Source: "#!/usr/bin/env -S node --inspect main.ts\n"}) + if err != nil || d == nil || jsRuntime != "" { + t.Errorf("decideDispatch(node --inspect) = %v, %q, %v; want a dispatch, \"\", nil", d, jsRuntime, err) + } + // A non-JavaScript shebang dispatches as before. + d, jsRuntime, err = decideDispatch(Options{Source: "#!/bin/sh\necho hi\n"}) + if err != nil || d == nil || jsRuntime != "" { + t.Errorf("decideDispatch(sh) = %v, %q, %v; want a dispatch, \"\", nil", d, jsRuntime, err) + } +} + +func TestRunJSRuntimeShebangKeepsHarness(t *testing.T) { + // The Codex finding on PR #2611, end to end: a Node .mjs file whose + // shebang names node must still go through the generated launcher, + // so its default export is called and its return value printed -- + // raw dispatch ran the file as a plain script and produced neither. + if _, err := exec.LookPath("node"); err != nil { + t.Skip("node is not installed") + } + dir := t.TempDir() + f := writeScript(t, dir, "main.mjs", + "#!/usr/bin/env node\nexport default () => \"expected-result\"\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: f, Stdout: &stdout, Stderr: &stderr, + // The launcher imports the generated client; an empty one does + // not export what it names, which is a failure of the fixture, + // not of the run. + ClientSource: codegen.Module(nil, "", ""), + }) + if err != nil { + t.Fatalf("Run: %v (stderr %q)", err, stderr.String()) + } + if res.ExitCode != 0 || !strings.Contains(stdout.String(), "expected-result") { + t.Errorf("res=%+v stdout=%q stderr=%q; the harness must call the default export and print its result", res, stdout.String(), stderr.String()) + } + if res.Runtime != "node" { + t.Errorf("Runtime = %q, want node (the shebang's choice)", res.Runtime) + } +} + func TestSplitCommandLine(t *testing.T) { got, err := SplitCommandLine(`python3 -u`) if err != nil || strings.Join(got, " ") != "python3 -u" { diff --git a/pkgs/mcpx/internal/runner/runner.go b/pkgs/mcpx/internal/runner/runner.go index 5a200d0069..5c6f020f30 100644 --- a/pkgs/mcpx/internal/runner/runner.go +++ b/pkgs/mcpx/internal/runner/runner.go @@ -178,10 +178,14 @@ func Run(ctx context.Context, opts Options) (*Result, error) { // runs the script under that interpreter, before any JavaScript // runtime is considered. Rank 3 (language/extension) is reserved // for #1917; rank 4 is everything below, unchanged. - if d, derr := decideDispatch(opts); derr != nil { + if d, jsRuntime, derr := decideDispatch(opts); derr != nil { return nil, derr } else if d != nil { return runDispatched(ctx, opts, d) + } else if jsRuntime != "" { + // A JavaScript shebang chose this runtime (rank 1); the harness + // below runs under it instead of the configured preference. + opts.Runtime = jsRuntime } rt, err := Resolve(opts.Runtime, opts.Permissions, opts.Setup) if err != nil { From 534a14a5e1039d3067887d60631e01933267ab7a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 03:02:02 -0500 Subject: [PATCH 03/14] fix(mcpx): honour env shebang options -u and -i (#2167) Fifth Codex P2 on 2cd05515 (/pull/2611): the env unwrapping in ParseShebangEnv dropped every option without consuming its operand, so "#!/usr/bin/env -S -u SECRET sh" dispatched SECRET instead of sh, and "-i" was silently ignored, leaving the child with the inherited environment. parseShebang now consumes env's options the way env(1) does: -u NAME / --unset[=NAME] / -uNAME remove a name from the inherited environment, -i / --ignore-environment / a bare "-" start from an empty one, -C DIR / --chdir[=DIR] consume their operand, -S keeps splitting as before, and "--" ends the options. The dispatch carries the result, and the child environment is built from os.Environ() (or nothing) minus the unset names, then the assignments, then the MCPX_* variables, so the run's own contract still wins. Tests: parser cases for each form, filterEnv, and end-to-end runs for -u and -i against the inherited environment. Co-authored-by: CommandCodeBot --- pkgs/mcpx/internal/runner/dispatch.go | 124 +++++++++++++++++---- pkgs/mcpx/internal/runner/dispatch_test.go | 67 +++++++++++ 2 files changed, 167 insertions(+), 24 deletions(-) diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 49de380233..b9641dcbc9 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -90,17 +90,19 @@ type dispatch struct { bin string args []string env []string // VAR=value assignments an env shebang carried + unset []string // names an env shebang removed from the environment (-u) + clear bool // an env shebang asked for an empty environment (-i) name string // interpreter name reported as the run's runtime source string // "shebang" or "interpreter" } // ParseShebang splits a #! line into the interpreter command it names. // The /usr/bin/env form is unwrapped the way the kernel cannot: env's -// own flags (-S, -i) are consumed, and what remains is the command. ok -// is false when the line is not a shebang. +// own options are consumed, and what remains is the command. ok is +// false when the line is not a shebang. func ParseShebang(line string) (tokens []string, ok bool) { - tokens, _, ok = ParseShebangEnv(line) - return tokens, ok + sp, ok := parseShebang(line) + return sp.tokens, ok } // ParseShebangEnv is ParseShebang that also returns the VAR=value @@ -110,31 +112,98 @@ func ParseShebang(line string) (tokens []string, ok bool) { // specifies, silently, so the dispatch carries them into the child // environment instead. func ParseShebangEnv(line string) (tokens []string, env []string, ok bool) { + sp, ok := parseShebang(line) + return sp.tokens, sp.set, ok +} + +// shebangEnv is a parsed shebang: the command it names, plus the +// environment changes an env(1) shebang asked for and the kernel never +// got to apply. +type shebangEnv struct { + tokens []string + set []string // VAR=value assignments + unset []string // names removed from the inherited environment (-u) + clear bool // start from an empty environment (-i) +} + +// parseShebang reads a #! line. Options of an env(1) shebang are +// consumed as env itself would consume them, including the operand of +// -u NAME and -C DIR, so that what remains is the command: without +// that, "#!/usr/bin/env -S -u SECRET sh" would try to run SECRET. +func parseShebang(line string) (shebangEnv, bool) { line = strings.TrimRight(line, "\r\n") if !strings.HasPrefix(line, "#!") { - return nil, nil, false + return shebangEnv{}, false } fields := strings.Fields(strings.TrimSpace(line[2:])) if len(fields) == 0 { - return nil, nil, true + return shebangEnv{}, true } + var sp shebangEnv if filepath.Base(fields[0]) == "env" { fields = fields[1:] + options: for len(fields) > 0 { f := fields[0] - if strings.HasPrefix(f, "-") { + switch { + case f == "-i" || f == "--ignore-environment" || f == "-": + sp.clear = true fields = fields[1:] - continue - } - if strings.Contains(f, "=") && !strings.Contains(f, "/") { - env = append(env, f) + case f == "--": + fields = fields[1:] + break options + case f == "-u" || f == "--unset" || f == "-C" || f == "--chdir": + if len(fields) < 2 { + fields = nil + break options + } + if f == "-u" || f == "--unset" { + sp.unset = append(sp.unset, fields[1]) + } + fields = fields[2:] + case strings.HasPrefix(f, "--unset="): + sp.unset = append(sp.unset, strings.TrimPrefix(f, "--unset=")) + fields = fields[1:] + case strings.HasPrefix(f, "-u") && len(f) > 2: + sp.unset = append(sp.unset, f[2:]) + fields = fields[1:] + case strings.HasPrefix(f, "-C") && len(f) > 2, strings.HasPrefix(f, "--chdir="): + fields = fields[1:] + case strings.HasPrefix(f, "-"): + // -S and the other operand-free options. The words + // arrive already split, which is what -S would have + // done to them. + fields = fields[1:] + case strings.Contains(f, "=") && !strings.Contains(f, "/"): + sp.set = append(sp.set, f) fields = fields[1:] - continue + default: + break options } - break } } - return fields, env, true + sp.tokens = fields + return sp, true +} + +// filterEnv drops the named variables from env, leaving everything else +// in order. The result is a fresh slice; env is not modified. +func filterEnv(env []string, unset []string) []string { + if len(unset) == 0 { + return env + } + drop := make(map[string]bool, len(unset)) + for _, name := range unset { + drop[name] = true + } + out := make([]string, 0, len(env)) + for _, kv := range env { + name, _, _ := strings.Cut(kv, "=") + if !drop[name] { + out = append(out, kv) + } + } + return out } // isJSRuntimeName reports whether a shebang's command names a @@ -249,18 +318,18 @@ func decideDispatch(opts Options) (*dispatch, string, error) { first = l } } - if tokens, env, ok := ParseShebangEnv(first); ok { - if len(tokens) == 0 { + if sp, ok := parseShebang(first); ok { + if len(sp.tokens) == 0 { return nil, "", errors.New("runner: the script's shebang line (#!) names no interpreter") } - if len(tokens) == 1 && isJSRuntimeName(opts.Setup, tokens[0]) { - return nil, tokens[0], nil + if len(sp.tokens) == 1 && isJSRuntimeName(opts.Setup, sp.tokens[0]) { + return nil, sp.tokens[0], nil } - d, err := dispatchFromTokens("shebang", tokens) + d, err := dispatchFromTokens("shebang", sp.tokens) if err != nil { return nil, "", err } - d.env = env + d.env, d.unset, d.clear = sp.set, sp.unset, sp.clear return d, "", nil } if strings.TrimSpace(opts.Interpreter) != "" { @@ -359,10 +428,17 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err args = append(args, opts.Args...) cmd := exec.Command(d.bin, args...) cmd.Dir = dir - // The shebang's own VAR=value assignments come first of the - // additions: env(1) would have set them, and the MCPX_* variables - // after them win any collision, as the run's own contract should. - cmd.Env = append(os.Environ(), d.env...) + // The shebang's own environment comes first of the additions: env(1) + // would have started from the inherited environment (or an empty one, + // with -i) minus the names it was told to unset, set its assignments, + // and then the MCPX_* variables win any collision, as the run's own + // contract should. + if d.clear { + cmd.Env = nil + } else { + cmd.Env = filterEnv(os.Environ(), d.unset) + } + cmd.Env = append(cmd.Env, d.env...) cmd.Env = append(cmd.Env, "MCPX_RUNTIME="+d.name, "MCPX_ENTRY="+scriptPath, "MCPX_DISPATCH="+d.source) for k, v := range opts.Env { cmd.Env = append(cmd.Env, k+"="+v) diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 57bef5dbef..86dab3d987 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -51,6 +51,73 @@ func TestParseShebangEnvAssignments(t *testing.T) { } } +func TestParseShebangEnvOptions(t *testing.T) { + for _, tc := range []struct { + line string + want string + set string + unset string + clear bool + }{ + {"#!/usr/bin/env -S -u SECRET sh", "sh", "", "SECRET", false}, + {"#!/usr/bin/env --unset=HOME sh", "sh", "", "HOME", false}, + {"#!/usr/bin/env -uSECRET sh", "sh", "", "SECRET", false}, + {"#!/usr/bin/env -C /tmp sh", "sh", "", "", false}, + {"#!/usr/bin/env --chdir=/tmp sh", "sh", "", "", false}, + {"#!/usr/bin/env -i sh", "sh", "", "", true}, + {"#!/usr/bin/env --ignore-environment sh", "sh", "", "", true}, + {"#!/usr/bin/env -S MODE=prod -u SECRET sh", "sh", "MODE=prod", "SECRET", false}, + {"#!/usr/bin/env -- sh", "sh", "", "", false}, + } { + sp, ok := parseShebang(tc.line) + if !ok || + strings.Join(sp.tokens, " ") != tc.want || + strings.Join(sp.set, " ") != tc.set || + strings.Join(sp.unset, " ") != tc.unset || + sp.clear != tc.clear { + t.Errorf("parseShebang(%q) = %v set=%v unset=%v clear=%v; want tokens=%q set=%q unset=%q clear=%v", + tc.line, sp.tokens, sp.set, sp.unset, sp.clear, tc.want, tc.set, tc.unset, tc.clear) + } + } +} + +func TestFilterEnv(t *testing.T) { + got := filterEnv([]string{"A=1", "B=2", "A=3"}, []string{"A"}) + if strings.Join(got, " ") != "B=2" { + t.Errorf("filterEnv = %v, want [B=2]", got) + } + // With nothing to drop the caller's slice is passed through as is. + in := []string{"A=1"} + if got := filterEnv(in, nil); &got[0] != &in[0] { + t.Errorf("filterEnv with no unset names copied the environment") + } +} + +func TestRunEnvShebangUnsetAndIgnore(t *testing.T) { + dir := t.TempDir() + t.Setenv("MCPX_TEST_DROP", "inherited") + + dropped := writeScript(t, dir, "dropped.sh", + "#!/usr/bin/env -S -u MCPX_TEST_DROP sh\necho \"drop=${MCPX_TEST_DROP-unset}\"\n") + var stdout, stderr bytes.Buffer + if _, err := Run(context.Background(), Options{File: dropped, Stdout: &stdout, Stderr: &stderr}); err != nil { + t.Fatalf("Run: %v", err) + } + if got := strings.TrimSpace(stdout.String()); got != "drop=unset" { + t.Errorf("stdout = %q, want drop=unset", got) + } + + ignored := writeScript(t, dir, "ignored.sh", + "#!/usr/bin/env -i sh\necho \"drop=${MCPX_TEST_DROP-unset} runtime=$MCPX_RUNTIME\"\n") + stdout.Reset() + if _, err := Run(context.Background(), Options{File: ignored, Stdout: &stdout, Stderr: &stderr}); err != nil { + t.Fatalf("Run: %v", err) + } + if got := strings.TrimSpace(stdout.String()); got != "drop=unset runtime=sh" { + t.Errorf("stdout = %q, want drop=unset runtime=sh", got) + } +} + func TestRunEnvShebangAssignmentsReachTheScript(t *testing.T) { dir := t.TempDir() f := writeScript(t, dir, "mode.sh", From 98367b9f9a47c1d80fc1913a2457009a99b007bc Mon Sep 17 00:00:00 2001 From: repo-worker-code Date: Fri, 30 Oct 2026 04:00:46 -0500 Subject: [PATCH 04/14] fix(mcpx): review findings on the shebang dispatch PR (#2167) Codex P2 + CodeRabbit on 534a14a5 (/pull/2611): - env -S payloads re-split with shell quoting rules, so '#!/usr/bin/env -S sh -c "printf hello"' keeps 'printf hello' one argument; an unterminated quote fails the run with a clear error instead of a silent mis-split. - -C/--chdir operands are carried onto the dispatch and move the run, beating script.cwd the way the interpreter choice beats script.runtime; relative -C resolves against the policy dir. - VAR=value assignments with '/' in the value reach the child. - A JavaScript shebang's env(1) changes ride with the runtime choice onto the harness path instead of being dropped. - Dispatched and harness runs never inherit MCPX_CLIENT, MCPX_RUNTIME, MCPX_ENTRY or MCPX_DISPATCH from an outer run. - execsvc.Result carries the runner notice through RunWith. - The notice names skipped launcher phases when any are set. Not taken: routing a JS shebang WITH extra arguments through the harness (the harness has nowhere to put the arguments, and raw dispatch still runs the named interpreter under the stated no-client notice). Tests: quote/resplit cases, chdir capture + end-to-end, slash values, owned-env filtering, phases notice, JS-choice env. --- pkgs/mcpx/docs/configuration.md | 12 ++ pkgs/mcpx/internal/execsvc/execsvc.go | 5 + pkgs/mcpx/internal/runner/dispatch.go | 132 +++++++++++++++---- pkgs/mcpx/internal/runner/dispatch_test.go | 145 +++++++++++++++++++-- pkgs/mcpx/internal/runner/runner.go | 15 ++- 5 files changed, 271 insertions(+), 38 deletions(-) diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index 4a71427cd7..1052969e02 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -598,6 +598,18 @@ and a switch to turn the report off would have kept it quiet. | `script.suffix` | source | *(empty)* | client | no | `--script-suffix` | `MCPX_SCRIPT_SUFFIX` | runs last on both paths, like a finally | | `script.typecheck` | enum | `off` | client | no | `--script-typecheck` | `MCPX_SCRIPT_TYPECHECK` | check the generated program before running it | +A script whose first line names its interpreter (`#!`) runs under that +interpreter, ahead of every setting above: a `-S`/`--split-string` +payload is re-split with shell quoting rules (so `-S sh -c "printf +hello"` keeps `printf hello` one argument; an unterminated quote fails +the run), `VAR=value` assignments reach the child even when the value +contains `/`, `env -u`/`env -i` apply, and `env -C`/`env --chdir` moves +the run, beating `script.cwd` the way the interpreter choice beats +`script.runtime`. A dispatched run never inherits `MCPX_CLIENT`, +`MCPX_RUNTIME`, `MCPX_ENTRY` or `MCPX_DISPATCH` from an outer run, and +its notice names anything else it goes without (no generated client, no +enforced permission profiles, skipped launcher phases). + ### search | setting | kind | default | scope | hot | flag | variable | governs | diff --git a/pkgs/mcpx/internal/execsvc/execsvc.go b/pkgs/mcpx/internal/execsvc/execsvc.go index 6aeae88728..e5647aae5c 100644 --- a/pkgs/mcpx/internal/execsvc/execsvc.go +++ b/pkgs/mcpx/internal/execsvc/execsvc.go @@ -249,6 +249,10 @@ type Result struct { Runtime string `json:"runtime,omitempty"` TimedOut bool `json:"timedOut,omitempty"` Error string `json:"error,omitempty"` + // Notice carries the runner's one-line statement of what a + // dispatched (non-JavaScript) run does not have: no generated + // client, no enforced permission profiles. + Notice string `json:"notice,omitempty"` } // Source supplies the generated client the script is run against. @@ -593,6 +597,7 @@ func (s *Service) RunWith(ctx context.Context, ropts runner.Options, opts Option res.DurationMs = rres.Duration.Milliseconds() res.Runtime = rres.Runtime res.TimedOut = rres.TimedOut + res.Notice = rres.Notice if rerr != nil { res.Error = rerr.Error() } diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index b9641dcbc9..ed99e8ec1a 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -92,6 +92,7 @@ type dispatch struct { env []string // VAR=value assignments an env shebang carried unset []string // names an env shebang removed from the environment (-u) clear bool // an env shebang asked for an empty environment (-i) + chdir string // directory an env shebang asked to run in (-C) name string // interpreter name reported as the run's runtime source string // "shebang" or "interpreter" } @@ -124,12 +125,22 @@ type shebangEnv struct { set []string // VAR=value assignments unset []string // names removed from the inherited environment (-u) clear bool // start from an empty environment (-i) + chdir string // directory env(1) would have moved to (-C/--chdir) + // splitErr is why an env -S payload could not be re-split (an + // unterminated quote). It is reported by decideDispatch; the + // exported ParseShebang wrappers keep best-effort tokens. + splitErr error } // parseShebang reads a #! line. Options of an env(1) shebang are // consumed as env itself would consume them, including the operand of // -u NAME and -C DIR, so that what remains is the command: without // that, "#!/usr/bin/env -S -u SECRET sh" would try to run SECRET. +// +// A -S/--split-string payload is re-split with shell quoting rules, +// because the kernel hands env the line already flattened: without +// that, `#!/usr/bin/env -S sh -c "printf hello"` would run sh with +// the two words '"printf' and 'hello"' and fail on the quotes. func parseShebang(line string) (shebangEnv, bool) { line = strings.TrimRight(line, "\r\n") if !strings.HasPrefix(line, "#!") { @@ -159,6 +170,8 @@ func parseShebang(line string) (shebangEnv, bool) { } if f == "-u" || f == "--unset" { sp.unset = append(sp.unset, fields[1]) + } else { + sp.chdir = fields[1] } fields = fields[2:] case strings.HasPrefix(f, "--unset="): @@ -167,14 +180,22 @@ func parseShebang(line string) (shebangEnv, bool) { case strings.HasPrefix(f, "-u") && len(f) > 2: sp.unset = append(sp.unset, f[2:]) fields = fields[1:] - case strings.HasPrefix(f, "-C") && len(f) > 2, strings.HasPrefix(f, "--chdir="): + case f == "-S" || f == "--split-string": + fields = sp.resplit(strings.Join(fields[1:], " ")) + case strings.HasPrefix(f, "--split-string="): + fields = sp.resplit(strings.TrimPrefix(f, "--split-string=") + " " + strings.Join(fields[1:], " ")) + case strings.HasPrefix(f, "-S") && len(f) > 2: + fields = sp.resplit(f[2:] + " " + strings.Join(fields[1:], " ")) + case strings.HasPrefix(f, "-C") && len(f) > 2: + sp.chdir = f[2:] + fields = fields[1:] + case strings.HasPrefix(f, "--chdir="): + sp.chdir = strings.TrimPrefix(f, "--chdir=") fields = fields[1:] case strings.HasPrefix(f, "-"): - // -S and the other operand-free options. The words - // arrive already split, which is what -S would have - // done to them. + // The other operand-free options. fields = fields[1:] - case strings.Contains(f, "=") && !strings.Contains(f, "/"): + case strings.Contains(f, "="): sp.set = append(sp.set, f) fields = fields[1:] default: @@ -186,6 +207,19 @@ func parseShebang(line string) (shebangEnv, bool) { return sp, true } +// resplit parses an env -S payload the way env(1) would: honouring +// single and double quotes and backslash escapes, so quoted text +// stays one argument. A payload that does not parse records the +// error for decideDispatch and yields no tokens. +func (sp *shebangEnv) resplit(payload string) []string { + fields, err := SplitCommandLine(payload) + if err != nil { + sp.splitErr = err + return nil + } + return fields +} + // filterEnv drops the named variables from env, leaving everything else // in order. The result is a fresh slice; env is not modified. func filterEnv(env []string, unset []string) []string { @@ -292,10 +326,22 @@ func fileFirstLine(path string) (string, error) { return line, nil } +// jsChoice is a shebang's choice of JavaScript runtime (rank 1): the +// runtime the harness must use, plus the environment changes the +// env(1) wrapper around it asked for. The environment rides with the +// runtime so the harness path cannot silently drop what +// ParseShebangEnv preserves for the raw path (#2611 review). +type jsChoice struct { + runtime string + set []string + unset []string + clear bool +} + // decideDispatch applies ranks 1 and 2 of the dispatch order. A nil // dispatch means the run falls through to the TypeScript runtime; the -// second return value then names the runtime a JavaScript shebang -// chose, so the harness honours the shebang's choice instead of the +// second return value then carries a JavaScript shebang's runtime +// choice, so the harness honours the shebang's choice instead of the // configured preference. // // A shebang naming a JavaScript runtime, with no extra arguments, is @@ -306,7 +352,7 @@ func fileFirstLine(path string) (string, error) { // shebang's runtime as its preference. A JavaScript shebang WITH extra // arguments keeps raw dispatch: the arguments are part of the command // the file names, and the harness has nowhere to put them. -func decideDispatch(opts Options) (*dispatch, string, error) { +func decideDispatch(opts Options) (*dispatch, jsChoice, error) { first := "" if opts.Source != "" { first = firstLineOf(opts.Source) @@ -319,34 +365,58 @@ func decideDispatch(opts Options) (*dispatch, string, error) { } } if sp, ok := parseShebang(first); ok { + if sp.splitErr != nil { + return nil, jsChoice{}, fmt.Errorf("runner: shebang -S payload: %w", sp.splitErr) + } if len(sp.tokens) == 0 { - return nil, "", errors.New("runner: the script's shebang line (#!) names no interpreter") + return nil, jsChoice{}, errors.New("runner: the script's shebang line (#!) names no interpreter") } if len(sp.tokens) == 1 && isJSRuntimeName(opts.Setup, sp.tokens[0]) { - return nil, sp.tokens[0], nil + return nil, jsChoice{runtime: sp.tokens[0], set: sp.set, unset: sp.unset, clear: sp.clear}, nil } d, err := dispatchFromTokens("shebang", sp.tokens) if err != nil { - return nil, "", err + return nil, jsChoice{}, err } - d.env, d.unset, d.clear = sp.set, sp.unset, sp.clear - return d, "", nil + d.env, d.unset, d.clear, d.chdir = sp.set, sp.unset, sp.clear, sp.chdir + return d, jsChoice{}, nil } if strings.TrimSpace(opts.Interpreter) != "" { tokens, err := SplitCommandLine(opts.Interpreter) if err != nil { - return nil, "", fmt.Errorf("runner: script.interpreter: %w", err) + return nil, jsChoice{}, fmt.Errorf("runner: script.interpreter: %w", err) } if len(tokens) == 0 { - return nil, "", errors.New("runner: script.interpreter is set but names no command") + return nil, jsChoice{}, errors.New("runner: script.interpreter is set but names no command") } d, err := dispatchFromTokens("interpreter", tokens) if err != nil { - return nil, "", err + return nil, jsChoice{}, err } - return d, "", nil + return d, jsChoice{}, nil } - return nil, "", nil + return nil, jsChoice{}, nil +} + +// ownedEnvNames are the MCPX_* variables a run sets itself. A child +// never inherits them: with duplicate keys the first wins, so a stale +// value from an outer run (a MCPX_CLIENT path, a MCPX_RUNTIME naming +// another interpreter) would silently beat the run's own contract. +var ownedEnvNames = []string{"MCPX_CLIENT", "MCPX_RUNTIME", "MCPX_ENTRY", "MCPX_DISPATCH"} + +// childBaseEnv is the environment a diverted run starts from: the +// inherited environment (or nothing, with -i), minus the names env(1) +// was told to unset and the run's own contract variables, plus the +// assignments the shebang carried. +func childBaseEnv(set, unset []string, clear bool) []string { + var base []string + if !clear { + drop := make([]string, 0, len(unset)+len(ownedEnvNames)) + drop = append(drop, unset...) + drop = append(drop, ownedEnvNames...) + base = filterEnv(os.Environ(), drop) + } + return append(base, set...) } func dispatchFromTokens(source string, tokens []string) (*dispatch, error) { @@ -411,11 +481,27 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err if err != nil { return nil, err } + if d.chdir != "" { + // A shebang's -C/--chdir is the program's own directory + // choice, so like its interpreter choice it beats + // configuration: the rank-1 rationale in decideDispatch + // applies to the directory too. A relative -C resolves + // against the policy directory, the way env(1) resolves it + // against the directory in force. + if filepath.IsAbs(d.chdir) { + dir = d.chdir + } else { + dir = filepath.Join(dir, d.chdir) + } + } notice := fmt.Sprintf("mcpx: running under %s (%s dispatch): no generated mcpx client is "+ "available to a non-JavaScript script, and script.permissions profiles are not enforced "+ "for this interpreter; MCPX_ENDPOINT, MCPX_SESSION and MCPX_SOCKET are in the environment", d.name, d.source) + if !opts.Phases.Empty() { + notice += "; configured launcher phases do not apply to a non-JavaScript run and are skipped" + } runCtx := ctx var cancel context.CancelFunc @@ -432,13 +518,9 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err // would have started from the inherited environment (or an empty one, // with -i) minus the names it was told to unset, set its assignments, // and then the MCPX_* variables win any collision, as the run's own - // contract should. - if d.clear { - cmd.Env = nil - } else { - cmd.Env = filterEnv(os.Environ(), d.unset) - } - cmd.Env = append(cmd.Env, d.env...) + // contract should. Names the run owns are never inherited: a stale + // outer value would shadow the contract (first duplicate wins). + cmd.Env = childBaseEnv(d.env, d.unset, d.clear) cmd.Env = append(cmd.Env, "MCPX_RUNTIME="+d.name, "MCPX_ENTRY="+scriptPath, "MCPX_DISPATCH="+d.source) for k, v := range opts.Env { cmd.Env = append(cmd.Env, k+"="+v) diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 86dab3d987..0aa7f378bd 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -81,6 +81,126 @@ func TestParseShebangEnvOptions(t *testing.T) { } } +func TestParseShebangSplitStringQuoting(t *testing.T) { + // The Codex P2 on PR #2611: a -S payload is one string env(1) + // splits with quoting rules, not pre-split words. + for _, tc := range []struct { + line string + want string + }{ + {`#!/usr/bin/env -S sh -c "printf hello"`, "sh -c printf hello"}, + {`#!/usr/bin/env -S python3 -c 'print("hi")'`, `python3 -c print("hi")`}, + {`#!/usr/bin/env -S sh -c a\ b`, "sh -c a b"}, + {`#!/usr/bin/env --split-string=sh -c "x y"`, "sh -c x y"}, + {`#!/usr/bin/env -Ssh -c "x y"`, "sh -c x y"}, + } { + got, ok := ParseShebang(tc.line) + if !ok || strings.Join(got, " ") != tc.want { + t.Errorf("ParseShebang(%q) = %v, %v; want [%s], true", tc.line, got, ok, tc.want) + } + } + // An unterminated quote is a dispatch error, not a silent + // mis-split: GNU env errors on it too. + if _, _, err := decideDispatch(Options{Source: "#!/usr/bin/env -S sh -c \"oops\necho hi\n"}); err == nil { + t.Error("decideDispatch(unterminated -S quote): want an error") + } +} + +func TestParseShebangChdir(t *testing.T) { + // The CodeRabbit finding on PR #2611: -C/--chdir was consumed and + // dropped, so the script ran somewhere its own first line did not + // name. The operand is carried on the dispatch now. + for _, tc := range []struct { + line string + want string + }{ + {"#!/usr/bin/env -C /tmp sh", "/tmp"}, + {"#!/usr/bin/env -Ctmp sh", "tmp"}, + {"#!/usr/bin/env --chdir=/tmp sh", "/tmp"}, + {"#!/usr/bin/env --chdir /tmp sh", "/tmp"}, + } { + sp, ok := parseShebang(tc.line) + if !ok || strings.Join(sp.tokens, " ") != "sh" || sp.chdir != tc.want { + t.Errorf("parseShebang(%q) = %v chdir=%q; want [sh] chdir=%q", tc.line, sp.tokens, sp.chdir, tc.want) + } + } +} + +func TestParseShebangEnvAssignmentWithSlash(t *testing.T) { + // The CodeRabbit finding on PR #2611: a value containing "/" is + // still an assignment (PATH=/x:/y), not the command. + tokens, env, ok := ParseShebangEnv("#!/usr/bin/env PATH=/x:/y sh") + if !ok || strings.Join(tokens, " ") != "sh" || strings.Join(env, " ") != "PATH=/x:/y" { + t.Errorf("ParseShebangEnv = %v, %v, %v; want [sh], [PATH=/x:/y], true", tokens, env, ok) + } +} + +func TestRunDispatchedDropsOwnedEnvNames(t *testing.T) { + // The CodeRabbit finding on PR #2611: a dispatched run must not + // inherit the run's own contract variables from an outer run -- + // with duplicate keys the first wins, so a stale MCPX_CLIENT path + // or MCPX_RUNTIME would silently beat the run's own. + t.Setenv("MCPX_CLIENT", "stale-from-parent") + t.Setenv("MCPX_RUNTIME", "stale-from-parent") + dir := t.TempDir() + f := writeScript(t, dir, "env.sh", + "#!/bin/sh\necho \"client=[${MCPX_CLIENT-unset}] runtime=$MCPX_RUNTIME\"\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{File: f, Stdout: &stdout, Stderr: &stderr}) + if err != nil { + t.Fatalf("Run: %v", err) + } + if got := strings.TrimSpace(stdout.String()); got != "client=[unset] runtime=sh" { + t.Errorf("stdout = %q, want client=[unset] runtime=sh", got) + } + if res.ExitCode != 0 { + t.Errorf("ExitCode = %d, want 0", res.ExitCode) + } +} + +func TestRunShebangChdir(t *testing.T) { + // End to end for the -C fix: the script runs where its shebang + // says, ahead of the script.cwd policy. + dir := t.TempDir() + target := filepath.Join(dir, "elsewhere") + if err := os.Mkdir(target, 0o755); err != nil { + t.Fatal(err) + } + f := writeScript(t, dir, "where.sh", + "#!/usr/bin/env -C "+target+" sh\ntouch ran-in-target-dir\n") + var stdout, stderr bytes.Buffer + if _, err := Run(context.Background(), Options{File: f, Stdout: &stdout, Stderr: &stderr}); err != nil { + t.Fatalf("Run: %v", err) + } + // A relative write lands where the shebang says, not next to the + // script: /bin/pwd is not portable enough to assert on here. + if _, err := os.Stat(filepath.Join(target, "ran-in-target-dir")); err != nil { + t.Errorf("marker missing in the -C directory: %v (stderr %q)", err, stderr.String()) + } + if _, err := os.Stat(filepath.Join(dir, "ran-in-target-dir")); !os.IsNotExist(err) { + t.Errorf("marker leaked into the script directory") + } +} + +func TestRunDispatchedNoticeNamesSkippedPhases(t *testing.T) { + // The CodeRabbit finding on runner.go: configured launcher phases + // are skipped on a dispatched run; the notice must say so instead + // of staying silent about it. + dir := t.TempDir() + f := writeScript(t, dir, "ph.sh", "#!/bin/sh\necho ok\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: f, Stdout: &stdout, Stderr: &stderr, + Phases: Phases{Before: []string{"// configured"}}, + }) + if err != nil { + t.Fatalf("Run: %v", err) + } + if !strings.Contains(res.Notice, "phases") { + t.Errorf("Notice = %q, want it to name the skipped launcher phases", res.Notice) + } +} + func TestFilterEnv(t *testing.T) { got := filterEnv([]string{"A=1", "B=2", "A=3"}, []string{"A"}) if strings.Join(got, " ") != "B=2" { @@ -137,20 +257,27 @@ func TestRunEnvShebangAssignmentsReachTheScript(t *testing.T) { func TestDecideDispatchJSRuntimeShebang(t *testing.T) { // A plain JavaScript-runtime shebang must NOT divert to raw // dispatch: the harness runs it, under the shebang's runtime. - d, jsRuntime, err := decideDispatch(Options{Source: "#!/usr/bin/env node\nexport default () => 1\n"}) - if err != nil || d != nil || jsRuntime != "node" { - t.Errorf("decideDispatch(node shebang) = %v, %q, %v; want nil, \"node\", nil", d, jsRuntime, err) + d, js, err := decideDispatch(Options{Source: "#!/usr/bin/env node\nexport default () => 1\n"}) + if err != nil || d != nil || js.runtime != "node" { + t.Errorf("decideDispatch(node shebang) = %v, %q, %v; want nil, \"node\", nil", d, js.runtime, err) } // A JavaScript shebang with extra arguments keeps raw dispatch: // the arguments are part of the named command. - d, jsRuntime, err = decideDispatch(Options{Source: "#!/usr/bin/env -S node --inspect main.ts\n"}) - if err != nil || d == nil || jsRuntime != "" { - t.Errorf("decideDispatch(node --inspect) = %v, %q, %v; want a dispatch, \"\", nil", d, jsRuntime, err) + d, js, err = decideDispatch(Options{Source: "#!/usr/bin/env -S node --inspect main.ts\n"}) + if err != nil || d == nil || js.runtime != "" { + t.Errorf("decideDispatch(node --inspect) = %v, %q, %v; want a dispatch, \"\", nil", d, js.runtime, err) } // A non-JavaScript shebang dispatches as before. - d, jsRuntime, err = decideDispatch(Options{Source: "#!/bin/sh\necho hi\n"}) - if err != nil || d == nil || jsRuntime != "" { - t.Errorf("decideDispatch(sh) = %v, %q, %v; want a dispatch, \"\", nil", d, jsRuntime, err) + d, js, err = decideDispatch(Options{Source: "#!/bin/sh\necho hi\n"}) + if err != nil || d == nil || js.runtime != "" { + t.Errorf("decideDispatch(sh) = %v, %q, %v; want a dispatch, \"\", nil", d, js.runtime, err) + } + // A JavaScript shebang's env(1) environment rides with the runtime + // choice instead of being dropped on the harness path. + d, js, err = decideDispatch(Options{Source: "#!/usr/bin/env -S MODE=prod -u SECRET node\nexport default () => 1\n"}) + if err != nil || d != nil || js.runtime != "node" || + strings.Join(js.set, " ") != "MODE=prod" || strings.Join(js.unset, " ") != "SECRET" { + t.Errorf("decideDispatch(node env) = %v, %+v, %v; want nil, {node [MODE=prod] [SECRET]}, nil", d, js, err) } } diff --git a/pkgs/mcpx/internal/runner/runner.go b/pkgs/mcpx/internal/runner/runner.go index 5c6f020f30..685ba12549 100644 --- a/pkgs/mcpx/internal/runner/runner.go +++ b/pkgs/mcpx/internal/runner/runner.go @@ -178,14 +178,18 @@ func Run(ctx context.Context, opts Options) (*Result, error) { // runs the script under that interpreter, before any JavaScript // runtime is considered. Rank 3 (language/extension) is reserved // for #1917; rank 4 is everything below, unchanged. - if d, jsRuntime, derr := decideDispatch(opts); derr != nil { + var jsEnv jsChoice + if d, js, derr := decideDispatch(opts); derr != nil { return nil, derr } else if d != nil { return runDispatched(ctx, opts, d) - } else if jsRuntime != "" { + } else if js.runtime != "" { // A JavaScript shebang chose this runtime (rank 1); the harness // below runs under it instead of the configured preference. - opts.Runtime = jsRuntime + // The env(1) wrapper's environment changes ride along, so the + // harness path honours what the raw path preserves. + opts.Runtime = js.runtime + jsEnv = js } rt, err := Resolve(opts.Runtime, opts.Permissions, opts.Setup) if err != nil { @@ -332,7 +336,10 @@ func Run(ctx context.Context, opts Options) (*Result, error) { cmd.Dir = dir // The kind, not the configured name: a script branching on its runtime // cares whether it is under Deno, not what somebody called the binary. - cmd.Env = append(os.Environ(), "MCPX_RUNTIME="+rt.Kind) + // A JavaScript shebang's env(1) changes apply here too, and names the + // run owns are never inherited (a stale outer value would shadow the + // contract: first duplicate wins). + cmd.Env = append(childBaseEnv(jsEnv.set, jsEnv.unset, jsEnv.clear), "MCPX_RUNTIME="+rt.Kind) // Resolved here rather than by the caller: only the runner knows the final // location of the entry script and the client it wrote beside it. cmd.Env = append(cmd.Env, "MCPX_ENTRY="+scriptPath, "MCPX_CLIENT="+clientPath) From 283126b8a39361d2583b897b72cc48c664a44be8 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 04:29:42 -0500 Subject: [PATCH 05/14] mcpx: shebang -C and PATH assignments honoured on both dispatch paths (#2167) Codex re-review of PR #2611, two P2s: - the JavaScript harness path dropped a shebang env -C directory: jsChoice now carries chdir and both paths apply it through one applyChdir helper, so the harness runs where the shebang says. - the interpreter was resolved with exec.LookPath on the parent process PATH before the shebang assignments were applied: the shebang path now resolves against the PATH the shebang itself establishes (assignments, -u, -i with the execvp /bin:/usr/bin default), the way env(1) resolves it. Tests: TestDecideDispatchJSCarriesChdir, TestDecideDispatchResolvesAgainstShebangPath (executable existing only in the assigned PATH is found; without the assignment it is not). Full internal/runner suite passes. --- pkgs/mcpx/internal/runner/dispatch.go | 98 ++++++++++++++++++---- pkgs/mcpx/internal/runner/dispatch_test.go | 41 +++++++++ pkgs/mcpx/internal/runner/runner.go | 2 +- 3 files changed, 122 insertions(+), 19 deletions(-) diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index ed99e8ec1a..803c0bcd44 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -336,6 +336,7 @@ type jsChoice struct { set []string unset []string clear bool + chdir string } // decideDispatch applies ranks 1 and 2 of the dispatch order. A nil @@ -372,9 +373,9 @@ func decideDispatch(opts Options) (*dispatch, jsChoice, error) { return nil, jsChoice{}, errors.New("runner: the script's shebang line (#!) names no interpreter") } if len(sp.tokens) == 1 && isJSRuntimeName(opts.Setup, sp.tokens[0]) { - return nil, jsChoice{runtime: sp.tokens[0], set: sp.set, unset: sp.unset, clear: sp.clear}, nil + return nil, jsChoice{runtime: sp.tokens[0], set: sp.set, unset: sp.unset, clear: sp.clear, chdir: sp.chdir}, nil } - d, err := dispatchFromTokens("shebang", sp.tokens) + d, err := dispatchFromTokens("shebang", sp.tokens, &sp) if err != nil { return nil, jsChoice{}, err } @@ -389,7 +390,7 @@ func decideDispatch(opts Options) (*dispatch, jsChoice, error) { if len(tokens) == 0 { return nil, jsChoice{}, errors.New("runner: script.interpreter is set but names no command") } - d, err := dispatchFromTokens("interpreter", tokens) + d, err := dispatchFromTokens("interpreter", tokens, nil) if err != nil { return nil, jsChoice{}, err } @@ -398,6 +399,24 @@ func decideDispatch(opts Options) (*dispatch, jsChoice, error) { return nil, jsChoice{}, nil } +// applyChdir applies an env shebang's -C/--chdir directory to the +// policy directory a run resolved. A shebang's -C is the program's own +// directory choice, so like its interpreter choice it beats +// configuration: the rank-1 rationale in decideDispatch applies to the +// directory too. A relative -C resolves against the policy directory, +// the way env(1) resolves it against the directory in force. Both +// dispatch paths (raw and the JavaScript harness) apply it through +// here, so neither can silently drop what the shebang asked for. +func applyChdir(dir, chdir string) string { + if chdir == "" { + return dir + } + if filepath.IsAbs(chdir) { + return chdir + } + return filepath.Join(dir, chdir) +} + // ownedEnvNames are the MCPX_* variables a run sets itself. A child // never inherits them: with duplicate keys the first wins, so a stale // value from an outer run (a MCPX_CLIENT path, a MCPX_RUNTIME naming @@ -419,11 +438,66 @@ func childBaseEnv(set, unset []string, clear bool) []string { return append(base, set...) } -func dispatchFromTokens(source string, tokens []string) (*dispatch, error) { +// shebangPath is the PATH env(1) would run the command with: the +// inherited one, emptied by -i or by unsetting PATH, with the shebang's +// own PATH assignment (the last one) replacing it. Resolving the +// interpreter against anything else runs a different interpreter than +// the one the script's first line names -- or none, when the executable +// exists only in the assigned PATH (#2611 review). +func shebangPath(sp *shebangEnv) string { + path := os.Getenv("PATH") + if sp.clear { + path = "" + } + for _, u := range sp.unset { + if u == "PATH" { + path = "" + } + } + for _, kv := range sp.set { + if k, v, ok := strings.Cut(kv, "="); ok && k == "PATH" { + path = v + } + } + if path == "" { + // env(1) runs the command through execvp, which falls back to + // a default path (confstr _CS_PATH: /bin:/usr/bin) when PATH is + // absent from the environment it builds -- the -i case. An + // empty effective PATH therefore means that default, not + // "nothing is findable". + path = "/bin:/usr/bin" + } + return path +} + +// lookPathIn is exec.LookPath against one explicit PATH value. +func lookPathIn(bin, path string) (string, error) { + for _, dir := range filepath.SplitList(path) { + if dir == "" { + dir = "." + } + p := filepath.Join(dir, bin) + if fi, err := os.Stat(p); err == nil && !fi.IsDir() && fi.Mode()&0o111 != 0 { + return p, nil + } + } + return "", exec.ErrNotFound +} + +func dispatchFromTokens(source string, tokens []string, sp *shebangEnv) (*dispatch, error) { bin := tokens[0] resolved := bin if !strings.Contains(bin, "/") { - p, err := exec.LookPath(bin) + var p string + var err error + if sp != nil { + // A shebang's command is resolved against the environment + // the shebang itself establishes, the way env(1) resolves + // it after applying its assignments. + p, err = lookPathIn(bin, shebangPath(sp)) + } else { + p, err = exec.LookPath(bin) + } if err != nil { return nil, fmt.Errorf("runner: %s interpreter %q not found on PATH: %w", source, bin, err) } @@ -481,19 +555,7 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err if err != nil { return nil, err } - if d.chdir != "" { - // A shebang's -C/--chdir is the program's own directory - // choice, so like its interpreter choice it beats - // configuration: the rank-1 rationale in decideDispatch - // applies to the directory too. A relative -C resolves - // against the policy directory, the way env(1) resolves it - // against the directory in force. - if filepath.IsAbs(d.chdir) { - dir = d.chdir - } else { - dir = filepath.Join(dir, d.chdir) - } - } + dir = applyChdir(dir, d.chdir) notice := fmt.Sprintf("mcpx: running under %s (%s dispatch): no generated mcpx client is "+ "available to a non-JavaScript script, and script.permissions profiles are not enforced "+ diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 0aa7f378bd..7405c73bc7 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -471,3 +471,44 @@ func TestRunCwdPolicyScript(t *testing.T) { t.Errorf("script.cwd=caller: pwd = %q, want %q", got, wantBase) } } + +// A JavaScript shebang's -C directory rides into the harness choice: +// dropping it would run the script in the policy directory while the +// raw path honours it (#2611 review). +func TestDecideDispatchJSCarriesChdir(t *testing.T) { + d, js, err := decideDispatch(Options{Source: "#!/usr/bin/env -S -C /tmp node\nexport default () => 1\n"}) + if err != nil { + t.Fatalf("decideDispatch: %v", err) + } + if d != nil { + t.Fatalf("decideDispatch(JS shebang with -C) dispatch = %v; want nil (harness path)", d) + } + if js.runtime != "node" || js.chdir != "/tmp" { + t.Errorf("jsChoice = %+v; want runtime node with chdir /tmp carried", js) + } +} + +// The interpreter a shebang names is resolved against the PATH the +// shebang itself assigns, not the parent process's: an executable that +// exists only in the assigned PATH must be found (#2611 review). +func TestDecideDispatchResolvesAgainstShebangPath(t *testing.T) { + dir := t.TempDir() + bin := filepath.Join(dir, "myinterp-probe") + if err := os.WriteFile(bin, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { + t.Fatal(err) + } + src := "#!/usr/bin/env -S PATH=" + dir + " myinterp-probe\necho hi\n" + d, _, err := decideDispatch(Options{Source: src}) + if err != nil { + t.Fatalf("decideDispatch(shebang PATH assignment): %v", err) + } + if d == nil || d.bin != bin { + t.Errorf("dispatch = %+v; want bin %q resolved via the shebang's PATH", d, bin) + } + // And without the assignment the same name is not found on the + // process PATH (it exists nowhere else), proving the assignment -- + // not luck -- did the resolving. + if _, _, err := decideDispatch(Options{Source: "#!/usr/bin/env myinterp-probe\necho hi\n"}); err == nil { + t.Error("decideDispatch without the PATH assignment: want a not-found error") + } +} diff --git a/pkgs/mcpx/internal/runner/runner.go b/pkgs/mcpx/internal/runner/runner.go index 685ba12549..5ac8abce63 100644 --- a/pkgs/mcpx/internal/runner/runner.go +++ b/pkgs/mcpx/internal/runner/runner.go @@ -333,7 +333,7 @@ func Run(ctx context.Context, opts Options) (*Result, error) { if derr != nil { return nil, derr } - cmd.Dir = dir + cmd.Dir = applyChdir(dir, jsEnv.chdir) // The kind, not the configured name: a script branching on its runtime // cares whether it is under Deno, not what somebody called the binary. // A JavaScript shebang's env(1) changes apply here too, and names the From 38b556e22d57308fd8a73ac9c1a3542387be5b74 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 06:35:43 -0500 Subject: [PATCH 06/14] fix(mcpx): resolve shebang interpreters after choosing cwd (#2167) Codex P2 on PR #2611: a raw-dispatched shebang such as #!/usr/bin/env -S -C /tmp/project PATH=bin custom-interpreter looked up bin/custom-interpreter relative to mcpx's own working directory, before -C was applied -- the interpreter was missed even though it exists exactly where the run goes. The shebang's interpreter lookup is now deferred to runDispatched, which resolves it against the run's effective directory (policy + the shebang's -C) through lookPathInDir and absolutizes the result, the way execvp resolves relative PATH entries after env(1) has applied -C. Tests: TestRunShebangRelativePathEntryResolvesPostChdir (fails on the pre-fix code with the reported not-found error); TestRunResolvesAgainstShebangPath replaces the decide-time TestDecideDispatchResolvesAgainstShebangPath. Full internal/runner and internal/execsvc suites pass. --- pkgs/mcpx/internal/runner/dispatch.go | 88 +++++++++++++++------- pkgs/mcpx/internal/runner/dispatch_test.go | 52 +++++++++++-- 2 files changed, 106 insertions(+), 34 deletions(-) diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 803c0bcd44..8eaac95ca0 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -95,6 +95,15 @@ type dispatch struct { chdir string // directory an env shebang asked to run in (-C) name string // interpreter name reported as the run's runtime source string // "shebang" or "interpreter" + // lookupBin/lookupPath defer a shebang's interpreter lookup to + // run time: relative PATH entries resolve against the run's + // effective directory (policy + the shebang's -C), the way + // execvp resolves them after env(1) has applied -C. Resolving + // at decide time would check them against mcpx's own working + // directory, which is the wrong directory whenever the run + // moves elsewhere (#2611 review). + lookupBin string // command name as the shebang named it (no "/") + lookupPath string // PATH value the shebang establishes } // ParseShebang splits a #! line into the interpreter command it names. @@ -470,13 +479,24 @@ func shebangPath(sp *shebangEnv) string { return path } -// lookPathIn is exec.LookPath against one explicit PATH value. -func lookPathIn(bin, path string) (string, error) { - for _, dir := range filepath.SplitList(path) { - if dir == "" { - dir = "." +// lookPathInDir is exec.LookPath against one explicit PATH value, +// with entries resolved against dir: an empty entry means the run's +// effective directory (not mcpx's own), and so does any other relative +// entry, the way execvp resolves them after env(1) has applied -C. The +// result is absolute, so the later exec cannot reinterpret it against +// a third directory. +func lookPathInDir(bin, path, dir string) (string, error) { + abs, err := filepath.Abs(dir) + if err != nil { + return "", err + } + for _, entry := range filepath.SplitList(path) { + if entry == "" { + entry = abs + } else if !filepath.IsAbs(entry) { + entry = filepath.Join(abs, entry) } - p := filepath.Join(dir, bin) + p := filepath.Join(entry, bin) if fi, err := os.Stat(p); err == nil && !fi.IsDir() && fi.Mode()&0o111 != 0 { return p, nil } @@ -486,29 +506,33 @@ func lookPathIn(bin, path string) (string, error) { func dispatchFromTokens(source string, tokens []string, sp *shebangEnv) (*dispatch, error) { bin := tokens[0] - resolved := bin - if !strings.Contains(bin, "/") { - var p string - var err error - if sp != nil { - // A shebang's command is resolved against the environment - // the shebang itself establishes, the way env(1) resolves - // it after applying its assignments. - p, err = lookPathIn(bin, shebangPath(sp)) - } else { - p, err = exec.LookPath(bin) - } - if err != nil { - return nil, fmt.Errorf("runner: %s interpreter %q not found on PATH: %w", source, bin, err) - } - resolved = p - } - return &dispatch{ - bin: resolved, + d := &dispatch{ args: append([]string{}, tokens[1:]...), name: filepath.Base(bin), source: source, - }, nil + } + if strings.Contains(bin, "/") { + // An explicit path is used verbatim, the way the kernel + // uses a slash-containing shebang path as-is. + d.bin = bin + return d, nil + } + if sp != nil { + // A shebang's command is resolved against the environment + // the shebang itself establishes, the way env(1) resolves + // it after applying its assignments -- but only once the + // run's effective directory is known (runDispatched): its + // relative PATH entries mean the directory the run moves + // to, not mcpx's own. + d.lookupBin, d.lookupPath = bin, shebangPath(sp) + return d, nil + } + p, err := exec.LookPath(bin) + if err != nil { + return nil, fmt.Errorf("runner: %s interpreter %q not found on PATH: %w", source, bin, err) + } + d.bin = p + return d, nil } // runDispatched executes a script under a non-JavaScript interpreter. @@ -556,6 +580,18 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err return nil, err } dir = applyChdir(dir, d.chdir) + if d.lookupBin != "" { + // The interpreter a shebang names is resolved here, against + // the directory the run actually moves to: deciding earlier + // would check relative PATH entries against mcpx's own + // working directory and miss an interpreter that exists + // only where the run goes. + abs, err := lookPathInDir(d.lookupBin, d.lookupPath, dir) + if err != nil { + return nil, fmt.Errorf("runner: %s interpreter %q not found on PATH: %w", d.source, d.lookupBin, err) + } + d.bin = abs + } notice := fmt.Sprintf("mcpx: running under %s (%s dispatch): no generated mcpx client is "+ "available to a non-JavaScript script, and script.permissions profiles are not enforced "+ diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 7405c73bc7..3c65bb9088 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -491,24 +491,60 @@ func TestDecideDispatchJSCarriesChdir(t *testing.T) { // The interpreter a shebang names is resolved against the PATH the // shebang itself assigns, not the parent process's: an executable that // exists only in the assigned PATH must be found (#2611 review). -func TestDecideDispatchResolvesAgainstShebangPath(t *testing.T) { +func TestRunResolvesAgainstShebangPath(t *testing.T) { dir := t.TempDir() bin := filepath.Join(dir, "myinterp-probe") if err := os.WriteFile(bin, []byte("#!/bin/sh\nexit 0\n"), 0o755); err != nil { t.Fatal(err) } - src := "#!/usr/bin/env -S PATH=" + dir + " myinterp-probe\necho hi\n" - d, _, err := decideDispatch(Options{Source: src}) + f := writeScript(t, dir, "uses-probe.sh", + "#!/usr/bin/env -S PATH="+dir+" myinterp-probe\necho hi\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: f, Stdout: &stdout, Stderr: &stderr, + }) if err != nil { - t.Fatalf("decideDispatch(shebang PATH assignment): %v", err) + t.Fatalf("Run(shebang PATH assignment): %v", err) } - if d == nil || d.bin != bin { - t.Errorf("dispatch = %+v; want bin %q resolved via the shebang's PATH", d, bin) + if res.Runtime != "myinterp-probe" { + t.Errorf("Runtime = %q, want the shebang's interpreter", res.Runtime) } // And without the assignment the same name is not found on the // process PATH (it exists nowhere else), proving the assignment -- // not luck -- did the resolving. - if _, _, err := decideDispatch(Options{Source: "#!/usr/bin/env myinterp-probe\necho hi\n"}); err == nil { - t.Error("decideDispatch without the PATH assignment: want a not-found error") + g := writeScript(t, dir, "no-probe.sh", + "#!/usr/bin/env myinterp-probe\necho hi\n") + if _, err := Run(context.Background(), Options{ + File: g, Stdout: &stdout, Stderr: &stderr, + }); err == nil || !strings.Contains(err.Error(), "not found on PATH") { + t.Errorf("Run without the PATH assignment: want a not-found error, got %v", err) + } +} + +// Relative PATH entries in a shebang resolve against the directory the +// run moves to (policy + the shebang's -C), not mcpx's own working +// directory: env(1) chdirs first and execvp resolves afterwards, so an +// interpreter that exists only there must be found (#2611 review). +func TestRunShebangRelativePathEntryResolvesPostChdir(t *testing.T) { + base := t.TempDir() + proj := filepath.Join(base, "project") + if err := os.MkdirAll(filepath.Join(proj, "bin"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(proj, "bin", "custom-interp-3201"), + []byte("#!/bin/sh\necho post-chdir-resolved\n"), 0o755); err != nil { + t.Fatal(err) + } + f := writeScript(t, base, "go.sh", + "#!/usr/bin/env -S -C "+proj+" PATH=bin custom-interp-3201\necho unreachable\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: f, Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("Run(relative PATH entry + -C): %v", err) + } + if res.Runtime != "custom-interp-3201" || !strings.Contains(stdout.String(), "post-chdir-resolved") { + t.Errorf("res=%+v stdout=%q; want the interpreter from the -C directory", res, stdout.String()) } } From 52dbf17d6516eaf99bc8d7d2fe667a274edd6521 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 07:35:04 -0500 Subject: [PATCH 07/14] fix(mcpx): honour env terminator assignments, raw -S payloads, empty PATH (#2167) --- pkgs/mcpx/internal/runner/dispatch.go | 226 +++++++++++++++------ pkgs/mcpx/internal/runner/dispatch_test.go | 74 +++++++ 2 files changed, 236 insertions(+), 64 deletions(-) diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 8eaac95ca0..e6733f4132 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -149,71 +149,156 @@ type shebangEnv struct { // A -S/--split-string payload is re-split with shell quoting rules, // because the kernel hands env the line already flattened: without // that, `#!/usr/bin/env -S sh -c "printf hello"` would run sh with -// the two words '"printf' and 'hello"' and fail on the quotes. +// the two words '"printf' and 'hello"' and fail on the quotes. The +// payload reaches the splitter UNTOUCHED (the raw remainder of the +// line after the -S token), not re-joined from pre-split fields: +// fieldsplitting first discards whitespace inside quotes, so +// `sh -c 'printf "<%s>" "a b"'` would silently run with "a b" +// (#2611 review). +// +// "--" ends option processing but not assignment processing: env's +// grammar is [OPTION]... [NAME=VALUE]... COMMAND, and assignments +// after the terminator still apply, so "#!/usr/bin/env -- MODE=prod +// sh" runs sh with MODE=prod set instead of trying to execute a +// program named MODE=prod (#2611 review). func parseShebang(line string) (shebangEnv, bool) { line = strings.TrimRight(line, "\r\n") if !strings.HasPrefix(line, "#!") { return shebangEnv{}, false } - fields := strings.Fields(strings.TrimSpace(line[2:])) - if len(fields) == 0 { + rest := strings.TrimSpace(line[2:]) + if rest == "" { return shebangEnv{}, true } + fields := strings.Fields(rest) var sp shebangEnv - if filepath.Base(fields[0]) == "env" { - fields = fields[1:] - options: - for len(fields) > 0 { - f := fields[0] - switch { - case f == "-i" || f == "--ignore-environment" || f == "-": - sp.clear = true - fields = fields[1:] - case f == "--": - fields = fields[1:] - break options - case f == "-u" || f == "--unset" || f == "-C" || f == "--chdir": - if len(fields) < 2 { - fields = nil - break options - } - if f == "-u" || f == "--unset" { - sp.unset = append(sp.unset, fields[1]) - } else { - sp.chdir = fields[1] + if filepath.Base(fields[0]) != "env" { + sp.tokens = fields + return sp, true + } + // env shebang: consume tokens from the raw remainder of the line, + // so a -S payload can still be recovered verbatim; tokens produced + // by a re-split queue in pending instead. + raw := strings.TrimSpace(rest[len(fields[0]):]) + var pending []string + next := func() (string, bool) { + if len(pending) > 0 { + t := pending[0] + pending = pending[1:] + return t, true + } + raw = strings.TrimLeft(raw, " \t") + if raw == "" { + return "", false + } + if i := strings.IndexAny(raw, " \t"); i >= 0 { + t := raw[:i] + raw = raw[i:] + return t, true + } + t := raw + raw = "" + return t, true + } + unread := func(t string) { pending = append([]string{t}, pending...) } + peek := func() (string, bool) { + t, ok := next() + if ok { + unread(t) + } + return t, ok + } + // remaining returns first plus everything not yet consumed, as + // the command and its arguments. + remaining := func(first string) []string { + out := []string{first} + out = append(out, pending...) + if strings.TrimSpace(raw) != "" { + out = append(out, strings.Fields(raw)...) + } + return out + } + // payloadFor builds a -S payload: with nothing queued the raw + // remainder is the payload, verbatim; with tokens queued by an + // earlier re-split it falls back to joining what remains. + payloadFor := func(head string) string { + if len(pending) == 0 { + tail := strings.TrimLeft(raw, " \t") + raw = "" + if head == "" { + return tail + } + if tail == "" { + return head + } + return head + " " + tail + } + parts := append([]string{}, pending...) + if strings.TrimSpace(raw) != "" { + parts = append(parts, strings.Fields(raw)...) + } + pending = nil + raw = "" + if head == "" { + return strings.Join(parts, " ") + } + return head + " " + strings.Join(parts, " ") + } + for { + f, ok := next() + if !ok { + return sp, true + } + switch { + case f == "-i" || f == "--ignore-environment" || f == "-": + sp.clear = true + case f == "--": + // Options are over; NAME=VALUE assignments are not. + for { + t, ok := peek() + if !ok || strings.HasPrefix(t, "-") || !strings.Contains(t, "=") { + break } - fields = fields[2:] - case strings.HasPrefix(f, "--unset="): - sp.unset = append(sp.unset, strings.TrimPrefix(f, "--unset=")) - fields = fields[1:] - case strings.HasPrefix(f, "-u") && len(f) > 2: - sp.unset = append(sp.unset, f[2:]) - fields = fields[1:] - case f == "-S" || f == "--split-string": - fields = sp.resplit(strings.Join(fields[1:], " ")) - case strings.HasPrefix(f, "--split-string="): - fields = sp.resplit(strings.TrimPrefix(f, "--split-string=") + " " + strings.Join(fields[1:], " ")) - case strings.HasPrefix(f, "-S") && len(f) > 2: - fields = sp.resplit(f[2:] + " " + strings.Join(fields[1:], " ")) - case strings.HasPrefix(f, "-C") && len(f) > 2: - sp.chdir = f[2:] - fields = fields[1:] - case strings.HasPrefix(f, "--chdir="): - sp.chdir = strings.TrimPrefix(f, "--chdir=") - fields = fields[1:] - case strings.HasPrefix(f, "-"): - // The other operand-free options. - fields = fields[1:] - case strings.Contains(f, "="): - sp.set = append(sp.set, f) - fields = fields[1:] - default: - break options + next() + sp.set = append(sp.set, t) + } + if t, ok := next(); ok { + sp.tokens = remaining(t) + } + return sp, true + case f == "-u" || f == "--unset" || f == "-C" || f == "--chdir": + operand, ok := next() + if !ok { + return sp, true + } + if f == "-u" || f == "--unset" { + sp.unset = append(sp.unset, operand) + } else { + sp.chdir = operand } + case strings.HasPrefix(f, "--unset="): + sp.unset = append(sp.unset, strings.TrimPrefix(f, "--unset=")) + case strings.HasPrefix(f, "-u") && len(f) > 2: + sp.unset = append(sp.unset, f[2:]) + case f == "-S" || f == "--split-string": + pending = sp.resplit(payloadFor("")) + case strings.HasPrefix(f, "--split-string="): + pending = sp.resplit(payloadFor(strings.TrimPrefix(f, "--split-string="))) + case strings.HasPrefix(f, "-S") && len(f) > 2: + pending = sp.resplit(payloadFor(f[2:])) + case strings.HasPrefix(f, "-C") && len(f) > 2: + sp.chdir = f[2:] + case strings.HasPrefix(f, "--chdir="): + sp.chdir = strings.TrimPrefix(f, "--chdir=") + case strings.HasPrefix(f, "-"): + // The other operand-free options. + case strings.Contains(f, "="): + sp.set = append(sp.set, f) + default: + sp.tokens = remaining(f) + return sp, true } } - sp.tokens = fields - return sp, true } // resplit parses an env -S payload the way env(1) would: honouring @@ -453,34 +538,41 @@ func childBaseEnv(set, unset []string, clear bool) []string { // interpreter against anything else runs a different interpreter than // the one the script's first line names -- or none, when the executable // exists only in the assigned PATH (#2611 review). +// +// Absence and emptiness are different states and are tracked as such: +// an ABSENT PATH (cleared with -i, unset with -u, or never inherited) +// gets execvp's default (/bin:/usr/bin), while an explicitly EMPTY +// PATH (PATH= in the shebang) stays empty, which execvp reads as +// "search the effective directory only" -- substituting the default +// for it would run a system executable the shebang did not name, or +// miss the one in the run's directory (#2611 review). func shebangPath(sp *shebangEnv) string { - path := os.Getenv("PATH") + path, present := os.LookupEnv("PATH") if sp.clear { - path = "" + path, present = "", false } for _, u := range sp.unset { if u == "PATH" { - path = "" + path, present = "", false } } for _, kv := range sp.set { if k, v, ok := strings.Cut(kv, "="); ok && k == "PATH" { - path = v + path, present = v, true } } - if path == "" { + if !present { // env(1) runs the command through execvp, which falls back to // a default path (confstr _CS_PATH: /bin:/usr/bin) when PATH is - // absent from the environment it builds -- the -i case. An - // empty effective PATH therefore means that default, not - // "nothing is findable". - path = "/bin:/usr/bin" + // absent from the environment it builds -- the -i case. + return "/bin:/usr/bin" } return path } // lookPathInDir is exec.LookPath against one explicit PATH value, -// with entries resolved against dir: an empty entry means the run's +// with entries resolved against dir: an empty PATH value means the +// effective directory alone, and an empty entry means the run's // effective directory (not mcpx's own), and so does any other relative // entry, the way execvp resolves them after env(1) has applied -C. The // result is absolute, so the later exec cannot reinterpret it against @@ -490,7 +582,13 @@ func lookPathInDir(bin, path, dir string) (string, error) { if err != nil { return "", err } - for _, entry := range filepath.SplitList(path) { + entries := filepath.SplitList(path) + if path == "" { + // An explicitly empty PATH is a single empty entry: the + // effective directory, and nothing else. + entries = []string{""} + } + for _, entry := range entries { if entry == "" { entry = abs } else if !filepath.IsAbs(entry) { diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 3c65bb9088..11bfd51d02 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -548,3 +548,77 @@ func TestRunShebangRelativePathEntryResolvesPostChdir(t *testing.T) { t.Errorf("res=%+v stdout=%q; want the interpreter from the -C directory", res, stdout.String()) } } + +// Assignments after env's "--" terminator still apply: the terminator +// ends options, not the [NAME=VALUE]... part of env's grammar, so +// "-- MODE=prod sh" runs sh with MODE=prod set rather than trying to +// execute a program named MODE=prod (#2611 review). +func TestParseShebangAssignmentsAfterTerminator(t *testing.T) { + for _, line := range []string{ + "#!/usr/bin/env -- MODE=prod sh", + "#!/usr/bin/env -S -- MODE=prod sh", + } { + sp, ok := parseShebang(line) + if !ok || strings.Join(sp.tokens, " ") != "sh" || strings.Join(sp.set, " ") != "MODE=prod" { + t.Errorf("parseShebang(%q) = %v set=%v, %v; want [sh] set=[MODE=prod], true", line, sp.tokens, sp.set, ok) + } + } +} + +// A -S payload reaches the splitter untouched: whitespace inside +// quotes is part of the argument, so 'a b' must not collapse to +// 'a b' on the way through fields-splitting (#2611 review). +func TestParseShebangSplitStringPreservesQuotedWhitespace(t *testing.T) { + line := `#!/usr/bin/env -S sh -c 'printf "<%s>" "a b"'` + want := []string{"sh", "-c", `printf "<%s>" "a b"`} + got, ok := ParseShebang(line) + if !ok || strings.Join(got, "\x00") != strings.Join(want, "\x00") { + t.Errorf("ParseShebang(%q) = %q, %v; want %q, true", line, got, ok, want) + } +} + +// An explicitly empty PATH (PATH=) is not an absent PATH: it stays +// empty (search the effective directory only), while -i and -u PATH +// make PATH absent and earn execvp's /bin:/usr/bin default +// (#2611 review). +func TestShebangPathEmptyVersusAbsent(t *testing.T) { + t.Setenv("PATH", "/ inherited") + if got := shebangPath(&shebangEnv{}); got != "/ inherited" { + t.Errorf("shebangPath(inherit) = %q, want the inherited PATH", got) + } + if got := shebangPath(&shebangEnv{set: []string{"PATH="}}); got != "" { + t.Errorf("shebangPath(PATH=) = %q, want empty (effective directory only)", got) + } + if got := shebangPath(&shebangEnv{clear: true}); got != "/bin:/usr/bin" { + t.Errorf("shebangPath(-i) = %q, want the execvp default", got) + } + if got := shebangPath(&shebangEnv{unset: []string{"PATH"}}); got != "/bin:/usr/bin" { + t.Errorf("shebangPath(-u PATH) = %q, want the execvp default", got) + } + if got := shebangPath(&shebangEnv{clear: true, set: []string{"PATH="}}); got != "" { + t.Errorf("shebangPath(-i PATH=) = %q, want empty: the assignment re-establishes PATH, empty", got) + } +} + +// End to end on the empty-PATH rule: an interpreter that exists only +// in the run's effective directory is found through PATH=, where the +// /bin:/usr/bin default would have missed it (#2611 review). +func TestRunShebangExplicitEmptyPathUsesEffectiveDir(t *testing.T) { + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "only-here-interp"), + []byte("#!/bin/sh\necho empty-path-resolved\n"), 0o755); err != nil { + t.Fatal(err) + } + f := writeScript(t, dir, "empty-path.sh", + "#!/usr/bin/env -S PATH= only-here-interp\necho unreachable\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: f, CwdPolicy: "script", Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("Run(PATH= shebang): %v", err) + } + if res.Runtime != "only-here-interp" || !strings.Contains(stdout.String(), "empty-path-resolved") { + t.Errorf("res=%+v stdout=%q; want the interpreter from the effective directory", res, stdout.String()) + } +} From 031db4d4929a21a998ade088751e395b2523b478 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 08:11:13 -0500 Subject: [PATCH 08/14] mcpx: fix the four Codex P2s on the shebang dispatch PR (#2611) JS shebang runtime resolved against the shebang PATH + effective dir (lookPathInDir override of rt.Bin); env -S payloads split with env split-string semantics (SplitEnvString: escape table incl. tab, ${VAR} expansion) instead of the shell tokenizer; hook options clear the main script interpreter; import preflight runs in the resolved execution directory (hoisted ResolveCwd). parity.md regenerated. --- pkgs/mcpx/docs/parity.md | 2 +- pkgs/mcpx/internal/execsvc/hooks.go | 7 ++ pkgs/mcpx/internal/runner/dispatch.go | 126 ++++++++++++++++++++- pkgs/mcpx/internal/runner/dispatch_test.go | 37 ++++++ pkgs/mcpx/internal/runner/runner.go | 40 ++++++- 5 files changed, 199 insertions(+), 13 deletions(-) diff --git a/pkgs/mcpx/docs/parity.md b/pkgs/mcpx/docs/parity.md index 2e13b86164..1d3f5b3e31 100644 --- a/pkgs/mcpx/docs/parity.md +++ b/pkgs/mcpx/docs/parity.md @@ -228,6 +228,6 @@ that will enforce it. `TestEveryEnforcedBoundaryNamesItsRefusal` holds both. | --- | --- | --- | --- | | `transport.allowedOrigins` | a web page on an origin that is not loopback, the daemon's own address or listed in transport.allowedOrigins cannot use /v1 or /mcp | **enforced** | `TestAWebPageCannotRunCodeThroughTheDaemon`, `TestV1AndMCPAgreeOnOrigins` | | `script.permissions` | a script runs with no more than the permission profile named; a runtime with no permission model refuses a narrowed profile | **enforced** | `TestScriptPermissionsIsReachableFromEverySurface`, `TestAStrictScriptCannotReadFilesOnARuntimeWithoutPermissions`, `TestARestrictedProfileIsRefusedByARuntimeThatCannotEnforceIt` | -| `elicit.confirmDestructive` | with it on, a call to a tool that may be destructive (annotated destructiveHint, or unannotated) does not run unless somebody confirms it | **enforced** | `TestADestructiveCallIsRefusedWhenNobodyConfirms`, `TestConfirmDestructiveHoldsOnAColdDaemon` | +| `elicit.confirmDestructive` | with it on, a call to a tool that may be destructive (annotated destructiveHint, or unannotated) does not run unless somebody confirms it; a remote server's annotation never clears the call (#2191) | **enforced** | `TestADestructiveCallIsRefusedWhenNobodyConfirms`, `TestConfirmDestructiveHoldsOnAColdDaemon` | | `autonomy.max` | mcpx does no more on its own than the daemon's autonomy.max allows: a prompt, a recipe run by name or a configured hook asked for above it is lowered to it and the answer says so, from /v1, the CLI, MCP and the plugin alike. It does not govern code a caller sends to /v1/exec itself | **enforced** | `TestV1CannotRaiseAutonomyAboveTheCeiling`, `TestTheCeilingCannotBeRaisedAtRuntime`, `TestTheCLICannotRaiseAutonomyAboveTheCeiling`, `TestMCPCannotRaiseAutonomyAboveTheCeiling`, `TestThePluginCannotRaiseAutonomyAboveTheCeiling`, `TestHooksFromConfigDoNotRunAboveTheCeiling`, `TestRepairCannotRaiseAutonomyAboveTheCeiling`, `TestACallerCannotRaiseAClampedSetting` | | `privileged operations (Admin)` | operations marked privileged change the daemon rather than read it; nothing checks who calls them, and every tool description and the OpenAPI document say so | **advisory** | #253 | diff --git a/pkgs/mcpx/internal/execsvc/hooks.go b/pkgs/mcpx/internal/execsvc/hooks.go index e7723b9f48..607a023785 100644 --- a/pkgs/mcpx/internal/execsvc/hooks.go +++ b/pkgs/mcpx/internal/execsvc/hooks.go @@ -227,6 +227,13 @@ func (s *Service) runOneHook(ctx context.Context, phase string, h Hook, hctx hoo } opts := ropts + // The main script's interpreter preference (script.interpreter) is + // not the hook's: hooks are TypeScript by definition here, and a + // configured sh interpreter would otherwise execute every hook's + // TypeScript under sh (Codex review, PR #2611). A hook's own + // shebang still selects its interpreter -- rank 1 in the runner's + // dispatch order is read from the hook script itself. + opts.Interpreter = "" // The hook gets the same runtime, permissions, working directory and // content-addressed client as the script, and nothing of the parent's // phases: a hook running the parent's onSuccess would recurse. diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index e6733f4132..0714a85e36 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -301,12 +301,11 @@ func parseShebang(line string) (shebangEnv, bool) { } } -// resplit parses an env -S payload the way env(1) would: honouring -// single and double quotes and backslash escapes, so quoted text -// stays one argument. A payload that does not parse records the -// error for decideDispatch and yields no tokens. +// resplit parses an env -S payload the way env(1) would. A payload +// that does not parse records the error for decideDispatch and +// yields no tokens. func (sp *shebangEnv) resplit(payload string) []string { - fields, err := SplitCommandLine(payload) + fields, err := SplitEnvString(payload) if err != nil { sp.splitErr = err return nil @@ -314,6 +313,115 @@ func (sp *shebangEnv) resplit(payload string) []string { return fields } +// SplitEnvString splits an env(1) -S/--split-string payload with +// env's own semantics, which are NOT the shell's: env defines a +// backslash escape table (\\, \", \', \t, \n, \r, \f, \v and +// \_ for a space) that applies inside quotes as well as outside -- +// the coreutils manual's own example, -S awk -v FS=\"\\t\" -f, +// depends on \\t becoming a tab, where a shell tokenizer leaves a +// literal "t" (Codex review, PR #2611). Quotes still group, as the +// earlier rounds of this parser established, and ${VAR} expands +// from the environment the payload itself is building (assignments +// already split, then the inherited one), as env expands it. +func SplitEnvString(s string) ([]string, error) { + var out []string + var word strings.Builder + quoted := byte(0) + started := false + assigned := map[string]string{} + seenCommand := false + flush := func() { + if !started { + return + } + f := word.String() + out = append(out, f) + word.Reset() + started = false + if !seenCommand { + if k, v, ok := strings.Cut(f, "="); ok && k != "" && !strings.ContainsAny(k, " \t") { + assigned[k] = v + } else { + seenCommand = true + } + } + } + expand := func(i int) (string, int, error) { + // s[i] == '$' and s[i+1] == '{'. + j := strings.IndexByte(s[i:], '}') + if j < 0 { + return "", 0, fmt.Errorf("unterminated ${ in env -S payload %q", s) + } + name := s[i+2 : i+j] + if v, ok := assigned[name]; ok { + return v, i + j + 1, nil + } + return os.Getenv(name), i + j + 1, nil + } + for i := 0; i < len(s); i++ { + c := s[i] + switch { + case c == '\\': + if i+1 >= len(s) { + return nil, fmt.Errorf("trailing backslash in env -S payload %q", s) + } + i++ + switch s[i] { + case 't': + word.WriteByte('\t') + case 'n': + word.WriteByte('\n') + case 'r': + word.WriteByte('\r') + case 'f': + word.WriteByte('\f') + case 'v': + word.WriteByte('\v') + case '_': + word.WriteByte(' ') + default: + word.WriteByte(s[i]) + } + started = true + case quoted != 0: + if c == quoted { + quoted = 0 + } else if c == '$' && quoted == '"' && i+1 < len(s) && s[i+1] == '{' { + v, ni, err := expand(i) + if err != nil { + return nil, err + } + word.WriteString(v) + i = ni - 1 + } else { + word.WriteByte(c) + } + started = true + case c == '\'' || c == '"': + quoted = c + started = true + case c == '$' && i+1 < len(s) && s[i+1] == '{': + v, ni, err := expand(i) + if err != nil { + return nil, err + } + word.WriteString(v) + i = ni - 1 + started = true + case c == ' ' || c == '\t': + flush() + default: + word.WriteByte(c) + started = true + } + } + if quoted != 0 { + return nil, fmt.Errorf("unterminated %q in env -S payload %q", string(quoted), s) + } + flush() + return out, nil +} + // filterEnv drops the named variables from env, leaving everything else // in order. The result is a fresh slice; env is not modified. func filterEnv(env []string, unset []string) []string { @@ -431,6 +539,12 @@ type jsChoice struct { unset []string clear bool chdir string + // path is the PATH env(1) would resolve the runtime against + // (shebangPath of the parsed wrapper), carried so the harness + // resolves the runtime against the shebang's environment and + // effective directory instead of mcpx's inherited PATH (Codex + // review, PR #2611). + path string } // decideDispatch applies ranks 1 and 2 of the dispatch order. A nil @@ -467,7 +581,7 @@ func decideDispatch(opts Options) (*dispatch, jsChoice, error) { return nil, jsChoice{}, errors.New("runner: the script's shebang line (#!) names no interpreter") } if len(sp.tokens) == 1 && isJSRuntimeName(opts.Setup, sp.tokens[0]) { - return nil, jsChoice{runtime: sp.tokens[0], set: sp.set, unset: sp.unset, clear: sp.clear, chdir: sp.chdir}, nil + return nil, jsChoice{runtime: sp.tokens[0], set: sp.set, unset: sp.unset, clear: sp.clear, chdir: sp.chdir, path: shebangPath(&sp)}, nil } d, err := dispatchFromTokens("shebang", sp.tokens, &sp) if err != nil { diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 11bfd51d02..1a262fec44 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -622,3 +622,40 @@ func TestRunShebangExplicitEmptyPathUsesEffectiveDir(t *testing.T) { t.Errorf("res=%+v stdout=%q; want the interpreter from the effective directory", res, stdout.String()) } } + +// TestSplitEnvStringUsesEnvSemantics is the Codex finding on +// PR #2611 (dispatch.go): the -S payload was split with the +// configured-interpreter (shell) tokenizer, whose escape rules +// turned the coreutils manual's own example FS=\"\\t\" into a +// literal FS="t" and left ${VAR} unexpanded. +func TestSplitEnvStringUsesEnvSemantics(t *testing.T) { + cases := []struct { + payload string + want []string + }{ + {`awk -v FS=\"\t\" -f`, []string{"awk", "-v", `FS="` + "\t" + `"`, "-f"}}, + {`sh -c "printf hello"`, []string{"sh", "-c", "printf hello"}}, + {`MODE=prod echo ${MODE}`, []string{"MODE=prod", "echo", "prod"}}, + {`echo a\_b`, []string{"echo", "a b"}}, + {"echo 'single quoted'", []string{"echo", "single quoted"}}, + } + for _, c := range cases { + got, err := SplitEnvString(c.payload) + if err != nil { + t.Errorf("SplitEnvString(%q): %v", c.payload, err) + continue + } + if len(got) != len(c.want) { + t.Errorf("SplitEnvString(%q) = %q, want %q", c.payload, got, c.want) + continue + } + for i := range got { + if got[i] != c.want[i] { + t.Errorf("SplitEnvString(%q)[%d] = %q, want %q (all: %q)", c.payload, i, got[i], c.want[i], got) + } + } + } + if _, err := SplitEnvString(`echo ${UNTERMINATED`); err == nil { + t.Error("SplitEnvString(unterminated ${): want an error") + } +} diff --git a/pkgs/mcpx/internal/runner/runner.go b/pkgs/mcpx/internal/runner/runner.go index d9ddca4388..499aa15f8d 100644 --- a/pkgs/mcpx/internal/runner/runner.go +++ b/pkgs/mcpx/internal/runner/runner.go @@ -315,6 +315,38 @@ func Run(ctx context.Context, opts Options) (*Result, error) { } } + // The execution directory is resolved here, once, because three + // consumers must agree on it: import preflight (a --config=./deno.json + // argument means the directory the run executes in, not the caller's), + // a JavaScript shebang's runtime lookup (relative PATH entries mean + // the directory the run moves to), and the subprocess itself. It was + // previously computed only for the subprocess, after preflight had + // already run against opts.Dir (Codex review, PR #2611). + execDir, derr := ResolveCwd(opts.CwdPolicy, opts.Dir, scriptPath, opts.ConfigDir, workDir) + if derr != nil { + return nil, derr + } + execDir = applyChdir(execDir, jsEnv.chdir) + + // A JavaScript shebang's runtime is resolved against the PATH the + // shebang itself establishes and the run's effective directory, + // the way env(1) resolves it: Resolve above used mcpx's inherited + // PATH, so #!/usr/bin/env -S PATH=/opt/project/node/bin node picked + // the wrong Node -- or none, when Node lived only there. Declared + // runtimes keep their configured binary; a path in the shebang is + // already verbatim. + if jsEnv.runtime != "" && !strings.Contains(jsEnv.runtime, "/") { + _, declared := opts.Setup.Runtimes[jsEnv.runtime] + _, declaredBase := opts.Setup.Runtimes[filepath.Base(jsEnv.runtime)] + if !declared && !declaredBase { + abs, lerr := lookPathInDir(jsEnv.runtime, jsEnv.path, execDir) + if lerr != nil { + return nil, fmt.Errorf("runner: shebang runtime %q not found on the shebang's PATH %q: %w", jsEnv.runtime, jsEnv.path, lerr) + } + rt.Bin = abs + } + } + // Checked after the launcher is written, because the launcher is what // actually gets run and therefore what has to be valid. Doing it here // also means a broken import is found before a single server starts. @@ -371,7 +403,7 @@ func Run(ctx context.Context, opts Options) (*Result, error) { rep = preflight.CheckImportsResolved(ctx, denoBin, scriptPath, preflight.ImportsMode(mode), preflight.DynamicImportMode(opts.ImportsOnDynamic), timeout, - rt.ConfigArgs, opts.Dir) + rt.ConfigArgs, execDir) } if err := rep.Err(); err != nil { return nil, err @@ -399,11 +431,7 @@ func Run(ctx context.Context, opts Options) (*Result, error) { // command line; the client import still resolves against the script // file, because ESM resolves relative specifiers against the // importing module. - dir, derr := ResolveCwd(opts.CwdPolicy, opts.Dir, scriptPath, opts.ConfigDir, workDir) - if derr != nil { - return nil, derr - } - cmd.Dir = applyChdir(dir, jsEnv.chdir) + cmd.Dir = execDir // The kind, not the configured name: a script branching on its runtime // cares whether it is under Deno, not what somebody called the binary. // A JavaScript shebang's env(1) changes apply here too, and names the From 4fff16aadd574f13b316934a7aa92d40c07bd2f7 Mon Sep 17 00:00:00 2001 From: repo-worker Date: Fri, 30 Oct 2026 09:04:27 -0500 Subject: [PATCH 09/14] WIP: disposition CodeRabbit round on 031db4d4 (#2167) --- pkgs/mcpx/docs/environment.md | 6 +++- pkgs/mcpx/internal/daemon/routes_exec.go | 22 ++++++++++--- pkgs/mcpx/internal/runner/dispatch.go | 28 +++++++++++++++- pkgs/mcpx/internal/runner/runner.go | 15 ++++++++- pkgs/mcpx/internal/runner/runtimes.go | 41 ++++++++++++++++++++++++ pkgs/mcpx/internal/settings/scriptenv.go | 2 +- 6 files changed, 106 insertions(+), 8 deletions(-) diff --git a/pkgs/mcpx/docs/environment.md b/pkgs/mcpx/docs/environment.md index 1b7c14f232..39e004776e 100644 --- a/pkgs/mcpx/docs/environment.md +++ b/pkgs/mcpx/docs/environment.md @@ -45,7 +45,11 @@ The table below is generated from `settings.ScriptEnv()` in ## This table is what mcpx adds, not all a child gets Every one of these is *added to* the environment mcpx itself was started with. -A child gets the parent's environment entire, and then these on top: +A child gets the parent's environment entire, and then these on top — unless its +shebang replaces part of it: `env -i` starts the child from an empty +environment, and `env -u NAME` removes just that name (both then get these on +top). Both the dispatched path and the JavaScript path apply what the shebang +asked for. - `internal/runner/runner.go:359` — `cmd.Env = append(os.Environ(), …)`, every script the runner starts diff --git a/pkgs/mcpx/internal/daemon/routes_exec.go b/pkgs/mcpx/internal/daemon/routes_exec.go index 3e2a355913..29fb819b92 100644 --- a/pkgs/mcpx/internal/daemon/routes_exec.go +++ b/pkgs/mcpx/internal/daemon/routes_exec.go @@ -59,6 +59,11 @@ func (s *Server) execSettings() *settings.Set { } set := settings.NewSet(sch) if s.cfg != nil && s.cfg.Path != "" { + // The path the settings were read from, kept with them: + // script.cwd=config has to resolve against the directory + // of the file this policy came from, not of whichever file + // a later reload moved s.cfg to (#2611 review). + s.execSetPath = s.cfg.Path if b, rerr := os.ReadFile(s.cfg.Path); rerr == nil { var doc map[string]any if json.Unmarshal(config.StripJSONC(b), &doc) == nil { @@ -189,11 +194,15 @@ func (s *Server) ExecService() *execsvc.Service { lim.InterceptImages = set.Bool("artifacts.interceptImages") // script.cwd=config resolves against the directory holding the - // configuration this daemon loaded -- the same cfg.Path the info - // file and the resolve route report. Without it every /v1/exec run - // under that policy fails in ResolveCwd before the script starts. + // configuration the exec policy was built from -- the file + // execSettings read, not whichever file a reload has since moved + // s.cfg to. Without it every /v1/exec run under that policy fails in + // ResolveCwd before the script starts; with s.cfg it could point at + // the wrong directory after a reload (#2611 review). configDir := "" - if cfg := s.currentConfig(); cfg != nil && cfg.Path != "" { + if s.execSetPath != "" { + configDir = filepath.Dir(s.execSetPath) + } else if cfg := s.currentConfig(); cfg != nil && cfg.Path != "" { configDir = filepath.Dir(cfg.Path) } @@ -503,6 +512,11 @@ type artifactState struct { artifactsErr error execSetOnce sync.Once execSet *settings.Set + // execSetPath is the configuration file execSettings built execSet + // from. script.cwd=config resolves against its directory, so a + // reload that moves s.cfg cannot redirect a policy already in force + // (#2611 review). + execSetPath string } // InlineArtifact renders one artifact as an MCP resource body. diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 0714a85e36..1f473fffef 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -139,6 +139,10 @@ type shebangEnv struct { // unterminated quote). It is reported by decideDispatch; the // exported ParseShebang wrappers keep best-effort tokens. splitErr error + // optErr is an env(1) option the shebang used that this dispatcher + // does not implement. Reported by decideDispatch, which refuses the + // run rather than dropping the option (#2611 review). + optErr error } // parseShebang reads a #! line. Options of an env(1) shebang are @@ -291,7 +295,15 @@ func parseShebang(line string) (shebangEnv, bool) { case strings.HasPrefix(f, "--chdir="): sp.chdir = strings.TrimPrefix(f, "--chdir=") case strings.HasPrefix(f, "-"): - // The other operand-free options. + // Anything left is an env(1) option this dispatcher cannot + // honour. Silently dropping it would run a different command + // than the shebang names -- `#!/usr/bin/env -S --bogus sh` + // would run sh with the option ignored -- and the options + // that would be dropped are not all inert: -0 makes env + // reject a command outright, -v/--debug write their own + // output to stderr (#2611 review). + sp.optErr = fmt.Errorf("%s is not a supported env option in a shebang", f) + return sp, true case strings.Contains(f, "="): sp.set = append(sp.set, f) default: @@ -577,6 +589,9 @@ func decideDispatch(opts Options) (*dispatch, jsChoice, error) { if sp.splitErr != nil { return nil, jsChoice{}, fmt.Errorf("runner: shebang -S payload: %w", sp.splitErr) } + if sp.optErr != nil { + return nil, jsChoice{}, fmt.Errorf("runner: shebang: %w", sp.optErr) + } if len(sp.tokens) == 0 { return nil, jsChoice{}, errors.New("runner: the script's shebang line (#!) names no interpreter") } @@ -739,6 +754,17 @@ func dispatchFromTokens(source string, tokens []string, sp *shebangEnv) (*dispat d.lookupBin, d.lookupPath = bin, shebangPath(sp) return d, nil } + // Always deferred, found or not: a relative PATH entry means the + // directory the run moves to, not mcpx's own, so a lookup here can + // both miss the right binary and find a different one. runDispatched + // resolves against the run's effective directory and reports the + // not-found error with the PATH it tried (#2611 review). A PATH that + // is absent from the environment keeps exec.LookPath's answer, since + // there is nothing to defer to. + if path, ok := os.LookupEnv("PATH"); ok { + d.lookupBin, d.lookupPath = bin, path + return d, nil + } p, err := exec.LookPath(bin) if err != nil { return nil, fmt.Errorf("runner: %s interpreter %q not found on PATH: %w", source, bin, err) diff --git a/pkgs/mcpx/internal/runner/runner.go b/pkgs/mcpx/internal/runner/runner.go index 499aa15f8d..de39dcbc22 100644 --- a/pkgs/mcpx/internal/runner/runner.go +++ b/pkgs/mcpx/internal/runner/runner.go @@ -214,7 +214,20 @@ func Run(ctx context.Context, opts Options) (*Result, error) { } rt, err := Resolve(opts.Runtime, opts.Permissions, opts.Setup) if err != nil { - return nil, err + // A JavaScript shebang's runtime is looked up against the PATH + // the shebang establishes, below, once the run's directory is + // known. Rejecting here searched mcpx's inherited PATH instead, + // so `#!/usr/bin/env -S PATH=/project/node/bin node` failed + // before the shebang's own PATH was ever consulted (#2611 + // review). The later block fills in Bin, and reports a runtime + // that is missing from both. + if jsEnv.runtime == "" { + return nil, err + } + rt, err = ResolveDeferred(jsEnv.runtime, opts.Permissions, opts.Setup) + if err != nil { + return nil, err + } } workDir := opts.WorkDir diff --git a/pkgs/mcpx/internal/runner/runtimes.go b/pkgs/mcpx/internal/runner/runtimes.go index 174c09d868..05b3bad971 100644 --- a/pkgs/mcpx/internal/runner/runtimes.go +++ b/pkgs/mcpx/internal/runner/runtimes.go @@ -407,6 +407,47 @@ func Resolve(prefer, permSpec string, s Setup) (*Runtime, error) { strings.Join(names, ", "), strings.Join(tried, "\n ")) } +// ResolveDeferred is Resolve for a runtime the caller will look up +// itself against a PATH it establishes. Same resolution and the same +// refusals, except that a binary absent from mcpx's own PATH comes back +// as its bare name instead of an error: a JavaScript shebang may name a +// runtime that exists only on the PATH the shebang sets, and that PATH +// cannot be applied until the run's effective directory is known +// (#2611 review). Resolve would reject it first and the run would fail +// with "not found" for a runtime the shebang's own environment has. +// +// A declared runtime keeps Resolve's behaviour: its binary is part of +// its declaration, not a question about PATH. +func ResolveDeferred(prefer, permSpec string, s Setup) (*Runtime, error) { + rt, err := Resolve(prefer, permSpec, s) + if err == nil { + return rt, nil + } + if prefer == "" || prefer == "auto" || strings.Contains(prefer, "/") { + return nil, err + } + if _, declared := s.Runtimes[prefer]; declared { + return nil, err + } + if !knownKind(prefer) { + // Only a kind name says how to build an argv without running + // the binary to find out what it is. + return nil, err + } + steps, perr := parseSpec(permSpec) + if perr != nil { + return nil, perr + } + perms, ref, rerr := s.renderPerms(steps, prefer) + if rerr != nil { + return nil, rerr + } + if ref != nil { + return nil, fmt.Errorf("%s", ref.msg(prefer)) + } + return build(candidate{name: prefer, kind: prefer, bin: prefer}, perms), nil +} + func build(c candidate, perms []string) *Runtime { rt := &Runtime{Name: c.name, Kind: c.kind, Bin: c.bin, Perms: perms, ConfigArgs: append([]string(nil), c.args...)} diff --git a/pkgs/mcpx/internal/settings/scriptenv.go b/pkgs/mcpx/internal/settings/scriptenv.go index ae7e7d33ea..90f1cf574b 100644 --- a/pkgs/mcpx/internal/settings/scriptenv.go +++ b/pkgs/mcpx/internal/settings/scriptenv.go @@ -264,7 +264,7 @@ func ScriptEnv() []EnvVar { Name: "MCPX_RUNTIME", SetBy: []Setter{SetByRunner}, Meaning: "deno, bun or node; on a dispatched run, the interpreter's name (sh, python3)", - ReadBy: client, + ReadBy: client + "; on a dispatched run, the script itself", }, { Name: "MCPX_DISPATCH", From 05b113ed250f8841ccde59dcc8741bf6d887430f Mon Sep 17 00:00:00 2001 From: repo-worker Date: Fri, 30 Oct 2026 09:09:50 -0500 Subject: [PATCH 10/14] fix(mcpx): disposition the CodeRabbit round on the dispatch PR (#2167) Six findings from the review of 031db4d4, all verified against the code before fixing: - Major: a JavaScript shebang's runtime is resolved against mcpx's inherited PATH before the shebang's own PATH is applied, so a node that exists only on the shebang's PATH failed with "not found". ResolveDeferred keeps the runtime when only the binary is missing and the existing lookPathInDir block fills it in from the shebang PATH. - script.interpreter was resolved with exec.LookPath at decide time, so a relative PATH entry was checked against mcpx's directory instead of the run's. Deferred to runDispatched, as the shebang branch already is. - An unrecognised env(1) option was silently dropped, running a different command than the shebang names. It now fails with a precise error; -0 and -v/--debug are in that class. - ConfigDir for script.cwd=config came from the reloaded s.cfg while the exec policy was cached from the original file; a reload could move the policy's directory. The cached set now carries the path it read. - environment.md said a child always inherits the parent's environment entire; env -i and env -u change that. Qualified. - MCPX_RUNTIME's reader on a dispatched run is the script itself, not only the generated client. Table regenerated. Effect probes added for script.cwd and script.interpreter, the two settings this PR introduced: without them the registry entry could be decoration. --- pkgs/mcpx/docs/configuration.md | 27 ++++--- pkgs/mcpx/docs/environment.md | 2 +- .../internal/e2e/dispatch_settings_test.go | 57 ++++++++++++++ pkgs/mcpx/internal/e2e/effect_test.go | 2 + pkgs/mcpx/internal/runner/dispatch_test.go | 78 +++++++++++++++++++ pkgs/mcpx/internal/settings/effect.go | 2 + 6 files changed, 155 insertions(+), 13 deletions(-) create mode 100644 pkgs/mcpx/internal/e2e/dispatch_settings_test.go diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index 4c351994ba..5af14ac9e4 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -249,6 +249,21 @@ field. This is deliberately not a setting: it is how `mcpx init` wrote `"mode": "session"` into every new config for months without anyone noticing, and a switch to turn the report off would have kept it quiet. +A script whose first line names its interpreter (`#!`) runs under that +interpreter, ahead of every setting below: a `-S`/`--split-string` +payload is re-split with shell quoting rules (so `-S sh -c "printf +hello"` keeps `printf hello` one argument; an unterminated quote fails +the run), `VAR=value` assignments reach the child even when the value +contains `/`, `env -u`/`env -i` apply (the child starts from the parent's +environment minus what they remove, or from an empty one), and +`env -C`/`env --chdir` moves the run, beating `script.cwd` the way the +interpreter choice beats `script.runtime`. An env option mcpx does not +implement fails the run rather than being dropped. A dispatched run +never inherits `MCPX_CLIENT`, `MCPX_RUNTIME`, `MCPX_ENTRY` or +`MCPX_DISPATCH` from an outer run, and its notice names anything else it +goes without (no generated client, no enforced permission profiles, +skipped launcher phases). + ### artifacts @@ -600,18 +615,6 @@ and a switch to turn the report off would have kept it quiet. | `script.suffix` | source | *(empty)* | client | no | `--script-suffix` | `MCPX_SCRIPT_SUFFIX` | runs last on both paths, like a finally | | `script.typecheck` | enum | `off` | client | no | `--script-typecheck` | `MCPX_SCRIPT_TYPECHECK` | check the generated program before running it | -A script whose first line names its interpreter (`#!`) runs under that -interpreter, ahead of every setting above: a `-S`/`--split-string` -payload is re-split with shell quoting rules (so `-S sh -c "printf -hello"` keeps `printf hello` one argument; an unterminated quote fails -the run), `VAR=value` assignments reach the child even when the value -contains `/`, `env -u`/`env -i` apply, and `env -C`/`env --chdir` moves -the run, beating `script.cwd` the way the interpreter choice beats -`script.runtime`. A dispatched run never inherits `MCPX_CLIENT`, -`MCPX_RUNTIME`, `MCPX_ENTRY` or `MCPX_DISPATCH` from an outer run, and -its notice names anything else it goes without (no generated client, no -enforced permission profiles, skipped launcher phases). - ### search | setting | kind | default | scope | hot | flag | variable | governs | diff --git a/pkgs/mcpx/docs/environment.md b/pkgs/mcpx/docs/environment.md index 39e004776e..b6e4823d98 100644 --- a/pkgs/mcpx/docs/environment.md +++ b/pkgs/mcpx/docs/environment.md @@ -117,7 +117,7 @@ and read by name for that reason. | `MCPX_CONFIG_PATH` | `mcpx exec` / `mcpx run` | always | the nearest configuration file in effect, empty when there is none | the generated client (paths.config) | | `MCPX_SCRIPT_DIRS` | `mcpx exec` / `mcpx run` | always | the directories searched for named scripts, nearest first, colon-separated | the generated client (paths.scriptDirs) | | `MCPX_API_DECLARATION_SHA256` | `mcpx exec` / `mcpx run` | always | the fingerprint of a declared API's declaration, set on the child a declared API launches: PoolID hashes the environment, so editing the declaration replaces the pool instead of keeping a child started for the old one | the pool, as a pool identity input (api serve: PoolID hashes the server environment) | -| `MCPX_RUNTIME` | the runner, for every script | always | deno, bun or node; on a dispatched run, the interpreter's name (sh, python3) | the generated client | +| `MCPX_RUNTIME` | the runner, for every script | always | deno, bun or node; on a dispatched run, the interpreter's name (sh, python3) | the generated client; on a dispatched run, the script itself | | `MCPX_DISPATCH` | the runner, for every script | only on a dispatched (non-JavaScript) run | how the interpreter was chosen: shebang or interpreter (script.interpreter) | the script itself, and anyone reading its environment | | `MCPX_ALLOW_READ` | the runner, for every script | only when the permissions allow reading files | 1: the client's file helpers may read. Without it they refuse, naming the permission, rather than leaving it to the sandbox | the generated client | | `MCPX_LOG_LEVEL` | `mcpx exec` / `mcpx run` | always | the lowest level the script's log keeps | the generated client; `mcpx` run inside the script or shell reads it as logging.level; also the setting `logging.level` | diff --git a/pkgs/mcpx/internal/e2e/dispatch_settings_test.go b/pkgs/mcpx/internal/e2e/dispatch_settings_test.go new file mode 100644 index 0000000000..0727e5e61b --- /dev/null +++ b/pkgs/mcpx/internal/e2e/dispatch_settings_test.go @@ -0,0 +1,57 @@ +package e2e_test + +// Effect probes for the dispatch settings (#2167): the two knobs that +// decide whether a script runs under an interpreter and where it runs +// must reach the CLI from the environment like every other setting, or +// the settings registry entry is decoration. + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +// MCPX_SCRIPT_INTERPRETER makes `mcpx exec` run the source under that +// command line instead of a JavaScript runtime. The source is not a +// TypeScript program, so without the setting the run cannot produce +// this output. +func TestScriptInterpreterIsReachableFromTheEnvironment(t *testing.T) { + e := newEnv(t, oneServer) + saved := e.envVars + e.envVars = append(append([]string{}, saved...), "MCPX_SCRIPT_INTERPRETER=sh") + defer func() { e.envVars = saved }() + + out := e.run("exec", "echo from-the-configured-interpreter") + if !strings.Contains(out, "from-the-configured-interpreter") { + t.Fatalf("MCPX_SCRIPT_INTERPRETER should run the source under sh:\n%s", out) + } +} + +// MCPX_SCRIPT_CWD=script moves a dispatched run to the script's own +// directory; the default (caller) leaves it where mcpx was invoked, so +// the two are distinguishable from the script's own pwd. +func TestScriptCwdIsReachableFromTheEnvironment(t *testing.T) { + e := newEnv(t, oneServer) + sub := filepath.Join(e.dir, "scripts") + if err := os.MkdirAll(sub, 0o755); err != nil { + t.Fatal(err) + } + script := filepath.Join(sub, "where.sh") + if err := os.WriteFile(script, []byte("#!/bin/sh\npwd\n"), 0o755); err != nil { + t.Fatal(err) + } + saved := e.envVars + e.envVars = append(append([]string{}, saved...), "MCPX_SCRIPT_CWD=script") + defer func() { e.envVars = saved }() + + out := e.run("run", script) + // The dispatch notice shares the stream; the script's pwd is the + // last line it printed. + lines := strings.Split(strings.TrimSpace(out), "\n") + got, _ := filepath.EvalSymlinks(strings.TrimSpace(lines[len(lines)-1])) + want, _ := filepath.EvalSymlinks(sub) + if got != want { + t.Fatalf("MCPX_SCRIPT_CWD=script: pwd = %q, want %q\n%s", got, want, out) + } +} diff --git a/pkgs/mcpx/internal/e2e/effect_test.go b/pkgs/mcpx/internal/e2e/effect_test.go index b27f7d5014..94d3ab4896 100644 --- a/pkgs/mcpx/internal/e2e/effect_test.go +++ b/pkgs/mcpx/internal/e2e/effect_test.go @@ -34,6 +34,8 @@ var implementedEffectProbes = map[string]string{ "pool.scope": "TestPoolDefaultsAreReachableFromTheEnvironment", "output.json": "TestOutputJSONIsReachableFromTheEnvironment", "script.prefix": "TestScriptPrefixIsReachableFromTheEnvironment", + "script.cwd": "TestScriptCwdIsReachableFromTheEnvironment", + "script.interpreter": "TestScriptInterpreterIsReachableFromTheEnvironment", "script.env": "TestScriptEnvIsReachableFromTheEnvironment", "script.captureConsole": "TestScriptCaptureConsoleOffDropsConsoleOutput", "script.typecheck": "TestScriptTypecheckOnRefusesATypeError", diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 1a262fec44..4750140d81 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -659,3 +659,81 @@ func TestSplitEnvStringUsesEnvSemantics(t *testing.T) { t.Error("SplitEnvString(unterminated ${): want an error") } } + +// A JavaScript shebang's runtime may exist only on the PATH the shebang +// sets, and that PATH is applied after the run's directory is known. +// Resolve runs first, against mcpx's inherited PATH, and must not reject +// the runtime before the shebang's own PATH is consulted (#2611 review, +// Major). +func TestRunJSRuntimeShebangFoundOnlyOnShebangPath(t *testing.T) { + dir := t.TempDir() + // A stand-in runtime of the node kind: it has to be found and + // executed, not be a real Node, because the point is resolution. + fake := writeScript(t, dir, "node", "#!/bin/sh\necho fake-node-ran\nexit 0\n") + _ = fake + script := writeScript(t, dir, "app.mjs", + "#!/usr/bin/env -S PATH="+dir+" node\nexport default () => 1\n") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: script, Stdout: &stdout, Stderr: &stderr, + ClientSource: codegen.Module(nil, "", ""), + }) + if err != nil { + t.Fatalf("Run(node on the shebang's PATH only): %v", err) + } + if res.Runtime != "node" { + t.Errorf("Runtime = %q, want node", res.Runtime) + } + if !strings.Contains(stdout.String(), "fake-node-ran") { + t.Errorf("stdout = %q; the shebang's own node must have run", stdout.String()) + } +} + +// A configured script.interpreter is looked up against the directory the +// run moves to, the way a shebang's is: a relative PATH entry means the +// run's directory, so an interpreter that exists only there must be +// found (#2611 review). +func TestRunInterpreterResolvedInRunDirectory(t *testing.T) { + base := t.TempDir() + scriptDir := filepath.Join(base, "project") + if err := os.MkdirAll(filepath.Join(scriptDir, "bin"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(scriptDir, "bin", "custom-interp-3201"), + []byte("#!/bin/sh\necho interpreter-from-run-dir\n"), 0o755); err != nil { + t.Fatal(err) + } + f := writeScript(t, scriptDir, "run.sh", "echo unreachable\n") + t.Setenv("PATH", "bin") + var stdout, stderr bytes.Buffer + res, err := Run(context.Background(), Options{ + File: f, Dir: scriptDir, CwdPolicy: "script", Interpreter: "custom-interp-3201", + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("Run(relative PATH entry, script.interpreter): %v", err) + } + if res.ExitCode != 0 || !strings.Contains(stdout.String(), "interpreter-from-run-dir") { + t.Errorf("res=%+v stdout=%q; want the interpreter from the run directory", res, stdout.String()) + } +} + +// An env option mcpx does not implement fails the run instead of being +// dropped: dropping it runs a different command than the shebang names, +// and -0/-v are not inert (#2611 review). +func TestRunRejectsUnsupportedEnvOption(t *testing.T) { + dir := t.TempDir() + for _, opt := range []string{"--bogus", "-0", "-v", "--debug"} { + f := writeScript(t, dir, "opt.sh", "#!/usr/bin/env -S "+opt+" sh\necho unreachable\n") + var stdout, stderr bytes.Buffer + _, err := Run(context.Background(), Options{ + File: f, Stdout: &stdout, Stderr: &stderr, + }) + if err == nil || !strings.Contains(err.Error(), "not a supported env option") { + t.Errorf("option %s: want a precise option error, got %v", opt, err) + } + if strings.Contains(stdout.String(), "unreachable") { + t.Errorf("option %s: the script ran despite the unsupported option", opt) + } + } +} diff --git a/pkgs/mcpx/internal/settings/effect.go b/pkgs/mcpx/internal/settings/effect.go index 2ca378c11d..120817e2f1 100644 --- a/pkgs/mcpx/internal/settings/effect.go +++ b/pkgs/mcpx/internal/settings/effect.go @@ -56,6 +56,8 @@ var EffectProbes = map[string]string{ "registry.pageSize": "TestRegistryPageSizeChangesWhatTheCLIAsksFor", "registry.maxPages": "TestTheRegistryPageCapSaysItStoppedEarly", "paths.configFile": "TestPathsConfigFileChangesWhichConfigLoads", + "script.cwd": "TestScriptCwdIsReachableFromTheEnvironment", + "script.interpreter": "TestScriptInterpreterIsReachableFromTheEnvironment", } // EffectExemptions maps a setting path to the reason no effect probe From 39240a45241abb7bddbbd0f7cf8871dde2b3e7ed Mon Sep 17 00:00:00 2001 From: repo-worker Date: Fri, 30 Oct 2026 10:57:57 -0500 Subject: [PATCH 11/14] fix(mcpx): disposition the two Codex P2s on the dispatch PR (#2167) - SplitCommandLine consumed every backslash inside double quotes, so script.interpreter = 'awk -v FS="\t" -f' passed FS=t and split on the letter t. A backslash inside double quotes is now literal unless it precedes one of the characters the shell still escapes there ($ ` " \ and newline); unquoted and single-quoted behaviour is unchanged. - inlineSource prepended the configured prefix ahead of an inline snippet's shebang, so dispatch saw a prefix line as the first line and sent a valid shell snippet to the JavaScript harness. The snippet's shebang now stays on line 1 and the prefix runs after it. Tests: TestSplitCommandLine gains the awk/double-quote cases, TestInlineSourceKeepsAShebangFirst/WithoutShebangIsUnchanged cover the splice. --- pkgs/mcpx/internal/cli/commands.go | 18 ++++++++++- pkgs/mcpx/internal/cli/inline_shebang_test.go | 31 +++++++++++++++++++ pkgs/mcpx/internal/runner/dispatch.go | 14 ++++++++- pkgs/mcpx/internal/runner/dispatch_test.go | 17 ++++++++++ 4 files changed, 78 insertions(+), 2 deletions(-) create mode 100644 pkgs/mcpx/internal/cli/inline_shebang_test.go diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index 16f3fac972..443e4a272a 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -2268,13 +2268,29 @@ type scriptShape struct { // inlineSource splices prefix and suffix lines around a snippet. A snippet is // generated wholesale, so prefix lines share its scope and can declare // bindings the snippet uses. +// +// A snippet's own shebang goes first, ahead of the prefix. Dispatch reads the +// first line to decide the interpreter (#2167), and a shell prefix line in +// front of it hid the shebang: `mcpx exec --prefix 'echo before' $'#!/bin/sh\necho hello'` +// then went to the JavaScript harness instead of sh (#2611 review). The +// shebang is still the program's own first line; the prefix runs after it, +// which is the order the interpreter would have imposed anyway. func (sh scriptShape) inlineSource(args []string) string { var body strings.Builder + var rest strings.Builder + rest.WriteString(strings.Join(args, " ")) + if first := rest.String(); strings.HasPrefix(first, "#!") { + line, tail, _ := strings.Cut(first, "\n") + body.WriteString(line) + body.WriteString("\n") + rest.Reset() + rest.WriteString(tail) + } for _, line := range sh.prefix { body.WriteString(line) body.WriteString("\n") } - body.WriteString(strings.Join(args, " ")) + body.WriteString(rest.String()) for _, line := range sh.suffix { body.WriteString("\n") body.WriteString(line) diff --git a/pkgs/mcpx/internal/cli/inline_shebang_test.go b/pkgs/mcpx/internal/cli/inline_shebang_test.go new file mode 100644 index 0000000000..fefbee1c53 --- /dev/null +++ b/pkgs/mcpx/internal/cli/inline_shebang_test.go @@ -0,0 +1,31 @@ +package cli + +// A snippet's own shebang must survive the prefix splice: dispatch reads +// the first line to pick the interpreter, and a prefix line in front of a +// shebang sent a valid shell snippet to the JavaScript harness (#2611 +// review). + +import ( + "strings" + "testing" +) + +func TestInlineSourceKeepsAShebangFirst(t *testing.T) { + sh := scriptShape{prefix: []string{`echo before`}} + got := sh.inlineSource([]string{"#!/bin/sh\necho hello"}) + if !strings.HasPrefix(got, "#!/bin/sh\n") { + t.Fatalf("the snippet's shebang must stay on line 1:\n%s", got) + } + if !strings.Contains(got, "echo before") || !strings.Contains(got, "echo hello") { + t.Fatalf("prefix and body must both survive:\n%s", got) + } +} + +func TestInlineSourceWithoutShebangIsUnchanged(t *testing.T) { + sh := scriptShape{prefix: []string{"const a = 1"}, suffix: []string{"const b = 2"}} + got := sh.inlineSource([]string{"console.log(1)"}) + want := "const a = 1\nconsole.log(1)\nconst b = 2" + if got != want { + t.Errorf("got %q, want %q", got, want) + } +} diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 1f473fffef..03dc5d35e7 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -494,8 +494,20 @@ func SplitCommandLine(s string) ([]string, error) { word.WriteByte(c) escaped = false started = true - case c == '\\' && quoted != '\'': + case c == '\\' && quoted == 0: escaped = true + case c == '\\' && quoted == '"': + // Inside double quotes the shell keeps a backslash literal + // unless it precedes one of the characters it still escapes + // ($ ` " \ and newline). Consuming every backslash turned + // `awk -v FS="\t" -f` into `FS=t`, splitting on the letter t + // (#2611 review). + if i+1 < len(s) && strings.ContainsRune("$`\"\\\n", rune(s[i+1])) { + escaped = true + } else { + word.WriteByte(c) + started = true + } case quoted != 0: if c == quoted { quoted = 0 diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 4750140d81..041e363dab 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -323,6 +323,23 @@ func TestSplitCommandLine(t *testing.T) { if _, err := SplitCommandLine(`"unterminated`); err == nil { t.Error("unterminated quote: want an error") } + // Inside double quotes a backslash is literal unless it precedes one + // of the characters the shell still escapes there: awk needs "\t" to + // arrive as a backslash and a t, not as a tab or as a bare t (#2611 + // review). + got, err = SplitCommandLine(`awk -v FS="\t" -f`) + if err != nil || len(got) != 4 || got[2] != `FS=\t` { + t.Errorf("double-quoted backslash: %v, %v; want FS=\\t", got, err) + } + got, err = SplitCommandLine(`sh -c "printf \"<%s>\" x"`) + if err != nil || len(got) != 3 || got[2] != `printf "<%s>" x` { + t.Errorf("escaped quote in double quotes: %v, %v", got, err) + } + // Outside quotes a backslash escapes the next character as before. + got, err = SplitCommandLine(`awk -v FS=\t -f`) + if err != nil || got[2] != "FS=t" { + t.Errorf("unquoted escape: %v, %v", got, err) + } } func TestResolveCwdPolicies(t *testing.T) { From fd64ab0561c7f311d0e2f4deacaffb51635d19ac Mon Sep 17 00:00:00 2001 From: repo-worker Date: Fri, 30 Oct 2026 11:14:42 -0500 Subject: [PATCH 12/14] fix(mcpx): keep backslashes literal in single-quoted env -S payloads (#2167) Codex P2 on 39240a45: SplitEnvString decoded every backslash escape even inside single quotes, so a shebang running python3 -c 'import re; print(bool(re.search(r"\\d", "5")))' got r"d" and printed False. env's own table limits single-quote escapes to \' and \\; every other backslash is now left alone. Double-quoted and unquoted payloads are unchanged. --- pkgs/mcpx/internal/runner/dispatch.go | 12 ++++++++++++ pkgs/mcpx/internal/runner/dispatch_test.go | 6 ++++++ 2 files changed, 18 insertions(+) diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 03dc5d35e7..5fa740fe6b 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -373,6 +373,18 @@ func SplitEnvString(s string) ([]string, error) { for i := 0; i < len(s); i++ { c := s[i] switch { + case c == '\\' && quoted == '\'': + // env's manual: inside single quotes only \' and \\ are + // escapes; every other backslash stays literal. Decoding + // them turned python3 -c '…re.search(r"\d", "5")…' into + // r"d" and changed the program's answer (#2611 review). + if i+1 < len(s) && (s[i+1] == '\'' || s[i+1] == '\\') { + i++ + word.WriteByte(s[i]) + } else { + word.WriteByte(c) + } + started = true case c == '\\': if i+1 >= len(s) { return nil, fmt.Errorf("trailing backslash in env -S payload %q", s) diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 041e363dab..fc4d160639 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -655,6 +655,12 @@ func TestSplitEnvStringUsesEnvSemantics(t *testing.T) { {`MODE=prod echo ${MODE}`, []string{"MODE=prod", "echo", "prod"}}, {`echo a\_b`, []string{"echo", "a b"}}, {"echo 'single quoted'", []string{"echo", "single quoted"}}, + // Inside single quotes only \' and \\ are escapes; every other + // backslash is literal, or a regexp like r"\d" loses its + // backslash and matches something else (#2611 review). + {`python3 -c 'import re; print(bool(re.search(r"\d", "5")))'`, + []string{"python3", "-c", `import re; print(bool(re.search(r"\d", "5")))`}}, + {`echo 'it\'s'`, []string{"echo", "it's"}}, } for _, c := range cases { got, err := SplitEnvString(c.payload) From bdd9231f68f4874fe3dbe7515522c78c27c41ac0 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Fri, 30 Oct 2026 23:13:06 -0500 Subject: [PATCH 13/14] =?UTF-8?q?mcpx:=20env=20-S=20splitter=20+=20workdir?= =?UTF-8?q?=20dispatch=20=E2=80=94=204=20Codex=20findings=20(PR=20#2611)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- pkgs/mcpx/internal/runner/dispatch.go | 72 +++++++++++++++------- pkgs/mcpx/internal/runner/dispatch_test.go | 61 +++++++++++++++++- 2 files changed, 109 insertions(+), 24 deletions(-) diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 5fa740fe6b..2099e88e47 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -328,35 +328,31 @@ func (sp *shebangEnv) resplit(payload string) []string { // SplitEnvString splits an env(1) -S/--split-string payload with // env's own semantics, which are NOT the shell's: env defines a // backslash escape table (\\, \", \', \t, \n, \r, \f, \v and -// \_ for a space) that applies inside quotes as well as outside -- +// \_) that applies inside quotes as well as outside -- // the coreutils manual's own example, -S awk -v FS=\"\\t\" -f, // depends on \\t becoming a tab, where a shell tokenizer leaves a // literal "t" (Codex review, PR #2611). Quotes still group, as the -// earlier rounds of this parser established, and ${VAR} expands -// from the environment the payload itself is building (assignments -// already split, then the inherited one), as env expands it. +// earlier rounds of this parser established. Two rules are easy to +// get wrong, both verified against env(1) itself: \_ outside quotes +// is an argument SEPARATOR, not a space (inside double quotes it is +// a literal space), and ${VAR} expands from the INHERITED +// environment -- env expands before it applies the payload's own +// VAR=value assignments, so `MODE=prod ... ${MODE}` sees the +// inherited MODE, never "prod" (Codex review, PR #2611). An +// unquoted # that begins an argument starts a comment: the rest of +// the payload is ignored. func SplitEnvString(s string) ([]string, error) { var out []string var word strings.Builder quoted := byte(0) started := false - assigned := map[string]string{} - seenCommand := false flush := func() { if !started { return } - f := word.String() - out = append(out, f) + out = append(out, word.String()) word.Reset() started = false - if !seenCommand { - if k, v, ok := strings.Cut(f, "="); ok && k != "" && !strings.ContainsAny(k, " \t") { - assigned[k] = v - } else { - seenCommand = true - } - } } expand := func(i int) (string, int, error) { // s[i] == '$' and s[i+1] == '{'. @@ -365,9 +361,6 @@ func SplitEnvString(s string) ([]string, error) { return "", 0, fmt.Errorf("unterminated ${ in env -S payload %q", s) } name := s[i+2 : i+j] - if v, ok := assigned[name]; ok { - return v, i + j + 1, nil - } return os.Getenv(name), i + j + 1, nil } for i := 0; i < len(s); i++ { @@ -402,7 +395,17 @@ func SplitEnvString(s string) ([]string, error) { case 'v': word.WriteByte('\v') case '_': - word.WriteByte(' ') + // Outside quotes \_ is an argument separator + // (env(1): `python3\_-u` is two arguments); + // inside double quotes it is a literal space. + // The single-quote case never reaches here. + if quoted == '"' { + word.WriteByte(' ') + started = true + } else { + flush() + } + continue default: word.WriteByte(s[i]) } @@ -432,6 +435,13 @@ func SplitEnvString(s string) ([]string, error) { word.WriteString(v) i = ni - 1 started = true + case c == '#' && !started: + // An unquoted # that begins an argument starts a + // comment (env(1)): the rest of the payload is not + // arguments. A # inside an argument stays literal, + // and quoted or escaped hashes never reach here. + flush() + return out, nil case c == ' ' || c == '\t': flush() default: @@ -811,6 +821,23 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err return nil, err } scriptPath = abs + if workDir == "" && opts.WorkRoot != "" { + // A file run has no generated client to key on, so its + // runner directory under the root is keyed on the + // script itself. Allocating it + // here is what makes script.cwd=workdir mean the + // runner directory for a dispatched run, the way it + // does for a JavaScript run; substituting the script's + // own directory (the old fallback below) made workdir + // behave identically to script, and relative output + // landed beside the source (Codex review, PR #2611). + sum := sha256sum([]byte(scriptPath)) + workDir = filepath.Join(opts.WorkRoot, sum[:16]) + if err := os.MkdirAll(workDir, 0o700); err != nil { + return nil, err + } + pruneWorkDirs(opts.WorkRoot, workDir) + } } else { // A snippet runs from a file of its own: no Prelude (that is // TypeScript for the generated client) and no .ts suffix (the @@ -833,9 +860,10 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err } } defer cleanup() - if workDir == "" { - workDir = filepath.Dir(scriptPath) - } + // No script-directory fallback for workDir: with no WorkDir and no + // WorkRoot, a script.cwd=workdir run has no runner directory, and + // ResolveCwd says so explicitly rather than silently running in + // the script's directory under the workdir name. dir, err := ResolveCwd(opts.CwdPolicy, opts.Dir, scriptPath, opts.ConfigDir, workDir) if err != nil { diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index fc4d160639..40c94205df 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -652,8 +652,17 @@ func TestSplitEnvStringUsesEnvSemantics(t *testing.T) { }{ {`awk -v FS=\"\t\" -f`, []string{"awk", "-v", `FS="` + "\t" + `"`, "-f"}}, {`sh -c "printf hello"`, []string{"sh", "-c", "printf hello"}}, - {`MODE=prod echo ${MODE}`, []string{"MODE=prod", "echo", "prod"}}, - {`echo a\_b`, []string{"echo", "a b"}}, + // \_ outside quotes is an argument separator in env(1), + // not a space: `python3\_-u` must dispatch python3 with -u + // (Codex review, PR #2611; verified against GNU env). + {`echo a\_b`, []string{"echo", "a", "b"}}, + {`python3\_-u script.py`, []string{"python3", "-u", "script.py"}}, + // Inside double quotes \_ is a literal space. + {`echo "a\_b"`, []string{"echo", "a b"}}, + // An unquoted # that begins an argument starts a comment; + // a # inside an argument is literal (Codex review, PR #2611). + {`sh # interpreter comment`, []string{"sh"}}, + {`echo a#b`, []string{"echo", "a#b"}}, {"echo 'single quoted'", []string{"echo", "single quoted"}}, // Inside single quotes only \' and \\ are escapes; every other // backslash is literal, or a regexp like r"\d" loses its @@ -683,6 +692,54 @@ func TestSplitEnvStringUsesEnvSemantics(t *testing.T) { } } +// TestSplitEnvStringExpandsFromTheInheritedEnvironment is the Codex +// finding on PR #2611: env expands ${VAR} BEFORE applying the +// payload's own assignments, so a preceding MODE=prod in the payload +// must not shadow the inherited MODE. Verified against GNU env: +// MODE=old env -S 'MODE=prod printf ${MODE}' prints "old". +func TestSplitEnvStringExpandsFromTheInheritedEnvironment(t *testing.T) { + t.Setenv("MODE", "old") + got, err := SplitEnvString(`MODE=prod printf ${MODE}`) + if err != nil { + t.Fatal(err) + } + want := []string{"MODE=prod", "printf", "old"} + if len(got) != len(want) { + t.Fatalf("SplitEnvString = %q, want %q", got, want) + } + for i := range got { + if got[i] != want[i] { + t.Fatalf("SplitEnvString = %q, want %q", got, want) + } + } +} + +// TestDispatchedWorkdirPolicyAllocatesARunnerDirectory is the Codex +// finding on PR #2611: a file-backed dispatched run under +// script.cwd=workdir with only a WorkRoot supplied ran in the +// script's own directory, making workdir behave as script. The run +// must land in a runner directory under the root. +func TestDispatchedWorkdirPolicyAllocatesARunnerDirectory(t *testing.T) { + dir := t.TempDir() + root := t.TempDir() + script := writeScript(t, dir, "job.sh", "#!/bin/sh\npwd\n") + var stdout, stderr bytes.Buffer + _, err := Run(context.Background(), Options{ + File: script, CwdPolicy: "workdir", WorkRoot: root, + Stdout: &stdout, Stderr: &stderr, + }) + if err != nil { + t.Fatalf("Run(workdir dispatch): %v (stderr %q)", err, stderr.String()) + } + got := strings.TrimSpace(stdout.String()) + if got == "" || !strings.HasPrefix(got, root) { + t.Fatalf("dispatched workdir run executed in %q, want a directory under WorkRoot %q", got, root) + } + if got == dir { + t.Fatalf("dispatched workdir run executed in the script directory %q", dir) + } +} + // A JavaScript shebang's runtime may exist only on the PATH the shebang // sets, and that PATH is applied after the run's directory is known. // Resolve runs first, against mcpx's inherited PATH, and must not reject From 631b3a80f6c48ef255b493283ddaf18ef198de2c Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sat, 31 Oct 2026 00:05:54 -0500 Subject: [PATCH 14/14] mcpx: lease dispatched workdirs + empty unquoted env expansions start no argument (#2167) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two Codex P2 findings on PR #2611 re-review of bdd9231f6: - runDispatched now leases its WorkRoot-allocated runner directory for the run's lifetime (cache.Acquire, mirroring Run's JavaScript path), so another run's cache pruning cannot delete a live dispatched run's directory. - SplitEnvString: an unquoted ${VAR} expansion that contributes nothing no longer starts an argument, matching env(1) — a shebang like `#!/usr/bin/env -S python3 ${PYFLAGS}` with PYFLAGS unset no longer hands python3 an empty string as its script filename. Explicitly quoted empty expansions still produce their argument. Tests: TestDispatchedWorkdirRunLeasesItsDirectory (leased live, released after) and TestSplitEnvStringEmptyUnquotedExpansionStartsNoArgument; runner + execsvc suites pass on laptop. --- pkgs/mcpx/internal/runner/dispatch.go | 21 +++++- pkgs/mcpx/internal/runner/dispatch_test.go | 82 ++++++++++++++++++++++ 2 files changed, 102 insertions(+), 1 deletion(-) diff --git a/pkgs/mcpx/internal/runner/dispatch.go b/pkgs/mcpx/internal/runner/dispatch.go index 2099e88e47..0435bd78be 100644 --- a/pkgs/mcpx/internal/runner/dispatch.go +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -47,6 +47,7 @@ import ( "syscall" "time" + "github.com/dezren39/mcpx/internal/cache" "github.com/dezren39/mcpx/internal/defaults" "github.com/dezren39/mcpx/internal/logging" ) @@ -434,7 +435,16 @@ func SplitEnvString(s string) ([]string, error) { } word.WriteString(v) i = ni - 1 - started = true + // An unquoted expansion that contributes nothing does + // not start an argument: env(1) omits the word, so + // `python3 ${PYFLAGS}` with PYFLAGS unset gains no + // empty argument for the interpreter to mistake for + // the script filename. A quoted empty expansion still + // counts — the quotes themselves start the word + // (Codex review, PR #2611). + if v != "" { + started = true + } case c == '#' && !started: // An unquoted # that begins an argument starts a // comment (env(1)): the rest of the payload is not @@ -837,6 +847,15 @@ func runDispatched(ctx context.Context, opts Options, d *dispatch) (*Result, err return nil, err } pruneWorkDirs(opts.WorkRoot, workDir) + // Lease the directory while this run uses it, as Run + // does for a JavaScript run: pruneWorkDirs protects + // only the current invocation's directory, so without + // a lease another run's pruning could delete this + // still-active directory once the shared cache passes + // its limit (Codex review, PR #2611). + if lease, lerr := cache.Acquire(workDir); lerr == nil { + cleanup = lease.Release + } } } else { // A snippet runs from a file of its own: no Prelude (that is diff --git a/pkgs/mcpx/internal/runner/dispatch_test.go b/pkgs/mcpx/internal/runner/dispatch_test.go index 40c94205df..e1d5ab7157 100644 --- a/pkgs/mcpx/internal/runner/dispatch_test.go +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -3,10 +3,14 @@ package runner import ( "bytes" "context" + "fmt" "os" "os/exec" + "time" + "github.com/dezren39/mcpx/internal/cache" "github.com/dezren39/mcpx/internal/codegen" + "github.com/dezren39/mcpx/internal/defaults" "path/filepath" "strings" "testing" @@ -714,6 +718,84 @@ func TestSplitEnvStringExpandsFromTheInheritedEnvironment(t *testing.T) { } } +// TestSplitEnvStringEmptyUnquotedExpansionStartsNoArgument is the +// Codex finding on PR #2611 (re-review): an unset variable's unquoted +// expansion must not create an empty argument — env(1) omits the word +// — while an explicitly quoted empty argument survives. +func TestSplitEnvStringEmptyUnquotedExpansionStartsNoArgument(t *testing.T) { + // Deliberately never set in this process. + const unset = "MCPX_SPLIT_TEST_UNSET_3201" + cases := []struct { + payload string + want []string + }{ + {`python3 ${` + unset + `}`, []string{"python3"}}, + {`python3 ${` + unset + `} script.py`, []string{"python3", "script.py"}}, + {`python3 "${` + unset + `}"`, []string{"python3", ""}}, + {`echo a${` + unset + `}b`, []string{"echo", "ab"}}, + {`${` + unset + `}`, nil}, + } + for _, c := range cases { + got, err := SplitEnvString(c.payload) + if err != nil { + t.Errorf("SplitEnvString(%q): %v", c.payload, err) + continue + } + if len(got) != len(c.want) { + t.Errorf("SplitEnvString(%q) = %q, want %q", c.payload, got, c.want) + continue + } + for i := range got { + if got[i] != c.want[i] { + t.Errorf("SplitEnvString(%q)[%d] = %q, want %q (all: %q)", c.payload, i, got[i], c.want[i], got) + } + } + } +} + +// TestDispatchedWorkdirRunLeasesItsDirectory is the Codex finding on +// PR #2611 (re-review): a dispatched run's allocated runner directory +// stayed unleased for the whole execution, so another run's cache +// pruning could delete it mid-run. The directory must be leased while +// the run is live and released when it finishes. +func TestDispatchedWorkdirRunLeasesItsDirectory(t *testing.T) { + dir := t.TempDir() + root := t.TempDir() + marker := filepath.Join(dir, "started") + script := writeScript(t, dir, "job.sh", + fmt.Sprintf("#!/bin/sh\npwd > %s\nsleep 2\n", marker)) + done := make(chan error, 1) + go func() { + var stdout, stderr bytes.Buffer + _, err := Run(context.Background(), Options{ + File: script, CwdPolicy: "workdir", WorkRoot: root, + Stdout: &stdout, Stderr: &stderr, + }) + done <- err + }() + deadline := time.Now().Add(10 * time.Second) + var cwd string + for time.Now().Before(deadline) { + if b, err := os.ReadFile(marker); err == nil && len(b) > 0 { + cwd = strings.TrimSpace(string(b)) + break + } + time.Sleep(20 * time.Millisecond) + } + if cwd == "" { + t.Fatal("the dispatched run never reported its directory") + } + if !cache.Leased(cwd, defaults.CacheLeaseStaleAge) { + t.Fatalf("dispatched workdir %q is not leased while the run is live", cwd) + } + if err := <-done; err != nil { + t.Fatalf("Run(workdir dispatch): %v", err) + } + if cache.Leased(cwd, defaults.CacheLeaseStaleAge) { + t.Fatalf("dispatched workdir %q is still leased after the run finished", cwd) + } +} + // TestDispatchedWorkdirPolicyAllocatesARunnerDirectory is the Codex // finding on PR #2611: a file-backed dispatched run under // script.cwd=workdir with only a WorkRoot supplied ran in the