rmcp_server_kit/lib.rs
1#![forbid(unsafe_code)]
2#![cfg_attr(
3 test,
4 allow(
5 clippy::unwrap_used,
6 clippy::expect_used,
7 clippy::panic,
8 clippy::panic_in_result_fn,
9 clippy::indexing_slicing,
10 clippy::unwrap_in_result,
11 clippy::print_stdout,
12 clippy::print_stderr,
13 reason = "test-only relaxations; production code uses ? and tracing"
14 )
15)]
16
17//! `rmcp-server-kit` — production-grade reusable framework for building
18//! [Model Context Protocol](https://modelcontextprotocol.io/) servers in Rust.
19//!
20//! Application crates depend on `rmcp-server-kit` and supply their own
21//! [`rmcp::handler::server::ServerHandler`] implementation; the kit provides
22//! transport, security, and observability around it.
23//!
24//! # What you get
25//!
26//! - **Streamable HTTP transport** with TLS / mTLS termination, configurable
27//! keep-alive and session idle timeouts, CORS, compression, body-size and
28//! concurrency caps, and graceful shutdown on `SIGINT`/`SIGTERM`.
29//! - **Authentication**: API keys (Argon2-hashed, constant-time compared),
30//! mTLS client certificates with optional CDP-driven CRL revocation, and —
31//! under the `oauth` feature — OAuth 2.1 Bearer JWT validation against a
32//! cached JWKS endpoint.
33//! - **RBAC** with per-tool argument allow-lists and per-IP per-tool rate
34//! limiting; policies and API keys are hot-reloadable at runtime via
35//! [`transport::ReloadHandle`] (lock-free [`arc_swap`] swaps).
36//! - **Observability**: `tracing` with JSON or pretty formats, optional audit
37//! file sink, `/healthz` + `/readyz` probes, `/version`, `/admin/*`
38//! diagnostics, and — under the `metrics` feature — a Prometheus
39//! `/metrics` endpoint on a separate listener.
40//! - **OWASP-grade defaults**: HSTS, CSP, `X-Frame-Options`, MCP `Origin`
41//! validation, and per-hop SSRF guards on outbound HTTP.
42//!
43//! # Quick start
44//!
45//! ```no_run
46//! use rmcp::{
47//! handler::server::ServerHandler,
48//! model::{ServerCapabilities, ServerInfo},
49//! };
50//! use rmcp_server_kit::transport::{McpServerConfig, serve};
51//!
52//! #[derive(Clone)]
53//! struct MyHandler;
54//!
55//! impl ServerHandler for MyHandler {
56//! fn get_info(&self) -> ServerInfo {
57//! ServerInfo::new(ServerCapabilities::builder().enable_tools().build())
58//! }
59//! }
60//!
61//! #[tokio::main]
62//! async fn main() -> rmcp_server_kit::Result<()> {
63//! let _ = rmcp_server_kit::observability::init_tracing("info");
64//!
65//! let config = McpServerConfig::new(
66//! "127.0.0.1:8080",
67//! "my-mcp-server",
68//! env!("CARGO_PKG_VERSION"),
69//! );
70//!
71//! serve(config.validate()?, || MyHandler).await
72//! }
73//! ```
74//!
75//! See [`examples/`](https://github.com/andrico21/rmcp-server-kit/tree/main/examples)
76//! for richer setups (API-key + RBAC, OAuth resource server) and
77//! [`docs/GUIDE.md`](https://github.com/andrico21/rmcp-server-kit/blob/main/docs/GUIDE.md)
78//! for the full TOML configuration reference.
79//!
80//! # Cargo features
81//!
82//! All features are **off by default**:
83//!
84//! - `oauth` — OAuth 2.1 Bearer JWT validation, JWKS cache, and optional
85//! OAuth proxy endpoints. Pulls in [`jsonwebtoken`] and [`urlencoding`].
86//! Required to use the [`oauth`] module.
87//! - `oauth-mtls-client` — RFC 8705 §2 mTLS client authentication for the
88//! OAuth token-exchange endpoint. Implies `oauth`. Without this feature,
89//! [`oauth::OAuthConfig::validate`] rejects any configuration that sets
90//! [`oauth::TokenExchangeConfig::client_cert`].
91//! - `metrics` — Prometheus registry and `/metrics` listener. Pulls in
92//! the [`prometheus`] crate. Required to use the [`metrics`] module.
93//! - `test-helpers` — exposes test-only helpers from [`bounded_limiter`] and
94//! [`mtls_revocation`] for downstream integration tests. **Not part of the
95//! stable API surface** — no semver guarantees across minor releases.
96//!
97//! # ⚠️ stdio transport is unauthenticated
98//!
99//! [`transport::serve_stdio`] runs MCP over the process's stdin/stdout for
100//! local subprocess scenarios (desktop clients, IDE integrations). It
101//! **bypasses authentication, RBAC, TLS, Origin validation, and rate
102//! limiting** — the surrounding OS process boundary is the only trust
103//! boundary. Never expose `serve_stdio` to untrusted callers; for any
104//! network-reachable deployment use [`transport::serve`] over HTTPS instead.
105
106/// Reusable server and observability configuration primitives.
107pub mod config;
108/// Generic error type and `Result` alias for server-side code.
109pub mod error;
110/// Tracing / JSON logs / audit file initialization.
111pub mod observability;
112/// Streamable HTTP transport and server entry points.
113pub mod transport;
114
115/// Authentication state (API keys, mTLS, OAuth JWT) and middleware.
116pub mod auth;
117/// Role-based access control policy engine and middleware.
118pub mod rbac;
119
120/// Memory-bounded keyed rate limiter (LRU + idle eviction).
121pub mod bounded_limiter;
122
123/// Cancellation primitives that detach in-flight async work on
124/// cancel/timeout instead of dropping it mid-`.await`.
125pub mod cancel;
126
127/// Admin diagnostic endpoints (status, auth keys metadata, counters, RBAC).
128pub mod admin;
129
130/// Re-exports for the [`secrecy`] crate's secret-wrapper types.
131pub mod secret;
132
133pub(crate) mod ssrf;
134pub(crate) mod ssrf_resolver;
135
136/// Opt-in tool-call hooks (before/after) and result-size cap.
137pub mod tool_hooks;
138
139#[cfg(feature = "oauth")]
140/// OAuth 2.1 JWKS cache, token validation, and token exchange helpers.
141pub mod oauth;
142
143#[cfg(feature = "metrics")]
144/// Prometheus metrics registry shared across server components.
145pub mod metrics;
146
147/// CDP-driven CRL revocation support for mTLS.
148pub mod mtls_revocation;
149
150// Re-export the canonical error types at the crate root for ergonomic
151// `rmcp_server_kit::Result<()>` / `rmcp_server_kit::McpxError` usage in downstream crates.
152pub use crate::error::{McpxError, Result};