Skip to main content

mcp_vol/
source_scan.rs

1use std::collections::BTreeMap;
2use std::fs;
3use std::path::Path;
4
5use serde::{Deserialize, Serialize};
6use serde_json::{json, Map, Value};
7
8use crate::error::Result;
9use crate::model::{Catalog, SourceLocation, ToolHints, ToolSpec, SCHEMA_VERSION};
10
11/// Source language supported by [`scan_source_str`] and [`scan_path`].
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
13#[serde(rename_all = "lowercase")]
14pub enum SourceLanguage {
15    /// Rust (`rmcp` `#[tool(...)]` attributes and `Tool::new(...)` constructors).
16    Rust,
17    /// TypeScript / JavaScript (`@modelcontextprotocol/sdk` `.tool(...)`, `.registerTool(...)`, or `tools: [...]`).
18    TypeScript,
19    /// Python (`FastMCP` / `mcp` `@*.tool(...)` decorated functions with docstrings and `Field(description=...)`).
20    Python,
21}
22
23impl SourceLanguage {
24    /// Infers a supported source language from a file extension, if recognized.
25    #[must_use]
26    pub fn from_extension(ext: &str) -> Option<Self> {
27        match ext.to_ascii_lowercase().as_str() {
28            "rs" => Some(Self::Rust),
29            "ts" | "tsx" | "mts" | "cts" | "js" | "jsx" | "mjs" | "cjs" => Some(Self::TypeScript),
30            "py" => Some(Self::Python),
31            _ => None,
32        }
33    }
34
35    /// Canonical lowercase label for reporting.
36    #[must_use]
37    pub const fn as_str(self) -> &'static str {
38        match self {
39            Self::Rust => "rust",
40            Self::TypeScript => "typescript",
41            Self::Python => "python",
42        }
43    }
44}
45
46/// Output returned by [`scan_path`] summarizing static MCP tool extraction across a codebase.
47#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
48pub struct SourceScanReport {
49    /// Report schema version.
50    pub schema_version: String,
51    /// Number of source files inspected.
52    pub files_scanned: usize,
53    /// Total MCP tool definitions extracted across all scanned files.
54    pub tools_discovered: usize,
55    /// Count of discovered tools grouped by source language (`rust`, `typescript`, `python`).
56    pub by_language: BTreeMap<String, usize>,
57    /// Extracted tool specifications (each carrying exact [`SourceLocation`]).
58    pub tools: Vec<ToolSpec>,
59}
60
61impl SourceScanReport {
62    /// Converts the discovered tools into an auditable [`Catalog`].
63    #[must_use]
64    pub fn to_catalog(&self) -> Catalog {
65        Catalog::new(self.tools.clone())
66    }
67
68    /// Serializes this scan report as pretty-printed JSON.
69    pub fn to_json_pretty(&self) -> Result<String> {
70        Ok(serde_json::to_string_pretty(self)?)
71    }
72
73    /// Serializes this scan report as minified single-line JSON.
74    pub fn to_json_compact(&self) -> Result<String> {
75        Ok(serde_json::to_string(self)?)
76    }
77}
78
79/// Recursively scans a source file or directory for static Rust (`rmcp`), TypeScript, and Python
80/// MCP tool definitions without compiling or spawning the server.
81pub fn scan_path(path: &Path) -> Result<SourceScanReport> {
82    let mut files = Vec::new();
83    collect_source_files(path, &mut files)?;
84    files.sort();
85
86    let mut tools = Vec::new();
87    let mut by_language: BTreeMap<String, usize> = BTreeMap::new();
88    let mut files_scanned = 0usize;
89
90    for (file_path, lang) in files {
91        let Ok(content) = fs::read_to_string(&file_path) else {
92            continue;
93        };
94        files_scanned += 1;
95        let display_path = file_path
96            .strip_prefix(path)
97            .ok()
98            .filter(|p| !p.as_os_str().is_empty())
99            .unwrap_or(&file_path)
100            .to_string_lossy()
101            .replace('\\', "/");
102
103        let extracted = scan_source_str(&display_path, &content, lang);
104        if !extracted.is_empty() {
105            *by_language.entry(lang.as_str().to_string()).or_insert(0) += extracted.len();
106            tools.extend(extracted);
107        }
108    }
109
110    Ok(SourceScanReport {
111        schema_version: SCHEMA_VERSION.into(),
112        files_scanned,
113        tools_discovered: tools.len(),
114        by_language,
115        tools,
116    })
117}
118
119/// Pure in-memory static extractor for a single Rust, TypeScript, or Python source string.
120///
121/// ```
122/// use mcp_vol::prelude::*;
123///
124/// let tools = scan_source_str(
125///     "src/server.py",
126///     "@mcp.tool()\ndef get_status():\n    \"\"\"Reads cluster status and returns JSON.\"\"\"\n    return {}\n",
127///     SourceLanguage::Python,
128/// );
129/// assert_eq!(tools.len(), 1);
130/// assert_eq!(tools[0].name, "get_status");
131/// ```
132#[must_use]
133pub fn scan_source_str(file_path: &str, content: &str, language: SourceLanguage) -> Vec<ToolSpec> {
134    match language {
135        SourceLanguage::Rust => scan_rust(file_path, content),
136        SourceLanguage::TypeScript => scan_typescript(file_path, content),
137        SourceLanguage::Python => scan_python(file_path, content),
138    }
139}
140
141fn collect_source_files(
142    path: &Path,
143    out: &mut Vec<(std::path::PathBuf, SourceLanguage)>,
144) -> Result<()> {
145    const SKIP_DIRS: &[&str] = &[
146        ".git",
147        "target",
148        "node_modules",
149        ".venv",
150        "venv",
151        "__pycache__",
152        "dist",
153        "build",
154        ".next",
155    ];
156    if path.is_file() {
157        if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
158            if let Some(lang) = SourceLanguage::from_extension(ext) {
159                out.push((path.to_path_buf(), lang));
160            }
161        }
162        return Ok(());
163    }
164
165    for entry in fs::read_dir(path)? {
166        let entry = entry?;
167        let p = entry.path();
168        let name = entry.file_name();
169        let name_str = name.to_string_lossy();
170        if p.is_dir() {
171            if SKIP_DIRS.contains(&name_str.as_ref()) {
172                continue;
173            }
174            collect_source_files(&p, out)?;
175        } else if let Some(ext) = p.extension().and_then(|e| e.to_str()) {
176            if let Some(lang) = SourceLanguage::from_extension(ext) {
177                out.push((p, lang));
178            }
179        }
180    }
181    Ok(())
182}
183
184// ---------------------------------------------------------------------------
185// Rust (`rmcp`) extractor: `#[tool(...)]` + parameter structs + `Tool::new(...)`
186// ---------------------------------------------------------------------------
187
188fn scan_rust(file_path: &str, src: &str) -> Vec<ToolSpec> {
189    let structs = parse_rust_structs(src);
190    let mut tools = Vec::new();
191
192    // Pattern A: `#[tool(...)]` or `#[rmcp::tool(...)]` attributes.
193    let bytes = src.as_bytes();
194    let mut i = 0usize;
195    while i < bytes.len() {
196        if bytes[i] == b'#' && src[i..].starts_with("#[") {
197            if let Some(attr_end) = find_balanced(src, i + 1, b'[', b']') {
198                let inner = src[i + 2..attr_end].trim();
199                let is_tool_attr = inner == "tool"
200                    || inner.starts_with("tool(")
201                    || inner.starts_with("rmcp::tool(")
202                    || inner == "rmcp::tool";
203                if is_tool_attr {
204                    let attr_body = inner
205                        .find('(')
206                        .and_then(|open| inner.rfind(')').map(|close| &inner[open + 1..close]))
207                        .unwrap_or("");
208                    let loc = byte_to_location(file_path, src, i);
209
210                    // Collect doc comments before or after the attribute and locate the `fn` item.
211                    let leading_doc = collect_rust_doc_comments_before(src, i);
212                    let after_attr = &src[attr_end + 1..];
213                    let (trailing_doc, fn_offset_rel) = collect_rust_doc_and_fn_after(after_attr);
214
215                    if let Some(fn_rel) = fn_offset_rel {
216                        let fn_start = attr_end + 1 + fn_rel;
217                        if let Some((fn_name, params_sig)) = parse_rust_fn_header(&src[fn_start..])
218                        {
219                            let explicit_name = extract_kv_string(attr_body, "name");
220                            let name = explicit_name.unwrap_or(fn_name);
221                            let explicit_desc = extract_kv_string(attr_body, "description");
222                            let combined_doc = if !trailing_doc.is_empty() {
223                                Some(trailing_doc)
224                            } else if !leading_doc.is_empty() {
225                                Some(leading_doc)
226                            } else {
227                                None
228                            };
229                            let description = explicit_desc.or(combined_doc);
230
231                            let annotations = parse_rust_tool_annotations(attr_body);
232                            let input_schema = build_rust_input_schema(&params_sig, &structs);
233
234                            let mut spec = ToolSpec::new(name, description, input_schema)
235                                .with_source_location(loc);
236                            if let Some(title) = extract_kv_string(attr_body, "title") {
237                                spec = spec.with_title(title);
238                            }
239                            if let Some(ann) = annotations {
240                                spec = spec.with_annotations(ann);
241                            }
242                            tools.push(spec);
243                            i = fn_start + 2;
244                            continue;
245                        }
246                    }
247                }
248                i = attr_end + 1;
249                continue;
250            }
251        }
252        i += 1;
253    }
254
255    // Pattern B: `Tool::new("name", "description", ...)`
256    let mut search_from = 0usize;
257    while let Some(rel) = src[search_from..].find("Tool::new(") {
258        let pos = search_from + rel;
259        let open_paren = pos + "Tool::new".len();
260        if let Some(close_paren) = find_balanced(src, open_paren, b'(', b')') {
261            let args_raw = &src[open_paren + 1..close_paren];
262            let args = split_top_level_args(args_raw);
263            if args.len() >= 2 {
264                if let Some(name) = parse_quoted_string(args[0].trim()) {
265                    let desc = parse_quoted_string(args[1].trim());
266                    let schema = args
267                        .get(2)
268                        .and_then(|a| extract_json_object_from_expr(a))
269                        .unwrap_or_else(empty_object_schema);
270                    let spec = ToolSpec::new(name, desc, schema)
271                        .with_source_location(byte_to_location(file_path, src, pos));
272                    tools.push(spec);
273                }
274            }
275            search_from = close_paren + 1;
276        } else {
277            break;
278        }
279    }
280
281    tools
282}
283
284#[derive(Debug, Clone)]
285struct RustField {
286    name: String,
287    rust_type: String,
288    description: Option<String>,
289    optional: bool,
290}
291
292fn parse_rust_structs(src: &str) -> BTreeMap<String, Vec<RustField>> {
293    let mut out = BTreeMap::new();
294    let mut search_from = 0usize;
295    while let Some(rel) = src[search_from..].find("struct ") {
296        let pos = search_from + rel;
297        let after = &src[pos + "struct ".len()..];
298        let name: String = after
299            .chars()
300            .take_while(|c| c.is_alphanumeric() || *c == '_')
301            .collect();
302        if name.is_empty() {
303            search_from = pos + 7;
304            continue;
305        }
306        let rest_start = pos + "struct ".len() + name.len();
307        let rest = &src[rest_start..];
308        let Some(brace_rel) = rest.find('{') else {
309            search_from = rest_start;
310            continue;
311        };
312        // Skip tuple/unit structs if a `;` precedes `{`.
313        if rest[..brace_rel].contains(';') {
314            search_from = rest_start;
315            continue;
316        }
317        let brace_pos = rest_start + brace_rel;
318        let Some(brace_end) = find_balanced(src, brace_pos, b'{', b'}') else {
319            break;
320        };
321        let body = &src[brace_pos + 1..brace_end];
322        let fields = parse_rust_struct_fields(body);
323        if !fields.is_empty() {
324            out.insert(name, fields);
325        }
326        search_from = brace_end + 1;
327    }
328    out
329}
330
331fn parse_rust_struct_fields(body: &str) -> Vec<RustField> {
332    let mut fields = Vec::new();
333    let mut pending_docs: Vec<String> = Vec::new();
334    let mut pending_schemars_desc: Option<String> = None;
335
336    for raw_line in body.lines() {
337        let line = raw_line.trim();
338        if line.is_empty() {
339            continue;
340        }
341        if let Some(doc) = line.strip_prefix("///") {
342            let trimmed = doc.trim();
343            if !trimmed.is_empty() {
344                pending_docs.push(trimmed.to_string());
345            }
346            continue;
347        }
348        if line.starts_with("#[") {
349            if let Some(d) = extract_kv_string(line, "description") {
350                pending_schemars_desc = Some(d);
351            }
352            continue;
353        }
354        if line.starts_with("//") {
355            continue;
356        }
357        let cleaned = line
358            .strip_prefix("pub(crate) ")
359            .or_else(|| line.strip_prefix("pub(super) "))
360            .or_else(|| line.strip_prefix("pub "))
361            .unwrap_or(line);
362        if let Some((lhs, rhs)) = cleaned.split_once(':') {
363            let field_name = lhs.trim().trim_start_matches("r#");
364            if !field_name.is_empty() && field_name.chars().all(|c| c.is_alphanumeric() || c == '_')
365            {
366                let ty = rhs
367                    .split("//")
368                    .next()
369                    .unwrap_or(rhs)
370                    .trim()
371                    .trim_end_matches(',')
372                    .trim();
373                let optional = ty.starts_with("Option<");
374                let desc = pending_schemars_desc.take().or_else(|| {
375                    if pending_docs.is_empty() {
376                        None
377                    } else {
378                        Some(pending_docs.join(" "))
379                    }
380                });
381                pending_docs.clear();
382                fields.push(RustField {
383                    name: field_name.to_string(),
384                    rust_type: ty.to_string(),
385                    description: desc,
386                    optional,
387                });
388            }
389        }
390    }
391    fields
392}
393
394fn build_rust_input_schema(
395    params_sig: &str,
396    structs: &BTreeMap<String, Vec<RustField>>,
397) -> Map<String, Value> {
398    let mut props = Map::new();
399    let mut required = Vec::new();
400
401    // Check for `Parameters<StructName>` or `Json<StructName>` wrapper.
402    for wrapper in ["Parameters<", "Json<"] {
403        if let Some(idx) = params_sig.find(wrapper) {
404            let after = &params_sig[idx + wrapper.len()..];
405            let type_name: String = after
406                .trim()
407                .chars()
408                .take_while(|c| c.is_alphanumeric() || *c == '_')
409                .collect();
410            if let Some(fields) = structs.get(&type_name) {
411                for f in fields {
412                    let mut prop = Map::new();
413                    prop.insert("type".into(), json!(rust_type_to_json_type(&f.rust_type)));
414                    if let Some(d) = &f.description {
415                        prop.insert("description".into(), json!(d));
416                    }
417                    props.insert(f.name.clone(), Value::Object(prop));
418                    if !f.optional {
419                        required.push(Value::String(f.name.clone()));
420                    }
421                }
422            }
423        }
424    }
425
426    let mut root = empty_object_schema();
427    if !props.is_empty() {
428        root.insert("properties".into(), Value::Object(props));
429    }
430    if !required.is_empty() {
431        root.insert("required".into(), Value::Array(required));
432    }
433    root
434}
435
436fn rust_type_to_json_type(ty: &str) -> &'static str {
437    let inner = ty
438        .strip_prefix("Option<")
439        .and_then(|s| s.strip_suffix('>'))
440        .unwrap_or(ty)
441        .trim();
442    match inner {
443        "String" | "&str" | "Cow<str>" => "string",
444        "bool" => "boolean",
445        "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64" | "u128"
446        | "usize" => "integer",
447        "f32" | "f64" => "number",
448        other if other.starts_with("Vec<") => "array",
449        _ => "object",
450    }
451}
452
453fn parse_rust_tool_annotations(attr_body: &str) -> Option<ToolHints> {
454    let read_only = extract_kv_bool(attr_body, "read_only_hint")
455        .or_else(|| extract_kv_bool(attr_body, "read_only"));
456    let destructive = extract_kv_bool(attr_body, "destructive_hint")
457        .or_else(|| extract_kv_bool(attr_body, "destructive"));
458    let idempotent = extract_kv_bool(attr_body, "idempotent_hint")
459        .or_else(|| extract_kv_bool(attr_body, "idempotent"));
460    let open_world = extract_kv_bool(attr_body, "open_world_hint")
461        .or_else(|| extract_kv_bool(attr_body, "open_world"));
462    let hints = ToolHints {
463        title: None,
464        read_only_hint: read_only,
465        destructive_hint: destructive,
466        idempotent_hint: idempotent,
467        open_world_hint: open_world,
468    };
469    if hints.has_any_behavior_hint() {
470        Some(hints)
471    } else {
472        None
473    }
474}
475
476fn collect_rust_doc_comments_before(src: &str, attr_start: usize) -> String {
477    let prefix = &src[..attr_start];
478    let mut lines = Vec::new();
479    for line in prefix.lines().rev() {
480        let trimmed = line.trim();
481        if let Some(doc) = trimmed.strip_prefix("///") {
482            let clean = doc.trim();
483            if !clean.is_empty() {
484                lines.push(clean.to_string());
485            }
486        } else if trimmed.starts_with("#[") || trimmed.is_empty() {
487            continue;
488        } else {
489            break;
490        }
491    }
492    lines.reverse();
493    lines.join(" ")
494}
495
496fn collect_rust_doc_and_fn_after(after: &str) -> (String, Option<usize>) {
497    let mut docs = Vec::new();
498    let mut offset = 0usize;
499    for raw_line in after.split_inclusive('\n') {
500        let trimmed = raw_line.trim();
501        if let Some(doc) = trimmed.strip_prefix("///") {
502            let clean = doc.trim();
503            if !clean.is_empty() {
504                docs.push(clean.to_string());
505            }
506        } else if trimmed.contains("fn ") {
507            if let Some(rel) = raw_line.find("fn ") {
508                return (docs.join(" "), Some(offset + rel));
509            }
510        } else if !trimmed.is_empty()
511            && !trimmed.starts_with("#[")
512            && !trimmed.starts_with("//")
513            && !trimmed.starts_with("pub")
514            && !trimmed.starts_with("async")
515        {
516            break;
517        }
518        offset += raw_line.len();
519    }
520    (docs.join(" "), None)
521}
522
523fn parse_rust_fn_header(from_fn: &str) -> Option<(String, String)> {
524    let after_fn = from_fn.strip_prefix("fn ")?;
525    let name: String = after_fn
526        .trim_start()
527        .chars()
528        .take_while(|c| c.is_alphanumeric() || *c == '_')
529        .collect();
530    if name.is_empty() {
531        return None;
532    }
533    let open = from_fn.find('(')?;
534    let close = find_balanced(from_fn, open, b'(', b')')?;
535    Some((name, from_fn[open + 1..close].to_string()))
536}
537
538// ---------------------------------------------------------------------------
539// TypeScript / JavaScript (`@modelcontextprotocol/sdk`) extractor
540// ---------------------------------------------------------------------------
541
542fn scan_typescript(file_path: &str, src: &str) -> Vec<ToolSpec> {
543    let mut tools = Vec::new();
544
545    // Pattern A & B: `.registerTool("name", { ... })` and `.tool("name", ...)`
546    for method in [".registerTool(", ".tool("] {
547        let mut search_from = 0usize;
548        while let Some(rel) = src[search_from..].find(method) {
549            let pos = search_from + rel;
550            let open_paren = pos + method.len() - 1;
551            let Some(close_paren) = find_balanced(src, open_paren, b'(', b')') else {
552                break;
553            };
554            let args_raw = &src[open_paren + 1..close_paren];
555            let args = split_top_level_args(args_raw);
556            if let Some(name) = args.first().and_then(|a| parse_quoted_string(a.trim())) {
557                let loc = byte_to_location(file_path, src, pos);
558                if method == ".registerTool(" {
559                    let cfg = args.get(1).map(|s| s.trim()).unwrap_or("");
560                    let desc = extract_js_string_prop(cfg, "description");
561                    let title = extract_js_string_prop(cfg, "title");
562                    let schema = extract_ts_input_schema(cfg);
563                    let annotations = extract_js_annotations(cfg);
564                    let mut spec = ToolSpec::new(name, desc, schema).with_source_location(loc);
565                    if let Some(t) = title {
566                        spec = spec.with_title(t);
567                    }
568                    if let Some(ann) = annotations {
569                        spec = spec.with_annotations(ann);
570                    }
571                    tools.push(spec);
572                } else {
573                    // `.tool("name", "desc", { zodProps }, handler)` or `.tool("name", { zodProps }, handler)`
574                    let second = args.get(1).map(|s| s.trim()).unwrap_or("");
575                    let (desc, schema_arg) = if let Some(d) = parse_quoted_string(second) {
576                        (Some(d), args.get(2).map(|s| s.trim()).unwrap_or(""))
577                    } else {
578                        (None, second)
579                    };
580                    let schema = parse_zod_object_schema(schema_arg);
581                    tools.push(ToolSpec::new(name, desc, schema).with_source_location(loc));
582                }
583            }
584            search_from = close_paren + 1;
585        }
586    }
587
588    tools
589}
590
591fn extract_ts_input_schema(cfg_obj: &str) -> Map<String, Value> {
592    if let Some(idx) = cfg_obj.find("inputSchema") {
593        let rest = &cfg_obj[idx + "inputSchema".len()..];
594        if let Some(brace_rel) = rest.find('{') {
595            let start = idx + "inputSchema".len() + brace_rel;
596            if let Some(end) = find_balanced(cfg_obj, start, b'{', b'}') {
597                let inner = &cfg_obj[start..=end];
598                if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(inner) {
599                    return map;
600                }
601                return parse_zod_object_schema(inner);
602            }
603        }
604    }
605    empty_object_schema()
606}
607
608fn parse_zod_object_schema(expr: &str) -> Map<String, Value> {
609    let trimmed = expr.trim();
610    let Some(open) = trimmed.find('{') else {
611        return empty_object_schema();
612    };
613    let Some(close) = find_balanced(trimmed, open, b'{', b'}') else {
614        return empty_object_schema();
615    };
616    let body = &trimmed[open + 1..close];
617    let entries = split_top_level_args(body);
618    let mut props = Map::new();
619    let mut required = Vec::new();
620
621    for entry in entries {
622        let Some((lhs, rhs)) = entry.split_once(':') else {
623            continue;
624        };
625        let prop_name = lhs.trim().trim_matches(|c| c == '"' || c == '\'');
626        if prop_name.is_empty()
627            || !prop_name
628                .chars()
629                .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
630        {
631            continue;
632        }
633        let val = rhs.trim();
634        let json_ty = if val.contains("z.number(") {
635            if val.contains(".int(") {
636                "integer"
637            } else {
638                "number"
639            }
640        } else if val.contains("z.boolean(") {
641            "boolean"
642        } else if val.contains("z.array(") {
643            "array"
644        } else if val.contains("z.object(") {
645            "object"
646        } else {
647            "string"
648        };
649
650        let mut p = Map::new();
651        p.insert("type".into(), json!(json_ty));
652        if let Some(desc) = extract_call_first_string(val, ".describe(") {
653            p.insert("description".into(), json!(desc));
654        }
655        if let Some(enum_vals) = extract_zod_enum(val) {
656            p.insert("enum".into(), Value::Array(enum_vals));
657        }
658        props.insert(prop_name.to_string(), Value::Object(p));
659        if !val.contains(".optional(") && !val.contains(".default(") {
660            required.push(Value::String(prop_name.to_string()));
661        }
662    }
663
664    let mut root = empty_object_schema();
665    if !props.is_empty() {
666        root.insert("properties".into(), Value::Object(props));
667    }
668    if !required.is_empty() {
669        root.insert("required".into(), Value::Array(required));
670    }
671    root
672}
673
674fn extract_zod_enum(expr: &str) -> Option<Vec<Value>> {
675    let idx = expr.find("z.enum(")?;
676    let rest = &expr[idx + "z.enum(".len()..];
677    let open = rest.find('[')?;
678    let close = find_balanced(rest, open, b'[', b']')?;
679    let items = split_top_level_args(&rest[open + 1..close]);
680    let vals: Vec<Value> = items
681        .into_iter()
682        .filter_map(|i| parse_quoted_string(i.trim()).map(Value::String))
683        .collect();
684    if vals.is_empty() {
685        None
686    } else {
687        Some(vals)
688    }
689}
690
691fn extract_js_annotations(cfg: &str) -> Option<ToolHints> {
692    let hints = ToolHints {
693        title: None,
694        read_only_hint: extract_js_bool_prop(cfg, "readOnlyHint"),
695        destructive_hint: extract_js_bool_prop(cfg, "destructiveHint"),
696        idempotent_hint: extract_js_bool_prop(cfg, "idempotentHint"),
697        open_world_hint: extract_js_bool_prop(cfg, "openWorldHint"),
698    };
699    if hints.has_any_behavior_hint() {
700        Some(hints)
701    } else {
702        None
703    }
704}
705
706// ---------------------------------------------------------------------------
707// Python (`FastMCP` / `mcp`) extractor: `@*.tool(...)` + docstrings + typing
708// ---------------------------------------------------------------------------
709
710fn scan_python(file_path: &str, src: &str) -> Vec<ToolSpec> {
711    let mut tools = Vec::new();
712    let lines: Vec<&str> = src.lines().collect();
713    let mut idx = 0usize;
714
715    while idx < lines.len() {
716        let trimmed = lines[idx].trim();
717        let is_tool_dec =
718            trimmed.starts_with('@') && (trimmed.contains(".tool(") || trimmed.ends_with(".tool"));
719        if !is_tool_dec {
720            idx += 1;
721            continue;
722        }
723
724        let dec_line_1based = idx + 1;
725        let dec_col_1based = lines[idx].find('@').map(|c| c + 1).unwrap_or(1);
726
727        // Collect full decorator expression (may span multiple lines).
728        let mut dec_buf = trimmed.to_string();
729        let mut cursor = idx;
730        while dec_buf.matches('(').count() > dec_buf.matches(')').count()
731            && cursor + 1 < lines.len()
732        {
733            cursor += 1;
734            dec_buf.push(' ');
735            dec_buf.push_str(lines[cursor].trim());
736        }
737
738        // Find following `def ` or `async def `.
739        let mut fn_idx = cursor + 1;
740        while fn_idx < lines.len()
741            && (lines[fn_idx].trim().is_empty() || lines[fn_idx].trim().starts_with('@'))
742        {
743            fn_idx += 1;
744        }
745        if fn_idx >= lines.len() {
746            break;
747        }
748        let fn_line = lines[fn_idx].trim();
749        let after_def = fn_line
750            .strip_prefix("async def ")
751            .or_else(|| fn_line.strip_prefix("def "));
752        let Some(after_def) = after_def else {
753            idx = fn_idx + 1;
754            continue;
755        };
756
757        let fn_name: String = after_def
758            .chars()
759            .take_while(|c| c.is_alphanumeric() || *c == '_')
760            .collect();
761        if fn_name.is_empty() {
762            idx = fn_idx + 1;
763            continue;
764        }
765
766        // Collect complete parameter signature across lines until matching `)`.
767        let mut sig_buf = after_def.to_string();
768        let mut sig_end_idx = fn_idx;
769        while sig_buf.matches('(').count() > sig_buf.matches(')').count()
770            && sig_end_idx + 1 < lines.len()
771        {
772            sig_end_idx += 1;
773            sig_buf.push(' ');
774            sig_buf.push_str(lines[sig_end_idx].trim());
775        }
776        let params_inner = sig_buf
777            .find('(')
778            .and_then(|o| find_balanced(&sig_buf, o, b'(', b')').map(|c| &sig_buf[o + 1..c]))
779            .unwrap_or("");
780
781        // Extract Python triple-quoted docstring on first body statement.
782        let docstring = extract_python_docstring(&lines, sig_end_idx + 1);
783
784        let dec_args = dec_buf
785            .find('(')
786            .and_then(|o| dec_buf.rfind(')').map(|c| &dec_buf[o + 1..c]))
787            .unwrap_or("");
788        let name = extract_kv_string(dec_args, "name").unwrap_or(fn_name);
789        let desc = extract_kv_string(dec_args, "description").or(docstring);
790        let input_schema = parse_python_params_schema(params_inner);
791
792        let mut spec =
793            ToolSpec::new(name, desc, input_schema).with_source_location(SourceLocation {
794                file: file_path.to_string(),
795                line: dec_line_1based,
796                column: dec_col_1based,
797            });
798        if let Some(ann) = extract_python_annotations(dec_args) {
799            spec = spec.with_annotations(ann);
800        }
801        tools.push(spec);
802        idx = sig_end_idx + 1;
803    }
804
805    tools
806}
807
808fn extract_python_docstring(lines: &[&str], start_idx: usize) -> Option<String> {
809    let mut i = start_idx;
810    while i < lines.len() && lines[i].trim().is_empty() {
811        i += 1;
812    }
813    let first = lines.get(i)?.trim();
814    let quote = if first.starts_with("\"\"\"") {
815        "\"\"\""
816    } else if first.starts_with("'''") {
817        "'''"
818    } else {
819        return None;
820    };
821    let rest = &first[3..];
822    if let Some(end) = rest.find(quote) {
823        let s = rest[..end].trim();
824        return if s.is_empty() {
825            None
826        } else {
827            Some(s.to_string())
828        };
829    }
830    let mut collected = Vec::new();
831    if !rest.trim().is_empty() {
832        collected.push(rest.trim().to_string());
833    }
834    i += 1;
835    while i < lines.len() {
836        let l = lines[i].trim();
837        if let Some(end) = l.find(quote) {
838            let tail = l[..end].trim();
839            if !tail.is_empty() {
840                collected.push(tail.to_string());
841            }
842            break;
843        }
844        if !l.is_empty() {
845            collected.push(l.to_string());
846        }
847        i += 1;
848    }
849    let joined = collected.join(" ");
850    if joined.is_empty() {
851        None
852    } else {
853        Some(joined)
854    }
855}
856
857fn parse_python_params_schema(params_inner: &str) -> Map<String, Value> {
858    let mut props = Map::new();
859    let mut required = Vec::new();
860
861    for raw in split_top_level_args(params_inner) {
862        let param = raw.trim();
863        if param.is_empty() || param == "*" || param == "/" || param.starts_with('*') {
864            continue;
865        }
866        let (decl, default_rhs) = split_top_level_eq(param);
867        let (name_raw, type_raw) = decl
868            .split_once(':')
869            .map(|(n, t)| (n.trim(), t.trim()))
870            .unwrap_or((decl.trim(), ""));
871        if matches!(name_raw, "self" | "cls" | "ctx" | "context") || type_raw.contains("Context") {
872            continue;
873        }
874
875        let is_optional = default_rhs.is_some()
876            || type_raw.contains("Optional[")
877            || type_raw.contains("| None")
878            || type_raw.contains("None |");
879        let json_ty = if type_raw.contains("int") {
880            "integer"
881        } else if type_raw.contains("float") {
882            "number"
883        } else if type_raw.contains("bool") {
884            "boolean"
885        } else if type_raw.contains("list") || type_raw.contains("List") {
886            "array"
887        } else if type_raw.contains("dict") || type_raw.contains("Dict") {
888            "object"
889        } else {
890            "string"
891        };
892
893        let mut p = Map::new();
894        p.insert("type".into(), json!(json_ty));
895        let desc = extract_kv_string(type_raw, "description")
896            .or_else(|| default_rhs.and_then(|d| extract_kv_string(d, "description")));
897        if let Some(d) = desc {
898            p.insert("description".into(), json!(d));
899        }
900        props.insert(name_raw.to_string(), Value::Object(p));
901        if !is_optional {
902            required.push(Value::String(name_raw.to_string()));
903        }
904    }
905
906    let mut root = empty_object_schema();
907    if !props.is_empty() {
908        root.insert("properties".into(), Value::Object(props));
909    }
910    if !required.is_empty() {
911        root.insert("required".into(), Value::Array(required));
912    }
913    root
914}
915
916fn extract_python_annotations(dec_args: &str) -> Option<ToolHints> {
917    let hints = ToolHints {
918        title: None,
919        read_only_hint: extract_py_bool(dec_args, "readOnlyHint")
920            .or_else(|| extract_py_bool(dec_args, "read_only_hint")),
921        destructive_hint: extract_py_bool(dec_args, "destructiveHint")
922            .or_else(|| extract_py_bool(dec_args, "destructive_hint")),
923        idempotent_hint: extract_py_bool(dec_args, "idempotentHint")
924            .or_else(|| extract_py_bool(dec_args, "idempotent_hint")),
925        open_world_hint: extract_py_bool(dec_args, "openWorldHint")
926            .or_else(|| extract_py_bool(dec_args, "open_world_hint")),
927    };
928    if hints.has_any_behavior_hint() {
929        Some(hints)
930    } else {
931        None
932    }
933}
934
935fn extract_py_bool(text: &str, key: &str) -> Option<bool> {
936    let idx = text.find(key)?;
937    let rest = text[idx + key.len()..]
938        .trim_start()
939        .trim_start_matches(['"', '\''])
940        .trim_start()
941        .trim_start_matches(['=', ':'])
942        .trim_start();
943    if rest.starts_with("True") || rest.starts_with("true") {
944        Some(true)
945    } else if rest.starts_with("False") || rest.starts_with("false") {
946        Some(false)
947    } else {
948        None
949    }
950}
951
952// ---------------------------------------------------------------------------
953// Shared balanced-delimiter & string literal utilities
954// ---------------------------------------------------------------------------
955
956fn empty_object_schema() -> Map<String, Value> {
957    let mut m = Map::new();
958    m.insert("type".into(), json!("object"));
959    m
960}
961
962fn byte_to_location(file: &str, src: &str, byte_offset: usize) -> SourceLocation {
963    let clamped = byte_offset.min(src.len());
964    let prefix = &src[..clamped];
965    let line = prefix.bytes().filter(|&b| b == b'\n').count() + 1;
966    let last_nl = prefix.rfind('\n').map(|p| p + 1).unwrap_or(0);
967    let column = prefix[last_nl..].chars().count() + 1;
968    SourceLocation {
969        file: file.to_string(),
970        line,
971        column,
972    }
973}
974
975fn find_balanced(src: &str, open_idx: usize, open_ch: u8, close_ch: u8) -> Option<usize> {
976    let bytes = src.as_bytes();
977    if bytes.get(open_idx).copied() != Some(open_ch) {
978        return None;
979    }
980    let mut depth = 0usize;
981    let mut i = open_idx;
982    let mut in_quote: Option<u8> = None;
983    while i < bytes.len() {
984        let b = bytes[i];
985        if let Some(q) = in_quote {
986            if b == b'\\' {
987                i += 2;
988                continue;
989            }
990            if b == q {
991                in_quote = None;
992            }
993            i += 1;
994            continue;
995        }
996        if b == b'"' || b == b'\'' || b == b'`' {
997            in_quote = Some(b);
998            i += 1;
999            continue;
1000        }
1001        if b == open_ch {
1002            depth += 1;
1003        } else if b == close_ch {
1004            depth = depth.saturating_sub(1);
1005            if depth == 0 {
1006                return Some(i);
1007            }
1008        }
1009        i += 1;
1010    }
1011    None
1012}
1013
1014fn split_top_level_args(s: &str) -> Vec<&str> {
1015    let mut out = Vec::new();
1016    let bytes = s.as_bytes();
1017    let mut depth_p = 0usize;
1018    let mut depth_b = 0usize;
1019    let mut depth_c = 0usize;
1020    let mut in_quote: Option<u8> = None;
1021    let mut start = 0usize;
1022    let mut i = 0usize;
1023
1024    while i < bytes.len() {
1025        let b = bytes[i];
1026        if let Some(q) = in_quote {
1027            if b == b'\\' {
1028                i += 2;
1029                continue;
1030            }
1031            if b == q {
1032                in_quote = None;
1033            }
1034            i += 1;
1035            continue;
1036        }
1037        match b {
1038            b'"' | b'\'' | b'`' => in_quote = Some(b),
1039            b'(' => depth_p += 1,
1040            b')' => depth_p = depth_p.saturating_sub(1),
1041            b'[' => depth_b += 1,
1042            b']' => depth_b = depth_b.saturating_sub(1),
1043            b'{' => depth_c += 1,
1044            b'}' => depth_c = depth_c.saturating_sub(1),
1045            b',' if depth_p == 0 && depth_b == 0 && depth_c == 0 => {
1046                out.push(&s[start..i]);
1047                start = i + 1;
1048            }
1049            _ => {}
1050        }
1051        i += 1;
1052    }
1053    if start < s.len() {
1054        out.push(&s[start..]);
1055    }
1056    out
1057}
1058
1059fn split_top_level_eq(s: &str) -> (&str, Option<&str>) {
1060    let bytes = s.as_bytes();
1061    let mut depth = 0usize;
1062    let mut in_quote: Option<u8> = None;
1063    let mut i = 0usize;
1064    while i < bytes.len() {
1065        let b = bytes[i];
1066        if let Some(q) = in_quote {
1067            if b == b'\\' {
1068                i += 2;
1069                continue;
1070            }
1071            if b == q {
1072                in_quote = None;
1073            }
1074            i += 1;
1075            continue;
1076        }
1077        match b {
1078            b'"' | b'\'' => in_quote = Some(b),
1079            b'(' | b'[' | b'{' => depth += 1,
1080            b')' | b']' | b'}' => depth = depth.saturating_sub(1),
1081            b'=' if depth == 0 => return (&s[..i], Some(s[i + 1..].trim())),
1082            _ => {}
1083        }
1084        i += 1;
1085    }
1086    (s, None)
1087}
1088
1089fn parse_quoted_string(s: &str) -> Option<String> {
1090    let trimmed = s.trim();
1091    let first = trimmed.as_bytes().first().copied()?;
1092    if first != b'"' && first != b'\'' && first != b'`' {
1093        return None;
1094    }
1095    let mut out = String::new();
1096    let mut chars = trimmed[1..].chars();
1097    while let Some(c) = chars.next() {
1098        if c == '\\' {
1099            if let Some(esc) = chars.next() {
1100                match esc {
1101                    'n' => out.push('\n'),
1102                    't' => out.push('\t'),
1103                    'r' => out.push('\r'),
1104                    other => out.push(other),
1105                }
1106            }
1107        } else if c as u8 == first && c.is_ascii() {
1108            return Some(out);
1109        } else {
1110            out.push(c);
1111        }
1112    }
1113    None
1114}
1115
1116fn extract_kv_string(text: &str, key: &str) -> Option<String> {
1117    let mut search = 0usize;
1118    while let Some(rel) = text[search..].find(key) {
1119        let pos = search + rel;
1120        let prev_ok = pos == 0
1121            || !text.as_bytes()[pos - 1].is_ascii_alphanumeric()
1122                && text.as_bytes()[pos - 1] != b'_';
1123        if prev_ok {
1124            let after = text[pos + key.len()..].trim_start();
1125            if let Some(rhs) = after.strip_prefix('=') {
1126                if let Some(val) = parse_quoted_string(rhs.trim_start()) {
1127                    return Some(val);
1128                }
1129            }
1130        }
1131        search = pos + key.len();
1132    }
1133    None
1134}
1135
1136fn extract_kv_bool(text: &str, key: &str) -> Option<bool> {
1137    let mut search = 0usize;
1138    while let Some(rel) = text[search..].find(key) {
1139        let pos = search + rel;
1140        let prev_ok = pos == 0
1141            || !text.as_bytes()[pos - 1].is_ascii_alphanumeric()
1142                && text.as_bytes()[pos - 1] != b'_';
1143        if prev_ok {
1144            let after = text[pos + key.len()..].trim_start();
1145            if let Some(rhs) = after.strip_prefix('=') {
1146                let v = rhs.trim_start();
1147                if v.starts_with("true") {
1148                    return Some(true);
1149                }
1150                if v.starts_with("false") {
1151                    return Some(false);
1152                }
1153            }
1154        }
1155        search = pos + key.len();
1156    }
1157    None
1158}
1159
1160fn extract_js_string_prop(obj: &str, key: &str) -> Option<String> {
1161    let mut search = 0usize;
1162    while let Some(rel) = obj[search..].find(key) {
1163        let pos = search + rel;
1164        let after = obj[pos + key.len()..]
1165            .trim_start()
1166            .trim_start_matches(['"', '\''])
1167            .trim_start();
1168        if let Some(rhs) = after.strip_prefix(':') {
1169            if let Some(val) = parse_quoted_string(rhs.trim_start()) {
1170                return Some(val);
1171            }
1172        }
1173        search = pos + key.len();
1174    }
1175    None
1176}
1177
1178fn extract_js_bool_prop(obj: &str, key: &str) -> Option<bool> {
1179    let mut search = 0usize;
1180    while let Some(rel) = obj[search..].find(key) {
1181        let pos = search + rel;
1182        let after = obj[pos + key.len()..]
1183            .trim_start()
1184            .trim_start_matches(['"', '\''])
1185            .trim_start();
1186        if let Some(rhs) = after.strip_prefix(':') {
1187            let v = rhs.trim_start();
1188            if v.starts_with("true") {
1189                return Some(true);
1190            }
1191            if v.starts_with("false") {
1192                return Some(false);
1193            }
1194        }
1195        search = pos + key.len();
1196    }
1197    None
1198}
1199
1200fn extract_call_first_string(expr: &str, call_prefix: &str) -> Option<String> {
1201    let idx = expr.find(call_prefix)?;
1202    let rest = &expr[idx + call_prefix.len()..];
1203    parse_quoted_string(rest.trim_start())
1204}
1205
1206fn extract_json_object_from_expr(expr: &str) -> Option<Map<String, Value>> {
1207    let start = expr.find('{')?;
1208    let end = find_balanced(expr, start, b'{', b'}')?;
1209    let candidate = &expr[start..=end];
1210    serde_json::from_str::<Value>(candidate)
1211        .ok()
1212        .and_then(|v| v.as_object().cloned())
1213}
1214
1215#[cfg(test)]
1216mod tests {
1217    use super::*;
1218
1219    #[test]
1220    fn extracts_rmcp_rust_tool_with_struct_params_and_location() {
1221        let rust_src = r#"
1222struct IssueQuery {
1223    /// Target repository in owner/name format.
1224    pub repo: String,
1225    pub limit: Option<usize>,
1226}
1227
1228#[tool(
1229    description = "Lists open GitHub issues for a repository, capped at 50 results.",
1230    annotations(read_only_hint = true, destructive_hint = false)
1231)]
1232async fn list_issues(Parameters(args): Parameters<IssueQuery>) -> String {
1233    todo!()
1234}
1235"#;
1236        let tools = scan_source_str("src/tools.rs", rust_src, SourceLanguage::Rust);
1237        assert_eq!(tools.len(), 1);
1238        let t = &tools[0];
1239        assert_eq!(t.name, "list_issues");
1240        assert!(t.description.as_deref().unwrap().contains("Lists open"));
1241        assert_eq!(t.annotations.as_ref().unwrap().read_only_hint, Some(true));
1242        assert_eq!(t.required_parameters(), vec!["repo"]);
1243        assert!(t.parameter_names().contains(&"limit"));
1244        assert_eq!(t.source_location.as_ref().unwrap().file, "src/tools.rs");
1245        assert_eq!(t.source_location.as_ref().unwrap().line, 8);
1246    }
1247
1248    #[test]
1249    fn extracts_typescript_sdk_tools_with_zod_schemas() {
1250        let ts_src = r#"
1251server.registerTool(
1252  "delete_cache",
1253  {
1254    description: "Deletes local cache entries permanently.",
1255    annotations: { readOnlyHint: true, destructiveHint: false },
1256    inputSchema: {
1257      bucket: z.string().describe("Cache namespace bucket."),
1258      mode: z.enum(["soft", "hard"]).optional().describe("Purge mode.")
1259    }
1260  },
1261  async () => ({})
1262);
1263"#;
1264        let tools = scan_source_str("src/server.ts", ts_src, SourceLanguage::TypeScript);
1265        assert_eq!(tools.len(), 1);
1266        let t = &tools[0];
1267        assert_eq!(t.name, "delete_cache");
1268        assert_eq!(t.annotations.as_ref().unwrap().read_only_hint, Some(true));
1269        assert_eq!(t.required_parameters(), vec!["bucket"]);
1270        assert_eq!(t.source_location.as_ref().unwrap().line, 2);
1271    }
1272
1273    #[test]
1274    fn extracts_python_fastmcp_tools_with_docstrings_and_fields() {
1275        let py_src = r#"
1276@mcp.tool(annotations={"readOnlyHint": True})
1277async def search_notes(
1278    query: Annotated[str, Field(description="Full-text search query.")],
1279    limit: int = 20,
1280) -> list[str]:
1281    """Searches local markdown notes and returns matching snippets up to limit."""
1282    return []
1283"#;
1284        let tools = scan_source_str("server.py", py_src, SourceLanguage::Python);
1285        assert_eq!(tools.len(), 1);
1286        let t = &tools[0];
1287        assert_eq!(t.name, "search_notes");
1288        assert!(t.description.as_deref().unwrap().contains("Searches local"));
1289        assert_eq!(t.required_parameters(), vec!["query"]);
1290        assert!(t.parameter_names().contains(&"limit"));
1291        assert_eq!(t.annotations.as_ref().unwrap().read_only_hint, Some(true));
1292        assert_eq!(t.source_location.as_ref().unwrap().line, 2);
1293    }
1294}