Skip to main content

strands/tools/
source.rs

1//! [`ToolSource`], anything that provides tools to an agent, and [`tool_list!`](crate::tool_list).
2
3use std::fmt;
4use std::sync::Arc;
5
6use super::tool::Tool;
7
8/// Something that provides tools to an agent.
9///
10/// Convert a tool, a shared `Arc<dyn Tool>` or a list with `.into()`. A list of different tool
11/// types needs [`tool_list!`](crate::tool_list) or `ToolSource::from` on each item, because `.into()` has no single
12/// target type there.
13#[derive(Clone)]
14#[non_exhaustive]
15pub enum ToolSource {
16    /// One tool.
17    Tool(Arc<dyn Tool>),
18    /// A nested list.
19    List(Vec<ToolSource>),
20    /// An MCP client; the agent lists its tools when it initializes.
21    #[cfg(feature = "mcp")]
22    McpClient(crate::mcp::McpClient),
23}
24
25impl ToolSource {
26    /// The tools, with nested lists flattened in order. MCP clients are left out: their tools
27    /// come from the server when an agent initializes.
28    #[must_use]
29    pub fn into_tools(self) -> Vec<Arc<dyn Tool>> {
30        self.into_parts().tools
31    }
32
33    /// The tools, for a registry, which cannot hold an MCP client.
34    pub(crate) fn into_registry_tools(self) -> crate::error::Result<Vec<Arc<dyn Tool>>> {
35        let parts = self.into_parts();
36        #[cfg(feature = "mcp")]
37        if !parts.mcp_clients.is_empty() {
38            return Err(crate::error::ToolValidationError::new(
39                "An MCP client is not a tool; pass it to the agent's tools, or register the tools from its list_tools()",
40            )
41            .into());
42        }
43        Ok(parts.tools)
44    }
45
46    /// The tools and the MCP clients, each in order.
47    pub(crate) fn into_parts(self) -> SourceParts {
48        let mut parts = SourceParts::default();
49        self.flatten_into(&mut parts);
50        parts
51    }
52
53    fn flatten_into(self, parts: &mut SourceParts) {
54        match self {
55            Self::Tool(tool) => parts.tools.push(tool),
56            Self::List(sources) => {
57                for source in sources {
58                    source.flatten_into(parts);
59                }
60            }
61            #[cfg(feature = "mcp")]
62            Self::McpClient(client) => parts.mcp_clients.push(client),
63        }
64    }
65}
66
67/// A flattened [`ToolSource`].
68#[derive(Default)]
69pub(crate) struct SourceParts {
70    pub(crate) tools: Vec<Arc<dyn Tool>>,
71    #[cfg(feature = "mcp")]
72    pub(crate) mcp_clients: Vec<crate::mcp::McpClient>,
73}
74
75#[cfg(feature = "mcp")]
76impl From<crate::mcp::McpClient> for ToolSource {
77    fn from(client: crate::mcp::McpClient) -> Self {
78        Self::McpClient(client)
79    }
80}
81
82impl<T: Tool> From<T> for ToolSource {
83    fn from(tool: T) -> Self {
84        Self::Tool(Arc::new(tool))
85    }
86}
87
88impl From<Arc<dyn Tool>> for ToolSource {
89    fn from(tool: Arc<dyn Tool>) -> Self {
90        Self::Tool(tool)
91    }
92}
93
94impl<T: Into<ToolSource>> From<Vec<T>> for ToolSource {
95    fn from(sources: Vec<T>) -> Self {
96        Self::List(sources.into_iter().map(Into::into).collect())
97    }
98}
99
100impl fmt::Debug for ToolSource {
101    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
102        match self {
103            Self::Tool(tool) => f.debug_tuple("Tool").field(&tool.name()).finish(),
104            Self::List(sources) => f.debug_tuple("List").field(sources).finish(),
105            #[cfg(feature = "mcp")]
106            Self::McpClient(client) => f.debug_tuple("McpClient").field(&client.client_name()).finish(),
107        }
108    }
109}
110
111/// Builds a `Vec<ToolSource>` from items of different types.
112///
113/// ```
114/// use strands::tools::{FunctionTool, ToolRegistry};
115/// use strands::{ToolSource, tool_list};
116///
117/// let ping = FunctionTool::builder("ping", "Replies pong").callback(|_, _| async { Ok("pong".into()) });
118/// let echo = FunctionTool::builder("echo", "Echoes").callback(|input, _| async move { Ok(input) });
119/// let tools: Vec<ToolSource> = tool_list![ping, vec![echo]];
120///
121/// let mut registry = ToolRegistry::new();
122/// registry.add(tools).unwrap();
123/// assert_eq!(registry.list().len(), 2);
124/// ```
125#[macro_export]
126macro_rules! tool_list {
127    ($($source:expr),* $(,)?) => {
128        ::std::vec![$($crate::ToolSource::from($source)),*]
129    };
130}