Skip to main content

strands/tools/
load_tools.rs

1//! The `load_tools` tool: loads the input schemas of deferred tools.
2
3use std::fmt;
4use std::sync::{Arc, LazyLock};
5
6use indexmap::IndexSet;
7use serde::Deserialize;
8use serde_json::json;
9
10use super::tool::{DelegationToken, SdkToolRole};
11use super::{SchemaValidator, Tool, ToolContext, ToolError, ToolOutcome, ToolStream};
12use crate::agent::ToolAgent;
13use crate::error::Error;
14use crate::types::{JsonValue, ToolReferenceBlock, ToolResultBlock, ToolResultContent, ToolSpec};
15
16/// Name of the tool a model calls to load the input schemas of deferred tools
17/// (`LOAD_TOOLS_TOOL_NAME`).
18pub const LOAD_TOOLS_TOOL_NAME: &str = "load_tools";
19
20const DESCRIPTION: &str =
21    "Load tools whose parameters are not shown yet, so you can call them. Load every tool you need in one call.";
22
23fn input_schema() -> JsonValue {
24    json!({
25        "type": "object",
26        "properties": {
27            "names": {
28                "type": "array",
29                "items": {"type": "string"},
30                "minItems": 1,
31                "description": "Names of the tools to load."
32            }
33        },
34        "required": ["names"],
35        "additionalProperties": false
36    })
37}
38
39static VALIDATOR: LazyLock<Option<SchemaValidator>> = LazyLock::new(|| SchemaValidator::new(&input_schema()).ok());
40
41#[derive(Deserialize)]
42struct LoadToolsInput {
43    names: Vec<String>,
44}
45
46/// Returns the names of an agent's deferred tools.
47pub(crate) type DeferredToolsFn = Arc<dyn Fn(&ToolAgent) -> Vec<String> + Send + Sync>;
48
49/// The tool a model calls to load deferred tools (`createLoadTools`). It returns one
50/// [`ToolReferenceBlock`] per tool and nothing else, since the Claude API rejects a tool result
51/// that mixes tool references with other content. A name that isn't a deferred tool fails the
52/// whole call, so the model can call again with the right names.
53pub(crate) struct LoadTools {
54    deferred_tools: DeferredToolsFn,
55    spec: ToolSpec,
56}
57
58impl fmt::Debug for LoadTools {
59    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
60        f.debug_struct("LoadTools").finish_non_exhaustive()
61    }
62}
63
64/// The `load_tools` tool for the deferred tools `deferred_tools` names.
65pub(crate) fn create_load_tools(deferred_tools: DeferredToolsFn) -> Arc<dyn Tool> {
66    Arc::new(LoadTools {
67        deferred_tools,
68        spec: ToolSpec::new(LOAD_TOOLS_TOOL_NAME, DESCRIPTION).with_input_schema(input_schema()),
69    })
70}
71
72impl LoadTools {
73    fn load(&self, agent: &ToolAgent, input: &JsonValue) -> Result<Vec<ToolResultContent>, Error> {
74        if let Some(Err(error)) = VALIDATOR.as_ref().map(|validator| validator.validate(input)) {
75            return Err(Error::other(error.to_string()));
76        }
77        let input: LoadToolsInput = serde_json::from_value(input.clone()).map_err(Error::other)?;
78        let deferred = (self.deferred_tools)(agent);
79        let names: IndexSet<String> = input.names.into_iter().collect();
80        let registry = agent.tool_registry();
81        let missing: Vec<&str> = names
82            .iter()
83            .filter(|name| registry.get(name).is_none())
84            .map(String::as_str)
85            .collect();
86        let shown: Vec<&str> = names
87            .iter()
88            .filter(|name| !deferred.contains(name) && registry.get(name).is_some())
89            .map(String::as_str)
90            .collect();
91        // One bad name loads none: a result that mixes references with text loses Claude's native references.
92        if !missing.is_empty() || !shown.is_empty() {
93            return Err(Error::other(nothing_loaded(&missing, &shown)));
94        }
95        Ok(names
96            .into_iter()
97            .map(|name| ToolReferenceBlock::new(name).into())
98            .collect())
99    }
100}
101
102impl Tool for LoadTools {
103    fn name(&self) -> &str {
104        LOAD_TOOLS_TOOL_NAME
105    }
106
107    fn description(&self) -> &str {
108        DESCRIPTION
109    }
110
111    fn tool_spec(&self) -> ToolSpec {
112        self.spec.clone()
113    }
114
115    fn stream(&self, context: ToolContext) -> ToolStream {
116        let tool_use_id = context.tool_use().tool_use_id.clone();
117        let outcome = match self.load(context.agent(), &context.tool_use().input) {
118            Ok(content) => ToolOutcome::Result(ToolResultBlock::success(tool_use_id, content)),
119            Err(error) => ToolError::new(error).into_outcome(tool_use_id),
120        };
121        ToolStream::ready(outcome)
122    }
123
124    fn sdk_tool_role(&self, _: DelegationToken) -> Option<SdkToolRole> {
125        Some(SdkToolRole::LoadTools)
126    }
127}
128
129/// Why a load loaded nothing, naming each tool it couldn't load and what to do instead.
130fn nothing_loaded(missing: &[&str], shown: &[&str]) -> String {
131    let mut reasons = Vec::new();
132    if !shown.is_empty() {
133        reasons.push(names_with(
134            shown,
135            "is shown in full, so call it directly",
136            "are shown in full, so call them directly",
137        ));
138    }
139    if !missing.is_empty() {
140        reasons.push(names_with(missing, "is not a tool", "are not tools"));
141    }
142    format!(
143        "Nothing loaded: {}. Load only tools whose parameters are not shown.",
144        reasons.join("; ")
145    )
146}
147
148/// The names, followed by the phrase that agrees with how many there are.
149fn names_with(names: &[&str], one: &str, many: &str) -> String {
150    let phrase = if names.len() == 1 { one } else { many };
151    format!("{} {phrase}", names.join(", "))
152}