lean_ctx/tools/registered/
ctx_search.rs1use rmcp::model::Tool;
2use rmcp::ErrorData;
3use serde_json::{json, Map, Value};
4
5use crate::server::tool_trait::{get_bool, get_int, get_str, McpTool, ToolContext, ToolOutput};
6use crate::tool_defs::tool_def;
7
8pub struct CtxSearchTool;
9
10impl McpTool for CtxSearchTool {
11 fn name(&self) -> &'static str {
12 "ctx_search"
13 }
14
15 fn tool_def(&self) -> Tool {
16 tool_def(
17 "ctx_search",
18 "Regex code search (.gitignore aware, compact results). Supports multi-root via `paths` array. Secret-like files skipped unless role allows.",
19 json!({
20 "type": "object",
21 "properties": {
22 "pattern": { "type": "string", "description": "Regex pattern" },
23 "path": { "type": "string", "description": "Directory to search" },
24 "paths": {
25 "type": "array",
26 "items": { "type": "string" },
27 "description": "Multiple directories to search (alternative to path)"
28 },
29 "ext": { "type": "string", "description": "File extension filter" },
30 "max_results": { "type": "integer", "description": "Max results (default: 20)" },
31 "ignore_gitignore": { "type": "boolean", "description": "Set true to scan ALL files including .gitignore'd paths (default: false). Requires role policy (e.g. admin)." }
32 },
33 "required": ["pattern"]
34 }),
35 )
36 }
37
38 fn handle(
39 &self,
40 args: &Map<String, Value>,
41 ctx: &ToolContext,
42 ) -> Result<ToolOutput, ErrorData> {
43 let pattern = get_str(args, "pattern")
44 .ok_or_else(|| ErrorData::invalid_params("pattern is required", None))?;
45 let resolved = crate::server::multi_path::resolve_tool_paths(args, ctx);
46 let ext = get_str(args, "ext");
47 let max = (get_int(args, "max_results").unwrap_or(20) as usize).min(500);
48 let no_gitignore = get_bool(args, "ignore_gitignore").unwrap_or(false);
49
50 if no_gitignore {
51 if let Err(e) = crate::core::io_boundary::ensure_ignore_gitignore_allowed("ctx_search")
52 {
53 return Ok(ToolOutput::simple(e));
54 }
55 }
56
57 let crp = ctx.crp_mode;
58 let respect = !no_gitignore;
59 let allow_secret_paths = crate::core::roles::active_role().io.allow_secret_paths;
60
61 if !resolved.is_multi {
62 return search_single(
63 &pattern,
64 &resolved.roots[0],
65 ext.as_deref(),
66 max,
67 crp,
68 respect,
69 allow_secret_paths,
70 );
71 }
72
73 let per_root_max = (max / resolved.roots.len()).max(5);
74 let mut combined = String::new();
75 let mut total_original: usize = 0;
76 let mut total_sent: usize = 0;
77
78 for root in &resolved.roots {
79 let pat = pattern.clone();
80 let r = root.clone();
81 let e = ext.clone();
82
83 let search_result = tokio::task::block_in_place(|| {
84 std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
85 crate::tools::ctx_search::handle(
86 &pat,
87 &r,
88 e.as_deref(),
89 per_root_max,
90 crp,
91 respect,
92 allow_secret_paths,
93 )
94 }))
95 .ok()
96 });
97
98 let Some((result, original)) = search_result else {
99 combined.push_str(&format!("── {root} ──\nERROR: search panicked\n\n"));
100 continue;
101 };
102
103 if result.starts_with("ERROR:") || result.trim().is_empty() {
104 if !result.trim().is_empty() {
105 combined.push_str(&format!("── {root} ──\n{result}\n\n"));
106 }
107 continue;
108 }
109
110 combined.push_str(&format!("── {root} ──\n{result}\n\n"));
111 total_original += original;
112 total_sent += crate::core::tokens::count_tokens(&result);
113 }
114
115 if combined.is_empty() {
116 combined = "No matches found across any root.".to_string();
117 }
118
119 let final_out =
120 crate::core::protocol::append_savings(&combined, total_original, total_sent);
121 let saved = total_original.saturating_sub(total_sent);
122
123 Ok(ToolOutput {
124 text: final_out,
125 original_tokens: total_original,
126 saved_tokens: saved,
127 mode: None,
128 path: None,
129 changed: false,
130 })
131 }
132}
133
134fn search_single(
135 pattern: &str,
136 path: &str,
137 ext: Option<&str>,
138 max: usize,
139 crp: crate::tools::CrpMode,
140 respect_gitignore: bool,
141 allow_secret_paths: bool,
142) -> Result<ToolOutput, ErrorData> {
143 let pattern_clone = pattern.to_string();
144 let path_clone = path.to_string();
145
146 let search_result = tokio::task::block_in_place(|| {
147 let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
148 crate::tools::ctx_search::handle(
149 &pattern_clone,
150 &path_clone,
151 ext,
152 max,
153 crp,
154 respect_gitignore,
155 allow_secret_paths,
156 )
157 }));
158 match result {
159 Ok(r) => Ok(r),
160 Err(_) => Err("search task panicked"),
161 }
162 });
163
164 let (result, original) = match search_result {
165 Ok(r) => r,
166 Err(e) => {
167 return Err(ErrorData::internal_error(
168 format!("search task failed: {e}"),
169 None,
170 ));
171 }
172 };
173
174 if result.starts_with("ERROR:") {
175 return Err(ErrorData::invalid_params(result, None));
176 }
177
178 let sent = crate::core::tokens::count_tokens(&result);
179 let saved = original.saturating_sub(sent);
180 let final_out = crate::core::protocol::append_savings(&result, original, sent);
181
182 Ok(ToolOutput {
183 text: final_out,
184 original_tokens: original,
185 saved_tokens: saved,
186 mode: None,
187 path: Some(path.to_string()),
188 changed: false,
189 })
190}