use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use serde::{Deserialize, Serialize};
use serde_json::{json, Map, Value};
use crate::error::Result;
use crate::model::{Catalog, SourceLocation, ToolHints, ToolSpec, SCHEMA_VERSION};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum SourceLanguage {
Rust,
TypeScript,
Python,
}
impl SourceLanguage {
#[must_use]
pub fn from_extension(ext: &str) -> Option<Self> {
match ext.to_ascii_lowercase().as_str() {
"rs" => Some(Self::Rust),
"ts" | "tsx" | "mts" | "cts" | "js" | "jsx" | "mjs" | "cjs" => Some(Self::TypeScript),
"py" => Some(Self::Python),
_ => None,
}
}
#[must_use]
pub const fn as_str(self) -> &'static str {
match self {
Self::Rust => "rust",
Self::TypeScript => "typescript",
Self::Python => "python",
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SourceScanReport {
pub schema_version: String,
pub files_scanned: usize,
pub tools_discovered: usize,
pub by_language: BTreeMap<String, usize>,
pub tools: Vec<ToolSpec>,
}
impl SourceScanReport {
#[must_use]
pub fn to_catalog(&self) -> Catalog {
Catalog::new(self.tools.clone())
}
pub fn to_json_pretty(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}
pub fn to_json_compact(&self) -> Result<String> {
Ok(serde_json::to_string(self)?)
}
}
pub fn scan_path(path: &Path) -> Result<SourceScanReport> {
let mut files = Vec::new();
collect_source_files(path, &mut files)?;
files.sort();
let mut tools = Vec::new();
let mut by_language: BTreeMap<String, usize> = BTreeMap::new();
let mut files_scanned = 0usize;
for (file_path, lang) in files {
let Ok(content) = fs::read_to_string(&file_path) else {
continue;
};
files_scanned += 1;
let display_path = file_path
.strip_prefix(path)
.ok()
.filter(|p| !p.as_os_str().is_empty())
.unwrap_or(&file_path)
.to_string_lossy()
.replace('\\', "/");
let extracted = scan_source_str(&display_path, &content, lang);
if !extracted.is_empty() {
*by_language.entry(lang.as_str().to_string()).or_insert(0) += extracted.len();
tools.extend(extracted);
}
}
Ok(SourceScanReport {
schema_version: SCHEMA_VERSION.into(),
files_scanned,
tools_discovered: tools.len(),
by_language,
tools,
})
}
#[must_use]
pub fn scan_source_str(file_path: &str, content: &str, language: SourceLanguage) -> Vec<ToolSpec> {
match language {
SourceLanguage::Rust => scan_rust(file_path, content),
SourceLanguage::TypeScript => scan_typescript(file_path, content),
SourceLanguage::Python => scan_python(file_path, content),
}
}
fn collect_source_files(
path: &Path,
out: &mut Vec<(std::path::PathBuf, SourceLanguage)>,
) -> Result<()> {
const SKIP_DIRS: &[&str] = &[
".git",
"target",
"node_modules",
".venv",
"venv",
"__pycache__",
"dist",
"build",
".next",
];
if path.is_file() {
if let Some(ext) = path.extension().and_then(|e| e.to_str()) {
if let Some(lang) = SourceLanguage::from_extension(ext) {
out.push((path.to_path_buf(), lang));
}
}
return Ok(());
}
for entry in fs::read_dir(path)? {
let entry = entry?;
let p = entry.path();
let name = entry.file_name();
let name_str = name.to_string_lossy();
if p.is_dir() {
if SKIP_DIRS.contains(&name_str.as_ref()) {
continue;
}
collect_source_files(&p, out)?;
} else if let Some(ext) = p.extension().and_then(|e| e.to_str()) {
if let Some(lang) = SourceLanguage::from_extension(ext) {
out.push((p, lang));
}
}
}
Ok(())
}
fn scan_rust(file_path: &str, src: &str) -> Vec<ToolSpec> {
let structs = parse_rust_structs(src);
let mut tools = Vec::new();
let bytes = src.as_bytes();
let mut i = 0usize;
while i < bytes.len() {
if bytes[i] == b'#' && src[i..].starts_with("#[") {
if let Some(attr_end) = find_balanced(src, i + 1, b'[', b']') {
let inner = src[i + 2..attr_end].trim();
let is_tool_attr = inner == "tool"
|| inner.starts_with("tool(")
|| inner.starts_with("rmcp::tool(")
|| inner == "rmcp::tool";
if is_tool_attr {
let attr_body = inner
.find('(')
.and_then(|open| inner.rfind(')').map(|close| &inner[open + 1..close]))
.unwrap_or("");
let loc = byte_to_location(file_path, src, i);
let leading_doc = collect_rust_doc_comments_before(src, i);
let after_attr = &src[attr_end + 1..];
let (trailing_doc, fn_offset_rel) = collect_rust_doc_and_fn_after(after_attr);
if let Some(fn_rel) = fn_offset_rel {
let fn_start = attr_end + 1 + fn_rel;
if let Some((fn_name, params_sig)) = parse_rust_fn_header(&src[fn_start..])
{
let explicit_name = extract_kv_string(attr_body, "name");
let name = explicit_name.unwrap_or(fn_name);
let explicit_desc = extract_kv_string(attr_body, "description");
let combined_doc = if !trailing_doc.is_empty() {
Some(trailing_doc)
} else if !leading_doc.is_empty() {
Some(leading_doc)
} else {
None
};
let description = explicit_desc.or(combined_doc);
let annotations = parse_rust_tool_annotations(attr_body);
let input_schema = build_rust_input_schema(¶ms_sig, &structs);
let mut spec = ToolSpec::new(name, description, input_schema)
.with_source_location(loc);
if let Some(title) = extract_kv_string(attr_body, "title") {
spec = spec.with_title(title);
}
if let Some(ann) = annotations {
spec = spec.with_annotations(ann);
}
tools.push(spec);
i = fn_start + 2;
continue;
}
}
}
i = attr_end + 1;
continue;
}
}
i += 1;
}
let mut search_from = 0usize;
while let Some(rel) = src[search_from..].find("Tool::new(") {
let pos = search_from + rel;
let open_paren = pos + "Tool::new".len();
if let Some(close_paren) = find_balanced(src, open_paren, b'(', b')') {
let args_raw = &src[open_paren + 1..close_paren];
let args = split_top_level_args(args_raw);
if args.len() >= 2 {
if let Some(name) = parse_quoted_string(args[0].trim()) {
let desc = parse_quoted_string(args[1].trim());
let schema = args
.get(2)
.and_then(|a| extract_json_object_from_expr(a))
.unwrap_or_else(empty_object_schema);
let spec = ToolSpec::new(name, desc, schema)
.with_source_location(byte_to_location(file_path, src, pos));
tools.push(spec);
}
}
search_from = close_paren + 1;
} else {
break;
}
}
tools
}
#[derive(Debug, Clone)]
struct RustField {
name: String,
rust_type: String,
description: Option<String>,
optional: bool,
}
fn parse_rust_structs(src: &str) -> BTreeMap<String, Vec<RustField>> {
let mut out = BTreeMap::new();
let mut search_from = 0usize;
while let Some(rel) = src[search_from..].find("struct ") {
let pos = search_from + rel;
let after = &src[pos + "struct ".len()..];
let name: String = after
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if name.is_empty() {
search_from = pos + 7;
continue;
}
let rest_start = pos + "struct ".len() + name.len();
let rest = &src[rest_start..];
let Some(brace_rel) = rest.find('{') else {
search_from = rest_start;
continue;
};
if rest[..brace_rel].contains(';') {
search_from = rest_start;
continue;
}
let brace_pos = rest_start + brace_rel;
let Some(brace_end) = find_balanced(src, brace_pos, b'{', b'}') else {
break;
};
let body = &src[brace_pos + 1..brace_end];
let fields = parse_rust_struct_fields(body);
if !fields.is_empty() {
out.insert(name, fields);
}
search_from = brace_end + 1;
}
out
}
fn parse_rust_struct_fields(body: &str) -> Vec<RustField> {
let mut fields = Vec::new();
let mut pending_docs: Vec<String> = Vec::new();
let mut pending_schemars_desc: Option<String> = None;
for raw_line in body.lines() {
let line = raw_line.trim();
if line.is_empty() {
continue;
}
if let Some(doc) = line.strip_prefix("///") {
let trimmed = doc.trim();
if !trimmed.is_empty() {
pending_docs.push(trimmed.to_string());
}
continue;
}
if line.starts_with("#[") {
if let Some(d) = extract_kv_string(line, "description") {
pending_schemars_desc = Some(d);
}
continue;
}
if line.starts_with("//") {
continue;
}
let cleaned = line
.strip_prefix("pub(crate) ")
.or_else(|| line.strip_prefix("pub(super) "))
.or_else(|| line.strip_prefix("pub "))
.unwrap_or(line);
if let Some((lhs, rhs)) = cleaned.split_once(':') {
let field_name = lhs.trim().trim_start_matches("r#");
if !field_name.is_empty() && field_name.chars().all(|c| c.is_alphanumeric() || c == '_')
{
let ty = rhs
.split("//")
.next()
.unwrap_or(rhs)
.trim()
.trim_end_matches(',')
.trim();
let optional = ty.starts_with("Option<");
let desc = pending_schemars_desc.take().or_else(|| {
if pending_docs.is_empty() {
None
} else {
Some(pending_docs.join(" "))
}
});
pending_docs.clear();
fields.push(RustField {
name: field_name.to_string(),
rust_type: ty.to_string(),
description: desc,
optional,
});
}
}
}
fields
}
fn build_rust_input_schema(
params_sig: &str,
structs: &BTreeMap<String, Vec<RustField>>,
) -> Map<String, Value> {
let mut props = Map::new();
let mut required = Vec::new();
for wrapper in ["Parameters<", "Json<"] {
if let Some(idx) = params_sig.find(wrapper) {
let after = ¶ms_sig[idx + wrapper.len()..];
let type_name: String = after
.trim()
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if let Some(fields) = structs.get(&type_name) {
for f in fields {
let mut prop = Map::new();
prop.insert("type".into(), json!(rust_type_to_json_type(&f.rust_type)));
if let Some(d) = &f.description {
prop.insert("description".into(), json!(d));
}
props.insert(f.name.clone(), Value::Object(prop));
if !f.optional {
required.push(Value::String(f.name.clone()));
}
}
}
}
}
let mut root = empty_object_schema();
if !props.is_empty() {
root.insert("properties".into(), Value::Object(props));
}
if !required.is_empty() {
root.insert("required".into(), Value::Array(required));
}
root
}
fn rust_type_to_json_type(ty: &str) -> &'static str {
let inner = ty
.strip_prefix("Option<")
.and_then(|s| s.strip_suffix('>'))
.unwrap_or(ty)
.trim();
match inner {
"String" | "&str" | "Cow<str>" => "string",
"bool" => "boolean",
"i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64" | "u128"
| "usize" => "integer",
"f32" | "f64" => "number",
other if other.starts_with("Vec<") => "array",
_ => "object",
}
}
fn parse_rust_tool_annotations(attr_body: &str) -> Option<ToolHints> {
let read_only = extract_kv_bool(attr_body, "read_only_hint")
.or_else(|| extract_kv_bool(attr_body, "read_only"));
let destructive = extract_kv_bool(attr_body, "destructive_hint")
.or_else(|| extract_kv_bool(attr_body, "destructive"));
let idempotent = extract_kv_bool(attr_body, "idempotent_hint")
.or_else(|| extract_kv_bool(attr_body, "idempotent"));
let open_world = extract_kv_bool(attr_body, "open_world_hint")
.or_else(|| extract_kv_bool(attr_body, "open_world"));
let hints = ToolHints {
title: None,
read_only_hint: read_only,
destructive_hint: destructive,
idempotent_hint: idempotent,
open_world_hint: open_world,
};
if hints.has_any_behavior_hint() {
Some(hints)
} else {
None
}
}
fn collect_rust_doc_comments_before(src: &str, attr_start: usize) -> String {
let prefix = &src[..attr_start];
let mut lines = Vec::new();
for line in prefix.lines().rev() {
let trimmed = line.trim();
if let Some(doc) = trimmed.strip_prefix("///") {
let clean = doc.trim();
if !clean.is_empty() {
lines.push(clean.to_string());
}
} else if trimmed.starts_with("#[") || trimmed.is_empty() {
continue;
} else {
break;
}
}
lines.reverse();
lines.join(" ")
}
fn collect_rust_doc_and_fn_after(after: &str) -> (String, Option<usize>) {
let mut docs = Vec::new();
let mut offset = 0usize;
for raw_line in after.split_inclusive('\n') {
let trimmed = raw_line.trim();
if let Some(doc) = trimmed.strip_prefix("///") {
let clean = doc.trim();
if !clean.is_empty() {
docs.push(clean.to_string());
}
} else if trimmed.contains("fn ") {
if let Some(rel) = raw_line.find("fn ") {
return (docs.join(" "), Some(offset + rel));
}
} else if !trimmed.is_empty()
&& !trimmed.starts_with("#[")
&& !trimmed.starts_with("//")
&& !trimmed.starts_with("pub")
&& !trimmed.starts_with("async")
{
break;
}
offset += raw_line.len();
}
(docs.join(" "), None)
}
fn parse_rust_fn_header(from_fn: &str) -> Option<(String, String)> {
let after_fn = from_fn.strip_prefix("fn ")?;
let name: String = after_fn
.trim_start()
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if name.is_empty() {
return None;
}
let open = from_fn.find('(')?;
let close = find_balanced(from_fn, open, b'(', b')')?;
Some((name, from_fn[open + 1..close].to_string()))
}
fn scan_typescript(file_path: &str, src: &str) -> Vec<ToolSpec> {
let mut tools = Vec::new();
for method in [".registerTool(", ".tool("] {
let mut search_from = 0usize;
while let Some(rel) = src[search_from..].find(method) {
let pos = search_from + rel;
let open_paren = pos + method.len() - 1;
let Some(close_paren) = find_balanced(src, open_paren, b'(', b')') else {
break;
};
let args_raw = &src[open_paren + 1..close_paren];
let args = split_top_level_args(args_raw);
if let Some(name) = args.first().and_then(|a| parse_quoted_string(a.trim())) {
let loc = byte_to_location(file_path, src, pos);
if method == ".registerTool(" {
let cfg = args.get(1).map(|s| s.trim()).unwrap_or("");
let desc = extract_js_string_prop(cfg, "description");
let title = extract_js_string_prop(cfg, "title");
let schema = extract_ts_input_schema(cfg);
let annotations = extract_js_annotations(cfg);
let mut spec = ToolSpec::new(name, desc, schema).with_source_location(loc);
if let Some(t) = title {
spec = spec.with_title(t);
}
if let Some(ann) = annotations {
spec = spec.with_annotations(ann);
}
tools.push(spec);
} else {
let second = args.get(1).map(|s| s.trim()).unwrap_or("");
let (desc, schema_arg) = if let Some(d) = parse_quoted_string(second) {
(Some(d), args.get(2).map(|s| s.trim()).unwrap_or(""))
} else {
(None, second)
};
let schema = parse_zod_object_schema(schema_arg);
tools.push(ToolSpec::new(name, desc, schema).with_source_location(loc));
}
}
search_from = close_paren + 1;
}
}
tools
}
fn extract_ts_input_schema(cfg_obj: &str) -> Map<String, Value> {
if let Some(idx) = cfg_obj.find("inputSchema") {
let rest = &cfg_obj[idx + "inputSchema".len()..];
if let Some(brace_rel) = rest.find('{') {
let start = idx + "inputSchema".len() + brace_rel;
if let Some(end) = find_balanced(cfg_obj, start, b'{', b'}') {
let inner = &cfg_obj[start..=end];
if let Ok(Value::Object(map)) = serde_json::from_str::<Value>(inner) {
return map;
}
return parse_zod_object_schema(inner);
}
}
}
empty_object_schema()
}
fn parse_zod_object_schema(expr: &str) -> Map<String, Value> {
let trimmed = expr.trim();
let Some(open) = trimmed.find('{') else {
return empty_object_schema();
};
let Some(close) = find_balanced(trimmed, open, b'{', b'}') else {
return empty_object_schema();
};
let body = &trimmed[open + 1..close];
let entries = split_top_level_args(body);
let mut props = Map::new();
let mut required = Vec::new();
for entry in entries {
let Some((lhs, rhs)) = entry.split_once(':') else {
continue;
};
let prop_name = lhs.trim().trim_matches(|c| c == '"' || c == '\'');
if prop_name.is_empty()
|| !prop_name
.chars()
.all(|c| c.is_alphanumeric() || c == '_' || c == '-')
{
continue;
}
let val = rhs.trim();
let json_ty = if val.contains("z.number(") {
if val.contains(".int(") {
"integer"
} else {
"number"
}
} else if val.contains("z.boolean(") {
"boolean"
} else if val.contains("z.array(") {
"array"
} else if val.contains("z.object(") {
"object"
} else {
"string"
};
let mut p = Map::new();
p.insert("type".into(), json!(json_ty));
if let Some(desc) = extract_call_first_string(val, ".describe(") {
p.insert("description".into(), json!(desc));
}
if let Some(enum_vals) = extract_zod_enum(val) {
p.insert("enum".into(), Value::Array(enum_vals));
}
props.insert(prop_name.to_string(), Value::Object(p));
if !val.contains(".optional(") && !val.contains(".default(") {
required.push(Value::String(prop_name.to_string()));
}
}
let mut root = empty_object_schema();
if !props.is_empty() {
root.insert("properties".into(), Value::Object(props));
}
if !required.is_empty() {
root.insert("required".into(), Value::Array(required));
}
root
}
fn extract_zod_enum(expr: &str) -> Option<Vec<Value>> {
let idx = expr.find("z.enum(")?;
let rest = &expr[idx + "z.enum(".len()..];
let open = rest.find('[')?;
let close = find_balanced(rest, open, b'[', b']')?;
let items = split_top_level_args(&rest[open + 1..close]);
let vals: Vec<Value> = items
.into_iter()
.filter_map(|i| parse_quoted_string(i.trim()).map(Value::String))
.collect();
if vals.is_empty() {
None
} else {
Some(vals)
}
}
fn extract_js_annotations(cfg: &str) -> Option<ToolHints> {
let hints = ToolHints {
title: None,
read_only_hint: extract_js_bool_prop(cfg, "readOnlyHint"),
destructive_hint: extract_js_bool_prop(cfg, "destructiveHint"),
idempotent_hint: extract_js_bool_prop(cfg, "idempotentHint"),
open_world_hint: extract_js_bool_prop(cfg, "openWorldHint"),
};
if hints.has_any_behavior_hint() {
Some(hints)
} else {
None
}
}
fn scan_python(file_path: &str, src: &str) -> Vec<ToolSpec> {
let mut tools = Vec::new();
let lines: Vec<&str> = src.lines().collect();
let mut idx = 0usize;
while idx < lines.len() {
let trimmed = lines[idx].trim();
let is_tool_dec =
trimmed.starts_with('@') && (trimmed.contains(".tool(") || trimmed.ends_with(".tool"));
if !is_tool_dec {
idx += 1;
continue;
}
let dec_line_1based = idx + 1;
let dec_col_1based = lines[idx].find('@').map(|c| c + 1).unwrap_or(1);
let mut dec_buf = trimmed.to_string();
let mut cursor = idx;
while dec_buf.matches('(').count() > dec_buf.matches(')').count()
&& cursor + 1 < lines.len()
{
cursor += 1;
dec_buf.push(' ');
dec_buf.push_str(lines[cursor].trim());
}
let mut fn_idx = cursor + 1;
while fn_idx < lines.len()
&& (lines[fn_idx].trim().is_empty() || lines[fn_idx].trim().starts_with('@'))
{
fn_idx += 1;
}
if fn_idx >= lines.len() {
break;
}
let fn_line = lines[fn_idx].trim();
let after_def = fn_line
.strip_prefix("async def ")
.or_else(|| fn_line.strip_prefix("def "));
let Some(after_def) = after_def else {
idx = fn_idx + 1;
continue;
};
let fn_name: String = after_def
.chars()
.take_while(|c| c.is_alphanumeric() || *c == '_')
.collect();
if fn_name.is_empty() {
idx = fn_idx + 1;
continue;
}
let mut sig_buf = after_def.to_string();
let mut sig_end_idx = fn_idx;
while sig_buf.matches('(').count() > sig_buf.matches(')').count()
&& sig_end_idx + 1 < lines.len()
{
sig_end_idx += 1;
sig_buf.push(' ');
sig_buf.push_str(lines[sig_end_idx].trim());
}
let params_inner = sig_buf
.find('(')
.and_then(|o| find_balanced(&sig_buf, o, b'(', b')').map(|c| &sig_buf[o + 1..c]))
.unwrap_or("");
let docstring = extract_python_docstring(&lines, sig_end_idx + 1);
let dec_args = dec_buf
.find('(')
.and_then(|o| dec_buf.rfind(')').map(|c| &dec_buf[o + 1..c]))
.unwrap_or("");
let name = extract_kv_string(dec_args, "name").unwrap_or(fn_name);
let desc = extract_kv_string(dec_args, "description").or(docstring);
let input_schema = parse_python_params_schema(params_inner);
let mut spec =
ToolSpec::new(name, desc, input_schema).with_source_location(SourceLocation {
file: file_path.to_string(),
line: dec_line_1based,
column: dec_col_1based,
});
if let Some(ann) = extract_python_annotations(dec_args) {
spec = spec.with_annotations(ann);
}
tools.push(spec);
idx = sig_end_idx + 1;
}
tools
}
fn extract_python_docstring(lines: &[&str], start_idx: usize) -> Option<String> {
let mut i = start_idx;
while i < lines.len() && lines[i].trim().is_empty() {
i += 1;
}
let first = lines.get(i)?.trim();
let quote = if first.starts_with("\"\"\"") {
"\"\"\""
} else if first.starts_with("'''") {
"'''"
} else {
return None;
};
let rest = &first[3..];
if let Some(end) = rest.find(quote) {
let s = rest[..end].trim();
return if s.is_empty() {
None
} else {
Some(s.to_string())
};
}
let mut collected = Vec::new();
if !rest.trim().is_empty() {
collected.push(rest.trim().to_string());
}
i += 1;
while i < lines.len() {
let l = lines[i].trim();
if let Some(end) = l.find(quote) {
let tail = l[..end].trim();
if !tail.is_empty() {
collected.push(tail.to_string());
}
break;
}
if !l.is_empty() {
collected.push(l.to_string());
}
i += 1;
}
let joined = collected.join(" ");
if joined.is_empty() {
None
} else {
Some(joined)
}
}
fn parse_python_params_schema(params_inner: &str) -> Map<String, Value> {
let mut props = Map::new();
let mut required = Vec::new();
for raw in split_top_level_args(params_inner) {
let param = raw.trim();
if param.is_empty() || param == "*" || param == "/" || param.starts_with('*') {
continue;
}
let (decl, default_rhs) = split_top_level_eq(param);
let (name_raw, type_raw) = decl
.split_once(':')
.map(|(n, t)| (n.trim(), t.trim()))
.unwrap_or((decl.trim(), ""));
if matches!(name_raw, "self" | "cls" | "ctx" | "context") || type_raw.contains("Context") {
continue;
}
let is_optional = default_rhs.is_some()
|| type_raw.contains("Optional[")
|| type_raw.contains("| None")
|| type_raw.contains("None |");
let json_ty = if type_raw.contains("int") {
"integer"
} else if type_raw.contains("float") {
"number"
} else if type_raw.contains("bool") {
"boolean"
} else if type_raw.contains("list") || type_raw.contains("List") {
"array"
} else if type_raw.contains("dict") || type_raw.contains("Dict") {
"object"
} else {
"string"
};
let mut p = Map::new();
p.insert("type".into(), json!(json_ty));
let desc = extract_kv_string(type_raw, "description")
.or_else(|| default_rhs.and_then(|d| extract_kv_string(d, "description")));
if let Some(d) = desc {
p.insert("description".into(), json!(d));
}
props.insert(name_raw.to_string(), Value::Object(p));
if !is_optional {
required.push(Value::String(name_raw.to_string()));
}
}
let mut root = empty_object_schema();
if !props.is_empty() {
root.insert("properties".into(), Value::Object(props));
}
if !required.is_empty() {
root.insert("required".into(), Value::Array(required));
}
root
}
fn extract_python_annotations(dec_args: &str) -> Option<ToolHints> {
let hints = ToolHints {
title: None,
read_only_hint: extract_py_bool(dec_args, "readOnlyHint")
.or_else(|| extract_py_bool(dec_args, "read_only_hint")),
destructive_hint: extract_py_bool(dec_args, "destructiveHint")
.or_else(|| extract_py_bool(dec_args, "destructive_hint")),
idempotent_hint: extract_py_bool(dec_args, "idempotentHint")
.or_else(|| extract_py_bool(dec_args, "idempotent_hint")),
open_world_hint: extract_py_bool(dec_args, "openWorldHint")
.or_else(|| extract_py_bool(dec_args, "open_world_hint")),
};
if hints.has_any_behavior_hint() {
Some(hints)
} else {
None
}
}
fn extract_py_bool(text: &str, key: &str) -> Option<bool> {
let idx = text.find(key)?;
let rest = text[idx + key.len()..]
.trim_start()
.trim_start_matches(['"', '\''])
.trim_start()
.trim_start_matches(['=', ':'])
.trim_start();
if rest.starts_with("True") || rest.starts_with("true") {
Some(true)
} else if rest.starts_with("False") || rest.starts_with("false") {
Some(false)
} else {
None
}
}
fn empty_object_schema() -> Map<String, Value> {
let mut m = Map::new();
m.insert("type".into(), json!("object"));
m
}
fn byte_to_location(file: &str, src: &str, byte_offset: usize) -> SourceLocation {
let clamped = byte_offset.min(src.len());
let prefix = &src[..clamped];
let line = prefix.bytes().filter(|&b| b == b'\n').count() + 1;
let last_nl = prefix.rfind('\n').map(|p| p + 1).unwrap_or(0);
let column = prefix[last_nl..].chars().count() + 1;
SourceLocation {
file: file.to_string(),
line,
column,
}
}
fn find_balanced(src: &str, open_idx: usize, open_ch: u8, close_ch: u8) -> Option<usize> {
let bytes = src.as_bytes();
if bytes.get(open_idx).copied() != Some(open_ch) {
return None;
}
let mut depth = 0usize;
let mut i = open_idx;
let mut in_quote: Option<u8> = None;
while i < bytes.len() {
let b = bytes[i];
if let Some(q) = in_quote {
if b == b'\\' {
i += 2;
continue;
}
if b == q {
in_quote = None;
}
i += 1;
continue;
}
if b == b'"' || b == b'\'' || b == b'`' {
in_quote = Some(b);
i += 1;
continue;
}
if b == open_ch {
depth += 1;
} else if b == close_ch {
depth = depth.saturating_sub(1);
if depth == 0 {
return Some(i);
}
}
i += 1;
}
None
}
fn split_top_level_args(s: &str) -> Vec<&str> {
let mut out = Vec::new();
let bytes = s.as_bytes();
let mut depth_p = 0usize;
let mut depth_b = 0usize;
let mut depth_c = 0usize;
let mut in_quote: Option<u8> = None;
let mut start = 0usize;
let mut i = 0usize;
while i < bytes.len() {
let b = bytes[i];
if let Some(q) = in_quote {
if b == b'\\' {
i += 2;
continue;
}
if b == q {
in_quote = None;
}
i += 1;
continue;
}
match b {
b'"' | b'\'' | b'`' => in_quote = Some(b),
b'(' => depth_p += 1,
b')' => depth_p = depth_p.saturating_sub(1),
b'[' => depth_b += 1,
b']' => depth_b = depth_b.saturating_sub(1),
b'{' => depth_c += 1,
b'}' => depth_c = depth_c.saturating_sub(1),
b',' if depth_p == 0 && depth_b == 0 && depth_c == 0 => {
out.push(&s[start..i]);
start = i + 1;
}
_ => {}
}
i += 1;
}
if start < s.len() {
out.push(&s[start..]);
}
out
}
fn split_top_level_eq(s: &str) -> (&str, Option<&str>) {
let bytes = s.as_bytes();
let mut depth = 0usize;
let mut in_quote: Option<u8> = None;
let mut i = 0usize;
while i < bytes.len() {
let b = bytes[i];
if let Some(q) = in_quote {
if b == b'\\' {
i += 2;
continue;
}
if b == q {
in_quote = None;
}
i += 1;
continue;
}
match b {
b'"' | b'\'' => in_quote = Some(b),
b'(' | b'[' | b'{' => depth += 1,
b')' | b']' | b'}' => depth = depth.saturating_sub(1),
b'=' if depth == 0 => return (&s[..i], Some(s[i + 1..].trim())),
_ => {}
}
i += 1;
}
(s, None)
}
fn parse_quoted_string(s: &str) -> Option<String> {
let trimmed = s.trim();
let first = trimmed.as_bytes().first().copied()?;
if first != b'"' && first != b'\'' && first != b'`' {
return None;
}
let mut out = String::new();
let mut chars = trimmed[1..].chars();
while let Some(c) = chars.next() {
if c == '\\' {
if let Some(esc) = chars.next() {
match esc {
'n' => out.push('\n'),
't' => out.push('\t'),
'r' => out.push('\r'),
other => out.push(other),
}
}
} else if c as u8 == first && c.is_ascii() {
return Some(out);
} else {
out.push(c);
}
}
None
}
fn extract_kv_string(text: &str, key: &str) -> Option<String> {
let mut search = 0usize;
while let Some(rel) = text[search..].find(key) {
let pos = search + rel;
let prev_ok = pos == 0
|| !text.as_bytes()[pos - 1].is_ascii_alphanumeric()
&& text.as_bytes()[pos - 1] != b'_';
if prev_ok {
let after = text[pos + key.len()..].trim_start();
if let Some(rhs) = after.strip_prefix('=') {
if let Some(val) = parse_quoted_string(rhs.trim_start()) {
return Some(val);
}
}
}
search = pos + key.len();
}
None
}
fn extract_kv_bool(text: &str, key: &str) -> Option<bool> {
let mut search = 0usize;
while let Some(rel) = text[search..].find(key) {
let pos = search + rel;
let prev_ok = pos == 0
|| !text.as_bytes()[pos - 1].is_ascii_alphanumeric()
&& text.as_bytes()[pos - 1] != b'_';
if prev_ok {
let after = text[pos + key.len()..].trim_start();
if let Some(rhs) = after.strip_prefix('=') {
let v = rhs.trim_start();
if v.starts_with("true") {
return Some(true);
}
if v.starts_with("false") {
return Some(false);
}
}
}
search = pos + key.len();
}
None
}
fn extract_js_string_prop(obj: &str, key: &str) -> Option<String> {
let mut search = 0usize;
while let Some(rel) = obj[search..].find(key) {
let pos = search + rel;
let after = obj[pos + key.len()..]
.trim_start()
.trim_start_matches(['"', '\''])
.trim_start();
if let Some(rhs) = after.strip_prefix(':') {
if let Some(val) = parse_quoted_string(rhs.trim_start()) {
return Some(val);
}
}
search = pos + key.len();
}
None
}
fn extract_js_bool_prop(obj: &str, key: &str) -> Option<bool> {
let mut search = 0usize;
while let Some(rel) = obj[search..].find(key) {
let pos = search + rel;
let after = obj[pos + key.len()..]
.trim_start()
.trim_start_matches(['"', '\''])
.trim_start();
if let Some(rhs) = after.strip_prefix(':') {
let v = rhs.trim_start();
if v.starts_with("true") {
return Some(true);
}
if v.starts_with("false") {
return Some(false);
}
}
search = pos + key.len();
}
None
}
fn extract_call_first_string(expr: &str, call_prefix: &str) -> Option<String> {
let idx = expr.find(call_prefix)?;
let rest = &expr[idx + call_prefix.len()..];
parse_quoted_string(rest.trim_start())
}
fn extract_json_object_from_expr(expr: &str) -> Option<Map<String, Value>> {
let start = expr.find('{')?;
let end = find_balanced(expr, start, b'{', b'}')?;
let candidate = &expr[start..=end];
serde_json::from_str::<Value>(candidate)
.ok()
.and_then(|v| v.as_object().cloned())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn extracts_rmcp_rust_tool_with_struct_params_and_location() {
let rust_src = r#"
struct IssueQuery {
/// Target repository in owner/name format.
pub repo: String,
pub limit: Option<usize>,
}
#[tool(
description = "Lists open GitHub issues for a repository, capped at 50 results.",
annotations(read_only_hint = true, destructive_hint = false)
)]
async fn list_issues(Parameters(args): Parameters<IssueQuery>) -> String {
todo!()
}
"#;
let tools = scan_source_str("src/tools.rs", rust_src, SourceLanguage::Rust);
assert_eq!(tools.len(), 1);
let t = &tools[0];
assert_eq!(t.name, "list_issues");
assert!(t.description.as_deref().unwrap().contains("Lists open"));
assert_eq!(t.annotations.as_ref().unwrap().read_only_hint, Some(true));
assert_eq!(t.required_parameters(), vec!["repo"]);
assert!(t.parameter_names().contains(&"limit"));
assert_eq!(t.source_location.as_ref().unwrap().file, "src/tools.rs");
assert_eq!(t.source_location.as_ref().unwrap().line, 8);
}
#[test]
fn extracts_typescript_sdk_tools_with_zod_schemas() {
let ts_src = r#"
server.registerTool(
"delete_cache",
{
description: "Deletes local cache entries permanently.",
annotations: { readOnlyHint: true, destructiveHint: false },
inputSchema: {
bucket: z.string().describe("Cache namespace bucket."),
mode: z.enum(["soft", "hard"]).optional().describe("Purge mode.")
}
},
async () => ({})
);
"#;
let tools = scan_source_str("src/server.ts", ts_src, SourceLanguage::TypeScript);
assert_eq!(tools.len(), 1);
let t = &tools[0];
assert_eq!(t.name, "delete_cache");
assert_eq!(t.annotations.as_ref().unwrap().read_only_hint, Some(true));
assert_eq!(t.required_parameters(), vec!["bucket"]);
assert_eq!(t.source_location.as_ref().unwrap().line, 2);
}
#[test]
fn extracts_python_fastmcp_tools_with_docstrings_and_fields() {
let py_src = r#"
@mcp.tool(annotations={"readOnlyHint": True})
async def search_notes(
query: Annotated[str, Field(description="Full-text search query.")],
limit: int = 20,
) -> list[str]:
"""Searches local markdown notes and returns matching snippets up to limit."""
return []
"#;
let tools = scan_source_str("server.py", py_src, SourceLanguage::Python);
assert_eq!(tools.len(), 1);
let t = &tools[0];
assert_eq!(t.name, "search_notes");
assert!(t.description.as_deref().unwrap().contains("Searches local"));
assert_eq!(t.required_parameters(), vec!["query"]);
assert!(t.parameter_names().contains(&"limit"));
assert_eq!(t.annotations.as_ref().unwrap().read_only_hint, Some(true));
assert_eq!(t.source_location.as_ref().unwrap().line, 2);
}
}