Skip to main content

rust_anything/
setup.rs

1//! `setup`: register rust-anything with the coding agents on this machine, in one command.
2//!
3//! For each agent it finds (or is told about), it adds the MCP server (`rust-anything mcp`) to
4//! the agent's own configuration and, where the agent reads skills, installs the workflow skill.
5//! Existing settings are kept: only the `rust-anything` entries are added or replaced, and a file
6//! that does not parse is left alone with an error. `--remove` takes the entries out again.
7
8use std::path::{Path, PathBuf};
9
10use anyhow::{Context, Result, bail};
11use serde::Serialize;
12use serde_json::{Map, Value, json};
13
14/// The server and skill name in every agent.
15pub const NAME: &str = "rust-anything";
16
17/// The workflow skill, as shipped in `skills/rust-anything/SKILL.md`.
18pub const SKILL: &str = include_str!("../skills/rust-anything/SKILL.md");
19pub(crate) const SKILL_FILES: &[(&str, &str)] = &[
20    ("SKILL.md", SKILL),
21    (
22        "whole-app.md",
23        include_str!("../skills/rust-anything/whole-app.md"),
24    ),
25];
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, clap::ValueEnum, Serialize)]
28#[serde(rename_all = "lowercase")]
29pub enum Agent {
30    /// Claude Code: `~/.claude.json`, skill in `~/.claude/skills`.
31    Claude,
32    /// OpenAI Codex CLI: `~/.codex/config.toml`, skill in `~/.codex/skills`.
33    Codex,
34    /// Cursor: `~/.cursor/mcp.json`.
35    Cursor,
36    /// Gemini CLI: `~/.gemini/settings.json`.
37    Gemini,
38    /// OpenCode: `~/.config/opencode/opencode.json`, skill in `~/.config/opencode/skills`.
39    #[value(name = "opencode")]
40    OpenCode,
41}
42
43impl Agent {
44    pub const ALL: [Agent; 5] = [
45        Agent::Claude,
46        Agent::Codex,
47        Agent::Cursor,
48        Agent::Gemini,
49        Agent::OpenCode,
50    ];
51
52    pub fn name(self) -> &'static str {
53        match self {
54            Agent::Claude => "Claude Code",
55            Agent::Codex => "Codex",
56            Agent::Cursor => "Cursor",
57            Agent::Gemini => "Gemini CLI",
58            Agent::OpenCode => "OpenCode",
59        }
60    }
61
62    /// The agent's folder in the home directory, and its command.
63    fn markers(self) -> (&'static str, &'static str) {
64        match self {
65            Agent::Claude => (".claude", "claude"),
66            Agent::Codex => (".codex", "codex"),
67            Agent::Cursor => (".cursor", "cursor"),
68            Agent::Gemini => (".gemini", "gemini"),
69            Agent::OpenCode => (".config/opencode", "opencode"),
70        }
71    }
72
73    /// The settings file that holds the agent's MCP servers.
74    pub(crate) fn config(self, home: &Path) -> PathBuf {
75        home.join(match self {
76            Agent::Claude => ".claude.json",
77            Agent::Codex => ".codex/config.toml",
78            Agent::Cursor => ".cursor/mcp.json",
79            Agent::Gemini => ".gemini/settings.json",
80            Agent::OpenCode => ".config/opencode/opencode.json",
81        })
82    }
83
84    /// Where the workflow skill goes, for agents that read skills.
85    pub(crate) fn skill_dir(self, home: &Path) -> Option<PathBuf> {
86        match self {
87            Agent::Claude => Some(home.join(".claude/skills").join(NAME)),
88            Agent::Codex => Some(home.join(".codex/skills").join(NAME)),
89            Agent::OpenCode => Some(home.join(".config/opencode/skills").join(NAME)),
90            Agent::Cursor | Agent::Gemini => None,
91        }
92    }
93
94    /// Whether the agent seems installed: its folder exists or its command is on `PATH`.
95    pub(crate) fn present(self, home: &Path) -> bool {
96        let (dir, command) = self.markers();
97        home.join(dir).is_dir() || on_path(command)
98    }
99}
100
101pub(crate) fn on_path(command: &str) -> bool {
102    std::env::var_os("PATH").is_some_and(|paths| {
103        std::env::split_paths(&paths).any(|dir| {
104            let file = dir.join(command);
105            file.is_file()
106                || file.with_extension("exe").is_file()
107                || file.with_extension("cmd").is_file()
108        })
109    })
110}
111
112pub struct Options<'a> {
113    pub home: &'a Path,
114    /// Agents to set up; empty means every agent found.
115    pub agents: Vec<Agent>,
116    /// The command the agents run; the current executable by default.
117    pub command: PathBuf,
118    pub remove: bool,
119    pub dry_run: bool,
120    /// Save `<file>.rust-anything.bak` before changing an existing file.
121    pub backup: bool,
122}
123
124/// One change: which agent, which file, and what happened.
125#[derive(Debug, Serialize)]
126pub struct Change {
127    pub agent: Agent,
128    pub file: PathBuf,
129    /// `added`, `updated`, `unchanged`, `removed` or `absent`.
130    pub action: &'static str,
131    /// The copy of the file as it was, when an existing file was changed.
132    #[serde(skip_serializing_if = "Option::is_none")]
133    pub backup: Option<PathBuf>,
134}
135
136#[derive(Debug, Serialize)]
137pub struct Report {
138    pub command: PathBuf,
139    pub agents: Vec<Agent>,
140    pub changes: Vec<Change>,
141    pub dry_run: bool,
142}
143
144/// The home directory: `HOME`, or `USERPROFILE` on Windows.
145pub fn home() -> Result<PathBuf> {
146    std::env::var_os("HOME")
147        .or_else(|| std::env::var_os("USERPROFILE"))
148        .map(PathBuf::from)
149        .context("no home directory (HOME is not set)")
150}
151
152pub fn setup(opts: &Options) -> Result<Report> {
153    let agents: Vec<Agent> = if opts.agents.is_empty() {
154        Agent::ALL
155            .into_iter()
156            .filter(|a| a.present(opts.home))
157            .collect()
158    } else {
159        opts.agents.clone()
160    };
161    if agents.is_empty() {
162        bail!(
163            "no coding agent found (looked for ~/.claude, ~/.codex, ~/.cursor, ~/.gemini, ~/.config/opencode and their commands); \
164             name one with --agent claude|codex|cursor|gemini|opencode"
165        );
166    }
167    let command = opts.command.to_string_lossy().into_owned();
168    let mut changes = Vec::new();
169    for &agent in &agents {
170        let config = agent.config(opts.home);
171        changes.push(match agent {
172            Agent::Codex => codex_server(agent, &config, &command, opts)?,
173            Agent::OpenCode => opencode_server(agent, &config, &command, opts)?,
174            _ => json_server(agent, &config, &command, opts, agent == Agent::Claude)?,
175        });
176        if let Some(dir) = agent.skill_dir(opts.home) {
177            changes.push(skill(agent, &dir, opts)?);
178        }
179    }
180    Ok(Report {
181        command: opts.command.clone(),
182        agents,
183        changes,
184        dry_run: opts.dry_run,
185    })
186}
187
188/// Copies an existing settings file to `<file>.rust-anything.bak` before it is changed.
189fn backup(path: &Path) -> Result<Option<PathBuf>> {
190    if !path.is_file() {
191        return Ok(None);
192    }
193    let mut name = path.file_name().unwrap_or_default().to_os_string();
194    name.push(".rust-anything.bak");
195    let copy = path.with_file_name(name);
196    std::fs::copy(path, &copy).with_context(|| format!("backing up {}", path.display()))?;
197    Ok(Some(copy))
198}
199
200/// Writes `text` to `path` through a temporary file, so a failed write never leaves half a file.
201/// A symlinked file (a dotfiles repo) is written at its target, and an existing file keeps its
202/// permissions (a settings file holding tokens stays private).
203fn write(path: &Path, text: &str) -> Result<()> {
204    let path = &std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
205    if let Some(dir) = path.parent() {
206        std::fs::create_dir_all(dir).with_context(|| format!("creating {}", dir.display()))?;
207    }
208    let tmp = path.with_extension("rust-anything.tmp");
209    let mut file =
210        std::fs::File::create(&tmp).with_context(|| format!("writing {}", tmp.display()))?;
211    if let Ok(meta) = std::fs::metadata(path) {
212        file.set_permissions(meta.permissions())
213            .with_context(|| format!("writing {}", tmp.display()))?;
214    }
215    std::io::Write::write_all(&mut file, text.as_bytes())
216        .with_context(|| format!("writing {}", tmp.display()))?;
217    drop(file);
218    std::fs::rename(&tmp, path).with_context(|| format!("replacing {}", path.display()))
219}
220
221/// The `mcpServers` entry of a JSON settings file (Claude Code, Cursor, Gemini CLI).
222fn json_server(
223    agent: Agent,
224    path: &Path,
225    command: &str,
226    opts: &Options,
227    stdio_type: bool,
228) -> Result<Change> {
229    let text = match std::fs::read_to_string(path) {
230        Ok(t) => Some(t),
231        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
232        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
233    };
234    let mut doc: Value = match text.as_deref().map(str::trim) {
235        None | Some("") => json!({}),
236        Some(t) => serde_json::from_str(t).with_context(|| {
237            format!(
238                "{} is not valid JSON; fix it or add the server by hand",
239                path.display()
240            )
241        })?,
242    };
243    let Some(root) = doc.as_object_mut() else {
244        bail!(
245            "{} is not a JSON object; add the server by hand",
246            path.display()
247        );
248    };
249    let servers = root.entry("mcpServers").or_insert_with(|| json!({}));
250    let Some(servers) = servers.as_object_mut() else {
251        bail!(
252            "`mcpServers` in {} is not an object; add the server by hand",
253            path.display()
254        );
255    };
256    let action = if opts.remove {
257        if servers.shift_remove(NAME).is_some() {
258            "removed"
259        } else {
260            "absent"
261        }
262    } else {
263        let existing = servers.get(NAME);
264        let mut entry = existing
265            .and_then(Value::as_object)
266            .cloned()
267            .unwrap_or_default();
268        entry.insert("command".into(), json!(command));
269        entry.insert("args".into(), json!(["mcp"]));
270        if stdio_type || entry.contains_key("type") {
271            entry.insert("type".into(), json!("stdio"));
272        }
273        if stdio_type {
274            entry.entry("env").or_insert_with(|| json!({}));
275        }
276        entry.shift_remove("url");
277        let entry = Value::Object(entry);
278        if existing == Some(&entry) {
279            "unchanged"
280        } else {
281            let action = if existing.is_some() {
282                "updated"
283            } else {
284                "added"
285            };
286            servers.insert(NAME.into(), entry);
287            action
288        }
289    };
290    let mut saved = None;
291    if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
292        if opts.backup {
293            saved = backup(path)?;
294        }
295        write(path, &(serde_json::to_string_pretty(&doc)? + "\n"))?;
296    }
297    Ok(Change {
298        agent,
299        file: path.to_path_buf(),
300        action,
301        backup: saved,
302    })
303}
304
305/// The map of servers in OpenCode's `mcp` object. Current OpenCode keeps them under
306/// `mcp.servers`; a `mcp` object that already lists servers by name (the shape older files
307/// use) is kept as it is, so the two shapes never end up mixed in one file.
308fn opencode_servers<'a>(
309    mcp: &'a mut Map<String, Value>,
310    path: &Path,
311) -> Result<&'a mut Map<String, Value>> {
312    if mcp.is_empty() || matches!(mcp.get("servers"), Some(Value::Object(_))) {
313        let servers = mcp.entry("servers").or_insert_with(|| json!({}));
314        return servers.as_object_mut().with_context(|| {
315            format!(
316                "`mcp.servers` in {} is not an object; add the server by hand",
317                path.display()
318            )
319        });
320    }
321    Ok(mcp)
322}
323
324/// `mcp.servers.rust-anything` in OpenCode's `opencode.json`: a local server whose `command`
325/// is the whole argv, so the executable and `mcp` go in one array.
326fn opencode_server(agent: Agent, path: &Path, command: &str, opts: &Options) -> Result<Change> {
327    let text = match std::fs::read_to_string(path) {
328        Ok(t) => Some(t),
329        Err(e) if e.kind() == std::io::ErrorKind::NotFound => None,
330        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
331    };
332    let mut doc: Value = match text.as_deref().map(str::trim) {
333        None | Some("") => json!({}),
334        Some(t) => serde_json::from_str(t).with_context(|| {
335            format!(
336                "{} is not valid JSON; fix it or add the server by hand",
337                path.display()
338            )
339        })?,
340    };
341    let Some(root) = doc.as_object_mut() else {
342        bail!(
343            "{} is not a JSON object; add the server by hand",
344            path.display()
345        );
346    };
347    let mcp = root.entry("mcp").or_insert_with(|| json!({}));
348    let Some(mcp) = mcp.as_object_mut() else {
349        bail!(
350            "`mcp` in {} is not an object; add the server by hand",
351            path.display()
352        );
353    };
354    let servers = opencode_servers(mcp, path)?;
355    let action = if opts.remove {
356        if servers.shift_remove(NAME).is_some() {
357            "removed"
358        } else {
359            "absent"
360        }
361    } else {
362        let existing = servers.get(NAME);
363        let mut entry = existing
364            .and_then(Value::as_object)
365            .cloned()
366            .unwrap_or_default();
367        entry.insert("type".into(), json!("local"));
368        entry.insert("command".into(), json!([command, "mcp"]));
369        // OpenCode keeps a server out of the way with `disabled`, and older files wrote the
370        // opposite `enabled`: setting one up means neither key.
371        entry.shift_remove("disabled");
372        entry.shift_remove("enabled");
373        entry.shift_remove("url");
374        let entry = Value::Object(entry);
375        if existing == Some(&entry) {
376            "unchanged"
377        } else {
378            let action = if existing.is_some() {
379                "updated"
380            } else {
381                "added"
382            };
383            servers.insert(NAME.into(), entry);
384            action
385        }
386    };
387    let mut saved = None;
388    if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
389        if opts.backup {
390            saved = backup(path)?;
391        }
392        write(path, &(serde_json::to_string_pretty(&doc)? + "\n"))?;
393    }
394    Ok(Change {
395        agent,
396        file: path.to_path_buf(),
397        action,
398        backup: saved,
399    })
400}
401
402/// `[mcp_servers.rust-anything]` in Codex's `config.toml`, keeping the rest of the file as is.
403fn codex_server(agent: Agent, path: &Path, command: &str, opts: &Options) -> Result<Change> {
404    let text = match std::fs::read_to_string(path) {
405        Ok(t) => t,
406        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
407        Err(e) => return Err(e).with_context(|| format!("reading {}", path.display())),
408    };
409    let mut doc: toml_edit::DocumentMut = text.parse().with_context(|| {
410        format!(
411            "{} is not valid TOML; fix it or add the server by hand",
412            path.display()
413        )
414    })?;
415    let servers = doc
416        .entry("mcp_servers")
417        .or_insert_with(|| {
418            let mut t = toml_edit::Table::new();
419            t.set_implicit(true);
420            toml_edit::Item::Table(t)
421        })
422        .as_table_mut()
423        .with_context(|| format!("`mcp_servers` in {} is not a table", path.display()))?;
424    let same = servers
425        .get(NAME)
426        .and_then(|t| t.as_table_like())
427        .is_some_and(|t| {
428            t.get("command").and_then(|c| c.as_str()) == Some(command)
429                && t.get("url").is_none()
430                && t.get("args").and_then(|a| a.as_array()).is_some_and(|a| {
431                    a.iter().map(|v| v.as_str()).collect::<Vec<_>>() == [Some("mcp")]
432                })
433        });
434    let action = if opts.remove {
435        if servers.remove(NAME).is_some() {
436            "removed"
437        } else {
438            "absent"
439        }
440    } else if same {
441        "unchanged"
442    } else {
443        let had = servers.contains_key(NAME);
444        // An entry written inline (`rust-anything = { ... }`) keeps its other keys too.
445        let mut entry = match servers.get(NAME) {
446            Some(toml_edit::Item::Table(t)) => t.clone(),
447            Some(toml_edit::Item::Value(toml_edit::Value::InlineTable(t))) => {
448                t.clone().into_table()
449            }
450            _ => toml_edit::Table::new(),
451        };
452        entry["command"] = toml_edit::value(command);
453        let mut args = toml_edit::Array::new();
454        args.push("mcp");
455        entry["args"] = toml_edit::value(args);
456        entry.remove("url");
457        servers.insert(NAME, toml_edit::Item::Table(entry));
458        if had { "updated" } else { "added" }
459    };
460    let mut saved = None;
461    if !opts.dry_run && matches!(action, "added" | "updated" | "removed") {
462        if opts.backup {
463            saved = backup(path)?;
464        }
465        write(path, &doc.to_string())?;
466    }
467    Ok(Change {
468        agent,
469        file: path.to_path_buf(),
470        action,
471        backup: saved,
472    })
473}
474
475/// The workflow skill in an agent's skills folder.
476fn skill(agent: Agent, dir: &Path, opts: &Options) -> Result<Change> {
477    let current: Vec<Option<String>> = SKILL_FILES
478        .iter()
479        .map(|(name, _)| std::fs::read_to_string(dir.join(name)).ok())
480        .collect();
481    let action = if opts.remove {
482        if current.iter().any(Option::is_some) {
483            "removed"
484        } else {
485            "absent"
486        }
487    } else if current.iter().all(Option::is_none) {
488        "added"
489    } else if current
490        .iter()
491        .zip(SKILL_FILES)
492        .all(|(have, (_, want))| have.as_deref() == Some(*want))
493    {
494        "unchanged"
495    } else {
496        "updated"
497    };
498    if !opts.dry_run {
499        for (name, text) in SKILL_FILES {
500            let path = dir.join(name);
501            match action {
502                "added" | "updated" => write(&path, text)?,
503                "removed" if path.exists() => {
504                    std::fs::remove_file(&path)
505                        .with_context(|| format!("removing {}", path.display()))?;
506                }
507                _ => {}
508            }
509        }
510        if action == "removed" {
511            // The folder is ours; leave it only if someone put other files in it.
512            let _ = std::fs::remove_dir(dir);
513        }
514    }
515    Ok(Change {
516        agent,
517        file: dir.join("SKILL.md"),
518        action,
519        backup: None,
520    })
521}
522
523/// The report for people.
524pub fn text(r: &Report) -> String {
525    let mut out = String::new();
526    let verb = if r.dry_run { "Would set up" } else { "Set up" };
527    let names: Vec<&str> = r.agents.iter().map(|a| a.name()).collect();
528    out.push_str(&format!("{verb} rust-anything for {}\n", names.join(", ")));
529    for c in &r.changes {
530        out.push_str(&format!(
531            "  {:<10} {:<9} {}\n",
532            c.agent.name(),
533            c.action,
534            c.file.display()
535        ));
536        if let Some(b) = &c.backup {
537            out.push_str(&format!("  {:<10} {:<9} {}\n", "", "backup", b.display()));
538        }
539    }
540    if !r.dry_run
541        && r.changes
542            .iter()
543            .any(|c| c.action != "removed" && c.action != "absent")
544    {
545        out.push_str(&format!(
546            "\nThe agents run `{} mcp`. Restart them, then ask, for example:\n  \
547             \"Profile this repo's slowest workflow with rust-anything and move the hot loop to Rust.\"\n",
548            r.command.display()
549        ));
550    }
551    out
552}
553
554#[cfg(test)]
555mod tests {
556    use super::*;
557
558    fn temp_home(name: &str) -> PathBuf {
559        let dir =
560            std::env::temp_dir().join(format!("rust-anything-setup-{name}-{}", std::process::id()));
561        let _ = std::fs::remove_dir_all(&dir);
562        std::fs::create_dir_all(&dir).unwrap();
563        dir
564    }
565
566    fn opts(home: &Path, agents: Vec<Agent>) -> Options<'_> {
567        Options {
568            home,
569            agents,
570            command: PathBuf::from("/opt/bin/rust-anything"),
571            remove: false,
572            dry_run: false,
573            backup: true,
574        }
575    }
576
577    #[test]
578    fn no_backup_changes_the_file_without_a_copy() {
579        let home = temp_home("no-backup");
580        let cursor = home.join(".cursor/mcp.json");
581        std::fs::create_dir_all(cursor.parent().unwrap()).unwrap();
582        std::fs::write(&cursor, r#"{"mcpServers":{"other":{"command":"x"}}}"#).unwrap();
583        let copy = home.join(".cursor/mcp.json.rust-anything.bak");
584
585        let mut options = opts(&home, vec![Agent::Cursor]);
586        options.backup = false;
587        let r = setup(&options).unwrap();
588        assert_eq!(r.changes[0].action, "added");
589        assert!(r.changes[0].backup.is_none());
590        assert!(!copy.exists());
591        assert!(
592            std::fs::read_to_string(&cursor)
593                .unwrap()
594                .contains("rust-anything")
595        );
596
597        options.remove = true;
598        options.backup = true;
599        let r = setup(&options).unwrap();
600        assert_eq!(r.changes[0].backup.as_deref(), Some(copy.as_path()));
601        assert!(copy.exists());
602        let _ = std::fs::remove_dir_all(&home);
603    }
604
605    #[test]
606    fn adds_keeps_and_removes_entries() {
607        let home = temp_home("all");
608        // Existing settings that must survive, in their own order.
609        std::fs::write(
610            home.join(".claude.json"),
611            r#"{"zeta": 1, "mcpServers": {"other": {"command": "x"}}, "alpha": true}"#,
612        )
613        .unwrap();
614        std::fs::create_dir_all(home.join(".codex")).unwrap();
615        std::fs::write(
616            home.join(".codex/config.toml"),
617            "model = \"o4\"\n\n[mcp_servers.other]\ncommand = \"x\"\n",
618        )
619        .unwrap();
620
621        let all = Agent::ALL.to_vec();
622        let r = setup(&opts(&home, all.clone())).unwrap();
623        assert!(
624            r.changes.iter().all(|c| c.action == "added"),
625            "{:?}",
626            r.changes
627        );
628
629        let claude: Value =
630            serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
631                .unwrap();
632        assert_eq!(
633            claude["mcpServers"]["rust-anything"]["args"],
634            json!(["mcp"])
635        );
636        assert_eq!(claude["mcpServers"]["other"]["command"], "x");
637        // The existing file was copied before the change; new files need no copy.
638        let saved = r.changes[0]
639            .backup
640            .clone()
641            .expect("an existing file is backed up");
642        assert!(
643            std::fs::read_to_string(saved)
644                .unwrap()
645                .starts_with(r#"{"zeta": 1"#)
646        );
647        assert!(r.changes.iter().any(|c| c.backup.is_none()));
648        let keys: Vec<&String> = claude.as_object().unwrap().keys().collect();
649        assert_eq!(keys, ["zeta", "mcpServers", "alpha"], "key order kept");
650        let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
651        assert!(codex.starts_with("model = \"o4\""), "{codex}");
652        assert!(codex.contains("[mcp_servers.rust-anything]\ncommand = \"/opt/bin/rust-anything\"\nargs = [\"mcp\"]"), "{codex}");
653        assert!(codex.contains("[mcp_servers.other]"));
654        assert_eq!(
655            std::fs::read_to_string(home.join(".claude/skills/rust-anything/SKILL.md")).unwrap(),
656            SKILL
657        );
658        assert!(
659            home.join(".codex/skills/rust-anything/whole-app.md")
660                .exists()
661        );
662        let cursor: Value =
663            serde_json::from_str(&std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap())
664                .unwrap();
665        assert_eq!(
666            cursor["mcpServers"]["rust-anything"]["command"],
667            "/opt/bin/rust-anything"
668        );
669        assert!(home.join(".gemini/settings.json").exists());
670
671        // Running again changes nothing.
672        let again = setup(&opts(&home, all.clone())).unwrap();
673        assert!(
674            again.changes.iter().all(|c| c.action == "unchanged"),
675            "{:?}",
676            again.changes
677        );
678
679        // A moved binary updates the entries.
680        let mut moved = opts(&home, vec![Agent::Codex]);
681        moved.command = PathBuf::from("/usr/local/bin/rust-anything");
682        let r = setup(&moved).unwrap();
683        assert_eq!(r.changes[0].action, "updated");
684
685        // Remove takes out only our entries.
686        let mut remove = opts(&home, all);
687        remove.remove = true;
688        setup(&remove).unwrap();
689        let claude: Value =
690            serde_json::from_str(&std::fs::read_to_string(home.join(".claude.json")).unwrap())
691                .unwrap();
692        assert!(claude["mcpServers"].get("rust-anything").is_none());
693        assert_eq!(claude["mcpServers"]["other"]["command"], "x");
694        assert!(!home.join(".claude/skills/rust-anything").exists());
695        let codex = std::fs::read_to_string(home.join(".codex/config.toml")).unwrap();
696        assert!(
697            !codex.contains("rust-anything") && codex.contains("[mcp_servers.other]"),
698            "{codex}"
699        );
700        std::fs::remove_dir_all(&home).unwrap();
701    }
702
703    #[test]
704    fn reinstall_preserves_custom_options_for_the_same_server() {
705        let home = temp_home("custom-entry");
706        let cursor = home.join(".cursor/mcp.json");
707        let codex = home.join(".codex/config.toml");
708        std::fs::create_dir_all(cursor.parent().unwrap()).unwrap();
709        std::fs::create_dir_all(codex.parent().unwrap()).unwrap();
710        std::fs::write(&cursor, r#"{"mcpServers":{"rust-anything":{"command":"old","args":["mcp"],"env":{"MODE":"custom"}}}}"#).unwrap();
711        std::fs::write(&codex, "[mcp_servers.rust-anything]\ncommand = \"old\"\nargs = [\"mcp\"]\ntool_timeout_sec = 120\n").unwrap();
712
713        let options = opts(&home, vec![Agent::Cursor, Agent::Codex]);
714        setup(&options).unwrap();
715        let cursor: Value =
716            serde_json::from_str(&std::fs::read_to_string(cursor).unwrap()).unwrap();
717        let codex: toml_edit::DocumentMut =
718            std::fs::read_to_string(codex).unwrap().parse().unwrap();
719        let again = setup(&options).unwrap();
720        std::fs::remove_dir_all(home).unwrap();
721        assert_eq!(cursor["mcpServers"][NAME]["env"]["MODE"], "custom");
722        assert_eq!(
723            cursor["mcpServers"][NAME]["command"],
724            "/opt/bin/rust-anything"
725        );
726        assert_eq!(
727            codex["mcp_servers"][NAME]["tool_timeout_sec"].as_integer(),
728            Some(120)
729        );
730        assert!(again.changes.iter().all(|c| c.action == "unchanged"));
731    }
732
733    #[test]
734    fn reinstall_keeps_an_inline_codex_entry() {
735        let home = temp_home("codex-inline");
736        let codex = home.join(".codex/config.toml");
737        std::fs::create_dir_all(codex.parent().unwrap()).unwrap();
738        std::fs::write(
739            &codex,
740            "[mcp_servers]\nrust-anything = { command = \"old\", args = [\"mcp\"], env = { MODE = \"custom\" } }\n",
741        )
742        .unwrap();
743
744        let options = opts(&home, vec![Agent::Codex]);
745        setup(&options).unwrap();
746        let doc: toml_edit::DocumentMut = std::fs::read_to_string(&codex).unwrap().parse().unwrap();
747        let again = setup(&options).unwrap();
748        std::fs::remove_dir_all(home).unwrap();
749        assert_eq!(
750            doc["mcp_servers"][NAME]["env"]["MODE"].as_str(),
751            Some("custom")
752        );
753        assert_eq!(
754            doc["mcp_servers"][NAME]["command"].as_str(),
755            Some("/opt/bin/rust-anything")
756        );
757        assert!(again.changes.iter().all(|c| c.action == "unchanged"));
758    }
759
760    #[test]
761    fn opencode_gets_a_local_server_and_the_skill() {
762        let home = temp_home("opencode");
763        let config = home.join(".config/opencode/opencode.json");
764        std::fs::create_dir_all(config.parent().unwrap()).unwrap();
765        // Other settings, another server and key order that must all survive.
766        std::fs::write(
767            &config,
768            r#"{"$schema":"https://opencode.ai/config.json","mcp":{"servers":{"other":{"type":"local","command":["x"]}}},"model":"a/b"}"#,
769        )
770        .unwrap();
771
772        let mut options = opts(&home, vec![Agent::OpenCode]);
773        setup(&options).unwrap();
774        let doc: Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
775        let entry = &doc["mcp"]["servers"][NAME];
776        assert_eq!(entry["type"], "local");
777        assert_eq!(entry["command"], json!(["/opt/bin/rust-anything", "mcp"]));
778        assert!(entry.get("disabled").is_none(), "{entry}");
779        assert_eq!(doc["mcp"]["servers"]["other"]["command"], json!(["x"]));
780        assert_eq!(doc["model"], "a/b");
781        let keys: Vec<&String> = doc.as_object().unwrap().keys().collect();
782        assert_eq!(keys, ["$schema", "mcp", "model"], "key order kept");
783        assert_eq!(
784            std::fs::read_to_string(home.join(".config/opencode/skills/rust-anything/SKILL.md"))
785                .unwrap(),
786            SKILL
787        );
788
789        // Running again changes nothing.
790        let again = setup(&options).unwrap();
791        assert!(
792            again.changes.iter().all(|c| c.action == "unchanged"),
793            "{:?}",
794            again.changes
795        );
796
797        // A disabled server is turned back on.
798        let mut doc: Value =
799            serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
800        doc["mcp"]["servers"][NAME]["disabled"] = json!(true);
801        std::fs::write(&config, serde_json::to_string(&doc).unwrap()).unwrap();
802        let r = setup(&options).unwrap();
803        assert_eq!(r.changes[0].action, "updated");
804        let doc: Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
805        assert!(doc["mcp"]["servers"][NAME].get("disabled").is_none());
806
807        // A moved binary updates the entry.
808        options.command = PathBuf::from("/usr/local/bin/rust-anything");
809        let r = setup(&options).unwrap();
810        assert_eq!(r.changes[0].action, "updated");
811
812        // Remove takes out only ours.
813        options.remove = true;
814        setup(&options).unwrap();
815        let doc: Value = serde_json::from_str(&std::fs::read_to_string(&config).unwrap()).unwrap();
816        assert!(doc["mcp"]["servers"].get(NAME).is_none());
817        assert_eq!(doc["mcp"]["servers"]["other"]["command"], json!(["x"]));
818        assert!(!home.join(".config/opencode/skills/rust-anything").exists());
819
820        // A file that lists servers in `mcp` by name (the older shape) keeps that shape.
821        let flat = temp_home("opencode-flat");
822        let flat_config = flat.join(".config/opencode/opencode.json");
823        std::fs::create_dir_all(flat_config.parent().unwrap()).unwrap();
824        std::fs::write(
825            &flat_config,
826            r#"{"mcp":{"other":{"type":"local","command":["x"]},"rust-anything":{"type":"local","command":["/old/rust-anything","mcp"],"enabled":true}}}"#,
827        )
828        .unwrap();
829        setup(&opts(&flat, vec![Agent::OpenCode])).unwrap();
830        let doc: Value =
831            serde_json::from_str(&std::fs::read_to_string(&flat_config).unwrap()).unwrap();
832        let entry = &doc["mcp"][NAME];
833        assert_eq!(entry["command"], json!(["/opt/bin/rust-anything", "mcp"]));
834        assert!(entry.get("enabled").is_none(), "{entry}");
835        assert!(entry.get("disabled").is_none(), "{entry}");
836        assert!(
837            doc["mcp"].get("servers").is_none(),
838            "shapes never mix: {doc}"
839        );
840        assert_eq!(doc["mcp"]["other"]["command"], json!(["x"]));
841        std::fs::remove_dir_all(&flat).unwrap();
842
843        // A file that does not parse is left alone with an error.
844        std::fs::write(&config, "{ not json").unwrap();
845        let err = setup(&opts(&home, vec![Agent::OpenCode])).unwrap_err();
846        assert!(format!("{err:#}").contains("not valid JSON"), "{err:#}");
847        assert_eq!(std::fs::read_to_string(&config).unwrap(), "{ not json");
848        std::fs::remove_dir_all(&home).unwrap();
849    }
850
851    #[cfg(unix)]
852    #[test]
853    fn keeps_a_symlinked_settings_file_and_its_permissions() {
854        use std::os::unix::fs::PermissionsExt;
855        let home = temp_home("link");
856        let dotfiles = home.join("dotfiles");
857        std::fs::create_dir_all(&dotfiles).unwrap();
858        let real = dotfiles.join("claude.json");
859        std::fs::write(&real, r#"{"token": "secret"}"#).unwrap();
860        std::fs::set_permissions(&real, std::fs::Permissions::from_mode(0o600)).unwrap();
861        std::os::unix::fs::symlink(&real, home.join(".claude.json")).unwrap();
862
863        setup(&opts(&home, vec![Agent::Claude])).unwrap();
864        let link = std::fs::symlink_metadata(home.join(".claude.json")).unwrap();
865        assert!(link.file_type().is_symlink(), "the link is kept");
866        let text = std::fs::read_to_string(&real).unwrap();
867        assert!(text.contains("rust-anything"), "{text}");
868        let mode = std::fs::metadata(&real).unwrap().permissions().mode() & 0o777;
869        assert_eq!(mode, 0o600, "permissions kept");
870        std::fs::remove_dir_all(&home).unwrap();
871    }
872
873    #[test]
874    fn finds_agents_and_never_breaks_a_bad_file() {
875        let home = temp_home("detect");
876        std::fs::create_dir_all(home.join(".cursor")).unwrap();
877        std::fs::write(home.join(".cursor/mcp.json"), "{ not json").unwrap();
878        // Only Cursor's folder exists (the commands may be on PATH on a developer machine).
879        let found: Vec<Agent> = Agent::ALL
880            .into_iter()
881            .filter(|a| a.present(&home))
882            .collect();
883        assert!(found.contains(&Agent::Cursor));
884        let err = setup(&opts(&home, vec![Agent::Cursor])).unwrap_err();
885        assert!(format!("{err:#}").contains("not valid JSON"), "{err:#}");
886        assert_eq!(
887            std::fs::read_to_string(home.join(".cursor/mcp.json")).unwrap(),
888            "{ not json"
889        );
890
891        // A dry run writes nothing.
892        let mut dry = opts(&home, vec![Agent::Gemini]);
893        dry.dry_run = true;
894        let r = setup(&dry).unwrap();
895        assert_eq!(r.changes[0].action, "added");
896        assert!(!home.join(".gemini").exists());
897        std::fs::remove_dir_all(&home).unwrap();
898    }
899}