Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(mcp): keep the bridge's server requests off environment proxies
Lucas Lucena640a62f19ef8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 5f56e23a..2c10fae6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -21,6 +21,11 @@ version in [`docs/changelog/`](docs/changelog/):relay and wiki sync companions take the same `rustls-webpki` bump.### Fixed+- `mcp-bridge` and the `setup` self-check no longer send requests to the+ server through `HTTP_PROXY`, `HTTPS_PROXY` or `ALL_PROXY`, as the hooks+ already did. A sandbox such as ai-jail exports a proxy with an empty+ `NO_PROXY`, and its filtering proxy answered the bridge's loopback+ `initialize` with 405, so Claude Code reported `CONNECTION_CLOSED`.- Bound native API-key hashes to their configured pepper with a persistedArgon2id verifier. A restored database with existing keys now refuses toserve under a different `[auth].token_pepper` instead of silently makingdiff --git a/Cargo.lock b/Cargo.lockindex 74f4dbe5..4f5b8092 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -60,6 +60,7 @@ dependencies = ["libc","parking_lot","reqwest 0.12.28",+ "reqwest 0.13.4","rmcp","rstest","rusqlite",diff --git a/crates/ai-memory-cli/Cargo.toml b/crates/ai-memory-cli/Cargo.tomlindex 68baa113..41a4c964 100644--- a/crates/ai-memory-cli/Cargo.toml+++ b/crates/ai-memory-cli/Cargo.toml@@ -76,6 +76,11 @@ rmcp = { workspace = true, features = ["transport-streamable-http-client-reqwest","reqwest-tls-no-provider",] }+# The reqwest 0.13 that rmcp's client transport is built on, named so the bridge+# can hand rmcp its own client (`mcp_bridge::upstream_transport`) instead of+# rmcp's default, which reads `HTTP_PROXY` and friends. No features of its own:+# rmcp's choice above is the whole TLS setup.+reqwest-mcp = { package = "reqwest", version = "0.13", default-features = false }rustls = { workspace = true }serde.workspace = trueserde_json.workspace = truediff --git a/crates/ai-memory-cli/src/commands/mcp_bridge.rs b/crates/ai-memory-cli/src/commands/mcp_bridge.rsindex d533b2d6..a66b23e8 100644--- a/crates/ai-memory-cli/src/commands/mcp_bridge.rs+++ b/crates/ai-memory-cli/src/commands/mcp_bridge.rs@@ -200,6 +200,28 @@ pub(crate) fn upstream_config(Ok(config)}+/// The upstream transport for `server_url`, built on a client that ignores+/// `HTTP_PROXY`, `HTTPS_PROXY` and `ALL_PROXY`, as the hooks' client does+/// (`hook_capture::build_client`). rmcp's default client reads them, so a+/// sandbox that exports a proxy with an empty `NO_PROXY` (ai-jail) sent the+/// loopback `initialize` to that proxy, which answered 405. Pooling and+/// redirects are off, as in rmcp's default.+pub(crate) fn upstream_transport(+ server_url: &str,+ session_id: Option<&str>,+ auth_token: Option<&str>,+) -> Result<StreamableHttpClientTransport<reqwest_mcp::Client>> {+ // First: it installs the crypto provider the client builder needs.+ let config = upstream_config(server_url, session_id, auth_token)?;+ let client = reqwest_mcp::Client::builder()+ .no_proxy()+ .pool_max_idle_per_host(0)+ .redirect(reqwest_mcp::redirect::Policy::none())+ .build()+ .context("building the MCP bridge HTTP client")?;+ Ok(StreamableHttpClientTransport::with_client(client, config))+}+/// The session id to forward: in the session-aware mode, the one `agent`/// sets (`CLAUDE_CODE_SESSION_ID` or `MUSE_SESSION_ID`), refusing to run/// without it; in the session-less mode nothing at all, whatever the@@ -320,11 +342,7 @@ pub async fn run(config: &Config, args: McpBridgeArgs) -> Result<()> {&config.server_url,));let bearer = bridge_bearer(config, &server_url)?;- let transport = StreamableHttpClientTransport::from_config(upstream_config(- &server_url,- session_id,- bearer.as_deref(),- )?);+ let transport = upstream_transport(&server_url, session_id, bearer.as_deref())?;// Connecting before serving stdio means a refused credential (401) or an// unreachable server ends the process with this error at once; the client@@ -624,14 +642,12 @@ mod tests {.unwrap();});- let upstream_transport = StreamableHttpClientTransport::from_config(- upstream_config(- &format!("http://{address}/mcp"),- Some("claude-session-244"),- None,- )- .unwrap(),- );+ let upstream_transport = upstream_transport(+ &format!("http://{address}/mcp"),+ Some("claude-session-244"),+ None,+ )+ .unwrap();let upstream = ().serve(upstream_transport).await.unwrap();let bridge = SessionAwareBridge {upstream: upstream.peer().clone(),diff --git a/crates/ai-memory-cli/src/commands/setup.rs b/crates/ai-memory-cli/src/commands/setup.rsindex 58fe9141..f00e4572 100644--- a/crates/ai-memory-cli/src/commands/setup.rs+++ b/crates/ai-memory-cli/src/commands/setup.rs@@ -1081,14 +1081,10 @@ async fn self_check(config: &Config, endpoint: &ServerEndpoint) -> Vec<String> {async fn memory_status(config: &Config) -> Result<()> {use rmcp::ServiceExt as _;use rmcp::model::CallToolRequestParams;- use rmcp::transport::StreamableHttpClientTransport;let url = install_mcp::mcp_server_url_from_base(&config.server_url);- let transport = StreamableHttpClientTransport::from_config(super::mcp_bridge::upstream_config(- &url,- None,- config.auth.bearer_token.as_deref(),- )?);+ let transport =+ super::mcp_bridge::upstream_transport(&url, None, config.auth.bearer_token.as_deref())?;let client = ().serve(transport).await.with_context(|| format!("connecting to {url}"))?;let result = client.peer()diff --git a/crates/ai-memory-cli/tests/suite/mcp_bridge_stdio.rs b/crates/ai-memory-cli/tests/suite/mcp_bridge_stdio.rsindex b7f5c783..8b25791d 100644--- a/crates/ai-memory-cli/tests/suite/mcp_bridge_stdio.rs+++ b/crates/ai-memory-cli/tests/suite/mcp_bridge_stdio.rs@@ -87,6 +87,28 @@ async fn reply(stdout: &mut Lines<BufReader<ChildStdout>>, id: Value) -> Value {message}+/// Spawn the shipped bridge against `url` with a throwaway home, plus `env`.+fn spawn_bridge(url: &str, home: &std::path::Path, env: &[(&str, &str)]) -> tokio::process::Child {+ let mut cmd = crate::e2e_support::hermetic(BIN);+ cmd.args(["mcp-bridge", "--no-session-id", "--server-url", url])+ .env("HOME", home)+ .env("USERPROFILE", home)+ .env("XDG_CONFIG_HOME", home.join(".config"))+ .env("AI_MEMORY_HOME", home)+ .env("AI_MEMORY_DATA_DIR", home.join("data"))+ .env("RUST_LOG", "off")+ .envs(env.iter().copied())+ .current_dir(home)+ .stdin(std::process::Stdio::piped())+ .stdout(std::process::Stdio::piped())+ // Shown with the test's output, so a bridge that exits says why.+ .stderr(std::process::Stdio::inherit());+ tokio::process::Command::from(cmd)+ .kill_on_drop(true)+ .spawn()+ .expect("spawn mcp-bridge")+}+/// The probe, a cancellation of it, a ping and an era-ambiguous `tools/list`/// before `initialize` each leave the bridge running: requests get a/// non-modern error (not `-32022` UnsupportedProtocolVersion, which would stop@@ -96,23 +118,7 @@ async fn reply(stdout: &mut Lines<BufReader<ChildStdout>>, id: Value) -> Value {async fn a_server_discover_probe_is_answered_and_initialize_still_works() {let (url, server) = upstream().await;let home = tempfile::tempdir().unwrap();- let mut cmd = crate::e2e_support::hermetic(BIN);- cmd.args(["mcp-bridge", "--no-session-id", "--server-url", &url])- .env("HOME", home.path())- .env("USERPROFILE", home.path())- .env("XDG_CONFIG_HOME", home.path().join(".config"))- .env("AI_MEMORY_HOME", home.path())- .env("AI_MEMORY_DATA_DIR", home.path().join("data"))- .env("RUST_LOG", "off")- .current_dir(home.path())- .stdin(std::process::Stdio::piped())- .stdout(std::process::Stdio::piped())- // Shown with the test's output, so a bridge that exits says why.- .stderr(std::process::Stdio::inherit());- let mut child = tokio::process::Command::from(cmd)- .kill_on_drop(true)- .spawn()- .expect("spawn mcp-bridge");+ let mut child = spawn_bridge(&url, home.path(), &[]);let mut stdin = child.stdin.take().unwrap();let mut stdout = BufReader::new(child.stdout.take().unwrap()).lines();let modern_meta = json!({@@ -193,3 +199,71 @@ async fn a_server_discover_probe_is_answered_and_initialize_still_works() {assert!(status.success(), "{status}");server.abort();}++/// A proxy from the environment never sees the bridge's requests, as with the+/// hooks' client (`hook_capture::build_client`). A sandbox such as ai-jail+/// exports `HTTP_PROXY` with an empty `NO_PROXY`; a filtering proxy there+/// answered the bridge's loopback `initialize` with 405, and the bridge+/// exited before Claude Code could list a tool.+#[tokio::test]+async fn a_proxy_in_the_environment_is_not_used_for_the_server() {+ let (url, server) = upstream().await;+ let proxy_listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let proxy_url = format!("http://{}", proxy_listener.local_addr().unwrap());+ // Answers every request the way ai-jail's filtering proxy did.+ let proxy = tokio::spawn(async move {+ while let Ok((mut socket, _)) = proxy_listener.accept().await {+ let mut request = [0_u8; 4096];+ let _ = tokio::io::AsyncReadExt::read(&mut socket, &mut request).await;+ let _ = socket+ .write_all(b"HTTP/1.1 405 Method Not Allowed\r\ncontent-length: 0\r\n\r\n")+ .await;+ }+ });+ let home = tempfile::tempdir().unwrap();+ let mut child = spawn_bridge(+ &url,+ home.path(),+ &[+ ("HTTP_PROXY", &proxy_url),+ ("http_proxy", &proxy_url),+ ("ALL_PROXY", &proxy_url),+ ("all_proxy", &proxy_url),+ ("NO_PROXY", ""),+ ("no_proxy", ""),+ ],+ );+ let mut stdin = child.stdin.take().unwrap();+ let mut stdout = BufReader::new(child.stdout.take().unwrap()).lines();++ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "id": 1, "method": "initialize",+ "params": {"protocolVersion": "2025-06-18", "capabilities": {},+ "clientInfo": {"name": "proxy-e2e", "version": "0"}}}),+ )+ .await;+ let init = reply(&mut stdout, json!(1)).await;+ assert!(init.get("result").is_some(), "{init}");+ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),+ )+ .await;+ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list", "params": {}}),+ )+ .await;+ let tools = reply(&mut stdout, json!(2)).await;+ assert_eq!(+ tools["result"]["tools"][0]["name"],+ json!("probe_tool"),+ "{tools}"+ );++ drop(stdin);+ let _ = child.wait().await;+ proxy.abort();+ server.abort();+}