Skip to main content

weirdnet_agent/
tool.rs

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