Skip to main content

lean_ctx/tools/registered/
ctx_read.rs

1use rmcp::model::Tool;
2use rmcp::ErrorData;
3use serde_json::{json, Map, Value};
4
5use crate::server::tool_trait::{get_bool, get_int, get_str, McpTool, ToolContext, ToolOutput};
6use crate::tool_defs::tool_def;
7use crate::tools::LeanCtxServer;
8
9pub struct CtxReadTool;
10
11impl McpTool for CtxReadTool {
12    fn name(&self) -> &'static str {
13        "ctx_read"
14    }
15
16    fn tool_def(&self) -> Tool {
17        tool_def(
18            "ctx_read",
19            "Read file (cached, compressed). Cached re-reads can be ~13 tok when unchanged. Auto-selects optimal mode. \
20Modes: full|map|signatures|diff|aggressive|entropy|task|reference|lines:N-M. fresh=true forces a disk re-read.",
21            json!({
22                "type": "object",
23                "properties": {
24                    "path": { "type": "string", "description": "Absolute file path to read" },
25                    "mode": {
26                        "type": "string",
27                        "description": "Compression mode (default: full). Use 'map' for context-only files. For line ranges: 'lines:N-M' (e.g. 'lines:400-500')."
28                    },
29                    "start_line": {
30                        "type": "integer",
31                        "description": "Read from this line number to end of file. Implies fresh=true (disk re-read) to avoid stale snippets."
32                    },
33                    "fresh": {
34                        "type": "boolean",
35                        "description": "Bypass cache and force a full re-read. Use when running as a subagent that may not have the parent's context."
36                    }
37                },
38                "required": ["path"]
39            }),
40        )
41    }
42
43    fn handle(
44        &self,
45        args: &Map<String, Value>,
46        ctx: &ToolContext,
47    ) -> Result<ToolOutput, ErrorData> {
48        let path = ctx
49            .resolved_path("path")
50            .ok_or_else(|| ErrorData::invalid_params("path is required", None))?
51            .to_string();
52
53        self.handle_inner(args, ctx, &path)
54    }
55}
56
57impl CtxReadTool {
58    #[allow(clippy::unused_self)]
59    fn handle_inner(
60        &self,
61        args: &Map<String, Value>,
62        ctx: &ToolContext,
63        path: &str,
64    ) -> Result<ToolOutput, ErrorData> {
65        let session_lock = ctx
66            .session
67            .as_ref()
68            .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
69        let cache_lock = ctx
70            .cache
71            .as_ref()
72            .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
73
74        let current_task = {
75            let session = session_lock.blocking_read();
76            session.task.as_ref().map(|t| t.description.clone())
77        };
78        let task_ref = current_task.as_deref();
79
80        let profile = crate::core::profiles::active_profile();
81        let mut mode = if let Some(m) = get_str(args, "mode") {
82            m
83        } else if profile.read.default_mode_effective() == "auto" {
84            let cache = cache_lock.blocking_read();
85            crate::tools::ctx_smart_read::select_mode_with_task(&cache, path, task_ref)
86        } else {
87            profile.read.default_mode_effective().to_string()
88        };
89
90        let mut fresh = get_bool(args, "fresh").unwrap_or(false);
91        let start_line = get_int(args, "start_line");
92        if let Some(sl) = start_line {
93            let sl = sl.max(1_i64);
94            mode = format!("lines:{sl}-999999");
95            fresh = true;
96        }
97
98        let gate_result = crate::server::context_gate::pre_dispatch_read(
99            path,
100            &mode,
101            task_ref,
102            Some(&ctx.project_root),
103        );
104        if let Some(overridden) = gate_result.overridden_mode {
105            mode = overridden;
106        }
107
108        let mode = if crate::tools::ctx_read::is_instruction_file(path) {
109            "full".to_string()
110        } else {
111            auto_degrade_read_mode(&mode)
112        };
113
114        let effective_mode = LeanCtxServer::upgrade_mode_if_stale(&mode, false).to_string();
115
116        if mode.starts_with("lines:") {
117            fresh = true;
118        }
119
120        if crate::core::binary_detect::is_binary_file(path) {
121            let msg = crate::core::binary_detect::binary_file_message(path);
122            return Err(ErrorData::invalid_params(msg, None));
123        }
124        {
125            let cap = crate::core::limits::max_read_bytes() as u64;
126            if let Ok(meta) = std::fs::metadata(path) {
127                if meta.len() > cap {
128                    let msg = format!(
129                        "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
130                         Use mode=\"lines:1-100\" for partial reads or increase the limit.",
131                        meta.len(),
132                        cap
133                    );
134                    return Err(ErrorData::invalid_params(msg, None));
135                }
136            }
137        }
138
139        // Acquire cache write lock for minimal duration: read + extract, then drop
140        let (output, resolved_mode, original, is_cache_hit, file_ref, cache_stats) = {
141            let mut cache = cache_lock.blocking_write();
142            let read_output = if fresh {
143                crate::tools::ctx_read::handle_fresh_with_task_resolved(
144                    &mut cache,
145                    path,
146                    &effective_mode,
147                    ctx.crp_mode,
148                    task_ref,
149                )
150            } else {
151                crate::tools::ctx_read::handle_with_task_resolved(
152                    &mut cache,
153                    path,
154                    &effective_mode,
155                    ctx.crp_mode,
156                    task_ref,
157                )
158            };
159            let content = read_output.content;
160            let rmode = read_output.resolved_mode;
161            let orig = cache.get(path).map_or(0, |e| e.original_tokens);
162            let hit = content.contains(" cached ");
163            let fref = cache.file_ref_map().get(path).cloned();
164            let stats = cache.get_stats();
165            let stats_snapshot = (stats.total_reads, stats.cache_hits);
166            (content, rmode, orig, hit, fref, stats_snapshot)
167        };
168
169        let stale_note = if !ctx.minimal && effective_mode != mode {
170            format!("[cache stale, {mode}→{effective_mode}]\n")
171        } else {
172            String::new()
173        };
174        let output = format!("{stale_note}{output}");
175        let output_tokens = crate::core::tokens::count_tokens(&output);
176        let saved = original.saturating_sub(output_tokens);
177
178        // Session updates (short lock)
179        let mut ensured_root: Option<String> = None;
180        let project_root_snapshot;
181        {
182            let mut session = session_lock.blocking_write();
183            session.touch_file(path, file_ref.as_deref(), &resolved_mode, original);
184            if is_cache_hit {
185                session.record_cache_hit();
186            }
187            if session.active_structured_intent.is_none() && session.files_touched.len() >= 2 {
188                let touched: Vec<String> = session
189                    .files_touched
190                    .iter()
191                    .map(|f| f.path.clone())
192                    .collect();
193                let inferred =
194                    crate::core::intent_engine::StructuredIntent::from_file_patterns(&touched);
195                if inferred.confidence >= 0.4 {
196                    session.active_structured_intent = Some(inferred);
197                }
198            }
199            let root_missing = session
200                .project_root
201                .as_deref()
202                .is_none_or(|r| r.trim().is_empty());
203            if root_missing {
204                if let Some(root) = crate::core::protocol::detect_project_root(path) {
205                    session.project_root = Some(root.clone());
206                    ensured_root = Some(root);
207                }
208            }
209            project_root_snapshot = session
210                .project_root
211                .clone()
212                .unwrap_or_else(|| ".".to_string());
213        }
214
215        if let Some(root) = ensured_root.as_deref() {
216            crate::core::index_orchestrator::ensure_all_background(root);
217        }
218
219        crate::core::heatmap::record_file_access(path, original, saved);
220
221        // Mode predictor + feedback — no locks needed, uses snapshots from above
222        {
223            let sig = crate::core::mode_predictor::FileSignature::from_path(path, original);
224            let density = if output_tokens > 0 {
225                original as f64 / output_tokens as f64
226            } else {
227                1.0
228            };
229            let outcome = crate::core::mode_predictor::ModeOutcome {
230                mode: resolved_mode.clone(),
231                tokens_in: original,
232                tokens_out: output_tokens,
233                density: density.min(1.0),
234            };
235            let mut predictor = crate::core::mode_predictor::ModePredictor::new();
236            predictor.set_project_root(&project_root_snapshot);
237            predictor.record(sig, outcome);
238            predictor.save();
239
240            let ext = std::path::Path::new(path)
241                .extension()
242                .and_then(|e| e.to_str())
243                .unwrap_or("")
244                .to_string();
245            let thresholds = crate::core::adaptive_thresholds::thresholds_for_path(path);
246            let feedback_outcome = crate::core::feedback::CompressionOutcome {
247                session_id: format!("{}", std::process::id()),
248                language: ext,
249                entropy_threshold: thresholds.bpe_entropy,
250                jaccard_threshold: thresholds.jaccard,
251                total_turns: cache_stats.0 as u32,
252                tokens_saved: saved as u64,
253                tokens_original: original as u64,
254                cache_hits: cache_stats.1 as u32,
255                total_reads: cache_stats.0 as u32,
256                task_completed: true,
257                timestamp: chrono::Local::now().to_rfc3339(),
258            };
259            let mut store = crate::core::feedback::FeedbackStore::load();
260            store.project_root = Some(project_root_snapshot.clone());
261            store.record_outcome(feedback_outcome);
262        }
263
264        // NOTE: pipeline_stats, context_ir, and ledger updates are handled by the
265        // dispatch layer's record_call flow. Agent registration requires server.agent_id
266        // which is not available in ToolContext; it will be added when ToolContext is
267        // extended with the remaining server state fields.
268
269        Ok(ToolOutput {
270            text: output,
271            original_tokens: original,
272            saved_tokens: saved,
273            mode: Some(resolved_mode),
274            path: Some(path.to_string()),
275        })
276    }
277}
278
279fn auto_degrade_read_mode(mode: &str) -> String {
280    use crate::core::degradation_policy::DegradationVerdictV1;
281    let profile = crate::core::profiles::active_profile();
282    if !profile.degradation.enforce_effective() {
283        return mode.to_string();
284    }
285    let policy = crate::core::degradation_policy::evaluate_v1_for_tool("ctx_read", None);
286    match policy.decision.verdict {
287        DegradationVerdictV1::Ok => mode.to_string(),
288        DegradationVerdictV1::Warn => match mode {
289            "full" => "map".to_string(),
290            other => other.to_string(),
291        },
292        DegradationVerdictV1::Throttle => match mode {
293            "full" | "map" => "signatures".to_string(),
294            other => other.to_string(),
295        },
296        DegradationVerdictV1::Block => "signatures".to_string(),
297    }
298}