Skip to content

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

Rust

feat(mcp): add Claude session-aware bridge

AkitaOnRailse3c3314e1334
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6bfee5a0..6c716345 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- `install-mcp --client claude-code --session-aware` now registers an
+ ai-memory-owned stdio bridge that forwards Claude Code's
+ `CLAUDE_CODE_SESSION_ID` as `X-Memory-Actor-Session-Id` on every upstream
+ HTTP MCP request. This makes `[auto_scope] mode = "per_session"` effective
+ for concurrent Claude Code sessions against local or remote servers while
+ leaving the existing static HTTP registration as the default. The bridge
+ preserves bearer auth, stateless/stateful HTTP compatibility, and uninstall
+ ownership; both Docker wrappers forward the Claude session variable into
+ the helper container. (#244)
- `GET /admin/open-sessions` lists open (not yet ended) sessions for one
workspace/project/agent, newest first (`all=true` returns every match).
`ai-memory finalize-session` now uses this endpoint instead of opening
diff --git a/Cargo.lock b/Cargo.lock
index b3eb9c0c..c920850a 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -52,7 +52,7 @@ dependencies = [
"flate2",
"fs2",
"jiff",
- "reqwest",
+ "reqwest 0.12.28",
"rmcp",
"secrecy",
"serde",
@@ -163,7 +163,7 @@ dependencies = [
"base64",
"jiff",
"regex",
- "reqwest",
+ "reqwest 0.12.28",
"schemars",
"secrecy",
"serde",
@@ -270,7 +270,7 @@ dependencies = [
"jiff",
"notify",
"notify-debouncer-full",
- "reqwest",
+ "reqwest 0.12.28",
"serde",
"serde_json",
"serde_yaml",
@@ -2307,11 +2307,45 @@ dependencies = [
"url",
"wasm-bindgen",
"wasm-bindgen-futures",
- "wasm-streams",
+ "wasm-streams 0.4.2",
"web-sys",
"webpki-roots",
]
+[[package]]
+name = "reqwest"
+version = "0.13.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "219c5811de6525e5416c7d5d53bb656d3afdbc6c5af816e0802bcfa42dbdc1c3"
+dependencies = [
+ "base64",
+ "bytes",
+ "futures-core",
+ "futures-util",
+ "http",
+ "http-body",
+ "http-body-util",
+ "hyper",
+ "hyper-util",
+ "js-sys",
+ "log",
+ "percent-encoding",
+ "pin-project-lite",
+ "serde",
+ "serde_json",
+ "sync_wrapper",
+ "tokio",
+ "tokio-util",
+ "tower",
+ "tower-http",
+ "tower-service",
+ "url",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "wasm-streams 0.5.0",
+ "web-sys",
+]
+
[[package]]
name = "ring"
version = "0.17.14"
@@ -2343,6 +2377,7 @@ dependencies = [
"pastey",
"pin-project-lite",
"rand 0.10.1",
+ "reqwest 0.13.4",
"rmcp-macros",
"schemars",
"serde",
@@ -3380,6 +3415,19 @@ dependencies = [
"web-sys",
]
+[[package]]
+name = "wasm-streams"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"
+dependencies = [
+ "futures-util",
+ "js-sys",
+ "wasm-bindgen",
+ "wasm-bindgen-futures",
+ "web-sys",
+]
+
[[package]]
name = "wasmparser"
version = "0.244.0"
diff --git a/README.md b/README.md
index 5978a84b..4288a012 100644
--- a/README.md
+++ b/README.md
@@ -22,7 +22,7 @@
| macOS | Supported | Workspace tests run in CI; tagged releases publish native `ai-memory-macos-aarch64.tar.gz` and `ai-memory-macos-x86_64.tar.gz` binaries. The native binary is the recommended path on Apple Silicon. See [`docs/macos.md`](docs/macos.md). |
| Windows via WSL2 | Supported | Use the Linux install path inside WSL2 when the agent runs there. |
| Native Windows | Experimental | Tagged releases publish `ai-memory-windows-x86_64.zip` with `ai-memory.exe`; Docker Desktop wrapper and source builds are also available. Local supported profiles default to host-native hook commands; Claude Code may use its Windows exec form, while other agents use native single command strings matching their hook schema. PowerShell/Git Bash scripts are compatibility fallbacks. See [`docs/windows.md`](docs/windows.md). |
-| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). |
+| Claude Code | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. `install-mcp --session-aware` optionally enables per-session auto-scope isolation through a local stdio bridge. Optionally captures the assistant's final turn on `Stop` when installed with `--capture-assistant` and the server enables `capture_assistant` (double opt-in, off by default). |
| Codex | Supported | MCP config + lifecycle hooks; native commands enforce capture exclusions. No automatic true session-end hook, so run `ai-memory finalize-session` when you need a final summary/handoff. |
| Devin CLI | Supported | MCP config + lifecycle hooks. Hooks use Devin's `PostCompaction` event, inject handoffs via `hookSpecificOutput.additionalContext`, and omit subagent events because Devin does not expose them. |
| OpenCode | Supported | Remote MCP config + generated TypeScript plugin; generated plugin enforces capture exclusions. |
@@ -122,7 +122,8 @@ priors are at the [bottom](#influences-and-prior-art).
Server runs local (loopback) OR on a homelab box (LAN/VPN/cloud)
with bearer-token auth. Shared servers can opt into
[`[auto_scope]` modes](docs/auto-scope.md) for per-user or
- session-aware current-project routing.
+ session-aware current-project routing; Claude Code has a built-in opt-in
+ bridge via `install-mcp --session-aware`.
- **Thin-client CLI.** `ai-memory status`, `bootstrap`, `checkpoints`,
`restore-page`, `purge-project`, `rename-project`, `move-project`,
`audit-contamination`, `lint`, `curator`, `auto-improve`,
@@ -339,6 +340,26 @@ open in this project will see a handoff with where you left off.
On macOS, the native release binary is also supported and recommended when you
do not need Docker; see [`docs/macos.md`](docs/macos.md).
+If two Claude Code sessions use the same server concurrently, enable
+per-session routing on the server and replace only the `ai-memory` MCP entry
+with the optional bridge:
+
+```toml
+# <ai-memory data dir>/config.toml
+[auto_scope]
+mode = "per_session"
+```
+
+```bash
+ai-memory install-mcp --client claude-code --session-aware --apply
+```
+
+The bridge still connects to the configured local or remote HTTP server and
+forwards its bearer token, but also attaches Claude's lifecycle session id to
+every MCP request. Existing static HTTP installs remain the default. See
+[`docs/auto-scope.md`](docs/auto-scope.md) for Claude's `/clear` and
+implicit-resume limitations.
+
The `install-mcp` / `install-hooks` commands use
`AI_MEMORY_SERVER_URL` / `AI_MEMORY_AUTH_TOKEN` when set; otherwise
they default to `http://127.0.0.1:49374` (matching the server above)
diff --git a/bin/ai-memory b/bin/ai-memory
index 4deecc26..94511ff4 100755
--- a/bin/ai-memory
+++ b/bin/ai-memory
@@ -334,6 +334,7 @@ for var in \
AI_MEMORY_HOOK_PLATFORM \
AI_MEMORY_HOOKS_HOST_ROOT \
CLAUDE_CONFIG_DIR \
+ CLAUDE_CODE_SESSION_ID \
ANTHROPIC_API_KEY \
OPENAI_API_KEY \
COPILOT_GITHUB_TOKEN \
diff --git a/bin/ai-memory.ps1 b/bin/ai-memory.ps1
index 3dc5f83f..57579642 100644
--- a/bin/ai-memory.ps1
+++ b/bin/ai-memory.ps1
@@ -80,6 +80,7 @@ foreach ($Name in @(
"AI_MEMORY_EMBEDDING_BASE_URL",
"AI_MEMORY_EMBEDDING_DIM",
"AI_MEMORY_ALLOWED_HOSTS",
+ "CLAUDE_CODE_SESSION_ID",
"ANTHROPIC_API_KEY",
"OPENAI_API_KEY",
"VOYAGE_API_KEY",
diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.toml
index 41b1498e..efb9bee0 100644
--- a/crates/ai-memory-cli/Cargo.toml
+++ b/crates/ai-memory-cli/Cargo.toml
@@ -34,7 +34,7 @@ dirs.workspace = true
figment.workspace = true
flate2.workspace = true
fs2.workspace = true
-rmcp.workspace = true
+rmcp = { workspace = true, features = ["client", "transport-streamable-http-client-reqwest"] }
serde.workspace = true
serde_json.workspace = true
toml_edit.workspace = true
diff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rs
index 81f6998b..d4d9c8b7 100644
--- a/crates/ai-memory-cli/src/cli.rs
+++ b/crates/ai-memory-cli/src/cli.rs
@@ -82,6 +82,9 @@ pub enum Command {
/// Current values are listed under `--client`; see docs/mcp-install.md
/// for the full guide.
InstallMcp(InstallMcpArgs),
+ /// Internal stdio-to-HTTP MCP bridge for session-aware Claude Code installs.
+ #[command(hide = true)]
+ McpBridge(McpBridgeArgs),
/// Stage + commit the wiki tree under git.
Commit(CommitArgs),
/// List recent wiki git checkpoints for recovery.
@@ -1475,6 +1478,19 @@ pub struct InstallMcpArgs {
/// absent (e.g. `~/.claude.json` for Claude Code).
#[arg(long)]
pub config_file: Option<PathBuf>,
+ /// For Claude Code, register an ai-memory stdio bridge that forwards the
+ /// current lifecycle session id to the HTTP server. This enables
+ /// `[auto_scope] mode = "per_session"` for concurrent Claude Code sessions.
+ #[arg(long)]
+ pub session_aware: bool,
+}
+
+/// Arguments for the internal Claude Code session-aware MCP bridge.
+#[derive(Debug, Clone, Args)]
+pub struct McpBridgeArgs {
+ /// Remote ai-memory base URL or full `/mcp` endpoint.
+ #[arg(long)]
+ pub server_url: Option<String>,
}
/// Transport for the MCP server.
@@ -1592,6 +1608,26 @@ mod tests {
use super::*;
use clap::Parser;
+ #[test]
+ fn claude_session_aware_mcp_flag_parses() {
+ let cli = Cli::try_parse_from([
+ "ai-memory",
+ "install-mcp",
+ "--client",
+ "claude-code",
+ "--session-aware",
+ "--apply",
+ ])
+ .unwrap();
+
+ let Command::InstallMcp(args) = cli.command else {
+ panic!("expected install-mcp command");
+ };
+ assert!(args.session_aware);
+ assert!(args.apply);
+ assert!(matches!(args.client, McpClient::ClaudeCode));
+ }
+
#[test]
fn pi_and_omp_mcp_clients_parse_to_distinct_variants() {
for (alias, expected_pi) in [("pi", true), ("omp", false), ("oh-my-pi", false)] {
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index 994e66b5..0553a705 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -52,6 +52,7 @@ pub fn run(config: &Config, args: InstallMcpArgs) -> Result<()> {
auth_token: args.auth_token.or_else(|| config.auth.bearer_token.clone()),
..args
};
+ validate_args(&args)?;
if args.apply {
return apply_to_config_file(&args);
}
@@ -92,7 +93,7 @@ fn effective_mcp_server_url(config: &Config, args: &InstallMcpArgs) -> String {
DEFAULT_MCP_URL.to_string()
}
-fn mcp_server_url_from_base(server_url: &str) -> String {
+pub(crate) fn mcp_server_url_from_base(server_url: &str) -> String {
let trimmed = server_url.trim().trim_end_matches('/');
if trimmed.ends_with("/mcp") {
trimmed.to_string()
@@ -101,6 +102,13 @@ fn mcp_server_url_from_base(server_url: &str) -> String {
}
}
+fn validate_args(args: &InstallMcpArgs) -> Result<()> {
+ if args.session_aware && !matches!(args.client, McpClient::ClaudeCode) {
+ bail!("--session-aware is supported only for --client claude-code");
+ }
+ Ok(())
+}
+
/// Default MCP config-file path for a client (ignores any
/// `--config-file` override). Shared by install and uninstall.
///
@@ -361,6 +369,7 @@ fn json_mcp_location(client: McpClient) -> Option<JsonMcpLocation> {
}
fn build_json_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {
+ validate_args(args)?;
match args.client {
McpClient::OpenCode => build_mcp_entry_opencode(args),
McpClient::Openclaw => build_mcp_entry_openclaw(args),
@@ -468,10 +477,22 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {
let mut entry = serde_json::Map::new();
match args.client {
McpClient::ClaudeCode => {
- entry.insert("type".into(), json!("http"));
- entry.insert("url".into(), json!(server_url));
- if let Some(b) = &bearer {
- entry.insert("headers".into(), json!({"Authorization": b}));
+ if args.session_aware {
+ entry.insert("type".into(), json!("stdio"));
+ entry.insert("command".into(), json!("ai-memory"));
+ entry.insert(
+ "args".into(),
+ json!(["mcp-bridge", "--server-url", server_url]),
+ );
+ if let Some(token) = &args.auth_token {
+ entry.insert("env".into(), json!({"AI_MEMORY_AUTH_TOKEN": token}));
+ }
+ } else {
+ entry.insert("type".into(), json!("http"));
+ entry.insert("url".into(), json!(server_url));
+ if let Some(b) = &bearer {
+ entry.insert("headers".into(), json!({"Authorization": b}));
+ }
}
}
McpClient::ClaudeDesktop => {
@@ -716,7 +737,18 @@ fn upsert_toml_mcp_server(doc: &mut toml_edit::DocumentMut, name: &str, server:
fn render_claude_code(args: &InstallMcpArgs, config_path: &Path) -> Result<String> {
let bearer = bearer_header_value(args.auth_token.as_deref());
- let cli_line = if let Some(b) = &bearer {
+ let cli_line = if args.session_aware {
+ let env = args
+ .auth_token
+ .as_deref()
+ .map(|token| format!(" --env \"AI_MEMORY_AUTH_TOKEN={token}\""))
+ .unwrap_or_default();
+ format!(
+ "claude mcp add --transport stdio{env} {name} -- \\\n ai-memory mcp-bridge --server-url {url}",
+ name = args.name,
+ url = args.server_url.as_deref().unwrap_or(DEFAULT_MCP_URL),
+ )
+ } else if let Some(b) = &bearer {
format!(
"claude mcp add --transport http {name} {url} \\\n --header \"Authorization: {b}\"",
name = args.name,
@@ -1012,6 +1044,7 @@ mod tests {
auth_token: None,
apply: false,
config_file: None,
+ session_aware: false,
}
}
@@ -1023,6 +1056,7 @@ mod tests {
auth_token: Some("test-token-deadbeef".into()),
apply: false,
config_file: None,
+ session_aware: false,
}
}
@@ -1156,6 +1190,71 @@ mod tests {
);
}
+ #[test]
+ fn claude_code_session_aware_entry_uses_owned_stdio_bridge() {
+ let mut args = args_with_token(McpClient::ClaudeCode);
+ args.server_url = Some("https://memory.example/mcp".into());
+ args.session_aware = true;
+
+ let entry = build_mcp_entry(&args).unwrap();
+
+ assert_eq!(entry["type"], "stdio");
+ assert_eq!(entry["command"], "ai-memory");
+ assert_eq!(
+ entry["args"],
+ json!(["mcp-bridge", "--server-url", "https://memory.example/mcp"])
+ );
+ assert_eq!(entry["env"]["AI_MEMORY_AUTH_TOKEN"], "test-token-deadbeef");
+ assert!(entry.get("url").is_none());
+ assert!(entry.get("headers").is_none());
+
+ let rendered = render_claude_code(&args, Path::new("/home/alice/.claude.json")).unwrap();
+ assert!(rendered.contains("claude mcp add --transport stdio"));
+ assert!(rendered.contains("ai-memory mcp-bridge --server-url"));
+ }
+
+ #[test]
+ fn claude_code_session_aware_apply_is_idempotent() {
+ let tmp = tempfile::TempDir::new().unwrap();
+ let config_file = tmp.path().join(".claude.json");
+ let mut args = args_with_token(McpClient::ClaudeCode);
+ args.server_url = Some("http://192.168.0.90:49374/mcp".into());
+ args.config_file = Some(config_file.clone());
+ args.session_aware = true;
+ args.apply = true;
+
+ apply_to_config_file(&args).unwrap();
+ let first = fs::read_to_string(&config_file).unwrap();
+ apply_to_config_file(&args).unwrap();
+ let second = fs::read_to_string(&config_file).unwrap();
+
+ assert_eq!(first, second);
+ let value: serde_json::Value = serde_json::from_str(&second).unwrap();
+ assert_eq!(
+ value["mcpServers"]["ai-memory"]["args"],
+ json!([
+ "mcp-bridge",
+ "--server-url",
+ "http://192.168.0.90:49374/mcp"
+ ])
+ );
+ }
+
+ #[test]
+ fn session_aware_rejects_non_claude_clients() {
+ let mut args = args_for(McpClient::Codex);
+ args.session_aware = true;
+
+ let error = build_json_mcp_entry(&args).unwrap_err();
+
+ assert!(
+ error
+ .to_string()
+ .contains("supported only for --client claude-code"),
+ "{error:#}"
+ );
+ }
+
fn render_with_token(client: McpClient) -> String {
let args = args_with_token(client);
match args.client {
diff --git a/crates/ai-memory-cli/src/commands/mcp_bridge.rs b/crates/ai-memory-cli/src/commands/mcp_bridge.rs
new file mode 100644
index 00000000..846780c9
--- /dev/null
+++ b/crates/ai-memory-cli/src/commands/mcp_bridge.rs
@@ -0,0 +1,302 @@
+//! Session-aware Claude Code stdio bridge for a remote ai-memory MCP server.
+
+use std::collections::HashMap;
+
+use anyhow::{Context, Result};
+use reqwest::header::{HeaderName, HeaderValue};
+use rmcp::model::{
+ CallToolRequestParams, CallToolResult, ListToolsResult, PaginatedRequestParams, ServerInfo,
+};
+use rmcp::service::{RequestContext, RoleClient, RoleServer, ServiceError};
+use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;
+use rmcp::transport::{StreamableHttpClientTransport, stdio};
+use rmcp::{ErrorData as McpError, Peer, ServerHandler, ServiceExt};
+
+use crate::cli::McpBridgeArgs;
+use crate::commands::install_mcp::mcp_server_url_from_base;
+use crate::config::Config;
+
+const ACTOR_SESSION_HEADER: HeaderName = HeaderName::from_static("x-memory-actor-session-id");
+
+#[derive(Clone)]
+struct SessionAwareBridge {
+ upstream: Peer<RoleClient>,
+ server_info: ServerInfo,
+}
+
+impl ServerHandler for SessionAwareBridge {
+ fn get_info(&self) -> ServerInfo {
+ self.server_info.clone()
+ }
+
+ async fn list_tools(
+ &self,
+ request: Option<PaginatedRequestParams>,
+ _context: RequestContext<RoleServer>,
+ ) -> Result<ListToolsResult, McpError> {
+ self.upstream
+ .list_tools(request)
+ .await
+ .map_err(upstream_error)
+ }
+
+ async fn call_tool(
+ &self,
+ request: CallToolRequestParams,
+ _context: RequestContext<RoleServer>,
+ ) -> Result<CallToolResult, McpError> {
+ self.upstream
+ .call_tool(request)
+ .await
+ .map_err(upstream_error)
+ }
+}
+
+fn upstream_error(error: ServiceError) -> McpError {
+ match error {
+ ServiceError::McpError(error) => error,
+ other => McpError::internal_error(format!("upstream MCP request failed: {other}"), None),
+ }
+}
+
+fn upstream_config(
+ server_url: &str,
+ session_id: &str,
+ auth_token: Option<&str>,
+) -> Result<StreamableHttpClientTransportConfig> {
+ let mut headers = HashMap::new();
+ headers.insert(
+ ACTOR_SESSION_HEADER,
+ HeaderValue::from_str(session_id).context(
+ "CLAUDE_CODE_SESSION_ID contains characters that are invalid in an HTTP header",
+ )?,
+ );
+
+ let mut config =
+ StreamableHttpClientTransportConfig::with_uri(server_url).custom_headers(headers);
+ if let Some(token) = auth_token {
+ config = config.auth_header(token);
+ }
+ Ok(config)
+}
+
+/// Run the Claude Code session-aware stdio bridge.
+///
+/// # Errors
+/// Returns an error when Claude did not provide a lifecycle session id, the
+/// upstream HTTP MCP server cannot initialize, or either transport fails.
+pub async fn run(config: &Config, args: McpBridgeArgs) -> Result<()> {
+ let session_id = config.runtime_env.claude_code_session_id().context(
+ "CLAUDE_CODE_SESSION_ID is missing; this bridge must be launched by Claude Code as an stdio MCP server",
+ )?;
+ let server_url = args
+ .server_url
+ .as_deref()
+ .map(mcp_server_url_from_base)
+ .unwrap_or_else(|| mcp_server_url_from_base(&config.server_url));
+ let transport = StreamableHttpClientTransport::from_config(upstream_config(
+ &server_url,
+ session_id,
+ config.auth.bearer_token.as_deref(),
+ )?);
+
+ let mut upstream = ()
+ .serve(transport)
+ .await
+ .with_context(|| format!("connecting session-aware bridge to {server_url}"))?;
+ let server_info = upstream
+ .peer_info()
+ .cloned()
+ .context("upstream MCP server completed initialization without server info")?;
+ let bridge = SessionAwareBridge {
+ upstream: upstream.peer().clone(),
+ server_info,
+ };
+ let downstream = bridge
+ .serve(stdio())
+ .await
+ .context("starting session-aware stdio MCP bridge")?;
+
+ downstream
+ .waiting()
+ .await
+ .context("waiting for Claude Code stdio MCP transport")?;
+ upstream
+ .close()
+ .await
+ .context("closing upstream HTTP MCP transport")?;
+ Ok(())
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::{Arc, Mutex};
+
+ use axum::Router;
+ use rmcp::model::{Content, ServerCapabilities, Tool};
+ use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
+ use rmcp::transport::streamable_http_server::{
+ StreamableHttpServerConfig, StreamableHttpService,
+ };
+
+ #[derive(Clone)]
+ struct EchoServer {
+ seen_session: Arc<Mutex<Option<String>>>,
+ }
+
+ impl ServerHandler for EchoServer {
+ fn get_info(&self) -> ServerInfo {
+ ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
+ }
+
+ async fn list_tools(
+ &self,
+ _request: Option<PaginatedRequestParams>,
+ _context: RequestContext<RoleServer>,
+ ) -> Result<ListToolsResult, McpError> {
+ Ok(ListToolsResult {
+ tools: vec![Tool::new(
+ "echo",
+ "Echo through the bridge",
+ Arc::new(Default::default()),
+ )],
+ ..Default::default()
+ })
+ }
+
+ async fn call_tool(
+ &self,
+ request: CallToolRequestParams,
+ context: RequestContext<RoleServer>,
+ ) -> Result<CallToolResult, McpError> {
+ let session = context
+ .extensions
+ .get::<axum::http::request::Parts>()
+ .and_then(|parts| parts.headers.get(&ACTOR_SESSION_HEADER))
+ .and_then(|value| value.to_str().ok())
+ .map(str::to_string);
+ *self.seen_session.lock().unwrap() = session;
+ Ok(CallToolResult::success(vec![Content::text(format!(
+ "echo:{}",
+ request.name
+ ))]))
+ }
+ }
+
+ #[test]
+ fn upstream_config_injects_session_id_and_raw_bearer_token() {
+ let config = upstream_config(
+ "https://memory.example/mcp",
+ "550e8400-e29b-41d4-a716-446655440000",
+ Some("secret-token"),
+ )
+ .unwrap();
+
+ assert_eq!(config.auth_header.as_deref(), Some("secret-token"));
+ assert_eq!(
+ config
+ .custom_headers
+ .get(&ACTOR_SESSION_HEADER)
+ .and_then(|value| value.to_str().ok()),
+ Some("550e8400-e29b-41d4-a716-446655440000")
+ );
+ assert!(config.allow_stateless);
+ assert!(config.reinit_on_expired_session);
+ }
+
+ #[test]
+ fn upstream_config_rejects_an_invalid_header_value() {
+ let error =
+ upstream_config("https://memory.example/mcp", "session\ninjected", None).unwrap_err();
+ assert!(
+ error.to_string().contains("invalid in an HTTP header"),
+ "{error:#}"
+ );
+ }
+
+ #[tokio::test]
+ async fn bridge_fails_closed_without_a_claude_session_id() {
+ let error = run(
+ &Config::default(),
+ McpBridgeArgs {
+ server_url: Some("https://memory.example/mcp".into()),
+ },
+ )
+ .await
+ .unwrap_err();
+
+ assert!(
+ error
+ .to_string()
+ .contains("CLAUDE_CODE_SESSION_ID is missing"),
+ "{error:#}"
+ );
+ }
+
+ async fn assert_bridge_round_trip(stateful: bool) {
+ let seen_session = Arc::new(Mutex::new(None));
+ let echo = EchoServer {
+ seen_session: seen_session.clone(),
+ };
+ let service: StreamableHttpService<EchoServer, LocalSessionManager> =
+ StreamableHttpService::new(
+ move || Ok(echo.clone()),
+ LocalSessionManager::default().into(),
+ StreamableHttpServerConfig::default()
+ .with_stateful_mode(stateful)
+ .with_json_response(!stateful),
+ );
+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
+ let address = listener.local_addr().unwrap();
+ let http_server = tokio::spawn(async move {
+ axum::serve(listener, Router::new().nest_service("/mcp", service))
+ .await
+ .unwrap();
+ });
+
+ let upstream_transport = StreamableHttpClientTransport::from_config(
+ upstream_config(&format!("http://{address}/mcp"), "claude-session-244", None).unwrap(),
+ );
+ let upstream = ().serve(upstream_transport).await.unwrap();
+ let bridge = SessionAwareBridge {
+ upstream: upstream.peer().clone(),
+ server_info: upstream.peer_info().cloned().unwrap(),
+ };
+ let (client_io, server_io) = tokio::io::duplex(64 * 1024);
+ let downstream_server = tokio::spawn(async move { bridge.serve(server_io).await.unwrap() });
+ let downstream_client = ().serve(client_io).await.unwrap();
+ let downstream_server = downstream_server.await.unwrap();
+
+ let tools = downstream_client.list_all_tools().await.unwrap();
+ assert_eq!(tools.len(), 1);
+ assert_eq!(tools[0].name, "echo");
+ let result = downstream_client
+ .call_tool(CallToolRequestParams::new("echo"))
+ .await
+ .unwrap();
+ assert_eq!(
+ result
+ .content
+ .first()
+ .and_then(|content| content.as_text())
+ .map(|text| text.text.as_str()),
+ Some("echo:echo")
+ );
+ assert_eq!(
+ seen_session.lock().unwrap().as_deref(),
+ Some("claude-session-244")
+ );
+
+ downstream_client.cancel().await.unwrap();
+ downstream_server.cancel().await.unwrap();
+ upstream.cancel().await.unwrap();
+ http_server.abort();
+ }
+
+ #[tokio::test]
+ async fn stdio_bridge_forwards_tools_and_session_header_in_both_http_modes() {
+ assert_bridge_round_trip(false).await;
+ assert_bridge_round_trip(true).await;
+ }
+}
diff --git a/crates/ai-memory-cli/src/commands/mod.rs b/crates/ai-memory-cli/src/commands/mod.rs
index cb1249f2..6344f9e4 100644
--- a/crates/ai-memory-cli/src/commands/mod.rs
+++ b/crates/ai-memory-cli/src/commands/mod.rs
@@ -32,6 +32,7 @@ pub mod install_mcp;
pub mod install_skills;
pub mod lint;
pub mod llm_test;
+pub mod mcp_bridge;
pub mod move_project;
pub mod openclaw_plugin;
pub mod path_util;
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index 686ff038..1f0ff407 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -946,10 +946,10 @@ fn mcp_servers_path(client: McpClient) -> Option<&'static [&'static str]> {
}
/// True when an MCP server entry is ai-memory's: its url/httpUrl/serverUrl
-/// equals the endpoint, or it is a `mcp-remote` stdio shim whose args contain
-/// the endpoint. The key/name alone is intentionally not enough: users may
-/// have unrelated entries named `ai-memory`, and uninstall must not remove
-/// them unless the endpoint also matches.
+/// equals the endpoint, or it is an ai-memory-owned / `mcp-remote` stdio
+/// bridge whose args contain the endpoint. The key/name alone is intentionally
+/// not enough: users may have unrelated entries named `ai-memory`, and
+/// uninstall must not remove them unless the endpoint also matches.
fn mcp_entry_is_ours(key: &str, entry: &serde_json::Value, name: Option<&str>, url: &str) -> bool {
if name.is_some_and(|name| key != name) {
return false;
@@ -961,8 +961,10 @@ fn mcp_entry_is_ours(key: &str, entry: &serde_json::Value, name: Option<&str>, u
}
if let Some(args) = entry.get("args").and_then(|a| a.as_array()) {
let has_remote = args.iter().any(|a| a.as_str() == Some("mcp-remote"));
+ let has_session_bridge = entry.get("command").and_then(|v| v.as_str()) == Some("ai-memory")
+ && args.iter().any(|a| a.as_str() == Some("mcp-bridge"));
let has_url = args.iter().any(|a| a.as_str() == Some(url));
- if has_remote && has_url {
+ if (has_remote || has_session_bridge) && has_url {
return true;
}
}
@@ -1714,6 +1716,23 @@ mod tests {
assert_eq!(removed, vec!["weird-name".to_string()]);
}
+ #[test]
+ fn strip_mcp_claude_code_session_aware_bridge() {
+ let content = r#"{"mcpServers":{"ai-memory":{"type":"stdio","command":"ai-memory","args":["mcp-bridge","--server-url","http://127.0.0.1:49374/mcp"]},"other":{"command":"other","args":["mcp-bridge","--server-url","http://127.0.0.1:49374/mcp"]}}}"#;
+ let (out, removed) = strip_mcp_json(
+ content,
+ McpClient::ClaudeCode,
+ None,
+ "http://127.0.0.1:49374/mcp",
+ )
+ .unwrap();
+
+ assert_eq!(removed, vec!["ai-memory".to_string()]);
+ let value: serde_json::Value = serde_json::from_str(&out).unwrap();
+ assert!(value["mcpServers"].get("ai-memory").is_none());
+ assert!(value["mcpServers"].get("other").is_some());
+ }
+
#[test]
fn strip_mcp_openclaw_nested_servers() {
let content = r#"{"mcp":{"servers":{"ai-memory":{"url":"http://127.0.0.1:49374/mcp"}}}}"#;
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index a1a67920..b0b96f44 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -198,6 +198,7 @@ pub struct RuntimeEnv {
server_url: Option<String>,
auth_token: Option<String>,
host_cwd: Option<String>,
+ claude_code_session_id: Option<String>,
anthropic_api_key: Option<SecretString>,
anthropic_oauth_token: Option<SecretString>,
openai_api_key: Option<SecretString>,
@@ -220,6 +221,7 @@ impl RuntimeEnv {
server_url: env_string("AI_MEMORY_SERVER_URL"),
auth_token: env_string("AI_MEMORY_AUTH_TOKEN"),
host_cwd: env_string("AI_MEMORY_HOST_CWD"),
+ claude_code_session_id: env_string("CLAUDE_CODE_SESSION_ID"),
anthropic_api_key: env_secret("ANTHROPIC_API_KEY"),
// CLAUDE_CODE_OAUTH_TOKEN is what `claude setup-token` writes;
// ANTHROPIC_OAUTH_TOKEN is our canonical name — accept both.
@@ -248,6 +250,12 @@ impl RuntimeEnv {
self.host_cwd.as_deref()
}
+ /// Claude Code lifecycle session id inherited by an stdio MCP subprocess.
+ #[must_use]
+ pub fn claude_code_session_id(&self) -> Option<&str> {
+ self.claude_code_session_id.as_deref()
+ }
+
#[cfg(test)]
pub fn with_host_cwd_for_tests(host_cwd: impl Into<String>) -> Self {
Self {
diff --git a/crates/ai-memory-cli/src/main.rs b/crates/ai-memory-cli/src/main.rs
index 45f3bb7c..36792a72 100644
--- a/crates/ai-memory-cli/src/main.rs
+++ b/crates/ai-memory-cli/src/main.rs
@@ -99,6 +99,7 @@ async fn main() -> Result<()> {
// `HookDrain` is handled in the fast-path above (before config/tracing).
Command::HookDrain(_args) => commands::hook::run_drain(Some(config.data_dir.clone())).await,
Command::InstallMcp(args) => commands::install_mcp::run(&config, args),
+ Command::McpBridge(args) => commands::mcp_bridge::run(&config, args).await,
Command::Commit(args) => commands::commit::run(&config, args).await,
Command::Checkpoints(args) => commands::checkpoints::run(&config, args).await,
Command::RestorePage(args) => commands::restore_page::run(&config, args).await,
diff --git a/crates/ai-memory-cli/tests/packaging.rs b/crates/ai-memory-cli/tests/packaging.rs
index d0f94359..7a471339 100644
--- a/crates/ai-memory-cli/tests/packaging.rs
+++ b/crates/ai-memory-cli/tests/packaging.rs
@@ -300,6 +300,10 @@ fn docker_wrappers_keep_stdin_attached_independently_of_tty_allocation() {
!posix.contains("TTY_ARGS=(-it)"),
"combined flags can drop stdin when only stdout is redirected"
);
+ assert!(
+ posix.contains("CLAUDE_CODE_SESSION_ID"),
+ "POSIX wrapper must forward Claude's session id into the bridge container"
+ );
let powershell = read_repo("bin/ai-memory.ps1");
assert!(
@@ -314,6 +318,10 @@ fn docker_wrappers_keep_stdin_attached_independently_of_tty_allocation() {
!powershell.contains("$DockerArgs += \"-it\""),
"PowerShell must not couple stdin attachment to TTY allocation"
);
+ assert!(
+ powershell.contains("\"CLAUDE_CODE_SESSION_ID\""),
+ "PowerShell wrapper must forward Claude's session id into the bridge container"
+ );
}
#[cfg(unix)]
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 121fe186..089747bb 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -328,6 +328,15 @@ MCP parameter aliases are intentionally sparse: `memory_query.query` accepts
`q|search`, and limit fields accept `n` / `top_k` where shipped. Project and
cwd parameters use their canonical names.
+Claude Code's optional session-aware MCP registration is a transport adapter,
+not a second tool implementation. `ai-memory mcp-bridge` serves the upstream
+tool catalogue over local stdio, delegates tool calls to the configured HTTP
+server through rmcp's client transport, and injects the inherited
+`CLAUDE_CODE_SESSION_ID` as `X-Memory-Actor-Session-Id`. The server therefore
+keeps the same auth, scope resolver, and tool handlers as direct HTTP clients.
+The adapter fails closed without a Claude session id and is installed only by
+the explicit `install-mcp --client claude-code --session-aware` option.
+
## CLI subcommand surface
```
diff --git a/docs/auto-scope.md b/docs/auto-scope.md
index a6642280..63ab183a 100644
--- a/docs/auto-scope.md
+++ b/docs/auto-scope.md
@@ -108,6 +108,26 @@ MCP client config files can only declare static URL/auth headers. Static
configs cannot inject the current agent-run session id into every tool
call.
+Claude Code can opt into ai-memory's session-aware stdio bridge:
+
+```bash
+ai-memory install-mcp --client claude-code --session-aware --apply
+```
+
+The bridge reads the `CLAUDE_CODE_SESSION_ID` that Claude supplies to its stdio
+MCP subprocess and forwards it as `X-Memory-Actor-Session-Id` while preserving
+the configured remote endpoint and bearer token. Existing Claude Code installs
+stay on the static HTTP transport unless this flag is used.
+
+Claude Code's stdio MCP subprocess keeps the id it received at startup across
+`/clear`, even though subsequent hooks receive the new id. On
+`--continue`/`--resume` without an explicit id, Claude may also give the MCP
+subprocess the startup id rather than the resumed id. Restart Claude Code after
+`/clear` when exact session-key continuity matters, and prefer
+`--resume <session-id>` for explicit resumes. The bridge deliberately fails
+when no `CLAUDE_CODE_SESSION_ID` is available instead of silently degrading to
+the shared single slot.
+
Use `per_session` only when your client or bridge can send the same
opaque session id from the hook payload on each MCP request as
`X-Memory-Actor-Session-Id` (preferred) or `Mcp-Session-Id`. Otherwise
@@ -130,6 +150,8 @@ For built-in installs that use static MCP config, prefer:
concurrent sessions still need explicit `workspace` + `project` args
or a session-aware bridge when the MCP client cannot forward the hook
session id.
+- `per_session` plus Claude Code's `install-mcp --session-aware` bridge when
+ one operator runs concurrent Claude Code sessions in different projects.
## Pairing with multi-user mode
@@ -144,8 +166,8 @@ sessions by the same user are isolated too.
Single-user installs can use `per_session` alone (no `token_pepper`,
no `users` row) only when the client/bridge forwards the session id on
-MCP calls. With the stock static MCP configs, use explicit
-`workspace` + `project` arguments for concurrent windows.
+MCP calls. Claude Code has the opt-in bridge above; with other stock static MCP
+configs, use explicit `workspace` + `project` arguments for concurrent windows.
## Memory footprint
diff --git a/docs/install.md b/docs/install.md
index 286e0fc7..c974de2d 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -68,6 +68,19 @@ ai-memory install-mcp --client claude-code --apply
ai-memory install-hooks --agent claude-code --apply
```
+`--session-aware` is an optional Claude Code MCP mode:
+
+```bash
+ai-memory install-mcp --client claude-code --session-aware --apply
+```
+
+It replaces the static HTTP MCP entry with a local ai-memory stdio bridge that
+still connects to the configured remote server and bearer token, while
+forwarding Claude's lifecycle session id. Pair it with
+`[auto_scope] mode = "per_session"` when the same operator runs concurrent
+Claude Code sessions in different projects. The default static HTTP
+registration remains appropriate for one active project at a time.
+
If `CLAUDE_CONFIG_DIR` is set, the claude-code installers match Claude Code's
own config resolution: `install-mcp` writes the MCP registration to
`$CLAUDE_CONFIG_DIR/.claude.json` (instead of `~/.claude.json`),
@@ -366,6 +379,11 @@ ai-memory install-mcp --client claude-code --apply
ai-memory install-hooks --agent claude-code --apply
```
+For concurrent Claude Code sessions, set `[auto_scope] mode = "per_session"` in
+the server config and add `--session-aware` to the `install-mcp` command. This
+works for local and LAN servers; the generated stdio bridge keeps using
+`AI_MEMORY_SERVER_URL` / `--server-url` and `AI_MEMORY_AUTH_TOKEN`.
+
For a bearer-protected local or LAN server, export the endpoint first. The MCP
URL includes `/mcp`; the hook URL is the bare origin.
diff --git a/docs/mcp-install.md b/docs/mcp-install.md
index c1d3e50e..9cc1eb72 100644
--- a/docs/mcp-install.md
+++ b/docs/mcp-install.md
@@ -116,6 +116,52 @@ metadata.
---
+## Claude Code
+
+**Status:** ✅ Native HTTP MCP supported. ✅ Optional session-aware stdio
+bridge supported for concurrent sessions.
+
+The default registration remains a static HTTP entry:
+
+```bash
+ai-memory install-mcp --client claude-code --apply
+```
+
+Static HTTP config cannot attach the current lifecycle-hook session id, so
+`[auto_scope] mode = "per_session"` cannot isolate two concurrent Claude Code
+sessions through that entry. Opt into ai-memory's local stdio bridge instead:
+
+```bash
+ai-memory install-mcp --client claude-code --session-aware --apply
+```
+
+The generated entry runs `ai-memory mcp-bridge`, connects to the same configured
+local or remote `/mcp` endpoint, preserves bearer authentication, and adds
+`X-Memory-Actor-Session-Id: <CLAUDE_CODE_SESSION_ID>` to every upstream request.
+It supports ai-memory's default stateless HTTP mode and opt-in stateful mode.
+The command fails closed if Claude did not supply a session id rather than
+silently falling back to the shared single slot.
+
+Pair the bridge with this server setting:
+
+```toml
+[auto_scope]
+mode = "per_session"
+```
+
+Claude Code sets `CLAUDE_CODE_SESSION_ID` on stdio MCP subprocesses, but the
+subprocess retains the id it was launched with across `/clear`. Also,
+`--continue` or `--resume` without an explicit id may expose the startup id
+instead of the resumed id. Restart Claude Code after `/clear` when exact
+session-key continuity matters, and prefer `--resume <session-id>` over an
+implicit resume. These are upstream lifecycle limits; the bridge does not guess
+or switch identities behind Claude Code.
+
+`--session-aware` is Claude-Code-only. Other clients keep their documented
+native HTTP or generated bridge paths.
+
+---
+
## Cursor
**Status:** ✅ MCP supported. ✅ Lifecycle hooks supported via