cratesio-mcp 0.2.1

MCP server for querying crates.io - the Rust package registry
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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
//! Format rustdoc items into LLM-readable markdown text.

use rustdoc_types::{
    AssocItemConstraint, AssocItemConstraintKind, Crate, DynTrait, Enum, Function, FunctionPointer,
    GenericArg, GenericArgs, GenericBound, GenericParamDef, GenericParamDefKind, Generics, Id,
    Item, ItemEnum, Struct, StructKind, Term, Trait, Type, VariantKind, Visibility,
};

/// Format a module listing showing grouped children with summaries.
pub fn format_module_listing(krate: &Crate, module_id: &Id) -> String {
    let module_item = match krate.index.get(module_id) {
        Some(item) => item,
        None => return "Module not found in index.".to_string(),
    };

    let children = match &module_item.inner {
        ItemEnum::Module(m) => &m.items,
        _ => return "Item is not a module.".to_string(),
    };

    let module_name = module_item.name.as_deref().unwrap_or("(root)");

    let mut output = String::new();
    output.push_str(&format!("# Module `{}`\n\n", module_name));

    if let Some(docs) = &module_item.docs {
        let summary = first_sentence(docs);
        if !summary.is_empty() {
            output.push_str(&format!("{}\n\n", summary));
        }
    }

    // Group children by kind
    let mut modules = Vec::new();
    let mut structs = Vec::new();
    let mut enums = Vec::new();
    let mut traits = Vec::new();
    let mut functions = Vec::new();
    let mut type_aliases = Vec::new();
    let mut constants = Vec::new();
    let mut macros = Vec::new();
    let mut other = Vec::new();

    for child_id in children {
        let Some(child) = krate.index.get(child_id) else {
            continue;
        };
        // Skip non-public items
        if !matches!(child.visibility, Visibility::Public) {
            continue;
        }
        match &child.inner {
            ItemEnum::Module(_) => modules.push(child),
            ItemEnum::Struct(_) => structs.push(child),
            ItemEnum::Enum(_) => enums.push(child),
            ItemEnum::Trait(_) => traits.push(child),
            ItemEnum::Function(_) => functions.push(child),
            ItemEnum::TypeAlias(_) => type_aliases.push(child),
            ItemEnum::Constant { .. } => constants.push(child),
            ItemEnum::Macro(_) | ItemEnum::ProcMacro(_) => macros.push(child),
            ItemEnum::Use(_) | ItemEnum::ExternCrate { .. } => {}
            _ => other.push(child),
        }
    }

    fn write_section(output: &mut String, heading: &str, items: &[&Item]) {
        if items.is_empty() {
            return;
        }
        output.push_str(&format!("## {}\n\n", heading));
        for item in items {
            let name = item.name.as_deref().unwrap_or("_");
            let summary = item.docs.as_deref().map(first_sentence).unwrap_or_default();
            if summary.is_empty() {
                output.push_str(&format!("- `{}`\n", name));
            } else {
                output.push_str(&format!("- `{}` -- {}\n", name, summary));
            }
        }
        output.push('\n');
    }

    write_section(&mut output, "Modules", &modules);
    write_section(&mut output, "Traits", &traits);
    write_section(&mut output, "Structs", &structs);
    write_section(&mut output, "Enums", &enums);
    write_section(&mut output, "Functions", &functions);
    write_section(&mut output, "Type Aliases", &type_aliases);
    write_section(&mut output, "Constants", &constants);
    write_section(&mut output, "Macros", &macros);
    write_section(&mut output, "Other", &other);

    output
}

/// Format full documentation for a specific item.
pub fn format_item_detail(krate: &Crate, item: &Item) -> String {
    let name = item.name.as_deref().unwrap_or("_");
    let mut output = String::new();

    match &item.inner {
        ItemEnum::Function(f) => {
            output.push_str(&format!("# Function `{}`\n\n", name));
            output.push_str("```rust\n");
            output.push_str(&format_function_signature(name, f));
            output.push_str("\n```\n\n");
        }
        ItemEnum::Struct(s) => {
            output.push_str(&format!("# Struct `{}`\n\n", name));
            output.push_str("```rust\n");
            output.push_str(&format_struct_definition(krate, name, s));
            output.push_str("\n```\n\n");
            format_struct_methods(krate, s, &mut output);
        }
        ItemEnum::Enum(e) => {
            output.push_str(&format!("# Enum `{}`\n\n", name));
            output.push_str("```rust\n");
            output.push_str(&format_enum_definition(krate, name, e));
            output.push_str("\n```\n\n");
        }
        ItemEnum::Trait(t) => {
            output.push_str(&format!("# Trait `{}`\n\n", name));
            output.push_str("```rust\n");
            output.push_str(&format_trait_definition(krate, name, t));
            output.push_str("\n```\n\n");
        }
        ItemEnum::TypeAlias(ta) => {
            output.push_str(&format!("# Type Alias `{}`\n\n", name));
            output.push_str("```rust\n");
            output.push_str(&format!(
                "type {}{} = {};\n",
                name,
                format_generics(&ta.generics),
                format_type(&ta.type_)
            ));
            output.push_str("```\n\n");
        }
        ItemEnum::Constant { type_, const_ } => {
            output.push_str(&format!("# Constant `{}`\n\n", name));
            output.push_str("```rust\n");
            output.push_str(&format!(
                "const {}: {} = {};\n",
                name,
                format_type(type_),
                const_.expr
            ));
            output.push_str("```\n\n");
        }
        ItemEnum::Macro(body) => {
            output.push_str(&format!("# Macro `{}`\n\n", name));
            output.push_str("```rust\n");
            output.push_str(body);
            output.push_str("\n```\n\n");
        }
        _ => {
            output.push_str(&format!("# `{}`\n\n", name));
        }
    }

    if let Some(docs) = &item.docs {
        // Cap at 200 lines
        let lines: Vec<&str> = docs.lines().collect();
        if lines.len() > 200 {
            for line in &lines[..200] {
                output.push_str(line);
                output.push('\n');
            }
            output.push_str("\n... (truncated)\n");
        } else {
            output.push_str(docs);
            output.push('\n');
        }
    }

    output
}

/// Format search results as a numbered list.
pub fn format_search_results(krate: &Crate, matches: &[(&Id, &Item)]) -> String {
    let mut output = String::new();

    for (i, (id, item)) in matches.iter().enumerate() {
        let name = item.name.as_deref().unwrap_or("_");
        let kind = item_kind_label(&item.inner);
        let path = item_path(krate, id);
        let summary = item.docs.as_deref().map(first_sentence).unwrap_or_default();

        output.push_str(&format!("{}. [{}] `{}`", i + 1, kind, path));
        if !summary.is_empty() {
            output.push_str(&format!(" -- {}", summary));
        }
        output.push('\n');

        // Show brief signature for functions
        if let ItemEnum::Function(f) = &item.inner {
            output.push_str(&format!(
                "   `{}`\n",
                format_function_signature(name, f).trim()
            ));
        }
    }

    output
}

/// Reconstruct the fully qualified path for an item.
pub fn item_path(krate: &Crate, id: &Id) -> String {
    if let Some(summary) = krate.paths.get(id) {
        summary.path.join("::")
    } else if let Some(item) = krate.index.get(id) {
        item.name.clone().unwrap_or_else(|| "_".to_string())
    } else {
        "_".to_string()
    }
}

/// Resolve an item path string (e.g. "de::from_str") against the crate index.
///
/// Walks from the root module, splitting on `::`.
pub fn resolve_item_path<'a>(krate: &'a Crate, path: &str) -> Option<&'a Item> {
    let segments: Vec<&str> = path.split("::").collect();

    // Strategy 1: Walk from root module through nested modules
    if let Some(item) = walk_modules(krate, &krate.root, &segments) {
        return Some(item);
    }

    // Strategy 2: Search by name match on the last segment, then verify path
    let target = segments.last()?;
    for item in krate.index.values() {
        if item.crate_id != 0 {
            continue;
        }
        if item.name.as_deref() == Some(target) {
            if segments.len() == 1 {
                return Some(item);
            }
            // Verify the path matches
            if let Some(summary) = krate.paths.get(&item.id) {
                let item_path: Vec<&str> = summary.path.iter().map(|s| s.as_str()).collect();
                if item_path.ends_with(&segments) {
                    return Some(item);
                }
            }
        }
    }

    None
}

/// Walk through nested modules to find an item.
fn walk_modules<'a>(krate: &'a Crate, module_id: &Id, segments: &[&str]) -> Option<&'a Item> {
    if segments.is_empty() {
        return krate.index.get(module_id);
    }

    let module_item = krate.index.get(module_id)?;
    let children = match &module_item.inner {
        ItemEnum::Module(m) => &m.items,
        _ => return None,
    };

    let target = segments[0];
    for child_id in children {
        let child = krate.index.get(child_id)?;
        if child.name.as_deref() == Some(target) {
            if segments.len() == 1 {
                return Some(child);
            }
            // Try to descend into this as a module
            if matches!(child.inner, ItemEnum::Module(_))
                && let Some(found) = walk_modules(krate, child_id, &segments[1..])
            {
                return Some(found);
            }
        }
    }

    None
}

/// Resolve a module path (e.g. "de" or "de::value") to a module Id.
pub fn resolve_module_path(krate: &Crate, path: &str) -> Option<Id> {
    let segments: Vec<&str> = path.split("::").collect();
    let mut current_id = krate.root;

    for segment in &segments {
        let module_item = krate.index.get(&current_id)?;
        let children = match &module_item.inner {
            ItemEnum::Module(m) => &m.items,
            _ => return None,
        };

        let mut found = false;
        for child_id in children {
            if let Some(child) = krate.index.get(child_id)
                && child.name.as_deref() == Some(segment)
                && matches!(child.inner, ItemEnum::Module(_))
            {
                current_id = *child_id;
                found = true;
                break;
            }
        }
        if !found {
            return None;
        }
    }

    Some(current_id)
}

// ── Type formatting ────────────────────────────────────────────────────

/// Render a `Type` to a human-readable string.
pub fn format_type(ty: &Type) -> String {
    match ty {
        Type::Primitive(name) => name.clone(),
        Type::Generic(name) => name.clone(),
        Type::ResolvedPath(path) => {
            let mut s = path.path.clone();
            if let Some(args) = &path.args {
                s.push_str(&format_generic_args(args));
            }
            s
        }
        Type::BorrowedRef {
            lifetime,
            is_mutable,
            type_,
        } => {
            let mut s = String::from("&");
            if let Some(lt) = lifetime {
                s.push_str(lt);
                s.push(' ');
            }
            if *is_mutable {
                s.push_str("mut ");
            }
            s.push_str(&format_type(type_));
            s
        }
        Type::Tuple(types) => {
            if types.is_empty() {
                "()".to_string()
            } else {
                let inner: Vec<String> = types.iter().map(format_type).collect();
                format!("({})", inner.join(", "))
            }
        }
        Type::Slice(ty) => format!("[{}]", format_type(ty)),
        Type::Array { type_, len } => format!("[{}; {}]", format_type(type_), len),
        Type::RawPointer { is_mutable, type_ } => {
            if *is_mutable {
                format!("*mut {}", format_type(type_))
            } else {
                format!("*const {}", format_type(type_))
            }
        }
        Type::ImplTrait(bounds) => format!("impl {}", format_bounds(bounds)),
        Type::DynTrait(dyn_trait) => format_dyn_trait(dyn_trait),
        Type::FunctionPointer(fp) => format_fn_pointer(fp),
        Type::QualifiedPath {
            name,
            self_type,
            trait_,
            ..
        } => {
            if let Some(t) = trait_ {
                format!("<{} as {}>::{}", format_type(self_type), t.path, name)
            } else {
                format!("<{}>::{}", format_type(self_type), name)
            }
        }
        Type::Infer => "_".to_string(),
        Type::Pat { type_, .. } => format_type(type_),
    }
}

fn format_generic_args(args: &GenericArgs) -> String {
    match args {
        GenericArgs::AngleBracketed {
            args, constraints, ..
        } => {
            let mut parts: Vec<String> = args.iter().map(format_generic_arg).collect();
            for c in constraints {
                parts.push(format_assoc_constraint(c));
            }
            if parts.is_empty() {
                String::new()
            } else {
                format!("<{}>", parts.join(", "))
            }
        }
        GenericArgs::Parenthesized { inputs, output } => {
            let input_str: Vec<String> = inputs.iter().map(format_type).collect();
            let mut s = format!("({})", input_str.join(", "));
            if let Some(out) = output {
                s.push_str(&format!(" -> {}", format_type(out)));
            }
            s
        }
        GenericArgs::ReturnTypeNotation => "(..)".to_string(),
    }
}

fn format_generic_arg(arg: &GenericArg) -> String {
    match arg {
        GenericArg::Lifetime(lt) => lt.clone(),
        GenericArg::Type(ty) => format_type(ty),
        GenericArg::Const(c) => c.expr.clone(),
        GenericArg::Infer => "_".to_string(),
    }
}

fn format_assoc_constraint(c: &AssocItemConstraint) -> String {
    match &c.binding {
        AssocItemConstraintKind::Equality(term) => {
            let val = match term {
                Term::Type(ty) => format_type(ty),
                Term::Constant(c) => c.expr.clone(),
            };
            format!("{} = {}", c.name, val)
        }
        AssocItemConstraintKind::Constraint(bounds) => {
            format!("{}: {}", c.name, format_bounds(bounds))
        }
    }
}

fn format_bounds(bounds: &[GenericBound]) -> String {
    let parts: Vec<String> = bounds
        .iter()
        .map(|b| match b {
            GenericBound::TraitBound { trait_, .. } => {
                let mut s = trait_.path.clone();
                if let Some(args) = &trait_.args {
                    s.push_str(&format_generic_args(args));
                }
                s
            }
            GenericBound::Outlives(lt) => lt.clone(),
            GenericBound::Use(_) => "use<..>".to_string(),
        })
        .collect();
    parts.join(" + ")
}

fn format_dyn_trait(dt: &DynTrait) -> String {
    let mut parts: Vec<String> = dt
        .traits
        .iter()
        .map(|pt| {
            let mut s = pt.trait_.path.clone();
            if let Some(args) = &pt.trait_.args {
                s.push_str(&format_generic_args(args));
            }
            s
        })
        .collect();
    if let Some(lt) = &dt.lifetime {
        parts.push(lt.clone());
    }
    format!("dyn {}", parts.join(" + "))
}

fn format_fn_pointer(fp: &FunctionPointer) -> String {
    let inputs: Vec<String> = fp
        .sig
        .inputs
        .iter()
        .map(|(_, ty)| format_type(ty))
        .collect();
    let mut s = format!("fn({})", inputs.join(", "));
    if let Some(out) = &fp.sig.output {
        s.push_str(&format!(" -> {}", format_type(out)));
    }
    s
}

// ── Signature formatting ───────────────────────────────────────────────

fn format_function_signature(name: &str, f: &Function) -> String {
    let mut s = String::new();
    if f.header.is_const {
        s.push_str("const ");
    }
    if f.header.is_async {
        s.push_str("async ");
    }
    if f.header.is_unsafe {
        s.push_str("unsafe ");
    }
    s.push_str("fn ");
    s.push_str(name);
    s.push_str(&format_generics(&f.generics));
    s.push('(');
    let params: Vec<String> = f
        .sig
        .inputs
        .iter()
        .map(|(param_name, ty)| format!("{}: {}", param_name, format_type(ty)))
        .collect();
    s.push_str(&params.join(", "));
    s.push(')');
    if let Some(ret) = &f.sig.output {
        s.push_str(&format!(" -> {}", format_type(ret)));
    }
    s.push_str(&format_where_clause(&f.generics));
    s
}

fn format_generics(g: &Generics) -> String {
    if g.params.is_empty() {
        return String::new();
    }
    let params: Vec<String> = g
        .params
        .iter()
        .filter(|p| {
            !matches!(
                p.kind,
                GenericParamDefKind::Type {
                    is_synthetic: true,
                    ..
                }
            )
        })
        .map(format_generic_param)
        .collect();
    if params.is_empty() {
        String::new()
    } else {
        format!("<{}>", params.join(", "))
    }
}

fn format_generic_param(p: &GenericParamDef) -> String {
    match &p.kind {
        GenericParamDefKind::Lifetime { .. } => p.name.clone(),
        GenericParamDefKind::Type {
            bounds, default, ..
        } => {
            let mut s = p.name.clone();
            if !bounds.is_empty() {
                s.push_str(&format!(": {}", format_bounds(bounds)));
            }
            if let Some(def) = default {
                s.push_str(&format!(" = {}", format_type(def)));
            }
            s
        }
        GenericParamDefKind::Const { type_, default } => {
            let mut s = format!("const {}: {}", p.name, format_type(type_));
            if let Some(def) = default {
                s.push_str(&format!(" = {}", def));
            }
            s
        }
    }
}

fn format_where_clause(g: &Generics) -> String {
    if g.where_predicates.is_empty() {
        return String::new();
    }
    let preds: Vec<String> = g
        .where_predicates
        .iter()
        .map(|wp| match wp {
            rustdoc_types::WherePredicate::BoundPredicate { type_, bounds, .. } => {
                format!("{}: {}", format_type(type_), format_bounds(bounds))
            }
            rustdoc_types::WherePredicate::LifetimePredicate {
                lifetime, outlives, ..
            } => {
                format!("{}: {}", lifetime, outlives.join(" + "))
            }
            rustdoc_types::WherePredicate::EqPredicate { lhs, rhs } => {
                let rhs_str = match rhs {
                    Term::Type(ty) => format_type(ty),
                    Term::Constant(c) => c.expr.clone(),
                };
                format!("{} = {}", format_type(lhs), rhs_str)
            }
        })
        .collect();
    format!("\nwhere\n    {}", preds.join(",\n    "))
}

fn format_struct_definition(krate: &Crate, name: &str, s: &Struct) -> String {
    let mut out = format!("struct {}{}", name, format_generics(&s.generics));
    match &s.kind {
        StructKind::Unit => {
            out.push(';');
        }
        StructKind::Tuple(fields) => {
            out.push('(');
            let field_strs: Vec<String> = fields
                .iter()
                .map(|f| {
                    f.as_ref()
                        .and_then(|id| krate.index.get(id))
                        .map(|item| match &item.inner {
                            ItemEnum::StructField(ty) => format_type(ty),
                            _ => "_".to_string(),
                        })
                        .unwrap_or_else(|| "/* private */".to_string())
                })
                .collect();
            out.push_str(&field_strs.join(", "));
            out.push_str(");");
        }
        StructKind::Plain { fields, .. } => {
            out.push_str(&format_where_clause(&s.generics));
            out.push_str(" {\n");
            for field_id in fields {
                if let Some(field) = krate.index.get(field_id) {
                    let field_name = field.name.as_deref().unwrap_or("_");
                    if let ItemEnum::StructField(ty) = &field.inner {
                        out.push_str(&format!("    pub {}: {},\n", field_name, format_type(ty)));
                    }
                }
            }
            out.push('}');
        }
    }
    out
}

fn format_struct_methods(krate: &Crate, s: &Struct, output: &mut String) {
    // Find inherent impls
    let mut methods: Vec<(&str, String)> = Vec::new();
    for impl_id in &s.impls {
        let Some(impl_item) = krate.index.get(impl_id) else {
            continue;
        };
        let ItemEnum::Impl(imp) = &impl_item.inner else {
            continue;
        };
        // Only inherent impls (no trait)
        if imp.trait_.is_some() {
            continue;
        }
        for method_id in &imp.items {
            let Some(method) = krate.index.get(method_id) else {
                continue;
            };
            if !matches!(method.visibility, Visibility::Public) {
                continue;
            }
            let name = method.name.as_deref().unwrap_or("_");
            if let ItemEnum::Function(f) = &method.inner {
                let sig = format_function_signature(name, f);
                methods.push((name, sig));
            }
        }
    }

    if !methods.is_empty() {
        output.push_str("## Methods\n\n");
        for (name, sig) in &methods {
            output.push_str(&format!("- `{}`\n  ```rust\n  {}\n  ```\n", name, sig));
        }
        output.push('\n');
    }
}

fn format_enum_definition(krate: &Crate, name: &str, e: &Enum) -> String {
    let mut out = format!("enum {}{}", name, format_generics(&e.generics));
    out.push_str(&format_where_clause(&e.generics));
    out.push_str(" {\n");
    for variant_id in &e.variants {
        if let Some(variant_item) = krate.index.get(variant_id) {
            let vname = variant_item.name.as_deref().unwrap_or("_");
            if let ItemEnum::Variant(v) = &variant_item.inner {
                out.push_str(&format!("    {}", vname));
                match &v.kind {
                    VariantKind::Plain => {}
                    VariantKind::Tuple(fields) => {
                        out.push('(');
                        let field_strs: Vec<String> = fields
                            .iter()
                            .map(|f| {
                                f.as_ref()
                                    .and_then(|id| krate.index.get(id))
                                    .map(|item| match &item.inner {
                                        ItemEnum::StructField(ty) => format_type(ty),
                                        _ => "_".to_string(),
                                    })
                                    .unwrap_or_else(|| "/* private */".to_string())
                            })
                            .collect();
                        out.push_str(&field_strs.join(", "));
                        out.push(')');
                    }
                    VariantKind::Struct { fields, .. } => {
                        out.push_str(" {\n");
                        for field_id in fields {
                            if let Some(field) = krate.index.get(field_id) {
                                let fname = field.name.as_deref().unwrap_or("_");
                                if let ItemEnum::StructField(ty) = &field.inner {
                                    out.push_str(&format!(
                                        "        {}: {},\n",
                                        fname,
                                        format_type(ty)
                                    ));
                                }
                            }
                        }
                        out.push_str("    }");
                    }
                }
                out.push_str(",\n");
            }
        }
    }
    out.push('}');
    out
}

fn format_trait_definition(krate: &Crate, name: &str, t: &Trait) -> String {
    let mut out = String::new();
    if t.is_unsafe {
        out.push_str("unsafe ");
    }
    out.push_str(&format!("trait {}{}", name, format_generics(&t.generics)));
    if !t.bounds.is_empty() {
        out.push_str(&format!(": {}", format_bounds(&t.bounds)));
    }
    out.push_str(&format_where_clause(&t.generics));
    out.push_str(" {\n");
    for item_id in &t.items {
        if let Some(item) = krate.index.get(item_id) {
            let iname = item.name.as_deref().unwrap_or("_");
            match &item.inner {
                ItemEnum::Function(f) => {
                    let sig = format_function_signature(iname, f);
                    if f.has_body {
                        out.push_str(&format!("    {} {{ ... }}\n", sig));
                    } else {
                        out.push_str(&format!("    {};\n", sig));
                    }
                }
                ItemEnum::AssocType {
                    bounds,
                    type_: default,
                    ..
                } => {
                    out.push_str(&format!("    type {}", iname));
                    if !bounds.is_empty() {
                        out.push_str(&format!(": {}", format_bounds(bounds)));
                    }
                    if let Some(def) = default {
                        out.push_str(&format!(" = {}", format_type(def)));
                    }
                    out.push_str(";\n");
                }
                ItemEnum::AssocConst { type_, .. } => {
                    out.push_str(&format!("    const {}: {};\n", iname, format_type(type_)));
                }
                _ => {}
            }
        }
    }
    out.push('}');
    out
}

// ── Helpers ────────────────────────────────────────────────────────────

fn item_kind_label(inner: &ItemEnum) -> &'static str {
    match inner {
        ItemEnum::Module(_) => "mod",
        ItemEnum::Function(_) => "fn",
        ItemEnum::Struct(_) => "struct",
        ItemEnum::Enum(_) => "enum",
        ItemEnum::Trait(_) => "trait",
        ItemEnum::TypeAlias(_) => "type",
        ItemEnum::Constant { .. } => "const",
        ItemEnum::Macro(_) => "macro",
        ItemEnum::ProcMacro(_) => "proc_macro",
        ItemEnum::Union(_) => "union",
        ItemEnum::Static(_) => "static",
        ItemEnum::Variant(_) => "variant",
        ItemEnum::StructField(_) => "field",
        ItemEnum::Impl(_) => "impl",
        ItemEnum::Use(_) => "use",
        ItemEnum::ExternCrate { .. } => "extern_crate",
        ItemEnum::TraitAlias(_) => "trait_alias",
        ItemEnum::ExternType => "extern_type",
        ItemEnum::AssocConst { .. } => "assoc_const",
        ItemEnum::AssocType { .. } => "assoc_type",
        ItemEnum::Primitive(_) => "primitive",
    }
}

/// Extract the first sentence from a doc string.
fn first_sentence(docs: &str) -> String {
    let first_line = docs.lines().next().unwrap_or("");
    // Truncate at first period followed by space or end
    if let Some(pos) = first_line.find(". ") {
        first_line[..=pos].to_string()
    } else {
        first_line.to_string()
    }
}

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

    #[test]
    fn first_sentence_extracts_correctly() {
        assert_eq!(first_sentence("Hello world. More text."), "Hello world.");
        assert_eq!(first_sentence("Single line"), "Single line");
        assert_eq!(first_sentence("Ends with period."), "Ends with period.");
        assert_eq!(first_sentence("Line one.\nLine two."), "Line one.");
    }

    #[test]
    fn format_primitive_type() {
        assert_eq!(format_type(&Type::Primitive("i32".to_string())), "i32");
    }

    #[test]
    fn format_generic_type() {
        assert_eq!(format_type(&Type::Generic("T".to_string())), "T");
    }

    #[test]
    fn format_borrowed_ref() {
        let ty = Type::BorrowedRef {
            lifetime: Some("'a".to_string()),
            is_mutable: true,
            type_: Box::new(Type::Primitive("str".to_string())),
        };
        assert_eq!(format_type(&ty), "&'a mut str");
    }

    #[test]
    fn format_tuple_type() {
        let ty = Type::Tuple(vec![
            Type::Primitive("i32".to_string()),
            Type::Primitive("bool".to_string()),
        ]);
        assert_eq!(format_type(&ty), "(i32, bool)");
    }

    #[test]
    fn format_unit_type() {
        assert_eq!(format_type(&Type::Tuple(vec![])), "()");
    }

    #[test]
    fn format_slice_type() {
        let ty = Type::Slice(Box::new(Type::Primitive("u8".to_string())));
        assert_eq!(format_type(&ty), "[u8]");
    }

    #[test]
    fn format_array_type() {
        let ty = Type::Array {
            type_: Box::new(Type::Primitive("u8".to_string())),
            len: "32".to_string(),
        };
        assert_eq!(format_type(&ty), "[u8; 32]");
    }

    #[test]
    fn format_raw_pointer() {
        let ty = Type::RawPointer {
            is_mutable: false,
            type_: Box::new(Type::Primitive("u8".to_string())),
        };
        assert_eq!(format_type(&ty), "*const u8");
    }

    #[test]
    fn item_kind_labels() {
        assert_eq!(
            item_kind_label(&ItemEnum::Module(Module {
                items: vec![],
                is_stripped: false,
                is_crate: false,
            })),
            "mod"
        );
    }

    // ── Helpers for building synthetic items and crates ───────────────────
    //
    // We construct a `Crate` from inline JSON (the same pattern used in
    // `src/docs/cache.rs` and `tests/mcp_integration.rs`). Building each
    // `Item` from JSON keeps the tests robust against `rustdoc_types`
    // adding new struct fields with serde defaults.

    /// Build JSON for an `Item` with the given id, name, docs, and inner.
    fn item_json(
        id: u32,
        name: &str,
        docs: Option<&str>,
        inner: serde_json::Value,
    ) -> serde_json::Value {
        serde_json::json!({
            "id": id,
            "crate_id": 0,
            "name": name,
            "span": null,
            "visibility": "public",
            "docs": docs,
            "links": {},
            "attrs": [],
            "deprecation": null,
            "inner": inner,
        })
    }

    /// Build JSON for a no-argument, unit-returning function inner.
    fn function_inner() -> serde_json::Value {
        serde_json::json!({
            "function": {
                "sig": { "inputs": [], "output": null, "is_c_variadic": false },
                "generics": { "params": [], "where_predicates": [] },
                "header": {
                    "is_const": false,
                    "is_unsafe": false,
                    "is_async": false,
                    "abi": "Rust"
                },
                "has_body": true
            }
        })
    }

    /// Build JSON for a unit-struct inner.
    fn struct_inner() -> serde_json::Value {
        serde_json::json!({
            "struct": {
                "kind": "unit",
                "generics": { "params": [], "where_predicates": [] },
                "impls": []
            }
        })
    }

    /// Build a `Crate` from a root module plus a set of item JSON values.
    fn synthetic_crate(root_children: &[u32], items: Vec<serde_json::Value>) -> Crate {
        let mut index = serde_json::Map::new();

        // Root module (id 0) holding the listed children.
        index.insert(
            "0".to_string(),
            item_json(
                0,
                "root_mod",
                Some("Root module docs. Extra detail."),
                serde_json::json!({
                    "module": {
                        "is_crate": true,
                        "items": root_children,
                        "is_stripped": false
                    }
                }),
            ),
        );

        for item in items {
            let id = item.get("id").and_then(|v| v.as_u64()).unwrap();
            index.insert(id.to_string(), item);
        }

        let json = serde_json::json!({
            "root": 0,
            "crate_version": "1.0.0",
            "includes_private": false,
            "index": index,
            "paths": {},
            "external_crates": {},
            "target": {
                "triple": "x86_64-unknown-linux-gnu",
                "target_features": []
            },
            "format_version": rustdoc_types::FORMAT_VERSION
        });
        serde_json::from_value(json).expect("synthetic crate should deserialize")
    }

    #[test]
    fn format_module_listing_groups_items() {
        let krate = synthetic_crate(
            &[1, 2],
            vec![
                item_json(1, "do_thing", Some("Does a thing. More."), function_inner()),
                item_json(2, "Widget", Some("A widget."), struct_inner()),
            ],
        );

        let out = format_module_listing(&krate, &Id(0));

        // Module heading and summary (first sentence only).
        assert!(out.contains("# Module `root_mod`"));
        assert!(out.contains("Root module docs."));
        // Section headings for the two kinds present.
        assert!(out.contains("## Functions"));
        assert!(out.contains("## Structs"));
        // Item names with their summaries.
        assert!(out.contains("`do_thing` -- Does a thing."));
        assert!(out.contains("`Widget` -- A widget."));
        // No section for kinds that are absent.
        assert!(!out.contains("## Enums"));
        assert!(!out.contains("## Traits"));
    }

    #[test]
    fn format_module_listing_empty_index() {
        // An empty index means the root id is not present.
        let json = serde_json::json!({
            "root": 0,
            "crate_version": "1.0.0",
            "includes_private": false,
            "index": {},
            "paths": {},
            "external_crates": {},
            "target": {
                "triple": "x86_64-unknown-linux-gnu",
                "target_features": []
            },
            "format_version": rustdoc_types::FORMAT_VERSION
        });
        let krate: Crate = serde_json::from_value(json).unwrap();

        let out = format_module_listing(&krate, &Id(0));
        assert!(!out.is_empty());
        assert_eq!(out, "Module not found in index.");
    }

    #[test]
    fn format_module_listing_empty_module() {
        // Root module present but with no children: graceful, non-empty output.
        let krate = synthetic_crate(&[], vec![]);
        let out = format_module_listing(&krate, &Id(0));
        assert!(!out.is_empty());
        assert!(out.contains("# Module `root_mod`"));
        // With no children, no kind sections are emitted.
        assert!(!out.contains("## Functions"));
        assert!(!out.contains("## Structs"));
    }

    #[test]
    fn format_module_listing_not_a_module() {
        // Pointing the listing at a non-module item yields the guard message.
        let krate = synthetic_crate(&[1], vec![item_json(1, "do_thing", None, function_inner())]);
        let out = format_module_listing(&krate, &Id(1));
        assert_eq!(out, "Item is not a module.");
    }

    #[test]
    fn item_kind_labels_cover_common_variants() {
        assert_eq!(
            item_kind_label(&ItemEnum::Struct(Struct {
                kind: StructKind::Unit,
                generics: Generics {
                    params: vec![],
                    where_predicates: vec![],
                },
                impls: vec![],
            })),
            "struct"
        );
        assert_eq!(
            item_kind_label(&ItemEnum::Enum(Enum {
                generics: Generics {
                    params: vec![],
                    where_predicates: vec![],
                },
                has_stripped_variants: false,
                variants: vec![],
                impls: vec![],
            })),
            "enum"
        );
        assert_eq!(
            item_kind_label(&ItemEnum::Function(Function {
                sig: FunctionSignature {
                    inputs: vec![],
                    output: None,
                    is_c_variadic: false,
                },
                generics: Generics {
                    params: vec![],
                    where_predicates: vec![],
                },
                header: FunctionHeader {
                    is_const: false,
                    is_unsafe: false,
                    is_async: false,
                    abi: Abi::Rust,
                },
                has_body: true,
            })),
            "fn"
        );
        assert_eq!(
            item_kind_label(&ItemEnum::Trait(Trait {
                is_auto: false,
                is_unsafe: false,
                is_dyn_compatible: true,
                items: vec![],
                generics: Generics {
                    params: vec![],
                    where_predicates: vec![],
                },
                bounds: vec![],
                implementations: vec![],
            })),
            "trait"
        );
        assert_eq!(
            item_kind_label(&ItemEnum::Constant {
                type_: Type::Primitive("u32".to_string()),
                const_: Constant {
                    expr: "1".to_string(),
                    value: Some("1".to_string()),
                    is_literal: true,
                },
            }),
            "const"
        );
        assert_eq!(
            item_kind_label(&ItemEnum::TypeAlias(TypeAlias {
                type_: Type::Primitive("u32".to_string()),
                generics: Generics {
                    params: vec![],
                    where_predicates: vec![],
                },
            })),
            "type"
        );
    }

    #[test]
    fn format_item_detail_function_with_docs() {
        let krate = synthetic_crate(&[1], vec![]);
        let item: Item = serde_json::from_value(item_json(
            1,
            "compute",
            Some("Computes a value.\n\nLonger description here."),
            function_inner(),
        ))
        .unwrap();

        let out = format_item_detail(&krate, &item);

        // Header for the function kind.
        assert!(out.contains("# Function `compute`"));
        // Rendered signature in a code block.
        assert!(out.contains("```rust"));
        assert!(out.contains("fn compute()"));
        // Full docs are appended (not just the first sentence).
        assert!(out.contains("Computes a value."));
        assert!(out.contains("Longer description here."));
    }

    #[test]
    fn format_item_detail_struct_renders_definition() {
        let krate = synthetic_crate(&[1], vec![]);
        let item: Item =
            serde_json::from_value(item_json(1, "Widget", Some("A widget."), struct_inner()))
                .unwrap();

        let out = format_item_detail(&krate, &item);

        assert!(out.contains("# Struct `Widget`"));
        // Unit struct renders as `struct Widget;`.
        assert!(out.contains("struct Widget;"));
        assert!(out.contains("A widget."));
    }
}