Skip to main content

lean_ctx/tools/registered/
ctx_smart_read.rs

1use rmcp::model::Tool;
2use rmcp::ErrorData;
3use serde_json::{json, Map, Value};
4
5use crate::server::tool_trait::{require_resolved_path, McpTool, ToolContext, ToolOutput};
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            "Auto-select optimal read mode for a file.",
19            json!({
20                "type": "object",
21                "properties": {
22                    "path": { "type": "string", "description": "Absolute file path to read" }
23                },
24                "required": ["path"]
25            }),
26        )
27    }
28
29    fn handle(
30        &self,
31        args: &Map<String, Value>,
32        ctx: &ToolContext,
33    ) -> Result<ToolOutput, ErrorData> {
34        let path = require_resolved_path(ctx, args, "path")?;
35
36        if crate::core::binary_detect::is_binary_file(&path) {
37            let msg = crate::core::binary_detect::binary_file_message(&path);
38            return Err(ErrorData::invalid_params(msg, None));
39        }
40        {
41            let cap = crate::core::limits::max_read_bytes() as u64;
42            if let Ok(meta) = std::fs::metadata(&path) {
43                if meta.len() > cap {
44                    let msg = format!(
45                        "File too large ({} bytes, limit {} bytes via LCTX_MAX_READ_BYTES). \
46                         Use mode=\"lines:1-100\" for partial reads or increase the limit.",
47                        meta.len(),
48                        cap
49                    );
50                    return Err(ErrorData::invalid_params(msg, None));
51                }
52            }
53        }
54
55        tokio::task::block_in_place(|| {
56            let cache_lock = ctx
57                .cache
58                .as_ref()
59                .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
60            let mut cache = cache_lock.blocking_write();
61            let output = crate::tools::ctx_smart_read::handle(&mut cache, &path, ctx.crp_mode);
62            let original = cache.get(&path).map_or(0, |e| e.original_tokens);
63            let tokens = crate::core::tokens::count_tokens(&output);
64            drop(cache);
65
66            let saved = original.saturating_sub(tokens);
67            Ok(ToolOutput {
68                text: output,
69                original_tokens: original,
70                saved_tokens: saved,
71                mode: Some("auto".to_string()),
72                path: Some(path),
73                changed: false,
74            })
75        })
76    }
77}