pmcp 2.9.0

High-quality Rust SDK for Model Context Protocol (MCP) with full TypeScript SDK compatibility
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
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
//! SEP-2640 Agent Skills — `ResourceHandler`-served skill resources with
//! a parallel `PromptHandler` fallback for SEP-2640-blind hosts.
//!
//! Both surfaces are derived from one [`Skill`] value: the SKILL.md
//! content + each reference body is byte-equal whether the host fetches
//! via [`crate::server::ResourceHandler::list`]/[`crate::server::ResourceHandler::read`]
//! (SEP-2640) or via [`crate::server::PromptHandler::handle`] (legacy).
//!
//! Internal storage uses [`indexmap::IndexMap`] so resource ordering is
//! deterministic across runs — required for stable example output,
//! snapshot tests, and predictable host UX.
//!
//! Wire shape: reads return [`crate::types::Content::resource_with_text`]
//! (NOT [`crate::types::Content::text`]) so per-resource MIME types survive
//! the wire round-trip — reference files like `schema.graphql` keep their
//! `application/graphql` MIME type.
//!
//! Byte-equal mirror of the doctest at the end of `pmcp-book/src/ch12-8-skills.md`.
//!
//! ```rust,no_run
//! use pmcp::server::skills::Skill;
//!
//! fn main() -> Result<(), Box<dyn std::error::Error>> {
//!     let greeting = Skill::new("hello-world", "# Hello\nThis is a minimal skill.\n");
//!     let prompt_text = greeting.as_prompt_text();
//!     assert!(prompt_text.starts_with("# Hello"));
//!
//!     let _server = pmcp::Server::builder()
//!         .name("doctest-skills-demo")
//!         .version("0.1.0")
//!         .bootstrap_skill_and_prompt(greeting, "hello_prompt")
//!         .build()?;
//!     Ok(())
//! }
//! ```

use std::collections::HashMap;
use std::sync::Arc;

use async_trait::async_trait;
use indexmap::IndexMap;
use serde_json::json;

use crate::error::{Error, ErrorCode, Result};
use crate::server::cancellation::RequestHandlerExtra;
use crate::server::{PromptHandler, ResourceHandler};
use crate::types::content::Role;
use crate::types::{
    Content, GetPromptResult, ListResourcesResult, PromptMessage, ReadResourceResult, ResourceInfo,
};

/// Reverse-domain key under `ServerCapabilities.extensions` advertising
/// SEP-2640 skill support. Set automatically when any skill is registered.
pub(crate) const SKILLS_EXTENSION_KEY: &str = "io.modelcontextprotocol/skills";

/// Synthesized discovery-index URI; emitted in `resources/list` and
/// served from `resources/read`.
const SKILL_INDEX_URI: &str = "skill://index.json";
const SKILL_MD_MIME: &str = "text/markdown";
const INDEX_JSON_MIME: &str = "application/json";

/// Flip `ServerCapabilities` to advertise skills support. Called from
/// every builder method that accepts a skill or skill registry — keeping
/// the four call sites in sync via one function instead of inline copies.
pub(crate) fn set_skills_capabilities(caps: &mut crate::types::ServerCapabilities) {
    if caps.resources.is_none() {
        caps.resources = Some(crate::types::ResourceCapabilities {
            subscribe: Some(false),
            list_changed: Some(false),
        });
    }
    caps.extensions
        .get_or_insert_with(HashMap::new)
        .entry(SKILLS_EXTENSION_KEY.to_string())
        .or_insert_with(|| json!({}));
}

// ── Public types ──────────────────────────────────────────────────────

/// A supporting file within a skill's directory (SEP-2640 §4 directory model).
///
/// Carries the relative path (e.g. `references/schema.graphql`), the
/// per-resource MIME type, and the body. Validation against duplicate or
/// invalid paths happens at [`Skill::with_reference`] /
/// [`Skill::try_with_reference`] time so that the parent skill's existing
/// references can be consulted.
///
/// # Examples
///
/// ```rust
/// use pmcp::server::skills::SkillReference;
///
/// let r = SkillReference::new("references/api.md", "text/markdown", "...");
/// assert_eq!(r.relative_path(), "references/api.md");
/// assert_eq!(r.mime_type(), "text/markdown");
/// ```
#[derive(Clone, Debug)]
pub struct SkillReference {
    relative_path: String,
    mime_type: String,
    body: String,
}

impl SkillReference {
    /// Construct a reference. Validation happens at
    /// [`Skill::with_reference`] / [`Skill::try_with_reference`] time so
    /// duplicate-within-skill checks can use the parent's reference set.
    pub fn new(
        relative_path: impl Into<String>,
        mime_type: impl Into<String>,
        body: impl Into<String>,
    ) -> Self {
        Self {
            relative_path: relative_path.into(),
            mime_type: mime_type.into(),
            body: body.into(),
        }
    }

    /// Relative path within the skill's directory (e.g.
    /// `references/schema.graphql`).
    pub fn relative_path(&self) -> &str {
        &self.relative_path
    }

    /// Per-resource MIME type (e.g. `application/graphql`).
    pub fn mime_type(&self) -> &str {
        &self.mime_type
    }

    /// Reference body text.
    pub fn body(&self) -> &str {
        &self.body
    }
}

/// A single Agent Skill (SEP-2640).
///
/// `name` is required (derived from SKILL.md frontmatter); `body` is the
/// SKILL.md content with YAML frontmatter intact. Optional `path` overrides
/// the default `skill://<name>/SKILL.md` URI. Optional `references` carry
/// supporting files (`schema.graphql`, `examples.md`, etc.) addressable at
/// `skill://<path>/<relative_path>`.
///
/// # Examples
///
/// ```rust
/// use pmcp::server::skills::{Skill, SkillReference};
///
/// let s = Skill::new("refunds", "---\nname: refunds\ndescription: Issue refunds\n---\nBody")
///     .with_reference(SkillReference::new("references/policy.md", "text/markdown", "..."));
/// assert_eq!(s.name(), "refunds");
/// assert_eq!(s.resolved_description(), "Issue refunds");
/// ```
#[derive(Clone, Debug)]
pub struct Skill {
    name: String,
    body: String,
    path: Option<String>,
    description: String,
    references: Vec<SkillReference>,
}

impl Skill {
    /// Create a skill from its frontmatter `name` and full SKILL.md body.
    ///
    /// The `description:` frontmatter line is parsed eagerly so per-skill
    /// metadata reads (e.g. `resources/list`, the discovery index) avoid
    /// re-scanning the body on every request.
    pub fn new(name: impl Into<String>, body: impl Into<String>) -> Self {
        let body = body.into();
        let description = parse_frontmatter_description(&body).unwrap_or_default();
        Self {
            name: name.into(),
            body,
            path: None,
            description,
            references: Vec::new(),
        }
    }

    /// Override the URI path (default: `skill://<name>/SKILL.md`).
    #[must_use]
    pub fn with_path(mut self, path: impl Into<String>) -> Self {
        self.path = Some(path.into());
        self
    }

    /// Explicit description override (otherwise the frontmatter
    /// `description:` line is used).
    #[must_use]
    pub fn with_description(mut self, description: impl Into<String>) -> Self {
        self.description = description.into();
        self
    }

    /// Append a reference. **Panics** on invalid `relative_path` — use
    /// [`Self::try_with_reference`] for fallible registration.
    ///
    /// Invalid inputs: empty, contains a null byte, exactly `"SKILL.md"`
    /// (collides with the canonical URI), contains a `..` segment, starts
    /// with `/`, contains `://`, or duplicates a `relative_path` already
    /// registered on this Skill.
    ///
    /// # Panics
    ///
    /// Panics if the reference's relative path violates any of the rules
    /// listed above. Use [`Self::try_with_reference`] to surface the same
    /// failures as `Result`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pmcp::server::skills::{Skill, SkillReference};
    ///
    /// let s = Skill::new("x", "body")
    ///     .with_reference(SkillReference::new("references/a.md", "text/markdown", "a"));
    /// assert_eq!(s.references().count(), 1);
    /// ```
    #[must_use]
    pub fn with_reference(self, reference: SkillReference) -> Self {
        match self.try_with_reference(reference) {
            Ok(s) => s,
            Err(e) => panic!("Skill::with_reference: {e}"),
        }
    }

    /// Append a reference, returning `Err` on invalid input — the fallible
    /// counterpart to [`Self::with_reference`] for runtime-dynamic
    /// registration where panicking is unacceptable.
    ///
    /// # Errors
    ///
    /// Returns `Err(pmcp::Error::Validation)` if the relative path is
    /// empty, contains a null byte, exactly `"SKILL.md"`, contains a `..`
    /// segment, starts with `/`, contains `://`, or duplicates an existing
    /// relative path on this skill.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pmcp::server::skills::{Skill, SkillReference};
    ///
    /// let ok = Skill::new("x", "body")
    ///     .try_with_reference(SkillReference::new("references/a.md", "text/markdown", "a"));
    /// assert!(ok.is_ok());
    ///
    /// let bad = Skill::new("x", "body")
    ///     .try_with_reference(SkillReference::new("", "text/markdown", "a"));
    /// assert!(bad.is_err());
    /// ```
    pub fn try_with_reference(mut self, reference: SkillReference) -> Result<Self> {
        validate_reference_path(&reference.relative_path, &self.references)?;
        self.references.push(reference);
        Ok(self)
    }

    /// Skill name (from frontmatter).
    pub fn name(&self) -> &str {
        &self.name
    }

    /// Full SKILL.md body (frontmatter + recipe).
    pub fn body(&self) -> &str {
        &self.body
    }

    /// Iterate over registered references in insertion order.
    pub fn references(&self) -> impl Iterator<Item = &SkillReference> {
        self.references.iter()
    }

    /// Resolved description: explicit [`Self::with_description`] override
    /// if set, otherwise the `description:` line parsed from the SKILL.md
    /// frontmatter at construction time. Returns `""` if neither is set.
    pub fn resolved_description(&self) -> &str {
        &self.description
    }

    pub(crate) fn resolved_path(&self) -> &str {
        self.path.as_deref().unwrap_or(&self.name)
    }

    pub(crate) fn skill_md_uri(&self) -> String {
        format!("skill://{}/SKILL.md", self.resolved_path())
    }

    pub(crate) fn reference_uri(&self, relative_path: &str) -> String {
        format!("skill://{}/{}", self.resolved_path(), relative_path)
    }

    /// Synthesize the PROMPT surface — body followed by each reference
    /// inlined with labelled `--- <relative_path> ---` rules.
    ///
    /// This is the load-bearing dual-surface invariant: the value
    /// returned here is byte-equal to the concatenation of the SKILL.md
    /// body and every reference body read via the
    /// [`crate::server::ResourceHandler`] surface, with a trailing
    /// newline normalization applied to each segment.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use pmcp::server::skills::{Skill, SkillReference};
    ///
    /// let s = Skill::new("x", "A")
    ///     .with_reference(SkillReference::new("ref1.md", "text/markdown", "refbody"));
    /// assert_eq!(s.as_prompt_text(), "A\n\n--- ref1.md ---\nrefbody\n");
    /// ```
    pub fn as_prompt_text(&self) -> String {
        let mut out = String::new();
        out.push_str(&self.body);
        if !self.body.ends_with('\n') {
            out.push('\n');
        }
        for r in &self.references {
            out.push_str("\n--- ");
            out.push_str(&r.relative_path);
            out.push_str(" ---\n");
            out.push_str(&r.body);
            if !r.body.ends_with('\n') {
                out.push('\n');
            }
        }
        out
    }
}

fn validate_reference_path(path: &str, existing: &[SkillReference]) -> Result<()> {
    if path.is_empty() {
        return Err(Error::validation(
            "SkillReference relative_path must not be empty",
        ));
    }
    if path.contains('\0') {
        return Err(Error::validation(
            "SkillReference relative_path must not contain null bytes",
        ));
    }
    if path == "SKILL.md" {
        return Err(Error::validation(
            "SkillReference relative_path 'SKILL.md' collides with the canonical SKILL.md URI",
        ));
    }
    if path.split('/').any(|seg| seg == "..") {
        return Err(Error::validation(format!(
            "SkillReference relative_path '{path}' must not contain '..' segments"
        )));
    }
    if path.starts_with('/') {
        return Err(Error::validation(format!(
            "SkillReference relative_path '{path}' must be relative (no leading '/')"
        )));
    }
    if path.contains("://") {
        return Err(Error::validation(format!(
            "SkillReference relative_path '{path}' must not contain a URI scheme"
        )));
    }
    if existing.iter().any(|r| r.relative_path == path) {
        return Err(Error::validation(format!(
            "SkillReference relative_path '{path}' is already registered on this Skill"
        )));
    }
    Ok(())
}

/// Collection of skills + auto-generated discovery index. Lifted into a
/// [`crate::server::ResourceHandler`] impl via [`Skills::into_handler`].
///
/// `Clone` is required so the builder's `try_skills` can probe duplicates
/// by cloning the registry before storing it (consume-by-value
/// `into_handler` API).
///
/// # Examples
///
/// ```rust
/// use pmcp::server::skills::{Skill, Skills};
///
/// let registry = Skills::new()
///     .add(Skill::new("a", "body-a"))
///     .add(Skill::new("b", "body-b"));
/// assert_eq!(registry.skill_md_uris(), vec![
///     "skill://a/SKILL.md".to_string(),
///     "skill://b/SKILL.md".to_string(),
/// ]);
/// ```
#[derive(Default, Clone, Debug)]
pub struct Skills {
    skills: Vec<Skill>,
}

impl Skills {
    /// Create an empty registry.
    pub fn new() -> Self {
        Self { skills: Vec::new() }
    }

    /// Append a skill to the registry.
    #[must_use]
    #[allow(clippy::should_implement_trait)] // builder-style consumer; not a std::ops::Add impl
    pub fn add(mut self, skill: Skill) -> Self {
        self.skills.push(skill);
        self
    }

    /// Concatenate another registry onto this one — the builder
    /// accumulator uses this on repeated `.skills(...)` calls so each
    /// call adds to (rather than replaces) prior registrations.
    #[must_use]
    pub fn merge(mut self, other: Self) -> Self {
        self.skills.extend(other.skills);
        self
    }

    /// Snapshot of all registered SKILL.md URIs in registration order.
    ///
    /// Reference URIs are NOT included — they're readable via
    /// `resources/read` but never enumerated (SEP-2640 §9).
    pub fn skill_md_uris(&self) -> Vec<String> {
        self.skills.iter().map(Skill::skill_md_uri).collect()
    }

    /// Flatten the registry into a [`crate::server::ResourceHandler`].
    ///
    /// Returns `Err` on:
    /// - Two skills resolving to the same `skill_md_uri()`.
    /// - Two skills' reference URIs colliding.
    ///
    /// Insertion order is preserved via [`indexmap::IndexMap`] so
    /// `resources/list` output is deterministic across runs.
    ///
    /// # Errors
    ///
    /// Returns `Err(pmcp::Error::Validation)` listing every duplicate URI
    /// detected. No silent overwrites.
    pub fn into_handler(self) -> Result<Arc<dyn ResourceHandler>> {
        let mut skill_md: IndexMap<String, Skill> = IndexMap::with_capacity(self.skills.len());
        let mut references: IndexMap<String, (String, String)> = IndexMap::new();
        let mut dup_skill: Vec<String> = Vec::new();
        let mut dup_ref: Vec<String> = Vec::new();
        for skill in self.skills {
            for r in &skill.references {
                let uri = skill.reference_uri(&r.relative_path);
                match references.entry(uri) {
                    indexmap::map::Entry::Occupied(e) => dup_ref.push(e.key().clone()),
                    indexmap::map::Entry::Vacant(e) => {
                        e.insert((r.mime_type.clone(), r.body.clone()));
                    },
                }
            }
            let uri = skill.skill_md_uri();
            match skill_md.entry(uri) {
                indexmap::map::Entry::Occupied(e) => dup_skill.push(e.key().clone()),
                indexmap::map::Entry::Vacant(e) => {
                    e.insert(skill);
                },
            }
        }
        if !dup_skill.is_empty() || !dup_ref.is_empty() {
            let mut msg = String::from("Skills::into_handler: duplicate URI(s):");
            if !dup_skill.is_empty() {
                msg.push_str(&format!(" SKILL.md=[{}]", dup_skill.join(", ")));
            }
            if !dup_ref.is_empty() {
                msg.push_str(&format!(" references=[{}]", dup_ref.join(", ")));
            }
            return Err(Error::validation(msg));
        }
        Ok(Arc::new(SkillsHandler::new(skill_md, references)))
    }
}

// ── Internal handler types ────────────────────────────────────────────

/// Internal [`crate::server::ResourceHandler`] impl synthesized by
/// [`Skills::into_handler`]. The registry is immutable post-construction,
/// so list/read responses are precomputed once and cloned per request.
pub(crate) struct SkillsHandler {
    list_resources: Vec<ResourceInfo>,
    skill_md: IndexMap<String, Skill>,
    references: IndexMap<String, (String, String)>, // uri -> (mime, body)
    index_json: String,
}

impl SkillsHandler {
    fn new(
        skill_md: IndexMap<String, Skill>,
        references: IndexMap<String, (String, String)>,
    ) -> Self {
        let mut list_resources: Vec<ResourceInfo> = skill_md
            .values()
            .map(|s| {
                ResourceInfo::new(s.skill_md_uri(), s.name().to_string())
                    .with_description(s.resolved_description())
                    .with_mime_type(SKILL_MD_MIME)
            })
            .collect();
        list_resources.push(
            ResourceInfo::new(SKILL_INDEX_URI, "index")
                .with_description("Skill discovery index (SEP-2640 §9)")
                .with_mime_type(INDEX_JSON_MIME),
        );
        let index_json = build_discovery_index_json(&skill_md);
        Self {
            list_resources,
            skill_md,
            references,
            index_json,
        }
    }
}

fn build_discovery_index_json(skill_md: &IndexMap<String, Skill>) -> String {
    let entries: Vec<_> = skill_md
        .values()
        .map(|s| {
            json!({
                "name": s.name(),
                "type": "skill-md",
                "description": s.resolved_description(),
                "url": s.skill_md_uri(),
            })
        })
        .collect();
    serde_json::to_string_pretty(&json!({
        "$schema": "https://schemas.agentskills.io/discovery/0.2.0/schema.json",
        "skills": entries,
    }))
    .expect("static JSON object — to_string_pretty cannot fail")
}

#[async_trait]
impl ResourceHandler for SkillsHandler {
    async fn list(
        &self,
        _cursor: Option<String>,
        _extra: RequestHandlerExtra,
    ) -> Result<ListResourcesResult> {
        // Per SEP-2640 §9: list emits SKILL.md entries + the discovery
        // index ONLY. Reference URIs are never enumerated.
        Ok(ListResourcesResult::new(self.list_resources.clone()))
    }

    async fn read(&self, uri: &str, _extra: RequestHandlerExtra) -> Result<ReadResourceResult> {
        // resource_with_text (not Content::text) preserves the per-resource
        // URI + MIME on the wire — required so a reference like
        // schema.graphql round-trips with `application/graphql`.
        if uri == SKILL_INDEX_URI {
            return Ok(ReadResourceResult::new(vec![Content::resource_with_text(
                uri,
                self.index_json.clone(),
                INDEX_JSON_MIME,
            )]));
        }
        if let Some(skill) = self.skill_md.get(uri) {
            return Ok(ReadResourceResult::new(vec![Content::resource_with_text(
                uri,
                skill.body().to_string(),
                SKILL_MD_MIME,
            )]));
        }
        if let Some((mime, body)) = self.references.get(uri) {
            return Ok(ReadResourceResult::new(vec![Content::resource_with_text(
                uri,
                body.clone(),
                mime.clone(),
            )]));
        }
        Err(Error::protocol(
            ErrorCode::METHOD_NOT_FOUND,
            format!("Skill resource not found: {uri}"),
        ))
    }
}

/// [`crate::server::PromptHandler`] impl that returns the
/// [`Skill::as_prompt_text`] body as a single user message.
///
/// The dual-surface invariant: the prompt body is byte-equal to the
/// concatenated SKILL.md + reference reads. Pointer-style prompts
/// (returning a `skill://` URI the host cannot fetch) are prohibited —
/// hosts that don't yet speak SEP-2640 need the content inlined.
pub(crate) struct SkillPromptHandler {
    prompt_text: String,
    description: String,
}

impl SkillPromptHandler {
    pub(crate) fn new(skill: Skill) -> Self {
        let prompt_text = skill.as_prompt_text();
        let description = skill.resolved_description().to_string();
        Self {
            prompt_text,
            description,
        }
    }
}

#[async_trait]
impl PromptHandler for SkillPromptHandler {
    async fn handle(
        &self,
        _args: HashMap<String, String>,
        _extra: RequestHandlerExtra,
    ) -> Result<GetPromptResult> {
        // Plain Content::text is correct here — this is a PromptMessage,
        // not a resource read. The resource_with_text shape applies only
        // to ResourceHandler::read.
        let message = PromptMessage::new(Role::User, Content::text(self.prompt_text.clone()));
        Ok(GetPromptResult::new(
            vec![message],
            Some(self.description.clone()),
        ))
    }
}

/// URI-prefix-routing composite [`crate::server::ResourceHandler`].
///
/// Constructed exactly once per server, in the builder's `.build()`
/// finalization step — never nested.
pub(crate) struct ComposedResources {
    pub(crate) skills: Arc<dyn ResourceHandler>,
    pub(crate) other: Arc<dyn ResourceHandler>,
}

#[async_trait]
impl ResourceHandler for ComposedResources {
    async fn list(
        &self,
        cursor: Option<String>,
        extra: RequestHandlerExtra,
    ) -> Result<ListResourcesResult> {
        // SkillsHandler::list ignores cursor + extra — pass owned defaults
        // so the user handler can take the real ones by move.
        let mut combined = self
            .skills
            .list(None, RequestHandlerExtra::default())
            .await?;
        let extra_other = self.other.list(cursor, extra).await?;
        combined.resources.extend(extra_other.resources);
        Ok(combined)
    }

    async fn read(&self, uri: &str, extra: RequestHandlerExtra) -> Result<ReadResourceResult> {
        if uri.starts_with("skill://") {
            self.skills.read(uri, extra).await
        } else {
            self.other.read(uri, extra).await
        }
    }
}

// ── Frontmatter parsing (internal) ───────────────────────────────────

fn parse_frontmatter_description(body: &str) -> Option<String> {
    // Strip UTF-8 BOM so frontmatter authored on Windows still parses;
    // `str::lines()` already handles both \n and \r\n line endings.
    let body = body.strip_prefix('\u{FEFF}').unwrap_or(body);
    let mut in_frontmatter = false;
    for line in body.lines().take(40) {
        if line == "---" {
            if in_frontmatter {
                break;
            }
            in_frontmatter = true;
            continue;
        }
        if in_frontmatter {
            if let Some(rest) = line.strip_prefix("description: ") {
                return Some(rest.trim().to_string());
            }
        }
    }
    None
}

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

    fn extra() -> RequestHandlerExtra {
        RequestHandlerExtra::default()
    }

    // ── Test 1.1 ──────────────────────────────────────────────────────
    #[test]
    fn test_1_1_skill_new_and_builders() {
        let s = Skill::new("foo", "body");
        assert_eq!(s.name(), "foo");
        assert_eq!(s.body(), "body");
        assert_eq!(s.references().count(), 0);
        assert_eq!(s.resolved_description(), "");

        let s = s
            .with_path("p")
            .with_description("d")
            .with_reference(SkillReference::new(
                "references/x.md",
                "text/markdown",
                "ref body",
            ));
        assert_eq!(s.resolved_path(), "p");
        assert_eq!(s.resolved_description(), "d");
        assert_eq!(s.references().count(), 1);
    }

    // ── Test 1.2 ──────────────────────────────────────────────────────
    #[test]
    fn test_1_2_skill_md_uri_default_and_override() {
        let s = Skill::new("foo", "");
        assert_eq!(s.skill_md_uri(), "skill://foo/SKILL.md");
        let s = s.with_path("acme/refunds");
        assert_eq!(s.skill_md_uri(), "skill://acme/refunds/SKILL.md");
    }

    // ── Test 1.3 ──────────────────────────────────────────────────────
    #[test]
    fn test_1_3_skill_reference_uri_resolution() {
        let s = Skill::new("x", "").with_reference(SkillReference::new(
            "references/a.md",
            "text/markdown",
            "...",
        ));
        assert_eq!(
            s.reference_uri("references/a.md"),
            "skill://x/references/a.md"
        );

        let s = s.with_path("y/z");
        assert_eq!(
            s.reference_uri("references/a.md"),
            "skill://y/z/references/a.md"
        );
    }

    // ── Test 1.4 ──────────────────────────────────────────────────────
    #[test]
    fn test_1_4_as_prompt_text_no_references() {
        let s = Skill::new("x", "---\nname: x\n---\nbody");
        assert_eq!(s.as_prompt_text(), "---\nname: x\n---\nbody\n");
    }

    // ── Test 1.5 ──────────────────────────────────────────────────────
    #[test]
    fn test_1_5_as_prompt_text_with_references() {
        let s = Skill::new("x", "A").with_reference(SkillReference::new(
            "ref1.md",
            "text/markdown",
            "refbody",
        ));
        assert_eq!(s.as_prompt_text(), "A\n\n--- ref1.md ---\nrefbody\n");

        let s = Skill::new("x", "A")
            .with_reference(SkillReference::new("r1.md", "text/markdown", "b1"))
            .with_reference(SkillReference::new("r2.md", "text/markdown", "b2"));
        assert_eq!(
            s.as_prompt_text(),
            "A\n\n--- r1.md ---\nb1\n\n--- r2.md ---\nb2\n"
        );
    }

    // ── Test 1.6 ──────────────────────────────────────────────────────
    #[test]
    fn test_1_6_resolved_description_frontmatter_parsing() {
        let s = Skill::new("x", "---\nname: x\ndescription: hello\n---\nbody");
        assert_eq!(s.resolved_description(), "hello");

        let s = Skill::new("x", "---\nname: x\ndescription: hello\n---\nbody")
            .with_description("override");
        assert_eq!(s.resolved_description(), "override");

        let s = Skill::new("x", "no frontmatter");
        assert_eq!(s.resolved_description(), "");
    }

    // ── Test 1.6a (CRLF) ──────────────────────────────────────────────
    #[test]
    fn test_1_6a_parse_frontmatter_crlf() {
        let s = Skill::new("x", "---\r\nname: x\r\ndescription: hello\r\n---\r\nbody");
        assert_eq!(s.resolved_description(), "hello");
    }

    // ── Test 1.6b (UTF-8 BOM) ─────────────────────────────────────────
    #[test]
    fn test_1_6b_parse_frontmatter_utf8_bom() {
        let s = Skill::new("x", "\u{FEFF}---\nname: x\ndescription: hello\n---\nbody");
        assert_eq!(s.resolved_description(), "hello");
    }

    // ── Test 1.7 ──────────────────────────────────────────────────────
    #[tokio::test]
    async fn test_1_7_skills_into_handler_happy_path() {
        let handler = Skills::new()
            .add(Skill::new("a", ""))
            .add(Skill::new("b", ""))
            .into_handler()
            .unwrap();
        let list = handler.list(None, extra()).await.unwrap();
        assert_eq!(list.resources.len(), 3);
        assert_eq!(list.resources[0].uri, "skill://a/SKILL.md");
        assert_eq!(list.resources[1].uri, "skill://b/SKILL.md");
        assert_eq!(list.resources[2].uri, "skill://index.json");
        // No references in the list.
        for r in &list.resources {
            assert!(!r.uri.contains("/references/"));
        }
    }

    // ── Test 1.7a (registration order) ────────────────────────────────
    #[tokio::test]
    async fn test_1_7a_skills_into_handler_preserves_registration_order() {
        for _ in 0..10 {
            let handler = Skills::new()
                .add(Skill::new("zeta", ""))
                .add(Skill::new("alpha", ""))
                .add(Skill::new("mu", ""))
                .into_handler()
                .unwrap();
            let list = handler.list(None, extra()).await.unwrap();
            assert_eq!(list.resources.len(), 4);
            assert_eq!(list.resources[0].uri, "skill://zeta/SKILL.md");
            assert_eq!(list.resources[1].uri, "skill://alpha/SKILL.md");
            assert_eq!(list.resources[2].uri, "skill://mu/SKILL.md");
            assert_eq!(list.resources[3].uri, "skill://index.json");
        }
    }

    // ── Test 1.8 ──────────────────────────────────────────────────────
    #[test]
    fn test_1_8_skills_into_handler_duplicate_skill_md_uri_rejected() {
        match Skills::new()
            .add(Skill::new("refunds", "a"))
            .add(Skill::new("refunds", "b"))
            .into_handler()
        {
            Err(Error::Validation(msg)) => {
                assert!(msg.contains("skill://refunds/SKILL.md"), "msg = {msg}");
            },
            Err(other) => panic!("expected Validation, got {other:?}"),
            Ok(_) => panic!("expected Err for duplicate names"),
        }

        // Different names colliding via path.
        match Skills::new()
            .add(Skill::new("a", "").with_path("p"))
            .add(Skill::new("b", "").with_path("p"))
            .into_handler()
        {
            Err(Error::Validation(msg)) => assert!(msg.contains("skill://p/SKILL.md")),
            Err(other) => panic!("expected Validation, got {other:?}"),
            Ok(_) => panic!("expected Err for colliding paths"),
        }
    }

    // ── Test 1.8a (cross-skill reference URI duplicates) ──────────────
    #[test]
    fn test_1_8a_skills_into_handler_duplicate_reference_uri_rejected() {
        let s1 = Skill::new("a", "").with_reference(SkillReference::new(
            "references/shared.md",
            "text/markdown",
            "x",
        ));
        let s2 = Skill::new("b", "")
            .with_path("a")
            .with_reference(SkillReference::new(
                "references/shared.md",
                "text/markdown",
                "y",
            ));
        match Skills::new().add(s1).add(s2).into_handler() {
            Err(Error::Validation(msg)) => {
                assert!(
                    msg.contains("skill://a/references/shared.md"),
                    "msg = {msg}"
                );
                assert!(msg.contains("references="), "msg = {msg}");
            },
            Err(other) => panic!("expected Validation, got {other:?}"),
            Ok(_) => panic!("expected Err for colliding reference URIs"),
        }
    }

    // ── Test 1.9 ──────────────────────────────────────────────────────
    #[tokio::test]
    async fn test_1_9_skills_handler_list_excludes_references() {
        let s = Skill::new("a", "")
            .with_reference(SkillReference::new(
                "references/r1.md",
                "text/markdown",
                "1",
            ))
            .with_reference(SkillReference::new(
                "references/r2.md",
                "text/markdown",
                "2",
            ));
        let handler = Skills::new().add(s).into_handler().unwrap();
        let list = handler.list(None, extra()).await.unwrap();
        let skill_md_count = list
            .resources
            .iter()
            .filter(|r| r.uri == "skill://a/SKILL.md")
            .count();
        assert_eq!(skill_md_count, 1);
        for r in &list.resources {
            assert!(!r.uri.contains("/references/"), "leaked: {}", r.uri);
        }
        let index_count = list
            .resources
            .iter()
            .filter(|r| r.uri == "skill://index.json")
            .count();
        assert_eq!(index_count, 1);
    }

    // ── Test 1.10 (wire shape SKILL.md) ───────────────────────────────
    #[tokio::test]
    async fn test_1_10_skills_handler_read_skill_md_returns_resource_with_text() {
        let handler = Skills::new()
            .add(Skill::new("a", "the body"))
            .into_handler()
            .unwrap();
        let res = handler.read("skill://a/SKILL.md", extra()).await.unwrap();
        assert_eq!(res.contents.len(), 1);
        match &res.contents[0] {
            Content::Resource {
                uri,
                text,
                mime_type,
                ..
            } => {
                assert_eq!(uri, "skill://a/SKILL.md");
                assert_eq!(text.as_deref(), Some("the body"));
                assert_eq!(mime_type.as_deref(), Some("text/markdown"));
            },
            other => panic!("expected Content::Resource, got {other:?}"),
        }
    }

    // ── Test 1.11 (wire shape reference) ──────────────────────────────
    #[tokio::test]
    async fn test_1_11_skills_handler_read_reference_carries_per_resource_mime() {
        let s = Skill::new("a", "").with_reference(SkillReference::new(
            "references/schema.graphql",
            "application/graphql",
            "schema { query: Q }",
        ));
        let handler = Skills::new().add(s).into_handler().unwrap();
        let res = handler
            .read("skill://a/references/schema.graphql", extra())
            .await
            .unwrap();
        match &res.contents[0] {
            Content::Resource {
                uri,
                text,
                mime_type,
                ..
            } => {
                assert_eq!(uri, "skill://a/references/schema.graphql");
                assert_eq!(text.as_deref(), Some("schema { query: Q }"));
                assert_eq!(mime_type.as_deref(), Some("application/graphql"));
            },
            other => panic!("expected Content::Resource, got {other:?}"),
        }
    }

    // ── Test 1.12 (wire shape index) ──────────────────────────────────
    #[tokio::test]
    async fn test_1_12_skills_handler_read_index_returns_resource_with_text() {
        let s = Skill::new("a", "").with_reference(SkillReference::new(
            "references/r.md",
            "text/markdown",
            "x",
        ));
        let handler = Skills::new().add(s).into_handler().unwrap();
        let res = handler.read("skill://index.json", extra()).await.unwrap();
        match &res.contents[0] {
            Content::Resource {
                uri,
                text,
                mime_type,
                ..
            } => {
                assert_eq!(uri, "skill://index.json");
                assert_eq!(mime_type.as_deref(), Some("application/json"));
                let parsed: serde_json::Value =
                    serde_json::from_str(text.as_deref().unwrap()).unwrap();
                assert!(parsed.get("$schema").is_some());
                assert!(parsed.get("skills").is_some());
                let arr = parsed["skills"].as_array().unwrap();
                assert_eq!(arr.len(), 1);
                // Reference entries MUST NOT appear in the discovery index.
                let serialized = serde_json::to_string(&parsed).unwrap();
                assert!(!serialized.contains("references/r.md"));
            },
            other => panic!("expected Content::Resource, got {other:?}"),
        }
    }

    // ── Test 1.13 ─────────────────────────────────────────────────────
    #[tokio::test]
    async fn test_1_13_skills_handler_read_unknown_uri_method_not_found() {
        let handler = Skills::new()
            .add(Skill::new("a", "body"))
            .into_handler()
            .unwrap();
        let err = handler
            .read("skill://nonexistent/SKILL.md", extra())
            .await
            .expect_err("unknown URI must error");
        match err {
            Error::Protocol { code, .. } => assert_eq!(code, ErrorCode::METHOD_NOT_FOUND),
            other => panic!("expected Protocol, got {other:?}"),
        }

        let err = handler
            .read("skill://a/references/missing.md", extra())
            .await
            .expect_err("unknown reference must error");
        match err {
            Error::Protocol { code, .. } => assert_eq!(code, ErrorCode::METHOD_NOT_FOUND),
            other => panic!("expected Protocol, got {other:?}"),
        }
    }

    // ── Test 1.14 ─────────────────────────────────────────────────────
    #[tokio::test]
    async fn test_1_14_skill_prompt_handler_returns_byte_equal_text() {
        let skill = Skill::new("x", "A").with_reference(SkillReference::new(
            "ref1.md",
            "text/markdown",
            "refbody",
        ));
        let handler = SkillPromptHandler::new(skill.clone());
        let result = handler.handle(HashMap::new(), extra()).await.unwrap();
        assert_eq!(result.messages.len(), 1);
        assert_eq!(result.messages[0].role, Role::User);
        match &result.messages[0].content {
            Content::Text { text } => assert_eq!(text, &skill.as_prompt_text()),
            other => panic!("expected Content::Text, got {other:?}"),
        }
    }

    // ── Test 1.15 ─────────────────────────────────────────────────────
    struct DocsHandler;

    #[async_trait]
    impl ResourceHandler for DocsHandler {
        async fn read(&self, uri: &str, _extra: RequestHandlerExtra) -> Result<ReadResourceResult> {
            Ok(ReadResourceResult::new(vec![Content::text(format!(
                "DOCS:{uri}"
            ))]))
        }

        async fn list(
            &self,
            _cursor: Option<String>,
            _extra: RequestHandlerExtra,
        ) -> Result<ListResourcesResult> {
            Ok(ListResourcesResult::new(vec![ResourceInfo::new(
                "docs://handbook",
                "handbook",
            )]))
        }
    }

    #[tokio::test]
    async fn test_1_15_composed_resources_uri_prefix_routing() {
        let skills: Arc<dyn ResourceHandler> = Skills::new()
            .add(Skill::new("a", "skill-a"))
            .into_handler()
            .unwrap();
        let other: Arc<dyn ResourceHandler> = Arc::new(DocsHandler);
        let composed = ComposedResources { skills, other };

        let res = composed.read("skill://a/SKILL.md", extra()).await.unwrap();
        match &res.contents[0] {
            Content::Resource { uri, .. } => assert_eq!(uri, "skill://a/SKILL.md"),
            other => panic!("expected Content::Resource, got {other:?}"),
        }

        let res = composed.read("docs://handbook", extra()).await.unwrap();
        match &res.contents[0] {
            Content::Text { text } => assert_eq!(text, "DOCS:docs://handbook"),
            other => panic!("expected Content::Text, got {other:?}"),
        }

        let res = composed.read("ftp://foo", extra()).await.unwrap();
        match &res.contents[0] {
            Content::Text { text } => assert_eq!(text, "DOCS:ftp://foo"),
            other => panic!("expected Content::Text, got {other:?}"),
        }
    }

    // ── Test 1.16 ─────────────────────────────────────────────────────
    #[tokio::test]
    async fn test_1_16_composed_resources_list_concatenates_skills_first() {
        let skills: Arc<dyn ResourceHandler> = Skills::new()
            .add(Skill::new("a", ""))
            .into_handler()
            .unwrap();
        let other: Arc<dyn ResourceHandler> = Arc::new(DocsHandler);
        let composed = ComposedResources { skills, other };
        let list = composed.list(None, extra()).await.unwrap();
        // Skills first (SKILL.md + index = 2), then other (1).
        assert_eq!(list.resources.len(), 3);
        assert_eq!(list.resources[0].uri, "skill://a/SKILL.md");
        assert_eq!(list.resources[1].uri, "skill://index.json");
        assert_eq!(list.resources[2].uri, "docs://handbook");
    }

    // ── Test 1.17 (property: no reference ever listed) ────────────────
    fn skill_strategy() -> impl Strategy<Value = Skill> {
        let name = "[a-z]{1,8}";
        let ref_strategy = (
            "ref_[a-z]{1,6}\\.md",
            Just("text/markdown".to_string()),
            "[a-zA-Z]{1,12}",
        )
            .prop_map(|(p, m, b)| SkillReference::new(p, m, b));
        (
            name,
            "[a-zA-Z]{0,20}",
            proptest::collection::vec(ref_strategy, 0..=5),
        )
            .prop_map(|(name, body, refs)| {
                let mut s = Skill::new(name, body);
                // De-duplicate within a single skill by relative_path.
                let mut seen: std::collections::HashSet<String> = std::collections::HashSet::new();
                for r in refs {
                    if seen.insert(r.relative_path().to_string()) {
                        s = s.with_reference(r);
                    }
                }
                s
            })
    }

    // Strategy that preserves references but uniquifies skill paths so
    // every reference URI is globally unique.
    fn skills_strategy_with_refs() -> impl Strategy<Value = Vec<Skill>> {
        proptest::collection::vec(skill_strategy(), 1..=10).prop_map(|skills| {
            skills
                .into_iter()
                .enumerate()
                .map(|(i, s)| {
                    let new_path = format!("p{i}");
                    let mut rebuilt = Skill::new(s.name().to_string(), s.body().to_string())
                        .with_path(new_path)
                        .with_description(s.resolved_description());
                    for r in s.references() {
                        rebuilt = rebuilt.with_reference(SkillReference::new(
                            r.relative_path(),
                            r.mime_type(),
                            r.body(),
                        ));
                    }
                    rebuilt
                })
                .collect()
        })
    }

    proptest! {
        #[test]
        fn prop_1_17_no_reference_ever_listed(skills in skills_strategy_with_refs()) {
            let mut registry = Skills::new();
            for s in skills {
                registry = registry.add(s);
            }
            // Skip inputs that produce duplicate URIs — covered by Test 1.18.
            let Ok(handler) = registry.into_handler() else { return Ok(()); };
            let rt = tokio::runtime::Runtime::new().unwrap();
            let list = rt.block_on(handler.list(None, RequestHandlerExtra::default())).unwrap();
            for r in &list.resources {
                prop_assert!(!r.uri.contains("/references/"), "leaked: {}", r.uri);
            }
        }
    }

    // ── Test 1.18 (property: duplicate URI always rejected) ───────────
    proptest! {
        #[test]
        fn prop_1_18_duplicate_uri_always_rejected(
            name in "[a-z]{1,6}",
            body_a in "[a-zA-Z]{0,12}",
            body_b in "[a-zA-Z]{0,12}",
        ) {
            // Same name → same skill_md_uri → always Err.
            let result = Skills::new()
                .add(Skill::new(name.clone(), body_a))
                .add(Skill::new(name, body_b))
                .into_handler();
            prop_assert!(result.is_err());
        }

        #[test]
        fn prop_1_18b_distinct_names_always_ok(
            name_a in "[a-z]{1,6}",
            name_b in "[a-z]{7,12}",
        ) {
            // Disjoint name lengths guarantee distinct names.
            prop_assume!(name_a != name_b);
            let result = Skills::new()
                .add(Skill::new(name_a, ""))
                .add(Skill::new(name_b, ""))
                .into_handler();
            prop_assert!(result.is_ok());
        }
    }

    // ── Test 1.19 (property: as_prompt_text byte-equal concat) ────────
    proptest! {
        #[test]
        fn prop_1_19_as_prompt_text_byte_equal_concat(skill in skill_strategy()) {
            // Manually concatenate the expected output.
            let mut expected = String::new();
            expected.push_str(skill.body());
            if !skill.body().ends_with('\n') {
                expected.push('\n');
            }
            for r in skill.references() {
                expected.push_str("\n--- ");
                expected.push_str(r.relative_path());
                expected.push_str(" ---\n");
                expected.push_str(r.body());
                if !r.body().ends_with('\n') {
                    expected.push('\n');
                }
            }
            prop_assert_eq!(skill.as_prompt_text(), expected);
        }
    }

    // ── Test 1.19a (property: read responses always have URI + MIME) ──
    fn collect_all_uris(skills: &[Skill]) -> Vec<String> {
        let mut uris: Vec<String> = vec!["skill://index.json".to_string()];
        for s in skills {
            uris.push(s.skill_md_uri());
            for r in s.references() {
                uris.push(s.reference_uri(r.relative_path()));
            }
        }
        uris
    }

    fn assert_read_response_has_uri_and_mime(
        contents: &[Content],
        expected_uri: &str,
    ) -> std::result::Result<(), proptest::test_runner::TestCaseError> {
        prop_assert_eq!(contents.len(), 1);
        match &contents[0] {
            Content::Resource {
                uri,
                text,
                mime_type,
                ..
            } => {
                prop_assert_eq!(uri, expected_uri);
                prop_assert!(text.is_some(), "text missing for {}", expected_uri);
                prop_assert!(mime_type.is_some(), "mime missing for {}", expected_uri);
                Ok(())
            },
            other => {
                prop_assert!(false, "expected Content::Resource, got {:?}", other);
                Ok(())
            },
        }
    }

    proptest! {
        #[test]
        fn prop_1_19a_read_responses_always_have_uri_and_mime(skills in skills_strategy_with_refs()) {
            let mut registry = Skills::new();
            for s in skills.clone() {
                registry = registry.add(s);
            }
            let Ok(handler) = registry.into_handler() else { return Ok(()); };
            let rt = tokio::runtime::Runtime::new().unwrap();
            let uris = collect_all_uris(&skills);
            for uri in uris {
                let Ok(res) = rt.block_on(handler.read(&uri, RequestHandlerExtra::default())) else { continue; };
                assert_read_response_has_uri_and_mime(&res.contents, &uri)?;
            }
        }
    }

    // ── Test 1.20 (with_reference validation panics) ──────────────────
    #[test]
    #[should_panic(expected = "must not be empty")]
    fn test_1_20_with_reference_panic_empty() {
        let _ =
            Skill::new("x", "b").with_reference(SkillReference::new("", "text/markdown", "body"));
    }

    #[test]
    #[should_panic(expected = "SKILL.md")]
    fn test_1_20_with_reference_panic_skill_md_collision() {
        let _ = Skill::new("x", "b").with_reference(SkillReference::new(
            "SKILL.md",
            "text/markdown",
            "body",
        ));
    }

    #[test]
    #[should_panic(expected = "..")]
    fn test_1_20_with_reference_panic_dotdot() {
        let _ = Skill::new("x", "b").with_reference(SkillReference::new(
            "../escape.md",
            "text/markdown",
            "body",
        ));
    }

    #[test]
    #[should_panic(expected = "leading")]
    fn test_1_20_with_reference_panic_absolute() {
        let _ = Skill::new("x", "b").with_reference(SkillReference::new(
            "/abs/path.md",
            "text/markdown",
            "body",
        ));
    }

    #[test]
    #[should_panic(expected = "URI scheme")]
    fn test_1_20_with_reference_panic_scheme() {
        let _ = Skill::new("x", "b").with_reference(SkillReference::new(
            "http://example.com/x",
            "text/markdown",
            "body",
        ));
    }

    #[test]
    #[should_panic(expected = "already registered")]
    fn test_1_20_with_reference_panic_duplicate_within_skill() {
        let _ = Skill::new("x", "b")
            .with_reference(SkillReference::new("a.md", "text/markdown", "body1"))
            .with_reference(SkillReference::new("a.md", "text/markdown", "body2"));
    }

    // ── Test 1.20a (try_with_reference returns Err) ───────────────────
    #[test]
    fn test_1_20a_try_with_reference_returns_err() {
        let invalid = [
            "",
            "SKILL.md",
            "../escape.md",
            "/abs/path.md",
            "http://example.com/x",
        ];
        for p in invalid {
            let res = Skill::new("x", "b").try_with_reference(SkillReference::new(
                p,
                "text/markdown",
                "body",
            ));
            assert!(res.is_err(), "expected Err for path = {p:?}");
            assert!(matches!(res.unwrap_err(), Error::Validation(_)));
        }
        // Duplicate within skill.
        let res = Skill::new("x", "b")
            .try_with_reference(SkillReference::new("a.md", "text/markdown", "1"))
            .and_then(|s| s.try_with_reference(SkillReference::new("a.md", "text/markdown", "2")));
        assert!(res.is_err());

        // Ok case.
        let res = Skill::new("x", "b").try_with_reference(SkillReference::new(
            "references/ok.md",
            "text/markdown",
            "body",
        ));
        assert!(res.is_ok());
    }

    // ── Test 1.21 (Skills::merge) ─────────────────────────────────────
    #[tokio::test]
    async fn test_1_21_skills_merge_concatenates() {
        let combined = Skills::new()
            .add(Skill::new("a", ""))
            .merge(Skills::new().add(Skill::new("b", "")));
        let handler = combined.into_handler().unwrap();
        let list = handler.list(None, extra()).await.unwrap();
        assert_eq!(list.resources.len(), 3);
        assert_eq!(list.resources[0].uri, "skill://a/SKILL.md");
        assert_eq!(list.resources[1].uri, "skill://b/SKILL.md");
        assert_eq!(list.resources[2].uri, "skill://index.json");
    }
}