gemini_adk_rs/tool/
typed.rs1use 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
14type TypedHandler<T> =
16 Box<dyn Fn(T) -> BoxFuture<Result<serde_json::Value, ToolError>> + Send + Sync>;
17
18pub 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 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 #[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 query: String,
114 scope: Scope,
116 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 #[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 #[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 #[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}