Skip to main content

symforge/protocol/
read_tools.rs

1//! Read-oriented MCP tool input types and pure request parsing helpers.
2
3use schemars::{JsonSchema, Schema};
4use serde::{Deserialize, Deserializer, Serialize};
5
6use crate::live_index::search;
7
8/// Deserialize a `u32` from either a JSON number or a stringified number like `"5"`.
9pub(crate) fn lenient_u32<'de, D: Deserializer<'de>>(
10    deserializer: D,
11) -> Result<Option<u32>, D::Error> {
12    #[derive(Deserialize)]
13    #[serde(untagged)]
14    enum NumOrStr {
15        Num(u32),
16        Str(String),
17        Null,
18    }
19    match NumOrStr::deserialize(deserializer)? {
20        NumOrStr::Num(n) => Ok(Some(n)),
21        NumOrStr::Str(s) if s.is_empty() => Ok(None),
22        NumOrStr::Str(s) => s.parse::<u32>().map(Some).map_err(serde::de::Error::custom),
23        NumOrStr::Null => Ok(None),
24    }
25}
26
27/// Deserialize a `bool` from either a JSON boolean or a stringified boolean like `"true"`.
28pub(crate) fn lenient_bool<'de, D: Deserializer<'de>>(
29    deserializer: D,
30) -> Result<Option<bool>, D::Error> {
31    #[derive(Deserialize)]
32    #[serde(untagged)]
33    enum BoolOrStr {
34        Bool(bool),
35        Str(String),
36        Null,
37    }
38    match BoolOrStr::deserialize(deserializer)? {
39        BoolOrStr::Bool(b) => Ok(Some(b)),
40        BoolOrStr::Str(s) => match s.as_str() {
41            "true" | "1" => Ok(Some(true)),
42            "false" | "0" => Ok(Some(false)),
43            "" => Ok(None),
44            _ => Err(serde::de::Error::custom(format!(
45                "expected boolean or \"true\"/\"false\", got \"{s}\""
46            ))),
47        },
48        BoolOrStr::Null => Ok(None),
49    }
50}
51
52pub(crate) fn lenient_bool_required<'de, D: Deserializer<'de>>(
53    deserializer: D,
54) -> Result<bool, D::Error> {
55    lenient_bool(deserializer).map(|value| value.unwrap_or(false))
56}
57
58const INCLUDE_TESTS_SECTION_MARKER: &str = "__symforge_include_tests";
59
60pub(crate) fn encode_include_tests_marker(
61    mut sections: Option<Vec<String>>,
62    include_tests: bool,
63) -> Option<Vec<String>> {
64    if include_tests {
65        sections
66            .get_or_insert_with(Vec::new)
67            .push(INCLUDE_TESTS_SECTION_MARKER.to_string());
68    }
69    sections
70}
71
72pub(crate) fn include_tests_from_sections(sections: Option<&Vec<String>>) -> bool {
73    sections
74        .map(|items| {
75            items
76                .iter()
77                .any(|section| section == INCLUDE_TESTS_SECTION_MARKER)
78        })
79        .unwrap_or(false)
80}
81
82pub(crate) fn visible_sections(sections: &Option<Vec<String>>) -> Option<Vec<String>> {
83    sections.as_ref().and_then(|items| {
84        let had_marker = items
85            .iter()
86            .any(|section| section.as_str() == INCLUDE_TESTS_SECTION_MARKER);
87        let visible = items
88            .iter()
89            .filter(|section| section.as_str() != INCLUDE_TESTS_SECTION_MARKER)
90            .cloned()
91            .collect::<Vec<_>>();
92        if visible.is_empty() && had_marker {
93            None
94        } else {
95            Some(visible)
96        }
97    })
98}
99
100fn add_include_tests_schema(schema: &mut Schema) {
101    if let Some(serde_json::Value::Object(properties)) = schema.get_mut("properties") {
102        properties.insert(
103            "include_tests".to_string(),
104            serde_json::json!({
105                "type": "boolean",
106                "default": false,
107                "description": "Include expanded test modules in context output."
108            }),
109        );
110    }
111}
112
113pub(crate) fn lenient_u32_required<'de, D: Deserializer<'de>>(
114    deserializer: D,
115) -> Result<u32, D::Error> {
116    #[derive(Deserialize)]
117    #[serde(untagged)]
118    enum NumOrStr {
119        Num(u32),
120        Str(String),
121    }
122    match NumOrStr::deserialize(deserializer)? {
123        NumOrStr::Num(n) => Ok(n),
124        NumOrStr::Str(s) => s.parse::<u32>().map_err(serde::de::Error::custom),
125    }
126}
127
128/// Deserialize a `u64` from either a JSON number or a stringified number.
129pub(crate) fn lenient_u64<'de, D: Deserializer<'de>>(
130    deserializer: D,
131) -> Result<Option<u64>, D::Error> {
132    #[derive(Deserialize)]
133    #[serde(untagged)]
134    enum NumOrStr {
135        Num(u64),
136        Str(String),
137        Null,
138    }
139    match NumOrStr::deserialize(deserializer)? {
140        NumOrStr::Num(n) => Ok(Some(n)),
141        NumOrStr::Str(s) if s.is_empty() => Ok(None),
142        NumOrStr::Str(s) => s.parse::<u64>().map(Some).map_err(serde::de::Error::custom),
143        NumOrStr::Null => Ok(None),
144    }
145}
146
147/// Deserialize an `i64` from either a JSON number or a stringified number.
148pub(crate) fn lenient_i64<'de, D: Deserializer<'de>>(
149    deserializer: D,
150) -> Result<Option<i64>, D::Error> {
151    #[derive(Deserialize)]
152    #[serde(untagged)]
153    enum NumOrStr {
154        Num(i64),
155        Str(String),
156        Null,
157    }
158    match NumOrStr::deserialize(deserializer)? {
159        NumOrStr::Num(n) => Ok(Some(n)),
160        NumOrStr::Str(s) if s.is_empty() => Ok(None),
161        NumOrStr::Str(s) => s.parse::<i64>().map(Some).map_err(serde::de::Error::custom),
162        NumOrStr::Null => Ok(None),
163    }
164}
165
166/// Leniently deserialize an `Option<Vec<T>>` — accepts a native JSON array, a
167/// stringified JSON array (as sent by some MCP clients like Kilo Code), or a
168/// native array of stringified JSON objects (as sent by Codex).
169pub(crate) fn lenient_option_vec<'de, D, T>(deserializer: D) -> Result<Option<Vec<T>>, D::Error>
170where
171    D: Deserializer<'de>,
172    T: serde::de::DeserializeOwned,
173{
174    #[derive(Deserialize)]
175    #[serde(untagged)]
176    enum VecOrStr {
177        Vec(Vec<serde_json::Value>),
178        Str(String),
179        Null,
180    }
181    match VecOrStr::deserialize(deserializer)? {
182        VecOrStr::Vec(values) => {
183            let result: Result<Vec<T>, _> = values
184                .into_iter()
185                .enumerate()
186                .map(|(i, v)| match serde_json::from_value::<T>(v.clone()) {
187                    Ok(item) => Ok(item),
188                    Err(direct_err) => {
189                        if let serde_json::Value::String(ref s) = v {
190                            serde_json::from_str::<T>(s).map_err(|_| {
191                                serde::de::Error::custom(format!("element {i}: {direct_err}"))
192                            })
193                        } else {
194                            Err(serde::de::Error::custom(format!(
195                                "element {i}: {direct_err}"
196                            )))
197                        }
198                    }
199                })
200                .collect();
201            result.map(Some)
202        }
203        VecOrStr::Str(s) if s.is_empty() || s == "null" => Ok(None),
204        VecOrStr::Str(s) => serde_json::from_str::<Vec<T>>(&s)
205            .map(Some)
206            .map_err(serde::de::Error::custom),
207        VecOrStr::Null => Ok(None),
208    }
209}
210
211/// Leniently deserialize a `Vec<T>` — accepts a native JSON array, a stringified
212/// JSON array (as sent by some MCP clients like Kilo Code), or a native array of
213/// stringified JSON objects (as sent by Codex, e.g. `["{...}", "{...}"]`).
214pub(crate) fn lenient_vec_required<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
215where
216    D: Deserializer<'de>,
217    T: serde::de::DeserializeOwned,
218{
219    #[derive(Deserialize)]
220    #[serde(untagged)]
221    enum VecOrStr {
222        /// Native JSON array — try direct deserialization first via raw Value.
223        Vec(Vec<serde_json::Value>),
224        /// Entire array serialized as a single JSON string.
225        Str(String),
226    }
227    match VecOrStr::deserialize(deserializer)? {
228        VecOrStr::Vec(values) => {
229            // Try deserializing each element. If an element is a JSON string
230            // that looks like a JSON object, parse the inner string first.
231            values
232                .into_iter()
233                .enumerate()
234                .map(|(i, v)| {
235                    // First try direct deserialization (normal case: native objects)
236                    match serde_json::from_value::<T>(v.clone()) {
237                        Ok(item) => Ok(item),
238                        Err(direct_err) => {
239                            // If the value is a string, try parsing it as JSON
240                            if let serde_json::Value::String(ref s) = v {
241                                serde_json::from_str::<T>(s).map_err(|_| {
242                                    serde::de::Error::custom(format!("element {i}: {direct_err}"))
243                                })
244                            } else {
245                                Err(serde::de::Error::custom(format!(
246                                    "element {i}: {direct_err}"
247                                )))
248                            }
249                        }
250                    }
251                })
252                .collect()
253        }
254        VecOrStr::Str(s) => serde_json::from_str::<Vec<T>>(&s).map_err(serde::de::Error::custom),
255    }
256}
257
258/// Input for `get_symbol`.
259#[derive(Deserialize, Serialize, JsonSchema)]
260pub struct GetSymbolInput {
261    /// Relative path to the file (required for single lookup; ignored when `targets` is provided).
262    #[serde(default)]
263    pub path: String,
264    /// Symbol name to look up (required for single lookup; ignored when `targets` is provided).
265    #[serde(default)]
266    pub name: String,
267    /// Optional kind filter: "fn", "struct", "enum", "impl", etc.
268    pub kind: Option<String>,
269    /// Disambiguate when multiple symbols share the same name. Pass the 1-based start line of the
270    /// desired symbol (shown in ambiguity errors and search_symbols output).
271    #[serde(default, deserialize_with = "lenient_u32")]
272    pub symbol_line: Option<u32>,
273    /// Optional batch mode: provide multiple targets to retrieve 2+ symbols or code slices in one call.
274    /// Each target is a file path + symbol name or byte range. When provided, path/name/kind above are ignored.
275    #[serde(default, deserialize_with = "lenient_option_vec")]
276    #[schemars(with = "Vec<SymbolTarget>")]
277    pub targets: Option<Vec<SymbolTarget>>,
278    /// When true, return an approximate token cost estimate instead of actual content.
279    /// Useful for budget planning before fetching large symbols.
280    #[serde(default, deserialize_with = "lenient_bool")]
281    pub estimate: Option<bool>,
282    /// Optional maximum token budget for the response (~1000 default when unset).
283    #[serde(default)]
284    pub max_tokens: Option<u64>,
285    /// When true, bypass session cache-hit and return a fresh payload.
286    #[serde(default, deserialize_with = "lenient_bool")]
287    pub force_refresh: Option<bool>,
288}
289
290/// A single target in a `get_symbols` batch request.
291///
292/// Either provide `name` (symbol lookup) or `start_byte`/`end_byte` (code slice).
293#[derive(Deserialize, Serialize, JsonSchema)]
294pub struct SymbolTarget {
295    /// Relative file path.
296    pub path: String,
297    /// Symbol name for symbol lookup (mutually exclusive with byte range).
298    pub name: Option<String>,
299    /// Kind filter for symbol lookup (e.g., "fn", "struct").
300    pub kind: Option<String>,
301    /// Disambiguate when multiple symbols share the same name. Pass the 1-based start line.
302    #[serde(default, deserialize_with = "lenient_u32")]
303    pub symbol_line: Option<u32>,
304    /// Start byte offset for code slice (mutually exclusive with name).
305    #[serde(default, deserialize_with = "lenient_u32")]
306    pub start_byte: Option<u32>,
307    /// End byte offset for code slice (inclusive).
308    #[serde(default, deserialize_with = "lenient_u32")]
309    pub end_byte: Option<u32>,
310}
311
312/// Input for `get_file_content`.
313#[derive(Deserialize, Serialize, JsonSchema)]
314#[serde(deny_unknown_fields)]
315pub struct GetFileContentInput {
316    /// Relative path to the file.
317    pub path: String,
318    /// Selection mode: `lines`, `symbol`, `match`, `chunk`.
319    /// When set, only flags valid for that mode are accepted; cross-mode flags error.
320    /// When omitted, mode is inferred from flags (backward compatible).
321    #[serde(default)]
322    pub mode: Option<String>,
323    /// First line to include (1-indexed).
324    #[serde(default, deserialize_with = "lenient_u32")]
325    pub start_line: Option<u32>,
326    /// Last line to include (1-indexed, inclusive).
327    #[serde(default, deserialize_with = "lenient_u32")]
328    pub end_line: Option<u32>,
329    /// Select a 1-based chunk from the file using `max_lines` as the chunk size.
330    #[serde(default, deserialize_with = "lenient_u32")]
331    pub chunk_index: Option<u32>,
332    /// Maximum number of lines to include in a chunked read.
333    #[serde(default, deserialize_with = "lenient_u32")]
334    pub max_lines: Option<u32>,
335    /// Center the read around this 1-indexed line.
336    #[serde(default, deserialize_with = "lenient_u32")]
337    pub around_line: Option<u32>,
338    /// Center the read around the first case-insensitive literal match in the file.
339    pub around_match: Option<String>,
340    /// Select a specific 1-based occurrence of `around_match` instead of the first match.
341    #[serde(default, deserialize_with = "lenient_u32")]
342    pub match_occurrence: Option<u32>,
343    /// Center the read around a symbol in the target file.
344    pub around_symbol: Option<String>,
345    /// Optional exact-selector line for `around_symbol`.
346    #[serde(default, deserialize_with = "lenient_u32")]
347    pub symbol_line: Option<u32>,
348    /// Number of lines of symmetric context to include around `around_line` or `around_match`.
349    #[serde(default, deserialize_with = "lenient_u32")]
350    pub context_lines: Option<u32>,
351    /// Show 1-indexed line numbers for ordinary full-file or explicit-range reads.
352    #[serde(default, deserialize_with = "lenient_bool")]
353    pub show_line_numbers: Option<bool>,
354    /// Prepend a stable path or path-plus-range header for ordinary full-file or explicit-range reads.
355    #[serde(default, deserialize_with = "lenient_bool")]
356    pub header: Option<bool>,
357    /// When true, return an approximate token count for the file instead of content.
358    #[serde(default, deserialize_with = "lenient_bool")]
359    pub estimate: Option<bool>,
360    /// Alias for `start_line` using the Read-tool idiom: 0-based line count to skip.
361    /// Translated to `start_line = offset + 1` before processing.
362    /// Cannot be combined with `start_line`, `end_line`, `around_line`, `around_match`,
363    /// `around_symbol`, `chunk_index`, or `mode`.
364    #[serde(default, deserialize_with = "lenient_u32")]
365    pub offset: Option<u32>,
366    /// Alias for `end_line` using the Read-tool idiom: number of lines to include.
367    /// Translated to `end_line = offset + limit` before processing.
368    /// Cannot be combined with the fields listed under `offset`.
369    #[serde(default, deserialize_with = "lenient_u32")]
370    pub limit: Option<u32>,
371    /// Optional maximum token budget for the response.
372    #[serde(default)]
373    pub max_tokens: Option<u64>,
374    /// When true, bypass session cache-hit and return a fresh payload.
375    #[serde(default, deserialize_with = "lenient_bool")]
376    pub force_refresh: Option<bool>,
377}
378
379/// Input for `symforge_retrieve` (CCR full output recovery, 011).
380#[derive(Deserialize, Serialize, JsonSchema)]
381pub struct SymforgeRetrieveInput {
382    /// 12-character hex handle from a CCR footer.
383    pub hash: String,
384}
385
386#[derive(Debug, Deserialize, Serialize, JsonSchema)]
387pub(crate) struct ValidateFileSyntaxInput {
388    pub path: String,
389    /// When true, return an approximate token cost estimate instead of actual content.
390    #[serde(default, deserialize_with = "lenient_bool")]
391    pub estimate: Option<bool>,
392}
393
394/// Input for `find_dependents`.
395#[derive(Deserialize, Serialize, JsonSchema)]
396pub struct FindDependentsInput {
397    /// Relative file path to find dependents for.
398    pub path: String,
399    /// Symbol name. NOT a valid parameter for file-level dependents — present
400    /// only to detect a symbol-shaped misuse: if you pass `name` (symbol-level)
401    /// alongside `path`, the handler returns an explicit redirect to
402    /// `find_references`, which answers "who calls this symbol?". Leave unset for
403    /// the file-level dependency graph ("what imports this file?").
404    #[serde(default)]
405    pub name: Option<String>,
406    /// Maximum number of dependent files to show (default 20, capped at 100).
407    #[serde(default, deserialize_with = "lenient_u32")]
408    pub limit: Option<u32>,
409    /// Maximum number of reference lines per file (default 5, capped at 50).
410    #[serde(default, deserialize_with = "lenient_u32")]
411    pub max_per_file: Option<u32>,
412    /// Output format: "text" (default), "mermaid", or "dot".
413    pub format: Option<String>,
414    /// When true, show compact output: one line per dependent file as
415    /// `path (N refs: M call, K type_usage, J import)` with no source text
416    /// (60-75% smaller). Best for hub files with many dependents.
417    #[serde(default, deserialize_with = "lenient_bool")]
418    pub compact: Option<bool>,
419    /// When true, return an approximate token cost estimate instead of actual content.
420    #[serde(default, deserialize_with = "lenient_bool")]
421    pub estimate: Option<bool>,
422    /// Optional maximum token budget for the response.
423    #[serde(default, deserialize_with = "lenient_u64")]
424    pub max_tokens: Option<u64>,
425}
426
427/// Input for `get_repo_map`.
428#[derive(Deserialize, Serialize, JsonSchema)]
429pub struct GetRepoMapInput {
430    /// Detail level: "compact" (default — ~500 token project overview), "full" (complete symbol outline of every file), "tree" (browsable file tree with per-file stats).
431    pub detail: Option<String>,
432    /// Subtree path to browse (only used when detail="tree", default: project root).
433    pub path: Option<String>,
434    /// Max depth levels to expand (only used when detail="tree", default: 2, max: 5).
435    #[serde(default, deserialize_with = "lenient_u32")]
436    pub depth: Option<u32>,
437    /// Maximum number of files to include in the output (only used when detail="full", default: 200).
438    #[serde(default, deserialize_with = "lenient_u32")]
439    pub max_files: Option<u32>,
440    /// When true, return an approximate token cost estimate instead of actual content.
441    #[serde(default, deserialize_with = "lenient_bool")]
442    pub estimate: Option<bool>,
443    /// Optional maximum token budget for the response.
444    #[serde(default, deserialize_with = "lenient_u64")]
445    pub max_tokens: Option<u64>,
446}
447
448/// Input for `get_file_context`.
449#[derive(Serialize, JsonSchema)]
450#[schemars(transform = add_include_tests_schema)]
451pub struct GetFileContextInput {
452    /// Relative path to the file.
453    pub path: String,
454    /// Optional max token budget, matching hook behavior.
455    #[serde(default, deserialize_with = "lenient_u64")]
456    pub max_tokens: Option<u64>,
457    /// Optional list of sections to include. Allowed values: "outline", "imports", "consumers", "references", "git". Omit to include all sections.
458    #[serde(default, deserialize_with = "lenient_option_vec")]
459    #[schemars(with = "Vec<String>")]
460    pub sections: Option<Vec<String>>,
461    /// When true, return an approximate token cost estimate instead of actual content.
462    #[serde(default, deserialize_with = "lenient_bool")]
463    pub estimate: Option<bool>,
464    /// When true, bypass session cache-hit and return a fresh payload.
465    #[serde(default, deserialize_with = "lenient_bool")]
466    pub force_refresh: Option<bool>,
467}
468
469impl<'de> Deserialize<'de> for GetFileContextInput {
470    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
471        #[derive(Deserialize)]
472        struct Raw {
473            path: String,
474            #[serde(default, deserialize_with = "lenient_u64")]
475            max_tokens: Option<u64>,
476            #[serde(default, deserialize_with = "lenient_option_vec")]
477            sections: Option<Vec<String>>,
478            #[serde(default, deserialize_with = "lenient_bool_required")]
479            include_tests: bool,
480            #[serde(default, deserialize_with = "lenient_bool")]
481            estimate: Option<bool>,
482            #[serde(default, deserialize_with = "lenient_bool")]
483            force_refresh: Option<bool>,
484        }
485
486        let raw = Raw::deserialize(deserializer)?;
487        Ok(Self {
488            path: raw.path,
489            max_tokens: raw.max_tokens,
490            sections: encode_include_tests_marker(raw.sections, raw.include_tests),
491            estimate: raw.estimate,
492            force_refresh: raw.force_refresh,
493        })
494    }
495}
496
497/// Input for `get_symbol_context`.
498#[derive(Serialize, JsonSchema)]
499#[schemars(transform = add_include_tests_schema)]
500pub struct GetSymbolContextInput {
501    /// Symbol name to inspect.
502    pub name: String,
503    /// Optional file filter (ignored when bundle=true; use path instead).
504    pub file: Option<String>,
505    /// File path from `search_symbols`. Required when bundle=true or sections is provided.
506    pub path: Option<String>,
507    /// Optional selected symbol kind such as `fn`, `class`, or `struct`.
508    pub symbol_kind: Option<String>,
509    /// Optional selected symbol line from `search_symbols`.
510    #[serde(default, deserialize_with = "lenient_u32")]
511    pub symbol_line: Option<u32>,
512    /// Output verbosity: "summary" (one-line natural language summary ~90% smaller), "signature" (name+params+return only, ~80% smaller), "compact" (signature + first doc line), "full" (default — complete body). Applies to all three modes: default (controls the definition body), bundle (controls the main symbol body; dependency types always show full definitions), and sections/trace (controls the definition shown in the trace header).
513    pub verbosity: Option<String>,
514    /// When true, switch to bundle mode: returns symbol body + full definitions of all referenced custom types, resolved recursively. Best for edit preparation. Requires path.
515    #[serde(default, deserialize_with = "lenient_bool")]
516    pub bundle: Option<bool>,
517    /// Optional trace-analysis sections. When provided, switches to trace mode: definition,
518    /// callers, callees, implementations, type dependencies, git activity.
519    /// Valid values: "dependents", "siblings", "implementations", "git".
520    /// Omit for default symbol-context mode. Pass empty array for all trace sections.
521    #[serde(default, deserialize_with = "lenient_option_vec")]
522    #[schemars(with = "Vec<String>")]
523    pub sections: Option<Vec<String>>,
524    /// Optional max token budget for bundle mode. When set, preserves the main
525    /// symbol body and sections, then includes type dependencies in priority
526    /// order (direct first, then transitive) until the approximate budget
527    /// (~4 chars per token) is exhausted.
528    #[serde(default, deserialize_with = "lenient_u64")]
529    pub max_tokens: Option<u64>,
530    /// When true, return an approximate token cost estimate instead of actual content.
531    /// Shows estimated tokens for body, callers, bundle, and raw file.
532    #[serde(default, deserialize_with = "lenient_bool")]
533    pub estimate: Option<bool>,
534}
535
536impl<'de> Deserialize<'de> for GetSymbolContextInput {
537    fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
538        #[derive(Deserialize)]
539        struct Raw {
540            name: String,
541            file: Option<String>,
542            path: Option<String>,
543            symbol_kind: Option<String>,
544            #[serde(default, deserialize_with = "lenient_u32")]
545            symbol_line: Option<u32>,
546            verbosity: Option<String>,
547            #[serde(default, deserialize_with = "lenient_bool")]
548            bundle: Option<bool>,
549            #[serde(default, deserialize_with = "lenient_option_vec")]
550            sections: Option<Vec<String>>,
551            #[serde(default, deserialize_with = "lenient_bool_required")]
552            include_tests: bool,
553            #[serde(default, deserialize_with = "lenient_u64")]
554            max_tokens: Option<u64>,
555            #[serde(default, deserialize_with = "lenient_bool")]
556            estimate: Option<bool>,
557        }
558
559        let raw = Raw::deserialize(deserializer)?;
560        let sections = match raw.sections {
561            Some(sections) => encode_include_tests_marker(Some(sections), raw.include_tests),
562            None => None,
563        };
564        Ok(Self {
565            name: raw.name,
566            file: raw.file,
567            path: raw.path,
568            symbol_kind: raw.symbol_kind,
569            symbol_line: raw.symbol_line,
570            verbosity: raw.verbosity,
571            bundle: raw.bundle,
572            sections,
573            max_tokens: raw.max_tokens,
574            estimate: raw.estimate,
575        })
576    }
577}
578
579/// Input for `trace_symbol`.
580#[derive(Deserialize, Serialize, JsonSchema)]
581pub struct TraceSymbolInput {
582    /// File path containing the symbol.
583    pub path: String,
584    /// Symbol name to trace.
585    pub name: String,
586    /// Optional kind filter (e.g., "fn", "struct").
587    pub kind: Option<String>,
588    /// Optional line number to disambiguate overloaded symbols.
589    #[serde(default, deserialize_with = "lenient_u32")]
590    pub symbol_line: Option<u32>,
591    /// Optional list of output sections to include. When omitted, all sections are included.
592    /// Valid values: "dependents", "siblings", "implementations", "git".
593    #[serde(default, deserialize_with = "lenient_option_vec")]
594    pub sections: Option<Vec<String>>,
595    /// Output verbosity: "summary" (one-line natural language summary ~90% smaller), "signature" (name+params+return only, ~80% smaller), "compact" (signature + first doc line), "full" (default — complete body).
596    pub verbosity: Option<String>,
597    /// Optional maximum token budget for the response.
598    #[serde(default, deserialize_with = "lenient_u64")]
599    pub max_tokens: Option<u64>,
600    /// When true, return an approximate token cost estimate instead of actual content.
601    #[serde(default, deserialize_with = "lenient_bool")]
602    pub estimate: Option<bool>,
603}
604
605/// Input for `inspect_match`.
606#[derive(Deserialize, Serialize, JsonSchema)]
607pub struct InspectMatchInput {
608    /// Relative path to the file.
609    pub path: String,
610    /// 1-based line number to inspect.
611    #[serde(deserialize_with = "lenient_u32_required")]
612    pub line: u32,
613    /// Number of context lines to show around the match (default 3).
614    #[serde(default, deserialize_with = "lenient_u32")]
615    pub context: Option<u32>,
616    /// Maximum number of siblings to show (default 10). Use 0 to hide siblings entirely.
617    #[serde(default, deserialize_with = "lenient_u32")]
618    pub sibling_limit: Option<u32>,
619    /// When true, return an approximate token cost estimate instead of actual content.
620    #[serde(default, deserialize_with = "lenient_bool")]
621    pub estimate: Option<bool>,
622    /// Optional maximum token budget for the response.
623    #[serde(default, deserialize_with = "lenient_u64")]
624    pub max_tokens: Option<u64>,
625}
626
627pub(crate) fn normalize_file_content_aliases(
628    input: &mut GetFileContentInput,
629) -> Result<(), String> {
630    if input.offset.is_none() && input.limit.is_none() {
631        return Ok(());
632    }
633
634    // Reject combination with any explicit native selector.
635    let mut conflicts: Vec<&str> = Vec::new();
636    if input.start_line.is_some() {
637        conflicts.push("`start_line`");
638    }
639    if input.end_line.is_some() {
640        conflicts.push("`end_line`");
641    }
642    if input.around_line.is_some() {
643        conflicts.push("`around_line`");
644    }
645    if input.around_match.is_some() {
646        conflicts.push("`around_match`");
647    }
648    if input.around_symbol.is_some() {
649        conflicts.push("`around_symbol`");
650    }
651    if input.chunk_index.is_some() {
652        conflicts.push("`chunk_index`");
653    }
654    if input.mode.is_some() {
655        conflicts.push("`mode`");
656    }
657    if !conflicts.is_empty() {
658        return Err(format!(
659            "Invalid get_file_content request: `offset`/`limit` aliases cannot be combined with {}. Use native params instead.",
660            conflicts.join(", ")
661        ));
662    }
663
664    if input.limit == Some(0) {
665        return Err("Invalid get_file_content request: `limit` must be 1 or greater.".to_string());
666    }
667
668    let offset = input.offset.unwrap_or(0);
669    input.start_line = Some(offset.saturating_add(1));
670    if let Some(limit) = input.limit {
671        input.end_line = Some(offset.saturating_add(limit));
672    }
673    input.offset = None;
674    input.limit = None;
675    Ok(())
676}
677
678pub(crate) fn file_content_options_from_input(
679    input: &GetFileContentInput,
680) -> Result<search::FileContentOptions, String> {
681    let show_line_numbers = input.show_line_numbers.unwrap_or(false);
682    let header = input.header.unwrap_or(false);
683
684    // ── Mode dispatch ───────────────────────────────────────────────────
685    if let Some(mode) = &input.mode {
686        let mode_str = mode.as_str();
687        let result = match mode_str {
688            "lines" => validate_lines_mode(input),
689            "symbol" => validate_symbol_mode(input),
690            "match" => validate_match_mode(input),
691            "chunk" => validate_chunk_mode(input),
692            "search" => Err("mode 'search' is not yet implemented".to_string()),
693            other => Err(format!(
694                "Unknown mode '{other}'. Valid modes: lines, symbol, match, chunk."
695            )),
696        };
697        return result.map(|mut opts| {
698            opts.content_context.mode_name = Some(mode_str.to_string());
699            opts.content_context.mode_explicit = true;
700            opts
701        });
702    }
703    // No mode — infer from flags (existing backward-compatible behavior below)
704
705    if input.symbol_line.is_some() && input.around_symbol.is_none() {
706        return Err(
707            "Invalid get_file_content request: `symbol_line` requires `around_symbol`.".to_string(),
708        );
709    }
710
711    if input.match_occurrence.is_some() && input.around_match.is_none() {
712        return Err(
713            "Invalid get_file_content request: `match_occurrence` requires `around_match`."
714                .to_string(),
715        );
716    }
717
718    if matches!(input.match_occurrence, Some(0)) {
719        return Err(
720            "Invalid get_file_content request: `match_occurrence` must be 1 or greater."
721                .to_string(),
722        );
723    }
724
725    if let Some(raw_around_symbol) = input.around_symbol.as_deref() {
726        let around_symbol = raw_around_symbol.trim();
727        if around_symbol.is_empty() {
728            return Err(
729                "Invalid get_file_content request: `around_symbol` must not be empty.".to_string(),
730            );
731        }
732
733        if input.start_line.is_some()
734            || input.end_line.is_some()
735            || input.around_line.is_some()
736            || input.around_match.is_some()
737            || input.chunk_index.is_some()
738        {
739            return Err(
740                "Invalid get_file_content request: `around_symbol` cannot be combined with `start_line`, `end_line`, `around_line`, `around_match`, or `chunk_index`. Valid with `around_symbol`: `symbol_line`, `context_lines`, `max_lines`."
741                    .to_string(),
742            );
743        }
744
745        let mut opts = search::FileContentOptions::for_explicit_path_read_around_symbol(
746            input.path.clone(),
747            around_symbol,
748            input.symbol_line,
749            input.context_lines,
750            input.max_lines,
751            show_line_numbers,
752            header,
753        );
754        opts.content_context.mode_name = Some("symbol".to_string());
755        opts.content_context.mode_explicit = false;
756        return Ok(opts);
757    }
758
759    if input.max_lines.is_some() && input.chunk_index.is_none() {
760        return Err(
761            "Invalid get_file_content request: `max_lines` requires `chunk_index`.".to_string(),
762        );
763    }
764
765    if let Some(chunk_index) = input.chunk_index {
766        let Some(max_lines) = input.max_lines else {
767            return Err(
768                "Invalid get_file_content request: `chunk_index` requires `max_lines`.".to_string(),
769            );
770        };
771
772        if chunk_index == 0 {
773            return Err(
774                "Invalid get_file_content request: `chunk_index` must be 1 or greater.".to_string(),
775            );
776        }
777
778        if max_lines == 0 {
779            return Err(
780                "Invalid get_file_content request: `max_lines` must be 1 or greater.".to_string(),
781            );
782        }
783
784        if input.start_line.is_some()
785            || input.end_line.is_some()
786            || input.around_line.is_some()
787            || input.around_match.is_some()
788        {
789            return Err(
790                "Invalid get_file_content request: chunked reads (`chunk_index` + `max_lines`) cannot be combined with `start_line`, `end_line`, `around_line`, or `around_match`."
791                    .to_string(),
792            );
793        }
794
795        let mut opts = search::FileContentOptions::for_explicit_path_read_chunk(
796            input.path.clone(),
797            chunk_index,
798            max_lines,
799        );
800        opts.content_context.mode_name = Some("chunk".to_string());
801        opts.content_context.mode_explicit = false;
802        return Ok(opts);
803    }
804
805    // show_line_numbers and header are now allowed with all read modes
806    // including around_line and around_match for better usability.
807
808    if let Some(raw_around_match) = input.around_match.as_deref() {
809        let around_match = raw_around_match.trim();
810        if around_match.is_empty() {
811            return Err(
812                "Invalid get_file_content request: `around_match` must not be empty.".to_string(),
813            );
814        }
815
816        if input.start_line.is_some() || input.end_line.is_some() || input.around_line.is_some() {
817            return Err(
818                "Invalid get_file_content request: `around_match` cannot be combined with `start_line`, `end_line`, or `around_line`. Valid with `around_match`: `context_lines`."
819                    .to_string(),
820            );
821        }
822
823        let mut opts = search::FileContentOptions::for_explicit_path_read_around_match(
824            input.path.clone(),
825            around_match,
826            input.match_occurrence,
827            input.context_lines,
828            show_line_numbers,
829            header,
830        );
831        opts.content_context.mode_name = Some("match".to_string());
832        opts.content_context.mode_explicit = false;
833        return Ok(opts);
834    }
835
836    if input.around_line.is_some() && (input.start_line.is_some() || input.end_line.is_some()) {
837        return Err(
838            "Invalid get_file_content request: `around_line` cannot be combined with `start_line` or `end_line`. Valid with `around_line`: `context_lines`."
839                .to_string(),
840        );
841    }
842
843    let mut opts = match input.around_line {
844        Some(around_line) => search::FileContentOptions::for_explicit_path_read_around_line(
845            input.path.clone(),
846            around_line,
847            input.context_lines,
848            show_line_numbers,
849            header,
850        ),
851        None => search::FileContentOptions::for_explicit_path_read_with_format(
852            input.path.clone(),
853            input.start_line,
854            input.end_line,
855            show_line_numbers,
856            header,
857        ),
858    };
859    opts.content_context.mode_name = Some("lines".to_string());
860    opts.content_context.mode_explicit = false;
861    Ok(opts)
862}
863
864// ── Mode validators for get_file_content ────────────────────────────────
865
866/// Collect names of flags that are `Some` / `true` for error messages.
867fn describe_received_flags(input: &GetFileContentInput) -> String {
868    let mut flags = Vec::new();
869    if input.start_line.is_some() {
870        flags.push("start_line");
871    }
872    if input.end_line.is_some() {
873        flags.push("end_line");
874    }
875    if input.around_line.is_some() {
876        flags.push("around_line");
877    }
878    if input.around_match.is_some() {
879        flags.push("around_match");
880    }
881    if input.match_occurrence.is_some() {
882        flags.push("match_occurrence");
883    }
884    if input.around_symbol.is_some() {
885        flags.push("around_symbol");
886    }
887    if input.symbol_line.is_some() {
888        flags.push("symbol_line");
889    }
890    if input.chunk_index.is_some() {
891        flags.push("chunk_index");
892    }
893    if input.max_lines.is_some() {
894        flags.push("max_lines");
895    }
896    if input.context_lines.is_some() {
897        flags.push("context_lines");
898    }
899    if input.show_line_numbers.is_some() {
900        flags.push("show_line_numbers");
901    }
902    if input.header.is_some() {
903        flags.push("header");
904    }
905    flags.join(", ")
906}
907
908fn validate_lines_mode(input: &GetFileContentInput) -> Result<search::FileContentOptions, String> {
909    let cross: Vec<&str> = [
910        input.around_symbol.as_ref().map(|_| "around_symbol"),
911        input.around_match.as_ref().map(|_| "around_match"),
912        input.match_occurrence.map(|_| "match_occurrence"),
913        input.chunk_index.map(|_| "chunk_index"),
914    ]
915    .into_iter()
916    .flatten()
917    .collect();
918
919    if !cross.is_empty() {
920        return Err(format!(
921            "mode=lines conflicts with {}. Use mode={}. Received: {}",
922            cross.join(", "),
923            if input.around_symbol.is_some() {
924                "symbol"
925            } else if input.around_match.is_some() || input.match_occurrence.is_some() {
926                "match"
927            } else {
928                "chunk"
929            },
930            describe_received_flags(input),
931        ));
932    }
933
934    let show_line_numbers = input.show_line_numbers.unwrap_or(false);
935    let header = input.header.unwrap_or(false);
936
937    if input.around_line.is_some() && (input.start_line.is_some() || input.end_line.is_some()) {
938        return Err(
939            "Invalid get_file_content request: `around_line` cannot be combined with `start_line` or `end_line`. Valid with `around_line`: `context_lines`."
940                .to_string(),
941        );
942    }
943
944    Ok(match input.around_line {
945        Some(around_line) => search::FileContentOptions::for_explicit_path_read_around_line(
946            input.path.clone(),
947            around_line,
948            input.context_lines,
949            show_line_numbers,
950            header,
951        ),
952        None => search::FileContentOptions::for_explicit_path_read_with_format(
953            input.path.clone(),
954            input.start_line,
955            input.end_line,
956            show_line_numbers,
957            header,
958        ),
959    })
960}
961
962fn validate_symbol_mode(input: &GetFileContentInput) -> Result<search::FileContentOptions, String> {
963    let Some(raw_around_symbol) = input.around_symbol.as_deref() else {
964        return Err("mode=symbol requires around_symbol".to_string());
965    };
966    let around_symbol = raw_around_symbol.trim();
967    if around_symbol.is_empty() {
968        return Err("mode=symbol requires around_symbol".to_string());
969    }
970
971    let cross: Vec<&str> = [
972        input.start_line.map(|_| "start_line"),
973        input.end_line.map(|_| "end_line"),
974        input.around_line.map(|_| "around_line"),
975        input.around_match.as_ref().map(|_| "around_match"),
976        input.match_occurrence.map(|_| "match_occurrence"),
977        input.chunk_index.map(|_| "chunk_index"),
978    ]
979    .into_iter()
980    .flatten()
981    .collect();
982
983    if !cross.is_empty() {
984        return Err(format!(
985            "mode=symbol conflicts with {}. Received: {}",
986            cross.join(", "),
987            describe_received_flags(input),
988        ));
989    }
990
991    let show_line_numbers = input.show_line_numbers.unwrap_or(false);
992    let header = input.header.unwrap_or(false);
993
994    Ok(
995        search::FileContentOptions::for_explicit_path_read_around_symbol(
996            input.path.clone(),
997            around_symbol,
998            input.symbol_line,
999            input.context_lines,
1000            input.max_lines,
1001            show_line_numbers,
1002            header,
1003        ),
1004    )
1005}
1006
1007fn validate_match_mode(input: &GetFileContentInput) -> Result<search::FileContentOptions, String> {
1008    let Some(raw_around_match) = input.around_match.as_deref() else {
1009        return Err("mode=match requires around_match".to_string());
1010    };
1011    let around_match = raw_around_match.trim();
1012    if around_match.is_empty() {
1013        return Err("mode=match requires around_match".to_string());
1014    }
1015    if matches!(input.match_occurrence, Some(0)) {
1016        return Err(
1017            "Invalid get_file_content request: `match_occurrence` must be 1 or greater."
1018                .to_string(),
1019        );
1020    }
1021
1022    let cross: Vec<&str> = [
1023        input.start_line.map(|_| "start_line"),
1024        input.end_line.map(|_| "end_line"),
1025        input.around_line.map(|_| "around_line"),
1026        input.around_symbol.as_ref().map(|_| "around_symbol"),
1027        input.chunk_index.map(|_| "chunk_index"),
1028    ]
1029    .into_iter()
1030    .flatten()
1031    .collect();
1032
1033    if !cross.is_empty() {
1034        return Err(format!(
1035            "mode=match conflicts with {}. Use mode={}. Received: {}",
1036            cross.join(", "),
1037            if input.around_symbol.is_some() {
1038                "symbol"
1039            } else if input.start_line.is_some()
1040                || input.end_line.is_some()
1041                || input.around_line.is_some()
1042            {
1043                "lines"
1044            } else {
1045                "chunk"
1046            },
1047            describe_received_flags(input),
1048        ));
1049    }
1050
1051    let show_line_numbers = input.show_line_numbers.unwrap_or(false);
1052    let header = input.header.unwrap_or(false);
1053
1054    Ok(
1055        search::FileContentOptions::for_explicit_path_read_around_match(
1056            input.path.clone(),
1057            around_match,
1058            input.match_occurrence,
1059            input.context_lines,
1060            show_line_numbers,
1061            header,
1062        ),
1063    )
1064}
1065
1066fn validate_chunk_mode(input: &GetFileContentInput) -> Result<search::FileContentOptions, String> {
1067    let chunk_index = input
1068        .chunk_index
1069        .ok_or_else(|| "mode=chunk requires chunk_index".to_string())?;
1070    let max_lines = input
1071        .max_lines
1072        .ok_or_else(|| "mode=chunk requires max_lines".to_string())?;
1073
1074    if chunk_index == 0 {
1075        return Err(
1076            "Invalid get_file_content request: `chunk_index` must be 1 or greater.".to_string(),
1077        );
1078    }
1079    if max_lines == 0 {
1080        return Err(
1081            "Invalid get_file_content request: `max_lines` must be 1 or greater.".to_string(),
1082        );
1083    }
1084
1085    let cross: Vec<&str> = [
1086        input.around_symbol.as_ref().map(|_| "around_symbol"),
1087        input.around_match.as_ref().map(|_| "around_match"),
1088        input.match_occurrence.map(|_| "match_occurrence"),
1089        input.around_line.map(|_| "around_line"),
1090        input.start_line.map(|_| "start_line"),
1091        input.end_line.map(|_| "end_line"),
1092    ]
1093    .into_iter()
1094    .flatten()
1095    .collect();
1096
1097    if !cross.is_empty() {
1098        return Err(format!(
1099            "mode=chunk conflicts with {}. Use mode={}. Received: {}",
1100            cross.join(", "),
1101            if input.around_symbol.is_some() {
1102                "symbol"
1103            } else if input.around_match.is_some() || input.match_occurrence.is_some() {
1104                "match"
1105            } else {
1106                "lines"
1107            },
1108            describe_received_flags(input),
1109        ));
1110    }
1111
1112    Ok(search::FileContentOptions::for_explicit_path_read_chunk(
1113        input.path.clone(),
1114        chunk_index,
1115        max_lines,
1116    ))
1117}