use crate::{
CallbackContext, Event, EventActions, LlmRequest, Memory, MemoryEntry, ReadonlyContext, Result,
RunConfig, Session,
};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::sync::Arc;
#[async_trait]
pub trait Tool: Send + Sync {
fn name(&self) -> &str;
fn description(&self) -> &str;
fn declaration(&self) -> Value {
let mut decl = serde_json::json!({
"name": self.name(),
"description": self.enhanced_description(),
});
if let Some(params) = self.parameters_schema() {
decl["parameters"] = params;
}
if let Some(response) = self.response_schema() {
decl["response"] = response;
}
decl
}
fn enhanced_description(&self) -> String {
self.description().to_string()
}
fn is_long_running(&self) -> bool {
false
}
fn is_builtin(&self) -> bool {
false
}
fn parameters_schema(&self) -> Option<Value> {
None
}
fn response_schema(&self) -> Option<Value> {
None
}
fn annotations(&self) -> Option<&Value> {
None
}
fn origin(&self) -> &str {
crate::STATIC_TOOL_ORIGIN
}
fn required_scopes(&self) -> &[&str] {
&[]
}
fn is_read_only(&self) -> bool {
false
}
fn effect(&self) -> ToolEffect {
if self.is_read_only() { ToolEffect::ReadOnly } else { ToolEffect::NonIdempotent }
}
fn timeout_override(&self) -> Option<Option<std::time::Duration>> {
None
}
fn is_concurrency_safe(&self) -> bool {
false
}
fn batch_group(&self) -> Option<BatchGroup> {
None
}
fn is_agent_delegation(&self) -> bool {
false
}
fn egress(&self, _args: &Value) -> crate::egress::ToolEgress {
crate::egress::ToolEgress::Undeclared
}
fn approval_evidence(&self, _args: &Value) -> Vec<crate::Evidence> {
Vec::new()
}
async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> Result<Value>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct BatchGroup {
pub name: std::borrow::Cow<'static, str>,
pub halt_text: std::borrow::Cow<'static, str>,
}
impl BatchGroup {
pub fn new(
name: impl Into<std::borrow::Cow<'static, str>>,
halt_text: impl Into<std::borrow::Cow<'static, str>>,
) -> Self {
Self { name: name.into(), halt_text: halt_text.into() }
}
}
#[async_trait]
pub trait ToolContext: CallbackContext {
fn function_call_id(&self) -> &str;
fn idempotency_key(&self) -> String {
format!(
"{}/{}/{}/{}/{}",
self.app_name(),
self.user_id(),
self.session_id(),
self.invocation_id(),
self.function_call_id()
)
}
fn actions(&self) -> EventActions;
fn set_actions(&self, actions: EventActions);
async fn search_memory(&self, query: &str) -> Result<Vec<MemoryEntry>>;
fn memory(&self) -> Option<Arc<dyn Memory>> {
None
}
fn session(&self) -> Option<&dyn Session> {
None
}
fn run_config(&self) -> Option<&RunConfig> {
None
}
fn egress_policy(&self) -> Option<&crate::egress::EgressPolicy> {
self.run_config().and_then(|config| config.egress_policy.as_ref())
}
fn agent_tool_names(&self) -> Option<Vec<String>> {
None
}
fn is_cancelled(&self) -> bool {
false
}
fn request_metadata(&self) -> std::collections::HashMap<String, Value> {
std::collections::HashMap::new()
}
fn delegation_depth(&self) -> u32 {
0
}
fn max_delegation_depth(&self) -> Option<u32> {
None
}
fn orchestration_root_invocation_id(&self) -> &str {
self.invocation_id()
}
fn orchestration_edge_id(&self) -> Option<&str> {
None
}
async fn emit_event(&self, _event: Event) {}
async fn emit_progress(&self, _stream: &str, _chunk: &str) {
}
fn user_scopes(&self) -> Vec<String> {
vec![]
}
async fn get_secret(&self, _name: &str) -> Result<Option<String>> {
Ok(None)
}
async fn get_secret_for_purpose(&self, name: &str, purpose: &str) -> Result<Option<String>> {
let _ = purpose;
self.get_secret(name).await
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[non_exhaustive]
pub enum ToolEffect {
ReadOnly,
Idempotent,
NonIdempotent,
}
impl ToolEffect {
pub fn is_retry_safe(self) -> bool {
match self {
Self::ReadOnly | Self::Idempotent => true,
Self::NonIdempotent => false,
}
}
}
#[derive(Debug, Clone)]
pub struct RetryBudget {
pub max_retries: u32,
pub delay: std::time::Duration,
pub max_delay: std::time::Duration,
}
impl RetryBudget {
pub const DEFAULT_MAX_DELAY: std::time::Duration = std::time::Duration::from_secs(30);
pub fn new(max_retries: u32, delay: std::time::Duration) -> Self {
Self { max_retries, delay, max_delay: delay.max(Self::DEFAULT_MAX_DELAY) }
}
pub fn with_max_delay(mut self, max_delay: std::time::Duration) -> Self {
self.max_delay = max_delay;
self
}
pub fn backoff_delay(&self, retry: u32) -> std::time::Duration {
let exponent = retry.saturating_sub(1).min(31);
let ceiling = self.delay.saturating_mul(1u32 << exponent).min(self.max_delay);
let ceiling_nanos = ceiling.as_nanos();
if ceiling_nanos == 0 {
return std::time::Duration::ZERO;
}
let half = ceiling_nanos / 2;
let jitter = uuid::Uuid::new_v4().as_u128() % (ceiling_nanos - half + 1);
let nanos = u64::try_from(half + jitter).unwrap_or(u64::MAX);
std::time::Duration::from_nanos(nanos)
}
}
#[async_trait]
pub trait Toolset: Send + Sync {
fn name(&self) -> &str;
async fn tools(&self, ctx: Arc<dyn crate::ReadonlyContext>) -> Result<Vec<Arc<dyn Tool>>>;
async fn process_llm_request(
&self,
_ctx: Arc<dyn ReadonlyContext>,
_request: &mut LlmRequest,
) -> Result<()> {
Ok(())
}
async fn close(&self) {}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub enum ToolExecutionStrategy {
#[default]
Sequential,
Parallel,
Auto,
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
pub enum ValidationMode {
#[default]
Strict,
Permissive,
}
pub trait ToolRegistry: Send + Sync {
fn resolve(&self, tool_name: &str) -> Option<Arc<dyn Tool>>;
fn available_tools(&self) -> Vec<String> {
vec![]
}
}
pub type ToolPredicate = Box<dyn Fn(&dyn Tool) -> bool + Send + Sync>;
pub const DUPLICATE_TOOL_NAME_CODE: &str = "agent.duplicate_tool_name";
pub fn ensure_unique_tool_names(agent_name: &str, tools: &[Arc<dyn Tool>]) -> Result<()> {
let mut seen = std::collections::HashSet::new();
match tools.iter().map(|tool| tool.name()).find(|name| !seen.insert(*name)) {
Some(name) => Err(crate::AdkError::new(
crate::ErrorComponent::Agent,
crate::ErrorCategory::InvalidInput,
DUPLICATE_TOOL_NAME_CODE,
format!(
"agent '{agent_name}' has two tools named '{name}'; the model calls tools by \
name, so only one could ever run. Rename one of them or register it once."
),
)),
None => Ok(()),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{Content, EventActions, ReadonlyContext, RunConfig};
use std::sync::Mutex;
struct TestTool {
name: String,
}
#[allow(dead_code)]
struct TestContext {
content: Content,
config: RunConfig,
actions: Mutex<EventActions>,
}
impl TestContext {
fn new() -> Self {
Self {
content: Content::new("user"),
config: RunConfig::default(),
actions: Mutex::new(EventActions::default()),
}
}
}
#[async_trait]
impl ReadonlyContext for TestContext {
fn invocation_id(&self) -> &str {
"test"
}
fn agent_name(&self) -> &str {
"test"
}
fn user_id(&self) -> &str {
"user"
}
fn app_name(&self) -> &str {
"app"
}
fn session_id(&self) -> &str {
"session"
}
fn branch(&self) -> &str {
""
}
fn user_content(&self) -> &Content {
&self.content
}
}
#[async_trait]
impl CallbackContext for TestContext {
fn artifacts(&self) -> Option<Arc<dyn crate::Artifacts>> {
None
}
}
#[async_trait]
impl ToolContext for TestContext {
fn function_call_id(&self) -> &str {
"call-123"
}
fn actions(&self) -> EventActions {
self.actions.lock().unwrap().clone()
}
fn set_actions(&self, actions: EventActions) {
*self.actions.lock().unwrap() = actions;
}
async fn search_memory(&self, _query: &str) -> Result<Vec<crate::MemoryEntry>> {
Ok(vec![])
}
}
#[async_trait]
impl Tool for TestTool {
fn name(&self) -> &str {
&self.name
}
fn description(&self) -> &str {
"test tool"
}
async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
Ok(Value::String("result".to_string()))
}
}
#[test]
fn test_tool_trait() {
let tool = TestTool { name: "test".to_string() };
assert_eq!(tool.name(), "test");
assert_eq!(tool.description(), "test tool");
assert!(!tool.is_long_running());
}
struct ReadOnlyTool;
#[async_trait]
impl Tool for ReadOnlyTool {
fn name(&self) -> &str {
"lookup"
}
fn description(&self) -> &str {
"reads"
}
fn is_read_only(&self) -> bool {
true
}
async fn execute(&self, _ctx: Arc<dyn ToolContext>, _args: Value) -> Result<Value> {
Ok(Value::Null)
}
}
#[test]
fn effect_defaults_follow_is_read_only() {
let tool = TestTool { name: "test".to_string() };
assert_eq!(tool.effect(), ToolEffect::NonIdempotent);
assert_eq!(ReadOnlyTool.effect(), ToolEffect::ReadOnly);
assert_eq!(tool.timeout_override(), None);
}
#[test]
fn idempotency_key_joins_identity_and_call_id() {
let ctx = TestContext::new();
assert_eq!(ctx.idempotency_key(), "app/user/session/test/call-123");
}
#[test]
fn backoff_grows_exponentially_with_jitter_and_respects_the_cap() {
let budget = RetryBudget::new(5, std::time::Duration::from_millis(100))
.with_max_delay(std::time::Duration::from_millis(350));
for _ in 0..50 {
let first = budget.backoff_delay(1);
assert!(first >= std::time::Duration::from_millis(50));
assert!(first <= std::time::Duration::from_millis(100));
let second = budget.backoff_delay(2);
assert!(second >= std::time::Duration::from_millis(100));
assert!(second <= std::time::Duration::from_millis(200));
let capped = budget.backoff_delay(10);
assert!(capped >= std::time::Duration::from_millis(175));
assert!(capped <= std::time::Duration::from_millis(350));
}
let zero = RetryBudget::new(1, std::time::Duration::ZERO);
assert_eq!(zero.backoff_delay(1), std::time::Duration::ZERO);
assert_eq!(zero.max_delay, RetryBudget::DEFAULT_MAX_DELAY);
}
#[tokio::test]
async fn test_tool_execute() {
let tool = TestTool { name: "test".to_string() };
let ctx = Arc::new(TestContext::new()) as Arc<dyn ToolContext>;
let result = tool.execute(ctx, Value::Null).await.unwrap();
assert_eq!(result, Value::String("result".to_string()));
}
}