supercode-cli 0.4.15

supercode — a lightweight, fully-customizable AI coding agent CLI in Rust. Any model via OpenRouter; natively continues Claude Code and Codex sessions.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
//! UX-27: first-run / on-demand import of MCP server definitions from
//! sibling coding-agent harnesses (Claude Code, Codex) into supercode's own
//! MCP registry (`userconfig::McpServers`).
//!
//! Zero-config borrowing of a sibling harness's MCP config is exactly the
//! "interop glue tool" promise supercode is built on — see AGENTS.md. This
//! module only *reads* sibling config and produces a plan; callers
//! (`main.rs`'s `mcp import` subcommand and the first-run offer in
//! `attach_mcp`) decide whether/how to apply it via [`apply`], which never
//! overwrites an existing supercode entry.
//!
//! Source shapes (verified against a real `~/.claude.json` on a dev box —
//! see the UX-27 build report for the inspection transcript):
//! - **Claude Code** `~/.claude.json`: top-level `mcpServers` (global) *and*
//!   per-project `projects."<abs-path>".mcpServers`, plus the standalone
//!   `~/.claude/mcp.json` and `~/.mcp.json` files — all the same
//!   `{ "<name>": { "command", "args", "env"? } }` (or `{"type": "http"|"sse",
//!   "url", ...}`) shape Claude Code's own `--mcp-config` files use.
//! - **Codex** `~/.codex/config.toml`: `[mcp_servers.<name>]` tables with
//!   `command`, `args`, `env` (documented shape — no Codex config was
//!   present on the build box to inspect directly; see the build report).
//!
//! supercode's own MCP schema ([`crate::userconfig::McpServerDef`]) is
//! `{ command, args, env? }` — `env` is imported faithfully (MCP-env
//! follow-up to this ticket; see the UX-27 tracker's "Deferred/out of
//! scope" note, now resolved). `url`/http/sse is still unsupported: those
//! servers are recognized and skipped with a reason, never silently
//! dropped or fabricated as stdio.

use std::collections::BTreeMap;
use std::path::{Path, PathBuf};

use serde_json::Value as JsonValue;

use crate::userconfig::McpServerDef;

/// Which sibling harness a candidate/skip came from.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Source {
    Claude,
    Codex,
}

impl Source {
    pub fn label(self) -> &'static str {
        match self {
            Source::Claude => "claude",
            Source::Codex => "codex",
        }
    }
}

/// A stdio server discovered in a sibling harness's config, ready to import
/// as-is into supercode's `{ command, args }` schema.
#[derive(Debug, Clone)]
pub struct Candidate {
    pub name: String,
    pub def: McpServerDef,
    pub source: Source,
    /// Where in the source config this came from (e.g. a project path), for
    /// a legible import summary. Purely informational.
    pub origin: String,
    /// Non-fatal fidelity notes for this entry. `env` vars are now imported
    /// faithfully (no longer a fidelity loss), so this is currently unused
    /// by either source scanner, but stays as the general escape hatch for
    /// any future partial-fidelity import — both callers print these
    /// alongside the candidate: `mcp_import_cmd`'s `for note in &c.notes`
    /// loop, and the first-run offer's `first_run_candidate_lines` (see
    /// `main.rs`) — before the import (or the first-run confirmation
    /// prompt) happens.
    pub notes: Vec<String>,
}

/// A source entry that was recognized but NOT imported (unsupported
/// transport, or unparseable), with a human reason. Always surfaced — never
/// silently dropped.
#[derive(Debug, Clone)]
pub struct SkippedEntry {
    pub name: String,
    pub source: Source,
    pub reason: String,
}

/// The result of scanning sibling-harness configs: what CAN be imported,
/// and what was recognized but can't be (with why).
#[derive(Debug, Default, Clone)]
pub struct ScanReport {
    pub candidates: Vec<Candidate>,
    pub skipped: Vec<SkippedEntry>,
}

/// What actually happened when a [`ScanReport`] was applied to an existing
/// registry via [`apply`].
#[derive(Debug, Default, Clone)]
pub struct ApplyOutcome {
    /// Names newly written into the registry.
    pub imported: Vec<String>,
    /// Names that already existed in the registry — left untouched
    /// (never-clobber guarantee).
    pub already_present: Vec<String>,
}

enum ParsedEntry {
    // Boxed: `McpServerDef` grew past clippy's large-enum-variant threshold
    // once P5-2 added the remote-transport/OAuth fields (§2 module 15) —
    // `Unsupported`'s `String` is comparatively tiny, so without boxing
    // every `ParsedEntry` (including every `Unsupported` one) would pay
    // `McpServerDef`'s full size.
    Stdio(Box<McpServerDef>, Vec<String>),
    Unsupported(String),
}

/// `$HOME` for the CURRENT process (not supercode's own `SUPERCODE_HOME` —
/// deliberately independent, so a test/CI harness can point supercode's own
/// config at one temp dir while pointing sibling-harness discovery at
/// another, real or fixture, `$HOME`).
pub fn home_dir() -> Option<PathBuf> {
    std::env::var_os("HOME")
        .filter(|h| !h.is_empty())
        .map(PathBuf::from)
}

/// Scan both Claude Code and Codex sources under `home` and classify every
/// entry found into candidates/skips (dedup by name: first source to define
/// a name wins; a later duplicate — same or different harness — is
/// recorded as skipped rather than silently overwriting the plan).
pub fn scan_all(home: &Path) -> ScanReport {
    let mut entries = raw_claude_entries(home);
    entries.extend(raw_codex_entries(home));
    classify(entries)
}

fn classify(entries: Vec<(String, Source, String, ParsedEntry)>) -> ScanReport {
    let mut report = ScanReport::default();
    let mut seen: BTreeMap<String, Source> = BTreeMap::new();
    for (name, source, origin, parsed) in entries {
        if let Some(prev) = seen.get(&name) {
            report.skipped.push(SkippedEntry {
                name,
                source,
                reason: format!("duplicate server name (already found via {})", prev.label()),
            });
            continue;
        }
        match parsed {
            ParsedEntry::Stdio(def, notes) => {
                seen.insert(name.clone(), source);
                report.candidates.push(Candidate {
                    name,
                    def: *def,
                    source,
                    origin,
                    notes,
                });
            }
            ParsedEntry::Unsupported(reason) => {
                // Don't mark unsupported entries as "seen" — if a LATER
                // source defines the same name as an importable stdio
                // server, it should still be picked up.
                report.skipped.push(SkippedEntry {
                    name,
                    source,
                    reason,
                });
            }
        }
    }
    report
}

/// Scan only Claude Code sources.
pub fn scan_claude(home: &Path) -> ScanReport {
    classify(raw_claude_entries(home))
}

/// Scan only Codex sources.
pub fn scan_codex(home: &Path) -> ScanReport {
    classify(raw_codex_entries(home))
}

fn raw_claude_entries(home: &Path) -> Vec<(String, Source, String, ParsedEntry)> {
    let mut out = Vec::new();

    // `~/.claude.json`: top-level `mcpServers` (global) + per-project
    // `projects.<abs-path>.mcpServers`.
    if let Some(root) = read_json(&home.join(".claude.json")) {
        if let Some(obj) = root.get("mcpServers").and_then(JsonValue::as_object) {
            let mut names: Vec<&String> = obj.keys().collect();
            names.sort();
            for name in names {
                out.push(claude_entry(name, &obj[name], "~/.claude.json".to_string()));
            }
        }
        if let Some(projects) = root.get("projects").and_then(JsonValue::as_object) {
            let mut paths: Vec<&String> = projects.keys().collect();
            paths.sort();
            for path in paths {
                if let Some(obj) = projects[path]
                    .get("mcpServers")
                    .and_then(JsonValue::as_object)
                {
                    let mut names: Vec<&String> = obj.keys().collect();
                    names.sort();
                    for name in names {
                        out.push(claude_entry(
                            name,
                            &obj[name],
                            format!("~/.claude.json (project {path})"),
                        ));
                    }
                }
            }
        }
    }

    // Standalone flat `{ "mcpServers": {...} }` files sharing the same
    // per-server shape.
    for (rel, label) in [
        (
            PathBuf::from(".claude").join("mcp.json"),
            "~/.claude/mcp.json",
        ),
        (PathBuf::from(".mcp.json"), "~/.mcp.json"),
    ] {
        if let Some(root) = read_json(&home.join(&rel)) {
            if let Some(obj) = root.get("mcpServers").and_then(JsonValue::as_object) {
                let mut names: Vec<&String> = obj.keys().collect();
                names.sort();
                for name in names {
                    out.push(claude_entry(name, &obj[name], label.to_string()));
                }
            }
        }
    }

    out
}

fn claude_entry(
    name: &str,
    v: &JsonValue,
    origin: String,
) -> (String, Source, String, ParsedEntry) {
    let ty = v.get("type").and_then(JsonValue::as_str).unwrap_or("stdio");
    let parsed = if ty != "stdio" || v.get("url").is_some() {
        ParsedEntry::Unsupported(format!(
            "`{ty}` transport (url-based) not supported — supercode's MCP config is stdio-only"
        ))
    } else {
        match v.get("command").and_then(JsonValue::as_str) {
            None => ParsedEntry::Unsupported("no `command` field".to_string()),
            Some(command) => {
                let args = v
                    .get("args")
                    .and_then(JsonValue::as_array)
                    .map(|a| {
                        a.iter()
                            .filter_map(JsonValue::as_str)
                            .map(String::from)
                            .collect()
                    })
                    .unwrap_or_default();
                let env = v
                    .get("env")
                    .and_then(JsonValue::as_object)
                    .map(|o| {
                        o.iter()
                            .filter_map(|(k, val)| val.as_str().map(|s| (k.clone(), s.to_string())))
                            .collect::<BTreeMap<String, String>>()
                    })
                    .filter(|m| !m.is_empty());
                ParsedEntry::Stdio(
                    Box::new(McpServerDef {
                        command: Some(command.to_string()),
                        args,
                        env,
                        ..Default::default()
                    }),
                    Vec::new(),
                )
            }
        }
    };
    (name.to_string(), Source::Claude, origin, parsed)
}

fn raw_codex_entries(home: &Path) -> Vec<(String, Source, String, ParsedEntry)> {
    let mut out = Vec::new();
    let path = home.join(".codex").join("config.toml");
    let Ok(text) = std::fs::read_to_string(&path) else {
        return out;
    };
    let Ok(root) = text.parse::<toml::Value>() else {
        return out;
    };
    if let Some(table) = root.get("mcp_servers").and_then(toml::Value::as_table) {
        let mut names: Vec<&String> = table.keys().collect();
        names.sort();
        for name in names {
            out.push(codex_entry(
                name,
                &table[name],
                "~/.codex/config.toml".to_string(),
            ));
        }
    }
    out
}

fn codex_entry(
    name: &str,
    v: &toml::Value,
    origin: String,
) -> (String, Source, String, ParsedEntry) {
    let parsed = if v.get("url").is_some() {
        ParsedEntry::Unsupported(
            "url-based transport not supported — supercode's MCP config is stdio-only".to_string(),
        )
    } else {
        match v.get("command").and_then(toml::Value::as_str) {
            None => ParsedEntry::Unsupported("no `command` field".to_string()),
            Some(command) => {
                let args = v
                    .get("args")
                    .and_then(toml::Value::as_array)
                    .map(|a| {
                        a.iter()
                            .filter_map(toml::Value::as_str)
                            .map(String::from)
                            .collect()
                    })
                    .unwrap_or_default();
                let env = v
                    .get("env")
                    .and_then(toml::Value::as_table)
                    .map(|t| {
                        t.iter()
                            .filter_map(|(k, val)| val.as_str().map(|s| (k.clone(), s.to_string())))
                            .collect::<BTreeMap<String, String>>()
                    })
                    .filter(|m| !m.is_empty());
                ParsedEntry::Stdio(
                    Box::new(McpServerDef {
                        command: Some(command.to_string()),
                        args,
                        env,
                        ..Default::default()
                    }),
                    Vec::new(),
                )
            }
        }
    };
    (name.to_string(), Source::Codex, origin, parsed)
}

fn read_json(path: &Path) -> Option<JsonValue> {
    let text = std::fs::read_to_string(path).ok()?;
    serde_json::from_str(&text).ok()
}

/// Apply a scan's candidates to an existing server map, IN PLACE. Never
/// overwrites an existing entry — a name already present is reported as
/// `already_present`, not touched. Re-applying the same report twice is a
/// no-op the second time (idempotent).
pub fn apply(report: &ScanReport, servers: &mut BTreeMap<String, McpServerDef>) -> ApplyOutcome {
    let mut outcome = ApplyOutcome::default();
    for c in &report.candidates {
        if servers.contains_key(&c.name) {
            outcome.already_present.push(c.name.clone());
        } else {
            servers.insert(c.name.clone(), c.def.clone());
            outcome.imported.push(c.name.clone());
        }
    }
    outcome
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;

    fn write(dir: &Path, rel: &str, content: &str) {
        let p = dir.join(rel);
        std::fs::create_dir_all(p.parent().unwrap()).unwrap();
        std::fs::write(p, content).unwrap();
    }

    fn tempdir(tag: &str) -> PathBuf {
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos();
        let dir = std::env::temp_dir().join(format!(
            "supercode-mcpimport-{tag}-{}-{nanos}",
            std::process::id()
        ));
        std::fs::create_dir_all(&dir).unwrap();
        dir
    }

    /// Real (redacted) shape of `~/.claude.json`, as verified against a live
    /// Claude Code install: top-level `mcpServers` + `projects.*.mcpServers`,
    /// stdio and http entries side by side.
    const CLAUDE_JSON: &str = r#"
    {
      "numStartups": 12,
      "mcpServers": {
        "github": {
          "command": "npx",
          "args": ["-y", "@modelcontextprotocol/server-github"],
          "env": { "GITHUB_TOKEN": "secret" }
        },
        "hosted": {
          "type": "http",
          "url": "https://example.com/mcp"
        }
      },
      "projects": {
        "/workspace/foo": {
          "mcpServers": {
            "project-only": { "command": "my-server", "args": ["--flag"] }
          }
        }
      }
    }
    "#;

    const CODEX_TOML: &str = r#"
    [mcp_servers.filesystem]
    command = "mcp-server-filesystem"
    args = ["/tmp"]

    [mcp_servers.filesystem.env]
    FS_ROOT = "/tmp"

    [mcp_servers.remote]
    url = "https://example.com/mcp"
    "#;

    #[test]
    fn parses_claude_top_level_and_per_project_stdio_servers() {
        let home = tempdir("claude-shape");
        write(&home, ".claude.json", CLAUDE_JSON);
        let report = scan_claude(&home);

        let names: Vec<&str> = report.candidates.iter().map(|c| c.name.as_str()).collect();
        assert!(names.contains(&"github"), "names: {names:?}");
        assert!(names.contains(&"project-only"), "names: {names:?}");

        let github = report
            .candidates
            .iter()
            .find(|c| c.name == "github")
            .unwrap();
        assert_eq!(github.def.command.as_deref(), Some("npx"));
        assert_eq!(
            github.def.args,
            vec!["-y", "@modelcontextprotocol/server-github"]
        );
        // env is now imported faithfully (MCP-env follow-up to UX-27) — no
        // fidelity loss, so no note either.
        assert_eq!(
            github.def.env.as_ref().and_then(|e| e.get("GITHUB_TOKEN")),
            Some(&"secret".to_string()),
            "env: {:?}",
            github.def.env
        );
        assert!(
            github.notes.is_empty(),
            "env is imported now, not dropped — no note expected: {:?}",
            github.notes
        );

        // A stdio server with no `env` block gets `None`, not `Some({})` —
        // no fabricated empty env key.
        let project_only = report
            .candidates
            .iter()
            .find(|c| c.name == "project-only")
            .unwrap();
        assert!(
            project_only.def.env.is_none(),
            "no-env source entry must not fabricate an env map: {:?}",
            project_only.def.env
        );

        let hosted = report.skipped.iter().find(|s| s.name == "hosted");
        assert!(
            hosted.is_some(),
            "http entry must be recognized+skipped, not silently dropped"
        );
        assert!(hosted.unwrap().reason.contains("http"));
    }

    #[test]
    fn parses_codex_toml_stdio_and_skips_url_entries() {
        let home = tempdir("codex-shape");
        write(&home, ".codex/config.toml", CODEX_TOML);
        let report = scan_codex(&home);

        let fs = report
            .candidates
            .iter()
            .find(|c| c.name == "filesystem")
            .expect("filesystem stdio server imported");
        assert_eq!(fs.def.command.as_deref(), Some("mcp-server-filesystem"));
        assert_eq!(fs.def.args, vec!["/tmp"]);
        assert_eq!(
            fs.def.env.as_ref().and_then(|e| e.get("FS_ROOT")),
            Some(&"/tmp".to_string()),
            "Codex TOML env table must be imported too: {:?}",
            fs.def.env
        );

        let remote = report.skipped.iter().find(|s| s.name == "remote");
        assert!(
            remote.is_some(),
            "url-based codex entry must be skipped with a reason"
        );
    }

    #[test]
    fn duplicate_names_across_sources_keep_the_first_and_report_the_rest() {
        let home = tempdir("dup");
        write(
            &home,
            ".claude.json",
            r#"{ "mcpServers": { "shared": { "command": "from-claude" } } }"#,
        );
        write(
            &home,
            ".codex/config.toml",
            "[mcp_servers.shared]\ncommand = \"from-codex\"\n",
        );
        let report = scan_all(&home);
        let shared: Vec<&Candidate> = report
            .candidates
            .iter()
            .filter(|c| c.name == "shared")
            .collect();
        assert_eq!(shared.len(), 1, "must not import the same name twice");
        assert_eq!(
            shared[0].def.command.as_deref(),
            Some("from-claude"),
            "claude scanned first, wins"
        );
        assert!(
            report
                .skipped
                .iter()
                .any(|s| s.name == "shared" && s.source == Source::Codex),
            "the losing duplicate must be reported, not silently dropped"
        );
    }

    #[test]
    fn apply_is_idempotent_and_never_clobbers_existing_entries() {
        let mut servers: BTreeMap<String, McpServerDef> = BTreeMap::new();
        servers.insert(
            "github".to_string(),
            McpServerDef {
                command: Some("user-configured-already".to_string()),
                args: vec![],
                env: None,
                ..Default::default()
            },
        );

        let report = ScanReport {
            candidates: vec![
                Candidate {
                    name: "github".to_string(),
                    def: McpServerDef {
                        command: Some("npx".to_string()),
                        args: vec![],
                        env: None,
                        ..Default::default()
                    },
                    source: Source::Claude,
                    origin: "~/.claude.json".to_string(),
                    notes: vec![],
                },
                Candidate {
                    name: "new-server".to_string(),
                    def: McpServerDef {
                        command: Some("my-server".to_string()),
                        args: vec![],
                        env: None,
                        ..Default::default()
                    },
                    source: Source::Claude,
                    origin: "~/.claude.json".to_string(),
                    notes: vec![],
                },
            ],
            skipped: vec![],
        };

        let outcome = apply(&report, &mut servers);
        assert_eq!(outcome.imported, vec!["new-server".to_string()]);
        assert_eq!(outcome.already_present, vec!["github".to_string()]);
        // The pre-existing user entry is untouched.
        assert_eq!(
            servers["github"].command.as_deref(),
            Some("user-configured-already")
        );
        assert_eq!(servers["new-server"].command.as_deref(), Some("my-server"));

        // Re-applying is a no-op: nothing "imported" the second time.
        let outcome2 = apply(&report, &mut servers);
        assert!(
            outcome2.imported.is_empty(),
            "second apply must not duplicate"
        );
        assert_eq!(
            outcome2.already_present,
            vec!["github".to_string(), "new-server".to_string()]
        );
    }

    #[test]
    fn no_source_files_yields_an_empty_report_not_an_error() {
        let home = tempdir("empty");
        let report = scan_all(&home);
        assert!(report.candidates.is_empty());
        assert!(report.skipped.is_empty());
    }
}