Skip to main content

aither_core/llm/
tool.rs

1//! # LLM Tool Calling Framework
2//!
3//!
4//! Type-safe tool calling system for Large Language Models. Enables LLMs to execute external
5//! functions, access APIs, and interact with systems through well-defined interfaces.
6//!
7//! ## How a model calls a tool
8//!
9//! A [`Tool`] declares a name, a description, and an `Arguments` type whose
10//! JSON schema is sent to the provider. When the model decides to use a tool it
11//! emits a [`ToolCall`](crate::llm::ToolCall) event carrying the tool name and
12//! arguments as JSON; this crate does not execute it. Executing the call and
13//! feeding the result back is the job of a higher layer such as `aither-agent`,
14//! which keeps tool execution under the caller's control.
15//!
16//! ## Core Components
17//!
18//! - [`Tool`] - Trait for defining executable tools
19//! - [`Tools`] - Registry for managing multiple tools
20//! - [`ToolContext`] - Per-call context through which a tool reports progress
21//! - [`tool::ToolDefinition`] - Metadata and schema for LLM consumption
22//!
23//! ## Quick Start
24//!
25//! ```rust
26//! use aither_core::llm::{Tool, ToolContext, ToolResult};
27//! use schemars::JsonSchema;
28//! use serde::Deserialize;
29//! use std::borrow::Cow;
30//!
31//! /// Performs basic math operations.
32//! #[derive(JsonSchema, Deserialize)]
33//! struct MathArgs {
34//!     /// Operation: "add", "subtract", "multiply", "divide"
35//!     operation: String,
36//!     /// First number
37//!     a: f64,
38//!     /// Second number
39//!     b: f64,
40//! }
41//!
42//! struct Calculator;
43//!
44//! impl Tool for Calculator {
45//!     fn name(&self) -> Cow<'static, str> {
46//!         Cow::Borrowed("calculator")
47//!     }
48//!
49//!     type Arguments = MathArgs;
50//!     type Res = ToolResult;
51//!
52//!     async fn call(
53//!         &self,
54//!         args: Self::Arguments,
55//!         _cx: ToolContext,
56//!     ) -> aither_core::Result<Self::Res> {
57//!         let result = match args.operation.as_str() {
58//!             "add" => args.a + args.b,
59//!             "subtract" => args.a - args.b,
60//!             "multiply" => args.a * args.b,
61//!             "divide" if args.b != 0.0 => args.a / args.b,
62//!             "divide" => return Err(anyhow::Error::msg("Division by zero")),
63//!             _ => return Err(anyhow::Error::msg("Unknown operation")),
64//!         };
65//!         Ok(ToolResult::text(result.to_string()))
66//!     }
67//! }
68//! ```
69//!
70//! ## Reporting progress
71//!
72//! A long-running tool reports how far it has got through the [`ToolContext`]
73//! its call receives. Whether anyone listens is the caller's business: an MCP
74//! server turns each report into a `notifications/progress` for the request's
75//! progress token, and a caller that does not listen passes
76//! [`ToolContext::new`], which drops the reports.
77//!
78//! ```rust
79//! use aither_core::llm::{Tool, ToolContext, ToolResult};
80//! use aither_core::llm::tool::Progress;
81//! use schemars::JsonSchema;
82//! use serde::Deserialize;
83//! use std::borrow::Cow;
84//!
85//! /// Copies the given files.
86//! #[derive(JsonSchema, Deserialize)]
87//! struct CopyArgs {
88//!     files: Vec<String>,
89//! }
90//!
91//! struct Copy;
92//!
93//! impl Tool for Copy {
94//!     fn name(&self) -> Cow<'static, str> {
95//!         "copy".into()
96//!     }
97//!
98//!     type Arguments = CopyArgs;
99//!     type Res = ToolResult;
100//!
101//!     async fn call(
102//!         &self,
103//!         args: Self::Arguments,
104//!         mut cx: ToolContext,
105//!     ) -> aither_core::Result<Self::Res> {
106//!         let total = args.files.len() as f64;
107//!         for (done, file) in args.files.iter().enumerate() {
108//!             // ... copy `file` ...
109//!             let progress = Progress::new(done as f64 + 1.0)
110//!                 .with_total(total)
111//!                 .with_message(format!("copied {file}"));
112//!             cx.report_progress(progress).await?;
113//!         }
114//!         Ok(ToolResult::text("done"))
115//!     }
116//! }
117//! ```
118//!
119//! ## Schema Design Best Practices
120//!
121//! ### 1. Use Clear Documentation Comments
122//! Doc comments automatically become schema descriptions:
123//!
124//! ```rust,ignore
125//! use schemars::JsonSchema;
126//! use serde::Deserialize;
127//!
128//! #[derive(JsonSchema, Deserialize)]
129//! struct WeatherArgs {
130//!     /// City name (e.g., "London", "Tokyo", "New York")
131//!     city: String,
132//!     /// Temperature unit: "celsius" or "fahrenheit"
133//!     #[serde(default = "default_celsius")]
134//!     unit: String,
135//! }
136//!
137//! fn default_celsius() -> String { "celsius".to_string() }
138//! ```
139//!
140//! ### 2. Prefer Enums Over Strings
141//! Enums provide clear constraints for LLMs:
142//!
143//! ```rust,ignore
144//! use schemars::JsonSchema;
145//! use serde::Deserialize;
146//!
147//! #[derive(JsonSchema, Deserialize)]
148//! enum Priority { Low, Medium, High, Critical }
149//!
150//! #[derive(JsonSchema, Deserialize)]  
151//! struct TaskArgs {
152//!     /// Task description
153//!     description: String,
154//!     /// Task priority level
155//!     priority: Priority,
156//! }
157//! ```
158//!
159//! ### 3. Add Validation Constraints
160//! Use schemars attributes for validation:
161//!
162//! ```rust,ignore
163//! use schemars::JsonSchema;
164//! use serde::Deserialize;
165//!
166//! #[derive(JsonSchema, Deserialize)]
167//! struct UserArgs {
168//!     /// Valid email address
169//!     #[schemars(regex(pattern = "^[^@]+@[^@]+\\.[^@]+$"))]
170//!     email: String,
171//!     /// Age between 13 and 120
172//!     #[schemars(range(min = 13, max = 120))]
173//!     age: u8,
174//!     /// Bio text, max 500 characters
175//!     #[schemars(length(max = 500))]
176//!     bio: Option<String>,
177//! }
178//! ```
179//!
180//! ### 4. Structure Complex Data
181//! Break down complex parameters into nested types:
182//!
183//! ```rust,ignore
184//! use schemars::JsonSchema;
185//! use serde::Deserialize;
186//!
187//! #[derive(JsonSchema, Deserialize)]
188//! struct Address {
189//!     street: String,
190//!     city: String,
191//!     /// Two-letter country code (e.g., "US", "GB", "JP")
192//!     country: String,
193//! }
194//!
195//! #[derive(JsonSchema, Deserialize)]
196//! struct CreateUserArgs {
197//!     name: String,
198//!     address: Address,
199//!     /// List of user interests
200//!     #[schemars(length(max = 10))]
201//!     interests: Vec<String>,
202//! }
203//! ```
204//!
205
206// Re-export procedural macros
207#[cfg(feature = "derive")]
208pub use aither_derive::tool;
209use alloc::borrow::Cow;
210use serde_json::Value;
211
212use crate::Result;
213use alloc::format;
214use alloc::string::{String, ToString};
215use alloc::vec::Vec;
216use alloc::{boxed::Box, collections::BTreeMap};
217use core::any::Any;
218use core::fmt::{Debug, Display};
219use core::{future::Future, pin::Pin};
220pub use mime::Mime;
221use schemars::{JsonSchema, Schema, schema_for};
222use serde::de::DeserializeOwned;
223
224mod approval;
225mod cancel;
226mod command;
227mod context;
228mod identity;
229
230pub use approval::{
231    AnyApprover, Approval, ApprovalError, ApprovalKind, ApprovalRequest, Approver, ApproverFailure,
232};
233pub use cancel::{CancelSignal, Canceller};
234pub use command::{
235    CommandOutcome, CommandResult, CommandStream, Interruption, InterruptionCause, StoredFile,
236    render_interruptions,
237};
238pub use context::{Progress, ProgressError, ProgressSink, ToolContext};
239pub use identity::{AgentIdentity, AgentPath, CallIdentity, SubagentIdentity, ToolCallId};
240
241/// Final structured result from a tool execution.
242///
243/// This keeps successful content and tool-level failures in distinct variants so
244/// UIs and runtimes do not need to infer errors from free-form strings.
245///
246/// # Example
247///
248/// ```rust,ignore
249/// use aither::llm::tool::ToolResult;
250///
251/// fn search_tool() -> ToolResult {
252///     ToolResult::text("Found 3 results...")
253/// }
254///
255/// fn delete_tool() -> ToolResult {
256///     ToolResult::Done
257/// }
258/// ```
259#[derive(Debug, Clone, PartialEq, Eq)]
260#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
261#[cfg_attr(feature = "serde", serde(tag = "kind", rename_all = "snake_case"))]
262pub enum ToolResult {
263    /// Tool completed with no output to return.
264    Done,
265
266    /// UTF-8 plain text output.
267    Text {
268        /// Plain text content.
269        text: String,
270    },
271
272    /// Tab-separated tabular output.
273    Tsv {
274        /// TSV content.
275        text: String,
276    },
277
278    /// Binary or media payload.
279    Binary {
280        /// MIME type of the payload (for example `image/png`).
281        mime: String,
282        /// Raw content bytes.
283        content: Vec<u8>,
284    },
285
286    /// Tool-level error. This is distinct from transport/runtime failures.
287    Error {
288        /// Tool-level error message.
289        message: String,
290    },
291
292    /// Typed record of a command run by a terminal-like tool.
293    ///
294    /// [`ToolResult::render_for_model`] renders the model's prose from it;
295    /// hosts read the fields and never parse that prose.
296    /// Boxed: the record is much larger than every other variant.
297    Command(Box<CommandResult>),
298
299    /// Several content items produced by one tool call.
300    ///
301    /// A single call can legitimately yield more than one payload — for
302    /// example a relayed MCP tool result that pairs explanatory text with a
303    /// screenshot. Parts never nest and never carry errors: tool-level
304    /// failures stay on [`ToolResult::Error`].
305    Parts {
306        /// Ordered content items.
307        parts: Vec<ToolResultPart>,
308    },
309}
310
311/// One content item inside [`ToolResult::Parts`].
312///
313/// Mirrors the payload-carrying [`ToolResult`] variants. `Done` and `Error`
314/// have no part equivalent: they describe the call as a whole.
315#[derive(Debug, Clone, PartialEq, Eq)]
316#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
317#[cfg_attr(feature = "serde", serde(tag = "kind", rename_all = "snake_case"))]
318pub enum ToolResultPart {
319    /// UTF-8 plain text output.
320    Text {
321        /// Plain text content.
322        text: String,
323    },
324
325    /// Tab-separated tabular output.
326    Tsv {
327        /// TSV content.
328        text: String,
329    },
330
331    /// Binary or media payload.
332    Binary {
333        /// MIME type of the payload (for example `image/png`).
334        mime: String,
335        /// Raw content bytes.
336        content: Vec<u8>,
337    },
338}
339
340impl ToolResult {
341    /// Creates a plain text result.
342    #[must_use]
343    pub fn text(s: impl Into<String>) -> Self {
344        Self::Text { text: s.into() }
345    }
346
347    /// Creates a TSV result.
348    #[must_use]
349    pub fn tsv(s: impl Into<String>) -> Self {
350        Self::Tsv { text: s.into() }
351    }
352
353    /// Creates an image result.
354    #[must_use]
355    pub fn image(data: Vec<u8>, media_type: &str) -> Self {
356        Self::Binary {
357            mime: parse_media_type_or_octet_stream(media_type),
358            content: data,
359        }
360    }
361
362    /// Creates a binary result.
363    #[must_use]
364    pub fn binary(data: Vec<u8>) -> Self {
365        Self::Binary {
366            mime: mime::APPLICATION_OCTET_STREAM.essence_str().to_string(),
367            content: data,
368        }
369    }
370
371    /// Creates a typed tool error result.
372    #[must_use]
373    pub fn error(message: impl Into<String>) -> Self {
374        Self::Error {
375            message: message.into(),
376        }
377    }
378
379    /// Creates a multi-part result.
380    ///
381    /// An empty part list collapses to [`ToolResult::Done`] and a single part
382    /// collapses to the matching single-payload variant, so callers that
383    /// conditionally accumulate parts never produce a degenerate `Parts`.
384    #[must_use]
385    pub fn parts(parts: Vec<ToolResultPart>) -> Self {
386        match <[ToolResultPart; 1]>::try_from(parts) {
387            Ok([part]) => part.into_result(),
388            Err(parts) if parts.is_empty() => Self::Done,
389            Err(parts) => Self::Parts { parts },
390        }
391    }
392
393    /// Returns `true` if this is a `Done` variant.
394    #[must_use]
395    pub const fn is_done(&self) -> bool {
396        matches!(self, Self::Done)
397    }
398
399    /// Returns `true` if this is a typed tool error.
400    #[must_use]
401    pub const fn is_error(&self) -> bool {
402        matches!(self, Self::Error { .. })
403    }
404
405    /// Returns plain textual content when every payload this result carries is text-like.
406    #[must_use]
407    pub fn as_text(&self) -> Option<&str> {
408        match self {
409            Self::Text { text } | Self::Tsv { text } => Some(text),
410            Self::Error { message } => Some(message),
411            Self::Done | Self::Binary { .. } | Self::Command(_) | Self::Parts { .. } => None,
412        }
413    }
414
415    /// Returns the typed command record if this is a command result.
416    #[must_use]
417    pub fn command(&self) -> Option<&CommandResult> {
418        match self {
419            Self::Command(command) => Some(command.as_ref()),
420            _ => None,
421        }
422    }
423
424    /// Returns the error message if this is a typed tool error.
425    #[must_use]
426    pub fn error_message(&self) -> Option<&str> {
427        match self {
428            Self::Error { message } => Some(message),
429            Self::Done
430            | Self::Text { .. }
431            | Self::Tsv { .. }
432            | Self::Binary { .. }
433            | Self::Command(_)
434            | Self::Parts { .. } => None,
435        }
436    }
437
438    /// Projects the result into a textual representation safe to re-inject into model context.
439    #[must_use]
440    pub fn render_for_model(&self) -> String {
441        match self {
442            Self::Done => String::new(),
443            Self::Text { text } | Self::Tsv { text } => text.clone(),
444            Self::Command(command) => command.render_for_model(),
445            Self::Binary { mime, content } => render_binary_placeholder(mime, content),
446            Self::Error { message } => message.clone(),
447            Self::Parts { parts } => join_part_renders(parts),
448        }
449    }
450
451    /// Parses and returns the MIME type when this result carries binary content.
452    ///
453    /// A multi-part result yields a MIME type only when it holds exactly one
454    /// binary part; mixed content has no single type to report.
455    #[must_use]
456    pub fn mime(&self) -> Option<Mime> {
457        match self {
458            Self::Binary { mime, .. } => mime.parse().ok(),
459            Self::Parts { parts } => match parts.as_slice() {
460                [ToolResultPart::Binary { mime, .. }] => mime.parse().ok(),
461                _ => None,
462            },
463            Self::Done
464            | Self::Text { .. }
465            | Self::Tsv { .. }
466            | Self::Command(_)
467            | Self::Error { .. } => None,
468        }
469    }
470
471    /// Returns raw bytes when this result carries binary content.
472    ///
473    /// Follows the same single-binary rule as [`Self::mime`].
474    #[must_use]
475    pub fn content(&self) -> Option<&[u8]> {
476        match self {
477            Self::Binary { content, .. } => Some(content),
478            Self::Parts { parts } => match parts.as_slice() {
479                [ToolResultPart::Binary { content, .. }] => Some(content),
480                _ => None,
481            },
482            Self::Done
483            | Self::Text { .. }
484            | Self::Tsv { .. }
485            | Self::Command(_)
486            | Self::Error { .. } => None,
487        }
488    }
489}
490
491impl ToolResultPart {
492    /// Creates a plain text part.
493    #[must_use]
494    pub fn text(s: impl Into<String>) -> Self {
495        Self::Text { text: s.into() }
496    }
497
498    /// Creates a TSV part.
499    #[must_use]
500    pub fn tsv(s: impl Into<String>) -> Self {
501        Self::Tsv { text: s.into() }
502    }
503
504    /// Creates an image part.
505    #[must_use]
506    pub fn image(data: Vec<u8>, media_type: &str) -> Self {
507        Self::Binary {
508            mime: parse_media_type_or_octet_stream(media_type),
509            content: data,
510        }
511    }
512
513    /// Creates a binary part.
514    #[must_use]
515    pub fn binary(data: Vec<u8>) -> Self {
516        Self::Binary {
517            mime: mime::APPLICATION_OCTET_STREAM.essence_str().to_string(),
518            content: data,
519        }
520    }
521
522    /// Returns plain textual content for text-like parts.
523    #[must_use]
524    pub fn as_text(&self) -> Option<&str> {
525        match self {
526            Self::Text { text } | Self::Tsv { text } => Some(text),
527            Self::Binary { .. } => None,
528        }
529    }
530
531    /// Projects the part into a textual representation safe to re-inject into model context.
532    #[must_use]
533    pub fn render_for_model(&self) -> String {
534        match self {
535            Self::Text { text } | Self::Tsv { text } => text.clone(),
536            Self::Binary { mime, content } => render_binary_placeholder(mime, content),
537        }
538    }
539
540    /// Parses and returns the MIME type when this part carries binary content.
541    #[must_use]
542    pub fn mime(&self) -> Option<Mime> {
543        match self {
544            Self::Binary { mime, .. } => mime.parse().ok(),
545            Self::Text { .. } | Self::Tsv { .. } => None,
546        }
547    }
548
549    /// Returns raw bytes for binary parts.
550    #[must_use]
551    pub fn content(&self) -> Option<&[u8]> {
552        match self {
553            Self::Binary { content, .. } => Some(content),
554            Self::Text { .. } | Self::Tsv { .. } => None,
555        }
556    }
557
558    /// Lifts the part into its single-payload [`ToolResult`] equivalent.
559    #[must_use]
560    pub fn into_result(self) -> ToolResult {
561        match self {
562            Self::Text { text } | Self::Tsv { text } => ToolResult::Text { text },
563            Self::Binary { mime, content } => ToolResult::Binary { mime, content },
564        }
565    }
566}
567
568fn render_binary_placeholder(mime: &str, content: &[u8]) -> String {
569    let mut rendered = String::new();
570    rendered.push_str("[binary tool result: ");
571    rendered.push_str(mime);
572    rendered.push_str(", ");
573    rendered.push_str(content.len().to_string().as_str());
574    rendered.push_str(" bytes]");
575    rendered
576}
577
578fn join_part_renders(parts: &[ToolResultPart]) -> String {
579    let mut rendered = String::new();
580    for part in parts {
581        let text = part.render_for_model();
582        if text.is_empty() {
583            continue;
584        }
585        if !rendered.is_empty() {
586            rendered.push('\n');
587        }
588        rendered.push_str(&text);
589    }
590    rendered
591}
592
593/// Conversion trait for values returned by [`Tool::call`].
594///
595/// Tool authors can return `Result<T: IntoToolResult, E: Display>`; an `Err`
596/// becomes a typed tool error inside [`ToolResult`]. Structured data is
597/// rendered to text by the tool itself, never by a serializer.
598pub trait IntoToolResult {
599    /// Converts the value into a final [`ToolResult`].
600    ///
601    /// # Errors
602    ///
603    /// Returns an error if the conversion cannot be completed.
604    fn into_tool_result(self) -> Result<ToolResult>;
605}
606
607impl IntoToolResult for ToolResult {
608    fn into_tool_result(self) -> Result<ToolResult> {
609        Ok(self)
610    }
611}
612
613impl IntoToolResult for CommandResult {
614    fn into_tool_result(self) -> Result<ToolResult> {
615        Ok(ToolResult::Command(Box::new(self)))
616    }
617}
618
619impl IntoToolResult for () {
620    fn into_tool_result(self) -> Result<ToolResult> {
621        Ok(ToolResult::Done)
622    }
623}
624
625impl IntoToolResult for String {
626    fn into_tool_result(self) -> Result<ToolResult> {
627        Ok(ToolResult::text(self))
628    }
629}
630
631impl IntoToolResult for &str {
632    fn into_tool_result(self) -> Result<ToolResult> {
633        Ok(ToolResult::text(self))
634    }
635}
636
637impl IntoToolResult for Cow<'_, str> {
638    fn into_tool_result(self) -> Result<ToolResult> {
639        Ok(ToolResult::text(self.into_owned()))
640    }
641}
642
643impl<T> IntoToolResult for Option<T>
644where
645    T: IntoToolResult,
646{
647    fn into_tool_result(self) -> Result<ToolResult> {
648        self.map_or_else(|| Ok(ToolResult::Done), IntoToolResult::into_tool_result)
649    }
650}
651
652impl IntoToolResult for Vec<ToolResultPart> {
653    fn into_tool_result(self) -> Result<ToolResult> {
654        Ok(ToolResult::parts(self))
655    }
656}
657
658impl<T, E> IntoToolResult for core::result::Result<T, E>
659where
660    T: IntoToolResult,
661    E: Display,
662{
663    fn into_tool_result(self) -> Result<ToolResult> {
664        match self {
665            Ok(value) => value.into_tool_result(),
666            Err(error) => Ok(ToolResult::error(error.to_string())),
667        }
668    }
669}
670
671fn parse_media_type_or_octet_stream(media_type: &str) -> String {
672    media_type
673        .parse::<Mime>()
674        .unwrap_or(mime::APPLICATION_OCTET_STREAM)
675        .essence_str()
676        .to_string()
677}
678
679/// Tools that can be called by language models.
680///
681/// # Example
682///
683/// ```rust,ignore
684/// use aither::llm::{Tool, ToolContext, ToolResult};
685/// use schemars::JsonSchema;
686/// use serde::Deserialize;
687///
688/// #[derive(JsonSchema, Deserialize)]
689/// struct CalculatorArgs {
690///     operation: String,
691///     a: f64,
692///     b: f64,
693/// }
694///
695/// struct Calculator;
696///
697/// impl Tool for Calculator {
698///     type Arguments = CalculatorArgs;
699///     type Res = ToolResult;
700///
701///     async fn call(&self, args: Self::Arguments, _cx: ToolContext) -> aither::Result<Self::Res> {
702///         match args.operation.as_str() {
703///             "add" => Ok(ToolResult::text((args.a + args.b).to_string())),
704///             "subtract" => Ok(ToolResult::text((args.a - args.b).to_string())),
705///             "multiply" => Ok(ToolResult::text((args.a * args.b).to_string())),
706///             "divide" => {
707///                 if args.b != 0.0 {
708///                     Ok(ToolResult::text((args.a / args.b).to_string()))
709///                 } else {
710///                     Err(anyhow::Error::msg("Division by zero"))
711///                 }
712///             }
713///             _ => Err(anyhow::Error::msg("Unknown operation")),
714///         }
715///     }
716/// }
717/// ```
718pub trait Tool: Send + Sync {
719    /// Tool name. Must be unique.
720    fn name(&self) -> Cow<'static, str>;
721
722    /// What the tool does, as shown to the model.
723    ///
724    /// This is the single most important thing a model uses to decide whether
725    /// to call a tool, so it must not be empty — [`Tools::register`] rejects a
726    /// tool whose description is blank.
727    ///
728    /// The default implementation reads the rustdoc comment on
729    /// [`Self::Arguments`], which `schemars` records in the generated schema.
730    /// Override it to supply the description directly.
731    fn description(&self) -> Cow<'static, str> {
732        description_from_schema::<Self::Arguments>().unwrap_or_default()
733    }
734
735    /// The JSON schema of the tool's arguments, as sent to the provider.
736    ///
737    /// The default derives it from [`Self::Arguments`]. Override it to build
738    /// the schema from the tool's own state, for an argument whose allowed
739    /// values are configured at runtime. Every reader of a tool's schema —
740    /// [`ToolDefinition::new`], and through it the provider request and
741    /// [`Tools::definitions`] — reads it here, so the override must keep the
742    /// shape `Self::Arguments` deserializes from. The root must be an object
743    /// schema, as providers require; the default wraps a non-object
744    /// `Arguments` type in one.
745    fn arguments_schema(&self) -> Schema {
746        derived_arguments_schema::<Self::Arguments>()
747    }
748
749    /// Tool arguments type. Must implement [`schemars::JsonSchema`] and [`serde::de::DeserializeOwned`].
750    /// Its rustdoc becomes the default tool description.
751    type Arguments: Send + JsonSchema + DeserializeOwned;
752
753    /// Raw return type from the tool implementation.
754    type Res: IntoToolResult + Send;
755
756    /// Executes the tool with the provided arguments.
757    ///
758    /// `cx` is this call's own context: report progress through
759    /// [`ToolContext::report_progress`], which reaches the caller when it
760    /// listens and is a no-op when it does not. It is owned, so the tool may
761    /// move it into whatever part of the work reports.
762    ///
763    /// Returns a value that can be converted into a final [`ToolResult`].
764    ///
765    /// Tools that need mutable state should use interior mutability (e.g., `Mutex`).
766    fn call(
767        &self,
768        arguments: Self::Arguments,
769        cx: ToolContext,
770    ) -> impl Future<Output = Result<Self::Res>> + Send;
771}
772
773trait ToolImpl: Send + Sync + Any {
774    fn call(
775        &self,
776        args: &str,
777        cx: ToolContext,
778    ) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send + '_>>;
779
780    /// The cached definition. Borrowed, so registering a tool does not have to
781    /// clone its argument schema.
782    fn definition(&self) -> &ToolDefinition;
783
784    /// Upcast to [`Any`] so [`Tools::get`] can recover the concrete tool.
785    ///
786    /// Casting the `Box<dyn ToolImpl>` itself would downcast the box rather
787    /// than the tool inside it, and so never match.
788    fn as_any(&self) -> &dyn Any;
789
790    /// Mutable counterpart of [`Self::as_any`].
791    fn as_any_mut(&mut self) -> &mut dyn Any;
792}
793
794/// Dynamic tool implementation for type-erased tools.
795struct DynToolImpl<F>
796where
797    F: Fn(&str, ToolContext) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send>>
798        + Send
799        + Sync,
800{
801    definition: ToolDefinition,
802    handler: F,
803}
804
805impl<F> ToolImpl for DynToolImpl<F>
806where
807    F: Fn(&str, ToolContext) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send>>
808        + Send
809        + Sync
810        + 'static,
811{
812    fn call(
813        &self,
814        args: &str,
815        cx: ToolContext,
816    ) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send + '_>> {
817        (self.handler)(args, cx)
818    }
819
820    fn definition(&self) -> &ToolDefinition {
821        &self.definition
822    }
823
824    fn as_any(&self) -> &dyn Any {
825        self
826    }
827
828    fn as_any_mut(&mut self) -> &mut dyn Any {
829        self
830    }
831}
832
833/// Whether a schema describes a JSON object, and so can be sent to a provider
834/// as tool arguments without being wrapped in [`ToolArgument`].
835fn schema_is_object(value: &Value) -> bool {
836    matches!(value.get("type").and_then(Value::as_str), Some("object"))
837        || value.get("properties").is_some()
838        || value.get("oneOf").is_some()
839        || value.get("anyOf").is_some()
840        || value.get("$defs").is_some()
841}
842
843fn is_object<T: JsonSchema>() -> bool {
844    schema_is_object(&schema_for!(T).to_value())
845}
846
847/// Builds the argument schema for a tool, wrapping scalars so the root is
848/// always an object as providers require.
849fn derived_arguments_schema<T: JsonSchema>() -> Schema {
850    if is_object::<T>() {
851        schema_for!(T)
852    } else {
853        schema_for!(ToolArgument<T>)
854    }
855}
856
857/// Reads the `description` a `JsonSchema` derive records from a type's rustdoc.
858fn description_from_schema<T: JsonSchema>() -> Option<Cow<'static, str>> {
859    schema_for!(T)
860        .to_value()
861        .get("description")
862        .and_then(Value::as_str)
863        .filter(|text| !text.trim().is_empty())
864        .map(|text| Cow::Owned(text.to_string()))
865}
866
867/// A registered tool together with everything derived from its type.
868///
869/// The argument schema and the "are these arguments an object?" decision are
870/// properties of `T::Arguments` alone, so they are computed once here rather
871/// than rebuilt on every invocation.
872struct RegisteredTool<T: Tool> {
873    tool: T,
874    definition: ToolDefinition,
875    args_are_object: bool,
876}
877
878impl<T: Tool> RegisteredTool<T> {
879    fn new(tool: T) -> Self {
880        let definition = ToolDefinition::new(&tool);
881        let args_are_object = is_object::<T::Arguments>();
882        Self {
883            tool,
884            definition,
885            args_are_object,
886        }
887    }
888}
889
890/// Error the model reads when it sends arguments that do not parse.
891#[derive(askama::Template)]
892#[template(path = "invalid_arguments.txt", escape = "none")]
893struct InvalidArguments<'a> {
894    tool: &'a str,
895    error: &'a serde_json::Error,
896}
897
898impl<T: Tool + 'static> ToolImpl for RegisteredTool<T> {
899    fn call(
900        &self,
901        args: &str,
902        cx: ToolContext,
903    ) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send + '_>> {
904        let result = if self.args_are_object {
905            serde_json::from_str::<T::Arguments>(args)
906        } else {
907            serde_json::from_str::<ToolArgument<T::Arguments>>(args).map(|wrapper| wrapper.value)
908        };
909
910        let arguments = match result {
911            Ok(arguments) => arguments,
912            Err(error) => {
913                let message = InvalidArguments {
914                    tool: self.definition.name(),
915                    error: &error,
916                }
917                .to_string();
918                return Box::pin(async move { Err(anyhow::Error::msg(message)) });
919            }
920        };
921
922        Box::pin(async move {
923            Tool::call(&self.tool, arguments, cx)
924                .await?
925                .into_tool_result()
926        })
927    }
928
929    fn definition(&self) -> &ToolDefinition {
930        &self.definition
931    }
932
933    fn as_any(&self) -> &dyn Any {
934        &self.tool
935    }
936
937    fn as_any_mut(&mut self) -> &mut dyn Any {
938        &mut self.tool
939    }
940}
941
942/// A tool definition carried something that is not a JSON schema.
943///
944/// JSON Schema allows an object or a bare boolean; anything else — a string, an
945/// array, a number — describes nothing a model could fill in.
946#[derive(Debug, Clone, PartialEq, Eq)]
947pub struct InvalidSchema {
948    /// The tool whose schema was rejected.
949    name: Cow<'static, str>,
950}
951
952impl InvalidSchema {
953    /// The name of the tool whose schema was rejected.
954    #[must_use]
955    pub fn name(&self) -> &str {
956        &self.name
957    }
958}
959
960impl Display for InvalidSchema {
961    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
962        write!(
963            f,
964            "tool '{}' has an argument schema that is neither an object nor a boolean",
965            self.name
966        )
967    }
968}
969
970impl core::error::Error for InvalidSchema {}
971
972/// Why a tool could not be added to a [`Tools`] registry.
973#[derive(Debug, Clone, PartialEq, Eq)]
974pub enum RegisterError {
975    /// A tool with this name is already registered.
976    ///
977    /// Names address tools in a model's tool-call, so they must be unique.
978    DuplicateName(Cow<'static, str>),
979
980    /// The tool's description is empty.
981    ///
982    /// A description is what a model uses to decide whether to call a tool, so
983    /// an empty one makes the tool unusable rather than merely undocumented.
984    EmptyDescription(Cow<'static, str>),
985}
986
987impl Display for RegisterError {
988    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
989        match self {
990            Self::DuplicateName(name) => {
991                write!(f, "a tool named '{name}' is already registered")
992            }
993            Self::EmptyDescription(name) => write!(
994                f,
995                "tool '{name}' has an empty description; add a rustdoc comment to its \
996                 Arguments type or implement Tool::description"
997            ),
998        }
999    }
1000}
1001
1002impl core::error::Error for RegisterError {}
1003
1004/// Tool registry for managing and calling tools by name.
1005///
1006///
1007/// # Example
1008///
1009/// ```rust,ignore
1010/// use aither::llm::tool::Tools;
1011///
1012/// let mut tools = Tools::new();
1013/// // tools.register(Calculator);
1014/// let definitions = tools.definitions();
1015/// // let result = tools
1016/// //     .call("calculator", r#"{"operation": "add", "a": 5, "b": 3}"#, ToolContext::new())
1017/// //     .await;
1018/// ```
1019pub struct Tools {
1020    tools: BTreeMap<Cow<'static, str>, Box<dyn ToolImpl>>,
1021}
1022
1023impl Debug for Tools {
1024    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1025        f.debug_struct("Tools")
1026            .field("tools", &self.tools.keys().collect::<Vec<_>>())
1027            .finish()
1028    }
1029}
1030
1031/// Tool definition including schema for language models.
1032///
1033/// Used to provide language models with information about available [`Tool`]s.
1034#[derive(Debug, Clone, PartialEq)]
1035#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1036pub struct ToolDefinition {
1037    /// Tool name.
1038    name: Cow<'static, str>,
1039    /// Tool description.
1040    description: Cow<'static, str>,
1041    /// JSON schema for tool arguments.
1042    arguments: Schema,
1043}
1044
1045impl ToolDefinition {
1046    /// Creates a tool definition for a given tool type.
1047    ///
1048    /// The description comes from [`Tool::description`], which by default reads
1049    /// the rustdoc on the tool's `Arguments` type.
1050    #[must_use]
1051    pub fn new<T: Tool>(tool: &T) -> Self {
1052        Self {
1053            name: tool.name(),
1054            description: tool.description(),
1055            arguments: tool.arguments_schema(),
1056        }
1057    }
1058
1059    /// Creates a tool definition from raw parts.
1060    ///
1061    /// This is useful for creating definitions from external sources like MCP servers.
1062    ///
1063    /// # Errors
1064    ///
1065    /// Returns [`InvalidSchema`] if the value is not a JSON schema — that is,
1066    /// anything other than an object or a boolean. The schema often comes from
1067    /// a remote server, so this is a rejection to report, not a bug to panic
1068    /// on.
1069    pub fn from_parts(
1070        name: Cow<'static, str>,
1071        description: Cow<'static, str>,
1072        schema: Value,
1073    ) -> core::result::Result<Self, InvalidSchema> {
1074        let arguments: Schema = schema
1075            .try_into()
1076            .map_err(|_| InvalidSchema { name: name.clone() })?;
1077
1078        Ok(Self {
1079            name,
1080            description,
1081            arguments,
1082        })
1083    }
1084
1085    /// Returns the tool's name.
1086    #[must_use]
1087    pub fn name(&self) -> &str {
1088        &self.name
1089    }
1090
1091    /// Returns the tool's description.
1092    #[must_use]
1093    pub fn description(&self) -> &str {
1094        &self.description
1095    }
1096
1097    /// Return an OpenAI-compatible JSON schema for the tool's arguments.
1098    ///
1099    /// This schema would have an object type at the root, as required by `OpenAI`.
1100    #[must_use]
1101    pub fn arguments_openai_schema(&self) -> serde_json::Value {
1102        let mut inner = self.arguments.clone().to_value();
1103        clean_schema(&mut inner);
1104
1105        inner
1106    }
1107}
1108
1109#[derive(Debug, serde::Serialize, serde::Deserialize, schemars::JsonSchema)]
1110struct ToolArgument<T> {
1111    value: T,
1112}
1113
1114fn clean_schema(value: &mut Value) {
1115    // First pass: extract $defs for reference resolution
1116    let defs = extract_defs(value);
1117
1118    // Second pass: resolve refs and clean
1119    resolve_and_clean(value, &defs);
1120
1121    // Clean up root-level schema
1122    if let Value::Object(map) = value {
1123        // Remove root-level description - it's already used as tool description
1124        // Keeping it duplicates the description in the API request
1125        map.remove("description");
1126
1127        // Ensure root has type: object (required by OpenAI function calling)
1128        if map.contains_key("properties") && !map.contains_key("type") {
1129            map.insert("type".to_string(), Value::String("object".to_string()));
1130        }
1131    }
1132}
1133
1134/// Extracts `$defs` or `definitions` from the root schema.
1135fn extract_defs(value: &Value) -> serde_json::Map<String, Value> {
1136    if let Value::Object(map) = value
1137        && let Some(Value::Object(defs)) = map.get("$defs").or_else(|| map.get("definitions"))
1138    {
1139        return defs.clone();
1140    }
1141    serde_json::Map::new()
1142}
1143
1144/// Resolves `$ref` and cleans the schema recursively.
1145#[allow(clippy::too_many_lines)]
1146fn resolve_and_clean(value: &mut Value, defs: &serde_json::Map<String, Value>) {
1147    resolve_and_clean_inner(value, defs, false);
1148}
1149
1150/// Inner recursive function with flag to track if we're inside a properties object.
1151#[allow(clippy::too_many_lines)]
1152fn resolve_and_clean_inner(
1153    value: &mut Value,
1154    defs: &serde_json::Map<String, Value>,
1155    inside_properties: bool,
1156) {
1157    match value {
1158        Value::Object(map) => {
1159            // Handle $ref - inline the referenced definition, preserving sibling properties
1160            if let Some(Value::String(ref_path)) = map.remove("$ref")
1161                && let Some(Value::Object(resolved_map)) = resolve_ref(&ref_path, defs)
1162            {
1163                // Merge resolved definition with any existing properties (like description)
1164                // Resolved definition takes precedence for conflicts except description
1165                let existing_description = map.remove("description");
1166                for (k, v) in resolved_map {
1167                    map.entry(k).or_insert(v);
1168                }
1169                // Preserve the field-level description if it exists
1170                if let Some(desc) = existing_description {
1171                    map.insert("description".to_string(), desc);
1172                }
1173            }
1174
1175            // Convert "const" to "enum" with single value (before filtering)
1176            if let Some(const_val) = map.remove("const") {
1177                map.insert("enum".to_string(), Value::Array(alloc::vec![const_val]));
1178            }
1179
1180            // Flatten oneOf/anyOf variants (before filtering, since oneOf is not in allowed list)
1181            if let Some(Value::Array(variants)) =
1182                map.remove("oneOf").or_else(|| map.remove("anyOf"))
1183            {
1184                // Check if this is a simple string enum (variants have const/type but no properties)
1185                let is_simple_enum = variants.iter().all(|v| {
1186                    if let Value::Object(vm) = v {
1187                        (vm.contains_key("const") || vm.contains_key("enum"))
1188                            && !vm.contains_key("properties")
1189                    } else {
1190                        false
1191                    }
1192                });
1193
1194                if is_simple_enum {
1195                    // Collect all const/enum values into a single enum array
1196                    let mut enum_values: alloc::vec::Vec<Value> = alloc::vec::Vec::new();
1197                    let mut variant_type: Option<String> = None;
1198
1199                    for variant in &variants {
1200                        if let Value::Object(vm) = variant {
1201                            if let Some(const_val) = vm.get("const")
1202                                && !enum_values.contains(const_val)
1203                            {
1204                                enum_values.push(const_val.clone());
1205                            }
1206                            if let Some(Value::Array(arr)) = vm.get("enum") {
1207                                for val in arr {
1208                                    if !enum_values.contains(val) {
1209                                        enum_values.push(val.clone());
1210                                    }
1211                                }
1212                            }
1213                            if variant_type.is_none()
1214                                && let Some(Value::String(t)) = vm.get("type")
1215                            {
1216                                variant_type = Some(t.clone());
1217                            }
1218                        }
1219                    }
1220
1221                    if !enum_values.is_empty() {
1222                        map.insert("enum".to_string(), Value::Array(enum_values));
1223                        if let Some(t) = variant_type {
1224                            map.insert("type".to_string(), Value::String(t));
1225                        }
1226                    }
1227                } else {
1228                    // Complex variants with properties - merge them
1229                    let mut all_properties = serde_json::Map::new();
1230
1231                    for variant in variants {
1232                        if let Value::Object(variant_map) = variant
1233                            && let Some(Value::Object(props)) = variant_map.get("properties")
1234                        {
1235                            for (key, val) in props {
1236                                // Extract enum value - handle both "enum" and "const"
1237                                let new_values: Option<alloc::vec::Vec<Value>> =
1238                                    if let Value::Object(val_obj) = val {
1239                                        if let Some(Value::Array(arr)) = val_obj.get("enum") {
1240                                            Some(arr.clone())
1241                                        } else {
1242                                            val_obj
1243                                                .get("const")
1244                                                .map(|const_val| alloc::vec![const_val.clone()])
1245                                        }
1246                                    } else {
1247                                        None
1248                                    };
1249
1250                                if all_properties.contains_key(key) {
1251                                    // Merge enum/const values into existing
1252                                    if let Some(values) = new_values
1253                                        && let Some(Value::Object(existing_obj)) =
1254                                            all_properties.get_mut(key)
1255                                        && let Some(Value::Array(existing_enum)) =
1256                                            existing_obj.get_mut("enum")
1257                                    {
1258                                        for e in values {
1259                                            if !existing_enum.contains(&e) {
1260                                                existing_enum.push(e);
1261                                            }
1262                                        }
1263                                    }
1264                                } else {
1265                                    // First time seeing this property - convert const to enum
1266                                    let mut val_clone = val.clone();
1267                                    if let Value::Object(obj) = &mut val_clone
1268                                        && let Some(const_val) = obj.remove("const")
1269                                    {
1270                                        obj.insert(
1271                                            "enum".to_string(),
1272                                            Value::Array(alloc::vec![const_val]),
1273                                        );
1274                                    }
1275                                    all_properties.insert(key.clone(), val_clone);
1276                                }
1277                            }
1278                        }
1279                    }
1280
1281                    // Set type as object if we have properties
1282                    if !all_properties.is_empty() {
1283                        map.insert("type".to_string(), Value::String("object".to_string()));
1284                        map.insert("properties".to_string(), Value::Object(all_properties));
1285                    }
1286                }
1287            }
1288
1289            // Only filter schema keywords, not property names inside "properties"
1290            // OpenAPI schema subset supported by most LLM providers
1291            if !inside_properties {
1292                let allowed = [
1293                    "type",
1294                    "description",
1295                    "properties",
1296                    "required",
1297                    "items",
1298                    "enum",
1299                    "nullable",
1300                ];
1301                map.retain(|k, _| allowed.contains(&k.as_str()));
1302            }
1303
1304            // Simplify "type" arrays like ["string", "null"] to single type
1305            if let Some(Value::Array(types)) = map.get("type") {
1306                // Filter out "null" and take the first non-null type
1307                let non_null: Vec<&Value> = types
1308                    .iter()
1309                    .filter(|t| !matches!(t, Value::String(s) if s == "null"))
1310                    .collect();
1311                if non_null.len() == 1 {
1312                    map.insert("type".to_string(), non_null[0].clone());
1313                }
1314            }
1315
1316            // Recursively clean all values
1317            for (key, v) in map.iter_mut() {
1318                // When entering "properties", its children are property definitions
1319                let child_inside_props = key == "properties";
1320                resolve_and_clean_inner(v, defs, child_inside_props);
1321            }
1322        }
1323        Value::Array(arr) => {
1324            for v in arr {
1325                resolve_and_clean_inner(v, defs, false);
1326            }
1327        }
1328        _ => {}
1329    }
1330}
1331
1332/// Resolves a `$ref` path like `#/$defs/FsOperation` to its definition.
1333fn resolve_ref(ref_path: &str, defs: &serde_json::Map<String, Value>) -> Option<Value> {
1334    // Handle common patterns: #/$defs/Name or #/definitions/Name
1335    let name = ref_path
1336        .strip_prefix("#/$defs/")
1337        .or_else(|| ref_path.strip_prefix("#/definitions/"))?;
1338
1339    defs.get(name).cloned()
1340}
1341
1342impl Default for Tools {
1343    fn default() -> Self {
1344        Self::new()
1345    }
1346}
1347
1348impl Tools {
1349    /// Creates a new empty tools registry.
1350    #[must_use]
1351    pub const fn new() -> Self {
1352        Self {
1353            tools: BTreeMap::new(),
1354        }
1355    }
1356
1357    /// Retrieves a tool by type.
1358    ///
1359    /// Returns `None` if the tool is not found.
1360    #[must_use]
1361    pub fn get<T>(&self) -> Option<&T>
1362    where
1363        T: Tool + 'static,
1364    {
1365        self.tools
1366            .values()
1367            .find_map(|tool| tool.as_any().downcast_ref::<T>())
1368    }
1369
1370    /// Retrieves a mutable reference to a tool by type.
1371    ///
1372    /// Returns `None` if the tool is not found.
1373    #[must_use]
1374    pub fn get_mut<T>(&mut self) -> Option<&mut T>
1375    where
1376        T: Tool + 'static,
1377    {
1378        self.tools
1379            .values_mut()
1380            .find_map(|tool| tool.as_any_mut().downcast_mut::<T>())
1381    }
1382
1383    /// Returns definitions of all registered tools.
1384    #[must_use]
1385    pub fn definitions(&self) -> Vec<ToolDefinition> {
1386        self.tools
1387            .values()
1388            .map(|tool| tool.definition().clone())
1389            .collect()
1390    }
1391
1392    /// Registers a new tool.
1393    ///
1394    /// The tool must implement [`Tool`] and be `'static`.
1395    ///
1396    /// # Errors
1397    ///
1398    /// Returns [`RegisterError::DuplicateName`] if a tool of that name is
1399    /// already registered, or [`RegisterError::EmptyDescription`] if the tool
1400    /// has no description — a model cannot use a tool it cannot read about, so
1401    /// this is rejected rather than silently passed on.
1402    pub fn register<T: Tool + 'static>(
1403        &mut self,
1404        tool: T,
1405    ) -> core::result::Result<(), RegisterError> {
1406        self.insert(Box::new(RegisteredTool::new(tool)))
1407    }
1408
1409    /// Registers a dynamic tool with a pre-made definition and handler.
1410    ///
1411    /// This is useful for type-erased tools (e.g., child terminal tools for subagents)
1412    /// where the concrete type isn't known at compile time. The handler
1413    /// receives the JSON arguments and the call's [`ToolContext`].
1414    ///
1415    /// # Errors
1416    ///
1417    /// Same conditions as [`Self::register`].
1418    pub fn register_dyn<F>(
1419        &mut self,
1420        definition: ToolDefinition,
1421        handler: F,
1422    ) -> core::result::Result<(), RegisterError>
1423    where
1424        F: Fn(&str, ToolContext) -> Pin<Box<dyn Future<Output = Result<ToolResult>> + Send>>
1425            + Send
1426            + Sync
1427            + 'static,
1428    {
1429        self.insert(Box::new(DynToolImpl {
1430            definition,
1431            handler,
1432        }))
1433    }
1434
1435    fn insert(&mut self, tool: Box<dyn ToolImpl>) -> core::result::Result<(), RegisterError> {
1436        let name = tool.definition().name.clone();
1437        if self.tools.contains_key(&name) {
1438            return Err(RegisterError::DuplicateName(name));
1439        }
1440        if tool.definition().description().trim().is_empty() {
1441            return Err(RegisterError::EmptyDescription(name));
1442        }
1443        self.tools.insert(name, tool);
1444        Ok(())
1445    }
1446
1447    /// Removes a tool from the registry.
1448    pub fn unregister(&mut self, name: &str) {
1449        self.tools.remove(name);
1450    }
1451
1452    /// Calls a tool by name with JSON arguments, running it with `cx` as its
1453    /// [`ToolContext`].
1454    ///
1455    /// # Errors
1456    ///
1457    /// Returns an error if the tool is not found, arguments cannot be parsed,
1458    /// or tool execution fails.
1459    pub async fn call(&self, name: &str, args: &str, cx: ToolContext) -> Result<ToolResult> {
1460        if let Some(tool) = self.tools.get(name) {
1461            tool.call(args, cx).await
1462        } else {
1463            Err(anyhow::Error::msg(format!("Tool '{name}' not found")))
1464        }
1465    }
1466}
1467
1468#[cfg(test)]
1469mod tests {
1470    use super::*;
1471    use alloc::{format, string::ToString, vec};
1472    use schemars::JsonSchema;
1473    use serde::Deserialize;
1474
1475    /// Performs basic mathematical operations.
1476    #[derive(JsonSchema, Deserialize, Debug, PartialEq)]
1477    struct CalculatorArgs {
1478        operation: String,
1479        a: f64,
1480        b: f64,
1481    }
1482
1483    struct Calculator;
1484
1485    impl Tool for Calculator {
1486        fn name(&self) -> Cow<'static, str> {
1487            "calculator".into()
1488        }
1489        type Arguments = CalculatorArgs;
1490        type Res = ToolResult;
1491
1492        fn call(
1493            &self,
1494            args: Self::Arguments,
1495            _cx: ToolContext,
1496        ) -> impl Future<Output = Result<Self::Res>> + Send {
1497            core::future::ready(match args.operation.as_str() {
1498                "add" => Ok(ToolResult::text((args.a + args.b).to_string())),
1499                "subtract" => Ok(ToolResult::text((args.a - args.b).to_string())),
1500                "multiply" => Ok(ToolResult::text((args.a * args.b).to_string())),
1501                "divide" => {
1502                    if args.b == 0.0 {
1503                        Err(anyhow::Error::msg("Division by zero"))
1504                    } else {
1505                        Ok(ToolResult::text((args.a / args.b).to_string()))
1506                    }
1507                }
1508                _ => Err(anyhow::Error::msg(format!(
1509                    "Unknown operation: {}",
1510                    args.operation
1511                ))),
1512            })
1513        }
1514    }
1515
1516    /// Greets a person by name.
1517    #[derive(JsonSchema, Deserialize)]
1518    struct GreetArgs {
1519        name: String,
1520    }
1521
1522    struct Greeter;
1523
1524    impl Tool for Greeter {
1525        fn name(&self) -> Cow<'static, str> {
1526            "greeter".into()
1527        }
1528        type Arguments = GreetArgs;
1529        type Res = ToolResult;
1530
1531        fn call(
1532            &self,
1533            args: Self::Arguments,
1534            _cx: ToolContext,
1535        ) -> impl Future<Output = Result<Self::Res>> + Send {
1536            core::future::ready(Ok(ToolResult::text(format!("Hello, {}!", args.name))))
1537        }
1538    }
1539
1540    #[test]
1541    fn from_parts_accepts_object_and_boolean_schemas() {
1542        // JSON Schema allows a bare boolean as well as an object.
1543        for schema in [
1544            serde_json::json!({"type": "object"}),
1545            serde_json::json!(true),
1546        ] {
1547            assert!(
1548                ToolDefinition::from_parts("t".into(), "does a thing".into(), schema.clone())
1549                    .is_ok(),
1550                "{schema} should be accepted"
1551            );
1552        }
1553    }
1554
1555    #[test]
1556    fn from_parts_rejects_non_schema_values() {
1557        // A server that sends any of these describes nothing a model could
1558        // fill in. Rejecting must not panic: the value came off the wire.
1559        for schema in [
1560            serde_json::json!("a string"),
1561            serde_json::json!([1, 2, 3]),
1562            serde_json::json!(7),
1563            serde_json::json!(null),
1564        ] {
1565            let result = ToolDefinition::from_parts("weird".into(), "d".into(), schema.clone());
1566            let Err(err) = result else {
1567                panic!("{schema} should be rejected");
1568            };
1569            assert_eq!(err.name(), "weird");
1570        }
1571    }
1572
1573    #[test]
1574    fn tool_definition_creation() {
1575        let calculator = Calculator;
1576        let definition = ToolDefinition::new(&calculator);
1577
1578        assert_eq!(definition.name, "calculator");
1579        assert_eq!(
1580            definition.description,
1581            "Performs basic mathematical operations."
1582        );
1583        // Schema should be present - just check it exists
1584        // The exact structure of schemars::Schema is implementation detail
1585    }
1586
1587    #[test]
1588    fn tools_creation() {
1589        let tools = Tools::new();
1590        assert_eq!(tools.definitions().len(), 0);
1591    }
1592
1593    #[test]
1594    fn tools_default() {
1595        let tools = Tools::default();
1596        assert_eq!(tools.definitions().len(), 0);
1597    }
1598
1599    #[tokio::test]
1600    async fn tools_register_and_call() {
1601        let mut tools = Tools::new();
1602        tools.register(Calculator).expect("calculator registers");
1603
1604        let definitions = tools.definitions();
1605        assert_eq!(definitions.len(), 1);
1606        assert_eq!(definitions[0].name, "calculator");
1607
1608        let result = tools
1609            .call(
1610                "calculator",
1611                r#"{"operation": "add", "a": 5, "b": 3}"#,
1612                ToolContext::new(),
1613            )
1614            .await;
1615        assert!(result.is_ok());
1616        assert_eq!(result.unwrap().as_text(), Some("8"));
1617    }
1618
1619    #[tokio::test]
1620    async fn invalid_arguments_report_the_parse_error_without_schema() {
1621        let mut tools = Tools::new();
1622        tools.register(Calculator).expect("calculator registers");
1623
1624        let error = tools
1625            .call("calculator", r#"{"operation": "add"}"#, ToolContext::new())
1626            .await
1627            .unwrap_err()
1628            .to_string();
1629        assert_eq!(
1630            error,
1631            "Invalid arguments for tool 'calculator': missing field `a` at line 1 column 20"
1632        );
1633    }
1634
1635    #[test]
1636    fn command_result_renders_its_text() {
1637        let result = ToolResult::Command(Box::new(CommandResult {
1638            stdout: CommandStream::Inline {
1639                text: "hi\n".to_string(),
1640            },
1641            stderr: None,
1642            outcome: CommandOutcome::Exited { code: 3 },
1643            interruptions: Vec::new(),
1644        }));
1645        assert_eq!(result.render_for_model(), "hi\nExit code: 3.\n");
1646        assert_eq!(
1647            result.command().map(|command| &command.outcome),
1648            Some(&CommandOutcome::Exited { code: 3 })
1649        );
1650    }
1651
1652    #[cfg(feature = "serde")]
1653    #[test]
1654    fn command_result_round_trips_through_serde() {
1655        let file = || crate::llm::StoredFile {
1656            url: "outputs/x.txt".to_string(),
1657            path: "/sandbox/outputs/x.txt".to_string(),
1658        };
1659        let results = [
1660            CommandResult {
1661                stdout: CommandStream::Inline {
1662                    text: "hi\n".to_string(),
1663                },
1664                stderr: Some(CommandStream::Inline {
1665                    text: "oops".to_string(),
1666                }),
1667                outcome: CommandOutcome::Exited { code: 1 },
1668                interruptions: Vec::new(),
1669            },
1670            CommandResult {
1671                stdout: CommandStream::Stored {
1672                    file: file(),
1673                    preview: "head".to_string(),
1674                    truncated: true,
1675                },
1676                stderr: None,
1677                outcome: CommandOutcome::Exited { code: 0 },
1678                interruptions: Vec::new(),
1679            },
1680            CommandResult {
1681                stdout: CommandStream::Image {
1682                    media_type: "image/png".to_string(),
1683                    file: file(),
1684                },
1685                stderr: None,
1686                outcome: CommandOutcome::Running {
1687                    task_id: "t1".to_string(),
1688                    output: file(),
1689                },
1690                interruptions: Vec::new(),
1691            },
1692        ];
1693        for command in results {
1694            let result = ToolResult::Command(Box::new(command));
1695            let json = serde_json::to_string(&result).expect("a command result serializes");
1696            let back: ToolResult = serde_json::from_str(&json).expect("it deserializes back");
1697            assert_eq!(back, result, "{json}");
1698        }
1699    }
1700
1701    #[tokio::test]
1702    async fn calculator_operations() {
1703        let mut tools = Tools::new();
1704        tools.register(Calculator).expect("calculator registers");
1705
1706        // Test addition
1707        let result = tools
1708            .call(
1709                "calculator",
1710                r#"{"operation": "add", "a": 10, "b": 5}"#,
1711                ToolContext::new(),
1712            )
1713            .await;
1714        assert_eq!(result.unwrap().as_text(), Some("15"));
1715
1716        // Test subtraction
1717        let result = tools
1718            .call(
1719                "calculator",
1720                r#"{"operation": "subtract", "a": 10, "b": 3}"#,
1721                ToolContext::new(),
1722            )
1723            .await;
1724        assert_eq!(result.unwrap().as_text(), Some("7"));
1725
1726        // Test multiplication
1727        let result = tools
1728            .call(
1729                "calculator",
1730                r#"{"operation": "multiply", "a": 4, "b": 3}"#,
1731                ToolContext::new(),
1732            )
1733            .await;
1734        assert_eq!(result.unwrap().as_text(), Some("12"));
1735
1736        // Test division
1737        let result = tools
1738            .call(
1739                "calculator",
1740                r#"{"operation": "divide", "a": 15, "b": 3}"#,
1741                ToolContext::new(),
1742            )
1743            .await;
1744        assert_eq!(result.unwrap().as_text(), Some("5"));
1745    }
1746
1747    #[tokio::test]
1748    async fn calculator_division_by_zero() {
1749        let mut tools = Tools::new();
1750        tools.register(Calculator).expect("calculator registers");
1751
1752        let result = tools
1753            .call(
1754                "calculator",
1755                r#"{"operation": "divide", "a": 10, "b": 0}"#,
1756                ToolContext::new(),
1757            )
1758            .await;
1759        assert!(result.is_err());
1760        assert!(result.unwrap_err().to_string().contains("Division by zero"));
1761    }
1762
1763    #[tokio::test]
1764    async fn calculator_unknown_operation() {
1765        let mut tools = Tools::new();
1766        tools.register(Calculator).expect("calculator registers");
1767
1768        let result = tools
1769            .call(
1770                "calculator",
1771                r#"{"operation": "modulo", "a": 10, "b": 3}"#,
1772                ToolContext::new(),
1773            )
1774            .await;
1775        assert!(result.is_err());
1776        assert!(
1777            result
1778                .unwrap_err()
1779                .to_string()
1780                .contains("Unknown operation")
1781        );
1782    }
1783
1784    #[tokio::test]
1785    async fn multiple_tools() {
1786        let mut tools = Tools::new();
1787        tools.register(Calculator).expect("calculator registers");
1788        tools.register(Greeter).expect("greeter registers");
1789
1790        let definitions = tools.definitions();
1791        assert_eq!(definitions.len(), 2);
1792
1793        // Find calculator and greeter in definitions
1794        let calc_def = definitions.iter().find(|d| d.name == "calculator").unwrap();
1795        let greet_def = definitions.iter().find(|d| d.name == "greeter").unwrap();
1796
1797        assert_eq!(
1798            calc_def.description,
1799            "Performs basic mathematical operations."
1800        );
1801        assert_eq!(greet_def.description, "Greets a person by name.");
1802
1803        // Test both tools
1804        let calc_result = tools
1805            .call(
1806                "calculator",
1807                r#"{"operation": "add", "a": 2, "b": 3}"#,
1808                ToolContext::new(),
1809            )
1810            .await;
1811        assert_eq!(calc_result.unwrap().as_text(), Some("5"));
1812
1813        let greet_result = tools
1814            .call("greeter", r#"{"name": "Alice"}"#, ToolContext::new())
1815            .await;
1816        assert_eq!(greet_result.unwrap().as_text(), Some("Hello, Alice!"));
1817    }
1818
1819    #[derive(Debug)]
1820    struct ToolFailure(&'static str);
1821
1822    impl core::fmt::Display for ToolFailure {
1823        fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1824            f.write_str(self.0)
1825        }
1826    }
1827
1828    impl core::error::Error for ToolFailure {}
1829
1830    #[test]
1831    fn into_tool_result_string_is_plain_text() {
1832        assert_eq!(
1833            String::from("hello").into_tool_result().unwrap(),
1834            ToolResult::text("hello")
1835        );
1836    }
1837
1838    #[test]
1839    fn into_tool_result_str_is_plain_text() {
1840        assert_eq!(
1841            "hello".into_tool_result().unwrap(),
1842            ToolResult::text("hello")
1843        );
1844    }
1845
1846    #[test]
1847    fn into_tool_result_option_none_is_done() {
1848        let result = Option::<String>::None.into_tool_result().unwrap();
1849        assert_eq!(result, ToolResult::Done);
1850    }
1851
1852    #[test]
1853    fn into_tool_result_option_some_delegates() {
1854        let result = Some("hello").into_tool_result().unwrap();
1855        assert_eq!(result, ToolResult::text("hello"));
1856    }
1857
1858    #[test]
1859    fn into_tool_result_result_ok_string_is_text() {
1860        let result = core::result::Result::<String, ToolFailure>::Ok(String::from("hello"))
1861            .into_tool_result()
1862            .unwrap();
1863        assert_eq!(result, ToolResult::text("hello"));
1864    }
1865
1866    #[test]
1867    fn into_tool_result_result_err_is_typed_error() {
1868        let result = core::result::Result::<String, ToolFailure>::Err(ToolFailure("boom"))
1869            .into_tool_result()
1870            .unwrap();
1871        assert_eq!(result, ToolResult::error("boom"));
1872        assert!(result.is_error());
1873        assert_eq!(result.error_message(), Some("boom"));
1874    }
1875
1876    #[tokio::test]
1877    async fn tool_not_found() {
1878        let tools = Tools::new();
1879
1880        let result = tools.call("nonexistent", "{}", ToolContext::new()).await;
1881        assert!(result.is_err());
1882        assert!(
1883            result
1884                .unwrap_err()
1885                .to_string()
1886                .contains("Tool 'nonexistent' not found")
1887        );
1888    }
1889
1890    #[tokio::test]
1891    async fn invalid_json() {
1892        let mut tools = Tools::new();
1893        tools.register(Calculator).expect("calculator registers");
1894
1895        let result = tools
1896            .call("calculator", "invalid json", ToolContext::new())
1897            .await;
1898        assert!(result.is_err());
1899    }
1900
1901    #[test]
1902    fn tools_unregister() {
1903        let mut tools = Tools::new();
1904        tools.register(Calculator).expect("calculator registers");
1905        tools.register(Greeter).expect("greeter registers");
1906
1907        assert_eq!(tools.definitions().len(), 2);
1908
1909        tools.unregister("calculator");
1910        assert_eq!(tools.definitions().len(), 1);
1911
1912        let remaining = &tools.definitions()[0];
1913        assert_eq!(remaining.name, "greeter");
1914
1915        tools.unregister("greeter");
1916        assert_eq!(tools.definitions().len(), 0);
1917    }
1918
1919    #[test]
1920    fn tools_debug() {
1921        let mut tools = Tools::new();
1922        tools.register(Calculator).expect("calculator registers");
1923        tools.register(Greeter).expect("greeter registers");
1924
1925        let debug_str = format!("{tools:?}");
1926        assert!(debug_str.contains("Tools"));
1927        assert!(debug_str.contains("calculator"));
1928        assert!(debug_str.contains("greeter"));
1929    }
1930
1931    #[test]
1932    fn tool_definition_debug() {
1933        let calculator = Calculator;
1934        let definition = ToolDefinition::new(&calculator);
1935        let debug_str = format!("{definition:?}");
1936
1937        assert!(debug_str.contains("ToolDefinition"));
1938        assert!(debug_str.contains("calculator"));
1939        assert!(debug_str.contains("Performs basic mathematical operations"));
1940    }
1941
1942    #[derive(JsonSchema, Deserialize)]
1943    #[expect(dead_code, reason = "only the schema is read")]
1944    struct PickArgs {
1945        /// The interpreter to run with.
1946        interpreter: String,
1947    }
1948
1949    /// A tool whose `interpreter` argument lists the values it was built with.
1950    struct Pick {
1951        interpreters: Vec<String>,
1952    }
1953
1954    impl Tool for Pick {
1955        fn name(&self) -> Cow<'static, str> {
1956            "pick".into()
1957        }
1958        fn description(&self) -> Cow<'static, str> {
1959            "Picks an interpreter.".into()
1960        }
1961        fn arguments_schema(&self) -> Schema {
1962            let mut schema = derived_arguments_schema::<PickArgs>();
1963            schema.ensure_object();
1964            let property = schema
1965                .get_mut("properties")
1966                .and_then(Value::as_object_mut)
1967                .and_then(|properties| properties.get_mut("interpreter"))
1968                .and_then(Value::as_object_mut)
1969                .expect("interpreter property");
1970            property.insert("enum".into(), self.interpreters.clone().into());
1971            schema
1972        }
1973        type Arguments = PickArgs;
1974        type Res = ToolResult;
1975
1976        fn call(
1977            &self,
1978            _args: Self::Arguments,
1979            _cx: ToolContext,
1980        ) -> impl Future<Output = Result<Self::Res>> + Send {
1981            core::future::ready(Ok(ToolResult::text("ok")))
1982        }
1983    }
1984
1985    #[test]
1986    fn runtime_schema_reaches_the_definition_and_the_registry() {
1987        let tool = Pick {
1988            interpreters: vec!["bash".to_string(), "python".to_string()],
1989        };
1990        let expected = serde_json::json!(["bash", "python"]);
1991
1992        let schema = ToolDefinition::new(&tool).arguments_openai_schema();
1993        assert_eq!(schema["properties"]["interpreter"]["enum"], expected);
1994
1995        let mut tools = Tools::new();
1996        tools.register(tool).expect("registers");
1997        let listed = tools.definitions();
1998        assert_eq!(
1999            listed[0].arguments_openai_schema()["properties"]["interpreter"]["enum"],
2000            expected
2001        );
2002    }
2003
2004    #[test]
2005    fn tool_without_override_sends_the_derived_schema() {
2006        let schema = ToolDefinition::new(&Calculator).arguments_openai_schema();
2007        let mut derived = schema_for!(<Calculator as Tool>::Arguments).to_value();
2008        clean_schema(&mut derived);
2009        assert_eq!(schema, derived);
2010        assert!(schema["properties"]["interpreter"].is_null());
2011    }
2012
2013    #[test]
2014    fn tool_definition_clone() {
2015        let calculator = Calculator;
2016        let original = ToolDefinition::new(&calculator);
2017        let cloned = original.clone();
2018
2019        assert_eq!(original.name, cloned.name);
2020        assert_eq!(original.description, cloned.description);
2021    }
2022
2023    #[test]
2024    fn schema_preserves_enum() {
2025        #[derive(JsonSchema, Deserialize)]
2026        #[serde(rename_all = "snake_case")]
2027        enum Status {
2028            Pending,
2029            InProgress,
2030            Completed,
2031        }
2032
2033        #[allow(dead_code)]
2034        #[derive(JsonSchema, Deserialize)]
2035        struct Item {
2036            status: Status,
2037        }
2038
2039        #[allow(dead_code)]
2040        #[derive(JsonSchema, Deserialize)]
2041        struct Args {
2042            items: Vec<Item>,
2043        }
2044
2045        struct TestTool;
2046
2047        impl Tool for TestTool {
2048            fn name(&self) -> Cow<'static, str> {
2049                "test".into()
2050            }
2051            type Arguments = Args;
2052            type Res = ToolResult;
2053
2054            fn call(
2055                &self,
2056                _args: Self::Arguments,
2057                _cx: ToolContext,
2058            ) -> impl Future<Output = Result<Self::Res>> + Send {
2059                core::future::ready(Ok(ToolResult::text("ok")))
2060            }
2061        }
2062
2063        let tool = TestTool;
2064        let def = ToolDefinition::new(&tool);
2065        let schema = def.arguments_openai_schema();
2066
2067        // Check that status has enum values
2068        let schema_obj = schema.as_object().expect("schema should be object");
2069        let properties = schema_obj
2070            .get("properties")
2071            .expect("should have properties")
2072            .as_object()
2073            .unwrap();
2074        let items = properties
2075            .get("items")
2076            .expect("should have items")
2077            .as_object()
2078            .unwrap();
2079        let item_props = items
2080            .get("items")
2081            .expect("items should have items schema")
2082            .as_object()
2083            .unwrap();
2084        let item_properties = item_props
2085            .get("properties")
2086            .expect("item should have properties")
2087            .as_object()
2088            .unwrap();
2089        let status = item_properties
2090            .get("status")
2091            .expect("should have status")
2092            .as_object()
2093            .unwrap();
2094
2095        // Status should have enum
2096        assert!(
2097            status.contains_key("enum"),
2098            "Status should have enum field. Full schema: {}",
2099            serde_json::to_string_pretty(&schema).unwrap()
2100        );
2101    }
2102
2103    #[test]
2104    fn schema_ref_resolution() {
2105        // Test that $ref schemas get resolved and enum values preserved
2106        let raw_schema = serde_json::json!({
2107            "type": "object",
2108            "properties": {
2109                "status": {
2110                    "$ref": "#/$defs/Status"
2111                }
2112            },
2113            "$defs": {
2114                "Status": {
2115                    "type": "string",
2116                    "enum": ["pending", "in_progress", "completed"]
2117                }
2118            }
2119        });
2120
2121        let mut schema = raw_schema;
2122        clean_schema(&mut schema);
2123
2124        let props = schema.get("properties").unwrap().as_object().unwrap();
2125        let status = props.get("status").unwrap().as_object().unwrap();
2126
2127        assert!(
2128            status.contains_key("enum"),
2129            "Status should have enum after ref resolution. Got: {}",
2130            serde_json::to_string_pretty(&schema).unwrap()
2131        );
2132    }
2133
2134    #[test]
2135    fn schema_nested_ref_in_array() {
2136        // Test nested $ref inside array items (like BatchWriteArgs)
2137        let raw_schema = serde_json::json!({
2138            "type": "object",
2139            "properties": {
2140                "entries": {
2141                    "type": "array",
2142                    "items": {
2143                        "$ref": "#/$defs/BatchItem"
2144                    }
2145                }
2146            },
2147            "$defs": {
2148                "BatchItem": {
2149                    "type": "object",
2150                    "properties": {
2151                        "content": { "type": "string" },
2152                        "status": { "$ref": "#/$defs/BatchStatus" }
2153                    },
2154                    "required": ["content", "status"]
2155                },
2156                "BatchStatus": {
2157                    "type": "string",
2158                    "enum": ["pending", "in_progress", "completed"]
2159                }
2160            }
2161        });
2162
2163        let mut schema = raw_schema;
2164        clean_schema(&mut schema);
2165
2166        // Navigate to status
2167        let props = schema.get("properties").unwrap().as_object().unwrap();
2168        let todos = props.get("entries").unwrap().as_object().unwrap();
2169        let items = todos.get("items").unwrap().as_object().unwrap();
2170        let item_props = items.get("properties").unwrap().as_object().unwrap();
2171        let status = item_props.get("status").unwrap().as_object().unwrap();
2172
2173        assert!(
2174            status.contains_key("enum"),
2175            "Nested status should have enum. Full schema: {}",
2176            serde_json::to_string_pretty(&schema).unwrap()
2177        );
2178    }
2179
2180    #[test]
2181    fn parts_collapses_degenerate_inputs() {
2182        assert_eq!(ToolResult::parts(vec![]), ToolResult::Done);
2183        assert_eq!(
2184            ToolResult::parts(vec![ToolResultPart::text("only")]),
2185            ToolResult::text("only")
2186        );
2187        let multi = ToolResult::parts(vec![
2188            ToolResultPart::text("a"),
2189            ToolResultPart::image(vec![1, 2], "image/png"),
2190        ]);
2191        let ToolResult::Parts { parts } = &multi else {
2192            panic!("two parts must stay a Parts result");
2193        };
2194        assert_eq!(parts.len(), 2);
2195    }
2196
2197    #[test]
2198    fn parts_render_joins_text_and_marks_binary() {
2199        let result = ToolResult::parts(vec![
2200            ToolResultPart::text("header"),
2201            ToolResultPart::tsv("n\n1\n"),
2202            ToolResultPart::image(vec![0x89], "image/png"),
2203        ]);
2204        assert_eq!(
2205            result.render_for_model(),
2206            "header\nn\n1\n\n[binary tool result: image/png, 1 bytes]"
2207        );
2208        assert!(result.mime().is_none() && result.content().is_none());
2209    }
2210
2211    #[test]
2212    fn parts_with_one_binary_expose_mime_and_content() {
2213        let result = ToolResult::Parts {
2214            parts: vec![ToolResultPart::image(vec![9, 9], "image/png")],
2215        };
2216        assert_eq!(result.mime().unwrap().essence_str(), "image/png");
2217        assert_eq!(result.content().unwrap(), &[9, 9]);
2218    }
2219
2220    #[cfg(feature = "serde")]
2221    #[test]
2222    fn parts_serde_roundtrip_uses_kind_tag() {
2223        let result = ToolResult::parts(vec![
2224            ToolResultPart::text("note"),
2225            ToolResultPart::tsv("k\ntrue\n"),
2226        ]);
2227        let value = serde_json::to_value(&result).unwrap();
2228        assert_eq!(value["kind"], "parts");
2229        assert_eq!(value["parts"][0]["kind"], "text");
2230        let back: ToolResult = serde_json::from_value(value).unwrap();
2231        assert_eq!(back, result);
2232    }
2233}