rmcp-server-kit
rmcp-server-kit is a production-grade, reusable framework for building Model Context Protocol servers in Rust. It provides a Streamable HTTP transport with TLS/mTLS, structured observability, authentication (Bearer / mTLS / OAuth 2.1 JWT), role-based access control (RBAC), per-IP rate limiting, and optional Prometheus metrics - all wired up and ready to go.
You supply a rmcp::handler::server::ServerHandler implementation; rmcp-server-kit
handles everything else.
Quick Start
[dependencies]
rmcp-server-kit = "3"
rmcp = { version = "3", features = ["server", "macros"] }
tokio = { version = "1", features = ["rt-multi-thread", "macros", "signal"] }
The minimal example below uses default features only. Enable the
oauthfeature (features = ["oauth"]) to validate JWTs against a JWKS, ormetricsfor the Prometheus/metricsendpoint - see the Cargo features table below.
use rmcp_server_kit::{
config::ObservabilityConfig,
observability::init_tracing_from_config_strict,
transport::{McpServerConfig, serve},
};
use rmcp::handler::server::ServerHandler;
use rmcp::model::{ServerCapabilities, ServerConfig};
#[derive(Clone)]
struct MyHandler;
impl ServerHandler for MyHandler {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
}
}
#[tokio::main]
async fn main() -> rmcp_server_kit::Result<()> {
let mut observability = ObservabilityConfig::default();
observability.log_level = "info,my_server=debug".into();
let _tracing_guard = init_tracing_from_config_strict(&observability)?;
let config = McpServerConfig::new("127.0.0.1:8080", "my-server", "0.1.0")
.with_request_timeout(std::time::Duration::from_secs(30))
.enable_request_header_logging();
serve(config.validate()?, || MyHandler).await
}
Full API documentation and worked examples live in
docs/GUIDE.md. For loading configuration from a TOML file and
bridging it into McpServerConfig via ServerConfig::apply_to_mcp_config, see
the TOML configuration reference.
Runnable end-to-end examples ship in the repository:
cargo run --example minimal_server
cargo run --example api_key_rbac
cargo run --example config_file_server
cargo run --example oauth_server --features oauth
cargo run --example oauth_proxy_as_demo --features oauth
Common configurations
API key + RBAC + per-tool argument allowlist:
use rmcp_server_kit::auth::{ApiKeyEntry, AuthConfig, RateLimitConfig, generate_api_key};
use rmcp_server_kit::rbac::{ArgumentAllowlist, RbacConfig, RbacPolicy, RoleConfig};
use std::sync::Arc;
let (token, hash) = generate_api_key()?;
let auth = AuthConfig::with_keys(vec![
ApiKeyEntry::new("viewer-key", hash, "viewer"),
])
// API-key auth without rate limiting is unsafe on a reachable listener.
// `with_pre_auth_burst(10)` caps the initial unauthenticated wave admitted
// to Argon2id verification at 10, well below the default of 300.
.with_rate_limit(RateLimitConfig::new(30).with_pre_auth_burst(10));
let viewer = RoleConfig::new("viewer", vec!["echo".into()], vec!["*".into()])
.with_argument_allowlists(vec![ArgumentAllowlist::new_required(
"echo", "message", vec!["hello".into(), "ping".into()],
)]);
let rbac = Arc::new(RbacPolicy::new(&RbacConfig::with_roles(vec![viewer])));
Use
ArgumentAllowlist::new_required(as above), notnew, unless omitting the argument is genuinely safe.requireddefaults tofalse- permanently
- so an allowlist built with
newconstrains the value only when the caller supplies it, and a tool that substitutes its own default for a missing argument bypasses the allowlist entirely. See the argument allowlist guide.
OAuth 2.1 resource server (JWT validation against JWKS):
use rmcp_server_kit::auth::AuthConfig;
use rmcp_server_kit::oauth::OAuthConfig;
let oauth = OAuthConfig::builder(
"https://auth.example.com/",
"my-mcp-server",
"https://auth.example.com/.well-known/jwks.json",
)
.scope("mcp:admin", "admin")
.scope("mcp:read", "viewer")
.build();
let mut auth = AuthConfig::with_keys(vec![]);
auth.oauth = Some(oauth);
The OAuth fetcher and the shared
OauthHttpClientenforce a strict per-hop SSRF guard and a fail-closed cap on JWKS key counts. Construct the client viaOauthHttpClient::with_config(&oauth_config)so the configured CA bundle, the SSRF guard, and the HTTPS-downgrade-rejecting redirect policy are all wired in one call. SeeSECURITY.mdfor the trust model.
OAuth in-cluster IdP (private/loopback IdP target, opt-in):
use rmcp_server_kit::oauth::{OAuthConfig, OAuthSsrfAllowlist};
// `OAuthSsrfAllowlist` is `#[non_exhaustive]`; build it via
// `Default::default()` and push into the public fields.
let mut allowlist = OAuthSsrfAllowlist::default();
allowlist.hosts.push("rhbk.ops.example.com".into());
allowlist.cidrs.push("10.0.0.0/8".into());
let oauth = OAuthConfig::builder(
"https://rhbk.ops.example.com/realms/main",
"my-mcp-server",
"https://rhbk.ops.example.com/realms/main/protocol/openid-connect/certs",
)
.ssrf_allowlist(allowlist)
.build();
The default fail-closed SSRF guard blocks targets that resolve into private (RFC 1918), loopback, CGNAT, unique-local, site-local, benchmarking, ORCHID, ORCHIDv2, or RFC 8215 local-use NAT64 space. Use
ssrf_allowlistonly when the IdP legitimately lives there (e.g. a KeycloakServiceClusterIP or local NAT64 gateway). Cloud-metadata addresses (AWS / GCP / Alibaba) remain unbypassable regardless of the allowlist contents, including when embedded in64:ff9b:1::/48using any RFC 6052 layout that fits inside the/48. Seedocs/GUIDE.mdand the "Operator allowlist" subsection ofSECURITY.mdfor the full trust model.
Prometheus metrics on a separate listener:
let config = McpServerConfig::new("127.0.0.1:8080", "my-server", "0.1.0")
.with_metrics("127.0.0.1:9090".parse().unwrap());
TLS:
let config = McpServerConfig::new("127.0.0.1:8443", "my-server", "0.1.0")
.with_tls("/etc/certs/server.crt", "/etc/certs/server.key");
Features
- Transport: Streamable HTTP (
/mcp), health (/healthz,/readyz), admin diagnostics, graceful shutdown, configurable TLS and mTLS. - Auth: API-key (Argon2 hashed), mTLS client certs, OAuth 2.1 JWT validation against JWKS (feature-gated).
- OAuth proxy modes: an optional OAuth proxy in front of your identity
provider, either the 3.20.0 passthrough proxy (default) or the opt-in
authorization_servermode with per-client consent andiss-consistent redirects, plus opt-in MCP authorization features (scope hints, step-up challenge, resource-URL audiences). See docs/OAUTH_PROXY.md for flows, configuration, Keycloak settings and a settings matrix of tested example cases (feature-gated). - RBAC: Tool-scoped allow-lists with per-role argument constraints and
task-local
current_role()/current_identity()accessors. - Observability: Tracing, JSON logs, optional audit-file sink.
- Hardening: Per-IP rate limiting (governor), request-body caps, OWASP security headers, configurable CORS and Host allow-lists.
- Metrics: Prometheus
/metricsendpoint (opt-in viametricsfeature).
Cargo features
test-helpersis not safe in production. It is not part of the stable API surface and carries no semver guarantees across minor releases. Some of the helpers it exposes deliberately bypass SSRF screening, the JWKS refresh cooldown, the CDP discovery rate limiter, the verified path CRL discovery gate, and CRL verifier publication. Enable it only in test and integration builds. See the Cargo features section of the guide for the per-helper detail.
Design decisions
Status: NO-GO. Reviewed and decided; recorded here so the reasoning is not rediscovered. The crate remains fully RFC-conformant without it.
What is missing
RFC 8693 defines two exchange semantics:
Delegation produces an act claim chain, letting a downstream service record
"service X acted for user Y" rather than just "user Y did this". In practice
this crate can only say the latter.
Per RFC 8693 §2.1, actor_token is OPTIONAL, and actor_token_type is
"REQUIRED when the actor_token parameter is present in the request but MUST
NOT be included otherwise." Because both are optional, omitting them is
conformant. This is a missing capability, not a defect.
Why NO-GO
- Already conformant. Nothing is broken; no spec violation exists.
- No user demand. Identified during an internal review, not requested.
- Thin real-world support. Keycloak's delegation support is limited, and Microsoft Entra ID does not use RFC 8693 for its on-behalf-of flow at all.
- The blocker is credential acquisition, not serialization. Delegation needs a token representing the server's own identity. This crate has no client-credentials flow and no way to obtain one. Adding it means a second OAuth client inside the crate - token cache, refresh scheduling, failure policy, SSRF/TLS handling - which is far larger than adding two form parameters.
Revisit criteria
Reopen when all of these are known:
- A named consumer requires delegation, with a concrete audit/compliance use case
- A named authorization server in their stack that actually supports RFC 8693 delegation
- A chosen actor-token acquisition model (see below)
- An expiry/rotation strategy for that credential
If revisited - design notes
Acquisition model. Preferred: an application-supplied async callback -
the application already owns service-identity lifecycle. Explicitly rejected:
reusing the mTLS client_cert identity, which is RFC 8705 §2 client
authentication, not an RFC 8693 actor token.
Known defect in the first sketch. build_exchange_form is synchronous,
so an async token provider cannot be invoked from it. The actor token must be
resolved before form construction, higher in the exchange path. Any future
attempt hits this immediately.
Serde feasibility (verified). TokenExchangeConfig derives
Debug, Clone, Deserialize with #[serde(deny_unknown_fields)] and is
#[non_exhaustive]. A #[serde(skip)] provider field composes correctly and
does not break existing TOML parsing. Clone survives with
Option<Arc<dyn _>>; Debug only survives if the trait itself requires
Debug - note ToolHooks sidesteps this by not deriving Debug.
Mandatory security constraints:
- Store as
secrecy::SecretString; never logged, debug-printed, audited, or included in errors - Least-privilege scope/audience - this is the service identity, so a leak affects every delegated exchange, not one user
- Do not reuse
client_secretas actor proof; client authentication and actor identity are distinct credentials - Stale or expired actor tokens must fail closed
- Preserve the RFC 8693 §2.1 invariant: emit
actor_token_typeiffactor_tokenis present - Preserve byte-identical request output for any config that does not opt into delegation
Status: shipped (minor, additive). Recorded here so the residual
trade-offs are not rediscovered. crl_discovery_rate_per_min gates admission
of new CDP URLs into the CRL fetch pipeline on the mTLS handshake path;
since 3.20.0 only CDP URLs named by the end entity or by intermediates on a
verified path of a presented chain (a path to the configured roots that
verifies, checked before the client proves key possession; revocation not
considered) are admitted. It is now keyed
per source peer IP for attributed handshakes (process-global fallback
when unattributed), which removes the
cross-peer starvation a single global bucket allowed: one peer could drain
the shared budget and fail-closed a concurrent legitimate peer whose
certificate pointed at a not-yet-cached CDP. It is a mitigation, not a
complete DoS defense; the accepted residuals are:
- Per-IP keying does not defeat a distributed attacker. A sprayer using many source IPs cycles through independent per-peer budgets. Each sprayed IP still pays a full TLS handshake and also needs a copy of a valid client chain, matching the default posture of the bearer pre-auth limiter elsewhere in this crate.
- The key is the direct peer IP. Behind a TCP load balancer that terminates the connection, that is the balancer's address, not the client's. Terminate TLS at the edge if you need true client attribution.
- A sprayer controlling more than the ~10k tracked peer keys can cycle into fresh buckets - the tracking map is bounded and idle/LRU-evicts, the same default posture as the pre-auth limiter, and still one full handshake per IP.
- Downstream code constructing
DynamicClientCertVerifieroutside this crate's transport gets the unattributed (global-only) fallback, because the peer-IP task-local is installed only by the scoped TLS accept worker. This is not remotely attacker-selectable: the only production path tonote_discovered_urlsis viaacceptor.acceptin that scoped worker. - The global aggregate rate ceiling for attributed traffic is
intentionally replaced by the per-peer quota plus the bounded discovery
queue, dedup (
crl_max_seen_urls), cache (crl_max_cache_entries), and outbound-fetch (crl_max_concurrent_fetches) caps. Distributed peers can fill the bounded pending set faster than before, but memory and outbound concurrency stay bounded - the discovery receiver processes URLs serially - so the residual is a bounded distributed-DoS, not unbounded amplification.
No config knob was added: the per-peer quota reuses crl_discovery_rate_per_min,
and the tracking-map bounds are private, non-operator-tunable constants, so
rollback is clean and no consumer TOML can depend on the new behaviour. See
SECURITY.md and
docs/MIGRATION.md.
Status: shipped (minor, no opt-out). Recorded here so the trade-off is not rediscovered or "optimized" away.
rustls restores a resumed handshake's peer certificate chain from cached
session state without ever calling ClientCertVerifier::verify_client_cert
- the only place this crate checks CRL revocation, certificate expiry
(
notAfter), and chain validity. Left enabled, a certificate that had since been revoked or expired could keep authenticating for as long as a session stayed resumable, with no log, metric, or audit signal distinguishing that connection from a freshly verified one.TlsListenernow disables the rustls session store and TLS 1.3 ticket emission whenever[mtls]is configured at all - not only when CRL checking is enabled, since non-CRL mTLS still relies onverify_client_certfor expiry and chain validation.
No config knob was added, and none is planned: an opt-out would reintroduce
the exact bypass this closes. The cost is a full handshake on every mTLS
connection instead of a cheaper resumed one where the client would otherwise
have resumed; high-churn clients should use HTTP keep-alive/connection
pooling to amortize it. Plain TLS (no client certificate) is unaffected. See
SECURITY.md and
docs/MIGRATION.md.
Minimum supported Rust
rmcp-server-kit targets stable Rust 1.99 or newer (tracks edition = "2024").
Repository
- GitHub (canonical): https://github.com/andrico21/rmcp-server-kit
The canonical release artifact is the rmcp-server-kit crate on crates.io.
License
Dual-licensed under either of:
- Apache License, Version 2.0 (LICENSE-APACHE or https://www.apache.org/licenses/LICENSE-2.0)
- MIT license (LICENSE-MIT or https://opensource.org/licenses/MIT)
at your option.
Contribution
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual-licensed as above, without any additional terms or conditions.