Skip to main content

adk_tool/
function_tool.rs

1use crate::arguments::ArgumentCheck;
2use adk_core::egress::ToolEgress;
3use adk_core::{Result, Tool, ToolContext, ToolEffect};
4use async_trait::async_trait;
5use schemars::{
6    JsonSchema,
7    generate::{SchemaGenerator, SchemaSettings},
8};
9use serde::Serialize;
10use serde_json::Value;
11use std::future::Future;
12use std::pin::Pin;
13use std::sync::Arc;
14
15type AsyncHandler = Box<
16    dyn Fn(Arc<dyn ToolContext>, Value) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>>
17        + Send
18        + Sync,
19>;
20
21/// A tool created from an async Rust function.
22///
23/// `FunctionTool` wraps an async closure and exposes it as a [`Tool`] that
24/// LLM agents can invoke. Use the builder methods to configure schema,
25/// execution flags, and required scopes.
26///
27/// # Argument validation
28///
29/// A tool given a schema with [`with_parameters_schema`](Self::with_parameters_schema)
30/// checks each call's arguments against it before the handler runs, as `#[tool]` does:
31/// a key the type does not declare, a value outside a `#[schemars(range(...))]`,
32/// `length(...)` or `pattern(...)` bound, or a missing required field fails the call
33/// with an `ErrorCategory::InvalidInput` error with code
34/// [`TOOL_INVALID_ARGUMENTS_CODE`](adk_core::TOOL_INVALID_ARGUMENTS_CODE) that the model
35/// sees and can correct. An integral float at an integer field, such as `3.0`, reaches
36/// the handler as the integer. [`with_lenient_args`](Self::with_lenient_args) turns the
37/// check off.
38pub struct FunctionTool {
39    name: String,
40    description: String,
41    handler: AsyncHandler,
42    long_running: bool,
43    read_only: bool,
44    concurrency_safe: bool,
45    effect: Option<ToolEffect>,
46    parameters_schema: Option<Value>,
47    arguments: Option<ArgumentCheck>,
48    lenient_args: bool,
49    response_schema: Option<Value>,
50    scopes: Vec<&'static str>,
51    egress: Option<EgressFn>,
52}
53
54/// What a [`FunctionTool`] declares about a call's network destinations, from its arguments.
55type EgressFn = Box<dyn Fn(&Value) -> ToolEgress + Send + Sync>;
56
57impl FunctionTool {
58    /// Create a new `FunctionTool` from an async handler function.
59    pub fn new<F, Fut>(name: impl Into<String>, description: impl Into<String>, handler: F) -> Self
60    where
61        F: Fn(Arc<dyn ToolContext>, Value) -> Fut + Send + Sync + 'static,
62        Fut: Future<Output = Result<Value>> + Send + 'static,
63    {
64        Self {
65            name: name.into(),
66            description: description.into(),
67            handler: Box::new(move |ctx, args| Box::pin(handler(ctx, args))),
68            long_running: false,
69            read_only: false,
70            concurrency_safe: false,
71            effect: None,
72            parameters_schema: None,
73            arguments: None,
74            lenient_args: false,
75            response_schema: None,
76            scopes: Vec::new(),
77            egress: None,
78        }
79    }
80
81    /// Mark this tool as long-running (prevents duplicate invocations).
82    pub fn with_long_running(mut self, long_running: bool) -> Self {
83        self.long_running = long_running;
84        self
85    }
86
87    /// Mark this tool as read-only (safe for parallel dispatch).
88    pub fn with_read_only(mut self, read_only: bool) -> Self {
89        self.read_only = read_only;
90        self
91    }
92
93    /// Mark this tool as concurrency-safe (can run in parallel with other tools).
94    pub fn with_concurrency_safe(mut self, concurrency_safe: bool) -> Self {
95        self.concurrency_safe = concurrency_safe;
96        self
97    }
98
99    /// Declare the tool's side-effect class.
100    ///
101    /// Without this, the effect follows [`with_read_only`](Self::with_read_only):
102    /// [`ToolEffect::ReadOnly`] for a read-only tool, otherwise
103    /// [`ToolEffect::NonIdempotent`]. Only `ReadOnly` and `Idempotent` tools are
104    /// retried under a [`RetryBudget`](adk_core::RetryBudget).
105    ///
106    /// # Example
107    ///
108    /// ```rust
109    /// use adk_core::{Tool, ToolEffect};
110    /// use adk_tool::FunctionTool;
111    ///
112    /// let tool = FunctionTool::new("set_status", "Sets the ticket status", |_ctx, args| async move {
113    ///     Ok(args)
114    /// })
115    /// .with_effect(ToolEffect::Idempotent);
116    /// assert_eq!(tool.effect(), ToolEffect::Idempotent);
117    /// ```
118    pub fn with_effect(mut self, effect: ToolEffect) -> Self {
119        self.effect = Some(effect);
120        self
121    }
122
123    /// Declares the network destinations every call reaches ([`Tool::egress`]); without a
124    /// declaration a run with an egress policy refuses the tool.
125    ///
126    /// # Example
127    ///
128    /// ```rust
129    /// use adk_core::Tool;
130    /// use adk_core::egress::ToolEgress;
131    /// use adk_tool::FunctionTool;
132    /// use serde_json::json;
133    ///
134    /// let add = FunctionTool::new("add", "Adds two numbers", |_ctx, args| async move {
135    ///     Ok(json!(args["a"].as_f64().unwrap_or(0.0) + args["b"].as_f64().unwrap_or(0.0)))
136    /// })
137    /// .with_egress(ToolEgress::None);
138    /// assert_eq!(add.egress(&json!({})), ToolEgress::None);
139    /// ```
140    pub fn with_egress(self, egress: ToolEgress) -> Self {
141        self.with_egress_fn(move |_args| egress.clone())
142    }
143
144    /// Declares the network destinations of each call from its arguments ([`Tool::egress`]),
145    /// for a tool whose destination is an argument.
146    ///
147    /// # Example
148    ///
149    /// ```rust
150    /// use adk_core::Tool;
151    /// use adk_core::egress::ToolEgress;
152    /// use adk_tool::FunctionTool;
153    /// use serde_json::json;
154    ///
155    /// let fetch = FunctionTool::new("fetch", "Fetches a URL", |_ctx, args| async move { Ok(args) })
156    ///     .with_egress_fn(|args| ToolEgress::for_urls([args["url"].as_str().unwrap_or_default()]));
157    /// assert_eq!(
158    ///     fetch.egress(&json!({ "url": "https://docs.rs/adk" })),
159    ///     ToolEgress::for_urls(["https://docs.rs/"])
160    /// );
161    /// ```
162    pub fn with_egress_fn(
163        mut self,
164        egress: impl Fn(&Value) -> ToolEgress + Send + Sync + 'static,
165    ) -> Self {
166        self.egress = Some(Box::new(egress));
167        self
168    }
169
170    /// Derive the parameters JSON Schema from a type implementing `JsonSchema`, and
171    /// check each call's arguments against it; see [Argument validation](Self#argument-validation).
172    ///
173    /// # Example
174    ///
175    /// ```rust
176    /// use adk_core::{TOOL_INVALID_ARGUMENTS_CODE, Tool};
177    /// use adk_tool::{FunctionTool, SimpleToolContext};
178    /// use schemars::JsonSchema;
179    /// use serde::Serialize;
180    /// use serde_json::json;
181    /// use std::sync::Arc;
182    ///
183    /// #[derive(Serialize, JsonSchema)]
184    /// struct Order {
185    ///     #[schemars(range(min = 1, max = 5))]
186    ///     quantity: u32,
187    /// }
188    ///
189    /// # #[tokio::main(flavor = "current_thread")]
190    /// # async fn main() {
191    /// let tool = FunctionTool::new("order", "Orders widgets", |_ctx, args| async move { Ok(args) })
192    ///     .with_parameters_schema::<Order>();
193    /// let ctx = Arc::new(SimpleToolContext::new("doc"));
194    ///
195    /// let err = tool.execute(ctx.clone(), json!({ "quantity": 50 })).await.unwrap_err();
196    /// assert_eq!(err.code, TOOL_INVALID_ARGUMENTS_CODE);
197    /// assert_eq!(tool.execute(ctx, json!({ "quantity": 3.0 })).await.unwrap(), json!({ "quantity": 3 }));
198    /// # }
199    /// ```
200    pub fn with_parameters_schema<T>(mut self) -> Self
201    where
202        T: JsonSchema + Serialize,
203    {
204        self.parameters_schema = Some(generate_schema::<T>());
205        self.arguments = Some(ArgumentCheck::for_type::<T>());
206        self
207    }
208
209    /// Turn off the argument check of [`with_parameters_schema`](Self::with_parameters_schema).
210    ///
211    /// The handler then receives the arguments as the model sent them, apart from integral
212    /// floats at integer fields: undeclared keys are kept and schema bounds are advisory.
213    pub fn with_lenient_args(mut self, lenient: bool) -> Self {
214        self.lenient_args = lenient;
215        self
216    }
217
218    /// Derive the response JSON Schema from a type implementing `JsonSchema`.
219    pub fn with_response_schema<T>(mut self) -> Self
220    where
221        T: JsonSchema + Serialize,
222    {
223        self.response_schema = Some(generate_schema::<T>());
224        self
225    }
226
227    /// Declare the scopes required to execute this tool.
228    ///
229    /// When set, the framework will enforce that the calling user possesses
230    /// **all** listed scopes before dispatching `execute()`.
231    ///
232    /// # Example
233    ///
234    /// ```rust,ignore
235    /// let tool = FunctionTool::new("transfer", "Transfer funds", handler)
236    ///     .with_scopes(&["finance:write", "verified"]);
237    /// ```
238    pub fn with_scopes(mut self, scopes: &[&'static str]) -> Self {
239        self.scopes = scopes.to_vec();
240        self
241    }
242
243    /// Get the parameters schema, if set.
244    pub fn parameters_schema(&self) -> Option<&Value> {
245        self.parameters_schema.as_ref()
246    }
247
248    /// Get the response schema, if set.
249    pub fn response_schema(&self) -> Option<&Value> {
250        self.response_schema.as_ref()
251    }
252}
253
254/// The note appended to long-running tool descriptions to prevent duplicate calls.
255const 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.";
256
257#[async_trait]
258impl Tool for FunctionTool {
259    fn name(&self) -> &str {
260        &self.name
261    }
262
263    fn description(&self) -> &str {
264        &self.description
265    }
266
267    /// Returns an enhanced description for long-running tools that includes
268    /// a note warning the model not to call the tool again if it's already pending.
269    fn enhanced_description(&self) -> String {
270        if self.long_running {
271            if self.description.is_empty() {
272                LONG_RUNNING_NOTE.to_string()
273            } else {
274                format!("{}\n\n{}", self.description, LONG_RUNNING_NOTE)
275            }
276        } else {
277            self.description.clone()
278        }
279    }
280
281    fn is_long_running(&self) -> bool {
282        self.long_running
283    }
284
285    fn is_read_only(&self) -> bool {
286        self.read_only
287    }
288
289    fn is_concurrency_safe(&self) -> bool {
290        self.concurrency_safe
291    }
292
293    fn effect(&self) -> ToolEffect {
294        match self.effect {
295            Some(effect) => effect,
296            None if self.read_only => ToolEffect::ReadOnly,
297            None => ToolEffect::NonIdempotent,
298        }
299    }
300
301    fn egress(&self, args: &Value) -> ToolEgress {
302        self.egress.as_ref().map_or(ToolEgress::Undeclared, |egress| egress(args))
303    }
304
305    fn parameters_schema(&self) -> Option<Value> {
306        self.parameters_schema.clone()
307    }
308
309    fn response_schema(&self) -> Option<Value> {
310        self.response_schema.clone()
311    }
312
313    fn required_scopes(&self) -> &[&str] {
314        &self.scopes
315    }
316
317    #[adk_telemetry::instrument(
318        skip(self, ctx, args),
319        fields(
320            tool.name = %self.name,
321            tool.description = %self.description,
322            tool.long_running = %self.long_running,
323            function_call.id = %ctx.function_call_id()
324        )
325    )]
326    async fn execute(&self, ctx: Arc<dyn ToolContext>, mut args: Value) -> Result<Value> {
327        adk_telemetry::debug!("Executing tool");
328        if let Some(check) = &self.arguments {
329            check.apply(&self.name, self.lenient_args, &mut args)?;
330        }
331        (self.handler)(ctx, args).await
332    }
333}
334
335fn generate_schema<T>() -> Value
336where
337    T: JsonSchema + Serialize,
338{
339    let settings = SchemaSettings::openapi3().with(|s| {
340        s.inline_subschemas = true;
341        s.meta_schema = None;
342    });
343    let generator = SchemaGenerator::new(settings);
344    let mut schema = generator.into_root_schema_for::<T>();
345    if let Some(object) = schema.as_object_mut() {
346        object.remove("title");
347    }
348    serde_json::to_value(schema).unwrap()
349}