agentmux_common/
mcp_config_path.rs1use std::path::{Path, PathBuf};
23
24use sha2::{Digest, Sha256};
25
26pub const MCP_JSON: &str = ".mcp.json";
28pub const RELOCATED_MCP_JSON: &str = "mcp.json";
30pub const CONTAINER_MCP_CONFIG_DIR: &str = "/home/agent/.agentmux/mcp";
32
33fn 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
51fn 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 if let Some(home) = dirs::home_dir() {
60 roots.push(home.join(".agentmux"));
61 }
62 let resolved: Vec<PathBuf> = roots.iter().filter_map(|root| canonical(root)).collect();
65 roots.extend(resolved);
66 roots
67}
68
69fn 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
88fn 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
103fn 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 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
136fn 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
151pub 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
157pub 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
173pub fn workdir_key(expanded: &Path) -> String {
175 spelling_key(&normalized(expanded))
176}
177
178pub 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
190pub const HOST_ONLY_DIR: &str = "mcp-host";
195
196pub fn host_only_root() -> Option<PathBuf> {
198 Some(crate::data_paths::agentmux_root().ok()?.join(HOST_ONLY_DIR))
199}
200
201pub fn host_only_dir_for(expanded: &Path) -> Option<PathBuf> {
204 Some(host_only_root()?.join(workdir_key(&absolutize(expanded))))
205}
206
207pub 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
222pub fn spelled_within(inner: &str, outer: &str) -> bool {
224 !outer.is_empty() && (inner == outer || inner.starts_with(&format!("{outer}/")))
225}
226
227pub 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
234pub fn relocated_path_for(expanded: &Path) -> Option<PathBuf> {
237 relocated_dir_for(expanded).map(|dir| dir.join(RELOCATED_MCP_JSON))
238}
239
240pub 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
247pub 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 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 #[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 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 #[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 assert_eq!(relocated_dir_for(&through_link), relocated_dir_for(&base.join("projects").join("sibling")));
338 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 #[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 #[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}