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