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;
pub const SKILLS_EXTENSION: &str = "io.modelcontextprotocol/skills";
pub const SKILL_URI_SCHEME: &str = "skill://";
pub const SKILL_TTL_MS: u64 = 300_000;
pub const MAX_SKILL_FILES: usize = 512;
pub const MAX_SKILL_BYTES: usize = 16 * 1024 * 1024;
pub const DEFAULT_SKILL_PAGE_SIZE: usize = 100;
pub const MAX_SKILL_NAME_LEN: usize = 64;
pub const SKILL_INVALID: &str = "MCP_SKILL_INVALID";
const INVALID_PARAMS: i32 = -32602;
const DIRECTORY_MIME: &str = "inode/directory";
#[derive(Debug, Clone, Default)]
pub enum McpSkillPublication {
#[default]
Generated,
Off,
Custom(McpSkillBundle),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum McpSkillContent {
Text(String),
Binary(Vec<u8>),
}
impl McpSkillContent {
pub fn as_bytes(&self) -> &[u8] {
match self {
Self::Text(text) => text.as_bytes(),
Self::Binary(bytes) => bytes,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct McpSkillFile {
pub path: String,
pub content: McpSkillContent,
pub mime_type: String,
}
impl McpSkillFile {
pub fn new(path: impl Into<String>, text: impl Into<String>) -> Self {
Self::with_content(path.into(), McpSkillContent::Text(text.into()))
}
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,
}
}
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>,
}
#[derive(Debug, Clone)]
pub struct McpSkillBundle {
skills: BTreeMap<String, StoredSkill>,
page_size: usize,
}
impl Default for McpSkillBundle {
fn default() -> Self {
Self::new()
}
}
impl McpSkillBundle {
pub fn new() -> Self {
Self {
skills: BTreeMap::new(),
page_size: DEFAULT_SKILL_PAGE_SIZE,
}
}
pub fn with_page_size(mut self, page_size: usize) -> Self {
self.page_size = page_size.max(1);
self
}
pub fn is_empty(&self) -> bool {
self.skills.is_empty()
}
pub fn names(&self) -> impl Iterator<Item = &str> {
self.skills.keys().map(String::as_str)
}
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)
}
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 {
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,
})
}
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)
}
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) })))
}
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] })))
}
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)
}
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(),
})
})
})
}
}
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
}
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)
}
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",
}
}
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")
}
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() {
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() {
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!(
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() {
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"
)
);
}
}