1use std::io::{BufRead, BufReader, Read, Write};
47use std::path::Path;
48
49use serde::{Deserialize, Serialize};
50use serde_json::{json, Map, Value};
51
52use crate::error::{MnemoError, Result};
53use crate::memory::{Memory, MemoryType, Metric, Scope};
54use crate::result_cache::{CachePutOpts, SemanticCachePutOpts, DEFAULT_SEMANTIC_THRESHOLD};
55use crate::store::{Mnemo, RecallRequest};
56
57const PROTOCOL_VERSION: &str = "2025-06-18";
59
60const PASSPHRASE_ENV: &str = "MNEMO_PASSPHRASE";
62
63#[doc(hidden)]
68pub fn __fuzz_parse_request_line(line: &str) -> std::result::Result<(), String> {
69 serde_json::from_str::<Request>(line)
70 .map(|_| ())
71 .map_err(|e| e.to_string())
72}
73
74#[derive(Debug, Deserialize)]
79struct Request {
80 #[serde(default)]
81 jsonrpc: String,
82 #[serde(default)]
83 id: Option<Value>,
84 method: String,
85 #[serde(default)]
86 params: Value,
87}
88
89#[derive(Debug, Serialize)]
91struct Response {
92 jsonrpc: &'static str,
93 id: Value,
94 #[serde(skip_serializing_if = "Option::is_none")]
95 result: Option<Value>,
96 #[serde(skip_serializing_if = "Option::is_none")]
97 error: Option<RpcError>,
98}
99
100#[derive(Debug, Serialize)]
102struct RpcError {
103 code: i32,
104 message: String,
105 #[serde(skip_serializing_if = "Option::is_none")]
106 data: Option<Value>,
107}
108
109impl RpcError {
110 fn new(code: i32, message: impl Into<String>) -> Self {
111 Self {
112 code,
113 message: message.into(),
114 data: None,
115 }
116 }
117}
118
119const PARSE_ERROR: i32 = -32700;
121const INVALID_REQUEST: i32 = -32600;
122const METHOD_NOT_FOUND: i32 = -32601;
123const INVALID_PARAMS: i32 = -32602;
124const INTERNAL_ERROR: i32 = -32603;
125
126pub fn serve_stdio(path: &Path) -> Result<()> {
139 serve_stdio_with_embedder(path, None)
140}
141
142pub fn serve_stdio_with_embedder(
152 path: &Path,
153 embed_spec: Option<(String, String, bool, std::time::Duration)>,
154) -> Result<()> {
155 let stdin = std::io::stdin();
156 let stdout = std::io::stdout();
157 serve_with_streams(path, stdin.lock(), stdout.lock(), embed_spec)
158}
159
160pub fn serve_with_streams<R: Read, W: Write>(
164 path: &Path,
165 reader: R,
166 mut writer: W,
167 embed_spec: Option<(String, String, bool, std::time::Duration)>,
168) -> Result<()> {
169 let passphrase = std::env::var(PASSPHRASE_ENV).map_err(|_| {
170 MnemoError::Invalid(format!(
171 "{PASSPHRASE_ENV} is required to serve — set it in the shell before starting"
172 ))
173 })?;
174
175 eprintln!(
176 "mnemo mcp: opening {} (protocol {PROTOCOL_VERSION})",
177 path.display()
178 );
179 let mut db = Mnemo::open(path, &passphrase)?;
180 if let Some((cmd, name, normalize, timeout)) = embed_spec {
181 let identity = crate::EmbedderIdentity {
182 name,
183 dimensions: db.dimensions(),
184 normalize,
185 };
186 let embedder = crate::EmbedCmd::new(&cmd, identity)?.with_timeout(timeout);
187 db.set_embedder(embedder)?;
188 eprintln!(
189 "mnemo mcp: embedder ready (text params accepted, timeout {}s)",
190 timeout.as_secs()
191 );
192 }
193 eprintln!("mnemo mcp: ready ({} live memories)", db.len());
194
195 let reader = BufReader::new(reader);
196 for line in reader.lines() {
197 let line = line.map_err(MnemoError::Io)?;
198 let trimmed = line.trim();
199 if trimmed.is_empty() {
200 continue;
201 }
202
203 let (id, out) = match serde_json::from_str::<Request>(trimmed) {
204 Ok(req) => {
205 let id = req.id.clone();
206 let is_notification = id.is_none();
207 let result = handle(&mut db, &req);
208 if is_notification {
209 continue;
211 }
212 (id.unwrap_or(Value::Null), result)
213 }
214 Err(e) => (
215 Value::Null,
216 Err(RpcError::new(PARSE_ERROR, format!("parse error: {e}"))),
217 ),
218 };
219
220 let resp = match out {
221 Ok(value) => Response {
222 jsonrpc: "2.0",
223 id,
224 result: Some(value),
225 error: None,
226 },
227 Err(err) => Response {
228 jsonrpc: "2.0",
229 id,
230 result: None,
231 error: Some(err),
232 },
233 };
234
235 let line =
236 serde_json::to_string(&resp).map_err(|e| MnemoError::Serialize(e.to_string()))?;
237 writeln!(writer, "{line}").map_err(MnemoError::Io)?;
238 writer.flush().map_err(MnemoError::Io)?;
239 }
240 if let Err(e) = db.flush() {
252 eprintln!("mnemo mcp: flush on shutdown failed: {e}");
253 }
254 eprintln!("mnemo mcp: stdin closed, shutting down");
255 Ok(())
256}
257
258fn handle(db: &mut Mnemo, req: &Request) -> std::result::Result<Value, RpcError> {
263 if req.jsonrpc != "2.0" {
264 return Err(RpcError::new(
265 INVALID_REQUEST,
266 format!("expected jsonrpc \"2.0\", got {:?}", req.jsonrpc),
267 ));
268 }
269 match req.method.as_str() {
270 "initialize" => Ok(initialize_result(&req.params)),
271 "notifications/initialized" | "notifications/cancelled" => Ok(Value::Null),
272 "ping" => Ok(json!({})),
273 "tools/list" => Ok(tools_list()),
274 "tools/call" => tools_call(db, &req.params),
275 other => Err(RpcError::new(
276 METHOD_NOT_FOUND,
277 format!("method '{other}' not implemented"),
278 )),
279 }
280}
281
282fn initialize_result(params: &Value) -> Value {
285 let client_version = params
286 .get("protocolVersion")
287 .and_then(|v| v.as_str())
288 .unwrap_or(PROTOCOL_VERSION)
289 .to_string();
290 json!({
291 "protocolVersion": client_version,
292 "capabilities": {
293 "tools": { "listChanged": false },
294 },
295 "serverInfo": {
296 "name": "mnemo",
297 "version": env!("CARGO_PKG_VERSION"),
298 },
299 })
300}
301
302fn tools_list() -> Value {
308 json!({
309 "tools": [
310 {
311 "name": "about",
312 "description": "Read-only briefing for this .mnemo file: manifest scaffold plus any memories tagged as onboarding. Run this first to learn how the file expects to be used.",
313 "inputSchema": {
314 "type": "object",
315 "properties": {},
316 "additionalProperties": false
317 }
318 },
319 {
320 "name": "remember",
321 "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`.",
322 "inputSchema": {
323 "type": "object",
324 "required": ["content", "memory_type"],
325 "properties": {
326 "content": { "type": "string" },
327 "memory_type": { "type": "string", "enum": ["episodic", "semantic", "procedural", "working"] },
328 "vector": { "type": "array", "items": { "type": "number" }, "description": "Explicit embedding; mutually exclusive with `text`." },
329 "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." },
330 "importance": { "type": "number", "minimum": 0, "maximum": 1 },
331 "agent_id": { "type": "string" },
332 "session_id": { "type": "string" },
333 "ttl_secs": { "type": "integer" },
334 "shared": { "type": "boolean" },
335 "metadata": { "type": "object" },
336 "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." }
337 },
338 "additionalProperties": false
339 }
340 },
341 {
342 "name": "update",
343 "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.",
344 "inputSchema": {
345 "type": "object",
346 "required": ["id"],
347 "properties": {
348 "id": { "type": "string", "description": "ULID of the memory to update." },
349 "content": { "type": "string", "description": "New content. Requires a matching `vector` (use `text` to re-embed instead)." },
350 "vector": { "type": "array", "items": { "type": "number" } },
351 "text": { "type": "string", "description": "New content; the server embeds it through its registered embedder. Mutually exclusive with `content` + `vector`." },
352 "importance": { "type": "number", "minimum": 0, "maximum": 1 },
353 "metadata": { "type": "object", "description": "Replace the user-visible metadata. Reserved `_mnemo.*` keys on the record are preserved." },
354 "ttl_secs": { "type": "integer", "description": "Set the TTL to this many seconds. Use `clear_ttl: true` to drop any TTL." },
355 "clear_ttl": { "type": "boolean", "description": "Clear any TTL on the record." }
356 },
357 "additionalProperties": false
358 }
359 },
360 {
361 "name": "history",
362 "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. Use `agent` for a private-scope slot; omit for the shared slot.",
363 "inputSchema": {
364 "type": "object",
365 "required": ["key"],
366 "properties": {
367 "key": { "type": "string" },
368 "agent": { "type": "string" }
369 },
370 "additionalProperties": false
371 }
372 },
373 {
374 "name": "recall",
375 "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).",
376 "inputSchema": {
377 "type": "object",
378 "properties": {
379 "query": { "type": "array", "items": { "type": "number" }, "description": "Explicit query vector; mutually exclusive with `text`." },
380 "text": { "type": "string", "description": "Query text; embedded by the server's registered embedder. Mutually exclusive with `query`." },
381 "top_k": { "type": "integer", "default": 10 },
382 "types": { "type": "array", "items": { "type": "string" } },
383 "agent": { "type": "string" },
384 "metric": { "type": "string", "enum": ["cosine", "l2", "dot"], "default": "cosine" },
385 "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." },
386 "filter": {
387 "type": "object",
388 "description": "Phase 12.6 pre-scoring filter. All conditions AND together. Shape: `{\"session_id\": \"...\", \"metadata\": {key: value | {\"$in\": [...]} | {\"$exists\": true} | {\"$gte\": n, \"$lte\": n}}}`.",
389 "properties": {
390 "session_id": { "type": "string" },
391 "metadata": { "type": "object" }
392 },
393 "additionalProperties": false
394 }
395 },
396 "additionalProperties": false
397 }
398 },
399 {
400 "name": "forget",
401 "description": "Soft-delete a memory by ULID. Space is reclaimed on the next `mnemo compact`. Persists to disk before returning.",
402 "inputSchema": {
403 "type": "object",
404 "required": ["id"],
405 "properties": {
406 "id": { "type": "string", "description": "ULID of the memory to delete" }
407 },
408 "additionalProperties": false
409 }
410 },
411 {
412 "name": "list",
413 "description": "Return every live memory as JSON. Sorted by creation time, oldest first. Vectors are omitted by default to keep payloads small.",
414 "inputSchema": {
415 "type": "object",
416 "properties": {
417 "include_vectors": { "type": "boolean", "default": false }
418 },
419 "additionalProperties": false
420 }
421 },
422 {
423 "name": "snapshot_list",
424 "description": "List every restorable snapshot (one per committed flush). Each entry gives the transaction ID, creation timestamp, and memory count.",
425 "inputSchema": {
426 "type": "object",
427 "properties": {},
428 "additionalProperties": false
429 }
430 },
431 {
432 "name": "stats",
433 "description": "Summary statistics: memory count, deleted count, agents present, snapshot count, page cache occupancy.",
434 "inputSchema": {
435 "type": "object",
436 "properties": {},
437 "additionalProperties": false
438 }
439 },
440 {
441 "name": "cache_put",
442 "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.",
443 "inputSchema": {
444 "type": "object",
445 "required": ["namespace", "key", "value"],
446 "properties": {
447 "namespace": { "type": "string" },
448 "key": { "type": "string" },
449 "value": { "type": "string" },
450 "content_type": { "type": "string", "default": "text" },
451 "ttl_secs": { "type": "integer", "minimum": 0 }
452 },
453 "additionalProperties": false
454 }
455 },
456 {
457 "name": "cache_get",
458 "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.",
459 "inputSchema": {
460 "type": "object",
461 "required": ["namespace", "key"],
462 "properties": {
463 "namespace": { "type": "string" },
464 "key": { "type": "string" }
465 },
466 "additionalProperties": false
467 }
468 },
469 {
470 "name": "cache_stats",
471 "description": "Cache statistics for a namespace (omit for the whole cache). Returns entries, bytes, hits, misses, hit_rate, evictions.",
472 "inputSchema": {
473 "type": "object",
474 "properties": {
475 "namespace": { "type": "string" }
476 },
477 "additionalProperties": false
478 }
479 },
480 {
481 "name": "cache_put_semantic",
482 "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).",
483 "inputSchema": {
484 "type": "object",
485 "required": ["namespace", "key", "value"],
486 "properties": {
487 "namespace": { "type": "string" },
488 "key": { "type": "string" },
489 "vector": { "type": "array", "items": { "type": "number" }, "description": "Explicit embedding; mutually exclusive with `text`. Requires `model`." },
490 "text": { "type": "string", "description": "Content to embed via the server's registered embedder; mutually exclusive with `vector`." },
491 "value": { "type": "string" },
492 "model": { "type": "string", "description": "Required with `vector`; optional with `text` (defaults to the embedder's identity name)." },
493 "content_type": { "type": "string", "default": "text" },
494 "ttl_secs": { "type": "integer", "minimum": 0 }
495 },
496 "additionalProperties": false
497 }
498 },
499 {
500 "name": "cache_get_semantic",
501 "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.",
502 "inputSchema": {
503 "type": "object",
504 "required": ["namespace"],
505 "properties": {
506 "namespace": { "type": "string" },
507 "query": { "type": "array", "items": { "type": "number" }, "description": "Explicit query vector; mutually exclusive with `text`. Requires `model`." },
508 "text": { "type": "string", "description": "Query text; embedded by the server. Mutually exclusive with `query`." },
509 "model": { "type": "string", "description": "Required with `query`; optional with `text`." },
510 "threshold": { "type": "number", "minimum": -1.0, "maximum": 1.0 }
511 },
512 "additionalProperties": false
513 }
514 }
515 ]
516 })
517}
518
519fn tools_call(db: &mut Mnemo, params: &Value) -> std::result::Result<Value, RpcError> {
524 let name = params
525 .get("name")
526 .and_then(|v| v.as_str())
527 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "missing tool name"))?;
528 let empty = json!({});
529 let args = params.get("arguments").unwrap_or(&empty);
530
531 let text = match name {
532 "about" => tool_about(db)?,
533 "remember" => tool_remember(db, args)?,
534 "update" => tool_update(db, args)?,
535 "history" => tool_history(db, args)?,
536 "recall" => tool_recall(db, args)?,
537 "forget" => tool_forget(db, args)?,
538 "list" => tool_list(db, args)?,
539 "snapshot_list" => tool_snapshot_list(db)?,
540 "stats" => tool_stats(db)?,
541 "cache_put" => tool_cache_put(db, args)?,
542 "cache_get" => tool_cache_get(db, args)?,
543 "cache_stats" => tool_cache_stats(db, args)?,
544 "cache_put_semantic" => tool_cache_put_semantic(db, args)?,
545 "cache_get_semantic" => tool_cache_get_semantic(db, args)?,
546 other => {
547 return Err(RpcError::new(
548 METHOD_NOT_FOUND,
549 format!("unknown tool '{other}'"),
550 ))
551 }
552 };
553
554 Ok(json!({
555 "content": [ { "type": "text", "text": text } ],
556 "isError": false,
557 }))
558}
559
560fn embed_text_via_server(
571 db: &mut Mnemo,
572 tool: &str,
573 text: &str,
574) -> std::result::Result<Vec<f32>, RpcError> {
575 let embedder = db.embedder().ok_or_else(|| {
576 RpcError::new(
577 INVALID_PARAMS,
578 format!(
579 "{tool}: 'text' requires an embedder on the server. \
580 Start with: mnemo serve --mcp <file> --embed-cmd '<cmd>' --embed-name <name>"
581 ),
582 )
583 })?;
584 let mut vs = embedder.embed(&[text]).map_err(mnemo_err)?;
585 vs.pop().ok_or_else(|| {
586 RpcError::new(
587 INTERNAL_ERROR,
588 format!("{tool}: embedder returned no vector for the input text"),
589 )
590 })
591}
592
593fn mnemo_err(e: MnemoError) -> RpcError {
594 RpcError::new(INTERNAL_ERROR, e.to_string())
595}
596
597fn tool_about(db: &mut Mnemo) -> std::result::Result<String, RpcError> {
598 let mems = db.about().map_err(mnemo_err)?;
599 let arr: Vec<Value> = mems.iter().map(memory_to_json).collect();
600 Ok(serde_json::to_string_pretty(&arr).unwrap_or_else(|_| "[]".into()))
601}
602
603fn tool_remember(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
604 let content = args
605 .get("content")
606 .and_then(|v| v.as_str())
607 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "remember: missing 'content'"))?;
608 let mtype_str = args
609 .get("memory_type")
610 .and_then(|v| v.as_str())
611 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "remember: missing 'memory_type'"))?;
612 let mtype = MemoryType::parse(mtype_str).ok_or_else(|| {
613 RpcError::new(
614 INVALID_PARAMS,
615 format!("remember: unknown memory_type '{mtype_str}'"),
616 )
617 })?;
618 let vector = match (args.get("vector"), args.get("text")) {
621 (Some(_), Some(_)) => {
622 return Err(RpcError::new(
623 INVALID_PARAMS,
624 "remember: pass EITHER 'vector' or 'text', not both",
625 ));
626 }
627 (Some(v), None) => v
628 .as_array()
629 .ok_or_else(|| {
630 RpcError::new(INVALID_PARAMS, "remember: 'vector' must be a JSON array")
631 })?
632 .iter()
633 .map(|v| v.as_f64().map(|f| f as f32))
634 .collect::<Option<Vec<f32>>>()
635 .ok_or_else(|| {
636 RpcError::new(
637 INVALID_PARAMS,
638 "remember: 'vector' must be an array of numbers",
639 )
640 })?,
641 (None, Some(t)) => {
642 let text = t.as_str().ok_or_else(|| {
643 RpcError::new(INVALID_PARAMS, "remember: 'text' must be a string")
644 })?;
645 embed_text_via_server(db, "remember", text)?
646 }
647 (None, None) => {
648 return Err(RpcError::new(
649 INVALID_PARAMS,
650 "remember: missing 'vector' or 'text'",
651 ))
652 }
653 };
654
655 let mut mem = Memory::new(content, mtype, vector);
656 if let Some(agent) = args.get("agent_id").and_then(|v| v.as_str()) {
657 mem = mem.with_agent(agent);
658 }
659 if let Some(sess) = args.get("session_id").and_then(|v| v.as_str()) {
660 mem = mem.with_session(sess);
661 }
662 if let Some(imp) = args.get("importance").and_then(|v| v.as_f64()) {
663 mem = mem.with_importance(imp as f32);
664 }
665 if let Some(ttl) = args.get("ttl_secs").and_then(|v| v.as_i64()) {
666 mem = mem.with_ttl(ttl);
667 }
668 if let Some(shared) = args.get("shared").and_then(|v| v.as_bool()) {
669 if shared {
670 mem = mem.with_scope(Scope::Shared);
671 }
672 }
673 if let Some(meta) = args.get("metadata").and_then(|v| v.as_object()) {
674 for (k, v) in meta {
675 mem.metadata.insert(k.clone(), v.clone());
676 }
677 }
678
679 match args.get("key").and_then(|v| v.as_str()) {
684 None => {
685 let id = db.remember(mem).map_err(mnemo_err)?;
686 db.flush().map_err(mnemo_err)?;
687 Ok(json!({ "id": id.to_string(), "outcome": "inserted" }).to_string())
688 }
689 Some(k) => {
690 let (id, outcome) = db.remember_keyed(mem, k).map_err(mnemo_err)?;
691 db.flush().map_err(mnemo_err)?;
692 let outcome_str = match outcome {
693 crate::WriteOutcome::Added => "added",
694 crate::WriteOutcome::Superseded => "superseded",
695 crate::WriteOutcome::Unchanged => "unchanged",
696 crate::WriteOutcome::Updated => "superseded",
697 };
698 Ok(json!({ "id": id.to_string(), "outcome": outcome_str }).to_string())
699 }
700 }
701}
702
703fn tool_update(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
704 use crate::Ulid;
705 use crate::{MemoryPatch, WriteOutcome};
706 let id_str = args
707 .get("id")
708 .and_then(|v| v.as_str())
709 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "update: missing 'id'"))?;
710 let id = Ulid::from_string(id_str)
711 .map_err(|_| RpcError::new(INVALID_PARAMS, format!("update: invalid ULID '{id_str}'")))?;
712 let has_text = args.get("text").is_some();
716 let has_content = args.get("content").is_some();
717 let has_vector = args.get("vector").is_some();
718 if has_text && (has_content || has_vector) {
719 return Err(RpcError::new(
720 INVALID_PARAMS,
721 "update: pass EITHER 'text' or 'content'+'vector', not both",
722 ));
723 }
724 let mut patch = MemoryPatch::default();
725 if has_content {
726 let c = args
727 .get("content")
728 .and_then(|v| v.as_str())
729 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "update: 'content' must be a string"))?;
730 patch.content = Some(c.to_string());
731 }
732 if has_vector {
733 let v = args
734 .get("vector")
735 .and_then(|v| v.as_array())
736 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "update: 'vector' must be a JSON array"))?
737 .iter()
738 .map(|v| v.as_f64().map(|f| f as f32))
739 .collect::<Option<Vec<f32>>>()
740 .ok_or_else(|| {
741 RpcError::new(
742 INVALID_PARAMS,
743 "update: 'vector' must be an array of numbers",
744 )
745 })?;
746 patch.vector = Some(v);
747 }
748 if let Some(imp) = args.get("importance").and_then(|v| v.as_f64()) {
749 patch.importance = Some(imp as f32);
750 }
751 if let Some(meta) = args.get("metadata").and_then(|v| v.as_object()) {
752 patch.metadata = Some(meta.clone());
753 }
754 let clear_ttl = args
755 .get("clear_ttl")
756 .and_then(|v| v.as_bool())
757 .unwrap_or(false);
758 if clear_ttl {
759 patch.ttl_secs = Some(None);
760 } else if let Some(ttl) = args.get("ttl_secs").and_then(|v| v.as_i64()) {
761 patch.ttl_secs = Some(Some(ttl));
762 }
763
764 let outcome = if has_text {
765 let t = args
766 .get("text")
767 .and_then(|v| v.as_str())
768 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "update: 'text' must be a string"))?;
769 db.update_text(&id, t, patch).map_err(mnemo_err)?
770 } else {
771 db.update(&id, patch).map_err(mnemo_err)?
772 };
773 db.flush().map_err(mnemo_err)?;
774 let outcome_str = match outcome {
775 WriteOutcome::Updated => "updated",
776 WriteOutcome::Unchanged => "unchanged",
777 WriteOutcome::Added => "updated",
778 WriteOutcome::Superseded => "updated",
779 };
780 Ok(json!({ "id": id.to_string(), "outcome": outcome_str }).to_string())
781}
782
783fn tool_history(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
784 let key = args
785 .get("key")
786 .and_then(|v| v.as_str())
787 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "history: missing 'key'"))?;
788 let agent = args.get("agent").and_then(|v| v.as_str());
789 let chain = db.history(key, agent).map_err(mnemo_err)?;
790 let out: Vec<Value> = chain
791 .iter()
792 .enumerate()
793 .map(|(i, m)| {
794 let mut v = memory_to_json(m);
795 if let Some(obj) = v.as_object_mut() {
796 obj.insert(
797 "state".into(),
798 Value::String(if i == 0 {
799 "live".into()
800 } else {
801 "superseded".into()
802 }),
803 );
804 }
805 v
806 })
807 .collect();
808 Ok(serde_json::to_string_pretty(&out).unwrap_or_else(|_| "[]".into()))
809}
810
811fn tool_recall(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
812 let query = match (args.get("query"), args.get("text")) {
814 (Some(_), Some(_)) => {
815 return Err(RpcError::new(
816 INVALID_PARAMS,
817 "recall: pass EITHER 'query' or 'text', not both",
818 ))
819 }
820 (Some(v), None) => v
821 .as_array()
822 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "recall: 'query' must be a JSON array"))?
823 .iter()
824 .map(|v| v.as_f64().map(|f| f as f32))
825 .collect::<Option<Vec<f32>>>()
826 .ok_or_else(|| {
827 RpcError::new(
828 INVALID_PARAMS,
829 "recall: 'query' must be an array of numbers",
830 )
831 })?,
832 (None, Some(t)) => {
833 let text = t
834 .as_str()
835 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "recall: 'text' must be a string"))?;
836 embed_text_via_server(db, "recall", text)?
837 }
838 (None, None) => {
839 return Err(RpcError::new(
840 INVALID_PARAMS,
841 "recall: missing 'query' or 'text'",
842 ))
843 }
844 };
845 let top_k = args.get("top_k").and_then(|v| v.as_u64()).unwrap_or(10) as usize;
846 let metric = match args
847 .get("metric")
848 .and_then(|v| v.as_str())
849 .unwrap_or("cosine")
850 {
851 "cosine" => Metric::Cosine,
852 "l2" => Metric::L2,
853 "dot" => Metric::Dot,
854 other => {
855 return Err(RpcError::new(
856 INVALID_PARAMS,
857 format!("recall: unknown metric '{other}'"),
858 ))
859 }
860 };
861 let mut req = RecallRequest::new(query)
874 .top_k(top_k)
875 .metric(metric)
876 .track_access(true);
877 if let Some(types) = args.get("types").and_then(|v| v.as_array()) {
878 let parsed: Vec<MemoryType> = types
879 .iter()
880 .filter_map(|t| t.as_str().and_then(MemoryType::parse))
881 .collect();
882 if !parsed.is_empty() {
883 req = req.types(parsed);
884 }
885 }
886 if let Some(agent) = args.get("agent").and_then(|v| v.as_str()) {
887 req = req.agent(agent.to_string());
888 }
889 if let Some(filter_obj) = args.get("filter").and_then(|v| v.as_object()) {
896 req = req.filter(parse_mcp_filter(filter_obj)?);
897 }
898 let has_max_bytes = args.get("max_bytes").is_some();
900 if let Some(n) = args.get("max_bytes").and_then(|v| v.as_u64()) {
901 req = req.max_bytes(n as usize);
902 }
903
904 let resp = db.recall_budgeted(&req).map_err(mnemo_err)?;
905 let out: Vec<Value> = resp
906 .hits
907 .into_iter()
908 .map(|h| {
909 let mut obj = memory_to_json(&h.memory);
910 if let Some(map) = obj.as_object_mut() {
911 map.insert("score".into(), json!(h.score));
912 map.insert("similarity".into(), json!(h.similarity));
913 }
914 obj
915 })
916 .collect();
917 if has_max_bytes {
918 let wrapped = json!({
921 "hits": out,
922 "truncated": resp.truncated,
923 });
924 Ok(serde_json::to_string_pretty(&wrapped).unwrap_or_else(|_| "{}".into()))
925 } else {
926 Ok(serde_json::to_string_pretty(&out).unwrap_or_else(|_| "[]".into()))
927 }
928}
929
930fn parse_mcp_filter(
940 obj: &serde_json::Map<String, Value>,
941) -> std::result::Result<crate::Filter, RpcError> {
942 let mut f = crate::Filter::default();
943 if let Some(sid) = obj.get("session_id").and_then(|v| v.as_str()) {
944 f = f.with_session(sid.to_string());
945 }
946 if let Some(meta) = obj.get("metadata").and_then(|v| v.as_object()) {
947 for (k, v) in meta {
948 match v {
949 Value::Object(ops) => {
951 for (op_key, op_val) in ops {
952 match op_key.as_str() {
953 "$exists" => match op_val.as_bool() {
954 Some(true) => {
955 f = f.metadata_exists(k.clone());
956 }
957 Some(false) => {
958 return Err(RpcError::new(
959 INVALID_PARAMS,
960 format!(
961 "filter.metadata.{k}.$exists=false isn't supported; \
962 drop the filter term instead"
963 ),
964 ));
965 }
966 None => {
967 return Err(RpcError::new(
968 INVALID_PARAMS,
969 format!("filter.metadata.{k}.$exists must be a boolean"),
970 ));
971 }
972 },
973 "$in" => {
974 let arr = op_val.as_array().ok_or_else(|| {
975 RpcError::new(
976 INVALID_PARAMS,
977 format!("filter.metadata.{k}.$in must be an array"),
978 )
979 })?;
980 f = f.metadata_in(k.clone(), arr.clone());
981 }
982 "$gte" | "$lte" => {
983 let mut min = None;
984 let mut max = None;
985 for (bound, bound_val) in ops {
986 let n = bound_val.as_f64().ok_or_else(|| {
987 RpcError::new(
988 INVALID_PARAMS,
989 format!("filter.metadata.{k}.{bound} must be a number"),
990 )
991 })?;
992 match bound.as_str() {
993 "$gte" => min = Some(n),
994 "$lte" => max = Some(n),
995 other => {
996 return Err(RpcError::new(
997 INVALID_PARAMS,
998 format!(
999 "filter.metadata.{k}: unsupported range \
1000 operator '{other}' (want $gte, $lte)"
1001 ),
1002 ));
1003 }
1004 }
1005 }
1006 f = f.metadata_range(k.clone(), min, max);
1007 break; }
1009 other => {
1010 return Err(RpcError::new(
1011 INVALID_PARAMS,
1012 format!(
1013 "filter.metadata.{k}: unknown operator '{other}' \
1014 (want $exists, $in, $gte, $lte)"
1015 ),
1016 ));
1017 }
1018 }
1019 }
1020 }
1021 other => {
1023 f = f.metadata_eq(k.clone(), other.clone());
1024 }
1025 }
1026 }
1027 }
1028 Ok(f)
1029}
1030
1031fn tool_forget(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1032 let id_str = args
1033 .get("id")
1034 .and_then(|v| v.as_str())
1035 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "forget: missing 'id'"))?;
1036 let ulid = crate::Ulid::from_string(id_str)
1037 .map_err(|_| RpcError::new(INVALID_PARAMS, format!("forget: invalid ULID '{id_str}'")))?;
1038 db.delete(&ulid).map_err(mnemo_err)?;
1039 db.flush().map_err(mnemo_err)?;
1040 Ok(json!({ "deleted": id_str }).to_string())
1041}
1042
1043fn tool_list(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1044 let include_vectors = args
1045 .get("include_vectors")
1046 .and_then(|v| v.as_bool())
1047 .unwrap_or(false);
1048 let mems = db.memories().map_err(mnemo_err)?;
1049 let out: Vec<Value> = mems
1050 .iter()
1051 .map(|m| {
1052 let mut v = memory_to_json(m);
1053 if !include_vectors {
1054 if let Some(o) = v.as_object_mut() {
1055 o.remove("vector");
1056 }
1057 }
1058 v
1059 })
1060 .collect();
1061 Ok(serde_json::to_string_pretty(&out).unwrap_or_else(|_| "[]".into()))
1062}
1063
1064fn tool_snapshot_list(db: &mut Mnemo) -> std::result::Result<String, RpcError> {
1065 let snaps = db.snapshots();
1066 let out: Vec<Value> = snaps
1067 .into_iter()
1068 .map(|s| {
1069 json!({
1070 "txn_id": s.txn_id,
1071 "created_at": s.created_at,
1072 "memory_count": s.memory_count,
1073 })
1074 })
1075 .collect();
1076 Ok(serde_json::to_string_pretty(&out).unwrap_or_else(|_| "[]".into()))
1077}
1078
1079fn tool_stats(db: &mut Mnemo) -> std::result::Result<String, RpcError> {
1080 let s = db.stats().map_err(mnemo_err)?;
1081 let (cache_pages, cache_capacity) = db.page_cache_stats();
1082 let snapshot_count = db.snapshots().len();
1083 Ok(json!({
1086 "memories": s.memories,
1087 "deleted": s.deleted,
1088 "dimensions": s.dimensions,
1089 "file_bytes": s.file_bytes,
1090 "agents": s.agents,
1091 "encrypted": s.encrypted,
1092 "created_at": s.created_at,
1093 "wal_pages": s.wal_pages,
1094 "index": s.index,
1095 "snapshot_count": snapshot_count,
1096 "cache_pages": cache_pages,
1097 "cache_capacity": cache_capacity,
1098 })
1099 .to_string())
1100}
1101
1102fn tool_cache_put(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1105 let ns = args
1106 .get("namespace")
1107 .and_then(|v| v.as_str())
1108 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put: missing 'namespace'"))?;
1109 let key = args
1110 .get("key")
1111 .and_then(|v| v.as_str())
1112 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put: missing 'key'"))?;
1113 let value = args
1114 .get("value")
1115 .and_then(|v| v.as_str())
1116 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put: missing 'value'"))?;
1117 let content_type = args
1118 .get("content_type")
1119 .and_then(|v| v.as_str())
1120 .unwrap_or("text")
1121 .to_string();
1122 let ttl_secs = args.get("ttl_secs").and_then(|v| v.as_u64());
1123 let opts = CachePutOpts {
1124 content_type,
1125 ttl_secs,
1126 cost_hint_ms: None,
1127 };
1128 db.cache_put(ns, key, value.as_bytes(), opts)
1129 .map_err(mnemo_err)?;
1130 db.flush().map_err(mnemo_err)?;
1131 Ok(json!({ "cached": true, "namespace": ns, "key": key, "bytes": value.len() }).to_string())
1132}
1133
1134fn tool_cache_get(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1135 let ns = args
1136 .get("namespace")
1137 .and_then(|v| v.as_str())
1138 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_get: missing 'namespace'"))?;
1139 let key = args
1140 .get("key")
1141 .and_then(|v| v.as_str())
1142 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_get: missing 'key'"))?;
1143 match db.cache_get(ns, key).map_err(mnemo_err)? {
1144 Some(hit) => Ok(json!({
1145 "hit": true,
1146 "value": String::from_utf8_lossy(&hit.value),
1147 "content_type": hit.content_type,
1148 "created_at": hit.created_at,
1149 "accessed_at": hit.accessed_at,
1150 "access_count": hit.access_count,
1151 })
1152 .to_string()),
1153 None => Ok(json!({ "hit": false }).to_string()),
1154 }
1155}
1156
1157fn tool_cache_stats(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1158 let ns = args.get("namespace").and_then(|v| v.as_str());
1159 let s = db.cache_stats(ns);
1160 Ok(json!({
1161 "namespace": ns,
1162 "entries": s.entries,
1163 "bytes": s.bytes,
1164 "hits": s.hits,
1165 "misses": s.misses,
1166 "hit_rate": s.hit_rate,
1167 "evictions": s.evictions,
1168 })
1169 .to_string())
1170}
1171
1172fn tool_cache_put_semantic(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1173 let ns = args
1174 .get("namespace")
1175 .and_then(|v| v.as_str())
1176 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put_semantic: missing 'namespace'"))?;
1177 let key = args
1178 .get("key")
1179 .and_then(|v| v.as_str())
1180 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put_semantic: missing 'key'"))?;
1181 let value = args
1182 .get("value")
1183 .and_then(|v| v.as_str())
1184 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_put_semantic: missing 'value'"))?;
1185 let (vector, model) = match (args.get("vector"), args.get("text")) {
1188 (Some(_), Some(_)) => {
1189 return Err(RpcError::new(
1190 INVALID_PARAMS,
1191 "cache_put_semantic: pass EITHER 'vector' or 'text', not both",
1192 ));
1193 }
1194 (Some(v), None) => {
1195 let vec = v
1196 .as_array()
1197 .ok_or_else(|| {
1198 RpcError::new(
1199 INVALID_PARAMS,
1200 "cache_put_semantic: 'vector' must be a JSON array",
1201 )
1202 })?
1203 .iter()
1204 .map(|v| v.as_f64().map(|f| f as f32))
1205 .collect::<Option<Vec<f32>>>()
1206 .ok_or_else(|| {
1207 RpcError::new(
1208 INVALID_PARAMS,
1209 "cache_put_semantic: 'vector' must be an array of numbers",
1210 )
1211 })?;
1212 let model = args
1213 .get("model")
1214 .and_then(|v| v.as_str())
1215 .ok_or_else(|| {
1216 RpcError::new(INVALID_PARAMS, "cache_put_semantic: missing 'model'")
1217 })?
1218 .to_string();
1219 (vec, model)
1220 }
1221 (None, Some(t)) => {
1222 let text = t.as_str().ok_or_else(|| {
1223 RpcError::new(
1224 INVALID_PARAMS,
1225 "cache_put_semantic: 'text' must be a string",
1226 )
1227 })?;
1228 let vec = embed_text_via_server(db, "cache_put_semantic", text)?;
1229 let model = match args.get("model").and_then(|v| v.as_str()) {
1231 Some(m) => m.to_string(),
1232 None => {
1233 db.embedder()
1234 .expect("embed_text_via_server would have errored otherwise")
1235 .identity()
1236 .name
1237 }
1238 };
1239 (vec, model)
1240 }
1241 (None, None) => {
1242 return Err(RpcError::new(
1243 INVALID_PARAMS,
1244 "cache_put_semantic: missing 'vector' or 'text'",
1245 ))
1246 }
1247 };
1248 let content_type = args
1249 .get("content_type")
1250 .and_then(|v| v.as_str())
1251 .unwrap_or("text")
1252 .to_string();
1253 let ttl_secs = args.get("ttl_secs").and_then(|v| v.as_u64());
1254 let opts = SemanticCachePutOpts {
1255 content_type,
1256 ttl_secs,
1257 cost_hint_ms: None,
1258 model,
1259 };
1260 db.cache_put_semantic(ns, key, vector, value.as_bytes(), opts)
1261 .map_err(mnemo_err)?;
1262 db.flush().map_err(mnemo_err)?;
1263 Ok(json!({ "cached": true, "namespace": ns, "key": key, "bytes": value.len() }).to_string())
1264}
1265
1266fn tool_cache_get_semantic(db: &mut Mnemo, args: &Value) -> std::result::Result<String, RpcError> {
1267 let ns = args
1268 .get("namespace")
1269 .and_then(|v| v.as_str())
1270 .ok_or_else(|| RpcError::new(INVALID_PARAMS, "cache_get_semantic: missing 'namespace'"))?;
1271 let (query, model_owned) = match (args.get("query"), args.get("text")) {
1274 (Some(_), Some(_)) => {
1275 return Err(RpcError::new(
1276 INVALID_PARAMS,
1277 "cache_get_semantic: pass EITHER 'query' or 'text', not both",
1278 ));
1279 }
1280 (Some(q), None) => {
1281 let vec = q
1282 .as_array()
1283 .ok_or_else(|| {
1284 RpcError::new(
1285 INVALID_PARAMS,
1286 "cache_get_semantic: 'query' must be a JSON array",
1287 )
1288 })?
1289 .iter()
1290 .map(|v| v.as_f64().map(|f| f as f32))
1291 .collect::<Option<Vec<f32>>>()
1292 .ok_or_else(|| {
1293 RpcError::new(
1294 INVALID_PARAMS,
1295 "cache_get_semantic: 'query' must be an array of numbers",
1296 )
1297 })?;
1298 let model = args
1299 .get("model")
1300 .and_then(|v| v.as_str())
1301 .ok_or_else(|| {
1302 RpcError::new(INVALID_PARAMS, "cache_get_semantic: missing 'model'")
1303 })?
1304 .to_string();
1305 (vec, model)
1306 }
1307 (None, Some(t)) => {
1308 let text = t.as_str().ok_or_else(|| {
1309 RpcError::new(
1310 INVALID_PARAMS,
1311 "cache_get_semantic: 'text' must be a string",
1312 )
1313 })?;
1314 let vec = embed_text_via_server(db, "cache_get_semantic", text)?;
1315 let model = match args.get("model").and_then(|v| v.as_str()) {
1316 Some(m) => m.to_string(),
1317 None => {
1318 db.embedder()
1319 .expect("embed_text_via_server would have errored otherwise")
1320 .identity()
1321 .name
1322 }
1323 };
1324 (vec, model)
1325 }
1326 (None, None) => {
1327 return Err(RpcError::new(
1328 INVALID_PARAMS,
1329 "cache_get_semantic: missing 'query' or 'text'",
1330 ))
1331 }
1332 };
1333 let model = model_owned.as_str();
1334 let threshold = args
1335 .get("threshold")
1336 .and_then(|v| v.as_f64())
1337 .map(|f| f as f32)
1338 .unwrap_or(DEFAULT_SEMANTIC_THRESHOLD);
1339 match db
1340 .cache_get_semantic(ns, &query, threshold, model)
1341 .map_err(mnemo_err)?
1342 {
1343 Some((hit, similarity)) => Ok(json!({
1344 "hit": true,
1345 "similarity": similarity,
1346 "value": String::from_utf8_lossy(&hit.value),
1347 "content_type": hit.content_type,
1348 "created_at": hit.created_at,
1349 "accessed_at": hit.accessed_at,
1350 "access_count": hit.access_count,
1351 })
1352 .to_string()),
1353 None => Ok(json!({ "hit": false }).to_string()),
1354 }
1355}
1356
1357fn memory_to_json(m: &Memory) -> Value {
1362 serde_json::to_value(m).unwrap_or_else(|_| {
1363 let mut map = Map::new();
1364 map.insert("id".into(), json!(m.id.to_string()));
1365 Value::Object(map)
1366 })
1367}