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
9 changes: 9 additions & 0 deletions pkgs/mcpx/internal/cli/commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,15 @@ func (a *App) runScript(ctx context.Context, args []string, inline bool) error {
return serr
}

// A recipe's @param holes are filled by `recipes run`, not here, and
// both run paths (local and on the daemon) would otherwise hand the
// raw holes to the runtime as a syntax error (#276).
if !inline && fs.NArg() > 0 {
if herr := refuseRecipeHoles(fs.Arg(0)); herr != nil {
return herr
}
}

if elsewhere {
return a.execOnDaemon(ctx, c, fs, inline, ns, sessionKey, eo,
execRemoteFlags{timeout: *timeout, runtime: *rt, permissions: *perms,
Expand Down
84 changes: 84 additions & 0 deletions pkgs/mcpx/internal/cli/recipe_holes_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
package cli

import (
"path/filepath"
"strings"
"testing"

"github.com/dezren39/mcpx/internal/testsupport"
)

// #276: `mcpx run greet hi` used to die with "SyntaxError: Expression
// expected" because run executed a recipe's @param holes as written.
// run must refuse early and name the command that fills them.

const holesRecipe = `// Greet someone through the demo server.
// @param message:string what to say
// @param loud:boolean = false shout it
const text = @loud ? String(@message).toUpperCase() : @message;
console.log(text);
`

func TestRunRefusesRecipeHolesAndPointsToRecipesRun(t *testing.T) {
root := testsupport.TempDir(t)
writeScript(t, filepath.Join(root, ScriptsDirName), "greet.ts", holesRecipe)
chdir(t, root)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "xdg"))

err := refuseRecipeHoles("greet")
if err == nil {
t.Fatal("a recipe with unfilled holes must not pass to the runtime")
}
msg := err.Error()
for _, want := range []string{
"greet is a recipe", "message", "loud",
"mcpx recipes run greet message=<value> [loud=<value>]",
} {
if !strings.Contains(msg, want) {
t.Errorf("error should mention %q:\n%s", want, msg)
}
}
}

func TestRunLeavesPlainScriptsAlone(t *testing.T) {
root := testsupport.TempDir(t)
writeScript(t, filepath.Join(root, ScriptsDirName), "plain.ts",
"console.log(\"hello\");\n")
// A body @name with no @param declaration is not a recipe: run's
// business is the script's, not the recipe check's.
writeScript(t, filepath.Join(root, ScriptsDirName), "undeclared.ts",
"const x = @thing;\nconsole.log(x);\n")
chdir(t, root)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "xdg"))

for _, name := range []string{"plain", "undeclared"} {
if err := refuseRecipeHoles(name); err != nil {
t.Errorf("%s: plain scripts must run as before, got:\n%v", name, err)
}
}
}

func TestRunRecipeOutsideScriptPathPointsToSave(t *testing.T) {
root := testsupport.TempDir(t)
p := writeScript(t, root, "greet.ts", holesRecipe)
chdir(t, root)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "xdg"))

err := refuseRecipeHoles(p)
if err == nil {
t.Fatal("a recipe addressed by path must still be refused")
}
if !strings.Contains(err.Error(), "mcpx recipes save greet ") {
t.Errorf("a recipe the daemon cannot find by name should be pointed at save:\n%v", err)
}
}

func TestRunMissingScriptIsLeftToTheRun(t *testing.T) {
root := testsupport.TempDir(t)
chdir(t, root)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "xdg"))

if err := refuseRecipeHoles("nope"); err != nil {
t.Errorf("an unresolvable name is resolveScript's error to report, got:\n%v", err)
}
}
82 changes: 82 additions & 0 deletions pkgs/mcpx/internal/cli/scripts.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
Expand Down Expand Up @@ -270,6 +271,87 @@ func resolveScript(arg string) (string, error) {
arg, path.Describe(), ScriptsDirName, filepath.Join(ScriptsDirName, arg+ScriptExt))
}

// paramDeclHead matches the head of one `@param` declaration line, the
// same spelling internal/recipes parses. Only the head is needed here:
// whether a script declares any holes at all, not what they are.
var paramDeclHead = regexp.MustCompile(`^\s*(?://|#|\*)\s*@param\s+[A-Za-z_]`)

// declaresParams reports whether a script declares recipe holes. A bare
// `@name` in a body is not enough -- an ordinary script may contain one
// for its own reasons -- but a declaration is a recipe saying so.
func declaresParams(src string) bool {
for _, line := range strings.Split(src, "\n") {
if paramDeclHead.MatchString(line) {
return true
}
}
return false
}

// onScriptPath reports whether file lives in one of the script search
// directories, which is what makes it findable as a recipe by name.
func onScriptPath(file string) bool {
abs, err := filepath.Abs(file)
if err != nil {
return false
}
dir := filepath.Dir(abs)
for _, d := range scriptSearchDirs() {
if ad, err := filepath.Abs(d); err == nil && ad == dir {
return true
}
}
return false
}

// refuseRecipeHoles stops `mcpx run <recipe>` before the runtime does.
//
// A recipe's @param holes are filled only by `recipes run`, which
// substitutes the values before anything executes. `run` executes the
// file as written, so a hole reaches the JavaScript parser untouched and
// the run dies with "SyntaxError: Expression expected" -- a message that
// names neither the hole nor the command that fills it (#276). Say which
// command fills them instead. A script that cannot be resolved or read
// is left alone: the run's own error paths report those.
func refuseRecipeHoles(arg string) error {
file, err := resolveScript(arg)
if err != nil {
return nil
}
b, err := os.ReadFile(file)
if err != nil {
return nil
}
src := string(b)
if !declaresParams(src) {
return nil
}
name := strings.TrimSuffix(filepath.Base(file),
filepath.Ext(file))
rec := recipes.Parse(name, file, src)
if len(rec.Placeholders) == 0 {
return nil
}
var assign []string
for _, p := range rec.Placeholders {
if p.Required {
assign = append(assign, p.Name+"=<value>")
} else {
assign = append(assign, "["+p.Name+"=<value>]")
}
}
head := fmt.Sprintf("%s is a recipe, not a plain script: it declares @param holes (%s) "+
"that `mcpx run` does not fill, so a hole would reach the runtime as-is and fail "+
"with a syntax error.", name, placeholderNames(rec))
if onScriptPath(file) {
return fmt.Errorf("%s\nRun it with:\n mcpx recipes run %s %s",
head, name, strings.Join(assign, " "))
}
return fmt.Errorf("%s\nSave it as a recipe, then run it with values:\n"+
" mcpx recipes save %s %s\n mcpx recipes run %s %s",
head, name, file, name, strings.Join(assign, " "))
}

// ScriptEntry is one discoverable script.
type ScriptEntry struct {
Name string `json:"name"`
Expand Down
20 changes: 20 additions & 0 deletions pkgs/mcpx/internal/e2e/consumer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,26 @@ func TestARecipeThatIsMissingAValueSaysSoRatherThanRunning(t *testing.T) {
}
}

func TestRunOnARecipePointsToRecipesRun(t *testing.T) {
// #276: `mcpx run say hi` handed the recipe's @param holes to the
// runtime as written and died with "SyntaxError: Expression
// expected". run must refuse and name the filling command.
e := newEnv(t, oneServer)
writeRecipe(t, e, "say", sayRecipe)
e.run("ls")
out, err := e.try("run", "say", "hi")
if err == nil {
t.Fatalf("run on an unfilled recipe must not succeed:\n%s", out)
}
if strings.Contains(out, "SyntaxError") {
t.Fatalf("the raw syntax error is the bug being fixed:\n%s", out)
}
if !strings.Contains(out, "mcpx recipes run say") ||
!strings.Contains(out, "message=<value>") {
t.Fatalf("run should point at recipes run with the holes named:\n%s", out)
}
}

func TestRecipesAreMatchedDeterministically(t *testing.T) {
e := newEnv(t, oneServer)
writeRecipe(t, e, "say", sayRecipe)
Expand Down
Loading