lean_ctx/tools/registered/
ctx_memory.rs1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::core::shared_context::SharedContext;
6use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_str, get_usize};
7use crate::tool_defs::tool_def;
8
9pub struct CtxMemoryTool;
10
11impl McpTool for CtxMemoryTool {
12 fn name(&self) -> &'static str {
13 "ctx_memory"
14 }
15
16 fn tool_def(&self) -> Tool {
17 tool_def(
18 self.name(),
19 "Store and retrieve durable cross-agent facts with BLAKE3 deduplication.",
20 json!({
21 "type": "object",
22 "properties": {
23 "action": {
24 "type": "string",
25 "enum": ["put", "get", "list", "stats", "prune"],
26 "description": "Memory operation"
27 },
28 "content": { "type": "string", "description": "Fact content (required for put)" },
29 "agent": { "type": "string", "description": "Agent identity for put; defaults to unknown" },
30 "query": { "type": "string", "description": "Keyword query (required for get)" },
31 "category": {
32 "type": "string",
33 "enum": ["fact", "decision", "blocker", "pattern"],
34 "description": "Category for put or list filter"
35 },
36 "limit": { "type": "integer", "minimum": 0, "default": 10 },
37 "max_age_seconds": { "type": "integer", "minimum": 0, "description": "Maximum idle age for prune" },
38 "max_entries": { "type": "integer", "minimum": 0, "description": "Maximum entries retained by prune" }
39 },
40 "required": ["action"]
41 }),
42 )
43 }
44
45 fn handle(
46 &self,
47 args: &Map<String, Value>,
48 _ctx: &ToolContext,
49 ) -> Result<ToolOutput, ErrorData> {
50 let action = get_str(args, "action")
51 .ok_or_else(|| ErrorData::invalid_params("action is required", None))?;
52 let store = SharedContext::default();
53 let limit = get_usize(args, "limit").unwrap_or(10);
54 let text = match action.as_str() {
55 "put" => {
56 let content = required(args, "content")?;
57 let agent = get_str(args, "agent").unwrap_or_else(|| "unknown".to_string());
58 let category = get_str(args, "category").unwrap_or_else(|| "fact".to_string());
59 let id = store.put(content, agent, category).map_err(memory_error)?;
60 format!("stored {id}")
61 }
62 "get" => {
63 let query = required(args, "query")?;
64 serialize(&store.get_relevant(query, limit).map_err(memory_error)?)?
65 }
66 "list" => {
67 let entries = match get_str(args, "category") {
68 Some(category) => store
69 .get_by_category(&category)
70 .map_err(memory_error)?
71 .into_iter()
72 .take(limit)
73 .collect(),
74 None => store.get_recent(limit).map_err(memory_error)?,
75 };
76 serialize(&entries)?
77 }
78 "stats" => serialize(&store.stats().map_err(memory_error)?)?,
79 "prune" => {
80 let max_age_seconds =
81 get_usize(args, "max_age_seconds").unwrap_or(60 * 60 * 24 * 30) as u64;
82 let max_entries = get_usize(args, "max_entries").unwrap_or(1_000);
83 let removed = store
84 .prune(max_age_seconds, max_entries)
85 .map_err(memory_error)?;
86 format!("pruned {removed} entries")
87 }
88 other => {
89 return Err(ErrorData::invalid_params(
90 format!("unknown action '{other}'"),
91 None,
92 ));
93 }
94 };
95 Ok(ToolOutput::simple(text))
96 }
97}
98
99fn required<'a>(args: &'a Map<String, Value>, key: &str) -> Result<&'a str, ErrorData> {
100 args.get(key)
101 .and_then(Value::as_str)
102 .filter(|value| !value.trim().is_empty())
103 .ok_or_else(|| ErrorData::invalid_params(format!("{key} is required"), None))
104}
105
106fn serialize<T: serde::Serialize>(value: &T) -> Result<String, ErrorData> {
107 serde_json::to_string_pretty(value).map_err(|error| {
108 ErrorData::internal_error(format!("serialize memory result: {error}"), None)
109 })
110}
111
112fn memory_error(error: impl std::fmt::Display) -> ErrorData {
113 ErrorData::internal_error(format!("shared context: {error}"), None)
114}
115
116#[cfg(test)]
117mod tests {
118 use super::*;
119
120 #[test]
121 fn memory_tool_schema_has_expected_actions() {
122 let definition = CtxMemoryTool.tool_def();
123 assert_eq!(definition.name, "ctx_memory");
124 }
125}