Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(run): keep an existing session-aware Claude Code MCP bridge on auto-wire
Felipe Neves Ricardob0fec19d1704
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 815328ed..5665a810 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0query before falling back. (#873)### Fixed+- `ai-memory run`'s auto-wire no longer overwrites an installed session-aware+ Claude Code MCP bridge with the static HTTP registration. The auto-wire+ sentinel is keyed by client version, so the MCP step re-ran on every upgrade+ and replaced the `ai-memory` entry wholesale; a user who had run `install-mcp+ --client claude-code --session-aware` lost the bridge on the next `ai-memory+ run` after an upgrade, silently disabling `[auto_scope] per_session` for their+ MCP calls. Auto-wire now detects an existing session-aware bridge and keeps+ it. (#888)- The Linux/macOS Docker wrapper now keeps its native host client in`${XDG_DATA_HOME:-~/.local/share}/ai-memory/native-runner` instead of`~/.cache/ai-memory/native-runner`. `ai-memory run` auto-wires hooks whosediff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex d954f53f..96b4abc5 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -430,6 +430,47 @@ fn resolve_config_file(args: &InstallMcpArgs) -> Result<PathBuf> {mcp_config_path(args.client)}+/// True when the client's MCP config already holds a session-aware ai-memory+/// bridge under `name` — a Claude Code stdio entry whose args run `mcp-bridge`.+///+/// Auto-wire consults this before its version-keyed re-wire so it never+/// downgrades a deliberately-installed bridge to the static HTTP registration,+/// which would silently disable `[auto_scope] per_session` for MCP calls. Only+/// Claude Code has a session-aware variant, so every other client answers+/// `false`. A missing file or any parse error also answers `false`: the caller+/// then falls back to its normal install, which is the safe default.+pub(crate) fn existing_entry_is_session_aware(+ client: McpClient,+ config_file: Option<&Path>,+ name: &str,+) -> bool {+ if !matches!(client, McpClient::ClaudeCode) {+ return false;+ }+ let path = match config_file {+ Some(path) => path.to_path_buf(),+ None => match mcp_config_path(client) {+ Ok(path) => path,+ Err(_) => return false,+ },+ };+ let Ok(text) = std::fs::read_to_string(&path) else {+ return false;+ };+ let Ok(root) = serde_json::from_str::<serde_json::Value>(&text) else {+ return false;+ };+ let Some(entry) = root.get("mcpServers").and_then(|servers| servers.get(name)) else {+ return false;+ };+ let is_stdio = entry.get("type").and_then(serde_json::Value::as_str) == Some("stdio");+ let runs_bridge = entry+ .get("args")+ .and_then(serde_json::Value::as_array)+ .is_some_and(|args| args.iter().any(|arg| arg.as_str() == Some("mcp-bridge")));+ is_stdio && runs_bridge+}+/// Mutate the resolved client config file in place. Idempotent —/// re-runs that produce the same content are reported as no-op.fn apply_to_config_file(args: &InstallMcpArgs) -> Result<()> {diff --git a/crates/ai-memory-cli/src/commands/run_autowire.rs b/crates/ai-memory-cli/src/commands/run_autowire.rsindex 495abde9..a6819a15 100644--- a/crates/ai-memory-cli/src/commands/run_autowire.rs+++ b/crates/ai-memory-cli/src/commands/run_autowire.rs@@ -131,8 +131,23 @@ pub(crate) fn ensure_wired_with(// Not every hook-capable harness has an MCP client the installer can write// (e.g. Pi bridges MCP through its generated extension); skip those quietly.- if let Some(client) = install_hooks::mcp_client_for_agent(agent)- && let Err(error) = install_mcp::run(+ if let Some(client) = install_hooks::mcp_client_for_agent(agent) {+ // The sentinel is version-keyed, so this whole step re-runs on every+ // upgrade. install-mcp replaces the `ai-memory` entry wholesale, so a+ // plain re-run would overwrite a session-aware Claude Code bridge the+ // user installed with `install-mcp --session-aware` back to static HTTP,+ // silently disabling per_session for their MCP calls. Preserve it.+ if install_mcp::existing_entry_is_session_aware(+ client,+ overrides.mcp_config_file.as_deref(),+ "ai-memory",+ ) {+ eprintln!(+ "ai-memory: keeping the existing session-aware {} MCP bridge; not \+ overwriting it with the static HTTP registration.",+ harness.as_str()+ );+ } else if let Err(error) = install_mcp::run(config,InstallMcpArgs {client,@@ -144,14 +159,14 @@ pub(crate) fn ensure_wired_with(session_aware: false,flavor: None,},- )- {- eprintln!(- "ai-memory: could not auto-install the {} MCP server ({error:#}); continuing \- launch. Wire it manually with `ai-memory install-mcp --client {} --apply`.",- harness.as_str(),- agent.kind().as_str()- );+ ) {+ eprintln!(+ "ai-memory: could not auto-install the {} MCP server ({error:#}); continuing \+ launch. Wire it manually with `ai-memory install-mcp --client {} --apply`.",+ harness.as_str(),+ agent.kind().as_str()+ );+ }}// Record the attempt even on partial failure: re-applying an idempotent@@ -297,6 +312,59 @@ mod tests {);}+ /// Auto-wire must not downgrade a deliberately-installed session-aware+ /// bridge to static HTTP. The sentinel is version-keyed, so this step+ /// re-runs on every upgrade; without the guard that re-run rewrites the+ /// Claude Code MCP entry wholesale, silently disabling the per_session+ /// isolation the user opted into with `install-mcp --session-aware`.+ #[test]+ fn wiring_preserves_an_existing_session_aware_bridge() {+ let home = tempfile::tempdir().unwrap();+ let data = tempfile::tempdir().unwrap();+ let settings = data.path().join("claude-settings.json");+ std::fs::write(&settings, "{}").unwrap();+ let mcp = data.path().join("claude.json");+ let bridge = r#"{+ "mcpServers": {+ "ai-memory": {+ "type": "stdio",+ "command": "ai-memory",+ "args": ["mcp-bridge", "--server-url", "http://127.0.0.1:49374/mcp"]+ }+ }+}"#;+ std::fs::write(&mcp, bridge).unwrap();++ let config = test_config(home.path(), data.path());+ let overrides = WireOverrides {+ hooks_dir: Some(repo_hooks()),+ hooks_config_file: Some(settings.clone()),+ mcp_config_file: Some(mcp.clone()),+ };+ ensure_wired_with(&config, ManagedHarness::Claude, &overrides);++ let mcp_json = std::fs::read_to_string(&mcp).unwrap();+ let entry: serde_json::Value = serde_json::from_str(&mcp_json).unwrap();+ let server = &entry["mcpServers"]["ai-memory"];+ assert_eq!(+ server["type"].as_str(),+ Some("stdio"),+ "auto-wire must keep the session-aware bridge, not downgrade it to http: {mcp_json}"+ );+ assert!(+ server["args"]+ .as_array()+ .is_some_and(|args| args.iter().any(|arg| arg == "mcp-bridge")),+ "the preserved entry must still be the mcp-bridge: {mcp_json}"+ );+ // The hooks still install, and the attempt is still recorded, so a plain+ // re-launch stays gated.+ assert!(+ sentinel_path(&config.data_dir, AgentChoice::ClaudeCode).exists(),+ "the attempt must be recorded even when the MCP bridge is preserved"+ );+ }+/// A harness with no installer support (Crush) is skipped before anything is/// written — no config touched, no sentinel churn.#[test]