Skip to main content

Tool

Trait Tool 

Source
pub trait Tool:
    Sized
    + WasmCompatSend
    + WasmCompatSync {
    type Error: Error + WasmCompatSend + WasmCompatSync + 'static;
    type Args: for<'a> Deserialize<'a> + WasmCompatSend + WasmCompatSync;
    type Output: Serialize;

    const NAME: &'static str;

    // Required methods
    fn description(&self) -> String;
    fn parameters(&self) -> Value;
    fn call(
        &self,
        args: Self::Args,
    ) -> impl Future<Output = Result<Self::Output, Self::Error>> + WasmCompatSend;

    // Provided methods
    fn name(&self) -> String { ... }
    fn call_with_extensions(
        &self,
        args: Self::Args,
        _extensions: &ToolCallExtensions,
    ) -> impl Future<Output = Result<Self::Output, Self::Error>> + WasmCompatSend { ... }
    fn classify_error(&self, error: &Self::Error) -> ToolFailure { ... }
    fn call_structured(
        &self,
        args: Self::Args,
        extensions: &ToolCallExtensions,
    ) -> impl Future<Output = Result<ToolReturn<Self::Output>, Self::Error>> + WasmCompatSend { ... }
}
Expand description

Trait that represents a simple LLM tool.

Tool authors provide flat metadata (NAME, description, and parameters). Provider-facing ToolDefinitions are generated by Rig when tools are registered in an agent request.

§Example

use rig_core::tool::{Tool, ToolSet};

#[derive(serde::Deserialize)]
struct AddArgs {
    x: i32,
    y: i32,
}

#[derive(Debug, thiserror::Error)]
#[error("Math error")]
struct MathError;

#[derive(serde::Deserialize, serde::Serialize)]
struct Adder;

impl Tool for Adder {
    const NAME: &'static str = "add";

    type Error = MathError;
    type Args = AddArgs;
    type Output = i32;

    fn description(&self) -> String {
        "Add x and y together".to_string()
    }

    fn parameters(&self) -> serde_json::Value {
        serde_json::json!({
            "type": "object",
            "properties": {
                "x": {
                    "type": "number",
                    "description": "The first number to add"
                },
                "y": {
                    "type": "number",
                    "description": "The second number to add"
                }
            }
        })
    }

    async fn call(&self, args: Self::Args) -> Result<Self::Output, Self::Error> {
        let result = args.x + args.y;
        Ok(result)
    }
}

Required Associated Constants§

Source

const NAME: &'static str

The name of the tool. This name should be unique within a single ToolSet or other registration scope that dispatches tools by name.

Required Associated Types§

Source

type Error: Error + WasmCompatSend + WasmCompatSync + 'static

The error type of the tool.

Source

type Args: for<'a> Deserialize<'a> + WasmCompatSend + WasmCompatSync

The arguments type of the tool.

Source

type Output: Serialize

The output type of the tool.

Required Methods§

Source

fn description(&self) -> String

Model-facing description of what the tool does.

Source

fn parameters(&self) -> Value

JSON Schema for the tool arguments.

Source

fn call( &self, args: Self::Args, ) -> impl Future<Output = Result<Self::Output, Self::Error>> + WasmCompatSend

The tool execution method. Both the arguments and return value are a String since these values are meant to be the output and input of LLM models (respectively)

Provided Methods§

Source

fn name(&self) -> String

A method returning the name of the tool.

Source

fn call_with_extensions( &self, args: Self::Args, _extensions: &ToolCallExtensions, ) -> impl Future<Output = Result<Self::Output, Self::Error>> + WasmCompatSend

Tool execution with per-call runtime extensions.

Override this to access runtime values (auth, session IDs, etc.) injected by the caller via ToolCallExtensions. The default ignores the extensions and delegates to Tool::call.

Override contract: the default Tool::call_structured delegates here, so overriding this method is how you read extensions for the common case — the agent loop drives call_structured, which reaches your override (with an empty ToolCallExtensions when no caller supplied one). Under dynamic dispatch this then becomes the single execution entry point (call’s body is unreachable that way; a direct Tool::call still runs it), so put your logic here and treat a missing value as the no-extensions case (e.g. ToolCallExtensions::get returning None). If you also override call_structured, that override supersedes this method on the agent’s structured path — put your logic there instead.

Source

fn classify_error(&self, error: &Self::Error) -> ToolFailure

Classify an error returned by this tool into a structured ToolFailure.

This is how a tool’s own error type reaches a hook, policy, or telemetry pipeline as a machine-readable ToolFailureKind — with no string parsing. The default classifies every error as ToolFailureKind::Other with the error’s Display as the message; override it to map your error variants onto the standard kinds (timeout, not-found, rate-limited, …) and attach a code / http_status / retryable hint:

fn classify_error(&self, error: &Self::Error) -> ToolFailure {
    match error {
        MyError::Timeout => ToolFailure::timeout(error.to_string()),
        MyError::Http { status: 404, .. } => {
            ToolFailure::not_found(error.to_string()).with_http_status(404)
        }
        other => ToolFailure::other(other.to_string()),
    }
}
Source

fn call_structured( &self, args: Self::Args, extensions: &ToolCallExtensions, ) -> impl Future<Output = Result<ToolReturn<Self::Output>, Self::Error>> + WasmCompatSend

Execute the tool, returning a structured ToolReturn instead of a bare output.

The richest tool-execution entry point. The default calls call_with_extensions and wraps the output as a plain ToolReturn::success with no metadata, so a tool that only implements call needs nothing extra. Override it to:

  • attach result metadata to a success (ToolReturn::success(out).with_extension(..));
  • report a handled failure that still shows output to the model (ToolReturn::failed);
  • mark the call denied — the tool refused it (a framework hook Flow::Skip is what yields a skipped outcome, not the tool).

Override contract: this is the single entry point under structured dynamic dispatch — the agent loop routes every tool call here via the blanket ToolDyn impl. If you override it, the call / call_with_extensions bodies are unreachable on that structured path (a direct call still runs them), so put your logic here. A returned Err(Self::Error) is still classified via classify_error.

Dyn Compatibility§

This trait is not dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl Tool for MockAddTool

Available on crate feature test-utils only.
Source§

impl Tool for MockBarrierTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "barrier_tool"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = String

Source§

impl Tool for MockControlledTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "controlled"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = i32

Source§

impl Tool for MockDeniedTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "guarded"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = String

Source§

impl Tool for MockExampleTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "example_tool"

Source§

type Error = MockToolError

Source§

type Args = ()

Source§

type Output = String

Source§

impl Tool for MockExtensionsProbeTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "context_probe"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = String

Source§

impl Tool for MockFailingTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "flaky_tool"

Source§

type Error = MockFailure

Source§

type Args = Value

Source§

type Output = String

Source§

impl Tool for MockHandledFailureTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "lookup"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = String

Source§

impl Tool for MockImageGeneratorTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "generate_test_image"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = String

Source§

impl Tool for MockImageOutputTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "image_output"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = String

Source§

impl Tool for MockMetadataTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "with_meta"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = String

Source§

impl Tool for MockObjectOutputTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "object_output"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = Value

Source§

impl Tool for MockStringOutputTool

Available on crate feature test-utils only.
Source§

const NAME: &'static str = "string_output"

Source§

type Error = MockToolError

Source§

type Args = Value

Source§

type Output = String

Source§

impl Tool for MockSubtractTool

Available on crate feature test-utils only.
Source§

impl Tool for ThinkTool

Source§

impl<M: CompletionModel + 'static> Tool for Agent<M>

Source§

const NAME: &'static str = "agent_tool"

Source§

type Error = PromptError

Source§

type Args = AgentToolArgs

Source§

type Output = String

Source§

impl<T, F> Tool for T
where F: SearchFilter<Value = Value> + WasmCompatSend + WasmCompatSync + for<'de> Deserialize<'de>, T: VectorStoreIndex<Filter = F>,