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