gadk_agent/tool.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//! Tool traits and the optional tool capabilities.
17
18use std::any::Any;
19use std::sync::Arc;
20
21use futures::stream::BoxStream;
22use gadk_genai::FunctionDeclaration;
23use gadk_model::LlmRequest;
24use serde_json::{Map, Value};
25
26use crate::agent::Agent;
27use crate::context::{Context, ReadonlyContext};
28use crate::error::ToolError;
29
30/// A tool, plus the optional capabilities as defaulted methods.
31#[async_trait::async_trait]
32pub trait Tool: Send + Sync + 'static {
33 /// The name of the tool.
34 fn name(&self) -> &str;
35 /// A description of the tool.
36 fn description(&self) -> &str;
37 /// Whether the tool is a long-running operation, which typically returns a resource id first
38 /// and finishes the operation later.
39 fn is_long_running(&self) -> bool {
40 false
41 }
42 /// The function declaration sent to the model.
43 fn declaration(&self) -> Option<FunctionDeclaration> {
44 None
45 }
46 /// Extra request edits only. The flow packs a tool that has
47 /// a [`declaration`](Tool::declaration) with `pack_tool` before this runs; a tool without one
48 /// is never packed. Async because implementations may do I/O (artifact listing, memory search).
49 async fn process_request(
50 &self,
51 _ctx: &Context,
52 _req: &mut LlmRequest,
53 ) -> Result<(), ToolError> {
54 Ok(())
55 }
56 /// The runnable capability.
57 fn as_runnable(&self) -> Option<&dyn RunnableTool> {
58 None
59 }
60 /// The streaming capability.
61 fn as_streaming(&self) -> Option<&dyn StreamingTool> {
62 None
63 }
64 /// Whether the tool defers its response: an empty result is then not sent to the model.
65 fn defers_response(&self) -> bool {
66 false
67 }
68 /// Whether the result is also shown as a text part when the call ends the agent loop with
69 /// `skip_summarization`.
70 fn display_result_on_skip_summarization(&self) -> bool {
71 false
72 }
73 /// The `finish_task` wrapper key.
74 fn wrapper_key(&self) -> Option<&str> {
75 None
76 }
77 /// The tool this one wraps, for a confirmation or delegating wrapper (the agent-analytics
78 /// plugin reaches the wrapped tool through it). `None` for a tool that wraps nothing.
79 fn unwrap(&self) -> Option<Arc<dyn Tool>> {
80 None
81 }
82 /// The kind of tool this is, for analytics (gadk tools declare it). A wrapper
83 /// keeps the default and is classified through [`unwrap`](Tool::unwrap).
84 fn origin_kind(&self) -> ToolOriginKind {
85 ToolOriginKind::Unknown
86 }
87 /// The agent a [`ToolOriginKind::SubAgent`] tool runs (this tells a sub-agent from a remote
88 /// A2A agent).
89 fn origin_agent(&self) -> Option<Arc<dyn Agent>> {
90 None
91 }
92 /// Every agent the tool can hand a call to, in order, for analytics
93 /// (e.g. a transfer tool's supported agents). Defaults to
94 /// [`origin_agent`](Tool::origin_agent) as a list of at most one.
95 fn origin_agents(&self) -> Vec<Arc<dyn Agent>> {
96 self.origin_agent().into_iter().collect()
97 }
98 /// Downcasting support.
99 fn as_any(&self) -> &dyn Any;
100}
101
102/// What kind of tool a [`Tool`] is, as the agent-analytics plugin reports it. The `TRANSFER_A2A`
103/// and `A2A` origins are not kinds: the plugin derives them from [`ToolOriginKind::TransferAgent`]
104/// and [`ToolOriginKind::SubAgent`] by looking at the target agent.
105#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
106#[non_exhaustive]
107pub enum ToolOriginKind {
108 /// `"UNKNOWN"`: the tool does not say (the default).
109 #[default]
110 Unknown,
111 /// `"LOCAL"`: a function tool or the load-memory tool.
112 Local,
113 /// `"MCP"`: a tool of an MCP toolset.
114 Mcp,
115 /// `"TRANSFER_AGENT"` (`"TRANSFER_A2A"` when the target is a remote
116 /// A2A agent): the transfer-to-agent tool.
117 TransferAgent,
118 /// `"SUB_AGENT"` (`"A2A"` when [`Tool::origin_agent`] is a remote A2A
119 /// agent): an agent tool, task-agent tool or single-turn tool.
120 SubAgent,
121 /// `"SKILL"`: a skill tool.
122 Skill,
123 /// `"TOOLBOX"`: a toolbox tool.
124 Toolbox,
125}
126
127/// A tool that runs to completion.
128#[async_trait::async_trait]
129pub trait RunnableTool: Send + Sync {
130 /// Runs the tool with `args`.
131 async fn run(&self, ctx: Context, args: Value) -> Result<Map<String, Value>, ToolError>;
132}
133
134/// A tool that streams partial results.
135pub trait StreamingTool: Send + Sync {
136 /// Runs the tool with `args`, streaming its output.
137 fn run_stream(
138 &self,
139 ctx: Context,
140 args: Value,
141 ) -> BoxStream<'static, Result<String, ToolError>>;
142}
143
144/// A collection of tools provided to an agent.
145#[async_trait::async_trait]
146pub trait Toolset: Send + Sync {
147 /// The name of the toolset.
148 fn name(&self) -> &str;
149 /// The tools in the toolset; `ctx` can be used to decide which tools to return.
150 async fn tools(&self, ctx: &ReadonlyContext) -> Result<Vec<Arc<dyn Tool>>, ToolError>;
151 /// Extra request edits for the toolset.
152 async fn process_request(
153 &self,
154 _ctx: &Context,
155 _req: &mut LlmRequest,
156 ) -> Result<(), ToolError> {
157 Ok(())
158 }
159 /// Downcasting support.
160 fn as_any(&self) -> &dyn Any;
161}
162
163/// Decides whether a tool is exposed to the LLM.
164pub type ToolPredicate = Arc<dyn Fn(&ReadonlyContext, &dyn Tool) -> bool + Send + Sync>;
165
166/// Decides whether a call to the named tool with the given arguments requires confirmation.
167pub type ConfirmationProvider = Arc<dyn Fn(&str, &Value) -> bool + Send + Sync>;
168
169pub use crate::tool_util::{pack_tool, tool_from_request};