Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix: stateless Streamable HTTP transport by default (#3)
AkitaOnRails9999a1da90fe
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 65322444..fba84574 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,13 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Changed+- HTTP transport now defaults to **stateless** mode (`json_response`, no+ `Mcp-Session-Id` required), so stateless MCP clients (OpenCode+ `type: "remote"`, `curl`) work without an `mcp-remote` stdio shim+ ([#3]). New `serve --transport http --http-stateful` flag restores the+ previous session+SSE behaviour for clients that need it.+## [0.1.1] - 2026-05-24### Addeddiff --git a/crates/ai-memory-cli/src/cli.rs b/crates/ai-memory-cli/src/cli.rsindex 11147eb9..9b37f09e 100644--- a/crates/ai-memory-cli/src/cli.rs+++ b/crates/ai-memory-cli/src/cli.rs@@ -576,6 +576,16 @@ pub struct ServeArgs {/// proxy that handles its own auth if you expose it.#[arg(long)]pub enable_web: bool,+ /// Run the HTTP transport in stateful (session) mode: the server+ /// issues an `Mcp-Session-Id` on `initialize` and requires it on+ /// every later request, with SSE-framed responses. Off by default —+ /// the HTTP transport is stateless and returns plain JSON, so+ /// stateless clients (OpenCode `type: "remote"`, `curl`) work without+ /// an `mcp-remote` stdio shim (issue #3). Enable this only for+ /// clients that need session continuity or server-initiated SSE+ /// streams. No effect on `--transport stdio`.+ #[arg(long)]+ pub http_stateful: bool,}/// Arguments for `write-page`.diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rsindex ea523ad7..5b16db4d 100644--- a/crates/ai-memory-cli/src/commands/serve.rs+++ b/crates/ai-memory-cli/src/commands/serve.rs@@ -181,12 +181,27 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {allowed_hosts = ?config.allowed_hosts,"MCP Host-header allowlist");+ // Default to stateless Streamable HTTP: each POST is serviced+ // independently and answered as plain `application/json`, so+ // stateless clients (OpenCode `type: "remote"`, curl) work+ // without an `mcp-remote` shim (issue #3). ai-memory's tools+ // are pure request-response and project resolution rides the+ // in-process `ActiveProject` pointer, not the transport+ // session — so session mode buys us nothing. `--http-stateful`+ // restores rmcp's session+SSE behaviour for clients that want+ // it.+ info!(+ stateful = args.http_stateful,+ "MCP Streamable HTTP transport mode"+ );let mcp_service = StreamableHttpService::new(move || Ok(server_clone.clone()),LocalSessionManager::default().into(),StreamableHttpServerConfig::default().with_cancellation_token(cancel.child_token())- .with_allowed_hosts(config.allowed_hosts.clone()),+ .with_allowed_hosts(config.allowed_hosts.clone())+ .with_stateful_mode(args.http_stateful)+ .with_json_response(!args.http_stateful),);let hooks = hook_router(HookState {workspace_id: ws,diff --git a/crates/ai-memory-mcp/tests/mcp_stateless_http.rs b/crates/ai-memory-mcp/tests/mcp_stateless_http.rsnew file mode 100644index 00000000..6802ac0f--- /dev/null+++ b/crates/ai-memory-mcp/tests/mcp_stateless_http.rs@@ -0,0 +1,161 @@+//! Integration tests for the Streamable HTTP transport's stateless vs.+//! stateful behaviour (issue #3).+//!+//! Stateless clients (OpenCode `type: "remote"`, curl) send `initialize`+//! and `tools/call` as independent requests without echoing an+//! `Mcp-Session-Id`. In rmcp's default *stateful* mode the server demands+//! that header and rejects the second request with 422 "Unexpected+//! message, expect initialize request". `ai-memory serve --transport http`+//! now defaults to *stateless* mode (`stateful_mode=false` ++//! `json_response=true`), so those clients work with no `mcp-remote` shim.+//! `--http-stateful` restores the session behaviour.+//!+//! These tests drive the exact `StreamableHttpService` wiring from+//! `serve.rs` through an axum router, so they catch a regression in either+//! direction.++use ai_memory_mcp::AiMemoryServer;+use ai_memory_store::Store;+use axum::Router;+use axum::body::Body;+use axum::http::{Request, StatusCode};+use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;+use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};+use tempfile::TempDir;+use tower::ServiceExt;++const INITIALIZE: &str = r#"{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2024-11-05","capabilities":{},"clientInfo":{"name":"test","version":"1.0"}}}"#;+const TOOLS_CALL_STATUS: &str = r#"{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"memory_status","arguments":{}}}"#;++/// Build a `/mcp` router exactly like `serve.rs` does, toggling stateful+/// mode. Returns the `Store` too so the writer actor stays alive for the+/// duration of the test.+async fn make_router(tmp: &TempDir, stateful: bool) -> (Router, Store) {+ let store = Store::open(tmp.path()).unwrap();+ let ws = store+ .writer+ .get_or_create_workspace("default".to_string())+ .await+ .unwrap();+ let proj = store+ .writer+ .get_or_create_project(ws, "scratch".to_string(), None)+ .await+ .unwrap();+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj);+ let svc = StreamableHttpService::new(+ move || Ok(server.clone()),+ LocalSessionManager::default().into(),+ StreamableHttpServerConfig::default()+ .with_stateful_mode(stateful)+ .with_json_response(!stateful),+ );+ let router = Router::new().nest_service("/mcp", svc);+ (router, store)+}++/// POST a JSON-RPC body to `/mcp` with the Accept header every compliant+/// Streamable HTTP client sends (both JSON and event-stream), and no+/// session id.+fn post(body: &'static str) -> Request<Body> {+ Request::builder()+ .method("POST")+ .uri("/mcp")+ // rmcp's DNS-rebinding guard rejects a missing/disallowed Host with+ // 400; `localhost` is in the default allowlist. Real HTTP clients+ // always send Host — oneshot does not, so set it explicitly.+ .header("host", "localhost")+ .header("content-type", "application/json")+ .header("accept", "application/json, text/event-stream")+ .body(Body::from(body))+ .unwrap()+}++async fn body_string(resp: axum::response::Response) -> String {+ let bytes = axum::body::to_bytes(resp.into_body(), 2_000_000)+ .await+ .unwrap();+ String::from_utf8(bytes.to_vec()).unwrap()+}++/// The fix: in the default stateless mode, a `tools/call` arriving with no+/// prior session and no `Mcp-Session-Id` header is serviced and returns a+/// JSON-RPC result — not a 422 / "Session not found".+#[tokio::test]+async fn stateless_tools_call_without_session_succeeds() {+ let tmp = TempDir::new().unwrap();+ let (router, _store) = make_router(&tmp, false).await;++ let resp = router+ .clone()+ .oneshot(post(TOOLS_CALL_STATUS))+ .await+ .unwrap();+ assert_eq!(+ resp.status(),+ StatusCode::OK,+ "stateless tools/call must succeed without a session id"+ );+ let body = body_string(resp).await;+ let json: serde_json::Value = serde_json::from_str(&body)+ .unwrap_or_else(|e| panic!("stateless response must be JSON, got: {body}\nerr: {e}"));+ assert!(+ json.get("error").is_none(),+ "expected a JSON-RPC result, got an error: {body}"+ );+ assert!(json.get("result").is_some(), "missing result: {body}");+ // memory_status serialises StatusCounts, whose fields include+ // `pages_latest` — proves the tool actually ran, not just an empty ack.+ assert!(+ body.contains("pages_latest"),+ "result should carry status counts: {body}"+ );+}++/// `initialize` in stateless mode also returns a plain JSON-RPC result+/// (no session handshake required).+#[tokio::test]+async fn stateless_initialize_returns_json_result() {+ let tmp = TempDir::new().unwrap();+ let (router, _store) = make_router(&tmp, false).await;++ let resp = router.clone().oneshot(post(INITIALIZE)).await.unwrap();+ assert_eq!(resp.status(), StatusCode::OK);+ let body = body_string(resp).await;+ let json: serde_json::Value = serde_json::from_str(&body).expect("initialize returns JSON");+ assert!(+ json.get("result").is_some(),+ "missing initialize result: {body}"+ );+ assert!(+ body.contains("serverInfo") || body.contains("protocolVersion"),+ "initialize result should carry server info: {body}"+ );+}++/// Contrast / guard: with `--http-stateful` (session mode), the same+/// session-less `tools/call` is rejected with 422 "Unexpected message,+/// expect initialize request" — the exact symptom from issue #3. This+/// proves the default flip is what resolves it, and pins the opt-in+/// behaviour so a future change to the default can't silently regress it.+#[tokio::test]+async fn stateful_tools_call_without_session_is_rejected() {+ let tmp = TempDir::new().unwrap();+ let (router, _store) = make_router(&tmp, true).await;++ let resp = router+ .clone()+ .oneshot(post(TOOLS_CALL_STATUS))+ .await+ .unwrap();+ assert_eq!(+ resp.status(),+ StatusCode::UNPROCESSABLE_ENTITY,+ "stateful mode must reject a session-less tools/call"+ );+ let body = body_string(resp).await;+ assert!(+ body.contains("initialize"),+ "stateful rejection should mention the missing initialize: {body}"+ );+}diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex c9e61460..3dc5b869 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -5,6 +5,17 @@> `Authorization: Bearer <token>` header to the `headers` block when bearer auth> is enabled. The MCP wire protocol expects the `/mcp` path suffix on the URL.+> **Transport is stateless by default.** Since v0.1.2 the HTTP transport+> answers each request independently (plain JSON, no `Mcp-Session-Id`+> required), so any client that points a remote URL at `/mcp` — including+> OpenCode `type: "remote"` and plain `curl` — works without an+> `mcp-remote` stdio shim (issue #3). The `mcp-remote` bridge is still+> needed for **Claude Desktop** specifically, because its config only+> supports stdio servers — not because of session state. If you run a+> client that *requires* MCP session continuity or server-initiated SSE+> streams, start the server with `ai-memory serve --transport http+> --http-stateful` to restore rmcp's session mode.+This page documents how to register ai-memory as an MCP server withthe agent CLIs **that are not covered inline in the README**.