Skip to main content

micromegas/servers/mcp/
skills.rs

1use anyhow::{Context, Result};
2use rmcp::handler::server::skill_catalog::SkillCatalog;
3use rmcp::model::{
4    GetSkillResult, ListSkillsResult, ReadResourceResult, Resource, ResourceContents, Skill,
5    SkillFrontmatter, SkillResource, SkillResources,
6};
7use std::path::Path;
8
9const MARKDOWN: &str = "text/markdown";
10
11const BUILTIN: &[&str] = &[
12    include_str!("skills/micromegas-query/SKILL.md"),
13    include_str!("skills/micromegas-notebooks/SKILL.md"),
14];
15
16struct BuiltinSkill {
17    skill: Skill,
18    text: &'static str,
19}
20
21/// The skills served over the MCP skills extension: the built-in ones plus those found in the
22/// optional skills directory.
23pub struct Skills {
24    builtin: Vec<BuiltinSkill>,
25    catalog: Option<SkillCatalog>,
26}
27
28/// Reads `name` and `description` from the `---` delimited frontmatter of a `SKILL.md`.
29pub fn parse_frontmatter(text: &str) -> Result<(String, String)> {
30    let mut lines = text.lines();
31    anyhow::ensure!(lines.next() == Some("---"), "missing frontmatter");
32    let (mut name, mut description) = (None, None);
33    for line in lines {
34        if line == "---" {
35            break;
36        }
37        if let Some(v) = line.strip_prefix("name:") {
38            name = Some(v.trim().to_string());
39        } else if let Some(v) = line.strip_prefix("description:") {
40            description = Some(v.trim().to_string());
41        }
42    }
43    Ok((
44        name.context("frontmatter has no name")?,
45        description.context("frontmatter has no description")?,
46    ))
47}
48
49fn skill_uri(name: &str) -> String {
50    format!("skill://{name}/SKILL.md")
51}
52
53impl Skills {
54    /// Computes the digest manifest of the built-in skills and loads `skills_dir` once.
55    pub fn new(skills_dir: Option<&Path>) -> Result<Self> {
56        let mut builtin = vec![];
57        for text in BUILTIN {
58            let (name, description) = parse_frontmatter(text)?;
59            let uri = skill_uri(&name);
60            let skill = Skill::new(
61                uri.clone(),
62                SkillFrontmatter::new(name, description),
63                SkillResources::Files(vec![SkillResource::from_bytes(uri, text.as_bytes())]),
64            );
65            skill.validate().context("invalid built-in skill")?;
66            builtin.push(BuiltinSkill { skill, text });
67        }
68        let catalog = match skills_dir {
69            Some(dir) => Some(
70                SkillCatalog::from_dir(dir)
71                    .with_context(|| format!("loading skills from {}", dir.display()))?,
72            ),
73            None => None,
74        };
75        Ok(Self { builtin, catalog })
76    }
77
78    fn is_builtin_uri(&self, uri: &str) -> bool {
79        self.builtin.iter().any(|b| b.skill.uri == uri)
80    }
81
82    /// Every skill; a directory skill never shadows a built-in one.
83    pub fn skills(&self) -> Vec<Skill> {
84        let mut skills: Vec<Skill> = self.builtin.iter().map(|b| b.skill.clone()).collect();
85        if let Some(catalog) = &self.catalog {
86            skills.extend(
87                catalog
88                    .skills()
89                    .into_iter()
90                    .filter(|s| !self.is_builtin_uri(&s.uri)),
91            );
92        }
93        skills
94    }
95
96    pub fn list_skills(&self) -> ListSkillsResult {
97        ListSkillsResult::with_all_items(self.skills())
98    }
99
100    pub fn get_skill(&self, uri: &str) -> Option<GetSkillResult> {
101        self.skills()
102            .into_iter()
103            .find(|s| s.uri == uri)
104            .map(GetSkillResult::new)
105    }
106
107    pub fn resources(&self) -> Vec<Resource> {
108        let mut resources: Vec<Resource> = self
109            .builtin
110            .iter()
111            .map(|b| {
112                Resource::new(&b.skill.uri, b.skill.name())
113                    .with_description(&b.skill.frontmatter.description)
114                    .with_mime_type(MARKDOWN)
115                    .with_size(b.text.len() as u64)
116            })
117            .collect();
118        if let Some(catalog) = &self.catalog {
119            resources.extend(
120                catalog
121                    .resources()
122                    .into_iter()
123                    .filter(|r| !self.is_builtin_uri(&r.uri)),
124            );
125        }
126        resources
127    }
128
129    pub fn read_resource(&self, uri: &str) -> Option<ReadResourceResult> {
130        if let Some(b) = self.builtin.iter().find(|b| b.skill.uri == uri) {
131            return Some(ReadResourceResult::new(vec![
132                ResourceContents::text(b.text, uri).with_mime_type(MARKDOWN),
133            ]));
134        }
135        self.catalog.as_ref()?.read_resource(uri)
136    }
137}