From f76452c780e9fd37cd0da101b1d6b016784aaf20 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 20:46:55 -0500 Subject: [PATCH 1/3] feat(mcpx): recipes as MCP tools and runtime on adapter declarations (#2117) --- pkgs/mcpx/docs/configuration.md | 26 +++ pkgs/mcpx/docs/consumer.md | 11 ++ pkgs/mcpx/internal/adapter/adapter.go | 41 ++++- pkgs/mcpx/internal/adapter/adapter_test.go | 71 ++++++++ pkgs/mcpx/internal/adapter/runtime.go | 144 +++++++++++++++++ .../mcpx/internal/cli/adapter_runtime_test.go | 133 +++++++++++++++ pkgs/mcpx/internal/cli/commands.go | 4 + pkgs/mcpx/internal/cli/recipe_tools.go | 133 +++++++++++++++ pkgs/mcpx/internal/cli/serve.go | 13 ++ pkgs/mcpx/internal/mcpserver/recipe_tools.go | 49 ++++++ .../internal/mcpserver/recipe_tools_test.go | 153 ++++++++++++++++++ pkgs/mcpx/internal/recipes/recipes.go | 24 ++- pkgs/mcpx/internal/recipes/tools.go | 139 ++++++++++++++++ pkgs/mcpx/internal/recipes/tools_test.go | 130 +++++++++++++++ 14 files changed, 1067 insertions(+), 4 deletions(-) create mode 100644 pkgs/mcpx/internal/adapter/runtime.go create mode 100644 pkgs/mcpx/internal/cli/adapter_runtime_test.go create mode 100644 pkgs/mcpx/internal/cli/recipe_tools.go create mode 100644 pkgs/mcpx/internal/mcpserver/recipe_tools.go create mode 100644 pkgs/mcpx/internal/mcpserver/recipe_tools_test.go create mode 100644 pkgs/mcpx/internal/recipes/tools.go create mode 100644 pkgs/mcpx/internal/recipes/tools_test.go diff --git a/pkgs/mcpx/docs/configuration.md b/pkgs/mcpx/docs/configuration.md index bf4f82ed73..ab868b2b50 100644 --- a/pkgs/mcpx/docs/configuration.md +++ b/pkgs/mcpx/docs/configuration.md @@ -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 | + +## 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. diff --git a/pkgs/mcpx/docs/consumer.md b/pkgs/mcpx/docs/consumer.md index c0f4c02055..e35e32ca09 100644 --- a/pkgs/mcpx/docs/consumer.md +++ b/pkgs/mcpx/docs/consumer.md @@ -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_`, +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 diff --git a/pkgs/mcpx/internal/adapter/adapter.go b/pkgs/mcpx/internal/adapter/adapter.go index 3c0c295df7..28014fbca6 100644 --- a/pkgs/mcpx/internal/adapter/adapter.go +++ b/pkgs/mcpx/internal/adapter/adapter.go @@ -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"` @@ -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()) } @@ -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. @@ -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 { @@ -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() @@ -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 diff --git a/pkgs/mcpx/internal/adapter/adapter_test.go b/pkgs/mcpx/internal/adapter/adapter_test.go index 85e747945c..ec6eb22373 100644 --- a/pkgs/mcpx/internal/adapter/adapter_test.go +++ b/pkgs/mcpx/internal/adapter/adapter_test.go @@ -3,6 +3,8 @@ package adapter_test import ( "context" "encoding/json" + "os" + "path/filepath" "strings" "testing" @@ -241,3 +243,72 @@ 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) + } +} diff --git a/pkgs/mcpx/internal/adapter/runtime.go b/pkgs/mcpx/internal/adapter/runtime.go new file mode 100644 index 0000000000..6b320c3299 --- /dev/null +++ b/pkgs/mcpx/internal/adapter/runtime.go @@ -0,0 +1,144 @@ +package adapter + +import ( + "fmt" + "os" + "os/exec" + "path/filepath" + "strings" + + "github.com/dezren39/mcpx/internal/defaults" +) + +// Runtime kinds a declaration may name. The set is the issue's: bash, js, +// ts, py. Each maps to a binary this machine has to provide. +const ( + RuntimeBash = "bash" + RuntimeJS = "js" + RuntimeTS = "ts" + RuntimePy = "py" +) + +// runtimeBinaries is the interpreter each kind resolves through, in the +// order tried. bash and py have one obvious answer plus the fallback name a +// machine without it actually uses; JavaScript reuses defaults.RuntimeOrder, +// the same deno/bun/node preference `mcpx exec` applies, because two orders +// for the same three binaries would be a preference nobody could predict. +var runtimeBinaries = map[string][]string{ + RuntimeBash: {"bash", "sh"}, + RuntimePy: {"python3", "python"}, + RuntimeJS: defaults.RuntimeOrder, + RuntimeTS: defaults.RuntimeOrder, +} + +// runtimePrefix is argv placed between the interpreter and the script. +// +// Only deno needs one: `deno script.ts` is not a thing, `deno run +// script.ts` is. bun and node take the file directly. +var runtimePrefix = map[string][]string{ + "deno": {"run"}, +} + +// interpreterName is a binary's bare name, without a Windows extension, so +// the deno `run` prefix is found however the path is spelled. +func interpreterName(path string) string { + base := filepath.Base(path) + return strings.TrimSuffix(base, filepath.Ext(base)) +} + +// checkRuntime rejects an unknown runtime name with the list of the ones +// that exist. Kept separate from resolution so Validate does not depend on +// what is installed. +func checkRuntime(name string) error { + if _, ok := runtimeBinaries[strings.ToLower(name)]; ok { + return nil + } + return fmt.Errorf("runtime %q is not supported; want bash|js|ts|py", name) +} + +// RuntimeInterpreter resolves a runtime name to a binary and the argv that +// must precede the script. +// +// A declaration naming bash or py is asking this machine for its +// interpreter, the same way a command name asks for a binary on PATH. Which +// binary answered is returned, so a caller can report it rather than let the +// author guess what "py" ran. +func RuntimeInterpreter(name string) (bin string, prefix []string, err error) { + kind := strings.ToLower(strings.TrimSpace(name)) + if err := checkRuntime(kind); err != nil { + return "", nil, err + } + var tried []string + for _, candidate := range runtimeBinaries[kind] { + p, lerr := exec.LookPath(candidate) + if lerr != nil { + tried = append(tried, candidate) + continue + } + return p, append([]string{}, runtimePrefix[interpreterName(p)]...), nil + } + return "", nil, fmt.Errorf("runtime %q: none of %s is on PATH", + name, strings.Join(tried, ", ")) +} + +// command resolves how this declaration is spawned. +// +// Without a runtime this is exactly what it always was: Command on PATH. +// With one, Command is a script -- a path to the file, or a name on PATH -- +// and the runtime supplies the executable. Command itself stays what the +// declaration wrote, which is what listings show; the interpreter and script +// are what actually run. +func (s Spec) command() (bin string, prefix []string, script string, err error) { + if s.Runtime == "" { + p, lerr := exec.LookPath(s.Command) + if lerr != nil { + return "", nil, "", fmt.Errorf("%s is not on PATH", s.Command) + } + return p, nil, "", nil + } + bin, prefix, err = RuntimeInterpreter(s.Runtime) + if err != nil { + return "", nil, "", err + } + command := s.Command + if s.Dir != "" && !filepath.IsAbs(command) { + // The declaration already says where the program's files live, and + // a script written beside them is the ordinary case. + command = filepath.Join(s.Dir, command) + } + script, err = scriptPath(command) + if err != nil { + return "", nil, "", err + } + return bin, prefix, script, nil +} + +// scriptPath finds the file a runtime should execute. +// +// An absolute path, a path relative to the declaration's Dir, or a name on +// PATH: all three are what people mean by "point it at this script". A +// command that is neither an existing file nor on PATH is the error worth +// having, because it is the one that would otherwise surface as an +// interpreter complaining about a file nobody named. +func scriptPath(command string) (string, error) { + if command == "" { + return "", fmt.Errorf("no script to run") + } + if filepath.IsAbs(command) { + if _, err := os.Stat(command); err != nil { + return "", fmt.Errorf("%s is not a file: %w", command, err) + } + return command, nil + } + if _, err := os.Stat(command); err == nil { + abs, aerr := filepath.Abs(command) + if aerr != nil { + return command, nil + } + return abs, nil + } + if p, err := exec.LookPath(command); err == nil { + return p, nil + } + return "", fmt.Errorf("%s is not a script file and is not on PATH", command) +} diff --git a/pkgs/mcpx/internal/cli/adapter_runtime_test.go b/pkgs/mcpx/internal/cli/adapter_runtime_test.go new file mode 100644 index 0000000000..d970bcb225 --- /dev/null +++ b/pkgs/mcpx/internal/cli/adapter_runtime_test.go @@ -0,0 +1,133 @@ +package cli + +import ( + "context" + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/dezren39/mcpx/internal/adapter" + "github.com/dezren39/mcpx/internal/mcpserver" + "github.com/dezren39/mcpx/internal/recipes" +) + +// These spawn for real: `mcpx adapter serve` mounts exactly these extras, +// and a runtime that resolved but could not run would pass every other test. + +func servedAdapter(t *testing.T, spec adapter.Spec) *mcpserver.Server { + t.Helper() + if err := spec.Validate(); err != nil { + t.Fatal(err) + } + if err := spec.Probe(); err != nil { + t.Fatal(err) + } + srv := mcpserver.New(nil, spec.Name, "test") + srv.ExtrasOnly = true + return srv.WithExtras(adapterTools([]adapter.Spec{spec}, false)) +} + +func TestABashScriptDeclaredWithARuntimeServesAndAnswers(t *testing.T) { + path := writeScript(t, t.TempDir(), "greet.sh", "#!/bin/sh\necho \"hello $1\"\n") + spec := adapter.Spec{ + Name: "shout", Command: path, Runtime: "bash", + Tools: []adapter.ToolSpec{{ + Name: "greet", + Params: []adapter.Param{{Name: "who", Required: true}}, + }}, + } + srv := servedAdapter(t, spec) + out, err := srv.InvokeTool(context.Background(), "greet", + json.RawMessage(`{"who":"world"}`)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "hello world") { + t.Errorf("out = %q", out) + } +} + +func TestAPythonScriptDeclaredWithARuntimeServesAndAnswers(t *testing.T) { + if _, _, err := adapter.RuntimeInterpreter("py"); err != nil { + t.Skip("no python3 on this machine: ", err) + } + path := writeScript(t, t.TempDir(), "greet.py", + "import sys\nprint('hello ' + sys.argv[1])\n") + spec := adapter.Spec{ + Name: "snake", Command: path, Runtime: "py", + Tools: []adapter.ToolSpec{{ + Name: "greet", + Params: []adapter.Param{{Name: "who", Required: true}}, + }}, + } + srv := servedAdapter(t, spec) + out, err := srv.InvokeTool(context.Background(), "greet", + json.RawMessage(`{"who":"world"}`)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "hello world") { + t.Errorf("out = %q", out) + } +} + +func TestAScriptPathIsResolvedAgainstTheDeclarationsDir(t *testing.T) { + // A declaration says where its program's files live; a script beside + // them is the ordinary case, and "./x.sh" has to mean that file. + dir := t.TempDir() + if err := os.WriteFile(filepath.Join(dir, "local.sh"), + []byte("#!/bin/sh\necho local\n"), 0o755); err != nil { + t.Fatal(err) + } + spec := adapter.Spec{ + Name: "local", Command: "./local.sh", Runtime: "bash", Dir: dir, + Tools: []adapter.ToolSpec{{Name: "run"}}, + } + srv := servedAdapter(t, spec) + out, err := srv.InvokeTool(context.Background(), "run", nil) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "local") { + t.Errorf("out = %q", out) + } +} + +func TestFormatRecipeToolStateNamesWhatWasSkipped(t *testing.T) { + // `mcpx catalog` is where somebody finds out what is exposed; a recipe + // kept out by a collision has to be visible there. + set := recipes.Tools( + []recipes.Recipe{ + recipes.Parse("taken", "/tmp/taken.ts", "// x\n"), + recipes.Parse("off", "/tmp/off.ts", "// x\n// @tool false\n"), + }, + map[string]bool{"recipe_taken": true}, 0) + text := formatRecipeToolState(set, nil) + for _, want := range []string{ + "recipe tools:", "exposed (budget", "1 opted out", + "recipe_taken", "already exposed", + } { + if !strings.Contains(text, want) { + t.Errorf("missing %q from:\n%s", want, text) + } + } +} + +func TestAnAdapterCommandWithNoRuntimeIsUnchanged(t *testing.T) { + // Backwards compatible: a declared binary is still looked up on PATH + // and exec'd directly. + spec := adapter.Spec{ + Name: "echoer", Command: "echo", + Tools: []adapter.ToolSpec{{Name: "say", Params: []adapter.Param{{Name: "x"}}}}, + } + srv := servedAdapter(t, spec) + out, err := srv.InvokeTool(context.Background(), "say", json.RawMessage(`{"x":"hi"}`)) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(out, "hi") { + t.Errorf("out = %q", out) + } +} diff --git a/pkgs/mcpx/internal/cli/commands.go b/pkgs/mcpx/internal/cli/commands.go index 75ab373891..04ac880c03 100644 --- a/pkgs/mcpx/internal/cli/commands.go +++ b/pkgs/mcpx/internal/cli/commands.go @@ -2044,6 +2044,10 @@ func (a *App) CmdCatalog(ctx context.Context, args []string) error { return err } fmt.Print(text) + // Recipe tools are not namespaces, so the catalog above cannot show + // them; report their own budget and anything the cap or a collision + // kept out. + a.printRecipeToolState(ctx, c) return nil } diff --git a/pkgs/mcpx/internal/cli/recipe_tools.go b/pkgs/mcpx/internal/cli/recipe_tools.go new file mode 100644 index 0000000000..15c5f6d891 --- /dev/null +++ b/pkgs/mcpx/internal/cli/recipe_tools.go @@ -0,0 +1,133 @@ +package cli + +import ( + "context" + "errors" + "fmt" + "strings" + + "github.com/dezren39/mcpx/internal/mcpserver" + "github.com/dezren39/mcpx/internal/recipes" +) + +// recipeToolSet is what the recipes on the search path contribute to +// tools/list, given the names the other producers already expose. +// +// The list comes from the daemon, which already resolved the script search +// path for this project. Nothing here reads a directory a second time. +func (a *App) recipeToolSet(ctx context.Context, c *Client, taken map[string]bool) (recipes.ToolSet, error) { + list, err := c.Recipes(ctx) + if err != nil { + return recipes.ToolSet{}, err + } + return recipes.Tools(list.Recipes, taken, recipes.DefaultToolBudget), nil +} + +// recipeToolExtras is recipeToolSet as MCP tools. +// +// Calling one posts to /v1/recipes/{name}/run, the path `mcpx recipes run` +// already uses: rendering, diagnostics, autonomy and the runner are the +// daemon's, not a copy here. +func (a *App) recipeToolExtras(ctx context.Context, c *Client, taken map[string]bool) ([]mcpserver.Extra, recipes.ToolSet, error) { + set, err := a.recipeToolSet(ctx, c, taken) + if err != nil { + return nil, set, err + } + run := func(ctx context.Context, name string, values map[string]any) (string, error) { + c, cerr := a.ensure(ctx) + if cerr != nil { + return "", cerr + } + res, rerr := c.RunRecipe(ctx, name, values, "run", a.mcpSession()) + if rerr != nil { + return "", rerr + } + return renderRecipeResult(res) + } + return mcpserver.RecipeTools(set.Tools, run), set, nil +} + +// renderRecipeResult favours the recipe's stdout, as the adapter path does: +// that is what the script has to say. Diagnostics and a non-zero exit are +// appended rather than substituted, and a run that produced nothing is +// reported as the message the daemon gave instead of an empty string. +func renderRecipeResult(res *Resolution) (string, error) { + if res == nil { + return "", errors.New("the recipe produced no answer") + } + if res.Result == nil { + if res.Message != "" { + return "", errors.New(res.Message) + } + return res.Source, nil + } + var b strings.Builder + b.WriteString(strings.TrimRight(res.Result.Stdout, "\n")) + if s := strings.TrimSpace(res.Result.Stderr); s != "" { + if b.Len() > 0 { + b.WriteString("\n\n") + } + b.WriteString("stderr:\n" + s) + } + if res.Result.ExitCode != 0 { + fmt.Fprintf(&b, "\n\n(exit %d)", res.Result.ExitCode) + } + if res.Result.Error != "" { + return b.String(), errors.New(res.Result.Error) + } + if b.Len() == 0 { + return "(no output)", nil + } + return b.String(), nil +} + +// printRecipeToolState reports what recipes add to tools/list, against what +// budget, and which ones did not make it. +// +// `mcpx catalog` is where somebody looks to find out what is exposed, so a +// recipe skipped for a name collision is named here rather than silently +// absent from the only list that would have shown it. +func (a *App) printRecipeToolState(ctx context.Context, c *Client) { + set, err := a.recipeToolSet(ctx, c, a.takenToolNames()) + fmt.Print(formatRecipeToolState(set, err)) +} + +// formatRecipeToolState renders the recipe block `mcpx catalog` ends with. +// +// Split from the listing so it can be checked without a daemon: the point of +// the block is that a skip is named, and that is a string contract. +func formatRecipeToolState(set recipes.ToolSet, err error) string { + if err != nil { + return fmt.Sprintf("\nrecipe tools: unavailable (%v)\n", err) + } + var b strings.Builder + hidden := "" + if set.Hidden > 0 { + hidden = fmt.Sprintf(", %d opted out", set.Hidden) + } + fmt.Fprintf(&b, "\nrecipe tools: %d exposed (budget %d%s)\n", + len(set.Tools), set.Budget, hidden) + for _, s := range set.Skipped { + fmt.Fprintf(&b, " %s: %s\n", s.Name, s.Reason) + } + return b.String() +} + +// takenToolNames is every name the other producers already claim, as far as +// they can be known without starting anything: adapter tools and the /v1 +// operation tools. OpenAPI operations are read over the network and are not +// included here; building the MCP surface itself checks against them. +func (a *App) takenToolNames() map[string]bool { + taken := map[string]bool{} + if specs, err := a.loadAdapters(); err == nil { + for _, s := range specs { + for _, t := range s.Tools { + taken[s.Name+"_"+t.Name] = true + } + } + } + for _, e := range a.v1OpTools() { + taken[e.Tool.Name] = true + } + return taken +} diff --git a/pkgs/mcpx/internal/cli/serve.go b/pkgs/mcpx/internal/cli/serve.go index f57c786fb1..53a621b541 100644 --- a/pkgs/mcpx/internal/cli/serve.go +++ b/pkgs/mcpx/internal/cli/serve.go @@ -541,6 +541,19 @@ func (a *App) MCPServer(ctx context.Context) (*mcpserver.Server, error) { // endpoint reachable from curl and from the plugin but not from MCP is // reachable from fewer places than it needs to be. extras = append(extras, a.v1OpTools()...) + // Recipes carry a typed schema in their header already; exposing each + // one as a tool is the shortest path from "saved script" to "an agent + // can see and call it". A name another producer already claimed is + // skipped and reported by `mcpx catalog`, never shadowed. + if c, err := a.ensure(ctx); err == nil { + taken := map[string]bool{} + for _, e := range extras { + taken[e.Tool.Name] = true + } + if recipeExtras, _, rerr := a.recipeToolExtras(ctx, c, taken); rerr == nil { + extras = append(extras, recipeExtras...) + } + } if len(extras) > 0 { srv = srv.WithExtras(extras) } diff --git a/pkgs/mcpx/internal/mcpserver/recipe_tools.go b/pkgs/mcpx/internal/mcpserver/recipe_tools.go new file mode 100644 index 0000000000..ff8a783878 --- /dev/null +++ b/pkgs/mcpx/internal/mcpserver/recipe_tools.go @@ -0,0 +1,49 @@ +package mcpserver + +import ( + "context" + "encoding/json" + "errors" + + "github.com/dezren39/mcpx/internal/recipes" +) + +// RecipeRunner runs one saved recipe with the values a caller supplied. +// +// Supplied rather than implemented here: a recipe runs through the daemon's +// existing /v1/recipes/{name}/run path, and a second runner in the protocol +// package would be a second set of bugs. The package that owns the client +// wires the two together. +type RecipeRunner func(ctx context.Context, recipe string, values map[string]any) (string, error) + +// RecipeTools presents exposed recipes as tools. +// +// A recipe already declares a typed schema in its header, and this is the +// place it becomes visible to a host that will never read the file: one +// tool per recipe, named recipe_, with the @param schema unchanged. +func RecipeTools(tools []recipes.Tool, run RecipeRunner) []Extra { + out := make([]Extra, 0, len(tools)) + for _, t := range tools { + t := t + out = append(out, Extra{ + Tool: Tool{ + Name: t.Name, + Description: t.Description, + InputSchema: t.InputSchema, + }, + Call: func(ctx context.Context, raw json.RawMessage) (string, error) { + if run == nil { + return "", errors.New("this recipe tool has no runner") + } + values := map[string]any{} + if len(raw) > 0 { + if err := json.Unmarshal(raw, &values); err != nil { + return "", err + } + } + return run(ctx, t.Recipe.Name, values) + }, + }) + } + return out +} diff --git a/pkgs/mcpx/internal/mcpserver/recipe_tools_test.go b/pkgs/mcpx/internal/mcpserver/recipe_tools_test.go new file mode 100644 index 0000000000..6c9c0166e6 --- /dev/null +++ b/pkgs/mcpx/internal/mcpserver/recipe_tools_test.go @@ -0,0 +1,153 @@ +package mcpserver_test + +import ( + "context" + "encoding/json" + "errors" + "strings" + "testing" + + "github.com/dezren39/mcpx/internal/mcpserver" + "github.com/dezren39/mcpx/internal/recipes" +) + +const recipeSource = `// Close stale issues in a repository. +// @param repo:string which repository, as owner/name +// @param days:number = 30 how old counts as stale +const found = await demo.search({ repo: @repo, olderThanDays: @days }); +` + +func parseRecipe(name, src string) recipes.Recipe { + return recipes.Parse(name, "/tmp/"+name+".ts", src) +} + +// recipeSurface is a server whose whole surface is the recipe tools, as +// `mcpx serve` builds it: the tools a host reads and calls. +func recipeSurface(t *testing.T, all []recipes.Recipe, + run mcpserver.RecipeRunner) *mcpserver.Server { + t.Helper() + set := recipes.Tools(all, nil, 0) + if len(set.Tools) == 0 { + t.Fatalf("no recipe tools to expose: %+v", set) + } + srv := mcpserver.New(nil, "mcpx", "test") + srv.ExtrasOnly = true + return srv.WithExtras(mcpserver.RecipeTools(set.Tools, run)) +} + +func TestARecipeAppearsInToolsListWithItsParamSchema(t *testing.T) { + srv := recipeSurface(t, + []recipes.Recipe{parseRecipe("close-stale", recipeSource)}, + func(context.Context, string, map[string]any) (string, error) { return "ok", nil }) + + var found *mcpserver.Tool + for _, tool := range srv.Tools() { + if tool.Name == "recipe_close-stale" { + found = &tool + } + } + if found == nil { + t.Fatalf("recipe_close-stale is not in %v", names(srv.Tools())) + } + var schema struct { + Properties map[string]struct { + Type string `json:"type"` + } `json:"properties"` + Required []string + } + if err := json.Unmarshal(found.InputSchema, &schema); err != nil { + t.Fatalf("schema: %v", err) + } + if schema.Properties["repo"].Type != "string" || + schema.Properties["days"].Type != "number" { + t.Errorf("the @param types should survive: %+v", schema.Properties) + } +} + +func TestARecipeToolIsCallableThroughTheMCPToolPath(t *testing.T) { + var gotName string + var gotValues map[string]any + srv := recipeSurface(t, + []recipes.Recipe{parseRecipe("close-stale", recipeSource)}, + func(_ context.Context, name string, values map[string]any) (string, error) { + gotName, gotValues = name, values + return "closed 3 issues", nil + }) + out, err := srv.InvokeTool(context.Background(), "recipe_close-stale", + json.RawMessage(`{"repo":"acme/web","days":7}`)) + if err != nil { + t.Fatal(err) + } + if out != "closed 3 issues" { + t.Errorf("out = %q", out) + } + if gotName != "close-stale" { + t.Errorf("the runner should be told the recipe, got %q", gotName) + } + if gotValues["repo"] != "acme/web" || gotValues["days"] != 7.0 { + t.Errorf("values = %+v", gotValues) + } + // A runtime failure is an error, not a result. + failing := recipeSurface(t, + []recipes.Recipe{parseRecipe("close-stale", recipeSource)}, + func(context.Context, string, map[string]any) (string, error) { + return "", errors.New("needs repo") + }) + if _, err := failing.InvokeTool(context.Background(), "recipe_close-stale", + json.RawMessage(`{}`)); err == nil { + t.Error("a failed run should be an error") + } +} + +func TestAnOptedOutRecipeIsAbsentFromToolsList(t *testing.T) { + all := []recipes.Recipe{ + parseRecipe("shown", recipeSource), + parseRecipe("hidden", recipeSource+"// @tool false\n"), + } + srv := recipeSurface(t, all, + func(context.Context, string, map[string]any) (string, error) { return "ok", nil }) + listed := strings.Join(names(srv.Tools()), ",") + if !strings.Contains(listed, "recipe_shown") { + t.Errorf("the default recipe should be listed: %v", listed) + } + if strings.Contains(listed, "recipe_hidden") { + t.Errorf("@tool false should keep the recipe out: %v", listed) + } +} + +func TestARecipeToolNameThatCollidesIsNotExposed(t *testing.T) { + // The documented rule is one tool name per surface; a producer that + // cannot have its name does not shadow the one that has it. + set := recipes.Tools( + []recipes.Recipe{parseRecipe("close-stale", recipeSource)}, + map[string]bool{"recipe_close-stale": true}, 0) + if len(set.Tools) != 0 || len(set.Skipped) != 1 { + t.Fatalf("collision should skip, not shadow: %+v", set) + } +} + +func TestReListingDoesNotDuplicateRecipeTools(t *testing.T) { + srv := recipeSurface(t, + []recipes.Recipe{parseRecipe("close-stale", recipeSource)}, + func(context.Context, string, map[string]any) (string, error) { return "ok", nil }) + first := names(srv.Tools()) + second := names(srv.Tools()) + if strings.Join(first, ",") != strings.Join(second, ",") { + t.Errorf("two listings differ: %v then %v", first, second) + } + seen := map[string]bool{} + for _, n := range second { + if seen[n] { + t.Errorf("%s appears twice in %v", n, second) + } + seen[n] = true + } +} + +func names(tools []mcpserver.Tool) []string { + out := make([]string, 0, len(tools)) + for _, t := range tools { + out = append(out, t.Name) + } + return out +} diff --git a/pkgs/mcpx/internal/recipes/recipes.go b/pkgs/mcpx/internal/recipes/recipes.go index 526b1a3b61..ce53fd2536 100644 --- a/pkgs/mcpx/internal/recipes/recipes.go +++ b/pkgs/mcpx/internal/recipes/recipes.go @@ -69,6 +69,10 @@ type Recipe struct { // Tools are the namespace.tool calls the body makes, which is what makes // matching free text to a recipe more than a name comparison. Tools []string `json:"tools,omitempty"` + // OptOut is set by a `@tool false` header. Recipe tools are exposed in + // tools/list by default -- the schema is already written down, so the + // useful question is how to hide one, not how to publish one. + OptOut bool `json:"optOut,omitempty"` // Source is the file's contents. Omitted from listings, which would // otherwise be dominated by it. Source string `json:"source,omitempty"` @@ -90,6 +94,12 @@ var paramDecl = regexp.MustCompile( // reads as a placeholder called "param". var declLine = regexp.MustCompile(`^\s*(?://|#|\*)\s*@param\b`) +// toolDecl matches the MCP exposure marker, `@tool` on its own (on, the +// default) or `@tool false` (off). A recipe is a tool unless its author says +// otherwise: the schema already exists, and a repository with fifty scripts +// is exactly the case the budget in `mcpx catalog` answers. +var toolDecl = regexp.MustCompile(`^\s*(?://|#|\*)\s*@tool\b\s*([A-Za-z0-9]*)`) + // Parse reads a script and describes it as a recipe. func Parse(name, path, src string) Recipe { r := Recipe{Name: name, Path: path, Source: src} @@ -99,11 +109,17 @@ func Parse(name, path, src string) Recipe { for _, line := range strings.Split(src, "\n") { trimmed := strings.TrimSpace(line) if r.Summary == "" && strings.HasPrefix(trimmed, "//") && - !strings.Contains(trimmed, "@param") { + !strings.Contains(trimmed, "@param") && !strings.Contains(trimmed, "@tool") { r.Summary = strings.TrimSpace(strings.TrimPrefix(trimmed, "//")) } m := paramDecl.FindStringSubmatch(line) if m == nil { + if t := toolDecl.FindStringSubmatch(line); t != nil { + switch strings.ToLower(t[1]) { + case "false", "off", "no", "0": + r.OptOut = true + } + } continue } p := Placeholder{Name: m[1], Type: normaliseType(m[3]), Required: true} @@ -276,6 +292,12 @@ func isWordByte(b byte) bool { (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z') || (b >= '0' && b <= '9') } +// ExposesTool says whether this recipe belongs in tools/list. +// +// Default on: a recipe already carries a typed schema, so hiding it should +// take a line somebody wrote. `@tool false` is that line. +func (r Recipe) ExposesTool() bool { return !r.OptOut } + // Missing lists the placeholders a set of values does not supply and that // have no default to fall back on. func (r Recipe) Missing(values map[string]any) []Placeholder { diff --git a/pkgs/mcpx/internal/recipes/tools.go b/pkgs/mcpx/internal/recipes/tools.go new file mode 100644 index 0000000000..f589bda329 --- /dev/null +++ b/pkgs/mcpx/internal/recipes/tools.go @@ -0,0 +1,139 @@ +package recipes + +import ( + "encoding/json" + "sort" + "strconv" + "strings" +) + +// Recipe tools share one namespace, as adapter tools do: `_` +// is the rule for a producer that is not a server of its own, and a recipe +// is the same shape -- one namespace, one tool per member. Recipes are not +// pooled servers, so the namespace is fixed rather than derived from a name +// somebody chose. +const ToolPrefix = "recipe_" + +// DefaultToolBudget caps how many recipe tools tools/list carries. +// +// A repository with fifty saved scripts would otherwise turn every host's +// tool list into those fifty schemas, which is the problem mcpx exists to +// avoid. The cap is reported by `mcpx catalog` beside the tools it did +// expose, so a recipe that did not make it is visible rather than absent. +const DefaultToolBudget = 25 + +// Tool is one recipe presented as an MCP tool. +type Tool struct { + // Recipe is the source recipe, with its body: not serialised, because a + // listing that carried every script would be the directory again. + Recipe Recipe `json:"-"` + // Name is the prefixed, tool-safe name: recipe_. + Name string + // Description is the summary a host shows, with the path, because two + // projects can hold recipes of the same name. + Description string + // InputSchema is the recipe's @param schema, already typed. + InputSchema json.RawMessage +} + +// Skip is an exposure that did not happen, and why. Reported rather than +// dropped: a recipe that collides is a naming mistake somebody can fix. +type Skip struct { + Recipe string `json:"recipe"` + Name string `json:"name"` + Reason string `json:"reason"` +} + +// ToolSet is what a set of recipes contributes to tools/list, plus the state +// needed to report it. +type ToolSet struct { + Tools []Tool `json:"tools"` + Skipped []Skip `json:"skipped,omitempty"` + // Budget is the cap that was applied; zero means DefaultToolBudget. + Budget int `json:"budget"` + // Hidden counts recipes that opted out with `@tool false`. + Hidden int `json:"hidden,omitempty"` + // Collisions counts skipped recipes whose name was already taken. + Collisions int `json:"collisions,omitempty"` +} + +// Tools builds the tool list from recipes. +// +// taken is every tool name the other producers already expose -- adapter +// tools, OpenAPI operations, mcpx's own. A recipe tool never shadows one: +// the documented rule for a collision is a loud report, and here the +// recipe is skipped and named in Skipped. Ordering is by recipe name so +// two runs of the same directory produce the same list. +func Tools(all []Recipe, taken map[string]bool, budget int) ToolSet { + if budget <= 0 { + budget = DefaultToolBudget + } + set := ToolSet{Budget: budget} + sorted := append([]Recipe(nil), all...) + sort.SliceStable(sorted, func(i, j int) bool { return sorted[i].Name < sorted[j].Name }) + + names := map[string]bool{} + for _, r := range sorted { + if !r.ExposesTool() { + set.Hidden++ + continue + } + name := ToolName(r.Name) + switch { + case name == ToolPrefix: + set.Skipped = append(set.Skipped, Skip{Recipe: r.Name, Name: name, + Reason: "the recipe has no usable name"}) + continue + case taken[name] || names[name]: + set.Collisions++ + set.Skipped = append(set.Skipped, Skip{Recipe: r.Name, Name: name, + Reason: "a tool named " + name + " is already exposed; rename the recipe"}) + continue + case len(set.Tools) >= budget: + set.Skipped = append(set.Skipped, Skip{Recipe: r.Name, Name: name, + Reason: "over the recipe tool budget of " + strconv.Itoa(budget)}) + continue + } + names[name] = true + set.Tools = append(set.Tools, r.tool(name)) + } + return set +} + +// tool renders one recipe as a tool. +func (r Recipe) tool(name string) Tool { + desc := strings.TrimSpace(r.Summary) + if desc == "" { + desc = "Saved mcpx recipe " + r.Name + "." + } + if r.Path != "" { + desc += "\n\nRuns " + r.Path + "." + } + return Tool{ + Recipe: r, + Name: name, + Description: desc, + InputSchema: FormSchema(r.Placeholders), + } +} + +// ToolName is the tool name a recipe gets: recipe_, with anything that +// is not legal in an MCP tool name replaced by an underscore. +// +// Recipe names are filenames, so a dot or a dash is ordinary; a space or a +// slash is not, and a name a host refuses is worse than one that reads +// slightly differently. +func ToolName(recipe string) string { + var b strings.Builder + b.WriteString(ToolPrefix) + for _, c := range recipe { + switch { + case c >= 'a' && c <= 'z', c >= 'A' && c <= 'Z', + c >= '0' && c <= '9', c == '_', c == '-', c == '.': + b.WriteRune(c) + default: + b.WriteByte('_') + } + } + return b.String() +} diff --git a/pkgs/mcpx/internal/recipes/tools_test.go b/pkgs/mcpx/internal/recipes/tools_test.go new file mode 100644 index 0000000000..e6bbd78fc6 --- /dev/null +++ b/pkgs/mcpx/internal/recipes/tools_test.go @@ -0,0 +1,130 @@ +package recipes_test + +import ( + "encoding/json" + "strings" + "testing" + + "github.com/dezren39/mcpx/internal/recipes" +) + +const exposed = `// Close stale issues in a repository. +// @param repo:string which repository, as owner/name +// @param days:number = 30 how old counts as stale +// @param dryRun:boolean? report without closing +const found = await demo.search({ repo: @repo, olderThanDays: @days }); +` + +func recipe(name, src string) recipes.Recipe { + return recipes.Parse(name, "/tmp/"+name+".ts", src) +} + +func TestARecipeBecomesAToolWithItsParamSchema(t *testing.T) { + set := recipes.Tools([]recipes.Recipe{recipe("close-stale", exposed)}, nil, 0) + if len(set.Tools) != 1 { + t.Fatalf("expected one tool, got %+v", set) + } + tool := set.Tools[0] + if tool.Name != "recipe_close-stale" { + t.Errorf("name = %q; recipe tools live under one namespace", tool.Name) + } + var schema struct { + Type string `json:"type"` + Required []string + Properties map[string]struct { + Type string `json:"type"` + Description string `json:"description"` + Default any `json:"default"` + } `json:"properties"` + } + if err := json.Unmarshal(tool.InputSchema, &schema); err != nil { + t.Fatalf("schema: %v in %s", err, tool.InputSchema) + } + if schema.Type != "object" { + t.Errorf("schema type = %q", schema.Type) + } + if p := schema.Properties["repo"]; p.Type != "string" || p.Description == "" { + t.Errorf("repo = %+v", p) + } + if p := schema.Properties["days"]; p.Type != "number" || p.Default != 30.0 { + t.Errorf("days should carry its type and default: %+v", p) + } + if p := schema.Properties["dryRun"]; p.Type != "boolean" { + t.Errorf("dryRun = %+v", p) + } + if strings.Join(schema.Required, ",") != "repo" { + t.Errorf("required = %v; only a hole with no default is required", schema.Required) + } +} + +func TestOptOutMarkerRemovesTheRecipeFromTheToolSet(t *testing.T) { + off := recipe("secret", exposed+"// @tool false\n") + if off.ExposesTool() { + t.Error("@tool false should opt the recipe out") + } + set := recipes.Tools([]recipes.Recipe{off}, nil, 0) + if len(set.Tools) != 0 || set.Hidden != 1 { + t.Errorf("an opted-out recipe must not be exposed: %+v", set) + } + // The default is on, which is what makes the marker the exception. + if !recipe("normal", exposed).ExposesTool() { + t.Error("a recipe without a marker should be exposed") + } +} + +func TestACollidingRecipeIsSkippedAndReported(t *testing.T) { + // Adapter and v1-op tools are already in tools/list; a recipe never + // shadows one, and `mcpx catalog` says which one it was. + set := recipes.Tools( + []recipes.Recipe{recipe("close-stale", exposed)}, + map[string]bool{"recipe_close-stale": true}, 0) + if len(set.Tools) != 0 { + t.Fatalf("a colliding recipe must not be exposed: %+v", set.Tools) + } + if set.Collisions != 1 || len(set.Skipped) != 1 { + t.Fatalf("the collision should be reported: %+v", set) + } + if !strings.Contains(set.Skipped[0].Reason, "already exposed") { + t.Errorf("reason = %q", set.Skipped[0].Reason) + } +} + +func TestTheBudgetIsAppliedAndReported(t *testing.T) { + all := []recipes.Recipe{ + recipe("a", exposed), recipe("b", exposed), recipe("c", exposed), + } + set := recipes.Tools(all, nil, 2) + if set.Budget != 2 || len(set.Tools) != 2 || len(set.Skipped) != 1 { + t.Fatalf("budget 2 of 3: %+v", set) + } + if !strings.Contains(set.Skipped[0].Reason, "budget") { + t.Errorf("reason = %q", set.Skipped[0].Reason) + } + // Unspecified is the built-in, not unlimited. + if got := recipes.Tools(all, nil, 0).Budget; got != recipes.DefaultToolBudget { + t.Errorf("budget = %d", got) + } +} + +func TestExposureIsIdempotent(t *testing.T) { + all := []recipes.Recipe{recipe("a", exposed), recipe("b", exposed)} + first := recipes.Tools(all, nil, 0) + second := recipes.Tools(all, nil, 0) + if len(first.Tools) != len(second.Tools) { + t.Fatalf("two runs differ: %d then %d", len(first.Tools), len(second.Tools)) + } + for i := range first.Tools { + if first.Tools[i].Name != second.Tools[i].Name { + t.Errorf("tool %d: %q then %q", i, first.Tools[i].Name, second.Tools[i].Name) + } + } +} + +func TestToolNamesAreSafeForAHost(t *testing.T) { + if got := recipes.ToolName("my recipe"); got != "recipe_my_recipe" { + t.Errorf("got %q", got) + } + if got := recipes.ToolName("close-stale"); got != "recipe_close-stale" { + t.Errorf("dots and dashes are legal and should survive: %q", got) + } +} From f495c8e5c6f7f9096263e3ff897087c0767de3ac Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 21:19:04 -0500 Subject: [PATCH 2/3] fix(mcpx): disposition Codex findings on recipe tools + runtime adapters (#2117) - recipe_tools: run recipes under the MCP caller's session (a.mcpCaller(ctx).SessionID), not the daemon process session, so session-scoped namespaces stay isolated per client (P1). - recipe_tools: a nonzero recipe exit now returns an error (output retained), so the MCP result is a tool failure, not a success (P2). - adapter/runtime: when Dir is set and the script is absent beside the declaration, fall back to resolving the bare name on PATH (P2); regression test probes+runs a PATH script with Dir elsewhere. - recipes: placeholder discovery (refs) skips // @tool marker lines as it already skipped @param declarations, so opting out of MCP exposure no longer invents a required 'tool' input (P2); regression test added. --- pkgs/mcpx/internal/adapter/adapter_test.go | 29 ++++++++++++++++++++++ pkgs/mcpx/internal/adapter/runtime.go | 5 ++++ pkgs/mcpx/internal/cli/recipe_tools.go | 11 +++++++- pkgs/mcpx/internal/recipes/recipes.go | 4 ++- pkgs/mcpx/internal/recipes/recipes_test.go | 11 ++++++++ 5 files changed, 58 insertions(+), 2 deletions(-) diff --git a/pkgs/mcpx/internal/adapter/adapter_test.go b/pkgs/mcpx/internal/adapter/adapter_test.go index ec6eb22373..ca1168a17e 100644 --- a/pkgs/mcpx/internal/adapter/adapter_test.go +++ b/pkgs/mcpx/internal/adapter/adapter_test.go @@ -312,3 +312,32 @@ func TestARuntimeWithNoScriptIsRefusedClearly(t *testing.T) { 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) + } +} diff --git a/pkgs/mcpx/internal/adapter/runtime.go b/pkgs/mcpx/internal/adapter/runtime.go index 6b320c3299..c172c99506 100644 --- a/pkgs/mcpx/internal/adapter/runtime.go +++ b/pkgs/mcpx/internal/adapter/runtime.go @@ -107,6 +107,11 @@ func (s Spec) command() (bin string, prefix []string, script string, err error) command = filepath.Join(s.Dir, command) } script, err = scriptPath(command) + if err != nil && command != s.Command { + // Not beside the declaration's files: the bare name may still be + // a script installed on PATH, which is the documented fallback. + script, err = scriptPath(s.Command) + } if err != nil { return "", nil, "", err } diff --git a/pkgs/mcpx/internal/cli/recipe_tools.go b/pkgs/mcpx/internal/cli/recipe_tools.go index 15c5f6d891..ec46b3703e 100644 --- a/pkgs/mcpx/internal/cli/recipe_tools.go +++ b/pkgs/mcpx/internal/cli/recipe_tools.go @@ -38,7 +38,10 @@ func (a *App) recipeToolExtras(ctx context.Context, c *Client, taken map[string] if cerr != nil { return "", cerr } - res, rerr := c.RunRecipe(ctx, name, values, "run", a.mcpSession()) + // The caller's own session, not this process's: recipes may call + // session-scoped namespaces, and two MCP clients must not share + // one upstream session by accident (see mcpCaller). + res, rerr := c.RunRecipe(ctx, name, values, "run", a.mcpCaller(ctx).SessionID) if rerr != nil { return "", rerr } @@ -75,6 +78,12 @@ func renderRecipeResult(res *Resolution) (string, error) { if res.Result.Error != "" { return b.String(), errors.New(res.Result.Error) } + if res.Result.ExitCode != 0 { + // A failed recipe is a failed tool call: the output above stays + // attached, but the MCP result must carry an error or callers + // read the failure as success. + return b.String(), fmt.Errorf("recipe exited with code %d", res.Result.ExitCode) + } if b.Len() == 0 { return "(no output)", nil } diff --git a/pkgs/mcpx/internal/recipes/recipes.go b/pkgs/mcpx/internal/recipes/recipes.go index ce53fd2536..03649b5aa8 100644 --- a/pkgs/mcpx/internal/recipes/recipes.go +++ b/pkgs/mcpx/internal/recipes/recipes.go @@ -255,7 +255,9 @@ func refs(src string) []string { var out []string seen := map[string]bool{} for _, line := range strings.Split(src, "\n") { - if declLine.MatchString(line) { + if declLine.MatchString(line) || toolDecl.MatchString(line) { + // Declaration and marker lines describe the recipe; the + // `@param`/`@tool` words in them are not placeholders. continue } for i := 0; i < len(line); i++ { diff --git a/pkgs/mcpx/internal/recipes/recipes_test.go b/pkgs/mcpx/internal/recipes/recipes_test.go index 0ac84c3b32..973af60a42 100644 --- a/pkgs/mcpx/internal/recipes/recipes_test.go +++ b/pkgs/mcpx/internal/recipes/recipes_test.go @@ -126,3 +126,14 @@ func TestAnEmailAddressIsNotAPlaceholder(t *testing.T) { t.Fatalf("placeholders = %+v", r.Placeholders) } } + +func TestAToolMarkerIsNotAPlaceholder(t *testing.T) { + r := recipes.Parse("x", "/tmp/x.ts", + "// @tool false\nawait demo.echo({ message: \"hi\" });") + if !r.OptOut { + t.Error("@tool false should opt the recipe out") + } + if len(r.Placeholders) != 0 { + t.Fatalf("the @tool marker is metadata, not an input: placeholders = %+v", r.Placeholders) + } +} From 78974986ed6b06ff99e53f8b2a544f079d48e488 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Thu, 29 Oct 2026 21:50:31 -0500 Subject: [PATCH 3/3] fix(mcpx): disposition Codex round-2 findings on PR #2504 (#2117) - adapter: resolve a relative executable against Dir when no runtime is declared (preserves pre-resolution exec behaviour for command: ./tool with dir set) - mcpserver: keep a failed tool's returned text in the isError result so a failed recipe's stdout/stderr reaches the caller alongside the error - regression tests for both --- pkgs/mcpx/internal/adapter/adapter_test.go | 27 +++++++++++++++++++ pkgs/mcpx/internal/adapter/runtime.go | 16 +++++++++++ .../internal/mcpserver/recipe_tools_test.go | 22 +++++++++++++++ pkgs/mcpx/internal/mcpserver/server.go | 11 +++++++- 4 files changed, 75 insertions(+), 1 deletion(-) diff --git a/pkgs/mcpx/internal/adapter/adapter_test.go b/pkgs/mcpx/internal/adapter/adapter_test.go index ca1168a17e..aff3b215b9 100644 --- a/pkgs/mcpx/internal/adapter/adapter_test.go +++ b/pkgs/mcpx/internal/adapter/adapter_test.go @@ -341,3 +341,30 @@ func TestAScriptOnPathFallsBackWhenAbsentFromDir(t *testing.T) { 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) + } +} diff --git a/pkgs/mcpx/internal/adapter/runtime.go b/pkgs/mcpx/internal/adapter/runtime.go index c172c99506..85a7bc71ca 100644 --- a/pkgs/mcpx/internal/adapter/runtime.go +++ b/pkgs/mcpx/internal/adapter/runtime.go @@ -90,6 +90,22 @@ func RuntimeInterpreter(name string) (bin string, prefix []string, err error) { // are what actually run. func (s Spec) command() (bin string, prefix []string, script string, err error) { if s.Runtime == "" { + if s.Dir != "" && !filepath.IsAbs(s.Command) && + (strings.ContainsRune(s.Command, '/') || strings.ContainsRune(s.Command, filepath.Separator)) { + // A relative path names a file, and the file it names is the + // one under the directory the call runs in: before commands + // were resolved here, Call handed the path to exec with + // cmd.Dir set, which resolved it there. LookPath alone + // resolves it against this process's own directory and + // misses an executable that exists only under Dir. + candidate := filepath.Join(s.Dir, s.Command) + if _, serr := os.Stat(candidate); serr == nil { + if abs, aerr := filepath.Abs(candidate); aerr == nil { + candidate = abs + } + return candidate, nil, "", nil + } + } p, lerr := exec.LookPath(s.Command) if lerr != nil { return "", nil, "", fmt.Errorf("%s is not on PATH", s.Command) diff --git a/pkgs/mcpx/internal/mcpserver/recipe_tools_test.go b/pkgs/mcpx/internal/mcpserver/recipe_tools_test.go index 6c9c0166e6..d202d96ac1 100644 --- a/pkgs/mcpx/internal/mcpserver/recipe_tools_test.go +++ b/pkgs/mcpx/internal/mcpserver/recipe_tools_test.go @@ -151,3 +151,25 @@ func names(tools []mcpserver.Tool) []string { } return out } + +func TestAFailedRecipeCallKeepsItsOutputInTheErrorResult(t *testing.T) { + // Regression (Codex on #2504): a recipe that printed diagnostics and + // exited nonzero had that output dropped by the tools/call handler, + // which sent only the error text, so the caller saw "recipe exited + // with code 1" and none of what the recipe actually said. + srv := recipeSurface(t, + []recipes.Recipe{parseRecipe("close-stale", recipeSource)}, + func(context.Context, string, map[string]any) (string, error) { + return "boom: the repo is gone\n\n(exit 1)", errors.New("recipe exited with code 1") + }) + text, isErr := call(t, srv, "recipe_close-stale", map[string]any{}) + if !isErr { + t.Fatalf("a failed recipe call should be an isError result, got %q", text) + } + if !strings.Contains(text, "boom: the repo is gone") { + t.Errorf("the recipe output should survive into the result: %q", text) + } + if !strings.Contains(text, "recipe exited with code 1") { + t.Errorf("the error should still be named: %q", text) + } +} diff --git a/pkgs/mcpx/internal/mcpserver/server.go b/pkgs/mcpx/internal/mcpserver/server.go index 8bb3edf01c..7e8189bea1 100644 --- a/pkgs/mcpx/internal/mcpserver/server.go +++ b/pkgs/mcpx/internal/mcpserver/server.go @@ -1024,8 +1024,17 @@ func (s *Server) handle(ctx context.Context, c *Conn, req request) *response { // error. The distinction matters: a protocol error means the // client did something wrong, and a client that retries the // wrong thing on a tool failure never converges. + // + // Text the tool returned alongside the error stays in the + // result: for a recipe that is its stdout/stderr, which is + // the diagnostics the caller needs. Dropping it left only + // "recipe exited with code N" to debug from. + errText := err.Error() + if text != "" && text != errText { + errText = text + "\n\n" + errText + } return reply(map[string]any{ - "content": []any{map[string]any{"type": "text", "text": err.Error()}}, + "content": []any{map[string]any{"type": "text", "text": errText}}, "isError": true, }) }