Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions pkgs/mcpx/docs/configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -646,3 +646,29 @@ and a switch to turn the report off would have kept it quiet.
| `upstream.protocol` | enum | `prefer-discover` | daemon | no | `--upstream-protocol` | `MCPX_UPSTREAM_PROTOCOL` | which request to send first to a server that names no protocol of its own; one of prefer-discover (also modern, prefer-modern, prefer-stateless, prefer-newest), prefer-initialize (also legacy, prefer-legacy, prefer-session, prefer-oldest), force-discover (also force-modern, force-stateless), force-initialize (also force-legacy, force-session), follow |

<!-- END GENERATED -->

## Adapter declarations

An entry in a `paths.adapters` file names a program and the subcommands worth
exposing. `command` is normally a binary on `PATH`; `runtime` makes it a
script instead, and resolves the interpreter for you:

```jsonc
{ "adapters": [{
"name": "reports", "command": "./tools/report.py", "runtime": "py",
"tools": [{ "name": "daily", "params": [{ "name": "day", "required": true }] }]
}] }
```

`runtime` is `bash`, `js`, `ts` or `py`. bash resolves `bash` (then `sh`), py
resolves `python3` (then `python`), and js/ts use the same deno/bun/node order
`script.runtimeOrder` chooses for `mcpx exec`. This is a separate resolver on
purpose: `script.runtime` names the runtime mcpx itself executes generated
scripts on, not the one a declaration asks for. A relative `command` resolves
against the declaration's `dir`, then `PATH`. Without `runtime`, nothing
changes: `command` is looked up on `PATH` and exec'd directly. `mcpx adapter
check` reports a missing interpreter or script.

`mcpx catalog` also ends with the recipe tools in `tools/list`: how many are
exposed against the recipe budget, and which recipes were kept out by a name
collision or the cap.
11 changes: 11 additions & 0 deletions pkgs/mcpx/docs/consumer.md
Original file line number Diff line number Diff line change
Expand Up @@ -155,6 +155,17 @@ Declaration is a header comment because a comment survives every runtime,
cannot affect execution, and is visible in the file somebody edits. References
are `@name`, the spelling the launcher already uses for its own holes.

**A recipe is also an MCP tool.** The `@param` header is already a typed
schema, so tools/list carries one tool per recipe, named `recipe_<name>`,
with that schema and the summary as its description. Calling it runs the
recipe through `/v1/recipes/{name}/run` -- the same render, diagnostics and
runner `mcpx recipes run` uses. Exposure is on by default; `// @tool false`
in the header opts one out. The number exposed is capped
(`DefaultToolBudget`, 25) so fifty saved scripts do not become fifty schemas
in every host, and `mcpx catalog` ends with the count, the cap and any recipe
kept out -- a name another producer already claimed is reported there rather
than silently dropped.

**Values are substituted as JSON, never as text.** A recipe runs with the
user's credentials; raw substitution would make every placeholder an injection
site. A string arrives quoted, an object arrives as an object, and a recipe
Expand Down
41 changes: 38 additions & 3 deletions pkgs/mcpx/internal/adapter/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,13 @@ type Spec struct {
Name string `json:"name"`
// Command is the binary.
Command string `json:"command"`
// Runtime is the interpreter a script command needs: bash, js, ts or
// py. Empty leaves Command as the executable itself, as it always was.
// A declared runtime is resolved on PATH by this package, deliberately
// not by script.runtime: that setting is about the JavaScript runtime
// mcpx itself executes generated scripts on, and a declaration naming
// its own interpreter means something different (#1875, #105/#106).
Runtime string `json:"runtime,omitempty"`
// Args are prepended to every invocation, for a program reached through
// a wrapper: {"command":"docker","args":["run","--rm","thing"]}.
Args []string `json:"args,omitempty"`
Expand Down Expand Up @@ -102,6 +109,13 @@ func (s Spec) Validate() error {
if strings.TrimSpace(s.Command) == "" {
problems = append(problems, s.Name+": no command")
}
if s.Runtime != "" {
// Only the name is checked here: whether an interpreter is
// installed is Probe's question, not a declaration's.
if err := checkRuntime(s.Runtime); err != nil {
problems = append(problems, s.Name+": "+err.Error())
}
}
if _, err := parseDuration(s.Timeout, time.Minute); err != nil {
problems = append(problems, s.Name+": timeout "+err.Error())
}
Expand Down Expand Up @@ -239,7 +253,19 @@ func (s Spec) Call(ctx context.Context, tool string, args map[string]any) (*Resu
if err != nil {
return nil, err
}

// A script declared with a runtime is spawned through its interpreter;
// without one this is the same exec as before.
bin, prefix, script, err := s.command()
if err != nil {
return nil, err
}
full := append(append([]string{}, s.Args...), argv...)
cmdArgs := append([]string{}, prefix...)
if script != "" {
cmdArgs = append(cmdArgs, script)
}
cmdArgs = append(cmdArgs, full...)

// Zero is unset (see parseDuration): a tool timeout of zero inherits
// the server timeout, and a server timeout of zero gets the default.
Expand All @@ -250,7 +276,7 @@ func (s Spec) Call(ctx context.Context, tool string, args map[string]any) (*Resu
cctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()

cmd := exec.CommandContext(cctx, s.Command, full...)
cmd := exec.CommandContext(cctx, bin, cmdArgs...)
cmd.Dir = s.Dir
cmd.Env = os.Environ()
for k, v := range s.Env {
Expand All @@ -263,10 +289,16 @@ func (s Spec) Call(ctx context.Context, tool string, args map[string]any) (*Resu
cmd.Stdout, cmd.Stderr = &out, &errb
runErr := cmd.Run()

display := s.Command + " " + strings.Join(full, " ")
if script != "" {
// The resolved form, so a failure names the interpreter that ran
// and the file it ran, not just the name the declaration used.
display = strings.Join(append([]string{bin}, cmdArgs...), " ")
}
res := &Result{
Stdout: out.String(),
Stderr: errb.String(),
Command: s.Command + " " + strings.Join(full, " "),
Command: display,
}
if ee, ok := runErr.(*exec.ExitError); ok {
res.ExitCode = ee.ExitCode()
Expand Down Expand Up @@ -390,7 +422,10 @@ func contains(list []string, v string) bool {

// Probe checks the binary exists before anything tries to call it.
func (s Spec) Probe() error {
if _, err := exec.LookPath(s.Command); err != nil {
if _, _, _, err := s.command(); err != nil {
if s.Runtime != "" {
return fmt.Errorf("%s: %w", s.Name, err)
}
return fmt.Errorf("%s: %s is not on PATH", s.Name, s.Command)
}
return nil
Expand Down
127 changes: 127 additions & 0 deletions pkgs/mcpx/internal/adapter/adapter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ package adapter_test
import (
"context"
"encoding/json"
"os"
"path/filepath"
"strings"
"testing"

Expand Down Expand Up @@ -241,3 +243,128 @@ func TestZeroTimeoutIsUnset(t *testing.T) {
t.Errorf("got %q", res.Stdout)
}
}

func TestAnUnsupportedRuntimeIsRefusedWithTheList(t *testing.T) {
spec := echoSpec()
spec.Runtime = "ruby"
err := spec.Validate()
if err == nil {
t.Fatal("ruby is not one of bash|js|ts|py")
}
if !strings.Contains(err.Error(), `runtime "ruby" is not supported; want bash|js|ts|py`) {
t.Errorf("the message should name the supported set: %v", err)
}
}

func TestSupportedRuntimesValidateWithoutAnInterpreterInstalled(t *testing.T) {
// Validate is a structural question: a declaration is well formed even
// on a machine where the interpreter is missing, and Probe is what
// says whether it can run.
for _, rt := range []string{"bash", "js", "ts", "py"} {
spec := echoSpec()
spec.Runtime = rt
spec.Command = "/nonexistent/script"
if err := spec.Validate(); err != nil {
t.Errorf("%s should validate: %v", rt, err)
}
}
}

func TestAScriptWithARuntimeProbesAndRuns(t *testing.T) {
// The two things a declaration with a runtime buys: `adapter check`
// passes for a path that is not on PATH, and Call spawns it through
// the interpreter.
if _, _, err := adapter.RuntimeInterpreter("bash"); err != nil {
t.Skip("no bash on this machine: ", err)
}
dir := t.TempDir()
path := filepath.Join(dir, "run.sh")
if err := os.WriteFile(path, []byte("#!/bin/sh\necho native\n"), 0o644); err != nil {
t.Fatal(err)
}
spec := adapter.Spec{
Name: "s", Command: path, Runtime: "bash",
Tools: []adapter.ToolSpec{{Name: "go"}},
}
if err := spec.Probe(); err != nil {
t.Fatalf("a script file with a runtime should probe: %v", err)
}
res, err := spec.Call(context.Background(), "go", nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(res.Stdout, "native") {
t.Errorf("got %q", res.Stdout)
}
if !strings.Contains(res.Command, "bash") || !strings.Contains(res.Command, path) {
t.Errorf("the resolved command should be reported: %q", res.Command)
}
}

func TestARuntimeWithNoScriptIsRefusedClearly(t *testing.T) {
spec := adapter.Spec{Name: "s", Command: "/nonexistent/x.sh", Runtime: "bash",
Tools: []adapter.ToolSpec{{Name: "go"}}}
err := spec.Probe()
if err == nil {
t.Fatal("a missing script should not probe")
}
if !strings.Contains(err.Error(), "not a file") {
t.Errorf("the message should say what is wrong: %v", err)
}
}

func TestAScriptOnPathFallsBackWhenAbsentFromDir(t *testing.T) {
// A runtime adapter may name a bare script that lives on PATH while
// its working dir is elsewhere: the dir-relative file is tried first,
// then the documented PATH fallback, not a stat error on the join.
if _, _, err := adapter.RuntimeInterpreter("bash"); err != nil {
t.Skip("no bash on this machine: ", err)
}
binDir := t.TempDir()
script := filepath.Join(binDir, "onpath.sh")
if err := os.WriteFile(script, []byte("#!/bin/sh\necho frompath\n"), 0o755); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
spec := adapter.Spec{
Name: "s", Command: "onpath.sh", Runtime: "bash", Dir: t.TempDir(),
Tools: []adapter.ToolSpec{{Name: "go"}},
}
if err := spec.Probe(); err != nil {
t.Fatalf("a PATH script with a working dir elsewhere should probe: %v", err)
}
res, err := spec.Call(context.Background(), "go", nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(res.Stdout, "frompath") {
t.Errorf("got %q", res.Stdout)
}
}

func TestARelativeExecutableResolvesAgainstDirWithoutARuntime(t *testing.T) {
// Regression (Codex on #2504): a declaration with command "./tool",
// an explicit dir and no runtime used to resolve the executable
// against the caller's working directory, so a tool that exists only
// under dir failed before it ever ran. Before commands were resolved
// in command(), exec resolved the path against cmd.Dir.
dir := t.TempDir()
path := filepath.Join(dir, "tool")
if err := os.WriteFile(path, []byte("#!/bin/sh\necho dirlocal\n"), 0o755); err != nil {
t.Fatal(err)
}
spec := adapter.Spec{
Name: "d", Command: "./tool", Dir: dir,
Tools: []adapter.ToolSpec{{Name: "go"}},
}
if err := spec.Probe(); err != nil {
t.Fatalf("an executable under Dir should probe: %v", err)
}
res, err := spec.Call(context.Background(), "go", nil)
if err != nil {
t.Fatal(err)
}
if !strings.Contains(res.Stdout, "dirlocal") {
t.Errorf("got %q", res.Stdout)
}
}
Loading
Loading