Skip to main content

a2a_protocol_server/skills/
tools.rs

1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! The two tools the model is given: `activate_skill` and `read_skill_file`.
5//!
6//! Each is an ordinary [`Tool`], so a call to either is traced as an
7//! `execute_tool` span, counted among the run's tool calls and bounded by the
8//! loop's turn limit like any other (ADR 0035). Both are read-only: running
9//! one again changes nothing.
10
11use std::future::Future;
12use std::pin::Pin;
13
14use serde_json::{Value, json};
15
16use super::catalog::{Skill, SkillCatalog, xml_escape};
17use super::config::SkillScope;
18use super::reader::{self, Refusal};
19use crate::tool_loop::{Tool, ToolError, ToolInvocation};
20
21/// The name of the tool that loads a skill's instructions.
22pub const ACTIVATE_SKILL_TOOL: &str = "activate_skill";
23
24/// The name of the tool that reads a file a skill bundles.
25pub const READ_SKILL_FILE_TOOL: &str = "read_skill_file";
26
27/// `activate_skill`: returns a skill's instructions and lists its files.
28///
29/// Its `name` parameter is a JSON Schema `enum` of the catalog's names, so a
30/// model cannot ask for anything else, and a name outside the catalog is
31/// refused before any file is touched (the instructions were read at
32/// discovery, so activation touches none at all).
33#[derive(Debug)]
34pub struct ActivateSkillTool {
35    catalog: SkillCatalog,
36}
37
38impl ActivateSkillTool {
39    pub(super) const fn new(catalog: SkillCatalog) -> Self {
40        Self { catalog }
41    }
42
43    fn activate(&self, arguments: &Value) -> Result<String, ToolError> {
44        let name = string_argument(arguments, "name")?;
45        let skill = skill_named(&self.catalog, name)?;
46        Ok(activation(skill))
47    }
48}
49
50impl Tool for ActivateSkillTool {
51    fn name(&self) -> &str {
52        ACTIVATE_SKILL_TOOL
53    }
54
55    fn description(&self) -> &'static str {
56        "Load the full instructions of one of the available skills. Call it when the task \
57         matches the description of a skill in the system prompt, before you act on the task. \
58         It returns the skill's instructions and the files the skill bundles."
59    }
60
61    fn parameters(&self) -> Value {
62        json!({
63            "type": "object",
64            "properties": {
65                "name": {
66                    "type": "string",
67                    "enum": names(&self.catalog, |_| true),
68                    "description": "The name of the skill to load."
69                }
70            },
71            "required": ["name"],
72            "additionalProperties": false
73        })
74    }
75
76    fn read_only(&self) -> bool {
77        true
78    }
79
80    fn call<'a>(
81        &'a self,
82        invocation: ToolInvocation,
83    ) -> Pin<Box<dyn Future<Output = Result<String, ToolError>> + Send + 'a>> {
84        Box::pin(async move { self.activate(&invocation.arguments) })
85    }
86}
87
88/// `read_skill_file`: returns the text of a file under a skill's
89/// `references/` or `assets/`, through the confined reader.
90///
91/// It refuses `..`, an absolute path, a NUL, a backslash, anything outside
92/// those two directories, a link that leaves them, a file over the configured
93/// size, and a file that is not UTF-8. See the `reader` module for what is
94/// left of a time-of-check to time-of-use window.
95#[derive(Debug)]
96pub struct ReadSkillFileTool {
97    catalog: SkillCatalog,
98}
99
100impl ReadSkillFileTool {
101    pub(super) const fn new(catalog: SkillCatalog) -> Self {
102        Self { catalog }
103    }
104}
105
106impl Tool for ReadSkillFileTool {
107    fn name(&self) -> &str {
108        READ_SKILL_FILE_TOOL
109    }
110
111    fn description(&self) -> &'static str {
112        "Read a text file that a skill bundles, by its path relative to the skill's directory, \
113         such as references/REFERENCE.md. Only files under references/ and assets/ can be read. \
114         The skill's instructions say which files to read and when."
115    }
116
117    fn parameters(&self) -> Value {
118        json!({
119            "type": "object",
120            "properties": {
121                "skill": {
122                    "type": "string",
123                    "enum": names(&self.catalog, |skill| !skill.resources.is_empty()),
124                    "description": "The name of the skill the file belongs to."
125                },
126                "path": {
127                    "type": "string",
128                    "description": "The file's path relative to the skill's directory, with \
129                                    forward slashes: references/REFERENCE.md."
130                }
131            },
132            "required": ["skill", "path"],
133            "additionalProperties": false
134        })
135    }
136
137    fn read_only(&self) -> bool {
138        true
139    }
140
141    fn call<'a>(
142        &'a self,
143        invocation: ToolInvocation,
144    ) -> Pin<Box<dyn Future<Output = Result<String, ToolError>> + Send + 'a>> {
145        Box::pin(async move {
146            let skill_name = string_argument(&invocation.arguments, "skill")?;
147            let path = string_argument(&invocation.arguments, "path")?.to_owned();
148            // Before any file is touched.
149            let skill = skill_named(&self.catalog, skill_name)?;
150            let (directory, root) = (skill.directory.clone(), skill.root.clone());
151            let max = self.catalog.max_resource_bytes();
152            let read = tokio::task::spawn_blocking(move || {
153                reader::read_text(&directory, &root, &path, max)
154            })
155            .await
156            .unwrap_or(Err(Refusal::Interrupted));
157            read.map_err(|refusal| {
158                trace_warn!(
159                    skill = %skill_name,
160                    refusal = ?refusal,
161                    "a skill file was not returned"
162                );
163                ToolError::Failed(refusal.to_string())
164            })
165        })
166    }
167}
168
169/// The names of the skills `keep` accepts, as a JSON array for an `enum`.
170fn names(catalog: &SkillCatalog, keep: impl Fn(&Skill) -> bool) -> Vec<&str> {
171    catalog
172        .skills()
173        .iter()
174        .filter(|skill| keep(skill))
175        .map(Skill::name)
176        .collect()
177}
178
179fn string_argument<'a>(arguments: &'a Value, key: &str) -> Result<&'a str, ToolError> {
180    arguments
181        .get(key)
182        .and_then(Value::as_str)
183        .ok_or_else(|| ToolError::Failed(format!("'{key}' is required and must be a string")))
184}
185
186fn skill_named<'a>(catalog: &'a SkillCatalog, name: &str) -> Result<&'a Skill, ToolError> {
187    catalog.get(name).ok_or_else(|| {
188        ToolError::Failed(format!(
189            "no skill named {name:?}; the skills are: {}",
190            names(catalog, |_| true).join(", ")
191        ))
192    })
193}
194
195/// What `activate_skill` returns for `skill`: its instructions in a
196/// `skill_content` element, then, when it has any, its compatibility note,
197/// the files `read_skill_file` can return and the scripts that are present
198/// and not run.
199fn activation(skill: &Skill) -> String {
200    let mut out = format!("<skill_content name=\"{}\"", skill.name);
201    if skill.scope == SkillScope::Project {
202        out.push_str(" origin=\"project\"");
203    }
204    out.push_str(">\n");
205    out.push_str(&skill.body);
206    out.push_str("\n\n");
207    if skill.shortened {
208        out.push_str("Description: ");
209        out.push_str(&skill.description);
210        out.push_str("\n\n");
211    }
212    if let Some(compatibility) = &skill.compatibility {
213        out.push_str("Compatibility: ");
214        out.push_str(compatibility);
215        out.push_str("\n\n");
216    }
217    out.push_str(
218        "Paths in this skill are relative to the skill's directory; read a file with \
219         read_skill_file.\n",
220    );
221    if !skill.resources.is_empty() {
222        out.push_str("<skill_resources>\n");
223        for file in &skill.resources {
224            out.push_str("  <file>");
225            out.push_str(&xml_escape(file));
226            out.push_str("</file>\n");
227        }
228        out.push_str("</skill_resources>\n");
229    }
230    if !skill.scripts.is_empty() {
231        out.push_str(
232            "These scripts are present. This agent cannot run them; do not try to call them.\n\
233             <skill_scripts>\n",
234        );
235        for file in &skill.scripts {
236            out.push_str("  <file>");
237            out.push_str(&xml_escape(file));
238            out.push_str("</file>\n");
239        }
240        out.push_str("</skill_scripts>\n");
241    }
242    out.push_str("</skill_content>");
243    out
244}
245
246#[cfg(test)]
247#[path = "tools_tests.rs"]
248mod tests;