Skip to main content

mnemo_engine/
mcp.rs

1//! Hand-rolled Model Context Protocol (MCP) stdio server for MNemo.
2//!
3//! Exposes a `.mnemo` file as an MCP server so any MCP-compatible agent
4//! (Claude Desktop, Cursor, mcp-server, custom clients) can drive it as a
5//! tool. Framed as **JSON-RPC 2.0 with newline-delimited JSON** over
6//! stdin/stdout, per the MCP spec. Stderr is used for human-readable
7//! diagnostics only — never for protocol traffic.
8//!
9//! ## Why hand-rolled
10//!
11//! The official [`rmcp`](https://crates.io/crates/rmcp) SDK declares
12//! `edition = "2024"` on its workspace, which requires Rust 1.85+; our
13//! MSRV is 1.75 and locked (transitive deps pin us). `rmcp` also brings
14//! in tokio + async, a big architectural shift for a sync-only core.
15//! Hand-rolling stdio JSON-RPC is ~250 LoC and adds zero dependencies
16//! beyond `serde_json` (already a dep). See CHANGELOG's Phase 4 entry
17//! for the decision record.
18//!
19//! ## Protocol version
20//!
21//! We advertise MCP protocol `2025-06-18` on `initialize`. If a client
22//! requests a different version we echo their version back — the standard
23//! compatibility dance. The seven tools we expose are stable across
24//! recent protocol revisions.
25//!
26//! ## Tools
27//!
28//! - `about` — read-only briefing (manifest + onboarding memories)
29//! - `remember` — insert a memory (BYO vector; embedder integration deferred to Phase 3)
30//! - `recall` — vector recall (BYO query vector)
31//! - `forget` — delete by ULID
32//! - `list` — enumerate live memories
33//! - `snapshot_list` — enumerate PITR snapshots
34//! - `stats` — database statistics
35//!
36//! Every mutation calls `Mnemo::flush()` before returning success — MCP
37//! clients treat tool calls as atomic and expect on-disk durability.
38//!
39//! ## Passphrase
40//!
41//! Read from the `MNEMO_PASSPHRASE` environment variable only.
42//! `serve_stdio` refuses to start without it. There is no CLI-flag
43//! fallback here — that would leave the passphrase in shell history
44//! and process listings.
45
46use std::io::{BufRead, BufReader, Read, Write};
47use std::path::Path;
48
49use serde::{Deserialize, Serialize};
50use serde_json::{json, Map, Value};
51
52use crate::error::{MnemoError, Result};
53use crate::memory::{Memory, MemoryType, Metric, Scope};
54use crate::result_cache::{CachePutOpts, SemanticCachePutOpts, DEFAULT_SEMANTIC_THRESHOLD};
55use crate::store::{Mnemo, RecallRequest};
56
57/// MCP protocol version we advertise on `initialize`.
58const PROTOCOL_VERSION: &str = "2025-06-18";
59
60/// Environment variable that supplies the database passphrase.
61const PASSPHRASE_ENV: &str = "MNEMO_PASSPHRASE";
62
63/// Fuzz-target helper: parse a single JSON-RPC line as a `Request` and
64/// discard. Panic-free — malformed input returns `Err(String)`, valid
65/// requests return `Ok(())`. Exposed only via `crate::__fuzz`; not part
66/// of the stable public API.
67#[doc(hidden)]
68pub fn __fuzz_parse_request_line(line: &str) -> std::result::Result<(), String> {
69    serde_json::from_str::<Request>(line)
70        .map(|_| ())
71        .map_err(|e| e.to_string())
72}
73
74// --- JSON-RPC 2.0 wire types ---------------------------------------------
75
76/// Incoming JSON-RPC 2.0 request or notification (a notification is a
77/// request with no `id`).
78#[derive(Debug, Deserialize)]
79struct Request {
80    #[serde(default)]
81    jsonrpc: String,
82    #[serde(default)]
83    id: Option<Value>,
84    method: String,
85    #[serde(default)]
86    params: Value,
87}
88
89/// Outgoing JSON-RPC 2.0 response envelope.
90#[derive(Debug, Serialize)]
91struct Response {
92    jsonrpc: &'static str,
93    id: Value,
94    #[serde(skip_serializing_if = "Option::is_none")]
95    result: Option<Value>,
96    #[serde(skip_serializing_if = "Option::is_none")]
97    error: Option<RpcError>,
98}
99
100/// JSON-RPC 2.0 error object.
101#[derive(Debug, Serialize)]
102struct RpcError {
103    code: i32,
104    message: String,
105    #[serde(skip_serializing_if = "Option::is_none")]
106    data: Option<Value>,
107}
108
109impl RpcError {
110    fn new(code: i32, message: impl Into<String>) -> Self {
111        Self {
112            code,
113            message: message.into(),
114            data: None,
115        }
116    }
117}
118
119// Standard JSON-RPC error codes.
120const PARSE_ERROR: i32 = -32700;
121const INVALID_REQUEST: i32 = -32600;
122const METHOD_NOT_FOUND: i32 = -32601;
123const INVALID_PARAMS: i32 = -32602;
124const INTERNAL_ERROR: i32 = -32603;
125
126// --- Entry point ---------------------------------------------------------
127
128/// Run the MCP stdio server over the provided `.mnemo` file.
129///
130/// Blocks the calling thread — reads JSON-RPC requests line-by-line from
131/// stdin, dispatches to the tool implementations, writes responses to
132/// stdout, and logs diagnostics to stderr. Returns when stdin closes
133/// (typical MCP client shutdown) or on a fatal I/O error.
134///
135/// The passphrase is read from the `MNEMO_PASSPHRASE` environment
136/// variable. If unset, returns [`MnemoError::Invalid`] without opening
137/// the file.
138pub fn serve_stdio(path: &Path) -> Result<()> {
139    serve_stdio_with_embedder(path, None)
140}
141
142/// Variant that optionally registers an [`crate::EmbedCmd`] embedder on
143/// the handle at server start (Phase 3 PR 10b). The MCP `remember`,
144/// `recall`, `cache_put_semantic` and `cache_get_semantic` tools then
145/// accept a `text` param as an alternative to the explicit vector —
146/// the embedder runs once per request against the persistent child
147/// process. Pass `None` for the pre-Phase-3 vector-only behavior.
148///
149/// `embed_spec` tuple fields: `(command, name, normalize)`. See
150/// [`crate::EmbedCmd::new`] for the command format.
151pub fn serve_stdio_with_embedder(
152    path: &Path,
153    embed_spec: Option<(String, String, bool, std::time::Duration)>,
154) -> Result<()> {
155    let stdin = std::io::stdin();
156    let stdout = std::io::stdout();
157    serve_with_streams(path, stdin.lock(), stdout.lock(), embed_spec)
158}
159
160/// Run the MCP loop against explicit reader/writer streams. Extracted so
161/// integration tests can pipe scripted input without touching the real
162/// stdin/stdout. `embed_spec` is as in [`serve_stdio_with_embedder`].
163pub fn serve_with_streams<R: Read, W: Write>(
164    path: &Path,
165    reader: R,
166    mut writer: W,
167    embed_spec: Option<(String, String, bool, std::time::Duration)>,
168) -> Result<()> {
169    let passphrase = std::env::var(PASSPHRASE_ENV).map_err(|_| {
170        MnemoError::Invalid(format!(
171            "{PASSPHRASE_ENV} is required to serve — set it in the shell before starting"
172        ))
173    })?;
174
175    eprintln!(
176        "mnemo mcp: opening {} (protocol {PROTOCOL_VERSION})",
177        path.display()
178    );
179    let mut db = Mnemo::open(path, &passphrase)?;
180    if let Some((cmd, name, normalize, timeout)) = embed_spec {
181        let identity = crate::EmbedderIdentity {
182            name,
183            dimensions: db.dimensions(),
184            normalize,
185        };
186        let embedder = crate::EmbedCmd::new(&cmd, identity)?.with_timeout(timeout);
187        db.set_embedder(embedder)?;
188        eprintln!(
189            "mnemo mcp: embedder ready (text params accepted, timeout {}s)",
190            timeout.as_secs()
191        );
192    }
193    eprintln!("mnemo mcp: ready ({} live memories)", db.len());
194
195    let reader = BufReader::new(reader);
196    for line in reader.lines() {
197        let line = line.map_err(MnemoError::Io)?;
198        let trimmed = line.trim();
199        if trimmed.is_empty() {
200            continue;
201        }
202
203        let (id, out) = match serde_json::from_str::<Request>(trimmed) {
204            Ok(req) => {
205                let id = req.id.clone();
206                let is_notification = id.is_none();
207                let result = handle(&mut db, &req);
208                if is_notification {
209                    // Per JSON-RPC 2.0: notifications get no response.
210                    continue;
211                }
212                (id.unwrap_or(Value::Null), result)
213            }
214            Err(e) => (
215                Value::Null,
216                Err(RpcError::new(PARSE_ERROR, format!("parse error: {e}"))),
217            ),
218        };
219
220        let resp = match out {
221            Ok(value) => Response {
222                jsonrpc: "2.0",
223                id,
224                result: Some(value),
225                error: None,
226            },
227            Err(err) => Response {
228                jsonrpc: "2.0",
229                id,
230                result: None,
231                error: Some(err),
232            },
233        };
234
235        let line =
236            serde_json::to_string(&resp).map_err(|e| MnemoError::Serialize(e.to_string()))?;
237        writeln!(writer, "{line}").map_err(MnemoError::Io)?;
238        writer.flush().map_err(MnemoError::Io)?;
239    }
240    // Scoring v2 (v0.7.0) flipped `tool_recall` to `track_access(true)`:
241    // every recall bumps `accessed_at` / `access_count` in the catalog
242    // in memory (no per-call fsync). The previous `db.flush()` only
243    // fired on each mutating tool call's exit path, so a session that
244    // issued only `recall` / `about` / `stats` / `list` /
245    // `cache_get_semantic`-on-hit calls (read-shaped) would exit with
246    // every one of its access-stat bumps still in RAM, discarded on
247    // shutdown. Flush at shutdown so a read-only session persists its
248    // access stats too — the write is cheap (catalog page only; the
249    // record bodies aren't dirty) and guarantees the usage-saturation
250    // signal survives across sessions.
251    // PERF-1 (R-004.3): `close()` also persists the ANN index, which plain
252    // flushes now write only every so often.
253    if let Err(e) = db.close() {
254        eprintln!("mnemo mcp: flush on shutdown failed: {e}");
255    }
256    eprintln!("mnemo mcp: stdin closed, shutting down");
257    Ok(())
258}
259
260// --- Dispatch ------------------------------------------------------------
261
262/// Route a request to a method handler. Returns either the `result`
263/// payload for a JSON-RPC success or an [`RpcError`] for a failure.
264fn handle(db: &mut Mnemo, req: &Request) -> std::result::Result<Value, RpcError> {
265    if req.jsonrpc != "2.0" {
266        return Err(RpcError::new(
267            INVALID_REQUEST,
268            format!("expected jsonrpc \"2.0\", got {:?}", req.jsonrpc),
269        ));
270    }
271    match req.method.as_str() {
272        "initialize" => Ok(initialize_result(&req.params)),
273        "notifications/initialized" | "notifications/cancelled" => Ok(Value::Null),
274        "ping" => Ok(json!({})),
275        "tools/list" => Ok(tools_list()),
276        "tools/call" => tools_call(db, &req.params),
277        other => Err(RpcError::new(
278            METHOD_NOT_FOUND,
279            format!("method '{other}' not implemented"),
280        )),
281    }
282}
283
284/// Echo the client's requested protocol version if present; fall back to
285/// ours. Always advertise the same `serverInfo` and `capabilities` block.
286fn initialize_result(params: &Value) -> Value {
287    let client_version = params
288        .get("protocolVersion")
289        .and_then(|v| v.as_str())
290        .unwrap_or(PROTOCOL_VERSION)
291        .to_string();
292    json!({
293        "protocolVersion": client_version,
294        "capabilities": {
295            "tools": { "listChanged": false },
296        },
297        "serverInfo": {
298            "name": "mnemo",
299            "version": env!("CARGO_PKG_VERSION"),
300        },
301    })
302}
303
304// --- Tools registry ------------------------------------------------------
305
306/// The seven tools this server exposes. Kept as a hand-authored constant
307/// (rather than macro-derived) so the JSON schemas stay auditable —
308/// every field a client sees is visible right here.
309fn tools_list() -> Value {
310    json!({
311        "tools": [
312            {
313                "name": "about",
314                "description": "Read-only briefing for this .mnemo file: manifest scaffold plus any memories tagged as onboarding, then the project essence (conventions, decisions, open items) as a final `{kind: \"essence\", render}` element when the file has one. Run this first to learn how the file expects to be used.",
315                "inputSchema": {
316                    "type": "object",
317                    "properties": {},
318                    "additionalProperties": false
319                }
320            },
321            {
322                "name": "remember",
323                "description": "Insert, overwrite, or UPSERT a memory. Pass EITHER `vector` (explicit embedding) OR `text` (embedded by the server if it was started with --embed-cmd / --embed-name). Phase 12.1: when `key` is set, this becomes a keyed upsert — if a live memory already holds this `(agent + key)` slot the prior record is marked `_mnemo.superseded_by` and a new one is inserted, and an identical re-write is a no-op. **PREFER `key` for any fact that replaces an earlier one** (versions, current status, user preferences, plan outcomes). Persists to disk before returning. Returns `{id, outcome}` where `outcome` is `added`, `superseded`, `unchanged`, or (no key) `inserted`.",
324                "inputSchema": {
325                    "type": "object",
326                    "required": ["content", "memory_type"],
327                    "properties": {
328                        "content": { "type": "string" },
329                        "memory_type": { "type": "string", "enum": ["episodic", "semantic", "procedural", "working"] },
330                        "vector": { "type": "array", "items": { "type": "number" }, "description": "Explicit embedding; mutually exclusive with `text`." },
331                        "text": { "type": "string", "description": "Content to embed via the server's registered embedder; mutually exclusive with `vector`. Requires the server to have been started with --embed-cmd." },
332                        "importance": { "type": "number", "minimum": 0, "maximum": 1 },
333                        "agent_id": { "type": "string" },
334                        "session_id": { "type": "string" },
335                        "ttl_secs": { "type": "integer" },
336                        "shared": { "type": "boolean" },
337                        "metadata": { "type": "object" },
338                        "key": { "type": "string", "description": "Phase 12.1 upsert slot name. A later `remember` with the same `key` + agent scope supersedes the prior record; an identical re-write is a no-op. Use this for any fact that replaces an earlier one." }
339                    },
340                    "additionalProperties": false
341                }
342            },
343            {
344                "name": "update",
345                "description": "Edit a memory in place (Phase 12.1). Preserves the ULID, `created_at` and access stats. Any of `content` (needs `vector` to avoid embedding drift), `text` (re-embeds via the server), `importance`, `metadata`, `ttl_secs` can change. An identical patch returns `{id, outcome: 'unchanged'}` without writing. Prefer `remember` with `key` for facts that replace earlier ones; use `update` for in-place corrections to one specific record.",
346                "inputSchema": {
347                    "type": "object",
348                    "required": ["id"],
349                    "properties": {
350                        "id": { "type": "string", "description": "ULID of the memory to update." },
351                        "content": { "type": "string", "description": "New content. Requires a matching `vector` (use `text` to re-embed instead)." },
352                        "vector": { "type": "array", "items": { "type": "number" } },
353                        "text": { "type": "string", "description": "New content; the server embeds it through its registered embedder. Mutually exclusive with `content` + `vector`." },
354                        "importance": { "type": "number", "minimum": 0, "maximum": 1 },
355                        "metadata": { "type": "object", "description": "Replace the user-visible metadata. Reserved `_mnemo.*` keys on the record are preserved." },
356                        "ttl_secs": { "type": "integer", "description": "Set the TTL to this many seconds. Use `clear_ttl: true` to drop any TTL." },
357                        "clear_ttl": { "type": "boolean", "description": "Clear any TTL on the record." }
358                    },
359                    "additionalProperties": false
360                }
361            },
362            {
363                "name": "essence",
364                "description": "Phase 12.7b: edit or render the essence layer of a thread (or the project layer). ONE tool for every op — set `op` to `add` / `append` / `update` / `resolve` / `remove` / `render`. **Call it when the goal, a decision, an open problem, the next step or the user's way of working changes, and append a timeline entry at each milestone.** Section items (`intent`, `conventions`, `decisions`, `state`, `open`, `next`, `lessons`) are ≤ 280 bytes and have an `open → resolved` lifecycle; `append` adds an append-only `timeline` entry (≤ 600 bytes). Thread-scoped (`thread`) or project-scoped (`project: true`). `render` returns the deterministic markdown view, budgeted at `budget` bytes (default 6144).",
365                "inputSchema": {
366                    "type": "object",
367                    "required": ["op"],
368                    "properties": {
369                        "op": { "type": "string", "enum": ["add", "append", "update", "resolve", "remove", "render"] },
370                        "thread": { "type": "string", "description": "Thread id. Omit with `project: true` for the project layer." },
371                        "project": { "type": "boolean", "default": false, "description": "Project-scoped item (shows in every thread's render). Mutually exclusive with `thread`." },
372                        "section": { "type": "string", "enum": ["intent", "conventions", "decisions", "state", "open", "next", "lessons"], "description": "Required for `op: add`. Timeline uses `op: append`, not add." },
373                        "id": { "type": "string", "description": "ULID of the section item. Required for update / resolve / remove." },
374                        "text": { "type": "string", "description": "Required for add / append / update." },
375                        "refs": { "type": "array", "items": { "type": "string" }, "description": "Optional free-form reference strings (turn ids, memory ids, commits, paths)." },
376                        "budget": { "type": "integer", "default": 6144, "description": "Byte budget for `op: render`." }
377                    },
378                    "additionalProperties": false
379                }
380            },
381            {
382                "name": "thread_start",
383                "description": "Phase 12.7c: start a new thread that continues from a previous one. `essence {op: render, thread: <new>}` then pulls the prior thread's open items, `next` and last-N timeline entries ahead of the new thread's own essence — the 'new thread, same experience' path. Returns `{id}` (the link-record ULID).",
384                "inputSchema": {
385                    "type": "object",
386                    "required": ["new", "from"],
387                    "properties": {
388                        "new": { "type": "string", "description": "New thread id." },
389                        "from": { "type": "string", "description": "Previous thread id to continue from." }
390                    },
391                    "additionalProperties": false
392                }
393            },
394            {
395                "name": "commit_deltas",
396                "description": "Atomic batch write: facts, essence ops and thread archive turns in one call. Every item is checked before anything is written, so an invalid item writes nothing; one flush on success. Facts may omit `vector`: the server embeds every fact `content`, essence text and turn in one batched call with its embedder (`--embed-cmd` or builtin). Use at a session end to save a burst of updates in one round trip. `turn_policy` defaults to `archive`; `expire_after` takes a TTL in seconds; `drop` discards turns. Returns a counts summary.",
397                "inputSchema": {
398                    "type": "object",
399                    "properties": {
400                        "facts": {
401                            "type": "array",
402                            "items": {
403                                "type": "object",
404                                "required": ["content", "memory_type"],
405                                "properties": {
406                                    "content": { "type": "string" },
407                                    "memory_type": { "type": "string", "enum": ["episodic", "semantic", "procedural", "working"] },
408                                    "vector": { "type": "array", "items": { "type": "number" }, "description": "Optional. Omit it to have the server embed `content`." },
409                                    "importance": { "type": "number", "minimum": 0, "maximum": 1 },
410                                    "agent_id": { "type": "string" },
411                                    "session_id": { "type": "string" },
412                                    "shared": { "type": "boolean" },
413                                    "metadata": { "type": "object" },
414                                    "key": { "type": "string" }
415                                }
416                            }
417                        },
418                        "essence_ops": {
419                            "type": "array",
420                            "items": {
421                                "type": "object",
422                                "required": ["kind"],
423                                "properties": {
424                                    "kind": { "type": "string", "enum": ["add", "append_timeline", "update", "resolve", "remove"] },
425                                    "thread": { "type": "string" },
426                                    "project": { "type": "boolean" },
427                                    "section": { "type": "string" },
428                                    "id": { "type": "string" },
429                                    "text": { "type": "string" },
430                                    "refs": { "type": "array", "items": { "type": "string" } }
431                                }
432                            }
433                        },
434                        "turns": {
435                            "type": "array",
436                            "items": {
437                                "type": "object",
438                                "required": ["turn_id", "role", "content"],
439                                "properties": {
440                                    "turn_id": { "type": "string" },
441                                    "role": { "type": "string" },
442                                    "content": { "type": "string" },
443                                    "timestamp": { "type": "integer" }
444                                }
445                            }
446                        },
447                        "thread_id": { "type": "string", "description": "Required when `turns` is non-empty." },
448                        "turn_policy": { "type": "string", "enum": ["archive", "expire_after", "drop"], "default": "archive" },
449                        "turn_policy_ttl": { "type": "integer", "description": "TTL in seconds; required when `turn_policy = 'expire_after'`." }
450                    },
451                    "additionalProperties": false
452                }
453            },
454            {
455                "name": "thread_ingest",
456                "description": "Phase 12.7a: ingest a transcript file into a thread's archive layer. Idempotent per `turn_id` — re-running on a longer transcript appends only the new turns. Requires an embedder on the server (`--embed-cmd` at serve start) because every turn is embedded. Returns `{added_records, skipped_existing_turns, chunked_turns, truncated_turns}`.",
457                "inputSchema": {
458                    "type": "object",
459                    "required": ["thread", "transcript_path"],
460                    "properties": {
461                        "thread": { "type": "string", "description": "Thread id to append under." },
462                        "transcript_path": { "type": "string", "description": "Local path to the transcript file." },
463                        "format": { "type": "string", "enum": ["jsonl", "claude-code-jsonl"], "default": "jsonl" }
464                    },
465                    "additionalProperties": false
466                }
467            },
468            {
469                "name": "thread_export",
470                "description": "Return a thread's archive in the ingest shape: `[{turn_id, role, content, timestamp}]` in order, one entry per turn (long turns' chunks joined), plus `sha256` and `original_length` on a truncated tool result. Feeding it back to ingest for the same thread adds nothing.",
471                "inputSchema": {
472                    "type": "object",
473                    "required": ["thread"],
474                    "properties": {
475                        "thread": { "type": "string", "description": "Thread id to export." }
476                    },
477                    "additionalProperties": false
478                }
479            },
480            {
481                "name": "history",
482                "description": "Walk the full chain for a keyed slot (Phase 12.1), newest first. Entry 0 is the live record (or empty if the slot is empty); subsequent entries are the superseded history. Slot resolution matches keyed `remember`: with no `agent` and `shared=false`, walks the default agent's private slot (v0.8.1 bugfix — pre-v0.8.1 this walked the shared slot by accident and returned empty for the common case). Pass `shared: true` for the shared slot; `agent` + `shared=true` is rejected.",
483                "inputSchema": {
484                    "type": "object",
485                    "required": ["key"],
486                    "properties": {
487                        "key": { "type": "string" },
488                        "agent": { "type": "string", "description": "Query the private slot for this agent. Mutually exclusive with `shared`." },
489                        "shared": { "type": "boolean", "default": false, "description": "Query the shared slot (one per file). Mutually exclusive with `agent`." }
490                    },
491                    "additionalProperties": false
492                }
493            },
494            {
495                "name": "recall",
496                "description": "Score every live memory (or the ANN-narrowed candidate set) against a query and return the top-k. Pass EITHER `query` (explicit vector) OR `text` (embedded by the server; requires --embed-cmd at serve start). Phase 12.6: add a `filter` object to restrict candidates before scoring (`session_id` plus per-metadata-key conditions: equality, `$in`, `$exists`, `$gte`/`$lte`). Phase 12.1: superseded records never appear. Phase 12.8: set `max_bytes: N` to cap the total UTF-8 bytes of returned `content` fields; the response is then shaped as `{hits: [...], truncated: bool}` so the caller can tell whether the budget cut hits. Without `max_bytes`, the response is a bare JSON array of hits (unchanged). FMT-9d (v9 files): put identifiers or exact terms from the request (a version like v0.9.0, a PR number, a function name) in `keywords` to add keyword matching; do not paste the question there. `keywords` alone (no `query`/`text`) is keyword-only recall.",
497                "inputSchema": {
498                    "type": "object",
499                    "properties": {
500                        "query": { "type": "array", "items": { "type": "number" }, "description": "Explicit query vector; mutually exclusive with `text`." },
501                        "keywords": { "type": "string", "description": "Identifiers or exact terms to match (a version, a PR number, a function name). Not the question. Needs a v9 file." },
502                        "text": { "type": "string", "description": "Query text; embedded by the server's registered embedder. Mutually exclusive with `query`." },
503                        "top_k": { "type": "integer", "default": 10 },
504                        "types": { "type": "array", "items": { "type": "string" } },
505                        "agent": { "type": "string" },
506                        "metric": { "type": "string", "enum": ["cosine", "l2", "dot"], "default": "cosine" },
507                        "max_bytes": { "type": "integer", "minimum": 1, "description": "Phase 12.8 budget: stop adding hits once the UTF-8 bytes of their `content` fields would exceed N. Always returns at least the top hit. When set, the response is `{hits, truncated}` instead of a bare array." },
508                        "filter": {
509                            "type": "object",
510                            "description": "Phase 12.6 pre-scoring filter. All conditions AND together. Shape: `{\"session_id\": \"...\", \"metadata\": {key: value | {\"$in\": [...]} | {\"$exists\": true} | {\"$gte\": n, \"$lte\": n}}}`.",
511                            "properties": {
512                                "session_id": { "type": "string" },
513                                "metadata": { "type": "object" }
514                            },
515                            "additionalProperties": false
516                        }
517                    },
518                    "additionalProperties": false
519                }
520            },
521            {
522                "name": "forget",
523                "description": "Soft-delete a memory by ULID. Space is reclaimed on the next `mnemo compact`. Persists to disk before returning.",
524                "inputSchema": {
525                    "type": "object",
526                    "required": ["id"],
527                    "properties": {
528                        "id": { "type": "string", "description": "ULID of the memory to delete" }
529                    },
530                    "additionalProperties": false
531                }
532            },
533            {
534                "name": "list",
535                "description": "Return every live memory as JSON. Sorted by creation time, oldest first. Vectors are omitted by default to keep payloads small.",
536                "inputSchema": {
537                    "type": "object",
538                    "properties": {
539                        "include_vectors": { "type": "boolean", "default": false }
540                    },
541                    "additionalProperties": false
542                }
543            },
544            {
545                "name": "snapshot_list",
546                "description": "List every restorable snapshot (one per committed flush). Each entry gives the transaction ID, creation timestamp, and memory count.",
547                "inputSchema": {
548                    "type": "object",
549                    "properties": {},
550                    "additionalProperties": false
551                }
552            },
553            {
554                "name": "stats",
555                "description": "Summary statistics: memory count, deleted count, agents present, snapshot count, page cache occupancy.",
556                "inputSchema": {
557                    "type": "object",
558                    "properties": {},
559                    "additionalProperties": false
560                }
561            },
562            {
563                "name": "cache_put",
564                "description": "Insert or overwrite an exact-key cache entry. Value is a UTF-8 string; use `content_type` to label the payload. Persists to disk before returning. Namespace and key are caller-chosen; the key is SHA-256 hashed by the engine.",
565                "inputSchema": {
566                    "type": "object",
567                    "required": ["namespace", "key", "value"],
568                    "properties": {
569                        "namespace": { "type": "string" },
570                        "key": { "type": "string" },
571                        "value": { "type": "string" },
572                        "content_type": { "type": "string", "default": "text" },
573                        "ttl_secs": { "type": "integer", "minimum": 0 }
574                    },
575                    "additionalProperties": false
576                }
577            },
578            {
579                "name": "cache_get",
580                "description": "Look up an exact-key cache entry. Returns `{value, content_type, hit}` on a hit, `{hit: false}` on miss (missing or TTL-expired). Bumps access stats catalog-only.",
581                "inputSchema": {
582                    "type": "object",
583                    "required": ["namespace", "key"],
584                    "properties": {
585                        "namespace": { "type": "string" },
586                        "key": { "type": "string" }
587                    },
588                    "additionalProperties": false
589                }
590            },
591            {
592                "name": "cache_stats",
593                "description": "Cache statistics for a namespace (omit for the whole cache). Returns entries, bytes, hits, misses, hit_rate, evictions.",
594                "inputSchema": {
595                    "type": "object",
596                    "properties": {
597                        "namespace": { "type": "string" }
598                    },
599                    "additionalProperties": false
600                }
601            },
602            {
603                "name": "cache_put_semantic",
604                "description": "Insert an entry with an embedding vector for semantic recall (Phase 10.2). Pass EITHER `vector` + `model` (explicit) OR `text` (embedded by the server; `model` defaults to the server embedder's identity name). Later cache_get_semantic calls under a different `model` won't see this entry (a different-model hit would be a semantics bug).",
605                "inputSchema": {
606                    "type": "object",
607                    "required": ["namespace", "key", "value"],
608                    "properties": {
609                        "namespace": { "type": "string" },
610                        "key": { "type": "string" },
611                        "vector": { "type": "array", "items": { "type": "number" }, "description": "Explicit embedding; mutually exclusive with `text`. Requires `model`." },
612                        "text": { "type": "string", "description": "Content to embed via the server's registered embedder; mutually exclusive with `vector`." },
613                        "value": { "type": "string" },
614                        "model": { "type": "string", "description": "Required with `vector`; optional with `text` (defaults to the embedder's identity name)." },
615                        "content_type": { "type": "string", "default": "text" },
616                        "ttl_secs": { "type": "integer", "minimum": 0 }
617                    },
618                    "additionalProperties": false
619                }
620            },
621            {
622                "name": "cache_get_semantic",
623                "description": "Semantic recall over the cache: top-1 cosine over live vectored entries in the namespace whose `model` matches. Pass EITHER `query` + `model` OR `text` (which embeds via the server and defaults the model to the embedder's identity). Returns `{hit: true, value, similarity, ...}` iff similarity >= threshold, else `{hit: false}`. Threshold defaults to 0.97.",
624                "inputSchema": {
625                    "type": "object",
626                    "required": ["namespace"],
627                    "properties": {
628                        "namespace": { "type": "string" },
629                        "query": { "type": "array", "items": { "type": "number" }, "description": "Explicit query vector; mutually exclusive with `text`. Requires `model`." },
630                        "text": { "type": "string", "description": "Query text; embedded by the server. Mutually exclusive with `query`." },
631                        "model": { "type": "string", "description": "Required with `query`; optional with `text`." },
632                        "threshold": { "type": "number", "minimum": -1.0, "maximum": 1.0 }
633                    },
634                    "additionalProperties": false
635                }
636            }
637        ]
638    })
639}
640
641// --- Tool dispatch -------------------------------------------------------
642
643/// The MCP `tools/call` method: dispatches on the caller-supplied `name`
644/// and returns the tool's `content` array wrapped in an MCP result.
645fn tools_call(db: &mut Mnemo, params: &Value) -> std::result::Result<Value, RpcError> {
646    let name = params
647        .get("name")
648        .and_then(|v| v.as_str())
649        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "missing tool name"))?;
650    let empty = json!({});
651    let args = params.get("arguments").unwrap_or(&empty);
652
653    let text = match name {
654        "about" => tool_about(db)?,
655        "remember" => tool_remember(db, args)?,
656        "update" => tool_update(db, args)?,
657        "history" => tool_history(db, args)?,
658        "thread_ingest" => tool_thread_ingest(db, args)?,
659        "thread_export" => tool_thread_export(db, args)?,
660        "thread_start" => tool_thread_start(db, args)?,
661        "commit_deltas" => tool_commit_deltas(db, args)?,
662        "essence" => tool_essence(db, args)?,
663        "recall" => tool_recall(db, args)?,
664        "forget" => tool_forget(db, args)?,
665        "list" => tool_list(db, args)?,
666        "snapshot_list" => tool_snapshot_list(db)?,
667        "stats" => tool_stats(db)?,
668        "cache_put" => tool_cache_put(db, args)?,
669        "cache_get" => tool_cache_get(db, args)?,
670        "cache_stats" => tool_cache_stats(db, args)?,
671        "cache_put_semantic" => tool_cache_put_semantic(db, args)?,
672        "cache_get_semantic" => tool_cache_get_semantic(db, args)?,
673        other => {
674            return Err(RpcError::new(
675                METHOD_NOT_FOUND,
676                format!("unknown tool '{other}'"),
677            ))
678        }
679    };
680
681    Ok(json!({
682        "content": [ { "type": "text", "text": text } ],
683        "isError": false,
684    }))
685}
686
687/// Convert a [`MnemoError`] to an [`RpcError`]. Every error becomes an
688/// `INTERNAL_ERROR` with the human-readable message — MCP clients
689/// display `error.message` verbatim to the user.
690/// Resolve a text argument into a vector via the server's registered
691/// embedder (Phase 3 PR 10b). Called by the four MCP tools that
692/// accept `text` as an alternative to the explicit vector: `remember`,
693/// `recall`, `cache_put_semantic`, `cache_get_semantic`. If no
694/// embedder was configured at server start (`mnemo serve --mcp
695/// --embed-cmd ...`) the error message tells the caller how to turn
696/// it on.
697fn embed_text_via_server(
698    db: &mut Mnemo,
699    tool: &str,
700    text: &str,
701) -> std::result::Result<Vec<f32>, RpcError> {
702    let embedder = db.embedder().ok_or_else(|| {
703        RpcError::new(
704            INVALID_PARAMS,
705            format!(
706                "{tool}: 'text' requires an embedder on the server. \
707                 Start with: mnemo serve --mcp <file> --embed-cmd '<cmd>' --embed-name <name>"
708            ),
709        )
710    })?;
711    let mut vs = embedder.embed(&[text]).map_err(mnemo_err)?;
712    vs.pop().ok_or_else(|| {
713        RpcError::new(
714            INTERNAL_ERROR,
715            format!("{tool}: embedder returned no vector for the input text"),
716        )
717    })
718}
719
720fn mnemo_err(e: MnemoError) -> RpcError {
721    RpcError::new(INTERNAL_ERROR, e.to_string())
722}
723
724fn tool_about(db: &mut Mnemo) -> std::result::Result<String, RpcError> {
725    let mems = db.about().map_err(mnemo_err)?;
726    let mut arr: Vec<Value> = mems.iter().map(memory_to_json).collect();
727    // Phase 12.7d: the project essence follows the manifest and the
728    // onboarding memories, as one tagged element.
729    if let Some(render) = db.about_essence().map_err(mnemo_err)? {
730        arr.push(json!({ "kind": "essence", "scope": "project", "render": render }));
731    }
732    Ok(serde_json::to_string_pretty(&arr).unwrap_or_else(|_| "[]".into()))
733}
734
735fn tool_thread_export(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
736    let thread = args
737        .get("thread")
738        .and_then(|v| v.as_str())
739        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "thread_export: missing 'thread'"))?;
740    let turns = db.thread_export_turns(thread).map_err(mnemo_err)?;
741    let arr: Vec<Value> = turns.iter().map(|t| t.to_json()).collect();
742    Ok(Value::Array(arr).to_string())
743}
744
745fn tool_remember(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
746    let content = args
747        .get("content")
748        .and_then(|v| v.as_str())
749        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "remember: missing 'content'"))?;
750    let mtype_str = args
751        .get("memory_type")
752        .and_then(|v| v.as_str())
753        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "remember: missing 'memory_type'"))?;
754    let mtype = MemoryType::parse(mtype_str).ok_or_else(|| {
755        RpcError::new(
756            INVALID_PARAMS,
757            format!("remember: unknown memory_type '{mtype_str}'"),
758        )
759    })?;
760    // Accept either `vector` (explicit) or `text` (embedded via the
761    // server's registered embedder, Phase 3). Exactly one required.
762    let vector = match (args.get("vector"), args.get("text")) {
763        (Some(_), Some(_)) => {
764            return Err(RpcError::new(
765                INVALID_PARAMS,
766                "remember: pass EITHER 'vector' or 'text', not both",
767            ));
768        }
769        (Some(v), None) => v
770            .as_array()
771            .ok_or_else(|| {
772                RpcError::new(INVALID_PARAMS, "remember: 'vector' must be a JSON array")
773            })?
774            .iter()
775            .map(|v| v.as_f64().map(|f| f as f32))
776            .collect::<Option<Vec<f32>>>()
777            .ok_or_else(|| {
778                RpcError::new(
779                    INVALID_PARAMS,
780                    "remember: 'vector' must be an array of numbers",
781                )
782            })?,
783        (None, Some(t)) => {
784            let text = t.as_str().ok_or_else(|| {
785                RpcError::new(INVALID_PARAMS, "remember: 'text' must be a string")
786            })?;
787            embed_text_via_server(db, "remember", text)?
788        }
789        (None, None) => {
790            return Err(RpcError::new(
791                INVALID_PARAMS,
792                "remember: missing 'vector' or 'text'",
793            ))
794        }
795    };
796
797    let mut mem = Memory::new(content, mtype, vector);
798    if let Some(agent) = args.get("agent_id").and_then(|v| v.as_str()) {
799        mem = mem.with_agent(agent);
800    }
801    if let Some(sess) = args.get("session_id").and_then(|v| v.as_str()) {
802        mem = mem.with_session(sess);
803    }
804    if let Some(imp) = args.get("importance").and_then(|v| v.as_f64()) {
805        mem = mem.with_importance(imp as f32);
806    }
807    if let Some(ttl) = args.get("ttl_secs").and_then(|v| v.as_i64()) {
808        mem = mem.with_ttl(ttl);
809    }
810    if let Some(shared) = args.get("shared").and_then(|v| v.as_bool()) {
811        if shared {
812            mem = mem.with_scope(Scope::Shared);
813        }
814    }
815    if let Some(meta) = args.get("metadata").and_then(|v| v.as_object()) {
816        for (k, v) in meta {
817            mem.metadata.insert(k.clone(), v.clone());
818        }
819    }
820
821    // Phase 12.1: when `key` is set, take the keyed-upsert path
822    // (supersede / no-op / add); otherwise keep the pre-12.1
823    // single-id return shape (now carrying `outcome: "inserted"` so
824    // callers can distinguish it from the keyed outcomes).
825    match args.get("key").and_then(|v| v.as_str()) {
826        None => {
827            let id = db.remember(mem).map_err(mnemo_err)?;
828            db.flush().map_err(mnemo_err)?;
829            Ok(json!({ "id": id.to_string(), "outcome": "inserted" }).to_string())
830        }
831        Some(k) => {
832            let (id, outcome) = db.remember_keyed(mem, k).map_err(mnemo_err)?;
833            db.flush().map_err(mnemo_err)?;
834            let outcome_str = match outcome {
835                crate::WriteOutcome::Added => "added",
836                crate::WriteOutcome::Superseded => "superseded",
837                crate::WriteOutcome::Unchanged => "unchanged",
838                crate::WriteOutcome::Updated => "superseded",
839            };
840            Ok(json!({ "id": id.to_string(), "outcome": outcome_str }).to_string())
841        }
842    }
843}
844
845fn tool_update(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
846    use crate::Ulid;
847    use crate::{MemoryPatch, WriteOutcome};
848    let id_str = args
849        .get("id")
850        .and_then(|v| v.as_str())
851        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "update: missing 'id'"))?;
852    let id = Ulid::from_string(id_str)
853        .map_err(|_| RpcError::new(INVALID_PARAMS, format!("update: invalid ULID '{id_str}'")))?;
854    // Mutually exclusive: `text` (server re-embeds) vs `content`+`vector`
855    // (explicit). Either path produces `(new_content, new_vector)` for
856    // the engine; both unset means no text/vector change.
857    let has_text = args.get("text").is_some();
858    let has_content = args.get("content").is_some();
859    let has_vector = args.get("vector").is_some();
860    if has_text && (has_content || has_vector) {
861        return Err(RpcError::new(
862            INVALID_PARAMS,
863            "update: pass EITHER 'text' or 'content'+'vector', not both",
864        ));
865    }
866    let mut patch = MemoryPatch::default();
867    if has_content {
868        let c = args
869            .get("content")
870            .and_then(|v| v.as_str())
871            .ok_or_else(|| RpcError::new(INVALID_PARAMS, "update: 'content' must be a string"))?;
872        patch.content = Some(c.to_string());
873    }
874    if has_vector {
875        let v = args
876            .get("vector")
877            .and_then(|v| v.as_array())
878            .ok_or_else(|| RpcError::new(INVALID_PARAMS, "update: 'vector' must be a JSON array"))?
879            .iter()
880            .map(|v| v.as_f64().map(|f| f as f32))
881            .collect::<Option<Vec<f32>>>()
882            .ok_or_else(|| {
883                RpcError::new(
884                    INVALID_PARAMS,
885                    "update: 'vector' must be an array of numbers",
886                )
887            })?;
888        patch.vector = Some(v);
889    }
890    if let Some(imp) = args.get("importance").and_then(|v| v.as_f64()) {
891        patch.importance = Some(imp as f32);
892    }
893    if let Some(meta) = args.get("metadata").and_then(|v| v.as_object()) {
894        patch.metadata = Some(meta.clone());
895    }
896    let clear_ttl = args
897        .get("clear_ttl")
898        .and_then(|v| v.as_bool())
899        .unwrap_or(false);
900    if clear_ttl {
901        patch.ttl_secs = Some(None);
902    } else if let Some(ttl) = args.get("ttl_secs").and_then(|v| v.as_i64()) {
903        patch.ttl_secs = Some(Some(ttl));
904    }
905
906    let outcome = if has_text {
907        let t = args
908            .get("text")
909            .and_then(|v| v.as_str())
910            .ok_or_else(|| RpcError::new(INVALID_PARAMS, "update: 'text' must be a string"))?;
911        db.update_text(&id, t, patch).map_err(mnemo_err)?
912    } else {
913        db.update(&id, patch).map_err(mnemo_err)?
914    };
915    db.flush().map_err(mnemo_err)?;
916    let outcome_str = match outcome {
917        WriteOutcome::Updated => "updated",
918        WriteOutcome::Unchanged => "unchanged",
919        WriteOutcome::Added => "updated",
920        WriteOutcome::Superseded => "updated",
921    };
922    Ok(json!({ "id": id.to_string(), "outcome": outcome_str }).to_string())
923}
924
925fn tool_thread_start(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
926    let new = args
927        .get("new")
928        .and_then(|v| v.as_str())
929        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "thread_start: missing 'new'"))?;
930    let from = args
931        .get("from")
932        .and_then(|v| v.as_str())
933        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "thread_start: missing 'from'"))?;
934    let id = db.thread_start(new, from).map_err(mnemo_err)?;
935    db.flush().map_err(mnemo_err)?;
936    Ok(json!({ "id": id.to_string() }).to_string())
937}
938
939fn tool_commit_deltas(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
940    use crate::{
941        CommitBatch, EssenceOp, EssenceOpKind, EssenceScope, EssenceSection, KeyedMemory,
942        ThreadTurn, TurnPolicy, Ulid,
943    };
944    let mut batch = CommitBatch::default();
945
946    // facts
947    if let Some(arr) = args.get("facts").and_then(|v| v.as_array()) {
948        for (i, f) in arr.iter().enumerate() {
949            let obj = f.as_object().ok_or_else(|| {
950                RpcError::new(
951                    INVALID_PARAMS,
952                    format!("commit_deltas: facts[{i}] must be an object"),
953                )
954            })?;
955            let content = obj.get("content").and_then(|v| v.as_str()).ok_or_else(|| {
956                RpcError::new(
957                    INVALID_PARAMS,
958                    format!("commit_deltas: facts[{i}] missing 'content'"),
959                )
960            })?;
961            let mtype_str = obj
962                .get("memory_type")
963                .and_then(|v| v.as_str())
964                .ok_or_else(|| {
965                    RpcError::new(
966                        INVALID_PARAMS,
967                        format!("commit_deltas: facts[{i}] missing 'memory_type'"),
968                    )
969                })?;
970            let mtype = MemoryType::parse(mtype_str).ok_or_else(|| {
971                RpcError::new(
972                    INVALID_PARAMS,
973                    format!("commit_deltas: facts[{i}] unknown memory_type '{mtype_str}'"),
974                )
975            })?;
976            // 12.7d: `vector` is optional. Without one the engine embeds
977            // `content` with the server's embedder, batched with the rest
978            // of the call.
979            let vector = match obj.get("vector") {
980                None | Some(Value::Null) => Vec::new(),
981                Some(v) => v
982                    .as_array()
983                    .and_then(|a| {
984                        a.iter()
985                            .map(|x| x.as_f64().map(|f| f as f32))
986                            .collect::<Option<Vec<f32>>>()
987                    })
988                    .ok_or_else(|| {
989                        RpcError::new(
990                            INVALID_PARAMS,
991                            format!("commit_deltas: facts[{i}] vector must be an array of numbers"),
992                        )
993                    })?,
994            };
995            let mut mem = Memory::new(content, mtype, vector);
996            if let Some(a) = obj.get("agent_id").and_then(|v| v.as_str()) {
997                mem = mem.with_agent(a);
998            }
999            if let Some(s) = obj.get("session_id").and_then(|v| v.as_str()) {
1000                mem = mem.with_session(s);
1001            }
1002            if let Some(imp) = obj.get("importance").and_then(|v| v.as_f64()) {
1003                mem = mem.with_importance(imp as f32);
1004            }
1005            if let Some(shared) = obj.get("shared").and_then(|v| v.as_bool()) {
1006                if shared {
1007                    mem = mem.with_scope(Scope::Shared);
1008                }
1009            }
1010            if let Some(meta) = obj.get("metadata").and_then(|v| v.as_object()) {
1011                for (k, v) in meta {
1012                    mem.metadata.insert(k.clone(), v.clone());
1013                }
1014            }
1015            let key = obj.get("key").and_then(|v| v.as_str()).map(String::from);
1016            batch.facts.push(KeyedMemory { memory: mem, key });
1017        }
1018    }
1019
1020    // essence_ops
1021    if let Some(arr) = args.get("essence_ops").and_then(|v| v.as_array()) {
1022        for (i, o) in arr.iter().enumerate() {
1023            let obj = o.as_object().ok_or_else(|| {
1024                RpcError::new(
1025                    INVALID_PARAMS,
1026                    format!("commit_deltas: essence_ops[{i}] must be an object"),
1027                )
1028            })?;
1029            let kind_str = obj.get("kind").and_then(|v| v.as_str()).ok_or_else(|| {
1030                RpcError::new(
1031                    INVALID_PARAMS,
1032                    format!("commit_deltas: essence_ops[{i}] missing 'kind'"),
1033                )
1034            })?;
1035            let kind = match kind_str {
1036                "add" => EssenceOpKind::Add,
1037                "append_timeline" => EssenceOpKind::AppendTimeline,
1038                "update" => EssenceOpKind::Update,
1039                "resolve" => EssenceOpKind::Resolve,
1040                "remove" => EssenceOpKind::Remove,
1041                other => {
1042                    return Err(RpcError::new(
1043                        INVALID_PARAMS,
1044                        format!("commit_deltas: essence_ops[{i}] unknown kind '{other}'"),
1045                    ));
1046                }
1047            };
1048            let thread = obj.get("thread").and_then(|v| v.as_str()).map(String::from);
1049            let project = obj
1050                .get("project")
1051                .and_then(|v| v.as_bool())
1052                .unwrap_or(false);
1053            let scope = match (thread, project) {
1054                (Some(t), false) => Some(EssenceScope::Thread(t)),
1055                (None, true) => Some(EssenceScope::Project),
1056                (None, false) => None,
1057                (Some(_), true) => {
1058                    return Err(RpcError::new(
1059                        INVALID_PARAMS,
1060                        format!(
1061                            "commit_deltas: essence_ops[{i}] can't set both 'thread' and 'project'"
1062                        ),
1063                    ));
1064                }
1065            };
1066            let section = obj
1067                .get("section")
1068                .and_then(|v| v.as_str())
1069                .and_then(EssenceSection::parse);
1070            let id = obj
1071                .get("id")
1072                .and_then(|v| v.as_str())
1073                .map(Ulid::from_string)
1074                .transpose()
1075                .map_err(|_| {
1076                    RpcError::new(
1077                        INVALID_PARAMS,
1078                        format!("commit_deltas: essence_ops[{i}] 'id' is not a valid ULID"),
1079                    )
1080                })?;
1081            let text = obj.get("text").and_then(|v| v.as_str()).map(String::from);
1082            let refs = obj.get("refs").and_then(|v| v.as_array()).map(|a| {
1083                a.iter()
1084                    .filter_map(|x| x.as_str().map(String::from))
1085                    .collect()
1086            });
1087            batch.essence_ops.push(EssenceOp {
1088                kind,
1089                scope,
1090                section,
1091                id,
1092                text,
1093                refs,
1094            });
1095        }
1096    }
1097
1098    // turns
1099    if let Some(arr) = args.get("turns").and_then(|v| v.as_array()) {
1100        for (i, t) in arr.iter().enumerate() {
1101            let obj = t.as_object().ok_or_else(|| {
1102                RpcError::new(
1103                    INVALID_PARAMS,
1104                    format!("commit_deltas: turns[{i}] must be an object"),
1105                )
1106            })?;
1107            let turn_id = obj
1108                .get("turn_id")
1109                .and_then(|v| v.as_str())
1110                .ok_or_else(|| {
1111                    RpcError::new(
1112                        INVALID_PARAMS,
1113                        format!("commit_deltas: turns[{i}] missing 'turn_id'"),
1114                    )
1115                })?
1116                .to_string();
1117            let role = obj
1118                .get("role")
1119                .and_then(|v| v.as_str())
1120                .ok_or_else(|| {
1121                    RpcError::new(
1122                        INVALID_PARAMS,
1123                        format!("commit_deltas: turns[{i}] missing 'role'"),
1124                    )
1125                })?
1126                .to_string();
1127            let content = obj
1128                .get("content")
1129                .and_then(|v| v.as_str())
1130                .ok_or_else(|| {
1131                    RpcError::new(
1132                        INVALID_PARAMS,
1133                        format!("commit_deltas: turns[{i}] missing 'content'"),
1134                    )
1135                })?
1136                .to_string();
1137            let timestamp = obj.get("timestamp").and_then(|v| v.as_i64());
1138            batch.turns.push(ThreadTurn {
1139                turn_id,
1140                role,
1141                content,
1142                timestamp,
1143            });
1144        }
1145    }
1146    batch.thread_id = args
1147        .get("thread_id")
1148        .and_then(|v| v.as_str())
1149        .map(String::from);
1150    let policy_str = args
1151        .get("turn_policy")
1152        .and_then(|v| v.as_str())
1153        .unwrap_or("archive");
1154    batch.turn_policy = match policy_str {
1155        "archive" => TurnPolicy::Archive,
1156        "drop" => TurnPolicy::Drop,
1157        "expire_after" => {
1158            let ttl = args
1159                .get("turn_policy_ttl")
1160                .and_then(|v| v.as_i64())
1161                .ok_or_else(|| {
1162                    RpcError::new(
1163                        INVALID_PARAMS,
1164                        "commit_deltas: turn_policy='expire_after' requires 'turn_policy_ttl' (seconds)",
1165                    )
1166                })?;
1167            TurnPolicy::ExpireAfter(ttl)
1168        }
1169        other => {
1170            return Err(RpcError::new(
1171                INVALID_PARAMS,
1172                format!("commit_deltas: unknown turn_policy '{other}'"),
1173            ));
1174        }
1175    };
1176
1177    let report = db.commit_deltas(batch).map_err(mnemo_err)?;
1178    Ok(json!({
1179        "facts_added": report.facts_added,
1180        "facts_superseded": report.facts_superseded,
1181        "facts_unchanged": report.facts_unchanged,
1182        "essence_ops_applied": report.essence_ops_applied,
1183        "essence_ops_unchanged": report.essence_ops_unchanged,
1184        "turns_added": report.turns_added,
1185        "turns_skipped": report.turns_skipped,
1186        "turns_truncated": report.turns_truncated,
1187        "turns_chunked": report.turns_chunked,
1188    })
1189    .to_string())
1190}
1191
1192fn tool_essence(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1193    use crate::{EssenceScope, EssenceSection, Ulid, WriteOutcome};
1194    let op = args
1195        .get("op")
1196        .and_then(|v| v.as_str())
1197        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "essence: missing 'op'"))?;
1198    let thread = args
1199        .get("thread")
1200        .and_then(|v| v.as_str())
1201        .map(String::from);
1202    let project = args
1203        .get("project")
1204        .and_then(|v| v.as_bool())
1205        .unwrap_or(false);
1206    let scope_from = |t: Option<String>, p: bool| -> std::result::Result<EssenceScope, RpcError> {
1207        match (t, p) {
1208            (Some(s), false) => Ok(EssenceScope::Thread(s)),
1209            (None, true) => Ok(EssenceScope::Project),
1210            (None, false) => Err(RpcError::new(
1211                INVALID_PARAMS,
1212                "essence: pass either `thread` or `project: true`",
1213            )),
1214            (Some(_), true) => Err(RpcError::new(
1215                INVALID_PARAMS,
1216                "essence: `thread` and `project` are mutually exclusive",
1217            )),
1218        }
1219    };
1220    let refs: Option<Vec<String>> = args.get("refs").and_then(|v| v.as_array()).map(|arr| {
1221        arr.iter()
1222            .filter_map(|x| x.as_str().map(String::from))
1223            .collect()
1224    });
1225    let text = args.get("text").and_then(|v| v.as_str()).map(String::from);
1226    let id_str = args.get("id").and_then(|v| v.as_str());
1227    let outcome_to_str = |o: WriteOutcome| -> &'static str {
1228        match o {
1229            WriteOutcome::Updated => "updated",
1230            WriteOutcome::Unchanged => "unchanged",
1231            WriteOutcome::Added => "updated",
1232            WriteOutcome::Superseded => "updated",
1233        }
1234    };
1235    match op {
1236        "add" => {
1237            let section_str = args
1238                .get("section")
1239                .and_then(|v| v.as_str())
1240                .ok_or_else(|| RpcError::new(INVALID_PARAMS, "essence add: missing 'section'"))?;
1241            let section = EssenceSection::parse(section_str).ok_or_else(|| {
1242                RpcError::new(
1243                    INVALID_PARAMS,
1244                    format!("essence add: unknown section '{section_str}'"),
1245                )
1246            })?;
1247            if section == EssenceSection::Timeline {
1248                return Err(RpcError::new(
1249                    INVALID_PARAMS,
1250                    "essence add: timeline uses op: append, not add",
1251                ));
1252            }
1253            let text =
1254                text.ok_or_else(|| RpcError::new(INVALID_PARAMS, "essence add: missing 'text'"))?;
1255            let scope = scope_from(thread, project)?;
1256            let id = db
1257                .essence_add(scope, section, &text, refs)
1258                .map_err(mnemo_err)?;
1259            db.flush().map_err(mnemo_err)?;
1260            Ok(json!({ "id": id.to_string(), "outcome": "added" }).to_string())
1261        }
1262        "append" => {
1263            let text = text
1264                .ok_or_else(|| RpcError::new(INVALID_PARAMS, "essence append: missing 'text'"))?;
1265            let scope = scope_from(thread, project)?;
1266            let id = db
1267                .essence_append_timeline(scope, &text, refs)
1268                .map_err(mnemo_err)?;
1269            db.flush().map_err(mnemo_err)?;
1270            Ok(json!({ "id": id.to_string(), "outcome": "appended" }).to_string())
1271        }
1272        "update" => {
1273            let id = id_str
1274                .ok_or_else(|| RpcError::new(INVALID_PARAMS, "essence update: missing 'id'"))?;
1275            let ulid = Ulid::from_string(id).map_err(|_| {
1276                RpcError::new(
1277                    INVALID_PARAMS,
1278                    format!("essence update: invalid ULID '{id}'"),
1279                )
1280            })?;
1281            let text = text
1282                .ok_or_else(|| RpcError::new(INVALID_PARAMS, "essence update: missing 'text'"))?;
1283            let outcome = db.essence_update(&ulid, &text, refs).map_err(mnemo_err)?;
1284            db.flush().map_err(mnemo_err)?;
1285            Ok(json!({ "id": id, "outcome": outcome_to_str(outcome) }).to_string())
1286        }
1287        "resolve" => {
1288            let id = id_str
1289                .ok_or_else(|| RpcError::new(INVALID_PARAMS, "essence resolve: missing 'id'"))?;
1290            let ulid = Ulid::from_string(id).map_err(|_| {
1291                RpcError::new(
1292                    INVALID_PARAMS,
1293                    format!("essence resolve: invalid ULID '{id}'"),
1294                )
1295            })?;
1296            let outcome = db.essence_resolve(&ulid).map_err(mnemo_err)?;
1297            db.flush().map_err(mnemo_err)?;
1298            let s = match outcome {
1299                WriteOutcome::Updated => "resolved",
1300                WriteOutcome::Unchanged => "already-resolved",
1301                _ => "resolved",
1302            };
1303            Ok(json!({ "id": id, "outcome": s }).to_string())
1304        }
1305        "remove" => {
1306            let id = id_str
1307                .ok_or_else(|| RpcError::new(INVALID_PARAMS, "essence remove: missing 'id'"))?;
1308            let ulid = Ulid::from_string(id).map_err(|_| {
1309                RpcError::new(
1310                    INVALID_PARAMS,
1311                    format!("essence remove: invalid ULID '{id}'"),
1312                )
1313            })?;
1314            db.essence_remove(&ulid).map_err(mnemo_err)?;
1315            db.flush().map_err(mnemo_err)?;
1316            Ok(json!({ "id": id, "outcome": "removed" }).to_string())
1317        }
1318        "render" => {
1319            let budget = args.get("budget").and_then(|v| v.as_u64()).unwrap_or(6144) as usize;
1320            let scope = scope_from(thread, project)?;
1321            let rendered = db.essence(scope, budget).map_err(mnemo_err)?;
1322            Ok(rendered)
1323        }
1324        other => Err(RpcError::new(
1325            INVALID_PARAMS,
1326            format!("essence: unknown op '{other}'"),
1327        )),
1328    }
1329}
1330
1331fn tool_thread_ingest(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1332    let thread = args
1333        .get("thread")
1334        .and_then(|v| v.as_str())
1335        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "thread_ingest: missing 'thread'"))?;
1336    let path = args
1337        .get("transcript_path")
1338        .and_then(|v| v.as_str())
1339        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "thread_ingest: missing 'transcript_path'"))?;
1340    let format_str = args
1341        .get("format")
1342        .and_then(|v| v.as_str())
1343        .unwrap_or("jsonl");
1344    let format = crate::TranscriptFormat::parse(format_str).ok_or_else(|| {
1345        RpcError::new(
1346            INVALID_PARAMS,
1347            format!(
1348                "thread_ingest: unknown format '{format_str}' (want 'jsonl' or 'claude-code-jsonl')"
1349            ),
1350        )
1351    })?;
1352    let file = std::fs::File::open(path).map_err(|e| {
1353        RpcError::new(
1354            INVALID_PARAMS,
1355            format!("thread_ingest: cannot open {path}: {e}"),
1356        )
1357    })?;
1358    let turns = crate::read_transcript(file, format).map_err(mnemo_err)?;
1359    let report = db.ingest_thread(thread, &turns).map_err(mnemo_err)?;
1360    db.flush().map_err(mnemo_err)?;
1361    Ok(json!({
1362        "added_records": report.added_records,
1363        "skipped_existing_turns": report.skipped_existing_turns,
1364        "chunked_turns": report.chunked_turns,
1365        "truncated_turns": report.truncated_turns,
1366    })
1367    .to_string())
1368}
1369
1370fn tool_history(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1371    use crate::KeyScope;
1372    let key = args
1373        .get("key")
1374        .and_then(|v| v.as_str())
1375        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "history: missing 'key'"))?;
1376    let agent = args.get("agent").and_then(|v| v.as_str());
1377    let shared = args
1378        .get("shared")
1379        .and_then(|v| v.as_bool())
1380        .unwrap_or(false);
1381    if shared && agent.is_some() {
1382        return Err(RpcError::new(
1383            INVALID_PARAMS,
1384            "history: 'agent' and 'shared' are mutually exclusive",
1385        ));
1386    }
1387    // v0.8.1 bugfix (lane A): match keyed `remember` slot resolution.
1388    let scope = if shared {
1389        KeyScope::Shared
1390    } else {
1391        match agent {
1392            Some(a) => KeyScope::Private(a.to_string()),
1393            None => KeyScope::private_default(),
1394        }
1395    };
1396    let chain = db.history_in(key, scope).map_err(mnemo_err)?;
1397    let out: Vec<Value> = chain
1398        .iter()
1399        .enumerate()
1400        .map(|(i, m)| {
1401            let mut v = memory_to_json(m);
1402            if let Some(obj) = v.as_object_mut() {
1403                obj.insert(
1404                    "state".into(),
1405                    Value::String(if i == 0 {
1406                        "live".into()
1407                    } else {
1408                        "superseded".into()
1409                    }),
1410                );
1411            }
1412            v
1413        })
1414        .collect();
1415    Ok(serde_json::to_string_pretty(&out).unwrap_or_else(|_| "[]".into()))
1416}
1417
1418fn tool_recall(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1419    // Accept either `query` (explicit) or `text` (embedded).
1420    let query = match (args.get("query"), args.get("text")) {
1421        (Some(_), Some(_)) => {
1422            return Err(RpcError::new(
1423                INVALID_PARAMS,
1424                "recall: pass EITHER 'query' or 'text', not both",
1425            ))
1426        }
1427        (Some(v), None) => v
1428            .as_array()
1429            .ok_or_else(|| RpcError::new(INVALID_PARAMS, "recall: 'query' must be a JSON array"))?
1430            .iter()
1431            .map(|v| v.as_f64().map(|f| f as f32))
1432            .collect::<Option<Vec<f32>>>()
1433            .ok_or_else(|| {
1434                RpcError::new(
1435                    INVALID_PARAMS,
1436                    "recall: 'query' must be an array of numbers",
1437                )
1438            })?,
1439        (None, Some(t)) => {
1440            let text = t
1441                .as_str()
1442                .ok_or_else(|| RpcError::new(INVALID_PARAMS, "recall: 'text' must be a string"))?;
1443            embed_text_via_server(db, "recall", text)?
1444        }
1445        // FMT-9d: `keywords` alone is keyword-only recall.
1446        (None, None) if args.get("keywords").is_some() => Vec::new(),
1447        (None, None) => {
1448            return Err(RpcError::new(
1449                INVALID_PARAMS,
1450                "recall: missing 'query', 'text' or 'keywords'",
1451            ))
1452        }
1453    };
1454    let top_k = args.get("top_k").and_then(|v| v.as_u64()).unwrap_or(10) as usize;
1455    let metric = match args
1456        .get("metric")
1457        .and_then(|v| v.as_str())
1458        .unwrap_or("cosine")
1459    {
1460        "cosine" => Metric::Cosine,
1461        "l2" => Metric::L2,
1462        "dot" => Metric::Dot,
1463        other => {
1464            return Err(RpcError::new(
1465                INVALID_PARAMS,
1466                format!("recall: unknown metric '{other}'"),
1467            ))
1468        }
1469    };
1470    // Scoring v2 (v0.7.0) flipped the default: MCP recalls DO track
1471    // access, so an agent's own retrievals contribute to the usage
1472    // saturation term on later queries. The bump happens in-memory
1473    // (`accessed_at` / `access_count` + `dirty_catalog`), and persists
1474    // through the next flush — recall itself does not fsync, so there
1475    // is no per-tool-call write-amplification cost. Access stats reach
1476    // disk on either (a) the next mutating tool call's exit path (every
1477    // one of `remember` / `forget` / `cache_put_semantic` /
1478    // `cache_get_semantic`-on-miss ends in `db.flush()`), or (b) the
1479    // server's own shutdown flush when stdin closes (see
1480    // `serve_with_streams`), so a read-only session that issued only
1481    // recalls still persists its stats.
1482    let mut req = RecallRequest::new(query)
1483        .top_k(top_k)
1484        .metric(metric)
1485        .track_access(true);
1486    if let Some(k) = args.get("keywords") {
1487        let k = k
1488            .as_str()
1489            .ok_or_else(|| RpcError::new(INVALID_PARAMS, "recall: 'keywords' must be a string"))?;
1490        req = req.keywords(k);
1491    }
1492    if let Some(types) = args.get("types").and_then(|v| v.as_array()) {
1493        let parsed: Vec<MemoryType> = types
1494            .iter()
1495            .filter_map(|t| t.as_str().and_then(MemoryType::parse))
1496            .collect();
1497        if !parsed.is_empty() {
1498            req = req.types(parsed);
1499        }
1500    }
1501    if let Some(agent) = args.get("agent").and_then(|v| v.as_str()) {
1502        req = req.agent(agent.to_string());
1503    }
1504    // Phase 12.6: filter object. Shape:
1505    //   { "session_id": "...",
1506    //     "metadata": { "k": v,
1507    //                   "k2": {"$in": [v1, v2]},
1508    //                   "k3": {"$exists": true},
1509    //                   "k4": {"$gte": 5, "$lte": 10} } }
1510    if let Some(filter_obj) = args.get("filter").and_then(|v| v.as_object()) {
1511        req = req.filter(parse_mcp_filter(filter_obj)?);
1512    }
1513    // Phase 12.8: `max_bytes` opts into the budgeted response shape.
1514    let has_max_bytes = args.get("max_bytes").is_some();
1515    if let Some(n) = args.get("max_bytes").and_then(|v| v.as_u64()) {
1516        req = req.max_bytes(n as usize);
1517    }
1518
1519    let resp = db.recall_budgeted(&req).map_err(mnemo_err)?;
1520    let out: Vec<Value> = resp
1521        .hits
1522        .into_iter()
1523        .map(|h| {
1524            let mut obj = memory_to_json(&h.memory);
1525            if let Some(map) = obj.as_object_mut() {
1526                map.insert("score".into(), json!(h.score));
1527                map.insert("similarity".into(), json!(h.similarity));
1528            }
1529            obj
1530        })
1531        .collect();
1532    if has_max_bytes {
1533        // Phase 12.8 wrapped shape so callers can tell whether the
1534        // budget cut anything.
1535        let wrapped = json!({
1536            "hits": out,
1537            "truncated": resp.truncated,
1538        });
1539        Ok(serde_json::to_string_pretty(&wrapped).unwrap_or_else(|_| "{}".into()))
1540    } else {
1541        Ok(serde_json::to_string_pretty(&out).unwrap_or_else(|_| "[]".into()))
1542    }
1543}
1544
1545/// Phase 12.6: parse an MCP `filter` object into a [`crate::Filter`].
1546///
1547/// Values under `metadata.<key>`:
1548/// * plain scalar / array / string → [`crate::FilterTerm::Eq`]
1549/// * `{"$exists": true}` → [`crate::FilterTerm::Exists`]
1550/// * `{"$in": [...]}` → [`crate::FilterTerm::In`]
1551/// * `{"$gte": n, "$lte": n}` → [`crate::FilterTerm::Range`] (either bound
1552///   optional)
1553/// * `{"$exists": false}` is rejected (use the absence of a term instead)
1554fn parse_mcp_filter(
1555    obj: &serde_json::Map<String, Value>,
1556) -> std::result::Result<crate::Filter, RpcError> {
1557    let mut f = crate::Filter::default();
1558    if let Some(sid) = obj.get("session_id").and_then(|v| v.as_str()) {
1559        f = f.with_session(sid.to_string());
1560    }
1561    if let Some(meta) = obj.get("metadata").and_then(|v| v.as_object()) {
1562        for (k, v) in meta {
1563            match v {
1564                // Nested operator object.
1565                Value::Object(ops) => {
1566                    for (op_key, op_val) in ops {
1567                        match op_key.as_str() {
1568                            "$exists" => match op_val.as_bool() {
1569                                Some(true) => {
1570                                    f = f.metadata_exists(k.clone());
1571                                }
1572                                Some(false) => {
1573                                    return Err(RpcError::new(
1574                                        INVALID_PARAMS,
1575                                        format!(
1576                                            "filter.metadata.{k}.$exists=false isn't supported; \
1577                                             drop the filter term instead"
1578                                        ),
1579                                    ));
1580                                }
1581                                None => {
1582                                    return Err(RpcError::new(
1583                                        INVALID_PARAMS,
1584                                        format!("filter.metadata.{k}.$exists must be a boolean"),
1585                                    ));
1586                                }
1587                            },
1588                            "$in" => {
1589                                let arr = op_val.as_array().ok_or_else(|| {
1590                                    RpcError::new(
1591                                        INVALID_PARAMS,
1592                                        format!("filter.metadata.{k}.$in must be an array"),
1593                                    )
1594                                })?;
1595                                f = f.metadata_in(k.clone(), arr.clone());
1596                            }
1597                            "$gte" | "$lte" => {
1598                                let mut min = None;
1599                                let mut max = None;
1600                                for (bound, bound_val) in ops {
1601                                    let n = bound_val.as_f64().ok_or_else(|| {
1602                                        RpcError::new(
1603                                            INVALID_PARAMS,
1604                                            format!("filter.metadata.{k}.{bound} must be a number"),
1605                                        )
1606                                    })?;
1607                                    match bound.as_str() {
1608                                        "$gte" => min = Some(n),
1609                                        "$lte" => max = Some(n),
1610                                        other => {
1611                                            return Err(RpcError::new(
1612                                                INVALID_PARAMS,
1613                                                format!(
1614                                                    "filter.metadata.{k}: unsupported range \
1615                                                     operator '{other}' (want $gte, $lte)"
1616                                                ),
1617                                            ));
1618                                        }
1619                                    }
1620                                }
1621                                f = f.metadata_range(k.clone(), min, max);
1622                                break; // All operator entries consumed in one pass.
1623                            }
1624                            other => {
1625                                return Err(RpcError::new(
1626                                    INVALID_PARAMS,
1627                                    format!(
1628                                        "filter.metadata.{k}: unknown operator '{other}' \
1629                                         (want $exists, $in, $gte, $lte)"
1630                                    ),
1631                                ));
1632                            }
1633                        }
1634                    }
1635                }
1636                // Plain scalar / array / string → equality.
1637                other => {
1638                    f = f.metadata_eq(k.clone(), other.clone());
1639                }
1640            }
1641        }
1642    }
1643    Ok(f)
1644}
1645
1646fn tool_forget(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1647    let id_str = args
1648        .get("id")
1649        .and_then(|v| v.as_str())
1650        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "forget: missing 'id'"))?;
1651    let ulid = crate::Ulid::from_string(id_str)
1652        .map_err(|_| RpcError::new(INVALID_PARAMS, format!("forget: invalid ULID '{id_str}'")))?;
1653    db.delete(&ulid).map_err(mnemo_err)?;
1654    db.flush().map_err(mnemo_err)?;
1655    Ok(json!({ "deleted": id_str }).to_string())
1656}
1657
1658fn tool_list(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1659    let include_vectors = args
1660        .get("include_vectors")
1661        .and_then(|v| v.as_bool())
1662        .unwrap_or(false);
1663    let mems = db.memories().map_err(mnemo_err)?;
1664    let out: Vec<Value> = mems
1665        .iter()
1666        .map(|m| {
1667            let mut v = memory_to_json(m);
1668            if !include_vectors {
1669                if let Some(o) = v.as_object_mut() {
1670                    o.remove("vector");
1671                }
1672            }
1673            v
1674        })
1675        .collect();
1676    Ok(serde_json::to_string_pretty(&out).unwrap_or_else(|_| "[]".into()))
1677}
1678
1679fn tool_snapshot_list(db: &mut Mnemo) -> std::result::Result<String, RpcError> {
1680    let snaps = db.snapshots();
1681    let out: Vec<Value> = snaps
1682        .into_iter()
1683        .map(|s| {
1684            json!({
1685                "txn_id": s.txn_id,
1686                "created_at": s.created_at,
1687                "memory_count": s.memory_count,
1688            })
1689        })
1690        .collect();
1691    Ok(serde_json::to_string_pretty(&out).unwrap_or_else(|_| "[]".into()))
1692}
1693
1694fn tool_stats(db: &mut Mnemo) -> std::result::Result<String, RpcError> {
1695    let s = db.stats().map_err(mnemo_err)?;
1696    let (cache_pages, cache_capacity) = db.page_cache_stats();
1697    let snapshot_count = db.snapshots().len();
1698    // Field names mirror `Stats` in `store/mod.rs` verbatim so MCP clients
1699    // that reference the Rust doc for the same DB see the same shape.
1700    Ok(json!({
1701        "memories": s.memories,
1702        "deleted": s.deleted,
1703        "dimensions": s.dimensions,
1704        "file_bytes": s.file_bytes,
1705        "agents": s.agents,
1706        "encrypted": s.encrypted,
1707        "created_at": s.created_at,
1708        "wal_pages": s.wal_pages,
1709        "recall_mode": s.recall_mode.as_str(),
1710        "index": s.index,
1711        "snapshot_count": snapshot_count,
1712        "snapshots_retained": s.snapshots_retained,
1713        "oldest_restorable_at": s.oldest_restorable_at,
1714        "snapshot_pinned_bytes": s.snapshot_pinned_bytes,
1715        "cache_pages": cache_pages,
1716        "cache_capacity": cache_capacity,
1717    })
1718    .to_string())
1719}
1720
1721// --- Result-cache tool handlers (Phase 10.4) -----------------------------
1722
1723fn tool_cache_put(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1724    let ns = args
1725        .get("namespace")
1726        .and_then(|v| v.as_str())
1727        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put: missing 'namespace'"))?;
1728    let key = args
1729        .get("key")
1730        .and_then(|v| v.as_str())
1731        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put: missing 'key'"))?;
1732    let value = args
1733        .get("value")
1734        .and_then(|v| v.as_str())
1735        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put: missing 'value'"))?;
1736    let content_type = args
1737        .get("content_type")
1738        .and_then(|v| v.as_str())
1739        .unwrap_or("text")
1740        .to_string();
1741    let ttl_secs = args.get("ttl_secs").and_then(|v| v.as_u64());
1742    let opts = CachePutOpts {
1743        content_type,
1744        ttl_secs,
1745        cost_hint_ms: None,
1746    };
1747    db.cache_put(ns, key, value.as_bytes(), opts)
1748        .map_err(mnemo_err)?;
1749    db.flush().map_err(mnemo_err)?;
1750    Ok(json!({ "cached": true, "namespace": ns, "key": key, "bytes": value.len() }).to_string())
1751}
1752
1753fn tool_cache_get(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1754    let ns = args
1755        .get("namespace")
1756        .and_then(|v| v.as_str())
1757        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_get: missing 'namespace'"))?;
1758    let key = args
1759        .get("key")
1760        .and_then(|v| v.as_str())
1761        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_get: missing 'key'"))?;
1762    match db.cache_get(ns, key).map_err(mnemo_err)? {
1763        Some(hit) => Ok(json!({
1764            "hit": true,
1765            "value": String::from_utf8_lossy(&hit.value),
1766            "content_type": hit.content_type,
1767            "created_at": hit.created_at,
1768            "accessed_at": hit.accessed_at,
1769            "access_count": hit.access_count,
1770        })
1771        .to_string()),
1772        None => Ok(json!({ "hit": false }).to_string()),
1773    }
1774}
1775
1776fn tool_cache_stats(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1777    let ns = args.get("namespace").and_then(|v| v.as_str());
1778    let s = db.cache_stats(ns);
1779    Ok(json!({
1780        "namespace": ns,
1781        "entries": s.entries,
1782        "bytes": s.bytes,
1783        "hits": s.hits,
1784        "misses": s.misses,
1785        "hit_rate": s.hit_rate,
1786        "evictions": s.evictions,
1787    })
1788    .to_string())
1789}
1790
1791fn tool_cache_put_semantic(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1792    let ns = args
1793        .get("namespace")
1794        .and_then(|v| v.as_str())
1795        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put_semantic: missing 'namespace'"))?;
1796    let key = args
1797        .get("key")
1798        .and_then(|v| v.as_str())
1799        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put_semantic: missing 'key'"))?;
1800    let value = args
1801        .get("value")
1802        .and_then(|v| v.as_str())
1803        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put_semantic: missing 'value'"))?;
1804    // When `text` is used, derive the model name from the server's
1805    // registered embedder (identity). Explicit `model` wins otherwise.
1806    let (vector, model) = match (args.get("vector"), args.get("text")) {
1807        (Some(_), Some(_)) => {
1808            return Err(RpcError::new(
1809                INVALID_PARAMS,
1810                "cache_put_semantic: pass EITHER 'vector' or 'text', not both",
1811            ));
1812        }
1813        (Some(v), None) => {
1814            let vec = v
1815                .as_array()
1816                .ok_or_else(|| {
1817                    RpcError::new(
1818                        INVALID_PARAMS,
1819                        "cache_put_semantic: 'vector' must be a JSON array",
1820                    )
1821                })?
1822                .iter()
1823                .map(|v| v.as_f64().map(|f| f as f32))
1824                .collect::<Option<Vec<f32>>>()
1825                .ok_or_else(|| {
1826                    RpcError::new(
1827                        INVALID_PARAMS,
1828                        "cache_put_semantic: 'vector' must be an array of numbers",
1829                    )
1830                })?;
1831            let model = args
1832                .get("model")
1833                .and_then(|v| v.as_str())
1834                .ok_or_else(|| {
1835                    RpcError::new(INVALID_PARAMS, "cache_put_semantic: missing 'model'")
1836                })?
1837                .to_string();
1838            (vec, model)
1839        }
1840        (None, Some(t)) => {
1841            let text = t.as_str().ok_or_else(|| {
1842                RpcError::new(
1843                    INVALID_PARAMS,
1844                    "cache_put_semantic: 'text' must be a string",
1845                )
1846            })?;
1847            let vec = embed_text_via_server(db, "cache_put_semantic", text)?;
1848            // Allow explicit model override; else derive from embedder.
1849            let model = match args.get("model").and_then(|v| v.as_str()) {
1850                Some(m) => m.to_string(),
1851                None => {
1852                    db.embedder()
1853                        .expect("embed_text_via_server would have errored otherwise")
1854                        .identity()
1855                        .name
1856                }
1857            };
1858            (vec, model)
1859        }
1860        (None, None) => {
1861            return Err(RpcError::new(
1862                INVALID_PARAMS,
1863                "cache_put_semantic: missing 'vector' or 'text'",
1864            ))
1865        }
1866    };
1867    let content_type = args
1868        .get("content_type")
1869        .and_then(|v| v.as_str())
1870        .unwrap_or("text")
1871        .to_string();
1872    let ttl_secs = args.get("ttl_secs").and_then(|v| v.as_u64());
1873    let opts = SemanticCachePutOpts {
1874        content_type,
1875        ttl_secs,
1876        cost_hint_ms: None,
1877        model,
1878    };
1879    db.cache_put_semantic(ns, key, vector, value.as_bytes(), opts)
1880        .map_err(mnemo_err)?;
1881    db.flush().map_err(mnemo_err)?;
1882    Ok(json!({ "cached": true, "namespace": ns, "key": key, "bytes": value.len() }).to_string())
1883}
1884
1885fn tool_cache_get_semantic(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1886    let ns = args
1887        .get("namespace")
1888        .and_then(|v| v.as_str())
1889        .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_get_semantic: missing 'namespace'"))?;
1890    // When `text` is used, derive the model name from the server's
1891    // registered embedder (identity). Explicit `model` wins otherwise.
1892    let (query, model_owned) = match (args.get("query"), args.get("text")) {
1893        (Some(_), Some(_)) => {
1894            return Err(RpcError::new(
1895                INVALID_PARAMS,
1896                "cache_get_semantic: pass EITHER 'query' or 'text', not both",
1897            ));
1898        }
1899        (Some(q), None) => {
1900            let vec = q
1901                .as_array()
1902                .ok_or_else(|| {
1903                    RpcError::new(
1904                        INVALID_PARAMS,
1905                        "cache_get_semantic: 'query' must be a JSON array",
1906                    )
1907                })?
1908                .iter()
1909                .map(|v| v.as_f64().map(|f| f as f32))
1910                .collect::<Option<Vec<f32>>>()
1911                .ok_or_else(|| {
1912                    RpcError::new(
1913                        INVALID_PARAMS,
1914                        "cache_get_semantic: 'query' must be an array of numbers",
1915                    )
1916                })?;
1917            let model = args
1918                .get("model")
1919                .and_then(|v| v.as_str())
1920                .ok_or_else(|| {
1921                    RpcError::new(INVALID_PARAMS, "cache_get_semantic: missing 'model'")
1922                })?
1923                .to_string();
1924            (vec, model)
1925        }
1926        (None, Some(t)) => {
1927            let text = t.as_str().ok_or_else(|| {
1928                RpcError::new(
1929                    INVALID_PARAMS,
1930                    "cache_get_semantic: 'text' must be a string",
1931                )
1932            })?;
1933            let vec = embed_text_via_server(db, "cache_get_semantic", text)?;
1934            let model = match args.get("model").and_then(|v| v.as_str()) {
1935                Some(m) => m.to_string(),
1936                None => {
1937                    db.embedder()
1938                        .expect("embed_text_via_server would have errored otherwise")
1939                        .identity()
1940                        .name
1941                }
1942            };
1943            (vec, model)
1944        }
1945        (None, None) => {
1946            return Err(RpcError::new(
1947                INVALID_PARAMS,
1948                "cache_get_semantic: missing 'query' or 'text'",
1949            ))
1950        }
1951    };
1952    let model = model_owned.as_str();
1953    let threshold = args
1954        .get("threshold")
1955        .and_then(|v| v.as_f64())
1956        .map(|f| f as f32)
1957        .unwrap_or(DEFAULT_SEMANTIC_THRESHOLD);
1958    match db
1959        .cache_get_semantic(ns, &query, threshold, model)
1960        .map_err(mnemo_err)?
1961    {
1962        Some((hit, similarity)) => Ok(json!({
1963            "hit": true,
1964            "similarity": similarity,
1965            "value": String::from_utf8_lossy(&hit.value),
1966            "content_type": hit.content_type,
1967            "created_at": hit.created_at,
1968            "accessed_at": hit.accessed_at,
1969            "access_count": hit.access_count,
1970        })
1971        .to_string()),
1972        None => Ok(json!({ "hit": false }).to_string()),
1973    }
1974}
1975
1976/// Serialize a `Memory` into the JSON shape MCP tool responses use.
1977/// Serde on `Memory` produces the canonical shape; we mirror what the
1978/// CLI's `memory_to_json` does but without the CLI-only vector-stripping
1979/// switch (that lives in the individual tools that care).
1980fn memory_to_json(m: &Memory) -> Value {
1981    serde_json::to_value(m).unwrap_or_else(|_| {
1982        let mut map = Map::new();
1983        map.insert("id".into(), json!(m.id.to_string()));
1984        Value::Object(map)
1985    })
1986}