Skip to main content

lean_ctx_cli/setup/
mcp.rs

1// SPDX-License-Identifier: Apache-2.0
2//! Per-agent MCP configuration (configure/disable, target resolution).
3//!
4//! Split out of `setup/mod.rs`; `use super::*` re-imports the parent module’s
5//! aliases and sibling helpers. Public fns are re-exported via `pub(crate) use`.
6
7#[allow(clippy::wildcard_imports)]
8use super::*;
9
10/// Result of setting up a single agent with all steps.
11#[derive(Debug, Default)]
12pub struct AgentSetupResult {
13    pub mcp_ok: bool,
14    /// MCP registration was intentionally skipped because `[setup]
15    /// auto_update_mcp = false` (#281), not because it failed.
16    pub mcp_skipped: bool,
17    pub rules: lean_ctx::rules_inject::InjectResult,
18    pub skill_installed: bool,
19    pub errors: Vec<String>,
20}
21
22/// Complete per-agent setup: MCP config + global rules + skill + hook.
23/// Single source of truth — called by both `init --agent` and `setup`.
24pub fn setup_single_agent(
25    agent_name: &str,
26    global: bool,
27    mode: lean_ctx_hooks::hooks::HookMode,
28) -> AgentSetupResult {
29    // Prefer HOME/USERPROFILE so tests and portable installs work on Windows
30    // (dirs::home_dir uses Known Folder API and ignores env overrides).
31    let home = lean_ctx::core::home::resolve_home_dir().unwrap_or_default();
32    let mut result = AgentSetupResult::default();
33
34    // #281: honor `[setup] auto_update_mcp = false` — skip MCP registration but
35    // still install the hook, rules and skill. Locked-down environments can keep
36    // the MCP server out of agent settings without losing the CLI integration.
37    // The MCP entry goes first: the hook step denies native search (Claude
38    // Code's Grep/Glob) only where the lean-ctx server that replaces it exists.
39    if lean_ctx::core::config::Config::load()
40        .setup
41        .should_update_mcp()
42    {
43        match configure_agent_mcp(agent_name) {
44            Ok(()) => result.mcp_ok = true,
45            Err(e) => result.errors.push(format!("MCP config: {e}")),
46        }
47    } else {
48        result.mcp_skipped = true;
49    }
50
51    lean_ctx_hooks::hooks::install_agent_hook_respecting_rules_off(agent_name, global, mode);
52
53    result.rules = lean_ctx::rules_inject::inject_rules_for_agent(&home, agent_name);
54
55    if let Ok(path) = lean_ctx::rules_inject::install_skill_for_agent(&home, agent_name) {
56        result.skill_installed = path.exists();
57    }
58
59    result
60}
61
62pub fn configure_agent_mcp(agent: &str) -> Result<(), String> {
63    let allow_rule_steering = lean_ctx::core::config::Config::load().rules_injection_effective()
64        != lean_ctx::core::config::RulesInjection::Off;
65
66    configure_agent_mcp_with_rule_steering(agent, allow_rule_steering)
67}
68
69pub(crate) fn configure_agent_mcp_with_rule_steering(
70    agent: &str,
71    allow_rule_steering: bool,
72) -> Result<(), String> {
73    // Prefer HOME/USERPROFILE (dirs::home_dir ignores env on Windows).
74    let home = lean_ctx::core::home::resolve_home_dir()
75        .ok_or_else(|| "Cannot determine home directory".to_string())?;
76    let binary = resolve_agent_binary();
77
78    let targets = agent_mcp_targets(agent, &home)?;
79
80    let mut errors = Vec::new();
81    for t in &targets {
82        if let Err(e) = lean_ctx::core::editor_registry::write_config_with_options_and_rule_steering(
83            t,
84            &binary,
85            WriteOptions {
86                overwrite_invalid: true,
87            },
88            allow_rule_steering,
89        ) {
90            eprintln!(
91                "\x1b[33m⚠\x1b[0m  Could not configure {}: {}",
92                t.config_path.display(),
93                e
94            );
95            errors.push(e);
96        }
97    }
98
99    if agent == "kiro" && allow_rule_steering {
100        install_kiro_steering(&home);
101    }
102
103    if (agent == "vscode" || agent == "copilot")
104        && let Err(e) = lean_ctx::core::editor_registry::plan_mode::write_vscode_plan_settings()
105    {
106        eprintln!("\x1b[33m⚠\x1b[0m  VS Code plan mode: {e}");
107    }
108    // The governor setup has no lean-ctx MCP tools to allow in plan mode.
109    if (agent == "claude" || agent == "claude-code")
110        && !lean_ctx_hooks::hooks::agents::claude_governor::is_installed(&home)
111        && let Err(e) =
112            lean_ctx::core::editor_registry::plan_mode::write_claude_code_plan_permissions()
113    {
114        eprintln!("\x1b[33m⚠\x1b[0m  Claude Code plan mode: {e}");
115    }
116    if agent == "codebuddy"
117        && let Err(e) =
118            lean_ctx::core::editor_registry::plan_mode::write_claude_code_plan_permissions()
119    {
120        eprintln!("\x1b[33m⚠\x1b[0m  CodeBuddy plan mode: {e}");
121    }
122
123    if errors.is_empty() {
124        Ok(())
125    } else {
126        Err(format!(
127            "{} config(s) could not be written. See warnings above.",
128            errors.len()
129        ))
130    }
131}
132
133pub(crate) fn agent_mcp_targets(
134    agent: &str,
135    home: &std::path::Path,
136) -> Result<Vec<EditorTarget>, String> {
137    let mut targets = Vec::<EditorTarget>::new();
138
139    let push = |targets: &mut Vec<EditorTarget>,
140                name: &'static str,
141                config_path: PathBuf,
142                config_type: ConfigType| {
143        targets.push(EditorTarget {
144            name,
145            agent_key: agent.to_string(),
146            detect_path: PathBuf::from("/nonexistent"), // not used in direct agent config
147            config_path,
148            config_type,
149        });
150    };
151
152    match agent {
153        "cursor" => push(
154            &mut targets,
155            "Cursor",
156            home.join(".cursor/mcp.json"),
157            ConfigType::McpJson,
158        ),
159        "claude" | "claude-code" => push(
160            &mut targets,
161            "Claude Code",
162            lean_ctx::core::editor_registry::claude_mcp_json_path(home),
163            ConfigType::McpJson,
164        ),
165        "codebuddy" => push(
166            &mut targets,
167            "CodeBuddy",
168            lean_ctx::core::editor_registry::codebuddy_mcp_json_path(home),
169            ConfigType::McpJson,
170        ),
171        "commandcode" => push(
172            &mut targets,
173            "Command Code",
174            home.join(".commandcode/mcp.json"),
175            ConfigType::CommandCode,
176        ),
177        "augment" => {
178            push(
179                &mut targets,
180                "Augment CLI",
181                lean_ctx::core::editor_registry::augment_cli_settings_path(home),
182                ConfigType::McpJson,
183            );
184            push(
185                &mut targets,
186                "Augment (VS Code)",
187                lean_ctx::core::editor_registry::augment_vscode_mcp_path(home),
188                ConfigType::AugmentVsCode,
189            );
190        }
191        "windsurf" => push(
192            &mut targets,
193            "Windsurf",
194            home.join(".codeium/windsurf/mcp_config.json"),
195            ConfigType::McpJson,
196        ),
197        "codex" => push(
198            &mut targets,
199            "Codex CLI",
200            lean_ctx::core::home::resolve_codex_config_path()
201                .unwrap_or_else(|| home.join(".codex/config.toml")),
202            ConfigType::Codex,
203        ),
204        "grok" => push(
205            &mut targets,
206            "Grok",
207            home.join(".grok/config.toml"),
208            ConfigType::Codex,
209        ),
210        "gemini" => {
211            push(
212                &mut targets,
213                "Gemini CLI",
214                home.join(".gemini/settings.json"),
215                ConfigType::GeminiSettings,
216            );
217            push(
218                &mut targets,
219                "Antigravity IDE",
220                home.join(".gemini/antigravity/mcp_config.json"),
221                ConfigType::McpJson,
222            );
223            push(
224                &mut targets,
225                "Antigravity CLI",
226                home.join(".gemini/antigravity-cli/mcp_config.json"),
227                ConfigType::McpJson,
228            );
229        }
230        "antigravity" => push(
231            &mut targets,
232            "Antigravity IDE",
233            home.join(".gemini/antigravity/mcp_config.json"),
234            ConfigType::McpJson,
235        ),
236        "antigravity-cli" => push(
237            &mut targets,
238            "Antigravity CLI",
239            home.join(".gemini/antigravity-cli/mcp_config.json"),
240            ConfigType::McpJson,
241        ),
242        "copilot" => push(
243            &mut targets,
244            "Copilot CLI",
245            home.join(".copilot/mcp-config.json"),
246            ConfigType::CopilotCli,
247        ),
248        "crush" => push(
249            &mut targets,
250            "Crush",
251            home.join(".config/crush/crush.json"),
252            ConfigType::Crush,
253        ),
254        "qoder" => {
255            for path in lean_ctx::core::editor_registry::qoder_all_mcp_paths(home) {
256                push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
257            }
258        }
259        "qoderwork" => push(
260            &mut targets,
261            "QoderWork",
262            lean_ctx::core::editor_registry::qoderwork_mcp_path(home),
263            ConfigType::McpJson,
264        ),
265        "qodercli" => push(
266            &mut targets,
267            "Qoder CLI",
268            lean_ctx::core::editor_registry::qodercli_settings_path(home),
269            ConfigType::QoderSettings,
270        ),
271        "cline" => push(
272            &mut targets,
273            "Cline",
274            lean_ctx::core::editor_registry::cline_mcp_path(),
275            ConfigType::McpJson,
276        ),
277        "cline-cli" => push(
278            &mut targets,
279            "Cline CLI",
280            lean_ctx::core::editor_registry::cline_cli_mcp_settings_path(),
281            ConfigType::ClineCli,
282        ),
283        "omp" => push(
284            &mut targets,
285            "Oh My Pi",
286            lean_ctx::core::editor_registry::omp_mcp_path(home),
287            ConfigType::OmpMcp,
288        ),
289        "roo" => push(
290            &mut targets,
291            "Roo Code",
292            lean_ctx::core::editor_registry::roo_mcp_path(),
293            ConfigType::McpJson,
294        ),
295        "kiro" => push(
296            &mut targets,
297            "AWS Kiro",
298            home.join(".kiro/settings/mcp.json"),
299            ConfigType::McpJson,
300        ),
301        "verdent" => push(
302            &mut targets,
303            "Verdent",
304            home.join(".verdent/mcp.json"),
305            ConfigType::McpJson,
306        ),
307        // pi: deliberately no MCP target. Pi has no native MCP adapter — a
308        // ~/.pi/agent/mcp.json entry is never served and made older pi-lean-ctx
309        // versions disable their embedded bridge (GitHub #361). Pi runs through
310        // the pi-lean-ctx npm package; install_pi_hook_with_mode removes stale
311        // entries instead.
312        "pi" | "jetbrains" | "amp" | "openclaw" => {
313            // jetbrains/amp/openclaw: handled by dedicated install hooks
314            // (servers[] array / amp.mcpServers / mcp.servers).
315        }
316        "qwen" => push(
317            &mut targets,
318            "Qwen Code",
319            home.join(".qwen/settings.json"),
320            ConfigType::McpJson,
321        ),
322        "trae" => push(
323            &mut targets,
324            "Trae",
325            home.join(".trae/mcp.json"),
326            ConfigType::McpJson,
327        ),
328        // #1402: resolves `~/.codewhale/mcp.json`, or the legacy
329        // `~/.deepseek/mcp.json` when that is the file CodeWhale still reads.
330        "codewhale" => push(
331            &mut targets,
332            "CodeWhale",
333            lean_ctx::core::editor_registry::codewhale_mcp_json_path(home),
334            ConfigType::CodeWhale,
335        ),
336        // #2198: `$XDG_CONFIG_HOME/muse/settings.json` (default ~/.config/muse).
337        "muse" => push(
338            &mut targets,
339            "Muse Code",
340            lean_ctx::core::editor_registry::muse_settings_path(home),
341            ConfigType::MuseSettings,
342        ),
343        "amazonq" => push(
344            &mut targets,
345            "Amazon Q Developer",
346            home.join(".aws/amazonq/default.json"),
347            ConfigType::McpJson,
348        ),
349        "opencode" => {
350            // #1585: write into the user's existing opencode.jsonc when that is
351            // the file they have, instead of creating a competing opencode.json.
352            let opencode_path = lean_ctx::core::opencode_config::resolve(home).path;
353            push(
354                &mut targets,
355                "OpenCode",
356                opencode_path,
357                ConfigType::OpenCode,
358            );
359        }
360        "hermes" => push(
361            &mut targets,
362            "Hermes Agent",
363            home.join(".hermes/config.yaml"),
364            ConfigType::HermesYaml,
365        ),
366        "vscode" => push(
367            &mut targets,
368            "VS Code",
369            lean_ctx::core::editor_registry::vscode_mcp_path(),
370            ConfigType::VsCodeMcp,
371        ),
372        "vscode-insiders" => push(
373            &mut targets,
374            "VS Code Insiders",
375            lean_ctx::core::editor_registry::vscode_insiders_mcp_path(),
376            ConfigType::VsCodeMcp,
377        ),
378        "zed" => push(
379            &mut targets,
380            "Zed",
381            lean_ctx::core::editor_registry::zed_settings_path(home),
382            ConfigType::Zed,
383        ),
384        "aider" => push(
385            &mut targets,
386            "Aider",
387            home.join(".aider/mcp.json"),
388            ConfigType::McpJson,
389        ),
390        "goose" => push(
391            &mut targets,
392            "Goose",
393            lean_ctx::core::editor_registry::goose_config_dir(&home).join("config.yaml"),
394            ConfigType::GooseYaml,
395        ),
396        "continue" => push(
397            &mut targets,
398            "Continue",
399            home.join(".continue/mcp.json"),
400            ConfigType::McpJson,
401        ),
402        "neovim" => push(
403            &mut targets,
404            "Neovim (mcphub.nvim)",
405            home.join(".config/mcphub/servers.json"),
406            ConfigType::McpJson,
407        ),
408        "emacs" => push(
409            &mut targets,
410            "Emacs (mcp.el)",
411            home.join(".emacs.d/mcp.json"),
412            ConfigType::McpJson,
413        ),
414        "sublime" => push(
415            &mut targets,
416            "Sublime Text",
417            home.join(".config/sublime-text/mcp.json"),
418            ConfigType::McpJson,
419        ),
420        _ => {
421            return Err(format!("Unknown agent '{agent}'"));
422        }
423    }
424
425    Ok(targets)
426}
427
428pub fn disable_agent_mcp(agent: &str, overwrite_invalid: bool) -> Result<(), String> {
429    // Prefer HOME/USERPROFILE (dirs::home_dir ignores env on Windows).
430    let home = lean_ctx::core::home::resolve_home_dir()
431        .ok_or_else(|| "Cannot determine home directory".to_string())?;
432
433    let mut targets = Vec::<EditorTarget>::new();
434
435    let push = |targets: &mut Vec<EditorTarget>,
436                name: &'static str,
437                config_path: PathBuf,
438                config_type: ConfigType| {
439        targets.push(EditorTarget {
440            name,
441            agent_key: agent.to_string(),
442            detect_path: PathBuf::from("/nonexistent"),
443            config_path,
444            config_type,
445        });
446    };
447
448    let pi_cfg = home.join(".pi").join("agent").join("mcp.json");
449
450    match agent {
451        "cursor" => push(
452            &mut targets,
453            "Cursor",
454            home.join(".cursor/mcp.json"),
455            ConfigType::McpJson,
456        ),
457        "claude" | "claude-code" => push(
458            &mut targets,
459            "Claude Code",
460            lean_ctx::core::editor_registry::claude_mcp_json_path(&home),
461            ConfigType::McpJson,
462        ),
463        "codebuddy" => push(
464            &mut targets,
465            "CodeBuddy",
466            lean_ctx::core::editor_registry::codebuddy_mcp_json_path(&home),
467            ConfigType::McpJson,
468        ),
469        "commandcode" => push(
470            &mut targets,
471            "Command Code",
472            home.join(".commandcode/mcp.json"),
473            ConfigType::CommandCode,
474        ),
475        "augment" => {
476            push(
477                &mut targets,
478                "Augment CLI",
479                lean_ctx::core::editor_registry::augment_cli_settings_path(&home),
480                ConfigType::McpJson,
481            );
482            push(
483                &mut targets,
484                "Augment (VS Code)",
485                lean_ctx::core::editor_registry::augment_vscode_mcp_path(&home),
486                ConfigType::AugmentVsCode,
487            );
488        }
489        "windsurf" => push(
490            &mut targets,
491            "Windsurf",
492            home.join(".codeium/windsurf/mcp_config.json"),
493            ConfigType::McpJson,
494        ),
495        "codex" => push(
496            &mut targets,
497            "Codex CLI",
498            lean_ctx::core::home::resolve_codex_config_path()
499                .unwrap_or_else(|| home.join(".codex/config.toml")),
500            ConfigType::Codex,
501        ),
502        "grok" => push(
503            &mut targets,
504            "Grok",
505            home.join(".grok/config.toml"),
506            ConfigType::Codex,
507        ),
508        "gemini" => {
509            push(
510                &mut targets,
511                "Gemini CLI",
512                home.join(".gemini/settings.json"),
513                ConfigType::GeminiSettings,
514            );
515            push(
516                &mut targets,
517                "Antigravity IDE",
518                home.join(".gemini/antigravity/mcp_config.json"),
519                ConfigType::McpJson,
520            );
521            push(
522                &mut targets,
523                "Antigravity CLI",
524                home.join(".gemini/antigravity-cli/mcp_config.json"),
525                ConfigType::McpJson,
526            );
527        }
528        "antigravity" => push(
529            &mut targets,
530            "Antigravity IDE",
531            home.join(".gemini/antigravity/mcp_config.json"),
532            ConfigType::McpJson,
533        ),
534        "antigravity-cli" => push(
535            &mut targets,
536            "Antigravity CLI",
537            home.join(".gemini/antigravity-cli/mcp_config.json"),
538            ConfigType::McpJson,
539        ),
540        "copilot" => push(
541            &mut targets,
542            "Copilot CLI",
543            home.join(".copilot/mcp-config.json"),
544            ConfigType::CopilotCli,
545        ),
546        "crush" => push(
547            &mut targets,
548            "Crush",
549            home.join(".config/crush/crush.json"),
550            ConfigType::Crush,
551        ),
552        "pi" => push(&mut targets, "Pi Coding Agent", pi_cfg, ConfigType::McpJson),
553        "qoder" => {
554            for path in lean_ctx::core::editor_registry::qoder_all_mcp_paths(&home) {
555                push(&mut targets, "Qoder", path, ConfigType::QoderSettings);
556            }
557        }
558        "qoderwork" => push(
559            &mut targets,
560            "QoderWork",
561            lean_ctx::core::editor_registry::qoderwork_mcp_path(&home),
562            ConfigType::McpJson,
563        ),
564        "qodercli" => push(
565            &mut targets,
566            "Qoder CLI",
567            lean_ctx::core::editor_registry::qodercli_settings_path(&home),
568            ConfigType::QoderSettings,
569        ),
570        "cline" => push(
571            &mut targets,
572            "Cline",
573            lean_ctx::core::editor_registry::cline_mcp_path(),
574            ConfigType::McpJson,
575        ),
576        "cline-cli" => push(
577            &mut targets,
578            "Cline CLI",
579            lean_ctx::core::editor_registry::cline_cli_mcp_settings_path(),
580            ConfigType::ClineCli,
581        ),
582        "omp" => push(
583            &mut targets,
584            "Oh My Pi",
585            lean_ctx::core::editor_registry::omp_mcp_path(&home),
586            ConfigType::OmpMcp,
587        ),
588        "roo" => push(
589            &mut targets,
590            "Roo Code",
591            lean_ctx::core::editor_registry::roo_mcp_path(),
592            ConfigType::McpJson,
593        ),
594        "kiro" => push(
595            &mut targets,
596            "AWS Kiro",
597            home.join(".kiro/settings/mcp.json"),
598            ConfigType::McpJson,
599        ),
600        "verdent" => push(
601            &mut targets,
602            "Verdent",
603            home.join(".verdent/mcp.json"),
604            ConfigType::McpJson,
605        ),
606        "jetbrains" | "amp" | "openclaw" => {
607            // Not supported for disable via this helper.
608        }
609        "qwen" => push(
610            &mut targets,
611            "Qwen Code",
612            home.join(".qwen/settings.json"),
613            ConfigType::McpJson,
614        ),
615        "trae" => push(
616            &mut targets,
617            "Trae",
618            home.join(".trae/mcp.json"),
619            ConfigType::McpJson,
620        ),
621        // #1402: same resolution as the enable path — disable must visit the
622        // exact file we wrote, never the shadowed legacy one.
623        "codewhale" => push(
624            &mut targets,
625            "CodeWhale",
626            lean_ctx::core::editor_registry::codewhale_mcp_json_path(home.as_ref()),
627            ConfigType::CodeWhale,
628        ),
629        "muse" => push(
630            &mut targets,
631            "Muse Code",
632            lean_ctx::core::editor_registry::muse_settings_path(home.as_ref()),
633            ConfigType::MuseSettings,
634        ),
635        "amazonq" => push(
636            &mut targets,
637            "Amazon Q Developer",
638            home.join(".aws/amazonq/default.json"),
639            ConfigType::McpJson,
640        ),
641        "opencode" => {
642            // #1585: write into the user's existing opencode.jsonc when that is
643            // the file they have, instead of creating a competing opencode.json.
644            let opencode_path = lean_ctx::core::opencode_config::resolve(home.as_ref()).path;
645            push(
646                &mut targets,
647                "OpenCode",
648                opencode_path,
649                ConfigType::OpenCode,
650            );
651        }
652        "hermes" => push(
653            &mut targets,
654            "Hermes Agent",
655            home.join(".hermes/config.yaml"),
656            ConfigType::HermesYaml,
657        ),
658        "vscode" => push(
659            &mut targets,
660            "VS Code",
661            lean_ctx::core::editor_registry::vscode_mcp_path(),
662            ConfigType::VsCodeMcp,
663        ),
664        "vscode-insiders" => push(
665            &mut targets,
666            "VS Code Insiders",
667            lean_ctx::core::editor_registry::vscode_insiders_mcp_path(),
668            ConfigType::VsCodeMcp,
669        ),
670        "zed" => push(
671            &mut targets,
672            "Zed",
673            lean_ctx::core::editor_registry::zed_settings_path(&home),
674            ConfigType::Zed,
675        ),
676        "aider" => push(
677            &mut targets,
678            "Aider",
679            home.join(".aider/mcp.json"),
680            ConfigType::McpJson,
681        ),
682        "goose" => push(
683            &mut targets,
684            "Goose",
685            lean_ctx::core::editor_registry::goose_config_dir(&home).join("config.yaml"),
686            ConfigType::GooseYaml,
687        ),
688        "continue" => push(
689            &mut targets,
690            "Continue",
691            home.join(".continue/mcp.json"),
692            ConfigType::McpJson,
693        ),
694        "neovim" => push(
695            &mut targets,
696            "Neovim (mcphub.nvim)",
697            home.join(".config/mcphub/servers.json"),
698            ConfigType::McpJson,
699        ),
700        "emacs" => push(
701            &mut targets,
702            "Emacs (mcp.el)",
703            home.join(".emacs.d/mcp.json"),
704            ConfigType::McpJson,
705        ),
706        "sublime" => push(
707            &mut targets,
708            "Sublime Text",
709            home.join(".config/sublime-text/mcp.json"),
710            ConfigType::McpJson,
711        ),
712        _ => {
713            return Err(format!("Unknown agent '{agent}'"));
714        }
715    }
716
717    for t in &targets {
718        lean_ctx::core::editor_registry::remove_lean_ctx_server(
719            t,
720            WriteOptions { overwrite_invalid },
721        )?;
722    }
723
724    Ok(())
725}
726
727#[cfg(test)]
728mod qodercli_tests {
729    use super::*;
730    use lean_ctx::test_env::CurrentDirGuard;
731
732    #[test]
733    fn kiro_mcp_configuration_respects_rule_steering_policy() {
734        let _env_lock = lean_ctx::core::data_dir::test_env_lock();
735        let tmp = tempfile::tempdir().unwrap();
736        let home = tmp.path().join("home");
737        let project = tmp.path().join("project");
738
739        std::fs::create_dir_all(&home).unwrap();
740        std::fs::create_dir_all(&project).unwrap();
741
742        let _home_guard =
743            lean_ctx::test_env::EnvVarGuard::set("HOME", home.to_string_lossy().as_ref());
744        let _profile_guard =
745            lean_ctx::test_env::EnvVarGuard::set("USERPROFILE", home.to_string_lossy().as_ref());
746        let _cwd_guard = CurrentDirGuard::enter(&project);
747
748        configure_agent_mcp_with_rule_steering("kiro", false).unwrap();
749
750        assert!(
751            home.join(".kiro/settings/mcp.json").exists(),
752            "Kiro MCP registration must still be written when steering is disabled"
753        );
754
755        let steering = project.join(".kiro/steering/lean-ctx.md");
756
757        assert!(
758            !steering.exists(),
759            "steering-disabled Kiro setup must not create lean-ctx steering"
760        );
761
762        configure_agent_mcp_with_rule_steering("kiro", true).unwrap();
763
764        assert!(
765            steering.exists(),
766            "test precondition failed: steering-enabled Kiro setup should create its steering file"
767        );
768    }
769
770    #[test]
771    fn commandcode_agent_target_uses_command_code_schema() {
772        let home = std::path::Path::new("/home/tester");
773        let targets = agent_mcp_targets("commandcode", home).unwrap();
774
775        assert_eq!(targets.len(), 1);
776        assert_eq!(targets[0].name, "Command Code");
777        assert_eq!(targets[0].config_path, home.join(".commandcode/mcp.json"));
778        assert_eq!(targets[0].config_type, ConfigType::CommandCode);
779    }
780
781    #[test]
782    fn codewhale_agent_target_uses_codewhale_schema_and_current_path() {
783        // No `~/.codewhale` or `~/.deepseek` exists under this synthetic home,
784        // so resolution must land on the current path, not the legacy one.
785        let home = std::path::Path::new("/home/tester");
786        let targets = agent_mcp_targets("codewhale", home).unwrap();
787
788        assert_eq!(targets.len(), 1);
789        assert_eq!(targets[0].name, "CodeWhale");
790        assert_eq!(targets[0].agent_key, "codewhale");
791        assert_eq!(targets[0].config_type, ConfigType::CodeWhale);
792        assert_eq!(targets[0].config_path, home.join(".codewhale/mcp.json"));
793    }
794
795    #[test]
796    fn codewhale_agent_target_follows_legacy_deepseek_config_when_that_is_the_live_one() {
797        let tmp = tempfile::tempdir().unwrap();
798        let home = tmp.path();
799        std::fs::create_dir_all(home.join(".deepseek")).unwrap();
800        std::fs::write(home.join(".deepseek/mcp.json"), "{}").unwrap();
801
802        let targets = agent_mcp_targets("codewhale", home).unwrap();
803        assert_eq!(targets[0].config_path, home.join(".deepseek/mcp.json"));
804    }
805
806    #[test]
807    fn muse_agent_target_uses_muse_settings_schema_and_path() {
808        let home = std::path::Path::new("/home/tester");
809        let targets = agent_mcp_targets("muse", home).unwrap();
810
811        assert_eq!(targets.len(), 1);
812        assert_eq!(targets[0].name, "Muse Code");
813        assert_eq!(targets[0].agent_key, "muse");
814        assert_eq!(targets[0].config_type, ConfigType::MuseSettings);
815        assert_eq!(
816            targets[0].config_path,
817            lean_ctx::core::editor_registry::muse_settings_path(home)
818        );
819    }
820
821    #[test]
822    fn cline_cli_agent_target_uses_cline_cli_schema() {
823        let home = std::path::Path::new("/home/tester");
824        let targets = agent_mcp_targets("cline-cli", home).unwrap();
825
826        assert_eq!(targets.len(), 1);
827        assert_eq!(targets[0].name, "Cline CLI");
828        assert_eq!(targets[0].config_type, ConfigType::ClineCli);
829    }
830
831    #[test]
832    fn omp_agent_target_uses_the_native_agent_dir_and_schema() {
833        let home = std::path::Path::new("/home/tester");
834        let targets = agent_mcp_targets("omp", home).unwrap();
835
836        assert_eq!(targets.len(), 1);
837        assert_eq!(targets[0].name, "Oh My Pi");
838        assert_eq!(
839            targets[0].config_path,
840            lean_ctx::core::editor_registry::omp_mcp_path(home)
841        );
842        assert_eq!(targets[0].config_type, ConfigType::OmpMcp);
843        // Default layout only holds when the environment does not relocate the
844        // OMP agent dir; PI_CODING_AGENT_DIR is a documented full override.
845        if std::env::var_os("PI_CODING_AGENT_DIR").is_none() {
846            assert_eq!(targets[0].config_path, home.join(".omp/agent/mcp.json"));
847        }
848    }
849
850    #[test]
851    fn omp_and_pi_stay_separate_setup_targets() {
852        let home = std::path::Path::new("/home/tester");
853        let omp = agent_mcp_targets("omp", home).unwrap();
854        let pi = agent_mcp_targets("pi", home).unwrap();
855        assert!(
856            pi.iter().all(|t| t.config_path != omp[0].config_path),
857            "Oh My Pi must not write into the stock Pi config"
858        );
859    }
860
861    #[test]
862    fn qodercli_agent_target_uses_settings_json() {
863        let home = std::path::Path::new("/home/tester");
864        let targets = agent_mcp_targets("qodercli", home).unwrap();
865
866        assert_eq!(targets.len(), 1);
867        assert_eq!(targets[0].name, "Qoder CLI");
868        assert_eq!(targets[0].config_path, home.join(".qoder/settings.json"));
869    }
870
871    #[test]
872    fn qodercli_agent_target_uses_qoder_settings_writer() {
873        let home = std::path::Path::new("/home/tester");
874        let targets = agent_mcp_targets("qodercli", home).unwrap();
875
876        assert_eq!(targets[0].agent_key, "qodercli");
877        assert_eq!(targets[0].config_type, ConfigType::QoderSettings);
878    }
879
880    #[test]
881    fn qodercli_agent_target_is_separate_from_qoder_ide_targets() {
882        let home = std::path::Path::new("/home/tester");
883        let cli = agent_mcp_targets("qodercli", home).unwrap();
884        let ide = agent_mcp_targets("qoder", home).unwrap();
885
886        assert!(
887            ide.iter()
888                .all(|target| target.config_path != cli[0].config_path)
889        );
890    }
891}