Skip to main content

mcp_server_core/
config.rs

1//! Configuration from environment variables.
2//!
3//! [`EnvReader`] reads variables and collects every problem in [`EnvReader::errors`], so a
4//! misconfigured server reports all of them at once instead of one per restart. Every variable
5//! may instead be given as a file: `NAME_FILE=/run/secrets/name` reads `NAME` from that file
6//! (without its trailing newline), for Docker and Kubernetes secrets. An empty value counts as
7//! unset.
8//!
9//! [`CoreConfig`] holds the settings every server shares:
10//!
11//! | Variable | Default | |
12//! |---|---|---|
13//! | `PUBLIC_URL` | required | External `https://` URL clients use, without a path. `http://` only for `localhost`, `127.0.0.1` or `[::1]`. |
14//! | `OAUTH_SIGNING_KEY` | required | At least 32 bytes. Signs every token; changing it signs everyone out. |
15//! | `MCP_AUTH_TOKEN` | none | A fixed bearer token for clients that cannot do OAuth: not when people sign in with their own credential or send it as a bearer token, and not shaped like a JWT (three dot-separated parts). |
16//! | `TRUSTED_PROXIES` | none | Comma-separated proxy IPs whose `X-Forwarded-For` is believed for rate limiting. |
17//! | `ALLOWED_ORIGINS` | none | Extra browser origins allowed to call the MCP endpoints. |
18//! | `BIND_ADDR` | `0.0.0.0:8443` | Listen address. |
19//! | `TLS_CERT_PATH`, `TLS_KEY_PATH` | none | PEM certificate chain and key, reloaded when they change. Without them a self-signed certificate is generated. |
20//! | `INSECURE_HTTP` | `false` | Serve plain HTTP, behind a TLS-terminating proxy. |
21//! | `LOG_LEVEL` | `info` | A `tracing` filter such as `info,my_crate=debug`. |
22//! | `LOG_FORMAT` | `json` | `json` or `pretty`. |
23//! | `DEBUG` | `false` | Debug logs for your crates and this one. |
24//! | `DEBUG_UNSAFE_LOG_CONTENT` | `false` | Also lets services log content (see [`crate::observability::content_logging_enabled`]). |
25//! | `METRICS_ADDR` | none | Serve Prometheus metrics at this address (feature `prometheus`). |
26//! | `OTEL_EXPORTER_OTLP_ENDPOINT` | none | Export traces over OTLP/HTTP (feature `otel`). Only this variable turns export on; the other `OTEL_*` variables then apply. |
27
28use crate::oauth::OAuthSettings;
29use crate::observability::{LogFormat, ObservabilityConfig};
30use crate::tls::TlsMode;
31use secrecy::SecretString;
32use std::net::{IpAddr, SocketAddr};
33use std::path::PathBuf;
34use std::str::FromStr;
35
36/// Reads configuration variables through a lookup function, collecting errors.
37///
38/// ```
39/// use mcp_server_core::config::EnvReader;
40///
41/// let mut env = EnvReader::new(|name: &str| (name == "PORT").then(|| "x".to_string()));
42/// let port: u16 = env.parse("PORT", 8080);
43/// let key = env.required("API_KEY");
44/// assert_eq!((port, key), (8080, None));
45/// assert_eq!(env.errors, ["PORT has an invalid value", "API_KEY is required"]);
46/// ```
47pub struct EnvReader<F: Fn(&str) -> Option<String>> {
48    get: F,
49    /// Every problem found so far, as messages for the operator. They never contain secret values.
50    pub errors: Vec<String>,
51}
52
53impl EnvReader<fn(&str) -> Option<String>> {
54    /// Reads the process environment.
55    pub fn from_process() -> Self {
56        EnvReader::new(|k: &str| std::env::var(k).ok())
57    }
58}
59
60impl<F: Fn(&str) -> Option<String>> EnvReader<F> {
61    /// Reads variables with `get`, e.g. from a map in tests.
62    pub fn new(get: F) -> Self {
63        Self {
64            get,
65            errors: Vec::new(),
66        }
67    }
68
69    fn raw(&self, name: &str) -> Option<String> {
70        (self.get)(name).filter(|v| !v.is_empty())
71    }
72
73    /// The value of `name`, or of the file named by `NAME_FILE`; `None` when neither is set.
74    pub fn optional(&mut self, name: &str) -> Option<String> {
75        if let Some(v) = self.raw(name) {
76            return Some(v);
77        }
78        let file_var = format!("{name}_FILE");
79        let path = self.raw(&file_var)?;
80        match std::fs::read_to_string(&path) {
81            Ok(s) => Some(s.trim_end_matches(['\r', '\n']).to_string()).filter(|v| !v.is_empty()),
82            Err(e) => {
83                self.errors
84                    .push(format!("{file_var}: cannot read {path}: {e}"));
85                None
86            }
87        }
88    }
89
90    /// Like [`optional`](Self::optional), recording "`NAME` is required" when unset.
91    pub fn required(&mut self, name: &str) -> Option<String> {
92        let errors_before = self.errors.len();
93        let value = self.optional(name);
94        if value.is_none() && self.errors.len() == errors_before {
95            self.errors.push(format!("{name} is required"));
96        }
97        value
98    }
99
100    /// [`optional`](Self::optional) as a secret that never prints.
101    pub fn secret_optional(&mut self, name: &str) -> Option<SecretString> {
102        self.optional(name).map(SecretString::from)
103    }
104
105    /// [`required`](Self::required) as a secret that never prints.
106    pub fn secret_required(&mut self, name: &str) -> Option<SecretString> {
107        self.required(name).map(SecretString::from)
108    }
109
110    /// A boolean: `1`, `true`, `yes`, `on` or `0`, `false`, `no`, `off`, in any case.
111    pub fn bool(&mut self, name: &str, default: bool) -> bool {
112        let Some(v) = self.optional(name) else {
113            return default;
114        };
115        match v.to_ascii_lowercase().as_str() {
116            "1" | "true" | "yes" | "on" => true,
117            "0" | "false" | "no" | "off" => false,
118            _ => {
119                self.errors
120                    .push(format!("{name} must be true or false, got \"{v}\""));
121                default
122            }
123        }
124    }
125
126    /// Parses `name`, or returns `default` when unset or invalid (recording the error).
127    pub fn parse<T: FromStr>(&mut self, name: &str, default: T) -> T {
128        self.parse_optional(name).unwrap_or(default)
129    }
130
131    /// Parses `name` when set, recording an error when it does not parse.
132    pub fn parse_optional<T: FromStr>(&mut self, name: &str) -> Option<T> {
133        let v = self.optional(name)?;
134        match v.parse() {
135            Ok(t) => Some(t),
136            Err(_) => {
137                self.errors.push(format!("{name} has an invalid value"));
138                None
139            }
140        }
141    }
142
143    /// A comma-separated list, trimmed, without empty entries.
144    pub fn list(&mut self, name: &str) -> Vec<String> {
145        self.optional(name)
146            .map(|v| {
147                v.split(',')
148                    .map(str::trim)
149                    .filter(|s| !s.is_empty())
150                    .map(String::from)
151                    .collect()
152            })
153            .unwrap_or_default()
154    }
155}
156
157/// The settings every server shares; see the [module documentation](self) for the variables.
158#[derive(Debug, Clone)]
159pub struct CoreConfig {
160    /// `PUBLIC_URL` without a trailing slash.
161    pub public_url: String,
162    /// The host of `PUBLIC_URL`, without IPv6 brackets.
163    pub public_host: String,
164    /// The authorization server's settings.
165    pub oauth: OAuthSettings,
166    /// `ALLOWED_ORIGINS`.
167    pub allowed_origins: Vec<String>,
168    /// `BIND_ADDR`.
169    pub bind_addr: SocketAddr,
170    /// How to serve: plain HTTP, certificate files or self-signed.
171    pub tls: TlsMode,
172    /// Logging, metrics and tracing.
173    pub observability: ObservabilityConfig,
174}
175
176fn parse_public_url(raw: &str) -> Result<(String, String), String> {
177    let url = url::Url::parse(raw).map_err(|_| "PUBLIC_URL must be an https URL".to_string())?;
178    let host = url
179        .host_str()
180        .ok_or_else(|| "PUBLIC_URL must be an https URL".to_string())?
181        .to_string();
182    let loopback = matches!(host.as_str(), "localhost" | "127.0.0.1" | "[::1]");
183    if url.scheme() != "https" && !(url.scheme() == "http" && loopback) {
184        return Err("PUBLIC_URL must be an https URL (http is only allowed for localhost)".into());
185    }
186    if url.query().is_some() || url.fragment().is_some() {
187        return Err("PUBLIC_URL must not contain a query or fragment".into());
188    }
189    if url.path() != "/" {
190        return Err("PUBLIC_URL must not contain a path".into());
191    }
192    let host = host
193        .trim_start_matches('[')
194        .trim_end_matches(']')
195        .to_string();
196    Ok((url.as_str().trim_end_matches('/').to_string(), host))
197}
198
199impl CoreConfig {
200    /// Reads the shared settings. `service_name` names the server in traces; `crate_target` is
201    /// the tracing target prefix of your crates, raised to debug by `DEBUG`. Errors go to
202    /// `env.errors`; `None` when there were any.
203    pub fn from_env<F: Fn(&str) -> Option<String>>(
204        env: &mut EnvReader<F>,
205        service_name: &str,
206        crate_target: &str,
207    ) -> Option<Self> {
208        let errors_before = env.errors.len();
209
210        let public = env
211            .required("PUBLIC_URL")
212            .and_then(|raw| match parse_public_url(&raw) {
213                Ok(v) => Some(v),
214                Err(e) => {
215                    env.errors.push(e);
216                    None
217                }
218            });
219        let signing_key = env.secret_required("OAUTH_SIGNING_KEY");
220        if let Some(k) = &signing_key {
221            use secrecy::ExposeSecret;
222            if k.expose_secret().len() < 32 {
223                env.errors
224                    .push("OAUTH_SIGNING_KEY must be at least 32 bytes".into());
225            }
226        }
227        let static_token = env.secret_optional("MCP_AUTH_TOKEN");
228        let mut trusted_proxies = Vec::new();
229        for raw in env.list("TRUSTED_PROXIES") {
230            match raw.parse::<IpAddr>() {
231                Ok(ip) => trusted_proxies.push(ip),
232                Err(_) => env.errors.push(format!(
233                    "TRUSTED_PROXIES contains an invalid IP address: {raw}"
234                )),
235            }
236        }
237        let allowed_origins = env.list("ALLOWED_ORIGINS");
238        let bind_addr = env.parse("BIND_ADDR", SocketAddr::from(([0, 0, 0, 0], 8443)));
239        let insecure = env.bool("INSECURE_HTTP", false);
240        let cert = env.optional("TLS_CERT_PATH").map(PathBuf::from);
241        let key = env.optional("TLS_KEY_PATH").map(PathBuf::from);
242        let log_level = env.optional("LOG_LEVEL").unwrap_or_else(|| "info".into());
243        let log_format = env.parse("LOG_FORMAT", LogFormat::Json);
244        let debug = env.bool("DEBUG", false);
245        let unsafe_content = env.bool("DEBUG_UNSAFE_LOG_CONTENT", false);
246        let metrics_addr = env.parse_optional::<SocketAddr>("METRICS_ADDR");
247        let otlp_enabled = env.optional("OTEL_EXPORTER_OTLP_ENDPOINT").is_some();
248
249        let (public_url, public_host) = public.unwrap_or_default();
250        let tls = match TlsMode::select(insecure, cert, key, &public_host) {
251            Ok(t) => Some(t),
252            Err(e) => {
253                env.errors.push(e);
254                None
255            }
256        };
257        if env.errors.len() != errors_before {
258            return None;
259        }
260        Some(CoreConfig {
261            oauth: OAuthSettings {
262                public_url: public_url.clone(),
263                signing_key: signing_key?,
264                trusted_proxies,
265                static_token,
266            },
267            public_url,
268            public_host,
269            allowed_origins,
270            bind_addr,
271            tls: tls?,
272            observability: ObservabilityConfig {
273                service_name: service_name.to_string(),
274                crate_target: crate_target.to_string(),
275                log_level,
276                log_format,
277                debug,
278                unsafe_content,
279                otlp_enabled,
280                metrics_addr,
281            },
282        })
283    }
284
285    /// External URL of a service mounted at `/<service>`.
286    pub fn service_url(&self, service: &str) -> String {
287        format!("{}/{service}", self.public_url)
288    }
289}
290
291#[cfg(test)]
292mod tests {
293    use super::*;
294    use secrecy::ExposeSecret;
295    use std::collections::HashMap;
296
297    fn reader(pairs: &[(&str, &str)]) -> EnvReader<impl Fn(&str) -> Option<String> + use<>> {
298        let map: HashMap<String, String> = pairs
299            .iter()
300            .map(|(k, v)| (k.to_string(), v.to_string()))
301            .collect();
302        EnvReader::new(move |k: &str| map.get(k).cloned())
303    }
304
305    #[test]
306    fn required_reports_missing() {
307        let mut env = reader(&[]);
308        assert_eq!(env.required("FOO"), None);
309        assert_eq!(env.errors, vec!["FOO is required".to_string()]);
310    }
311
312    #[test]
313    fn empty_values_count_as_unset() {
314        let mut env = reader(&[("FOO", "")]);
315        assert_eq!(env.optional("FOO"), None);
316    }
317
318    #[test]
319    fn file_variant_is_read_and_trailing_newline_trimmed() {
320        let dir = tempfile::tempdir().unwrap();
321        let path = dir.path().join("secret");
322        std::fs::write(&path, "s3cret\n").unwrap();
323        let p = path.to_str().unwrap().to_string();
324        let mut env = reader(&[("PASS_FILE", p.as_str())]);
325        assert_eq!(
326            env.secret_required("PASS").unwrap().expose_secret(),
327            "s3cret"
328        );
329        assert!(env.errors.is_empty());
330    }
331
332    #[test]
333    fn direct_value_wins_over_file() {
334        let mut env = reader(&[("PASS", "direct"), ("PASS_FILE", "/nonexistent")]);
335        assert_eq!(env.required("PASS").as_deref(), Some("direct"));
336    }
337
338    #[test]
339    fn unreadable_file_is_an_error_without_leaking_contents() {
340        let mut env = reader(&[("PASS_FILE", "/definitely/not/here")]);
341        assert_eq!(env.required("PASS"), None);
342        assert_eq!(env.errors.len(), 1);
343        assert!(env.errors[0].starts_with("PASS_FILE: cannot read /definitely/not/here"));
344    }
345
346    #[test]
347    fn bool_parsing() {
348        let mut env = reader(&[("A", "true"), ("B", "0"), ("C", "yes"), ("D", "maybe")]);
349        assert!(env.bool("A", false));
350        assert!(!env.bool("B", true));
351        assert!(env.bool("C", false));
352        assert!(env.bool("MISSING", true));
353        assert!(!env.bool("D", false));
354        assert_eq!(
355            env.errors,
356            vec!["D must be true or false, got \"maybe\"".to_string()]
357        );
358    }
359
360    #[test]
361    fn parse_with_default_and_error() {
362        let mut env = reader(&[("N", "42"), ("BAD", "x")]);
363        assert_eq!(env.parse("N", 1u32), 42);
364        assert_eq!(env.parse("MISSING", 7u32), 7);
365        assert_eq!(env.parse("BAD", 3u32), 3);
366        assert_eq!(env.errors, vec!["BAD has an invalid value".to_string()]);
367    }
368
369    #[test]
370    fn list_splits_and_trims() {
371        let mut env = reader(&[("L", " a, b ,,c ")]);
372        assert_eq!(env.list("L"), vec!["a", "b", "c"]);
373    }
374
375    fn core_env(extra: &[(&str, &str)]) -> Vec<(String, String)> {
376        let mut v: Vec<(String, String)> = [
377            ("PUBLIC_URL", "https://mcp.example.com/"),
378            ("OAUTH_SIGNING_KEY", "0123456789abcdef0123456789abcdef"),
379        ]
380        .iter()
381        .map(|(a, b)| (a.to_string(), b.to_string()))
382        .collect();
383        v.extend(extra.iter().map(|(a, b)| (a.to_string(), b.to_string())));
384        v
385    }
386
387    fn core(pairs: Vec<(String, String)>) -> (Option<CoreConfig>, Vec<String>) {
388        let map: HashMap<String, String> = pairs.into_iter().collect();
389        let mut env = EnvReader::new(move |k: &str| map.get(k).cloned());
390        let c = CoreConfig::from_env(&mut env, "mcp-example", "mcp_example");
391        (c, env.errors)
392    }
393
394    #[test]
395    fn core_config_defaults() {
396        let (c, errors) = core(core_env(&[]));
397        assert!(errors.is_empty(), "{errors:?}");
398        let c = c.unwrap();
399        assert_eq!(c.public_url, "https://mcp.example.com");
400        assert_eq!(c.public_host, "mcp.example.com");
401        assert_eq!(c.service_url("weather"), "https://mcp.example.com/weather");
402        assert_eq!(c.bind_addr.to_string(), "0.0.0.0:8443");
403        assert!(matches!(c.tls, crate::tls::TlsMode::SelfSigned { .. }));
404        assert!(matches!(
405            c.observability.log_format,
406            crate::observability::LogFormat::Json
407        ));
408        assert!(!c.observability.otlp_enabled);
409    }
410
411    #[test]
412    fn core_config_collects_all_errors() {
413        let (c, errors) = core(vec![
414            ("PUBLIC_URL".into(), "ftp://x".into()),
415            ("OAUTH_SIGNING_KEY".into(), "short".into()),
416            ("TLS_CERT_PATH".into(), "/c".into()),
417            ("LOG_FORMAT".into(), "xml".into()),
418        ]);
419        assert!(c.is_none());
420        let joined = errors.join("\n");
421        assert!(
422            joined.contains("PUBLIC_URL must be an https URL"),
423            "{joined}"
424        );
425        assert!(
426            joined.contains("OAUTH_SIGNING_KEY must be at least 32 bytes"),
427            "{joined}"
428        );
429        assert!(
430            joined.contains("TLS_CERT_PATH and TLS_KEY_PATH must be set together"),
431            "{joined}"
432        );
433        assert!(
434            joined.contains("LOG_FORMAT has an invalid value"),
435            "{joined}"
436        );
437        assert!(!joined.contains("short"), "secret value leaked: {joined}");
438    }
439
440    #[test]
441    fn http_public_url_allowed_only_for_localhost() {
442        let (c, errors) = core(core_env(&[("PUBLIC_URL", "http://localhost:8443")]));
443        assert!(errors.is_empty(), "{errors:?}");
444        assert_eq!(c.unwrap().public_url, "http://localhost:8443");
445        let (_, errors) = core(core_env(&[("PUBLIC_URL", "http://mcp.example.com")]));
446        assert!(!errors.is_empty());
447    }
448
449    #[test]
450    fn trusted_proxies_default_empty_and_parse() {
451        let (c, _) = core(core_env(&[]));
452        assert!(c.unwrap().oauth.trusted_proxies.is_empty());
453        let (c, errors) = core(core_env(&[("TRUSTED_PROXIES", "10.0.0.1, ::1")]));
454        assert!(errors.is_empty(), "{errors:?}");
455        assert_eq!(
456            c.unwrap().oauth.trusted_proxies,
457            vec![
458                "10.0.0.1".parse::<std::net::IpAddr>().unwrap(),
459                "::1".parse().unwrap()
460            ]
461        );
462        let (c, errors) = core(core_env(&[("TRUSTED_PROXIES", "10.0.0.1,nope")]));
463        assert!(c.is_none());
464        assert!(errors.join("\n").contains("TRUSTED_PROXIES"), "{errors:?}");
465    }
466
467    #[test]
468    fn public_url_with_path_is_rejected() {
469        let (c, errors) = core(core_env(&[("PUBLIC_URL", "https://mcp.example.com/sub")]));
470        assert!(c.is_none());
471        assert!(
472            errors
473                .join("\n")
474                .contains("PUBLIC_URL must not contain a path"),
475            "{errors:?}"
476        );
477    }
478
479    #[test]
480    fn otlp_enabled_when_endpoint_set() {
481        let (c, _) = core(core_env(&[(
482            "OTEL_EXPORTER_OTLP_ENDPOINT",
483            "http://collector:4318",
484        )]));
485        assert!(c.unwrap().observability.otlp_enabled);
486    }
487}