Skip to main content

agentmux_srv_core/backend/
agent_mcp_flag.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! The MCP config flags of a Claude turn: which config file Claude is pointed at, and when it is told to read
5//! no other. `agent_runtime::with_runtime_flags` adds them after the model and permission flags.
6
7use crate::backend::obj::MetaMapType;
8
9/// Point a Claude turn at the agent's MCP config when it lives outside the working directory
10/// (#3680): a launch into the user's own project writes it under AgentMux's data root, which
11/// Claude does not find on its own. `--mcp-config` adds it to whatever Claude already reads, so
12/// the project's own `.mcp.json` keeps reaching it. Every other harness is handed the servers by
13/// srv (`mcp_config_file::read_for_turn`), so it needs no flag.
14///
15/// Never overrides a `--mcp-config` already in the argv (an agent's own provider flags), and
16/// idempotent, so a pane that spawns through more than one of the paths gets one flag.
17///
18/// A host agent in a folder a container agent can write is the exception: there Claude is given
19/// AgentMux's own config, settings, instructions and skills, and told to read no other
20/// ([`with_nothing_of_the_folder`]).
21pub(crate) fn with_mcp_config_flag(meta: &MetaMapType, mut args: Vec<String>) -> Vec<String> {
22    let provider = crate::backend::providers::resolve_provider_alias(&crate::backend::obj::meta_get_string(meta, "agentProvider", ""));
23    if provider != "claude" {
24        return args;
25    }
26    let work_dir = crate::backend::obj::meta_get_string(meta, "cmd:cwd", "");
27    if work_dir.trim().is_empty() {
28        return args;
29    }
30    if crate::backend::mcp_folder_rule::folder_of(meta).is_some() {
31        return with_nothing_of_the_folder(args, &work_dir);
32    }
33    if crate::backend::agent_runtime::flag_value(&args, &["--mcp-config"]).is_some() {
34        return args;
35    }
36    let Some(path) = crate::backend::mcp_config_file::relocated_path(&work_dir) else {
37        return args;
38    };
39    if !path.is_file() {
40        return args;
41    }
42    let runtime = crate::backend::runtime_adapter::RuntimeKind::of_block_meta(meta);
43    let shown = runtime
44        .adapter()
45        .map_mount(crate::backend::runtime_adapter::MountRole::McpConfig, &path.to_string_lossy());
46    args.push("--mcp-config".to_string());
47    args.push(shown);
48    args
49}
50
51/// A Claude turn on the host in a folder a container agent can write (`mcp_folder_rule`): the CLI takes its
52/// MCP servers, settings, instructions and skills from AgentMux's own files outside the folder
53/// (`host_agent_files`), and nothing of the folder's.
54///
55/// - `--strict-mcp-config` leaves out the servers Claude would read on its own (the folder's `.mcp.json`, the
56///   account's, a plugin's), and `--mcp-config` names AgentMux's file. A config that is not there yet, or that
57///   names a command by a bare name, leaves the turn with no servers until the next launch or repair writes it.
58/// - `--setting-sources user` leaves out the folder's settings (and with them its hooks and environment), its
59///   instruction files, skills, commands, subagents, output styles, workflows and the plugins its settings
60///   turn on. `--settings` names AgentMux's own settings.
61/// - `--add-dir` names the folder that holds the agent's startup instructions and nothing else, and
62///   `--plugin-dir` the one that holds its skills and commands.
63///
64/// What the argv already had of these goes: a flag AgentMux sets itself (`--mcp-config`, `--settings`,
65/// `--setting-sources`), and any flag that names a file or folder a container agent can write, or one that is
66/// not written as an absolute path. Idempotent.
67fn with_nothing_of_the_folder(args: Vec<String>, work_dir: &str) -> Vec<String> {
68    use crate::backend::host_agent_files as own;
69    const STRICT: &str = "--strict-mcp-config";
70    const CONFIG: &str = "--mcp-config";
71    const SOURCES: &str = "--setting-sources";
72    const SETTINGS: &str = "--settings";
73    const ADD_DIR: &str = "--add-dir";
74    const PLUGIN_DIR: &str = "--plugin-dir";
75    /// Flags AgentMux sets itself there: whatever the argv had of them goes, with every value.
76    const OURS: &[&str] = &[CONFIG, SOURCES, SETTINGS];
77    /// Flags that name a file or folder: a value stays only when it is outside every folder a container agent
78    /// can write.
79    const NAMES_A_PATH: &[&str] = &[ADD_DIR, PLUGIN_DIR, "--append-system-prompt-file", "--system-prompt-file", "--agents"];
80
81    let config = crate::backend::mcp_config_file::host_config_path(work_dir);
82    let dir = own::dir_of(work_dir);
83    let given = |path: std::path::PathBuf, there: bool| there.then(|| path.to_string_lossy().into_owned());
84    let settings = dir.as_deref().and_then(|d| given(own::settings_path(d), own::settings_path(d).is_file()));
85    let instructions = dir.as_deref().and_then(|d| given(own::instructions_dir(d), own::instructions_path(d).is_file()));
86    let plugin = dir.as_deref().and_then(|d| given(own::plugin_dir(d), own::plugin_dir(d).join(".claude-plugin").join("plugin.json").is_file()));
87    let is_ours = |value: &str| [&instructions, &plugin].into_iter().flatten().any(|path| path == value);
88    // An inline JSON value (`--agents '{...}'`) names no file.
89    let stays = |flag: &str, value: &str| {
90        let inline = flag == "--agents" && value.trim_start().starts_with('{');
91        !is_ours(value) && (inline || (std::path::Path::new(value).is_absolute() && !crate::backend::mcp_folder_rule::holds_in(value)))
92    };
93
94    let mut out = Vec::with_capacity(args.len() + 10);
95    let mut next = 0;
96    while next < args.len() {
97        let arg = &args[next];
98        next += 1;
99        if arg == STRICT {
100            continue;
101        }
102        let (flag, inline) = match arg.split_once('=') {
103            Some((flag, value)) if flag.starts_with("--") => (flag, Some(value)),
104            _ => (arg.as_str(), None),
105        };
106        let (ours, names_a_path) = (OURS.contains(&flag), NAMES_A_PATH.contains(&flag));
107        if !ours && !names_a_path {
108            out.push(arg.clone());
109            continue;
110        }
111        // Its values: the one written with it, or what follows up to the next flag (one value, except for the
112        // two flags that take several).
113        let mut values: Vec<&str> = inline.into_iter().collect();
114        if inline.is_none() {
115            let several = flag == CONFIG || flag == ADD_DIR;
116            while next < args.len() && !args[next].starts_with('-') && (several || values.is_empty()) {
117                values.push(&args[next]);
118                next += 1;
119            }
120        }
121        if ours {
122            continue;
123        }
124        let kept: Vec<String> = values.into_iter().filter(|value| stays(flag, value)).map(str::to_string).collect();
125        if !kept.is_empty() {
126            out.push(flag.to_string());
127            out.extend(kept);
128        }
129    }
130
131    out.push(STRICT.to_string());
132    // Only a config whose every command is a path outside the folder, in none a container agent can write, is
133    // handed over.
134    if std::fs::read_to_string(&config).is_ok_and(|text| crate::backend::mcp_folder_rule::names_every_command_outside(&text, work_dir)) {
135        out.extend([CONFIG.to_string(), config.to_string_lossy().into_owned()]);
136    }
137    out.extend([SOURCES.to_string(), "user".to_string()]);
138    for (flag, value) in [(SETTINGS, settings), (ADD_DIR, instructions), (PLUGIN_DIR, plugin)] {
139        if let Some(value) = value {
140            out.extend([flag.to_string(), value]);
141        }
142    }
143    out
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149    use crate::backend::agent_runtime::with_runtime_flags;
150    use serde_json::json;
151
152    fn s(v: &[&str]) -> Vec<String> {
153        v.iter().map(|x| x.to_string()).collect()
154    }
155    fn after(args: &[String], flag: &str) -> Option<String> {
156        args.iter().position(|a| a == flag).and_then(|i| args.get(i + 1)).cloned()
157    }
158    fn meta_of(provider: &str) -> MetaMapType {
159        let mut m = MetaMapType::new();
160        m.insert("agentProvider".to_string(), json!(provider));
161        m
162    }
163
164    #[test]
165    fn a_claude_turn_in_a_folder_a_container_agent_can_write_reads_agentmuxs_config_alone() {
166        let (data, folder) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
167        let dir = folder.path().to_string_lossy().into_owned();
168        crate::backend::mcp_config_file::with_data_home(data.path(), || {
169            let mut meta = meta_of("claude");
170            meta.insert("cmd:cwd".to_string(), json!(dir));
171            crate::backend::mcp_folder_rule::mark(&dir);
172            let config = crate::backend::mcp_config_file::host_config_path(&dir);
173            let config_text = config.to_string_lossy().into_owned();
174
175            // Before AgentMux's config is written: no servers at all, never the folder's.
176            let bare = with_runtime_flags(&meta, s(&["-p"]));
177            assert!(bare.iter().any(|a| a == "--strict-mcp-config") && !bare.iter().any(|a| a == "--mcp-config"), "{bare:?}");
178
179            // A config that names the `agentmux` command by a bare name is not handed over either.
180            crate::backend::mcp_config_file::write_relocated(&config, r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#).unwrap();
181            let by_name = with_runtime_flags(&meta, s(&["-p"]));
182            assert!(by_name.iter().any(|a| a == "--strict-mcp-config") && !by_name.iter().any(|a| a == "--mcp-config"), "{by_name:?}");
183
184            let by_path = serde_json::json!({ "mcpServers": { "agentmux": { "command": data.path().join("tools").join("agentmux-mcp").to_string_lossy() } } });
185            crate::backend::mcp_config_file::write_relocated(&config, &by_path.to_string()).unwrap();
186            let own_flags = s(&["-p", "--mcp-config", ".mcp.json", "extra.json", "--model", "sonnet", "--mcp-config=other.json"]);
187            let out = with_runtime_flags(&meta, own_flags);
188            assert_eq!(out.iter().filter(|a| *a == "--strict-mcp-config").count(), 1, "{out:?}");
189            assert_eq!(out.iter().filter(|a| *a == "--mcp-config").count(), 1, "{out:?}");
190            assert_eq!(after(&out, "--mcp-config").as_deref(), Some(config_text.as_str()), "AgentMux's file outside the folder");
191            assert!(!out.iter().any(|a| a == ".mcp.json" || a == "extra.json" || a.starts_with("--mcp-config=")), "no other config is named: {out:?}");
192            assert_eq!(after(&out, "--model").as_deref(), Some("sonnet"), "the other flags stay");
193            assert_eq!(with_runtime_flags(&meta, out.clone()), out, "added once");
194
195            // The container agent itself, and a harness that is not Claude Code, get no such flags.
196            let mut container = meta.clone();
197            container.insert("agentMode".to_string(), json!("container"));
198            assert!(!with_runtime_flags(&container, s(&["-p"])).iter().any(|a| a == "--strict-mcp-config"));
199            let mut codex = meta.clone();
200            codex.insert("agentProvider".to_string(), json!("codex"));
201            assert!(!with_runtime_flags(&codex, s(&["exec", "-"])).iter().any(|a| a == "--strict-mcp-config"));
202        });
203    }
204
205    /// The files AgentMux gives a host agent there, as a launch writes them.
206    const LAUNCH: &[(&str, &str)] = &[
207        ("CLAUDE.md", "be kind"),
208        (".claude/settings.json", r#"{"hooks":{}}"#),
209        (".claude/skills/review/SKILL.md", "---\nname: review\n---\nbody"),
210        (".mcp.json", r#"{"mcpServers":{}}"#),
211    ];
212
213    #[test]
214    fn a_claude_turn_there_takes_its_settings_instructions_and_skills_from_agentmuxs_own_files() {
215        let (data, folder, elsewhere) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
216        let dir = folder.path().to_string_lossy().into_owned();
217        crate::backend::mcp_config_file::with_data_home(data.path(), || {
218            let mut meta = meta_of("claude");
219            meta.insert("cmd:cwd".to_string(), json!(dir));
220            crate::backend::mcp_folder_rule::mark(&dir);
221
222            // Before a launch has written anything: the folder's own is left out all the same.
223            let bare = with_runtime_flags(&meta, s(&["-p"]));
224            assert_eq!(after(&bare, "--setting-sources").as_deref(), Some("user"), "{bare:?}");
225            assert!(!bare.iter().any(|a| a == "--settings" || a == "--add-dir" || a == "--plugin-dir"), "nothing is named that is not there: {bare:?}");
226
227            assert_eq!(crate::backend::host_agent_files::write(&dir, LAUNCH.iter().copied()), Ok(true));
228            let own = crate::backend::host_agent_files::dir_of(&dir).unwrap();
229            let shown = |path: std::path::PathBuf| path.to_string_lossy().into_owned();
230            let out = with_runtime_flags(&meta, s(&["-p"]));
231            assert_eq!(after(&out, "--setting-sources").as_deref(), Some("user"));
232            assert_eq!(after(&out, "--settings"), Some(shown(crate::backend::host_agent_files::settings_path(&own))));
233            assert_eq!(after(&out, "--add-dir"), Some(shown(crate::backend::host_agent_files::instructions_dir(&own))));
234            assert_eq!(after(&out, "--plugin-dir"), Some(shown(crate::backend::host_agent_files::plugin_dir(&own))));
235            assert!(out.iter().any(|a| a == "--strict-mcp-config"));
236            assert!(!out.iter().any(|a| std::path::Path::new(a).starts_with(folder.path())), "no flag names a path in the folder: {out:?}");
237            assert_eq!(with_runtime_flags(&meta, out.clone()), out, "added once");
238
239            // The agent's own flags: what AgentMux sets itself is replaced, a path in the folder or a relative
240            // one goes, a path elsewhere and every other flag stay.
241            let kept_dir = elsewhere.path().to_string_lossy().into_owned();
242            let in_folder = folder.path().join("sub").to_string_lossy().into_owned();
243            let own_flags = s(&[
244                "-p", "--setting-sources", "user,project,local", "--settings", "mine.json", "--settings={\"env\":{}}", "--add-dir", &in_folder, &kept_dir, "rel/dir",
245                "--plugin-dir", &in_folder, "--plugin-dir", &kept_dir, "--append-system-prompt-file", "notes.md", "--system-prompt-file=prompt.md",
246                "--agents", "{\"helper\":{\"description\":\"d\",\"prompt\":\"p\"}}", "--agents", "agents.json", "--model", "sonnet", "--append-system-prompt", "be brief",
247            ]);
248            let out = with_runtime_flags(&meta, own_flags);
249            assert_eq!(out.iter().filter(|a| *a == "--setting-sources").count(), 1, "{out:?}");
250            assert_eq!(after(&out, "--setting-sources").as_deref(), Some("user"));
251            assert!(!out.iter().any(|a| a == "user,project,local" || a == "mine.json" || a.starts_with("--settings=")), "{out:?}");
252            assert_eq!(out.iter().filter(|a| *a == "--settings").count(), 1);
253            assert!(!out.iter().any(|a| a == &in_folder || a == "rel/dir" || a == "notes.md" || a == "agents.json" || a.contains("prompt.md")), "{out:?}");
254            assert_eq!(out.iter().filter(|a| *a == &kept_dir).count(), 2, "a folder elsewhere stays, for both flags: {out:?}");
255            assert!(out.iter().any(|a| a.starts_with("{\"helper\"")), "subagents written inline name no file: {out:?}");
256            assert!(!out.iter().any(|a| a == "--append-system-prompt-file" || a == "--system-prompt-file"), "a flag left with no value goes: {out:?}");
257            assert_eq!(after(&out, "--model").as_deref(), Some("sonnet"));
258            assert_eq!(after(&out, "--append-system-prompt").as_deref(), Some("be brief"));
259            assert_eq!(with_runtime_flags(&meta, out.clone()), out, "added once");
260
261            // A folder of the agent's own, the container agent itself and another harness get none of this.
262            let mut plain = meta_of("claude");
263            plain.insert("cmd:cwd".to_string(), json!(elsewhere.path().to_string_lossy()));
264            let mut container = meta.clone();
265            container.insert("agentMode".to_string(), json!("container"));
266            let mut codex = meta.clone();
267            codex.insert("agentProvider".to_string(), json!("codex"));
268            for (why, meta) in [("a folder of its own", plain), ("the container agent", container), ("another harness", codex)] {
269                let out = with_runtime_flags(&meta, s(&["-p", "--add-dir", "rel/dir"]));
270                assert!(!out.iter().any(|a| a == "--setting-sources" || a == "--settings" || a == "--plugin-dir"), "{why}: {out:?}");
271                assert_eq!(after(&out, "--add-dir").as_deref(), Some("rel/dir"), "{why}: its own flags are as it wrote them");
272            }
273        });
274    }
275
276    #[test]
277    fn a_claude_turn_in_a_folder_of_its_own_gets_no_strict_flag() {
278        let (data, folder) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
279        crate::backend::mcp_config_file::with_data_home(data.path(), || {
280            let mut meta = meta_of("claude");
281            meta.insert("cmd:cwd".to_string(), json!(folder.path().to_string_lossy()));
282            let own = s(&["-p", "--mcp-config", "mine.json"]);
283            assert_eq!(with_runtime_flags(&meta, own.clone()).iter().filter(|a| a.contains("mcp-config")).collect::<Vec<_>>(), vec!["--mcp-config"], "as before: the agent's own flag stays, nothing is added");
284        });
285    }
286}