lean_ctx/tools/registered/
ctx_multi_read.rs1use 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
56pub(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 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 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 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 #[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 #[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 #[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}