1use std::fmt;
4use std::sync::Arc;
5
6use super::tool::Tool;
7
8#[derive(Clone)]
14#[non_exhaustive]
15pub enum ToolSource {
16 Tool(Arc<dyn Tool>),
18 List(Vec<ToolSource>),
20 #[cfg(feature = "mcp")]
22 McpClient(crate::mcp::McpClient),
23}
24
25impl ToolSource {
26 #[must_use]
29 pub fn into_tools(self) -> Vec<Arc<dyn Tool>> {
30 self.into_parts().tools
31 }
32
33 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 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#[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#[macro_export]
126macro_rules! tool_list {
127 ($($source:expr),* $(,)?) => {
128 ::std::vec![$($crate::ToolSource::from($source)),*]
129 };
130}