Skip to main content

mcp_server_core/
app.rs

1//! [`Server`]: a whole MCP server binary from a list of services.
2//!
3//! ```no_run
4//! # use mcp_server_core::service::{Service, ServiceEnv};
5//! # use std::sync::Arc;
6//! # fn weather(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> { None }
7//! # fn tides(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> { None }
8//! use mcp_server_core::app::{Server, SignIn};
9//!
10//! #[tokio::main]
11//! async fn main() -> std::process::ExitCode {
12//!     Server::new("mcp-sea", env!("CARGO_PKG_VERSION"))
13//!         .env_prefix("SEA")
14//!         .service("weather", weather)
15//!         .service("tides", tides)
16//!         .sign_in(SignIn::OwnerPassword)
17//!         .docs_url("https://example.com/mcp-sea")
18//!         .main()
19//!         .await
20//! }
21//! ```
22//!
23//! [`Server::main`] handles `--version`, `--help` and `--healthcheck`, reads the configuration
24//! (reporting every error at once), starts logging, mounts each service at `/<name>` and serves.
25//!
26//! Besides the [core variables](crate::config), a server reads, with `SEA` standing for its
27//! [prefix](Server::env_prefix):
28//!
29//! | Variable | Default | |
30//! |---|---|---|
31//! | `SEA_SERVICES` | every service | Comma-separated services to run. Unselected services read no configuration. |
32//! | `SEA_COMBINED` | `true` | Also serve every service's tools together at `/mcp`, as `<service>_<tool>`. |
33//! | `SEA_READ_ONLY` | none | Comma-separated services (or `all`) whose write tools are hidden and refused. |
34//! | `AUDIT_LOG_PATH` | none | Append an audit line (JSON) for every write tool call to this file. |
35//! | `OAUTH_ADMIN_PASSWORD` | required with [`SignIn::OwnerPassword`] | The owner's password, at least 12 characters. |
36
37use crate::combined::{COMBINED, Combined, DynHandler, prefixed_name};
38use crate::config::{CoreConfig, EnvReader};
39use crate::credential::{CredentialVerifier, PasswordVerifier};
40use crate::oauth::AuthState;
41use crate::policy::{AUDIT_TARGET, AuditLog, Guarded, ToolPolicy};
42use crate::server::build_app;
43use crate::service::{HttpSettings, Service, ServiceContext, ServiceEnv, ServiceFactory, icons};
44use crate::{install_crypto_provider, observability, shutdown_signal, tls};
45use rmcp::model::Implementation;
46use secrecy::ExposeSecret;
47use std::net::SocketAddr;
48use std::path::PathBuf;
49use std::process::ExitCode;
50use std::sync::Arc;
51
52/// Shortest `OAUTH_ADMIN_PASSWORD` accepted.
53pub const MIN_ADMIN_PASSWORD_CHARS: usize = 12;
54/// `OAUTH_ADMIN_PASSWORD`s shorter than this get a warning at startup.
55pub const RECOMMENDED_ADMIN_PASSWORD_CHARS: usize = 15;
56/// `MCP_AUTH_TOKEN`s shorter than this get a warning at startup.
57pub const RECOMMENDED_STATIC_TOKEN_CHARS: usize = 32;
58
59/// How people sign in, and what their tokens carry.
60///
61/// Deliberately small. For single sign-on, MFA or many named users, put an identity-aware
62/// gateway (such as Cloudflare Access or oauth2-proxy) in front of `/authorize`; see
63/// SECURITY.md.
64#[derive(Clone, Copy)]
65#[non_exhaustive]
66pub enum SignIn {
67    /// One person, the owner, signs in with `OAUTH_ADMIN_PASSWORD`. Tools act with the server's
68    /// own upstream configuration (say, an account's app password in the environment).
69    /// `MCP_AUTH_TOKEN` may be set as well, for clients that cannot do OAuth.
70    OwnerPassword,
71    /// Each person signs in with their own credential for the upstream service, checked by the
72    /// [`CredentialVerifier`] of the enabled service that has one
73    /// ([`Service::credential_verifier`]; more than one is a configuration error, since each
74    /// service's tools would receive a credential meant for another upstream). Tools find it as a
75    /// [`Credential`](crate::credential::Credential) in the request extensions, so one server can
76    /// serve many people. Clients may also send the credential itself as their bearer token.
77    ///
78    /// A verifier with an [`upstream`](CredentialVerifier::upstream) provider, such as an
79    /// [`UpstreamVerifier`](crate::upstream::UpstreamVerifier), has people sign in at the
80    /// provider instead, and the credential it grants is carried the same way; see
81    /// [`crate::upstream`].
82    ServiceCredential,
83    /// A verifier built from the environment by your function, which records any problems in
84    /// `env.errors`.
85    Custom(fn(&mut ServiceEnv) -> Option<Arc<dyn CredentialVerifier>>),
86}
87
88impl std::fmt::Debug for SignIn {
89    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
90        f.write_str(match self {
91            SignIn::OwnerPassword => "OwnerPassword",
92            SignIn::ServiceCredential => "ServiceCredential",
93            SignIn::Custom(_) => "Custom(..)",
94        })
95    }
96}
97
98/// The read-only services and the audit log, applied to every service's tools.
99#[derive(Clone)]
100pub struct Safety {
101    /// Services whose write tools are hidden and refused.
102    pub read_only: Vec<&'static str>,
103    /// Where write tool calls are recorded.
104    pub audit: Arc<AuditLog>,
105}
106
107impl Safety {
108    /// Whether `service` is read-only.
109    pub fn is_read_only(&self, service: &str) -> bool {
110        self.read_only.contains(&service)
111    }
112
113    /// The policy for `service` on its own endpoint `/<service>`.
114    pub fn policy(&self, service: &str) -> ToolPolicy {
115        ToolPolicy {
116            service: service.to_string(),
117            endpoint: format!("/{service}"),
118            read_only: self.is_read_only(service),
119            audit: self.audit.clone(),
120        }
121    }
122}
123
124/// A server's configuration, read and checked, with its services built.
125#[non_exhaustive]
126pub struct Loaded {
127    /// The core settings.
128    pub core: CoreConfig,
129    /// The selected services, in registration order or in the order `<PREFIX>_SERVICES` names
130    /// them.
131    pub services: Vec<Arc<dyn Service>>,
132    /// Read-only services and the audit log.
133    pub safety: Safety,
134    /// Whether every service's tools are also served together at `/mcp`.
135    pub combined: bool,
136    /// Who may sign in.
137    pub verifier: Arc<dyn CredentialVerifier>,
138    /// Settings that work but are weak, logged at startup.
139    pub warnings: Vec<String>,
140}
141
142/// Builds an MCP server binary from services. See the [module documentation](self).
143pub struct Server {
144    name: &'static str,
145    version: &'static str,
146    crate_target: String,
147    env_prefix: String,
148    services: Vec<(&'static str, ServiceFactory)>,
149    sign_in: SignIn,
150    icon: Option<(&'static [u8], &'static str)>,
151    docs_url: Option<&'static str>,
152    wrap: Option<fn(axum::Router) -> axum::Router>,
153}
154
155/// Why `name` cannot be a service name, if it cannot.
156fn invalid_service_name(name: &str) -> Option<&'static str> {
157    if name == COMBINED {
158        return Some("is reserved for the combined endpoint");
159    }
160    let ok = !name.is_empty()
161        && name
162            .bytes()
163            .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-');
164    (!ok).then_some("must be lowercase letters, digits and '-'")
165}
166
167impl Server {
168    /// A server called `name` (used in logs, traces and the combined endpoint's `serverInfo`) at
169    /// `version`. Its environment prefix defaults to `MCP` and its tracing target to `name` with
170    /// `-` replaced by `_`; people sign in with the owner's password unless you choose otherwise.
171    pub fn new(name: &'static str, version: &'static str) -> Self {
172        Server {
173            name,
174            version,
175            crate_target: name.replace('-', "_"),
176            env_prefix: "MCP".into(),
177            services: Vec::new(),
178            sign_in: SignIn::OwnerPassword,
179            icon: None,
180            docs_url: None,
181            wrap: None,
182        }
183    }
184
185    /// The prefix of this server's own variables: `<PREFIX>_SERVICES`, `<PREFIX>_COMBINED` and
186    /// `<PREFIX>_READ_ONLY`.
187    pub fn env_prefix(mut self, prefix: &str) -> Self {
188        self.env_prefix = prefix.trim_end_matches('_').to_ascii_uppercase();
189        self
190    }
191
192    /// The tracing target prefix of your crates, which `DEBUG` raises to debug. With
193    /// `mcp_weather`, `mcp_weather_api::client` is covered too.
194    pub fn crate_target(mut self, target: &str) -> Self {
195        self.crate_target = target.to_string();
196        self
197    }
198
199    /// Registers a service, mounted at `/<name>`. Services are mounted, and their tools listed on
200    /// `/mcp`, in registration order, or in the order `<PREFIX>_SERVICES` names them when it is
201    /// set.
202    ///
203    /// # Panics
204    ///
205    /// If `name` is not lowercase letters, digits and `-`, is `mcp`, or is already registered.
206    pub fn service(mut self, name: &'static str, factory: ServiceFactory) -> Self {
207        if let Some(why) = invalid_service_name(name) {
208            panic!("service name {name:?} {why}");
209        }
210        assert!(
211            self.services.iter().all(|(n, _)| *n != name),
212            "service {name:?} is registered twice"
213        );
214        self.services.push((name, factory));
215        self
216    }
217
218    /// Registers several services; see [`service`](Self::service).
219    pub fn services(self, services: &[(&'static str, ServiceFactory)]) -> Self {
220        services
221            .iter()
222            .fold(self, |s, (name, factory)| s.service(name, *factory))
223    }
224
225    /// How people sign in. Defaults to [`SignIn::OwnerPassword`].
226    pub fn sign_in(mut self, sign_in: SignIn) -> Self {
227        self.sign_in = sign_in;
228        self
229    }
230
231    /// The server's icon: a 128x128 PNG, served as `/favicon.ico` and in the combined endpoint's
232    /// `serverInfo`, and an SVG.
233    pub fn icon(mut self, png: &'static [u8], svg: &'static str) -> Self {
234        self.icon = Some((png, svg));
235        self
236    }
237
238    /// Wraps the whole application in your own layers, for example a request rate limiter or extra
239    /// routes. They sit outside every built-in layer except the security headers. Routes added
240    /// here, like `/favicon.ico`, are outside the body limit, the request metrics and the request
241    /// span:
242    ///
243    /// ```
244    /// # use mcp_server_core::app::Server;
245    /// use mcp_server_core::axum::{Router, routing::get};
246    ///
247    /// fn extras(app: Router) -> Router {
248    ///     app.route("/version", get(|| async { env!("CARGO_PKG_VERSION") }))
249    /// }
250    ///
251    /// let server = Server::new("mcp-example", "1.0.0").wrap_router(extras);
252    /// ```
253    pub fn wrap_router(mut self, wrap: fn(axum::Router) -> axum::Router) -> Self {
254        self.wrap = Some(wrap);
255        self
256    }
257
258    /// Where the configuration is documented, for `--help`.
259    pub fn docs_url(mut self, url: &'static str) -> Self {
260        self.docs_url = Some(url);
261        self
262    }
263
264    /// The server's name.
265    pub fn name(&self) -> &'static str {
266        self.name
267    }
268
269    /// The server's version.
270    pub fn version(&self) -> &'static str {
271        self.version
272    }
273
274    /// The registered services' names, in order.
275    pub fn registered(&self) -> Vec<&'static str> {
276        self.services.iter().map(|(n, _)| *n).collect()
277    }
278
279    /// `<PREFIX>_<suffix>`.
280    pub fn var(&self, suffix: &str) -> String {
281        format!("{}_{suffix}", self.env_prefix)
282    }
283
284    fn known(&self) -> String {
285        self.registered().join(", ")
286    }
287
288    /// Resolves `<PREFIX>_SERVICES` (comma list, unset means every registered service).
289    fn select(&self, raw: Option<&str>) -> Result<Vec<(&'static str, ServiceFactory)>, String> {
290        let Some(raw) = raw else {
291            return Ok(self.services.clone());
292        };
293        let var = self.var("SERVICES");
294        let mut selected: Vec<(&'static str, ServiceFactory)> = Vec::new();
295        for name in raw.split(',').map(str::trim).filter(|s| !s.is_empty()) {
296            let Some(entry) = self.services.iter().find(|(n, _)| *n == name) else {
297                return Err(format!(
298                    "{var} contains an unknown service: {name} (known: {})",
299                    self.known()
300                ));
301            };
302            if !selected.iter().any(|(n, _)| *n == name) {
303                selected.push(*entry);
304            }
305        }
306        if selected.is_empty() {
307            return Err(format!(
308                "{var} must name at least one service (known: {})",
309                self.known()
310            ));
311        }
312        Ok(selected)
313    }
314
315    /// Resolves `<PREFIX>_READ_ONLY` (comma list or `all`, unset or empty means none). Names
316    /// that are registered but not selected are accepted and have no effect.
317    fn read_only(&self, raw: Option<&str>) -> Result<Vec<&'static str>, String> {
318        let names = raw
319            .unwrap_or_default()
320            .split(',')
321            .map(str::trim)
322            .filter(|s| !s.is_empty());
323        let mut out: Vec<&'static str> = Vec::new();
324        for name in names {
325            if name == "all" {
326                return Ok(self.registered());
327            }
328            let Some((known, _)) = self.services.iter().find(|(n, _)| *n == name) else {
329                return Err(format!(
330                    "{} contains an unknown service: {name} (known: all, {})",
331                    self.var("READ_ONLY"),
332                    self.known()
333                ));
334            };
335            if !out.contains(known) {
336                out.push(known);
337            }
338        }
339        Ok(out)
340    }
341
342    /// Reads the configuration and builds every selected service. Every problem is recorded in
343    /// `env.errors` (each once); `None` means the server cannot start. Unselected services never
344    /// read their configuration.
345    pub fn load(&self, env: &mut ServiceEnv) -> Option<Loaded> {
346        let core = CoreConfig::from_env(env, self.name, &self.crate_target);
347        let mut verifier: Option<Arc<dyn CredentialVerifier>> = match self.sign_in {
348            SignIn::OwnerPassword => owner_password(env),
349            SignIn::ServiceCredential => None,
350            SignIn::Custom(build) => build(env),
351        };
352        let selected = match self.select(env.optional(&self.var("SERVICES")).as_deref()) {
353            Ok(s) => s,
354            Err(e) => {
355                env.errors.push(e);
356                Vec::new()
357            }
358        };
359        let read_only = match self.read_only(env.optional(&self.var("READ_ONLY")).as_deref()) {
360            Ok(r) => r,
361            Err(e) => {
362                env.errors.push(e);
363                Vec::new()
364            }
365        };
366        let audit_path = env.optional("AUDIT_LOG_PATH").map(PathBuf::from);
367        let combined = env.bool(&self.var("COMBINED"), true);
368        let mut services: Vec<Arc<dyn Service>> = Vec::new();
369        for (name, factory) in selected {
370            if let Some(s) = factory(env) {
371                if s.name() != name {
372                    env.errors.push(format!(
373                        "the service registered as {name} is named {}",
374                        s.name()
375                    ));
376                }
377                services.push(s);
378            }
379        }
380        if matches!(self.sign_in, SignIn::ServiceCredential) {
381            let defining: Vec<(&str, Arc<dyn CredentialVerifier>)> = services
382                .iter()
383                .filter_map(|s| s.credential_verifier().map(|v| (s.name(), v)))
384                .collect();
385            match defining.as_slice() {
386                [] if !services.is_empty() => env
387                    .errors
388                    .push("no enabled service defines how people sign in".to_string()),
389                [] => {}
390                [(_, v)] => verifier = Some(v.clone()),
391                several => env.errors.push(format!(
392                    "more than one enabled service defines how people sign in ({}): enable one of them",
393                    several.iter().map(|(n, _)| *n).collect::<Vec<_>>().join(", ")
394                )),
395            }
396        }
397        if verifier.as_ref().is_some_and(|v| v.upstream().is_some())
398            && services
399                .iter()
400                .any(|s| crate::upstream::CALLBACK_PATH.strip_prefix('/') == Some(s.name()))
401        {
402            env.errors.push(format!(
403                "a service cannot be named {} when people sign in through an upstream provider: the provider sends them back there",
404                crate::upstream::CALLBACK_PATH.trim_start_matches('/')
405            ));
406        }
407        let mut warnings = Vec::new();
408        if let Some(token) = core.as_ref().and_then(|c| c.oauth.static_token.as_ref()) {
409            let token = token.expose_secret();
410            let problems: Vec<String> = verifier
411                .as_ref()
412                .and_then(|v| crate::oauth::static_token_verifier_problem(v.as_ref()))
413                .into_iter()
414                .chain(crate::oauth::static_token_shape_problem(token))
415                .collect();
416            if !problems.is_empty() {
417                env.errors.extend(problems);
418            } else if token.chars().count() < RECOMMENDED_STATIC_TOKEN_CHARS {
419                warnings.push(format!(
420                    "MCP_AUTH_TOKEN is shorter than {RECOMMENDED_STATIC_TOKEN_CHARS} characters: use a long random value"
421                ));
422            }
423        }
424        if matches!(self.sign_in, SignIn::OwnerPassword)
425            && let Some(p) = env.optional("OAUTH_ADMIN_PASSWORD")
426            && p.chars().count() < RECOMMENDED_ADMIN_PASSWORD_CHARS
427            && p.chars().count() >= MIN_ADMIN_PASSWORD_CHARS
428        {
429            warnings.push(format!(
430                "OAUTH_ADMIN_PASSWORD is shorter than {RECOMMENDED_ADMIN_PASSWORD_CHARS} characters: a longer passphrase is much harder to guess"
431            ));
432        }
433        // Services may share variables: report each error once.
434        let mut seen = std::collections::HashSet::new();
435        env.errors.retain(|e| seen.insert(e.clone()));
436        if !env.errors.is_empty() {
437            return None;
438        }
439        Some(Loaded {
440            core: core?,
441            services,
442            safety: Safety {
443                read_only,
444                audit: Arc::new(AuditLog::new(audit_path)),
445            },
446            combined,
447            verifier: verifier?,
448            warnings,
449        })
450    }
451
452    /// The combined endpoint's `serverInfo`: this server's name, version and icon.
453    fn combined_info(&self) -> Implementation {
454        let info = Implementation::new(self.name, self.version);
455        match self.icon {
456            Some((png, svg)) => info.with_icons(icons(png, svg)),
457            None => info,
458        }
459    }
460
461    /// The combined endpoint: every service's tools as `<service>_<tool>`, each service under its
462    /// own read-only rule and audit log, recorded with endpoint `/mcp`.
463    fn combined_router(&self, loaded: &Loaded, ctx: &ServiceContext) -> axum::Router {
464        let parts: Vec<(Arc<dyn Service>, ToolPolicy)> = loaded
465            .services
466            .iter()
467            .map(|s| {
468                let policy = ToolPolicy {
469                    endpoint: format!("/{COMBINED}"),
470                    ..loaded.safety.policy(s.name())
471                };
472                (s.clone(), policy)
473            })
474            .collect();
475        let info = self.combined_info();
476        crate::service::mcp_service(ctx, move || {
477            let handlers = parts
478                .iter()
479                .map(|(s, policy)| {
480                    let guarded = Guarded::with_policy(s.handler(), policy.clone());
481                    (s.name(), DynHandler::new(guarded))
482                })
483                .collect();
484            Ok(Combined::new(info.clone(), handlers))
485        })
486    }
487
488    /// The whole HTTP application: `/healthz`, the OAuth routes, each service at `/<name>` (its
489    /// own OAuth protected resource, under its read-only rule and audit log), `/favicon.ico` when
490    /// there is an icon and, when `loaded.combined`, every service's tools together at `/mcp`,
491    /// passed through [`wrap_router`](Self::wrap_router). Every response, the wrapped routes'
492    /// too, sends `X-Content-Type-Options: nosniff`, and `Strict-Transport-Security` when the
493    /// server serves certificate files (`TLS_CERT_PATH`).
494    pub fn router(&self, loaded: &Loaded, ctx: &ServiceContext) -> axum::Router {
495        let services = &loaded.services;
496        assert!(
497            services.iter().all(|s| s.name() != COMBINED),
498            "{COMBINED} is reserved for the combined endpoint"
499        );
500        let combined = loaded.combined && !services.is_empty();
501        let mut names: Vec<&str> = services.iter().map(|s| s.name()).collect();
502        if combined {
503            names.push(COMBINED);
504        }
505        let auth = AuthState::new(loaded.core.oauth.clone(), &names, loaded.verifier.clone());
506        let mut routers: Vec<(&'static str, axum::Router)> = services
507            .iter()
508            .map(|s| {
509                let policy = axum::Extension(loaded.safety.policy(s.name()));
510                (s.name(), s.clone().router(ctx).layer(policy))
511            })
512            .collect();
513        if combined {
514            routers.push((COMBINED, self.combined_router(loaded, ctx)));
515        }
516        let app = build_app(auth, routers);
517        let app = match self.icon {
518            Some((png, _)) => app.route(
519                "/favicon.ico",
520                axum::routing::get(move || async move {
521                    ([(axum::http::header::CONTENT_TYPE, "image/png")], png)
522                }),
523            ),
524            None => app,
525        };
526        let app = match self.wrap {
527            Some(wrap) => wrap(app),
528            None => app,
529        };
530        // HSTS only with certificate files: a self-signed certificate means local use or a proxy
531        // in front, and the proxy sets its own policy.
532        let hsts = matches!(loaded.core.tls, tls::TlsMode::Files { .. });
533        app.layer(axum::middleware::map_response(
534            move |mut res: axum::response::Response| async move {
535                let headers = res.headers_mut();
536                headers.insert(
537                    axum::http::header::X_CONTENT_TYPE_OPTIONS,
538                    axum::http::HeaderValue::from_static("nosniff"),
539                );
540                if hsts {
541                    headers.insert(
542                        axum::http::header::STRICT_TRANSPORT_SECURITY,
543                        axum::http::HeaderValue::from_static("max-age=31536000"),
544                    );
545                }
546                res
547            },
548        ))
549    }
550
551    /// Every service's log caps.
552    pub fn log_caps(services: &[Arc<dyn Service>]) -> Vec<&'static str> {
553        services
554            .iter()
555            .flat_map(|s| s.log_caps().iter().copied())
556            .collect()
557    }
558
559    /// The tool names `/mcp` offers, in order.
560    pub fn combined_tool_names(services: &[Arc<dyn Service>]) -> Vec<String> {
561        services
562            .iter()
563            .flat_map(|s| {
564                s.tool_names()
565                    .into_iter()
566                    .map(|t| prefixed_name(s.name(), &t))
567            })
568            .collect()
569    }
570
571    /// Starts logging and serves `loaded` until Ctrl-C or SIGTERM.
572    pub async fn run(&self, loaded: Loaded) -> anyhow::Result<()> {
573        let mut obs = loaded.core.observability.clone();
574        obs.log_level = observability::log_filter(
575            &obs.log_level,
576            &Self::log_caps(&loaded.services),
577            &[AUDIT_TARGET],
578        );
579        let _guard = observability::init(&obs)?;
580        tracing::info!(version = self.version, "starting {}", self.name);
581        for w in &loaded.warnings {
582            tracing::warn!("{w}");
583        }
584        for s in &loaded.services {
585            tracing::info!(
586                service = s.name(),
587                url = loaded.core.service_url(s.name()),
588                read_only = loaded.safety.is_read_only(s.name()),
589                tools = ?s.tool_names(),
590                "service enabled"
591            );
592        }
593        if loaded.combined && !loaded.services.is_empty() {
594            tracing::info!(
595                url = loaded.core.service_url(COMBINED),
596                tools = Self::combined_tool_names(&loaded.services).len(),
597                "combined endpoint enabled"
598            );
599        }
600        let shutdown = shutdown_signal();
601        let ctx = ServiceContext {
602            http: HttpSettings::from_core(&loaded.core),
603            shutdown: shutdown.clone(),
604        };
605        let app = self.router(&loaded, &ctx);
606        tracing::info!(addr = %loaded.core.bind_addr, "listening");
607        tls::serve(
608            app,
609            loaded.core.bind_addr,
610            loaded.core.tls.clone(),
611            shutdown,
612        )
613        .await
614    }
615
616    fn usage(&self) -> String {
617        let docs = match self.docs_url {
618            Some(url) => format!("; see {url}"),
619            None => ".".to_string(),
620        };
621        format!(
622            "usage: {} [--version | --healthcheck]\nAll configuration is read from environment variables{docs}",
623            self.name
624        )
625    }
626
627    /// Everything `main` does: handles `--version`, `--help` and `--healthcheck`, reads the
628    /// configuration from the process environment (printing every error), then [`run`](Self::run)s.
629    pub async fn main(self) -> ExitCode {
630        let arg = std::env::args().nth(1);
631        match arg.as_deref() {
632            Some("--version" | "-V") => {
633                println!("{} {}", self.name, self.version);
634                return ExitCode::SUCCESS;
635            }
636            Some("--healthcheck") => return healthcheck().await,
637            Some("--help" | "-h") => {
638                println!("{}", self.usage());
639                return ExitCode::SUCCESS;
640            }
641            Some(other) => {
642                eprintln!("unknown argument: {other}\n{}", self.usage());
643                return ExitCode::from(2);
644            }
645            None => {}
646        }
647        install_crypto_provider();
648        let mut env: ServiceEnv = EnvReader::new(Box::new(|k: &str| std::env::var(k).ok()));
649        let Some(loaded) = self.load(&mut env) else {
650            for e in &env.errors {
651                eprintln!("configuration error: {e}");
652            }
653            return ExitCode::FAILURE;
654        };
655        match self.run(loaded).await {
656            Ok(()) => ExitCode::SUCCESS,
657            Err(e) => {
658                tracing::error!(error = %e, "fatal");
659                eprintln!("error: {e:#}");
660                ExitCode::FAILURE
661            }
662        }
663    }
664}
665
666/// Reads `OAUTH_ADMIN_PASSWORD` for [`SignIn::OwnerPassword`].
667fn owner_password(env: &mut ServiceEnv) -> Option<Arc<dyn CredentialVerifier>> {
668    let password = env.secret_required("OAUTH_ADMIN_PASSWORD")?;
669    let p = password.expose_secret();
670    if p.chars().count() < MIN_ADMIN_PASSWORD_CHARS || p.trim().is_empty() {
671        env.errors.push(format!(
672            "OAUTH_ADMIN_PASSWORD must be at least {MIN_ADMIN_PASSWORD_CHARS} characters, not only spaces"
673        ));
674        return None;
675    }
676    Some(Arc::new(PasswordVerifier::new(password)))
677}
678
679/// The container healthcheck: `GET /healthz` on 127.0.0.1 at the `BIND_ADDR` port.
680pub async fn healthcheck() -> ExitCode {
681    install_crypto_provider();
682    let mut env = EnvReader::from_process();
683    let addr = env.parse("BIND_ADDR", SocketAddr::from(([0, 0, 0, 0], 8443)));
684    let insecure = env.bool("INSECURE_HTTP", false);
685    if tls::healthcheck(addr.port(), !insecure).await {
686        return ExitCode::SUCCESS;
687    }
688    eprintln!("healthcheck failed");
689    ExitCode::FAILURE
690}
691
692#[cfg(test)]
693mod tests {
694    use super::*;
695    use std::collections::HashMap;
696
697    fn env(pairs: &[(&str, &str)]) -> ServiceEnv {
698        let map: HashMap<String, String> = pairs
699            .iter()
700            .map(|(k, v)| (k.to_string(), v.to_string()))
701            .collect();
702        ServiceEnv::new(Box::new(move |k: &str| map.get(k).cloned()))
703    }
704
705    const CORE: &[(&str, &str)] = &[
706        ("PUBLIC_URL", "https://mcp.example.com"),
707        ("OAUTH_SIGNING_KEY", "0123456789abcdef0123456789abcdef"),
708        ("OAUTH_ADMIN_PASSWORD", "a long password"),
709    ];
710
711    fn with_core(extra: &[(&str, &str)]) -> ServiceEnv {
712        let mut all = CORE.to_vec();
713        all.extend_from_slice(extra);
714        env(&all)
715    }
716
717    #[derive(Clone)]
718    struct Nothing;
719    impl rmcp::ServerHandler for Nothing {}
720
721    struct Named(&'static str);
722    impl Service for Named {
723        fn name(&self) -> &'static str {
724            self.0
725        }
726        fn handler(&self) -> DynHandler {
727            DynHandler::new(Nothing)
728        }
729    }
730
731    fn alpha(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
732        Some(Arc::new(Named("alpha")))
733    }
734
735    fn needy(env: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
736        env.required("NEEDY_TOKEN");
737        None
738    }
739
740    /// Two services reading the same variable.
741    fn sharing(env: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
742        env.required("SHARED_TOKEN");
743        None
744    }
745
746    fn misnamed(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
747        Some(Arc::new(Named("other")))
748    }
749
750    fn two() -> Server {
751        Server::new("mcp-test", "1.0.0")
752            .env_prefix("TEST")
753            .service("alpha", alpha)
754            .service("needy", needy)
755    }
756
757    fn names(v: &[(&'static str, ServiceFactory)]) -> Vec<&'static str> {
758        v.iter().map(|(n, _)| *n).collect()
759    }
760
761    #[test]
762    fn defaults() {
763        let s = Server::new("mcp-test", "1.0.0");
764        assert_eq!(s.crate_target, "mcp_test");
765        assert_eq!(s.var("SERVICES"), "MCP_SERVICES");
766        assert_eq!(s.env_prefix("my_app_").var("COMBINED"), "MY_APP_COMBINED");
767    }
768
769    #[test]
770    fn unset_selects_every_registered_service() {
771        assert_eq!(names(&two().select(None).unwrap()), vec!["alpha", "needy"]);
772    }
773
774    #[test]
775    fn explicit_selection_is_trimmed_and_deduplicated() {
776        assert_eq!(
777            names(&two().select(Some(" needy , alpha,needy")).unwrap()),
778            vec!["needy", "alpha"]
779        );
780    }
781
782    #[test]
783    fn unknown_or_empty_selection_is_an_error() {
784        let e = two().select(Some("alpha,beta")).unwrap_err();
785        assert_eq!(
786            e,
787            "TEST_SERVICES contains an unknown service: beta (known: alpha, needy)"
788        );
789        let e = two().select(Some(" , ")).unwrap_err();
790        assert!(
791            e.starts_with("TEST_SERVICES must name at least one service"),
792            "{e}"
793        );
794        let e = two().select(Some(COMBINED)).unwrap_err();
795        assert!(e.contains("unknown service: mcp"), "{e}");
796    }
797
798    #[test]
799    fn unselected_services_do_not_read_config() {
800        let mut e = with_core(&[("TEST_SERVICES", "alpha")]);
801        let loaded = two().load(&mut e).expect("loads");
802        assert!(e.errors.is_empty(), "{:?}", e.errors);
803        assert_eq!(loaded.services.len(), 1);
804        assert_eq!(loaded.services[0].name(), "alpha");
805
806        let mut e = with_core(&[]);
807        assert!(two().load(&mut e).is_none());
808        assert_eq!(e.errors, vec!["NEEDY_TOKEN is required".to_string()]);
809    }
810
811    #[test]
812    fn core_and_service_errors_are_reported_together() {
813        let mut e = env(&[("PUBLIC_URL", "ftp://x"), ("OAUTH_ADMIN_PASSWORD", "short")]);
814        assert!(two().load(&mut e).is_none());
815        let joined = e.errors.join("\n");
816        assert!(joined.contains("PUBLIC_URL"), "{joined}");
817        assert!(joined.contains("OAUTH_SIGNING_KEY is required"), "{joined}");
818        assert!(
819            joined.contains("OAUTH_ADMIN_PASSWORD must be at least 12 characters"),
820            "{joined}"
821        );
822        assert!(joined.contains("NEEDY_TOKEN is required"), "{joined}");
823        assert!(!joined.contains("short"), "secret leaked: {joined}");
824    }
825
826    #[test]
827    fn the_owner_password_is_required_and_twelve_characters_is_enough() {
828        let mut e = env(&CORE[..2]);
829        assert!(two().load(&mut e).is_none());
830        assert!(
831            e.errors
832                .contains(&"OAUTH_ADMIN_PASSWORD is required".to_string()),
833            "{:?}",
834            e.errors
835        );
836        let mut e = with_core(&[
837            ("TEST_SERVICES", "alpha"),
838            ("OAUTH_ADMIN_PASSWORD", "twelve chars"),
839        ]);
840        let loaded = two().load(&mut e).expect("loads");
841        assert!(!loaded.verifier.carried());
842    }
843
844    #[test]
845    fn shared_variable_errors_are_reported_once() {
846        let s = Server::new("mcp-test", "1")
847            .service("one", sharing)
848            .service("two", sharing);
849        let mut e = with_core(&[]);
850        assert!(s.load(&mut e).is_none());
851        assert_eq!(e.errors, vec!["SHARED_TOKEN is required".to_string()]);
852    }
853
854    #[test]
855    fn a_service_must_have_the_name_it_was_registered_with() {
856        let s = Server::new("mcp-test", "1").service("alpha", misnamed);
857        let mut e = with_core(&[]);
858        assert!(s.load(&mut e).is_none());
859        assert_eq!(
860            e.errors,
861            vec!["the service registered as alpha is named other".to_string()]
862        );
863    }
864
865    #[test]
866    #[should_panic(expected = "is reserved for the combined endpoint")]
867    fn mcp_is_not_a_service_name() {
868        let _ = Server::new("mcp-test", "1").service("mcp", alpha);
869    }
870
871    #[test]
872    #[should_panic(expected = "must be lowercase letters, digits and '-'")]
873    fn service_names_are_path_segments() {
874        let _ = Server::new("mcp-test", "1").service("my_service", alpha);
875    }
876
877    #[test]
878    #[should_panic(expected = "registered twice")]
879    fn service_names_are_unique() {
880        let _ = Server::new("mcp-test", "1")
881            .service("alpha", alpha)
882            .service("alpha", alpha);
883    }
884
885    #[test]
886    fn the_combined_endpoint_is_on_unless_turned_off() {
887        let s = Server::new("mcp-test", "1")
888            .env_prefix("TEST")
889            .service("alpha", alpha);
890        let mut e = with_core(&[]);
891        assert!(s.load(&mut e).expect("loads").combined);
892        let mut e = with_core(&[("TEST_COMBINED", "false")]);
893        assert!(!s.load(&mut e).expect("loads").combined);
894        let mut e = with_core(&[("TEST_COMBINED", "maybe")]);
895        assert!(s.load(&mut e).is_none());
896        assert_eq!(e.errors.len(), 1, "{:?}", e.errors);
897        assert!(e.errors[0].contains("TEST_COMBINED"), "{:?}", e.errors);
898    }
899
900    #[test]
901    fn read_only_accepts_names_all_and_nothing() {
902        let s = two();
903        assert_eq!(s.read_only(None).unwrap(), Vec::<&str>::new());
904        assert_eq!(s.read_only(Some(" , ")).unwrap(), Vec::<&str>::new());
905        assert_eq!(
906            s.read_only(Some(" needy,alpha,needy")).unwrap(),
907            vec!["needy", "alpha"]
908        );
909        assert_eq!(
910            s.read_only(Some("alpha,all")).unwrap(),
911            vec!["alpha", "needy"]
912        );
913        assert_eq!(
914            s.read_only(Some("alpha,beta")).unwrap_err(),
915            "TEST_READ_ONLY contains an unknown service: beta (known: all, alpha, needy)"
916        );
917    }
918
919    #[test]
920    fn read_only_names_need_not_be_selected() {
921        let mut e = with_core(&[("TEST_SERVICES", "alpha"), ("TEST_READ_ONLY", "needy")]);
922        let loaded = two().load(&mut e).expect("loads");
923        assert!(loaded.safety.is_read_only("needy"));
924        assert!(!loaded.safety.is_read_only("alpha"));
925        assert!(!loaded.safety.policy("alpha").read_only);
926        assert_eq!(loaded.safety.policy("alpha").endpoint, "/alpha");
927    }
928
929    struct Keyed;
930    impl Service for Keyed {
931        fn name(&self) -> &'static str {
932            "keyed"
933        }
934        fn handler(&self) -> DynHandler {
935            DynHandler::new(Nothing)
936        }
937        fn credential_verifier(&self) -> Option<Arc<dyn CredentialVerifier>> {
938            struct Key;
939            impl CredentialVerifier for Key {
940                fn label(&self) -> &str {
941                    "example key"
942                }
943                fn check<'a>(&'a self, _: &'a str) -> crate::credential::CheckFuture<'a> {
944                    Box::pin(async { crate::credential::CredentialCheck::Valid })
945                }
946            }
947            Some(Arc::new(Key))
948        }
949    }
950
951    fn keyed(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
952        Some(Arc::new(Keyed))
953    }
954
955    #[test]
956    fn service_credentials_come_from_the_one_service_that_defines_them() {
957        let s = Server::new("mcp-test", "1")
958            .service("alpha", alpha)
959            .service("keyed", keyed)
960            .sign_in(SignIn::ServiceCredential);
961        let mut e = env(&CORE[..2]);
962        let loaded = s.load(&mut e).expect("no admin password needed");
963        assert_eq!(loaded.verifier.label(), "example key");
964        assert!(loaded.verifier.carried());
965
966        let s = Server::new("mcp-test", "1")
967            .service("alpha", alpha)
968            .sign_in(SignIn::ServiceCredential);
969        let mut e = env(&CORE[..2]);
970        assert!(s.load(&mut e).is_none());
971        assert_eq!(
972            e.errors,
973            vec!["no enabled service defines how people sign in".to_string()]
974        );
975    }
976
977    #[test]
978    fn a_static_token_needs_sign_in_that_carries_no_credential() {
979        let s = Server::new("mcp-test", "1")
980            .service("keyed", keyed)
981            .sign_in(SignIn::ServiceCredential);
982        let mut e = with_core(&[("MCP_AUTH_TOKEN", "static-token")]);
983        assert!(s.load(&mut e).is_none());
984        assert_eq!(
985            e.errors,
986            vec![
987                "MCP_AUTH_TOKEN cannot be used when people sign in with their own example key"
988                    .to_string()
989            ]
990        );
991        let s = Server::new("mcp-test", "1").service("alpha", alpha);
992        let mut e = with_core(&[("MCP_AUTH_TOKEN", "static-token")]);
993        assert!(s.load(&mut e).is_some(), "{:?}", e.errors);
994    }
995
996    #[test]
997    fn two_services_that_both_define_sign_in_are_refused() {
998        fn keyed_too(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
999            struct KeyedToo;
1000            impl Service for KeyedToo {
1001                fn name(&self) -> &'static str {
1002                    "keyed-too"
1003                }
1004                fn handler(&self) -> DynHandler {
1005                    DynHandler::new(Nothing)
1006                }
1007                fn credential_verifier(&self) -> Option<Arc<dyn CredentialVerifier>> {
1008                    Keyed.credential_verifier()
1009                }
1010            }
1011            Some(Arc::new(KeyedToo))
1012        }
1013        let s = Server::new("mcp-test", "1")
1014            .service("keyed", keyed)
1015            .service("keyed-too", keyed_too)
1016            .sign_in(SignIn::ServiceCredential);
1017        let mut e = env(&CORE[..2]);
1018        assert!(s.load(&mut e).is_none());
1019        assert_eq!(
1020            e.errors,
1021            vec![
1022                "more than one enabled service defines how people sign in (keyed, keyed-too): enable one of them"
1023                    .to_string()
1024            ]
1025        );
1026        let mut e = env(&[CORE[0], CORE[1], ("MCP_SERVICES", "keyed-too")]);
1027        assert!(s.load(&mut e).is_some(), "{:?}", e.errors);
1028    }
1029
1030    #[test]
1031    fn a_password_of_spaces_is_refused_and_a_short_one_warned_about() {
1032        let s = Server::new("mcp-test", "1").service("alpha", alpha);
1033        let mut e = with_core(&[("OAUTH_ADMIN_PASSWORD", "              ")]);
1034        assert!(s.load(&mut e).is_none());
1035        assert!(e.errors[0].contains("not only spaces"), "{:?}", e.errors);
1036        let mut e = with_core(&[("OAUTH_ADMIN_PASSWORD", "twelve chars")]);
1037        let loaded = s.load(&mut e).expect("loads");
1038        assert_eq!(loaded.warnings.len(), 1);
1039        assert!(loaded.warnings[0].contains("shorter than 15"));
1040        let mut e = with_core(&[("OAUTH_ADMIN_PASSWORD", "a much longer passphrase")]);
1041        assert!(s.load(&mut e).expect("loads").warnings.is_empty());
1042    }
1043
1044    #[test]
1045    fn a_static_token_shaped_like_a_jwt_or_short_is_reported() {
1046        let s = Server::new("mcp-test", "1").service("alpha", alpha);
1047        let mut e = with_core(&[("MCP_AUTH_TOKEN", "aaa.bbb.ccc")]);
1048        assert!(s.load(&mut e).is_none());
1049        assert!(e.errors[0].contains("shape of a JWT"), "{:?}", e.errors);
1050        // Reported with the other errors, not only once they are fixed.
1051        let mut e = with_core(&[
1052            ("OAUTH_ADMIN_PASSWORD", "short"),
1053            ("MCP_AUTH_TOKEN", "aaa.bbb.ccc"),
1054        ]);
1055        assert!(s.load(&mut e).is_none());
1056        assert!(e.errors.iter().any(|x| x.contains("shape of a JWT")));
1057        assert!(e.errors.iter().any(|x| x.contains("OAUTH_ADMIN_PASSWORD")));
1058        let mut e = with_core(&[("MCP_AUTH_TOKEN", "short-token")]);
1059        let loaded = s.load(&mut e).expect("loads");
1060        assert!(
1061            loaded.warnings.iter().any(|w| w.contains("MCP_AUTH_TOKEN")),
1062            "{:?}",
1063            loaded.warnings
1064        );
1065    }
1066
1067    #[test]
1068    fn custom_sign_in_reads_its_own_configuration() {
1069        fn custom(env: &mut ServiceEnv) -> Option<Arc<dyn CredentialVerifier>> {
1070            let p = env.secret_required("CUSTOM_PASSWORD")?;
1071            Some(Arc::new(PasswordVerifier::new(p)))
1072        }
1073        let s = Server::new("mcp-test", "1")
1074            .service("alpha", alpha)
1075            .sign_in(SignIn::Custom(custom));
1076        let mut e = env(&CORE[..2]);
1077        assert!(s.load(&mut e).is_none());
1078        assert_eq!(e.errors, vec!["CUSTOM_PASSWORD is required".to_string()]);
1079    }
1080
1081    #[test]
1082    fn callback_is_reserved_when_people_sign_in_upstream() {
1083        use crate::upstream::{Exchange, ExchangeFuture, UpstreamSignIn, UpstreamVerifier};
1084        struct Provider;
1085        impl UpstreamSignIn for Provider {
1086            fn provider(&self) -> &str {
1087                "Provider"
1088            }
1089            fn authorize_url(&self, _: &str, _: &str) -> String {
1090                "https://provider.example.com/authorize".into()
1091            }
1092            fn exchange<'a>(&'a self, _: &'a str, _: &'a str) -> ExchangeFuture<'a> {
1093                Box::pin(async { Exchange::Refused("no".into()) })
1094            }
1095        }
1096        fn upstream(_: &mut ServiceEnv) -> Option<Arc<dyn CredentialVerifier>> {
1097            Some(Arc::new(UpstreamVerifier::new(
1098                "Provider account",
1099                Provider,
1100            )))
1101        }
1102        fn callback(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
1103            Some(Arc::new(Named("callback")))
1104        }
1105        let s = Server::new("mcp-test", "1")
1106            .service("callback", callback)
1107            .sign_in(SignIn::Custom(upstream));
1108        let mut e = env(&CORE[..2]);
1109        assert!(s.load(&mut e).is_none());
1110        assert!(
1111            e.errors[0].contains("cannot be named callback"),
1112            "{:?}",
1113            e.errors
1114        );
1115        let s = Server::new("mcp-test", "1")
1116            .service("alpha", alpha)
1117            .sign_in(SignIn::Custom(upstream));
1118        let mut e = env(&CORE[..2]);
1119        let loaded = s.load(&mut e).expect("loads");
1120        assert!(loaded.verifier.upstream().is_some());
1121        // With a password, callback is an ordinary name.
1122        let s = Server::new("mcp-test", "1").service("callback", callback);
1123        let mut e = env(CORE);
1124        assert!(s.load(&mut e).is_some(), "{:?}", e.errors);
1125    }
1126
1127    #[test]
1128    fn usage_names_the_docs() {
1129        let s = Server::new("mcp-test", "1");
1130        assert!(s.usage().ends_with("environment variables."));
1131        let s = s.docs_url("https://example.com/docs");
1132        assert!(s.usage().ends_with("; see https://example.com/docs"));
1133    }
1134
1135    #[test]
1136    fn log_caps_are_the_services_own() {
1137        assert!(Server::log_caps(&[]).is_empty());
1138    }
1139}