1use rmcp::ErrorData;
3use rmcp::model::Tool;
4use serde_json::{Map, Value, json};
5
6use crate::server::tool_trait::{
7 McpTool, ToolContext, ToolOutput, get_bool, get_int, get_str, get_str_array, get_usize,
8};
9use lean_ctx::core::ocla::cache_types::{CacheKeyBuilder, SearchQueryKey};
10use lean_ctx::tool_defs::tool_def;
11
12pub struct CtxSearchTool;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22enum SearchAction {
23 Regex,
24 Semantic,
25 Symbol,
26 MovedReindex,
28 FindRelated,
29}
30
31impl SearchAction {
32 fn resolve(args: &Map<String, Value>) -> Self {
36 if let Some(a) = get_str(args, "action") {
37 match a.trim().to_ascii_lowercase().as_str() {
38 "regex" | "grep" | "pattern" => return Self::Regex,
39 "semantic" | "search" => return Self::Semantic,
40 "symbol" => return Self::Symbol,
41 "reindex" => return Self::MovedReindex,
42 "find_related" | "related" => return Self::FindRelated,
43 _ => {}
44 }
45 }
46 if args.contains_key("handle") {
47 Self::Symbol
48 } else if args.contains_key("pattern") {
49 Self::Regex
50 } else if args.contains_key("name") {
51 Self::Symbol
52 } else if args.contains_key("file_path") && args.contains_key("line") {
53 Self::FindRelated
54 } else if args.contains_key("query") {
55 Self::Semantic
56 } else {
57 Self::Regex
58 }
59 }
60}
61
62pub(crate) fn uses_kernel_context(args: &Map<String, Value>) -> bool {
64 SearchAction::resolve(args) == SearchAction::Semantic
65}
66
67impl McpTool for CtxSearchTool {
68 fn name(&self) -> &'static str {
69 "ctx_search"
70 }
71
72 fn tool_def(&self) -> Tool {
73 tool_def(
74 "ctx_search",
75 "Search code: regex(pattern, default) | semantic(query) | symbol(name|handle) | \
76 find_related(file_path,line). Read-only. anchored=true enables ctx_patch refs; \
77 queries batches regex searches. Run ctx_compose FIRST.",
78 json!({
79 "type": "object",
80 "properties": {
81 "action": {
82 "type": "string",
83 "enum": ["regex", "semantic", "symbol", "find_related"]
84 },
85 "pattern": { "type": "string" },
86 "query": { "type": "string" },
87 "name": { "type": "string" },
88 "handle": { "type": "string" },
89 "path": { "type": "string" },
90 "paths": { "type": "array", "items": { "type": "string" } },
91 "include": { "type": "string", "description": "Glob, e.g. *.rs" },
92 "exclude": { "type": "string" },
93 "exclude_pattern": { "type": "string" },
94 "anchored": { "type": "boolean" },
95 "max_results": {
96 "type": "integer",
97 "description": "shared across queries"
98 },
99 "top_k": { "type": "integer" },
100 "mode": { "type": "string", "enum": ["bm25", "dense", "hybrid"] },
101 "file": { "type": "string" },
102 "kind": { "type": "string" },
103 "file_path": { "type": "string" },
104 "line": { "type": "integer" },
105 "queries": {
106 "type": "array",
107 "items": { "type": "object" }
108 }
109 },
110 "allOf": [
111 {
112 "if": { "properties": { "action": { "const": "regex" } }, "required": ["action"] },
113 "then": { "anyOf": [{ "required": ["pattern"] }, { "required": ["queries"] }] }
114 },
115 {
116 "if": { "properties": { "action": { "const": "semantic" } }, "required": ["action"] },
117 "then": { "required": ["query"] }
118 },
119 {
120 "if": { "properties": { "action": { "const": "symbol" } }, "required": ["action"] },
121 "then": { "anyOf": [{ "required": ["name"] }, { "required": ["handle"] }] }
122 }
123 ]
124 }),
125 )
126 }
127
128 fn handle(
129 &self,
130 args: &Map<String, Value>,
131 ctx: &ToolContext,
132 ) -> Result<ToolOutput, ErrorData> {
133 let action = SearchAction::resolve(args);
134 let result = match action {
135 SearchAction::Regex => handle_regex(args, ctx),
136 SearchAction::Semantic => handle_semantic(args, ctx),
137 SearchAction::Symbol => handle_symbol(args, ctx),
138 SearchAction::MovedReindex => Err(moved_reindex_error()),
139 SearchAction::FindRelated => handle_find_related(args, ctx),
140 };
141 let mut result = result;
145 if let Ok(output) = &mut result
146 && matches!(action, SearchAction::Regex | SearchAction::Semantic)
147 && let Some(block) = crate::tools::seamit_answer::block(args, &ctx.project_root)
148 {
149 output.text.push_str(&block);
150 }
151 if let Ok(output) = &result {
152 record_attribution_result(ctx, action, args, output);
153 }
154 result
155 }
156
157 fn publishes_every_source(&self, args: Option<&Map<String, Value>>) -> bool {
170 args.is_some_and(|args| matches!(SearchAction::resolve(args), SearchAction::Regex))
171 && !crate::tools::seamit_answer::configured()
172 }
173}
174
175fn record_attribution_result(
176 ctx: &ToolContext,
177 action: SearchAction,
178 args: &Map<String, Value>,
179 output: &ToolOutput,
180) {
181 let session_id = lean_ctx::core::task_spine::TaskSpine::task_id()
182 .or_else(|| {
183 ctx.session
184 .as_ref()
185 .and_then(|session| session.try_read().ok().map(|state| state.id.clone()))
186 })
187 .unwrap_or_else(|| "mcp-session".to_string());
188 let action = match action {
189 SearchAction::Regex => "regex",
190 SearchAction::Semantic => "semantic",
191 SearchAction::Symbol => "symbol",
192 SearchAction::MovedReindex => "reindex",
193 SearchAction::FindRelated => "find_related",
194 };
195 let query = get_str(args, "pattern")
196 .or_else(|| get_str(args, "query"))
197 .or_else(|| get_str(args, "handle"))
198 .or_else(|| get_str(args, "name"))
199 .or_else(|| get_str(args, "file_path"))
200 .unwrap_or_default();
201 let source = if query.is_empty() {
202 format!("ctx_search {action}")
203 } else {
204 format!("ctx_search {action} {query}")
205 };
206 let turn_provided = ctx.call_count.as_ref().map_or(0, |count| {
207 count.load(std::sync::atomic::Ordering::Relaxed) as u64
208 });
209 let token_cost = lean_ctx::core::tokens::count_tokens(&output.text);
210 let chunk = lean_ctx::core::causal_attribution::ContextChunkRecord::new(
211 &output.text,
212 source,
213 token_cost,
214 turn_provided,
215 );
216 if let Err(error) = lean_ctx::core::causal_attribution::record_chunk(&session_id, chunk) {
217 tracing::debug!(%error, "causal attribution ctx_search recording failed");
218 }
219}
220
221const KNOWN_KEYS: &[&str] = &[
224 "action",
225 "pattern",
226 "query",
227 "name",
228 "handle",
229 "path",
230 "paths",
231 "include",
232 "exclude",
233 "exclude_pattern",
234 "ext",
235 "anchored",
236 "max_results",
237 "top_k",
238 "mode",
239 "file",
240 "kind",
241 "file_path",
242 "line",
243 "languages",
244 "path_glob",
245 "workspace",
246 "artifacts",
247 "ignore_gitignore",
248];
249
250fn handle_regex(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
252 if let Some(Value::Array(queries)) = args.get("queries") {
255 return handle_batch_queries(queries, args, ctx);
256 }
257 let pattern = get_str(args, "pattern")
261 .or_else(|| {
262 args.iter()
263 .find(|(k, v)| !KNOWN_KEYS.contains(&k.as_str()) && v.is_string())
264 .and_then(|(_, v)| v.as_str().map(String::from))
265 })
266 .ok_or_else(|| {
267 ErrorData::invalid_params(
268 "pattern is required. Example: ctx_search(pattern=\"fn main\", path=\"/src\")",
269 None,
270 )
271 })?;
272 let resolved = crate::server::multi_path::resolve_tool_paths(args, ctx)
273 .map_err(|e| ErrorData::invalid_params(format!("ERROR: {e}"), None))?;
274 let include =
277 get_str(args, "include").or_else(|| get_str(args, "ext").map(|e| ext_to_include(&e)));
278 let max = (get_int(args, "max_results").unwrap_or(20) as usize).min(500);
279 let no_gitignore = get_bool(args, "ignore_gitignore").unwrap_or(false);
280 let anchored = get_bool(args, "anchored").unwrap_or(false);
282 let exclude = get_str(args, "exclude");
285 let exclude_pattern = get_str(args, "exclude_pattern");
286
287 if no_gitignore
288 && let Err(e) = lean_ctx::core::io_boundary::ensure_ignore_gitignore_allowed("ctx_search")
289 {
290 return Err(crate::server::tool_trait::tool_execution_error(e));
292 }
293
294 let crp = ctx.crp_mode;
295 let respect = !no_gitignore;
296 let allow_secret_paths = lean_ctx::core::roles::active_role().io.allow_secret_paths;
297
298 if !resolved.is_multi {
299 return search_single(
300 &pattern,
301 &resolved.roots[0],
302 include.as_deref(),
303 max,
304 crp,
305 respect,
306 allow_secret_paths,
307 anchored,
308 exclude.as_deref(),
309 exclude_pattern.as_deref(),
310 )
311 .map(|output| resolved.annotate(output));
312 }
313
314 let _mode_guard = lean_ctx::core::savings_footer::ModeGuard::new("search");
315 let per_root_max = (max / resolved.roots.len()).max(5);
316 let mut combined = String::new();
317 let mut total_observed: usize = 0;
318 let mut total_sent: usize = 0;
319 let mut remaining_budget = max;
320 let mut failed_roots: usize = 0;
323 let mut answered_roots: usize = 0;
324
325 for root in &resolved.roots {
326 if remaining_budget == 0 {
327 break;
328 }
329 let this_root_max = per_root_max.min(remaining_budget);
330 let search_result = tokio::task::block_in_place(|| {
331 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
332 cached_or_search(
333 &pattern,
334 root,
335 include.as_deref(),
336 this_root_max,
337 crp,
338 respect,
339 allow_secret_paths,
340 anchored,
341 exclude.as_deref(),
342 exclude_pattern.as_deref(),
343 )
344 }))
345 .ok()
346 });
347
348 let Some(outcome) = search_result else {
349 combined.push_str(&format!("── {root} ──\nERROR: search panicked\n\n"));
350 failed_roots += 1;
351 continue;
352 };
353 note_secret_paths_withheld(outcome.secret_paths_withheld);
354 let failed = outcome.failed;
355 let result = outcome.text;
356
357 if result.trim().is_empty() {
358 continue;
359 }
360
361 combined.push_str(&format!("── {root} ──\n{result}\n\n"));
362
363 if failed {
364 failed_roots += 1;
365 continue;
366 }
367 answered_roots += 1;
368
369 let result_matches = result.lines().filter(|l| !l.is_empty()).count();
370 remaining_budget = remaining_budget.saturating_sub(result_matches);
371 total_observed += outcome.observed_tokens;
372 total_sent += lean_ctx::core::tokens::count_tokens(&result);
373 }
374
375 if combined.is_empty() {
376 combined = "No matches found across any root.".to_string();
377 }
378
379 let final_out = lean_ctx::core::protocol::append_savings(&combined, total_observed, total_sent);
384 if failed_roots > 0 && answered_roots == 0 {
385 return Err(crate::server::tool_trait::tool_execution_error(final_out));
387 }
388 let saved = total_observed.saturating_sub(total_sent);
389 lean_ctx::core::savings_ledger::record_tool_event(
393 "ctx_search",
394 total_observed,
395 total_sent,
396 None,
397 None,
398 );
399
400 crate::tools::search_hook::on_search("batch_query", "regex", total_observed, total_sent);
402
403 Ok(ToolOutput {
404 text: final_out,
405 original_tokens: total_observed,
406 saved_tokens: saved,
407 mode: None,
408 path: None,
409 changed: false,
410 shell_outcome: None,
411 content_blocks: None,
412 })
413}
414
415fn resolve_path_or_root(ctx: &ToolContext) -> Result<String, ErrorData> {
418 if let Some(p) = ctx.resolved_path("path") {
419 Ok(p.to_string())
420 } else if let Some(err) = ctx.path_error("path") {
421 Err(ErrorData::invalid_params(format!("path: {err}"), None))
422 } else {
423 Ok(ctx.project_root.clone())
424 }
425}
426
427fn prime_bm25_cache(ctx: &ToolContext) {
430 if let Some(ref cache) = ctx.bm25_cache {
431 crate::tools::ctx_semantic_search::set_thread_cache(cache.clone());
432 }
433}
434
435fn handle_semantic(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
437 let path = resolve_path_or_root(ctx)?;
438 lean_ctx::core::policy::runtime::with_project_source_view(&path, || {
439 handle_semantic_in_view(args, ctx)
440 })
441 .map_err(|_| {
442 ErrorData::internal_error("Search source authority changed or is unavailable", None)
443 })?
444}
445
446fn handle_semantic_in_view(
447 args: &Map<String, Value>,
448 ctx: &ToolContext,
449) -> Result<ToolOutput, ErrorData> {
450 let query = get_str(args, "query")
451 .ok_or_else(|| ErrorData::invalid_params("query is required for action=semantic", None))?;
452 let path = resolve_path_or_root(ctx)?;
453 let top_k = get_usize(args, "top_k").unwrap_or(10).min(1000);
454 let mode = get_str(args, "mode");
455 let languages = get_str_array(args, "languages");
456 let path_glob = get_str(args, "path_glob");
457 let workspace = get_bool(args, "workspace").unwrap_or(false);
458 let artifacts = get_bool(args, "artifacts").unwrap_or(false);
459 prime_bm25_cache(ctx);
460
461 let search_phase = lean_ctx::core::phase_timing::enter("ctx_search semantic: search");
462 let mut result = tokio::task::block_in_place(|| {
463 crate::tools::ctx_semantic_search::handle(
464 &query,
465 &path,
466 top_k,
467 ctx.crp_mode,
468 languages.as_deref(),
469 path_glob.as_deref(),
470 mode.as_deref(),
471 Some(workspace),
472 Some(artifacts),
473 )
474 });
475
476 drop(search_phase);
477
478 if !lean_ctx::core::policy::runtime::is_active() && !result.starts_with("ERR:") {
481 let _phase = lean_ctx::core::phase_timing::enter("ctx_search semantic: kernel enrichment");
482 let kernel_budget = 100;
483 if let Some(enrichment) =
484 lean_ctx::core::context_kernel::bridge::kernel_enrich(&query, &path, kernel_budget)
485 && !enrichment.blocks.is_empty()
486 {
487 result.push_str("\n--- kernel context ---\n");
488 result.push_str(&enrichment.blocks);
489 }
490 }
491
492 let search_tokens = lean_ctx::core::tokens::count_tokens(&result);
494 crate::tools::search_hook::on_search(&query, "semantic", search_tokens, search_tokens);
495 Ok(semantic_output(result))
496}
497
498fn resolve_symbol_root(args: &Map<String, Value>, session_root: &str) -> String {
502 let candidate = get_str(args, "path")
503 .or_else(|| get_str(args, "file"))
504 .filter(|p| std::path::Path::new(p.as_str()).is_absolute());
505
506 if let Some(abs_path) = candidate
507 && let Some(detected) = lean_ctx::core::protocol::detect_project_root(&abs_path)
508 && detected != session_root
509 && lean_ctx::core::workspace_authority::root_authorized(std::path::Path::new(&detected))
511 {
512 return detected;
513 }
514 session_root.to_string()
515}
516
517fn handle_symbol(args: &Map<String, Value>, ctx: &ToolContext) -> Result<ToolOutput, ErrorData> {
521 let effective_root = resolve_symbol_root(args, &ctx.project_root);
525
526 if let Some(handle) = get_str(args, "handle") {
527 let (result, original) =
528 crate::tools::ctx_symbol::render_by_handle(&handle, &effective_root);
529 let sent = lean_ctx::core::tokens::count_tokens(&result);
530 return Ok(ToolOutput {
531 text: result,
532 original_tokens: original,
533 saved_tokens: original.saturating_sub(sent),
534 mode: Some("handle".to_string()),
535 path: None,
536 changed: false,
537 shell_outcome: None,
538 content_blocks: None,
539 });
540 }
541
542 let name = ["name", "symbol", "query", "pattern"]
545 .iter()
546 .find_map(|key| get_str(args, key).filter(|value| !value.trim().is_empty()))
547 .ok_or_else(|| {
548 ErrorData::invalid_params("name or handle is required for action=symbol", None)
549 })?;
550 let file = get_str(args, "file");
551 let kind = get_str(args, "kind");
552
553 let (result, original) =
554 crate::tools::ctx_symbol::handle(&name, file.as_deref(), kind.as_deref(), &effective_root);
555 let sent = lean_ctx::core::tokens::count_tokens(&result);
556 crate::tools::search_hook::on_search(&name, "symbol", original, sent);
558 Ok(ToolOutput {
559 text: result,
560 original_tokens: original,
561 saved_tokens: original.saturating_sub(sent),
562 mode: kind,
563 path: file,
564 changed: false,
565 shell_outcome: None,
566 content_blocks: None,
567 })
568}
569
570fn moved_reindex_error() -> ErrorData {
582 ErrorData::invalid_params(
583 "ctx_search no longer performs reindex — it is read-only so it stays available \
584 in read-only/plan modes (#1624). Rebuild the index with \
585 ctx_index(action=\"build-full\"), or ctx_index(action=\"build\") for an \
586 incremental pass.",
587 None,
588 )
589}
590
591fn handle_find_related(
593 args: &Map<String, Value>,
594 ctx: &ToolContext,
595) -> Result<ToolOutput, ErrorData> {
596 let path = resolve_path_or_root(ctx)?;
597 let top_k = get_usize(args, "top_k").unwrap_or(10).min(1000);
598 let fp = get_str(args, "file_path").unwrap_or_default();
599 let line = get_int(args, "line").unwrap_or(1) as usize;
600 if fp.is_empty() {
601 return Err(ErrorData::invalid_params(
602 "find_related requires file_path and line",
603 None,
604 ));
605 }
606 prime_bm25_cache(ctx);
607
608 let result = tokio::task::block_in_place(|| {
609 crate::tools::ctx_semantic_search::handle_find_related(
610 &fp,
611 line,
612 &path,
613 top_k,
614 ctx.crp_mode,
615 )
616 });
617
618 Ok(semantic_output(result))
619}
620
621fn semantic_output(text: String) -> ToolOutput {
624 let tokens = lean_ctx::core::tokens::count_tokens(&text);
625 ToolOutput {
626 text,
627 original_tokens: tokens,
628 saved_tokens: 0,
629 mode: Some("semantic".to_string()),
630 path: None,
631 changed: false,
632 shell_outcome: None,
633 content_blocks: None,
634 }
635}
636
637fn note_secret_paths_withheld(n: usize) {
640 lean_ctx::core::security_events::note_refusals(
641 lean_ctx::core::security_events::RefusalClass::SecretPath,
642 n,
643 );
644}
645
646#[allow(clippy::too_many_arguments)]
647fn cached_or_search(
648 pattern: &str,
649 path: &str,
650 include: Option<&str>,
651 max: usize,
652 crp: crate::tools::CrpMode,
653 respect_gitignore: bool,
654 allow_secret_paths: bool,
655 anchored: bool,
656 exclude: Option<&str>,
657 exclude_pattern: Option<&str>,
658) -> crate::tools::ctx_search::SearchOutcome {
659 let builder = regex_cache_builder(
660 pattern,
661 path,
662 include,
663 exclude,
664 exclude_pattern,
665 max,
666 respect_gitignore,
667 allow_secret_paths,
668 anchored,
669 );
670 if let Some(builder) = &builder
671 && let Some(entry) = lean_ctx::core::ocla::cache_delivery::check(
672 &builder.cache_key(),
673 &builder.validator(),
674 "ctx_search",
675 )
676 {
677 let text = lean_ctx::core::ocla::cache_delivery::stub(&entry, "regex search");
678 return crate::tools::ctx_search::SearchOutcome {
679 text,
680 modeled_baseline: entry.token_count as usize,
681 observed_tokens: entry.token_count as usize,
682 failed: false,
683 secret_paths_withheld: 0,
685 };
686 }
687
688 let outcome = crate::tools::ctx_search::handle_filtered(
689 pattern,
690 path,
691 include,
692 max,
693 crp,
694 respect_gitignore,
695 allow_secret_paths,
696 anchored,
697 exclude,
698 exclude_pattern,
699 );
700 if !outcome.failed
701 && let Some(builder) = builder
702 {
703 lean_ctx::core::ocla::cache_delivery::record(
704 builder.cache_key(),
705 lean_ctx::core::ocla::cache_types::DeliveryKind::SearchQuery,
706 builder.validator(),
707 Some(builder.path),
708 &outcome.text,
709 "ctx_search",
710 );
711 }
712 outcome
713}
714
715#[allow(clippy::too_many_arguments)]
716fn regex_cache_builder(
717 pattern: &str,
718 path: &str,
719 include: Option<&str>,
720 exclude: Option<&str>,
721 exclude_pattern: Option<&str>,
722 max: usize,
723 respect_gitignore: bool,
724 allow_secret_paths: bool,
725 anchored: bool,
726) -> Option<SearchQueryKey> {
727 if lean_ctx::core::policy::runtime::active().is_some() {
728 return None;
729 }
730 let canonical = lean_ctx::core::pathutil::safe_canonicalize_or_self(std::path::Path::new(path));
731 let revision = lean_ctx::core::search_index::corpus_signature(
735 &canonical.to_string_lossy(),
736 respect_gitignore,
737 allow_secret_paths,
738 )?;
739 Some(SearchQueryKey {
740 pattern: pattern.into(),
741 include: format!(
742 "{}\\x1fmax:{max}\\x1fgitignore:{respect_gitignore}\\x1fsecret:{allow_secret_paths}\\x1fanchored:{anchored}",
743 include.unwrap_or_default()
744 ),
745 exclude: format!(
746 "{}\\x1fline:{}",
747 exclude.unwrap_or_default(),
748 exclude_pattern.unwrap_or_default()
749 ),
750 path: canonical.to_string_lossy().into_owned(),
751 index_rev: revision.to_string(),
752 })
753}
754
755#[cfg(test)]
756mod cache_delivery_tests {
757 use super::*;
758
759 #[test]
760 fn regex_adapter_records_then_serves_a_cross_agent_reference() {
761 let _policy = lean_ctx::core::policy::runtime::TestPolicyOverride::set(None);
762 let directory = tempfile::tempdir().unwrap();
763 std::fs::write(
764 directory.path().join("cached.rs"),
765 "fn cache_delivery_probe() {}\n",
766 )
767 .unwrap();
768 let path = directory.path().to_string_lossy();
769
770 let first = search_single(
771 "cache_delivery_probe",
772 &path,
773 Some("*.rs"),
774 20,
775 crate::tools::CrpMode::Off,
776 true,
777 true,
778 false,
779 None,
780 None,
781 )
782 .unwrap();
783 assert!(first.text.contains("cache_delivery_probe"));
784 let second = search_single(
785 "cache_delivery_probe",
786 &path,
787 Some("*.rs"),
788 20,
789 crate::tools::CrpMode::Off,
790 true,
791 true,
792 false,
793 None,
794 None,
795 )
796 .unwrap();
797 assert!(
798 second.text.contains("[cross-agent cache"),
799 "{}",
800 second.text
801 );
802 std::fs::write(
804 directory.path().join("cached.rs"),
805 "fn cache_delivery_probe_updated() {}\n",
806 )
807 .unwrap();
808 let updated = search_single(
809 "cache_delivery_probe",
810 &path,
811 Some("*.rs"),
812 20,
813 crate::tools::CrpMode::Off,
814 true,
815 true,
816 false,
817 None,
818 None,
819 )
820 .unwrap();
821 assert!(updated.text.contains("cache_delivery_probe_updated"));
822 assert!(!updated.text.contains("[cross-agent cache"));
823 }
824}
825
826#[allow(clippy::too_many_arguments)]
827fn search_single(
828 pattern: &str,
829 path: &str,
830 include: Option<&str>,
831 max: usize,
832 crp: crate::tools::CrpMode,
833 respect_gitignore: bool,
834 allow_secret_paths: bool,
835 anchored: bool,
836 exclude: Option<&str>,
837 exclude_pattern: Option<&str>,
838) -> Result<ToolOutput, ErrorData> {
839 let _mode_guard = lean_ctx::core::savings_footer::ModeGuard::new("search");
840
841 let search_result = tokio::task::block_in_place(|| {
842 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
843 cached_or_search(
844 pattern,
845 path,
846 include,
847 max,
848 crp,
849 respect_gitignore,
850 allow_secret_paths,
851 anchored,
852 exclude,
853 exclude_pattern,
854 )
855 }));
856 match result {
857 Ok(r) => Ok(r),
858 Err(_) => Err("search task panicked"),
859 }
860 });
861
862 let outcome = match search_result {
863 Ok(r) => r,
864 Err(e) => {
865 return Err(ErrorData::internal_error(
866 format!("search task failed: {e}"),
867 None,
868 ));
869 }
870 };
871 note_secret_paths_withheld(outcome.secret_paths_withheld);
872 let failed = outcome.failed;
873 let result = outcome.text;
874 let observed = outcome.observed_tokens;
877
878 if failed {
881 return Err(ErrorData::invalid_params(result, None));
882 }
883
884 let sent = lean_ctx::core::tokens::count_tokens(&result);
885 let saved = observed.saturating_sub(sent);
886 let final_out = lean_ctx::core::protocol::append_savings(&result, observed, sent);
887 lean_ctx::core::savings_ledger::record_tool_event("ctx_search", observed, sent, None, None);
890
891 crate::tools::search_hook::on_search(pattern, "regex", observed, sent);
893
894 Ok(ToolOutput {
895 text: final_out,
896 original_tokens: observed,
897 saved_tokens: saved,
898 mode: None,
899 path: Some(path.to_string()),
900 changed: false,
901 shell_outcome: None,
902 content_blocks: None,
903 })
904}
905
906const QUERY_KEYS: &[&str] = &[
919 "pattern",
920 "include",
921 "ext",
922 "exclude",
923 "exclude_pattern",
924 "max_results",
925 "path",
926 "file_path",
927];
928
929const QUERY_KEY_ALIASES: &[(&str, &str)] = &[
934 ("regex", "pattern"),
935 ("query", "pattern"),
936 ("maxResults", "max_results"),
937 ("limit", "max_results"),
938 ("glob", "include"),
939 ("filePattern", "include"),
940 ("file_pattern", "include"),
941 ("excludePattern", "exclude_pattern"),
942 ("filePath", "file_path"),
943];
944
945fn normalize_query_keys(
948 obj: &Map<String, Value>,
949 idx: usize,
950) -> Result<Map<String, Value>, String> {
951 let mut out = Map::with_capacity(obj.len());
952 for (key, value) in obj {
953 let canonical = if QUERY_KEYS.contains(&key.as_str()) {
954 key.as_str()
955 } else if let Some((_, canonical)) =
956 QUERY_KEY_ALIASES.iter().find(|(alias, _)| *alias == key)
957 {
958 if obj.contains_key(*canonical) {
959 continue;
960 }
961 canonical
962 } else {
963 return Err(format!(
964 "queries[{}]: unknown key '{key}' — accepted keys are {}",
965 idx + 1,
966 QUERY_KEYS.join(", ")
967 ));
968 };
969 out.insert(canonical.to_string(), value.clone());
970 }
971 Ok(out)
972}
973
974fn resolve_query_cap(
978 obj: &Map<String, Value>,
979 default_share: usize,
980 idx: usize,
981) -> Result<usize, String> {
982 match get_int(obj, "max_results") {
983 Some(n) if n > 0 => Ok((n as usize).min(500)),
984 Some(_) => Err(format!(
985 "queries[{}].max_results must be a positive integer",
986 idx + 1
987 )),
988 None => Ok(default_share),
989 }
990}
991
992fn handle_batch_queries(
994 queries: &[Value],
995 args: &Map<String, Value>,
996 ctx: &ToolContext,
997) -> Result<ToolOutput, ErrorData> {
998 if queries.is_empty() {
999 return Err(ErrorData::invalid_params(
1000 "queries array must not be empty",
1001 None,
1002 ));
1003 }
1004 if queries.len() > 10 {
1005 return Err(ErrorData::invalid_params(
1006 "queries array limited to 10 entries",
1007 None,
1008 ));
1009 }
1010
1011 let resolved = crate::server::multi_path::resolve_tool_paths(args, ctx)
1012 .map_err(|e| ErrorData::invalid_params(format!("ERROR: {e}"), None))?;
1013 let no_gitignore = get_bool(args, "ignore_gitignore").unwrap_or(false);
1014 let anchored = get_bool(args, "anchored").unwrap_or(false);
1015 let crp = ctx.crp_mode;
1016 let respect = !no_gitignore;
1017 let allow_secret_paths = lean_ctx::core::roles::active_role().io.allow_secret_paths;
1018 let root = &resolved.roots[0];
1019 let global_max = (get_int(args, "max_results").unwrap_or(20) as usize).min(500);
1020 let default_share = (global_max / queries.len()).max(5);
1028
1029 let _mode_guard = lean_ctx::core::savings_footer::ModeGuard::new("search");
1030 let mut combined = String::new();
1031 let mut total_observed: usize = 0;
1032 let mut total_sent: usize = 0;
1033 let mut failed_queries: usize = 0;
1036 let mut answered_queries: usize = 0;
1037 let mut secret_paths_withheld: usize = 0;
1040
1041 for (idx, q) in queries.iter().enumerate() {
1042 let Some(obj) = q.as_object() else {
1043 combined.push_str(&format!(
1044 "── query {} ──\nERROR: expected object\n\n",
1045 idx + 1
1046 ));
1047 failed_queries += 1;
1048 continue;
1049 };
1050 let obj =
1054 &normalize_query_keys(obj, idx).map_err(|e| ErrorData::invalid_params(e, None))?;
1055 let Some(pattern) = get_str(obj, "pattern") else {
1056 combined.push_str(&format!(
1057 "── query {} ──\nERROR: pattern required\n\n",
1058 idx + 1
1059 ));
1060 failed_queries += 1;
1061 continue;
1062 };
1063 let include =
1064 get_str(obj, "include").or_else(|| get_str(obj, "ext").map(|e| ext_to_include(&e)));
1065 let exclude = get_str(obj, "exclude");
1066 let exclude_pattern = get_str(obj, "exclude_pattern");
1067 let per_query_max = resolve_query_cap(obj, default_share, idx)
1068 .map_err(|e| ErrorData::invalid_params(e, None))?;
1069 let query_root = match get_str(obj, "path").or_else(|| get_str(obj, "file_path")) {
1072 Some(raw) => match ctx.resolve_path_sync(&raw) {
1073 Ok(p) => p,
1074 Err(e) => {
1075 combined.push_str(&format!(
1076 "── query {}: '{}' ──\nERROR: {e}\n\n",
1077 idx + 1,
1078 truncate_query(&pattern, 40)
1079 ));
1080 continue;
1081 }
1082 },
1083 None => root.clone(),
1084 };
1085
1086 let search_result = tokio::task::block_in_place(|| {
1087 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
1088 cached_or_search(
1089 &pattern,
1090 &query_root,
1091 include.as_deref(),
1092 per_query_max,
1093 crp,
1094 respect,
1095 allow_secret_paths,
1096 anchored,
1097 exclude.as_deref(),
1098 exclude_pattern.as_deref(),
1099 )
1100 }))
1101 .ok()
1102 });
1103
1104 let label = if queries.len() > 1 {
1105 format!(
1106 "── query {}: '{}' ──\n",
1107 idx + 1,
1108 truncate_query(&pattern, 40)
1109 )
1110 } else {
1111 String::new()
1112 };
1113
1114 let Some(outcome) = search_result else {
1115 combined.push_str(&format!("{label}ERROR: search panicked\n\n"));
1116 failed_queries += 1;
1117 continue;
1118 };
1119
1120 secret_paths_withheld = secret_paths_withheld.max(outcome.secret_paths_withheld);
1121 if outcome.failed {
1122 failed_queries += 1;
1123 } else {
1124 answered_queries += 1;
1125 }
1126 if !outcome.text.trim().is_empty() {
1127 combined.push_str(&format!("{label}{}\n\n", outcome.text));
1128 total_observed += outcome.observed_tokens;
1129 total_sent += lean_ctx::core::tokens::count_tokens(&outcome.text);
1130 }
1131 }
1132
1133 note_secret_paths_withheld(secret_paths_withheld);
1134 if combined.is_empty() {
1135 combined = "No matches found for any query.".to_string();
1136 }
1137
1138 let final_out = lean_ctx::core::protocol::append_savings(&combined, total_observed, total_sent);
1139 if failed_queries > 0 && answered_queries == 0 {
1140 return Err(crate::server::tool_trait::tool_execution_error(final_out));
1142 }
1143 let saved = total_observed.saturating_sub(total_sent);
1144 lean_ctx::core::savings_ledger::record_tool_event(
1145 "ctx_search",
1146 total_observed,
1147 total_sent,
1148 None,
1149 None,
1150 );
1151
1152 crate::tools::search_hook::on_search("batch_query", "regex", total_observed, total_sent);
1154
1155 Ok(resolved.annotate(ToolOutput {
1156 text: final_out,
1157 original_tokens: total_observed,
1158 saved_tokens: saved,
1159 mode: None,
1160 path: None,
1161 changed: false,
1162 shell_outcome: None,
1163 content_blocks: None,
1164 }))
1165}
1166
1167fn truncate_query(q: &str, max: usize) -> String {
1169 if q.len() <= max {
1170 q.to_string()
1171 } else {
1172 format!("{}...", &q[..q.floor_char_boundary(max)])
1173 }
1174}
1175
1176fn ext_to_include(ext: &str) -> String {
1177 if ext.contains(['*', '{', '?', '/']) {
1178 return ext.to_string();
1179 }
1180 let bare = ext.strip_prefix('.').unwrap_or(ext);
1181 format!("*.{bare}")
1182}
1183
1184#[cfg(test)]
1185#[path = "ctx_search_tests.rs"]
1186mod tests;
1187
1188#[cfg(test)]
1189#[path = "ctx_search_mcp_tests.rs"]
1190mod mcp_tests;