diff --git a/.opencode/plugin/core/ops.gen.ts b/.opencode/plugin/core/ops.gen.ts index 00c3b82dce..96ef50e1e2 100644 --- a/.opencode/plugin/core/ops.gen.ts +++ b/.opencode/plugin/core/ops.gen.ts @@ -20,7 +20,7 @@ type OpSpec = { response: "json" | "response" } -export const OPERATION_FINGERPRINT = "8560a42def5f8ce8a9e4c2d50d8aef3f0380caffd0b81b7f07bfac75f9a0aced" +export const OPERATION_FINGERPRINT = "4cb2e300265729ccb26e7f9e7d3775cd10618dfb27223f89a3a3da3310d7b314" /** Every /v1 operation, by name. */ export const OPS: Record = { @@ -545,6 +545,14 @@ export const OPS: Record = { }, response: "json", }, + recipe_remove: { + method: "DELETE", + path: "/v1/recipes/{name}", + params: { + name: { in: "path", required: true }, + }, + response: "json", + }, recipe_run: { method: "POST", path: "/v1/recipes/{name}/run", @@ -1368,6 +1376,15 @@ export class DaemonOps { return this.invoke("recipe_get", args, opts) as Promise } + /** + * Remove a saved recipe. `DELETE /v1/recipes/{name}`. + * Privileged: it changes the daemon rather than reading it. + * Destructive: it cannot be undone, and other callers are affected. + */ + recipeRemove(args: { name: string }, opts: CallOptions = {}): Promise { + return this.invoke("recipe_remove", args, opts) as Promise + } + /** * Run a recipe with its placeholders filled in. `POST /v1/recipes/{name}/run`. */ diff --git a/pkgs/mcpx/docs/parity.md b/pkgs/mcpx/docs/parity.md index 300dc47d3c..ac24b2988a 100644 --- a/pkgs/mcpx/docs/parity.md +++ b/pkgs/mcpx/docs/parity.md @@ -32,7 +32,7 @@ and costs an agent the ability to restart a server that has wedged. What they carry instead is a description that says so and MCP annotations (`readOnlyHint`, `destructiveHint`) for a client that wants to scope on them. -## /v1 operations (93) +## /v1 operations (94) | Operation | Route | CLI | MCP tool | Plugin | Notes | | --- | --- | --- | --- | --- | --- | @@ -90,6 +90,7 @@ carry instead is a description that says so and MCP annotations | `prompts` | `GET /v1/prompts` | `mcpx prompts` | `mcpx_prompts` | `ops.prompts()` | | | `protocol` | `GET /v1/protocol` | `mcpx protocol` *generated* | `mcpx_protocol` | `ops.protocol()` | | | `recipes_list` | `GET /v1/recipes` | `mcpx recipes list` | `mcpx_recipes_list` | `ops.recipesList()` | | +| `recipe_remove` | `DELETE /v1/recipes/{name}` | `mcpx recipes remove` | `mcpx_recipe_remove` | `ops.recipeRemove()` | Privileged. Destructive. | | `recipe_get` | `GET /v1/recipes/{name}` | `mcpx recipes show` | `mcpx_recipe_get` | `ops.recipeGet()` | | | `recipe_save` | `POST /v1/recipes/{name}` | `mcpx recipes save` | `mcpx_recipe_save` | `ops.recipeSave()` | | | `recipe_run` | `POST /v1/recipes/{name}/run` | `mcpx recipes run` | `mcpx_recipe_run` | `ops.recipeRun()` | | @@ -180,7 +181,7 @@ that reaches none says why: those are decisions, not gaps. | `prompts` | `prompt_get`, `prompts` | | | `protocol` | `protocol` | Generated from the operation table. | | `proxy` | `chat_completions` | | -| `recipes` | `recipes_list`, `recipe_get`, `recipe_save`, `recipe_run` | | +| `recipes` | `recipes_list`, `recipe_remove`, `recipe_get`, `recipe_save`, `recipe_run` | | | `refresh` | `refresh` | | | `registry` | `registry_search` | | | `reload` | `reload` | | diff --git a/pkgs/mcpx/internal/api/ops_consumer.go b/pkgs/mcpx/internal/api/ops_consumer.go index 4d0b5b0a9c..931da36678 100644 --- a/pkgs/mcpx/internal/api/ops_consumer.go +++ b/pkgs/mcpx/internal/api/ops_consumer.go @@ -85,6 +85,20 @@ func consumerOps() []Op { Desc: "replace an existing recipe of this name"}, }, }, + { + Name: "recipe_remove", Method: "DELETE", Path: "/v1/recipes/{name}", + Permission: PermissionAdmin, + Idempotent: true, + Command: "recipes remove", + Summary: "Remove a saved recipe", + Description: "Deletes the visible recipe file from the directory that " + + "defines it. If a same-name recipe is shadowed in a farther directory, " + + "that recipe becomes visible after removal.", + Admin: true, Mutating: true, Destructive: true, + Params: []Param{ + {Name: "name", In: InPath, Type: "string", Required: true, Desc: "the recipe to remove"}, + }, + }, { Name: "recipe_run", Method: "POST", Path: "/v1/recipes/{name}/run", Permission: PermissionRun, diff --git a/pkgs/mcpx/internal/cli/consumer.go b/pkgs/mcpx/internal/cli/consumer.go index 825d8eeff2..1c25a51d0c 100644 --- a/pkgs/mcpx/internal/cli/consumer.go +++ b/pkgs/mcpx/internal/cli/consumer.go @@ -91,6 +91,10 @@ func (c *Client) SaveRecipe(ctx context.Context, name, source string, overwrite map[string]any{"source": source, "overwrite": overwrite}) } +func (c *Client) RemoveRecipe(ctx context.Context, name string) (json.RawMessage, error) { + return c.do(ctx, "DELETE", "/v1/recipes/"+url.PathEscape(name), nil) +} + // Resolution is the answer shape recipe_run and intent share. type Resolution struct { Autonomy string `json:"autonomy"` @@ -371,6 +375,20 @@ func (a *App) CmdRecipes(ctx context.Context, args []string) error { fmt.Printf("Saved %s\nRun it with: mcpx recipes run %s\n", doc.Path, fs.Arg(0)) return nil + case "remove": + if fs.NArg() != 1 { + return errors.New("usage: mcpx recipes remove ") + } + raw, rerr := c.RemoveRecipe(ctx, fs.Arg(0)) + if rerr != nil { + return rerr + } + if a.JSON { + return a.out(json.RawMessage(raw)) + } + fmt.Printf("Removed recipe %s\n", fs.Arg(0)) + return nil + case "run": if fs.NArg() == 0 { return errors.New("usage: mcpx recipes run [key=value...]") @@ -389,7 +407,7 @@ func (a *App) CmdRecipes(ctx context.Context, args []string) error { } return a.showResolution(res) } - return fmt.Errorf("unknown subcommand %q; try list, show, match, save or run", sub) + return fmt.Errorf("unknown subcommand %q; try list, show, match, save, remove or run", sub) } func placeholderNames(r recipes.Recipe) string { diff --git a/pkgs/mcpx/internal/cli/consumer_recipe_test.go b/pkgs/mcpx/internal/cli/consumer_recipe_test.go new file mode 100644 index 0000000000..73c12576e4 --- /dev/null +++ b/pkgs/mcpx/internal/cli/consumer_recipe_test.go @@ -0,0 +1,31 @@ +package cli + +import ( + "context" + "net/http" + "net/http/httptest" + "testing" + + "github.com/developing-today/code/pkgs/mcpx/internal/daemon" +) + +func TestRecipesRemoveCommandCallsDeleteEndpoint(t *testing.T) { + requests := make(chan [2]string, 1) + ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests <- [2]string{r.Method, r.URL.Path} + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"name":"demo"}`)) + })) + defer ts.Close() + + app := &App{ + client: NewClientAt(daemon.Paths{}, "", ts.URL), + connected: true, + } + if err := app.CmdRecipes(context.Background(), []string{"remove", "demo"}); err != nil { + t.Fatalf("recipes remove: %v", err) + } + if got, want := <-requests, [2]string{http.MethodDelete, "/v1/recipes/demo"}; got != want { + t.Fatalf("request = %v, want %v", got, want) + } +} diff --git a/pkgs/mcpx/internal/daemon/recipe_mutation_test.go b/pkgs/mcpx/internal/daemon/recipe_mutation_test.go new file mode 100644 index 0000000000..33a35a7c55 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/recipe_mutation_test.go @@ -0,0 +1,163 @@ +package daemon + +import ( + "errors" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +func setupRecipeMutation(t *testing.T) (*Server, string, string) { + t.Helper() + s, _ := setupPersist(t, nil, false) + first := filepath.Join(t.TempDir(), "project", ".config", "mcpx", "scripts") + second := filepath.Join(t.TempDir(), "user", "scripts") + if err := os.MkdirAll(first, 0o755); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(second, 0o755); err != nil { + t.Fatal(err) + } + s.consumer.dirs = []string{first, second} + return s, first, second +} + +func saveRecipeRequest(t *testing.T, s *Server, name, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/v1/recipes/"+name, strings.NewReader(body)) + req.SetPathValue("name", name) + rec := httptest.NewRecorder() + s.handleRecipeSave(rec, req) + return rec +} + +func removeRecipeRequest(t *testing.T, s *Server, name string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodDelete, "/v1/recipes/"+name, nil) + req.SetPathValue("name", name) + rec := httptest.NewRecorder() + s.handleRecipeRemove(rec, req) + return rec +} + +func TestRecipeSaveRefusesCrossDirectoryDuplicateAndOverwriteEditsVisibleFile(t *testing.T) { + s, first, second := setupRecipeMutation(t) + near := filepath.Join(first, "demo.ts") + far := filepath.Join(second, "demo.ts") + if err := os.WriteFile(near, []byte("const near = true;\n"), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(far, []byte("const far = true;\n"), 0o644); err != nil { + t.Fatal(err) + } + if rec := saveRecipeRequest(t, s, "demo", `{"source":"const changed = true;"}`); rec.Code != http.StatusConflict { + t.Fatalf("duplicate status %d, want 409: %s", rec.Code, rec.Body) + } + if rec := saveRecipeRequest(t, s, "demo", `{"source":"const changed = true;","overwrite":true}`); rec.Code != http.StatusOK { + t.Fatalf("overwrite status %d, want 200: %s", rec.Code, rec.Body) + } + gotNear, _ := os.ReadFile(near) + gotFar, _ := os.ReadFile(far) + if !strings.Contains(string(gotNear), "changed") || strings.Contains(string(gotFar), "changed") { + t.Fatalf("overwrite did not edit visible definition: near=%q far=%q", gotNear, gotFar) + } +} + +func TestRecipeRemoveDeletesVisibleDefinitionAndNotFoundIs404(t *testing.T) { + s, first, second := setupRecipeMutation(t) + near := filepath.Join(first, "demo.ts") + far := filepath.Join(second, "demo.ts") + for path, source := range map[string]string{near: "const near = true;", far: "const far = true;"} { + if err := os.WriteFile(path, []byte(source), 0o644); err != nil { + t.Fatal(err) + } + } + if rec := removeRecipeRequest(t, s, "demo"); rec.Code != http.StatusOK { + t.Fatalf("remove status %d, want 200: %s", rec.Code, rec.Body) + } + if _, err := os.Stat(near); !os.IsNotExist(err) { + t.Fatalf("visible definition still exists: %v", err) + } + if _, err := os.Stat(far); err != nil { + t.Fatalf("shadowed definition was removed: %v", err) + } + if _, ok := s.findRecipe("demo"); !ok { + t.Fatal("farther definition did not become visible after removal") + } + if rec := removeRecipeRequest(t, s, "missing"); rec.Code != http.StatusNotFound { + t.Fatalf("missing remove status %d, want 404: %s", rec.Code, rec.Body) + } +} + +func TestRecipeSaveRejectsSymlinkOverwriteTarget(t *testing.T) { + s, first, _ := setupRecipeMutation(t) + target := filepath.Join(t.TempDir(), "outside.ts") + if err := os.WriteFile(target, []byte("const outside = true;\n"), 0o644); err != nil { + t.Fatal(err) + } + link := filepath.Join(first, "demo.ts") + if err := os.Symlink(target, link); err != nil { + t.Fatal(err) + } + if rec := saveRecipeRequest(t, s, "demo", `{"source":"const changed = true;","overwrite":true}`); rec.Code != http.StatusConflict { + t.Fatalf("symlink overwrite status %d, want 409: %s", rec.Code, rec.Body) + } + got, err := os.ReadFile(target) + if err != nil { + t.Fatal(err) + } + if strings.Contains(string(got), "changed") { + t.Fatalf("overwrite followed symlink and changed target: %q", got) + } + if _, err := os.Lstat(link); err != nil { + t.Fatalf("symlink was removed: %v", err) + } +} + +func TestRecipeSaveFindsUnreadableFartherDuplicate(t *testing.T) { + s, first, second := setupRecipeMutation(t) + far := filepath.Join(second, "demo.ts") + // A dangling symlink is a same-name filesystem entry that recipes.Load + // cannot read or parse; save must still see it and refuse to shadow it. + if err := os.Symlink(filepath.Join(second, "missing-target.ts"), far); err != nil { + t.Fatal(err) + } + if rec := saveRecipeRequest(t, s, "demo", `{"source":"const new = true;"}`); rec.Code != http.StatusConflict { + t.Fatalf("duplicate status %d, want 409: %s", rec.Code, rec.Body) + } + if _, err := os.Stat(filepath.Join(first, "demo.ts")); !os.IsNotExist(err) { + t.Fatalf("save shadowed farther entry: %v", err) + } +} + +func TestCreateRecipeFileNoReplacePreservesExistingTarget(t *testing.T) { + target := filepath.Join(t.TempDir(), "demo.ts") + original := []byte("const original = true;\n") + if err := os.WriteFile(target, original, 0o644); err != nil { + t.Fatal(err) + } + + err := createRecipeFileNoReplace(target, []byte("const replacement = true;\n")) + if !errors.Is(err, os.ErrExist) { + t.Fatalf("createRecipeFileNoReplace error = %v, want os.ErrExist", err) + } + got, err := os.ReadFile(target) + if err != nil { + t.Fatal(err) + } + if string(got) != string(original) { + t.Fatalf("existing target changed: got %q, want %q", got, original) + } +} + +func TestRecipeRemoveRejectsUnsafeNames(t *testing.T) { + s, _, _ := setupRecipeMutation(t) + for _, name := range []string{"", "../secret", ".hidden", `a\\b`} { + if rec := removeRecipeRequest(t, s, name); rec.Code != http.StatusBadRequest { + t.Errorf("name %q: status %d, want 400", name, rec.Code) + } + } +} diff --git a/pkgs/mcpx/internal/daemon/routes_consumer.go b/pkgs/mcpx/internal/daemon/routes_consumer.go index b6c953f762..11a2152ebf 100644 --- a/pkgs/mcpx/internal/daemon/routes_consumer.go +++ b/pkgs/mcpx/internal/daemon/routes_consumer.go @@ -30,6 +30,7 @@ func (s *Server) routesConsumer(mux *http.ServeMux) { s.route(mux, "GET /v1/recipes", s.handleRecipesList) s.route(mux, "GET /v1/recipes/{name}", s.handleRecipeGet) s.route(mux, "POST /v1/recipes/{name}", s.handleRecipeSave) + s.route(mux, "DELETE /v1/recipes/{name}", s.handleRecipeRemove) s.route(mux, "POST /v1/recipes/{name}/run", s.handleRecipeRun) s.route(mux, "POST /v1/intent", s.handleIntent) } @@ -211,13 +212,49 @@ func (s *Server) handleRecipeSave(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusBadRequest, errors.New("source is required")) return } + s.reloadMu.Lock() + defer s.reloadMu.Unlock() + // A same-name recipe in any search directory shadows the write target. + // Refuse that ambiguity unless overwrite explicitly targets the visible + // defining file, matching recipe lookup's nearest-directory precedence. + var existing string + var existingIsSymlink bool + for _, searchDir := range s.consumer.dirs { + candidate := filepath.Join(searchDir, name+recipes.Ext) + info, statErr := os.Lstat(candidate) + if errors.Is(statErr, os.ErrNotExist) { + continue + } + if statErr != nil { + writeErr(w, http.StatusInternalServerError, statErr) + return + } + if info.IsDir() { + continue + } + existing = candidate + existingIsSymlink = info.Mode()&os.ModeSymlink != 0 + break + } dir, err := recipes.SaveDir(s.consumer.dirs) if err != nil { writeErr(w, http.StatusInternalServerError, err) return } path := filepath.Join(dir, name+recipes.Ext) - if _, err := os.Stat(path); err == nil && !req.Overwrite { + if existing != "" { + if !req.Overwrite { + writeErr(w, http.StatusConflict, + fmt.Errorf("recipe %q already exists at %s; pass overwrite to replace it", name, existing)) + return + } + if existingIsSymlink { + writeErr(w, http.StatusConflict, + fmt.Errorf("recipe %q at %s is a symlink and cannot be overwritten", name, existing)) + return + } + path = existing + } else if _, err := os.Stat(path); err == nil && !req.Overwrite { writeErr(w, http.StatusConflict, fmt.Errorf("%s already exists; pass overwrite to replace it", path)) return @@ -226,7 +263,17 @@ func (s *Server) handleRecipeSave(w http.ResponseWriter, r *http.Request) { if !strings.HasSuffix(body, "\n") { body += "\n" } - if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + if req.Overwrite { + err = replaceRecipeFile(path, []byte(body)) + } else { + err = createRecipeFileNoReplace(path, []byte(body)) + } + if err != nil { + if errors.Is(err, os.ErrExist) { + writeErr(w, http.StatusConflict, + fmt.Errorf("%s already exists; pass overwrite to replace it", path)) + return + } writeErr(w, http.StatusInternalServerError, err) return } @@ -236,6 +283,76 @@ func (s *Server) handleRecipeSave(w http.ResponseWriter, r *http.Request) { }) } +// replaceRecipeFile writes beside the destination and renames into place. +// Unlike os.WriteFile, this never opens or follows a destination symlink if +// the path changes after the caller's Lstat check. +func replaceRecipeFile(path string, body []byte) error { + tmp, err := os.CreateTemp(filepath.Dir(path), ".recipe-*.tmp") + if err != nil { + return err + } + tmpName := tmp.Name() + defer os.Remove(tmpName) + if err := tmp.Chmod(0o644); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(body); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Rename(tmpName, path) +} + +// createRecipeFileNoReplace writes beside the destination and links into place. +// Unlike os.Rename, os.Link fails if another writer created the destination +// after the caller's existence check, rather than replacing that file. +func createRecipeFileNoReplace(path string, body []byte) error { + tmp, err := os.CreateTemp(filepath.Dir(path), ".recipe-*.tmp") + if err != nil { + return err + } + tmpName := tmp.Name() + defer os.Remove(tmpName) + if err := tmp.Chmod(0o644); err != nil { + tmp.Close() + return err + } + if _, err := tmp.Write(body); err != nil { + tmp.Close() + return err + } + if err := tmp.Close(); err != nil { + return err + } + return os.Link(tmpName, path) +} + +func (s *Server) handleRecipeRemove(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + if !recipeNameOK(name) { + writeErr(w, http.StatusBadRequest, + fmt.Errorf("%q is not a usable recipe name", name)) + return + } + s.reloadMu.Lock() + defer s.reloadMu.Unlock() + recipe, ok := s.findRecipe(name) + if !ok { + writeErr(w, http.StatusNotFound, + fmt.Errorf("no recipe named %q; looked in %s", name, strings.Join(s.consumer.dirs, ", "))) + return + } + if err := os.Remove(recipe.Path); err != nil { + writeErr(w, http.StatusInternalServerError, err) + return + } + writeJSON(w, http.StatusOK, map[string]string{"name": name, "path": recipe.Path}) +} + // resolution is the answer shape shared by recipe_run and intent. // // One shape for both because they are the same operation seen from two diff --git a/pkgs/mcpx/plugin/core/ops.gen.ts b/pkgs/mcpx/plugin/core/ops.gen.ts index 00c3b82dce..96ef50e1e2 100644 --- a/pkgs/mcpx/plugin/core/ops.gen.ts +++ b/pkgs/mcpx/plugin/core/ops.gen.ts @@ -20,7 +20,7 @@ type OpSpec = { response: "json" | "response" } -export const OPERATION_FINGERPRINT = "8560a42def5f8ce8a9e4c2d50d8aef3f0380caffd0b81b7f07bfac75f9a0aced" +export const OPERATION_FINGERPRINT = "4cb2e300265729ccb26e7f9e7d3775cd10618dfb27223f89a3a3da3310d7b314" /** Every /v1 operation, by name. */ export const OPS: Record = { @@ -545,6 +545,14 @@ export const OPS: Record = { }, response: "json", }, + recipe_remove: { + method: "DELETE", + path: "/v1/recipes/{name}", + params: { + name: { in: "path", required: true }, + }, + response: "json", + }, recipe_run: { method: "POST", path: "/v1/recipes/{name}/run", @@ -1368,6 +1376,15 @@ export class DaemonOps { return this.invoke("recipe_get", args, opts) as Promise } + /** + * Remove a saved recipe. `DELETE /v1/recipes/{name}`. + * Privileged: it changes the daemon rather than reading it. + * Destructive: it cannot be undone, and other callers are affected. + */ + recipeRemove(args: { name: string }, opts: CallOptions = {}): Promise { + return this.invoke("recipe_remove", args, opts) as Promise + } + /** * Run a recipe with its placeholders filled in. `POST /v1/recipes/{name}/run`. */