lean_ctx/tools/registered/
ctx_smart_read.rs1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, require_resolved_path};
6use crate::tool_defs::tool_def;
7
8pub struct CtxSmartReadTool;
9
10impl McpTool for CtxSmartReadTool {
11 fn name(&self) -> &'static str {
12 "ctx_smart_read"
13 }
14
15 fn tool_def(&self) -> Tool {
16 tool_def(
17 "ctx_smart_read",
18 "DEPRECATED → use ctx_read (it auto-selects the mode; omit `mode`). Folded\n\
19 into ctx_read (#509); hidden from tools/list, still callable for one release.",
20 json!({
21 "type": "object",
22 "properties": {
23 "path": { "type": "string", "description": "File path" }
24 },
25 "required": ["path"]
26 }),
27 )
28 }
29
30 fn handle(
31 &self,
32 args: &Map<String, Value>,
33 ctx: &ToolContext,
34 ) -> Result<ToolOutput, ErrorData> {
35 let path = require_resolved_path(ctx, args, "path")?;
36
37 if crate::core::binary_detect::is_binary_file(&path) {
38 let msg = crate::core::binary_detect::binary_file_message(&path);
39 return Err(ErrorData::invalid_params(msg, None));
40 }
41 {
42 let cap = crate::core::limits::max_read_bytes() as u64;
43 if let Ok(meta) = std::fs::metadata(&path)
44 && meta.len() > cap
45 {
46 let msg = format!(
47 "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
48 Use mode=\"lines:1-100\" for partial reads or increase the limit.",
49 meta.len(),
50 cap
51 );
52 return Err(ErrorData::invalid_params(msg, None));
53 }
54 }
55
56 tokio::task::block_in_place(|| {
57 let cache_lock = ctx
58 .cache
59 .as_ref()
60 .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
61 let timeout_dur =
62 crate::core::io_health::adaptive_timeout(std::time::Duration::from_secs(10));
63 let Ok(mut cache) = tokio::runtime::Handle::current()
64 .block_on(tokio::time::timeout(timeout_dur, cache_lock.write()))
65 else {
66 crate::core::io_health::record_freeze();
67 return Err(ErrorData::internal_error(
68 "cache busy (ctx_smart_read) — retry in a moment",
69 None,
70 ));
71 };
72 let output = crate::tools::ctx_smart_read::handle(&mut cache, &path, ctx.crp_mode);
73 let original = cache.get(&path).map_or(0, |e| e.original_tokens);
74 let tokens = crate::core::tokens::count_tokens(&output);
75 drop(cache);
76
77 let saved = original.saturating_sub(tokens);
78 Ok(ToolOutput {
79 text: output,
80 original_tokens: original,
81 saved_tokens: saved,
82 mode: Some("auto".to_string()),
83 path: Some(path),
84 changed: false,
85 shell_outcome: None,
86 })
87 })
88 }
89}