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