Skip to main content

gemini_adk_rs/tool/
typed.rs

1//! Type-safe function tool with auto-generated JSON Schema.
2
3use std::marker::PhantomData;
4
5use async_trait::async_trait;
6use schemars::JsonSchema;
7use serde::de::DeserializeOwned;
8
9use crate::BoxFuture;
10use crate::error::ToolError;
11
12use super::ToolFunction;
13
14/// Async handler over deserialized arguments of type `T`.
15type TypedHandler<T> =
16    Box<dyn Fn(T) -> BoxFuture<Result<serde_json::Value, ToolError>> + Send + Sync>;
17
18/// Type-safe function tool with auto-generated JSON Schema.
19///
20/// Unlike [`super::SimpleTool`] which takes raw `serde_json::Value` arguments and
21/// requires a manually written schema, `TypedTool` auto-generates the JSON
22/// Schema from a struct that derives [`schemars::JsonSchema`] and deserializes
23/// the arguments into that struct before calling the handler.
24///
25/// # Example
26///
27/// ```ignore
28/// use schemars::JsonSchema;
29/// use serde::Deserialize;
30///
31/// #[derive(Deserialize, JsonSchema)]
32/// struct WeatherArgs {
33///     /// The city to get weather for
34///     city: String,
35/// }
36///
37/// let tool = TypedTool::new::<WeatherArgs>(
38///     "get_weather",
39///     "Get current weather for a city",
40///     |args: WeatherArgs| async move {
41///         Ok(serde_json::json!({ "temp": 22, "city": args.city }))
42///     },
43/// );
44/// ```
45pub struct TypedTool<T: DeserializeOwned + JsonSchema + Send + Sync + 'static> {
46    name: String,
47    description: String,
48    schema: serde_json::Value,
49    handler: TypedHandler<T>,
50    _phantom: PhantomData<T>,
51}
52
53impl<T: DeserializeOwned + JsonSchema + Send + Sync + 'static> TypedTool<T> {
54    /// Create a new typed function tool with auto-generated schema.
55    ///
56    /// The JSON Schema is derived from `T`'s [`JsonSchema`] implementation,
57    /// including any doc-comment descriptions on fields.
58    pub fn new<F, Fut>(name: impl Into<String>, description: impl Into<String>, handler: F) -> Self
59    where
60        F: Fn(T) -> Fut + Send + Sync + 'static,
61        Fut: std::future::Future<Output = Result<serde_json::Value, ToolError>> + Send + 'static,
62    {
63        let schema = super::wire_schema::<T>();
64
65        Self {
66            name: name.into(),
67            description: description.into(),
68            schema,
69            handler: Box::new(move |args| Box::pin(handler(args))),
70            _phantom: PhantomData,
71        }
72    }
73}
74
75#[async_trait]
76impl<T: DeserializeOwned + JsonSchema + Send + Sync + 'static> ToolFunction for TypedTool<T> {
77    fn name(&self) -> &str {
78        &self.name
79    }
80
81    fn description(&self) -> &str {
82        &self.description
83    }
84
85    fn parameters(&self) -> Option<serde_json::Value> {
86        Some(self.schema.clone())
87    }
88
89    async fn call(&self, args: serde_json::Value) -> Result<serde_json::Value, ToolError> {
90        let typed_args: T = serde_json::from_value(args)
91            .map_err(|e| ToolError::InvalidArgs(format!("Failed to deserialize arguments: {e}")))?;
92        (self.handler)(typed_args).await
93    }
94}
95
96#[cfg(test)]
97mod tests {
98    use super::*;
99    use serde::Deserialize;
100
101    /// A nested type is what triggers `definitions` + `$ref`.
102    #[derive(Deserialize, JsonSchema)]
103    #[allow(dead_code, reason = "fixture types exist only to derive a schema")]
104    enum Scope {
105        Recent,
106        Persistent,
107    }
108
109    #[derive(Deserialize, JsonSchema)]
110    #[allow(dead_code, reason = "fixture types exist only to derive a schema")]
111    struct Args {
112        /// What to look for.
113        query: String,
114        /// Which slice to search.
115        scope: Scope,
116        /// Optional — the construct the API rejects outright.
117        note: Option<String>,
118    }
119
120    fn schema_of<T: DeserializeOwned + JsonSchema + Send + Sync + 'static>() -> serde_json::Value {
121        TypedTool::<T>::new("probe", "Probe", |_: T| async { Ok(serde_json::json!({})) })
122            .parameters()
123            .expect("typed tools declare parameters")
124    }
125
126    /// A declaration that points outside itself is not merely useless — the
127    /// Live endpoint closes the connection during setup rather than accept it,
128    /// and the batch endpoints ignore the constraint and let the model invent
129    /// enum variants that will not deserialize.
130    #[test]
131    fn a_nested_type_does_not_leak_refs_into_the_declaration() {
132        let rendered = schema_of::<Args>().to_string();
133
134        assert!(
135            !rendered.contains("$ref"),
136            "the API does not resolve $ref, so the schema silently stops \
137             constraining: {rendered}"
138        );
139        assert!(
140            !rendered.contains("definitions"),
141            "schema leaks definitions: {rendered}"
142        );
143        assert!(
144            !rendered.contains("$schema"),
145            "schema leaks its meta-schema: {rendered}"
146        );
147    }
148
149    /// Inlining must preserve the constraint, not just remove the pointer.
150    #[test]
151    fn the_inlined_schema_still_carries_the_enum_variants() {
152        let schema = schema_of::<Args>();
153        let scope = &schema["properties"]["scope"];
154
155        assert_eq!(
156            scope["type"], "string",
157            "a fieldless enum must narrow to a plain string type: {scope}"
158        );
159        assert_eq!(
160            scope["enum"],
161            serde_json::json!(["Recent", "Persistent"]),
162            "flattening dropped the variants it was supposed to preserve: {scope}"
163        );
164        assert!(
165            scope.get("oneOf").is_none(),
166            "the API does not understand `oneOf` here, so the constraint would \
167             silently stop applying: {scope}"
168        );
169    }
170
171    /// The one that closes a Live session mid-handshake: `Option<String>`
172    /// derives `"type": ["string", "null"]`, and the API's `Schema.type` is a
173    /// single value. It rejects the whole request rather than ignoring it.
174    #[test]
175    fn an_optional_field_does_not_declare_a_union_type() {
176        let schema = schema_of::<Args>();
177        let note = &schema["properties"]["note"];
178
179        assert_eq!(
180            note["type"], "string",
181            "a union type is rejected outright by the API: {note}"
182        );
183        assert!(
184            !schema["required"]
185                .as_array()
186                .expect("required list")
187                .iter()
188                .any(|r| r == "note"),
189            "optionality must still be carried by absence from `required`: {schema}"
190        );
191    }
192}