Skip to main content

graphrt_mcp/
config.rs

1//! MCP server configuration.
2//!
3//! Parsing is strict: unknown keys (typically typos such as `alowed_tools`) are
4//! rejected, because a silently ignored allow-list would expose every tool of a
5//! server. The camelCase spellings common in MCP client configs
6//! (`allowedTools`, `timeoutMs`, `passEnv`, `inheritEnv`, `showStderr`,
7//! `bearerToken`) are accepted as aliases.
8
9use indexmap::IndexMap;
10use serde::{Deserialize, Serialize};
11
12/// Default per-call timeout.
13pub const DEFAULT_TIMEOUT_MS: u64 = 30_000;
14
15/// Host variables passed to stdio servers when `inherit_env` is false.
16/// Most launchers (`npx`, `uvx`, `docker`) need these to start at all.
17pub const DEFAULT_PASS_ENV: &[&str] = &["PATH", "HOME", "LANG", "TMPDIR", "SYSTEMROOT", "USERPROFILE", "APPDATA"];
18
19/// One MCP server.
20///
21/// ```json
22/// { "name": "fs", "command": "npx", "args": ["-y", "@modelcontextprotocol/server-filesystem", "/data"] }
23/// { "name": "remote", "url": "https://mcp.example.com/mcp", "bearer_token": "..." }
24/// ```
25///
26/// Exactly one of `command` (stdio) or `url` (Streamable HTTP) must be present, and
27/// transport-specific keys must match the chosen transport.
28#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
29#[serde(try_from = "RawServer")]
30pub struct McpServerConfig {
31    /// Provider name used to reference the server's tools (`<name>` and `mcp:<name>`).
32    /// Optional when the config comes from a named map ([`McpServers`]).
33    pub name: String,
34    #[serde(flatten)]
35    pub transport: McpTransport,
36    /// Timeout for each request (connect handshake, list, call), in milliseconds.
37    /// Defaults to [`DEFAULT_TIMEOUT_MS`].
38    pub timeout_ms: u64,
39    /// When set, only these tools are listed and callable.
40    #[serde(skip_serializing_if = "Option::is_none")]
41    pub allowed_tools: Option<Vec<String>>,
42}
43
44/// How to reach an MCP server. Chosen by the presence of `command` or `url`.
45#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
46#[serde(untagged)]
47pub enum McpTransport {
48    /// Spawn a child process speaking MCP over stdin/stdout.
49    Stdio(StdioConfig),
50    /// Connect to a Streamable HTTP endpoint.
51    Http(HttpConfig),
52}
53
54/// Child-process server.
55#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
56#[serde(deny_unknown_fields)]
57pub struct StdioConfig {
58    pub command: String,
59    #[serde(default)]
60    pub args: Vec<String>,
61    /// Explicit environment variables for the child.
62    #[serde(default)]
63    pub env: IndexMap<String, String>,
64    /// Names of host variables copied into the child's environment
65    /// (in addition to [`DEFAULT_PASS_ENV`]).
66    #[serde(default, alias = "passEnv")]
67    pub pass_env: Vec<String>,
68    /// Inherit the full host environment. Off by default so host secrets are
69    /// not leaked to third-party servers.
70    #[serde(default, alias = "inheritEnv")]
71    pub inherit_env: bool,
72    #[serde(default)]
73    pub cwd: Option<String>,
74    /// Forward the server's stderr to this process's stderr (default: discarded).
75    #[serde(default, alias = "showStderr")]
76    pub show_stderr: bool,
77}
78
79/// Streamable HTTP server.
80#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
81#[serde(deny_unknown_fields)]
82pub struct HttpConfig {
83    pub url: String,
84    /// Extra headers sent with every request.
85    #[serde(default)]
86    pub headers: IndexMap<String, String>,
87    /// Bearer token for the `Authorization` header (without the `Bearer ` prefix).
88    #[serde(default, alias = "bearerToken")]
89    pub bearer_token: Option<String>,
90}
91
92/// Every key a server entry may contain, used to validate configs strictly.
93#[derive(Deserialize)]
94#[serde(deny_unknown_fields)]
95struct RawServer {
96    #[serde(default)]
97    name: String,
98    /// Optional explicit transport kind, as written by many MCP clients.
99    #[serde(default, rename = "type", alias = "transport")]
100    kind: Option<String>,
101    #[serde(default, alias = "timeoutMs")]
102    timeout_ms: Option<u64>,
103    #[serde(default, alias = "allowedTools")]
104    allowed_tools: Option<Vec<String>>,
105    // stdio
106    #[serde(default)]
107    command: Option<String>,
108    #[serde(default)]
109    args: Option<Vec<String>>,
110    #[serde(default)]
111    env: Option<IndexMap<String, String>>,
112    #[serde(default, alias = "passEnv")]
113    pass_env: Option<Vec<String>>,
114    #[serde(default, alias = "inheritEnv")]
115    inherit_env: Option<bool>,
116    #[serde(default)]
117    cwd: Option<String>,
118    #[serde(default, alias = "showStderr")]
119    show_stderr: Option<bool>,
120    // http
121    #[serde(default)]
122    url: Option<String>,
123    #[serde(default)]
124    headers: Option<IndexMap<String, String>>,
125    #[serde(default, alias = "bearerToken")]
126    bearer_token: Option<String>,
127}
128
129impl TryFrom<RawServer> for McpServerConfig {
130    type Error = String;
131
132    fn try_from(raw: RawServer) -> Result<Self, String> {
133        let label = if raw.name.is_empty() { "MCP server".to_owned() } else { format!("MCP server `{}`", raw.name) };
134        let transport = match (raw.command, raw.url) {
135            (Some(_), Some(_)) => {
136                return Err(format!("{label}: set either `command` (stdio) or `url` (http), not both"));
137            }
138            (None, None) => return Err(format!("{label}: needs `command` (stdio) or `url` (http)")),
139            (Some(command), None) => {
140                if let Some(kind) = raw.kind.as_deref().filter(|k| !k.eq_ignore_ascii_case("stdio")) {
141                    return Err(format!("{label}: `type: {kind}` does not match a stdio `command`"));
142                }
143                let http_keys = [("headers", raw.headers.is_some()), ("bearer_token", raw.bearer_token.is_some())];
144                reject_foreign_keys(&label, "stdio", &http_keys)?;
145                McpTransport::Stdio(StdioConfig {
146                    command,
147                    args: raw.args.unwrap_or_default(),
148                    env: raw.env.unwrap_or_default(),
149                    pass_env: raw.pass_env.unwrap_or_default(),
150                    inherit_env: raw.inherit_env.unwrap_or(false),
151                    cwd: raw.cwd,
152                    show_stderr: raw.show_stderr.unwrap_or(false),
153                })
154            }
155            (None, Some(url)) => {
156                let http_kinds = ["http", "streamable-http", "streamable_http", "streamablehttp"];
157                if let Some(kind) =
158                    raw.kind.as_deref().filter(|k| !http_kinds.iter().any(|h| h.eq_ignore_ascii_case(k)))
159                {
160                    return Err(format!("{label}: `type: {kind}` does not match an http `url`"));
161                }
162                let stdio_keys = [
163                    ("args", raw.args.is_some()),
164                    ("env", raw.env.is_some()),
165                    ("pass_env", raw.pass_env.is_some()),
166                    ("inherit_env", raw.inherit_env.is_some()),
167                    ("cwd", raw.cwd.is_some()),
168                    ("show_stderr", raw.show_stderr.is_some()),
169                ];
170                reject_foreign_keys(&label, "http", &stdio_keys)?;
171                McpTransport::Http(HttpConfig {
172                    url,
173                    headers: raw.headers.unwrap_or_default(),
174                    bearer_token: raw.bearer_token,
175                })
176            }
177        };
178        Ok(McpServerConfig {
179            name: raw.name,
180            transport,
181            timeout_ms: raw.timeout_ms.unwrap_or(DEFAULT_TIMEOUT_MS),
182            allowed_tools: raw.allowed_tools,
183        })
184    }
185}
186
187fn reject_foreign_keys(label: &str, transport: &str, keys: &[(&str, bool)]) -> Result<(), String> {
188    match keys.iter().find(|(_, present)| *present) {
189        Some((key, _)) => Err(format!("{label}: `{key}` does not apply to {transport} servers")),
190        None => Ok(()),
191    }
192}
193
194/// A named collection of servers, e.g. a config file:
195///
196/// ```json
197/// { "mcpServers": { "fs": { "command": "npx", "args": ["..."] } } }
198/// ```
199#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
200#[serde(deny_unknown_fields)]
201pub struct McpServers {
202    #[serde(alias = "mcpServers", alias = "mcp_servers")]
203    pub servers: IndexMap<String, McpServerConfig>,
204}
205
206impl McpServers {
207    /// Server configs with `name` filled from the map keys.
208    pub fn into_configs(self) -> Vec<McpServerConfig> {
209        self.servers
210            .into_iter()
211            .map(|(key, mut cfg)| {
212                if cfg.name.is_empty() {
213                    cfg.name = key;
214                }
215                cfg
216            })
217            .collect()
218    }
219}
220
221impl McpServerConfig {
222    /// Whether `tool` passes the allow-list.
223    pub fn allows(&self, tool: &str) -> bool {
224        self.allowed_tools.as_ref().is_none_or(|list| list.iter().any(|t| t == tool))
225    }
226}
227
228#[cfg(test)]
229mod tests {
230    use super::*;
231
232    fn parse(value: serde_json::Value) -> Result<McpServerConfig, String> {
233        serde_json::from_value::<McpServerConfig>(value).map_err(|e| e.to_string())
234    }
235
236    #[test]
237    fn parses_stdio_and_http() {
238        let stdio = parse(serde_json::json!({
239            "name": "fs", "command": "npx", "args": ["-y", "srv"], "env": {"A": "1"}, "pass_env": ["GITHUB_TOKEN"]
240        }))
241        .unwrap();
242        match &stdio.transport {
243            McpTransport::Stdio(s) => {
244                assert_eq!(s.command, "npx");
245                assert_eq!(s.args, ["-y", "srv"]);
246                assert!(!s.inherit_env);
247                assert_eq!(s.pass_env, ["GITHUB_TOKEN"]);
248            }
249            other => panic!("unexpected {other:?}"),
250        }
251        assert_eq!(stdio.timeout_ms, DEFAULT_TIMEOUT_MS);
252
253        let http = parse(serde_json::json!({
254            "name": "r", "url": "https://x/mcp", "bearer_token": "t", "timeout_ms": 5,
255            "allowed_tools": ["a"]
256        }))
257        .unwrap();
258        assert!(matches!(&http.transport, McpTransport::Http(h) if h.bearer_token.as_deref() == Some("t")));
259        assert!(http.allows("a"));
260        assert!(!http.allows("b"));
261        assert!(stdio.allows("anything"));
262    }
263
264    #[test]
265    fn accepts_camel_case_aliases() {
266        let cfg = parse(serde_json::json!({
267            "name": "fs", "type": "stdio", "command": "srv", "allowedTools": ["read"], "timeoutMs": 7,
268            "passEnv": ["X"], "inheritEnv": true, "showStderr": true
269        }))
270        .unwrap();
271        assert_eq!(cfg.allowed_tools, Some(vec!["read".to_owned()]));
272        assert_eq!(cfg.timeout_ms, 7);
273        assert!(!cfg.allows("write"));
274        match &cfg.transport {
275            McpTransport::Stdio(s) => assert!(s.inherit_env && s.show_stderr && s.pass_env == ["X"]),
276            other => panic!("unexpected {other:?}"),
277        }
278        let http =
279            parse(serde_json::json!({"url": "https://x", "type": "streamable-http", "bearerToken": "t"})).unwrap();
280        assert!(matches!(&http.transport, McpTransport::Http(h) if h.bearer_token.as_deref() == Some("t")));
281    }
282
283    #[test]
284    fn rejects_typos_and_mixed_transports() {
285        let typo = parse(serde_json::json!({"command": "srv", "alowed_tools": ["a"]})).unwrap_err();
286        assert!(typo.contains("alowed_tools"), "{typo}");
287        let both = parse(serde_json::json!({"command": "srv", "url": "https://x"})).unwrap_err();
288        assert!(both.contains("not both"), "{both}");
289        let foreign = parse(serde_json::json!({"url": "https://x", "args": ["a"]})).unwrap_err();
290        assert!(foreign.contains("`args`"), "{foreign}");
291        let kind = parse(serde_json::json!({"command": "srv", "type": "http"})).unwrap_err();
292        assert!(kind.contains("type"), "{kind}");
293    }
294
295    #[test]
296    fn rejects_config_without_transport() {
297        assert!(parse(serde_json::json!({"name": "x"})).is_err());
298    }
299
300    #[test]
301    fn serialization_round_trips() {
302        let cfg = parse(serde_json::json!({"name": "fs", "command": "srv", "allowedTools": ["a"]})).unwrap();
303        let text = serde_json::to_value(&cfg).unwrap();
304        assert_eq!(parse(text).unwrap(), cfg);
305    }
306
307    #[test]
308    fn named_map_fills_names() {
309        let servers: McpServers = serde_json::from_value(serde_json::json!({
310            "mcpServers": {"fs": {"command": "srv"}, "web": {"name": "custom", "url": "http://h"}}
311        }))
312        .unwrap();
313        let cfgs = servers.into_configs();
314        assert_eq!(cfgs[0].name, "fs");
315        assert_eq!(cfgs[1].name, "custom");
316        assert!(serde_json::from_value::<McpServers>(serde_json::json!({"mcpServer": {}})).is_err());
317    }
318}