Skip to content

Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors

Rust

fix(install-mcp): build the printed Codex table with the TOML writer

Rudy Celekli28c398a16eb1
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index 75fa5828..42f61cd5 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -199,7 +199,7 @@ pub(crate) fn run_with_opencode_dialect(
}
let snippet = match args.client {
McpClient::ClaudeCode => render_claude_code(&args, &resolve_config_file(&args)?)?,
- McpClient::Codex => render_codex(&args),
+ McpClient::Codex => render_codex(&args)?,
McpClient::Grok => render_grok(&args)?,
McpClient::OpenCode => render_opencode(&args)?,
McpClient::OpenCode2 => render_opencode2(&args)?,
@@ -2309,9 +2309,20 @@ fn render_claude_code(args: &InstallMcpArgs, config_path: &Path) -> Result<Strin
))
}
-fn render_codex(args: &InstallMcpArgs) -> String {
- // Codex uses TOML, not JSON. Hand-render the snippet so the
- // table headers stay deterministic.
+fn render_codex(args: &InstallMcpArgs) -> Result<String> {
+ // Codex uses TOML, not JSON. Build the printed table with the very
+ // writer `--apply` uses (`codex_upsert_mcp_server`) so the snippet and
+ // the file can never disagree. Hand-interpolating `[mcp_servers.{name}]`
+ // made them disagree for any name TOML has to quote: `--name ai.memory`
+ // printed a header that reads as `mcp_servers` -> `ai` -> `memory`, and
+ // `--name "my memory"` printed an unparseable header that breaks the
+ // whole `config.toml` it is pasted into -- while `--apply` wrote
+ // `[mcp_servers."ai.memory"]` correctly all along. `render_grok` was
+ // moved onto its writer for exactly this reason; Codex is the other
+ // TOML client and was missed.
+ //
+ // The explanatory comments ride along as `toml_edit` decor, so the
+ // snippet for an ordinary name is byte-for-byte what it always was.
//
// Schema: Codex's MCP `streamable_http` transport accepts
// - `bearer_token_env_var = "NAME"` (env-var indirection)
@@ -2320,35 +2331,45 @@ fn render_codex(args: &InstallMcpArgs) -> String {
// — NOT a literal `bearer_token = "..."` (that's stdio-only)
// and NOT a `[mcp_servers.<name>.headers]` sub-table (the key
// is `http_headers`, with the `http_` prefix).
- let mut out = format!(
- "# Codex CLI — append to $CODEX_HOME/config.toml (default ~/.codex/config.toml)\n\
- #\n\
- [mcp_servers.{name}]\n\
- url = \"{url}\"\n\
- # Skip per-call approval prompts on ai-memory's tools.\n\
- # ai-memory is read-mostly + writes are auto-capture; the\n\
- # approval friction makes it unusable otherwise.\n\
- default_tools_approval_mode = \"approve\"\n",
- name = args.name,
- url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),
+ let mut doc = toml_edit::DocumentMut::new();
+ codex_upsert_mcp_server(&mut doc, args)?;
+ let server = doc
+ .get_mut("mcp_servers")
+ .and_then(toml_edit::Item::as_table_mut)
+ .and_then(|servers| servers.get_mut(&args.name))
+ .and_then(toml_edit::Item::as_table_mut)
+ .context("internal: generated Codex TOML table missing")?;
+ if let Some(mut key) = server.key_mut("default_tools_approval_mode") {
+ key.leaf_decor_mut().set_prefix(
+ "# Skip per-call approval prompts on ai-memory's tools.\n\
+ # ai-memory is read-mostly + writes are auto-capture; the\n\
+ # approval friction makes it unusable otherwise.\n",
+ );
+ }
+ if let Some(headers) = server
+ .get_mut("http_headers")
+ .and_then(toml_edit::Item::as_table_mut)
+ {
+ headers.decor_mut().set_prefix("\n");
+ }
+ let mut out = String::from(
+ "# Codex CLI — append to $CODEX_HOME/config.toml (default ~/.codex/config.toml)\n#\n",
);
+ out.push_str(&doc.to_string());
+ // Trailing prose: `toml_edit` 0.22 has no document-trailer setter, and a
+ // comment after the last key carries no TOML structure either way.
if args.token_env_var {
out.push_str(&format!(
- "bearer_token_env_var = \"{PRIME_AGENT_TOKEN_ENV}\"\n\
- # The token is read from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch codex.\n"
+ "# The token is read from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch codex.\n"
));
- } else if let Some(b) = bearer_header_value(args.auth_token.as_deref()) {
- out.push_str(&format!(
- "\n[mcp_servers.{name}.http_headers]\n\
- Authorization = \"{b}\"\n\
- # Alternative (avoids embedding the literal token):\n\
+ } else if bearer_header_value(args.auth_token.as_deref()).is_some() {
+ out.push_str(
+ "# Alternative (avoids embedding the literal token):\n\
# bearer_token_env_var = \"AI_MEMORY_AUTH_TOKEN\"\n\
# — and export AI_MEMORY_AUTH_TOKEN in your shell init.\n",
- name = args.name,
- b = b,
- ));
+ );
}
- out
+ Ok(out)
}
fn render_grok(args: &InstallMcpArgs) -> Result<String> {
@@ -4102,7 +4123,7 @@ mod tests {
/// rendered inside the Docker image, whose paths mean nothing on the host.
#[test]
fn codex_render_names_codex_home() {
- let out = render_codex(&args_for(McpClient::Codex));
+ let out = render_codex(&args_for(McpClient::Codex)).unwrap();
assert!(
out.contains("$CODEX_HOME/config.toml"),
"render must point a relocated Codex at its config home:\n{out}"
@@ -4509,7 +4530,7 @@ mod tests {
McpClient::ClaudeCode => {
render_claude_code(&args, Path::new("/home/alice/.claude.json")).unwrap()
}
- McpClient::Codex => render_codex(&args),
+ McpClient::Codex => render_codex(&args).unwrap(),
McpClient::Grok => render_grok(&args).unwrap(),
McpClient::OpenCode => render_opencode(&args).unwrap(),
McpClient::OpenCode2 => render_opencode2(&args).unwrap(),
@@ -4643,7 +4664,7 @@ mod tests {
McpClient::ClaudeCode => {
render_claude_code(&args, Path::new("/home/alice/.claude.json")).unwrap()
}
- McpClient::Codex => render_codex(&args),
+ McpClient::Codex => render_codex(&args).unwrap(),
McpClient::Grok => render_grok(&args).unwrap(),
McpClient::OpenCode => render_opencode(&args).unwrap(),
McpClient::OpenCode2 => render_opencode2(&args).unwrap(),
@@ -6120,6 +6141,131 @@ mod tests {
);
}
+ #[test]
+ fn codex_print_uses_apply_toml_builder_for_dotted_names_and_quotes() {
+ let mut args = args_with_token(McpClient::Codex);
+ args.name = "ai.memory".into();
+ args.server_url = Some("https://memory.example/mcp?note=\"quoted\"".into());
+
+ let printed = render_codex(&args).unwrap();
+ let mut applied = toml_edit::DocumentMut::new();
+ codex_upsert_mcp_server(&mut applied, &args).unwrap();
+
+ // The print path and the --apply path must agree on the table name.
+ let parsed: toml_edit::DocumentMut = printed
+ .lines()
+ .filter(|line| !line.starts_with('#'))
+ .collect::<Vec<_>>()
+ .join("\n")
+ .parse()
+ .unwrap_or_else(|error| {
+ panic!("printed snippet is not valid TOML: {error}\n{printed}")
+ });
+ let servers = parsed.get("mcp_servers").unwrap().as_table().unwrap();
+ assert_eq!(servers.len(), 1, "print output:\n{printed}");
+ assert!(
+ servers.get("ai.memory").is_some(),
+ "print output:\n{printed}"
+ );
+ assert_eq!(
+ servers
+ .get("ai.memory")
+ .and_then(|server| server.get("url"))
+ .and_then(|url| url.as_str()),
+ Some("https://memory.example/mcp?note=\"quoted\""),
+ "print output:\n{printed}"
+ );
+ assert!(
+ printed.contains(&format!("[mcp_servers.{:?}]", "ai.memory")),
+ "print output:\n{printed}"
+ );
+ assert!(
+ applied
+ .to_string()
+ .contains(&format!("[mcp_servers.{:?}]", "ai.memory")),
+ "applied output:\n{applied}"
+ );
+ }
+
+ #[test]
+ fn codex_print_quotes_a_table_name_containing_a_space() {
+ let mut args = args_for(McpClient::Codex);
+ args.name = "my memory".into();
+
+ let printed = render_codex(&args).unwrap();
+ let parsed: toml_edit::DocumentMut = printed
+ .lines()
+ .filter(|line| !line.starts_with('#'))
+ .collect::<Vec<_>>()
+ .join("\n")
+ .parse()
+ .unwrap_or_else(|error| {
+ panic!("printed snippet is not valid TOML: {error}\n{printed}")
+ });
+ let servers = parsed.get("mcp_servers").unwrap().as_table().unwrap();
+ assert_eq!(servers.len(), 1, "print output:\n{printed}");
+ assert!(
+ servers.get("my memory").is_some(),
+ "print output:\n{printed}"
+ );
+ }
+
+ #[test]
+ fn codex_print_is_byte_identical_for_an_ordinary_name() {
+ let mut plain = args_for(McpClient::Codex);
+ plain.server_url = Some("http://127.0.0.1:49374/mcp".into());
+ assert_eq!(
+ render_codex(&plain).unwrap(),
+ "# Codex CLI — append to $CODEX_HOME/config.toml (default ~/.codex/config.toml)\n\
+ #\n\
+ [mcp_servers.ai-memory]\n\
+ url = \"http://127.0.0.1:49374/mcp\"\n\
+ # Skip per-call approval prompts on ai-memory's tools.\n\
+ # ai-memory is read-mostly + writes are auto-capture; the\n\
+ # approval friction makes it unusable otherwise.\n\
+ default_tools_approval_mode = \"approve\"\n"
+ );
+
+ let mut with_token = args_with_token(McpClient::Codex);
+ with_token.server_url = Some("http://127.0.0.1:49374/mcp".into());
+ assert_eq!(
+ render_codex(&with_token).unwrap(),
+ "# Codex CLI — append to $CODEX_HOME/config.toml (default ~/.codex/config.toml)\n\
+ #\n\
+ [mcp_servers.ai-memory]\n\
+ url = \"http://127.0.0.1:49374/mcp\"\n\
+ # Skip per-call approval prompts on ai-memory's tools.\n\
+ # ai-memory is read-mostly + writes are auto-capture; the\n\
+ # approval friction makes it unusable otherwise.\n\
+ default_tools_approval_mode = \"approve\"\n\
+ \n\
+ [mcp_servers.ai-memory.http_headers]\n\
+ Authorization = \"Bearer test-token-deadbeef\"\n\
+ # Alternative (avoids embedding the literal token):\n\
+ # bearer_token_env_var = \"AI_MEMORY_AUTH_TOKEN\"\n\
+ # — and export AI_MEMORY_AUTH_TOKEN in your shell init.\n"
+ );
+
+ let mut env_var = args_for(McpClient::Codex);
+ env_var.server_url = Some("http://127.0.0.1:49374/mcp".into());
+ env_var.token_env_var = true;
+ assert_eq!(
+ render_codex(&env_var).unwrap(),
+ format!(
+ "# Codex CLI — append to $CODEX_HOME/config.toml (default ~/.codex/config.toml)\n\
+ #\n\
+ [mcp_servers.ai-memory]\n\
+ url = \"http://127.0.0.1:49374/mcp\"\n\
+ # Skip per-call approval prompts on ai-memory's tools.\n\
+ # ai-memory is read-mostly + writes are auto-capture; the\n\
+ # approval friction makes it unusable otherwise.\n\
+ default_tools_approval_mode = \"approve\"\n\
+ bearer_token_env_var = \"{PRIME_AGENT_TOKEN_ENV}\"\n\
+ # The token is read from ${PRIME_AGENT_TOKEN_ENV}; export it where you launch codex.\n"
+ )
+ );
+ }
+
#[test]
fn grok_print_uses_apply_toml_builder_for_dotted_names_and_quotes() {
let mut args = args_with_token(McpClient::Grok);