diff --git a/pkgs/mcpx/docs/parity.md b/pkgs/mcpx/docs/parity.md index 96badbd3e5..2e13b86164 100644 --- a/pkgs/mcpx/docs/parity.md +++ b/pkgs/mcpx/docs/parity.md @@ -32,10 +32,12 @@ 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 (81) +## /v1 operations (83) | Operation | Route | CLI | MCP tool | Plugin | Notes | | --- | --- | --- | --- | --- | --- | +| `adapters_add` | `POST /v1/adapters` | `mcpx adapter add` | `mcpx_adapters_add` | `ops.adaptersAdd()` | Privileged. | +| `adapters_remove` | `DELETE /v1/adapters/{name}` | `mcpx adapter remove` | `mcpx_adapters_remove` | `ops.adaptersRemove()` | Privileged. Destructive. | | `artifacts_list` | `GET /v1/artifacts` | `mcpx artifact list` *generated* | `mcpx_artifacts_list` | `ops.artifactsList()` | | | `artifact_put` | `POST /v1/artifacts` | `mcpx artifact put` *generated* | `mcpx_artifact_put` | `ops.artifactPut()` | Privileged. | | `artifact_delete` | `DELETE /v1/artifacts/{id}` | `mcpx artifact delete` *generated* | `mcpx_artifact_delete` | `ops.artifactDelete()` | Privileged. Destructive. | @@ -125,7 +127,7 @@ that reaches none says why: those are decisions, not gaps. | Command | Operations | Notes | | --- | --- | --- | -| `adapter` | – | Adapter declarations are files the CLI reads; the daemon serves each adapter as a server of its own, so its tools reach every tool operation (call, types, search, catalog) like any upstream's. | +| `adapter` | `adapters_add`, `adapters_remove` | | | `api` | – | OpenAPI declarations are files the CLI reads; the tools they produce are served over MCP, and are not yet a tool source the daemon owns (#83). | | `artifact` / `artifacts` | `artifacts_list`, `artifact_put`, `artifact_delete`, `artifact_get` | Generated from the operation table. | | `ask` | `ask_begin`, `ask_poll`, `ask_abandon`, `ask_answers` | Generated from the operation table. | diff --git a/pkgs/mcpx/internal/api/ops_settings.go b/pkgs/mcpx/internal/api/ops_settings.go index 0ab5d64b21..e1d5617105 100644 --- a/pkgs/mcpx/internal/api/ops_settings.go +++ b/pkgs/mcpx/internal/api/ops_settings.go @@ -143,5 +143,52 @@ func settingsOps() []Op { Desc: "which file to edit; by default, the one that defines it"}, }, }, + { + Name: "adapters_add", Method: "POST", Path: "/v1/adapters", + Command: "adapter add", + Summary: "Add an adapter declaration, live", + Description: "Writes the declaration to the first file paths.adapters " + + "names and reloads, so the adapter is callable immediately and " + + "is still there after a restart. The body is the declaration " + + "itself: name, command, and its tools. A name another configured " + + "file already declares is refused rather than duplicated across " + + "files, and a replacement edits the file that defines it. " + + "Refused, with the remedy, when paths.adapters names no file, " + + "because a declaration written somewhere nothing reads would " + + "report success and change nothing.", + Admin: true, Mutating: true, + Params: []Param{ + {Name: "name", In: InBody, Type: "string", Required: true, + Desc: "the adapter's name, which is also its namespace"}, + {Name: "command", In: InBody, Type: "string", Required: true, + Desc: "the executable the declaration wraps"}, + {Name: "runtime", In: InBody, Type: "string", + Desc: "the interpreter a script command needs: bash, js, ts or py"}, + {Name: "args", In: InBody, Type: "array", Desc: "arguments prepended to every invocation", + Schema: `{"type":"array","items":{"type":"string"}}`}, + {Name: "env", In: InBody, Type: "object", Desc: "environment added to every invocation", + Schema: `{"type":"object","additionalProperties":{"type":"string"}}`}, + {Name: "description", In: InBody, Type: "string", + Desc: "one line shown beside the namespace"}, + {Name: "tools", In: InBody, Type: "array", Desc: "the subcommands worth exposing", + Schema: `{"type":"array","items":{"type":"object","additionalProperties":true}}`}, + {Name: "replace", In: InBody, Type: "boolean", + Desc: "overwrite a declaration of the same name instead of refusing"}, + }, + }, + { + Name: "adapters_remove", Method: "DELETE", Path: "/v1/adapters/{name}", + Idempotent: true, + Command: "adapter remove", + Summary: "Remove an adapter declaration, live", + Description: "Deletes the declaration from whichever configured " + + "adapters file defines it and reloads. Instances of that " + + "adapter stop; a caller mid-call against it fails.", + Admin: true, Mutating: true, Destructive: true, + Params: []Param{ + {Name: "name", In: InPath, Type: "string", Required: true, + Desc: "the adapter to remove, by its declared name"}, + }, + }, } } diff --git a/pkgs/mcpx/internal/cli/adapter.go b/pkgs/mcpx/internal/cli/adapter.go index 17cf8dc707..2449bfd2ea 100644 --- a/pkgs/mcpx/internal/cli/adapter.go +++ b/pkgs/mcpx/internal/cli/adapter.go @@ -2,8 +2,11 @@ package cli import ( "context" + "crypto/sha256" + "encoding/hex" "encoding/json" "fmt" + "net/http" "os" "path/filepath" "sort" @@ -74,6 +77,15 @@ func (a *App) CmdAdapter(ctx context.Context, args []string) error { if len(args) > 0 && !strings.HasPrefix(args[0], "-") { sub, args = args[0], args[1:] } + // add and remove go through the daemon, like servers add/remove: the + // write has to land where the running daemon reads, and the local + // declaration files are not the authority for a live change. + if sub == "add" { + return a.adapterAdd(ctx, args) + } + if sub == "remove" { + return a.adapterRemove(ctx, args) + } fs := newFlagSet("adapter") if err := parseFlags(a, fs, args); err != nil { return err @@ -200,7 +212,7 @@ func (a *App) CmdAdapter(ctx context.Context, args []string) error { } return fmt.Errorf("no adapter named %q", fs.Arg(0)) } - return fmt.Errorf("no adapter subcommand %q; list, check, call, tools or serve", sub) + return fmt.Errorf("no adapter subcommand %q; list, check, call, tools, serve, add or remove", sub) } // augmentAdapters adds every declared adapter to cfg as a server of its @@ -242,9 +254,139 @@ func (a *App) augmentAdapters(cfg *config.Config) error { Name: s.Name, Command: self, Args: append([]string{"adapter", "serve", s.Name}, files...), + // The declaration's fingerprint rides in the environment + // because PoolID hashes the environment: replacing the + // declaration (command, env, tools) and reloading then + // replaces this adapter's pool instead of silently keeping + // the child that captured the old declaration at startup + // (Codex review, PR #2565; the same shape augmentAPIs uses + // for APIs since PR #2514). + Env: map[string]string{"MCPX_ADAPTER_DECLARATION_SHA256": adapterDeclarationFingerprint(s)}, // Instructions arrive from initialize, as a real server's do. Mcpx: &config.Extras{Description: s.Description}, } } return nil } + +// adapterDeclarationFingerprint identifies one adapter declaration's +// content, for the process identity augmentAdapters builds. +func adapterDeclarationFingerprint(s adapter.Spec) string { + h := sha256.New() + if raw, err := json.Marshal(s); err == nil { + h.Write(raw) + } + return hex.EncodeToString(h.Sum(nil))[:32] +} + +// adapterAddValuedFlags are adapter add's flags that take a value, for +// hoistFlags: a flag and its value move together, so --tool status stays +// a pair wherever it started (Codex review, PR #2565). +var adapterAddValuedFlags = map[string]bool{"runtime": true, "description": true, "tool": true} + +// adapterToolEntries builds the declaration's tools from the subcommands +// named on the command line. +func adapterToolEntries(values []string) []map[string]any { + tools := []map[string]any{} + for _, t := range values { + // The subcommand is the tool's fixed argument, not just its name: + // ToolSpec.buildArgs starts from ToolSpec.Args, so a tool with no + // args would run the bare command — every tool the same command + // (Codex review, PR #2565). + tools = append(tools, map[string]any{"name": t, "args": []string{t}}) + } + return tools +} + +// adapterAdd declares a new adapter through the daemon, the way servers +// add does: the write lands in the declaration file the running daemon +// reads and the reload makes it callable at once. The tools named here +// are a starting declaration; the file is the editable source, and +// `mcpx adapter check` validates whatever it grows into. +func (a *App) adapterAdd(ctx context.Context, args []string) error { + fs := newFlagSet("adapter") + var after []string + for i, v := range args { + if v == "--" { + args, after = args[:i], args[i+1:] + break + } + } + args = hoistFlags(args, adapterAddValuedFlags) + runtime := fs.String("runtime", "", "the interpreter a script command needs: bash, js, ts or py") + desc := fs.String("description", "", "one line about what it wraps") + tool := newRepeated() + fs.Var(tool, "tool", "a subcommand worth exposing (repeatable)") + replace := fs.Bool("replace", false, "overwrite a declaration of the same name") + if err := parseFlags(a, fs, args); err != nil { + return err + } + if fs.NArg() == 0 { + return fmt.Errorf("usage: mcpx adapter add [--tool ]... -- [args...]") + } + name := fs.Arg(0) + rest := append(fs.Args()[1:], after...) + if len(rest) == 0 { + return fmt.Errorf("an adapter needs a command after --") + } + tools := adapterToolEntries(tool.values) + body := map[string]any{ + "name": name, "command": rest[0], "replace": *replace, "tools": tools, + } + if len(rest) > 1 { + body["args"] = rest[1:] + } + if *runtime != "" { + body["runtime"] = *runtime + } + if *desc != "" { + body["description"] = *desc + } + c, err := a.ensure(ctx) + if err != nil { + return err + } + raw, err := c.Do(ctx, http.MethodPost, "/v1/adapters", mustMarshal(body)) + if err != nil { + return err + } + var out map[string]any + if err := json.Unmarshal(raw, &out); err != nil { + return err + } + if a.JSON { + return a.out(out) + } + fmt.Printf("added adapter %s to %v; it is live now\n", name, out["written"]) + return nil +} + +// adapterRemove removes a declaration through the daemon, mirroring +// servers remove: the file that defines it is the one edited. +func (a *App) adapterRemove(ctx context.Context, args []string) error { + fs := newFlagSet("adapter") + if err := parseFlags(a, fs, args); err != nil { + return err + } + if fs.NArg() == 0 { + return fmt.Errorf("usage: mcpx adapter remove ") + } + name := fs.Arg(0) + c, err := a.ensure(ctx) + if err != nil { + return err + } + raw, err := c.Do(ctx, http.MethodDelete, "/v1/adapters/"+urlEscape(name), nil) + if err != nil { + return err + } + var out map[string]any + if err := json.Unmarshal(raw, &out); err != nil { + return err + } + if a.JSON { + return a.out(out) + } + fmt.Printf("removed adapter %s from %v; it is gone from the running daemon\n", name, out["written"]) + return nil +} diff --git a/pkgs/mcpx/internal/cli/adapter_add_test.go b/pkgs/mcpx/internal/cli/adapter_add_test.go new file mode 100644 index 0000000000..154242ac3c --- /dev/null +++ b/pkgs/mcpx/internal/cli/adapter_add_test.go @@ -0,0 +1,96 @@ +package cli + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/dezren39/mcpx/internal/config" + "github.com/dezren39/mcpx/internal/daemon" + "github.com/dezren39/mcpx/internal/testsupport" +) + +// The advertised form puts flags after the name: mcpx adapter add demo +// --tool status -- git. Hoisting must keep each --tool with its value, or +// the parser reads demo as the tool and status as the name (Codex review, +// PR #2565). +func TestHoistKeepsToolFlagsPairedWithTheirValues(t *testing.T) { + in := []string{"demo", "--tool", "status", "--tool", "log", "--runtime", "bash"} + got := hoistFlags(in, adapterAddValuedFlags) + want := []string{"--tool", "status", "--tool", "log", "--runtime", "bash", "demo"} + if strings.Join(got, " ") != strings.Join(want, " ") { + t.Fatalf("hoisted %v, want %v", got, want) + } +} + +// A generated tool's fixed arguments select its subcommand: without them +// the tool runs the bare command (Codex review, PR #2565). +func TestAdapterToolEntriesCarryTheSubcommandAsArgs(t *testing.T) { + tools := adapterToolEntries([]string{"status", "log"}) + if len(tools) != 2 { + t.Fatalf("entries %v", tools) + } + for i, name := range []string{"status", "log"} { + if tools[i]["name"] != name { + t.Fatalf("tool %d name %v, want %s", i, tools[i]["name"], name) + } + args, ok := tools[i]["args"].([]string) + if !ok || len(args) != 1 || args[0] != name { + t.Fatalf("tool %d args %v, want [%s]", i, tools[i]["args"], name) + } + } +} + +// adapterApp builds an App whose paths.adapters names file, in a scratch +// home so no real declaration can leak into the test. +func adapterApp(t *testing.T, adaptersFile string) *App { + t.Helper() + root := testsupport.TempDir(t) + t.Setenv("HOME", root) + t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "xdg")) + t.Setenv("MCPX_PATHS_ADAPTERS", adaptersFile) + cfg := filepath.Join(root, "mcpx.json") + if err := os.WriteFile(cfg, []byte(`{"mcpServers":{}}`), 0o600); err != nil { + t.Fatal(err) + } + return &App{ConfigPath: cfg, Paths: daemon.PathsAt(root, "")} +} + +// Replacing a declaration must change the generated server's identity, or +// the reload keeps the child that captured the old declaration at startup +// (Codex review, PR #2565). +func TestAugmentAdaptersFingerprintMovesWithTheDeclaration(t *testing.T) { + dir := t.TempDir() + file := filepath.Join(dir, "adapters.json") + write := func(tools string) { + t.Helper() + decl := `{"adapters":[{"name":"git","command":"git","tools":[` + tools + `]}]}` + if err := os.WriteFile(file, []byte(decl), 0o644); err != nil { + t.Fatal(err) + } + } + fingerprint := func() string { + t.Helper() + a := adapterApp(t, file) + cfg := &config.Config{MCPServers: map[string]*config.Server{}} + if err := a.augmentAdapters(cfg); err != nil { + t.Fatal(err) + } + s, ok := cfg.MCPServers["git"] + if !ok { + t.Fatalf("adapter not added as a server: %v", cfg.MCPServers) + } + fp := s.Env["MCPX_ADAPTER_DECLARATION_SHA256"] + if fp == "" { + t.Fatal("generated server carries no declaration fingerprint") + } + return fp + } + write(`{"name":"status"}`) + before := fingerprint() + write(`{"name":"status"},{"name":"log"}`) + if after := fingerprint(); after == before { + t.Fatalf("fingerprint did not move when the declaration changed: %s", before) + } +} diff --git a/pkgs/mcpx/internal/cli/manual.go b/pkgs/mcpx/internal/cli/manual.go index 52565b094c..b379473cc0 100644 --- a/pkgs/mcpx/internal/cli/manual.go +++ b/pkgs/mcpx/internal/cli/manual.go @@ -617,8 +617,7 @@ func handCommands() []Command { }, { Name: "adapter", Group: "configuration", - Local: "Adapter declarations are files the CLI reads; the daemon serves each adapter as a server of its own, so its tools reach every tool operation (call, types, search, catalog) like any upstream's.", - Usage: "[list|check|call|tools|serve] [. '' | [file...]]", + Usage: "[list|check|call|tools|serve|add|remove] [. '' | [file...]]", Summary: "command-line programs declared as MCP tools", Detail: "An adapter file, named by paths.adapters, declares a program and " + "the tools it offers. list shows them, check says whether each " + @@ -626,10 +625,14 @@ func handCommands() []Command { "tool definitions an MCP host would see. Every adapter is also a " + "namespace: the daemon runs it as `mcpx adapter serve `, " + "so it is in mcpx ls, types, search, catalog and the generated " + - "client, and a script calls it as .({...}).", + "client, and a script calls it as .({...}). add and " + + "remove go through the daemon (/v1/adapters): the declaration " + + "is written to a configured file and reloaded, so the change " + + "is live at once and survives a restart.", Examples: []string{ "mcpx adapter check", `mcpx adapter call jq.run '{"filter":"."}'`, + "mcpx adapter add demo --tool status -- git", }, }, { diff --git a/pkgs/mcpx/internal/cli/plugin.go b/pkgs/mcpx/internal/cli/plugin.go index 17d1a52876..67a8ed6e4c 100644 --- a/pkgs/mcpx/internal/cli/plugin.go +++ b/pkgs/mcpx/internal/cli/plugin.go @@ -126,9 +126,9 @@ func (a *App) augmentAPIs(cfg *config.Config) error { // declaration (baseUrl, headers, spec, filters) and // reloading then replaces this API's pool instead of // silently keeping the child that was started for the old - // declaration (Codex review, PR #2514). Adapters have the - // same shape of staleness via their files; that is #2118 - // follow-up material, not hidden here. + // declaration (Codex review, PR #2514). Adapters carry + // the same fingerprint for the same reason since #2118 + // (augmentAdapters, MCPX_ADAPTER_DECLARATION_SHA256). Env: map[string]string{"MCPX_API_DECLARATION_SHA256": apiDeclarationFingerprint(s)}, Mcpx: &config.Extras{Description: s.Description}, } diff --git a/pkgs/mcpx/internal/config/write.go b/pkgs/mcpx/internal/config/write.go index 8694a5e6a2..d1454b8529 100644 --- a/pkgs/mcpx/internal/config/write.go +++ b/pkgs/mcpx/internal/config/write.go @@ -2,6 +2,7 @@ package config import ( "encoding/json" + "errors" "fmt" "os" "path/filepath" @@ -204,3 +205,148 @@ func RemoveServer(path, name string) (bool, error) { }) return found, err } + +// ---- adapter declaration files ---- +// +// An adapter declaration file is not a configuration file: it is a list of +// declarations, held either as {"adapters": [...]} or as a bare array. Live +// add and remove edit that list in place, preserving whichever shape the +// file already uses, because a person who wrote one shape should not find +// the other when they next open the file. + +// adapterEntries reads a declaration file and returns its entries plus +// whether the file uses the bare-array shape. A missing file reads as an +// empty object-shaped document: the first live add creates it. +func adapterEntries(path string) (entries []any, bare bool, err error) { + entries, bare, _, err = adapterDocument(path) + return entries, bare, err +} + +// adapterDocument is adapterEntries plus the file's whole object, for the +// object shape. A declaration file may be a combined document: the loaders +// accept files that also carry configuration or API declarations +// (settings/file.go recognises those sections), so an edit that rewrote +// the file as only its adapters list would permanently delete the +// sibling sections (Codex review, PR #2565). Writers keep the document +// and replace only its adapters field. +func adapterDocument(path string) (entries []any, bare bool, doc map[string]any, err error) { + b, rerr := os.ReadFile(path) + if rerr != nil { + if os.IsNotExist(rerr) { + return nil, false, nil, nil + } + return nil, false, nil, rerr + } + trimmed := strings.TrimSpace(string(StripJSONC(b))) + if strings.HasPrefix(trimmed, "[") { + if err := json.Unmarshal([]byte(trimmed), &entries); err != nil { + return nil, false, nil, fmt.Errorf("%s is not a valid adapter file: %w", path, err) + } + return entries, true, nil, nil + } + if err := json.Unmarshal([]byte(trimmed), &doc); err != nil { + return nil, false, nil, fmt.Errorf("%s is not a valid adapter file: %w", path, err) + } + list, _ := doc["adapters"].([]any) + return list, false, doc, nil +} + +func writeAdapterEntries(path string, entries []any, bare bool, doc map[string]any) error { + var out []byte + var err error + if bare { + out, err = json.MarshalIndent(entries, "", " ") + } else { + if doc == nil { + doc = map[string]any{} + } + doc["adapters"] = entries + out, err = json.MarshalIndent(doc, "", " ") + } + if err != nil { + return err + } + if dir := filepath.Dir(path); dir != "" && dir != "." { + if err := os.MkdirAll(dir, DirMode); err != nil { + return err + } + } + return os.WriteFile(path, append(out, '\n'), FileMode) +} + +func adapterEntryName(e any) string { + obj, _ := e.(map[string]any) + if obj == nil { + return "" + } + name, _ := obj["name"].(string) + return name +} + +// AddAdapterEntry inserts one adapter declaration into the file at path. +// +// Refusing a name the file already declares rather than replacing it, for +// the same reason AddServer does: a silent overwrite of a declaration +// somebody wrote by hand is a loss noticed only when the tool stops +// working. +func AddAdapterEntry(path string, entry map[string]any, replace bool) error { + name := adapterEntryName(entry) + if name == "" { + return errors.New("an adapter declaration needs a name") + } + entries, bare, doc, err := adapterDocument(path) + if err != nil { + return err + } + for i, e := range entries { + if adapterEntryName(e) == name { + if !replace { + return fmt.Errorf("%s already declares adapter %q; remove it first or pick another name", + path, name) + } + entries[i] = entry + return writeAdapterEntries(path, entries, bare, doc) + } + } + return writeAdapterEntries(path, append(entries, entry), bare, doc) +} + +// RemoveAdapterEntry drops the declaration named name from the file at +// path, reporting whether it was there. +func RemoveAdapterEntry(path, name string) (bool, error) { + entries, bare, doc, err := adapterDocument(path) + if err != nil { + return false, err + } + for i, e := range entries { + if adapterEntryName(e) == name { + return true, writeAdapterEntries(path, append(entries[:i], entries[i+1:]...), bare, doc) + } + } + return false, nil +} + +// AdapterDefinedIn returns the first of paths whose declaration file +// declares an adapter named name. Removing an adapter has to edit the +// file that defines it; editing any other would report success and +// change nothing. +func AdapterDefinedIn(paths []string, name string) (string, bool, error) { + for _, p := range paths { + if p == "" { + continue + } + entries, _, err := adapterEntries(p) + if err != nil { + if os.IsNotExist(err) { + continue + } + return "", false, err + } + for _, e := range entries { + if adapterEntryName(e) == name { + return p, true, nil + } + } + } + return "", false, nil +} diff --git a/pkgs/mcpx/internal/config/write_adapters_test.go b/pkgs/mcpx/internal/config/write_adapters_test.go new file mode 100644 index 0000000000..3305a73ed1 --- /dev/null +++ b/pkgs/mcpx/internal/config/write_adapters_test.go @@ -0,0 +1,98 @@ +package config + +import ( + "os" + "path/filepath" + "strings" + "testing" +) + +func TestAddAdapterEntryCreatesObjectFile(t *testing.T) { + path := filepath.Join(t.TempDir(), "adapters.json") + entry := map[string]any{"name": "jq", "command": "jq", + "tools": []any{map[string]any{"name": "run"}}} + if err := AddAdapterEntry(path, entry, false); err != nil { + t.Fatal(err) + } + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !strings.Contains(string(b), `"adapters"`) || !strings.Contains(string(b), `"jq"`) { + t.Fatalf("written file does not hold the declaration:\n%s", b) + } + if err := AddAdapterEntry(path, entry, false); err == nil { + t.Fatal("a duplicate name was accepted without replace") + } + entry["command"] = "jaq" + if err := AddAdapterEntry(path, entry, true); err != nil { + t.Fatalf("replace refused: %v", err) + } + where, found, err := AdapterDefinedIn([]string{path}, "jq") + if err != nil || !found || where != path { + t.Fatalf("AdapterDefinedIn = %q, %v, %v", where, found, err) + } +} + +func TestAdapterEntriesKeepBareArrayShape(t *testing.T) { + path := filepath.Join(t.TempDir(), "adapters.json") + if err := os.WriteFile(path, []byte(`[{"name":"old","command":"old"}]`), 0o644); err != nil { + t.Fatal(err) + } + if err := AddAdapterEntry(path, + map[string]any{"name": "new", "command": "new"}, false); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(path) + if !strings.HasPrefix(strings.TrimSpace(string(b)), "[") { + t.Fatalf("bare-array file was rewritten as an object:\n%s", b) + } + removed, err := RemoveAdapterEntry(path, "old") + if err != nil || !removed { + t.Fatalf("RemoveAdapterEntry = %v, %v", removed, err) + } + removed, err = RemoveAdapterEntry(path, "old") + if err != nil || removed { + t.Fatalf("second remove = %v, %v; want false, nil", removed, err) + } + b, _ = os.ReadFile(path) + if strings.Contains(string(b), `"old"`) || !strings.Contains(string(b), `"new"`) { + t.Fatalf("file after remove is wrong:\n%s", b) + } +} + +// TestAdapterEditsPreserveSiblingSections: a declaration file may be a +// combined document carrying configuration sections beside its adapters. +// Adding or removing an adapter must update only the adapters field, never +// rewrite the whole document and delete the siblings (Codex review, +// PR #2565). +func TestAdapterEditsPreserveSiblingSections(t *testing.T) { + path := filepath.Join(t.TempDir(), "combined.json") + doc := `{"mcpServers":{"srv":{"command":"x"}},"paths":{"adapters":["a.json"]},` + + `"adapters":[{"name":"old","command":"old"}]}` + if err := os.WriteFile(path, []byte(doc), 0o644); err != nil { + t.Fatal(err) + } + if err := AddAdapterEntry(path, map[string]any{"name": "new", "command": "new"}, false); err != nil { + t.Fatal(err) + } + b, _ := os.ReadFile(path) + for _, want := range []string{`"mcpServers"`, `"srv"`, `"paths"`, `"old"`, `"new"`} { + if !strings.Contains(string(b), want) { + t.Fatalf("add lost %s:\n%s", want, b) + } + } + removed, err := RemoveAdapterEntry(path, "old") + if err != nil || !removed { + t.Fatalf("RemoveAdapterEntry = %v, %v", removed, err) + } + b, _ = os.ReadFile(path) + for _, want := range []string{`"mcpServers"`, `"srv"`, `"paths"`, `"new"`} { + if !strings.Contains(string(b), want) { + t.Fatalf("remove lost %s:\n%s", want, b) + } + } + if strings.Contains(string(b), `"old"`) { + t.Fatalf("remove left the entry behind:\n%s", b) + } +} diff --git a/pkgs/mcpx/internal/daemon/adapter_routes_test.go b/pkgs/mcpx/internal/daemon/adapter_routes_test.go new file mode 100644 index 0000000000..c27800ac91 --- /dev/null +++ b/pkgs/mcpx/internal/daemon/adapter_routes_test.go @@ -0,0 +1,164 @@ +package daemon + +import ( + "fmt" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "sync" + "testing" +) + +// setupAdapterRoutes builds a daemon whose paths.adapters names two +// declaration files; the second already declares demo. +func setupAdapterRoutes(t *testing.T) (*Server, string, string) { + t.Helper() + s, _ := setupPersist(t, nil, false) + dir := t.TempDir() + first := filepath.Join(dir, "adapters-a.json") + second := filepath.Join(dir, "adapters-b.json") + if err := os.WriteFile(first, []byte(`{"adapters":[]}`), 0o644); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(second, []byte( + `{"adapters":[{"name":"demo","command":"/bin/true","tools":[{"name":"run"}]}]}`), 0o644); err != nil { + t.Fatal(err) + } + joined := first + string(os.PathListSeparator) + second + if err := s.set.SetRuntime("paths.adapters", joined); err != nil { + t.Fatal(err) + } + return s, first, second +} + +func postAdapter(t *testing.T, s *Server, body string) *httptest.ResponseRecorder { + t.Helper() + req := httptest.NewRequest(http.MethodPost, "/v1/adapters", strings.NewReader(body)) + rec := httptest.NewRecorder() + s.handleAdaptersAdd(rec, req) + return rec +} + +func readFile(t *testing.T, path string) string { + t.Helper() + b, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(b) +} + +// A name the second file declares must not be written into the first: +// loadAdapterFiles refuses names two files declare, so the duplicate +// would persist and break every later reload and start (Codex review, +// PR #2565). +func TestAdapterAddRefusesANameDeclaredInAnotherFile(t *testing.T) { + s, first, second := setupAdapterRoutes(t) + rec := postAdapter(t, s, `{"name":"demo","command":"/bin/false","tools":[{"name":"run"}]}`) + if rec.Code != http.StatusConflict { + t.Fatalf("status %d, want 409: %s", rec.Code, rec.Body) + } + if got := readFile(t, first); strings.Contains(got, "demo") { + t.Fatalf("the duplicate was written to the first file: %s", got) + } + if got := readFile(t, second); !strings.Contains(got, "/bin/true") { + t.Fatalf("the existing declaration was touched: %s", got) + } +} + +// A replacement edits the file that defines the adapter, not the first +// file on the list. +func TestAdapterReplaceEditsTheDefiningFile(t *testing.T) { + s, first, second := setupAdapterRoutes(t) + rec := postAdapter(t, s, `{"name":"demo","command":"/bin/false","replace":true,"tools":[{"name":"run"}]}`) + if rec.Code != http.StatusOK { + t.Fatalf("status %d, want 200: %s", rec.Code, rec.Body) + } + if got := readFile(t, second); !strings.Contains(got, "/bin/false") { + t.Fatalf("the defining file was not updated: %s", got) + } + if got := readFile(t, first); strings.Contains(got, "demo") { + t.Fatalf("a second definition was written to the first file: %s", got) + } +} + +// Concurrent live adds must not lose each other's file edits: the +// handler holds the reload lock over lookup, write and reload (Codex +// review, PR #2565). +func TestConcurrentAdapterAddsAllLand(t *testing.T) { + s, first, _ := setupAdapterRoutes(t) + const n = 8 + var wg sync.WaitGroup + codes := make([]int, n) + for i := range n { + wg.Add(1) + go func() { + defer wg.Done() + body := fmt.Sprintf(`{"name":"a%d","command":"/bin/true","tools":[{"name":"run"}]}`, i) + req := httptest.NewRequest(http.MethodPost, "/v1/adapters", strings.NewReader(body)) + rec := httptest.NewRecorder() + s.handleAdaptersAdd(rec, req) + codes[i] = rec.Code + }() + } + wg.Wait() + for i, code := range codes { + if code != http.StatusOK { + t.Fatalf("add a%d: status %d, want 200", i, code) + } + } + got := readFile(t, first) + for i := range n { + if !strings.Contains(got, fmt.Sprintf(`"a%d"`, i)) { + t.Fatalf("add a%d is missing from the file: %s", i, got) + } + } +} + +// A name a configured server already owns must be refused BEFORE anything +// is persisted: augmentAdapters rejects such an adapter at load, so +// writing it would return 500 on reload while leaving a declaration that +// breaks every later reload and start (Codex review, PR #2565). +func TestAdapterAddRefusesServerNamespaceCollision(t *testing.T) { + s, _ := setupPersist(t, []byte(`{"mcpServers":{"clash":{"command":"/bin/true"}}}`), false) + dir := t.TempDir() + file := filepath.Join(dir, "adapters.json") + if err := os.WriteFile(file, []byte(`{"adapters":[]}`), 0o644); err != nil { + t.Fatal(err) + } + if err := s.set.SetRuntime("paths.adapters", file); err != nil { + t.Fatal(err) + } + rec := postAdapter(t, s, `{"name":"clash","command":"/bin/false","tools":[{"name":"run"}]}`) + if rec.Code != http.StatusConflict { + t.Fatalf("status %d, want 409: %s", rec.Code, rec.Body) + } + if got := readFile(t, file); strings.Contains(got, "clash") { + t.Fatalf("the colliding declaration was persisted: %s", got) + } +} + +// The collision rule is on resolved namespaces: foo_bar the adapter +// and foo-bar the configured server are different map keys but one +// namespace after SanitizeNamespace, and the reload rejects the pair +// (Codex review, PR #2565). +func TestAdapterAddRefusesResolvedNamespaceCollision(t *testing.T) { + s, _ := setupPersist(t, []byte(`{"mcpServers":{"foo-bar":{"command":"/bin/true"}}}`), false) + dir := t.TempDir() + file := filepath.Join(dir, "adapters.json") + if err := os.WriteFile(file, []byte(`{"adapters":[]}`), 0o644); err != nil { + t.Fatal(err) + } + if err := s.set.SetRuntime("paths.adapters", file); err != nil { + t.Fatal(err) + } + rec := postAdapter(t, s, `{"name":"foo_bar","command":"/bin/false","tools":[{"name":"run"}]}`) + if rec.Code != http.StatusConflict { + t.Fatalf("status %d, want 409: %s", rec.Code, rec.Body) + } + if got := readFile(t, file); strings.Contains(got, "foo_bar") { + t.Fatalf("the colliding declaration was persisted: %s", got) + } +} diff --git a/pkgs/mcpx/internal/daemon/routes_settings.go b/pkgs/mcpx/internal/daemon/routes_settings.go index ad20ec4074..3f321cc82f 100644 --- a/pkgs/mcpx/internal/daemon/routes_settings.go +++ b/pkgs/mcpx/internal/daemon/routes_settings.go @@ -11,6 +11,7 @@ import ( "sort" "strings" + "github.com/dezren39/mcpx/internal/adapter" "github.com/dezren39/mcpx/internal/config" "github.com/dezren39/mcpx/internal/settings" ) @@ -39,6 +40,8 @@ func (s *Server) routesSettings(mux *http.ServeMux) { mux.HandleFunc("GET /v1/servers/{name}", s.handleServerGet) mux.HandleFunc("POST /v1/servers", s.handleServersAdd) mux.HandleFunc("DELETE /v1/servers/{name}", s.handleServersRemove) + mux.HandleFunc("POST /v1/adapters", s.handleAdaptersAdd) + mux.HandleFunc("DELETE /v1/adapters/{name}", s.handleAdaptersRemove) } // Settings exposes the daemon's resolved configuration. @@ -796,3 +799,161 @@ func (s *Server) reloadConfig() (added, removed []string, err error) { s.logger.Printf("config reloaded: %d added, %d removed", len(added), len(removed)) return added, removed, nil } + +// ---- live adapter add/remove (#2118) ---- +// +// Servers got live add first because they live in the configuration file +// the daemon already edits. Adapters live one step away, in the +// declaration files paths.adapters names, so the same persist + reload +// shape needs a different writer (config.AddAdapterEntry) and a rule for +// which file receives a new declaration: the first file paths.adapters +// names, mirroring how augmentAdapters reads them in order. When no file +// is configured there is nowhere a reload would find a new declaration, +// so the request is refused with the remedy rather than written to a +// file nothing reads. + +type addAdapterReq struct { + adapter.Spec + Replace bool `json:"replace"` +} + +func (s *Server) adapterFiles() []string { + var out []string + for _, p := range splitPathList(s.set.String("paths.adapters")) { + if p != "" && p != settings.NullMarker { + out = append(out, p) + } + } + return out +} + +func (s *Server) handleAdaptersAdd(w http.ResponseWriter, r *http.Request) { + var req addAdapterReq + if err := json.NewDecoder(http.MaxBytesReader(w, r.Body, + s.set.Bytes("http.bodyLimit"))).Decode(&req); err != nil { + writeErr(w, http.StatusBadRequest, err) + return + } + if err := req.Spec.Validate(); err != nil { + writeErr(w, http.StatusBadRequest, err) + return + } + // The lookup, the file write and the reload are one transaction: two + // live changes racing would otherwise read the same declarations and + // overwrite each other's file edit while both report success (Codex + // review, PR #2565). The servers handlers hold reloadMu the same way. + s.reloadMu.Lock() + defer s.reloadMu.Unlock() + files := s.adapterFiles() + if len(files) == 0 { + writeErr(w, http.StatusBadRequest, fmt.Errorf( + "no adapters file is configured: set paths.adapters to a declaration file first "+ + "(for example `mcpx settings set paths.adapters .mcpx/adapters.json`), "+ + "so the declaration written here is one a reload will find")) + return + } + raw, err := json.Marshal(req.Spec) + if err != nil { + writeErr(w, http.StatusInternalServerError, err) + return + } + var entry map[string]any + if err := json.Unmarshal(raw, &entry); err != nil { + writeErr(w, http.StatusInternalServerError, err) + return + } + // The name is looked up across every configured file, not just the + // destination: loadAdapterFiles refuses a name two files declare, so + // writing a second definition into the first file would persist a + // duplicate the next reload — and the next daemon start — rejects + // (Codex review, PR #2565). A replacement edits the file that + // defines the adapter, like remove does. + path := files[0] + if existing, found, err := config.AdapterDefinedIn(files, req.Spec.Name); err != nil { + writeErr(w, http.StatusInternalServerError, err) + return + } else if found { + if !req.Replace { + writeErr(w, http.StatusConflict, fmt.Errorf( + "%s already declares adapter %q; remove it first or pick another name", + existing, req.Spec.Name)) + return + } + path = existing + } + // The name must not collide with a server namespace that is not this + // adapter: augmentAdapters refuses to load an adapter whose name a + // configured server already owns, so persisting one would return 500 + // on the reload while leaving a declaration that breaks every later + // reload and daemon start (Codex review, PR #2565). Adapter-generated + // servers carry the declaration fingerprint in their environment; + // one of those under this name is this adapter itself (a replace), + // anything else -- a configured server, an API -- is a collision. + if cfg := s.currentConfig(); cfg != nil { + // The comparison is on RESOLVED namespaces, not map keys: a + // configured foo-bar and a requested foo_bar are different keys + // and the same namespace after config.SanitizeNamespace, and + // the reload rejects the pair just the same (Codex review, + // PR #2565). The adapter-generated exemption applies only to + // this adapter's own exact name, which a replace legitimately + // redefines. + want := config.SanitizeNamespace(req.Spec.Name) + for name, srv := range cfg.MCPServers { + if srv == nil || config.SanitizeNamespace(name) != want { + continue + } + if name == req.Spec.Name { + if _, isAdapter := srv.Env["MCPX_ADAPTER_DECLARATION_SHA256"]; isAdapter { + continue + } + } + writeErr(w, http.StatusConflict, fmt.Errorf( + "%q resolves to namespace %q, already used by configured server %q; pick another adapter name", + req.Spec.Name, want, name)) + return + } + } + if err := config.AddAdapterEntry(path, entry, req.Replace); err != nil { + writeErr(w, http.StatusConflict, err) + return + } + added, removed, rerr := s.reloadConfig() + if rerr != nil { + writeErr(w, http.StatusInternalServerError, rerr) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "name": req.Spec.Name, "written": path, "added": added, "removed": removed, + }) +} + +func (s *Server) handleAdaptersRemove(w http.ResponseWriter, r *http.Request) { + name := r.PathValue("name") + // Same transaction rule as add: lookup, write and reload under + // reloadMu, so a concurrent add cannot resurrect what this removes + // (or be discarded by it). + s.reloadMu.Lock() + defer s.reloadMu.Unlock() + path, found, err := config.AdapterDefinedIn(s.adapterFiles(), name) + if err != nil { + writeErr(w, http.StatusInternalServerError, err) + return + } + if !found { + writeErr(w, http.StatusNotFound, fmt.Errorf( + "no configured adapters file declares %q", name)) + return + } + if _, err := config.RemoveAdapterEntry(path, name); err != nil { + writeErr(w, http.StatusInternalServerError, err) + return + } + added, removed, rerr := s.reloadConfig() + if rerr != nil { + writeErr(w, http.StatusInternalServerError, rerr) + return + } + writeJSON(w, http.StatusOK, map[string]any{ + "name": name, "written": path, "added": added, "removed": removed, + }) +} diff --git a/pkgs/mcpx/plugin/opencode/mcpx/ops.gen.ts b/pkgs/mcpx/plugin/opencode/mcpx/ops.gen.ts index 44e7f04f35..a1318d4683 100644 --- a/pkgs/mcpx/plugin/opencode/mcpx/ops.gen.ts +++ b/pkgs/mcpx/plugin/opencode/mcpx/ops.gen.ts @@ -22,6 +22,29 @@ type OpSpec = { /** Every /v1 operation, by name. */ export const OPS: Record = { + adapters_add: { + method: "POST", + path: "/v1/adapters", + params: { + name: { in: "body", required: true }, + command: { in: "body", required: true }, + runtime: { in: "body" }, + args: { in: "body" }, + env: { in: "body" }, + description: { in: "body" }, + tools: { in: "body" }, + replace: { in: "body" }, + }, + response: "json", + }, + adapters_remove: { + method: "DELETE", + path: "/v1/adapters/{name}", + params: { + name: { in: "path", required: true }, + }, + response: "json", + }, artifact_delete: { method: "DELETE", path: "/v1/artifacts/{id}", @@ -862,6 +885,23 @@ export class DaemonOps { return text ? JSON.parse(text) : undefined } + /** + * Add an adapter declaration, live. `POST /v1/adapters`. + * Privileged: it changes the daemon rather than reading it. + */ + adaptersAdd(args: { name: string; command: string; runtime?: string; args?: unknown[]; env?: Record; description?: string; tools?: unknown[]; replace?: boolean }, opts: CallOptions = {}): Promise { + return this.invoke("adapters_add", args, opts) as Promise + } + + /** + * Remove an adapter declaration, live. `DELETE /v1/adapters/{name}`. + * Privileged: it changes the daemon rather than reading it. + * Destructive: it cannot be undone, and other callers are affected. + */ + adaptersRemove(args: { name: string }, opts: CallOptions = {}): Promise { + return this.invoke("adapters_remove", args, opts) as Promise + } + /** * Forget one artifact. `DELETE /v1/artifacts/{id}`. * Privileged: it changes the daemon rather than reading it.