Skip to main content

agentmux_common/
mcp_config_path.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Where an agent's MCP config lives (#3680), shared by srv and `agentmux-mcp doctor`.
5//!
6//! An agent's working directory may be the user's own project. A launch used to write
7//! `.mcp.json` there; now, for a folder AgentMux does not own, the config goes under the data
8//! root, outside the project:
9//!
10//! ```text
11//! <data root>/mcp/<hash of the expanded working directory>/mcp.json
12//! ```
13//!
14//! In a folder AgentMux owns the file stays `<working directory>/.mcp.json`, which Claude Code
15//! reads on its own. srv derives the path to write and read it; `agentmux-mcp doctor` derives
16//! the same one to diagnose it, so the two cannot disagree.
17//!
18//! A container gets the folder as a read-only bind at [`CONTAINER_MCP_CONFIG_DIR`]; the file
19//! keeps its name inside it. The folder rather than the file matters: a single-file bind keeps
20//! the inode it was made with, so an atomic rewrite would leave the container on a stale copy.
21
22use std::path::{Path, PathBuf};
23
24use sha2::{Digest, Sha256};
25
26/// The file name every provider's workspace MCP config uses.
27pub const MCP_JSON: &str = ".mcp.json";
28/// The file name of the relocated config inside its own folder.
29pub const RELOCATED_MCP_JSON: &str = "mcp.json";
30/// Where a container agent's relocated config folder is mounted.
31pub const CONTAINER_MCP_CONFIG_DIR: &str = "/home/agent/.agentmux/mcp";
32
33/// `path` as a comparable string: separators normalized, no trailing slash, and folded on
34/// Windows, where two spellings of one folder must compare equal.
35fn normalized(path: &Path) -> String {
36    let s = path.to_string_lossy().replace('\\', "/");
37    let s = s.trim_end_matches('/').to_string();
38    if cfg!(windows) {
39        s.to_lowercase()
40    } else {
41        s
42    }
43}
44
45fn is_within(path: &Path, root: &Path) -> bool {
46    let path = normalized(path);
47    let root = normalized(root);
48    !root.is_empty() && (path == root || path.starts_with(&format!("{root}/")))
49}
50
51/// The roots a launch may write into: AgentMux's own data tree.
52fn owned_roots() -> Vec<PathBuf> {
53    let mut roots = Vec::new();
54    if let Ok(root) = crate::data_paths::agentmux_root() {
55        roots.push(root);
56    }
57    // The default agent home is `~/.agentmux/agents/<slug>`, resolved from the real home even
58    // when a data-home override is set for an isolated instance.
59    if let Some(home) = dirs::home_dir() {
60        roots.push(home.join(".agentmux"));
61    }
62    // A working directory is compared with its links followed, so a root that is itself a link
63    // is compared by what it points at too.
64    let resolved: Vec<PathBuf> = roots.iter().filter_map(|root| canonical(root)).collect();
65    roots.extend(resolved);
66    roots
67}
68
69/// `std::fs::canonicalize` of `path`, without the `\\?\` prefix Windows puts on it (the roots
70/// and the paths compared with them are written without it). `None` when it does not resolve.
71fn canonical(path: &Path) -> Option<PathBuf> {
72    let resolved = std::fs::canonicalize(path).ok()?;
73    #[cfg(windows)]
74    {
75        let text = resolved.to_string_lossy();
76        if let Some(rest) = text.strip_prefix(r"\\?\UNC\") {
77            return Some(PathBuf::from(format!(r"\\{rest}")));
78        }
79        if let Some(rest) = text.strip_prefix(r"\\?\") {
80            if rest.as_bytes().get(1) == Some(&b':') {
81                return Some(PathBuf::from(rest));
82            }
83        }
84    }
85    Some(resolved)
86}
87
88/// Whether `meta` is a symlink, or on Windows any reparse point (a junction is one).
89fn is_link(meta: &std::fs::Metadata) -> bool {
90    if meta.file_type().is_symlink() {
91        return true;
92    }
93    #[cfg(windows)]
94    {
95        use std::os::windows::fs::MetadataExt;
96        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
97        return meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0;
98    }
99    #[cfg(not(windows))]
100    false
101}
102
103/// `path` with every `.` and `..` resolved, and every symlink on the way followed as it is met,
104/// so a `..` after a link goes up from the link's target, as the filesystem does (`link/..` is
105/// the target's parent, not the link's). A folder that does not exist yet (or a link that does
106/// not resolve) is kept as written. A `..` above the root stays at the root.
107fn normalize_path(path: &Path) -> PathBuf {
108    use std::path::Component;
109    let mut out = PathBuf::new();
110    for component in path.components() {
111        match component {
112            Component::Prefix(prefix) => out.push(prefix.as_os_str()),
113            Component::RootDir => out.push(component.as_os_str()),
114            Component::CurDir => {}
115            Component::ParentDir => match out.components().next_back() {
116                Some(Component::Normal(_)) => {
117                    out.pop();
118                }
119                // At a root or prefix there is nowhere above it to go.
120                Some(_) => {}
121                None => out.push(".."),
122            },
123            Component::Normal(part) => {
124                out.push(part);
125                if std::fs::symlink_metadata(&out).is_ok_and(|meta| is_link(&meta)) {
126                    if let Some(target) = canonical(&out) {
127                        out = target;
128                    }
129                }
130            }
131        }
132    }
133    out
134}
135
136/// `path` made absolute against the process's current directory, exactly as srv resolves a
137/// relative `cmd:cwd` (and ACP/MSP's `session_cwd` does), with parent traversal resolved. The
138/// traversal must be gone before the ownership check, or `.agentmux/../project` reads as owned by
139/// its text and the launch writes the config (and its keys) into the project (#47392).
140fn absolutize(path: &Path) -> PathBuf {
141    let absolute = if path.is_absolute() {
142        path.to_path_buf()
143    } else {
144        std::env::current_dir()
145            .map(|cwd| cwd.join(path))
146            .unwrap_or_else(|_| path.to_path_buf())
147    };
148    normalize_path(&absolute)
149}
150
151/// Whether `work_dir` is AgentMux's own folder, where the config belongs in it.
152pub fn is_agent_owned_workdir(work_dir: &Path) -> bool {
153    let work_dir = absolutize(work_dir);
154    owned_roots().iter().any(|root| is_within(&work_dir, root))
155}
156
157/// Expand a leading `~` against the real home. srv has its own expander (it also honours the
158/// dev-instance home override for paths under `~/.agentmux`); a user's project expands the same
159/// way in both.
160pub fn expand_home(path: &Path) -> PathBuf {
161    let text = path.to_string_lossy();
162    if text == "~" {
163        return dirs::home_dir().unwrap_or_else(|| path.to_path_buf());
164    }
165    if let Some(rest) = text.strip_prefix("~/").or_else(|| text.strip_prefix("~\\")) {
166        if let Some(home) = dirs::home_dir() {
167            return home.join(rest);
168        }
169    }
170    path.to_path_buf()
171}
172
173/// A stable, filesystem-safe key for an already-expanded working directory.
174pub fn workdir_key(expanded: &Path) -> String {
175    spelling_key(&normalized(expanded))
176}
177
178/// The folder holding `expanded`'s relocated config, or `None` when the folder is AgentMux's
179/// own (the file belongs in the working directory itself). A relative path is resolved first, so
180/// both the writer and ACP/MSP's `session_cwd` key the same folder.
181pub fn relocated_dir_for(expanded: &Path) -> Option<PathBuf> {
182    let expanded = absolutize(expanded);
183    if is_agent_owned_workdir(&expanded) {
184        return None;
185    }
186    let root = crate::data_paths::agentmux_root().ok()?;
187    Some(root.join("mcp").join(workdir_key(&expanded)))
188}
189
190/// The folder, under the data root, of what AgentMux keeps for host agents alone. Nothing in it is bound into
191/// a container: a relocated config's folder under `mcp` is (read-only, `container::mounts`), this one never.
192/// The data root is one version's of one install: what is kept here is written again by a launch, so nothing
193/// that must outlive an upgrade belongs in it.
194pub const HOST_ONLY_DIR: &str = "mcp-host";
195
196/// [`HOST_ONLY_DIR`] under the data root. `None` when the data root can't be named.
197pub fn host_only_root() -> Option<PathBuf> {
198    Some(crate::data_paths::agentmux_root().ok()?.join(HOST_ONLY_DIR))
199}
200
201/// The folder under [`host_only_root`] that is keyed by an expanded working directory, whoever owns that
202/// directory: where srv keeps the config of a host agent whose own folder may not hold it.
203pub fn host_only_dir_for(expanded: &Path) -> Option<PathBuf> {
204    Some(host_only_root()?.join(workdir_key(&absolutize(expanded))))
205}
206
207/// The spellings one folder is compared under: as it is written (absolute, `.` and `..` and links resolved
208/// as they are met), and as the filesystem names it when it exists (which also settles letter case on a
209/// filesystem that ignores it, and short names on Windows). Each is separator-normalized, with no trailing
210/// separator, and case-folded on Windows. One entry when the two are the same.
211pub fn spellings(expanded: &Path) -> Vec<String> {
212    let written = absolutize(expanded);
213    let mut all = vec![normalized(&written)];
214    if let Some(real) = canonical(&written).map(|real| normalized(&real)) {
215        if real != all[0] {
216            all.push(real);
217        }
218    }
219    all
220}
221
222/// Whether the folder spelled `inner` is the one spelled `outer` or lies beneath it (two of [`spellings`]).
223pub fn spelled_within(inner: &str, outer: &str) -> bool {
224    !outer.is_empty() && (inner == outer || inner.starts_with(&format!("{outer}/")))
225}
226
227/// The key of one of [`spellings`], as [`workdir_key`] makes it for a path.
228pub fn spelling_key(spelling: &str) -> String {
229    let mut hash = Sha256::new();
230    hash.update(spelling.as_bytes());
231    hash.finalize()[..16].iter().map(|byte| format!("{byte:02x}")).collect()
232}
233
234/// The relocated config for an expanded working directory, or `None` when the file belongs in
235/// the working directory itself.
236pub fn relocated_path_for(expanded: &Path) -> Option<PathBuf> {
237    relocated_dir_for(expanded).map(|dir| dir.join(RELOCATED_MCP_JSON))
238}
239
240/// Where this agent's MCP config is: in its working directory when AgentMux owns the folder,
241/// else under the data root.
242pub fn config_path_for(expanded: &Path) -> PathBuf {
243    let expanded = absolutize(expanded);
244    relocated_path_for(&expanded).unwrap_or_else(|| expanded.join(MCP_JSON))
245}
246
247/// The config's path inside a container, where its folder is mounted.
248pub fn container_config_path() -> PathBuf {
249    Path::new(CONTAINER_MCP_CONFIG_DIR).join(RELOCATED_MCP_JSON)
250}
251
252#[cfg(test)]
253mod tests {
254    use super::*;
255
256    #[test]
257    fn an_agents_own_folder_keeps_the_workspace_file() {
258        let home = dirs::home_dir().unwrap();
259        let agent = home.join(".agentmux").join("agents").join("aria");
260        assert!(relocated_path_for(&agent).is_none(), "an AgentMux folder keeps .mcp.json in it");
261        assert_eq!(config_path_for(&agent), absolutize(&agent).join(MCP_JSON));
262    }
263
264    #[test]
265    fn a_users_project_gets_a_folder_outside_it_with_mcp_json_in_it() {
266        // A directory that is not under any AgentMux root, without having to exist.
267        let project = if cfg!(windows) { Path::new(r"C:\agentmux-test-project") } else { Path::new("/agentmux-test-project") };
268        assert!(!is_agent_owned_workdir(project));
269        let path = relocated_path_for(project).expect("a project is not AgentMux's");
270        assert_eq!(path.file_name().and_then(|n| n.to_str()), Some(RELOCATED_MCP_JSON));
271        assert!(path.parent().is_some_and(|dir| dir.file_name().is_some_and(|n| n.to_str().unwrap_or("").len() == 32)), "a 16-byte hex key: {path:?}");
272        assert!(!path.starts_with(project), "never under the project: {path:?}");
273        assert_eq!(config_path_for(project), path);
274    }
275
276    #[test]
277    fn the_same_project_gets_the_same_key_and_another_gets_another() {
278        let a = Path::new("/agentmux-test-a");
279        let b = Path::new("/agentmux-test-b");
280        assert_eq!(workdir_key(a), workdir_key(a));
281        assert_ne!(workdir_key(a), workdir_key(b));
282    }
283
284    #[test]
285    fn a_containers_config_is_the_file_inside_the_mounted_folder() {
286        assert_eq!(
287            container_config_path(),
288            Path::new(CONTAINER_MCP_CONFIG_DIR).join(RELOCATED_MCP_JSON)
289        );
290    }
291
292    #[test]
293    fn a_tilde_is_expanded_for_a_user_path() {
294        let home = dirs::home_dir().unwrap();
295        assert_eq!(expand_home(Path::new("~/work")), home.join("work"));
296        assert_eq!(expand_home(Path::new("/already/absolute")), Path::new("/already/absolute"));
297    }
298
299    /// A `..` must be resolved before the ownership check: `.agentmux/agents/x/../../../..` reads
300    /// as AgentMux's by its text, but is the user's folder.
301    #[test]
302    fn parent_traversal_cannot_pass_as_an_agentmux_folder() {
303        let home = dirs::home_dir().unwrap();
304        let inside_agent = home.join(".agentmux").join("agents").join("aria");
305        assert!(is_agent_owned_workdir(&inside_agent), "the fixture starts owned");
306        let escapes = inside_agent.join("..").join("..").join("..").join("..").join("agentmux-escape-project");
307        assert!(!is_agent_owned_workdir(&escapes), "resolved out of .agentmux: {}", escapes.display());
308        assert_eq!(relocated_dir_for(&escapes), relocated_dir_for(&normalize_path(&escapes)), "one resolved key");
309        assert!(!config_path_for(&escapes).starts_with(normalize_path(&escapes)), "the config is not in the project");
310    }
311
312    /// A directory link: a symlink, or a junction on Windows (it needs no privilege there).
313    fn link_dir(link: &Path, target: &Path) {
314        #[cfg(unix)]
315        std::os::unix::fs::symlink(target, link).unwrap();
316        #[cfg(windows)]
317        junction::create(target, link).unwrap();
318    }
319
320    /// #47418: `<dir>/link/..` is the link's target's parent, not `<dir>`. Resolved by its text,
321    /// a project reached through a link to a folder elsewhere would read as the folder the link
322    /// is in, and be classified (and written into) as if it were there.
323    #[test]
324    fn a_parent_after_a_link_goes_up_from_the_links_target() {
325        let tmp = tempfile::tempdir().unwrap();
326        let base = canonical(tmp.path()).expect("the temp folder resolves");
327        let child = base.join("projects").join("child");
328        std::fs::create_dir_all(&child).unwrap();
329        std::fs::create_dir_all(base.join("home")).unwrap();
330        let link = base.join("home").join("link");
331        link_dir(&link, &child);
332
333        let through_link = link.join("..").join("sibling");
334        assert_eq!(normalize_path(&through_link), base.join("projects").join("sibling"));
335        assert_ne!(normalize_path(&through_link), base.join("home").join("sibling"), "not the lexical answer");
336        // The same folder spelled with and without the link keys one config folder.
337        assert_eq!(relocated_dir_for(&through_link), relocated_dir_for(&base.join("projects").join("sibling")));
338        // A link as the last part is followed too, and a path with no link in it is left as written.
339        assert_eq!(normalize_path(&link), child);
340        assert_eq!(normalize_path(&base.join("home").join("not-there")), base.join("home").join("not-there"));
341    }
342
343    /// One folder written another way compares as the same folder: a trailing separator, a way round, a link
344    /// to it, and another letter case where the filesystem ignores it.
345    #[test]
346    fn one_folder_has_a_spelling_in_common_however_it_is_written() {
347        let tmp = tempfile::tempdir().unwrap();
348        let base = canonical(tmp.path()).expect("the temp folder resolves");
349        let folder = base.join("Work").join("Project");
350        std::fs::create_dir_all(folder.join("src")).unwrap();
351        let own = spellings(&folder);
352        let same = |other: &Path| spellings(other).iter().any(|s| own.contains(s));
353        assert!(same(&PathBuf::from(format!("{}{}", folder.display(), std::path::MAIN_SEPARATOR))), "a trailing separator");
354        assert!(same(&folder.join("src").join("..")), "a way round");
355        let link = base.join("link");
356        link_dir(&link, &folder);
357        assert!(same(&link), "a link to it");
358        #[cfg(windows)]
359        assert!(same(Path::new(&folder.to_string_lossy().to_uppercase())), "another letter case");
360        assert!(!same(&base.join("Work")), "its parent is another folder");
361        let inner = spellings(&folder.join("src"));
362        assert!(spelled_within(&inner[0], &own[0]) && !spelled_within(&own[0], &inner[0]));
363        assert!(own.iter().all(|s| spelling_key(s).len() == 32));
364        assert_eq!(spelling_key(&own[0]), workdir_key(&absolutize(&folder)), "the key a config's folder is named by");
365    }
366
367    #[test]
368    fn what_is_kept_for_host_agents_alone_is_apart_from_the_relocated_configs() {
369        let project = if cfg!(windows) { Path::new(r"C:\agentmux-test-project") } else { Path::new("/agentmux-test-project") };
370        let host_only = host_only_dir_for(project).unwrap();
371        let relocated = relocated_dir_for(project).unwrap();
372        assert_eq!(host_only.file_name(), relocated.file_name(), "the same key");
373        assert_ne!(host_only.parent(), relocated.parent(), "another folder: a relocated config's is bound into a container");
374        assert!(host_only.parent().is_some_and(|dir| dir.ends_with(HOST_ONLY_DIR)));
375    }
376
377    /// #47392: the writer gets `cmd:cwd` as written; ACP/MSP resolve a relative one against the
378    /// server's cwd before asking. Both must key the same folder.
379    #[test]
380    fn a_relative_workdir_resolves_like_the_absolute_one() {
381        let cwd = std::env::current_dir().unwrap();
382        let relative = Path::new("agentmux-relative-test-project");
383        let absolute = cwd.join(relative);
384        assert_eq!(relocated_dir_for(relative), relocated_dir_for(&absolute));
385        assert_eq!(relocated_path_for(relative), relocated_path_for(&absolute));
386        assert_eq!(config_path_for(relative), config_path_for(&absolute));
387        assert_eq!(is_agent_owned_workdir(relative), is_agent_owned_workdir(&absolute));
388    }
389}