agentmux_srv/server/app_api/
agent_config_render.rs1use serde_json::json;
5
6use crate::backend::storage::store::Store;
7
8pub(crate) fn render_agent_config_files(
14 mstore: &Store,
15 id_store: &Store,
16 identity_store: &Store,
17 agent: &crate::backend::storage::AgentDefinition,
18 display_name: &str,
19 agent_slug: &str,
20 work_dir: &str,
21 workdir_is_shared: bool,
22) -> Vec<crate::backend::agent_config::AgentConfigFile> {
23 let mut content_map = crate::server::memory_launch_cost::startup_content_map(mstore, id_store, agent);
26
27 if workdir_is_shared {
33 disable_autonomous_memory(&mut content_map, work_dir);
34 }
35
36 let effective_skills = mstore.effective_skills(identity_store, &agent.id);
42
43 let mut config_files = crate::backend::agent_config::build_config_files(
44 &content_map,
45 &effective_skills,
46 display_name,
47 &agent.id,
48 agent_slug,
49 work_dir,
50 &agent.provider,
51 );
52 config_files.extend(crate::backend::computer_use_skill::sibling_files(&effective_skills, identity_store));
54
55 let visible_mcp: Vec<crate::backend::storage::McpServer> = mstore.effective_mcp_servers(identity_store, &agent.id, agent.runtime().is_container());
63 let has_own_mcp_refs = visible_mcp.iter().any(|server| !server.is_global);
64 if !visible_mcp.is_empty() {
65 let blob_for_merge = if has_own_mcp_refs {
66 None
67 } else {
68 content_map.get("mcp").map(|s| s.as_str())
69 };
70 if let Some(mcp_json) = crate::backend::agent_config::build_mcp_config_from_refs(
71 &visible_mcp,
72 blob_for_merge,
73 agent_slug,
74 &agent.agent_bus_id,
75 ) {
76 if let Some(pos) = config_files.iter().position(|f| f.filename == ".mcp.json") {
77 config_files[pos].content = mcp_json;
78 } else {
79 config_files.push(crate::backend::agent_config::AgentConfigFile {
80 filename: ".mcp.json".to_string(),
81 content: mcp_json,
82 });
83 }
84 }
85 }
86
87 if let Some(file) = config_files.iter_mut().find(|f| f.filename == ".mcp.json") {
102 crate::backend::mcp_json_identity::keys_for_agent_open(&mut file.content, &mstore, agent_slug, &agent);
103 }
104 config_files
105}
106
107fn disable_autonomous_memory(content_map: &mut std::collections::HashMap<String, String>, work_dir: &str) {
109 let settings_str = content_map
110 .entry("settings".to_string())
111 .or_insert_with(|| "{}".to_string());
112 match serde_json::from_str::<serde_json::Map<String, serde_json::Value>>(settings_str) {
113 Ok(mut obj) => {
114 obj.entry("autoMemoryEnabled".to_string())
115 .or_insert(json!(false));
116 *settings_str =
117 serde_json::to_string(&obj).unwrap_or_else(|_| "{}".to_string());
118 }
119 Err(e) => {
120 tracing::warn!(
121 work_dir = %work_dir,
122 error = %e,
123 "write_agent_config_files: settings JSON unparseable; \
124 autoMemoryEnabled guard skipped — memory writes may be active on shared workdir"
125 );
126 }
127 }
128}
129
130pub(super) fn write_config_file(
133 wd: &crate::backend::workdir_fs::Workdir,
134 base_path: &std::path::Path,
135 expanded_dir: &str,
136 file: &crate::backend::agent_config::AgentConfigFile,
137 on_host: bool,
138) -> Result<(), String> {
139 if file.filename == "CLAUDE.md" {
144 if let Err(e) =
145 crate::backend::agent_config::write_claude_md_respecting_ownership(base_path, &file.content)
146 {
147 return Err(format!("failed to write CLAUDE.md: {e}"));
148 }
149 return Ok(());
150 }
151 if crate::backend::providers::is_known_startup_instructions_filename(&file.filename) {
158 crate::backend::agent_config::write_startup_instructions_respecting_existing(
159 base_path,
160 &file.filename,
161 &file.content,
162 )
163 .map_err(|e| format!("failed to write {}: {e}", file.filename))?;
164 return Ok(());
165 }
166 if file.filename == ".mcp.json" {
172 let outside = if on_host {
173 crate::backend::mcp_config_file::host_relocated_path(expanded_dir)
174 } else {
175 crate::backend::mcp_config_file::relocated_path(expanded_dir)
176 };
177 if let Some(path) = outside {
178 let content = if on_host { crate::backend::mcp_config_file::host_content(expanded_dir, file.content.clone()) } else { file.content.clone() };
179 crate::backend::mcp_config_file::write_relocated(&path, &content)
180 .map_err(|e| format!("failed to write the agent's MCP config: {e}"))?;
181 return Ok(());
182 }
183 crate::backend::agent_config::write_mcp_json_respecting_user_servers(base_path, &file.content)
184 .map_err(|e| format!("failed to write .mcp.json: {e}"))?;
185 return Ok(());
186 }
187 match wd.write(&file.filename, file.content.as_bytes(), false) {
191 Err(e) if e.kind() == std::io::ErrorKind::PermissionDenied => {
192 tracing::warn!(
193 work_dir = %expanded_dir,
194 path = %file.filename,
195 error = %e,
196 "write_agent_config_files: refusing to write a config path outside the working directory"
197 );
198 }
199 other => other.map_err(|e| format!("failed to write {}: {e}", file.filename))?,
200 }
201
202 Ok(())
203}
204
205#[cfg(test)]
206mod tests {
207 use super::*;
208 use crate::backend::agent_config::AgentConfigFile;
209
210 fn files_under(dir: &std::path::Path) -> Vec<std::path::PathBuf> {
211 let mut out = Vec::new();
212 let mut stack = vec![dir.to_path_buf()];
213 while let Some(path) = stack.pop() {
214 for entry in std::fs::read_dir(&path).unwrap().flatten() {
215 let path = entry.path();
216 if path.is_dir() {
217 stack.push(path);
218 } else {
219 out.push(path);
220 }
221 }
222 }
223 out
224 }
225
226 #[test]
230 fn a_launch_into_a_user_project_leaves_its_mcp_json_alone_and_writes_no_keys_there() {
231 let data = tempfile::tempdir().unwrap();
232 let project = tempfile::tempdir().unwrap();
233 let project_mcp = project.path().join(".mcp.json");
234 let original = "{\n \"mcpServers\": {\n \"postgres\": { \"command\": \"pg-mcp\" }\n },\n \"kept\": true\n}\n";
235 std::fs::write(&project_mcp, original).unwrap();
236 let project_str = project.path().to_string_lossy().into_owned();
237
238 let relocated = crate::backend::mcp_config_file::with_data_home(data.path(), || {
239 let wd = crate::backend::workdir_fs::Workdir::open(project.path()).unwrap();
240 let file = AgentConfigFile {
241 filename: ".mcp.json".into(),
242 content: r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp","env":{"AGENTMUX_AGENT_ID":"aria","AGENTMUX_JEKT_KEY":"PRIVATE-JEKT","AGENTMUX_LAN_KEY":"PRIVATE-LAN"}}}}"#.into(),
243 };
244 write_config_file(&wd, project.path(), &project_str, &file, true).unwrap();
245 crate::backend::mcp_config_file::config_path(&project_str)
246 });
247
248 assert_eq!(
249 std::fs::read_to_string(&project_mcp).unwrap(),
250 original,
251 "the user's .mcp.json is byte-for-byte unchanged"
252 );
253 for file in files_under(project.path()) {
254 let body = std::fs::read_to_string(&file).unwrap_or_default();
255 assert!(
256 !body.contains("AGENTMUX_JEKT_KEY") && !body.contains("PRIVATE-JEKT") && !body.contains("PRIVATE-LAN"),
257 "no signing material may appear under the project: {file:?}"
258 );
259 }
260 assert!(!project.path().join(".claude").join(".agentmux-managed-mcp-servers.json").exists());
261 assert!(relocated.starts_with(data.path().join("mcp")), "{relocated:?}");
262 let written = std::fs::read_to_string(&relocated).unwrap();
263 assert!(written.contains("agentmux-mcp"), "{written}");
264 assert!(written.contains("PRIVATE-JEKT"), "the agent's own config may carry its keys: {written}");
265 }
266
267 #[test]
270 fn a_launch_into_an_agentmux_folder_keeps_the_file_in_it() {
271 let data = tempfile::tempdir().unwrap();
272 let home = data.path().join("agents").join("aria");
273 std::fs::create_dir_all(&home).unwrap();
274 let home_str = home.to_string_lossy().into_owned();
275 let relocated = crate::backend::mcp_config_file::with_data_home(data.path(), || {
276 let wd = crate::backend::workdir_fs::Workdir::open(&home).unwrap();
277 let file = AgentConfigFile {
278 filename: ".mcp.json".into(),
279 content: r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#.into(),
280 };
281 write_config_file(&wd, &home, &home_str, &file, true).unwrap();
282 crate::backend::mcp_config_file::relocated_path(&home_str)
283 });
284 assert!(home.join(".mcp.json").is_file());
285 assert!(relocated.is_none());
286 }
287
288 #[test]
291 fn a_host_launch_into_a_container_agents_folder_keeps_its_config_outside_and_takes_none_of_the_folders_servers() {
292 let data = tempfile::tempdir().unwrap();
293 let home = data.path().join("agents").join("aria");
294 std::fs::create_dir_all(&home).unwrap();
295 let home_str = home.to_string_lossy().into_owned();
296 let theirs = r#"{"mcpServers":{"agentmux":{"command":"other"},"theirs":{"command":"theirs-mcp"}}}"#;
297 std::fs::write(home.join(".mcp.json"), theirs).unwrap();
298 let file = AgentConfigFile {
299 filename: ".mcp.json".into(),
300 content: r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp","env":{"AGENTMUX_JEKT_KEY":"PRIVATE-JEKT"}}}}"#.into(),
301 };
302 let outside = crate::backend::mcp_config_file::with_data_home(data.path(), || {
303 crate::backend::mcp_folder_rule::mark(&home_str);
304 let wd = crate::backend::workdir_fs::Workdir::open(&home).unwrap();
305 write_config_file(&wd, &home, &home_str, &file, true).unwrap();
306 crate::backend::mcp_config_file::host_config_path(&home_str)
307 });
308 assert!(outside.starts_with(data.path().join(agentmux_common::mcp_config_path::HOST_ONLY_DIR)) && !outside.starts_with(&home), "{outside:?}");
309 let text = std::fs::read_to_string(&outside).unwrap();
310 let written: serde_json::Value = serde_json::from_str(&text).unwrap();
311 assert!(crate::backend::mcp_folder_rule::names_the_command_by_path(&text), "{text}");
313 assert_ne!(written["mcpServers"]["agentmux"]["command"], "agentmux-mcp");
314 assert!(written["mcpServers"].as_object().unwrap().keys().all(|name| name == "agentmux"), "none of the folder's servers: {written}");
315 assert_eq!(std::fs::read_to_string(home.join(".mcp.json")).unwrap(), theirs, "the folder's file is left as it is");
316 for file in files_under(&home) {
317 assert!(!std::fs::read_to_string(&file).unwrap_or_default().contains("PRIVATE-JEKT"), "no signing key in the folder: {file:?}");
318 }
319 }
320
321 #[test]
323 fn a_container_agents_own_launch_still_writes_the_file_in_its_folder() {
324 let data = tempfile::tempdir().unwrap();
325 let home = data.path().join("agents").join("aria");
326 std::fs::create_dir_all(&home).unwrap();
327 let home_str = home.to_string_lossy().into_owned();
328 let file = AgentConfigFile { filename: ".mcp.json".into(), content: r#"{"mcpServers":{"agentmux":{"command":"agentmux-mcp"}}}"#.into() };
329 crate::backend::mcp_config_file::with_data_home(data.path(), || {
330 crate::backend::mcp_folder_rule::mark(&home_str);
331 let wd = crate::backend::workdir_fs::Workdir::open(&home).unwrap();
332 write_config_file(&wd, &home, &home_str, &file, false).unwrap();
333 assert!(!crate::backend::mcp_config_file::host_config_path(&home_str).exists(), "nothing is written outside for it");
334 });
335 assert!(std::fs::read_to_string(home.join(".mcp.json")).unwrap().contains("agentmux-mcp"));
336 }
337}