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