| 1 | package cli |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "os" |
| 9 | "path/filepath" |
| 10 | "reflect" |
| 11 | "strings" |
| 12 | "testing" |
| 13 | |
| 14 | tea "charm.land/bubbletea/v2" |
| 15 | |
| 16 | "reasonix/internal/config" |
| 17 | "reasonix/internal/control" |
| 18 | "reasonix/internal/mcpregistry" |
| 19 | "reasonix/internal/plugin" |
| 20 | ) |
| 21 | |
| 22 | func stubMCPReadinessProbe(t *testing.T) { |
| 23 | t.Helper() |
| 24 | previous := mcpProbeForInstall |
| 25 | mcpProbeForInstall = func(entry config.PluginEntry) (plugin.MCPInstallResult, error) { |
| 26 | return plugin.ReadyInstallResult(entry.Name, 3), nil |
| 27 | } |
| 28 | t.Cleanup(func() { mcpProbeForInstall = previous }) |
| 29 | } |
| 30 | |
| 31 | func TestParseMCPAddStdio(t *testing.T) { |
| 32 | e, err := parseMCPAdd([]string{"fs", "npx", "-y", "@modelcontextprotocol/server-filesystem", "."}) |
| 33 | if err != nil { |
| 34 | t.Fatalf("unexpected error: %v", err) |
| 35 | } |
| 36 | if e.Name != "fs" || e.Command != "npx" { |
| 37 | t.Fatalf("name/command = %q/%q", e.Name, e.Command) |
| 38 | } |
| 39 | // The command keeps its own -flags: "-y" is an arg, not parsed as our flag. |
| 40 | if want := []string{"-y", "@modelcontextprotocol/server-filesystem", "."}; !reflect.DeepEqual(e.Args, want) { |
| 41 | t.Fatalf("args = %v, want %v", e.Args, want) |
| 42 | } |
| 43 | if e.URL != "" { |
| 44 | t.Errorf("stdio entry should have no URL, got %q", e.URL) |
| 45 | } |
| 46 | } |
| 47 | |
| 48 | func TestParseMCPAddStdioEnv(t *testing.T) { |
| 49 | e, err := parseMCPAdd([]string{"db", "--env", "PGHOST=localhost", "node", "server.js"}) |
| 50 | if err != nil { |
| 51 | t.Fatalf("unexpected error: %v", err) |
| 52 | } |
| 53 | if e.Command != "node" || !reflect.DeepEqual(e.Args, []string{"server.js"}) { |
| 54 | t.Fatalf("command/args = %q/%v", e.Command, e.Args) |
| 55 | } |
| 56 | if e.Env["PGHOST"] != "localhost" { |
| 57 | t.Errorf("env PGHOST = %q, want localhost", e.Env["PGHOST"]) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | func TestParseMCPAddHTTP(t *testing.T) { |
| 62 | for _, args := range [][]string{ |
| 63 | {"stripe", "--http", "https://mcp.stripe.com"}, |
| 64 | {"stripe", "--http=https://mcp.stripe.com"}, |
| 65 | } { |
| 66 | e, err := parseMCPAdd(args) |
| 67 | if err != nil { |
| 68 | t.Fatalf("%v: %v", args, err) |
| 69 | } |
| 70 | if e.Type != "http" || e.URL != "https://mcp.stripe.com" { |
| 71 | t.Errorf("%v -> type/url = %q/%q", args, e.Type, e.URL) |
| 72 | } |
| 73 | if e.Command != "" { |
| 74 | t.Errorf("%v -> remote entry should have no command, got %q", args, e.Command) |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | func TestParseMCPAddHTTPHeader(t *testing.T) { |
| 80 | e, err := parseMCPAdd([]string{"x", "--http", "https://x", "--header", "Authorization=Bearer abc"}) |
| 81 | if err != nil { |
| 82 | t.Fatalf("unexpected error: %v", err) |
| 83 | } |
| 84 | if e.Headers["Authorization"] != "Bearer abc" { |
| 85 | t.Errorf("header = %q, want %q", e.Headers["Authorization"], "Bearer abc") |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | func TestParseMCPAddErrors(t *testing.T) { |
| 90 | cases := map[string][]string{ |
| 91 | "no name": {}, |
| 92 | "name is a flag": {"--http", "https://x"}, |
| 93 | "no command/url": {"fs"}, |
| 94 | "command and url": {"x", "--http", "https://x", "node"}, |
| 95 | "unknown flag": {"x", "--bogus", "y", "cmd"}, |
| 96 | "env without value": {"x", "--env"}, |
| 97 | "bare dash dash": {"--"}, |
| 98 | } |
| 99 | for name, args := range cases { |
| 100 | if _, err := parseMCPAdd(args); err == nil { |
| 101 | t.Errorf("%s: expected an error for %v", name, args) |
| 102 | } |
| 103 | } |
| 104 | } |
| 105 | |
| 106 | func TestParseMCPAddDashDashArgv(t *testing.T) { |
| 107 | e, err := parseMCPAdd([]string{"--", "npx", "-y", "chrome-devtools-mcp@latest"}) |
| 108 | if err != nil { |
| 109 | t.Fatalf("unexpected error: %v", err) |
| 110 | } |
| 111 | if e.Name != "chrome-devtools-mcp" { |
| 112 | t.Fatalf("name = %q, want chrome-devtools-mcp", e.Name) |
| 113 | } |
| 114 | if e.Command != "npx" || !reflect.DeepEqual(e.Args, []string{"-y", "chrome-devtools-mcp@latest"}) { |
| 115 | t.Fatalf("command/args = %q/%v", e.Command, e.Args) |
| 116 | } |
| 117 | |
| 118 | named, err := parseMCPAdd([]string{"chrome", "--", "npx", "-y", "chrome-devtools-mcp@latest"}) |
| 119 | if err != nil { |
| 120 | t.Fatalf("named -- form: %v", err) |
| 121 | } |
| 122 | if named.Name != "chrome" || named.Command != "npx" { |
| 123 | t.Fatalf("named entry = %+v", named) |
| 124 | } |
| 125 | } |
| 126 | |
| 127 | func TestParseMCPAddDashDashNamesLauncherPackageNotTrailingArgument(t *testing.T) { |
| 128 | e, err := parseMCPAdd([]string{"--", "npx", "-y", "@modelcontextprotocol/server-filesystem", "/srv/shared"}) |
| 129 | if err != nil { |
| 130 | t.Fatal(err) |
| 131 | } |
| 132 | if e.Name != "server-filesystem" { |
| 133 | t.Fatalf("name = %q, want server-filesystem", e.Name) |
| 134 | } |
| 135 | |
| 136 | python, err := parseMCPAdd([]string{"--", "python", "-m", "mcp_server_time", "--local-timezone=UTC"}) |
| 137 | if err != nil { |
| 138 | t.Fatal(err) |
| 139 | } |
| 140 | if python.Name != "mcp-server-time" { |
| 141 | t.Fatalf("python module name = %q, want mcp-server-time", python.Name) |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | func TestParseMCPAddBareURL(t *testing.T) { |
| 146 | e, err := parseMCPAdd([]string{"https://mcp.example.com/path"}) |
| 147 | if err != nil { |
| 148 | t.Fatalf("unexpected error: %v", err) |
| 149 | } |
| 150 | if e.Type != "http" || e.URL != "https://mcp.example.com/path" { |
| 151 | t.Fatalf("type/url = %q/%q", e.Type, e.URL) |
| 152 | } |
| 153 | if e.Name != "mcp" { |
| 154 | t.Fatalf("name = %q, want mcp", e.Name) |
| 155 | } |
| 156 | } |
| 157 | |
| 158 | func TestTokenizeArgs(t *testing.T) { |
| 159 | got := tokenizeArgs(`/mcp add s --header "Authorization=Bearer abc" --http https://x`) |
| 160 | want := []string{"/mcp", "add", "s", "--header", "Authorization=Bearer abc", "--http", "https://x"} |
| 161 | if !reflect.DeepEqual(got, want) { |
| 162 | t.Fatalf("tokenizeArgs = %v, want %v", got, want) |
| 163 | } |
| 164 | // Single quotes work too, and surrounding whitespace collapses. |
| 165 | if got := tokenizeArgs(" a 'b c' d "); !reflect.DeepEqual(got, []string{"a", "b c", "d"}) { |
| 166 | t.Fatalf("tokenizeArgs single-quote = %v", got) |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | func TestMCPGetOpenDesignStyleInstall(t *testing.T) { |
| 171 | isolateCLIConfigHome(t) |
| 172 | stubMCPReadinessProbe(t) |
| 173 | |
| 174 | addOut := captureStdout(t, func() { |
| 175 | if rc := Run([]string{ |
| 176 | "mcp", "add", "open-design", |
| 177 | "--env", "OD_DAEMON_URL=http://127.0.0.1:7456", |
| 178 | "--env", "OPEN_DESIGN_TOKEN=placeholder-value", |
| 179 | "node", "open-design-mcp.js", "--stdio", |
| 180 | }, "test-version"); rc != 0 { |
| 181 | t.Fatalf("mcp add rc = %d, want 0", rc) |
| 182 | } |
| 183 | }) |
| 184 | if !strings.Contains(addOut, `added MCP server "open-design"`) { |
| 185 | t.Fatalf("mcp add output = %q", addOut) |
| 186 | } |
| 187 | |
| 188 | getOut := captureStdout(t, func() { |
| 189 | if rc := Run([]string{"mcp", "get", "open-design"}, "test-version"); rc != 0 { |
| 190 | t.Fatalf("mcp get rc = %d, want 0", rc) |
| 191 | } |
| 192 | }) |
| 193 | for _, want := range []string{ |
| 194 | "name: open-design", |
| 195 | "type: stdio", |
| 196 | "command: node", |
| 197 | "args: open-design-mcp.js", |
| 198 | " --stdio", |
| 199 | "OD_DAEMON_URL=http://127.0.0.1:7456", |
| 200 | "OPEN_DESIGN_TOKEN=<redacted>", |
| 201 | } { |
| 202 | if !strings.Contains(getOut, want) { |
| 203 | t.Fatalf("mcp get output missing %q:\n%s", want, getOut) |
| 204 | } |
| 205 | } |
| 206 | if strings.Contains(getOut, "placeholder-value") { |
| 207 | t.Fatalf("mcp get leaked sensitive env value:\n%s", getOut) |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | func TestMCPGetMissingServerFails(t *testing.T) { |
| 212 | isolateCLIConfigHome(t) |
| 213 | |
| 214 | errOut := captureStderr(t, func() { |
| 215 | if rc := Run([]string{"mcp", "get", "open-design"}, "test-version"); rc != 1 { |
| 216 | t.Fatalf("mcp get missing rc = %d, want 1", rc) |
| 217 | } |
| 218 | }) |
| 219 | if !strings.Contains(errOut, `no MCP server named "open-design"`) { |
| 220 | t.Fatalf("mcp get missing stderr = %q", errOut) |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | func TestMCPDisablePersistsProjectWorkspaceActivation(t *testing.T) { |
| 225 | isolateCLIConfigHome(t) |
| 226 | workspace := mcpCLIWorkspaceRoot() |
| 227 | if err := os.WriteFile(filepath.Join(workspace, "reasonix.toml"), []byte(` |
| 228 | [[plugins]] |
| 229 | name = "project-mcp" |
| 230 | command = "project-mcp" |
| 231 | `), 0o644); err != nil { |
| 232 | t.Fatal(err) |
| 233 | } |
| 234 | |
| 235 | captureStdout(t, func() { |
| 236 | if rc := mcpEnableCLI([]string{"project-mcp"}, false); rc != 0 { |
| 237 | t.Fatalf("mcp disable rc = %d, want 0", rc) |
| 238 | } |
| 239 | }) |
| 240 | cfg, err := config.LoadForRoot(workspace) |
| 241 | if err != nil { |
| 242 | t.Fatal(err) |
| 243 | } |
| 244 | entry := cfg.Plugins[0] |
| 245 | enabled, err := config.DefaultMCPActivationStore().IsEnabled(entry, workspace) |
| 246 | if err != nil { |
| 247 | t.Fatal(err) |
| 248 | } |
| 249 | if enabled { |
| 250 | t.Fatal("project MCP remained enabled after CLI disable") |
| 251 | } |
| 252 | scope, _, source, owner := config.ActivationIdentity(entry, workspace) |
| 253 | if _, found, err := config.DefaultMCPActivationStore().Lookup(scope, "", source, owner, entry.Name); err != nil { |
| 254 | t.Fatal(err) |
| 255 | } else if found { |
| 256 | t.Fatal("project MCP activation was incorrectly stored under an empty workspace fingerprint") |
| 257 | } |
| 258 | } |
| 259 | |
| 260 | func TestPersistCLIInstalledMCPAlwaysWritesGlobalConfig(t *testing.T) { |
| 261 | isolateCLIConfigHome(t) |
| 262 | workspace := mcpCLIWorkspaceRoot() |
| 263 | projectPath := filepath.Join(workspace, "reasonix.toml") |
| 264 | if err := os.WriteFile(projectPath, []byte(` |
| 265 | [[plugins]] |
| 266 | name = "project-mcp" |
| 267 | command = "project-mcp" |
| 268 | `), 0o644); err != nil { |
| 269 | t.Fatal(err) |
| 270 | } |
| 271 | if err := persistCLIInstalledMCP(workspace, config.PluginEntry{ |
| 272 | Name: "global-mcp", Command: "global-mcp", |
| 273 | }); err != nil { |
| 274 | t.Fatal(err) |
| 275 | } |
| 276 | |
| 277 | userCfg := config.LoadForEdit(config.UserConfigPath()) |
| 278 | if entry, ok := findCLIPlugin(userCfg.Plugins, "global-mcp"); !ok || entry.Command != "global-mcp" { |
| 279 | t.Fatalf("global config entry = %+v, found=%v", entry, ok) |
| 280 | } |
| 281 | projectCfg := config.LoadForEdit(projectPath) |
| 282 | if _, ok := findCLIPlugin(projectCfg.Plugins, "global-mcp"); ok { |
| 283 | t.Fatalf("CLI-installed global MCP leaked into project config: %+v", projectCfg.Plugins) |
| 284 | } |
| 285 | } |
| 286 | |
| 287 | func findCLIPlugin(entries []config.PluginEntry, name string) (config.PluginEntry, bool) { |
| 288 | for _, entry := range entries { |
| 289 | if entry.Name == name { |
| 290 | return entry, true |
| 291 | } |
| 292 | } |
| 293 | return config.PluginEntry{}, false |
| 294 | } |
| 295 | |
| 296 | func TestMCPUpdateProbesCandidateWithoutRewritingConfig(t *testing.T) { |
| 297 | isolateCLIConfigHome(t) |
| 298 | stubMCPReadinessProbe(t) |
| 299 | cfg, err := config.Load() |
| 300 | if err != nil { |
| 301 | t.Fatal(err) |
| 302 | } |
| 303 | entry := config.PluginEntry{Name: "chrome", Command: "npx", Args: []string{"-y", "chrome-devtools-mcp@latest"}} |
| 304 | if err := cfg.UpsertPlugin(entry); err != nil { |
| 305 | t.Fatal(err) |
| 306 | } |
| 307 | if err := cfg.Save(); err != nil { |
| 308 | t.Fatal(err) |
| 309 | } |
| 310 | |
| 311 | out := captureStdout(t, func() { |
| 312 | if rc := mcpUpdateCLI([]string{"chrome"}); rc != 0 { |
| 313 | t.Fatalf("mcp update rc = %d", rc) |
| 314 | } |
| 315 | }) |
| 316 | if !strings.Contains(out, "candidate handshake passed with 3 tools") { |
| 317 | t.Fatalf("mcp update output = %q", out) |
| 318 | } |
| 319 | after, err := config.Load() |
| 320 | if err != nil { |
| 321 | t.Fatal(err) |
| 322 | } |
| 323 | if len(after.Plugins) != 1 || !reflect.DeepEqual(after.Plugins[0].Args, entry.Args) { |
| 324 | t.Fatalf("candidate verification unexpectedly rewrote config: %+v", after.Plugins) |
| 325 | } |
| 326 | } |
| 327 | |
| 328 | func TestMCPBrowseAndInstallOfficialRegistryEntry(t *testing.T) { |
| 329 | isolateCLIConfigHome(t) |
| 330 | stubMCPReadinessProbe(t) |
| 331 | registry := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { |
| 332 | _ = json.NewEncoder(w).Encode(map[string]any{"servers": []any{map[string]any{"server": map[string]any{ |
| 333 | "name": "io.example/demo", "title": "Demo MCP", "version": "1.0.0", |
| 334 | "remotes": []any{map[string]any{"type": "streamable-http", "url": "https://mcp.example.test/mcp"}}, |
| 335 | }}}}) |
| 336 | })) |
| 337 | defer registry.Close() |
| 338 | client := mcpregistry.New("") |
| 339 | client.BaseURL = registry.URL |
| 340 | |
| 341 | browseOut := captureStdout(t, func() { |
| 342 | if rc := mcpBrowseWithClient([]string{"demo", "--limit", "5"}, client); rc != 0 { |
| 343 | t.Fatalf("mcp browse rc = %d", rc) |
| 344 | } |
| 345 | }) |
| 346 | for _, want := range []string{"io.example/demo", "1.0.0", "http", "Demo MCP"} { |
| 347 | if !strings.Contains(browseOut, want) { |
| 348 | t.Fatalf("mcp browse output missing %q: %s", want, browseOut) |
| 349 | } |
| 350 | } |
| 351 | |
| 352 | installOut := captureStdout(t, func() { |
| 353 | if rc := mcpInstallWithClient([]string{"io.example/demo", "--as", "demo-market"}, client); rc != 0 { |
| 354 | t.Fatalf("mcp install rc = %d", rc) |
| 355 | } |
| 356 | }) |
| 357 | if !strings.Contains(installOut, `installed MCP Registry server "io.example/demo" as "demo-market"`) { |
| 358 | t.Fatalf("mcp install output = %q", installOut) |
| 359 | } |
| 360 | cfg, err := config.Load() |
| 361 | if err != nil { |
| 362 | t.Fatal(err) |
| 363 | } |
| 364 | if len(cfg.Plugins) != 1 || cfg.Plugins[0].Name != "demo-market" || cfg.Plugins[0].Type != "http" || cfg.Plugins[0].URL != "https://mcp.example.test/mcp" { |
| 365 | t.Fatalf("installed plugins = %+v", cfg.Plugins) |
| 366 | } |
| 367 | } |
| 368 | |
| 369 | func TestMCPGetRedactsRemoteAuthMaterial(t *testing.T) { |
| 370 | isolateCLIConfigHome(t) |
| 371 | stubMCPReadinessProbe(t) |
| 372 | |
| 373 | _ = captureStdout(t, func() { |
| 374 | if rc := Run([]string{ |
| 375 | "mcp", "add", "stripe", |
| 376 | "--http", "https://mcp.example.test/mcp?access_token=abc&key=xyz&workspace=main", |
| 377 | "--header", "Authorization=Bearer abc", |
| 378 | }, "test-version"); rc != 0 { |
| 379 | t.Fatalf("mcp add remote rc = %d, want 0", rc) |
| 380 | } |
| 381 | }) |
| 382 | |
| 383 | getOut := captureStdout(t, func() { |
| 384 | if rc := Run([]string{"mcp", "get", "stripe"}, "test-version"); rc != 0 { |
| 385 | t.Fatalf("mcp get remote rc = %d, want 0", rc) |
| 386 | } |
| 387 | }) |
| 388 | for _, want := range []string{ |
| 389 | "type: http", |
| 390 | "workspace=main", |
| 391 | "access_token=%3Credacted%3E", |
| 392 | "key=%3Credacted%3E", |
| 393 | "Authorization=<redacted>", |
| 394 | } { |
| 395 | if !strings.Contains(getOut, want) { |
| 396 | t.Fatalf("mcp get remote output missing %q:\n%s", want, getOut) |
| 397 | } |
| 398 | } |
| 399 | if strings.Contains(getOut, "Bearer abc") || strings.Contains(getOut, "access_token=abc") || strings.Contains(getOut, "key=xyz") { |
| 400 | t.Fatalf("mcp get leaked remote auth material:\n%s", getOut) |
| 401 | } |
| 402 | } |
| 403 | |
| 404 | func TestRenderMCPStatusGroupsAndCompactsResources(t *testing.T) { |
| 405 | longURI := "file:///Users/example/project/docs/really/deep/path/with/a/very/long/resource-name.md" |
| 406 | got := renderMCPStatus(110, |
| 407 | []plugin.ServerStatus{{Name: "docs", Transport: "stdio", Tools: 2}}, |
| 408 | []plugin.Prompt{{Server: "docs", Name: "mcp__docs__summarize", Description: "Summarize a selected document for review"}}, |
| 409 | []plugin.Resource{{Server: "docs", URI: longURI, Name: "Resource manual", MimeType: "text/markdown"}}, |
| 410 | nil, |
| 411 | ) |
| 412 | for _, want := range []string{ |
| 413 | "MCP servers (1)", |
| 414 | "docs", |
| 415 | "prompts", |
| 416 | "/mcp__docs__summarize", |
| 417 | "resources", |
| 418 | "@docs:file:///", |
| 419 | "…", |
| 420 | "Resource manual [text/markdown]", |
| 421 | } { |
| 422 | if !strings.Contains(got, want) { |
| 423 | t.Fatalf("rendered MCP status missing %q:\n%s", want, got) |
| 424 | } |
| 425 | } |
| 426 | if strings.Contains(got, longURI) { |
| 427 | t.Fatalf("long resource URI should be compacted:\n%s", got) |
| 428 | } |
| 429 | } |
| 430 | |
| 431 | func TestRenderMCPStatusCapsLongSections(t *testing.T) { |
| 432 | var resources []plugin.Resource |
| 433 | for i := 0; i < mcpMaxItemsPerSection+2; i++ { |
| 434 | resources = append(resources, plugin.Resource{Server: "fs", URI: "file:///tmp/resource.md"}) |
| 435 | } |
| 436 | got := renderMCPStatus(80, |
| 437 | []plugin.ServerStatus{{Name: "fs", Transport: "stdio"}}, |
| 438 | nil, |
| 439 | resources, |
| 440 | nil, |
| 441 | ) |
| 442 | if !strings.Contains(got, "+2 more resources") { |
| 443 | t.Fatalf("rendered MCP status should cap long resource sections:\n%s", got) |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | func TestRenderMCPStatusShowsQuarantinedTools(t *testing.T) { |
| 448 | got := renderMCPStatus(200, |
| 449 | []plugin.ServerStatus{{ |
| 450 | Name: "yakit", Transport: "stdio", Tools: 1, |
| 451 | ToolList: []plugin.ToolInfo{ |
| 452 | {Name: "echo", Description: "available"}, |
| 453 | {Name: "generate_yso_bytes", SchemaError: "invalid input schema: bad type at /properties/options/items/type"}, |
| 454 | }, |
| 455 | }}, |
| 456 | nil, |
| 457 | nil, |
| 458 | nil, |
| 459 | ) |
| 460 | for _, want := range []string{"1 tool", "1 unavailable tool", "unavailable tools", "generate_yso_bytes", "invalid input schema"} { |
| 461 | if !strings.Contains(got, want) { |
| 462 | t.Fatalf("rendered MCP status missing %q:\n%s", want, got) |
| 463 | } |
| 464 | } |
| 465 | } |
| 466 | |
| 467 | func TestRenderMCPStatusShowsConfigSource(t *testing.T) { |
| 468 | got := renderMCPStatus(120, |
| 469 | []plugin.ServerStatus{{ |
| 470 | Name: "docs", Transport: "stdio", ConfigSource: "project_config", Tools: 1, |
| 471 | ToolList: []plugin.ToolInfo{{Name: "search", Description: "find docs"}}, |
| 472 | }}, |
| 473 | nil, nil, nil, |
| 474 | ) |
| 475 | for _, want := range []string{"docs", "source=project_config", "tools", "search", "source=project_config"} { |
| 476 | if !strings.Contains(got, want) { |
| 477 | t.Fatalf("rendered MCP status missing %q:\n%s", want, got) |
| 478 | } |
| 479 | } |
| 480 | } |
| 481 | |
| 482 | func TestRenderMCPStatusStripsControlSequencesFromExternalText(t *testing.T) { |
| 483 | // Malicious MCP description with CSI clear + OSC clipboard poke must not |
| 484 | // survive into the TUI payload. |
| 485 | evil := "safe\x1b[2J\x1b]52;c;AAAA\x07 payload" |
| 486 | got := renderMCPStatus(160, |
| 487 | []plugin.ServerStatus{{ |
| 488 | Name: "evil\x1b[31m", Transport: "stdio", ConfigSource: "user\x1b[0m", |
| 489 | Tools: 1, |
| 490 | ToolList: []plugin.ToolInfo{ |
| 491 | {Name: "ok", Description: evil}, |
| 492 | {Name: "bad", SchemaError: "schema\x1b[1merr"}, |
| 493 | }, |
| 494 | }}, |
| 495 | []plugin.Prompt{{Server: "evil", Name: "p", Description: "prompt\x1b[2J"}}, |
| 496 | []plugin.Resource{{Server: "evil", URI: "file:///x", Name: "res\x1b]0;x\x07"}}, |
| 497 | []plugin.Failure{{Name: "fail", Error: "boom\x1b[2J"}}, |
| 498 | ) |
| 499 | for _, ban := range []string{"\x1b", "\x07", "]52;", "[2J", "[31m", "[1m"} { |
| 500 | if strings.Contains(got, ban) { |
| 501 | t.Fatalf("control sequence %q leaked into MCP status:\n%q", ban, got) |
| 502 | } |
| 503 | } |
| 504 | if !strings.Contains(got, "safe") || !strings.Contains(got, "payload") { |
| 505 | t.Fatalf("sanitized description lost content:\n%s", got) |
| 506 | } |
| 507 | // Invalid tools must not appear under the ordinary tools list. |
| 508 | toolsIdx := strings.Index(got, "tools") |
| 509 | unavailIdx := strings.Index(got, "unavailable tools") |
| 510 | if toolsIdx < 0 || unavailIdx < 0 { |
| 511 | t.Fatalf("expected tools and unavailable sections:\n%s", got) |
| 512 | } |
| 513 | toolsSection := got[toolsIdx:unavailIdx] |
| 514 | if strings.Contains(toolsSection, "bad") { |
| 515 | t.Fatalf("invalid tool listed under tools:\n%s", toolsSection) |
| 516 | } |
| 517 | if !strings.Contains(got[unavailIdx:], "bad") { |
| 518 | t.Fatalf("invalid tool missing from unavailable:\n%s", got) |
| 519 | } |
| 520 | } |
| 521 | |
| 522 | func TestSanitizeExternalDisplayText(t *testing.T) { |
| 523 | in := "hello\x1b[2J\x1b]52;c;QQ\x07 world\n\t!" |
| 524 | got := sanitizeExternalDisplayText(in) |
| 525 | if strings.ContainsAny(got, "\x1b\x07\n\t") { |
| 526 | t.Fatalf("controls remain: %q", got) |
| 527 | } |
| 528 | if got != "hello world !" { |
| 529 | t.Fatalf("sanitize = %q", got) |
| 530 | } |
| 531 | } |
| 532 | |
| 533 | func TestMCPCapabilitiesTextUsesAdvertisedTools(t *testing.T) { |
| 534 | if got := mcpCapabilitiesText(mcpServerView{HasTools: true}); got != "tools" { |
| 535 | t.Fatalf("mcpCapabilitiesText = %q, want tools", got) |
| 536 | } |
| 537 | } |
| 538 | |
| 539 | func TestRenderMCPStatusShowsFailures(t *testing.T) { |
| 540 | got := renderMCPStatus(90, |
| 541 | nil, |
| 542 | nil, |
| 543 | nil, |
| 544 | []plugin.Failure{{Name: "broken", Transport: "stdio", Error: "npm error ENOENT"}}, |
| 545 | ) |
| 546 | for _, want := range []string{"MCP servers (0)", "broken", "npm error ENOENT"} { |
| 547 | if !strings.Contains(got, want) { |
| 548 | t.Fatalf("rendered MCP status missing %q:\n%s", want, got) |
| 549 | } |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | func TestRenderMCPManagerListGroupsRuntimeAndConfiguredServers(t *testing.T) { |
| 554 | p := &mcpManager{snapshot: mcpSnapshot{ |
| 555 | configPath: "config.toml", |
| 556 | servers: []mcpServerView{ |
| 557 | {Name: "managed-search", Transport: "stdio", Status: "connected", BuiltIn: true, Tools: 4}, |
| 558 | {Name: "project-docs", Transport: "http", Status: "deferred", Configured: true, Source: config.MCPSourceProjectConfig}, |
| 559 | {Name: "github", Transport: "stdio", Status: "deferred", Configured: true, Tier: "background", Tools: 12}, |
| 560 | {Name: "figma", Transport: "http", Status: "failed", Configured: true, Tier: "background", URL: "https://mcp.figma.com", Error: "connect: 401 unauthorized"}, |
| 561 | }, |
| 562 | }} |
| 563 | got := p.renderList(120) |
| 564 | for _, want := range []string{ |
| 565 | "Manage MCP servers", |
| 566 | "4 servers", |
| 567 | "Managed MCPs", |
| 568 | "Project MCPs", |
| 569 | "Global MCPs (config.toml)", |
| 570 | "managed-search", |
| 571 | "connected", |
| 572 | "project-docs", |
| 573 | "preparing in background", |
| 574 | "github", |
| 575 | "preparing in background", |
| 576 | "figma", |
| 577 | "needs authentication", |
| 578 | } { |
| 579 | if !strings.Contains(got, want) { |
| 580 | t.Fatalf("rendered MCP manager list missing %q:\n%s", want, got) |
| 581 | } |
| 582 | } |
| 583 | } |
| 584 | |
| 585 | func TestBuildMCPSnapshotUsesControllerWorkspaceAndPerServerConfigPaths(t *testing.T) { |
| 586 | isolateCLIConfigHome(t) |
| 587 | workspace := t.TempDir() |
| 588 | other := t.TempDir() |
| 589 | t.Chdir(other) |
| 590 | userPath := config.UserConfigPath() |
| 591 | userCfg := config.LoadForEdit(userPath) |
| 592 | userCfg.Plugins = []config.PluginEntry{ |
| 593 | {Name: "global-only", Command: "global-only"}, |
| 594 | {Name: "shared", Command: "global-shared"}, |
| 595 | } |
| 596 | if err := userCfg.SaveTo(userPath); err != nil { |
| 597 | t.Fatal(err) |
| 598 | } |
| 599 | projectPath := filepath.Join(workspace, "reasonix.toml") |
| 600 | if err := os.WriteFile(projectPath, []byte(` |
| 601 | [[plugins]] |
| 602 | name = "project-only" |
| 603 | command = "project-only" |
| 604 | `), 0o644); err != nil { |
| 605 | t.Fatal(err) |
| 606 | } |
| 607 | mcpJSONPath := filepath.Join(workspace, ".mcp.json") |
| 608 | if err := os.WriteFile(mcpJSONPath, []byte(`{ |
| 609 | "mcpServers": { |
| 610 | "shared": { "command": "project-shared" } |
| 611 | } |
| 612 | }`), 0o644); err != nil { |
| 613 | t.Fatal(err) |
| 614 | } |
| 615 | |
| 616 | ctrl := control.New(control.Options{WorkspaceRoot: workspace, Host: plugin.NewHost()}) |
| 617 | defer ctrl.Close() |
| 618 | m := newTestChatTUI() |
| 619 | m.ctrl = ctrl |
| 620 | m.host = ctrl.Host() |
| 621 | snapshot := m.buildMCPSnapshot() |
| 622 | byName := map[string]mcpServerView{} |
| 623 | for _, server := range snapshot.servers { |
| 624 | byName[server.Name] = server |
| 625 | } |
| 626 | if got := byName["global-only"]; got.Source != config.MCPSourceUserConfig || got.ConfigPath != userPath { |
| 627 | t.Fatalf("global-only view = %+v, want global source path %q", got, userPath) |
| 628 | } |
| 629 | if got := byName["project-only"]; got.Source != config.MCPSourceProjectConfig || got.ConfigPath != projectPath { |
| 630 | t.Fatalf("project-only view = %+v, want project source path %q", got, projectPath) |
| 631 | } |
| 632 | if got := byName["shared"]; got.Source != config.MCPSourceProjectMCPJSON || got.ConfigPath != mcpJSONPath || got.Command != "project-shared" { |
| 633 | t.Fatalf("shared view = %+v, want project .mcp.json to override global", got) |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | func TestMCPConfigPathForViewPrefersSelectedServerSource(t *testing.T) { |
| 638 | if got := mcpConfigPathForView(mcpServerView{ConfigPath: "/project/.mcp.json"}, "/global/config.toml"); got != "/project/.mcp.json" { |
| 639 | t.Fatalf("selected config path = %q", got) |
| 640 | } |
| 641 | if got := mcpConfigPathForView(mcpServerView{}, "/global/config.toml"); got != "/global/config.toml" { |
| 642 | t.Fatalf("fallback config path = %q", got) |
| 643 | } |
| 644 | } |
| 645 | |
| 646 | func TestRenderMCPManagerListCompactsLongNames(t *testing.T) { |
| 647 | p := &mcpManager{snapshot: mcpSnapshot{servers: []mcpServerView{ |
| 648 | {Name: "@modelcontextprotocol/server-sequential-thinking", Transport: "stdio", Status: "deferred", Configured: true, Tier: "background"}, |
| 649 | }}} |
| 650 | got := p.renderList(80) |
| 651 | for _, line := range strings.Split(got, "\n") { |
| 652 | if visibleWidth(line) > 80 { |
| 653 | t.Fatalf("line exceeds width 80 (%d): %q\n%s", visibleWidth(line), line, got) |
| 654 | } |
| 655 | } |
| 656 | if strings.Contains(got, "\n 0") || strings.Contains(got, "\n use") { |
| 657 | t.Fatalf("list row should not wrap status onto the next line:\n%s", got) |
| 658 | } |
| 659 | } |
| 660 | |
| 661 | func TestRenderMCPManagerAuthFailureActions(t *testing.T) { |
| 662 | p := &mcpManager{ |
| 663 | stage: mcpStageDetail, |
| 664 | name: "figma", |
| 665 | snapshot: mcpSnapshot{ |
| 666 | configPath: "reasonix.toml", |
| 667 | servers: []mcpServerView{{ |
| 668 | Name: "figma", Transport: "http", Status: "failed", Configured: true, |
| 669 | Tier: "background", URL: "https://mcp.figma.com", Error: "connect: 401 unauthorized", |
| 670 | }}, |
| 671 | }, |
| 672 | } |
| 673 | got := p.renderDetail(120) |
| 674 | for _, want := range []string{ |
| 675 | "Figma MCP Server", |
| 676 | "needs authentication", |
| 677 | "not authenticated", |
| 678 | "Authenticate", |
| 679 | "Clear authentication", |
| 680 | "View logs", |
| 681 | "Edit config", |
| 682 | "Remove server", |
| 683 | } { |
| 684 | if !strings.Contains(got, want) { |
| 685 | t.Fatalf("rendered auth failure details missing %q:\n%s", want, got) |
| 686 | } |
| 687 | } |
| 688 | if strings.Contains(got, "Retry") { |
| 689 | t.Fatalf("auth failures should prefer Authenticate over Retry:\n%s", got) |
| 690 | } |
| 691 | } |
| 692 | |
| 693 | func TestRenderMCPManagerProjectServerIsReadyWithoutInstallAction(t *testing.T) { |
| 694 | p := &mcpManager{ |
| 695 | stage: mcpStageDetail, |
| 696 | name: "project-docs", |
| 697 | snapshot: mcpSnapshot{ |
| 698 | configPath: "reasonix.toml", |
| 699 | servers: []mcpServerView{{ |
| 700 | Name: "project-docs", Transport: "http", Status: "connected", Configured: true, |
| 701 | Source: config.MCPSourceProjectConfig, URL: "https://example.test/mcp", |
| 702 | Tools: 2, HasTools: true, |
| 703 | }}, |
| 704 | }, |
| 705 | } |
| 706 | got := p.renderDetail(120) |
| 707 | for _, want := range []string{ |
| 708 | "connected", |
| 709 | "current project reasonix.toml", |
| 710 | "View tools", |
| 711 | "Disable for this session", |
| 712 | } { |
| 713 | if !strings.Contains(got, want) { |
| 714 | t.Fatalf("rendered project MCP details missing %q:\n%s", want, got) |
| 715 | } |
| 716 | } |
| 717 | if strings.Contains(got, "Install and use") || strings.Contains(got, "Authorize") { |
| 718 | t.Fatalf("trusted project MCP must not expose an installation or authorization action:\n%s", got) |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | func TestRenderMCPManagerClearAuthConfirmation(t *testing.T) { |
| 723 | p := &mcpManager{ |
| 724 | stage: mcpStageConfirmClearAuth, |
| 725 | name: "figma", |
| 726 | confirm: 1, |
| 727 | snapshot: mcpSnapshot{ |
| 728 | servers: []mcpServerView{{ |
| 729 | Name: "figma", Transport: "http", Status: "failed", Configured: true, |
| 730 | Tier: "background", URL: "https://mcp.figma.com", Error: "connect: 401 unauthorized", |
| 731 | }}, |
| 732 | }, |
| 733 | } |
| 734 | got := p.renderConfirmClearAuth(120) |
| 735 | for _, want := range []string{ |
| 736 | "Clear authentication for MCP server \"figma\"?", |
| 737 | "Confirm clear authentication", |
| 738 | "Cancel", |
| 739 | } { |
| 740 | if !strings.Contains(got, want) { |
| 741 | t.Fatalf("rendered clear-auth confirmation missing %q:\n%s", want, got) |
| 742 | } |
| 743 | } |
| 744 | if hint := p.footerHint(); !strings.Contains(hint, "y confirm") { |
| 745 | t.Fatalf("clear-auth footer hint missing confirm shortcut: %q", hint) |
| 746 | } |
| 747 | } |
| 748 | |
| 749 | func TestRenderMCPManagerRemoteDeferredAuthHint(t *testing.T) { |
| 750 | p := &mcpManager{ |
| 751 | stage: mcpStageDetail, |
| 752 | name: "dida", |
| 753 | snapshot: mcpSnapshot{ |
| 754 | configPath: "reasonix.toml", |
| 755 | servers: []mcpServerView{{ |
| 756 | Name: "dida", Transport: "http", Status: "deferred", Configured: true, |
| 757 | Tier: "background", URL: "https://mcp.dida365.com", |
| 758 | }}, |
| 759 | }, |
| 760 | } |
| 761 | got := p.renderDetail(100) |
| 762 | for _, want := range []string{ |
| 763 | "preparing in background", |
| 764 | "Auth:", |
| 765 | "may need authorization", |
| 766 | "Reconnect", |
| 767 | } { |
| 768 | if !strings.Contains(got, want) { |
| 769 | t.Fatalf("rendered deferred remote details missing %q:\n%s", want, got) |
| 770 | } |
| 771 | } |
| 772 | if strings.Contains(got, "Connect now") { |
| 773 | t.Fatalf("automatic background MCP should not expose manual connect:\n%s", got) |
| 774 | } |
| 775 | if strings.Contains(got, "Authenticate") { |
| 776 | t.Fatalf("possible auth should not replace connect action before a failure:\n%s", got) |
| 777 | } |
| 778 | } |
| 779 | |
| 780 | func TestRenderMCPManagerDetailCompactsConfigPath(t *testing.T) { |
| 781 | p := &mcpManager{ |
| 782 | stage: mcpStageDetail, |
| 783 | name: "github", |
| 784 | snapshot: mcpSnapshot{ |
| 785 | configPath: "/Users/example/Library/Application Support/reasonix/config.toml", |
| 786 | servers: []mcpServerView{{ |
| 787 | Name: "github", Transport: "stdio", Status: "deferred", Configured: true, |
| 788 | Tier: "background", Command: "npx", Args: []string{"-y", "@modelcontextprotocol/server-github"}, |
| 789 | }}, |
| 790 | }, |
| 791 | } |
| 792 | got := p.renderDetail(80) |
| 793 | for _, line := range strings.Split(got, "\n") { |
| 794 | if visibleWidth(line) > 80 { |
| 795 | t.Fatalf("detail line exceeds width 80 (%d): %q\n%s", visibleWidth(line), line, got) |
| 796 | } |
| 797 | } |
| 798 | if strings.Contains(got, "Application Support/reasonix/config.toml") { |
| 799 | t.Fatalf("long config path should be compacted:\n%s", got) |
| 800 | } |
| 801 | } |
| 802 | |
| 803 | func TestMCPEditConfigLaunchUsesVisualBeforeEditor(t *testing.T) { |
| 804 | t.Setenv("VISUAL", "vim") |
| 805 | t.Setenv("EDITOR", "nano") |
| 806 | |
| 807 | path := "/tmp/reasonix config.toml" |
| 808 | launch, err := mcpEditConfigLaunchCommand(path, func(string) (string, error) { |
| 809 | t.Fatal("lookPath should not be called when VISUAL is set") |
| 810 | return "", errors.New("unexpected lookup") |
| 811 | }) |
| 812 | if err != nil { |
| 813 | t.Fatalf("edit command: %v", err) |
| 814 | } |
| 815 | if launch.systemDefault { |
| 816 | t.Fatalf("VISUAL should not use system default: %+v", launch) |
| 817 | } |
| 818 | if launch.editor != "vim" { |
| 819 | t.Fatalf("editor = %q, want vim", launch.editor) |
| 820 | } |
| 821 | // VISUAL must run the editor binary directly (not via sh -lc) so that |
| 822 | // shell metacharacters in the env value cannot be executed. argv is |
| 823 | // [editorBinary, path]. |
| 824 | if len(launch.cmd.Args) != 2 || launch.cmd.Args[0] != "vim" || launch.cmd.Args[1] != path { |
| 825 | t.Fatalf("VISUAL should invoke editor binary directly, args=%v", launch.cmd.Args) |
| 826 | } |
| 827 | } |
| 828 | |
| 829 | // TestMCPEditConfigLaunchEditorWithArgs confirms that an EDITOR/VISUAL value |
| 830 | // carrying arguments (e.g. "code --wait") is split into argv correctly and |
| 831 | // the path is appended as the final argument, without going through a shell. |
| 832 | func TestMCPEditConfigLaunchEditorWithArgs(t *testing.T) { |
| 833 | t.Setenv("VISUAL", "code --wait") |
| 834 | t.Setenv("EDITOR", "") |
| 835 | |
| 836 | path := "/tmp/reasonix.toml" |
| 837 | launch, err := mcpEditConfigLaunchCommand(path, func(string) (string, error) { |
| 838 | t.Fatal("lookPath should not be called when VISUAL is set") |
| 839 | return "", errors.New("unexpected lookup") |
| 840 | }) |
| 841 | if err != nil { |
| 842 | t.Fatalf("edit command: %v", err) |
| 843 | } |
| 844 | if launch.editor != "code" { |
| 845 | t.Fatalf("editor display name = %q, want code", launch.editor) |
| 846 | } |
| 847 | want := []string{"code", "--wait", path} |
| 848 | if len(launch.cmd.Args) != len(want) { |
| 849 | t.Fatalf("args length = %d, want %d, args=%v", len(launch.cmd.Args), len(want), launch.cmd.Args) |
| 850 | } |
| 851 | for i, w := range want { |
| 852 | if launch.cmd.Args[i] != w { |
| 853 | t.Fatalf("args[%d] = %q, want %q, full args=%v", i, launch.cmd.Args[i], w, launch.cmd.Args) |
| 854 | } |
| 855 | } |
| 856 | } |
| 857 | |
| 858 | func TestMCPEditConfigLaunchEditorParsesShellStyleQuotes(t *testing.T) { |
| 859 | path := "/tmp/reasonix.toml" |
| 860 | cases := []struct { |
| 861 | name string |
| 862 | editor string |
| 863 | wantEditor string |
| 864 | wantArgs []string |
| 865 | }{ |
| 866 | { |
| 867 | name: "empty fallback arg", |
| 868 | editor: "emacsclient -c -a ''", |
| 869 | wantEditor: "emacsclient", |
| 870 | wantArgs: []string{"emacsclient", "-c", "-a", "", path}, |
| 871 | }, |
| 872 | { |
| 873 | name: "quoted editor path", |
| 874 | editor: "'/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code' --wait", |
| 875 | wantEditor: "/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code", |
| 876 | wantArgs: []string{"/Applications/Visual Studio Code.app/Contents/Resources/app/bin/code", "--wait", path}, |
| 877 | }, |
| 878 | { |
| 879 | name: "escaped whitespace", |
| 880 | editor: `/opt/My\ Editor/bin/edit --flag`, |
| 881 | wantEditor: "/opt/My Editor/bin/edit", |
| 882 | wantArgs: []string{"/opt/My Editor/bin/edit", "--flag", path}, |
| 883 | }, |
| 884 | { |
| 885 | name: "quoted arg", |
| 886 | editor: `nvim --cmd "set tabstop=2"`, |
| 887 | wantEditor: "nvim", |
| 888 | wantArgs: []string{"nvim", "--cmd", "set tabstop=2", path}, |
| 889 | }, |
| 890 | { |
| 891 | name: "double quoted literal backslashes", |
| 892 | editor: `nvim "C:\tmp\file"`, |
| 893 | wantEditor: "nvim", |
| 894 | wantArgs: []string{"nvim", `C:\tmp\file`, path}, |
| 895 | }, |
| 896 | } |
| 897 | for _, c := range cases { |
| 898 | t.Run(c.name, func(t *testing.T) { |
| 899 | t.Setenv("VISUAL", c.editor) |
| 900 | t.Setenv("EDITOR", "") |
| 901 | launch, err := mcpEditConfigLaunchCommand(path, func(string) (string, error) { |
| 902 | t.Fatal("lookPath should not be called when VISUAL is set") |
| 903 | return "", errors.New("unexpected lookup") |
| 904 | }) |
| 905 | if err != nil { |
| 906 | t.Fatalf("edit command: %v", err) |
| 907 | } |
| 908 | if launch.editor != c.wantEditor { |
| 909 | t.Fatalf("editor display name = %q, want %q", launch.editor, c.wantEditor) |
| 910 | } |
| 911 | if !reflect.DeepEqual(launch.cmd.Args, c.wantArgs) { |
| 912 | t.Fatalf("args = %#v, want %#v", launch.cmd.Args, c.wantArgs) |
| 913 | } |
| 914 | }) |
| 915 | } |
| 916 | } |
| 917 | |
| 918 | func TestMCPEditConfigLaunchEditorRejectsUnterminatedQuote(t *testing.T) { |
| 919 | t.Setenv("VISUAL", `code --wait "unterminated`) |
| 920 | t.Setenv("EDITOR", "") |
| 921 | |
| 922 | _, err := mcpEditConfigLaunchCommand("/tmp/reasonix.toml", func(string) (string, error) { |
| 923 | t.Fatal("lookPath should not be called when VISUAL is set") |
| 924 | return "", errors.New("unexpected lookup") |
| 925 | }) |
| 926 | if err == nil { |
| 927 | t.Fatal("expected unterminated quote error") |
| 928 | } |
| 929 | } |
| 930 | |
| 931 | // TestMCPEditConfigLaunchEditorRejectsShellMetachars confirms that shell |
| 932 | // metacharacters in EDITOR/VISUAL are rejected before launch — the previous |
| 933 | // sh -lc construction would have run "rm" here. |
| 934 | func TestMCPEditConfigLaunchEditorRejectsShellMetachars(t *testing.T) { |
| 935 | t.Setenv("VISUAL", "") |
| 936 | t.Setenv("EDITOR", "vim; rm -rf /tmp/should-not-exist") |
| 937 | |
| 938 | path := "/tmp/reasonix.toml" |
| 939 | _, err := mcpEditConfigLaunchCommand(path, func(string) (string, error) { |
| 940 | t.Fatal("lookPath should not be called when EDITOR is set") |
| 941 | return "", errors.New("unexpected lookup") |
| 942 | }) |
| 943 | if err == nil || !strings.Contains(err.Error(), "shell control syntax") { |
| 944 | t.Fatalf("expected shell control rejection, got %v", err) |
| 945 | } |
| 946 | } |
| 947 | |
| 948 | // TestMCPEditConfigLaunchEditorExpandsEnvVar confirms that $VAR references |
| 949 | // in EDITOR/VISUAL are expanded without going through a shell, preserving |
| 950 | // the behavior of the prior sh -lc path for users who set values such as |
| 951 | // EDITOR="$HOME/bin/myeditor" verbatim (rather than relying on the shell |
| 952 | // to expand at export time). |
| 953 | func TestMCPEditConfigLaunchEditorExpandsEnvVar(t *testing.T) { |
| 954 | t.Setenv("REASONIX_TEST_EDITOR_BIN", "/opt/custom/bin/myed") |
| 955 | t.Setenv("VISUAL", "$REASONIX_TEST_EDITOR_BIN --flag") |
| 956 | t.Setenv("EDITOR", "") |
| 957 | |
| 958 | path := "/tmp/reasonix.toml" |
| 959 | launch, err := mcpEditConfigLaunchCommand(path, func(string) (string, error) { |
| 960 | t.Fatal("lookPath should not be called when VISUAL is set") |
| 961 | return "", errors.New("unexpected lookup") |
| 962 | }) |
| 963 | if err != nil { |
| 964 | t.Fatalf("edit command: %v", err) |
| 965 | } |
| 966 | want := []string{"/opt/custom/bin/myed", "--flag", path} |
| 967 | if len(launch.cmd.Args) != len(want) { |
| 968 | t.Fatalf("args length = %d, want %d, args=%v", len(launch.cmd.Args), len(want), launch.cmd.Args) |
| 969 | } |
| 970 | for i, w := range want { |
| 971 | if launch.cmd.Args[i] != w { |
| 972 | t.Fatalf("args[%d] = %q, want %q, full args=%v", i, launch.cmd.Args[i], w, launch.cmd.Args) |
| 973 | } |
| 974 | } |
| 975 | } |
| 976 | |
| 977 | // TestMCPEditConfigLaunchEditorExpandsTilde confirms that a leading ~ or ~/ |
| 978 | // in EDITOR/VISUAL is expanded to the user's home directory without a shell. |
| 979 | func TestMCPEditConfigLaunchEditorExpandsTilde(t *testing.T) { |
| 980 | home, err := os.UserHomeDir() |
| 981 | if err != nil { |
| 982 | t.Skipf("cannot determine home dir: %v", err) |
| 983 | } |
| 984 | cases := []struct { |
| 985 | name string |
| 986 | editor string |
| 987 | want0 string |
| 988 | }{ |
| 989 | {"tilde_slash", "~/bin/myed", home + "/bin/myed"}, |
| 990 | {"bare_tilde", "~", home}, |
| 991 | } |
| 992 | for _, c := range cases { |
| 993 | t.Run(c.name, func(t *testing.T) { |
| 994 | t.Setenv("VISUAL", c.editor+" --wait") |
| 995 | t.Setenv("EDITOR", "") |
| 996 | launch, err := mcpEditConfigLaunchCommand("/tmp/reasonix.toml", func(string) (string, error) { |
| 997 | t.Fatal("lookPath should not be called when VISUAL is set") |
| 998 | return "", errors.New("unexpected lookup") |
| 999 | }) |
| 1000 | if err != nil { |
| 1001 | t.Fatalf("edit command: %v", err) |
| 1002 | } |
| 1003 | if launch.cmd.Args[0] != c.want0 { |
| 1004 | t.Fatalf("args[0] = %q, want %q", launch.cmd.Args[0], c.want0) |
| 1005 | } |
| 1006 | if launch.cmd.Args[1] != "--wait" { |
| 1007 | t.Fatalf("args[1] = %q, want --wait", launch.cmd.Args[1]) |
| 1008 | } |
| 1009 | }) |
| 1010 | } |
| 1011 | } |
| 1012 | |
| 1013 | // TestMCPEditConfigLaunchEditorTildeNotInPayload confirms that a tilde |
| 1014 | // appearing in an injection payload cannot be used because shell control syntax |
| 1015 | // is rejected before any expansion beyond the leading editor token matters. |
| 1016 | func TestMCPEditConfigLaunchEditorTildeNotInPayload(t *testing.T) { |
| 1017 | t.Setenv("VISUAL", "") |
| 1018 | t.Setenv("EDITOR", "vim; rm -rf ~/should-not-exist") |
| 1019 | |
| 1020 | _, err := mcpEditConfigLaunchCommand("/tmp/reasonix.toml", func(string) (string, error) { |
| 1021 | t.Fatal("lookPath should not be called when EDITOR is set") |
| 1022 | return "", errors.New("unexpected lookup") |
| 1023 | }) |
| 1024 | if err == nil || !strings.Contains(err.Error(), "shell control syntax") { |
| 1025 | t.Fatalf("expected shell control rejection, got %v", err) |
| 1026 | } |
| 1027 | } |
| 1028 | |
| 1029 | func TestMCPEditConfigLaunchFallsBackToTerminalEditor(t *testing.T) { |
| 1030 | t.Setenv("VISUAL", "") |
| 1031 | t.Setenv("EDITOR", "") |
| 1032 | |
| 1033 | launch, err := mcpEditConfigLaunchCommand("/tmp/reasonix.toml", func(name string) (string, error) { |
| 1034 | if name == "vim" { |
| 1035 | return "/usr/bin/vim", nil |
| 1036 | } |
| 1037 | return "", errors.New("not found") |
| 1038 | }) |
| 1039 | if err != nil { |
| 1040 | t.Fatalf("edit command: %v", err) |
| 1041 | } |
| 1042 | if launch.systemDefault { |
| 1043 | t.Fatalf("terminal editor fallback should not use system default: %+v", launch) |
| 1044 | } |
| 1045 | if launch.editor != "vim" { |
| 1046 | t.Fatalf("editor = %q, want vim", launch.editor) |
| 1047 | } |
| 1048 | if len(launch.cmd.Args) != 2 || launch.cmd.Args[0] != "/usr/bin/vim" || launch.cmd.Args[1] != "/tmp/reasonix.toml" { |
| 1049 | t.Fatalf("terminal editor args=%v", launch.cmd.Args) |
| 1050 | } |
| 1051 | } |
| 1052 | |
| 1053 | func TestMCPEditConfigLaunchUsesSystemDefaultLast(t *testing.T) { |
| 1054 | t.Setenv("VISUAL", "") |
| 1055 | t.Setenv("EDITOR", "") |
| 1056 | |
| 1057 | path := "/tmp/reasonix.toml" |
| 1058 | launch, err := mcpEditConfigLaunchCommand(path, func(string) (string, error) { |
| 1059 | return "", errors.New("not found") |
| 1060 | }) |
| 1061 | if err != nil { |
| 1062 | t.Fatalf("edit command: %v", err) |
| 1063 | } |
| 1064 | if !launch.systemDefault { |
| 1065 | t.Fatalf("missing terminal editors should use system default: %+v", launch) |
| 1066 | } |
| 1067 | want, err := mcpOpenCommand(path) |
| 1068 | if err != nil { |
| 1069 | t.Fatalf("open command: %v", err) |
| 1070 | } |
| 1071 | if len(launch.cmd.Args) == 0 || len(want.Args) == 0 || launch.cmd.Args[0] != want.Args[0] { |
| 1072 | t.Fatalf("system default command = %v, want command starting with %v", launch.cmd.Args, want.Args) |
| 1073 | } |
| 1074 | } |
| 1075 | |
| 1076 | func TestApplyMCPModeDropsLegacyTier(t *testing.T) { |
| 1077 | isolateUserConfig(t) |
| 1078 | cfg := config.Default() |
| 1079 | cfg.Plugins = []config.PluginEntry{{Name: "github", Command: "npx", Args: []string{"server"}, Tier: "lazy"}} |
| 1080 | if err := cfg.SaveTo("reasonix.toml"); err != nil { |
| 1081 | t.Fatalf("save config: %v", err) |
| 1082 | } |
| 1083 | |
| 1084 | m := newTestChatTUI() |
| 1085 | m.mcp = &mcpManager{ |
| 1086 | stage: mcpStageMode, |
| 1087 | name: "github", |
| 1088 | snapshot: mcpSnapshot{configPath: "reasonix.toml", servers: []mcpServerView{{ |
| 1089 | Name: "github", Transport: "stdio", Status: "deferred", Configured: true, Tier: "background", |
| 1090 | }}}, |
| 1091 | } |
| 1092 | _, _ = m.applyMCPMode("background") |
| 1093 | |
| 1094 | loaded, err := config.Load() |
| 1095 | if err != nil { |
| 1096 | t.Fatalf("load config: %v", err) |
| 1097 | } |
| 1098 | if len(loaded.Plugins) != 1 || loaded.Plugins[0].Tier != "" { |
| 1099 | t.Fatalf("tier should be migrated away, plugins=%+v", loaded.Plugins) |
| 1100 | } |
| 1101 | raw, err := os.ReadFile("reasonix.toml") |
| 1102 | if err != nil { |
| 1103 | t.Fatalf("read config: %v", err) |
| 1104 | } |
| 1105 | if strings.Contains(string(raw), "\ntier") { |
| 1106 | t.Fatalf("legacy tier should not be written back:\n%s", raw) |
| 1107 | } |
| 1108 | } |
| 1109 | |
| 1110 | func TestApplyMCPModeRecordsPluginConnectFailure(t *testing.T) { |
| 1111 | isolateUserConfig(t) |
| 1112 | t.Setenv("PATH", "") |
| 1113 | cfg := config.Default() |
| 1114 | cfg.Plugins = []config.PluginEntry{{Name: "broken", Command: "definitely-missing-reasonix-mcp", Tier: "background"}} |
| 1115 | if err := cfg.SaveTo("reasonix.toml"); err != nil { |
| 1116 | t.Fatalf("save config: %v", err) |
| 1117 | } |
| 1118 | |
| 1119 | m := newTestChatTUI() |
| 1120 | m.ctrl = control.New(control.Options{Host: plugin.NewHost()}) |
| 1121 | defer m.ctrl.Close() |
| 1122 | m.host = m.ctrl.Host() |
| 1123 | m.mcp = &mcpManager{ |
| 1124 | stage: mcpStageMode, |
| 1125 | name: "broken", |
| 1126 | snapshot: mcpSnapshot{configPath: "reasonix.toml", servers: []mcpServerView{{ |
| 1127 | Name: "broken", Transport: "stdio", Status: "deferred", Configured: true, Tier: "background", |
| 1128 | }}}, |
| 1129 | } |
| 1130 | |
| 1131 | _, _ = m.applyMCPMode("background") |
| 1132 | |
| 1133 | failures := m.ctrl.Host().Failures() |
| 1134 | if len(failures) != 1 || failures[0].Name != "broken" { |
| 1135 | t.Fatalf("Host.Failures() = %+v, want broken failure", failures) |
| 1136 | } |
| 1137 | v, ok := m.mcp.selectedServer() |
| 1138 | if !ok { |
| 1139 | t.Fatal("selected server missing after refresh") |
| 1140 | } |
| 1141 | if v.Status != "failed" { |
| 1142 | t.Fatalf("server status = %q, want failed; server = %+v", v.Status, v) |
| 1143 | } |
| 1144 | } |
| 1145 | |
| 1146 | func TestMCPManagerEscFromDetailReturnsToList(t *testing.T) { |
| 1147 | m := newTestChatTUI() |
| 1148 | m.mcp = &mcpManager{ |
| 1149 | stage: mcpStageDetail, |
| 1150 | name: "managed-search", |
| 1151 | snapshot: mcpSnapshot{servers: []mcpServerView{{ |
| 1152 | Name: "managed-search", Transport: "stdio", Status: "connected", BuiltIn: true, |
| 1153 | }}}, |
| 1154 | } |
| 1155 | |
| 1156 | got, _ := m.handleMCPManagerKey(tea.KeyPressMsg{Code: tea.KeyEscape}) |
| 1157 | next := got.(chatTUI) |
| 1158 | if next.mcp == nil || next.mcp.stage != mcpStageList { |
| 1159 | t.Fatalf("Esc from detail should return to list, got %#v", next.mcp) |
| 1160 | } |
| 1161 | } |
| 1162 |