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        // Either copy is re-admitted under the current policy before the query
69        // runs, so a masked value can never be matched (G5).
70        let result = match guard.current_full_content(&resolved) {
71            Some(Ok((full, _tokens))) => {
72                if let Some(ref q) = query {
73                    ccr_search_within(&full, q)
74                } else {
75                    full
76                }
77            }
78            Some(Err(reason)) => format!("ERROR: {reason}"),
79            None => {
80                format!("No cached content for \"{path_raw}\". Use ctx_read(\"{path_raw}\") first.")
81            }
82        };
83
84        Ok(ToolOutput::simple(result))
85    }
86}
87
88fn ccr_search_within(content: &str, query: &str) -> String {
89    let query_lower = query.to_lowercase();
90    let terms: Vec<&str> = query_lower.split_whitespace().collect();
91    if terms.is_empty() {
92        return content.to_string();
93    }
94
95    let mut matches: Vec<(usize, &str)> = Vec::new();
96    for (i, line) in content.lines().enumerate() {
97        let lower = line.to_lowercase();
98        if terms.iter().any(|t| lower.contains(t)) {
99            matches.push((i + 1, line));
100        }
101    }
102
103    if matches.is_empty() {
104        return format!("No lines matching \"{query}\" in cached content.");
105    }
106
107    let total = content.lines().count();
108    let mut out = format!("# {}/{total} lines match \"{query}\"\n", matches.len());
109    for (lineno, line) in matches.iter().take(200) {
110        out.push_str(&format!("{lineno:>6}| {line}\n"));
111    }
112    if matches.len() > 200 {
113        out.push_str(&format!("... and {} more matches\n", matches.len() - 200));
114    }
115    out
116}
117
118#[cfg(test)]
119mod tests {
120    use super::*;
121    use crate::core::cache::SessionCache;
122    use crate::server::tool_trait::ToolContext;
123    use std::collections::HashMap;
124    use std::sync::Arc;
125    use tokio::sync::RwLock;
126
127    fn ctx_with_cache(cache: Arc<RwLock<SessionCache>>, path: &str) -> ToolContext {
128        ToolContext {
129            cache: Some(cache),
130            resolved_paths: HashMap::from([("path".to_string(), path.to_string())]),
131            ..Default::default()
132        }
133    }
134
135    fn args(path: &str, query: Option<&str>) -> Map<String, Value> {
136        let mut m = Map::new();
137        m.insert("path".to_string(), Value::String(path.to_string()));
138        if let Some(q) = query {
139            m.insert("query".to_string(), Value::String(q.to_string()));
140        }
141        m
142    }
143
144    /// Run the real handler the way dispatch does: synchronously on a blocking
145    /// thread that still has a runtime handle (so `bounded_lock` can block_on).
146    async fn run(args: Map<String, Value>, ctx: ToolContext) -> String {
147        tokio::task::spawn_blocking(move || CtxRetrieveTool.handle(&args, &ctx))
148            .await
149            .unwrap()
150            .unwrap()
151            .text
152    }
153
154    #[tokio::test(flavor = "multi_thread")]
155    async fn retrieve_serves_cached_when_fresh() {
156        let dir = tempfile::tempdir().unwrap();
157        let file = dir.path().join("h.md");
158        std::fs::write(&file, "FRESH marker-AAA\n").unwrap();
159        let path = file.to_str().unwrap().to_string();
160
161        let cache = Arc::new(RwLock::new(SessionCache::new()));
162        cache.write().await.store(&path, "FRESH marker-AAA\n");
163
164        let out = run(args(&path, None), ctx_with_cache(cache, &path)).await;
165        assert!(out.contains("marker-AAA"), "got: {out}");
166    }
167
168    #[tokio::test(flavor = "multi_thread")]
169    async fn retrieve_rereads_changed_file_not_stale() {
170        // CCR retrieve after the file was edited must return the NEW content.
171        let dir = tempfile::tempdir().unwrap();
172        let file = dir.path().join("h.md");
173        std::fs::write(&file, "V1 marker-AAA\n").unwrap();
174        let path = file.to_str().unwrap().to_string();
175
176        let cache = Arc::new(RwLock::new(SessionCache::new()));
177        cache.write().await.store(&path, "V1 marker-AAA\n");
178
179        std::thread::sleep(std::time::Duration::from_millis(10));
180        std::fs::write(&file, "V2 marker-BBB\n").unwrap();
181
182        let out = run(args(&path, None), ctx_with_cache(cache, &path)).await;
183        assert!(out.contains("marker-BBB"), "fresh content missing: {out}");
184        assert!(!out.contains("marker-AAA"), "stale content served: {out}");
185    }
186
187    #[tokio::test(flavor = "multi_thread")]
188    async fn retrieve_query_runs_on_fresh_content() {
189        // A query must search the CURRENT file, not the stale cached copy.
190        let dir = tempfile::tempdir().unwrap();
191        let file = dir.path().join("h.md");
192        std::fs::write(&file, "old keep\n").unwrap();
193        let path = file.to_str().unwrap().to_string();
194
195        let cache = Arc::new(RwLock::new(SessionCache::new()));
196        cache.write().await.store(&path, "old keep\n");
197
198        std::thread::sleep(std::time::Duration::from_millis(10));
199        std::fs::write(&file, "alpha\nNEEDLE here\nbeta\n").unwrap();
200
201        let out = run(args(&path, Some("NEEDLE")), ctx_with_cache(cache, &path)).await;
202        assert!(
203            out.contains("NEEDLE"),
204            "query must match fresh content: {out}"
205        );
206    }
207
208    #[tokio::test(flavor = "multi_thread")]
209    async fn retrieve_without_cache_entry_directs_to_ctx_read() {
210        let dir = tempfile::tempdir().unwrap();
211        let file = dir.path().join("h.md");
212        std::fs::write(&file, "x\n").unwrap();
213        let path = file.to_str().unwrap().to_string();
214
215        let cache = Arc::new(RwLock::new(SessionCache::new())); // empty
216        let out = run(args(&path, None), ctx_with_cache(cache, &path)).await;
217        assert!(out.contains("No cached content"), "got: {out}");
218    }
219}