Skip to main content

lean_ctx/tools/registered/
ctx_retrieve.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_str};
6use crate::tool_defs::tool_def;
7
8pub struct CtxRetrieveTool;
9
10impl McpTool for CtxRetrieveTool {
11    fn name(&self) -> &'static str {
12        "ctx_retrieve"
13    }
14
15    fn tool_def(&self) -> Tool {
16        tool_def(
17            "ctx_retrieve",
18            "Retrieve original uncompressed content from the session cache (CCR). \
19             Use when a compressed ctx_read output is insufficient.",
20            json!({
21                "type": "object",
22                "properties": {
23                    "path": {
24                        "type": "string",
25                        "description": "File path whose original content to retrieve"
26                    },
27                    "query": {
28                        "type": "string",
29                        "description": "Optional: search within cached content"
30                    }
31                },
32                "required": ["path"]
33            }),
34        )
35    }
36
37    fn handle(
38        &self,
39        args: &Map<String, Value>,
40        ctx: &ToolContext,
41    ) -> Result<ToolOutput, ErrorData> {
42        let path_raw = get_str(args, "path")
43            .ok_or_else(|| ErrorData::invalid_params("path is required", None))?;
44        let resolved = if let Some(p) = ctx.resolved_path("path") {
45            p.to_string()
46        } else if let Some(err) = ctx.path_error("path") {
47            return Err(ErrorData::invalid_params(format!("path: {err}"), None));
48        } else {
49            path_raw.clone()
50        };
51        let query = get_str(args, "query");
52
53        let cache = ctx
54            .cache
55            .as_ref()
56            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
57        let Some(guard) = crate::server::bounded_lock::read(cache, "ctx_retrieve") else {
58            return Ok(ToolOutput::simple(
59                "[retrieve unavailable — cache busy, retry]".to_string(),
60            ));
61        };
62        // `current_full_content` revalidates against disk and re-reads when the
63        // cached copy is stale, so CCR can never hand back a version that no
64        // longer matches the file (e.g. a handover file edited between agents).
65        let result = match guard.current_full_content(&resolved) {
66            Some((full, _tokens)) => {
67                if let Some(ref q) = query {
68                    ccr_search_within(&full, q)
69                } else {
70                    full
71                }
72            }
73            None => {
74                format!("No cached content for \"{path_raw}\". Use ctx_read(\"{path_raw}\") first.")
75            }
76        };
77
78        Ok(ToolOutput::simple(result))
79    }
80}
81
82fn ccr_search_within(content: &str, query: &str) -> String {
83    let query_lower = query.to_lowercase();
84    let terms: Vec<&str> = query_lower.split_whitespace().collect();
85    if terms.is_empty() {
86        return content.to_string();
87    }
88
89    let mut matches: Vec<(usize, &str)> = Vec::new();
90    for (i, line) in content.lines().enumerate() {
91        let lower = line.to_lowercase();
92        if terms.iter().any(|t| lower.contains(t)) {
93            matches.push((i + 1, line));
94        }
95    }
96
97    if matches.is_empty() {
98        return format!("No lines matching \"{query}\" in cached content.");
99    }
100
101    let total = content.lines().count();
102    let mut out = format!("# {}/{total} lines match \"{query}\"\n", matches.len());
103    for (lineno, line) in matches.iter().take(200) {
104        out.push_str(&format!("{lineno:>6}| {line}\n"));
105    }
106    if matches.len() > 200 {
107        out.push_str(&format!("... and {} more matches\n", matches.len() - 200));
108    }
109    out
110}
111
112#[cfg(test)]
113mod tests {
114    use super::*;
115    use crate::core::cache::SessionCache;
116    use crate::server::tool_trait::ToolContext;
117    use std::collections::HashMap;
118    use std::sync::Arc;
119    use tokio::sync::RwLock;
120
121    fn ctx_with_cache(cache: Arc<RwLock<SessionCache>>, path: &str) -> ToolContext {
122        ToolContext {
123            cache: Some(cache),
124            resolved_paths: HashMap::from([("path".to_string(), path.to_string())]),
125            ..Default::default()
126        }
127    }
128
129    fn args(path: &str, query: Option<&str>) -> Map<String, Value> {
130        let mut m = Map::new();
131        m.insert("path".to_string(), Value::String(path.to_string()));
132        if let Some(q) = query {
133            m.insert("query".to_string(), Value::String(q.to_string()));
134        }
135        m
136    }
137
138    /// Run the real handler the way dispatch does: synchronously on a blocking
139    /// thread that still has a runtime handle (so `bounded_lock` can block_on).
140    async fn run(args: Map<String, Value>, ctx: ToolContext) -> String {
141        tokio::task::spawn_blocking(move || CtxRetrieveTool.handle(&args, &ctx))
142            .await
143            .unwrap()
144            .unwrap()
145            .text
146    }
147
148    #[tokio::test(flavor = "multi_thread")]
149    async fn retrieve_serves_cached_when_fresh() {
150        let dir = tempfile::tempdir().unwrap();
151        let file = dir.path().join("h.md");
152        std::fs::write(&file, "FRESH marker-AAA\n").unwrap();
153        let path = file.to_str().unwrap().to_string();
154
155        let cache = Arc::new(RwLock::new(SessionCache::new()));
156        cache.write().await.store(&path, "FRESH marker-AAA\n");
157
158        let out = run(args(&path, None), ctx_with_cache(cache, &path)).await;
159        assert!(out.contains("marker-AAA"), "got: {out}");
160    }
161
162    #[tokio::test(flavor = "multi_thread")]
163    async fn retrieve_rereads_changed_file_not_stale() {
164        // CCR retrieve after the file was edited must return the NEW content.
165        let dir = tempfile::tempdir().unwrap();
166        let file = dir.path().join("h.md");
167        std::fs::write(&file, "V1 marker-AAA\n").unwrap();
168        let path = file.to_str().unwrap().to_string();
169
170        let cache = Arc::new(RwLock::new(SessionCache::new()));
171        cache.write().await.store(&path, "V1 marker-AAA\n");
172
173        std::thread::sleep(std::time::Duration::from_millis(10));
174        std::fs::write(&file, "V2 marker-BBB\n").unwrap();
175
176        let out = run(args(&path, None), ctx_with_cache(cache, &path)).await;
177        assert!(out.contains("marker-BBB"), "fresh content missing: {out}");
178        assert!(!out.contains("marker-AAA"), "stale content served: {out}");
179    }
180
181    #[tokio::test(flavor = "multi_thread")]
182    async fn retrieve_query_runs_on_fresh_content() {
183        // A query must search the CURRENT file, not the stale cached copy.
184        let dir = tempfile::tempdir().unwrap();
185        let file = dir.path().join("h.md");
186        std::fs::write(&file, "old keep\n").unwrap();
187        let path = file.to_str().unwrap().to_string();
188
189        let cache = Arc::new(RwLock::new(SessionCache::new()));
190        cache.write().await.store(&path, "old keep\n");
191
192        std::thread::sleep(std::time::Duration::from_millis(10));
193        std::fs::write(&file, "alpha\nNEEDLE here\nbeta\n").unwrap();
194
195        let out = run(args(&path, Some("NEEDLE")), ctx_with_cache(cache, &path)).await;
196        assert!(
197            out.contains("NEEDLE"),
198            "query must match fresh content: {out}"
199        );
200    }
201
202    #[tokio::test(flavor = "multi_thread")]
203    async fn retrieve_without_cache_entry_directs_to_ctx_read() {
204        let dir = tempfile::tempdir().unwrap();
205        let file = dir.path().join("h.md");
206        std::fs::write(&file, "x\n").unwrap();
207        let path = file.to_str().unwrap().to_string();
208
209        let cache = Arc::new(RwLock::new(SessionCache::new())); // empty
210        let out = run(args(&path, None), ctx_with_cache(cache, &path)).await;
211        assert!(out.contains("No cached content"), "got: {out}");
212    }
213}