a2a_protocol_server/tool_loop/tool.rs
1// SPDX-License-Identifier: Apache-2.0
2// Copyright 2026 Tom F. <[email protected]> (https://github.com/tomtom215)
3
4//! [`Tool`], something a model may call, and [`ToolSet`], the catalogue the
5//! loop offers it.
6
7use std::fmt;
8use std::future::Future;
9use std::pin::Pin;
10use std::sync::Arc;
11
12use serde_json::Value;
13
14use super::model::ToolSpec;
15
16/// Why a call produced no result.
17#[derive(Debug, Clone, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum ToolError {
20 /// The call failed in a way the model can act on: a bad argument, a name
21 /// that does not exist, a record not found. The message goes back to the
22 /// model as the call's result and the loop continues. This is the
23 /// common case: "no service named 'billing'; call `list_services`" is how
24 /// a model recovers.
25 Failed(String),
26 /// The call failed in a way no further turn can fix, such as the tool's
27 /// own backend being down. The task ends `Failed`, class `internal`.
28 Fatal(String),
29}
30
31impl fmt::Display for ToolError {
32 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
33 match self {
34 Self::Failed(e) | Self::Fatal(e) => f.write_str(e),
35 }
36 }
37}
38
39impl std::error::Error for ToolError {}
40
41/// One call, as a [`Tool`] is given it.
42#[derive(Debug, Clone, PartialEq, Eq)]
43#[non_exhaustive]
44pub struct ToolInvocation {
45 /// The arguments, always a JSON object: the loop answers arguments that
46 /// are not one itself, without calling the tool.
47 pub arguments: Value,
48 /// This call's idempotency key (ADR 0026): 64 lowercase hex digits,
49 /// the same for the same tool and arguments within one run of the loop
50 /// over one message, different otherwise, and not computable without
51 /// the loop's secret. A tool with side effects passes it to its backend
52 /// where the backend takes one (an `Idempotency-Key` header, a unique
53 /// request id), so a retried request does its work once.
54 pub idempotency_key: String,
55}
56
57impl ToolInvocation {
58 /// An invocation with `arguments` and `idempotency_key`, for calling a
59 /// tool outside a loop, as a test does.
60 #[must_use]
61 pub fn new(arguments: Value, idempotency_key: impl Into<String>) -> Self {
62 Self {
63 arguments,
64 idempotency_key: idempotency_key.into(),
65 }
66 }
67}
68
69/// Something a model may call.
70///
71/// Object-safe, with a boxed future like [`AgentExecutor`](crate::AgentExecutor).
72/// [`ToolSet`] holds each as an `Arc<dyn Tool>`.
73pub trait Tool: Send + Sync + 'static {
74 /// The name the model calls it by. Unique within a [`ToolSet`].
75 fn name(&self) -> &str;
76
77 /// What it does. The model chooses tools by this text, so say when to
78 /// call it as well as what it returns.
79 fn description(&self) -> &str;
80
81 /// A JSON Schema for the arguments, an `object` schema.
82 fn parameters(&self) -> Value;
83
84 /// Whether a call changes nothing, so running it again is harmless:
85 /// a lookup, a status query, a search. `false` unless a tool says so.
86 ///
87 /// Within one run, a call identical to one that already succeeded —
88 /// same tool, same arguments — is not run again when the tool is not
89 /// read-only: the model is sent the earlier result, marked as such
90 /// (ADR 0026). A read-only tool is run each time, so a model can poll
91 /// it for a change.
92 fn read_only(&self) -> bool {
93 false
94 }
95
96 /// Runs the call.
97 ///
98 /// # Errors
99 ///
100 /// [`ToolError::Failed`] to tell the model what went wrong;
101 /// [`ToolError::Fatal`] to end the task.
102 fn call<'a>(
103 &'a self,
104 invocation: ToolInvocation,
105 ) -> Pin<Box<dyn Future<Output = Result<String, ToolError>> + Send + 'a>>;
106}
107
108/// Two tools in one [`ToolSet`] with the same name.
109#[derive(Debug, Clone, PartialEq, Eq)]
110pub struct DuplicateTool(pub String);
111
112impl fmt::Display for DuplicateTool {
113 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114 write!(f, "a tool named '{}' is already in this set", self.0)
115 }
116}
117
118impl std::error::Error for DuplicateTool {}
119
120/// The tools a [`ToolLoop`](super::ToolLoop) offers its model, in the order
121/// they were added. Names are unique: a model asking for a name two tools
122/// share could not be answered.
123#[derive(Clone, Default)]
124pub struct ToolSet {
125 tools: Vec<Arc<dyn Tool>>,
126}
127
128impl fmt::Debug for ToolSet {
129 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
130 f.debug_list()
131 .entries(self.tools.iter().map(|t| t.name()))
132 .finish()
133 }
134}
135
136impl ToolSet {
137 /// An empty set. A loop over it is a plain chat.
138 #[must_use]
139 pub fn new() -> Self {
140 Self::default()
141 }
142
143 /// Adds `tool`.
144 ///
145 /// # Errors
146 ///
147 /// [`DuplicateTool`] when the set already holds a tool of that name; the
148 /// set is unchanged.
149 pub fn add(&mut self, tool: impl Tool) -> Result<(), DuplicateTool> {
150 self.add_arc(Arc::new(tool))
151 }
152
153 /// Adds a shared `tool`, for one instance offered by several sets.
154 ///
155 /// # Errors
156 ///
157 /// [`DuplicateTool`] when the set already holds a tool of that name; the
158 /// set is unchanged.
159 pub fn add_arc(&mut self, tool: Arc<dyn Tool>) -> Result<(), DuplicateTool> {
160 if self.get(tool.name()).is_some() {
161 return Err(DuplicateTool(tool.name().to_owned()));
162 }
163 self.tools.push(tool);
164 Ok(())
165 }
166
167 /// Adds `tool`, by value, for building a set in one expression.
168 ///
169 /// # Errors
170 ///
171 /// [`DuplicateTool`] when the set already holds a tool of that name.
172 pub fn with(mut self, tool: impl Tool) -> Result<Self, DuplicateTool> {
173 self.add(tool)?;
174 Ok(self)
175 }
176
177 /// The tool named `name`.
178 #[must_use]
179 pub fn get(&self, name: &str) -> Option<&Arc<dyn Tool>> {
180 self.tools.iter().find(|t| t.name() == name)
181 }
182
183 /// The names, in the order the tools were added.
184 #[must_use]
185 pub fn names(&self) -> Vec<String> {
186 self.tools.iter().map(|t| t.name().to_owned()).collect()
187 }
188
189 /// The catalogue as the model is told it.
190 #[must_use]
191 pub fn specs(&self) -> Vec<ToolSpec> {
192 self.tools
193 .iter()
194 .map(|t| ToolSpec::new(t.name(), t.description(), t.parameters()))
195 .collect()
196 }
197
198 /// How many tools the set holds.
199 #[must_use]
200 pub fn len(&self) -> usize {
201 self.tools.len()
202 }
203
204 /// Whether the set holds none.
205 #[must_use]
206 pub fn is_empty(&self) -> bool {
207 self.tools.is_empty()
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 /// Says nothing about itself beyond what the trait requires.
216 struct Plain;
217
218 impl Tool for Plain {
219 fn name(&self) -> &'static str {
220 "plain"
221 }
222 fn description(&self) -> &'static str {
223 "Does something."
224 }
225 fn parameters(&self) -> Value {
226 serde_json::json!({"type": "object"})
227 }
228 fn call<'a>(
229 &'a self,
230 _invocation: ToolInvocation,
231 ) -> Pin<Box<dyn Future<Output = Result<String, ToolError>> + Send + 'a>> {
232 Box::pin(async { Ok(String::new()) })
233 }
234 }
235
236 /// A tool that does not say it is read-only is treated as changing
237 /// something, so its repeated calls are not run again (ADR 0026). The
238 /// mutation gate found the default untested: `true` survived.
239 #[test]
240 fn a_tool_is_not_read_only_unless_it_says_so() {
241 assert!(!Plain.read_only());
242 }
243
244 /// Either kind of failure displays as its message alone. The loop
245 /// matches on the variant, so only a caller logging the error reads
246 /// this: the mutation gate found it untested.
247 #[test]
248 fn a_tool_error_displays_as_its_message() {
249 assert_eq!(
250 ToolError::Failed("no such record".to_owned()).to_string(),
251 "no such record"
252 );
253 assert_eq!(
254 ToolError::Fatal("backend down".to_owned()).to_string(),
255 "backend down"
256 );
257 }
258
259 /// The refusal names the tool.
260 #[test]
261 fn a_duplicate_names_the_tool() {
262 assert_eq!(
263 DuplicateTool("lookup".to_owned()).to_string(),
264 "a tool named 'lookup' is already in this set"
265 );
266 }
267}