Skip to main content

agentmux_srv_core/backend/
mcp_config_file.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where an agent's MCP config lives (#3680).
5//!
6//! An agent's `working_directory` may be the user's own project. A launch used to write
7//! `.mcp.json` there, which overwrote the project's own file and put the agent's signing
8//! keys where a routine `git add -A` could publish them. This module is the one answer to
9//! "where is this agent's MCP config":
10//!
11//! - In a folder AgentMux owns (under its data directory) the file stays where it has
12//!   always been, `<working directory>/.mcp.json`, which Claude Code reads on its own.
13//! - In a user's project the file moves to AgentMux's data directory, outside the project,
14//!   in a folder keyed by the project path: `<data dir>/mcp/<hash>/mcp.json`. Claude is
15//!   pointed at it with `--mcp-config` (it still reads the project's own `.mcp.json`
16//!   itself); every other harness is given the servers from it by srv. A launch never
17//!   writes into the project.
18//!
19//! The config has its own folder rather than a bare file because a container gets it as a
20//! bind mount. A single-file bind keeps the inode it was made with, so an atomic rewrite
21//! (a new inode) would leave a running container reading the old config; a directory bind
22//! follows the replacement.
23//!
24//! The relocated file is written `0600` and lives under the data root AgentMux keeps
25//! owner-only. The path itself is derived by [`agentmux_common::mcp_config_path`], so srv
26//! (which writes it) and `agentmux-mcp doctor` (which diagnoses it) cannot disagree.
27
28use std::io::Write;
29use std::path::{Path, PathBuf};
30
31pub use agentmux_common::mcp_config_path::MCP_JSON;
32use agentmux_common::mcp_config_path as shared;
33
34/// Whether `work_dir` is AgentMux's own folder, where a launch may keep the agent's
35/// `.mcp.json` as it always has.
36pub fn is_agent_owned_workdir(work_dir: &Path) -> bool {
37    shared::is_agent_owned_workdir(work_dir)
38}
39
40/// The folder holding `work_dir`'s relocated config, or `None` when the folder is AgentMux's
41/// own and the file belongs in it (`<work_dir>/.mcp.json`). This is what a container binds
42/// (a directory, not the file: see the module doc).
43pub fn relocated_dir(work_dir: &str) -> Option<PathBuf> {
44    let expanded = crate::backend::blockcontroller::core::expand_home_dir(work_dir);
45    shared::relocated_dir_for(Path::new(&expanded))
46}
47
48/// The relocated config for `work_dir`, or `None` when the folder is AgentMux's own and the
49/// file belongs in it (`<work_dir>/.mcp.json`).
50pub fn relocated_path(work_dir: &str) -> Option<PathBuf> {
51    let expanded = crate::backend::blockcontroller::core::expand_home_dir(work_dir);
52    shared::relocated_path_for(Path::new(&expanded))
53}
54
55/// Where this agent's MCP config is: in its working directory when AgentMux owns the folder,
56/// else under AgentMux's data root.
57pub fn config_path(work_dir: &str) -> PathBuf {
58    let expanded = crate::backend::blockcontroller::core::expand_home_dir(work_dir);
59    shared::config_path_for(Path::new(&expanded))
60}
61
62/// The config of a host agent in `work_dir` when it is kept outside the folder: [`relocated_path`] for a
63/// user's project. For any folder the rule of [`crate::backend::mcp_folder_rule`] holds for (a container agent
64/// can write it), AgentMux's own included, it is in the folder kept for host agents alone
65/// (`mcp_config_path::HOST_ONLY_DIR`), which no container has in its mounts. `None` when the file belongs in
66/// the folder. Reads the disk and the store.
67pub fn host_relocated_path(work_dir: &str) -> Option<PathBuf> {
68    if crate::backend::mcp_folder_rule::holds_in(work_dir) {
69        let expanded = crate::backend::blockcontroller::core::expand_home_dir(work_dir);
70        return shared::host_only_dir_for(Path::new(&expanded)).map(|dir| dir.join(shared::RELOCATED_MCP_JSON));
71    }
72    relocated_path(work_dir)
73}
74
75/// `content` as a host agent's config is written for `work_dir`: as it is, except in a folder the rule holds
76/// for, where the `agentmux` command is named by its path (`mcp_folder_rule::with_the_command_by_path`). Every
77/// writer of a host agent's config outside its folder passes the text through here.
78pub fn host_content(work_dir: &str, content: String) -> String {
79    if crate::backend::mcp_folder_rule::holds_in(work_dir) {
80        return crate::backend::mcp_folder_rule::with_the_command_by_path(&content, work_dir);
81    }
82    content
83}
84
85/// Where a host agent's MCP config is: [`config_path`], except that it is outside a folder a container agent
86/// can write ([`host_relocated_path`]).
87pub fn host_config_path(work_dir: &str) -> PathBuf {
88    host_relocated_path(work_dir).unwrap_or_else(|| config_path(work_dir))
89}
90
91/// Write the relocated config `content` at `path`: parent folders created, the file `0600` on
92/// Unix, through a temporary file and a rename so it is never briefly readable.
93pub fn write_relocated(path: &Path, content: &str) -> std::io::Result<()> {
94    let Some(parent) = path.parent() else {
95        return Err(std::io::Error::new(
96            std::io::ErrorKind::InvalidInput,
97            "the MCP config path has no parent",
98        ));
99    };
100    std::fs::create_dir_all(parent)?;
101    let name = path
102        .file_name()
103        .and_then(|n| n.to_str())
104        .unwrap_or("mcp.json");
105    let tmp = parent.join(format!(".{name}.{}.tmp", uuid::Uuid::new_v4()));
106    let mut options = std::fs::OpenOptions::new();
107    options.write(true).create_new(true);
108    #[cfg(unix)]
109    {
110        use std::os::unix::fs::OpenOptionsExt;
111        options.mode(0o600);
112    }
113    let written = options.open(&tmp).and_then(|mut file| {
114        file.write_all(content.as_bytes())?;
115        file.sync_all()
116    });
117    if let Err(e) = written {
118        let _ = std::fs::remove_file(&tmp);
119        return Err(e);
120    }
121    if let Err(e) = std::fs::rename(&tmp, path) {
122        let _ = std::fs::remove_file(&tmp);
123        return Err(e);
124    }
125    Ok(())
126}
127
128/// The MCP config a host turn reads: for a user's project, AgentMux's relocated config merged
129/// with the project's own `.mcp.json` servers (read-only — the project file is never written),
130/// so a user's servers keep reaching every harness, as they did when the launch merged them.
131/// `None` when neither file exists or is usable.
132///
133/// In a folder a container agent can write (`mcp_folder_rule`) the turn reads AgentMux's own config and
134/// nothing of the folder's: neither its `.mcp.json` as the config nor its servers merged in.
135pub fn read_for_turn(work_dir: &str) -> Option<String> {
136    let expanded = crate::backend::blockcontroller::core::expand_home_dir(work_dir);
137    if crate::backend::mcp_folder_rule::holds_in(&expanded) {
138        return host_relocated_path(&expanded).and_then(|path| std::fs::read_to_string(path).ok());
139    }
140    let Some(relocated) = relocated_path(&expanded) else {
141        return std::fs::read_to_string(Path::new(&expanded).join(MCP_JSON)).ok();
142    };
143    let ours = std::fs::read_to_string(&relocated).ok();
144    let theirs = std::fs::read_to_string(Path::new(&expanded).join(MCP_JSON)).ok();
145    match (ours, theirs) {
146        (Some(ours), Some(theirs)) => Some(merge_project_servers(&ours, &theirs)),
147        (Some(ours), None) => Some(ours),
148        (None, Some(theirs)) => Some(theirs),
149        (None, None) => None,
150    }
151}
152
153/// `ours` with every `mcpServers` entry from `theirs` added where it does not already exist.
154/// AgentMux's own entries win a name clash; other top-level keys are ours'.
155fn merge_project_servers(ours: &str, theirs: &str) -> String {
156    let Ok(mut ours) = serde_json::from_str::<serde_json::Value>(ours) else {
157        return theirs.to_string();
158    };
159    let Ok(theirs) = serde_json::from_str::<serde_json::Value>(theirs) else {
160        return ours.to_string();
161    };
162    let Some(ours_obj) = ours.as_object_mut() else {
163        return theirs.to_string();
164    };
165    let servers = ours_obj
166        .entry("mcpServers")
167        .or_insert_with(|| serde_json::json!({}));
168    let Some(servers) = servers.as_object_mut() else {
169        return ours.to_string();
170    };
171    if let Some(theirs) = theirs
172        .get("mcpServers")
173        .and_then(serde_json::Value::as_object)
174    {
175        for (name, value) in theirs {
176            servers.entry(name.clone()).or_insert_with(|| value.clone());
177        }
178    }
179    serde_json::to_string_pretty(&ours).unwrap_or_else(|_| ours.to_string())
180}
181
182/// What [`data_home_lock`] holds: the lock for `AGENTMUX_DATA_HOME` and the crate-wide one for the other
183/// variables the data root is read from.
184#[cfg(any(test, feature = "test-support"))]
185pub struct DataHomeGuard {
186    _data_home: std::sync::MutexGuard<'static, ()>,
187    _root_env: std::sync::MutexGuard<'static, ()>,
188}
189
190/// The one lock every test holds while it points `AGENTMUX_DATA_HOME` at a temp folder. The
191/// variable is process-wide, so tests in different modules must not overlap; a second private
192/// mutex would let one test restore the value under another.
193///
194/// The data root is also read from `AGENTMUX_HOME_OVERRIDE`, which wins over `AGENTMUX_DATA_HOME`, and
195/// that is set under [`ISOLATED_AUTH_ENV_LOCK`](crate::test_support::ISOLATED_AUTH_ENV_LOCK). So this holds
196/// that lock too (always after its own, so two tests cannot wait on each other): a test elsewhere that points
197/// the root at its own folder cannot run beside one that has written under another, and its test of the
198/// default data folder does not read one that is set here.
199#[cfg(any(test, feature = "test-support"))]
200pub fn data_home_lock() -> DataHomeGuard {
201    static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
202    let data_home = LOCK.lock().unwrap_or_else(|e| e.into_inner());
203    let root_env = crate::test_support::ISOLATED_AUTH_ENV_LOCK.lock().unwrap_or_else(|e| e.into_inner());
204    DataHomeGuard { _data_home: data_home, _root_env: root_env }
205}
206
207/// A test points `AGENTMUX_DATA_HOME` at a temp folder so the relocated configs it writes never
208/// reach the real data root. Tests that set it hold [`data_home_lock`].
209#[cfg(any(test, feature = "test-support"))]
210pub fn with_data_home<T>(root: &Path, f: impl FnOnce() -> T) -> T {
211    let _held = data_home_lock();
212    let saved = std::env::var_os("AGENTMUX_DATA_HOME");
213    std::env::set_var("AGENTMUX_DATA_HOME", root);
214    // The marks of folders a container agent ran in are in the shared folder: a test gets its own.
215    let marks = crate::backend::mcp_folder_rule::set_marks_dir_for_test(Some(root.join("shared-for-test").join("container-agent-folders")));
216    let out = f();
217    crate::backend::mcp_folder_rule::set_marks_dir_for_test(marks);
218    match saved {
219        Some(v) => std::env::set_var("AGENTMUX_DATA_HOME", v),
220        None => std::env::remove_var("AGENTMUX_DATA_HOME"),
221    }
222    out
223}
224
225#[cfg(test)]
226mod tests {
227    use super::*;
228
229    #[test]
230    fn a_test_that_sets_the_data_home_also_holds_the_lock_of_the_other_root_variables() {
231        let _held = data_home_lock();
232        assert!(
233            matches!(crate::test_support::ISOLATED_AUTH_ENV_LOCK.try_lock(), Err(std::sync::TryLockError::WouldBlock)),
234            "a test that reads the data root from another variable must wait for this one"
235        );
236    }
237
238    #[test]
239    fn a_users_project_gets_a_config_outside_it_and_an_agent_folder_keeps_its_own() {
240        let data = tempfile::tempdir().unwrap();
241        let project = tempfile::tempdir().unwrap();
242        with_data_home(data.path(), || {
243            let project_path = project.path().to_string_lossy().into_owned();
244            let relocated =
245                relocated_path(&project_path).expect("a project folder is not AgentMux's");
246            assert!(
247                relocated.starts_with(data.path().join("mcp")),
248                "{relocated:?}"
249            );
250            assert!(
251                !relocated.starts_with(project.path()),
252                "never under the project: {relocated:?}"
253            );
254
255            let owned = data.path().join("agents").join("aria");
256            std::fs::create_dir_all(&owned).unwrap();
257            let owned_path = owned.to_string_lossy().into_owned();
258            assert_eq!(relocated_path(&owned_path), None);
259            // The config path is resolved, so compare the folder resolved the same way: on macOS
260            // the temp dir is under /var, a link to /private/var.
261            let config = config_path(&owned_path);
262            assert_eq!(config.file_name(), Some(std::ffi::OsStr::new(".mcp.json")));
263            assert_eq!(
264                std::fs::canonicalize(config.parent().unwrap()).unwrap(),
265                std::fs::canonicalize(&owned).unwrap()
266            );
267        });
268    }
269
270    #[test]
271    fn the_same_project_always_gets_the_same_file_and_another_gets_another() {
272        let data = tempfile::tempdir().unwrap();
273        let a = tempfile::tempdir().unwrap();
274        let b = tempfile::tempdir().unwrap();
275        with_data_home(data.path(), || {
276            let a = a.path().to_string_lossy().into_owned();
277            let b = b.path().to_string_lossy().into_owned();
278            assert_eq!(config_path(&a), config_path(&a));
279            assert_ne!(config_path(&a), config_path(&b));
280        });
281    }
282
283    #[test]
284    fn the_relocated_file_is_written_owner_only_and_read_back() {
285        let data = tempfile::tempdir().unwrap();
286        let project = tempfile::tempdir().unwrap();
287        with_data_home(data.path(), || {
288            let path = relocated_path(&project.path().to_string_lossy()).unwrap();
289            write_relocated(&path, r#"{"mcpServers":{"agentmux":{}}}"#).unwrap();
290            assert_eq!(
291                std::fs::read_to_string(&path).unwrap(),
292                r#"{"mcpServers":{"agentmux":{}}}"#
293            );
294            #[cfg(unix)]
295            {
296                use std::os::unix::fs::PermissionsExt;
297                assert_eq!(
298                    std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,
299                    0o600
300                );
301            }
302        });
303    }
304
305    #[test]
306    fn a_project_file_is_merged_read_only_with_agentmuxs_servers_winning() {
307        let data = tempfile::tempdir().unwrap();
308        let project = tempfile::tempdir().unwrap();
309        with_data_home(data.path(), || {
310            std::fs::write(
311                project.path().join(MCP_JSON),
312                r#"{"mcpServers":{"agentmux":{"command":"stale"},"mine":{"command":"mine-mcp"}}}"#,
313            )
314            .unwrap();
315            let path = relocated_path(&project.path().to_string_lossy()).unwrap();
316            write_relocated(
317                &path,
318                r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#,
319            )
320            .unwrap();
321            let merged = read_for_turn(&project.path().to_string_lossy()).unwrap();
322            let value: serde_json::Value = serde_json::from_str(&merged).unwrap();
323            assert_eq!(
324                value["mcpServers"]["agentmux"]["command"], "agentmux-mcp",
325                "ours wins"
326            );
327            assert_eq!(
328                value["mcpServers"]["mine"]["command"], "mine-mcp",
329                "the user's server is kept"
330            );
331            assert_eq!(
332                std::fs::read_to_string(project.path().join(MCP_JSON)).unwrap(),
333                r#"{"mcpServers":{"agentmux":{"command":"stale"},"mine":{"command":"mine-mcp"}}}"#,
334                "the project file is never rewritten"
335            );
336        });
337    }
338
339    #[test]
340    fn a_host_agents_config_is_outside_a_folder_a_container_agent_can_write_and_nothing_of_the_folders_is_read() {
341        let (data, project) = (tempfile::tempdir().unwrap(), tempfile::tempdir().unwrap());
342        with_data_home(data.path(), || {
343            // AgentMux's own folder (under the data root) and a user's project, each with a file of its own.
344            let owned = data.path().join("agents").join("aria");
345            std::fs::create_dir_all(&owned).unwrap();
346            let theirs = r#"{"mcpServers":{"agentmux":{"command":"other"},"theirs":{"command":"theirs-mcp"}}}"#;
347            for folder in [owned.as_path(), project.path()] {
348                std::fs::write(folder.join(MCP_JSON), theirs).unwrap();
349            }
350            let owned_dir = owned.to_string_lossy().into_owned();
351            let project_dir = project.path().to_string_lossy().into_owned();
352            // As today while no container agent has to do with them.
353            assert_eq!(host_relocated_path(&owned_dir), None);
354            let untouched = r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#;
355            assert_eq!(host_content(&project_dir, untouched.to_string()), untouched, "a folder of the agent's own keeps the command as the launch writes it");
356            // A config path is resolved, so compare the folder resolved the same way (a temp dir can be a link).
357            let in_the_folder = |config: PathBuf| config.file_name() == Some(std::ffi::OsStr::new(MCP_JSON)) && std::fs::canonicalize(config.parent().unwrap()).unwrap() == std::fs::canonicalize(&owned).unwrap();
358            assert!(in_the_folder(host_config_path(&owned_dir)));
359            assert_eq!(read_for_turn(&owned_dir).as_deref(), Some(theirs), "the folder's own file is the config");
360            assert_eq!(host_relocated_path(&project_dir), relocated_path(&project_dir));
361
362            for (folder, dir) in [(owned.as_path(), &owned_dir), (project.path(), &project_dir)] {
363                crate::backend::mcp_folder_rule::mark(dir);
364                let outside = host_relocated_path(dir).expect("kept outside the folder");
365                assert!(outside.starts_with(data.path().join(shared::HOST_ONLY_DIR)) && !outside.starts_with(folder), "{outside:?}");
366                // Not the folder a container agent of a project is given (its relocated config's, read-only).
367                assert!(relocated_dir(dir).is_none_or(|given| !outside.starts_with(given)), "{outside:?}");
368                assert_eq!(host_config_path(dir), outside);
369                assert_eq!(read_for_turn(dir), None, "no config of AgentMux's yet: the folder's is not read in its place");
370                // As a writer writes it: the `agentmux` command by its path, or no such entry.
371                let content = host_content(dir, r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"},"git":{"command":"git-mcp"}}}"#.to_string());
372                assert!(crate::backend::mcp_folder_rule::names_the_command_by_path(&content), "{content}");
373                write_relocated(&outside, r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#).unwrap();
374                let read: serde_json::Value = serde_json::from_str(&read_for_turn(dir).unwrap()).unwrap();
375                assert_eq!(read["mcpServers"]["agentmux"]["command"], "agentmux-mcp");
376                assert_eq!(read["mcpServers"].as_object().unwrap().len(), 1, "the folder's servers are not merged in");
377                assert_eq!(std::fs::read_to_string(folder.join(MCP_JSON)).unwrap(), theirs, "the folder's file is left as it is");
378            }
379            // A container agent's own launch still finds its file where it was.
380            assert_eq!(relocated_path(&owned_dir), None);
381            assert!(in_the_folder(config_path(&owned_dir)));
382        });
383    }
384}