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 cap = crate::core::limits::max_read_bytes() as u64;
84
85    // Resolve and filter paths under one short session read lock.
86    // `bounded_lock` uses `Handle::block_on` directly — NOT a nested
87    // `block_in_place` — because the dispatch layer already wraps this handler in
88    // `block_in_place`. The previous nested `block_in_place` calls could exhaust the
89    // 32-thread blocking pool under concurrent reads and freeze the server (#271).
90    let (paths, task) = {
91        let Some(session) =
92            crate::server::bounded_lock::read(session_lock, "ctx_multi_read:session")
93        else {
94            return Err(ErrorData::internal_error(
95                "session read-lock timeout in ctx_multi_read — another tool may be holding it. Retry in a moment.",
96                None,
97            ));
98        };
99        let mut paths = Vec::with_capacity(raw_paths.len());
100        for p in &raw_paths {
101            let resolved = super::resolve_path_sync(&session, p)
102                .map_err(|e| ErrorData::invalid_params(e, None))?;
103            if crate::core::binary_detect::is_binary_file(&resolved) {
104                continue;
105            }
106            if let Ok(meta) = std::fs::metadata(&resolved)
107                && meta.len() > cap
108            {
109                continue;
110            }
111            paths.push(resolved);
112        }
113        // #1590: an inferred task never steers a read or its supplement.
114        let task = session
115            .task
116            .as_ref()
117            .filter(|t| super::ctx_read::task_intent_steers_read(t.intent.as_deref()))
118            .map(|t| t.description.clone());
119        (paths, 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    // Share single-read precedence: explicit > config > learned > default.
130    // `auto` delegates the learned per-file decision to ctx_read below.
131    // #1993: `raw=true` means exact bytes here too, as it does for a single read.
132    let explicit_mode = super::ctx_read::resolve_explicit_mode(
133        get_bool(args, "raw").unwrap_or(false),
134        get_str(args, "mode"),
135    );
136    let configured_mode = explicit_mode
137        .is_none()
138        .then(crate::core::auto_mode_resolver::configured_default_mode)
139        .flatten();
140    let mode = crate::core::auto_mode_resolver::resolve_mode_precedence(
141        explicit_mode,
142        configured_mode,
143        Some("auto".to_string()),
144        "full",
145    );
146    let max_bytes = crate::tools::ctx_multi_read::max_multi_read_bytes();
147    let mut single_args = args.clone();
148    single_args.remove("paths");
149    single_args.insert("mode".into(), Value::String(mode.clone()));
150    let mut sections = Vec::with_capacity(paths.len());
151    let mut deliveries = Vec::with_capacity(paths.len());
152    let mut bytes = 0usize;
153    let mut total_original = 0usize;
154    // Each file uses the same admitted source, policy refresh, rendering and
155    // optional private hints as a single read. Never hold the batch cache lock
156    // across that path: it owns its short cache locks and bounded worker itself.
157    for path in &paths {
158        single_args.insert("path".into(), Value::String(path.clone()));
159        let prepared =
160            super::ctx_read::CtxReadTool.handle_inner_prepared(&single_args, ctx, path, false)?;
161        let output = &prepared.output;
162        if !sections.is_empty() && bytes.saturating_add(output.text.len()) > max_bytes {
163            break;
164        }
165        bytes = bytes.saturating_add(output.text.len());
166        total_original = total_original.saturating_add(output.original_tokens);
167        sections.push(output.text.clone());
168        deliveries.push(prepared);
169    }
170    let count = sections.len();
171    let mut text = sections.join("\n---\n");
172    if count < paths.len() {
173        text.push_str(&format!(
174            "\n---\nRead {count}/{} files\nOutput capped at {max_bytes} bytes (LCTX_MAX_MULTI_READ_BYTES). {} file(s) skipped. Use individual ctx_read calls for remaining files.",
175            paths.len(), paths.len() - count,
176        ));
177    } else {
178        text.push_str(&format!("\n---\nRead {count} files"));
179    }
180    // One kernel supplement per batch, never per file; raw stays verbatim.
181    if mode != "raw" {
182        if let Some(trailer) = crate::tools::ctx_read::kernel_trailer(task.as_deref()) {
183            text.push('\n');
184            text.push_str(&trailer);
185        }
186    }
187    // Count the actual combined application output, including per-file hints
188    // and framing. Inner source metrics are not a second savings claim.
189    let tokens = crate::core::tokens::count_tokens(&text);
190    let agent_id = ctx
191        .agent_id
192        .as_ref()
193        .and_then(|lock| lock.try_read().ok().and_then(|id| id.clone()));
194    if let Some(id) = agent_id.as_deref()
195        && let crate::core::agent_budget::BudgetCheckResult::Exceeded { limit, consumed } =
196            crate::core::agent_budget::check_budget(id, tokens)
197    {
198        return Err(ErrorData::invalid_params(
199            format!(
200                "Agent budget exceeded: {consumed}/{limit} tokens consumed; batch requires {tokens} tokens."
201            ),
202            None,
203        ));
204    }
205    // Only the complete, admitted application response counts as delivered.
206    // A capped item or an error later in the batch drops its pending effects.
207    for prepared in deliveries {
208        prepared.commit(ctx, false);
209    }
210    if let Some(id) = agent_id.as_deref() {
211        crate::core::agent_budget::record_consumption(id, tokens);
212    }
213
214    Ok(ToolOutput {
215        text,
216        original_tokens: total_original,
217        saved_tokens: total_original.saturating_sub(tokens),
218        mode: Some(mode),
219        path: None,
220        changed: false,
221        shell_outcome: None,
222        content_blocks: None,
223    })
224}
225
226#[cfg(test)]
227mod tests {
228    use super::*;
229    use std::sync::Arc;
230    use std::time::Duration;
231    use tokio::sync::RwLock;
232
233    use crate::core::cache::SessionCache;
234    use crate::core::session::SessionState;
235    use crate::tools::CrpMode;
236
237    fn ctx_with(
238        cache: Arc<RwLock<SessionCache>>,
239        session: Arc<RwLock<SessionState>>,
240        project_root: &str,
241    ) -> ToolContext {
242        ToolContext {
243            project_root: project_root.to_string(),
244            extra_roots: Vec::new(),
245            minimal: false,
246            resolved_paths: std::collections::HashMap::new(),
247            crp_mode: CrpMode::Off,
248            cache: Some(cache),
249            session: Some(session),
250            tool_calls: None,
251            agent_id: None,
252            workflow: None,
253            ledger: None,
254            client_name: None,
255            client_role: None,
256            shell_access: None,
257            pipeline_stats: None,
258            call_count: None,
259            autonomy: None,
260            pressure_snapshot: None,
261            path_errors: std::collections::HashMap::new(),
262            bm25_cache: None,
263            progress_sender: None,
264            cancel: None,
265        }
266    }
267
268    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
269    async fn dropped_prepared_read_does_not_publish_a_compressed_variant_or_session_read() {
270        let _data = crate::core::data_dir::isolated_data_dir();
271        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
272        let dir = tempfile::tempdir().unwrap();
273        let path = dir.path().join("pending.rs");
274        std::fs::write(&path, "fn pending() { let x = 42; }\n").unwrap();
275        let root = dir.path().to_str().unwrap();
276        let mut state = SessionState::new();
277        state.project_root = Some(root.to_owned());
278        let cache = Arc::new(RwLock::new(SessionCache::new()));
279        let session = Arc::new(RwLock::new(state));
280        let ctx = ctx_with(cache.clone(), session.clone(), root);
281        let args = json!({"mode":"map"}).as_object().unwrap().clone();
282        let prepared = tokio::task::block_in_place(|| {
283            super::super::ctx_read::CtxReadTool.handle_inner_prepared(
284                &args,
285                &ctx,
286                path.to_str().unwrap(),
287                false,
288            )
289        })
290        .unwrap();
291        assert!(prepared.output.text.contains("pending"));
292        drop(prepared);
293        let key =
294            crate::tools::ctx_read::compressed_cache_key("map", CrpMode::Off, None, None, &[]);
295        assert!(
296            cache
297                .read()
298                .await
299                .get_compressed(path.to_str().unwrap(), &key)
300                .is_none()
301        );
302        assert_eq!(session.read().await.stats.files_read, 0);
303    }
304
305    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
306    async fn batch_budget_checks_combined_output_before_delivery() {
307        use std::fmt::Write as _;
308
309        let _data = crate::core::data_dir::isolated_data_dir();
310        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
311        let dir = tempfile::tempdir().unwrap();
312        let mut paths = Vec::new();
313        for name in ["one.rs", "two.rs"] {
314            let path = dir.path().join(name);
315            let mut content = String::new();
316            for i in 0..100 {
317                writeln!(content, "let variable_{i} = {i};").unwrap();
318            }
319            std::fs::write(&path, content).unwrap();
320            paths.push(path);
321        }
322        let root = dir.path().to_str().unwrap();
323        let mut state = SessionState::new();
324        state.project_root = Some(root.to_owned());
325        let cache = Arc::new(RwLock::new(SessionCache::new()));
326        let session = Arc::new(RwLock::new(state));
327        let mut ctx = ctx_with(cache.clone(), session.clone(), root);
328        let id = format!("batch-budget-{root}");
329        ctx.agent_id = Some(Arc::new(RwLock::new(Some(id.clone()))));
330        crate::core::agent_budget::set_limit(&id, 1200);
331        let args = json!({"paths":paths, "mode":"full"})
332            .as_object()
333            .unwrap()
334            .clone();
335        let result = tokio::task::block_in_place(|| CtxMultiReadTool.handle(&args, &ctx));
336        let status = crate::core::agent_budget::get_status(&id);
337        crate::core::agent_budget::remove(&id);
338        assert!(
339            result
340                .err()
341                .expect("aggregate budget must refuse the batch")
342                .message
343                .contains("batch requires")
344        );
345        assert_eq!(status.tokens_consumed, 0);
346        assert_eq!(session.read().await.stats.files_read, 0);
347        let guard = cache.read().await;
348        for path in &paths {
349            assert!(
350                !guard
351                    .get(path.to_str().unwrap())
352                    .unwrap()
353                    .full_content_delivered
354            );
355        }
356    }
357
358    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
359    async fn batch_shares_raw_alias_and_line_window_semantics() {
360        let _data = crate::core::data_dir::isolated_data_dir();
361        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
362        let dir = tempfile::tempdir().unwrap();
363        let path = dir.path().join("sample.py");
364        std::fs::write(
365            &path,
366            "def sample():\n    return 'batch_exact_value'\n# last_window_marker\n",
367        )
368        .unwrap();
369        let root = dir.path().to_string_lossy().into_owned();
370        let mut state = SessionState::new();
371        state.project_root = Some(root.clone());
372        let ctx = ctx_with(
373            Arc::new(RwLock::new(SessionCache::new())),
374            Arc::new(RwLock::new(state)),
375            &root,
376        );
377        let raw = json!({"paths":[path], "mode":"map", "raw":true})
378            .as_object()
379            .unwrap()
380            .clone();
381        let output = tokio::task::block_in_place(|| CtxMultiReadTool.handle(&raw, &ctx)).unwrap();
382        assert!(output.text.contains("return 'batch_exact_value'"));
383        assert_eq!(output.mode.as_deref(), Some("raw"));
384        let window = json!({"paths":[path], "mode":"full", "start_line":2, "limit":1})
385            .as_object()
386            .unwrap()
387            .clone();
388        let output =
389            tokio::task::block_in_place(|| CtxMultiReadTool.handle(&window, &ctx)).unwrap();
390        assert!(output.text.contains("batch_exact_value"));
391        assert!(!output.text.contains("last_window_marker"));
392        assert_eq!(
393            output.saved_tokens,
394            output
395                .original_tokens
396                .saturating_sub(crate::core::tokens::count_tokens(&output.text))
397        );
398    }
399
400    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
401    async fn changed_policy_rechecks_batch_source_before_reusing_compressed_view() {
402        let _data = crate::core::data_dir::isolated_data_dir();
403        let dir = tempfile::tempdir().unwrap();
404        let path = dir.path().join("restricted.py");
405        std::fs::write(
406            &path,
407            "def restricted():\n    # CONFIDENTIAL\n    return 'batch_sensitive_value'\n",
408        )
409        .unwrap();
410        let root = dir.path().to_string_lossy().into_owned();
411        let mut state = SessionState::new();
412        state.project_root = Some(root.clone());
413        let ctx = ctx_with(
414            Arc::new(RwLock::new(SessionCache::new())),
415            Arc::new(RwLock::new(state)),
416            &root,
417        );
418        let args = json!({"paths":[path], "mode":"map"})
419            .as_object()
420            .unwrap()
421            .clone();
422        {
423            let _policy = crate::core::policy::runtime::TestPolicyOverride::set(None);
424            let output =
425                tokio::task::block_in_place(|| CtxMultiReadTool.handle(&args, &ctx)).unwrap();
426            assert!(output.text.contains("restricted"));
427        }
428        let policy = "name='batch-block'\nversion='1.0.0'\ndescription='test'\n[filters]\nclassification='block'\n";
429        let _policy = crate::core::policy::runtime::TestPolicyOverride::set(Some(
430            crate::core::policy::resolve(&crate::core::policy::parse(policy).unwrap()).unwrap(),
431        ));
432        // Dispatch normally binds the request project before invoking a tool;
433        // reproduce that scope so detached single-read workers inherit it.
434        let result = crate::core::policy::runtime::REQUEST_PROJECT.sync_scope(
435            std::cell::RefCell::new(Some(dir.path().to_path_buf())),
436            || tokio::task::block_in_place(|| CtxMultiReadTool.handle(&args, &ctx)),
437        );
438        let withheld = match result {
439            Ok(output) => output.text,
440            Err(error) => error.message.into_owned(),
441        };
442        assert!(withheld.contains("withheld by policy"), "{withheld}");
443        assert!(!withheld.contains("batch_sensitive_value"));
444    }
445
446    /// Regression for #271 (crash vector 11): under concurrent load,
447    /// `ctx_multi_read` must not hang. The handler runs inside the dispatch
448    /// layer's `block_in_place`, so it must acquire its session/cache locks
449    /// via `Handle::block_on` WITHOUT nesting another `block_in_place` —
450    /// nesting consumes extra blocking-pool threads and, under load, exhausts
451    /// the pool, hanging the call (no JSON-RPC response → client "invoke"
452    /// error).
453    ///
454    /// With only 2 worker threads and 8 concurrent batch reads, a nested
455    /// `block_in_place` regression would deadlock the pool and trip the 20s
456    /// timeout below.
457    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
458    async fn concurrent_multi_read_does_not_hang() {
459        let dir = tempfile::tempdir().unwrap();
460        let mut paths = Vec::new();
461        for i in 0..6 {
462            let p = dir.path().join(format!("file_{i}.rs"));
463            std::fs::write(&p, format!("fn f{i}() {{ let _ = {i}; }}\n")).unwrap();
464            paths.push(p.to_string_lossy().to_string());
465        }
466        let root = dir.path().to_string_lossy().to_string();
467
468        let cache: Arc<RwLock<SessionCache>> = Arc::new(RwLock::new(SessionCache::new()));
469        let session = {
470            let mut s = SessionState::new();
471            s.project_root = Some(root.clone());
472            Arc::new(RwLock::new(s))
473        };
474
475        let mut handles = Vec::new();
476        for _ in 0..8 {
477            let cache = cache.clone();
478            let session = session.clone();
479            let paths = paths.clone();
480            let root = root.clone();
481            handles.push(tokio::spawn(async move {
482                let ctx = ctx_with(cache, session, &root);
483                let args = json!({ "paths": paths, "mode": "full" })
484                    .as_object()
485                    .unwrap()
486                    .clone();
487                tokio::task::block_in_place(|| CtxMultiReadTool.handle(&args, &ctx))
488            }));
489        }
490
491        for h in handles {
492            let joined = tokio::time::timeout(Duration::from_secs(20), h)
493                .await
494                .expect("ctx_multi_read hung (>20s) — nested block_in_place regression?")
495                .expect("spawned task panicked");
496            let out = joined.expect("ctx_multi_read returned an error");
497            assert!(
498                out.text.contains("Read 6 files"),
499                "unexpected output: {}",
500                out.text
501            );
502        }
503    }
504
505    /// #509: `ctx_read` with a `paths` array must route to the shared
506    /// `batch_read` (folding `ctx_multi_read` into `ctx_read`), producing the
507    /// same multi-file batch output as calling `ctx_multi_read` directly.
508    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
509    async fn ctx_read_with_paths_delegates_to_batch_read() {
510        use crate::tools::registered::ctx_read::CtxReadTool;
511
512        let dir = tempfile::tempdir().unwrap();
513        let mut paths = Vec::new();
514        for i in 0..3 {
515            let p = dir.path().join(format!("f{i}.rs"));
516            std::fs::write(&p, format!("fn f{i}() {{ let _ = {i}; }}\n")).unwrap();
517            paths.push(p.to_string_lossy().to_string());
518        }
519        let root = dir.path().to_string_lossy().to_string();
520
521        let cache: Arc<RwLock<SessionCache>> = Arc::new(RwLock::new(SessionCache::new()));
522        let session = {
523            let mut s = SessionState::new();
524            s.project_root = Some(root.clone());
525            Arc::new(RwLock::new(s))
526        };
527        let ctx = ctx_with(cache, session, &root);
528        let args = json!({ "paths": paths, "mode": "full" })
529            .as_object()
530            .unwrap()
531            .clone();
532
533        let out = tokio::task::block_in_place(|| CtxReadTool.handle(&args, &ctx))
534            .expect("ctx_read(paths) returned an error");
535        assert!(
536            out.text.contains("Read 3 files"),
537            "ctx_read(paths) must batch-read like ctx_multi_read, got: {}",
538            out.text
539        );
540    }
541
542    /// #421: `ctx_multi_read` used to force `auto`→`full`, so omitting `mode`
543    /// over-expanded every file regardless of the active profile. With no `mode`
544    /// arg the handler must fall back to the profile's effective read mode
545    /// (`auto` by default) and pass it through to `ctx_read` — never silently
546    /// rewrite it to `full`.
547    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
548    async fn omitting_mode_uses_profile_default_not_forced_full() {
549        let dir = tempfile::tempdir().unwrap();
550        let p = dir.path().join("lib.rs");
551        std::fs::write(&p, "fn a() {}\nfn b() {}\n").unwrap();
552        let root = dir.path().to_string_lossy().to_string();
553
554        let cache: Arc<RwLock<SessionCache>> = Arc::new(RwLock::new(SessionCache::new()));
555        let session = {
556            let mut s = SessionState::new();
557            s.project_root = Some(root.clone());
558            Arc::new(RwLock::new(s))
559        };
560        let ctx = ctx_with(cache, session, &root);
561        let args = json!({ "paths": [p.to_string_lossy()] })
562            .as_object()
563            .unwrap()
564            .clone();
565
566        let out = tokio::task::block_in_place(|| CtxMultiReadTool.handle(&args, &ctx))
567            .expect("ctx_multi_read returned an error");
568
569        let expected = crate::core::profiles::active_profile()
570            .read
571            .default_mode_effective()
572            .to_string();
573        assert_eq!(
574            out.mode,
575            Some(expected),
576            "omitting mode must use the profile default, not a forced override (#421)"
577        );
578    }
579}