1use 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
19pub trait Tool: Send + Sync + 'static {
57 fn name(&self) -> &str;
59
60 fn description(&self) -> &str;
62
63 fn tool_spec(&self) -> ToolSpec;
65
66 fn stream(&self, context: ToolContext) -> ToolStream;
68
69 #[doc(hidden)]
73 fn is_delegation_tool(&self, _: DelegationToken) -> bool {
74 false
75 }
76
77 #[doc(hidden)]
81 fn sdk_tool_role(&self, _: DelegationToken) -> Option<SdkToolRole> {
82 None
83 }
84}
85
86#[doc(hidden)]
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89#[non_exhaustive]
90pub enum SdkToolRole {
91 LoadTools,
93 ManageBackgroundTasks,
95}
96
97pub(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 #[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#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
123#[serde(tag = "type", rename = "toolStreamEvent")]
124#[non_exhaustive]
125pub struct ToolStreamEvent {
126 #[serde(default, skip_serializing_if = "Option::is_none")]
128 pub data: Option<JsonValue>,
129}
130
131impl ToolStreamEvent {
132 pub fn new(data: impl Into<JsonValue>) -> Self {
134 Self {
135 data: Some(data.into()),
136 }
137 }
138
139 #[must_use]
141 pub fn empty() -> Self {
142 Self::default()
143 }
144}
145
146#[derive(Debug, Clone, PartialEq)]
148#[non_exhaustive]
149pub enum ToolOutcome {
150 Result(ToolResultBlock),
152 Interrupt(InterruptError),
155}
156
157impl ToolOutcome {
158 #[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#[derive(Debug, Clone, PartialEq)]
188#[non_exhaustive]
189pub enum ToolStreamItem {
190 Event(ToolStreamEvent),
192 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
214pub struct ToolStream {
218 inner: BoxStream<'static, ToolStreamItem>,
219}
220
221impl ToolStream {
222 pub fn new(stream: impl Stream<Item = ToolStreamItem> + Send + 'static) -> Self {
224 Self {
225 inner: Box::pin(stream),
226 }
227 }
228
229 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 pub fn ready(outcome: impl Into<ToolOutcome>) -> Self {
236 Self::new(futures::stream::iter([ToolStreamItem::Outcome(outcome.into())]))
237 }
238
239 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#[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 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 #[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 #[must_use]
306 pub(crate) fn with_interrupt(mut self, interrupt: InterruptFn) -> Self {
307 self.interrupt = Some(interrupt);
308 self
309 }
310
311 #[must_use]
313 pub fn tool_use(&self) -> &ToolUse {
314 &self.tool_use
315 }
316
317 #[must_use]
319 pub fn agent(&self) -> &ToolAgent {
320 &self.agent
321 }
322
323 #[must_use]
325 pub fn invocation_state(&self) -> &InvocationState {
326 &self.invocation_state
327 }
328
329 #[must_use]
332 pub fn cancel_signal(&self) -> &CancelSignal {
333 &self.cancel_signal
334 }
335
336 #[must_use]
339 pub fn invocation_context(&self) -> Option<&InvocationContext> {
340 self.invocation_context.as_ref()
341 }
342
343 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(¶ms);
358 }
359 let id = format!("tool:{}:{}", self.tool_use.tool_use_id, params.name);
360 self.agent.interrupt_state().raise(&id, ¶ms, 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
373pub 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#[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#[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}