Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(mcp-bridge): answer server/discover before initialize instead of exiting
4nrry742c680dc311
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 59954396..69488566 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -11,6 +11,18 @@ version in [`docs/changelog/`](docs/changelog/):## [Unreleased]+### Fixed+- Fixed `ai-memory mcp-bridge` exiting when a client sent `server/discover`+ before `initialize`. A client that supports both the 2026-07-28 MCP revision+ and the older `initialize` handshake, such as Antigravity CLI 1.4 and the+ Antigravity 2.24 app, sends that probe first and falls back to `initialize`+ when the server answers with an error. The bridge ended the session instead,+ so the fallback found a closed pipe (`calling initialize: client is closing:+ EOF`) and the client never connected. Until `initialize` arrives, the bridge+ now answers every other request with a JSON-RPC Method not found error,+ ignores notifications such as the client cancelling its probe, and still+ answers `ping`. A client that starts with `initialize` sees no change.+## [3.1.0] - 2026-10-16### Addeddiff --git a/crates/ai-memory-cli/src/commands/mcp_bridge.rs b/crates/ai-memory-cli/src/commands/mcp_bridge.rsindex e33c3ec4..bd0c7df1 100644--- a/crates/ai-memory-cli/src/commands/mcp_bridge.rs+++ b/crates/ai-memory-cli/src/commands/mcp_bridge.rs@@ -31,11 +31,13 @@ use std::collections::HashMap;use anyhow::{Context, Result};use reqwest::header::{HeaderName, HeaderValue};use rmcp::model::{- CallToolRequestParams, CallToolResult, ListToolsResult, PaginatedRequestParams, ServerInfo,+ CallToolRequestParams, CallToolResult, ClientJsonRpcMessage, ClientRequest, ErrorCode,+ ListToolsResult, PaginatedRequestParams, ServerInfo, ServerJsonRpcMessage,};use rmcp::service::{RequestContext, RoleClient, RoleServer, ServiceError};+use rmcp::transport::async_rw::AsyncRwTransport;use rmcp::transport::streamable_http_client::StreamableHttpClientTransportConfig;-use rmcp::transport::{StreamableHttpClientTransport, stdio};+use rmcp::transport::{StreamableHttpClientTransport, Transport, stdio};use rmcp::{ErrorData as McpError, Peer, ServerHandler, ServiceExt};use crate::cli::{BridgeAgent, McpBridgeArgs};@@ -85,6 +87,80 @@ fn upstream_error(error: ServiceError) -> McpError {}}+/// The stdio transport, kept open through a dual-era client's version probe.+///+/// rmcp 2.2's server handshake answers `ping` before `initialize` and ends+/// the session on any other message. A client that speaks both the 2026-07-28+/// revision and the `initialize` handshake (Antigravity CLI 1.4, the+/// Antigravity 2.24 app) first sends `server/discover`, and falls back to+/// `initialize` when the server answers with any error or not at all+/// (<https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio#backward-compatibility>).+/// Exiting instead closes the pipe under that fallback. Until `initialize`+/// arrives this answers every other request with Method not found, so the+/// client sees a legacy server, and drops notifications: a client that stopped+/// waiting for its probe may cancel it. From `initialize` on, every message+/// passes through to rmcp unchanged.+///+/// Revisit on an rmcp 3.x bump: its handshake answers the probe itself+/// (modelcontextprotocol/rust-sdk#1248).+struct PreInitializeGate<T> {+ inner: T,+ initialize_seen: bool,+}++impl<T> PreInitializeGate<T> {+ fn new(inner: T) -> Self {+ Self {+ inner,+ initialize_seen: false,+ }+ }+}++impl<T: Transport<RoleServer>> Transport<RoleServer> for PreInitializeGate<T> {+ type Error = T::Error;++ fn send(+ &mut self,+ item: ServerJsonRpcMessage,+ ) -> impl Future<Output = Result<(), Self::Error>> + Send + 'static {+ self.inner.send(item)+ }++ async fn receive(&mut self) -> Option<ClientJsonRpcMessage> {+ while !self.initialize_seen {+ let ClientJsonRpcMessage::Request(request) = self.inner.receive().await? else {+ continue;+ };+ match request.request {+ ClientRequest::InitializeRequest(_) => self.initialize_seen = true,+ ClientRequest::PingRequest(_) => {}+ _ => {+ let error = McpError::new(+ ErrorCode::METHOD_NOT_FOUND,+ format!(+ "{} is not available before initialize",+ request.request.method()+ ),+ None,+ );+ self.inner+ .send(ServerJsonRpcMessage::error(error, Some(request.id)))+ .await+ .ok()?;+ continue;+ }+ }+ return Some(ClientJsonRpcMessage::Request(request));+ }+ self.inner.receive().await+ }++ fn close(&mut self) -> impl Future<Output = Result<(), Self::Error>> + Send {+ self.inner.close()+ }+}+pub(crate) fn upstream_config(server_url: &str,session_id: Option<&str>,@@ -228,8 +304,11 @@ pub async fn run(config: &Config, args: McpBridgeArgs) -> Result<()> {upstream: upstream.peer().clone(),server_info,};+ let (stdin, stdout) = stdio();let downstream = bridge- .serve(stdio())+ .serve(PreInitializeGate::new(AsyncRwTransport::new_server(+ stdin, stdout,+ ))).await.context("starting session-aware stdio MCP bridge")?;diff --git a/crates/ai-memory-cli/tests/suite/main.rs b/crates/ai-memory-cli/tests/suite/main.rsindex 793f646f..dd310c88 100644--- a/crates/ai-memory-cli/tests/suite/main.rs+++ b/crates/ai-memory-cli/tests/suite/main.rs@@ -24,6 +24,7 @@ mod hook_payload;mod install_script;mod jail_toggles_e2e;mod marker_scope;+mod mcp_bridge_stdio;mod message_e2e;mod opencode_dialect;mod packaging;diff --git a/crates/ai-memory-cli/tests/suite/mcp_bridge_stdio.rs b/crates/ai-memory-cli/tests/suite/mcp_bridge_stdio.rsnew file mode 100644index 00000000..b7f5c783--- /dev/null+++ b/crates/ai-memory-cli/tests/suite/mcp_bridge_stdio.rs@@ -0,0 +1,195 @@+//! `ai-memory mcp-bridge` over stdio, through the shipped binary, against an+//! in-process upstream MCP server.+//!+//! A dual-era client (Antigravity CLI 1.4, the Antigravity 2.24 app) probes+//! with `server/discover` before anything else and falls back to `initialize`+//! when a legacy server answers with any error or not at all:+//! <https://modelcontextprotocol.io/specification/2026-07-28/basic/transports/stdio#backward-compatibility>.+//! The bridge used to exit on the probe, so the fallback hit a closed pipe.++use std::sync::Arc;+use std::time::Duration;++use axum::Router;+use rmcp::model::{ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerInfo, Tool};+use rmcp::service::{RequestContext, RoleServer};+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};+use rmcp::{ErrorData as McpError, ServerHandler};+use serde_json::{Value, json};+use tokio::io::{AsyncBufReadExt as _, AsyncWriteExt as _, BufReader, Lines};+use tokio::process::{ChildStdin, ChildStdout};++const BIN: &str = env!("CARGO_BIN_EXE_ai-memory");++#[derive(Clone)]+struct OneTool;++impl ServerHandler for OneTool {+ 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(+ "probe_tool",+ "Reached through the bridge",+ Arc::new(Default::default()),+ )],+ ..Default::default()+ })+ }+}++/// The upstream the bridge connects to before it serves stdio, stateless like+/// `ai-memory serve`'s default.+async fn upstream() -> (String, tokio::task::JoinHandle<()>) {+ let service: StreamableHttpService<OneTool, LocalSessionManager> = StreamableHttpService::new(+ || Ok(OneTool),+ LocalSessionManager::default().into(),+ StreamableHttpServerConfig::default()+ .with_stateful_mode(false)+ .with_json_response(true),+ );+ let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();+ let address = listener.local_addr().unwrap();+ let server = tokio::spawn(async move {+ axum::serve(listener, Router::new().nest_service("/mcp", service))+ .await+ .unwrap();+ });+ (format!("http://{address}/mcp"), server)+}++async fn send(stdin: &mut ChildStdin, message: Value) {+ stdin+ .write_all(format!("{message}\n").as_bytes())+ .await+ .unwrap();+ stdin.flush().await.unwrap();+}++/// The next line the bridge writes, which must be the reply to `id`: nothing+/// else (a reply to a notification included) may come before it.+async fn reply(stdout: &mut Lines<BufReader<ChildStdout>>, id: Value) -> Value {+ let line = tokio::time::timeout(Duration::from_secs(20), stdout.next_line())+ .await+ .unwrap_or_else(|_| panic!("no reply to {id} within 20s"))+ .unwrap()+ .unwrap_or_else(|| panic!("the bridge closed stdout instead of answering {id}"));+ let message: Value = serde_json::from_str(&line).unwrap();+ assert_eq!(message["id"], id, "{message}");+ message+}++/// 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+/// the fallback), the notification gets nothing, and the handshake that+/// follows reaches the upstream tools.+#[tokio::test]+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 stdin = child.stdin.take().unwrap();+ let mut stdout = BufReader::new(child.stdout.take().unwrap()).lines();+ let modern_meta = json!({+ "io.modelcontextprotocol/protocolVersion": "2026-07-28",+ "io.modelcontextprotocol/clientCapabilities": {},+ "io.modelcontextprotocol/clientInfo": {"name": "dual-era-e2e", "version": "0"}+ });++ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "id": 1, "method": "server/discover",+ "params": {"_meta": modern_meta}}),+ )+ .await;+ let discover = reply(&mut stdout, json!(1)).await;+ assert!(discover.get("result").is_none(), "{discover}");+ assert_eq!(discover["error"]["code"], json!(-32601), "{discover}");++ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "method": "notifications/cancelled",+ "params": {"requestId": 1, "reason": "probe timed out"}}),+ )+ .await;+ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "id": "early-ping", "method": "ping"}),+ )+ .await;+ let ping = reply(&mut stdout, json!("early-ping")).await;+ assert_eq!(ping["result"], json!({}), "{ping}");++ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "id": 2, "method": "tools/list",+ "params": {"_meta": modern_meta}}),+ )+ .await;+ let early = reply(&mut stdout, json!(2)).await;+ assert!(early.get("result").is_none(), "{early}");+ assert_eq!(early["error"]["code"], json!(-32601), "{early}");++ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "id": 3, "method": "initialize",+ "params": {"protocolVersion": "2025-06-18", "capabilities": {},+ "clientInfo": {"name": "dual-era-e2e", "version": "0"}}}),+ )+ .await;+ let init = reply(&mut stdout, json!(3)).await;+ assert_eq!(+ init["result"]["protocolVersion"],+ json!("2025-06-18"),+ "{init}"+ );+ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "method": "notifications/initialized"}),+ )+ .await;+ send(+ &mut stdin,+ json!({"jsonrpc": "2.0", "id": 4, "method": "tools/list", "params": {}}),+ )+ .await;+ let tools = reply(&mut stdout, json!(4)).await;+ assert_eq!(+ tools["result"]["tools"][0]["name"],+ json!("probe_tool"),+ "{tools}"+ );++ drop(stdin);+ let status = tokio::time::timeout(Duration::from_secs(20), child.wait())+ .await+ .expect("the bridge exits when stdin closes")+ .unwrap();+ assert!(status.success(), "{status}");+ server.abort();+}