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
6 changes: 4 additions & 2 deletions pkgs/mcpx/docs/parity.md
Original file line number Diff line number Diff line change
Expand Up @@ -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. |
Expand Down Expand Up @@ -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. |
Expand Down
47 changes: 47 additions & 0 deletions pkgs/mcpx/internal/api/ops_settings.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
},
},
}
}
144 changes: 143 additions & 1 deletion pkgs/mcpx/internal/cli/adapter.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ package cli

import (
"context"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"fmt"
"net/http"
"os"
"path/filepath"
"sort"
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 <name> [--tool <subcommand>]... -- <command> [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>")
}
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
}
96 changes: 96 additions & 0 deletions pkgs/mcpx/internal/cli/adapter_add_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
9 changes: 6 additions & 3 deletions pkgs/mcpx/internal/cli/manual.go
Original file line number Diff line number Diff line change
Expand Up @@ -617,19 +617,22 @@ 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] [<name>.<tool> '<json>' | <name> [file...]]",
Usage: "[list|check|call|tools|serve|add|remove] [<name>.<tool> '<json>' | <name> [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 " +
"program is installed, call runs one tool, and tools prints the " +
"tool definitions an MCP host would see. Every adapter is also a " +
"namespace: the daemon runs it as `mcpx adapter serve <name>`, " +
"so it is in mcpx ls, types, search, catalog and the generated " +
"client, and a script calls it as <name>.<tool>({...}).",
"client, and a script calls it as <name>.<tool>({...}). 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",
},
},
{
Expand Down
6 changes: 3 additions & 3 deletions pkgs/mcpx/internal/cli/plugin.go
Original file line number Diff line number Diff line change
Expand Up @@ -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},
}
Expand Down
Loading