Skip to main content

troupekit_tools/
typed.rs

1use crate::tool::{Tool, ToolContext, ToolError, ToolOutput};
2use async_trait::async_trait;
3use schemars::JsonSchema;
4use serde::de::DeserializeOwned;
5use serde_json::Value;
6use std::future::Future;
7use std::marker::PhantomData;
8use troupekit_core::tool::ToolSpec;
9
10/// A tool whose arguments are the serde struct `A` and whose body is the
11/// async closure `F`. Build it with `typed_tool`; the argument schema comes
12/// from `A`'s `schemars::JsonSchema` derive, so it never drifts from the type.
13pub struct TypedTool<A, F> {
14    spec: ToolSpec,
15    f: F,
16    args: PhantomData<fn() -> A>,
17}
18
19/// Builds a tool called `name` from the argument type `A` and closure `f`.
20/// `f` receives the parsed arguments and an owned `ToolContext`, so it may
21/// hold the context across awaits. Returns the tool; wrap it in an `Arc`.
22pub fn typed_tool<A, F, Fut>(name: &str, description: &str, f: F) -> TypedTool<A, F>
23where
24    A: DeserializeOwned + JsonSchema + Send + 'static,
25    F: Fn(A, ToolContext) -> Fut + Send + Sync + 'static,
26    Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
27{
28    let mut schema = serde_json::to_value(schemars::schema_for!(A))
29        .expect("a derived schema serializes to JSON");
30    if let Value::Object(map) = &mut schema {
31        map.remove("$schema");
32        map.remove("title");
33    }
34    TypedTool {
35        spec: ToolSpec {
36            name: name.into(),
37            description: description.into(),
38            schema,
39            hosted: None,
40        },
41        f,
42        args: PhantomData,
43    }
44}
45
46#[async_trait]
47impl<A, F, Fut> Tool for TypedTool<A, F>
48where
49    A: DeserializeOwned + JsonSchema + Send + 'static,
50    F: Fn(A, ToolContext) -> Fut + Send + Sync + 'static,
51    Fut: Future<Output = Result<ToolOutput, ToolError>> + Send + 'static,
52{
53    fn spec(&self) -> &ToolSpec {
54        &self.spec
55    }
56
57    async fn call(&self, args: Value, ctx: &ToolContext) -> Result<ToolOutput, ToolError> {
58        let parsed: A =
59            serde_json::from_value(args).map_err(|e| ToolError::InvalidArgs(e.to_string()))?;
60        (self.f)(parsed, ctx.clone()).await
61    }
62}
63
64#[cfg(test)]
65mod tests {
66    use super::*;
67    use crate::registry::ToolRegistry;
68    use crate::tool::{Tool, ToolContext, ToolError, ToolOutput};
69    use serde::Deserialize;
70    use serde_json::json;
71    use std::sync::Arc;
72    use troupekit_core::ids::RunId;
73
74    #[derive(Deserialize, schemars::JsonSchema)]
75    struct Args {
76        city: String,
77        days: Option<u8>,
78    }
79
80    fn weather() -> Arc<dyn Tool> {
81        Arc::new(typed_tool(
82            "weather",
83            "Forecast for a city",
84            |a: Args, _ctx: ToolContext| async move {
85                Ok(ToolOutput::text(format!(
86                    "{}:{}",
87                    a.city,
88                    a.days.map_or("none".into(), |d| d.to_string())
89                )))
90            },
91        ))
92    }
93
94    #[test]
95    fn schema_comes_from_the_struct() {
96        let tool = weather();
97        let s = &tool.spec().schema;
98        assert_eq!(tool.spec().name, "weather");
99        assert_eq!(s["type"], "object");
100        assert_eq!(s["properties"]["city"]["type"], "string");
101        assert_eq!(s["required"], json!(["city"]));
102        assert!(s.get("$schema").is_none() && s.get("title").is_none());
103    }
104
105    #[tokio::test]
106    async fn typed_tool_runs_through_registry() {
107        let mut r = ToolRegistry::new();
108        r.register(weather()).unwrap();
109        let ctx = ToolContext::default();
110        assert_eq!(
111            r.call("weather", json!({"city":"Oslo"}), &ctx)
112                .await
113                .unwrap()
114                .content,
115            "Oslo:none"
116        );
117        assert_eq!(
118            r.call("weather", json!({"city":"Oslo","days":3}), &ctx)
119                .await
120                .unwrap()
121                .content,
122            "Oslo:3"
123        );
124        assert!(matches!(
125            r.call("weather", json!({"city":3}), &ctx).await,
126            Err(ToolError::InvalidArgs(_))
127        ));
128    }
129
130    #[tokio::test]
131    async fn direct_call_with_bad_args_is_invalid_args() {
132        let err = weather()
133            .call(json!({"days":1}), &ToolContext::default())
134            .await
135            .unwrap_err();
136        assert!(matches!(err, ToolError::InvalidArgs(_)), "{err}");
137    }
138
139    #[tokio::test]
140    async fn closure_uses_context_across_await() {
141        let tool = typed_tool("who", "Run id", |_a: Args, ctx: ToolContext| async move {
142            tokio::task::yield_now().await;
143            Ok(ToolOutput::text(format!("{:?}", ctx.run_id.is_some())))
144        });
145        let ctx = ToolContext {
146            run_id: Some(RunId::new()),
147            idempotency_key: None,
148        };
149        assert_eq!(
150            tool.call(json!({"city":"x"}), &ctx).await.unwrap().content,
151            "true"
152        );
153    }
154}