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 crate::core::legacy_adoption::auto_adopt_shared_context(&ctx.project_root);
54 let store = SharedContext::for_project(&ctx.project_root).map_err(memory_error)?;
55 let limit = get_usize(args, "limit").unwrap_or(10);
56 let text = match action.as_str() {
57 "put" => {
58 let content = storable(required(args, "content")?)?;
59 let agent = get_str(args, "agent").unwrap_or_else(|| "unknown".to_string());
60 let category = get_str(args, "category").unwrap_or_else(|| "fact".to_string());
61 let id = store.put(content, agent, category).map_err(memory_error)?;
62 format!("stored {id}")
63 }
64 "get" => {
65 let query = required(args, "query")?;
66 served(&serialize(
67 &store.get_relevant(query, limit).map_err(memory_error)?,
68 )?)
69 }
70 "list" => {
71 let entries = match get_str(args, "category") {
72 Some(category) => store
73 .get_by_category(&category)
74 .map_err(memory_error)?
75 .into_iter()
76 .take(limit)
77 .collect(),
78 None => store.get_recent(limit).map_err(memory_error)?,
79 };
80 served(&serialize(&entries)?)
81 }
82 "stats" => serialize(&store.stats().map_err(memory_error)?)?,
83 "prune" => {
84 let max_age_seconds =
85 get_usize(args, "max_age_seconds").unwrap_or(60 * 60 * 24 * 30) as u64;
86 let max_entries = get_usize(args, "max_entries").unwrap_or(1_000);
87 let removed = store
88 .prune(max_age_seconds, max_entries)
89 .map_err(memory_error)?;
90 format!("pruned {removed} entries")
91 }
92 other => {
93 return Err(ErrorData::invalid_params(
94 format!("unknown action '{other}'"),
95 None,
96 ));
97 }
98 };
99 Ok(ToolOutput::simple(text))
100 }
101}
102
103fn required<'a>(args: &'a Map<String, Value>, key: &str) -> Result<&'a str, ErrorData> {
104 args.get(key)
105 .and_then(Value::as_str)
106 .filter(|value| !value.trim().is_empty())
107 .ok_or_else(|| ErrorData::invalid_params(format!("{key} is required"), None))
108}
109
110fn serialize<T: serde::Serialize>(value: &T) -> Result<String, ErrorData> {
111 serde_json::to_string_pretty(value).map_err(|error| {
112 ErrorData::internal_error(format!("serialize memory result: {error}"), None)
113 })
114}
115
116fn memory_error(error: impl std::fmt::Display) -> ErrorData {
117 ErrorData::internal_error(format!("shared context: {error}"), None)
118}
119
120fn storable(content: &str) -> Result<String, ErrorData> {
125 crate::core::context_admission::carrier::admit_for_store(content)
126 .map_err(|withheld| ErrorData::invalid_params(withheld.message("memory content"), None))
127}
128
129fn served(rendered: &str) -> String {
134 crate::tools::admitted_sources::serve_originless(rendered, "shared memory")
135 .unwrap_or_else(|reason| format!("[withheld: {reason}]"))
136}
137
138#[cfg(test)]
139mod tests {
140 use super::*;
141
142 #[test]
145 fn shared_memory_is_admitted_at_write_and_served_under_the_originless_rule() {
146 const AWS_KEY: &str = concat!("AK", "IAIOSFODNN7EXAMPLE");
147 let _data = crate::core::data_dir::isolated_data_dir();
148 let entries = "[\n {\n \"content\": \"retries live in net/retry.rs\"\n }\n]";
149 {
150 let _community = crate::core::policy::runtime::TestPolicyOverride::set(None);
151 let clean = storable("retries live in net/retry.rs");
152 assert!(clean.is_ok_and(|text| text == "retries live in net/retry.rs"));
153 let keyed = storable(&format!("deploy key is {AWS_KEY}"));
154 assert!(keyed.is_ok_and(|text| !text.contains(AWS_KEY)));
155 assert_eq!(served(entries), entries);
156 let legacy = served(&format!("[{{\"content\": \"key {AWS_KEY}\"}}]"));
157 assert!(!legacy.contains(AWS_KEY), "{legacy}");
158 }
159 let policy = crate::core::policy::load(
160 "name = \"ctx-memory-test\"\nversion = \"1.0.0\"\ndescription = \"test\"\n\
161 [filters]\nclassification = \"block\"\nblocked_labels = [\"CONFIDENTIAL\"]\n",
162 )
163 .unwrap();
164 let _policy = crate::core::policy::runtime::TestPolicyOverride::set(Some(policy));
165 assert!(storable("CONFIDENTIAL\nroadmap-marker").is_err());
166 let withheld = served(entries);
167 assert!(withheld.starts_with("[withheld: "), "{withheld}");
168 assert!(!withheld.contains("retry.rs"), "{withheld}");
169 }
170
171 #[test]
172 fn memory_tool_schema_has_expected_actions() {
173 let definition = CtxMemoryTool.tool_def();
174 assert_eq!(definition.name, "ctx_memory");
175 }
176}