Skip to content

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

Rust

feat(mcp): add strip_root_combinators toggle for schema-strict upstreams

changshenhan68d650d712d5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 28fbefb4..8bee9c42 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,6 +8,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
### Added
+- New `strip_root_combinators` config flag (env `AI_MEMORY_STRIP_ROOT_COMBINATORS`,
+ or `strip_root_combinators = true` in config.toml) strips root-level
+ `anyOf`/`oneOf`/`allOf` from MCP tool input schemas on every `tools/list`.
+ Generic MCP clients such as OpenCode and Cursor never send the `?flavor=`
+ marker, yet forward schemas verbatim to strict upstreams (Moonshot, Bedrock)
+ that reject root combinators with a 400 — this gives operators behind such an
+ upstream a mode-independent opt-in. Runtime "exactly one of" validation is
+ unchanged ([#412]).
- The built-in sanitizer now redacts seven further credential shapes, completing
three vendor families it already covered only in part. **GitHub:** every
token prefix — `gho_` (OAuth, the form `gh auth login` writes to disk),
diff --git a/crates/ai-memory-cli/src/commands/serve.rs b/crates/ai-memory-cli/src/commands/serve.rs
index 3810ffa5..40362523 100644
--- a/crates/ai-memory-cli/src/commands/serve.rs
+++ b/crates/ai-memory-cli/src/commands/serve.rs
@@ -485,7 +485,8 @@ pub async fn run(config: &Config, args: ServeArgs) -> Result<()> {
.with_active_project(active_project.clone())
.with_sanitizer(sanitizer.clone())
.with_trusted_proxy_identity(trusted_proxy_identity_enabled(&config.auth))
- .with_per_user_slots(config.slots.per_user);
+ .with_per_user_slots(config.slots.per_user)
+ .with_strip_root_combinators(config.strip_root_combinators);
if let Some(e) = embedder.clone() {
server = server.with_embedder(e);
}
diff --git a/crates/ai-memory-cli/src/config.rs b/crates/ai-memory-cli/src/config.rs
index 2675861d..615c61fb 100644
--- a/crates/ai-memory-cli/src/config.rs
+++ b/crates/ai-memory-cli/src/config.rs
@@ -156,6 +156,17 @@ pub struct Config {
/// `install-hooks --capture-assistant`. Set with
/// `AI_MEMORY_CAPTURE_ASSISTANT=true`.
pub capture_assistant: bool,
+ /// Strip root-level `anyOf`/`oneOf`/`allOf` from MCP tool input
+ /// schemas (e.g. `memory_read_page`'s "exactly one of path/query"
+ /// contract) on every `tools/list`, regardless of client or `?flavor=`
+ /// marker. Moonshot and Bedrock reject root combinators with a 400, and
+ /// generic MCP clients (OpenCode, Cursor) never send the flavor marker —
+ /// so operators routing through a strict upstream can opt in here.
+ /// Runtime "exactly one of" validation is unchanged and remains the
+ /// enforcement backstop (issue #412). Set with
+ /// `AI_MEMORY_STRIP_ROOT_COMBINATORS=true` or `strip_root_combinators = true`
+ /// in config.toml.
+ pub strip_root_combinators: bool,
/// Opt-in post-RRF reranker for `memory_query`. Only `"llm"` is
/// supported: LLM-as-judge over the configured LLM provider, so it
/// requires `AI_MEMORY_LLM_PROVIDER` too. Off by default — it puts
@@ -543,6 +554,7 @@ impl Default for Config {
llm_compat_strict: true,
consolidate_on_session_end: false,
capture_assistant: false,
+ strip_root_combinators: false,
reranker: None,
embedding_provider: None,
embedding_model: None,
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index 1578c666..1018f556 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -405,6 +405,14 @@ pub struct AiMemoryServer {
/// keeps manual runs at least as strict as the operator's configured
/// Phase 1/2 budgets instead of falling back to compiled defaults.
auto_improve_review_config: AutoImproveReviewConfig,
+ /// Opt-in: strip root-level `anyOf`/`oneOf`/`allOf` from MCP tool input
+ /// schemas on every `tools/list`, even without a `?flavor=` marker
+ /// (issue #412). Generic MCP clients (OpenCode, Cursor) never send the
+ /// flavor marker, and Moonshot/Bedrock reject root combinators with a
+ /// 400 — so operators behind a strict upstream set this via
+ /// `AI_MEMORY_STRIP_ROOT_COMBINATORS=true`. Runtime "exactly one of"
+ /// validation is unchanged.
+ strip_root_combinators: bool,
/// Cooldown clock for the M8 access-bump reinforcement: the last
/// instant each page's access counter was bumped. A page returned by
/// many searches in quick succession is bumped at most once per
@@ -1254,6 +1262,7 @@ impl AiMemoryServer {
sanitizer: ai_memory_core::Sanitizer::builtin(),
auto_improve_require_approval: false,
auto_improve_review_config: default_auto_improve_review_config(),
+ strip_root_combinators: false,
access_bump_seen: Arc::new(Mutex::new(HashMap::new())),
trusted_proxy_identity: false,
per_user_slots: false,
@@ -1280,6 +1289,15 @@ impl AiMemoryServer {
self
}
+ /// Opt in to stripping root-level combinators from MCP tool input schemas
+ /// on every `tools/list`, independent of the `?flavor=` marker (issue
+ /// #412). See [`Self::strip_root_combinators`].
+ #[must_use]
+ pub fn with_strip_root_combinators(mut self, enabled: bool) -> Self {
+ self.strip_root_combinators = enabled;
+ self
+ }
+
/// Configure whether auto-improvement requires manual pending-writes approval.
#[must_use]
pub fn with_auto_improve_require_approval(mut self, require_approval: bool) -> Self {
@@ -3854,11 +3872,18 @@ impl ServerHandler for AiMemoryServer {
// rmcp injects `http::request::Parts` into request extensions in
// both stateless and stateful modes, so the flavor marker is
// available even without peer clientInfo.
- let restricted_schema = context
- .extensions
- .get::<http::request::Parts>()
- .and_then(|parts| parts.uri.query())
- .is_some_and(has_restricted_schema_flavor);
+ // Operator opt-in (issue #412): generic clients such as OpenCode and
+ // Cursor never send the `?flavor=` marker, yet forward tool schemas
+ // verbatim to strict upstreams (Moonshot, Bedrock) that 400 on root
+ // combinators. `strip_root_combinators` serves the restricted
+ // dialect unconditionally; the flavor marker remains the
+ // per-client override.
+ let restricted_schema = self.strip_root_combinators
+ || context
+ .extensions
+ .get::<http::request::Parts>()
+ .and_then(|parts| parts.uri.query())
+ .is_some_and(has_restricted_schema_flavor);
if restricted_schema {
Ok(ListToolsResult::with_all_items(
restricted_schema_tool_list(tools),
diff --git a/crates/ai-memory-mcp/tests/mcp_stateless_http.rs b/crates/ai-memory-mcp/tests/mcp_stateless_http.rs
index 386f18a0..f7c155c1 100644
--- a/crates/ai-memory-mcp/tests/mcp_stateless_http.rs
+++ b/crates/ai-memory-mcp/tests/mcp_stateless_http.rs
@@ -32,6 +32,15 @@ const TOOLS_LIST: &str = r#"{"jsonrpc":"2.0","id":3,"method":"tools/list","param
/// 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) {
+ make_router_with_strip(tmp, stateful, false).await
+}
+
+/// [`make_router`] with the `strip_root_combinators` server toggle exposed.
+async fn make_router_with_strip(
+ tmp: &TempDir,
+ stateful: bool,
+ strip_root_combinators: bool,
+) -> (Router, Store) {
let store = Store::open(tmp.path()).unwrap();
let ws = store
.writer
@@ -43,7 +52,8 @@ async fn make_router(tmp: &TempDir, stateful: bool) -> (Router, Store) {
.get_or_create_project(ws, "scratch".to_string(), None)
.await
.unwrap();
- let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj);
+ let server = AiMemoryServer::new(store.reader.clone(), store.writer.clone(), ws, proj)
+ .with_strip_root_combinators(strip_root_combinators);
let svc = StreamableHttpService::new(
move || Ok(server.clone()),
LocalSessionManager::default().into(),
@@ -237,6 +247,47 @@ async fn stateless_bedrock_flavor_strips_root_any_of() {
assert!(schema.get("properties").is_some());
}
+/// Generic clients (OpenCode, Cursor) never send the `?flavor=` marker, yet
+/// forward tool schemas verbatim to strict upstreams. The
+/// `strip_root_combinators` toggle must serve the restricted dialect to them
+/// anyway (issue #412) — same transport wiring, no flavor parameter.
+#[tokio::test]
+async fn stateless_config_strip_strips_root_any_of_without_flavor() {
+ let tmp = TempDir::new().unwrap();
+ let (router, _store) = make_router_with_strip(&tmp, false, true).await;
+
+ let resp = router.oneshot(post_to("/mcp", TOOLS_LIST)).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let schema = read_page_input_schema(&body_string(resp).await);
+ for key in ["anyOf", "oneOf", "allOf"] {
+ assert!(
+ schema.get(key).is_none(),
+ "config strip must remove root `{key}` without a flavor marker: {schema}"
+ );
+ }
+ assert!(
+ schema.get("properties").is_some(),
+ "the flat schema must keep describing the args: {schema}"
+ );
+}
+
+/// The toggle is opt-in: with it off and no flavor marker, the upstream root
+/// `anyOf` stays, so schema-respecting clients keep their early refusal
+/// (issue #155).
+#[tokio::test]
+async fn stateless_config_without_strip_keeps_root_any_of_without_flavor() {
+ let tmp = TempDir::new().unwrap();
+ let (router, _store) = make_router(&tmp, false).await;
+
+ let resp = router.oneshot(post_to("/mcp", TOOLS_LIST)).await.unwrap();
+ assert_eq!(resp.status(), StatusCode::OK);
+ let schema = read_page_input_schema(&body_string(resp).await);
+ assert!(
+ schema.get("anyOf").is_some(),
+ "default config must keep the upstream root anyOf: {schema}"
+ );
+}
+
/// Control: without the marker, tools/list keeps the upstream root `anyOf`.
#[tokio::test]
async fn stateless_tools_list_without_flavor_keeps_root_any_of() {