Skip to main content

lean_ctx/tools/registered/
ctx_search.rs

1use rmcp::ErrorData;
2use rmcp::model::Tool;
3use serde_json::{Map, Value, json};
4
5use crate::server::tool_trait::{McpTool, ToolContext, ToolOutput, get_bool, get_int, get_str};
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. Prefer over native Grep/rg/find (compact, .gitignore-aware).",
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 roots (alternative to path)"
28                    },
29                    "include": { "type": "string", "description": "Glob filter, e.g. *.ts, src/**/*.rs" },
30                    "ext": { "type": "string", "description": "Deprecated; use include" },
31                    "max_results": { "type": "integer", "description": "Default 20" },
32                    "ignore_gitignore": { "type": "boolean", "description": "Also scan gitignored files (needs role)" }
33                },
34                "required": ["pattern"]
35            }),
36        )
37    }
38
39    fn handle(
40        &self,
41        args: &Map<String, Value>,
42        ctx: &ToolContext,
43    ) -> Result<ToolOutput, ErrorData> {
44        let pattern = get_str(args, "pattern")
45            .ok_or_else(|| ErrorData::invalid_params("pattern is required", None))?;
46        let resolved = crate::server::multi_path::resolve_tool_paths(args, ctx)
47            .map_err(|e| ErrorData::invalid_params(format!("ERROR: {e}"), None))?;
48        // `include` is the canonical glob filter; `ext` is the deprecated alias
49        // (bare extension → `*.{ext}`). `include` wins when both are supplied.
50        let include =
51            get_str(args, "include").or_else(|| get_str(args, "ext").map(|e| ext_to_include(&e)));
52        let max = (get_int(args, "max_results").unwrap_or(20) as usize).min(500);
53        let no_gitignore = get_bool(args, "ignore_gitignore").unwrap_or(false);
54
55        if no_gitignore
56            && let Err(e) = crate::core::io_boundary::ensure_ignore_gitignore_allowed("ctx_search")
57        {
58            return Ok(ToolOutput::simple(e));
59        }
60
61        let crp = ctx.crp_mode;
62        let respect = !no_gitignore;
63        let allow_secret_paths = crate::core::roles::active_role().io.allow_secret_paths;
64
65        if !resolved.is_multi {
66            return search_single(
67                &pattern,
68                &resolved.roots[0],
69                include.as_deref(),
70                max,
71                crp,
72                respect,
73                allow_secret_paths,
74            );
75        }
76
77        let _mode_guard = crate::core::savings_footer::ModeGuard::new("search");
78        let per_root_max = (max / resolved.roots.len()).max(5);
79        let mut combined = String::new();
80        let mut total_observed: usize = 0;
81        let mut total_sent: usize = 0;
82
83        for root in &resolved.roots {
84            let pat = pattern.clone();
85            let r = root.clone();
86            let inc = include.clone();
87
88            let search_result = tokio::task::block_in_place(|| {
89                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
90                    crate::tools::ctx_search::handle(
91                        &pat,
92                        &r,
93                        inc.as_deref(),
94                        per_root_max,
95                        crp,
96                        respect,
97                        allow_secret_paths,
98                    )
99                }))
100                .ok()
101            });
102
103            let Some(outcome) = search_result else {
104                combined.push_str(&format!("── {root} ──\nERROR: search panicked\n\n"));
105                continue;
106            };
107            let result = outcome.text;
108
109            if result.starts_with("ERROR:") || result.trim().is_empty() {
110                if !result.trim().is_empty() {
111                    combined.push_str(&format!("── {root} ──\n{result}\n\n"));
112                }
113                continue;
114            }
115
116            combined.push_str(&format!("── {root} ──\n{result}\n\n"));
117            total_observed += outcome.observed_tokens;
118            total_sent += crate::core::tokens::count_tokens(&result);
119        }
120
121        if combined.is_empty() {
122            combined = "No matches found across any root.".to_string();
123        }
124
125        // Dashboard, footer and verified ledger all use *observed* tokens —
126        // the modeled 2.5x native-grep baseline never inflates user-facing
127        // numbers (GL #573). It only feeds the explicitly-estimated stats
128        // series via `tool_lifecycle::record_search`.
129        let final_out =
130            crate::core::protocol::append_savings(&combined, total_observed, total_sent);
131        let saved = total_observed.saturating_sub(total_sent);
132        // #685: `actual_tokens` is the *sent* output, not the saving — passing
133        // `saved` here recorded `actual=observed−sent` and `saved=sent` (both
134        // wrong). Align with cli_grep/cli_shell, which pass the output count.
135        crate::core::savings_ledger::record_tool_event("ctx_search", total_observed, total_sent);
136
137        Ok(ToolOutput {
138            text: final_out,
139            original_tokens: total_observed,
140            saved_tokens: saved,
141            mode: None,
142            path: None,
143            changed: false,
144            shell_outcome: None,
145        })
146    }
147}
148
149fn search_single(
150    pattern: &str,
151    path: &str,
152    include: Option<&str>,
153    max: usize,
154    crp: crate::tools::CrpMode,
155    respect_gitignore: bool,
156    allow_secret_paths: bool,
157) -> Result<ToolOutput, ErrorData> {
158    let _mode_guard = crate::core::savings_footer::ModeGuard::new("search");
159    let pattern_clone = pattern.to_string();
160    let path_clone = path.to_string();
161
162    let search_result = tokio::task::block_in_place(|| {
163        let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
164            crate::tools::ctx_search::handle(
165                &pattern_clone,
166                &path_clone,
167                include,
168                max,
169                crp,
170                respect_gitignore,
171                allow_secret_paths,
172            )
173        }));
174        match result {
175            Ok(r) => Ok(r),
176            Err(_) => Err("search task panicked"),
177        }
178    });
179
180    let outcome = match search_result {
181        Ok(r) => r,
182        Err(e) => {
183            return Err(ErrorData::internal_error(
184                format!("search task failed: {e}"),
185                None,
186            ));
187        }
188    };
189    let result = outcome.text;
190    // Observed tokens only — the modeled native-grep baseline stays out of
191    // dashboard/footer/ledger (GL #573); see the multi-root branch above.
192    let observed = outcome.observed_tokens;
193
194    if result.starts_with("ERROR:") {
195        return Err(ErrorData::invalid_params(result, None));
196    }
197
198    let sent = crate::core::tokens::count_tokens(&result);
199    let saved = observed.saturating_sub(sent);
200    let final_out = crate::core::protocol::append_savings(&result, observed, sent);
201    // #685: pass the *sent* output as `actual_tokens` (not `saved`); see the
202    // multi-root branch above for why the previous arg was a double bug.
203    crate::core::savings_ledger::record_tool_event("ctx_search", observed, sent);
204
205    Ok(ToolOutput {
206        text: final_out,
207        original_tokens: observed,
208        saved_tokens: saved,
209        mode: None,
210        path: Some(path.to_string()),
211        changed: false,
212        shell_outcome: None,
213    })
214}
215
216/// Translate the deprecated `ext` parameter into an `include` glob.
217///
218/// The historical `ext` accepted a bare extension (`rs` or `.rs`) and matched it
219/// exactly; the equivalent glob is `*.{ext}` (the `glob` crate's `*` spans path
220/// separators, so it still matches at any depth, preserving the old behaviour).
221/// A value that already looks like a glob/path (`*`, `{`, `?`, `/`) is passed
222/// through untouched so any power user who put a pattern in `ext` keeps working.
223fn ext_to_include(ext: &str) -> String {
224    if ext.contains(['*', '{', '?', '/']) {
225        return ext.to_string();
226    }
227    let bare = ext.strip_prefix('.').unwrap_or(ext);
228    format!("*.{bare}")
229}
230
231#[cfg(test)]
232mod tests {
233    use super::ext_to_include;
234
235    #[test]
236    fn ext_alias_bare_extension_becomes_glob() {
237        assert_eq!(ext_to_include("rs"), "*.rs");
238        assert_eq!(ext_to_include("ts"), "*.ts");
239    }
240
241    #[test]
242    fn ext_alias_strips_leading_dot() {
243        assert_eq!(ext_to_include(".rs"), "*.rs");
244        assert_eq!(ext_to_include(".tsx"), "*.tsx");
245    }
246
247    #[test]
248    fn ext_alias_passes_through_glob_like_values() {
249        // Already a glob/path → keep verbatim, don't double-wrap.
250        assert_eq!(ext_to_include("*.rs"), "*.rs");
251        assert_eq!(ext_to_include("*.{rs,ts}"), "*.{rs,ts}");
252        assert_eq!(ext_to_include("src/**/*.tsx"), "src/**/*.tsx");
253    }
254}