Skip to main content

rinne_types/
skill.rs

1//! Agent Skills (`MCP_SKILLS.md` ยง11).
2//!
3//! A skill is a folder with a `SKILL.md`: YAML-ish frontmatter (`name`,
4//! `description`, optional `allowed-tools`) plus a markdown body of instructions,
5//! and optionally bundled scripts. The format follows Anthropic Agent Skills so
6//! existing skills work as-is, and it is model-agnostic โ€” usable by any worker.
7//!
8//! Progressive disclosure: the conductor sees only the cheap [`Skill::summary`]
9//! (name + description); the full [`Skill::body`] loads only when a skill is
10//! attached to a node and that node runs.
11
12use std::path::PathBuf;
13
14use serde::Serialize;
15
16/// One installed skill.
17#[derive(Debug, Clone, Serialize)]
18pub struct Skill {
19    /// Unique skill name (from frontmatter, else the folder name).
20    pub name: String,
21    /// One-line description โ€” the cheap layer the conductor plans over.
22    pub description: String,
23    /// Tools the skill declares it may use (optional; advisory).
24    pub allowed_tools: Vec<String>,
25    /// The instruction body injected into a worker's prompt for an attached node.
26    pub body: String,
27    /// The skill's directory (for resolving any bundled scripts).
28    pub dir: PathBuf,
29}
30
31impl Skill {
32    /// Parse a `SKILL.md`'s contents into a [`Skill`]. Pure string work โ€” the
33    /// caller does the filesystem read and passes a `fallback_name` (the folder)
34    /// for a skill whose frontmatter omits `name`.
35    pub fn parse_md(content: &str, dir: PathBuf, fallback_name: &str) -> Skill {
36        let (front, body) = split_frontmatter(content);
37        let mut name = None;
38        let mut description = String::new();
39        let mut allowed_tools = Vec::new();
40        for line in front.lines() {
41            let Some((k, v)) = line.split_once(':') else {
42                continue;
43            };
44            let val = v.trim();
45            match k.trim() {
46                "name" if !val.is_empty() => name = Some(unquote(val)),
47                "description" => description = unquote(val),
48                "allowed-tools" | "allowed_tools" => allowed_tools = parse_list(val),
49                _ => {}
50            }
51        }
52        Skill {
53            name: name.unwrap_or_else(|| fallback_name.to_string()),
54            description,
55            allowed_tools,
56            body: body.trim().to_string(),
57            dir,
58        }
59    }
60
61    /// The cheap layer the conductor sees: `name: description`.
62    pub fn summary(&self) -> String {
63        format!("{}: {}", self.name, self.description)
64    }
65}
66
67/// Split YAML-style frontmatter (between `---` fences) from the body. Returns
68/// `(frontmatter, body)`; if there is no frontmatter, the whole content is body.
69fn split_frontmatter(content: &str) -> (String, String) {
70    let content = content.trim_start_matches('\u{feff}');
71    if content.trim_start().starts_with("---") {
72        let mut started = false;
73        let mut closed = false;
74        let mut front = String::new();
75        let mut body: Vec<&str> = Vec::new();
76        for line in content.lines() {
77            if !started {
78                if line.trim() == "---" {
79                    started = true;
80                }
81                continue;
82            }
83            if !closed {
84                if line.trim() == "---" {
85                    closed = true;
86                    continue;
87                }
88                front.push_str(line);
89                front.push('\n');
90            } else {
91                body.push(line);
92            }
93        }
94        if closed {
95            return (front, body.join("\n"));
96        }
97    }
98    (String::new(), content.to_string())
99}
100
101/// Strip a single layer of matching single or double quotes.
102fn unquote(s: &str) -> String {
103    let s = s.trim();
104    for q in ['"', '\''] {
105        if s.len() >= 2 && s.starts_with(q) && s.ends_with(q) {
106            return s[1..s.len() - 1].to_string();
107        }
108    }
109    s.to_string()
110}
111
112/// Parse a frontmatter list value: `[a, b]` or `a, b`.
113fn parse_list(s: &str) -> Vec<String> {
114    s.trim()
115        .trim_start_matches('[')
116        .trim_end_matches(']')
117        .split(',')
118        .map(|t| unquote(t.trim()))
119        .filter(|t| !t.is_empty())
120        .collect()
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126
127    #[test]
128    fn parses_frontmatter_and_body() {
129        let md = "---\nname: pdf-forms\ndescription: Fill PDF forms\nallowed-tools: [read, write]\n---\n# Steps\n1. open the pdf\n";
130        let s = Skill::parse_md(md, PathBuf::from("/x"), "folder");
131        assert_eq!(s.name, "pdf-forms");
132        assert_eq!(s.description, "Fill PDF forms");
133        assert_eq!(s.allowed_tools, vec!["read", "write"]);
134        assert!(s.body.starts_with("# Steps"));
135        assert_eq!(s.summary(), "pdf-forms: Fill PDF forms");
136    }
137
138    #[test]
139    fn name_falls_back_to_folder() {
140        let s = Skill::parse_md("just a body, no frontmatter", PathBuf::from("/x"), "myskill");
141        assert_eq!(s.name, "myskill");
142        assert_eq!(s.body, "just a body, no frontmatter");
143        assert!(s.description.is_empty());
144    }
145}