Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
M22 fixes: Claude Code target, allowed_hosts, Codex block-form, preserve_order
AkitaOnRailsce13316ac096
diff --git a/Cargo.lock b/Cargo.lockindex 5d96e6c3..756eba27 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -2246,6 +2246,7 @@ version = "1.0.150"source = "registry+https://github.com/rust-lang/crates.io-index"checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"dependencies = [+ "indexmap","itoa","memchr","serde",diff --git a/Cargo.toml b/Cargo.tomlindex 9f6d1eb0..2e8d646f 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -37,7 +37,12 @@ thiserror = "2"# Serialization.serde = { version = "1", features = ["derive"] }-serde_json = "1"+# `preserve_order` keeps existing JSON key order intact when we+# round-trip user config files via `install-mcp --apply`. Without it,+# `~/.claude.json` (which has dozens of CC-managed keys) would be+# alphabetised on every write — semantically equivalent but a giant+# cosmetic diff the user didn't ask for.+serde_json = { version = "1", features = ["preserve_order"] }serde_yaml = "0.9"# Async runtime.diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex 13605dce..7a3ad236 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -63,7 +63,15 @@ fn resolve_config_file(args: &InstallMcpArgs) -> Result<PathBuf> {}let home = dirs::home_dir().context("could not locate $HOME for config-file auto-detect")?;Ok(match args.client {- McpClient::ClaudeCode => home.join(".claude").join("settings.json"),+ // Claude Code reads MCP-server registrations from `~/.claude.json`+ // (the same file `claude mcp add`/`claude mcp list` operate on).+ // `~/.claude/settings.json` is a separate file for hooks /+ // permissions / etc. — putting `mcpServers` there does NOT make+ // Claude Code load the server. (Confirmed against CC 1.x by+ // observing that `mcpServers` in settings.json is silently+ // ignored while the same entry under `~/.claude.json` shows up+ // in `claude mcp list`.)+ McpClient::ClaudeCode => home.join(".claude.json"),McpClient::Codex => home.join(".codex").join("config.toml"),McpClient::OpenCode => home.join(".config").join("opencode").join("opencode.json"),McpClient::Cursor => home.join(".cursor").join("mcp.json"),@@ -147,18 +155,7 @@ fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {})})?,McpClient::Codex => apply_atomic(&path, |existing| {- mutate_toml(existing, |doc| {- // `[mcp_servers.<name>]` table.- let bearer = bearer_header_value_shared(args.auth_token.as_deref());- let key = format!("mcp_servers.{}", args.name);- let _ = key; // (used in the comment above; toml_edit indexes via [] chain)- doc["mcp_servers"][&args.name]["url"] = toml_edit::value(args.server_url.clone());- if let Some(b) = bearer {- doc["mcp_servers"][&args.name]["headers"]["Authorization"] =- toml_edit::value(b);- }- Ok(())- })+ mutate_toml(existing, |doc| codex_upsert_mcp_server(doc, args))})?,McpClient::Pi => unreachable!("pi guarded above"),};@@ -249,6 +246,60 @@ fn bearer_header_value(args: &InstallMcpArgs) -> Option<String> {bearer_header_value_shared(args.auth_token.as_deref())}+/// Insert / replace `[mcp_servers.<name>]` in a Codex `config.toml`.+///+/// Codex parses both forms (block-style `[mcp_servers.foo]` and the+/// dotted-inline `mcp_servers = { foo = { ... } }`), but its docs show+/// the block form and that's the only one humans want to read. This+/// helper canonicalises to the block form even when the file currently+/// stores `mcp_servers` as an inline table — siblings are preserved.+fn codex_upsert_mcp_server(+ doc: &mut toml_edit::DocumentMut,+ args: &InstallMcpArgs,+) -> anyhow::Result<()> {+ use toml_edit::{Item, Table, Value, value};++ let bearer = bearer_header_value_shared(args.auth_token.as_deref());++ // Capture sibling entries from either inline-table or block-table+ // storage so we can rebuild in block form without dropping them.+ let preserved: Vec<(String, Item)> = match doc.get("mcp_servers") {+ Some(Item::Table(t)) => t+ .iter()+ .filter(|(k, _)| *k != args.name.as_str())+ .map(|(k, v)| (k.to_string(), v.clone()))+ .collect(),+ Some(Item::Value(Value::InlineTable(it))) => it+ .iter()+ .filter(|(k, _)| *k != args.name.as_str())+ .map(|(k, v)| (k.to_string(), Item::Value(v.clone())))+ .collect(),+ _ => Vec::new(),+ };++ // Build our `[mcp_servers.<name>]` as a block-style table.+ let mut server = Table::new();+ server["url"] = value(args.server_url.clone());+ if let Some(b) = bearer {+ let mut headers = Table::new();+ headers["Authorization"] = value(b);+ server["headers"] = Item::Table(headers);+ }++ // Replace `mcp_servers` wholesale with a fresh implicit parent+ // table. Implicit = render only the dotted `[mcp_servers.<name>]`+ // headers, never a bare `[mcp_servers]` header.+ let mut parent = Table::new();+ parent.set_implicit(true);+ for (k, v) in preserved {+ parent.insert(&k, v);+ }+ parent.insert(&args.name, Item::Table(server));++ doc.insert("mcp_servers", Item::Table(parent));+ Ok(())+}+fn render_claude_code(args: &InstallMcpArgs) -> Result<String> {let bearer = bearer_header_value(args);let cli_line = if let Some(b) = &bearer {@@ -558,4 +609,80 @@ mod tests {assert!(render_for_test(McpClient::Openclaw).contains("\"streamable-http\""));assert!(render_for_test(McpClient::Codex).contains("[mcp_servers.ai-memory]"));}++ /// The Codex apply path must emit block-form `[mcp_servers.<name>]`+ /// headers, NOT a dotted inline-table on one line. Regression+ /// guard: M22 originally created `mcp_servers = { ai-memory = {...} }`+ /// because toml_edit auto-vivifies inline tables when you assign+ /// through `doc["foo"]["bar"]`.+ #[test]+ fn codex_apply_writes_block_form_tables() {+ let args = args_with_token(McpClient::Codex);+ let mut doc: toml_edit::DocumentMut = "".parse().unwrap();+ codex_upsert_mcp_server(&mut doc, &args).unwrap();+ let out = doc.to_string();+ assert!(+ out.contains("[mcp_servers.ai-memory]"),+ "expected block-form table header, got:\n{out}"+ );+ assert!(+ out.contains("[mcp_servers.ai-memory.headers]"),+ "expected block-form headers sub-table, got:\n{out}"+ );+ assert!(+ !out.contains("mcp_servers = {"),+ "found inline-table form (regression):\n{out}"+ );+ assert!(out.contains("Bearer test-token-deadbeef"));+ }++ /// Migrating from the old M22 inline-table form to block form must+ /// be idempotent — the second apply produces identical output.+ #[test]+ fn codex_apply_migrates_inline_form_and_is_idempotent() {+ let args = args_with_token(McpClient::Codex);++ // Simulate a config.toml in the *old* inline form.+ let original = "approval_policy = \"on-request\"\n\+ mcp_servers = { ai-memory = { url = \"http://old\", \+ headers = { Authorization = \"Bearer old\" } } }\n\+ \n\+ [other]\n\+ keep = \"this\"\n";+ let mut doc: toml_edit::DocumentMut = original.parse().unwrap();+ codex_upsert_mcp_server(&mut doc, &args).unwrap();+ let first = doc.to_string();++ // After migration the inline-table form is gone.+ assert!(!first.contains("mcp_servers = {"));+ assert!(first.contains("[mcp_servers.ai-memory]"));+ // Unrelated content survives.+ assert!(first.contains("approval_policy"));+ assert!(first.contains("[other]"));+ assert!(first.contains("keep = \"this\""));++ // Re-applying produces the same bytes (idempotency contract).+ let mut doc2: toml_edit::DocumentMut = first.parse().unwrap();+ codex_upsert_mcp_server(&mut doc2, &args).unwrap();+ let second = doc2.to_string();+ assert_eq!(+ first, second,+ "second apply must produce identical bytes; diff:\n--- first\n{first}\n--- second\n{second}"+ );+ }++ /// Sibling `[mcp_servers.<other>]` entries the user has configured+ /// (e.g. a different MCP server) must survive an --apply.+ #[test]+ fn codex_apply_preserves_sibling_mcp_servers() {+ let args = args_for(McpClient::Codex);+ let original = "[mcp_servers.other-server]\n\+ url = \"http://other\"\n";+ let mut doc: toml_edit::DocumentMut = original.parse().unwrap();+ codex_upsert_mcp_server(&mut doc, &args).unwrap();+ let out = doc.to_string();+ assert!(out.contains("[mcp_servers.other-server]"));+ assert!(out.contains("http://other"));+ assert!(out.contains("[mcp_servers.ai-memory]"));+ }}diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex 0e1c942b..a59f7645 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -142,10 +142,31 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {let bind = args.bind.unwrap_or_else(|| config.bind.clone());let cancel = CancellationToken::new();let server_clone = server.clone();+ // `Host`-header allowlist for rmcp's DNS-rebinding guard.+ // Precedence: AI_MEMORY_ALLOWED_HOSTS env (comma-separated)+ // overrides config.allowed_hosts entirely; both default to+ // loopback. Matches the AI_MEMORY_AUTH_TOKEN env-overrides-+ // config pattern just below.+ let allowed_hosts: Vec<String> = std::env::var("AI_MEMORY_ALLOWED_HOSTS")+ .ok()+ .filter(|s| !s.is_empty())+ .map(|s| {+ s.split(',')+ .map(|x| x.trim().to_string())+ .filter(|x| !x.is_empty())+ .collect()+ })+ .unwrap_or_else(|| config.allowed_hosts.clone());+ info!(+ allowed_hosts = ?allowed_hosts,+ "MCP Host-header allowlist"+ );let mcp_service = StreamableHttpService::new(move || Ok(server_clone.clone()),LocalSessionManager::default().into(),- StreamableHttpServerConfig::default().with_cancellation_token(cancel.child_token()),+ StreamableHttpServerConfig::default()+ .with_cancellation_token(cancel.child_token())+ .with_allowed_hosts(allowed_hosts),);let hooks = hook_router(HookState {workspace_id: ws,diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rsindex b1b5fcc8..e741228c 100644--- a/crates/ai-memory-cli/src/config.rs+++ b/crates/ai-memory-cli/src/config.rs@@ -49,6 +49,13 @@ pub struct Config {/// `AI_MEMORY_AUTH_TOKEN` env var or `[auth].bearer_token` in/// config.toml.pub auth: AuthSettings,+ /// `Host`-header allowlist for the MCP transport. rmcp's+ /// `StreamableHttpService` rejects any inbound request whose+ /// `Host` header doesn't match this list (DNS-rebinding defence).+ /// Default is loopback only; to expose ai-memory on a LAN+ /// IP / `home.lan` / etc., add that authority here or pass it via+ /// `AI_MEMORY_ALLOWED_HOSTS=host1,host2,…` at startup.+ pub allowed_hosts: Vec<String>,}/// `[auth]` section of `config.toml`.@@ -70,6 +77,7 @@ impl Default for Config {decay: ai_memory_store::DecayParams::default(),sanitize: ai_memory_core::SanitizeConfig::default(),auth: AuthSettings::default(),+ allowed_hosts: vec!["localhost".into(), "127.0.0.1".into(), "::1".into()],}}}