multicast 2.0.0

A declarative CLI framework for Rust with typed commands, agent discovery, HTTP, and MCP
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
//! Agent Skills published over MCP.
//!
//! Implements the server side of the `io.modelcontextprotocol/skills`
//! extension: `skills/list`, `skills/get`, skill file reads through
//! `resources/read`, and `resources/directory/read`. A [`McpSkillBundle`] is
//! built once, before serving, and never changes while the server runs, so every
//! manifest is computed from the exact bytes later served.

use std::collections::{BTreeMap, BTreeSet};
use std::ops::Bound;

use serde_json::{Map, Value, json};
use sha2::{Digest, Sha256};

use super::McpResourceError;
use crate::errors::MulticastError;

/// Extension identifier advertised in server capabilities.
pub const SKILLS_EXTENSION: &str = "io.modelcontextprotocol/skills";

/// URI scheme used for every published skill file.
pub const SKILL_URI_SCHEME: &str = "skill://";

/// Freshness hint attached to every skills result. The bundle is immutable for
/// the life of the server, so results remain valid for this long.
pub const SKILL_TTL_MS: u64 = 300_000;

/// Most files one skill may publish, including `SKILL.md`.
pub const MAX_SKILL_FILES: usize = 512;

/// Most bytes one skill may publish, including `SKILL.md`.
pub const MAX_SKILL_BYTES: usize = 16 * 1024 * 1024;

/// Default number of skills or directory children returned per page.
pub const DEFAULT_SKILL_PAGE_SIZE: usize = 100;

/// Longest permitted skill name, in bytes.
pub const MAX_SKILL_NAME_LEN: usize = 64;

/// Error code for a skill rejected while building a bundle.
pub const SKILL_INVALID: &str = "MCP_SKILL_INVALID";

const INVALID_PARAMS: i32 = -32602;
const DIRECTORY_MIME: &str = "inode/directory";

/// Which skills an MCP server publishes.
#[derive(Debug, Clone, Default)]
pub enum McpSkillPublication {
    /// Publish the CLI's generated command skills and its shipped Prompt
    /// Guides. Servers built from bare command trees have neither and publish
    /// nothing.
    #[default]
    Generated,
    /// Publish no skills and do not advertise the extension.
    Off,
    /// Publish exactly this bundle.
    Custom(McpSkillBundle),
}

/// The exact bytes served for one skill file.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum McpSkillContent {
    /// UTF-8 text, served as a `text` resource content.
    Text(String),
    /// Arbitrary bytes, served base64-encoded as a `blob` resource content.
    Binary(Vec<u8>),
}

impl McpSkillContent {
    /// The served bytes, over which size and digest are computed.
    pub fn as_bytes(&self) -> &[u8] {
        match self {
            Self::Text(text) => text.as_bytes(),
            Self::Binary(bytes) => bytes,
        }
    }
}

/// One file inside a skill, addressed relative to the skill's root directory.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct McpSkillFile {
    /// Slash-separated path relative to the skill root, such as `SKILL.md` or
    /// `references/checklist.md`.
    pub path: String,
    /// Exact content served for this file.
    pub content: McpSkillContent,
    /// Media type reported by reads and directory listings.
    pub mime_type: String,
}

impl McpSkillFile {
    /// Creates a text file, inferring its media type from the extension.
    pub fn new(path: impl Into<String>, text: impl Into<String>) -> Self {
        Self::with_content(path.into(), McpSkillContent::Text(text.into()))
    }

    /// Creates a binary file, such as an image or an archive, inferring its
    /// media type from the extension. `SKILL.md` must be text.
    pub fn binary(path: impl Into<String>, bytes: impl Into<Vec<u8>>) -> Self {
        Self::with_content(path.into(), McpSkillContent::Binary(bytes.into()))
    }

    fn with_content(path: String, content: McpSkillContent) -> Self {
        let mime_type = match (mime_for(&path), &content) {
            ("text/plain", McpSkillContent::Binary(_)) => "application/octet-stream",
            (mime_type, _) => mime_type,
        }
        .to_string();
        Self {
            path,
            content,
            mime_type,
        }
    }

    /// Overrides the inferred media type.
    pub fn with_mime_type(mut self, mime_type: impl Into<String>) -> Self {
        self.mime_type = mime_type.into();
        self
    }
}

#[derive(Debug, Clone)]
struct StoredFile {
    content: McpSkillContent,
    mime_type: String,
    digest: String,
}

#[derive(Debug, Clone)]
struct StoredSkill {
    frontmatter: Map<String, Value>,
    files: BTreeMap<String, StoredFile>,
}

/// An immutable set of skills with precomputed manifests.
#[derive(Debug, Clone)]
pub struct McpSkillBundle {
    skills: BTreeMap<String, StoredSkill>,
    page_size: usize,
}

impl Default for McpSkillBundle {
    fn default() -> Self {
        Self::new()
    }
}

impl McpSkillBundle {
    /// Creates an empty bundle.
    pub fn new() -> Self {
        Self {
            skills: BTreeMap::new(),
            page_size: DEFAULT_SKILL_PAGE_SIZE,
        }
    }

    /// Sets how many skills, or directory children, one page returns.
    /// Values below one are treated as one.
    pub fn with_page_size(mut self, page_size: usize) -> Self {
        self.page_size = page_size.max(1);
        self
    }

    /// Returns whether the bundle publishes no skills.
    pub fn is_empty(&self) -> bool {
        self.skills.is_empty()
    }

    /// Returns the published skill names in listing order.
    pub fn names(&self) -> impl Iterator<Item = &str> {
        self.skills.keys().map(String::as_str)
    }

    /// Adds one skill.
    ///
    /// The files must include `SKILL.md`, whose YAML frontmatter names the
    /// skill. The name must be 1–64 lowercase letters, digits, and single
    /// hyphens, must equal `name`, and must not already be published. Paths
    /// must be relative and free of `.`/`..` segments. A skill may hold at
    /// most [`MAX_SKILL_FILES`] files and [`MAX_SKILL_BYTES`] bytes. Any
    /// violation returns an `MCP_SKILL_INVALID` error and leaves the bundle
    /// unchanged.
    pub fn add(
        &mut self,
        name: &str,
        files: impl IntoIterator<Item = McpSkillFile>,
    ) -> Result<&mut Self, MulticastError> {
        validate_name(name)?;
        if self.skills.contains_key(name) {
            return Err(invalid(format!("Duplicate MCP skill name: {name}")));
        }
        let mut stored = BTreeMap::new();
        let mut total = 0usize;
        for file in files {
            validate_path(name, &file.path)?;
            total = total.saturating_add(file.content.as_bytes().len());
            let digest = format!(
                "sha256:{}",
                sha256_hex(Sha256::digest(file.content.as_bytes()))
            );
            let previous = stored.insert(
                file.path.clone(),
                StoredFile {
                    content: file.content,
                    mime_type: file.mime_type,
                    digest,
                },
            );
            if previous.is_some() {
                return Err(invalid(format!(
                    "Skill {name} lists the file {} more than once",
                    file.path
                )));
            }
        }
        if stored.len() > MAX_SKILL_FILES {
            return Err(invalid(format!(
                "Skill {name} has {} files; the limit is {MAX_SKILL_FILES}",
                stored.len()
            )));
        }
        if total > MAX_SKILL_BYTES {
            return Err(invalid(format!(
                "Skill {name} has {total} bytes; the limit is {MAX_SKILL_BYTES}"
            )));
        }
        let Some(skill_md) = stored.get("SKILL.md") else {
            return Err(invalid(format!("Skill {name} has no SKILL.md")));
        };
        let McpSkillContent::Text(skill_md) = &skill_md.content else {
            return Err(invalid(format!("Skill {name} has a binary SKILL.md")));
        };
        let frontmatter = parse_frontmatter(skill_md)
            .map_err(|message| invalid(format!("Skill {name}: {message}")))?;
        match frontmatter.get("name") {
            Some(Value::String(declared)) if declared == name => {}
            Some(Value::String(declared)) => {
                return Err(invalid(format!(
                    "Skill directory {name} does not match its frontmatter name {declared}"
                )));
            }
            _ => {
                return Err(invalid(format!(
                    "Skill {name} frontmatter has no string name"
                )));
            }
        }
        if !matches!(frontmatter.get("description"), Some(Value::String(_))) {
            return Err(invalid(format!(
                "Skill {name} frontmatter has no string description"
            )));
        }
        self.skills.insert(
            name.to_string(),
            StoredSkill {
                frontmatter,
                files: stored,
            },
        );
        Ok(self)
    }

    /// Builds the bundle published by default for a CLI: one skill per
    /// generated command group, as `skills add` installs them, followed by one
    /// skill per shipped Prompt Guide.
    pub(crate) fn generated(
        skill_files: &[crate::skill::SkillFile],
        guides: &[crate::prompt::PromptGuide],
    ) -> Result<Self, MulticastError> {
        let mut bundle = Self::new();
        for file in skill_files {
            // `skills add` writes the generated content followed by a newline;
            // serve the same bytes so digests agree with installed files.
            let text = format!("{}\n", file.content);
            let name = parse_frontmatter(&text)
                .ok()
                .and_then(|frontmatter| {
                    frontmatter
                        .get("name")
                        .and_then(Value::as_str)
                        .map(str::to_string)
                })
                .ok_or_else(|| invalid(format!("Generated skill {} has no name", file.dir)))?;
            bundle.add(&name, [McpSkillFile::new("SKILL.md", text)])?;
        }
        for guide in guides {
            let name = slug(&guide.name);
            bundle.add(
                &name,
                [McpSkillFile::new("SKILL.md", guide_markdown(&name, guide))],
            )?;
        }
        Ok(bundle)
    }

    fn entry(&self, name: &str, skill: &StoredSkill) -> Value {
        let resources = skill
            .files
            .iter()
            .map(|(path, file)| {
                json!({
                    "uri": file_uri(name, path),
                    "digest": file.digest,
                    "size": file.content.as_bytes().len(),
                })
            })
            .collect::<Vec<_>>();
        json!({
            "uri": file_uri(name, "SKILL.md"),
            "frontmatter": skill.frontmatter,
            "resources": resources,
        })
    }

    /// Answers `skills/list`. Each entry is complete; pages never split one.
    pub(crate) fn list(&self, cursor: Option<&str>) -> Result<Value, McpResourceError> {
        let start = match cursor {
            None => None,
            Some(cursor) => {
                let name = cursor
                    .strip_prefix("skill:")
                    .filter(|name| self.skills.contains_key(*name))
                    .ok_or_else(|| invalid_params("Invalid skills/list cursor"))?;
                Some(name)
            }
        };
        let mut remaining = match start {
            Some(name) => self
                .skills
                .range::<str, _>((Bound::Included(name), Bound::Unbounded)),
            None => self.skills.range::<str, _>(..),
        };
        let skills = remaining
            .by_ref()
            .take(self.page_size)
            .map(|(name, skill)| self.entry(name, skill))
            .collect::<Vec<_>>();
        let mut result = cached(json!({ "skills": skills }));
        if let Some((next, _)) = remaining.next() {
            result["nextCursor"] = json!(format!("skill:{next}"));
        }
        Ok(result)
    }

    /// Answers `skills/get` for a skill's `SKILL.md` URI.
    pub(crate) fn get(&self, uri: &str) -> Result<Value, McpResourceError> {
        let (name, path) = split_uri(uri).ok_or_else(|| unknown_skill(uri))?;
        if path != "SKILL.md" {
            return Err(unknown_skill(uri));
        }
        let skill = self.skills.get(name).ok_or_else(|| unknown_skill(uri))?;
        Ok(cached(json!({ "skill": self.entry(name, skill) })))
    }

    /// Reads one published file, or returns `None` when the URI does not name
    /// a published file.
    pub(crate) fn read(&self, uri: &str) -> Option<Value> {
        let (name, path) = split_uri(uri)?;
        let file = self.skills.get(name)?.files.get(path)?;
        let content = match &file.content {
            McpSkillContent::Text(text) => json!({
                "uri": uri,
                "mimeType": file.mime_type,
                "text": text,
            }),
            McpSkillContent::Binary(bytes) => json!({
                "uri": uri,
                "mimeType": file.mime_type,
                "blob": encode_base64(bytes),
            }),
        };
        Some(cached(json!({ "contents": [content] })))
    }

    /// Answers `resources/directory/read` with the direct children of a skill
    /// directory.
    pub(crate) fn read_directory(
        &self,
        uri: &str,
        cursor: Option<&str>,
    ) -> Result<Value, McpResourceError> {
        let rest = uri
            .strip_prefix(SKILL_URI_SCHEME)
            .filter(|rest| !rest.is_empty() && !rest.ends_with('/'))
            .ok_or_else(|| invalid_directory(uri))?;
        let (name, prefix) = match rest.split_once('/') {
            Some((name, dir)) => (name, format!("{dir}/")),
            None => (rest, String::new()),
        };
        let skill = self
            .skills
            .get(name)
            .ok_or_else(|| invalid_directory(uri))?;
        let mut children: BTreeMap<String, Value> = BTreeMap::new();
        let mut directories = BTreeSet::new();
        for (path, file) in &skill.files {
            let Some(relative) = path.strip_prefix(prefix.as_str()) else {
                continue;
            };
            match relative.split_once('/') {
                Some((child, _)) => {
                    directories.insert(child.to_string());
                }
                None => {
                    children.insert(
                        relative.to_string(),
                        json!({
                            "uri": file_uri(name, path),
                            "name": relative,
                            "mimeType": file.mime_type,
                        }),
                    );
                }
            }
        }
        if children.is_empty() && directories.is_empty() {
            return Err(invalid_directory(uri));
        }
        for child in directories {
            children.insert(
                child.clone(),
                json!({
                    "uri": format!("{uri}/{child}"),
                    "name": child,
                    "mimeType": DIRECTORY_MIME,
                }),
            );
        }
        let start = match cursor {
            None => None,
            Some(cursor) => Some(
                cursor
                    .strip_prefix("child:")
                    .filter(|child| children.contains_key(*child))
                    .ok_or_else(|| invalid_params("Invalid resources/directory/read cursor"))?
                    .to_string(),
            ),
        };
        let mut remaining = match &start {
            Some(child) => {
                children.range::<str, _>((Bound::Included(child.as_str()), Bound::Unbounded))
            }
            None => children.range::<str, _>(..),
        };
        let resources = remaining
            .by_ref()
            .take(self.page_size)
            .map(|(_, value)| value.clone())
            .collect::<Vec<_>>();
        let mut result = cached(json!({ "resources": resources }));
        if let Some((next, _)) = remaining.next() {
            result["nextCursor"] = json!(format!("child:{next}"));
        }
        Ok(result)
    }

    /// Lists every published file as an ordinary resource, so clients without
    /// the extension can still read skill content.
    pub(crate) fn resources(&self) -> impl Iterator<Item = Value> + '_ {
        self.skills.iter().flat_map(|(name, skill)| {
            skill.files.iter().map(move |(path, file)| {
                json!({
                    "uri": file_uri(name, path),
                    "name": format!("{name}/{path}"),
                    "mimeType": file.mime_type,
                    "size": file.content.as_bytes().len(),
                })
            })
        })
    }
}

/// Encodes bytes as RFC 4648 base64 with padding.
pub(crate) fn encode_base64(bytes: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
    let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);
    for chunk in bytes.chunks(3) {
        let value = chunk.iter().enumerate().fold(0u32, |value, (index, byte)| {
            value | (u32::from(*byte) << (16 - 8 * index))
        });
        for index in 0..4 {
            if index <= chunk.len() {
                out.push(char::from(
                    ALPHABET[(value >> (18 - 6 * index)) as usize & 63],
                ));
            } else {
                out.push('=');
            }
        }
    }
    out
}

/// Strict RFC 4648 base64 with padding, rejecting non-canonical trailing bits.
pub(crate) fn decode_base64(input: &str) -> Option<Vec<u8>> {
    fn sextet(byte: u8) -> Option<u32> {
        Some(match byte {
            b'A'..=b'Z' => byte - b'A',
            b'a'..=b'z' => byte - b'a' + 26,
            b'0'..=b'9' => byte - b'0' + 52,
            b'+' => 62,
            b'/' => 63,
            _ => return None,
        } as u32)
    }
    let bytes = input.as_bytes();
    if !bytes.len().is_multiple_of(4) {
        return None;
    }
    let mut out = Vec::with_capacity(bytes.len() / 4 * 3);
    let chunks = bytes.len() / 4;
    for (index, chunk) in bytes.chunks(4).enumerate() {
        let padding = chunk.iter().rev().take_while(|byte| **byte == b'=').count();
        if padding > 2 || (padding > 0 && index + 1 != chunks) {
            return None;
        }
        let mut value = 0u32;
        for byte in &chunk[..4 - padding] {
            value = (value << 6) | sextet(*byte)?;
        }
        value <<= 6 * padding as u32;
        let decoded = [(value >> 16) as u8, (value >> 8) as u8, value as u8];
        let kept = 3 - padding;
        if decoded[kept..].iter().any(|byte| *byte != 0) {
            return None;
        }
        out.extend_from_slice(&decoded[..kept]);
    }
    Some(out)
}

/// Lowercase hex of a digest.
pub(crate) fn sha256_hex(digest: impl AsRef<[u8]>) -> String {
    use std::fmt::Write as _;
    digest.as_ref().iter().fold(String::new(), |mut out, byte| {
        let _ = write!(out, "{byte:02x}");
        out
    })
}

fn cached(mut value: Value) -> Value {
    value["resultType"] = json!("complete");
    value["ttlMs"] = json!(SKILL_TTL_MS);
    value["cacheScope"] = json!("public");
    value
}

fn file_uri(name: &str, path: &str) -> String {
    format!("{SKILL_URI_SCHEME}{name}/{path}")
}

fn split_uri(uri: &str) -> Option<(&str, &str)> {
    uri.strip_prefix(SKILL_URI_SCHEME)?.split_once('/')
}

fn invalid(message: String) -> MulticastError {
    MulticastError {
        message,
        code: SKILL_INVALID.to_string(),
        hint: Some(
            "Skill names are 1-64 lowercase letters, digits, and single hyphens, and must equal the SKILL.md frontmatter name."
                .to_string(),
        ),
        retryable: false,
        exit_code: None,
        cause: None,
    }
}

fn invalid_params(message: &str) -> McpResourceError {
    McpResourceError {
        code: INVALID_PARAMS,
        message: message.to_string(),
        data: None,
    }
}

fn unknown_skill(uri: &str) -> McpResourceError {
    McpResourceError {
        code: INVALID_PARAMS,
        message: format!("Unknown skill: {uri}"),
        data: Some(json!({ "uri": uri })),
    }
}

fn invalid_directory(uri: &str) -> McpResourceError {
    McpResourceError {
        code: INVALID_PARAMS,
        message: format!("Invalid skill directory: {uri}"),
        data: Some(json!({ "uri": uri })),
    }
}

fn validate_name(name: &str) -> Result<(), MulticastError> {
    let valid = !name.is_empty()
        && name.len() <= MAX_SKILL_NAME_LEN
        && name
            .bytes()
            .all(|byte| byte.is_ascii_lowercase() || byte.is_ascii_digit() || byte == b'-')
        && !name.starts_with('-')
        && !name.ends_with('-')
        && !name.contains("--");
    if valid {
        Ok(())
    } else {
        Err(invalid(format!("Invalid MCP skill name: {name:?}")))
    }
}

fn validate_path(name: &str, path: &str) -> Result<(), MulticastError> {
    let valid = !path.is_empty()
        && !path.contains('\\')
        && path
            .split('/')
            .all(|segment| !segment.is_empty() && segment != "." && segment != "..");
    if valid {
        Ok(())
    } else {
        Err(invalid(format!(
            "Skill {name} has an invalid file path: {path:?}"
        )))
    }
}

fn mime_for(path: &str) -> &'static str {
    match path.rsplit_once('.').map(|(_, extension)| extension) {
        Some("md" | "markdown") => "text/markdown",
        Some("json") => "application/json",
        Some("yaml" | "yml") => "application/yaml",
        Some("html" | "htm") => "text/html",
        Some("py") => "text/x-python",
        Some("sh") => "text/x-shellscript",
        Some("js" | "mjs") => "text/javascript",
        Some("png") => "image/png",
        Some("jpg" | "jpeg") => "image/jpeg",
        Some("gif") => "image/gif",
        Some("webp") => "image/webp",
        Some("svg") => "image/svg+xml",
        Some("pdf") => "application/pdf",
        Some("zip") => "application/zip",
        _ => "text/plain",
    }
}

/// Converts a Prompt Guide name to a skill name.
fn slug(value: &str) -> String {
    let mut slug = String::with_capacity(value.len());
    for character in value.chars().flat_map(char::to_lowercase) {
        if character.is_ascii_lowercase() || character.is_ascii_digit() {
            slug.push(character);
        } else if !slug.is_empty() && !slug.ends_with('-') {
            slug.push('-');
        }
    }
    while slug.ends_with('-') {
        slug.pop();
    }
    slug
}

fn guide_markdown(name: &str, guide: &crate::prompt::PromptGuide) -> String {
    let description = Value::String(guide.summary.clone()).to_string();
    let instructions = guide.instructions.trim_end();
    format!("---\nname: {name}\ndescription: {description}\n---\n\n{instructions}\n")
}

/// Parses the flat `key: value` YAML frontmatter that opens a `SKILL.md`.
///
/// Values may be plain, single-quoted, or double-quoted scalars; nested
/// mappings, sequences, and block scalars are rejected rather than guessed at.
pub(crate) fn parse_frontmatter(text: &str) -> Result<Map<String, Value>, String> {
    let mut lines = text.split('\n');
    if lines.next().map(|line| line.trim_end_matches('\r')) != Some("---") {
        return Err("SKILL.md must begin with YAML frontmatter".to_string());
    }
    let mut frontmatter = Map::new();
    for line in lines {
        let line = line.trim_end_matches('\r');
        if line == "---" {
            return Ok(frontmatter);
        }
        if line.trim().is_empty() || line.trim_start().starts_with('#') {
            continue;
        }
        if line.starts_with([' ', '\t', '-']) {
            return Err(format!("unsupported frontmatter line: {line:?}"));
        }
        let (key, value) = line
            .split_once(':')
            .ok_or_else(|| format!("frontmatter line is not key: value: {line:?}"))?;
        let key = key.trim();
        let value = value.trim();
        let value = if value.starts_with('"') {
            serde_json::from_str::<String>(value)
                .map_err(|_| format!("invalid double-quoted value for {key}"))?
        } else if let Some(inner) = value.strip_prefix('\'') {
            inner
                .strip_suffix('\'')
                .ok_or_else(|| format!("unterminated single-quoted value for {key}"))?
                .replace("''", "'")
        } else if value.is_empty() || value.starts_with(['|', '>', '[', '{']) {
            return Err(format!("unsupported frontmatter value for {key}"));
        } else {
            value.to_string()
        };
        if frontmatter
            .insert(key.to_string(), Value::String(value))
            .is_some()
        {
            return Err(format!("duplicate frontmatter key {key}"));
        }
    }
    Err("SKILL.md frontmatter is not closed".to_string())
}

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

    fn bundle() -> McpSkillBundle {
        let mut bundle = McpSkillBundle::new();
        bundle
            .add(
                "code-review",
                [
                    McpSkillFile::new(
                        "SKILL.md",
                        "---\nname: code-review\ndescription: Review code using the team's checklist.\n---\n\n# Code review\n\nRead `references/checklist.md`, then review the diff.\n",
                    ),
                    McpSkillFile::new(
                        "references/checklist.md",
                        "# Review checklist\n\nCheck correctness, tests, and compatibility.\n",
                    ),
                ],
            )
            .unwrap();
        bundle
    }

    #[test]
    fn manifest_matches_the_specification_example() {
        // Digests and sizes were computed outside this crate with
        // `shasum -a 256` and `wc -c` over the same file bytes.
        let listing = bundle().list(None).unwrap();
        assert_eq!(
            listing,
            json!({
                "resultType": "complete",
                "skills": [{
                    "uri": "skill://code-review/SKILL.md",
                    "frontmatter": {
                        "name": "code-review",
                        "description": "Review code using the team's checklist."
                    },
                    "resources": [
                        {
                            "uri": "skill://code-review/SKILL.md",
                            "digest": "sha256:d2489d6c182e8df9c178563ff9f2eac7998a0c1bb1278c52a7fd5306e4259160",
                            "size": 149
                        },
                        {
                            "uri": "skill://code-review/references/checklist.md",
                            "digest": "sha256:dbab2de7bf7db9cc95cb6ce681c3690b26184db39f75b958a0287ca6d9e24e20",
                            "size": 65
                        }
                    ]
                }],
                "ttlMs": 300000,
                "cacheScope": "public"
            })
        );
    }

    #[test]
    fn binary_files_are_served_as_blobs_with_byte_manifests() {
        // Digest and base64 computed outside this crate with Python's hashlib
        // and base64 over the bytes 89 50 4e 47 00 01 02 ff.
        let mut bundle = bundle();
        let skill_md = "---\nname: assets\ndescription: d\n---\n";
        bundle
            .add(
                "assets",
                [
                    McpSkillFile::new("SKILL.md", skill_md),
                    McpSkillFile::binary(
                        "logo.png",
                        [0x89, 0x50, 0x4e, 0x47, 0x00, 0x01, 0x02, 0xff],
                    ),
                    McpSkillFile::binary("data.bin", [0_u8]),
                ],
            )
            .unwrap();
        let listing = bundle.get("skill://assets/SKILL.md").unwrap();
        assert_eq!(
            // Files are listed in path order: SKILL.md, data.bin, logo.png.
            listing["skill"]["resources"][2],
            json!({
                "uri": "skill://assets/logo.png",
                "digest": "sha256:5ec770aa8b97e5faafa2f01dcab2aed7d090c5685a47c4bc90db867b9bf6c3a4",
                "size": 8
            })
        );
        assert_eq!(
            bundle.read("skill://assets/logo.png").unwrap()["contents"],
            json!([{
                "uri": "skill://assets/logo.png",
                "mimeType": "image/png",
                "blob": "iVBORwABAv8="
            }])
        );
        assert_eq!(
            bundle.read("skill://assets/data.bin").unwrap()["contents"][0]["mimeType"],
            "application/octet-stream"
        );
        let error = McpSkillBundle::new()
            .add(
                "binary",
                [McpSkillFile::binary("SKILL.md", skill_md.as_bytes())],
            )
            .unwrap_err();
        assert!(error.to_string().contains("binary SKILL.md"), "{error}");
    }

    #[test]
    fn base64_round_trips_every_length_and_rejects_noncanonical_input() {
        // Expected encodings from RFC 4648 section 10.
        for (plain, encoded) in [
            ("", ""),
            ("f", "Zg=="),
            ("fo", "Zm8="),
            ("foo", "Zm9v"),
            ("foob", "Zm9vYg=="),
            ("fooba", "Zm9vYmE="),
            ("foobar", "Zm9vYmFy"),
        ] {
            assert_eq!(encode_base64(plain.as_bytes()), encoded);
            assert_eq!(decode_base64(encoded).unwrap(), plain.as_bytes());
        }
        for bad in ["Zg=", "Zh==", "Zm9v=", "Z===", "Zm8=Zm8="] {
            assert_eq!(decode_base64(bad), None, "{bad}");
        }
    }

    #[test]
    fn directory_read_lists_direct_children_only() {
        let bundle = bundle();
        assert_eq!(
            bundle.read_directory("skill://code-review", None).unwrap()["resources"],
            json!([
                {"uri": "skill://code-review/SKILL.md", "name": "SKILL.md", "mimeType": "text/markdown"},
                {"uri": "skill://code-review/references", "name": "references", "mimeType": "inode/directory"}
            ])
        );
        assert_eq!(
            bundle
                .read_directory("skill://code-review/references", None)
                .unwrap()["resources"],
            json!([{
                "uri": "skill://code-review/references/checklist.md",
                "name": "checklist.md",
                "mimeType": "text/markdown"
            }])
        );
        for uri in [
            "skill://code-review/",
            "skill://code-review/missing",
            "skill://other",
            "skill://code-review/SKILL.md",
        ] {
            assert_eq!(
                bundle.read_directory(uri, None).unwrap_err().code,
                -32602,
                "{uri}"
            );
        }
    }

    #[test]
    fn pages_hold_whole_entries_and_resume_from_the_cursor() {
        let mut bundle = McpSkillBundle::new().with_page_size(2);
        for name in ["alpha", "bravo", "charlie", "delta", "echo"] {
            bundle
                .add(
                    name,
                    [
                        McpSkillFile::new(
                            "SKILL.md",
                            format!("---\nname: {name}\ndescription: d\n---\n"),
                        ),
                        McpSkillFile::new("extra.md", "x"),
                    ],
                )
                .unwrap();
        }
        let mut seen = Vec::new();
        let mut cursor: Option<String> = None;
        let mut pages = 0;
        loop {
            let page = bundle.list(cursor.as_deref()).unwrap();
            pages += 1;
            for skill in page["skills"].as_array().unwrap() {
                assert_eq!(skill["resources"].as_array().unwrap().len(), 2);
                seen.push(skill["frontmatter"]["name"].as_str().unwrap().to_string());
            }
            match page.get("nextCursor") {
                Some(next) => cursor = Some(next.as_str().unwrap().to_string()),
                None => break,
            }
        }
        assert_eq!(pages, 3);
        assert_eq!(seen, ["alpha", "bravo", "charlie", "delta", "echo"]);
        assert_eq!(bundle.list(Some("bogus")).unwrap_err().code, -32602);
    }

    #[test]
    fn get_and_read_agree_with_the_manifest() {
        let bundle = bundle();
        let entry = bundle.get("skill://code-review/SKILL.md").unwrap();
        for resource in entry["skill"]["resources"].as_array().unwrap() {
            let uri = resource["uri"].as_str().unwrap();
            let read = bundle.read(uri).unwrap();
            let text = read["contents"][0]["text"].as_str().unwrap();
            assert_eq!(resource["size"], json!(text.len()));
            assert_eq!(
                resource["digest"],
                json!(format!(
                    "sha256:{}",
                    sha256_hex(Sha256::digest(text.as_bytes()))
                ))
            );
        }
        assert_eq!(
            bundle
                .get("skill://code-review/references/checklist.md")
                .unwrap_err()
                .code,
            -32602
        );
        assert_eq!(
            bundle.get("skill://missing/SKILL.md").unwrap_err().code,
            -32602
        );
        assert!(bundle.read("skill://code-review/missing.md").is_none());
    }

    #[test]
    fn invalid_skills_are_rejected_before_serving() {
        let skill_md = |name: &str| {
            McpSkillFile::new(
                "SKILL.md",
                format!("---\nname: {name}\ndescription: d\n---\n"),
            )
        };
        let mut bundle = McpSkillBundle::new();
        bundle.add("ok", [skill_md("ok")]).unwrap();
        let cases: Vec<(&str, Vec<McpSkillFile>)> = vec![
            ("ok", vec![skill_md("ok")]),
            ("Upper", vec![skill_md("Upper")]),
            ("dir", vec![skill_md("other")]),
            ("no-skill", vec![McpSkillFile::new("README.md", "x")]),
            (
                "escape",
                vec![skill_md("escape"), McpSkillFile::new("../x.md", "x")],
            ),
            (
                "no-description",
                vec![McpSkillFile::new(
                    "SKILL.md",
                    "---\nname: no-description\n---\n",
                )],
            ),
            (
                "unclosed",
                vec![McpSkillFile::new(
                    "SKILL.md",
                    "---\nname: unclosed\ndescription: d\n",
                )],
            ),
            ("trailing-", vec![skill_md("trailing-")]),
        ];
        for (name, files) in cases {
            let error = bundle.add(name, files).unwrap_err();
            assert_eq!(error.code, SKILL_INVALID, "{name}");
        }
        let too_many = std::iter::once(skill_md("many"))
            .chain((0..MAX_SKILL_FILES).map(|index| McpSkillFile::new(format!("f{index}.md"), "")))
            .collect::<Vec<_>>();
        assert_eq!(
            bundle.add("many", too_many).unwrap_err().code,
            SKILL_INVALID
        );
        let too_big = vec![
            skill_md("big"),
            McpSkillFile::new("big.txt", "x".repeat(MAX_SKILL_BYTES)),
        ];
        assert_eq!(bundle.add("big", too_big).unwrap_err().code, SKILL_INVALID);
        assert_eq!(bundle.names().collect::<Vec<_>>(), ["ok"]);
    }

    #[test]
    fn frontmatter_keeps_every_field() {
        let frontmatter = parse_frontmatter(
            "---\nname: x\ndescription: \"quoted \\\"text\\\"\"\nrequires_bin: tool\ncommand: 'it''s'\n---\nbody",
        )
        .unwrap();
        assert_eq!(
            Value::Object(frontmatter),
            json!({"name": "x", "description": "quoted \"text\"", "requires_bin": "tool", "command": "it's"})
        );
    }

    #[test]
    fn prompt_guides_become_skills() {
        let guide = crate::prompt::PromptGuide::new(
            "Release_Notes",
            "Write release notes.",
            "Use the log.",
            ["log"],
        );
        let bundle = McpSkillBundle::generated(&[], &[guide]).unwrap();
        let read = bundle.read("skill://release-notes/SKILL.md").unwrap();
        assert_eq!(
            read["contents"][0]["text"],
            json!(
                "---\nname: release-notes\ndescription: \"Write release notes.\"\n---\n\nUse the log.\n"
            )
        );
    }
}