Skip to main content

gadk_engine/tool/
function.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! Function tool: a tool wrapping a typed async function.
17
18use 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, go_type_name,
31    infer_output_schema, infer_schema, panic_message, schema_expects_object, validate_with_schema,
32};
33
34/// The note added to a long-running tool's declaration.
35pub(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/// Configuration of a function tool.
38///
39/// A confirmation provider is the typed `provider` argument of
40/// [`FunctionTool::with_confirmation_provider`] / `StreamingFunctionTool::with_confirmation_provider`.
41#[derive(Clone)]
42pub struct FunctionToolConfig {
43    /// The tool name.
44    pub name: String,
45    /// The tool description sent to the model.
46    pub description: String,
47    /// Overrides the input schema inferred from the handler's argument type.
48    pub input_schema: Option<Value>,
49    /// Overrides the output schema inferred from the handler's result type.
50    pub output_schema: Option<Value>,
51    /// Whether the tool is a long-running operation (adds a note to the declaration).
52    pub is_long_running: bool,
53    /// Whether every call requires a Human-in-the-Loop confirmation.
54    pub require_confirmation: bool,
55    /// What [`Tool::origin_kind`] reports for the built tool (default [`ToolOriginKind::Local`],
56    /// as the analytics plugin classifies a function tool). gadk's skill tools set
57    /// [`ToolOriginKind::Skill`] here instead.
58    pub origin: ToolOriginKind,
59}
60
61impl Default for FunctionToolConfig {
62    /// Every field at its zero value except [`origin`](FunctionToolConfig::origin), which is
63    /// [`ToolOriginKind::Local`].
64    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    /// A config with the given name and description and every other field at its default.
79    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
94/// A tool wrapping a typed async Rust function.
95///
96/// The input (and output) JSON schemas are inferred from the handler's argument and result types unless
97/// [`FunctionToolConfig`] overrides them. Type-erased: the generic handler lives in `run`.
98pub struct FunctionTool {
99    cfg: FunctionToolConfig,
100    input_schema: Arc<CompiledSchema>,
101    output_schema: Arc<CompiledSchema>,
102    run: ErasedRun,
103}
104
105/// Checks the kind of the argument type (struct, map, or pointer to those
106/// ⇔ the inferred schema's root type is or includes "object"). Checked on the inferred schema
107/// even when `cfg.input_schema` overrides it.
108pub(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
118/// The override when given, else the inferred schema; compiled.
119pub(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
129/// The function declaration (shared by both tool variants).
130pub(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
153/// The confirmation check of a call. `Ok(())` ⇒ proceed to the handler.
154///
155/// `require` is evaluated only when the context carries no confirmation.
156pub(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
181/// Turns a result value into a map: a `null` that passed the output schema becomes an empty
182/// map, not an error.
183fn 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
190/// Accepts an object or `null`; any other value is an "unexpected args type" error.
191pub(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, got: {}",
196            go_type_name(other)
197        ))),
198    }
199}
200
201impl FunctionTool {
202    /// A tool calling `f` with arguments decoded (and validated) as `Args`.
203    ///
204    /// Fails with [`ToolError::InvalidArgument`] when `Args` is not an object type or a schema cannot be
205    /// compiled.
206    #[allow(clippy::new_ret_no_self)] // returns the tool as `Arc<dyn Tool>`
207    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    /// Like [`FunctionTool::new`], with a confirmation provider: when the call carries no
218    /// confirmation, `provider(&args)` decides whether one is required, overriding
219    /// `cfg.require_confirmation`.
220    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                // A result that cannot be represented as JSON must not be wrapped: it cannot be
286                // sent.
287                let value =
288                    serde_json::to_value(&output).map_err(|e| ToolError::Execution(e.into()))?;
289                // A schema inferred from the output type describes the type, not what
290                // serialization emits for it, so only an explicit output schema is enforced.
291                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    // `process_request` is deliberately not overridden: its job is `pack_tool`, which
329    // the flow runs via `gadk_agent::pack_tool` before calling `Tool::process_request`.
330
331    fn as_runnable(&self) -> Option<&dyn RunnableTool> {
332        Some(self)
333    }
334
335    /// [`FunctionToolConfig::origin`] (default [`ToolOriginKind::Local`]).
336    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    /// Runs the handler. A panic becomes [`ToolError::Panic`] with the text
348    /// `panic in tool "<name>": <message>` (no stack: Rust cannot capture the panicking stack
349    /// after unwinding).
350    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}