Skip to main content

strands/mcp/
config.rs

1//! [`McpClient::load_servers`]: MCP clients from an `mcp.json`-style server map.
2
3use std::collections::BTreeMap;
4use std::path::{Path, PathBuf};
5use std::sync::LazyLock;
6
7use indexmap::IndexMap;
8use regex::Regex;
9use serde::Deserialize;
10
11use super::client::{McpClient, McpClientConfig, McpClientOptions};
12use super::error::McpError;
13use super::filters::{McpToolFilters, McpToolMatcher};
14use super::http::McpClientCredentials;
15use super::transport::{McpTransport, StdioServerParameters, default_environment};
16use crate::error::{Error, Result};
17use crate::types::{JsonObject, JsonValue};
18
19static PLACEHOLDER: LazyLock<Option<Regex>> =
20    LazyLock::new(|| Regex::new(r"\$\{(?:env:)?([A-Za-z_][A-Za-z0-9_]*)\}").ok());
21
22/// Tool filters in a config file (`SerializableMcpToolFilters`): each pattern is a regex
23/// matched from the start of the server-side tool name.
24#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, bon::Builder)]
25pub struct SerializableMcpToolFilters {
26    /// When present, only tools whose names match one of these patterns are exposed.
27    #[serde(default)]
28    pub allowed: Option<Vec<String>>,
29    /// Tools whose names match one of these patterns are excluded, even when also allowed.
30    #[serde(default)]
31    pub rejected: Option<Vec<String>>,
32}
33
34/// The transport of a config entry (`'stdio' | 'sse' | 'streamable-http'`).
35#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
36#[non_exhaustive]
37pub enum McpServerTransport {
38    /// A child process (`stdio`).
39    #[serde(rename = "stdio")]
40    Stdio,
41    /// The legacy HTTP+SSE protocol (`sse`).
42    #[serde(rename = "sse")]
43    Sse,
44    /// Streamable HTTP (`streamable-http`).
45    #[serde(rename = "streamable-http")]
46    StreamableHttp,
47}
48
49const TRANSPORT_NAMES: [&str; 3] = ["stdio", "sse", "streamable-http"];
50
51/// One server entry of a config file or map (`McpServerConfig`).
52///
53/// Give `command` (stdio) or `url` (streamable HTTP or SSE). Without `transport` it is detected
54/// from the fields present. String fields support `${VAR}` and `${env:VAR}` placeholders.
55#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize, bon::Builder)]
56#[serde(rename_all = "camelCase")]
57#[builder(on(String, into))]
58pub struct McpServerConfig {
59    /// The command to spawn (stdio).
60    pub command: Option<String>,
61    /// Its arguments.
62    pub args: Option<Vec<String>>,
63    /// Variables for the child process, over the default environment.
64    pub env: Option<BTreeMap<String, String>>,
65    /// The working directory of the child process.
66    pub cwd: Option<String>,
67    /// The server URL (streamable HTTP or SSE).
68    pub url: Option<String>,
69    /// Headers sent with every request.
70    pub headers: Option<BTreeMap<String, String>>,
71    /// The transport; detected from `command` or `url` when absent.
72    pub transport: Option<McpServerTransport>,
73    /// OAuth client credentials (streamable HTTP only).
74    pub auth: Option<McpClientCredentials>,
75    /// Prefix for agent-facing tool names.
76    pub prefix: Option<String>,
77    /// Filters applied to tool names.
78    pub tool_filters: Option<SerializableMcpToolFilters>,
79    /// Skips this server.
80    #[serde(default)]
81    #[builder(default)]
82    pub disabled: bool,
83    /// Skips config and connection failures and overlong prefixed names with warnings.
84    pub continue_on_error: Option<bool>,
85}
86
87/// How [`McpClient::load_servers`] turns entries into clients (`McpLoadServersOptions`).
88#[derive(Debug, Clone, Default, bon::Builder)]
89pub struct McpLoadServersOptions {
90    /// Servers without an explicit `prefix` use their config key as the tool name prefix, with
91    /// characters outside `[A-Za-z0-9_-]` replaced by `_`. Takes precedence over a default
92    /// `prefix`; a server opts out with `prefix: ""`.
93    #[builder(default)]
94    pub prefix_with_server_name: bool,
95}
96
97/// Where [`McpClient::load_servers`] reads servers from: a JSON file (flat or under
98/// `mcpServers`, `~/` expanded), a typed map, or a JSON object of entries.
99#[derive(Debug, Clone)]
100#[non_exhaustive]
101pub enum McpServersSource {
102    /// A JSON config file.
103    Path(PathBuf),
104    /// Server entries by name, in order; a repeated name replaces the earlier entry in its place.
105    Servers(Vec<(String, McpServerConfig)>),
106    /// Server entries by name, as JSON.
107    Json(JsonObject),
108}
109
110impl From<&str> for McpServersSource {
111    fn from(path: &str) -> Self {
112        Self::Path(PathBuf::from(path))
113    }
114}
115
116impl From<String> for McpServersSource {
117    fn from(path: String) -> Self {
118        Self::Path(PathBuf::from(path))
119    }
120}
121
122impl From<PathBuf> for McpServersSource {
123    fn from(path: PathBuf) -> Self {
124        Self::Path(path)
125    }
126}
127
128impl From<&Path> for McpServersSource {
129    fn from(path: &Path) -> Self {
130        Self::Path(path.to_path_buf())
131    }
132}
133
134impl From<Vec<(String, McpServerConfig)>> for McpServersSource {
135    fn from(servers: Vec<(String, McpServerConfig)>) -> Self {
136        Self::Servers(servers)
137    }
138}
139
140impl From<BTreeMap<String, McpServerConfig>> for McpServersSource {
141    fn from(servers: BTreeMap<String, McpServerConfig>) -> Self {
142        Self::Servers(servers.into_iter().collect())
143    }
144}
145
146impl<const N: usize> From<[(&str, McpServerConfig); N]> for McpServersSource {
147    fn from(servers: [(&str, McpServerConfig); N]) -> Self {
148        Self::Servers(
149            servers
150                .into_iter()
151                .map(|(name, config)| (name.to_owned(), config))
152                .collect(),
153        )
154    }
155}
156
157impl From<JsonObject> for McpServersSource {
158    fn from(servers: JsonObject) -> Self {
159        Self::Json(servers)
160    }
161}
162
163/// Process state the loader reads; tests substitute it.
164pub(crate) struct LoadEnv<'a> {
165    pub(crate) var: &'a (dyn Fn(&str) -> Option<String> + Sync),
166    pub(crate) home: Option<PathBuf>,
167}
168
169impl LoadEnv<'static> {
170    fn process() -> Self {
171        Self {
172            var: &|key| std::env::var(key).ok(),
173            home: std::env::home_dir(),
174        }
175    }
176}
177
178/// A transport a config entry resolved to.
179#[derive(Debug, Clone, PartialEq)]
180pub(crate) enum ResolvedTransport {
181    Stdio(StdioServerParameters),
182    StreamableHttp {
183        url: String,
184        headers: Option<BTreeMap<String, String>>,
185        auth: Option<McpClientCredentials>,
186    },
187    Sse {
188        url: String,
189        headers: Option<BTreeMap<String, String>>,
190    },
191}
192
193pub(crate) struct ResolvedServer {
194    pub(crate) transport: ResolvedTransport,
195    pub(crate) options: McpClientOptions,
196}
197
198impl ResolvedServer {
199    fn into_client_config(self) -> Result<McpClientConfig> {
200        let mut config = McpClientConfig {
201            options: self.options,
202            ..McpClientConfig::default()
203        };
204        match self.transport {
205            ResolvedTransport::Stdio(params) => config.transport = Some(McpTransport::stdio(params)),
206            ResolvedTransport::StreamableHttp { url, headers, auth } => {
207                config.url = Some(url);
208                config.headers = headers;
209                config.auth = auth;
210            }
211            ResolvedTransport::Sse { url, headers } => {
212                config.transport = Some(McpTransport::sse(&url, headers)?);
213            }
214        }
215        Ok(config)
216    }
217}
218
219fn interpolate(value: &str, env: &LoadEnv<'_>) -> Result<String> {
220    let Some(placeholder) = PLACEHOLDER.as_ref() else {
221        return Ok(value.to_owned());
222    };
223    let mut output = String::with_capacity(value.len());
224    let mut last = 0;
225    for captures in placeholder.captures_iter(value) {
226        let (Some(whole), Some(key)) = (captures.get(0), captures.get(1)) else {
227            continue;
228        };
229        let key = key.as_str();
230        let resolved =
231            (env.var)(key).ok_or_else(|| McpError::other(format!("Environment variable \"{key}\" is not set")))?;
232        output.push_str(&value[last..whole.start()]);
233        output.push_str(&resolved);
234        last = whole.end();
235    }
236    output.push_str(&value[last..]);
237    Ok(output)
238}
239
240fn interpolate_all(values: &[String], env: &LoadEnv<'_>) -> Result<Vec<String>> {
241    values.iter().map(|value| interpolate(value, env)).collect()
242}
243
244fn interpolate_record(record: &BTreeMap<String, String>, env: &LoadEnv<'_>) -> Result<BTreeMap<String, String>> {
245    record
246        .iter()
247        .map(|(key, value)| Ok((key.clone(), interpolate(value, env)?)))
248        .collect()
249}
250
251fn non_empty(value: Option<&String>) -> Option<&String> {
252    value.filter(|value| !value.is_empty())
253}
254
255fn build_stdio(server: &McpServerConfig, env: &LoadEnv<'_>) -> Result<ResolvedTransport> {
256    let Some(command) = non_empty(server.command.as_ref()) else {
257        return Err(McpError::other("Stdio transport requires \"command\" field").into());
258    };
259    let mut params = StdioServerParameters::new(interpolate(command, env)?, Vec::<String>::new());
260    if let Some(args) = &server.args {
261        params.args = interpolate_all(args, env)?;
262    }
263    if let Some(vars) = &server.env {
264        let mut merged = default_environment();
265        merged.extend(interpolate_record(vars, env)?);
266        params.env = Some(merged);
267    }
268    if let Some(cwd) = non_empty(server.cwd.as_ref()) {
269        params.cwd = Some(PathBuf::from(interpolate(cwd, env)?));
270    }
271    Ok(ResolvedTransport::Stdio(params))
272}
273
274fn build_http(server: &McpServerConfig, env: &LoadEnv<'_>) -> Result<ResolvedTransport> {
275    let Some(url) = non_empty(server.url.as_ref()) else {
276        return Err(McpError::other("Streamable HTTP transport requires \"url\" field").into());
277    };
278    let headers = server
279        .headers
280        .as_ref()
281        .map(|headers| interpolate_record(headers, env))
282        .transpose()?;
283    let auth = server
284        .auth
285        .as_ref()
286        .map(|auth| -> Result<McpClientCredentials> {
287            Ok(McpClientCredentials {
288                client_id: interpolate(&auth.client_id, env)?,
289                client_secret: interpolate(&auth.client_secret, env)?,
290                scopes: auth
291                    .scopes
292                    .as_ref()
293                    .map(|scopes| interpolate_all(scopes, env))
294                    .transpose()?,
295                allow_private_addresses: auth.allow_private_addresses,
296            })
297        })
298        .transpose()?;
299    Ok(ResolvedTransport::StreamableHttp {
300        url: interpolate(url, env)?,
301        headers,
302        auth,
303    })
304}
305
306fn build_sse(server: &McpServerConfig, env: &LoadEnv<'_>) -> Result<ResolvedTransport> {
307    let Some(url) = non_empty(server.url.as_ref()) else {
308        return Err(McpError::other("SSE transport requires \"url\" field").into());
309    };
310    if server.auth.is_some() {
311        return Err(McpError::other(
312            "SSE transport does not support auth — use streamable-http or provide a pre-configured transport",
313        )
314        .into());
315    }
316    let headers = server
317        .headers
318        .as_ref()
319        .map(|headers| interpolate_record(headers, env))
320        .transpose()?;
321    let url = interpolate(url, env)?;
322    McpTransport::sse(&url, headers.clone())?;
323    Ok(ResolvedTransport::Sse { url, headers })
324}
325
326fn build_transport(server: &McpServerConfig, env: &LoadEnv<'_>) -> Result<ResolvedTransport> {
327    let command = non_empty(server.command.as_ref());
328    let url = non_empty(server.url.as_ref());
329    if command.is_some() && url.is_some() && server.transport.is_none() {
330        return Err(McpError::other(
331            "Server config has both \"command\" and \"url\" — set \"transport\" explicitly or remove one",
332        )
333        .into());
334    }
335    let detected = match (command, url) {
336        (Some(_), _) => Some(McpServerTransport::Stdio),
337        (None, Some(_)) => Some(McpServerTransport::StreamableHttp),
338        (None, None) => None,
339    };
340    match server.transport.or(detected) {
341        Some(McpServerTransport::Stdio) => build_stdio(server, env),
342        Some(McpServerTransport::StreamableHttp) => build_http(server, env),
343        Some(McpServerTransport::Sse) => build_sse(server, env),
344        None => Err(McpError::other("Server config must include either \"command\" (stdio) or \"url\" (http)").into()),
345    }
346}
347
348/// `name.replace(/[^A-Za-z0-9_-]/g, '_')`.
349pub(crate) fn sanitize_prefix(name: &str) -> String {
350    name.chars()
351        .map(|c| {
352            if c.is_ascii_alphanumeric() || c == '_' || c == '-' {
353                c
354            } else {
355                '_'
356            }
357        })
358        .collect()
359}
360
361fn compile_matchers(name: &str, key: &str, patterns: &[String], env: &LoadEnv<'_>) -> Result<Vec<McpToolMatcher>> {
362    interpolate_all(patterns, env)?
363        .into_iter()
364        .map(|pattern| {
365            Regex::new(&pattern).map(McpToolMatcher::Regex).map_err(|error| {
366                Error::from(McpError::other(format!(
367                    "Server \"{name}\": invalid regex in toolFilters.{key}: \"{pattern}\": {error}"
368                )))
369            })
370        })
371        .collect()
372}
373
374fn compile_filters(name: &str, filters: &SerializableMcpToolFilters, env: &LoadEnv<'_>) -> Result<McpToolFilters> {
375    Ok(McpToolFilters {
376        allowed: filters
377            .allowed
378            .as_ref()
379            .map(|patterns| compile_matchers(name, "allowed", patterns, env))
380            .transpose()?,
381        rejected: filters
382            .rejected
383            .as_ref()
384            .map(|patterns| compile_matchers(name, "rejected", patterns, env))
385            .transpose()?,
386    })
387}
388
389fn base_options(
390    name: &str,
391    server: &McpServerConfig,
392    defaults: &McpClientOptions,
393    options: &McpLoadServersOptions,
394    env: &LoadEnv<'_>,
395) -> Result<McpClientOptions> {
396    let mut resolved = defaults.clone();
397    resolved.application_name = Some(defaults.application_name.clone().unwrap_or_else(|| name.to_owned()));
398    if options.prefix_with_server_name {
399        resolved.prefix = Some(sanitize_prefix(name));
400    }
401    if let Some(continue_on_error) = server.continue_on_error {
402        resolved.continue_on_error = continue_on_error;
403    }
404    if let Some(prefix) = &server.prefix {
405        resolved.prefix = Some(interpolate(prefix, env)?);
406    }
407    if let Some(filters) = &server.tool_filters {
408        resolved.tool_filters = Some(compile_filters(name, filters, env)?);
409    }
410    Ok(resolved)
411}
412
413fn resolve_server(
414    name: &str,
415    server: &McpServerConfig,
416    defaults: &McpClientOptions,
417    options: &McpLoadServersOptions,
418    env: &LoadEnv<'_>,
419) -> Result<ResolvedServer> {
420    let transport = build_transport(server, env)?;
421    let options = base_options(name, server, defaults, options, env)?;
422    Ok(ResolvedServer { transport, options })
423}
424
425fn js_type_of(value: &JsonValue) -> &'static str {
426    match value {
427        JsonValue::Array(_) => "array",
428        JsonValue::Bool(_) => "boolean",
429        JsonValue::Number(_) => "number",
430        JsonValue::String(_) => "string",
431        JsonValue::Null | JsonValue::Object(_) => "object",
432    }
433}
434
435fn entry_config(name: &str, entry: &JsonValue) -> Result<std::result::Result<McpServerConfig, Error>> {
436    if !entry.is_object() {
437        return Err(McpError::other(format!(
438            "Server \"{name}\" must be an object, got {}",
439            js_type_of(entry)
440        ))
441        .into());
442    }
443    if let Some(JsonValue::String(kind)) = entry.get("transport")
444        && !TRANSPORT_NAMES.contains(&kind.as_str())
445    {
446        return Ok(Err(
447            McpError::other(format!("Unsupported transport type: {kind}")).into()
448        ));
449    }
450    Ok(McpServerConfig::deserialize(entry).map_err(Error::from))
451}
452
453struct Entry {
454    name: String,
455    config: std::result::Result<McpServerConfig, Error>,
456    continue_on_error: Option<bool>,
457}
458
459fn json_entries(servers: JsonObject) -> Result<Vec<Entry>> {
460    servers
461        .into_iter()
462        .filter(|(_, entry)| !entry.get("disabled").is_some_and(is_truthy))
463        .map(|(name, entry)| {
464            let config = entry_config(&name, &entry)?;
465            let continue_on_error = entry.get("continueOnError").and_then(JsonValue::as_bool);
466            Ok(Entry {
467                name,
468                config,
469                continue_on_error,
470            })
471        })
472        .collect()
473}
474
475fn is_truthy(value: &JsonValue) -> bool {
476    match value {
477        JsonValue::Null => false,
478        JsonValue::Bool(value) => *value,
479        JsonValue::Number(number) => number.as_f64().is_some_and(|n| n != 0.0 && !n.is_nan()),
480        JsonValue::String(text) => !text.is_empty(),
481        JsonValue::Array(_) | JsonValue::Object(_) => true,
482    }
483}
484
485async fn read_servers(path: &Path, env: &LoadEnv<'_>) -> Result<JsonObject> {
486    let expanded = match (path.to_str().and_then(|text| text.strip_prefix("~/")), &env.home) {
487        (Some(rest), Some(home)) => home.join(rest),
488        _ => path.to_path_buf(),
489    };
490    let text = tokio::fs::read_to_string(&expanded).await?;
491    let mut parsed: JsonValue = serde_json::from_str(&text)?;
492    let servers = match parsed.get_mut("mcpServers") {
493        Some(servers) if !servers.is_null() => servers.take(),
494        _ => parsed,
495    };
496    match servers {
497        JsonValue::Object(servers) => Ok(servers),
498        _ => Err(McpError::other(
499            "MCP config must be a JSON object mapping server names to configs, e.g. { \"my-server\": { \"command\": \"node\" } }",
500        )
501        .into()),
502    }
503}
504
505/// Resolves every enabled entry. A non-object entry always fails;
506/// another failure skips the server with a warning under its `continue_on_error`.
507pub(crate) async fn resolve_server_configs(
508    source: McpServersSource,
509    defaults: &McpClientOptions,
510    options: &McpLoadServersOptions,
511    env: &LoadEnv<'_>,
512) -> Result<Vec<ResolvedServer>> {
513    let entries = match source {
514        McpServersSource::Path(path) => json_entries(read_servers(&path, env).await?)?,
515        McpServersSource::Json(servers) => json_entries(servers)?,
516        McpServersSource::Servers(servers) => servers
517            .into_iter()
518            .collect::<IndexMap<_, _>>()
519            .into_iter()
520            .map(|(name, config)| Entry {
521                continue_on_error: config.continue_on_error,
522                name,
523                config: Ok(config),
524            })
525            .collect(),
526    };
527    let mut resolved = Vec::new();
528    for entry in entries {
529        let continue_on_error = entry.continue_on_error.unwrap_or(defaults.continue_on_error);
530        let result = entry.config.and_then(|config| {
531            if config.disabled {
532                return Ok(None);
533            }
534            resolve_server(&entry.name, &config, defaults, options, env).map(Some)
535        });
536        match result {
537            Ok(Some(server)) => resolved.push(server),
538            Ok(None) => {}
539            Err(error) if continue_on_error => skip_server(&entry.name, &error),
540            Err(error) => return Err(error),
541        }
542    }
543    Ok(resolved)
544}
545
546fn skip_server(name: &str, error: &Error) {
547    tracing::warn!("server=<{name}>, error=<{error}> | MCP server config failed, skipping (continueOnError)");
548}
549
550pub(crate) fn clients_from(resolved: Vec<ResolvedServer>) -> Result<Vec<McpClient>> {
551    let mut clients = Vec::new();
552    for server in resolved {
553        let continue_on_error = server.options.continue_on_error;
554        let name = server.options.application_name.clone().unwrap_or_default();
555        match server.into_client_config().and_then(McpClient::new) {
556            Ok(client) => clients.push(client),
557            Err(error) if continue_on_error => {
558                tracing::warn!(
559                    "server=<{name}>, error=<{error}> | MCP client config failed, skipping (continueOnError)"
560                );
561            }
562            Err(error) => return Err(error),
563        }
564    }
565    Ok(clients)
566}
567
568impl McpClient {
569    /// Creates one client per enabled server of an `mcp.json`-style config.
570    ///
571    /// `defaults` apply to every client unless the entry overrides them; each client is named
572    /// after its config key unless `defaults` names the application.
573    ///
574    /// ```
575    /// use strands::mcp::{McpClient, McpClientOptions, McpLoadServersOptions, McpServerConfig};
576    ///
577    /// # tokio::runtime::Builder::new_current_thread().enable_all().build().unwrap().block_on(async {
578    /// let clients = McpClient::load_servers(
579    ///     [("docs", McpServerConfig::builder().url("https://example.com/mcp").build())],
580    ///     McpClientOptions::default(),
581    ///     McpLoadServersOptions::default(),
582    /// )
583    /// .await?;
584    /// assert_eq!(clients[0].client_name(), "docs");
585    /// # Ok::<(), strands::Error>(())
586    /// # });
587    /// ```
588    ///
589    /// # Errors
590    ///
591    /// An unreadable or malformed file, a non-object entry, or an entry that fails to resolve
592    /// (missing fields, an unset variable, an invalid regex or URL) unless `continue_on_error`
593    /// applies to it.
594    pub async fn load_servers(
595        source: impl Into<McpServersSource>,
596        defaults: McpClientOptions,
597        options: McpLoadServersOptions,
598    ) -> Result<Vec<Self>> {
599        let resolved = resolve_server_configs(source.into(), &defaults, &options, &LoadEnv::process()).await?;
600        clients_from(resolved)
601    }
602}