1use std::any::Any;
19use std::panic::AssertUnwindSafe;
20use std::sync::Arc;
21
22use async_trait::async_trait;
23use futures::FutureExt;
24use futures::future::BoxFuture;
25use gadk_agent::{Context, RunnableTool, Tool, ToolError, ToolOriginKind};
26use gadk_genai::FunctionDeclaration;
27use serde_json::{Map, Value};
28
29use crate::tool::utils::{
30 CompiledSchema, convert_args_with_schema, convert_with_schema, infer_output_schema,
31 infer_schema, json_kind_article, panic_message, schema_expects_object, validate_with_schema,
32};
33
34pub(crate) const LONG_RUNNING_NOTE: &str = "NOTE: This is a long-running operation. Do not call this tool again if it has already returned some intermediate or pending status.";
36
37#[derive(Clone)]
42pub struct FunctionToolConfig {
43 pub name: String,
45 pub description: String,
47 pub input_schema: Option<Value>,
49 pub output_schema: Option<Value>,
51 pub is_long_running: bool,
53 pub require_confirmation: bool,
55 pub origin: ToolOriginKind,
59}
60
61impl Default for FunctionToolConfig {
62 fn default() -> Self {
65 Self {
66 name: String::new(),
67 description: String::new(),
68 input_schema: None,
69 output_schema: None,
70 is_long_running: false,
71 require_confirmation: false,
72 origin: ToolOriginKind::Local,
73 }
74 }
75}
76
77impl FunctionToolConfig {
78 pub fn new(name: impl Into<String>, description: impl Into<String>) -> Self {
80 Self {
81 name: name.into(),
82 description: description.into(),
83 ..Default::default()
84 }
85 }
86}
87
88type ErasedRun = Arc<
89 dyn Fn(Context, Value) -> BoxFuture<'static, Result<Map<String, Value>, ToolError>>
90 + Send
91 + Sync,
92>;
93
94pub struct FunctionTool {
99 cfg: FunctionToolConfig,
100 input_schema: Arc<CompiledSchema>,
101 output_schema: Arc<CompiledSchema>,
102 run: ErasedRun,
103}
104
105pub(crate) fn check_args_type<Args: schemars::JsonSchema>() -> Result<(), ToolError> {
109 if schema_expects_object(&infer_schema::<Args>()) {
110 return Ok(());
111 }
112 Err(ToolError::InvalidArgument(format!(
113 "input must be a struct or a map or a pointer to those types, but received: {}: invalid argument",
114 std::any::type_name::<Args>()
115 )))
116}
117
118pub(crate) fn resolved_schema(
120 override_schema: Option<&Value>,
121 inferred: impl FnOnce() -> Value,
122 what: &str,
123) -> Result<CompiledSchema, ToolError> {
124 let schema = override_schema.cloned().unwrap_or_else(inferred);
125 CompiledSchema::new(schema)
126 .map_err(|e| ToolError::InvalidArgument(format!("failed to infer {what} schema: {e}")))
127}
128
129pub(crate) fn declaration(
131 cfg: &FunctionToolConfig,
132 input: &CompiledSchema,
133 output: Option<&CompiledSchema>,
134) -> FunctionDeclaration {
135 let mut description = cfg.description.clone();
136 if cfg.is_long_running {
137 if description.is_empty() {
138 description = LONG_RUNNING_NOTE.to_string();
139 } else {
140 description.push_str("\n\n");
141 description.push_str(LONG_RUNNING_NOTE);
142 }
143 }
144 FunctionDeclaration {
145 name: cfg.name.clone(),
146 description,
147 parameters_json_schema: Some(input.schema().clone()),
148 response_json_schema: output.map(|s| s.schema().clone()),
149 ..Default::default()
150 }
151}
152
153pub(crate) fn check_confirmation(
157 ctx: &Context,
158 name: &str,
159 require: impl FnOnce() -> bool,
160) -> Result<(), ToolError> {
161 if let Some(confirmation) = ctx.tool_confirmation() {
162 return if confirmation.confirmed {
163 Ok(())
164 } else {
165 Err(ToolError::ConfirmationRejected)
166 };
167 }
168 if !require() {
169 return Ok(());
170 }
171 ctx.request_confirmation(
172 &format!(
173 "Please approve or reject the tool call {name}() by responding with a FunctionResponse with an expected ToolConfirmation payload."
174 ),
175 None,
176 )?;
177 ctx.update_actions(|a| a.skip_summarization = true);
178 Err(ToolError::ConfirmationRequired)
179}
180
181fn result_map(v: Value) -> Result<Map<String, Value>, String> {
184 match v {
185 Value::Null => Ok(Map::new()),
186 v => serde_json::from_value(v).map_err(|e| e.to_string()),
187 }
188}
189
190pub(crate) fn check_args_value(args: &Value) -> Result<(), ToolError> {
192 match args {
193 Value::Object(_) | Value::Null => Ok(()),
194 other => Err(ToolError::InvalidArgument(format!(
195 "unexpected args type: expected a JSON object, found {}",
196 json_kind_article(other)
197 ))),
198 }
199}
200
201impl FunctionTool {
202 #[allow(clippy::new_ret_no_self)] pub fn new<Args, Out, F, Fut>(cfg: FunctionToolConfig, f: F) -> Result<Arc<dyn Tool>, ToolError>
208 where
209 Args: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static,
210 Out: serde::Serialize + schemars::JsonSchema + Send + 'static,
211 F: Fn(Context, Args) -> Fut + Send + Sync + 'static,
212 Fut: std::future::Future<Output = Result<Out, ToolError>> + Send + 'static,
213 {
214 Self::build::<Args, Out, F, Fut, fn(&Args) -> bool>(cfg, f, None)
215 }
216
217 pub fn with_confirmation_provider<Args, Out, F, Fut, P>(
221 cfg: FunctionToolConfig,
222 f: F,
223 provider: P,
224 ) -> Result<Arc<dyn Tool>, ToolError>
225 where
226 Args: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static,
227 Out: serde::Serialize + schemars::JsonSchema + Send + 'static,
228 F: Fn(Context, Args) -> Fut + Send + Sync + 'static,
229 Fut: std::future::Future<Output = Result<Out, ToolError>> + Send + 'static,
230 P: Fn(&Args) -> bool + Send + Sync + 'static,
231 {
232 Self::build(cfg, f, Some(provider))
233 }
234
235 fn build<Args, Out, F, Fut, P>(
236 cfg: FunctionToolConfig,
237 f: F,
238 provider: Option<P>,
239 ) -> Result<Arc<dyn Tool>, ToolError>
240 where
241 Args: serde::de::DeserializeOwned + schemars::JsonSchema + Send + 'static,
242 Out: serde::Serialize + schemars::JsonSchema + Send + 'static,
243 F: Fn(Context, Args) -> Fut + Send + Sync + 'static,
244 Fut: std::future::Future<Output = Result<Out, ToolError>> + Send + 'static,
245 P: Fn(&Args) -> bool + Send + Sync + 'static,
246 {
247 check_args_type::<Args>()?;
248 let input_schema = Arc::new(resolved_schema(
249 cfg.input_schema.as_ref(),
250 infer_schema::<Args>,
251 "input",
252 )?);
253 let output_schema = Arc::new(resolved_schema(
254 cfg.output_schema.as_ref(),
255 infer_output_schema::<Out>,
256 "output",
257 )?);
258
259 let f = Arc::new(f);
260 let provider = provider.map(Arc::new);
261 let name = cfg.name.clone();
262 let require_confirmation = cfg.require_confirmation;
263 let explicit_output = cfg.output_schema.is_some();
264 let (in_schema, out_schema) = (input_schema.clone(), output_schema.clone());
265 let run: ErasedRun = Arc::new(move |ctx: Context, args: Value| {
266 let (f, provider, name) = (f.clone(), provider.clone(), name.clone());
267 let (input_schema, output_schema) = (in_schema.clone(), out_schema.clone());
268 async move {
269 check_args_value(&args)?;
270 let input: Args = convert_args_with_schema(&args, Some(&input_schema))
271 .map_err(ToolError::InvalidArgument)?;
272 check_confirmation(&ctx, &name, || {
273 provider
274 .as_ref()
275 .map_or(require_confirmation, |p| p(&input))
276 })?;
277 let output: Out = f(ctx, input).await?;
278 let conv_err =
279 match convert_with_schema::<Out, Value>(&output, Some(&output_schema))
280 .and_then(result_map)
281 {
282 Ok(m) => return Ok(m),
283 Err(e) => e,
284 };
285 let value =
288 serde_json::to_value(&output).map_err(|e| ToolError::Execution(e.into()))?;
289 if explicit_output && validate_with_schema(&output, Some(&output_schema)).is_err() {
292 return Err(ToolError::Execution(conv_err.into()));
293 }
294 Ok(Map::from_iter([("result".to_string(), value)]))
295 }
296 .boxed()
297 });
298 Ok(Arc::new(FunctionTool {
299 cfg,
300 input_schema,
301 output_schema,
302 run,
303 }))
304 }
305}
306
307impl Tool for FunctionTool {
308 fn name(&self) -> &str {
309 &self.cfg.name
310 }
311
312 fn description(&self) -> &str {
313 &self.cfg.description
314 }
315
316 fn is_long_running(&self) -> bool {
317 self.cfg.is_long_running
318 }
319
320 fn declaration(&self) -> Option<FunctionDeclaration> {
321 Some(declaration(
322 &self.cfg,
323 &self.input_schema,
324 Some(&self.output_schema),
325 ))
326 }
327
328 fn as_runnable(&self) -> Option<&dyn RunnableTool> {
332 Some(self)
333 }
334
335 fn origin_kind(&self) -> ToolOriginKind {
337 self.cfg.origin
338 }
339
340 fn as_any(&self) -> &dyn Any {
341 self
342 }
343}
344
345#[async_trait]
346impl RunnableTool for FunctionTool {
347 async fn run(&self, ctx: Context, args: Value) -> Result<Map<String, Value>, ToolError> {
351 match AssertUnwindSafe((self.run)(ctx, args)).catch_unwind().await {
352 Ok(result) => result,
353 Err(payload) => Err(ToolError::Panic(format!(
354 "panic in tool {}: {}",
355 gadk_agent::go_quote(&self.cfg.name),
356 panic_message(&*payload)
357 ))),
358 }
359 }
360}
361
362#[cfg(test)]
363#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
364mod origin_tests {
365 use super::*;
366
367 #[derive(serde::Deserialize, schemars::JsonSchema)]
368 struct NoArgs {}
369
370 fn tool(cfg: FunctionToolConfig) -> Arc<dyn Tool> {
371 FunctionTool::new(cfg, |_ctx: Context, _args: NoArgs| async {
372 Ok::<_, ToolError>(String::new())
373 })
374 .unwrap()
375 }
376
377 #[test]
378 fn config_origin_defaults_to_local() {
379 assert_eq!(
380 FunctionToolConfig::new("t", "").origin,
381 ToolOriginKind::Local
382 );
383 assert_eq!(FunctionToolConfig::default().origin, ToolOriginKind::Local);
384 }
385
386 #[test]
387 fn function_tool_reports_its_configured_origin() {
388 let local = tool(FunctionToolConfig::new("t", ""));
389 assert_eq!(local.origin_kind(), ToolOriginKind::Local);
390 assert!(local.origin_agent().is_none());
391 assert!(local.unwrap().is_none());
392 let skill = tool(FunctionToolConfig {
393 origin: ToolOriginKind::Skill,
394 ..FunctionToolConfig::new("t", "")
395 });
396 assert_eq!(skill.origin_kind(), ToolOriginKind::Skill);
397 }
398}