1use std::collections::{BTreeMap, BTreeSet};
9use std::sync::Arc;
10
11use async_trait::async_trait;
12use serde::{Deserialize, Serialize};
13use serde_json::Value;
14
15use crate::cancel::CancelToken;
16use crate::identity::AgentIdentity;
17use crate::policy::{Tier, site_of};
18use crate::trace::{SessionMark, StepKind};
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
22#[serde(rename_all = "snake_case")]
23pub enum BudgetCharge {
24 #[default]
25 None,
26 Search,
27 Page,
28}
29
30#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
32pub struct ToolAnnotations {
33 pub read_only: bool,
34 pub destructive: bool,
35 pub open_world: bool,
36}
37
38#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
40pub struct ToolSpec {
41 pub name: String,
42 pub description: String,
43 pub input_schema: Value,
45 pub annotations: ToolAnnotations,
46 pub tier: Tier,
47 #[serde(default)]
48 pub charge: BudgetCharge,
49}
50
51impl ToolSpec {
52 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
54 Self {
55 name: name.into(),
56 description: description.into(),
57 input_schema: serde_json::json!({ "type": "object", "properties": {} }),
58 annotations: ToolAnnotations::default(),
59 tier: Tier::Navigate,
60 charge: BudgetCharge::None,
61 }
62 }
63
64 pub fn schema(mut self, schema: Value) -> Self {
65 self.input_schema = schema;
66 self
67 }
68
69 pub fn annotations(mut self, a: ToolAnnotations) -> Self {
71 self.annotations = a;
72 self.tier = Tier::from_annotations(a.read_only, a.destructive, a.open_world);
73 self
74 }
75
76 pub fn tier(mut self, tier: Tier) -> Self {
78 self.tier = tier;
79 self
80 }
81
82 pub fn charge(mut self, charge: BudgetCharge) -> Self {
83 self.charge = charge;
84 self
85 }
86}
87
88#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
90pub struct CallTarget {
91 pub url: Option<String>,
92 pub site: Option<String>,
93 pub provider: Option<String>,
94}
95
96impl CallTarget {
97 pub fn url(url: impl Into<String>) -> Self {
98 let url = url.into();
99 Self { site: site_of(&url), url: Some(url), provider: None }
100 }
101
102 pub fn provider(provider: impl Into<String>) -> Self {
103 Self { provider: Some(provider.into()), ..Self::default() }
104 }
105
106 pub fn resolved_site(&self) -> Option<String> {
108 self.site.clone().or_else(|| self.url.as_deref().and_then(site_of))
109 }
110}
111
112#[derive(Debug, Clone)]
114pub struct ToolContext {
115 pub agent: AgentIdentity,
116 pub task_id: String,
117 pub session: SessionMark,
118 pub cancel: CancelToken,
119}
120
121#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
124pub struct ToolOutput {
125 pub content: String,
126 #[serde(default)]
127 pub is_error: bool,
128 #[serde(default)]
129 pub steps: Vec<StepKind>,
130}
131
132impl ToolOutput {
133 pub fn text(content: impl Into<String>) -> Self {
134 Self { content: content.into(), ..Self::default() }
135 }
136
137 pub fn error(content: impl Into<String>) -> Self {
138 Self { content: content.into(), is_error: true, steps: Vec::new() }
139 }
140
141 pub fn with_step(mut self, step: StepKind) -> Self {
142 self.steps.push(step);
143 self
144 }
145}
146
147#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
148#[serde(rename_all = "snake_case", tag = "error", content = "detail")]
149pub enum ToolError {
150 #[error("unknown tool {0}")]
151 NotFound(String),
152 #[error("tool {0} is turned off")]
153 Disabled(String),
154 #[error("invalid arguments: {0}")]
155 InvalidArgs(String),
156 #[error("{0}")]
157 Failed(String),
158 #[error("timed out")]
159 Timeout,
160 #[error("cancelled")]
161 Cancelled,
162}
163
164#[async_trait]
166pub trait Tool: Send + Sync {
167 fn spec(&self) -> ToolSpec;
168
169 fn target(&self, _args: &Value) -> CallTarget {
171 CallTarget::default()
172 }
173
174 async fn call(&self, ctx: &ToolContext, args: Value) -> Result<ToolOutput, ToolError>;
175}
176
177#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
179#[serde(rename_all = "snake_case")]
180pub enum SourceKind {
181 Local,
182 Mcp,
183 Node,
184}
185
186#[async_trait]
188pub trait ToolSource: Send + Sync {
189 fn id(&self) -> &str;
190 fn kind(&self) -> SourceKind;
191 async fn list(&self) -> Result<Vec<ToolSpec>, ToolError>;
192 fn target(&self, _tool: &str, _args: &Value) -> CallTarget {
193 CallTarget::default()
194 }
195 async fn call(&self, tool: &str, ctx: &ToolContext, args: Value) -> Result<ToolOutput, ToolError>;
196}
197
198pub struct LocalTools {
200 id: String,
201 tools: BTreeMap<String, Arc<dyn Tool>>,
202}
203
204impl LocalTools {
205 pub fn new(id: impl Into<String>) -> Self {
206 Self { id: id.into(), tools: BTreeMap::new() }
207 }
208
209 pub fn with(mut self, tool: impl Tool + 'static) -> Self {
210 self.add(Arc::new(tool));
211 self
212 }
213
214 pub fn add(&mut self, tool: Arc<dyn Tool>) {
215 self.tools.insert(tool.spec().name, tool);
216 }
217}
218
219#[async_trait]
220impl ToolSource for LocalTools {
221 fn id(&self) -> &str {
222 &self.id
223 }
224
225 fn kind(&self) -> SourceKind {
226 SourceKind::Local
227 }
228
229 async fn list(&self) -> Result<Vec<ToolSpec>, ToolError> {
230 Ok(self.tools.values().map(|t| t.spec()).collect())
231 }
232
233 fn target(&self, tool: &str, args: &Value) -> CallTarget {
234 self.tools.get(tool).map(|t| t.target(args)).unwrap_or_default()
235 }
236
237 async fn call(&self, tool: &str, ctx: &ToolContext, args: Value) -> Result<ToolOutput, ToolError> {
238 let t = self.tools.get(tool).ok_or_else(|| ToolError::NotFound(tool.to_string()))?;
239 t.call(ctx, args).await
240 }
241}
242
243#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
244pub enum RegistryError {
245 #[error("tool {tool} is offered by both {first} and {second}")]
246 Duplicate { tool: String, first: String, second: String },
247 #[error("source {source_id} failed to list tools: {error}")]
248 List { source_id: String, error: ToolError },
249 #[error("tier override for {tool} would loosen it")]
250 LooserTier { tool: String },
251}
252
253#[derive(Default)]
255pub struct ToolRegistry {
256 sources: Vec<Arc<dyn ToolSource>>,
257 index: BTreeMap<String, (usize, ToolSpec)>,
258 disabled_sources: BTreeSet<String>,
259 disabled_tools: BTreeSet<String>,
260 tier_overrides: BTreeMap<String, Tier>,
261}
262
263impl ToolRegistry {
264 pub fn new() -> Self {
265 Self::default()
266 }
267
268 pub fn add_source(&mut self, source: Arc<dyn ToolSource>) {
270 self.sources.push(source);
271 }
272
273 pub fn source_ids(&self) -> impl Iterator<Item = &str> {
274 self.sources.iter().map(|s| s.id())
275 }
276
277 pub async fn refresh(&mut self) -> Result<(), RegistryError> {
279 let mut index = BTreeMap::new();
280 for (i, src) in self.sources.iter().enumerate() {
281 let specs = src.list().await.map_err(|error| RegistryError::List { source_id: src.id().to_string(), error })?;
282 for spec in specs {
283 if let Some((j, _)) = index.get(&spec.name) {
284 let first: &Arc<dyn ToolSource> = &self.sources[*j];
285 return Err(RegistryError::Duplicate { tool: spec.name, first: first.id().to_string(), second: src.id().to_string() });
286 }
287 index.insert(spec.name.clone(), (i, spec));
288 }
289 }
290 self.index = index;
291 Ok(())
292 }
293
294 pub fn set_source_enabled(&mut self, source_id: &str, on: bool) {
295 if on {
296 self.disabled_sources.remove(source_id);
297 } else {
298 self.disabled_sources.insert(source_id.to_string());
299 }
300 }
301
302 pub fn set_tool_enabled(&mut self, tool: &str, on: bool) {
303 if on {
304 self.disabled_tools.remove(tool);
305 } else {
306 self.disabled_tools.insert(tool.to_string());
307 }
308 }
309
310 pub fn set_tier_override(&mut self, tool: &str, tier: Tier) -> Result<(), RegistryError> {
312 if let Some((_, spec)) = self.index.get(tool)
313 && !spec.tier.allows_override_to(tier)
314 {
315 return Err(RegistryError::LooserTier { tool: tool.to_string() });
316 }
317 self.tier_overrides.insert(tool.to_string(), tier);
318 Ok(())
319 }
320
321 fn effective(&self, idx: usize, spec: &ToolSpec) -> Option<ToolSpec> {
322 let src = &self.sources[idx];
323 if self.disabled_sources.contains(src.id()) || self.disabled_tools.contains(&spec.name) {
324 return None;
325 }
326 let mut spec = spec.clone();
327 if let Some(t) = self.tier_overrides.get(&spec.name)
328 && spec.tier.allows_override_to(*t)
329 {
330 spec.tier = *t;
331 }
332 Some(spec)
333 }
334
335 pub fn specs(&self) -> Vec<ToolSpec> {
337 self.index.values().filter_map(|(i, s)| self.effective(*i, s)).filter(|s| s.tier != Tier::Never).collect()
338 }
339
340 pub fn lookup(&self, tool: &str) -> Result<(Arc<dyn ToolSource>, ToolSpec), ToolError> {
342 let (i, spec) = self.index.get(tool).ok_or_else(|| ToolError::NotFound(tool.to_string()))?;
343 let spec = self.effective(*i, spec).ok_or_else(|| ToolError::Disabled(tool.to_string()))?;
344 Ok((self.sources[*i].clone(), spec))
345 }
346}
347
348#[cfg(test)]
349mod tests {
350 use super::*;
351 use crate::testing::FnTool;
352
353 fn src(id: &str, names: &[&str]) -> Arc<dyn ToolSource> {
354 let mut l = LocalTools::new(id);
355 for n in names {
356 l.add(Arc::new(FnTool::new(ToolSpec::new(*n, "t"), |_| Ok(ToolOutput::text("ok")))));
357 }
358 Arc::new(l)
359 }
360
361 #[tokio::test]
362 async fn registry_merges_switches_and_rejects_duplicates() {
363 let mut r = ToolRegistry::new();
364 r.add_source(src("browser", &["tabs.open", "page.click"]));
365 r.add_source(src("mcp:mouser", &["search_issues"]));
366 r.refresh().await.unwrap();
367 assert_eq!(r.specs().len(), 3);
368 r.set_source_enabled("mcp:mouser", false);
369 assert_eq!(r.lookup("search_issues").err(), Some(ToolError::Disabled("search_issues".into())));
370 r.set_source_enabled("mcp:mouser", true);
371 r.set_tool_enabled("page.click", false);
372 assert_eq!(r.specs().len(), 2);
373 assert_eq!(r.lookup("nope").err(), Some(ToolError::NotFound("nope".into())));
374 assert_eq!(r.source_ids().collect::<Vec<_>>(), vec!["browser", "mcp:mouser"]);
375
376 r.add_source(src("other", &["tabs.open"]));
377 assert!(matches!(r.refresh().await, Err(RegistryError::Duplicate { .. })));
378 }
379
380 #[tokio::test]
381 async fn tier_overrides_only_tighten() {
382 let mut l = LocalTools::new("mcp:x");
383 l.add(Arc::new(FnTool::new(ToolSpec::new("delete", "d").annotations(ToolAnnotations { destructive: true, ..Default::default() }), |_| {
384 Ok(ToolOutput::text(""))
385 })));
386 l.add(Arc::new(FnTool::new(ToolSpec::new("read", "r").annotations(ToolAnnotations { read_only: true, ..Default::default() }), |_| {
387 Ok(ToolOutput::text(""))
388 })));
389 let mut r = ToolRegistry::new();
390 r.add_source(Arc::new(l));
391 r.refresh().await.unwrap();
392 assert_eq!(r.lookup("delete").unwrap().1.tier, Tier::Interact);
393 assert!(r.set_tier_override("delete", Tier::Navigate).is_err());
394 r.set_tier_override("read", Tier::Interact).unwrap();
395 assert_eq!(r.lookup("read").unwrap().1.tier, Tier::Interact);
396 r.set_tier_override("delete", Tier::Never).unwrap();
397 assert!(r.specs().iter().all(|s| s.name != "delete"));
398 }
399
400 #[test]
401 fn call_target_resolves_site() {
402 let t = CallTarget::url("https://www.Docs.rs/tokio");
403 assert_eq!(t.resolved_site().as_deref(), Some("docs.rs"));
404 assert_eq!(CallTarget::provider("kagi").resolved_site(), None);
405 }
406}