Skip to content

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

Rust

fix(install-mcp): name the install's data dir in bridge entries

Felipe Neves Ricardo5698e8d3f9ee
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ec3ddd56..174b7980 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,16 @@ version in [`docs/changelog/`](docs/changelog/):
## [Unreleased]
+### Fixed
+- Named the install's data dir in the `mcp-bridge` entries `install-mcp`
+ writes for Claude Code and the session-less stdio bridge when the install
+ was given one (`--data-dir`, `AI_MEMORY_DATA_DIR` or `data_dir` in the
+ config), as Muse's entry and the install's hooks already did. The bridge
+ read the default data dir's config and token instead, so on a host whose
+ server uses the default data dir it authenticated with the server's root
+ bearer.
+ ([#1489](https://github.com/akitaonrails/ai-memory/issues/1489))
+
## [3.1.2] - 2026-10-20
### Fixed
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 07528099..c6a0d835 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -3369,9 +3369,10 @@ pub struct InstallMcpArgs {
/// in `[auth].bearer_token_file`.
#[arg(skip)]
pub stdio_bridge: bool,
- /// The data dir a bridge entry passes as `--data-dir`, for a client that
- /// starts its MCP servers with a cleared environment (Muse Code), where
- /// the bridge could not otherwise find this install's config and token.
+ /// The data dir a bridge entry passes as `--data-dir`: always for a client
+ /// that starts its MCP servers with a cleared environment (Muse Code), and
+ /// for any other bridge entry when the install was given a data dir, so
+ /// the bridge reads the same config and token as the install's hooks.
/// Set by the installer, never a flag.
#[arg(skip)]
pub bridge_data_dir: Option<std::path::PathBuf>,
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index 6125900b..4f9c2cda 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -123,19 +123,26 @@ pub(crate) fn run_with_opencode_dialect(
auth_token,
..args
};
- // Muse starts stdio servers with a cleared environment (`HOME`, `PATH`
- // and its own `MUSE_SESSION_ID`), so the bridge it launches finds this
- // install's config and token only through an explicit `--data-dir`, as
- // the Muse hooks do. Not from inside the Docker helper, whose data dir is
- // a container path the host-side bridge cannot open.
- if args.client == McpClient::Muse && config.runtime_env.host_cwd().is_none() {
- args.bridge_data_dir = Some(config.data_dir.clone());
- }
if args.auth_token.is_none()
&& let Some(token_file) = token_file
{
route_file_token(&mut args, token_file)?;
}
+ // The bridge loads its config and token from a data dir the way any CLI
+ // call does. Muse starts stdio servers with a cleared environment (`HOME`,
+ // `PATH` and its own `MUSE_SESSION_ID`), so its bridge finds this install
+ // only through an explicit `--data-dir`, as the Muse hooks do. Any other
+ // bridge needs it when this install was given a data dir: the hooks name
+ // that dir, and a bridge without it would read the default one, with its
+ // own config and bearer. Not from inside the Docker helper, whose data dir
+ // is a container path the host-side bridge cannot open.
+ let runs_bridge =
+ (args.client == McpClient::ClaudeCode && args.session_aware) || args.stdio_bridge;
+ if config.runtime_env.host_cwd().is_none()
+ && (args.client == McpClient::Muse || (runs_bridge && config.data_dir_explicit))
+ {
+ args.bridge_data_dir = Some(config.data_dir.clone());
+ }
validate_args(&args)?;
if args.apply {
return apply_to_config_file(&args);
@@ -249,12 +256,27 @@ fn is_bridge_command(command: &str) -> bool {
/// to it verbatim and the client is the one that needs the dialect.
fn session_less_bridge_args(args: &InstallMcpArgs) -> Vec<String> {
let base_url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL);
- vec![
+ let mut argv = vec![
"mcp-bridge".to_owned(),
"--no-session-id".to_owned(),
"--server-url".to_owned(),
flavored_url_for(args, base_url),
- ]
+ ];
+ argv.extend(bridge_data_dir_args(args));
+ argv
+}
+
+/// `--data-dir <dir>` for a bridge entry when [`InstallMcpArgs::bridge_data_dir`]
+/// is set, else nothing.
+fn bridge_data_dir_args(args: &InstallMcpArgs) -> Vec<String> {
+ args.bridge_data_dir
+ .as_ref()
+ .map_or_else(Vec::new, |data_dir| {
+ vec![
+ "--data-dir".to_owned(),
+ data_dir.to_string_lossy().into_owned(),
+ ]
+ })
}
/// The upstream URL of an ai-memory bridge entry: an ai-memory `command` with
@@ -1575,10 +1597,13 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {
if args.session_aware {
entry.insert("type".into(), json!("stdio"));
entry.insert("command".into(), json!(bridge_command()));
- entry.insert(
- "args".into(),
- json!(["mcp-bridge", "--server-url", base_url]),
- );
+ let mut argv = vec![
+ "mcp-bridge".to_owned(),
+ "--server-url".to_owned(),
+ base_url.to_owned(),
+ ];
+ argv.extend(bridge_data_dir_args(args));
+ entry.insert("args".into(), json!(argv));
if let Some(token) = &args.auth_token {
entry.insert("env".into(), json!({"AI_MEMORY_AUTH_TOKEN": token}));
}
@@ -1845,10 +1870,7 @@ fn build_mcp_entry_muse(args: &InstallMcpArgs) -> Result<serde_json::Value> {
json!("--server-url"),
json!(base_url),
];
- if let Some(data_dir) = &args.bridge_data_dir {
- argv.push(json!("--data-dir"));
- argv.push(json!(data_dir.to_string_lossy()));
- }
+ argv.extend(bridge_data_dir_args(args).into_iter().map(|arg| json!(arg)));
entry.insert("args".into(), serde_json::Value::Array(argv));
if let Some(token) = &args.auth_token {
entry.insert("env".into(), json!({"AI_MEMORY_AUTH_TOKEN": token}));
@@ -4296,6 +4318,62 @@ mod tests {
assert!(!text.contains(FILE_TOKEN), "{text}");
}
+ /// Every bridge entry names a data dir the install was given, as the
+ /// install's hooks do, so the bridge reads that install's config and
+ /// bearer rather than the default data dir's. Controls: a default install
+ /// keeps its entries unchanged (only Muse, which clears the environment,
+ /// names the dir regardless), and the Docker helper, whose data dir is a
+ /// container path, names it for no client.
+ #[test]
+ fn bridge_entries_name_a_data_dir_the_install_was_given() {
+ let tmp = tempfile::tempdir().unwrap();
+ let data_dir = tmp.path().join("client-data");
+ let marker = data_dir.to_string_lossy().into_owned();
+ let installed = |config: &Config, label: &str| {
+ let mut bridges = 0;
+ for &client in <McpClient as clap::ValueEnum>::value_variants() {
+ if matches!(client, McpClient::Pi | McpClient::Dsh | McpClient::Zcode) {
+ continue; // no config file, print-only, and HTTP-only
+ }
+ let ext = if matches!(client, McpClient::Codex | McpClient::Grok) {
+ "toml"
+ } else {
+ "json"
+ };
+ let file = tmp.path().join(format!("{label}-{client:?}.{ext}"));
+ apply_with(config, client, &file).unwrap_or_else(|e| panic!("{client:?}: {e:#}"));
+ let text = std::fs::read_to_string(&file).unwrap();
+ if text.contains("mcp-bridge") {
+ bridges += 1;
+ }
+ let names_dir = text.contains("--data-dir") && text.contains(marker.as_str());
+ let expected = match label {
+ "explicit" => text.contains("mcp-bridge"),
+ "default" => client == McpClient::Muse,
+ _ => false,
+ };
+ assert_eq!(names_dir, expected, "{label} {client:?}: {text}");
+ }
+ assert!(
+ bridges > 2,
+ "{label}: too few bridge entries to prove anything"
+ );
+ };
+
+ let mut explicit = file_token_config(&data_dir);
+ explicit.data_dir = data_dir.clone();
+ explicit.data_dir_explicit = true;
+ installed(&explicit, "explicit");
+
+ let mut default = explicit.clone();
+ default.data_dir_explicit = false;
+ installed(&default, "default");
+
+ let mut docker = explicit.clone();
+ docker.runtime_env = crate::config::RuntimeEnv::with_host_cwd_for_tests("/host/repo");
+ installed(&docker, "docker");
+ }
+
#[test]
fn mcp_server_url_defaults_to_configured_server_url() {
let config = Config {
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index d924a019..dd6beccb 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -274,6 +274,17 @@ pub struct FallbackProfile {
pub struct Config {
/// Root data directory holding `wiki/`, `raw/`, `db/`, `models/`, `logs/`.
pub data_dir: PathBuf,
+ /// Whether `--data-dir`, `AI_MEMORY_DATA_DIR` or the config file's
+ /// `data_dir` key chose [`Self::data_dir`], including an explicit value
+ /// equal to the platform default.
+ ///
+ /// Loader provenance, like [`Self::server_url_explicit`]. `install-mcp`
+ /// names the data dir in the bridge entries it writes only when it was
+ /// chosen, so a bridge installed against a non-default data dir reads the
+ /// same config and token as the hooks of that install, while a default
+ /// install keeps resolving its data dir when the bridge starts.
+ #[serde(skip)]
+ pub data_dir_explicit: bool,
/// HTTP bind address used by `ai-memory serve`.
pub bind: String,
/// Idle-time (seconds) before the OS starts probing an accepted `serve`
@@ -1348,6 +1359,7 @@ impl Default for Config {
fn default() -> Self {
Self {
data_dir: default_data_dir(),
+ data_dir_explicit: false,
bind: DEFAULT_BIND.into(),
tcp_keepalive_secs: DEFAULT_TCP_KEEPALIVE_SECS,
server_url: DEFAULT_SERVER_URL.into(),
@@ -2346,6 +2358,14 @@ impl Config {
// so the #103 catch-all guard is not inert there.
config.home_dir = runtime_env.home_dir.as_deref().and_then(normalize_home_dir);
+ // As with `server_url`, the file is asked for the key: a chosen dir
+ // equal to the default still counts as chosen.
+ config.data_dir_explicit = cli_data_dir.is_some()
+ || runtime_env.data_dir.is_some()
+ || (resolved_config_path.exists()
+ && Figment::from(Toml::file(&resolved_config_path))
+ .find_value("data_dir")
+ .is_ok());
// CLI override always wins (figment doesn't see it because clap has
// already parsed the flag into `cli_data_dir`).
if let Some(dir) = cli_data_dir {
@@ -3799,6 +3819,39 @@ mod tests {
assert!(cfg.server_url_configured());
}
+ /// `data_dir_explicit` records whether the flag, the environment or the
+ /// file chose the data dir, never whether it differs from the default.
+ #[test]
+ fn data_dir_explicit_tracks_who_chose_the_data_dir() {
+ let tmp = TempDir::new().unwrap();
+ let config_path = tmp.path().join("config.toml");
+ std::fs::write(&config_path, "bind = \"127.0.0.1:49921\"\n").unwrap();
+ let load = |config_path: &Path, cli: Option<PathBuf>, env: Option<PathBuf>| {
+ Config::load_with_runtime_env(
+ Some(config_path),
+ cli,
+ RuntimeEnv {
+ data_dir: env,
+ ..RuntimeEnv::default()
+ },
+ )
+ .unwrap()
+ };
+
+ assert!(!load(&config_path, None, None).data_dir_explicit);
+ assert!(load(&config_path, Some(tmp.path().to_path_buf()), None).data_dir_explicit);
+ assert!(load(&config_path, None, Some(tmp.path().to_path_buf())).data_dir_explicit);
+
+ // The file's key counts even when it names the default dir itself.
+ let from_file = tmp.path().join("from-file.toml");
+ std::fs::write(
+ &from_file,
+ format!("data_dir = {:?}\n", default_data_dir().to_string_lossy()),
+ )
+ .unwrap();
+ assert!(load(&from_file, None, None).data_dir_explicit);
+ }
+
/// A bind that maps onto the default URL (an unspecified address on the
/// default port, as containers bind) is not a derivation.
#[test]
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index 8737f4ff..d659e295 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -25,7 +25,11 @@ Warp, Cline, Kilo Code, Goose, Qwen Code and OpenHuman have no
> the token file at launch and forwards no session id, so the client passes
> `workspace` and `project` like any static client. Stdio entries name the
> `ai-memory` binary by its absolute path, so the client does not need it on
-> its `PATH`; the Docker wrapper keeps the bare `ai-memory`. ZCode keeps
+> its `PATH`; the Docker wrapper keeps the bare `ai-memory`. When the install
+> was given a data dir (`--data-dir`, `AI_MEMORY_DATA_DIR` or `data_dir` in
+> the config), every bridge entry names it with `--data-dir`, as that
+> install's hooks do, so the bridge reads that install's config and token
+> rather than the default data dir's. ZCode keeps
> HTTP entries only and is refused. Passing `--auth-token` explicitly (or
> `AI_MEMORY_AUTH_TOKEN`) keeps the HTTP snippets below, header included.