Skip to content

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

Rust

style(comments): trim kimi-code additions to rationale only

Lucas Oliveira876a81b5e94a
diff --git a/crates/ai-memory-cli/src/commands/install_hooks.rs b/crates/ai-memory-cli/src/commands/install_hooks.rs
index 312053d9..958e66eb 100644
--- a/crates/ai-memory-cli/src/commands/install_hooks.rs
+++ b/crates/ai-memory-cli/src/commands/install_hooks.rs
@@ -673,11 +673,9 @@ fn expand_grok_placeholders_with(
}
fn hook_server_url_from_mcp_url(url: &str) -> Option<String> {
- // 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.
+ // Drop query/fragment BEFORE the `/mcp` peel: Kimi Code's
+ // `?flavor=moonshot` marker must never leak into hook URLs (and it
+ // would stop the suffix from matching).
let base = url
.trim()
.split(['?', '#'])
@@ -3685,11 +3683,8 @@ 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.
+ /// Inferring the hook URL from Kimi Code's flavored mcp.json entry
+ /// must yield the bare origin — hooks POST to `<origin>/hook`.
#[test]
fn kimi_code_mcp_inference_strips_flavor_query_and_mcp_path() {
let inferred = infer_json_mcp_config(
@@ -3727,8 +3722,7 @@ mod tests {
"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).
+ // Reverse-proxy prefix survives; hooks POST under it.
(
"http://homelab:49374/wiki/mcp",
Some("http://homelab:49374/wiki"),
diff --git a/crates/ai-memory-cli/src/commands/install_mcp.rs b/crates/ai-memory-cli/src/commands/install_mcp.rs
index bf044b75..8fc49a64 100644
--- a/crates/ai-memory-cli/src/commands/install_mcp.rs
+++ b/crates/ai-memory-cli/src/commands/install_mcp.rs
@@ -348,16 +348,11 @@ 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.
+/// Append the `flavor=moonshot` marker to the MCP URL written into Kimi
+/// Code's mcp.json: Moonshot's API 400s root-level `anyOf`/`oneOf`/`allOf`
+/// in tool parameter schemas (issue #155's `anyOf` on `memory_read_page`),
+/// and the server answers flavored requests with flat schemas. Idempotent
+/// so re-runs never 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();
@@ -438,10 +433,7 @@ 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. 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.
+ // SSE endpoints.
entry.insert("url".into(), json!(moonshot_flavored_mcp_url(server_url)));
if let Some(b) = &bearer {
entry.insert("headers".into(), json!({"Authorization": b}));
@@ -882,9 +874,8 @@ 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\
+ # `?flavor=moonshot`: Moonshot's API rejects root-level schema\n\
+ # combinators; ai-memory serves flat schemas to flavored requests.\n\
{snippet}\n",
snippet = render_json_mcp_fragment(args)?,
))
@@ -1188,9 +1179,6 @@ 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\""));
@@ -1227,10 +1215,8 @@ 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.
+ /// Pin the append rules: `?` on a bare endpoint, `&` with an existing
+ /// query, never duplicate an existing marker.
#[test]
fn moonshot_flavored_mcp_url_appends_marker_idempotently() {
for (input, expected) in [
@@ -1242,8 +1228,6 @@ mod tests {
"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",
@@ -1252,8 +1236,7 @@ mod tests {
"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.
+ // Whole-pair match: a marker inside another pair's VALUE doesn't count.
(
"http://homelab:49374/mcp?note=flavor=moonshot",
"http://homelab:49374/mcp?note=flavor=moonshot&flavor=moonshot",
diff --git a/crates/ai-memory-cli/src/commands/uninstall.rs b/crates/ai-memory-cli/src/commands/uninstall.rs
index d4715c9f..e8c16420 100644
--- a/crates/ai-memory-cli/src/commands/uninstall.rs
+++ b/crates/ai-memory-cli/src/commands/uninstall.rs
@@ -941,12 +941,10 @@ fn mcp_entry_is_ours(key: &str, entry: &serde_json::Value, name: Option<&str>, u
false
}
-/// 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.
+/// URL forms uninstall matches for `client`: the endpoint as given, plus
+/// for KimiCode the `flavor=moonshot` form install-mcp actually writes
+/// (`--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) {
@@ -958,9 +956,7 @@ fn mcp_url_candidates(client: McpClient, url: &str) -> Vec<String> {
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`.
+/// [`strip_mcp_json`] over each URL candidate form of the client.
fn strip_mcp_json_client(
content: &str,
client: McpClient,
@@ -1854,7 +1850,6 @@ command = "'/usr/local/bin/ai-memory' hook --event stop --agent kimi-code --serv
"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,
@@ -1862,16 +1857,14 @@ command = "'/usr/local/bin/ai-memory' hook --event stop --agent kimi-code --serv
),
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.
+ /// install-mcp writes the flavored URL while `--mcp-url` defaults
+ /// unflavored — the strip must still match.
#[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"}}}"#;
diff --git a/crates/ai-memory-hooks/src/payload.rs b/crates/ai-memory-hooks/src/payload.rs
index 4f1e4a98..4dd16c11 100644
--- a/crates/ai-memory-hooks/src/payload.rs
+++ b/crates/ai-memory-hooks/src/payload.rs
@@ -571,11 +571,9 @@ fn best_title_hint(event: HookEvent, raw: &serde_json::Value) -> Option<String>
match event {
HookEvent::SessionStart => extract_string(raw, &["model", "title"]),
HookEvent::UserPrompt => {
- // `extract_content` (not `extract_string`): Kimi Code sends
- // `prompt` as content blocks (`[{"type":"text","text":...}]`),
- // which only `value_to_text` flattens — plain-string agents
- // (Claude Code et al.) get the identical value back, so this
- // widens coverage without changing their behaviour.
+ // Kimi Code sends `prompt` as content blocks
+ // (`[{"type":"text","text":...}]`); `extract_content` flattens
+ // them and returns identical values for plain-string agents.
extract_content(raw, &["prompt", "message", "text"]).map(|s| truncate_for_title(&s))
}
HookEvent::PreToolUse | HookEvent::PostToolUse => {
@@ -1293,10 +1291,8 @@ mod tests {
assert!(title.ends_with('…'));
}
- /// Kimi Code sends `prompt` as Anthropic-style content blocks, not a
- /// plain string. The title hint must flatten them exactly like the
- /// body excerpt does, or the observation title degrades to the bare
- /// event kind while the body holds the actual prompt.
+ /// Kimi Code's content-block `prompt` must flatten into the title
+ /// exactly like the body excerpt does.
#[test]
fn user_prompt_title_flattens_kimi_code_content_blocks() {
let q = HookQuery {
diff --git a/crates/ai-memory-mcp/src/server.rs b/crates/ai-memory-mcp/src/server.rs
index c3ff9f5b..71505262 100644
--- a/crates/ai-memory-mcp/src/server.rs
+++ b/crates/ai-memory-mcp/src/server.rs
@@ -660,10 +660,9 @@ struct ExploreArgs {
// 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.
+// Moonshot ("moonshot flavored json schema") rejects this root-level
+// `anyOf`; Kimi Code sessions get a patched schema instead
+// (`moonshot_safe_tool_list`). Every other client keeps this exact shape.
#[derive(Debug, Serialize, Deserialize, schemars::JsonSchema)]
#[schemars(extend("anyOf" = [
{"required": ["path"], "properties": {"path": {"type": "string"}}},
@@ -2529,19 +2528,17 @@ impl ServerHandler for AiMemoryServer {
.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.
+ // Declared manually so `#[tool_handler]` skips its generated
+ // `list_tools` and the flavor patch 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.
+ // 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 moonshot = context
.extensions
.get::<http::request::Parts>()
@@ -2557,20 +2554,12 @@ impl ServerHandler for AiMemoryServer {
}
}
-/// 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.
+/// Moonshot ("moonshot flavored json schema") rejects root-level
+/// `anyOf`/`oneOf`/`allOf` in tool parameter schemas with a 400 at
+/// `tools/list` time. Requests marked `?flavor=moonshot` (the URL
+/// `install-mcp --client kimi-code` writes) get the tool list with
+/// those root keys stripped; nested combinators stay, and the handlers'
+/// runtime validation still enforces the arg contracts.
fn moonshot_safe_tool_list(tools: Vec<Tool>) -> Vec<Tool> {
const ROOT_COMBINATORS: [&str; 3] = ["anyOf", "oneOf", "allOf"];
tools
@@ -4541,10 +4530,7 @@ 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.
+ // Pins what the patch strips (root combinators) and what it preserves.
#[test]
fn moonshot_safe_tool_list_strips_root_combinators_only() {
let schema: serde_json::Map<String, serde_json::Value> =
@@ -4555,8 +4541,7 @@ mod tests {
"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.
+ // Nested combinator: must survive (rejection is root-specific).
"query": { "anyOf": [{ "type": "string" }, { "type": "null" }] }
},
"anyOf": [{ "required": ["path"] }, { "required": ["query"] }],
diff --git a/crates/ai-memory-mcp/tests/mcp_stateless_http.rs b/crates/ai-memory-mcp/tests/mcp_stateless_http.rs
index 818b08ea..d6b42350 100644
--- a/crates/ai-memory-mcp/tests/mcp_stateless_http.rs
+++ b/crates/ai-memory-mcp/tests/mcp_stateless_http.rs
@@ -62,8 +62,7 @@ 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.
+/// [`post`] against an explicit URI (tests carrying `?flavor=moonshot`).
fn post_to(uri: &str, body: &'static str) -> Request<Body> {
Request::builder()
.method("POST")
@@ -167,9 +166,7 @@ async fn stateful_tools_call_without_session_is_rejected() {
);
}
-/// 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.
+/// Pull `memory_read_page`'s inputSchema from a tools/list response body.
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}"));
@@ -185,12 +182,9 @@ fn read_page_input_schema(body: &str) -> serde_json::Value {
.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.
+/// Kimi Code's real flow: independent stateless POSTs against
+/// `/mcp?flavor=moonshot` must return `memory_read_page` without root
+/// combinators, the rest of the schema intact.
#[tokio::test]
async fn stateless_moonshot_flavor_strips_root_any_of() {
let tmp = TempDir::new().unwrap();
@@ -221,9 +215,7 @@ async fn stateless_moonshot_flavor_strips_root_any_of() {
);
}
-/// 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.
+/// Control: without the marker, tools/list keeps the upstream root `anyOf`.
#[tokio::test]
async fn stateless_tools_list_without_flavor_keeps_root_any_of() {
let tmp = TempDir::new().unwrap();
diff --git a/scripts/install-hooks.sh b/scripts/install-hooks.sh
index 80e2219a..337563f4 100755
--- a/scripts/install-hooks.sh
+++ b/scripts/install-hooks.sh
@@ -91,9 +91,8 @@ SCRIPTS=(
"session-end"
)
-# kimi-code hooks also cover the subagent lifecycle: its on-disk bundle
-# mirrors hooks/claude-code/ (which ships subagent-start/stop), while the
-# default SCRIPTS list above omits them — so they are appended only here.
+# kimi-code also captures the subagent lifecycle (its bundle mirrors
+# hooks/claude-code/, which ships them); the default list omits them.
if [[ "$AGENT" == "kimi-code" ]]; then
SCRIPTS+=("subagent-start" "subagent-stop")
fi