Skip to main content

a2a_protocol_server/skills/
catalog.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`Skill`] and [`SkillCatalog`]: what discovery found, the prompt that
5//! announces it, and the tools that serve it.
6
7use std::fmt;
8use std::path::PathBuf;
9use std::sync::Arc;
10
11use a2a_protocol_types::agent_card::AgentSkill;
12
13use super::config::{SkillScope, SkillsConfig};
14use super::diagnostic::SkillDiagnostic;
15use super::discover;
16use super::tools::{ActivateSkillTool, ReadSkillFileTool};
17use crate::tool_loop::Tool;
18
19/// The tag on the [`AgentSkill`] a skill is advertised as.
20pub const AGENT_SKILL_TAG: &str = "agent-skill";
21
22/// One skill: a directory with a `SKILL.md`, read at discovery.
23#[derive(Clone)]
24pub struct Skill {
25    pub(super) name: String,
26    pub(super) description: String,
27    pub(super) catalog_description: String,
28    /// Whether the catalog shows less of the description than there is.
29    pub(super) shortened: bool,
30    pub(super) license: Option<String>,
31    pub(super) compatibility: Option<String>,
32    pub(super) allowed_tools: Option<String>,
33    pub(super) metadata: Vec<(String, String)>,
34    pub(super) body: String,
35    pub(super) scope: SkillScope,
36    /// The directory as it was configured, for reporting.
37    pub(super) directory: PathBuf,
38    /// The directory resolved, which every read is confined to.
39    pub(super) root: PathBuf,
40    /// Files under `references/` and `assets/`, as `references/a.md`.
41    pub(super) resources: Vec<String>,
42    /// Files under `scripts/`: present, and never run.
43    pub(super) scripts: Vec<String>,
44}
45
46impl fmt::Debug for Skill {
47    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48        f.debug_struct("Skill")
49            .field("name", &self.name)
50            .field("scope", &self.scope)
51            .field("location", &self.location())
52            .finish_non_exhaustive()
53    }
54}
55
56impl Skill {
57    /// The skill's name: the frontmatter's `name`, which is the key the
58    /// catalog and `activate_skill` use.
59    #[must_use]
60    pub fn name(&self) -> &str {
61        &self.name
62    }
63
64    /// The description, whole, as the frontmatter has it. The prompt's
65    /// catalog shows a shortened one; see
66    /// [`SkillsConfig::with_max_description_chars`].
67    #[must_use]
68    pub fn description(&self) -> &str {
69        &self.description
70    }
71
72    /// The path of the skill's `SKILL.md`, under the directory as it was
73    /// configured.
74    #[must_use]
75    pub fn location(&self) -> PathBuf {
76        self.directory.join("SKILL.md")
77    }
78
79    /// Where the skill came from.
80    #[must_use]
81    pub const fn scope(&self) -> SkillScope {
82        self.scope
83    }
84
85    /// The instructions: `SKILL.md` after the frontmatter, trimmed.
86    #[must_use]
87    pub fn body(&self) -> &str {
88        &self.body
89    }
90
91    /// The `license` field, when there is one.
92    #[must_use]
93    pub fn license(&self) -> Option<&str> {
94        self.license.as_deref()
95    }
96
97    /// The `compatibility` field, when there is one.
98    #[must_use]
99    pub fn compatibility(&self) -> Option<&str> {
100        self.compatibility.as_deref()
101    }
102
103    /// The `metadata` field's keys and values, in file order.
104    #[must_use]
105    pub fn metadata(&self) -> &[(String, String)] {
106        &self.metadata
107    }
108
109    /// The `allowed-tools` field, recorded. It is experimental in the
110    /// specification and this module never acts on it: no skill adds a tool
111    /// to the loop or approves one.
112    #[must_use]
113    pub fn allowed_tools(&self) -> Option<&str> {
114        self.allowed_tools.as_deref()
115    }
116
117    /// The files `read_skill_file` can return, as `references/a.md`.
118    #[must_use]
119    pub fn resources(&self) -> &[String] {
120        &self.resources
121    }
122
123    /// The files under `scripts/`, which are listed to the model as present
124    /// and never run.
125    #[must_use]
126    pub fn scripts(&self) -> &[String] {
127        &self.scripts
128    }
129}
130
131struct Inner {
132    skills: Vec<Skill>,
133    diagnostics: Vec<SkillDiagnostic>,
134    max_resource_bytes: usize,
135}
136
137/// The skills found in the configured directories, and what was noticed on
138/// the way.
139///
140/// Cheap to clone: the skills are shared. Built once, at start-up, by
141/// [`discover`](Self::discover); it does not change afterwards, so the prompt
142/// and the tools' schemas stay what the model was told. To pick up changed
143/// files, discover again and build a new executor.
144///
145/// ```no_run
146/// use a2a_protocol_server::skills::{SkillCatalog, SkillSource, SkillsConfig};
147///
148/// let catalog = SkillCatalog::discover(
149///     &SkillsConfig::new().with_source(SkillSource::operator("/etc/my-agent/skills")),
150/// );
151/// for problem in catalog.diagnostics() {
152///     eprintln!("{problem}");
153/// }
154/// println!("{} skills", catalog.len());
155/// ```
156#[derive(Clone)]
157pub struct SkillCatalog {
158    inner: Arc<Inner>,
159}
160
161impl fmt::Debug for SkillCatalog {
162    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163        f.debug_struct("SkillCatalog")
164            .field(
165                "skills",
166                &self
167                    .inner
168                    .skills
169                    .iter()
170                    .map(Skill::name)
171                    .collect::<Vec<_>>(),
172            )
173            .field("diagnostics", &self.inner.diagnostics.len())
174            .finish()
175    }
176}
177
178impl SkillCatalog {
179    /// Reads the skills `config` names.
180    ///
181    /// Never fails and never panics: a directory that cannot be read, a
182    /// `SKILL.md` that is malformed, a name that is taken, are each a
183    /// [`SkillDiagnostic`] and the rest is still loaded. It reads files, so
184    /// call it at start-up, or from a blocking task.
185    #[must_use]
186    pub fn discover(config: &SkillsConfig) -> Self {
187        let (skills, diagnostics) = discover::discover(config);
188        Self {
189            inner: Arc::new(Inner {
190                skills,
191                diagnostics,
192                max_resource_bytes: config.max_resource_bytes,
193            }),
194        }
195    }
196
197    /// The skills, operator directories first, each directory's in name order.
198    #[must_use]
199    pub fn skills(&self) -> &[Skill] {
200        &self.inner.skills
201    }
202
203    /// The skill named `name`.
204    #[must_use]
205    pub fn get(&self, name: &str) -> Option<&Skill> {
206        self.inner.skills.iter().find(|skill| skill.name == name)
207    }
208
209    /// How many skills there are.
210    #[must_use]
211    pub fn len(&self) -> usize {
212        self.inner.skills.len()
213    }
214
215    /// Whether there are none.
216    #[must_use]
217    pub fn is_empty(&self) -> bool {
218        self.inner.skills.is_empty()
219    }
220
221    /// What discovery noticed, in the order it noticed it. Log it:
222    /// [`SkillDiagnostic`] is `Display`, and a skill that is missing from the
223    /// catalog is explained here and nowhere else.
224    #[must_use]
225    pub fn diagnostics(&self) -> &[SkillDiagnostic] {
226        &self.inner.diagnostics
227    }
228
229    pub(super) fn max_resource_bytes(&self) -> usize {
230        self.inner.max_resource_bytes
231    }
232
233    /// Whether any skill bundles a file `read_skill_file` can return.
234    pub(super) fn has_resources(&self) -> bool {
235        self.inner
236            .skills
237            .iter()
238            .any(|skill| !skill.resources.is_empty())
239    }
240
241    /// The catalog as the model is told it: a short instruction and each
242    /// skill's name and description, in the form the specification's client
243    /// guide shows. `None` when there are no skills, because an empty catalog
244    /// would only confuse the model.
245    ///
246    /// A description is on one line, shortened to the configured length,
247    /// and XML-escaped, so it cannot close the element it is in. A project
248    /// skill is marked `<origin>project</origin>`.
249    #[must_use]
250    pub fn prompt(&self) -> Option<String> {
251        if self.is_empty() {
252            return None;
253        }
254        let mut out = String::from(
255            "The following skills provide specialized instructions for specific tasks.\n\
256             When a task matches a skill's description, call the activate_skill tool with \
257             the skill's name to load its full instructions before you proceed.\n",
258        );
259        if self.has_resources() {
260            out.push_str(
261                "A skill may bundle files under references/ and assets/; read one with the \
262                 read_skill_file tool, naming the skill and the path relative to its directory.\n",
263            );
264        }
265        out.push_str("Skill scripts are never run by this agent.\n\n<available_skills>\n");
266        for skill in &self.inner.skills {
267            out.push_str("<skill>\n<name>");
268            out.push_str(&xml_escape(&skill.name));
269            out.push_str("</name>\n<description>");
270            out.push_str(&xml_escape(&skill.catalog_description));
271            out.push_str("</description>\n");
272            if skill.scope == SkillScope::Project {
273                out.push_str("<origin>project</origin>\n");
274            }
275            out.push_str("</skill>\n");
276        }
277        out.push_str("</available_skills>");
278        Some(out)
279    }
280
281    /// The tools that serve the catalog: `activate_skill`, and
282    /// `read_skill_file` when some skill bundles files. None at all when the
283    /// catalog is empty, because a tool whose `name` has no valid value
284    /// would confuse the model.
285    ///
286    /// [`ToolLoopExecutor::with_skills`](crate::tool_loop::ToolLoopExecutor::with_skills)
287    /// adds these and the [`prompt`](Self::prompt); this is for a loop run
288    /// without it.
289    #[must_use]
290    pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
291        let mut tools: Vec<Arc<dyn Tool>> = Vec::new();
292        if !self.is_empty() {
293            tools.push(Arc::new(ActivateSkillTool::new(self.clone())));
294        }
295        if self.has_resources() {
296            tools.push(Arc::new(ReadSkillFileTool::new(self.clone())));
297        }
298        tools
299    }
300
301    /// Each skill as an [`AgentSkill`] for the agent card, which is public:
302    /// `id` and `name` are the skill's name, `description` is its
303    /// description whole and verbatim, and the one tag is
304    /// [`AGENT_SKILL_TAG`]. Nothing is advertised unless the card is built
305    /// from this, and a skill's description is not necessarily meant to be
306    /// public.
307    ///
308    /// ```no_run
309    /// # use a2a_protocol_server::skills::SkillCatalog;
310    /// # fn advertise(catalog: &SkillCatalog) {
311    /// use a2a_protocol_types::agent_card::{AgentCard, AgentInterface};
312    ///
313    /// let mut card = AgentCard::new("agent", "1.0.0", AgentInterface::jsonrpc("http://127.0.0.1:3000"));
314    /// for skill in catalog.agent_skills() {
315    ///     card = card.with_skill(skill);
316    /// }
317    /// # drop(card); }
318    /// ```
319    #[must_use]
320    pub fn agent_skills(&self) -> Vec<AgentSkill> {
321        self.inner
322            .skills
323            .iter()
324            .map(|skill| {
325                AgentSkill::new(&skill.name, &skill.name, &skill.description)
326                    .with_tags([AGENT_SKILL_TAG])
327            })
328            .collect()
329    }
330}
331
332/// `text` with each run of white space one space, so a description cannot
333/// lay out lines of its own in a prompt.
334pub(super) fn collapse_whitespace(text: &str) -> String {
335    text.split_whitespace().collect::<Vec<_>>().join(" ")
336}
337
338/// `text` cut to at most `max` characters, the last an ellipsis when it was
339/// cut; and whether it was. `0` is taken as `1`.
340pub(super) fn shorten(text: &str, max: usize) -> (String, bool) {
341    let max = max.max(1);
342    if text.chars().count() <= max {
343        return (text.to_owned(), false);
344    }
345    let mut cut: String = text.chars().take(max - 1).collect();
346    cut.truncate(cut.trim_end().len());
347    cut.push('…');
348    (cut, true)
349}
350
351/// `text` safe inside an XML element.
352pub(super) fn xml_escape(text: &str) -> String {
353    let mut out = String::with_capacity(text.len());
354    for c in text.chars() {
355        match c {
356            '&' => out.push_str("&amp;"),
357            '<' => out.push_str("&lt;"),
358            '>' => out.push_str("&gt;"),
359            other => out.push(other),
360        }
361    }
362    out
363}
364
365#[cfg(test)]
366#[path = "catalog_tests.rs"]
367mod tests;