diff --git a/cmd/mcpproxy/access_cmd.go b/cmd/mcpproxy/access_cmd.go index ef463ad2e..78c5cc276 100644 --- a/cmd/mcpproxy/access_cmd.go +++ b/cmd/mcpproxy/access_cmd.go @@ -286,12 +286,14 @@ func fixCommand(f runtime.Fix, tool string) string { case profile.FixApproveTool: // A tool-approval target is "server:tool": approve only that tool (a bare // `approve ` approves every pending tool of the server). A - // quarantined-server target is the server name alone, where approving - // the whole server is the intended action. + // quarantined-server target is the server name alone, where admitting + // the whole server is the intended action: that is `review approve`, + // because `upstream approve` only approves pending tools and leaves a + // quarantined server quarantined. if server, tool, ok := strings.Cut(f.Target, ":"); ok && server != "" && tool != "" { return "mcpproxy upstream approve " + server + " " + tool } - return "mcpproxy upstream approve " + f.Target + return "mcpproxy review approve " + f.Target case profile.FixChangeSetting: if f.Target == "require_mcp_auth" { return "set require_mcp_auth: true (config or Settings → Security)" diff --git a/cmd/mcpproxy/access_fix_command_test.go b/cmd/mcpproxy/access_fix_command_test.go index 3dabcda51..435e84ca1 100644 --- a/cmd/mcpproxy/access_fix_command_test.go +++ b/cmd/mcpproxy/access_fix_command_test.go @@ -29,16 +29,17 @@ func TestAccessExplain_MoveClientFixNamesDestinationProfile(t *testing.T) { // A tool_approval failure targets one tool, so its hint must approve only that // tool: `upstream approve ` with no tool list approves every pending -// tool of the server. Only a quarantined SERVER (target = the server name) is -// approved as a whole. +// tool of the server. A quarantined SERVER (target = the server name) is +// admitted with `review approve `: `upstream approve ` only +// approves pending tools and leaves a quarantined server quarantined. func TestAccessExplain_ApproveToolFixNamesOnlyThatTool(t *testing.T) { for _, tc := range []struct { name, target, want string }{ {"tool approval", "github:create_issue", "mcpproxy upstream approve github create_issue"}, - {"server quarantine", "github", "mcpproxy upstream approve github"}, + {"server quarantine", "github", "mcpproxy review approve github"}, {"cut at the first colon only", "github:ns:create_issue", "mcpproxy upstream approve github ns:create_issue"}, - {"empty tool part is the server", "github:", "mcpproxy upstream approve github:"}, + {"empty tool part is the server", "github:", "mcpproxy review approve github:"}, } { t.Run(tc.name, func(t *testing.T) { got := fixCommand(runtime.Fix{Action: profile.FixApproveTool, Target: tc.target}, "github:create_issue") diff --git a/cmd/mcpproxy/catalog_cmd.go b/cmd/mcpproxy/catalog_cmd.go index 64f643a7d..a2b7622cf 100644 --- a/cmd/mcpproxy/catalog_cmd.go +++ b/cmd/mcpproxy/catalog_cmd.go @@ -69,7 +69,8 @@ the curated official/popular sections with no query. mcpproxy catalog search # browse official + popular mcpproxy catalog show official/io.github.github/github-mcp-server mcpproxy catalog add official/io.github.github/github-mcp-server - mcpproxy upstream approve # approve once trusted + mcpproxy review show # inspect the captured tools + mcpproxy review approve --yes # approve once trusted 'catalog search'/'catalog add' supersede 'registry search'/'registry add'. 'registry list'/'add-source'/'edit'/'remove' still manage catalog SOURCES.`, @@ -182,8 +183,10 @@ func newCatalogAddCmd() *cobra.Command { Use: "add /", Short: "Add a catalog entry as a (quarantined) upstream server", Long: `Add a server found via 'catalog search'/'catalog show' as an upstream server. -The server is added quarantined by default; approve it once you trust it: - mcpproxy upstream approve +The server is added quarantined by default; inspect it, then approve it once +you trust it: + mcpproxy review show + mcpproxy review approve --yes This is the same keystone add operation as 'registry add ' (Spec 070) — it just takes the combined "/" ref catalog results print.`, diff --git a/cmd/mcpproxy/registry_add_message_test.go b/cmd/mcpproxy/registry_add_message_test.go index f10c700a7..4a7912bd1 100644 --- a/cmd/mcpproxy/registry_add_message_test.go +++ b/cmd/mcpproxy/registry_add_message_test.go @@ -17,6 +17,18 @@ func TestRegistryAddMessage(t *testing.T) { t.Fatalf("expected quarantined message to say %q, got %q", "quarantined for review", quarantined) } + // The quarantined hint must name the step that actually admits the + // server. `mcpproxy upstream approve` only approves pending tools: on a + // quarantined server it prints "Approved 0 tools" and the server stays + // quarantined, which left first-run users stuck. + if !strings.Contains(quarantined, "mcpproxy review show github-server") || + !strings.Contains(quarantined, "mcpproxy review approve github-server --yes") { + t.Fatalf("quarantined message must name review show / review approve --yes, got %q", quarantined) + } + if strings.Contains(quarantined, "upstream approve") { + t.Fatalf("quarantined message must not point at upstream approve, got %q", quarantined) + } + notQuarantined := registryAddMessage("github-server", false) if !strings.Contains(notQuarantined, "Added github-server to MCPProxy") { t.Fatalf("expected message to contain %q, got %q", "Added github-server to MCPProxy", notQuarantined) diff --git a/cmd/mcpproxy/registry_cmd.go b/cmd/mcpproxy/registry_cmd.go index 407a3c95a..72d46419c 100644 --- a/cmd/mcpproxy/registry_cmd.go +++ b/cmd/mcpproxy/registry_cmd.go @@ -56,7 +56,7 @@ Typical flow: mcpproxy registry list # see available registries mcpproxy registry search weather -r pulse # find a server mcpproxy registry add pulse weather-mcp # add it (quarantined) - mcpproxy upstream approve weather-mcp # approve once you trust it + mcpproxy review approve weather-mcp --yes # approve once you trust it Add your own registry source (any official modelcontextprotocol/registry v0.1 endpoint): mcpproxy registry add-source https://registry.example.com # tagged "custom" @@ -168,7 +168,7 @@ add through it follow the global quarantine default like any other server, so with quarantine enabled (the default) they land quarantined for review: mcpproxy registry search -r mcpproxy registry add - mcpproxy upstream approve `, + mcpproxy review approve --yes`, Args: cobra.ExactArgs(1), RunE: func(_ *cobra.Command, args []string) error { sourceURL := args[0] @@ -424,7 +424,7 @@ func newRegistryAddCmd() *cobra.Command { Long: `Add a server discovered in a registry as an upstream server. The server is added quarantined by default; approve it once you trust it: - mcpproxy upstream approve + mcpproxy review approve --yes The daemon re-derives the runnable config (command/args/url) from the registry entry — you only supply optional overrides. If the server declares required @@ -487,7 +487,9 @@ inputs, supply them with --env KEY=VALUE.`, func registryAddMessage(name string, quarantined bool) string { msg := fmt.Sprintf("✅ Added %s to MCPProxy", name) if quarantined { - msg += fmt.Sprintf(" (quarantined for review — approve with: mcpproxy upstream approve %s)", name) + // Name the step that admits the server. `upstream approve` only + // approves pending tools and leaves a quarantined server quarantined. + msg += fmt.Sprintf(" (quarantined for review — inspect with: mcpproxy review show %s, then approve with: mcpproxy review approve %s --yes)", name, name) } return msg } diff --git a/cmd/mcpproxy/upstream_cmd.go b/cmd/mcpproxy/upstream_cmd.go index 4b9edd38d..aca80435f 100644 --- a/cmd/mcpproxy/upstream_cmd.go +++ b/cmd/mcpproxy/upstream_cmd.go @@ -19,6 +19,7 @@ import ( "github.com/spf13/cobra" "go.uber.org/zap" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/auth" "github.com/smart-mcp-proxy/mcpproxy-go/internal/cli/output" "github.com/smart-mcp-proxy/mcpproxy-go/internal/cliclient" "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" @@ -429,10 +430,13 @@ func runUpstreamList(_ *cobra.Command, _ []string) error { return outputError(err, output.ErrCodeOperationFailed) } - // Check if daemon is running (socket first, then TCP fallback) - if client, ok := newDaemonClient(globalConfig, logger.Sugar()); ok { + // Check if daemon is running (socket first, then TCP fallback). The key + // the client will send decides whether the list is the whole install: + // none (the socket) or the admin key is, an agent token's is not. + if endpoint, apiKey, ok := daemonEndpoint(globalConfig); ok { logger.Info("Detected running daemon, using client mode") - return runUpstreamListClientMode(ctx, client, logger) + client := cliclient.NewClientWithAPIKey(endpoint, apiKey, logger.Sugar()) + return runUpstreamListClientMode(ctx, client, apiKey, logger) } if upstreamListProfile != "" { return outputError(output.NewStructuredError(output.ErrCodeConnectionFailed, @@ -459,7 +463,7 @@ func upstreamListQuery() url.Values { return q } -func runUpstreamListClientMode(ctx context.Context, client *cliclient.Client, _ *zap.Logger) error { +func runUpstreamListClientMode(ctx context.Context, client *cliclient.Client, apiKey string, _ *zap.Logger) error { // Call GET /api/v1/servers servers, err := client.GetServersWithQuery(ctx, upstreamListQuery()) if err != nil { @@ -468,6 +472,10 @@ func runUpstreamListClientMode(ctx context.Context, client *cliclient.Client, _ WithRecoveryCommand("mcpproxy serve"), output.ErrCodeConnectionFailed) } + upstreamListSource = listOriginDaemonAdmin + if strings.HasPrefix(apiKey, auth.TokenPrefixStr) { + upstreamListSource = listOriginDaemonScoped + } return outputServers(servers) } @@ -557,10 +565,18 @@ func runUpstreamListFromConfig(globalConfig *config.Config) error { } } + upstreamListSource = listOriginConfig return outputServers(servers) } func outputServers(servers []map[string]interface{}) error { + // An install with no servers at all gets a next step after the empty + // table, in table output only. A --profile list holds only that profile's + // servers, so an empty one says nothing about the install. (A --status + // filter is applied below, after this check.) + noServersConfigured := len(servers) == 0 && upstreamListProfile == "" && + upstreamListSource != listOriginDaemonScoped + // FR-015: --status is repeatable, and a comma-separated value is // equivalent to repeating the flag; several values select the UNION of // their statuses. Applies to every output format (table, json, yaml). @@ -601,6 +617,9 @@ func outputServers(servers []map[string]interface{}) error { return fmt.Errorf("failed to format table: %w", err) } fmt.Print(result) + if noServersConfigured { + fmt.Print(firstServerHint(exec.LookPath, upstreamListSource != listOriginConfig)) + } return nil } @@ -2787,3 +2806,51 @@ func viewOr(view map[string]interface{}, key, fallback string) string { } return fallback } + +// firstServerHint is the empty-state next step for `mcpproxy upstream list` +// on an install with no servers (Spec 126 US2, CLI surface). It suggests one +// credential-free reference server through the catalog door, in the Spec 126 +// FR-002 starter order (time, then sequentialthinking), choosing the first +// whose launcher this machine has. The catalog door applies quarantine, trust +// mode and the admission scan exactly as for any catalog add; the hint itself +// adds, runs and approves nothing. lookPath is exec.LookPath in production. +func firstServerHint(lookPath func(string) (string, error), daemonRunning bool) string { + var b strings.Builder + b.WriteString("\nNo upstream servers yet. Next steps:\n") + if !daemonRunning { + b.WriteString(" mcpproxy serve # start the core first (catalog add and review need it)\n") + } + has := func(name string) bool { _, err := lookPath(name); return err == nil } + switch { + case has("uvx"): + b.WriteString(" mcpproxy catalog add reference/time # reference server, no credentials (runs: uvx mcp-server-time)\n") + case has("npx"): + b.WriteString(" mcpproxy catalog add reference/sequentialthinking # reference server, no credentials (runs: npx -y @modelcontextprotocol/server-sequential-thinking)\n") + default: + b.WriteString(" (local reference servers need uv (uvx) or Node.js (npx); neither is on PATH)\n") + } + b.WriteString(" mcpproxy upstream add # any remote MCP server\n") + b.WriteString(" mcpproxy catalog search # browse the catalog\n") + b.WriteString("New servers are quarantined and scanned; inspect one with 'mcpproxy review show ' and admit it with 'mcpproxy review approve --yes'.\n") + return b.String() +} + +// upstreamListOrigin says where `upstream list` got its servers, which +// decides whether an empty list means an empty install (first-server hint). +type upstreamListOrigin int + +const ( + // listOriginDaemonAdmin: the daemon, as an administrator (socket or the + // instance API key). An empty list is an empty install. + listOriginDaemonAdmin upstreamListOrigin = iota + // listOriginConfig: no daemon; the config file. An empty list is an empty + // install, but the core must be started before catalog add / review. + listOriginConfig + // listOriginDaemonScoped: the daemon, as an agent token. The list holds + // only the servers the token may see, so an empty one says nothing about + // the install, and adding servers is not the token's operation. + listOriginDaemonScoped +) + +// upstreamListSource is set by the two list paths before outputServers. +var upstreamListSource = listOriginDaemonAdmin diff --git a/cmd/mcpproxy/upstream_first_server_hint_test.go b/cmd/mcpproxy/upstream_first_server_hint_test.go new file mode 100644 index 000000000..2e6f9508f --- /dev/null +++ b/cmd/mcpproxy/upstream_first_server_hint_test.go @@ -0,0 +1,187 @@ +package main + +import ( + "context" + "errors" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "github.com/smart-mcp-proxy/mcpproxy-go/internal/cliclient" + "github.com/smart-mcp-proxy/mcpproxy-go/internal/config" +) + +func fakeLookPath(present ...string) func(string) (string, error) { + return func(name string) (string, error) { + for _, p := range present { + if p == name { + return "/usr/local/bin/" + name, nil + } + } + return "", errors.New("not found") + } +} + +// A fresh install that runs `mcpproxy upstream list` used to get only "No +// results found": a dead end. The hint names one credential-free reference +// server through the catalog door (so it is quarantined and scanned like any +// catalog add), picked by which launcher this machine has, plus the remote +// route. It never adds or approves anything itself. +func TestFirstServerHint(t *testing.T) { + cases := []struct { + name string + present []string + want []string + mustNot []string + }{ + {"uvx", []string{"uvx", "npx"}, []string{"mcpproxy catalog add reference/time", "uvx mcp-server-time", "mcpproxy upstream add ", "review"}, []string{"sequentialthinking"}}, + {"npx only", []string{"npx"}, []string{"mcpproxy catalog add reference/sequentialthinking", "mcpproxy upstream add "}, []string{"reference/time"}}, + {"no launcher", nil, []string{"mcpproxy upstream add ", "uv", "Node.js"}, []string{"catalog add reference/"}}, + } + for _, c := range cases { + t.Run(c.name, func(t *testing.T) { + got := firstServerHint(fakeLookPath(c.present...), true) + for _, w := range c.want { + if !strings.Contains(got, w) { + t.Errorf("hint missing %q:\n%s", w, got) + } + } + for _, m := range c.mustNot { + if strings.Contains(got, m) { + t.Errorf("hint must not contain %q:\n%s", m, got) + } + } + }) + } +} + +// Without a running daemon, 'catalog add' and 'review' cannot work yet, so +// the hint starts with 'mcpproxy serve'. +func TestFirstServerHint_NoDaemonStartsWithServe(t *testing.T) { + got := firstServerHint(fakeLookPath("uvx"), false) + serve := strings.Index(got, "mcpproxy serve") + add := strings.Index(got, "mcpproxy catalog add reference/time") + if serve < 0 || add < 0 || serve > add { + t.Errorf("no-daemon hint must name 'mcpproxy serve' before the catalog add:\n%s", got) + } + if strings.Contains(firstServerHint(fakeLookPath("uvx"), true), "mcpproxy serve") { + t.Errorf("with a daemon running the hint must not tell the user to start one") + } +} + +// A scoped caller (an agent token) sees only the servers it may see; an +// empty list is not an empty install, and catalog add is not its operation. +func TestOutputServers_ScopedCallerGetsNoFirstServerHint(t *testing.T) { + setOutputGlobals(t, "table", false) + old := upstreamListSource + upstreamListSource = listOriginDaemonScoped + t.Cleanup(func() { upstreamListSource = old }) + out := captureOutput(func() { + if err := outputServers([]map[string]interface{}{}); err != nil { + t.Fatalf("outputServers: %v", err) + } + }) + if strings.Contains(out, "No upstream servers yet") { + t.Errorf("a scoped caller must not get the empty-install hint, got:\n%s", out) + } + + upstreamListSource = listOriginConfig + out = captureOutput(func() { + if err := outputServers([]map[string]interface{}{}); err != nil { + t.Fatalf("outputServers: %v", err) + } + }) + if !strings.Contains(out, "mcpproxy serve") { + t.Errorf("config-file mode (no daemon) must tell the user to start the core, got:\n%s", out) + } +} + +// The list paths themselves set the origin: config-file mode (no daemon) +// tells the user to start the core; client mode decides from the key the +// client actually sends (no key = socket = administrator; an mcp_agt_ key = +// a scoped agent token, which gets no hint). +func TestUpstreamListPaths_SetTheHintOrigin(t *testing.T) { + setOutputGlobals(t, "table", false) + old := upstreamListSource + t.Cleanup(func() { upstreamListSource = old }) + + out := captureOutput(func() { + if err := runUpstreamListFromConfig(&config.Config{}); err != nil { + t.Fatalf("runUpstreamListFromConfig: %v", err) + } + }) + if !strings.Contains(out, "No upstream servers yet") || !strings.Contains(out, "mcpproxy serve") { + t.Errorf("config-file mode with no servers must print the hint with 'mcpproxy serve', got:\n%s", out) + } + + daemon := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _, _ = io.WriteString(w, `{"success":true,"data":{"servers":[]}}`) + })) + t.Cleanup(daemon.Close) + + for _, c := range []struct { + name, key string + hint bool + }{ + {"socket or no key: administrator", "", true}, + {"instance admin key", "plain-admin-key", true}, + {"agent token", "mcp_agt_0123456789abcdef", false}, + } { + t.Run(c.name, func(t *testing.T) { + upstreamListSource = listOriginConfig // must be reset by the path + client := cliclient.NewClientWithAPIKey(daemon.URL, c.key, nil) + out := captureOutput(func() { + if err := runUpstreamListClientMode(context.Background(), client, c.key, nil); err != nil { + t.Fatalf("runUpstreamListClientMode: %v", err) + } + }) + if got := strings.Contains(out, "No upstream servers yet"); got != c.hint { + t.Errorf("hint printed = %v, want %v:\n%s", got, c.hint, out) + } + if strings.Contains(out, "mcpproxy serve") { + t.Errorf("with a daemon answering, the hint must not say to start one:\n%s", out) + } + }) + } +} + +func TestOutputServers_EmptyListPrintsFirstServerHint(t *testing.T) { + setOutputGlobals(t, "table", false) + out := captureOutput(func() { + if err := outputServers([]map[string]interface{}{}); err != nil { + t.Fatalf("outputServers: %v", err) + } + }) + if !strings.Contains(out, "No upstream servers yet") { + t.Errorf("empty list must print the first-server hint, got:\n%s", out) + } + + // A --profile list is only that profile's servers: an empty one is not + // an empty install. + oldProfile := upstreamListProfile + upstreamListProfile = "work" + t.Cleanup(func() { upstreamListProfile = oldProfile }) + out = captureOutput(func() { + if err := outputServers([]map[string]interface{}{}); err != nil { + t.Fatalf("outputServers: %v", err) + } + }) + if strings.Contains(out, "No upstream servers yet") { + t.Errorf("an empty --profile list must not print the first-server hint, got:\n%s", out) + } + upstreamListProfile = oldProfile + + // Structured output stays pure data. + setOutputGlobals(t, "json", false) + out = captureOutput(func() { + if err := outputServers([]map[string]interface{}{}); err != nil { + t.Fatalf("outputServers: %v", err) + } + }) + if strings.Contains(out, "No upstream servers yet") { + t.Errorf("json output must not carry the hint, got:\n%s", out) + } +} diff --git a/cmd/mcpproxy/upstream_list_socket_hint_test.go b/cmd/mcpproxy/upstream_list_socket_hint_test.go new file mode 100644 index 000000000..7e083ba2d --- /dev/null +++ b/cmd/mcpproxy/upstream_list_socket_hint_test.go @@ -0,0 +1,77 @@ +//go:build !windows + +package main + +import ( + "io" + "net" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" +) + +// runUpstreamList end to end over a unix socket: the socket is an +// administrator connection (no key is sent), so an empty install gets the +// first-server hint even when an agent token is exported. Review r3/r4: the +// hint must follow the key the client actually sends, which only the +// wiring in runUpstreamList decides. +func TestRunUpstreamList_SocketAdminGetsHintDespiteAgentTokenInEnv(t *testing.T) { + clearDaemonEnv(t) + t.Setenv("MCPPROXY_API_KEY", "mcp_agt_0123456789abcdef") + setOutputGlobals(t, "table", false) + oldSource := upstreamListSource + t.Cleanup(func() { upstreamListSource = oldSource }) + + // macOS caps unix socket paths at 104 bytes; t.TempDir() can exceed it. + dir, err := os.MkdirTemp("/tmp", "mcpx-hint-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.RemoveAll(dir) }) + + ln, err := net.Listen("unix", filepath.Join(dir, "mcpproxy.sock")) + if err != nil { + t.Fatal(err) + } + var sawKey string + srv := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Header.Get("X-API-Key") != "" { + sawKey = r.Header.Get("X-API-Key") + } + w.Header().Set("Content-Type", "application/json") + if r.URL.Path == "/api/v1/servers" { + _, _ = io.WriteString(w, `{"success":true,"data":{"servers":[]}}`) + return + } + _, _ = io.WriteString(w, `{"success":true,"data":{}}`) + })) + srv.Listener = ln + srv.Start() + t.Cleanup(srv.Close) + + cfgPath := filepath.Join(dir, "mcp_config.json") + if err := os.WriteFile(cfgPath, []byte(`{"listen":"127.0.0.1:0","data_dir":"`+dir+`","mcpServers":[]}`), 0o600); err != nil { + t.Fatal(err) + } + oldPath := upstreamConfigPath + upstreamConfigPath = cfgPath + t.Cleanup(func() { upstreamConfigPath = oldPath }) + + out := captureOutput(func() { + if err := runUpstreamList(nil, nil); err != nil { + t.Fatalf("runUpstreamList: %v", err) + } + }) + if sawKey != "" { + t.Fatalf("a socket connection must send no API key, saw one") + } + if !strings.Contains(out, "No upstream servers yet") { + t.Errorf("socket admin on an empty install must get the hint despite an agent token in the env, got:\n%s", out) + } + if strings.Contains(out, "mcpproxy serve") { + t.Errorf("the daemon answered over the socket; the hint must not say to start it:\n%s", out) + } +} diff --git a/docs/features/registry-add.md b/docs/features/registry-add.md index 87a2e4b75..62acf58ed 100644 --- a/docs/features/registry-add.md +++ b/docs/features/registry-add.md @@ -51,8 +51,11 @@ tool is `search_servers`. - **Quarantined by default.** A freshly added server is quarantined until you approve it: ```bash - mcpproxy upstream approve + mcpproxy review show # inspect the captured tools and scan + mcpproxy review approve --yes # admit the server ``` + (`mcpproxy upstream approve` approves pending tools only; it does not admit a + quarantined server.) - **Required inputs are explicit.** If a registry entry declares required inputs (e.g. `${GITHUB_TOKEN}`) and you don't supply them, the add fails with the stable code `missing_required_input` and the exact input names — no partially @@ -90,7 +93,7 @@ Example: ```bash mcpproxy secrets set github-token mcpproxy registry add official io.github.example/github-mcp --env 'GITHUB_TOKEN=${keyring:github-token}' -# ✅ Added 'github-mcp' (quarantined — approve with: mcpproxy upstream approve github-mcp) +# ✅ Added github-mcp to MCPProxy (quarantined for review — inspect with: mcpproxy review show github-mcp, then approve with: mcpproxy review approve github-mcp --yes) ``` For credentials, avoid putting a literal value in `--env`: it is a command-line argument and may be retained in shell history or exposed in process listings. Store the value with `mcpproxy secrets set github-token`, then use a quoted keyring reference such as `--env 'GITHUB_TOKEN=${keyring:github-token}'`. The current interactive prompt echoes typed characters in the terminal; use `--from-stdin` with a trusted secret source when that is unsuitable. diff --git a/internal/registries/findserver_source_prefix_test.go b/internal/registries/findserver_source_prefix_test.go new file mode 100644 index 000000000..b8bff9279 --- /dev/null +++ b/internal/registries/findserver_source_prefix_test.go @@ -0,0 +1,44 @@ +package registries + +import ( + "context" + "testing" + + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +// The compiled-in reference catalog gives every entry an id that already +// starts with its source ("reference/time"), and `catalog search` prints that +// id in its ID column. A user who copies it writes `catalog add +// reference/time`, which splits into source "reference" and id "time". Before +// this fix only the doubled ref "reference/reference/time" resolved, so the +// first-run catalog door failed with "server not found in registry". +func TestFindServerByID_AcceptsSourcePrefixedReferenceID(t *testing.T) { + withTestRegistries(t, []RegistryEntry{{ID: "reference", Name: "Reference", Protocol: protocolReference}}) + + for _, id := range []string{"time", "reference/time"} { + got, err := FindServerByID(context.Background(), "reference", id, nil) + require.NoError(t, err, "id %q must resolve", id) + assert.Equal(t, "reference/time", got.ID) + } + + _, err := FindServerByID(context.Background(), "reference", "no-such-server", nil) + assert.ErrorIs(t, err, ErrServerNotFound) +} + +// An exact id always wins over the source-prefixed alias, so a listing that +// holds both "x" and "/x" never resolves "x" to the other entry. +func TestFindServerByIDInSource_ExactMatchWins(t *testing.T) { + servers := []ServerEntry{{ID: "src/x", Name: "alias"}, {ID: "x", Name: "exact"}} + got, err := findServerByIDInSource(servers, "src", "x") + require.NoError(t, err) + assert.Equal(t, "exact", got.Name) + + got, err = findServerByIDInSource([]ServerEntry{{ID: "src/x"}}, "src", "x") + require.NoError(t, err) + assert.Equal(t, "src/x", got.ID) + + _, err = findServerByIDInSource([]ServerEntry{{ID: "other/x"}}, "src", "x") + assert.ErrorIs(t, err, ErrServerNotFound) +} diff --git a/internal/registries/search.go b/internal/registries/search.go index 2ad515ee4..75c30d021 100644 --- a/internal/registries/search.go +++ b/internal/registries/search.go @@ -263,7 +263,7 @@ func FindServerByID(ctx context.Context, registryID, serverID string, guesser *e // regardless of its position in the listing. func findServerByIDFetch(ctx context.Context, reg *RegistryEntry, serverID string) (*ServerEntry, error) { if servers, err := fetchServers(ctx, reg, nil, serverID, 0); err == nil { - if match, err := findServerByIDIn(servers, serverID); err == nil { + if match, err := findServerByIDInSource(servers, reg.ID, serverID); err == nil { return match, nil } } @@ -271,7 +271,7 @@ func findServerByIDFetch(ctx context.Context, reg *RegistryEntry, serverID strin if err != nil { return nil, err } - return findServerByIDIn(servers, serverID) + return findServerByIDInSource(servers, reg.ID, serverID) } // findServerByIDIn returns the first server whose ID exactly matches serverID. @@ -770,3 +770,21 @@ func derivePulseServerDetailsWithoutGuesser(itemMap map[string]interface{}) (ins return installCmd, connectURL } + +// findServerByIDInSource resolves serverID within one source's listing. An +// exact id always wins. Failing that, it accepts the id with the source +// prefix added: the compiled-in reference catalog gives every entry an id +// that already starts with its source ("reference/time"), and `catalog +// search` prints that id, so a user who copies it into `catalog add +// reference/time` passes source "reference" and id "time". The alias is +// looked up in the same listing, so it never costs a second fetch, and it +// cannot match an entry of another source. +func findServerByIDInSource(servers []ServerEntry, sourceID, serverID string) (*ServerEntry, error) { + if match, err := findServerByIDIn(servers, serverID); err == nil { + return match, nil + } + if sourceID == "" || strings.HasPrefix(serverID, sourceID+"/") { + return nil, ErrServerNotFound + } + return findServerByIDIn(servers, sourceID+"/"+serverID) +}