Skip to main content

agentmux_srv_core/backend/
mcp_rewrite.rs

1// Copyright 2026, AgentMux Corp.
2// SPDX-License-Identifier: Apache-2.0
3
4//! Rungs 3 and 4 of the MCP self-heal ladder (`mcp_health`,
5//! `docs/specs/SPEC_AGENT_MCP_SELF_HEAL_2026_10_10.md` ยง5): put the `agentmux` entry of the agent's
6//! workspace `.mcp.json` right, then reconnect. Rung 3 rewrites it the way a launch writes it (the
7//! bare `agentmux-mcp` command, this agent's id and channel, and no signing value: the file holds
8//! references, not values), which mends a missing or stale
9//! entry or one the user edited. Rung 4 makes the command the absolute path of the `agentmux-mcp`
10//! that ships with this install, which mends a `PATH` that does not find it.
11//!
12//! Only `mcpServers.agentmux` is touched. A launch's merge (`write_mcp_json_respecting_user_servers`)
13//! would also drop the servers the agent had bound and unbound since, which a repair in the middle of
14//! a session must not do. The write is under the same directory lock the launch writes with.
15
16use std::path::{Path, PathBuf};
17
18use serde_json::{json, Value};
19
20use crate::backend::mcp_health::Shape;
21
22const COMMAND: &str = "agentmux-mcp";
23
24/// Block -> the directory its CLI was last spawned in, where its `.mcp.json` is.
25fn 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
30/// A pane's CLI is spawned in `work_dir` (called at each spawn).
31pub(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
35/// The directory `block_id`'s CLI was last spawned in.
36pub(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
40/// The `agentmux-mcp` that ships with this install: the bundled copy, else the user tools dir's
41/// (where `task dev` puts it), the order `tool_store::bashwrap_path` uses.
42pub(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
51/// `content` (a `.mcp.json`; empty when there is none) with its `agentmux` entry made `shape` for
52/// `slug`: type `stdio`, the command, no arguments, and the entry's `env` with `AGENTMUX_AGENT_ID` set.
53/// The rest of `env` (bus id, channel, keys) and every other server stay as they were. `Err` when the
54/// file is not a JSON object, which is not ours to replace, or when the shape needs an `exe` and there
55/// is none.
56fn repaired(content: &str, slug: &str, shape: Shape, exe: Option<&Path>) -> Result<String, String> {
57    // An entry that names another id is a rename's leftover: its keys go with the old name.
58    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
82/// Rewrite the `agentmux` entry of the `.mcp.json` in `work_dir` for `slug`, with its signing keys
83/// when `carries_keys` (never for a container agent: its file is mounted into the container),
84/// under the launch's directory lock. `Ok(true)` when the file changed, `Ok(false)` when it already
85/// was so (a reconnect cannot come out differently, so the ladder moves on).
86fn 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    // A user's project keeps its own `.mcp.json` (#3680): the agent's config is AgentMux's
99    // relocated file, and that is the one a repair may rewrite. So is the config of a host agent in a
100    // folder a container agent can write (only a host agent's file is repaired here).
101    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        // In a folder a container agent can write the command stays named by its path, whatever the rung.
115        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    // Read under the lock: a launch may have written it meanwhile.
130    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    // The keys are ensured in the store; the file holds none of their values, whether or not that worked.
137    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
150/// A repair rewrites a host agent's config. Not a container agent's, wherever its folder is: it starts its
151/// server inside the image, from the file in its own folder.
152fn 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
159/// Rung 3 or 4 for the agent on `block_id`, whose pane runs in `work_dir`. A container agent starts its
160/// server inside the image, from a copy of the file the host does not own.
161pub 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            // The agent's file is AgentMux's relocated one for a user project (#3680).
253            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}