diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index 7afe8e49fd..92a2092076 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -356,6 +356,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 @@ -711,9 +726,11 @@ 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.imports` | enum | `report` | client | no | `--script-imports` | `MCPX_SCRIPT_IMPORTS` | resolve the script's import graph before running it | | `script.importsOnDynamic` | enum | `warn` | client | no | `--script-imports-on-dynamic` | `MCPX_SCRIPT_IMPORTS_ON_DYNAMIC` | what to do about an import() whose specifier is computed | +| `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 5310c598af..6cb0ead606 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 @@ -86,56 +90,57 @@ and read by name for that reason. -| variable | set by | when | what it is | read by | -| ----------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | -| `MCPX_SESSION` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`); an event consumer | always | the session key this run's tool calls are leased under: --session, else MCPX_SESSION_ID, else one minted for the run | the generated client, which sends it with every call | -| `MCPX_SESSION_ID` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`); an event consumer; the opencode plugin; the plugin loader, for a discovered plugin | the CLI passes through the value it was given, which may be empty; the plugin sets it at every plugin.env level | the session the host assigned. Unlike MCPX_SESSION it survives from one command to the next, so it is what session-scoped servers key on | `mcpx` run inside the script or shell, as its session when --session is not given | -| `MCPX_PARENT_SESSION_ID` | `mcpx exec` / `mcpx run`; the opencode plugin | the CLI passes through what it was given; the plugin at plugin.env=full, when there is a parent | the session that spawned this one, so a parent agent and its subagents can share a server | `mcpx` run inside the script or shell, and the generated client for parent-session scoping | -| `MCPX_EPHEMERAL` | `mcpx exec` / `mcpx run` | always | 1 when the session key was minted for this run alone, so its instances may be stopped as soon as it ends | the generated client | -| `MCPX_RUN` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`) | always | this execution's run id, which groups the artifacts it produces | the generated client, when storing an artifact | -| `MCPX_INPUT` | `mcpx exec` / `mcpx run` | mcpx exec and mcpx run, locally and with --remote; not when mcpx serve collects the output | report: nothing in this run can answer a server's question mid-call, so a call that asks one exits 75 with the question instead of waiting for it to expire | the generated client, sent as X-Mcpx-Input | -| `MCPX_HOOK_NAME` | the declared-hook runner, for a hook it runs | always | the declared name of the hook being run | the hook itself | -| `MCPX_HOOK_PHASE` | the declared-hook runner, for a hook it runs; the exec service (`/v1/exec`, `mcpx_exec`) | always | the hook's phase; always observe for config-declared hooks, the exec hook's phase (pre, post, onError, onSuccess) for a per-call exec hook | the hook itself | -| `MCPX_HOOK_POINT` | the exec service (`/v1/exec`, `mcpx_exec`) | always | the point the hook is attached to; script for per-call exec hooks in this version | the hook itself | -| `MCPX_HOOK_ERROR` | the exec service (`/v1/exec`, `mcpx_exec`) | only for a hook running because the script failed; truncated to 1024 bytes | the error the hook is running for, in one line; the full hook context is JSON on stdin | the hook itself | -| `MCPX_HOOK_EVENT_KIND` | the declared-hook runner, for a hook it runs | always | the kind of the event the hook is running for; the full event is JSON on stdin | the hook itself | -| `MCPX_HOOK_EVENT_SEQ` | the declared-hook runner, for a hook it runs | always | the event's sequence number on the daemon's bus | the hook itself | -| `MCPX_HOOK_EVENT_SERVER` | the declared-hook runner, for a hook it runs | empty when the event names no server | the server the event is about | the hook itself | -| `MCPX_HOOK_EVENT_SESSION` | the declared-hook runner, for a hook it runs | empty when the event belongs to no session | the session the event belongs to | the hook itself | -| `MCPX_HOOK_EVENT_URI` | the declared-hook runner, for a hook it runs | empty when the event names no resource | the resource URI the event is about | the hook itself | -| `MCPX_ENDPOINT` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`); an event consumer | always | the daemon's HTTP endpoint | the generated client; the plugin as a fallback for MCPX_DAEMON_ENDPOINT | -| `MCPX_SOCKET` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`); the plugin loader, for a discovered plugin | empty when the daemon is remote, since its socket is not reachable from here | the daemon's unix socket, which is faster than the endpoint. Also where a daemon binds and a client dials, for anyone who sets it by hand | the generated client, `mcpx` run inside the script or shell, the plugin | -| `MCPX_TRANSPORT_BEARER_TOKEN` | `mcpx exec` / `mcpx run` | only when transport.bearerToken is configured | the daemon's bearer token, handed to the script so the generated client can authenticate to a daemon that requires it (#1975); the token itself stays out of the generated code | the generated client, `mcpx` run inside the script or shell, the plugin; also the setting `transport.bearerToken` | -| `MCPX_ARTIFACTS_LOCAL` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`) | always | 1 when the daemon shares this filesystem, so artifact({path}) may hand over a path instead of the bytes | the generated client | -| `MCPX_CWD` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`) | the exec service only when the caller sent its working directory | the directory the caller ran mcpx from, which a remote run cannot discover | the generated client (paths.cwd, and cwd scoping) | -| `MCPX_PID` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`) | always | the pid of the mcpx process that started the script | the generated client, for pid scoping | -| `MCPX_ENTRY` | the runner, for every script | always | the file the runtime was started on: mcpx's generated launcher, or the script itself under --no-launcher. For exec the script is a generated file | the generated client (paths.entry) | -| `MCPX_CLIENT` | the runner, for every script | always | the generated client module | the generated client (paths.client) | -| `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_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 | -| `MCPX_DAEMON_ENDPOINT` | the opencode plugin | plugin.env=standard or above, once the plugin has chosen a daemon | the daemon this editor session settled on, so a shell command that runs mcpx talks to the same one instead of looking for its own | `mcpx` run inside the script or shell, as daemon.endpoint; the plugin, as the daemon to use; also the setting `daemon.endpoint` | -| `MCPX_TRACE_IDS` | the opencode plugin | plugin.env=standard or above, when there is anything to say | JSON pairs such as [["session_id","abc"],["worktree","/p"]], extended at full with the parent session and the whole ancestry | `mcpx` run inside the script or shell, which puts every pair on every log record | -| `MCPX_CALL_ID` | the opencode plugin | plugin.env=standard or above | the editor's id for this one tool call | the command | -| `MCPX_OPENCODE_CWD` | the opencode plugin | plugin.env=standard or above | the directory the command runs in, which is not always the project root | the command | -| `MCPX_OPENCODE_DIRECTORY` | the opencode plugin | plugin.env=standard or above | the project directory the editor opened | the command | -| `MCPX_OPENCODE_WORKTREE` | the opencode plugin | plugin.env=standard or above | the project's worktree | the command | -| `MCPX_WORKTREE_NAME` | the opencode plugin | plugin.env=standard or above, when there is a worktree | the worktree's last path element | the command | -| `MCPX_PROJECT_ID` | the opencode plugin | plugin.env=standard or above | the editor's project id | the command | -| `MCPX_HARNESS` | the opencode plugin | plugin.env=standard or above | opencode | the command | -| `MCPX_HARNESS_VERSION` | the opencode plugin | plugin.env=standard or above | the editor's version | the command | -| `MCPX_HARNESS_PID` | the opencode plugin | plugin.env=standard or above | the editor's pid | the command | -| `MCPX_HARNESS_STARTED` | the opencode plugin | plugin.env=standard or above | when the plugin started | the command | -| `MCPX_SHELL_SEQ` | the opencode plugin | plugin.env=standard or above | a counter of shell commands in this editor process | the command | -| `MCPX_SESSION_TITLE` | the opencode plugin | plugin.env=full | the session's title | the command | -| `MCPX_SESSION_DIRECTORY` | the opencode plugin | plugin.env=full | the session's directory | the command | -| `MCPX_SESSION_VERSION` | the opencode plugin | plugin.env=full | the editor version that created the session | the command | -| `MCPX_SESSION_DEPTH` | the opencode plugin | plugin.env=full | how many parents the session has | the command | -| `MCPX_SESSION_CREATED` | the opencode plugin | plugin.env=full, when known | when the session was created, ISO 8601 | the command | -| `MCPX_SESSION_AGE_MS` | the opencode plugin | plugin.env=full, when known | the session's age when the command started, in milliseconds | the command | +| variable | set by | when | what it is | read by | +| --- | --- | --- | --- | --- | +| `MCPX_SESSION` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`); an event consumer | always | the session key this run's tool calls are leased under: --session, else MCPX_SESSION_ID, else one minted for the run | the generated client, which sends it with every call | +| `MCPX_SESSION_ID` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`); an event consumer; the opencode plugin; the plugin loader, for a discovered plugin | the CLI passes through the value it was given, which may be empty; the plugin sets it at every plugin.env level | the session the host assigned. Unlike MCPX_SESSION it survives from one command to the next, so it is what session-scoped servers key on | `mcpx` run inside the script or shell, as its session when --session is not given | +| `MCPX_PARENT_SESSION_ID` | `mcpx exec` / `mcpx run`; the opencode plugin | the CLI passes through what it was given; the plugin at plugin.env=full, when there is a parent | the session that spawned this one, so a parent agent and its subagents can share a server | `mcpx` run inside the script or shell, and the generated client for parent-session scoping | +| `MCPX_EPHEMERAL` | `mcpx exec` / `mcpx run` | always | 1 when the session key was minted for this run alone, so its instances may be stopped as soon as it ends | the generated client | +| `MCPX_RUN` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`) | always | this execution's run id, which groups the artifacts it produces | the generated client, when storing an artifact | +| `MCPX_INPUT` | `mcpx exec` / `mcpx run` | mcpx exec and mcpx run, locally and with --remote; not when mcpx serve collects the output | report: nothing in this run can answer a server's question mid-call, so a call that asks one exits 75 with the question instead of waiting for it to expire | the generated client, sent as X-Mcpx-Input | +| `MCPX_HOOK_NAME` | the declared-hook runner, for a hook it runs | always | the declared name of the hook being run | the hook itself | +| `MCPX_HOOK_PHASE` | the declared-hook runner, for a hook it runs; the exec service (`/v1/exec`, `mcpx_exec`) | always | the hook's phase; always observe for config-declared hooks, the exec hook's phase (pre, post, onError, onSuccess) for a per-call exec hook | the hook itself | +| `MCPX_HOOK_POINT` | the exec service (`/v1/exec`, `mcpx_exec`) | always | the point the hook is attached to; script for per-call exec hooks in this version | the hook itself | +| `MCPX_HOOK_ERROR` | the exec service (`/v1/exec`, `mcpx_exec`) | only for a hook running because the script failed; truncated to 1024 bytes | the error the hook is running for, in one line; the full hook context is JSON on stdin | the hook itself | +| `MCPX_HOOK_EVENT_KIND` | the declared-hook runner, for a hook it runs | always | the kind of the event the hook is running for; the full event is JSON on stdin | the hook itself | +| `MCPX_HOOK_EVENT_SEQ` | the declared-hook runner, for a hook it runs | always | the event's sequence number on the daemon's bus | the hook itself | +| `MCPX_HOOK_EVENT_SERVER` | the declared-hook runner, for a hook it runs | empty when the event names no server | the server the event is about | the hook itself | +| `MCPX_HOOK_EVENT_SESSION` | the declared-hook runner, for a hook it runs | empty when the event belongs to no session | the session the event belongs to | the hook itself | +| `MCPX_HOOK_EVENT_URI` | the declared-hook runner, for a hook it runs | empty when the event names no resource | the resource URI the event is about | the hook itself | +| `MCPX_ENDPOINT` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`); an event consumer | always | the daemon's HTTP endpoint | the generated client; the plugin as a fallback for MCPX_DAEMON_ENDPOINT | +| `MCPX_SOCKET` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`); the plugin loader, for a discovered plugin | empty when the daemon is remote, since its socket is not reachable from here | the daemon's unix socket, which is faster than the endpoint. Also where a daemon binds and a client dials, for anyone who sets it by hand | the generated client, `mcpx` run inside the script or shell, the plugin | +| `MCPX_TRANSPORT_BEARER_TOKEN` | `mcpx exec` / `mcpx run` | only when transport.bearerToken is configured | the daemon's bearer token, handed to the script so the generated client can authenticate to a daemon that requires it (#1975); the token itself stays out of the generated code | the generated client, `mcpx` run inside the script or shell, the plugin; also the setting `transport.bearerToken` | +| `MCPX_ARTIFACTS_LOCAL` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`) | always | 1 when the daemon shares this filesystem, so artifact({path}) may hand over a path instead of the bytes | the generated client | +| `MCPX_CWD` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`) | the exec service only when the caller sent its working directory | the directory the caller ran mcpx from, which a remote run cannot discover | the generated client (paths.cwd, and cwd scoping) | +| `MCPX_PID` | `mcpx exec` / `mcpx run`; the exec service (`/v1/exec`, `mcpx_exec`) | always | the pid of the mcpx process that started the script | the generated client, for pid scoping | +| `MCPX_ENTRY` | the runner, for every script | always | the file the runtime was started on: mcpx's generated launcher, or the script itself under --no-launcher. For exec the script is a generated file | the generated client (paths.entry) | +| `MCPX_CLIENT` | the runner, for every script | always | the generated client module | the generated client (paths.client) | +| `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; 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` | +| `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 | +| `MCPX_DAEMON_ENDPOINT` | the opencode plugin | plugin.env=standard or above, once the plugin has chosen a daemon | the daemon this editor session settled on, so a shell command that runs mcpx talks to the same one instead of looking for its own | `mcpx` run inside the script or shell, as daemon.endpoint; the plugin, as the daemon to use; also the setting `daemon.endpoint` | +| `MCPX_TRACE_IDS` | the opencode plugin | plugin.env=standard or above, when there is anything to say | JSON pairs such as [["session_id","abc"],["worktree","/p"]], extended at full with the parent session and the whole ancestry | `mcpx` run inside the script or shell, which puts every pair on every log record | +| `MCPX_CALL_ID` | the opencode plugin | plugin.env=standard or above | the editor's id for this one tool call | the command | +| `MCPX_OPENCODE_CWD` | the opencode plugin | plugin.env=standard or above | the directory the command runs in, which is not always the project root | the command | +| `MCPX_OPENCODE_DIRECTORY` | the opencode plugin | plugin.env=standard or above | the project directory the editor opened | the command | +| `MCPX_OPENCODE_WORKTREE` | the opencode plugin | plugin.env=standard or above | the project's worktree | the command | +| `MCPX_WORKTREE_NAME` | the opencode plugin | plugin.env=standard or above, when there is a worktree | the worktree's last path element | the command | +| `MCPX_PROJECT_ID` | the opencode plugin | plugin.env=standard or above | the editor's project id | the command | +| `MCPX_HARNESS` | the opencode plugin | plugin.env=standard or above | opencode | the command | +| `MCPX_HARNESS_VERSION` | the opencode plugin | plugin.env=standard or above | the editor's version | the command | +| `MCPX_HARNESS_PID` | the opencode plugin | plugin.env=standard or above | the editor's pid | the command | +| `MCPX_HARNESS_STARTED` | the opencode plugin | plugin.env=standard or above | when the plugin started | the command | +| `MCPX_SHELL_SEQ` | the opencode plugin | plugin.env=standard or above | a counter of shell commands in this editor process | the command | +| `MCPX_SESSION_TITLE` | the opencode plugin | plugin.env=full | the session's title | the command | +| `MCPX_SESSION_DIRECTORY` | the opencode plugin | plugin.env=full | the session's directory | the command | +| `MCPX_SESSION_VERSION` | the opencode plugin | plugin.env=full | the editor version that created the session | the command | +| `MCPX_SESSION_DEPTH` | the opencode plugin | plugin.env=full | how many parents the session has | the command | +| `MCPX_SESSION_CREATED` | the opencode plugin | plugin.env=full, when known | when the session was created, ISO 8601 | the command | +| `MCPX_SESSION_AGE_MS` | the opencode plugin | plugin.env=full, when known | the session's age when the command started, in milliseconds | the command | diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index 0f26844682..f2a272f5b1 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -953,6 +953,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. @@ -961,6 +970,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, @@ -2272,13 +2284,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/exec.go b/pkgs/mcpx/internal/cli/exec.go index 7375bfee6e..603866edbe 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") @@ -554,7 +556,15 @@ func (a *App) execOnDaemon(ctx context.Context, c *Client, fs *flag.FlagSet, inl opts := execsvc.Options{ Runtime: rf.runtime, Permissions: rf.permissions, - Session: session, + // 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"), + // 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/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/daemon/routes_exec.go b/pkgs/mcpx/internal/daemon/routes_exec.go index 4bc05705ab..c2cd42c67d 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 { @@ -173,6 +178,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"), @@ -187,12 +194,26 @@ func (s *Server) ExecService() *execsvc.Service { lim.InterceptImages = set.Bool("artifacts.interceptImages") lim.StdoutLimit = set.Bytes("exec.maxOutputBytes") + // script.cwd=config resolves against the directory holding the + // 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 s.execSetPath != "" { + configDir = filepath.Dir(s.execSetPath) + } else if cfg := s.currentConfig(); cfg != nil && cfg.Path != "" { + configDir = filepath.Dir(cfg.Path) + } + svc := &execsvc.Service{ - Calls: s.callRegistry(), - 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, + Calls: s.callRegistry(), // 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. @@ -504,6 +525,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/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/execsvc/execsvc.go b/pkgs/mcpx/internal/execsvc/execsvc.go index 7e5a03190e..563cb499e4 100644 --- a/pkgs/mcpx/internal/execsvc/execsvc.go +++ b/pkgs/mcpx/internal/execsvc/execsvc.go @@ -103,7 +103,17 @@ 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"` + // 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"` @@ -372,6 +382,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. @@ -394,6 +408,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. @@ -448,6 +466,9 @@ type Service struct { BearerToken string // 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 @@ -526,6 +547,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: firstNonEmpty(opts.CwdPolicy, s.Limits.CwdPolicy), + ConfigDir: s.ConfigDir, Setup: s.Limits.Setup, Timeout: timeout, Permissions: firstNonEmpty(opts.Permissions, s.Limits.Permissions), @@ -780,6 +804,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/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/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 new file mode 100644 index 0000000000..0435bd78be --- /dev/null +++ b/pkgs/mcpx/internal/runner/dispatch.go @@ -0,0 +1,1019 @@ +// 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. 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 +// 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/cache" + "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 + 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" + // 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. +// The /usr/bin/env form is unwrapped the way the kernel cannot: env's +// 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) { + sp, ok := parseShebang(line) + return sp.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) { + 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) + 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 + // 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 +// 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. 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 + } + rest := strings.TrimSpace(line[2:]) + if rest == "" { + return shebangEnv{}, true + } + fields := strings.Fields(rest) + var sp shebangEnv + 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 + } + 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, "-"): + // 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: + sp.tokens = remaining(f) + return sp, true + } + } +} + +// 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 := SplitEnvString(payload) + if err != nil { + sp.splitErr = err + return nil + } + 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 +// \_) 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. 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 + flush := func() { + if !started { + return + } + out = append(out, word.String()) + word.Reset() + started = false + } + 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] + return os.Getenv(name), i + j + 1, nil + } + 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) + } + 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 '_': + // 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]) + } + 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 + // 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 + // 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: + 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 { + 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 +// 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) +// 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 == 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 + } 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 +} + +// 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 + 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 +// dispatch means the run falls through to the TypeScript runtime; 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 +// 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, jsChoice, 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 sp, ok := parseShebang(first); ok { + 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") + } + 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, path: shebangPath(&sp)}, nil + } + d, err := dispatchFromTokens("shebang", sp.tokens, &sp) + if err != nil { + return nil, jsChoice{}, err + } + 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, jsChoice{}, fmt.Errorf("runner: script.interpreter: %w", err) + } + if len(tokens) == 0 { + return nil, jsChoice{}, errors.New("runner: script.interpreter is set but names no command") + } + d, err := dispatchFromTokens("interpreter", tokens, nil) + if err != nil { + return nil, jsChoice{}, err + } + return d, jsChoice{}, nil + } + 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 +// 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...) +} + +// 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). +// +// 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, present := os.LookupEnv("PATH") + if sp.clear { + path, present = "", false + } + for _, u := range sp.unset { + if u == "PATH" { + path, present = "", false + } + } + for _, kv := range sp.set { + if k, v, ok := strings.Cut(kv, "="); ok && k == "PATH" { + path, present = v, true + } + } + 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. + return "/bin:/usr/bin" + } + return path +} + +// lookPathInDir is exec.LookPath against one explicit PATH value, +// 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 +// a third directory. +func lookPathInDir(bin, path, dir string) (string, error) { + abs, err := filepath.Abs(dir) + if err != nil { + return "", err + } + 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) { + entry = filepath.Join(abs, entry) + } + p := filepath.Join(entry, 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] + d := &dispatch{ + args: append([]string{}, tokens[1:]...), + name: filepath.Base(bin), + source: source, + } + 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 + } + // 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) + } + d.bin = p + return d, 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 + 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) + // 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 + // 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() + // 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 { + 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 "+ + "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 + 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 + // 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. 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) + } + 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..e1d5ab7157 --- /dev/null +++ b/pkgs/mcpx/internal/runner/dispatch_test.go @@ -0,0 +1,901 @@ +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" +) + +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 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 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 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" { + 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", + "#!/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, 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, 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, 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) + } +} + +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" { + 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") + } + // 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) { + 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) + } +} + +// 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 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) + } + 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("Run(shebang PATH assignment): %v", err) + } + 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. + 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()) + } +} + +// 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()) + } +} + +// 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"}}, + // \_ 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 + // 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) + 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") + } +} + +// 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) + } + } +} + +// 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 +// 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 +// 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/runner/runner.go b/pkgs/mcpx/internal/runner/runner.go index c36da9835c..de39dcbc22 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. @@ -157,6 +168,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 } @@ -180,9 +195,39 @@ 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. + 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 js.runtime != "" { + // A JavaScript shebang chose this runtime (rank 1); the harness + // below runs under it instead of the configured preference. + // 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 { - 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 @@ -283,6 +328,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. @@ -339,7 +416,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 @@ -361,14 +438,19 @@ 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. + 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. - 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) 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/effect.go b/pkgs/mcpx/internal/settings/effect.go index 8e8b910c99..1448c68a95 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 diff --git a/pkgs/mcpx/internal/settings/registry.go b/pkgs/mcpx/internal/settings/registry.go index da0002c9b3..f6bf5f2d51 100644 --- a/pkgs/mcpx/internal/settings/registry.go +++ b/pkgs/mcpx/internal/settings/registry.go @@ -260,6 +260,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 80046c5092..8eb216fd74 100644 --- a/pkgs/mcpx/internal/settings/scriptenv.go +++ b/pkgs/mcpx/internal/settings/scriptenv.go @@ -273,8 +273,15 @@ func ScriptEnv() []EnvVar { { Name: "MCPX_RUNTIME", SetBy: []Setter{SetByRunner}, - Meaning: "deno, bun or node", - ReadBy: client, + Meaning: "deno, bun or node; on a dispatched run, the interpreter's name (sh, python3)", + ReadBy: client + "; on a dispatched run, the script itself", + }, + { + 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",