Skip to main content

adk_tool/
simple_context.rs

1//! Lightweight [`ToolContext`] implementation for use outside the agent loop.
2//!
3//! [`SimpleToolContext`] provides sensible defaults for all trait methods so
4//! that callers in MCP server mode, testing, or sub-agent delegation can
5//! invoke tools without constructing a full invocation context.
6//!
7//! # Example
8//!
9//! ```rust,no_run
10//! use adk_tool::SimpleToolContext;
11//! use std::sync::Arc;
12//!
13//! let ctx = SimpleToolContext::new("my-caller");
14//! let ctx: Arc<dyn adk_core::ToolContext> = Arc::new(ctx);
15//! ```
16
17use adk_core::context::{Artifacts, CallbackContext, MemoryEntry, ReadonlyContext};
18use adk_core::types::Content;
19use adk_core::{EventActions, Result, ToolContext};
20use async_trait::async_trait;
21use std::sync::{Arc, Mutex};
22
23/// A lightweight [`ToolContext`] with sensible defaults for non-agent callers.
24///
25/// Implements [`ReadonlyContext`], [`CallbackContext`], and [`ToolContext`]
26/// with minimal configuration. Construct via [`SimpleToolContext::new`] with
27/// a caller name; all other fields use safe defaults.
28pub struct SimpleToolContext {
29    caller_name: String,
30    session_id: String,
31    invocation_id: String,
32    function_call_id: String,
33    user_content: Content,
34    actions: Mutex<EventActions>,
35    acting: Option<adk_core::ActingContext>,
36}
37
38impl SimpleToolContext {
39    /// Create a new context with the given caller name.
40    ///
41    /// Generates unique UUIDs for `invocation_id` and `function_call_id`.
42    /// The caller name is returned by both [`agent_name()`](ReadonlyContext::agent_name)
43    /// and [`app_name()`](ReadonlyContext::app_name).
44    pub fn new(caller_name: impl Into<String>) -> Self {
45        Self {
46            caller_name: caller_name.into(),
47            session_id: String::new(),
48            invocation_id: uuid::Uuid::new_v4().to_string(),
49            function_call_id: uuid::Uuid::new_v4().to_string(),
50            user_content: Content::new("user"),
51            actions: Mutex::new(EventActions::default()),
52            acting: None,
53        }
54    }
55
56    /// Override the default function call ID.
57    ///
58    /// By default a UUID is generated at construction. Use this builder
59    /// method to provide a specific ID instead.
60    pub fn with_function_call_id(mut self, id: impl Into<String>) -> Self {
61        self.function_call_id = id.into();
62        self
63    }
64
65    /// Attach the session that owns this tool call.
66    ///
67    /// This is useful for desktop shells, test harnesses, and other callers
68    /// that execute tools outside the full agent loop but still need
69    /// session-aware callbacks such as MCP elicitation.
70    pub fn with_session_id(mut self, id: impl Into<String>) -> Self {
71        self.session_id = id.into();
72        self
73    }
74
75    /// Sets the acting context tools see through
76    /// [`acting_context`](ReadonlyContext::acting_context).
77    ///
78    /// Without one, the context reports the identity derived from the caller name.
79    ///
80    /// # Example
81    ///
82    /// ```rust
83    /// use adk_core::{ActingContext, AgentId, AgentPrincipal, ReadonlyContext};
84    /// use adk_tool::SimpleToolContext;
85    ///
86    /// let principal = AgentPrincipal::new(AgentId::new("urn:adk:agent:billing")?);
87    /// let ctx = SimpleToolContext::new("billing")
88    ///     .with_acting_context(ActingContext::new(principal));
89    /// assert_eq!(ctx.acting_context().agent.id.as_str(), "urn:adk:agent:billing");
90    /// # Ok::<(), adk_core::AdkError>(())
91    /// ```
92    pub fn with_acting_context(mut self, acting: adk_core::ActingContext) -> Self {
93        self.acting = Some(acting);
94        self
95    }
96}
97
98#[async_trait]
99impl ReadonlyContext for SimpleToolContext {
100    fn invocation_id(&self) -> &str {
101        &self.invocation_id
102    }
103
104    fn agent_name(&self) -> &str {
105        &self.caller_name
106    }
107
108    fn user_id(&self) -> &str {
109        "anonymous"
110    }
111
112    fn app_name(&self) -> &str {
113        &self.caller_name
114    }
115
116    fn session_id(&self) -> &str {
117        &self.session_id
118    }
119
120    fn branch(&self) -> &str {
121        ""
122    }
123
124    fn user_content(&self) -> &Content {
125        &self.user_content
126    }
127
128    fn acting_context(&self) -> adk_core::ActingContext {
129        self.acting.clone().unwrap_or_else(|| {
130            adk_core::ActingContext::derived(
131                &self.caller_name,
132                &self.caller_name,
133                "anonymous",
134                adk_core::SubjectKind::Human,
135            )
136        })
137    }
138}
139
140#[async_trait]
141impl CallbackContext for SimpleToolContext {
142    fn artifacts(&self) -> Option<Arc<dyn Artifacts>> {
143        None
144    }
145}
146
147#[async_trait]
148impl ToolContext for SimpleToolContext {
149    fn function_call_id(&self) -> &str {
150        &self.function_call_id
151    }
152
153    fn actions(&self) -> EventActions {
154        self.actions.lock().unwrap_or_else(|e| e.into_inner()).clone()
155    }
156
157    fn set_actions(&self, actions: EventActions) {
158        *self.actions.lock().unwrap_or_else(|e| e.into_inner()) = actions;
159    }
160
161    async fn search_memory(&self, _query: &str) -> Result<Vec<MemoryEntry>> {
162        Ok(vec![])
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169
170    #[test]
171    fn session_id_is_empty_by_default() {
172        let context = SimpleToolContext::new("test");
173        assert_eq!(ReadonlyContext::session_id(&context), "");
174    }
175
176    #[test]
177    fn session_id_can_be_attached_for_out_of_loop_tool_calls() {
178        let context = SimpleToolContext::new("desktop").with_session_id("session-123");
179        assert_eq!(ReadonlyContext::session_id(&context), "session-123");
180    }
181}