Skip to main content

troupekit_tools/
tool.rs

1use async_trait::async_trait;
2use serde_json::Value;
3use std::sync::Arc;
4use troupekit_core::http::{HttpError, HttpErrorKind};
5use troupekit_core::ids::RunId;
6use troupekit_core::tool::{HostedTool, ToolSpec};
7
8/// Per-call context handed to every tool.
9/// Cheap to clone, so typed tool closures can own a copy across awaits.
10/// `run_id` names the run that made the call; `idempotency_key` is the same
11/// for a replayed call and new for every other, for tools that dedupe.
12#[derive(Debug, Clone, Default)]
13pub struct ToolContext {
14    pub run_id: Option<RunId>,
15    pub idempotency_key: Option<String>,
16}
17
18impl ToolContext {
19    /// Builds the context for call `index` of step `step` of run `run_id`.
20    /// The key is `"{run_id}:{step}:{index}"`, so replaying a step from its
21    /// checkpoint gives the same keys and the next step new ones.
22    pub fn for_call(run_id: RunId, step: u64, index: usize) -> ToolContext {
23        ToolContext {
24            run_id: Some(run_id),
25            idempotency_key: Some(format!("{run_id}:{step}:{index}")),
26        }
27    }
28}
29
30/// What a tool returns to the model.
31/// `is_error` marks content that describes a failure the model may react to,
32/// such as an HTTP error status from a remote API.
33#[derive(Debug, Clone, PartialEq, Eq)]
34pub struct ToolOutput {
35    pub content: String,
36    pub is_error: bool,
37}
38
39impl ToolOutput {
40    /// Builds a successful output holding `content`.
41    /// Returns the output with `is_error` false.
42    pub fn text(content: impl Into<String>) -> Self {
43        Self {
44            content: content.into(),
45            is_error: false,
46        }
47    }
48
49    /// Builds an error output holding `content`.
50    /// Returns the output with `is_error` true.
51    pub fn error(content: impl Into<String>) -> Self {
52        Self {
53            content: content.into(),
54            is_error: true,
55        }
56    }
57
58    /// Folds a tool result into what the model sees.
59    /// `Ok` passes through; `Err` becomes an error output whose content is
60    /// the error's display text, which never holds secret values.
61    pub fn from_result(result: Result<ToolOutput, ToolError>) -> Self {
62        result.unwrap_or_else(|e| Self::error(e.to_string()))
63    }
64}
65
66/// Why a tool call or tool setup failed.
67/// Unknown tools, schema-invalid arguments, blocked addresses, transport
68/// and decode failures and bad configuration each have their own variant.
69#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
70pub enum ToolError {
71    #[error("invalid arguments: {0}")]
72    InvalidArgs(String),
73    #[error("unknown tool: {0}")]
74    UnknownTool(String),
75    #[error("duplicate tool: {0}")]
76    DuplicateTool(String),
77    #[error("invalid tool spec: {0}")]
78    InvalidSpec(String),
79    #[error("config: {0}")]
80    Config(String),
81    #[error("blocked: {0}")]
82    Blocked(String),
83    #[error("http: {0}")]
84    Http(String),
85    #[error("decode: {0}")]
86    Decode(String),
87    #[error("failed: {0}")]
88    Failed(String),
89}
90
91impl From<HttpError> for ToolError {
92    fn from(e: HttpError) -> Self {
93        match e.kind {
94            HttpErrorKind::Invalid => ToolError::InvalidArgs(e.message),
95            HttpErrorKind::Blocked => ToolError::Blocked(e.message),
96            _ => ToolError::Http(e.message),
97        }
98    }
99}
100
101/// A capability an agent can call: a spec the model sees and an async call.
102/// Object safe, so registries hold `Arc<dyn Tool>`. Arguments arrive as JSON
103/// already checked against `spec().schema` when called through a registry.
104#[async_trait]
105pub trait Tool: Send + Sync {
106    /// Returns the name, description and argument schema the model sees.
107    fn spec(&self) -> &ToolSpec;
108
109    /// Runs the tool with JSON `args` and the per-call `ctx`.
110    /// Returns the model-facing output or a `ToolError`.
111    async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError>;
112
113    /// Reports whether a call sends a request over the network, as
114    /// `web_fetch`, `web_search`, HTTP and hosted tools do. A private agent
115    /// refuses such a tool at build. Default false: override it when true.
116    fn uses_network(&self) -> bool {
117        false
118    }
119}
120
121struct Networked(Arc<dyn Tool>);
122
123#[async_trait]
124impl Tool for Networked {
125    fn spec(&self) -> &ToolSpec {
126        self.0.spec()
127    }
128
129    async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
130        self.0.call(args, ctx).await
131    }
132
133    fn uses_network(&self) -> bool {
134        true
135    }
136}
137
138/// Marks `inner` as a tool whose calls go over the network, so a private
139/// agent refuses it. Spec and calls pass through unchanged.
140/// Output: the marked tool.
141pub(crate) fn networked(inner: Arc<dyn Tool>) -> Arc<dyn Tool> {
142    let tool: Arc<dyn Tool> = Arc::new(Networked(inner));
143    assert!(tool.uses_network(), "a networked tool reports the network");
144    tool
145}
146
147struct Hosted {
148    inner: Arc<dyn Tool>,
149    spec: ToolSpec,
150}
151
152#[async_trait]
153impl Tool for Hosted {
154    fn spec(&self) -> &ToolSpec {
155        &self.spec
156    }
157
158    async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
159        self.inner.call(args, ctx).await
160    }
161
162    fn uses_network(&self) -> bool {
163        true
164    }
165}
166
167/// Marks local tool `inner` as standing in for server-side tool `kind`:
168/// vendors that host it run theirs, every other vendor calls `inner`.
169/// Panics when `inner` is not named as `kind` requires.
170pub fn hosted(inner: Arc<dyn Tool>, kind: HostedTool) -> Arc<dyn Tool> {
171    assert_eq!(
172        inner.spec().name,
173        kind.name(),
174        "a hosted stand-in carries the hosted tool's name"
175    );
176    let spec = ToolSpec {
177        hosted: Some(kind),
178        ..inner.spec().clone()
179    };
180    Arc::new(Hosted { inner, spec })
181}
182
183#[cfg(test)]
184mod tests {
185    use super::*;
186
187    #[test]
188    fn hosted_stand_in_reports_the_network() {
189        let inner = crate::typed::typed_tool(
190            "web_search",
191            "Search.",
192            |_a: serde_json::Value, _c: ToolContext| async { Ok(ToolOutput::text("x")) },
193        );
194        let inner: Arc<dyn Tool> = Arc::new(inner);
195        assert!(!inner.uses_network(), "a plain tool stays local by default");
196        assert!(hosted(inner, HostedTool::WebSearch { max_uses: 1 }).uses_network());
197    }
198
199    #[test]
200    fn for_call_builds_stable_keys() {
201        let run = RunId::new();
202        let a = ToolContext::for_call(run, 3, 1);
203        assert_eq!(a.run_id, Some(run));
204        assert_eq!(a.idempotency_key, Some(format!("{run}:3:1")));
205        assert_eq!(
206            ToolContext::for_call(run, 3, 1).idempotency_key,
207            a.idempotency_key
208        );
209        assert_ne!(
210            ToolContext::for_call(run, 4, 1).idempotency_key,
211            a.idempotency_key
212        );
213        assert_eq!(ToolContext::default().idempotency_key, None);
214    }
215}