Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(install-mcp): make Codex prompt before destructive ai-memory tools
AkitaOnRailsd34d0ff3e9d5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 27043f48..ef5648eb 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -43,6 +43,15 @@ version in [`docs/changelog/`](docs/changelog/):`--with-config`. Reported by @FabioLeitao.([GHSA-jpcg-w5c5-wcv6](https://github.com/akitaonrails/ai-memory/security/advisories/GHSA-jpcg-w5c5-wcv6))+- `install-mcp --client codex` now makes Codex ask before running ai-memory's+ destructive tools. The read tools still run without a prompt; every tool+ annotated destructive (deleting or restoring a page, the forget sweep,+ accepting or cancelling a handoff, popping or cancelling messages, recall+ feedback) gets a per-tool `approval_mode = "prompt"`, and a re-install keeps+ per-tool settings you already chose. Re-run `install-mcp --client codex+ --apply` to update an existing entry. Reported by @FabioLeitao.+ ([GHSA-jpcg-w5c5-wcv6](https://github.com/akitaonrails/ai-memory/security/advisories/GHSA-jpcg-w5c5-wcv6))+## [3.2.0] - 2026-10-21### Addeddiff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 75fa5828..30f59686 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -2163,20 +2163,27 @@ fn codex_upsert_mcp_server(// - v3 (this): `[mcp_servers.X.http_headers]` with// `Authorization = "Bearer ..."`. Codex schema-validates// and uses it as a static auth header.+ // Read before the server table is replaced: per-tool approval+ // overrides the user already chose survive a re-install.+ let tools = codex_tool_approvals(+ doc.get("mcp_servers")+ .and_then(|servers| servers.get(&args.name))+ .and_then(|server| server.get("tools")),+ );let mut server = Table::new();server["url"] = value(args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL));// Auto-approve ai-memory's tool calls. Without this, Codex// prompts on EVERY tool invocation ("approve memory_query?"// "approve memory_briefing?" …) which makes the MCP unusable- // for an auto-capture workflow. The valid TOML values per- // Codex's `AppToolApproval` enum are "auto" / "prompt" /- // "approve" — `approve` means "no prompt, just run it". ai-- // memory's surface is dominantly read-only (query, recent,- // status, briefing, explore); the few writes (consolidate,- // forget_sweep) are tagged `destructiveHint: true` upstream- // so any agent that wants to gate THOSE specifically can- // override per-tool — see Codex's `[mcp_servers.X.tools]`- // map.+ // for an auto-capture workflow. The valid values per Codex's+ // config reference are "auto" / "prompt" / "writes" /+ // "approve" — `approve` means "no prompt, just run it". The+ // tools annotated destructive get a per-tool+ // `[mcp_servers.X.tools.<tool>] approval_mode = "prompt"`+ // override below (`codex_tool_approvals`).+ // https://developers.openai.com/codex/config-reference+ // (`mcp_servers.<id>.default_tools_approval_mode`,+ // `mcp_servers.<id>.tools.<tool>.approval_mode`).server["default_tools_approval_mode"] = value("approve");if args.token_env_var {server["bearer_token_env_var"] = value(PRIME_AGENT_TOKEN_ENV);@@ -2185,11 +2192,49 @@ fn codex_upsert_mcp_server(headers["Authorization"] = value(b);server["http_headers"] = Item::Table(headers);}+ server.insert("tools", Item::Table(tools));upsert_toml_mcp_server(doc, &args.name, server);Ok(())}+/// Codex `[mcp_servers.<name>.tools]`: the user's existing per-tool entries,+/// copied as plain keys, plus `approval_mode = "prompt"` for every tool+/// annotated destructive that has no approval mode yet. The server-wide+/// default stays `approve`, so the read tools never prompt, while every tool+/// annotated destructive asks first.+fn codex_tool_approvals(existing: Option<&toml_edit::Item>) -> toml_edit::Table {+ use toml_edit::{Item, Table, value};++ let mut tools = Table::new();+ tools.set_implicit(true);+ if let Some(existing) = existing.and_then(Item::as_table_like) {+ for (tool, entry) in existing.iter() {+ let Some(entry) = entry.as_table_like() else {+ continue;+ };+ let mut copy = Table::new();+ for (key, item) in entry.iter() {+ if let Some(value) = item.as_value() {+ copy.insert(key, Item::Value(value.clone()));+ }+ }+ tools.insert(tool, Item::Table(copy));+ }+ }+ for tool in ai_memory_mcp::AiMemoryServer::destructive_tool_names() {+ if !tools.contains_key(&tool) {+ tools.insert(&tool, Item::Table(Table::new()));+ }+ if let Some(entry) = tools.get_mut(&tool).and_then(Item::as_table_mut)+ && !entry.contains_key("approval_mode")+ {+ entry.insert("approval_mode", value("prompt"));+ }+ }+ tools+}+/// Insert / replace `[mcp_servers.<name>]` in a Grok `config.toml`.////// Grok's schema (user-guide § MCP Servers) uses:@@ -2325,9 +2370,8 @@ fn render_codex(args: &InstallMcpArgs) -> String {#\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\+ # Skip per-call approval prompts on ai-memory's read tools;\n\+ # the destructive ones below still ask first.\n\default_tools_approval_mode = \"approve\"\n",name = args.name,url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),@@ -2348,6 +2392,12 @@ fn render_codex(args: &InstallMcpArgs) -> String {b = b,));}+ for tool in ai_memory_mcp::AiMemoryServer::destructive_tool_names() {+ out.push_str(&format!(+ "\n[mcp_servers.{name}.tools.{tool}]\napproval_mode = \"prompt\"\n",+ name = args.name,+ ));+ }out}@@ -5876,6 +5926,77 @@ mod tests {);}+ /// Codex keeps auto-approving the read tools, but every tool annotated+ /// destructive gets a per-tool prompt.+ #[test]+ fn codex_apply_prompts_for_every_destructive_tool() {+ let destructive = ai_memory_mcp::AiMemoryServer::destructive_tool_names();+ assert!(+ destructive.iter().any(|tool| tool == "memory_delete_page"),+ "{destructive:?}"+ );+ let mut doc: toml_edit::DocumentMut = "".parse().unwrap();+ codex_upsert_mcp_server(&mut doc, &args_for(McpClient::Codex)).unwrap();+ let out = doc.to_string();+ assert!(+ out.contains("default_tools_approval_mode = \"approve\""),+ "{out}"+ );+ let server = &doc["mcp_servers"]["ai-memory"];+ for tool in &destructive {+ assert_eq!(+ server["tools"][tool.as_str()]["approval_mode"].as_str(),+ Some("prompt"),+ "{tool} must prompt:\n{out}"+ );+ }+ for read_tool in ["memory_query", "memory_recent", "memory_briefing"] {+ assert!(+ server["tools"].get(read_tool).is_none(),+ "{read_tool} keeps the approve default:\n{out}"+ );+ }++ let rendered = render_codex(&args_for(McpClient::Codex));+ for tool in &destructive {+ assert!(+ rendered.contains(&format!(+ "[mcp_servers.ai-memory.tools.{tool}]\napproval_mode = \"prompt\""+ )),+ "{tool} missing from the printed snippet:\n{rendered}"+ );+ }+ rendered.parse::<toml_edit::DocumentMut>().unwrap();+ }++ /// A re-install keeps the per-tool choices the user already made.+ #[test]+ fn codex_apply_keeps_existing_per_tool_overrides() {+ let original = "[mcp_servers.ai-memory]\n\+ url = \"http://old\"\n\+ \n\+ [mcp_servers.ai-memory.tools.memory_delete_page]\n\+ approval_mode = \"approve\"\n\+ \n\+ [mcp_servers.ai-memory.tools.memory_query]\n\+ approval_mode = \"prompt\"\n";+ let mut doc: toml_edit::DocumentMut = original.parse().unwrap();+ codex_upsert_mcp_server(&mut doc, &args_for(McpClient::Codex)).unwrap();+ let tools = &doc["mcp_servers"]["ai-memory"]["tools"];+ assert_eq!(+ tools["memory_delete_page"]["approval_mode"].as_str(),+ Some("approve")+ );+ assert_eq!(+ tools["memory_query"]["approval_mode"].as_str(),+ Some("prompt")+ );+ assert_eq!(+ tools["memory_forget_sweep"]["approval_mode"].as_str(),+ Some("prompt")+ );+ }+/// Sibling `[mcp_servers.<other>]` entries the user has configured/// (e.g. a different MCP server) must survive an --apply.#[test]diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex 6681f730..f60cf6bc 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -7315,6 +7315,27 @@ fn select_bumpable(}impl AiMemoryServer {+ /// Names of the tools annotated `destructive_hint = true`, sorted.+ /// `install-mcp` gives each a per-tool approval prompt in clients that+ /// support one, so a new destructive tool inherits it from its+ /// annotation.+ #[must_use]+ pub fn destructive_tool_names() -> Vec<String> {+ let mut names: Vec<String> = Self::tool_router()+ .list_all()+ .into_iter()+ .filter(|tool| {+ tool.annotations+ .as_ref()+ .and_then(|annotations| annotations.destructive_hint)+ == Some(true)+ })+ .map(|tool| tool.name.to_string())+ .collect();+ names.sort();+ names+ }+/// The latest version id of a page in an already-authorized scope.async fn latest_page_id(&self,@@ -8759,6 +8780,21 @@ mod tests {let (_tmp, _store, _server, _ws, _pj) = setup_server().await;}+ #[test]+ fn destructive_tool_names_follow_the_annotations() {+ let names = AiMemoryServer::destructive_tool_names();+ for destructive in [+ "memory_delete_page",+ "memory_forget_sweep",+ "memory_message_pop",+ ] {+ assert!(names.iter().any(|name| name == destructive), "{names:?}");+ }+ for read_only in ["memory_query", "memory_recent", "memory_status"] {+ assert!(!names.iter().any(|name| name == read_only), "{names:?}");+ }+ }+#[tokio::test]async fn prompts_cover_every_registered_mcp_tool() {let (_tmp, _store, server, _ws, _pj) = setup_server().await;diff --git a/docs/install.md b/docs/install.mdindex 0f1c5106..a57be469 100644--- a/docs/install.md+++ b/docs/install.md@@ -1333,6 +1333,15 @@ docker run --rm akitaonrails/ai-memory:latest \--auth-token "$TOKEN"```+The Codex entry `install-mcp` writes sets `default_tools_approval_mode =+"approve"`, so ai-memory's read tools run without a prompt, and adds+`[mcp_servers.<name>.tools.<tool>]` with `approval_mode = "prompt"` for every+tool annotated destructive (`memory_delete_page`, `memory_forget_sweep`,+`memory_restore_page`, the handoff accept and cancel tools, the message pop and+cancel tools, and `memory_feedback`), so Codex asks before running them. A+re-install keeps any per-tool `approval_mode` you set yourself. Both keys are in+Codex's [configuration reference](https://developers.openai.com/codex/config-reference).+Native Codex tool hooks use top-level `tool_name`, `tool_input`, `tool_response`,and `tool_use_id` fields (verified against CLI 0.154.0). ai-memory records thetool family and call ID on `PreToolUse` and `PostToolUse`; recognized tools such