Skip to main content

lean_ctx/tools/registered/
ctx_retrieve.rs

1use rmcp::model::Tool;
2use rmcp::ErrorData;
3use serde_json::{json, Map, Value};
4
5use crate::server::tool_trait::{get_str, McpTool, ToolContext, ToolOutput};
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 = ctx.resolved_path("path").unwrap_or(&path_raw).to_string();
45        let query = get_str(args, "query");
46
47        let cache = ctx.cache.as_ref().unwrap();
48        let guard = tokio::task::block_in_place(|| cache.blocking_read());
49        let result = match guard.get_full_content(&resolved) {
50            Some(full) => {
51                if let Some(ref q) = query {
52                    ccr_search_within(&full, q)
53                } else {
54                    full
55                }
56            }
57            None => {
58                format!("No cached content for \"{path_raw}\". Use ctx_read(\"{path_raw}\") first.")
59            }
60        };
61
62        Ok(ToolOutput::simple(result))
63    }
64}
65
66fn ccr_search_within(content: &str, query: &str) -> String {
67    let query_lower = query.to_lowercase();
68    let terms: Vec<&str> = query_lower.split_whitespace().collect();
69    if terms.is_empty() {
70        return content.to_string();
71    }
72
73    let mut matches: Vec<(usize, &str)> = Vec::new();
74    for (i, line) in content.lines().enumerate() {
75        let lower = line.to_lowercase();
76        if terms.iter().any(|t| lower.contains(t)) {
77            matches.push((i + 1, line));
78        }
79    }
80
81    if matches.is_empty() {
82        return format!("No lines matching \"{query}\" in cached content.");
83    }
84
85    let total = content.lines().count();
86    let mut out = format!("# {}/{total} lines match \"{query}\"\n", matches.len());
87    for (lineno, line) in matches.iter().take(200) {
88        out.push_str(&format!("{lineno:>6}| {line}\n"));
89    }
90    if matches.len() > 200 {
91        out.push_str(&format!("... and {} more matches\n", matches.len() - 200));
92    }
93    out
94}