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