Skip to main content

adk_core/
tool.rs

1use crate::{
2    CallbackContext, Event, EventActions, LlmRequest, Memory, MemoryEntry, ReadonlyContext, Result,
3    RunConfig, Session,
4};
5use async_trait::async_trait;
6use serde::{Deserialize, Serialize};
7use serde_json::Value;
8use std::sync::Arc;
9
10/// The core trait for all tools that agents can invoke.
11///
12/// Tools extend agent capabilities with custom functions. Each tool has a name,
13/// description, optional parameter schema, and an async `execute` method.
14#[async_trait]
15pub trait Tool: Send + Sync {
16    /// Returns the unique name of this tool.
17    fn name(&self) -> &str;
18    /// Returns a human-readable description of what this tool does.
19    fn description(&self) -> &str;
20
21    /// Returns the tool declaration that should be exposed to model providers.
22    ///
23    /// The default implementation produces the standard ADK function-tool
24    /// declaration (`name`, `description`, optional `parameters`, optional
25    /// `response`). Provider-specific built-in tools may override this to attach
26    /// additional metadata that the provider adapters understand.
27    ///
28    /// # Example
29    ///
30    /// ```rust,ignore
31    /// fn declaration(&self) -> serde_json::Value {
32    ///     serde_json::json!({
33    ///         "name": self.name(),
34    ///         "description": self.description(),
35    ///         "x-adk-openai-tool": {
36    ///             "type": "web_search"
37    ///         }
38    ///     })
39    /// }
40    /// ```
41    fn declaration(&self) -> Value {
42        let mut decl = serde_json::json!({
43            "name": self.name(),
44            "description": self.enhanced_description(),
45        });
46
47        if let Some(params) = self.parameters_schema() {
48            decl["parameters"] = params;
49        }
50
51        if let Some(response) = self.response_schema() {
52            decl["response"] = response;
53        }
54
55        decl
56    }
57
58    /// Returns an enhanced description that may include additional notes.
59    /// For long-running tools, this includes a warning not to call the tool
60    /// again if it has already returned a pending status.
61    /// Default implementation returns the base description.
62    fn enhanced_description(&self) -> String {
63        self.description().to_string()
64    }
65
66    /// Indicates whether the tool is a long-running operation.
67    /// Long-running tools typically return a task ID immediately and
68    /// complete the operation asynchronously.
69    fn is_long_running(&self) -> bool {
70        false
71    }
72
73    /// Indicates whether this tool is a built-in server-side tool (e.g., `google_search`, `url_context`).
74    ///
75    /// Built-in tools are executed server-side by the model provider and should not be
76    /// executed locally by the agent. The default implementation returns `false`.
77    fn is_builtin(&self) -> bool {
78        false
79    }
80
81    /// Returns the JSON Schema for this tool's parameters, if any.
82    fn parameters_schema(&self) -> Option<Value> {
83        None
84    }
85    /// Returns the JSON Schema for this tool's response, if any.
86    fn response_schema(&self) -> Option<Value> {
87        None
88    }
89
90    /// Returns the behaviour annotations the tool's publisher declared, if any.
91    ///
92    /// MCP tools return the server's `annotations` object unchanged, with its
93    /// camelCase keys: `title`, `readOnlyHint`, `destructiveHint`,
94    /// `idempotentHint`, and `openWorldHint`. The values are hints from the
95    /// publisher, not guarantees, so trust them only as far as the publisher.
96    /// The default returns `None`; tools that wrap another tool forward it.
97    ///
98    /// # Example
99    ///
100    /// ```rust
101    /// use adk_core::{Result, Tool, ToolContext};
102    /// use serde_json::{Value, json};
103    /// use std::sync::{Arc, LazyLock};
104    ///
105    /// static HINTS: LazyLock<Value> =
106    ///     LazyLock::new(|| json!({ "destructiveHint": true, "openWorldHint": false }));
107    ///
108    /// struct DeleteLogs;
109    ///
110    /// #[async_trait::async_trait]
111    /// impl Tool for DeleteLogs {
112    ///     fn name(&self) -> &str {
113    ///         "delete_logs"
114    ///     }
115    ///     fn description(&self) -> &str {
116    ///         "Deletes the service logs"
117    ///     }
118    ///     fn annotations(&self) -> Option<&Value> {
119    ///         Some(&HINTS)
120    ///     }
121    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
122    ///         Ok(Value::Null)
123    ///     }
124    /// }
125    ///
126    /// let destructive = DeleteLogs
127    ///     .annotations()
128    ///     .and_then(|hints| hints["destructiveHint"].as_bool())
129    ///     .unwrap_or(true);
130    /// assert!(destructive);
131    /// ```
132    fn annotations(&self) -> Option<&Value> {
133        None
134    }
135
136    /// Returns who publishes this tool: the toolset or server it comes from.
137    ///
138    /// A call held for approval records it in the call's [`ToolOrigin`](crate::ToolOrigin),
139    /// with a digest of [`declaration`](Self::declaration) and
140    /// [`annotations`](Self::annotations), and a decision applies only to calls to a tool
141    /// with the same origin and declaration. A held call that resumes against a tool with
142    /// another origin is answered as not run. MCP tools return `mcp:{toolset name}`; tools
143    /// that wrap another tool forward it. The default,
144    /// [`STATIC_TOOL_ORIGIN`](crate::STATIC_TOOL_ORIGIN), fits a tool compiled into the
145    /// agent.
146    ///
147    /// # Example
148    ///
149    /// ```rust
150    /// use adk_core::{Result, Tool, ToolContext};
151    /// use serde_json::Value;
152    /// use std::sync::Arc;
153    ///
154    /// /// A tool fetched from a plugin registry, identified by the registry entry.
155    /// struct RegistryTool {
156    ///     origin: String,
157    /// }
158    ///
159    /// #[async_trait::async_trait]
160    /// impl Tool for RegistryTool {
161    ///     fn name(&self) -> &str {
162    ///         "lookup"
163    ///     }
164    ///     fn description(&self) -> &str {
165    ///         "Looks up a customer"
166    ///     }
167    ///     fn origin(&self) -> &str {
168    ///         &self.origin
169    ///     }
170    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
171    ///         Ok(Value::Null)
172    ///     }
173    /// }
174    ///
175    /// let tool = RegistryTool { origin: "registry:crm@4".into() };
176    /// assert_eq!(tool.origin(), "registry:crm@4");
177    /// ```
178    fn origin(&self) -> &str {
179        crate::STATIC_TOOL_ORIGIN
180    }
181
182    /// Returns the scopes required to execute this tool.
183    ///
184    /// When non-empty, the framework can enforce that the calling user
185    /// possesses **all** listed scopes before dispatching `execute()`.
186    /// The default implementation returns an empty slice (no scopes required).
187    ///
188    /// # Example
189    ///
190    /// ```rust,ignore
191    /// fn required_scopes(&self) -> &[&str] {
192    ///     &["finance:write", "verified"]
193    /// }
194    /// ```
195    fn required_scopes(&self) -> &[&str] {
196        &[]
197    }
198
199    /// Indicates whether this tool performs no side effects.
200    ///
201    /// [`ToolExecutionStrategy::Auto`] overlaps a call with its adjacent
202    /// neighbours only when the selected tool is both read-only and
203    /// concurrency-safe.
204    fn is_read_only(&self) -> bool {
205        false
206    }
207
208    /// Returns the side-effect class of this tool.
209    ///
210    /// The runtime retries a failed call only when the effect is
211    /// [`ToolEffect::ReadOnly`] or [`ToolEffect::Idempotent`] and the error is
212    /// retryable, and records [`ToolEffect::NonIdempotent`] calls in the
213    /// [`ActionLedger`](crate::ActionLedger) when one is configured. The default
214    /// derives the effect from [`Tool::is_read_only`], so a tool that declares
215    /// nothing is treated as non-idempotent and never retried.
216    ///
217    /// # Example
218    ///
219    /// ```rust
220    /// use adk_core::{Result, Tool, ToolContext, ToolEffect};
221    /// use serde_json::{Value, json};
222    /// use std::sync::Arc;
223    ///
224    /// struct SetThermostat;
225    ///
226    /// #[async_trait::async_trait]
227    /// impl Tool for SetThermostat {
228    ///     fn name(&self) -> &str {
229    ///         "set_thermostat"
230    ///     }
231    ///     fn description(&self) -> &str {
232    ///         "Sets the target temperature"
233    ///     }
234    ///     // Setting the same target twice leaves the same state as setting it once.
235    ///     fn effect(&self) -> ToolEffect {
236    ///         ToolEffect::Idempotent
237    ///     }
238    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
239    ///         Ok(json!({ "target": args["celsius"] }))
240    ///     }
241    /// }
242    ///
243    /// assert_eq!(SetThermostat.effect(), ToolEffect::Idempotent);
244    /// ```
245    fn effect(&self) -> ToolEffect {
246        if self.is_read_only() { ToolEffect::ReadOnly } else { ToolEffect::NonIdempotent }
247    }
248
249    /// Overrides the per-call timeout the agent applies to this tool.
250    ///
251    /// | Value | Timeout applied to each call |
252    /// |-------|------------------------------|
253    /// | `None` (default) | The agent's own tool timeout |
254    /// | `Some(None)` | None; the call runs until it finishes or the run is cancelled |
255    /// | `Some(Some(duration))` | `duration` instead of the agent's tool timeout |
256    ///
257    /// Agent-as-tool delegations use this so a long sub-agent run is bounded by
258    /// its own configuration rather than by a timeout sized for ordinary calls.
259    ///
260    /// # Example
261    ///
262    /// ```rust
263    /// use adk_core::{Result, Tool, ToolContext};
264    /// use serde_json::Value;
265    /// use std::{sync::Arc, time::Duration};
266    ///
267    /// struct BuildReport;
268    ///
269    /// #[async_trait::async_trait]
270    /// impl Tool for BuildReport {
271    ///     fn name(&self) -> &str {
272    ///         "build_report"
273    ///     }
274    ///     fn description(&self) -> &str {
275    ///         "Builds the quarterly report"
276    ///     }
277    ///     fn timeout_override(&self) -> Option<Option<Duration>> {
278    ///         Some(Some(Duration::from_secs(30 * 60)))
279    ///     }
280    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
281    ///         Ok(Value::Null)
282    ///     }
283    /// }
284    ///
285    /// assert_eq!(BuildReport.timeout_override(), Some(Some(Duration::from_secs(1800))));
286    /// ```
287    fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
288        None
289    }
290
291    /// Indicates whether this tool is safe for concurrent execution.
292    ///
293    /// [`ToolExecutionStrategy::Auto`] requires this signal in addition to
294    /// [`Tool::is_read_only`]. [`ToolExecutionStrategy::Parallel`] is an
295    /// explicit caller override and does not inspect either signal.
296    fn is_concurrency_safe(&self) -> bool {
297        false
298    }
299
300    /// The ordered batch this tool's calls belong to, if any.
301    ///
302    /// Calls to tools that name the same group run in the order the model listed them, one
303    /// at a time. The first call in the group that does not succeed — it fails, is refused,
304    /// does not run, or is held for approval — stops the group for the rest of the model's
305    /// turn: every later call in the group is answered with the group's
306    /// [`halt_text`](BatchGroup::halt_text) instead of running, because the model planned it
307    /// assuming the earlier calls succeeded. Computer use and browser use actions need this.
308    /// `None` by default.
309    ///
310    /// # Example
311    ///
312    /// ```rust
313    /// use adk_core::{BatchGroup, Result, Tool, ToolContext};
314    /// use async_trait::async_trait;
315    /// use serde_json::Value;
316    /// use std::sync::Arc;
317    ///
318    /// struct Click;
319    ///
320    /// #[async_trait]
321    /// impl Tool for Click {
322    ///     fn name(&self) -> &str {
323    ///         "click"
324    ///     }
325    ///
326    ///     fn description(&self) -> &str {
327    ///         "Clicks at a position"
328    ///     }
329    ///
330    ///     fn batch_group(&self) -> Option<BatchGroup> {
331    ///         Some(BatchGroup::new("desktop", "Not executed: an earlier action failed."))
332    ///     }
333    ///
334    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
335    ///         Ok(Value::Null)
336    ///     }
337    /// }
338    ///
339    /// assert_eq!(Click.batch_group().unwrap().name, "desktop");
340    /// ```
341    fn batch_group(&self) -> Option<BatchGroup> {
342        None
343    }
344
345    /// Indicates whether this tool delegates work to another agent.
346    ///
347    /// Agent implementations can use this marker to overlap consecutive
348    /// delegation calls while preserving sequential execution for ordinary
349    /// tools.
350    fn is_agent_delegation(&self) -> bool {
351        false
352    }
353
354    /// The network destinations a call with `args` reaches.
355    ///
356    /// Under a run egress policy ([`RunConfig::egress_policy`]),
357    /// [`authorize_tool_call`](crate::authorize_tool_call) refuses the call before it runs
358    /// unless the policy admits the declaration; the default,
359    /// [`ToolEgress::Undeclared`](crate::egress::ToolEgress::Undeclared), is refused. A wrapper
360    /// forwards its inner tool's declaration. See [`ToolEgress`](crate::egress::ToolEgress).
361    ///
362    /// # Example
363    ///
364    /// ```rust
365    /// use std::sync::Arc;
366    ///
367    /// use adk_core::egress::ToolEgress;
368    /// use adk_core::{Result, Tool, ToolContext};
369    /// use serde_json::{Value, json};
370    ///
371    /// struct FetchIssue;
372    ///
373    /// #[async_trait::async_trait]
374    /// impl Tool for FetchIssue {
375    ///     fn name(&self) -> &str {
376    ///         "fetch_issue"
377    ///     }
378    ///     fn description(&self) -> &str {
379    ///         "Reads one GitHub issue"
380    ///     }
381    ///     fn egress(&self, _args: &Value) -> ToolEgress {
382    ///         ToolEgress::for_urls(["https://api.github.com/"])
383    ///     }
384    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
385    ///         Ok(json!({ "issue": args["number"] }))
386    ///     }
387    /// }
388    ///
389    /// let declared = FetchIssue.egress(&json!({ "number": 7 }));
390    /// assert_eq!(declared, ToolEgress::for_urls(["https://api.github.com/"]));
391    /// ```
392    fn egress(&self, _args: &Value) -> crate::egress::ToolEgress {
393        crate::egress::ToolEgress::Undeclared
394    }
395
396    /// What an approver sees with a call with `args` when it is held, such as the exact image
397    /// it would send ([`Evidence`](crate::Evidence)).
398    ///
399    /// [`GovernedCall::for_tool`](crate::GovernedCall::for_tool) records it on the call, the
400    /// held request carries it, and its digests are part of the call's
401    /// [fingerprint](crate::ToolConfirmationRequest::fingerprint): a decision applies only to
402    /// a call with the same evidence, so an image that changes before the call runs holds it
403    /// again. The default is no evidence. A wrapper forwards its inner tool's evidence.
404    ///
405    /// # Example
406    ///
407    /// ```rust
408    /// use std::sync::Arc;
409    ///
410    /// use adk_core::{ArtifactLocator, Evidence, ImageEvidence, Result, Tool, ToolContext};
411    /// use serde_json::{Value, json};
412    ///
413    /// struct SendCrop;
414    ///
415    /// #[async_trait::async_trait]
416    /// impl Tool for SendCrop {
417    ///     fn name(&self) -> &str {
418    ///         "send_crop"
419    ///     }
420    ///     fn description(&self) -> &str {
421    ///         "Sends a redacted crop to a cloud model"
422    ///     }
423    ///     fn approval_evidence(&self, args: &Value) -> Vec<Evidence> {
424    ///         let digest = args["digest"].as_str().unwrap_or_default();
425    ///         let file = args["file"].as_str().unwrap_or_default();
426    ///         let locator = ArtifactLocator::new("desk", "ana", "s1", file, 1);
427    ///         vec![ImageEvidence::new(digest, locator, "image/png", 640, 180).into()]
428    ///     }
429    ///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
430    ///         Ok(json!({ "sent": args["digest"] }))
431    ///     }
432    /// }
433    ///
434    /// let evidence = SendCrop.approval_evidence(&json!({ "digest": "sha256:aa", "file": "crop.png" }));
435    /// assert_eq!(evidence[0].digest(), "sha256:aa");
436    /// ```
437    fn approval_evidence(&self, _args: &Value) -> Vec<crate::Evidence> {
438        Vec::new()
439    }
440
441    /// Executes the tool with the given context and arguments.
442    async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value>;
443}
444
445/// An ordered batch of tool calls that stops at its first failure; see
446/// [`Tool::batch_group`].
447#[derive(Debug, Clone, PartialEq, Eq)]
448pub struct BatchGroup {
449    /// The group's name; tools that return the same name share one batch.
450    pub name: std::borrow::Cow<'static, str>,
451    /// The exact result text for each call skipped after a failure.
452    pub halt_text: std::borrow::Cow<'static, str>,
453}
454
455impl BatchGroup {
456    /// A group called `name` that answers skipped calls with `halt_text`.
457    pub fn new(
458        name: impl Into<std::borrow::Cow<'static, str>>,
459        halt_text: impl Into<std::borrow::Cow<'static, str>>,
460    ) -> Self {
461        Self { name: name.into(), halt_text: halt_text.into() }
462    }
463}
464
465/// Context available to tools during execution.
466///
467/// Extends [`CallbackContext`] with tool-specific operations like accessing
468/// the function call ID, managing event actions, and searching memory.
469#[async_trait]
470pub trait ToolContext: CallbackContext {
471    /// Returns the function call ID for this tool invocation.
472    fn function_call_id(&self) -> &str;
473    /// Returns the key that identifies this tool call across retries and replays.
474    ///
475    /// The default is `"{app}/{user}/{session}/{invocation}/{function_call_id}"`.
476    /// Every attempt of one call shares the key and no other call has it, so a
477    /// tool can pass it to a downstream API that accepts an idempotency key, and
478    /// the [`ActionLedger`](crate::ActionLedger) records non-idempotent calls
479    /// under it.
480    ///
481    /// # Example
482    ///
483    /// ```rust,ignore
484    /// async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
485    ///     let key = ctx.idempotency_key();
486    ///     self.payments.charge(&args, &key).await
487    /// }
488    /// ```
489    fn idempotency_key(&self) -> String {
490        format!(
491            "{}/{}/{}/{}/{}",
492            self.app_name(),
493            self.user_id(),
494            self.session_id(),
495            self.invocation_id(),
496            self.function_call_id()
497        )
498    }
499    /// Get the current event actions. Returns an owned copy for thread safety.
500    fn actions(&self) -> EventActions;
501    /// Set the event actions (e.g., to trigger escalation or skip summarization).
502    fn set_actions(&self, actions: EventActions);
503    /// Searches memory for entries matching the query.
504    async fn search_memory(&self, query: &str) -> Result<Vec<MemoryEntry>>;
505
506    /// Returns the memory service backing the parent invocation, when exposed.
507    ///
508    /// The default keeps contexts written before this capability backward
509    /// compatible. Agent-as-tool adapters use it only when memory forwarding is
510    /// explicitly enabled.
511    fn memory(&self) -> Option<Arc<dyn Memory>> {
512        None
513    }
514
515    /// Returns the parent session, when exposed by the runtime tool context.
516    ///
517    /// Agent-as-tool adapters can snapshot its history and state for a child
518    /// invocation without sharing mutable session ownership.
519    fn session(&self) -> Option<&dyn Session> {
520        None
521    }
522
523    /// Returns the parent run configuration, when exposed by the runtime.
524    fn run_config(&self) -> Option<&RunConfig> {
525        None
526    }
527
528    /// The run's egress policy ([`RunConfig::egress_policy`]), which a tool that opens its own
529    /// connections enforces, for example by building a
530    /// [`GuardedClient`](crate::egress::GuardedClient) from it. `None` when the run has none or
531    /// the runtime does not expose its configuration.
532    fn egress_policy(&self) -> Option<&crate::egress::EgressPolicy> {
533        self.run_config().and_then(|config| config.egress_policy.as_ref())
534    }
535
536    /// The names of the tools the agent making this call has, when its runtime says: a tool
537    /// that names another tool for a person to ask for, such as a drawn form's action, checks
538    /// the name against them (spec 3.3 §7.4 rule 5). `None`, the default, when it does not.
539    fn agent_tool_names(&self) -> Option<Vec<String>> {
540        None
541    }
542
543    /// Returns whether the parent invocation has been cancelled.
544    fn is_cancelled(&self) -> bool {
545        false
546    }
547
548    /// Returns the request metadata inherited from the parent run
549    /// ([`InvocationContext::request_metadata`](crate::InvocationContext::request_metadata)):
550    /// authenticated only when [`is_authenticated`](crate::ReadonlyContext::is_authenticated)
551    /// says so.
552    fn request_metadata(&self) -> std::collections::HashMap<String, Value> {
553        std::collections::HashMap::new()
554    }
555
556    /// Returns the current nested agent-as-tool delegation depth.
557    fn delegation_depth(&self) -> u32 {
558        0
559    }
560
561    /// Returns the maximum nested agent-as-tool delegation depth.
562    fn max_delegation_depth(&self) -> Option<u32> {
563        None
564    }
565
566    /// Returns the root invocation that owns this orchestration tree.
567    fn orchestration_root_invocation_id(&self) -> &str {
568        self.invocation_id()
569    }
570
571    /// Returns the causal relationship execution containing this tool call.
572    fn orchestration_edge_id(&self) -> Option<&str> {
573        None
574    }
575
576    /// Emits a nested agent event through the parent agent's event stream.
577    ///
578    /// The default is a no-op. AgentTool uses this only when event forwarding is
579    /// explicitly enabled, preserving existing callers' output behavior.
580    async fn emit_event(&self, _event: Event) {}
581
582    /// Emit streaming progress output during long-running tool execution.
583    ///
584    /// Tools call this to push intermediate stdout/stderr to the UI layer
585    /// as it arrives, rather than waiting for the tool to finish. This enables
586    /// streaming terminal output for shell commands, build logs, etc.
587    ///
588    /// # Arguments
589    ///
590    /// * `stream` - The output stream: `"stdout"`, `"stderr"`, or a custom label
591    /// * `chunk` - The text chunk to emit
592    ///
593    /// # Example
594    ///
595    /// ```rust,ignore
596    /// // Inside a tool's execute() method:
597    /// ctx.emit_progress("stdout", "Compiling project...\n").await;
598    /// ctx.emit_progress("stdout", "Build successful!\n").await;
599    /// ctx.emit_progress("stderr", "warning: unused variable\n").await;
600    /// ```
601    ///
602    /// The default implementation is a no-op. Runners and UI layers that support
603    /// streaming output override this to forward chunks to the client.
604    async fn emit_progress(&self, _stream: &str, _chunk: &str) {
605        // Default: discard. Override in runners that support streaming tool output.
606    }
607
608    /// Returns the scopes granted to the current user for this invocation.
609    ///
610    /// Implementations may resolve scopes from session state, JWT claims,
611    /// or an external identity provider. The default returns an empty set
612    /// (no scopes granted), which means scope-protected tools will be denied
613    /// unless the implementation is overridden.
614    fn user_scopes(&self) -> Vec<String> {
615        vec![]
616    }
617
618    /// Retrieve a secret by name from the configured secret provider.
619    ///
620    /// Returns `Ok(Some(value))` if a secret provider is configured and the
621    /// secret exists, `Ok(None)` if no secret provider is configured, or an
622    /// error if the provider fails.
623    ///
624    /// # Example
625    ///
626    /// ```rust,ignore
627    /// async fn use_secret(ctx: &dyn ToolContext) -> adk_core::Result<()> {
628    ///     if let Some(api_key) = ctx.get_secret("slack-bot-token").await? {
629    ///         // use the secret
630    ///     }
631    ///     Ok(())
632    /// }
633    /// ```
634    async fn get_secret(&self, _name: &str) -> Result<Option<String>> {
635        Ok(None)
636    }
637
638    /// Resolves a secret, stating why it is needed.
639    ///
640    /// The tool identity is added by the framework, not taken from the tool, so a
641    /// purpose is the only part a tool contributes. An authorizing
642    /// [`SecretService`](crate::SecretService) sees both.
643    async fn get_secret_for_purpose(&self, name: &str, purpose: &str) -> Result<Option<String>> {
644        let _ = purpose;
645        self.get_secret(name).await
646    }
647}
648
649/// The side-effect class of a tool, reported by [`Tool::effect`].
650///
651/// | Effect | Retried after a retryable error | Recorded in the action ledger |
652/// |--------|---------------------------------|-------------------------------|
653/// | `ReadOnly` | Yes | No |
654/// | `Idempotent` | Yes | No |
655/// | `NonIdempotent` | No | Yes, when a ledger is configured |
656///
657/// # Example
658///
659/// ```rust
660/// use adk_core::ToolEffect;
661///
662/// assert!(ToolEffect::Idempotent.is_retry_safe());
663/// assert!(!ToolEffect::NonIdempotent.is_retry_safe());
664/// ```
665#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
666#[serde(rename_all = "snake_case")]
667#[non_exhaustive]
668pub enum ToolEffect {
669    /// Reads without changing anything.
670    ReadOnly,
671    /// Changes state, but repeating a call with the same arguments leaves the
672    /// same state as making it once.
673    Idempotent,
674    /// Changes state, and repeating a call repeats the change — a payment, an
675    /// email, an order.
676    NonIdempotent,
677}
678
679impl ToolEffect {
680    /// Returns `true` when repeating a call cannot repeat a side effect.
681    pub fn is_retry_safe(self) -> bool {
682        match self {
683            Self::ReadOnly | Self::Idempotent => true,
684            Self::NonIdempotent => false,
685        }
686    }
687}
688
689/// Configuration for automatic tool retry on failure.
690///
691/// A failed call is retried only when its tool's [`Tool::effect`] is
692/// [`ToolEffect::ReadOnly`] or [`ToolEffect::Idempotent`] and the error is
693/// [retryable](crate::AdkError::is_retryable) — a rate limit, an unavailable
694/// dependency, or a timeout. The delay before retry `n` is
695/// `delay * 2^(n - 1)`, capped at `max_delay`, with jitter; see
696/// [`RetryBudget::backoff_delay`].
697///
698/// # Example
699///
700/// ```rust
701/// use std::time::Duration;
702/// use adk_core::RetryBudget;
703///
704/// // Retry up to 2 times, starting at 500ms (3 total attempts)
705/// let budget = RetryBudget::new(2, Duration::from_millis(500))
706///     .with_max_delay(Duration::from_secs(5));
707/// assert_eq!(budget.max_retries, 2);
708/// assert!(budget.backoff_delay(1) <= Duration::from_millis(500));
709/// ```
710#[derive(Debug, Clone)]
711pub struct RetryBudget {
712    /// Maximum number of retry attempts (not counting the initial attempt).
713    /// E.g., `max_retries: 2` means up to 3 total attempts.
714    pub max_retries: u32,
715    /// Base delay before the first retry. Each later retry doubles it.
716    pub delay: std::time::Duration,
717    /// Upper bound on the delay before any one retry.
718    pub max_delay: std::time::Duration,
719}
720
721impl RetryBudget {
722    /// The `max_delay` that [`RetryBudget::new`] applies.
723    pub const DEFAULT_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(30);
724
725    /// Create a new retry budget.
726    ///
727    /// `max_delay` is [`RetryBudget::DEFAULT_MAX_DELAY`], or `delay` when that is
728    /// larger.
729    ///
730    /// # Arguments
731    ///
732    /// * `max_retries` - Maximum retry attempts (not counting the initial attempt)
733    /// * `delay` - Base delay before the first retry
734    pub fn new(max_retries: u32, delay: std::time::Duration) -> Self {
735        Self { max_retries, delay, max_delay: delay.max(Self::DEFAULT_MAX_DELAY) }
736    }
737
738    /// Sets the upper bound on the delay before any one retry.
739    pub fn with_max_delay(mut self, max_delay: std::time::Duration) -> Self {
740        self.max_delay = max_delay;
741        self
742    }
743
744    /// Returns the delay before retry number `retry`, where `1` is the first retry.
745    ///
746    /// The ceiling is `delay * 2^(retry - 1)`, capped at `max_delay`. The
747    /// returned delay is drawn uniformly from the upper half of that ceiling, so
748    /// callers that failed together do not retry in lockstep.
749    pub fn backoff_delay(&self, retry: u32) -> std::time::Duration {
750        let exponent = retry.saturating_sub(1).min(31);
751        let ceiling = self.delay.saturating_mul(1u32 << exponent).min(self.max_delay);
752        let ceiling_nanos = ceiling.as_nanos();
753        if ceiling_nanos == 0 {
754            return std::time::Duration::ZERO;
755        }
756        let half = ceiling_nanos / 2;
757        let jitter = uuid::Uuid::new_v4().as_u128() % (ceiling_nanos - half + 1);
758        let nanos = u64::try_from(half + jitter).unwrap_or(u64::MAX);
759        std::time::Duration::from_nanos(nanos)
760    }
761}
762
763/// A collection of tools that can be resolved dynamically from context.
764#[async_trait]
765pub trait Toolset: Send + Sync {
766    /// Returns the name of this toolset.
767    fn name(&self) -> &str;
768    /// Returns the tools available in this toolset for the given context.
769    async fn tools(&self, ctx: Arc<dyn crate::ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>>;
770
771    /// Applies toolset-specific context to an LLM request before each model call.
772    ///
773    /// Toolsets can use this hook to describe a dynamic tool protocol without
774    /// requiring every agent that installs the toolset to repeat that guidance
775    /// in its instruction. The default implementation leaves the request
776    /// unchanged.
777    ///
778    /// # Example
779    ///
780    /// ```rust,ignore
781    /// async fn process_llm_request(
782    ///     &self,
783    ///     _ctx: std::sync::Arc<dyn adk_core::ReadonlyContext>,
784    ///     request: &mut adk_core::LlmRequest,
785    /// ) -> adk_core::Result<()> {
786    ///     request.contents.insert(0, adk_core::Content::new("user").with_text("Tool guidance"));
787    ///     Ok(())
788    /// }
789    /// ```
790    async fn process_llm_request(
791        &self,
792        _ctx: Arc<dyn ReadonlyContext>,
793        _request: &mut LlmRequest,
794    ) -> Result<()> {
795        Ok(())
796    }
797
798    /// Releases what the toolset holds open, such as a server connection or a subprocess.
799    ///
800    /// The agent that owns the toolset calls this from [`Agent::close`](crate::Agent::close),
801    /// which `adk_runner::Runner::close` reaches for every agent in its tree. Closing twice
802    /// must be harmless. The default does nothing.
803    ///
804    /// # Example
805    ///
806    /// ```rust,ignore
807    /// async fn close(&self) {
808    ///     self.connection.lock().await.take();
809    /// }
810    /// ```
811    async fn close(&self) {}
812}
813
814/// Controls how multiple tool calls from a single LLM response are dispatched.
815#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
816pub enum ToolExecutionStrategy {
817    /// Execute tools one at a time in LLM-returned order. Default.
818    #[default]
819    Sequential,
820    /// Execute all tools concurrently without inspecting tool metadata.
821    ///
822    /// This is an explicit caller override. The caller is responsible for
823    /// ensuring every selected tool is safe to execute concurrently.
824    Parallel,
825    /// Execute calls in LLM-returned order, overlapping only a run of adjacent
826    /// calls whose tools report both read-only and concurrency-safe. Any other
827    /// call runs alone, in its place: it starts after the calls listed before it
828    /// finish, and the calls listed after it wait for it.
829    Auto,
830}
831
832/// Controls how the framework handles skills/agents that request unavailable tools.
833#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
834pub enum ValidationMode {
835    /// Reject the operation entirely if any requested tool is missing from the registry.
836    #[default]
837    Strict,
838    /// Bind available tools, omit missing ones, and log a warning.
839    Permissive,
840}
841
842/// A registry that maps tool names to concrete tool instances.
843///
844/// Implementations resolve string identifiers (e.g. from a skill or config)
845/// into executable `Arc<dyn Tool>` instances.
846pub trait ToolRegistry: Send + Sync {
847    /// Resolve a tool name to a concrete tool instance.
848    /// Returns `None` if the tool is not available in this registry.
849    fn resolve(&self, tool_name: &str) -> Option<Arc<dyn Tool>>;
850
851    /// Returns a list of all tool names available in this registry.
852    fn available_tools(&self) -> Vec<String> {
853        vec![]
854    }
855}
856
857/// A predicate function for filtering tools.
858pub type ToolPredicate = Box<dyn Fn(&dyn Tool) -> bool + Send + Sync>;
859
860/// The error code for an agent built with two static tools of one name.
861pub const DUPLICATE_TOOL_NAME_CODE: &str = "agent.duplicate_tool_name";
862
863/// Checks that no two of `tools` share a name.
864///
865/// A model calls a tool by name, so with two tools of one name only one can
866/// ever be called. Agent builders call this on their static tool list, naming
867/// the agent being built as `agent_name`.
868///
869/// # Example
870///
871/// ```rust
872/// use std::sync::Arc;
873///
874/// use adk_core::{DUPLICATE_TOOL_NAME_CODE, Result, Tool, ToolContext, ensure_unique_tool_names};
875/// use async_trait::async_trait;
876/// use serde_json::Value;
877///
878/// struct Lookup;
879///
880/// #[async_trait]
881/// impl Tool for Lookup {
882///     fn name(&self) -> &str {
883///         "lookup"
884///     }
885///     fn description(&self) -> &str {
886///         "Looks things up"
887///     }
888///     async fn execute(&self, _ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value> {
889///         Ok(args)
890///     }
891/// }
892///
893/// let tools: Vec<Arc<dyn Tool>> = vec![Arc::new(Lookup), Arc::new(Lookup)];
894/// let err = ensure_unique_tool_names("support", &tools).unwrap_err();
895/// assert_eq!(err.code, DUPLICATE_TOOL_NAME_CODE);
896/// assert!(ensure_unique_tool_names("support", &tools[..1]).is_ok());
897/// ```
898///
899/// # Errors
900///
901/// Returns an [`ErrorCategory::InvalidInput`](crate::ErrorCategory::InvalidInput)
902/// error with code [`DUPLICATE_TOOL_NAME_CODE`] naming the first repeated name.
903pub fn ensure_unique_tool_names(agent_name: &str, tools: &[Arc<dyn Tool>]) -> Result<()> {
904    let mut seen = std::collections::HashSet::new();
905    match tools.iter().map(|tool| tool.name()).find(|name| !seen.insert(*name)) {
906        Some(name) => Err(crate::AdkError::new(
907            crate::ErrorComponent::Agent,
908            crate::ErrorCategory::InvalidInput,
909            DUPLICATE_TOOL_NAME_CODE,
910            format!(
911                "agent '{agent_name}' has two tools named '{name}'; the model calls tools by \
912                 name, so only one could ever run. Rename one of them or register it once."
913            ),
914        )),
915        None => Ok(()),
916    }
917}
918
919#[cfg(test)]
920mod tests {
921    use super::*;
922    use crate::{Content, EventActions, ReadonlyContext, RunConfig};
923    use std::sync::Mutex;
924
925    struct TestTool {
926        name: String,
927    }
928
929    #[allow(dead_code)]
930    struct TestContext {
931        content: Content,
932        config: RunConfig,
933        actions: Mutex<EventActions>,
934    }
935
936    impl TestContext {
937        fn new() -> Self {
938            Self {
939                content: Content::new("user"),
940                config: RunConfig::default(),
941                actions: Mutex::new(EventActions::default()),
942            }
943        }
944    }
945
946    #[async_trait]
947    impl ReadonlyContext for TestContext {
948        fn invocation_id(&self) -> &str {
949            "test"
950        }
951        fn agent_name(&self) -> &str {
952            "test"
953        }
954        fn user_id(&self) -> &str {
955            "user"
956        }
957        fn app_name(&self) -> &str {
958            "app"
959        }
960        fn session_id(&self) -> &str {
961            "session"
962        }
963        fn branch(&self) -> &str {
964            ""
965        }
966        fn user_content(&self) -> &Content {
967            &self.content
968        }
969    }
970
971    #[async_trait]
972    impl CallbackContext for TestContext {
973        fn artifacts(&self) -> Option<Arc<dyn crate::Artifacts>> {
974            None
975        }
976    }
977
978    #[async_trait]
979    impl ToolContext for TestContext {
980        fn function_call_id(&self) -> &str {
981            "call-123"
982        }
983        fn actions(&self) -> EventActions {
984            self.actions.lock().unwrap().clone()
985        }
986        fn set_actions(&self, actions: EventActions) {
987            *self.actions.lock().unwrap() = actions;
988        }
989        async fn search_memory(&self, _query: &str) -> Result<Vec<crate::MemoryEntry>> {
990            Ok(vec![])
991        }
992    }
993
994    #[async_trait]
995    impl Tool for TestTool {
996        fn name(&self) -> &str {
997            &self.name
998        }
999
1000        fn description(&self) -> &str {
1001            "test tool"
1002        }
1003
1004        async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
1005            Ok(Value::String("result".to_string()))
1006        }
1007    }
1008
1009    #[test]
1010    fn test_tool_trait() {
1011        let tool = TestTool { name: "test".to_string() };
1012        assert_eq!(tool.name(), "test");
1013        assert_eq!(tool.description(), "test tool");
1014        assert!(!tool.is_long_running());
1015    }
1016
1017    struct ReadOnlyTool;
1018
1019    #[async_trait]
1020    impl Tool for ReadOnlyTool {
1021        fn name(&self) -> &str {
1022            "lookup"
1023        }
1024        fn description(&self) -> &str {
1025            "reads"
1026        }
1027        fn is_read_only(&self) -> bool {
1028            true
1029        }
1030        async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
1031            Ok(Value::Null)
1032        }
1033    }
1034
1035    #[test]
1036    fn effect_defaults_follow_is_read_only() {
1037        let tool = TestTool { name: "test".to_string() };
1038        assert_eq!(tool.effect(), ToolEffect::NonIdempotent);
1039        assert_eq!(ReadOnlyTool.effect(), ToolEffect::ReadOnly);
1040        assert_eq!(tool.timeout_override(), None);
1041    }
1042
1043    #[test]
1044    fn idempotency_key_joins_identity_and_call_id() {
1045        let ctx = TestContext::new();
1046        assert_eq!(ctx.idempotency_key(), "app/user/session/test/call-123");
1047    }
1048
1049    #[test]
1050    fn backoff_grows_exponentially_with_jitter_and_respects_the_cap() {
1051        let budget = RetryBudget::new(5, std::time::Duration::from_millis(100))
1052            .with_max_delay(std::time::Duration::from_millis(350));
1053        for _ in 0..50 {
1054            let first = budget.backoff_delay(1);
1055            assert!(first >= std::time::Duration::from_millis(50));
1056            assert!(first <= std::time::Duration::from_millis(100));
1057            let second = budget.backoff_delay(2);
1058            assert!(second >= std::time::Duration::from_millis(100));
1059            assert!(second <= std::time::Duration::from_millis(200));
1060            let capped = budget.backoff_delay(10);
1061            assert!(capped >= std::time::Duration::from_millis(175));
1062            assert!(capped <= std::time::Duration::from_millis(350));
1063        }
1064        let zero = RetryBudget::new(1, std::time::Duration::ZERO);
1065        assert_eq!(zero.backoff_delay(1), std::time::Duration::ZERO);
1066        assert_eq!(zero.max_delay, RetryBudget::DEFAULT_MAX_DELAY);
1067    }
1068
1069    #[tokio::test]
1070    async fn test_tool_execute() {
1071        let tool = TestTool { name: "test".to_string() };
1072        let ctx = Arc::new(TestContext::new()) as Arc<dyn ToolContext>;
1073        let result = tool.execute(ctx, Value::Null).await.unwrap();
1074        assert_eq!(result, Value::String("result".to_string()));
1075    }
1076}