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