1use std::path::{Path, PathBuf};
17
18use serde_json::{json, Value};
19
20use crate::backend::mcp_health::Shape;
21
22const COMMAND: &str = "agentmux-mcp";
23
24fn workdirs() -> &'static std::sync::Mutex<std::collections::HashMap<String, String>> {
26 static DIRS: std::sync::OnceLock<std::sync::Mutex<std::collections::HashMap<String, String>>> = std::sync::OnceLock::new();
27 DIRS.get_or_init(Default::default)
28}
29
30pub(crate) fn remember_workdir(block_id: &str, work_dir: &str) {
32 workdirs().lock().unwrap_or_else(|e| e.into_inner()).insert(block_id.to_string(), work_dir.to_string());
33}
34
35pub(crate) fn workdir_of(block_id: &str) -> Option<String> {
37 workdirs().lock().unwrap_or_else(|e| e.into_inner()).get(block_id).cloned()
38}
39
40pub(crate) fn shipped_exe() -> Option<PathBuf> {
43 let name = if cfg!(windows) { "agentmux-mcp.exe" } else { COMMAND };
44 [crate::backend::tool_store::bundled_tools_dir(), crate::backend::tool_store::user_tools_dir()]
45 .into_iter()
46 .flatten()
47 .map(|dir| dir.join(name))
48 .find(|p| p.is_file())
49}
50
51fn repaired(content: &str, slug: &str, shape: Shape, exe: Option<&Path>) -> Result<String, String> {
57 let content = crate::backend::mcp_json_identity::set_agent_id(content, slug).map_or_else(|| content.to_string(), |(c, _)| c);
59 let mut doc: Value = if content.trim().is_empty() {
60 json!({})
61 } else {
62 serde_json::from_str(&content).map_err(|e| format!(".mcp.json is not JSON: {e}"))?
63 };
64 let root = doc.as_object_mut().ok_or("the .mcp.json is not a JSON object")?;
65 let command = match shape {
66 Shape::Canonical => COMMAND.to_string(),
67 Shape::AbsolutePath => exe.ok_or("no agentmux-mcp ships with this install")?.to_string_lossy().into_owned(),
68 };
69 let servers = root.entry("mcpServers").or_insert_with(|| json!({}));
70 let servers = servers.as_object_mut().ok_or("mcpServers is not an object")?;
71 let mut env = servers
72 .get("agentmux")
73 .and_then(|e| e.get("env"))
74 .and_then(Value::as_object)
75 .cloned()
76 .unwrap_or_default();
77 env.insert("AGENTMUX_AGENT_ID".to_string(), json!(slug));
78 servers.insert("agentmux".to_string(), json!({ "type": "stdio", "command": command, "args": [], "env": env }));
79 serde_json::to_string_pretty(&doc).map_err(|e| e.to_string())
80}
81
82fn rewrite_file(
87 mstore: &crate::backend::storage::store::Store,
88 work_dir: &str,
89 slug: &str,
90 shape: Shape,
91 exe: Option<&Path>,
92 carries_keys: bool,
93) -> Result<bool, String> {
94 if work_dir.trim().is_empty() {
95 return Err("the pane has no working directory".to_string());
96 }
97 let expanded = crate::backend::blockcontroller::core::expand_home_dir(work_dir);
98 if let Some(path) = crate::backend::mcp_config_file::host_relocated_path(&expanded) {
102 let content = match std::fs::read_to_string(&path) {
103 Ok(text) => text,
104 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
105 Err(e) => return Err(format!("cannot read the agent's MCP config: {e}")),
106 };
107 let body = repaired(&content, slug, shape, exe)?;
108 let body = if carries_keys {
109 crate::backend::agent_config::inject_jekt_signing_keys_into_mcp_json(&body, mstore, slug).unwrap_or(body)
110 } else {
111 body
112 };
113 let body = crate::backend::mcp_json_identity::strip_signing_keys(&body).unwrap_or(body);
114 let body = crate::backend::mcp_config_file::host_content(&expanded, body);
116 if serde_json::from_str::<Value>(&body).ok() == serde_json::from_str::<Value>(&content).ok() {
117 return Ok(false);
118 }
119 crate::backend::mcp_config_file::write_relocated(&path, &body)
120 .map_err(|e| format!("cannot write the agent's MCP config: {e}"))?;
121 return Ok(true);
122 }
123 let wd = crate::backend::workdir_fs::Workdir::open(Path::new(&expanded)).map_err(|e| format!("cannot open {expanded}: {e}"))?;
124 let path = wd.resolve(".mcp.json").map_err(|e| format!("cannot use .mcp.json: {e}"))?;
125 let _lock = wd
126 .open_lock_file(crate::backend::agent_config::MCP_JSON_WRITE_LOCK)
127 .and_then(|f| f.lock().map(|()| f))
128 .map_err(|e| format!(".mcp.json lock unavailable: {e}"))?;
129 let content = match std::fs::read_to_string(&path) {
131 Ok(text) => text,
132 Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
133 Err(e) => return Err(format!("cannot read .mcp.json: {e}")),
134 };
135 let body = repaired(&content, slug, shape, exe)?;
136 let body = if carries_keys {
138 crate::backend::agent_config::inject_jekt_signing_keys_into_mcp_json(&body, mstore, slug).unwrap_or(body)
139 } else {
140 body
141 };
142 let body = crate::backend::mcp_json_identity::strip_signing_keys(&body).unwrap_or(body);
143 if serde_json::from_str::<Value>(&body).ok() == serde_json::from_str::<Value>(&content).ok() {
144 return Ok(false);
145 }
146 wd.write(".mcp.json", body.as_bytes(), true).map_err(|e| format!("cannot write .mcp.json: {e}"))?;
147 Ok(true)
148}
149
150fn host_agents_only(def: &crate::backend::storage::AgentDefinition) -> Result<(), String> {
153 if def.runtime().is_container() {
154 return Err("a container agent starts its server inside the image".to_string());
155 }
156 Ok(())
157}
158
159pub fn run(mstore: &crate::backend::storage::store::Store, block_id: &str, work_dir: &str, shape: Shape) -> Result<bool, String> {
162 let instance = mstore
163 .instance_get_active_for_block(block_id)
164 .map_err(|e| e.to_string())?
165 .ok_or("no agent runs in this pane")?;
166 let def = mstore
167 .agent_def_get(&instance.definition_id)
168 .map_err(|e| e.to_string())?
169 .ok_or("the agent's definition is gone")?;
170 host_agents_only(&def)?;
171 if def.slug.trim().is_empty() {
172 return Err("the agent has no id".to_string());
173 }
174 rewrite_file(mstore, work_dir, &def.slug, shape, shipped_exe().as_deref(), def.runtime().adapter().carries_signing_keys())
175}
176
177#[cfg(test)]
178mod tests {
179 use super::*;
180
181 fn entry(content: &str) -> Value {
182 serde_json::from_str::<Value>(content).unwrap()["mcpServers"]["agentmux"].clone()
183 }
184
185 #[test]
186 fn a_missing_file_or_entry_gets_the_canonical_entry_and_the_users_servers_stay() {
187 let fresh = entry(&repaired("", "manoz", Shape::Canonical, None).unwrap());
188 assert_eq!(fresh, json!({ "type": "stdio", "command": "agentmux-mcp", "args": [], "env": { "AGENTMUX_AGENT_ID": "manoz" } }));
189
190 let theirs = r#"{ "mcpServers": { "github": { "command": "gh-mcp" } }, "other": 1 }"#;
191 let out: Value = serde_json::from_str(&repaired(theirs, "manoz", Shape::Canonical, None).unwrap()).unwrap();
192 assert_eq!(out["mcpServers"]["github"], json!({ "command": "gh-mcp" }));
193 assert_eq!(out["other"], 1);
194 assert_eq!(out["mcpServers"]["agentmux"]["command"], "agentmux-mcp");
195 }
196
197 #[test]
198 fn an_edited_entry_is_restored_and_its_env_is_kept() {
199 let edited = json!({ "mcpServers": { "agentmux": {
200 "type": "sse", "command": "/old/agentmux-mcp", "args": ["--debug"], "extra": true,
201 "env": { "AGENTMUX_AGENT_ID": "manoz", "AGENTMUX_AGENT_BUS_ID": "bus-1", "AGENTMUX_JEKT_KEY": "k" }
202 }}})
203 .to_string();
204 let out = entry(&repaired(&edited, "manoz", Shape::Canonical, None).unwrap());
205 assert_eq!(out["type"], "stdio");
206 assert_eq!(out["command"], "agentmux-mcp");
207 assert_eq!(out["args"], json!([]));
208 assert!(out.get("extra").is_none());
209 assert_eq!(out["env"]["AGENTMUX_AGENT_BUS_ID"], "bus-1");
210 assert_eq!(out["env"]["AGENTMUX_JEKT_KEY"], "k", "the repair keeps the env; the signing values go when the file is written");
211 }
212
213 #[test]
214 fn a_renamed_agents_old_keys_do_not_sign_for_the_new_name() {
215 let old = json!({ "mcpServers": { "agentmux": { "command": "agentmux-mcp", "env": {
216 "AGENTMUX_AGENT_ID": "old-name", "AGENTMUX_JEKT_KEY": "k", "AGENTMUX_LAN_KEY": "l"
217 }}}})
218 .to_string();
219 let out = entry(&repaired(&old, "new-name", Shape::Canonical, None).unwrap());
220 assert_eq!(out["env"]["AGENTMUX_AGENT_ID"], "new-name");
221 assert!(out["env"].get("AGENTMUX_JEKT_KEY").is_none() && out["env"].get("AGENTMUX_LAN_KEY").is_none());
222 }
223
224 #[test]
225 fn the_absolute_shape_names_the_shipped_binary_and_needs_one() {
226 let exe = Path::new("/app/tools/bin/agentmux-mcp");
227 let out = entry(&repaired("", "manoz", Shape::AbsolutePath, Some(exe)).unwrap());
228 assert_eq!(out["command"], exe.to_string_lossy().as_ref());
229 assert!(repaired("", "manoz", Shape::AbsolutePath, None).unwrap_err().contains("no agentmux-mcp ships"));
230 }
231
232 #[test]
233 fn a_file_that_is_not_ours_to_replace_is_an_error() {
234 assert!(repaired("not json", "manoz", Shape::Canonical, None).unwrap_err().contains("not JSON"));
235 assert!(repaired("[1]", "manoz", Shape::Canonical, None).unwrap_err().contains("not a JSON object"));
236 assert!(repaired(r#"{"mcpServers": 3}"#, "manoz", Shape::Canonical, None).unwrap_err().contains("not an object"));
237 }
238
239 #[test]
240 fn a_file_already_canonical_is_unchanged_and_one_that_is_not_is_rewritten_once() {
241 let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
242 let data = tempfile::tempdir().unwrap();
243 let dir = tempfile::tempdir().unwrap();
244 let work_dir = dir.path().to_string_lossy().into_owned();
245 let broken = json!({ "mcpServers": {
246 "agentmux": { "command": "/gone/agentmux-mcp", "args": [], "env": { "AGENTMUX_AGENT_ID": "manoz" } },
247 "github": { "command": "gh-mcp" }
248 }})
249 .to_string();
250
251 crate::backend::mcp_config_file::with_data_home(data.path(), || {
252 let file = crate::backend::mcp_config_file::config_path(&work_dir);
254 crate::backend::mcp_config_file::write_relocated(&file, &broken).unwrap();
255
256 assert_eq!(rewrite_file(&store, &work_dir, "manoz", Shape::Canonical, None, true), Ok(true));
257 let after: Value = serde_json::from_str(&std::fs::read_to_string(&file).unwrap()).unwrap();
258 assert_eq!(after["mcpServers"]["agentmux"]["command"], "agentmux-mcp");
259 assert_eq!(after["mcpServers"]["github"]["command"], "gh-mcp");
260 let env = &after["mcpServers"]["agentmux"]["env"];
261 assert!(env.get("AGENTMUX_JEKT_KEY").is_none() && env.get("AGENTMUX_LAN_KEY").is_none(), "the file holds references, not values");
262 assert!(env["AGENTMUX_CHANNEL"].is_string(), "its keys are ensured in the store");
263
264 assert_eq!(rewrite_file(&store, &work_dir, "manoz", Shape::Canonical, None, true), Ok(false), "nothing left to change");
265 let exe = dir.path().join("agentmux-mcp");
266 assert_eq!(rewrite_file(&store, &work_dir, "manoz", Shape::AbsolutePath, Some(&exe), true), Ok(true));
267 assert_eq!(rewrite_file(&store, &work_dir, "manoz", Shape::AbsolutePath, Some(&exe), true), Ok(false));
268 assert!(!dir.path().join(".mcp.json").exists(), "the project's own file is never written");
269 });
270 }
271
272 #[test]
273 fn a_repair_takes_out_a_signing_value_even_when_the_keys_cannot_be_ensured() {
274 let broken = crate::backend::storage::store::Store::open_in_memory().unwrap();
275 broken.test_break_name_key_tables().unwrap();
276 let data = tempfile::tempdir().unwrap();
277 let dir = tempfile::tempdir().unwrap();
278 let work_dir = dir.path().to_string_lossy().into_owned();
279 let old = json!({ "mcpServers": { "agentmux": { "command": "agentmux-mcp", "args": [], "env": {
280 "AGENTMUX_AGENT_ID": "manoz", "AGENTMUX_JEKT_KEY": "old-jekt-value", "AGENTMUX_LAN_KEY": "old-lan-value"
281 }}}})
282 .to_string();
283 crate::backend::mcp_config_file::with_data_home(data.path(), || {
284 let file = crate::backend::mcp_config_file::config_path(&work_dir);
285 crate::backend::mcp_config_file::write_relocated(&file, &old).unwrap();
286 assert_eq!(rewrite_file(&broken, &work_dir, "manoz", Shape::Canonical, None, true), Ok(true));
287 let text = std::fs::read_to_string(&file).unwrap();
288 assert!(!text.contains("old-jekt-value") && !text.contains("old-lan-value"), "{text}");
289 });
290 }
291
292 #[test]
293 fn a_pane_without_a_directory_or_agent_is_an_error_not_a_panic() {
294 let store = crate::backend::storage::store::Store::open_in_memory().unwrap();
295 assert!(rewrite_file(&store, "", "manoz", Shape::Canonical, None, true).unwrap_err().contains("no working directory"));
296 assert!(run(&store, "no-such-block", "/tmp", Shape::Canonical).unwrap_err().contains("no agent runs"));
297 }
298
299 #[test]
300 fn a_repair_is_never_run_for_a_container_agent() {
301 use crate::backend::storage::agents::test_agent_def;
302 assert!(host_agents_only(&test_agent_def("a-1", "Aria", "claude", "container", 1, "")).unwrap_err().contains("inside the image"));
303 assert_eq!(host_agents_only(&test_agent_def("a-2", "Bryn", "claude", "host", 1, "")), Ok(()));
304 }
305}