Skip to main content

strands/tools/
tool.rs

1//! The [`Tool`] trait, its stream and its context.
2
3use std::fmt;
4use std::future::Future;
5use std::pin::Pin;
6use std::sync::Arc;
7use std::task::{Context, Poll};
8
9use futures::{Stream, StreamExt};
10use serde::{Deserialize, Serialize};
11
12use crate::agent::{InvocationContext, InvocationState, ToolAgent};
13use crate::cancel::CancelSignal;
14use crate::error::BoxError;
15use crate::interrupt::{Interrupt, InterruptError, InterruptSource};
16use crate::models::BoxStream;
17use crate::types::{InterruptParams, JsonValue, ToolResultBlock, ToolResultContent, ToolSpec, ToolUse};
18
19/// A tool the model can call (`Tool`).
20///
21/// [`stream`](Tool::stream) yields zero or more progress events and ends with exactly one
22/// [`ToolOutcome`]: the result, or an interrupt that pauses the agent for human input. A failing
23/// tool returns an error result rather than failing the stream.
24///
25/// Most tools are written with `#[tool]` or [`FunctionTool`](crate::tools::FunctionTool);
26/// implement the trait directly for full control.
27///
28/// ```
29/// use strands::tools::{Tool, ToolContext, ToolOutcome, ToolStream};
30/// use strands::{ToolResultBlock, ToolResultContent, ToolSpec};
31///
32/// struct Echo;
33///
34/// impl Tool for Echo {
35///     fn name(&self) -> &str {
36///         "echo"
37///     }
38///
39///     fn description(&self) -> &str {
40///         "Echoes its input"
41///     }
42///
43///     fn tool_spec(&self) -> ToolSpec {
44///         ToolSpec::new(self.name(), self.description())
45///     }
46///
47///     fn stream(&self, context: ToolContext) -> ToolStream {
48///         ToolStream::from_future(async move {
49///             let text = context.tool_use().input.to_string();
50///             let id = context.tool_use().tool_use_id.clone();
51///             ToolOutcome::from(ToolResultBlock::success(id, vec![ToolResultContent::text(text)]))
52///         })
53///     }
54/// }
55/// ```
56pub trait Tool: Send + Sync + 'static {
57    /// The unique tool name; it must match the spec's name.
58    fn name(&self) -> &str;
59
60    /// What the tool does; it must match the spec's description.
61    fn description(&self) -> &str;
62
63    /// The spec sent to the model: name, description and input schema.
64    fn tool_spec(&self) -> ToolSpec;
65
66    /// Runs the tool. The stream is `'static`, so the agent can run it on its own task.
67    fn stream(&self, context: ToolContext) -> ToolStream;
68
69    /// Whether this is an agent-as-tool that delegates (`AgentAsTool` with `delegate: true`); the
70    /// agent's delegation and background-task rules read it. Only the SDK can name the token, so
71    /// only its tools answer.
72    #[doc(hidden)]
73    fn is_delegation_tool(&self, _: DelegationToken) -> bool {
74        false
75    }
76
77    /// Whether this is the SDK's `load_tools` or the background-tasks manage tool, rather than a
78    /// user's tool of the same name; deferred tool loading and background tasks read it. Only the
79    /// SDK can name the token, so only its tools answer.
80    #[doc(hidden)]
81    fn sdk_tool_role(&self, _: DelegationToken) -> Option<SdkToolRole> {
82        None
83    }
84}
85
86/// Which SDK tool a [`Tool::sdk_tool_role`] names.
87#[doc(hidden)]
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89#[non_exhaustive]
90pub enum SdkToolRole {
91    /// The `load_tools` tool of deferred tool loading.
92    LoadTools,
93    /// The background-tasks manage tool, under any `manage_tool_name`.
94    ManageBackgroundTasks,
95}
96
97/// Whether `tool` is the SDK tool with this role.
98pub(crate) fn has_sdk_tool_role(tool: Option<&Arc<dyn Tool>>, role: SdkToolRole) -> bool {
99    tool.is_some_and(|tool| tool.sdk_tool_role(DelegationToken(())) == Some(role))
100}
101
102mod sealed {
103    /// The argument of [`Tool::is_delegation_tool`](super::Tool::is_delegation_tool); only the SDK
104    /// can name it, so only the SDK overrides or calls the method.
105    #[derive(Debug, Clone, Copy)]
106    pub struct DelegationToken(pub(crate) ());
107}
108
109pub(crate) use sealed::DelegationToken;
110
111impl fmt::Debug for dyn Tool {
112    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
113        f.debug_struct("Tool")
114            .field("name", &self.name())
115            .finish_non_exhaustive()
116    }
117}
118
119/// Progress data a tool yields while it runs (`ToolStreamEvent`).
120///
121/// Serializes as `{"type":"toolStreamEvent","data":...}`, without `data` when there is none.
122#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
123#[serde(tag = "type", rename = "toolStreamEvent")]
124#[non_exhaustive]
125pub struct ToolStreamEvent {
126    /// Caller-defined progress data.
127    #[serde(default, skip_serializing_if = "Option::is_none")]
128    pub data: Option<JsonValue>,
129}
130
131impl ToolStreamEvent {
132    /// Creates an event carrying `data`.
133    pub fn new(data: impl Into<JsonValue>) -> Self {
134        Self {
135            data: Some(data.into()),
136        }
137    }
138
139    /// Creates an event without data.
140    #[must_use]
141    pub fn empty() -> Self {
142        Self::default()
143    }
144}
145
146/// How a tool run ended.
147#[derive(Debug, Clone, PartialEq)]
148#[non_exhaustive]
149pub enum ToolOutcome {
150    /// The tool finished with a result, successful or not.
151    Result(ToolResultBlock),
152    /// The tool raised one or more interrupts (a sub-agent can raise several); it runs again
153    /// from the start when the agent resumes.
154    Interrupt(InterruptError),
155}
156
157impl ToolOutcome {
158    /// The result, unless the tool was interrupted.
159    #[must_use]
160    pub fn result(&self) -> Option<&ToolResultBlock> {
161        match self {
162            Self::Result(result) => Some(result),
163            Self::Interrupt(_) => None,
164        }
165    }
166}
167
168impl From<ToolResultBlock> for ToolOutcome {
169    fn from(result: ToolResultBlock) -> Self {
170        Self::Result(result)
171    }
172}
173
174impl From<Interrupt> for ToolOutcome {
175    fn from(interrupt: Interrupt) -> Self {
176        Self::Interrupt(interrupt.into())
177    }
178}
179
180impl From<InterruptError> for ToolOutcome {
181    fn from(interrupts: InterruptError) -> Self {
182        Self::Interrupt(interrupts)
183    }
184}
185
186/// One item of a [`ToolStream`].
187#[derive(Debug, Clone, PartialEq)]
188#[non_exhaustive]
189pub enum ToolStreamItem {
190    /// A progress event.
191    Event(ToolStreamEvent),
192    /// The final outcome; the stream ends after it.
193    Outcome(ToolOutcome),
194}
195
196impl From<ToolStreamEvent> for ToolStreamItem {
197    fn from(event: ToolStreamEvent) -> Self {
198        Self::Event(event)
199    }
200}
201
202impl From<ToolOutcome> for ToolStreamItem {
203    fn from(outcome: ToolOutcome) -> Self {
204        Self::Outcome(outcome)
205    }
206}
207
208impl From<ToolResultBlock> for ToolStreamItem {
209    fn from(result: ToolResultBlock) -> Self {
210        Self::Outcome(result.into())
211    }
212}
213
214/// The stream a [`Tool`] returns (`ToolStreamGenerator`): progress events, then one outcome.
215///
216/// A stream that ends without an outcome becomes an error result.
217pub struct ToolStream {
218    inner: BoxStream<'static, ToolStreamItem>,
219}
220
221impl ToolStream {
222    /// Wraps a stream of items.
223    pub fn new(stream: impl Stream<Item = ToolStreamItem> + Send + 'static) -> Self {
224        Self {
225            inner: Box::pin(stream),
226        }
227    }
228
229    /// A stream with no progress events, for tools that only compute a result.
230    pub fn from_future(future: impl Future<Output = ToolOutcome> + Send + 'static) -> Self {
231        Self::new(futures::stream::once(future).map(ToolStreamItem::Outcome))
232    }
233
234    /// A stream that ends at once with `outcome`.
235    pub fn ready(outcome: impl Into<ToolOutcome>) -> Self {
236        Self::new(futures::stream::iter([ToolStreamItem::Outcome(outcome.into())]))
237    }
238
239    /// Drains the stream, passing each progress event to `on_event`, and returns the first
240    /// outcome, or `None` when the stream ends without one. Items after the outcome are ignored.
241    pub(crate) async fn run(mut self, mut on_event: impl FnMut(ToolStreamEvent)) -> Option<ToolOutcome> {
242        while let Some(item) = self.next().await {
243            match item {
244                ToolStreamItem::Event(event) => on_event(event),
245                ToolStreamItem::Outcome(outcome) => return Some(outcome),
246            }
247        }
248        None
249    }
250}
251
252impl Stream for ToolStream {
253    type Item = ToolStreamItem;
254
255    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
256        self.inner.as_mut().poll_next(cx)
257    }
258}
259
260impl fmt::Debug for ToolStream {
261    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
262        f.debug_struct("ToolStream").finish_non_exhaustive()
263    }
264}
265
266pub(crate) type InterruptFn = Arc<dyn Fn(&InterruptParams) -> Result<JsonValue, InterruptError> + Send + Sync>;
267
268/// What a tool receives when it runs (`ToolContext`).
269///
270/// Cheap to clone and `'static`, so tools can move it into spawned work.
271#[derive(Clone)]
272pub struct ToolContext {
273    tool_use: ToolUse,
274    agent: ToolAgent,
275    invocation_state: InvocationState,
276    cancel_signal: CancelSignal,
277    invocation_context: Option<InvocationContext>,
278    interrupt: Option<InterruptFn>,
279}
280
281impl ToolContext {
282    /// Creates the context for one tool call. The cancel signal starts as the agent's.
283    pub(crate) fn new(tool_use: ToolUse, agent: ToolAgent, invocation_state: InvocationState) -> Self {
284        let cancel_signal = agent.cancel_signal();
285        let invocation_context = agent.invocation_context().cloned();
286        Self {
287            tool_use,
288            agent,
289            invocation_state,
290            cancel_signal,
291            invocation_context,
292            interrupt: None,
293        }
294    }
295
296    /// Sets the execution-scoped cancel signal.
297    #[must_use]
298    #[cfg(test)]
299    pub(crate) fn with_cancel_signal(mut self, cancel_signal: CancelSignal) -> Self {
300        self.cancel_signal = cancel_signal;
301        self
302    }
303
304    /// Replaces how interrupts are raised, for callers that scope interrupt ids differently.
305    #[must_use]
306    pub(crate) fn with_interrupt(mut self, interrupt: InterruptFn) -> Self {
307        self.interrupt = Some(interrupt);
308        self
309    }
310
311    /// The tool use that started this call: name, id and input.
312    #[must_use]
313    pub fn tool_use(&self) -> &ToolUse {
314        &self.tool_use
315    }
316
317    /// The agent running the tool.
318    #[must_use]
319    pub fn agent(&self) -> &ToolAgent {
320        &self.agent
321    }
322
323    /// The caller's per-invocation state, shared with hooks and other tools.
324    #[must_use]
325    pub fn invocation_state(&self) -> &InvocationState {
326        &self.invocation_state
327    }
328
329    /// The cancellation signal for this tool call. Cancellation is cooperative: check it between
330    /// steps or await [`CancelSignal::cancelled`].
331    #[must_use]
332    pub fn cancel_signal(&self) -> &CancelSignal {
333        &self.cancel_signal
334    }
335
336    /// The request this call belongs to; pass it to a nested agent call to share its limits and
337    /// usage.
338    #[must_use]
339    pub fn invocation_context(&self) -> Option<&InvocationContext> {
340        self.invocation_context.as_ref()
341    }
342
343    /// Raises an interrupt for human input (`interrupt`).
344    ///
345    /// Returns the response when the agent resumed with one (or `params` carries a preemptive
346    /// response). Otherwise returns the [`InterruptError`]; propagate it with `?` into a
347    /// [`ToolError`](super::ToolError) or a [`BoxError`], which ends the tool as
348    /// [`ToolOutcome::Interrupt`]. The tool runs again from the start on resume, and this call
349    /// then returns the response. The interrupt id is `tool:<toolUseId>:<name>`.
350    ///
351    /// # Errors
352    ///
353    /// The unanswered interrupt.
354    pub fn interrupt(&self, params: impl Into<InterruptParams>) -> Result<JsonValue, InterruptError> {
355        let params = params.into();
356        if let Some(interrupt) = &self.interrupt {
357            return interrupt(&params);
358        }
359        let id = format!("tool:{}:{}", self.tool_use.tool_use_id, params.name);
360        self.agent.interrupt_state().raise(&id, &params, InterruptSource::Tool)
361    }
362}
363
364impl fmt::Debug for ToolContext {
365    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
366        f.debug_struct("ToolContext")
367            .field("tool_use", &self.tool_use)
368            .field("agent", &self.agent)
369            .finish_non_exhaustive()
370    }
371}
372
373/// An error tool result whose content is `Error: <message>` and which keeps the original error.
374pub fn create_error_result(error: impl Into<BoxError>, tool_use_id: impl Into<String>) -> ToolResultBlock {
375    let error = error.into();
376    ToolResultBlock::error(tool_use_id, vec![ToolResultContent::text(format!("Error: {error}"))]).with_error(error)
377}
378
379const TOOL_NAME_MAX_LENGTH: usize = 64;
380
381/// Whether `name` is a tool name providers accept: 1 to 64 characters, only
382/// ASCII letters, digits, `_` and `-`.
383#[must_use]
384pub fn is_valid_tool_name(name: &str) -> bool {
385    (1..=TOOL_NAME_MAX_LENGTH).contains(&name.len())
386        && name
387            .bytes()
388            .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-')
389}
390
391/// Tests tool name validation, tool stream events and the `Tool` trait.
392#[cfg(test)]
393mod tests {
394    use serde_json::json;
395
396    use super::*;
397    use crate::testing::tool_context;
398
399    #[test]
400    fn accepts_valid_names() {
401        for name in [
402            "simple",
403            "with_underscore",
404            "with-hyphen",
405            "Mixed-Case_123",
406            "a",
407            &"a".repeat(64),
408        ] {
409            assert!(is_valid_tool_name(name), "{name}");
410        }
411    }
412
413    #[test]
414    fn rejects_invalid_names() {
415        for name in [
416            "",
417            &"a".repeat(65),
418            "has space",
419            "has.dot",
420            "has/slash",
421            "has:colon",
422            "emoji🚀",
423        ] {
424            assert!(!is_valid_tool_name(name), "{name}");
425        }
426    }
427
428    #[test]
429    fn creates_instance_with_data() {
430        let event = ToolStreamEvent::new("Processing...");
431        assert_eq!(event.data, Some(json!("Processing...")));
432        assert_eq!(
433            serde_json::to_value(&event).unwrap(),
434            json!({"type": "toolStreamEvent", "data": "Processing..."})
435        );
436    }
437
438    #[test]
439    fn creates_instance_without_data() {
440        let event = ToolStreamEvent::empty();
441        assert_eq!(event.data, None);
442        assert_eq!(
443            serde_json::to_value(&event).unwrap(),
444            json!({"type": "toolStreamEvent"})
445        );
446    }
447
448    #[test]
449    fn creates_instance_with_structured_data() {
450        let data = json!({"progress": 50, "message": "Halfway complete"});
451        let event: ToolStreamEvent = serde_json::from_value(json!({"type": "toolStreamEvent", "data": data})).unwrap();
452        assert_eq!(
453            event,
454            ToolStreamEvent::new(json!({"progress": 50, "message": "Halfway complete"}))
455        );
456    }
457
458    #[test]
459    fn creates_an_error_result_with_the_error_prefix() {
460        let result = create_error_result("boom", "t-1");
461        assert_eq!(
462            serde_json::to_value(&result).unwrap(),
463            json!({"toolUseId": "t-1", "status": "error", "content": [{"text": "Error: boom"}]})
464        );
465        assert_eq!(result.error.map(|error| error.to_string()).as_deref(), Some("boom"));
466    }
467
468    #[tokio::test]
469    async fn run_returns_the_first_outcome_and_forwards_events() {
470        let stream = ToolStream::new(futures::stream::iter([
471            ToolStreamItem::from(ToolStreamEvent::new(1)),
472            ToolResultBlock::success("t", vec![]).into(),
473            ToolStreamItem::from(ToolStreamEvent::new(2)),
474        ]));
475        let mut events = Vec::new();
476        let outcome = stream.run(|event| events.push(event)).await;
477        assert_eq!(
478            outcome,
479            Some(ToolOutcome::Result(ToolResultBlock::success("t", vec![])))
480        );
481        assert_eq!(events, vec![ToolStreamEvent::new(1)]);
482        assert_eq!(ToolStream::new(futures::stream::empty()).run(|_| {}).await, None);
483    }
484
485    #[test]
486    fn interrupt_raises_with_the_tool_scoped_id_and_returns_the_response_on_resume() {
487        let context = tool_context(ToolUse::new("delete", "t-1", json!({})));
488        let interrupt = context
489            .interrupt(InterruptParams::new("confirm").with_reason("sure?"))
490            .unwrap_err();
491        assert_eq!(
492            serde_json::to_value(&interrupt.interrupts).unwrap(),
493            json!([{"id": "tool:t-1:confirm", "name": "confirm", "reason": "sure?", "source": "tool"}])
494        );
495        context
496            .agent()
497            .interrupt_state()
498            .respond("tool:t-1:confirm", json!("yes"));
499        assert_eq!(context.interrupt("confirm").unwrap(), json!("yes"));
500    }
501
502    #[test]
503    fn interrupt_returns_a_preemptive_response_at_once() {
504        let context = tool_context(ToolUse::new("delete", "t-1", json!({})));
505        let response = context.interrupt(InterruptParams::new("confirm").with_response(true));
506        assert_eq!(response.unwrap(), json!(true));
507    }
508}