mcp_server_core/lib.rs
1//! A batteries-included base for [Model Context Protocol](https://modelcontextprotocol.io) servers
2//! served over Streamable HTTP.
3//!
4//! You write the tools, as an [`rmcp`] `ServerHandler`. This crate puts them on the network the way
5//! hosted MCP clients such as claude.ai expect:
6//!
7//! - **OAuth 2.1 sign-in** with dynamic client registration, PKCE (S256), resource indicators
8//! (RFC 8707) and protected-resource metadata (RFC 9728). It is stateless: every token is a
9//! signed JWT, so nothing needs storing and restarts sign nobody out.
10//! - **Two ways for people to sign in**, chosen with [`app::SignIn`]: the owner's password (one
11//! person, with the server's own upstream access) or each person's own credential for the
12//! upstream service, such as an API key, which is checked upstream, sealed into their tokens
13//! and handed to your tools. You can also supply your own check.
14//! - **Several services on one server**, each at `/<name>` and its own OAuth protected resource,
15//! plus every service's tools together at `/mcp`.
16//! - **Hardening for servers shared by many people**: sign-in limits per address, per network
17//! and overall, capped and shared upstream credential checks, MCP sessions bound to each
18//! person's credential, host and origin checks, body limits and constant-time comparisons.
19//! - **Read-only mode and a write audit log** for every service, driven by each tool's
20//! `read_only_hint` annotation.
21//! - **TLS** from certificate files (hot reloaded) or a self-signed certificate, or plain HTTP
22//! behind a proxy, a container healthcheck, graceful shutdown, JSON logs, Prometheus metrics
23//! and OpenTelemetry traces.
24//! - **Configuration from environment variables**, with `<NAME>_FILE` variants for secrets and
25//! every error reported at once.
26//!
27//! # Quick start
28//!
29//! A service is a name and an MCP handler. The [`app::Server`] builder does the rest:
30//!
31//! ```no_run
32//! use mcp_server_core::app::{Server, SignIn};
33//! use mcp_server_core::combined::DynHandler;
34//! use mcp_server_core::rmcp::ServerHandler;
35//! use mcp_server_core::service::{Service, ServiceEnv};
36//! use std::sync::Arc;
37//!
38//! // Your MCP server: in practice a `#[tool_router]` with your tools.
39//! #[derive(Clone)]
40//! struct Hello;
41//!
42//! impl ServerHandler for Hello {}
43//!
44//! struct HelloService;
45//!
46//! impl Service for HelloService {
47//! fn name(&self) -> &'static str {
48//! "hello"
49//! }
50//! fn handler(&self) -> DynHandler {
51//! DynHandler::new(Hello)
52//! }
53//! }
54//!
55//! fn hello(_env: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
56//! Some(Arc::new(HelloService))
57//! }
58//!
59//! #[tokio::main]
60//! async fn main() -> std::process::ExitCode {
61//! Server::new("mcp-hello", env!("CARGO_PKG_VERSION"))
62//! .env_prefix("HELLO")
63//! .service("hello", hello)
64//! .sign_in(SignIn::OwnerPassword)
65//! .main()
66//! .await
67//! }
68//! ```
69//!
70//! Run it with `PUBLIC_URL`, `OAUTH_SIGNING_KEY` and `OAUTH_ADMIN_PASSWORD` set and the service is
71//! at `https://<host>/hello`. See the repository's `examples/` for a complete tool server and for
72//! signing people in with their own API keys.
73//!
74//! # Lower-level pieces
75//!
76//! [`app::Server`] is a thin layer over the modules below; use them directly when you need a
77//! different shape: [`server::build_app`] mounts services behind the OAuth routes,
78//! [`service::mcp_service`] wraps any rmcp handler in the hardened Streamable HTTP transport and
79//! [`tls::serve`] serves the result.
80//!
81//! # Feature flags
82//!
83//! - `otel` (default): export traces over OTLP/HTTP when `OTEL_EXPORTER_OTLP_ENDPOINT` is set.
84//! - `prometheus` (default): serve Prometheus metrics on `METRICS_ADDR`.
85#![cfg_attr(docsrs, feature(doc_cfg))]
86
87pub mod app;
88pub mod caller;
89pub mod combined;
90pub mod config;
91pub mod credential;
92pub mod guards;
93pub mod jwt;
94pub mod oauth;
95pub mod observability;
96pub mod pkce;
97pub mod policy;
98pub mod prompt;
99pub mod server;
100pub mod service;
101pub mod tls;
102pub mod upstream;
103
104pub use axum;
105pub use rmcp;
106
107/// The README's examples, compiled as doctests so they stay correct.
108#[cfg(doctest)]
109#[doc = include_str!("../README.md")]
110struct ReadmeDoctests;
111
112/// The documentation site's pages (`docs/src`), compiled as doctests so their examples stay
113/// correct.
114#[cfg(doctest)]
115mod book {
116 #[doc = include_str!("../docs/src/introduction.md")]
117 struct Introduction;
118 #[doc = include_str!("../docs/src/quick-start.md")]
119 struct QuickStart;
120 #[doc = include_str!("../docs/src/writing-a-service.md")]
121 struct WritingAService;
122 #[doc = include_str!("../docs/src/combined.md")]
123 struct Combined;
124 #[doc = include_str!("../docs/src/prompts.md")]
125 struct Prompts;
126 #[doc = include_str!("../docs/src/examples.md")]
127 struct Examples;
128 #[doc = include_str!("../docs/src/sign-in.md")]
129 struct SignIn;
130 #[doc = include_str!("../docs/src/oauth.md")]
131 struct Oauth;
132 #[doc = include_str!("../docs/src/connecting-clients.md")]
133 struct ConnectingClients;
134 #[doc = include_str!("../docs/src/configuration.md")]
135 struct Configuration;
136 #[doc = include_str!("../docs/src/deployment.md")]
137 struct Deployment;
138 #[doc = include_str!("../docs/src/read-only-and-audit.md")]
139 struct ReadOnlyAndAudit;
140 #[doc = include_str!("../docs/src/observability.md")]
141 struct Observability;
142 #[doc = include_str!("../docs/src/troubleshooting.md")]
143 struct Troubleshooting;
144 #[doc = include_str!("../docs/src/security.md")]
145 struct Security;
146 #[doc = include_str!("../docs/src/limits.md")]
147 struct Limits;
148 #[doc = include_str!("../docs/src/endpoints.md")]
149 struct Endpoints;
150 #[doc = include_str!("../docs/src/lower-level-api.md")]
151 struct LowerLevelApi;
152 #[doc = include_str!("../docs/src/changelog.md")]
153 struct Changelog;
154 #[doc = include_str!("../docs/src/architecture.md")]
155 struct Architecture;
156 #[doc = include_str!("../docs/src/contributing.md")]
157 struct Contributing;
158 #[doc = include_str!("../docs/src/releases.md")]
159 struct Releases;
160}
161
162/// Installs rustls' `ring` crypto provider as the process default. Call it once before serving
163/// TLS or making TLS requests; later calls do nothing. [`app::Server::main`] calls it for you.
164pub fn install_crypto_provider() {
165 let _ = rustls::crypto::ring::default_provider().install_default();
166}
167
168/// A token cancelled on Ctrl-C, or on SIGTERM on Unix, for graceful shutdown. Must be called
169/// inside a Tokio runtime.
170pub fn shutdown_signal() -> tokio_util::sync::CancellationToken {
171 let ct = tokio_util::sync::CancellationToken::new();
172 let trigger = ct.clone();
173 tokio::spawn(async move {
174 let ctrl_c = async {
175 let _ = tokio::signal::ctrl_c().await;
176 };
177 #[cfg(unix)]
178 let term = async {
179 match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
180 Ok(mut s) => {
181 s.recv().await;
182 }
183 Err(_) => std::future::pending::<()>().await,
184 }
185 };
186 #[cfg(not(unix))]
187 let term = std::future::pending::<()>();
188 tokio::select! { _ = ctrl_c => {}, _ = term => {} }
189 tracing::info!("shutdown signal received");
190 trigger.cancel();
191 });
192 ct
193}