Skip to main content

lean_ctx/tools/registered/
ctx_multi_read.rs

1// noqa: SIZE_OK — single-responsibility tool handler, 255 pure LOC (5 over).
2// Inline tests (~80 lines) are conventional in Rust. Self-contained MCP tool wrapper.
3use rmcp::ErrorData;
4use rmcp::model::Tool;
5use serde_json::{Map, Value, json};
6
7use crate::server::tool_trait::{
8    McpTool, ToolContext, ToolOutput, get_bool, get_str, get_str_array,
9};
10use crate::tool_defs::tool_def;
11
12pub struct CtxMultiReadTool;
13
14impl McpTool for CtxMultiReadTool {
15    fn name(&self) -> &'static str {
16        "ctx_multi_read"
17    }
18
19    fn tool_def(&self) -> Tool {
20        tool_def(
21            "ctx_multi_read",
22            "DEPRECATED → use ctx_read with paths=['a.rs','b.rs']. Folded into ctx_read\n\
23             (#509); hidden from tools/list, still callable for one release.",
24            json!({
25                "type": "object",
26                "properties": {
27                    "paths": {
28                        "type": "array",
29                        "items": { "type": "string" },
30                        "description": "Paths to batch-read, in order"
31                    },
32                    "mode": {
33                        "type": "string",
34                        "default": "auto",
35                        "description": "auto|full|raw|signatures|map (same as ctx_read)"
36                    },
37                    "fresh": {
38                        "type": "boolean",
39                        "description": "Bypass cache, full re-read"
40                    }
41                },
42                "required": ["paths"]
43            }),
44        )
45    }
46
47    fn handle(
48        &self,
49        args: &Map<String, Value>,
50        ctx: &ToolContext,
51    ) -> Result<ToolOutput, ErrorData> {
52        batch_read(args, ctx)
53    }
54}
55
56/// Batch-read multiple files in one call. The single implementation shared by
57/// the (deprecated) `ctx_multi_read` tool and by `ctx_read` when it is called
58/// with a `paths` array (#509) — no duplicated batch logic across the two.
59///
60/// Panic guard (mirrors ctx_read): a panic in tree-sitter / compression must
61/// never unwind through the dispatch `block_in_place` and kill the MCP server.
62pub(crate) fn batch_read(
63    args: &Map<String, Value>,
64    ctx: &ToolContext,
65) -> Result<ToolOutput, ErrorData> {
66    match std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| handle_inner(args, ctx))) {
67        Ok(result) => result,
68        Err(_) => Err(ErrorData::internal_error(
69            "ctx_multi_read panicked while processing the batch. This is a bug — please report it.",
70            None,
71        )),
72    }
73}
74
75fn handle_inner(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
76    let raw_paths = get_str_array(args, "paths")
77        .ok_or_else(|| ErrorData::invalid_params("paths array is required", None))?;
78
79    let session_lock = ctx
80        .session
81        .as_ref()
82        .ok_or_else(|| ErrorData::internal_error("session not available", None))?;
83    let cache_lock = ctx
84        .cache
85        .as_ref()
86        .ok_or_else(|| ErrorData::internal_error("cache not available", None))?;
87
88    let cap = crate::core::limits::max_read_bytes() as u64;
89
90    // Resolve + filter paths and capture the active task under one short read lock.
91    // `bounded_lock` uses `Handle::block_on` directly — NOT a nested
92    // `block_in_place` — because the dispatch layer already wraps this handler in
93    // `block_in_place`. The previous nested `block_in_place` calls could exhaust the
94    // 32-thread blocking pool under concurrent reads and freeze the server (#271).
95    let (paths, current_task) = {
96        let Some(session) =
97            crate::server::bounded_lock::read(session_lock, "ctx_multi_read:session")
98        else {
99            return Err(ErrorData::internal_error(
100                "session read-lock timeout in ctx_multi_read — another tool may be holding it. Retry in a moment.",
101                None,
102            ));
103        };
104        let mut paths = Vec::with_capacity(raw_paths.len());
105        for p in &raw_paths {
106            let resolved = super::resolve_path_sync(&session, p)
107                .map_err(|e| ErrorData::invalid_params(e, None))?;
108            if crate::core::binary_detect::is_binary_file(&resolved) {
109                continue;
110            }
111            if let Ok(meta) = std::fs::metadata(&resolved)
112                && meta.len() > cap
113            {
114                continue;
115            }
116            paths.push(resolved);
117        }
118        let current_task = session.task.as_ref().map(|t| t.description.clone());
119        (paths, current_task)
120    };
121
122    if paths.is_empty() {
123        return Err(ErrorData::invalid_params(
124            "all paths are binary or exceed the size limit",
125            None,
126        ));
127    }
128
129    // Default to the profile's read mode (auto) and let ctx_read resolve the
130    // optimal mode per file. Previously this forced auto→full, which is exactly
131    // the "everything comes back as full" complaint (#421): batch reads must
132    // honour auto like single ctx_read does.
133    let mode = get_str(args, "mode").unwrap_or_else(|| {
134        crate::core::profiles::active_profile()
135            .read
136            .default_mode_effective()
137            .to_string()
138    });
139    let fresh = get_bool(args, "fresh").unwrap_or(false);
140
141    // Batch read under one bounded write lock. `bounded_lock` guarantees we never
142    // block the runtime indefinitely and degrade gracefully on contention instead
143    // of hanging; ctx_read's own fast/slow path tolerates this lock being held.
144    let Some(mut cache) = crate::server::bounded_lock::write(cache_lock, "ctx_multi_read:cache")
145    else {
146        return Err(ErrorData::internal_error(
147            "cache write-lock timeout in ctx_multi_read — another tool may be holding it. Retry in a moment.",
148            None,
149        ));
150    };
151    let output = crate::tools::ctx_multi_read::handle_with_task_fresh(
152        &mut cache,
153        &paths,
154        &mode,
155        fresh,
156        ctx.crp_mode,
157        current_task.as_deref(),
158    );
159    let mut total_original: usize = 0;
160    for path in &paths {
161        total_original =
162            total_original.saturating_add(cache.get(path).map_or(0, |e| e.original_tokens));
163    }
164    let tokens = crate::core::tokens::count_tokens(&output);
165    drop(cache);
166
167    Ok(ToolOutput {
168        text: output,
169        original_tokens: total_original,
170        saved_tokens: total_original.saturating_sub(tokens),
171        mode: Some(mode),
172        path: None,
173        changed: false,
174        shell_outcome: None,
175    })
176}
177
178#[cfg(test)]
179mod tests {
180    use super::*;
181    use std::sync::Arc;
182    use std::time::Duration;
183    use tokio::sync::RwLock;
184
185    use crate::core::cache::SessionCache;
186    use crate::core::session::SessionState;
187    use crate::tools::CrpMode;
188
189    fn ctx_with(
190        cache: Arc<RwLock<SessionCache>>,
191        session: Arc<RwLock<SessionState>>,
192        project_root: &str,
193    ) -> ToolContext {
194        ToolContext {
195            project_root: project_root.to_string(),
196            extra_roots: Vec::new(),
197            minimal: false,
198            resolved_paths: std::collections::HashMap::new(),
199            crp_mode: CrpMode::Off,
200            cache: Some(cache),
201            session: Some(session),
202            tool_calls: None,
203            agent_id: None,
204            workflow: None,
205            ledger: None,
206            client_name: None,
207            pipeline_stats: None,
208            call_count: None,
209            autonomy: None,
210            pressure_snapshot: None,
211            path_errors: std::collections::HashMap::new(),
212            bm25_cache: None,
213            progress_sender: None,
214        }
215    }
216
217    /// Regression for #271 (crash vector 11): under concurrent load,
218    /// `ctx_multi_read` must not hang. The handler runs inside the dispatch
219    /// layer's `block_in_place`, so it must acquire its session/cache locks
220    /// via `Handle::block_on` WITHOUT nesting another `block_in_place` —
221    /// nesting consumes extra blocking-pool threads and, under load, exhausts
222    /// the pool, hanging the call (no JSON-RPC response → client "invoke"
223    /// error).
224    ///
225    /// With only 2 worker threads and 8 concurrent batch reads, a nested
226    /// `block_in_place` regression would deadlock the pool and trip the 20s
227    /// timeout below.
228    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
229    async fn concurrent_multi_read_does_not_hang() {
230        let dir = tempfile::tempdir().unwrap();
231        let mut paths = Vec::new();
232        for i in 0..6 {
233            let p = dir.path().join(format!("file_{i}.rs"));
234            std::fs::write(&p, format!("fn f{i}() {{ let _ = {i}; }}\n")).unwrap();
235            paths.push(p.to_string_lossy().to_string());
236        }
237        let root = dir.path().to_string_lossy().to_string();
238
239        let cache: Arc<RwLock<SessionCache>> = Arc::new(RwLock::new(SessionCache::new()));
240        let session = {
241            let mut s = SessionState::new();
242            s.project_root = Some(root.clone());
243            Arc::new(RwLock::new(s))
244        };
245
246        let mut handles = Vec::new();
247        for _ in 0..8 {
248            let cache = cache.clone();
249            let session = session.clone();
250            let paths = paths.clone();
251            let root = root.clone();
252            handles.push(tokio::spawn(async move {
253                let ctx = ctx_with(cache, session, &root);
254                let args = json!({ "paths": paths, "mode": "full" })
255                    .as_object()
256                    .unwrap()
257                    .clone();
258                tokio::task::block_in_place(|| CtxMultiReadTool.handle(&args, &ctx))
259            }));
260        }
261
262        for h in handles {
263            let joined = tokio::time::timeout(Duration::from_secs(20), h)
264                .await
265                .expect("ctx_multi_read hung (>20s) — nested block_in_place regression?")
266                .expect("spawned task panicked");
267            let out = joined.expect("ctx_multi_read returned an error");
268            assert!(
269                out.text.contains("Read 6 files"),
270                "unexpected output: {}",
271                out.text
272            );
273        }
274    }
275
276    /// #509: `ctx_read` with a `paths` array must route to the shared
277    /// `batch_read` (folding `ctx_multi_read` into `ctx_read`), producing the
278    /// same multi-file batch output as calling `ctx_multi_read` directly.
279    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
280    async fn ctx_read_with_paths_delegates_to_batch_read() {
281        use crate::tools::registered::ctx_read::CtxReadTool;
282
283        let dir = tempfile::tempdir().unwrap();
284        let mut paths = Vec::new();
285        for i in 0..3 {
286            let p = dir.path().join(format!("f{i}.rs"));
287            std::fs::write(&p, format!("fn f{i}() {{ let _ = {i}; }}\n")).unwrap();
288            paths.push(p.to_string_lossy().to_string());
289        }
290        let root = dir.path().to_string_lossy().to_string();
291
292        let cache: Arc<RwLock<SessionCache>> = Arc::new(RwLock::new(SessionCache::new()));
293        let session = {
294            let mut s = SessionState::new();
295            s.project_root = Some(root.clone());
296            Arc::new(RwLock::new(s))
297        };
298        let ctx = ctx_with(cache, session, &root);
299        let args = json!({ "paths": paths, "mode": "full" })
300            .as_object()
301            .unwrap()
302            .clone();
303
304        let out = tokio::task::block_in_place(|| CtxReadTool.handle(&args, &ctx))
305            .expect("ctx_read(paths) returned an error");
306        assert!(
307            out.text.contains("Read 3 files"),
308            "ctx_read(paths) must batch-read like ctx_multi_read, got: {}",
309            out.text
310        );
311    }
312
313    /// #421: `ctx_multi_read` used to force `auto`→`full`, so omitting `mode`
314    /// over-expanded every file regardless of the active profile. With no `mode`
315    /// arg the handler must fall back to the profile's effective read mode
316    /// (`auto` by default) and pass it through to `ctx_read` — never silently
317    /// rewrite it to `full`.
318    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
319    async fn omitting_mode_uses_profile_default_not_forced_full() {
320        let dir = tempfile::tempdir().unwrap();
321        let p = dir.path().join("lib.rs");
322        std::fs::write(&p, "fn a() {}\nfn b() {}\n").unwrap();
323        let root = dir.path().to_string_lossy().to_string();
324
325        let cache: Arc<RwLock<SessionCache>> = Arc::new(RwLock::new(SessionCache::new()));
326        let session = {
327            let mut s = SessionState::new();
328            s.project_root = Some(root.clone());
329            Arc::new(RwLock::new(s))
330        };
331        let ctx = ctx_with(cache, session, &root);
332        let args = json!({ "paths": [p.to_string_lossy()] })
333            .as_object()
334            .unwrap()
335            .clone();
336
337        let out = tokio::task::block_in_place(|| CtxMultiReadTool.handle(&args, &ctx))
338            .expect("ctx_multi_read returned an error");
339
340        let expected = crate::core::profiles::active_profile()
341            .read
342            .default_mode_effective()
343            .to_string();
344        assert_eq!(
345            out.mode,
346            Some(expected),
347            "omitting mode must use the profile default, not a forced override (#421)"
348        );
349    }
350}