alef 0.83.1

Opinionated polyglot binding generator for Rust libraries
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
use super::context::{CliCommand, CliOption, CliSurface, McpItem, McpSurface};
use crate::core::config::{DeclaredMcpItem, DeclaredMcpKind};
use anyhow::Context as _;
use heck::ToKebabCase;
use quote::ToTokens;
use std::collections::{BTreeMap, HashMap};
use std::path::PathBuf;
use syn::{Fields, FnArg, Item, Type};

pub fn extract_cli_surface(sources: &[PathBuf]) -> anyhow::Result<CliSurface> {
    let parsed = parse_sources(sources)?;
    let mut structs = HashMap::new();
    let mut enums = HashMap::new();

    for file in &parsed {
        for item in &file.items {
            match item {
                Item::Struct(item) => {
                    if has_derive(&item.attrs, "Parser")
                        || has_derive(&item.attrs, "Args")
                        || item.attrs.iter().any(|attr| attr.path().is_ident("command"))
                    {
                        structs.insert(item.ident.to_string(), item.clone());
                    }
                }
                Item::Enum(item) if has_derive(&item.attrs, "Subcommand") => {
                    enums.insert(item.ident.to_string(), item.clone());
                }
                _ => {}
            }
        }
    }

    let mut commands = Vec::new();
    let mut roots: Vec<_> = structs
        .values()
        .filter(|item| has_derive(&item.attrs, "Parser"))
        .collect();
    roots.sort_by_key(|item| item.ident.to_string());

    for root in roots {
        commands.push(command_from_struct(root, &structs, &enums, None));
    }

    Ok(CliSurface { commands })
}

/// Extract the MCP surface from attribute-declared `#[tool]`/`#[prompt]`/`#[resource]` methods,
/// then append `declared` — the config fallback for surfaces built at runtime (for example a
/// `Prompt::new(...)` call) that carry no attribute for this scan to find. See
/// [`crate::core::config::DocsMcpConfig::declared`] for the precedence rule: an attribute-derived
/// item always wins over a declared entry with the same `(kind, name)`.
pub fn extract_mcp_surface(sources: &[PathBuf], declared: &[DeclaredMcpItem]) -> anyhow::Result<McpSurface> {
    let parsed = parse_sources(sources)?;
    let mut surface = McpSurface::default();

    for file in &parsed {
        for item in &file.items {
            let Item::Impl(item_impl) = item else {
                continue;
            };
            for item in &item_impl.items {
                let syn::ImplItem::Fn(method) = item else {
                    continue;
                };
                for attr_name in ["tool", "prompt", "resource"] {
                    let Some(tokens) = attr_tokens(&method.attrs, attr_name) else {
                        continue;
                    };
                    let name = quoted_value(&tokens, "name").unwrap_or_else(|| method.sig.ident.to_string());
                    let description = quoted_value(&tokens, "description")
                        .or_else(|| first_doc_paragraph(&method.attrs))
                        .unwrap_or_default();
                    let annotations = annotation_map(&tokens);
                    let title = annotations
                        .get("title")
                        .cloned()
                        .unwrap_or_else(|| name.replace('_', " ").to_title_case());
                    let item = McpItem {
                        name,
                        title,
                        description,
                        handler: method.sig.ident.to_string(),
                        params_type: method_params_type(method),
                        annotations,
                    };
                    match attr_name {
                        "tool" => surface.tools.push(item),
                        "prompt" => surface.prompts.push(item),
                        "resource" => surface.resources.push(item),
                        _ => unreachable!(),
                    }
                }
            }
        }
    }

    merge_declared_items(&mut surface, declared);

    surface.tools.sort_by(|left, right| left.name.cmp(&right.name));
    surface.prompts.sort_by(|left, right| left.name.cmp(&right.name));
    surface.resources.sort_by(|left, right| left.name.cmp(&right.name));
    Ok(surface)
}

/// Append `declared` config entries to the attribute-derived `surface`, one list per kind.
///
/// Precedence: an attribute-derived item always wins. When a declared entry's name collides
/// with one already found by attribute scanning, the declared entry is dropped rather than
/// appended — a collision means the source has since grown an attribute for that surface and
/// the config entry is stale, not that the surface legitimately has two definitions. Dropped
/// entries are reported once, as a single counted warning, so a consumer notices the drift
/// without one log line per stale entry.
fn merge_declared_items(surface: &mut McpSurface, declared: &[DeclaredMcpItem]) {
    let mut skipped = Vec::new();
    for entry in declared {
        let (target, kind_label) = match entry.kind {
            DeclaredMcpKind::Tool => (&mut surface.tools, "tool"),
            DeclaredMcpKind::Prompt => (&mut surface.prompts, "prompt"),
            DeclaredMcpKind::Resource => (&mut surface.resources, "resource"),
        };
        if target.iter().any(|item| item.name == entry.name) {
            skipped.push(format!("{kind_label} `{}`", entry.name));
            continue;
        }
        target.push(declared_to_mcp_item(entry));
    }
    if !skipped.is_empty() {
        tracing::warn!(
            skipped_count = skipped.len(),
            skipped = %skipped.join(", "),
            "docs.mcp.declared has {} entr{} that duplicate attribute-derived MCP surfaces; \
             keeping the attribute-derived definition and ignoring the declared duplicate(s)",
            skipped.len(),
            if skipped.len() == 1 { "y" } else { "ies" },
        );
    }
}

fn declared_to_mcp_item(entry: &DeclaredMcpItem) -> McpItem {
    let title = entry
        .title
        .clone()
        .unwrap_or_else(|| entry.name.replace('_', " ").to_title_case());
    McpItem {
        name: entry.name.clone(),
        title,
        description: entry.description.clone().unwrap_or_default(),
        handler: entry.name.clone(),
        params_type: entry.params_type.clone(),
        annotations: entry.annotations.clone(),
    }
}

fn parse_sources(sources: &[PathBuf]) -> anyhow::Result<Vec<syn::File>> {
    let mut parsed = Vec::new();
    for source in sources {
        if !source.exists() {
            continue;
        }
        let content = std::fs::read_to_string(source)
            .with_context(|| format!("failed to read docs source {}", source.display()))?;
        parsed.push(
            syn::parse_file(&content).with_context(|| format!("failed to parse docs source {}", source.display()))?,
        );
    }
    Ok(parsed)
}

fn command_from_struct(
    item: &syn::ItemStruct,
    structs: &HashMap<String, syn::ItemStruct>,
    enums: &HashMap<String, syn::ItemEnum>,
    forced_name: Option<String>,
) -> CliCommand {
    let name = forced_name
        .or_else(|| command_name(&item.attrs))
        .unwrap_or_else(|| item.ident.to_string().to_kebab_case());
    let about = command_about(&item.attrs)
        .or_else(|| first_doc_paragraph(&item.attrs))
        .unwrap_or_default();
    let mut command = CliCommand {
        path: name.clone(),
        name,
        about,
        ..CliCommand::default()
    };

    let Fields::Named(fields) = &item.fields else {
        return command;
    };

    for field in &fields.named {
        process_command_field(field, &mut command, structs, enums);
    }

    command
}

/// Add a single named clap field to `command`, resolving `#[command(subcommand)]`
/// and `#[command(flatten)]` — flattened args are expanded inline rather than
/// emitted as an opaque struct row. Shared by struct-derived commands and
/// struct-like enum-variant commands so both expand flattened args identically.
fn process_command_field(
    field: &syn::Field,
    command: &mut CliCommand,
    structs: &HashMap<String, syn::ItemStruct>,
    enums: &HashMap<String, syn::ItemEnum>,
) {
    if has_attr_word(&field.attrs, "command", "subcommand") {
        if let Some(enum_name) = type_last_ident(&field.ty)
            && let Some(en) = enums.get(&enum_name)
        {
            command.subcommands = commands_from_enum(en, structs, enums, &command.path);
        }
        return;
    }
    if has_attr_word(&field.attrs, "command", "flatten") {
        if let Some(struct_name) = type_last_ident(&field.ty)
            && let Some(flattened) = structs.get(&struct_name)
        {
            let mut flattened_command = command_from_struct(flattened, structs, enums, Some(command.name.clone()));
            command.options.append(&mut flattened_command.options);
            command.positionals.append(&mut flattened_command.positionals);
        }
        return;
    }
    let option = option_from_field(field);
    if option.long.is_some() || option.short.is_some() || option.ty == "bool" {
        command.options.push(option);
    } else {
        command.positionals.push(option);
    }
}

fn commands_from_enum(
    item: &syn::ItemEnum,
    structs: &HashMap<String, syn::ItemStruct>,
    enums: &HashMap<String, syn::ItemEnum>,
    parent_path: &str,
) -> Vec<CliCommand> {
    let mut commands = Vec::new();
    for variant in &item.variants {
        let name = command_name(&variant.attrs).unwrap_or_else(|| variant.ident.to_string().to_kebab_case());
        let about = command_about(&variant.attrs)
            .or_else(|| first_doc_paragraph(&variant.attrs))
            .unwrap_or_default();
        let mut command = CliCommand {
            path: format!("{parent_path} {name}"),
            name,
            about,
            ..CliCommand::default()
        };

        match &variant.fields {
            Fields::Named(fields) => {
                for field in &fields.named {
                    process_command_field(field, &mut command, structs, enums);
                }
            }
            Fields::Unnamed(fields) if fields.unnamed.len() == 1 => {
                let ty = &fields.unnamed.first().expect("checked len").ty;
                if let Some(struct_name) = type_last_ident(ty)
                    && let Some(args) = structs.get(&struct_name)
                {
                    let nested = command_from_struct(args, structs, enums, Some(command.name.clone()));
                    command.options = nested.options;
                    command.positionals = nested.positionals;
                    command.subcommands = nested.subcommands;
                }
            }
            Fields::Unnamed(fields) => {
                for (index, field) in fields.unnamed.iter().enumerate() {
                    let mut option = option_from_field(field);
                    if option.name.is_empty() {
                        option.name = format!("arg{}", index + 1);
                    }
                    command.positionals.push(option);
                }
            }
            Fields::Unit => {}
        }
        commands.push(command);
    }
    commands.sort_by(|left, right| left.name.cmp(&right.name));
    commands
}

fn option_from_field(field: &syn::Field) -> CliOption {
    let name = field.ident.as_ref().map(ToString::to_string).unwrap_or_default();
    let arg_tokens = attr_tokens(&field.attrs, "arg").unwrap_or_default();
    let long = if let Some(value) = quoted_value(&arg_tokens, "long") {
        Some(value)
    } else if has_bare_word(&arg_tokens, "long") {
        Some(name.to_kebab_case())
    } else {
        None
    };
    let short = quoted_value(&arg_tokens, "short").or_else(|| char_value(&arg_tokens, "short"));
    let default = quoted_value(&arg_tokens, "default_value")
        .or_else(|| quoted_value(&arg_tokens, "default_value_t"))
        .or_else(|| bare_value(&arg_tokens, "default_value_t"));
    CliOption {
        name,
        long,
        short,
        value_name: quoted_value(&arg_tokens, "value_name"),
        ty: type_to_string(&field.ty),
        default,
        required: has_bare_word(&arg_tokens, "required"),
        help: first_doc_paragraph(&field.attrs).unwrap_or_default(),
    }
}

fn method_params_type(method: &syn::ImplItemFn) -> Option<String> {
    method.sig.inputs.iter().find_map(|input| {
        let FnArg::Typed(pat_ty) = input else {
            return None;
        };
        let text = type_to_string(&pat_ty.ty);
        text.contains("Parameters").then_some(text)
    })
}

fn has_derive(attrs: &[syn::Attribute], derive_name: &str) -> bool {
    attrs.iter().any(|attr| {
        if !attr.path().is_ident("derive") {
            return false;
        }
        let paths = attr.parse_args_with(syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated);
        paths.is_ok_and(|paths| {
            paths
                .iter()
                .any(|path| path.segments.last().is_some_and(|segment| segment.ident == derive_name))
        })
    })
}

fn attr_tokens(attrs: &[syn::Attribute], attr_name: &str) -> Option<String> {
    attrs.iter().find_map(|attr| {
        attr.path()
            .is_ident(attr_name)
            .then(|| attr.meta.to_token_stream().to_string())
    })
}

fn command_name(attrs: &[syn::Attribute]) -> Option<String> {
    let tokens = attr_tokens(attrs, "command")?;
    quoted_value(&tokens, "name")
}

fn command_about(attrs: &[syn::Attribute]) -> Option<String> {
    let tokens = attr_tokens(attrs, "command")?;
    quoted_value(&tokens, "about").or_else(|| quoted_value(&tokens, "long_about"))
}

fn has_attr_word(attrs: &[syn::Attribute], attr_name: &str, word: &str) -> bool {
    attr_tokens(attrs, attr_name).is_some_and(|tokens| has_bare_word(&tokens, word))
}

fn first_doc_paragraph(attrs: &[syn::Attribute]) -> Option<String> {
    let mut lines = Vec::new();
    for attr in attrs {
        if !attr.path().is_ident("doc") {
            continue;
        }
        if let syn::Meta::NameValue(meta) = &attr.meta
            && let syn::Expr::Lit(expr_lit) = &meta.value
            && let syn::Lit::Str(lit) = &expr_lit.lit
        {
            let line = lit.value().trim().to_string();
            if line.is_empty() {
                if !lines.is_empty() {
                    break;
                }
            } else {
                lines.push(line);
            }
        }
    }
    (!lines.is_empty()).then(|| lines.join(" "))
}

fn annotation_map(tokens: &str) -> BTreeMap<String, String> {
    let Some(start) = tokens.find("annotations") else {
        return BTreeMap::new();
    };
    let mut map = BTreeMap::new();
    let tail = &tokens[start..];
    for key in [
        "title",
        "read_only_hint",
        "destructive_hint",
        "idempotent_hint",
        "open_world_hint",
    ] {
        if let Some(value) = quoted_value(tail, key).or_else(|| bare_value(tail, key)) {
            map.insert(key.to_string(), value);
        }
    }
    map
}

fn quoted_value(tokens: &str, key: &str) -> Option<String> {
    let needle = format!("{key} = \"");
    let start = tokens.find(&needle)? + needle.len();
    let rest = &tokens[start..];
    let end = rest.find('"')?;
    Some(rest[..end].to_string())
}

fn char_value(tokens: &str, key: &str) -> Option<String> {
    let needle = format!("{key} = '");
    let start = tokens.find(&needle)? + needle.len();
    let rest = &tokens[start..];
    let end = rest.find('\'')?;
    Some(rest[..end].to_string())
}

fn bare_value(tokens: &str, key: &str) -> Option<String> {
    let needle = format!("{key} = ");
    let start = tokens.find(&needle)? + needle.len();
    let rest = &tokens[start..];
    let value: String = rest
        .chars()
        .take_while(|ch| ch.is_ascii_alphanumeric() || matches!(ch, '_' | '-' | '.'))
        .collect();
    (!value.is_empty()).then_some(value)
}

fn has_bare_word(tokens: &str, word: &str) -> bool {
    tokens
        .split(|ch: char| !ch.is_ascii_alphanumeric() && ch != '_')
        .any(|part| part == word)
}

fn type_last_ident(ty: &Type) -> Option<String> {
    let Type::Path(type_path) = ty else {
        return None;
    };
    let segment = type_path.path.segments.last()?;
    if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
        for arg in &args.args {
            if let syn::GenericArgument::Type(inner) = arg
                && let Some(name) = type_last_ident(inner)
            {
                return Some(name);
            }
        }
    }
    Some(segment.ident.to_string())
}

fn type_to_string<T: ToTokens + ?Sized>(ty: &T) -> String {
    let text = ty.to_token_stream().to_string();
    text.replace(" :: ", "::")
        .replace(" < ", "<")
        .replace(" >", ">")
        .replace(" , ", ", ")
        .replace("& '", "&'")
}

trait TitleCase {
    fn to_title_case(&self) -> String;
}

impl TitleCase for str {
    fn to_title_case(&self) -> String {
        let mut out = String::with_capacity(self.len());
        let mut uppercase = true;
        for ch in self.chars() {
            if ch == '_' || ch == '-' {
                out.push(' ');
                uppercase = true;
            } else if uppercase {
                out.extend(ch.to_uppercase());
                uppercase = false;
            } else {
                out.push(ch);
            }
        }
        out
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn empty_mcp_source(dir: &std::path::Path) -> PathBuf {
        let source = dir.join("mcp.rs");
        std::fs::write(&source, "struct Server;\n").unwrap();
        source
    }

    #[test]
    fn runtime_constructed_prompts_and_resources_are_invisible_to_attribute_extraction() {
        // Proves the reported defect red first: a prompt/resource built at runtime via a
        // constructor call (not a `#[prompt]`/`#[resource]` attribute) is not found by scanning
        // method attributes, however many source files are pointed at it. ~keep
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("mcp.rs");
        std::fs::write(
            &source,
            r#"
            struct Server;
            impl Server {
                fn build_prompts(&self) -> Vec<Prompt> {
                    vec![Prompt::new("summarize", "Summarize the input")]
                }
                fn build_resources(&self) -> Vec<Resource> {
                    vec![Resource::new("config", "App configuration")]
                }
            }
            "#,
        )
        .unwrap();
        let surface = extract_mcp_surface(&[source], &[]).unwrap();
        assert!(surface.prompts.is_empty());
        assert!(surface.resources.is_empty());
    }

    #[test]
    fn declared_prompts_and_resources_fill_the_gap_attribute_extraction_misses() {
        let dir = tempfile::tempdir().unwrap();
        let source = empty_mcp_source(dir.path());
        let declared = vec![
            DeclaredMcpItem {
                kind: DeclaredMcpKind::Prompt,
                name: "summarize".to_string(),
                title: None,
                description: Some("Summarize the input".to_string()),
                params_type: None,
                annotations: BTreeMap::new(),
            },
            DeclaredMcpItem {
                kind: DeclaredMcpKind::Resource,
                name: "config".to_string(),
                title: Some("App Config".to_string()),
                description: Some("App configuration".to_string()),
                params_type: None,
                annotations: BTreeMap::new(),
            },
        ];
        let surface = extract_mcp_surface(&[source], &declared).unwrap();
        assert_eq!(surface.prompts.len(), 1);
        assert_eq!(surface.prompts[0].name, "summarize");
        assert_eq!(surface.prompts[0].description, "Summarize the input");
        assert_eq!(surface.prompts[0].title, "Summarize");
        assert_eq!(surface.resources.len(), 1);
        assert_eq!(surface.resources[0].name, "config");
        assert_eq!(surface.resources[0].title, "App Config");

        let page = crate::docs::render::generate_mcp_doc(&surface, PathBuf::from("mcp.md"));
        assert!(
            page.content.contains("summarize"),
            "declared prompt must render into mcp.md"
        );
        assert!(
            page.content.contains("config"),
            "declared resource must render into mcp.md"
        );
    }

    #[test]
    fn attribute_declared_surfaces_render_identically_when_config_declares_nothing() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("mcp.rs");
        std::fs::write(
            &source,
            r#"
            struct Server;
            #[tool_router]
            impl Server {
                #[tool(description = "Do work")]
                async fn do_work(&self, Parameters(params): Parameters<crate::Params>) {}
            }
            "#,
        )
        .unwrap();
        let with_empty_config = extract_mcp_surface(std::slice::from_ref(&source), &[]).unwrap();
        let with_no_config_field = extract_mcp_surface(&[source], &Vec::new()).unwrap();
        assert_eq!(with_empty_config.tools.len(), 1);
        assert_eq!(with_empty_config.tools[0].name, "do_work");
        assert_eq!(with_empty_config.tools[0].name, with_no_config_field.tools[0].name);
        assert_eq!(
            with_empty_config.tools[0].description,
            with_no_config_field.tools[0].description
        );
        assert_eq!(with_empty_config.tools[0].title, with_no_config_field.tools[0].title);
    }

    #[test]
    fn declared_entry_duplicating_an_attribute_derived_tool_is_dropped_not_doubled() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("mcp.rs");
        std::fs::write(
            &source,
            r#"
            struct Server;
            #[tool_router]
            impl Server {
                #[tool(description = "Do work")]
                async fn do_work(&self, Parameters(params): Parameters<crate::Params>) {}
            }
            "#,
        )
        .unwrap();
        let declared = vec![DeclaredMcpItem {
            kind: DeclaredMcpKind::Tool,
            name: "do_work".to_string(),
            title: None,
            description: Some("Stale declared description".to_string()),
            params_type: None,
            annotations: BTreeMap::new(),
        }];
        let surface = extract_mcp_surface(&[source], &declared).unwrap();
        assert_eq!(
            surface.tools.len(),
            1,
            "a declared entry duplicating an attribute-derived one must not double-list it"
        );
        assert_eq!(
            surface.tools[0].description, "Do work",
            "the attribute-derived definition must win over the declared duplicate"
        );
    }

    #[test]
    fn extracts_mcp_tool_attribute() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("mcp.rs");
        std::fs::write(
            &source,
            r#"
            struct Server;
            #[tool_router]
            impl Server {
                /// Fallback docs.
                #[tool(description = "Do work", annotations(title = "Do Work", read_only_hint = true))]
                async fn do_work(&self, Parameters(params): Parameters<crate::Params>) {}
            }
            "#,
        )
        .unwrap();
        let surface = extract_mcp_surface(&[source], &[]).unwrap();
        assert_eq!(surface.tools.len(), 1);
        assert_eq!(surface.tools[0].name, "do_work");
        assert_eq!(surface.tools[0].description, "Do work");
        assert_eq!(surface.tools[0].title, "Do Work");
    }

    #[test]
    fn extracts_clap_parser_subcommands() {
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("cli.rs");
        std::fs::write(
            &source,
            r#"
            use clap::{Parser, Subcommand};
            #[derive(Parser)]
            #[command(name = "demo", about = "Demo CLI")]
            struct Cli {
                #[command(subcommand)]
                command: Commands,
            }
            #[derive(Subcommand)]
            enum Commands {
                /// Convert input.
                Convert {
                    /// Input file
                    input: String,
                    /// Output file
                    #[arg(short, long, value_name = "FILE")]
                    output: Option<String>,
                },
            }
            "#,
        )
        .unwrap();
        let surface = extract_cli_surface(&[source]).unwrap();
        assert_eq!(surface.commands[0].name, "demo");
        assert_eq!(surface.commands[0].subcommands[0].name, "convert");
        assert_eq!(
            surface.commands[0].subcommands[0].options[0].long.as_deref(),
            Some("output")
        );
        assert_eq!(surface.commands[0].subcommands[0].positionals[0].name, "input");
    }

    #[test]
    fn expands_command_flatten_in_enum_variant_commands() {
        // `#[command(flatten)]` on a struct-like enum-variant field (e.g. `extract`/`batch`
        let dir = tempfile::tempdir().unwrap();
        let source = dir.path().join("cli.rs");
        std::fs::write(
            &source,
            r#"
            use clap::{Args, Parser, Subcommand};
            #[derive(Parser)]
            #[command(name = "demo")]
            struct Cli {
                #[command(subcommand)]
                command: Commands,
            }
            #[derive(Subcommand)]
            enum Commands {
                /// Extract a document.
                Extract {
                    /// Document path.
                    path: String,
                    #[command(flatten)]
                    overrides: Overrides,
                },
            }
            #[derive(Args)]
            struct Overrides {
                /// Enable OCR.
                #[arg(long)]
                ocr: bool,
            }
            "#,
        )
        .unwrap();
        let surface = extract_cli_surface(&[source]).unwrap();
        let extract = &surface.commands[0].subcommands[0];
        assert_eq!(extract.name, "extract");
        assert!(
            extract.options.iter().any(|option| option.name == "ocr"),
            "flattened field `ocr` must be expanded inline, got options: {:?}",
            extract.options.iter().map(|option| &option.name).collect::<Vec<_>>()
        );
        assert!(
            !extract
                .options
                .iter()
                .chain(&extract.positionals)
                .any(|option| option.name == "overrides"),
            "flattened struct must not appear as an opaque `overrides` row"
        );
        assert_eq!(extract.positionals[0].name, "path");
    }
}