strands/vended_tools/mcp_router/
mod.rs1mod types;
5
6use std::collections::{BTreeMap, HashSet};
7use std::sync::{Arc, Mutex, PoisonError, RwLock, Weak};
8
9use indexmap::IndexMap;
10use serde_json::json;
11
12pub use types::{MCP_ROUTER_DESCRIPTION, McpRouterCommand, McpRouterInput, McpRouterToolError};
13
14use crate::error::{Error, Result};
15use crate::mcp::{
16 McpCallToolOptions, McpClient, McpClientOptions, McpConnectionState, McpListToolsOptions, McpLoadServersOptions,
17 McpServerConfig, McpServersSource, McpTool, McpToolConfig, tool_result,
18};
19use crate::tools::{FunctionTool, Tool, ToolContext, ToolError};
20use crate::types::{JsonObject, JsonValue, ToolResultContent, ToolResultStatus};
21
22const DEFAULT_MAX_CONNECTIONS: usize = 10;
23
24#[derive(Debug, Clone, Default, bon::Builder)]
26#[builder(on(String, into))]
27pub struct MakeMcpRouterOptions {
28 pub name: Option<String>,
30 pub description: Option<String>,
33 pub servers: BTreeMap<String, McpServerConfig>,
36 pub max_connections: Option<usize>,
38}
39
40struct Connection {
41 client: McpClient,
42 listed_names: Option<HashSet<String>>,
43}
44
45type AgentKey = Weak<RwLock<JsonObject>>;
46
47struct AgentConnections {
48 agent: AgentKey,
49 connections: IndexMap<String, Connection>,
50}
51
52struct Router {
53 servers: BTreeMap<String, McpServerConfig>,
54 max_connections: usize,
55 agents: Mutex<Vec<AgentConnections>>,
56}
57
58fn quoted(text: &str) -> String {
59 serde_json::to_string(text).unwrap_or_else(|_| format!("\"{text}\""))
60}
61
62fn router_error(message: impl Into<String>) -> ToolError {
63 ToolError::new(McpRouterToolError::new(message))
64}
65
66async fn stop_client(client: &McpClient) {
67 if let Err(error) = client.disconnect().await {
68 tracing::debug!("error=<{error}> | failed to stop MCP client");
69 }
70}
71
72fn stop_in_background(connections: IndexMap<String, Connection>) {
73 let Ok(runtime) = tokio::runtime::Handle::try_current() else {
74 return;
75 };
76 for (connection_id, connection) in connections {
77 tracing::debug!("connection_id=<{connection_id}> | closing MCP connection during garbage collection");
78 runtime.spawn(async move { stop_client(&connection.client).await });
79 }
80}
81
82impl Router {
83 fn with_agent<T>(&self, key: &AgentKey, f: impl FnOnce(&mut IndexMap<String, Connection>) -> T) -> T {
86 let mut agents = self.agents.lock().unwrap_or_else(PoisonError::into_inner);
87 let (live, dead): (Vec<_>, Vec<_>) = agents.drain(..).partition(|entry| entry.agent.strong_count() > 0);
88 *agents = live;
89 for entry in dead {
90 stop_in_background(entry.connections);
91 }
92 let index = match agents.iter().position(|entry| Weak::ptr_eq(&entry.agent, key)) {
93 Some(index) => index,
94 None => {
95 agents.push(AgentConnections {
96 agent: key.clone(),
97 connections: IndexMap::new(),
98 });
99 agents.len() - 1
100 }
101 };
102 f(&mut agents[index].connections)
103 }
104
105 fn client(&self, key: &AgentKey, connection_id: &str) -> std::result::Result<McpClient, McpRouterToolError> {
106 self.with_agent(key, |connections| {
107 connections
108 .get(connection_id)
109 .map(|connection| connection.client.clone())
110 })
111 .ok_or_else(|| McpRouterToolError::new(format!("No active connection for id {}", quoted(connection_id))))
112 }
113
114 fn list_connections(&self, key: &AgentKey) -> JsonValue {
115 let mut ids: Vec<String> = self.with_agent(key, |connections| connections.keys().cloned().collect());
116 ids.sort();
117 JsonValue::String(ids.join(", "))
118 }
119
120 async fn run(&self, input: McpRouterInput, context: &ToolContext) -> std::result::Result<JsonValue, ToolError> {
121 let key = context.agent().app_state().downgrade();
122 let connection_id = || {
123 input.connection_id.as_deref().ok_or_else(|| {
124 McpRouterToolError::new("`connection_id` is required for all commands except 'list_connections'")
125 })
126 };
127 match input.command {
128 McpRouterCommand::ListConnections => Ok(self.list_connections(&key)),
129 McpRouterCommand::Connect => {
130 let connection_id = connection_id()?;
131 let Some(server_name) = input.server_name.as_deref() else {
132 return Err(router_error("`server_name` is required for command='connect'"));
133 };
134 self.connect(&key, server_name, connection_id).await
135 }
136 McpRouterCommand::ListTools => {
137 let connection_id = connection_id()?;
138 let client = self.client(&key, connection_id)?;
139 let specs = self.list_and_cache(&key, connection_id, &client).await?;
140 Ok(serde_json::to_value(specs)?)
141 }
142 McpRouterCommand::CallTool => {
143 let connection_id = connection_id()?;
144 let client = self.client(&key, connection_id)?;
145 let Some(tool_name) = input.tool_name.as_deref() else {
146 return Err(router_error("`tool_name` is required for command='call_tool'"));
147 };
148 self.ensure_tool_listed(&key, connection_id, &client, tool_name).await?;
149 call_tool(&client, tool_name, input.arguments.clone().unwrap_or_default(), context).await
150 }
151 McpRouterCommand::Disconnect => Ok(self.disconnect(&key, connection_id()?).await),
152 }
153 }
154
155 async fn connect(
156 &self,
157 key: &AgentKey,
158 server_name: &str,
159 connection_id: &str,
160 ) -> std::result::Result<JsonValue, ToolError> {
161 let Some(config) = self.servers.get(server_name) else {
162 let permitted: Vec<&str> = self.servers.keys().map(String::as_str).collect();
163 return Err(router_error(format!(
164 "Server {} is not on the MCP server allowlist: {}",
165 quoted(server_name),
166 permitted.join(", ")
167 )));
168 };
169 let source = McpServersSource::Servers(vec![(server_name.to_owned(), config.clone())]);
170 let loaded =
171 McpClient::load_servers(source, McpClientOptions::default(), McpLoadServersOptions::default()).await?;
172 let Some(client) = loaded.into_iter().next() else {
173 return Err(router_error(format!(
174 "Server {} failed to initialise; check the server config",
175 quoted(server_name)
176 )));
177 };
178 if let Err(error) = client.connect(false).await {
179 stop_client(&client).await;
180 return Err(error.into());
181 }
182 if client.connection_state() == McpConnectionState::Failed {
183 stop_client(&client).await;
184 return Err(router_error(format!(
185 "Server {} failed to connect; check the server config",
186 quoted(server_name)
187 )));
188 }
189 let rejected = self.with_agent(key, |connections| {
190 if connections.len() >= self.max_connections {
191 let mut active: Vec<&str> = connections.keys().map(String::as_str).collect();
192 active.sort_unstable();
193 return Some(format!(
194 "Connection limit of {} reached. Disconnect one of the active connections before opening a new one. Active connection_ids: {}",
195 self.max_connections,
196 active.join(", ")
197 ));
198 }
199 if connections.contains_key(connection_id) {
200 return Some(format!(
201 "Connection {} already exists. Disconnect it first or use a different connection_id.",
202 quoted(connection_id)
203 ));
204 }
205 connections.insert(
206 connection_id.to_owned(),
207 Connection {
208 client: client.clone(),
209 listed_names: None,
210 },
211 );
212 None
213 });
214 if let Some(message) = rejected {
215 stop_client(&client).await;
216 return Err(router_error(message));
217 }
218 tracing::debug!("connection_id=<{connection_id}>, server_name=<{server_name}> | opened MCP connection");
219 Ok(JsonValue::String(format!(
220 "Successfully connected to {server_name} as {}",
221 quoted(connection_id)
222 )))
223 }
224
225 async fn list_and_cache(
226 &self,
227 key: &AgentKey,
228 connection_id: &str,
229 client: &McpClient,
230 ) -> Result<Vec<crate::types::ToolSpec>> {
231 let options = McpListToolsOptions {
232 prefix: Some(String::new()),
233 tool_filters: None,
234 };
235 let tools = client.list_tools_with(options).await?;
236 let specs: Vec<crate::types::ToolSpec> = tools.iter().map(Tool::tool_spec).collect();
237 let names: HashSet<String> = specs.iter().map(|spec| spec.name.clone()).collect();
238 self.with_agent(key, |connections| {
239 if let Some(connection) = connections.get_mut(connection_id) {
240 connection.listed_names = Some(names);
241 }
242 });
243 Ok(specs)
244 }
245
246 fn is_listed(&self, key: &AgentKey, connection_id: &str, tool_name: &str) -> bool {
247 self.with_agent(key, |connections| {
248 connections
249 .get(connection_id)
250 .and_then(|connection| connection.listed_names.as_ref())
251 .is_some_and(|names| names.contains(tool_name))
252 })
253 }
254
255 async fn ensure_tool_listed(
257 &self,
258 key: &AgentKey,
259 connection_id: &str,
260 client: &McpClient,
261 tool_name: &str,
262 ) -> std::result::Result<(), ToolError> {
263 if self.is_listed(key, connection_id, tool_name) {
264 return Ok(());
265 }
266 self.list_and_cache(key, connection_id, client).await?;
267 if self.is_listed(key, connection_id, tool_name) {
268 return Ok(());
269 }
270 Err(router_error(format!(
271 "Tool {} is not available on connection {}. Call list_tools to see the tools you can call.",
272 quoted(tool_name),
273 quoted(connection_id)
274 )))
275 }
276
277 async fn disconnect(&self, key: &AgentKey, connection_id: &str) -> JsonValue {
278 let removed = self.with_agent(key, |connections| connections.shift_remove(connection_id));
279 if let Some(connection) = removed {
280 stop_client(&connection.client).await;
281 }
282 JsonValue::String("Successfully disconnected".to_owned())
283 }
284}
285
286fn content_text(content: &ToolResultContent) -> String {
287 match content {
288 ToolResultContent::Text(block) => block.text.clone(),
289 other => serde_json::to_string(other).unwrap_or_default(),
290 }
291}
292
293async fn call_tool(
294 client: &McpClient,
295 tool_name: &str,
296 arguments: JsonObject,
297 context: &ToolContext,
298) -> std::result::Result<JsonValue, ToolError> {
299 let tool = McpTool::new(McpToolConfig {
300 name: tool_name.to_owned(),
301 description: String::new(),
302 input_schema: json!({"type": "object"}),
303 output_schema: None,
304 annotations: None,
305 client: client.clone(),
306 });
307 let options = McpCallToolOptions {
308 cancel_signal: Some(context.cancel_signal().clone()),
309 ..McpCallToolOptions::default()
310 };
311 let raw = client.call_tool(&tool, JsonValue::Object(arguments), options).await;
312 let result = tool_result(context.tool_use().tool_use_id.clone(), raw);
313 if result.status == ToolResultStatus::Error {
314 let text = result.content.iter().map(content_text).collect::<Vec<_>>().join("\n");
315 let message = if text.is_empty() {
316 "MCP tool returned an error".to_owned()
317 } else {
318 text
319 };
320 return Err(router_error(message));
321 }
322 Ok(serde_json::to_value(&result.content)?)
323}
324
325pub fn make_mcp_router(options: MakeMcpRouterOptions) -> Result<FunctionTool> {
354 if options.servers.is_empty() {
355 return Err(Error::other(
356 "`servers` must not be empty; the mcp_router tool requires at least one server",
357 ));
358 }
359 let max_connections = options.max_connections.unwrap_or(DEFAULT_MAX_CONNECTIONS);
360 if max_connections < 1 {
361 return Err(Error::other("`maxConnections` must be at least 1"));
362 }
363 let description = options.description.unwrap_or_else(|| {
364 let names: Vec<String> = options.servers.keys().map(|name| format!("'{name}'")).collect();
365 format!("{MCP_ROUTER_DESCRIPTION} Permitted server names: {}.", names.join(", "))
366 });
367 let router = Arc::new(Router {
368 servers: options.servers,
369 max_connections,
370 agents: Mutex::new(Vec::new()),
371 });
372 let name = options.name.unwrap_or_else(|| "mcp_router".to_owned());
373 Ok(FunctionTool::builder(name, description)
374 .input_schema_for::<McpRouterInput>()
375 .callback(move |input, context| {
376 let router = router.clone();
377 async move {
378 let input: McpRouterInput = serde_json::from_value(input)?;
379 router.run(input, &context).await
380 }
381 }))
382}
383
384#[cfg(test)]
385mod tests;