Solution for long term memory for agent coding CLIs and to facilitate handoff between different agent vendors
Rust
fix(mcp): serve moonshot-flavored tool schemas behind ?flavor=moonshot
Lucas Oliveira453ee1dbcdc9
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex b51ba11a..cac600d3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -30,7 +30,16 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0`SubagentStop`, and `PreCompact`. Both paths honor `$KIMI_CODE_HOME`.Handoff injection happens at `SessionStart` through hook stdout, which KimiCode appends to the model context; `setup-agent` and `uninstall` handle the- new agent like the other first-class integrations.+ new agent like the other first-class integrations. The `install-mcp` entry+ points at `/mcp?flavor=moonshot`: the Moonshot API validates tool parameter+ schemas against a restricted dialect ("moonshot flavored json schema") that+ rejects root-level `anyOf`/`oneOf`/`allOf` combinators — including the+ `anyOf` on `memory_read_page` — and fails the whole session at `tools/list`.+ Requests carrying that flavor receive flat tool schemas from the server;+ every other client keeps receiving the upstream schemas unchanged.+ `uninstall` matches the Kimi Code entry in either URL form, so removing an+ install made before or after this change both work with the default+ `--mcp-url`.- Grok Build CLI is now a first-class MCP client as well as a hook agent:`install-mcp --client grok` renders and `--apply` merges a native HTTPentry into `$GROK_HOME/config.toml` (default `~/.grok/config.toml`)diff --git a/Cargo.lock b/Cargo.lockindex 04add83c..b1fa723e 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -189,6 +189,7 @@ dependencies = ["async-trait","axum","flate2",+ "http","jiff","rmcp","schemars",diff --git a/Cargo.toml b/Cargo.tomlindex 7b0a3e48..43e56313 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -97,6 +97,9 @@ winapi-util = "0.1"rmcp = { version = "1.7", features = ["server", "macros", "transport-io", "transport-streamable-http-server", "schemars"] }schemars = "1"axum = "0.8"+# Same `http` 1.x rmcp/axum use, so handlers can read the injected+# `http::request::Parts` (URI + headers) from MCP request extensions.+http = "1"# Direct dep so tests can use `Router::oneshot` via `ServiceExt`.tower = { version = "0.5", features = ["util"] }tower-http = { version = "0.6", features = ["fs", "cors"] }diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rsindex 644a7386..312053d9 100644--- a/crates/ai-memory-cli/src/commands/install_hooks.rs+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs@@ -673,11 +673,21 @@ fn expand_grok_placeholders_with(}fn hook_server_url_from_mcp_url(url: &str) -> Option<String> {- let trimmed = url.trim().trim_end_matches('/');- if trimmed.is_empty() {+ // Client-flavor query markers (Kimi Code's `?flavor=moonshot`) must+ // not leak into the hook URL: hooks POST to `<origin>/hook`, so the+ // inferred base needs query/fragment dropped BEFORE the `/mcp`+ // suffix peel below — otherwise the suffix never matches and the+ // whole `/mcp?flavor=...` tail would be baked into hook commands.+ let base = url+ .trim()+ .split(['?', '#'])+ .next()+ .unwrap_or_default()+ .trim_end_matches('/');+ if base.is_empty() {return None;}- Some(trimmed.strip_suffix("/mcp").unwrap_or(trimmed).to_string())+ Some(base.strip_suffix("/mcp").unwrap_or(base).to_string())}fn bearer_token_from_header(header: &str) -> Option<String> {@@ -3675,6 +3685,69 @@ mod tests {assert_eq!(inferred.auth_token.as_deref(), Some("secret-token"));}+ /// Kimi Code's mcp.json entry points at `/mcp?flavor=moonshot`+ /// (Moonshot rejects root-level schema combinators). Inferring the+ /// hook URL from that entry must strip BOTH the query marker and the+ /// `/mcp` path — hooks POST to `<origin>/hook`, so a flavored or+ /// `/mcp`-suffixed base would 404 every capture.+ #[test]+ fn kimi_code_mcp_inference_strips_flavor_query_and_mcp_path() {+ let inferred = infer_json_mcp_config(+ r#"{+ "mcpServers": {+ "ai-memory": {+ "url": "http://homelab:49374/mcp?flavor=moonshot",+ "headers": { "Authorization": "Bearer secret-token" }+ }+ }+ }"#,+ &["mcpServers", "ai-memory"],+ "url",+ )+ .unwrap();++ assert_eq!(+ inferred.hook_server_url.as_deref(),+ Some("http://homelab:49374")+ );+ assert_eq!(inferred.auth_token.as_deref(), Some("secret-token"));+ }++ #[test]+ fn hook_server_url_from_mcp_url_strips_query_and_suffix() {+ for (input, expected) in [+ ("http://homelab:49374/mcp", Some("http://homelab:49374")),+ ("http://homelab:49374", Some("http://homelab:49374")),+ ("http://homelab:49374/", Some("http://homelab:49374")),+ (+ "http://homelab:49374/mcp?flavor=moonshot",+ Some("http://homelab:49374"),+ ),+ (+ "http://homelab:49374/mcp/?flavor=moonshot",+ Some("http://homelab:49374"),+ ),+ // A reverse-proxy prefix survives — hooks then POST to+ // `<prefix>/hook` under it (base_path handling).+ (+ "http://homelab:49374/wiki/mcp",+ Some("http://homelab:49374/wiki"),+ ),+ (+ "http://homelab:49374/wiki/mcp?flavor=moonshot",+ Some("http://homelab:49374/wiki"),+ ),+ ("", None),+ (" ", None),+ ] {+ assert_eq!(+ hook_server_url_from_mcp_url(input).as_deref(),+ expected,+ "input: {input:?}"+ );+ }+ }+#[test]fn codex_mcp_inference_accepts_block_form_config() {let inferred = infer_toml_mcp_config(diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rsindex e2ae4fdf..bf044b75 100644--- a/crates/ai-memory-cli/src/commands/install_mcp.rs+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs@@ -348,6 +348,29 @@ fn render_json_mcp_fragment(args: &InstallMcpArgs) -> Result<String> {Ok(serde_json::to_string_pretty(&fragment)?)}+/// Append the `flavor=moonshot` marker to the MCP endpoint URL written+/// into Kimi Code's mcp.json. Moonshot's API validates tool parameter+/// schemas against a restricted JSON Schema dialect ("moonshot flavored+/// json schema") that rejects root-level `anyOf`/`oneOf`/`allOf` —+/// including the `anyOf` issue #155 put on `memory_read_page` — and+/// fails the whole session with a 400 at `tools/list`. The ai-memory+/// server answers requests carrying this flavor with flat schemas;+/// every other client keeps the upstream shape. Idempotent so a+/// re-run (or a user-pasted already-flavored `--server-url`) doesn't+/// stack duplicate query pairs.+pub(crate) fn moonshot_flavored_mcp_url(server_url: &str) -> String {+ const FLAVOR: &str = "flavor=moonshot";+ let url = server_url.trim();+ let already_marked = url+ .split_once('?')+ .is_some_and(|(_, query)| query.split('&').any(|pair| pair == FLAVOR));+ if already_marked {+ return url.to_string();+ }+ let separator = if url.contains('?') { '&' } else { '?' };+ format!("{url}{separator}{FLAVOR}")+}+/// JSON entry shape used by Claude Code, Claude Desktop, Cursor, and/// Gemini CLI — they all accept `mcpServers.<name>` with `url` or/// `httpUrl` plus optional `headers`. Returns the per-client variant.@@ -415,8 +438,11 @@ fn build_mcp_entry(args: &InstallMcpArgs) -> Result<serde_json::Value> {McpClient::KimiCode => {// Kimi Code treats an entry with `url` and no `transport`// field as streamable-HTTP; `transport` is only for legacy- // SSE endpoints.- entry.insert("url".into(), json!(server_url));+ // SSE endpoints. The URL carries `flavor=moonshot` because+ // the Moonshot API rejects root-level schema combinators+ // (the `anyOf` on `memory_read_page`, issue #155) — the+ // server answers flavored requests with flat schemas.+ entry.insert("url".into(), json!(moonshot_flavored_mcp_url(server_url)));if let Some(b) = &bearer {entry.insert("headers".into(), json!({"Authorization": b}));}@@ -856,6 +882,9 @@ fn render_kimi_code(args: &InstallMcpArgs) -> Result<String> {#\n\# An entry with `url` and no `transport` field is a streamable-HTTP\n\# server; `transport` is only needed for legacy SSE endpoints.\n\+ # The URL carries `?flavor=moonshot` because the Moonshot API rejects\n\+ # root-level `anyOf`/`oneOf`/`allOf` in tool parameter schemas;\n\+ # ai-memory serves flat schemas to requests with this flavor.\n\{snippet}\n",snippet = render_json_mcp_fragment(args)?,))@@ -1159,9 +1188,13 @@ mod tests {// Kimi Code: `url` with NO `transport` field means streamable-HTTP// (`transport` is legacy-SSE-only there), and the URL key is plain// `url` — not Gemini's `httpUrl` or Antigravity's `serverUrl`.+ // The URL must pin `flavor=moonshot`: the Moonshot API rejects+ // root-level combinators in tool parameter schemas, so Kimi's+ // tools/list needs the server's flat-schema response.let kimi = render_for_test(McpClient::KimiCode);assert!(kimi.contains("\"mcpServers\""));assert!(kimi.contains("\"url\""));+ assert!(kimi.contains("http://127.0.0.1:49374/mcp?flavor=moonshot"));assert!(!kimi.contains("\"transport\""));assert!(!kimi.contains("\"httpUrl\""));assert!(!kimi.contains("\"serverUrl\""));@@ -1194,6 +1227,42 @@ mod tests {assert_eq!(kimi_code_home(None).unwrap(), default);}+ /// The `flavor=moonshot` marker is what makes the server answer Kimi+ /// Code's tools/list with flat (Moonshot-compatible) schemas. Pin the+ /// append rules: `?` for a bare endpoint, `&` when a query already+ /// exists, and never duplicate a marker that is already there.+ #[test]+ fn moonshot_flavored_mcp_url_appends_marker_idempotently() {+ for (input, expected) in [+ (+ "http://127.0.0.1:49374/mcp",+ "http://127.0.0.1:49374/mcp?flavor=moonshot",+ ),+ (+ "http://homelab:49374/mcp?token=abc",+ "http://homelab:49374/mcp?token=abc&flavor=moonshot",+ ),+ // A re-run (or user-pasted already-flavored --server-url)+ // must not stack a second marker.+ (+ "http://127.0.0.1:49374/mcp?flavor=moonshot",+ "http://127.0.0.1:49374/mcp?flavor=moonshot",+ ),+ (+ "http://homelab:49374/mcp?token=abc&flavor=moonshot",+ "http://homelab:49374/mcp?token=abc&flavor=moonshot",+ ),+ // A marker mentioned inside another pair's VALUE is not the+ // marker itself — match whole query pairs only.+ (+ "http://homelab:49374/mcp?note=flavor=moonshot",+ "http://homelab:49374/mcp?note=flavor=moonshot&flavor=moonshot",+ ),+ ] {+ assert_eq!(moonshot_flavored_mcp_url(input), expected, "input: {input}");+ }+ }+#[test]fn pi_apply_fails_closed_without_writing_even_with_config_override() {let tmp = tempfile::TempDir::new().unwrap();diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rsindex a7f73057..d4715c9f 100644--- a/crates/ai-memory-cli/src/commands/uninstall.rs+++ b/crates/ai-memory-cli/src/commands/uninstall.rs@@ -288,7 +288,7 @@ fn build_plan(args: &UninstallArgs) -> anyhow::Result<Vec<PlannedChange>> {let (_new, removed) = if matches!(client, Codex | Grok) {strip_mcp_toml(&content, name, url)?} else {- strip_mcp_json(&content, client, name, url)?+ strip_mcp_json_client(&content, client, name, url)?};let op = if matches!(client, Codex | Grok) {RewriteOp::McpToml@@ -941,6 +941,42 @@ fn mcp_entry_is_ours(key: &str, entry: &serde_json::Value, name: Option<&str>, ufalse}+/// URL forms uninstall should match for `client`: the endpoint as given,+/// plus — for KimiCode only — the `flavor=moonshot` form install-mcp+/// actually writes (Moonshot rejects root-level schema combinators, so+/// kimi's mcp.json points at `/mcp?flavor=moonshot` while `--mcp-url`+/// keeps the unflavored default). Every other client keeps exact-match+/// semantics.+fn mcp_url_candidates(client: McpClient, url: &str) -> Vec<String> {+ let mut candidates = vec![url.to_string()];+ if matches!(client, McpClient::KimiCode) {+ let flavored = install_mcp::moonshot_flavored_mcp_url(url);+ if !candidates.contains(&flavored) {+ candidates.push(flavored);+ }+ }+ candidates+}++/// [`strip_mcp_json`] over each of the client's URL candidate forms, so a+/// Kimi Code entry installed with the `flavor=moonshot` marker is still+/// matched by the default unflavored `--mcp-url`.+fn strip_mcp_json_client(+ content: &str,+ client: McpClient,+ name: Option<&str>,+ url: &str,+) -> Result<(String, Vec<String>)> {+ let mut new_content = content.to_string();+ let mut removed = Vec::new();+ for candidate in mcp_url_candidates(client, url) {+ let (next, mut hits) = strip_mcp_json(&new_content, client, name, &candidate)?;+ new_content = next;+ removed.append(&mut hits);+ }+ Ok((new_content, removed))+}+/// Remove ai-memory's MCP server from a JSON client config. Returns/// the new content and the names removed. Prunes the (possibly nested)/// servers object and its parents if they empty.@@ -1808,4 +1844,47 @@ command = "'/usr/local/bin/ai-memory' hook --event stop --agent kimi-code --servassert!(v["mcpServers"].get("ai-memory").is_none());assert!(v["mcpServers"].get("other").is_some());}++ #[test]+ fn mcp_url_candidates_adds_moonshot_flavor_for_kimi_code_only() {+ assert_eq!(+ mcp_url_candidates(McpClient::KimiCode, "http://127.0.0.1:49374/mcp"),+ vec![+ "http://127.0.0.1:49374/mcp".to_string(),+ "http://127.0.0.1:49374/mcp?flavor=moonshot".to_string()+ ]+ );+ // An already-flavored --mcp-url must not stack a duplicate.+ assert_eq!(+ mcp_url_candidates(+ McpClient::KimiCode,+ "http://127.0.0.1:49374/mcp?flavor=moonshot"+ ),+ vec!["http://127.0.0.1:49374/mcp?flavor=moonshot".to_string()]+ );+ // Every other client keeps exact-match semantics.+ assert_eq!(+ mcp_url_candidates(McpClient::Cursor, "http://127.0.0.1:49374/mcp"),+ vec!["http://127.0.0.1:49374/mcp".to_string()]+ );+ }++ /// Regression: install-mcp writes kimi's entry with the+ /// `?flavor=moonshot` marker, while `--mcp-url` keeps the unflavored+ /// default — the exact-match strip must still find the entry.+ #[test]+ fn strip_mcp_kimi_code_matches_flavored_url_with_default_mcp_url() {+ let content = r#"{"mcpServers":{"ai-memory":{"url":"http://127.0.0.1:49374/mcp?flavor=moonshot","headers":{"X-Token":"t"}},"other":{"url":"http://x"}}}"#;+ let (out, removed) = strip_mcp_json_client(+ content,+ McpClient::KimiCode,+ Some("ai-memory"),+ "http://127.0.0.1:49374/mcp",+ )+ .unwrap();+ assert_eq!(removed, vec!["ai-memory".to_string()]);+ let v: serde_json::Value = serde_json::from_str(&out).unwrap();+ assert!(v["mcpServers"].get("ai-memory").is_none());+ assert!(v["mcpServers"].get("other").is_some());+ }}diff --git a/crates/ai-memory-mcp/Cargo.toml b/crates/ai-memory-mcp/Cargo.tomlindex 6bf0310a..e206f350 100644--- a/crates/ai-memory-mcp/Cargo.toml+++ b/crates/ai-memory-mcp/Cargo.toml@@ -27,6 +27,7 @@ tracing.workspace = truermcp.workspace = trueschemars.workspace = trueaxum.workspace = true+http.workspace = true# Time gap calculation for `memory_explore` (parse stored ISO-8601# timestamps + delta against now). The rest of the crate doesn't# need a clock dep.diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rsindex c618c81c..c3ff9f5b 100644--- a/crates/ai-memory-mcp/src/server.rs+++ b/crates/ai-memory-mcp/src/server.rs@@ -19,9 +19,13 @@ use ai_memory_wiki::{Wiki, WikiError, WritePageRequest};use rmcp::handler::server::router::tool::ToolRouter;use rmcp::handler::server::wrapper::Parameters;use rmcp::model::{- CallToolResult, Content, Implementation, ProtocolVersion, ServerCapabilities, ServerInfo,+ CallToolResult, Content, Implementation, ListToolsResult, PaginatedRequestParams,+ ProtocolVersion, ServerCapabilities, ServerInfo, Tool,+};+use rmcp::service::RequestContext;+use rmcp::{+ ErrorData as McpError, RoleServer, ServerHandler, schemars, tool, tool_handler, tool_router,};-use rmcp::{ErrorData as McpError, ServerHandler, schemars, tool, tool_handler, tool_router};use serde::{Deserialize, Serialize};const HANDOFF_SUMMARY_MAX_CHARS: usize = 3_000;@@ -655,6 +659,11 @@ struct ExploreArgs {// `required` with `path: null` and still hit the runtime error. Encoding// it here lets schema-respecting clients refuse the invalid call before// it ever reaches the server.+//+// NOTE(kimi-code): Moonshot ("moonshot flavored json schema") rejects+// this root-level `anyOf`, so Kimi Code sessions get a patched schema+// without it — see `moonshot_safe_tool_list`. Every other client keeps+// receiving this exact shape.#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]#[schemars(extend("anyOf" = [{"required": ["path"], "properties": {"path": {"type": "string"}}},@@ -2519,6 +2528,68 @@ impl ServerHandler for AiMemoryServer {.with_protocol_version(ProtocolVersion::V_2024_11_05).with_instructions(MEMORY_INSTRUCTIONS.to_string())}++ // Declaring `list_tools` here makes the `#[tool_handler]` macro skip+ // its generated version (rmcp-macros only emits methods that are+ // missing), so the flavor patch below runs on every tools/list.+ async fn list_tools(+ &self,+ _request: Option<PaginatedRequestParams>,+ context: RequestContext<RoleServer>,+ ) -> Result<ListToolsResult, McpError> {+ let tools = self.tool_router.list_all();+ // rmcp's streamable-HTTP transport injects the request's+ // `http::request::Parts` into the extensions of every request in+ // both stateless and stateful modes, which is how the flavor+ // marker survives even when no peer clientInfo is available.+ let moonshot = context+ .extensions+ .get::<http::request::Parts>()+ .and_then(|parts| parts.uri.query())+ .is_some_and(|query| query.split('&').any(|pair| pair == "flavor=moonshot"));+ if moonshot {+ Ok(ListToolsResult::with_all_items(moonshot_safe_tool_list(+ tools,+ )))+ } else {+ Ok(ListToolsResult::with_all_items(tools))+ }+ }+}++/// Moonshot ("moonshot flavored json schema") rejects any root-level+/// `anyOf`/`oneOf`/`allOf` in tool parameter schemas — the `anyOf` that+/// issue #155 added to `memory_read_page` included — failing the whole+/// session with a 400 at `tools/list` time. Requests carrying the+/// `?flavor=moonshot` marker (the URL `install-mcp --client kimi-code`+/// writes) therefore get a copy of the tool list with those three+/// root keys stripped; nested combinators are left alone because the+/// rejection is specific to the schema root, and every other client+/// keeps receiving the exact upstream shape.+///+/// The path/query contract that `anyOf` encoded stays enforced by the+/// runtime handler validation, and the field descriptions still spell+/// it out — the guard loss is confined to the one client that cannot+/// parse it.+fn moonshot_safe_tool_list(tools: Vec<Tool>) -> Vec<Tool> {+ const ROOT_COMBINATORS: [&str; 3] = ["anyOf", "oneOf", "allOf"];+ tools+ .into_iter()+ .map(|mut tool| {+ if !ROOT_COMBINATORS+ .iter()+ .any(|key| tool.input_schema.contains_key(*key))+ {+ return tool;+ }+ let mut schema = (*tool.input_schema).clone();+ for key in ROOT_COMBINATORS {+ schema.shift_remove(key);+ }+ tool.input_schema = Arc::new(schema);+ tool+ })+ .collect()}impl AiMemoryServer {@@ -4470,6 +4541,67 @@ mod tests {}}+ // Kimi Code: Moonshot rejects root-level combinators in tool+ // parameter schemas ("moonshot flavored json schema"), so requests+ // marked `?flavor=moonshot` get a patched tool list. Pins what the+ // patch strips and — just as important — what it preserves.+ #[test]+ fn moonshot_safe_tool_list_strips_root_combinators_only() {+ let schema: serde_json::Map<String, serde_json::Value> =+ serde_json::from_value(serde_json::json!({+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "ReadPageArgs",+ "type": "object",+ "description": "Read one wiki page.",+ "properties": {+ "path": { "type": "string", "description": "Exact wiki path" },+ // A NESTED combinator must survive: Moonshot's+ // rejection is specific to the schema root.+ "query": { "anyOf": [{ "type": "string" }, { "type": "null" }] }+ },+ "anyOf": [{ "required": ["path"] }, { "required": ["query"] }],+ "oneOf": [{ "required": ["path"] }],+ "allOf": [{ "required": ["query"] }]+ }))+ .unwrap();+ let tool = Tool::new("memory_read_page", "Read a wiki page", schema);++ let patched = moonshot_safe_tool_list(vec![tool]);+ let out = &patched[0].input_schema;++ for key in ["anyOf", "oneOf", "allOf"] {+ assert!(+ !out.contains_key(key),+ "root `{key}` must be stripped: {out:?}"+ );+ }+ for key in ["$schema", "title", "type", "description", "properties"] {+ assert!(out.contains_key(key), "root `{key}` must survive: {out:?}");+ }+ assert_eq!(+ out["properties"]["query"]["anyOf"],+ serde_json::json!([{ "type": "string" }, { "type": "null" }]),+ "nested combinators are out of scope for the patch"+ );+ }++ #[test]+ fn moonshot_safe_tool_list_leaves_flat_tools_untouched() {+ let schema: serde_json::Map<String, serde_json::Value> =+ serde_json::from_value(serde_json::json!({+ "type": "object",+ "properties": { "verbose": { "type": "boolean" } }+ }))+ .unwrap();+ let tool = Tool::new("memory_status", "Status counts", schema);+ let before = serde_json::to_value(&tool).unwrap();++ let patched = moonshot_safe_tool_list(vec![tool]);+ let after = serde_json::to_value(&patched[0]).unwrap();++ assert_eq!(before, after, "flat tools must pass through unchanged");+ }+// Issue #155: the neither-arg error must teach a looping model what a// valid retry looks like, naming both args and a concrete example.#[tokio::test]diff --git a/crates/ai-memory-mcp/tests/mcp_stateless_http.rs b/crates/ai-memory-mcp/tests/mcp_stateless_http.rsindex 6802ac0f..818b08ea 100644--- a/crates/ai-memory-mcp/tests/mcp_stateless_http.rs+++ b/crates/ai-memory-mcp/tests/mcp_stateless_http.rs@@ -26,6 +26,7 @@ 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":{}}}"#;+const TOOLS_LIST: &str = r#"{"jsonrpc":"2.0","id":3,"method":"tools/list","params":{}}"#;/// Build a `/mcp` router exactly like `serve.rs` does, toggling stateful/// mode. Returns the `Store` too so the writer actor stays alive for the@@ -58,9 +59,15 @@ async fn make_router(tmp: &TempDir, stateful: bool) -> (Router, Store) {/// Streamable HTTP client sends (both JSON and event-stream), and no/// session id.fn post(body: &'static str) -> Request<Body> {+ post_to("/mcp", body)+}++/// Same as [`post`] but against an explicit URI, so tests can carry the+/// `?flavor=moonshot` marker Kimi Code's installed URL uses.+fn post_to(uri: &str, body: &'static str) -> Request<Body> {Request::builder().method("POST")- .uri("/mcp")+ .uri(uri)// 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.@@ -159,3 +166,74 @@ async fn stateful_tools_call_without_session_is_rejected() {"stateful rejection should mention the missing initialize: {body}");}++/// Extract `memory_read_page`'s inputSchema from a tools/list JSON-RPC+/// response body — the one tool whose root `anyOf` (issue #155) decides+/// whether a Moonshot-flavored client can list tools at all.+fn read_page_input_schema(body: &str) -> serde_json::Value {+ let json: serde_json::Value = serde_json::from_str(body)+ .unwrap_or_else(|e| panic!("tools/list response must be JSON, got: {body}\nerr: {e}"));+ let tools = json["result"]["tools"]+ .as_array()+ .unwrap_or_else(|| panic!("missing result.tools: {body}"));+ tools+ .iter()+ .find(|tool| tool["name"] == "memory_read_page")+ .unwrap_or_else(|| panic!("memory_read_page missing from tools/list: {body}"))[+ "inputSchema"+ ]+ .clone()+}++/// The real Kimi Code flow: `initialize` and `tools/list` as independent+/// POSTs (stateless — no session id) against `/mcp?flavor=moonshot`, the+/// URL `install-mcp --client kimi-code` writes. The Moonshot API rejects+/// tool parameter schemas with root-level `anyOf`/`oneOf`/`allOf`, so+/// the flavored tools/list must return `memory_read_page` without them+/// while keeping the rest of the schema intact.+#[tokio::test]+async fn stateless_moonshot_flavor_strips_root_any_of() {+ let tmp = TempDir::new().unwrap();+ let (router, _store) = make_router(&tmp, false).await;++ let init = router+ .clone()+ .oneshot(post_to("/mcp?flavor=moonshot", INITIALIZE))+ .await+ .unwrap();+ assert_eq!(init.status(), StatusCode::OK);++ let resp = router+ .oneshot(post_to("/mcp?flavor=moonshot", 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(),+ "moonshot flavor must strip root `{key}`: {schema}"+ );+ }+ assert!(+ schema.get("properties").is_some(),+ "the flat schema must keep describing the args: {schema}"+ );+}++/// Control: without the flavor marker the SAME tools/list keeps the+/// upstream schema shape, root `anyOf` included — every other client is+/// unaffected by the Kimi Code workaround.+#[tokio::test]+async fn stateless_tools_list_without_flavor_keeps_root_any_of() {+ let tmp = TempDir::new().unwrap();+ let (router, _store) = make_router(&tmp, false).await;++ let resp = router.oneshot(post(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(),+ "unflavored tools/list must keep the upstream root anyOf: {schema}"+ );+}diff --git a/docs/install.md b/docs/install.mdindex 50c2d150..8c28dd99 100644--- a/docs/install.md+++ b/docs/install.md@@ -580,7 +580,11 @@ so those events are still captured. A payload-provided value always wins.Kimi Code keeps MCP servers in `~/.kimi-code/mcp.json` and lifecycle hooks in`~/.kimi-code/config.toml`; both move together when `$KIMI_CODE_HOME` is set.-The CLI also accepts `--agent kimi` as an alias.+The CLI also accepts `--agent kimi` as an alias. `install-mcp` writes the+server URL with a `?flavor=moonshot` query because the Moonshot API rejects+root-level `anyOf`/`oneOf`/`allOf` in tool parameter schemas ("moonshot+flavored json schema") — the ai-memory server answers flavored requests with+flat schemas, and all other clients keep the upstream shape.```bashai-memory install-mcp --client kimi-code --apply \diff --git a/docs/mcp-install.md b/docs/mcp-install.mdindex c5b1dedb..c4462fb6 100644--- a/docs/mcp-install.md+++ b/docs/mcp-install.md@@ -596,13 +596,22 @@ which merges:{"mcpServers": {"ai-memory": {- "url": "http://homelab:49374/mcp",+ "url": "http://homelab:49374/mcp?flavor=moonshot","headers": { "Authorization": "Bearer <token>" }}}}```+`install-mcp` appends the `?flavor=moonshot` query itself (idempotently, so+re-runs don't duplicate it). The Moonshot API validates tool parameter+schemas against a restricted dialect ("moonshot flavored json schema") that+rejects root-level `anyOf`/`oneOf`/`allOf` combinators — including the+`anyOf` on `memory_read_page` — and fails the whole session with a 400 at+`tools/list`. The ai-memory server answers requests carrying this flavor+with flat schemas; every other client keeps receiving the upstream schemas+unchanged.+**Config file (hooks):** `~/.kimi-code/config.toml` (same `$KIMI_CODE_HOME`base). Kimi Code stores hooks as `[[hooks]]` array entries in the same TOMLfile that holds its provider/model settings; `install-hooks` merges@@ -626,6 +635,9 @@ same pattern as Gemini CLI.**Gotchas:**- Do not add a `transport` field for HTTP servers: `url` alone meansstreamable HTTP; `transport: "sse"` selects the legacy SSE transport.+- Do not strip the `?flavor=moonshot` query from the installed URL: without+ it the Moonshot API rejects `memory_read_page`'s root `anyOf` and every+ session fails at `tools/list`.- Hook entries accept only `event`, `matcher`, `command`, and `timeout`(seconds, 1-600, default 30). Any extra field makes Kimi Code fail to loadthe entire `config.toml`, so prefer `install-hooks --apply` over hand