Skip to main content

adk_tool/
stateful_tool.rs

1use adk_core::{Result, Tool, ToolContext};
2use async_trait::async_trait;
3use schemars::{
4    JsonSchema,
5    generate::{SchemaGenerator, SchemaSettings},
6};
7use serde::Serialize;
8use serde_json::Value;
9use std::future::Future;
10use std::pin::Pin;
11use std::sync::Arc;
12
13type AsyncStatefulHandler<S> = Box<
14    dyn Fn(
15            Arc<S>,
16            Arc<dyn ToolContext>,
17            Value,
18        ) -> Pin<Box<dyn Future<Output = Result<Value>> + Send>>
19        + Send
20        + Sync,
21>;
22
23/// A generic tool wrapper that manages shared state for stateful closures.
24///
25/// `StatefulTool<S>` accepts an `Arc<S>` and a handler closure that receives
26/// the state alongside the tool context and arguments. The `Arc<S>` is cloned
27/// (cheap reference count bump) on each invocation, so all executions share
28/// the same underlying state.
29///
30/// # Example
31///
32/// ```rust,ignore
33/// use adk_tool::StatefulTool;
34/// use adk_core::{ToolContext, Result};
35/// use serde_json::{json, Value};
36/// use std::sync::Arc;
37/// use tokio::sync::RwLock;
38///
39/// struct Counter { count: RwLock<u64> }
40///
41/// let state = Arc::new(Counter { count: RwLock::new(0) });
42///
43/// let tool = StatefulTool::new(
44///     "increment",
45///     "Increment a counter",
46///     state,
47///     |s, _ctx, _args| async move {
48///         let mut count = s.count.write().await;
49///         *count += 1;
50///         Ok(json!({ "count": *count }))
51///     },
52/// );
53/// ```
54pub struct StatefulTool<S: Send + Sync + 'static> {
55    name: String,
56    description: String,
57    state: Arc<S>,
58    handler: AsyncStatefulHandler<S>,
59    long_running: bool,
60    read_only: bool,
61    concurrency_safe: bool,
62    parameters_schema: Option<Value>,
63    arguments: Option<crate::arguments::ArgumentCheck>,
64    lenient_args: bool,
65    response_schema: Option<Value>,
66    scopes: Vec<&'static str>,
67}
68
69impl<S: Send + Sync + 'static> StatefulTool<S> {
70    /// Create a new stateful tool.
71    ///
72    /// # Arguments
73    ///
74    /// * `name` - Tool name exposed to the LLM
75    /// * `description` - Human-readable description of what the tool does
76    /// * `state` - Shared state wrapped in `Arc<S>`
77    /// * `handler` - Async closure receiving `(Arc<S>, Arc<dyn ToolContext>, Value)`
78    pub fn new<F, Fut>(
79        name: impl Into<String>,
80        description: impl Into<String>,
81        state: Arc<S>,
82        handler: F,
83    ) -> Self
84    where
85        F: Fn(Arc<S>, Arc<dyn ToolContext>, Value) -> Fut + Send + Sync + 'static,
86        Fut: Future<Output = Result<Value>> + Send + 'static,
87    {
88        Self {
89            name: name.into(),
90            description: description.into(),
91            state,
92            handler: Box::new(move |s, ctx, args| Box::pin(handler(s, ctx, args))),
93            long_running: false,
94            read_only: false,
95            concurrency_safe: false,
96            parameters_schema: None,
97            arguments: None,
98            lenient_args: false,
99            response_schema: None,
100            scopes: Vec::new(),
101        }
102    }
103
104    /// Mark this tool as long-running (prevents duplicate invocations).
105    pub fn with_long_running(mut self, long_running: bool) -> Self {
106        self.long_running = long_running;
107        self
108    }
109
110    /// Mark this tool as read-only (safe for parallel dispatch).
111    pub fn with_read_only(mut self, read_only: bool) -> Self {
112        self.read_only = read_only;
113        self
114    }
115
116    /// Mark this tool as concurrency-safe (can run in parallel with other tools).
117    pub fn with_concurrency_safe(mut self, concurrency_safe: bool) -> Self {
118        self.concurrency_safe = concurrency_safe;
119        self
120    }
121
122    /// Derive the parameters JSON Schema from a type implementing `JsonSchema`, and
123    /// check each call's arguments against it as
124    /// [`FunctionTool`](crate::FunctionTool#argument-validation) does.
125    pub fn with_parameters_schema<T>(mut self) -> Self
126    where
127        T: JsonSchema + Serialize,
128    {
129        self.parameters_schema = Some(generate_schema::<T>());
130        self.arguments = Some(crate::arguments::ArgumentCheck::for_type::<T>());
131        self
132    }
133
134    /// Turn off the argument check of [`with_parameters_schema`](Self::with_parameters_schema);
135    /// integral floats at integer fields are still read as integers.
136    pub fn with_lenient_args(mut self, lenient: bool) -> Self {
137        self.lenient_args = lenient;
138        self
139    }
140
141    /// Derive the response JSON Schema from a type implementing `JsonSchema`.
142    pub fn with_response_schema<T>(mut self) -> Self
143    where
144        T: JsonSchema + Serialize,
145    {
146        self.response_schema = Some(generate_schema::<T>());
147        self
148    }
149
150    /// Declare the scopes required to execute this tool.
151    ///
152    /// When set, the framework will enforce that the calling user possesses
153    /// **all** listed scopes before dispatching `execute()`.
154    pub fn with_scopes(mut self, scopes: &[&'static str]) -> Self {
155        self.scopes = scopes.to_vec();
156        self
157    }
158
159    /// Get the parameters schema, if set.
160    pub fn parameters_schema(&self) -> Option<&Value> {
161        self.parameters_schema.as_ref()
162    }
163
164    /// Get the response schema, if set.
165    pub fn response_schema(&self) -> Option<&Value> {
166        self.response_schema.as_ref()
167    }
168}
169
170/// The note appended to long-running tool descriptions to prevent duplicate calls.
171const 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.";
172
173#[async_trait]
174impl<S: Send + Sync + 'static> Tool for StatefulTool<S> {
175    fn name(&self) -> &str {
176        &self.name
177    }
178
179    fn description(&self) -> &str {
180        &self.description
181    }
182
183    fn enhanced_description(&self) -> String {
184        if self.long_running {
185            if self.description.is_empty() {
186                LONG_RUNNING_NOTE.to_string()
187            } else {
188                format!("{}\n\n{}", self.description, LONG_RUNNING_NOTE)
189            }
190        } else {
191            self.description.clone()
192        }
193    }
194
195    fn is_long_running(&self) -> bool {
196        self.long_running
197    }
198
199    fn is_read_only(&self) -> bool {
200        self.read_only
201    }
202
203    fn is_concurrency_safe(&self) -> bool {
204        self.concurrency_safe
205    }
206
207    fn parameters_schema(&self) -> Option<Value> {
208        self.parameters_schema.clone()
209    }
210
211    fn response_schema(&self) -> Option<Value> {
212        self.response_schema.clone()
213    }
214
215    fn required_scopes(&self) -> &[&str] {
216        &self.scopes
217    }
218
219    #[adk_telemetry::instrument(
220        skip(self, ctx, args),
221        fields(
222            tool.name = %self.name,
223            tool.description = %self.description,
224            tool.long_running = %self.long_running,
225            function_call.id = %ctx.function_call_id()
226        )
227    )]
228    async fn execute(&self, ctx: Arc<dyn ToolContext>, mut args: Value) -> Result<Value> {
229        adk_telemetry::debug!("Executing stateful tool");
230        if let Some(check) = &self.arguments {
231            check.apply(&self.name, self.lenient_args, &mut args)?;
232        }
233        let state = Arc::clone(&self.state);
234        (self.handler)(state, ctx, args).await
235    }
236}
237
238fn generate_schema<T>() -> Value
239where
240    T: JsonSchema + Serialize,
241{
242    let settings = SchemaSettings::openapi3().with(|s| {
243        s.inline_subschemas = true;
244        s.meta_schema = None;
245    });
246    let generator = SchemaGenerator::new(settings);
247    let mut schema = generator.into_root_schema_for::<T>();
248    if let Some(object) = schema.as_object_mut() {
249        object.remove("title");
250    }
251    serde_json::to_value(schema).unwrap()
252}