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
114struct Hosted {
115    inner: Arc<dyn Tool>,
116    spec: ToolSpec,
117}
118
119#[async_trait]
120impl Tool for Hosted {
121    fn spec(&self) -> &ToolSpec {
122        &self.spec
123    }
124
125    async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
126        self.inner.call(args, ctx).await
127    }
128}
129
130/// Marks local tool `inner` as standing in for server-side tool `kind`:
131/// vendors that host it run theirs, every other vendor calls `inner`.
132/// Panics when `inner` is not named as `kind` requires.
133pub fn hosted(inner: Arc<dyn Tool>, kind: HostedTool) -> Arc<dyn Tool> {
134    assert_eq!(
135        inner.spec().name,
136        kind.name(),
137        "a hosted stand-in carries the hosted tool's name"
138    );
139    let spec = ToolSpec {
140        hosted: Some(kind),
141        ..inner.spec().clone()
142    };
143    Arc::new(Hosted { inner, spec })
144}
145
146#[cfg(test)]
147mod tests {
148    use super::*;
149
150    #[test]
151    fn for_call_builds_stable_keys() {
152        let run = RunId::new();
153        let a = ToolContext::for_call(run, 3, 1);
154        assert_eq!(a.run_id, Some(run));
155        assert_eq!(a.idempotency_key, Some(format!("{run}:3:1")));
156        assert_eq!(
157            ToolContext::for_call(run, 3, 1).idempotency_key,
158            a.idempotency_key
159        );
160        assert_ne!(
161            ToolContext::for_call(run, 4, 1).idempotency_key,
162            a.idempotency_key
163        );
164        assert_eq!(ToolContext::default().idempotency_key, None);
165    }
166}