Introduction
mcp-server-core is a Rust crate for building Model Context Protocol (MCP) servers that clients such as claude.ai, Claude Desktop and Claude Code reach over the internet. You write the tools; the crate serves them over Streamable HTTP with sign-in, TLS and the protections a server shared by many people needs.
It is built on rmcp, the official Rust SDK for MCP, and re-exports it, so your tools are ordinary rmcp tools.
| Crate | crates.io/crates/mcp-server-core |
| API documentation | docs.rs/mcp-server-core |
| Source | github.com/Trozz/mcp-server-core-rs |
| Licence | MIT or Apache-2.0, at your option |
Who it is for
You have, or want to write, MCP tools in Rust: a wrapper around an API, your own data, a device on your network. You want claude.ai or another hosted client to use them, which means a public HTTPS endpoint that signs people in with OAuth. That part is where the risk lies: an MCP server on the internet acts on someone’s behalf, and anyone can reach its sign-in page.
This crate is that part, extracted from the two servers built on it, which each carried a copy of the code. It suits:
- A personal server: one person, the owner, signs in with a password, and the tools use the server’s own access to an upstream service, such as an app password in the environment.
- A shared server: many people each sign in with their own key for the upstream API, and the tools act with that person’s key. The server stores no keys.
What you write and what you get
| You write | The crate gives you |
|---|---|
Your tools, as an rmcp handler with #[tool] methods, each marked read-only or not | Streamable HTTP serving, a new handler for each MCP session, and, when people sign in with their own credentials, sessions bound to the credential that opened them |
A Service: a name and the handler | The service at /<name>, its own OAuth protected resource, and its tools on the combined /mcp endpoint |
| A factory that reads your service’s settings | The server’s own settings, _FILE variants for secrets, and every configuration error reported at once |
| Optionally, a check of a person’s upstream credential | The sign-in page, OAuth 2.1, sealed credentials handed to your tools, and limits on guessing |
main: a Server with your services | --version, --help, --healthcheck, TLS, logs, metrics, traces and graceful shutdown |
The smallest server is about sixty lines; see the quick start.
Features
- OAuth 2.1 built in: dynamic client registration, PKCE (S256), resource indicators (RFC 8707) and protected-resource metadata (RFC 9728). Every token is a signed JWT, so there is no database, and restarts and extra replicas sign nobody out. See OAuth and tokens.
- Two ways to sign in: the owner’s password, or each person’s own credential for the upstream service, checked when they sign in and sealed into their tokens. You can also supply your own check. See Sign-in modes.
- Several services on one server, each at
/<name>and each its own OAuth resource, plus all of their tools and prompts together at/mcpas<service>_<tool>. See Several services and /mcp and Prompts. - Read-only mode and an audit log for every service, from each tool’s
read_only_hint. See Read-only mode and the audit log. - Abuse limits: sign-in attempts limited per address, per network block and overall, capped and shared upstream credential checks, capped client registration, sessions capped per credential, body limits. See Limits and abuse protection.
- Ready to deploy: TLS from certificate files (reloaded when they change), a self-signed certificate, or plain HTTP behind a proxy; Host and Origin checks against DNS rebinding; a container healthcheck; graceful shutdown. See TLS and deployment.
- Observability: JSON logs that keep secrets and content out, Prometheus metrics and OpenTelemetry traces. See Observability.
- Configured by environment variables, with
_FILEvariants for secrets and every error reported at once. See the configuration reference.
How people sign in
You choose one sign-in mode for the whole server with Server::sign_in:
| Mode | Who signs in | What your tools get |
|---|---|---|
SignIn::OwnerPassword (the default) | One person, with OAUTH_ADMIN_PASSWORD. A static bearer token, MCP_AUTH_TOKEN, can be set as well for clients that cannot do OAuth. | Nothing about the person: tools act with the server’s own upstream configuration. |
SignIn::ServiceCredential | Anyone with a credential the upstream service accepts, such as an API key, checked by your service’s verifier. | The person’s credential, sealed inside their tokens and handed to tools on every request. Clients may also send the credential itself as their bearer token. |
SignIn::Custom(..) | Whoever your own verifier accepts. | Either, depending on the verifier. |
Every request a tool receives also says who signed in and how. Sign-in modes covers all of this; for single sign-on, MFA or many named users, it explains how to put an identity-aware gateway in front of the sign-in page instead.
Who uses it
Two open-source servers are built on mcp-server-core, one for each sign-in model:
| Server | What it does | Sign-in |
|---|---|---|
| mcp-icloud | iCloud mail, calendars and contacts, as services /mail, /calendar and /contacts | The owner’s password; the server holds the owner’s app-specific password for Apple |
| mcp-companies-house | The UK Companies House register: companies, officers, owners, filings and charges | Each person’s own Companies House API key; the server holds none |
Both are larger examples of what this site describes. The repository’s own examples are small versions of the same two shapes.
How this site is organised
| Section | Pages |
|---|---|
| Getting started | Quick start, Writing a service, Several services and /mcp, Prompts, Examples |
| Signing people in | Sign-in modes, OAuth and tokens, Connecting clients |
| Running a server | Configuration reference, TLS and deployment, Read-only mode and the audit log, Observability, Troubleshooting |
| Security | Security model, Limits and abuse protection |
| Reference | Endpoints, Lower-level API, Changelog |
| Project | Architecture, Contributing, Releases and versioning |
If you are new, read the quick start, then Writing a service. If you are deploying a server someone else wrote, start at the configuration reference and TLS and deployment. The API documentation on docs.rs has every public item; this site explains how they fit together.
Requirements
- Rust 1.88 or later.
- A Tokio runtime:
Server::mainisasync. - rmcp through the re-export
mcp_server_core::rmcp, withuse mcp_server_core::rmcp;in each file that uses its macros (see the quick start). Its types appear in this crate’s API, so this crate follows rmcp’s minor versions; see Releases and versioning.
Licence
mcp-server-core is licensed under either of the Apache License, Version 2.0 or the MIT licence, at your option. Unless you state otherwise, any contribution you submit for inclusion is dual licensed in the same way, without any additional terms or conditions.
Quick start
This page takes you from an empty crate to an MCP server running on your machine, with Claude Code connected to it.
Add the crate
In a new binary crate (cargo new mcp-hello), add the crate, Tokio and serde:
cargo add mcp-server-core
cargo add tokio --features macros,rt-multi-thread
cargo add serde --features derive
The serde crate is not needed by the server below, but every tool with arguments derives Deserialize, so you will want it soon. Use rmcp through the crate’s re-export, mcp_server_core::rmcp, rather than adding it yourself: its types appear in this crate’s API, so the versions must match.
rmcp’s macros (#[tool_router], #[tool_handler], #[prompt_router] and the rest) generate code that names the crate rmcp. Without rmcp in your own Cargo.toml, that name only resolves if you bring the re-export into scope under it, so every file that uses the macros has use mcp_server_core::rmcp; among its use lines, as below.
The smallest server
A service is a name and an rmcp handler; the Server builder does the rest. Put this in src/main.rs:
// rmcp's macros name the crate `rmcp`: this makes that name the re-export.
use mcp_server_core::rmcp;
use mcp_server_core::app::{Server, SignIn};
use mcp_server_core::combined::DynHandler;
use mcp_server_core::rmcp::handler::server::router::tool::ToolRouter;
use mcp_server_core::rmcp::model::{CallToolResult, ContentBlock, ServerCapabilities, ServerConfig};
use mcp_server_core::rmcp::{ErrorData as McpError, ServerHandler, tool, tool_handler, tool_router};
use mcp_server_core::service::{Service, ServiceEnv};
use std::sync::Arc;
/// The MCP handler: one per MCP session.
#[derive(Clone)]
struct Hello {
tool_router: ToolRouter<Self>,
}
#[tool_router]
impl Hello {
fn new() -> Self {
Self { tool_router: Self::tool_router() }
}
#[tool(description = "Say hello.", annotations(read_only_hint = true))]
async fn hello(&self) -> Result<CallToolResult, McpError> {
Ok(CallToolResult::success(vec![ContentBlock::text("Hello from mcp-hello.")]))
}
}
#[tool_handler(router = self.tool_router)]
impl ServerHandler for Hello {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
}
}
/// The service, mounted at `/hello`.
struct HelloService;
impl Service for HelloService {
fn name(&self) -> &'static str {
"hello"
}
fn handler(&self) -> DynHandler {
DynHandler::new(Hello::new())
}
// Only used for the startup log.
fn tool_names(&self) -> Vec<String> {
vec!["hello".into()]
}
}
/// Reads the service's own configuration (none here) and builds it.
fn hello(_env: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
Some(Arc::new(HelloService))
}
#[tokio::main]
async fn main() -> std::process::ExitCode {
Server::new("mcp-hello", env!("CARGO_PKG_VERSION"))
.env_prefix("HELLO")
.service("hello", hello)
.sign_in(SignIn::OwnerPassword)
.main()
.await
}
The pieces, from the top:
| Piece | What it is |
|---|---|
Hello | An ordinary rmcp handler. #[tool_router] collects the #[tool] methods and #[tool_handler] answers tools/list and tools/call from them. |
read_only_hint = true | Marks hello as a tool that only reads. The server uses it for read-only mode and the audit log; a tool without it counts as a write. |
HelloService | Implements Service: a name, which becomes the path /hello, and a handler for each MCP session. |
hello | A service factory. It receives the environment reader so a service can read its own variables, and returns None when it cannot start. |
Server | Builds the binary: --version, --help and --healthcheck, configuration, logging, OAuth, TLS and serving. env_prefix("HELLO") names this server’s own variables HELLO_SERVICES, HELLO_READ_ONLY and HELLO_COMBINED. |
Writing a service covers each of these in full.
Run it locally
Everything is configured with environment variables. For a first run on your own machine:
PUBLIC_URL=http://localhost:8443 INSECURE_HTTP=true \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) OAUTH_ADMIN_PASSWORD='a long password' \
LOG_FORMAT=pretty cargo run
| Variable | Why |
|---|---|
PUBLIC_URL | The URL clients use, without a path. It must be https://, except for localhost, 127.0.0.1 and [::1], where http:// is allowed. |
INSECURE_HTTP=true | Serve plain HTTP, to match the http:// URL. Without it the server serves HTTPS with a self-signed certificate it generates at startup. |
OAUTH_SIGNING_KEY | Signs every token; at least 32 bytes. A new key signs everyone out, so the $(openssl rand -hex 32) above signs clients out on each restart. For longer use, generate one once and keep it, for example in a file named by OAUTH_SIGNING_KEY_FILE. |
OAUTH_ADMIN_PASSWORD | The owner’s password for the sign-in page: at least 12 characters, and not only spaces. Shorter than 15 gets a warning at startup. |
LOG_FORMAT=pretty | Readable logs instead of JSON. |
The server listens on 0.0.0.0:8443 (change it with BIND_ADDR). The startup log says what it is serving, in this order:
| Message | Fields |
|---|---|
starting mcp-hello | version |
service enabled, once per service | service, url (http://localhost:8443/hello), read_only, tools (from tool_names) |
combined endpoint enabled | url (http://localhost:8443/mcp), tools (how many) |
listening | addr |
INSECURE_HTTP=true: serving plaintext HTTP without TLS (a warning) | addr |
Any warnings about weak settings, such as a short password, come straight after starting.
The service is at http://localhost:8443/hello, and every service’s tools together are at http://localhost:8443/mcp, where hello is called hello_hello (see Several services and /mcp).
If something is missing or wrong, the server prints every problem at once and exits with status 1, without starting:
configuration error: PUBLIC_URL is required
configuration error: OAUTH_SIGNING_KEY must be at least 32 bytes
configuration error: OAUTH_ADMIN_PASSWORD is required
The configuration reference lists every variable, and Troubleshooting every startup error.
Check it is running
/healthz needs no authentication and answers ok:
curl http://localhost:8443/healthz
The binary checks itself the same way, which is what a container HEALTHCHECK runs. Run it with the same environment as the server, since it reads BIND_ADDR and INSECURE_HTTP:
INSECURE_HTTP=true cargo run -- --healthcheck && echo healthy
cargo run -- --version
--healthcheck requests /healthz on 127.0.0.1 at the BIND_ADDR port, over TLS unless INSECURE_HTTP is set, and exits 0 on a 200. --version prints mcp-hello 0.1.0.
Connect Claude Code
Claude Code can sign in with OAuth, but the quickest way on your own machine is the static token, MCP_AUTH_TOKEN: a fixed bearer token accepted on every path. Stop the server, choose a token and start it again with the token set:
export MCP_AUTH_TOKEN=$(openssl rand -hex 32)
PUBLIC_URL=http://localhost:8443 INSECURE_HTTP=true \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) OAUTH_ADMIN_PASSWORD='a long password' \
LOG_FORMAT=pretty cargo run
Then, in another terminal with the same MCP_AUTH_TOKEN:
claude mcp add --transport http hello http://localhost:8443/hello \
--header "Authorization: Bearer $MCP_AUTH_TOKEN"
Start claude and ask it to say hello with the hello tool. The static token has rules of its own:
- It must not have the shape of a JWT (three dot-separated parts), or the server refuses to start.
- One shorter than 32 characters gets a warning at startup.
openssl rand -hex 32gives 64. - It cannot be used when people sign in with their own credential, as with
SignIn::ServiceCredential: the server refuses to start. - Wrong tokens count towards the sign-in limits, which bounds how fast anyone can guess it.
Leave out --header and Claude Code signs in with OAuth instead: it registers itself, opens the sign-in page in your browser, and you enter OAUTH_ADMIN_PASSWORD. Sign-in modes explains the other ways to sign in, and Connecting clients covers Claude Code and other clients in full.
You can also talk to the server with curl. An initialize request answers with an mcp-session-id header and a short server-sent event stream whose last data: line holds the result:
curl -i http://localhost:8443/hello \
-H "Authorization: Bearer $MCP_AUTH_TOKEN" \
-H 'Content-Type: application/json' \
-H 'Accept: application/json, text/event-stream' \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}'
Without the Authorization header the answer is 401 with a WWW-Authenticate header naming http://localhost:8443/.well-known/oauth-protected-resource/hello, which is how MCP clients find the sign-in flow.
Why claude.ai needs more
claude.ai connects from Anthropic’s servers, not from your machine, so it cannot reach localhost, and it only accepts a certificate it trusts. To add the server as a claude.ai custom connector, run it at a public https:// address: with a certificate from files (Let’s Encrypt works), or with INSECURE_HTTP=true behind a reverse proxy or tunnel that terminates TLS, with TRUSTED_PROXIES set to the proxy’s address. A self-signed certificate is not enough: claude.ai does not trust it. TLS and deployment shows both setups.
Next steps
- Writing a service: tools with arguments, reading configuration, the caller’s credential, and the rest of the
Serverbuilder. - Examples: two complete servers in the repository, one for the owner and one shared by many people.
- Sign-in modes: let each person sign in with their own API key for the upstream service.
- TLS and deployment: put the server on the internet.
Writing a service
This page covers everything you write yourself: the Service trait, the factory that reads a service’s configuration, tools written with rmcp, how a tool finds out who is calling, and the Server builder that turns services into a binary.
The examples build one service, tasks, a small task list that talks to an imaginary upstream API.
The parts
| You write | It is | The server does with it |
|---|---|---|
| An rmcp handler | A type implementing rmcp’s ServerHandler, usually with #[tool_router] | Serves it over Streamable HTTP, one instance per MCP session |
A Service | A name and a way to make a handler | Mounts it at /<name>, makes it an OAuth protected resource, adds its tools to /mcp |
A ServiceFactory | fn(&mut ServiceEnv) -> Option<Arc<dyn Service>> | Calls it at startup when the service is selected, so the service reads its own variables |
main | A Server with your services | Reads the configuration, signs people in, serves |
The Service trait
Service is Send + Sync + 'static. Only name and handler are required:
| Method | Default | Purpose |
|---|---|---|
fn name(&self) -> &'static str | required | The path segment, OAuth resource suffix and scope, and the prefix on /mcp. See Names. |
fn handler(&self) -> DynHandler | required | A new MCP handler. Called once per MCP session, on /<name> and on /mcp. |
fn router(self: Arc<Self>, ctx: &ServiceContext) -> axum::Router | serves handler() with mcp_service | The Streamable HTTP service mounted at /<name>. Override it to serve resources or to do work when the service is mounted. |
fn tool_names(&self) -> Vec<String> | none | Tool names for the startup log. They change nothing that is served. |
fn log_caps(&self) -> &'static [&'static str] | none | Tracing targets, usually dependencies, kept at info or below whatever LOG_LEVEL says, because their debug output could leak secrets. |
fn credential_verifier(&self) -> Option<Arc<dyn CredentialVerifier>> | None | How people sign in with their own credential for this service’s upstream, with SignIn::ServiceCredential. |
A service with every method written out:
#![allow(unused)]
fn main() {
use mcp_server_core::axum::Router;
use mcp_server_core::combined::DynHandler;
use mcp_server_core::credential::CredentialVerifier;
use mcp_server_core::service::{Service, ServiceContext, mcp_service};
use std::sync::Arc;
use mcp_server_core::rmcp::ServerHandler;
#[derive(Clone)]
struct TasksTools;
impl TasksTools { fn new(_: Arc<String>) -> Self { TasksTools } }
impl ServerHandler for TasksTools {}
struct TasksService {
/// Shared by every session: clone it into each handler.
api_url: Arc<String>,
}
impl Service for TasksService {
fn name(&self) -> &'static str {
"tasks"
}
fn handler(&self) -> DynHandler {
DynHandler::new(TasksTools::new(self.api_url.clone()))
}
// The default, written out.
fn router(self: Arc<Self>, ctx: &ServiceContext) -> Router {
mcp_service(ctx, move || Ok(self.handler()))
}
fn tool_names(&self) -> Vec<String> {
vec!["add_task".into(), "list_tasks".into()]
}
fn log_caps(&self) -> &'static [&'static str] {
&["hyper", "reqwest"]
}
fn credential_verifier(&self) -> Option<Arc<dyn CredentialVerifier>> {
None
}
}
}
Names
A service name is used as the path (/tasks), the OAuth resource (PUBLIC_URL/tasks) and its scope, the tool prefix on /mcp (tasks_add_task) and the service field of the audit log. So it must be:
- lowercase ASCII letters, digits and
-, and not empty._is not allowed because/mcpsplits a prefixed name at its first_; - not
mcp, which is the combined endpoint; - unique within the server.
Server::service checks these when you register the service and panics, so a bad name fails the first time you run the binary:
| Name | Panic message |
|---|---|
my_service | service name "my_service" must be lowercase letters, digits and '-' |
mcp | service name "mcp" is reserved for the combined endpoint |
| registered twice | service "tasks" is registered twice |
The service the factory returns must report the name it was registered under. Otherwise startup stops with the service registered as tasks is named todo.
The handler
handler runs once for every MCP session, on the service’s own path and again on /mcp, so keep it cheap: clone Arcs into a new handler and do the real work in tools. State shared by every session, such as an HTTP client, a cache or a connection pool, lives in the Service and is cloned into each handler.
DynHandler boxes any rmcp ServerHandler, so services with different handler types fit in one server. It forwards the server information (initialize), tools and prompts: get_info, get_tool, list_tools, call_tool, list_prompts and get_prompt. Tools and prompts are listed in one page. Everything else, such as resources and completions, is not forwarded.
Overriding the router
The default router serves handler(), which carries tools and prompts. Override it when you need more:
- Resources. Serve your concrete handler type with
mcp_service, so rmcp sees all of its methods. Resources are served on the service’s own path only, never on/mcp. - Work at mount time, such as logging the service’s settings or warming a cache.
routerruns once, when the server mounts the service.
#![allow(unused)]
fn main() {
use mcp_server_core::axum::Router;
use mcp_server_core::combined::DynHandler;
use mcp_server_core::service::{Service, ServiceContext, mcp_service};
use std::sync::Arc;
use mcp_server_core::rmcp::ServerHandler;
#[derive(Clone)]
struct TasksTools;
impl TasksTools { fn new(_: Arc<String>) -> Self { TasksTools } }
impl ServerHandler for TasksTools {}
struct TasksService {
api_url: Arc<String>,
}
impl Service for TasksService {
fn name(&self) -> &'static str {
"tasks"
}
fn handler(&self) -> DynHandler {
DynHandler::new(TasksTools::new(self.api_url.clone()))
}
fn router(self: Arc<Self>, ctx: &ServiceContext) -> Router {
// Runs once, when the service is mounted: warm caches or log settings here.
let api_url = self.api_url.clone();
// The concrete type, not DynHandler, so resources are served too.
mcp_service(ctx, move || Ok(TasksTools::new(api_url.clone())))
}
}
}
The read-only rule and the audit log still apply to an overridden router: the server attaches the service’s policy to the router it returns, and mcp_service wraps every handler it makes. mcp_service also adds the Host and Origin checks, the request body limit and session binding; see Lower-level API for using it on its own.
Log caps
log_caps names tracing targets whose debug or trace output could reveal secrets, typically an HTTP client that logs request headers. Each target and its children are capped at info, and never raised above what LOG_LEVEL sets for everything. With reqwest capped as above, LOG_LEVEL=trace still cannot make it log at trace. See Observability.
Sign-in
With SignIn::ServiceCredential, people sign in with their own credential for the upstream service, and the server asks the enabled service that returns a verifier from credential_verifier. Exactly one enabled service may return one:
- none, with at least one service enabled, stops startup with
no enabled service defines how people sign in; - two or more stop it with
more than one enabled service defines how people sign in (<names>): enable one of them, because each service’s tools would receive a credential meant for another upstream.
With the other sign-in modes credential_verifier is not asked. See Only one service may define sign-in.
Service factories
A ServiceFactory is a plain function:
#![allow(unused)]
fn main() {
use mcp_server_core::service::{Service, ServiceEnv};
use std::sync::Arc;
type ServiceFactory = fn(&mut ServiceEnv) -> Option<Arc<dyn Service>>;
}
The server calls the factory of each selected service once at startup: in registration order, or, when <PREFIX>_SERVICES is set, in the order that variable names them. A service that is not selected (see <PREFIX>_SERVICES in the configuration reference) never has its factory called, so its variables are not read and a missing one does not stop the server. The factory records every problem in env.errors and returns None when the service cannot start.
Reading configuration with ServiceEnv
ServiceEnv is an EnvReader over the process environment. It reads every variable the same way as the server’s own:
- An empty value counts as unset.
- Any variable can come from a file instead:
TASKS_API_KEY_FILE=/run/secrets/tasksreadsTASKS_API_KEYfrom that file, without its trailing newline (\nor\r\n). A value set directly wins over the file. - Problems are pushed to
env.errorsinstead of returned, so one start reports all of them.
| Method | Returns | Behaviour and error message |
|---|---|---|
optional(name) | Option<String> | The value, or the contents of the file named by <name>_FILE. An unreadable file records <name>_FILE: cannot read <path>: <reason>. |
required(name) | Option<String> | Like optional; when neither is set it records <name> is required. |
secret_optional(name) | Option<SecretString> | optional as a secrecy::SecretString, which never prints its value. |
secret_required(name) | Option<SecretString> | required as a SecretString. |
bool(name, default) | bool | 1, true, yes, on or 0, false, no, off, in any case. Anything else records <name> must be true or false, got "<value>" and returns default. |
parse(name, default) | T: FromStr | default when unset. A value that does not parse records <name> has an invalid value and returns default. |
parse_optional(name) | Option<T> | Like parse, without a default. |
list(name) | Vec<String> | A comma-separated list, each entry trimmed, empty entries dropped. Unset is an empty list. |
ServiceEnv::new(get) | ServiceEnv | A reader over your own lookup function, for tests. |
errors | Vec<String> | Every problem so far, as messages for the operator. Only bool quotes the value it could not read, and the _FILE error names the file’s path; the other messages name only the variable, so secrets stay out of them. |
To read a SecretString you need the secrecy crate (cargo add secrecy) for its ExposeSecret trait.
A configuration reader for the tasks service, and a test of it:
#![allow(unused)]
fn main() {
use mcp_server_core::service::ServiceEnv;
use secrecy::{ExposeSecret, SecretString};
use std::collections::HashMap;
use std::time::Duration;
struct TasksConfig {
api_url: String,
api_key: SecretString,
timeout: Duration,
projects: Vec<String>,
archive_done: bool,
}
/// Reads every variable first, so every problem is recorded, then gives up if there were any.
fn tasks_config(env: &mut ServiceEnv) -> Option<TasksConfig> {
let before = env.errors.len();
let api_url = env
.optional("TASKS_API_URL")
.unwrap_or_else(|| "https://api.example.com".into());
if !api_url.starts_with("https://") {
env.errors.push("TASKS_API_URL must be an https URL".into());
}
let api_key = env.secret_required("TASKS_API_KEY");
let timeout = Duration::from_secs(env.parse("TASKS_TIMEOUT_SECS", 10));
let projects = env.list("TASKS_PROJECTS");
let archive_done = env.bool("TASKS_ARCHIVE_DONE", false);
if env.errors.len() > before {
return None;
}
Some(TasksConfig { api_url, api_key: api_key?, timeout, projects, archive_done })
}
// Three mistakes, all reported by one start.
let vars: HashMap<String, String> = [
("TASKS_API_URL", "http://api.example.com"),
("TASKS_TIMEOUT_SECS", "soon"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
let mut env = ServiceEnv::new(Box::new(move |k: &str| vars.get(k).cloned()));
assert!(tasks_config(&mut env).is_none());
assert_eq!(
env.errors,
[
"TASKS_API_URL must be an https URL",
"TASKS_API_KEY is required",
"TASKS_TIMEOUT_SECS has an invalid value",
]
);
// A good configuration, with the key from the environment.
let vars: HashMap<String, String> = [
("TASKS_API_KEY", "tk_live_0123"),
("TASKS_PROJECTS", "home, work,,"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
let mut env = ServiceEnv::new(Box::new(move |k: &str| vars.get(k).cloned()));
let config = tasks_config(&mut env).expect("valid");
assert_eq!(config.api_url, "https://api.example.com");
assert_eq!(config.api_key.expose_secret(), "tk_live_0123");
assert_eq!(config.timeout, Duration::from_secs(10));
assert_eq!(config.projects, ["home", "work"]);
assert!(!config.archive_done);
}
The factory then builds the service from it:
#![allow(unused)]
fn main() {
use mcp_server_core::combined::DynHandler;
use mcp_server_core::rmcp::ServerHandler;
use mcp_server_core::service::{Service, ServiceEnv};
use std::sync::Arc;
#[derive(Clone)] struct Tools;
impl ServerHandler for Tools {}
struct TasksConfig;
fn tasks_config(_: &mut ServiceEnv) -> Option<TasksConfig> { Some(TasksConfig) }
struct TasksService { config: Arc<TasksConfig> }
impl Service for TasksService {
fn name(&self) -> &'static str { "tasks" }
fn handler(&self) -> DynHandler { DynHandler::new(Tools) }
}
fn tasks(env: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
let config = tasks_config(env)?;
Some(Arc::new(TasksService { config: Arc::new(config) }))
}
}
Every error at once
Server::load reads the core variables, the sign-in settings, the server’s own <PREFIX>_ variables and AUDIT_LOG_PATH, and then each selected service’s, all into the same ServiceEnv. When anything was recorded, the binary prints each problem on its own line and exits with status 1 without starting:
configuration error: OAUTH_SIGNING_KEY must be at least 32 bytes
configuration error: TASKS_API_URL must be an https URL
configuration error: TASKS_API_KEY is required
Each message is printed once, so two services reading the same variable do not report it twice. Name your variables after the service (TASKS_…) unless two services share them on purpose. The configuration reference lists the server’s own variables.
Writing tools with rmcp
Tools are ordinary rmcp tools. Use rmcp through the re-export, mcp_server_core::rmcp, so the versions match.
#![allow(unused)]
fn main() {
use mcp_server_core::rmcp;
use mcp_server_core::rmcp::handler::server::router::tool::ToolRouter;
use mcp_server_core::rmcp::handler::server::wrapper::Parameters;
use mcp_server_core::rmcp::model::{CallToolResult, ContentBlock, ServerCapabilities, ServerConfig};
use mcp_server_core::rmcp::schemars::{self, JsonSchema};
use mcp_server_core::rmcp::{ErrorData as McpError, ServerHandler, tool, tool_handler, tool_router};
use serde::Deserialize;
use std::sync::{Arc, Mutex};
/// One instance per MCP session; the task list is shared.
#[derive(Clone)]
struct TasksTools {
tasks: Arc<Mutex<Vec<String>>>,
tool_router: ToolRouter<Self>,
}
#[derive(Deserialize, JsonSchema)]
struct AddTask {
/// What needs doing.
title: String,
/// When it is due, as YYYY-MM-DD.
due: Option<String>,
}
#[tool_router]
impl TasksTools {
fn new(tasks: Arc<Mutex<Vec<String>>>) -> Self {
Self { tasks, tool_router: Self::tool_router() }
}
#[tool(description = "List the open tasks.", annotations(read_only_hint = true))]
async fn list_tasks(&self) -> Result<CallToolResult, McpError> {
let text = self.tasks.lock().unwrap().join("\n");
Ok(CallToolResult::success(vec![ContentBlock::text(text)]))
}
#[tool(
description = "Add a task.",
annotations(read_only_hint = false, destructive_hint = false, idempotent_hint = false)
)]
async fn add_task(
&self,
Parameters(AddTask { title, due }): Parameters<AddTask>,
) -> Result<CallToolResult, McpError> {
if title.trim().is_empty() {
// `kind: message`: the audit log records the kind.
return Ok(CallToolResult::error(vec![ContentBlock::text(
"invalid_argument: title is empty",
)]));
}
let entry = match due {
Some(due) => format!("{title} (due {due})"),
None => title,
};
self.tasks.lock().unwrap().push(entry);
Ok(CallToolResult::success(vec![ContentBlock::text("added")]))
}
}
#[tool_handler(router = self.tool_router)]
impl ServerHandler for TasksTools {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_instructions("Keeps a task list. Dates are YYYY-MM-DD.")
}
}
}
use mcp_server_core::rmcp;is needed in every file that uses rmcp’s macros: they generate code that names the cratermcp, which otherwise only resolves when rmcp is in your ownCargo.toml.#[tool_router]collects the#[tool]methods of theimplblock into aToolRouter, and#[tool_handler]answerstools/listandtools/callfrom it.- Arguments are one
Parameters<T>whoseTderivesDeserializeandJsonSchema. Doc comments on its fields become the descriptions in the tool’s input schema. Importschemarsfrommcp_server_core::rmcpas above so the derive finds it. get_infodeclares the capabilities and the instructions clients show the model. On/mcpeach service’s instructions appear under its name; see Several services and /mcp.
Annotations
rmcp’s annotations(...) sets the MCP tool annotations clients see:
| Annotation | Used by this crate | Meaning to clients |
|---|---|---|
read_only_hint | yes | The tool does not change anything |
destructive_hint | no | A write may delete or overwrite, not only add |
idempotent_hint | no | Repeating a call with the same arguments changes nothing more |
open_world_hint | no | The tool reaches beyond a closed set of data, such as the web |
title | no | A display name |
The server reads only read_only_hint. A tool marked read_only_hint = true is a read. Every other tool, including one with no annotations at all, is a write: it is hidden and refused on a read-only service, and every call to it, made or refused, is written to the audit log. Mark every tool explicitly. See Read-only mode and the audit log.
Results and errors
| You return | Client sees | Audit outcome, error_kind (writes only) |
|---|---|---|
Ok(CallToolResult::success(..)) | A result | ok, none |
Ok(CallToolResult::error(..)) whose first text starts kind: | A tool error the model can read and act on | error, the kind |
Ok(CallToolResult::error(..)) without that prefix | A tool error | error, none |
Err(McpError) | A JSON-RPC error | error, protocol |
A kind is lowercase ASCII letters and _, followed by : , such as not_found: no task with that id or conflict: the task changed since you read it. Prefer tool errors over Err for anything the model could fix, such as a bad argument: a tool error reaches the model as the call’s result, while a JSON-RPC error may not.
Who is calling
The bearer guard in front of each service puts what it knows about the caller in the HTTP request’s extensions, and rmcp passes the request’s Parts to tools that ask for them with an Extension<Parts> argument. This works the same on the service’s own path and on /mcp.
| Extension | Type | Present when |
|---|---|---|
| The caller | caller::Caller | Every request that reached the service |
| The person’s credential | credential::Credential | The verifier carries credentials, as with SignIn::ServiceCredential: from a sealed OAuth token or a credential sent directly as the bearer token |
| The token’s claims | jwt::Claims | The request used one of this server’s OAuth access tokens |
Caller has two fields:
subject: who signed in.ownerfor the owner’s password,key:and 16 hex digits for a person’s own credential (a keyed hash, never the credential),staticfor the static token, or what a custom verifier names. The audit log records it.via: how the request was authenticated, aVia:OAuth { client_id },Credential(sent directly as the bearer token) orStaticToken.
Credential::expose gives the secret to send upstream; its Debug output never shows it. Never log it.
#![allow(unused)]
fn main() {
use mcp_server_core::rmcp;
use mcp_server_core::axum::http::request::Parts;
use mcp_server_core::caller::{Caller, Via};
use mcp_server_core::credential::Credential;
use mcp_server_core::rmcp::handler::server::router::tool::ToolRouter;
use mcp_server_core::rmcp::handler::server::tool::Extension;
use mcp_server_core::rmcp::model::{CallToolResult, ContentBlock};
use mcp_server_core::rmcp::{ErrorData as McpError, ServerHandler, tool, tool_handler, tool_router};
#[derive(Clone)]
struct AccountTools {
tool_router: ToolRouter<Self>,
}
#[tool_router]
impl AccountTools {
#[tool(description = "Say who is calling.", annotations(read_only_hint = true))]
async fn whoami(&self, Extension(parts): Extension<Parts>) -> Result<CallToolResult, McpError> {
let caller = parts.extensions.get::<Caller>();
let subject = caller.map_or("unknown", |c| c.subject.as_str());
// `Via` is #[non_exhaustive]: keep a catch-all arm.
let how = match caller.map(|c| &c.via) {
Some(Via::OAuth { client_id: Some(id) }) => format!("OAuth client {id}"),
Some(Via::OAuth { client_id: None }) => "OAuth".to_string(),
Some(Via::Credential) => "a credential sent as the bearer token".to_string(),
Some(Via::StaticToken) => "the static token".to_string(),
_ => "an unknown way".to_string(),
};
let key = match parts.extensions.get::<Credential>() {
// Send `c.expose()` upstream; never log it.
Some(c) => format!("a key of {} characters", c.expose().len()),
None => "no key of their own".to_string(),
};
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"{subject}, through {how}, with {key}."
))]))
}
}
#[tool_handler(router = self.tool_router)]
impl ServerHandler for AccountTools {}
}
On an owner’s-password server there is no Credential: tools use the server’s own upstream configuration, read by the factory. Who made a request and Subjects explain callers and subjects in full, and Sealed credentials how the credential travels.
ServiceContext and HttpSettings
router receives a ServiceContext:
| Field | Type | Holds |
|---|---|---|
http | HttpSettings | What mcp_service needs for its Host and Origin checks |
shutdown | tokio_util::sync::CancellationToken | Cancelled on Ctrl-C or SIGTERM. Watch it to stop a background task you started in router. |
HttpSettings has three fields, built from the core configuration with HttpSettings::from_core(&core):
| Field | Holds |
|---|---|
public_url | PUBLIC_URL without a trailing slash, such as https://mcp.example.com |
public_host | Its host, such as mcp.example.com (IPv6 without brackets) |
allowed_origins | ALLOWED_ORIGINS |
The Server builder
app::Server turns services into a binary. A complete main:
use mcp_server_core::app::{Server, SignIn};
use mcp_server_core::axum::{Router, routing::get};
use mcp_server_core::service::{Service, ServiceEnv};
use std::sync::Arc;
fn tasks(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> { None }
fn calendar(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> { None }
const ICON_PNG: &[u8] = b"";
const ICON_SVG: &str = "<svg/>";
/// Extra routes, outside every service.
fn extras(app: Router) -> Router {
app.route("/version", get(|| async { env!("CARGO_PKG_VERSION") }))
}
#[tokio::main]
async fn main() -> std::process::ExitCode {
Server::new("mcp-planner", env!("CARGO_PKG_VERSION"))
.env_prefix("PLANNER")
.crate_target("mcp_planner")
.services(&[("tasks", tasks), ("calendar", calendar)])
.sign_in(SignIn::OwnerPassword)
.icon(ICON_PNG, ICON_SVG)
.docs_url("https://example.com/mcp-planner")
.wrap_router(extras)
.main()
.await
}
Every public method:
| Method | Default | What it does |
|---|---|---|
Server::new(name, version) | A server called name, used in logs, as the OpenTelemetry service name, in --version and --help, and as the /mcp endpoint’s serverInfo. | |
.env_prefix(prefix) | MCP | The prefix of <PREFIX>_SERVICES, <PREFIX>_COMBINED and <PREFIX>_READ_ONLY. Upper-cased, with trailing _ removed: "my_app_" gives MY_APP_SERVICES. |
.crate_target(target) | name with - replaced by _ | The tracing target prefix of your crates, raised to debug by DEBUG=true (or DEBUG_UNSAFE_LOG_CONTENT=true). With mcp_planner, mcp_planner_api::client is covered too. |
.service(name, factory) | Registers a service at /<name>. Services are mounted, and their tools listed on /mcp, in registration order, or in the order <PREFIX>_SERVICES names them when it is set. Panics on a bad or repeated name. | |
.services(&[(name, factory), ..]) | Registers several, as service does. | |
.sign_in(sign_in) | SignIn::OwnerPassword | How people sign in. See Sign-in modes. |
.icon(png, svg) | none | A 128x128 PNG, served at /favicon.ico, and an SVG; both appear as icons in the /mcp endpoint’s serverInfo. |
.wrap_router(f) | none | f: fn(axum::Router) -> axum::Router wraps the whole application: extra routes, or your own layers such as a request rate limiter, outside every built-in layer except the one that adds the security headers, so responses from your routes get them too. |
.docs_url(url) | none | Named by --help. |
.name(), .version() | What new was given. | |
.registered() | The registered service names, in order. | |
.var(suffix) | <PREFIX>_<suffix>: .var("SERVICES") is PLANNER_SERVICES. | |
.load(&mut env) | Reads and checks the whole configuration and builds the selected services, returning an app::Loaded, or None with every problem in env.errors. | |
.router(&loaded, &ctx) | The whole HTTP application as an axum::Router, without serving it. | |
.run(loaded) | Starts logging, logs the services and serves until Ctrl-C or SIGTERM. | |
.main() | Everything a binary’s main does: the flags below, load from the process environment, then run. Returns the exit code. | |
Server::log_caps(&services) | Every service’s log_caps, together. | |
Server::combined_tool_names(&services) | The tool names /mcp offers, from each service’s tool_names. |
Loaded holds the core settings (core), the built services, the read-only services and the audit log (safety), whether /mcp is served (combined), the sign-in verifier (verifier) and the warnings logged at startup. It is #[non_exhaustive].
Testing a whole server
load and router build exactly what main serves, from a map instead of the process environment, so a test can send requests to it without a network. This test uses the tower crate (cargo add --dev tower --features util):
use mcp_server_core::app::Server;
use mcp_server_core::axum::body::Body;
use mcp_server_core::axum::http::{Request, StatusCode};
use mcp_server_core::service::{HttpSettings, Service, ServiceContext, ServiceEnv};
use std::collections::HashMap;
use std::sync::Arc;
use tower::ServiceExt;
use mcp_server_core::combined::DynHandler;
use mcp_server_core::rmcp::ServerHandler;
#[derive(Clone)] struct Tools;
impl ServerHandler for Tools {}
struct Tasks;
impl Service for Tasks {
fn name(&self) -> &'static str { "tasks" }
fn handler(&self) -> DynHandler { DynHandler::new(Tools) }
}
fn tasks(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> { Some(Arc::new(Tasks)) }
#[tokio::main(flavor = "current_thread")]
async fn main() {
let server = Server::new("mcp-planner", "1.0.0").service("tasks", tasks);
let vars: HashMap<String, String> = [
("PUBLIC_URL", "https://mcp.example.com"),
("OAUTH_SIGNING_KEY", "0123456789abcdef0123456789abcdef"),
("OAUTH_ADMIN_PASSWORD", "a long password"),
]
.into_iter()
.map(|(k, v)| (k.to_string(), v.to_string()))
.collect();
let mut env = ServiceEnv::new(Box::new(move |k: &str| vars.get(k).cloned()));
let loaded = server.load(&mut env).unwrap_or_else(|| panic!("{:?}", env.errors));
let ctx = ServiceContext {
http: HttpSettings::from_core(&loaded.core),
shutdown: Default::default(),
};
let app = server.router(&loaded, &ctx);
let res = app.clone().oneshot(Request::get("/healthz").body(Body::empty()).unwrap()).await.unwrap();
assert_eq!(res.status(), StatusCode::OK);
// Without a token, the service asks the client to sign in.
let res = app.oneshot(Request::post("/tasks").body(Body::empty()).unwrap()).await.unwrap();
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
The repository’s tests/app_e2e.rs goes further: it opens MCP sessions with a static token and calls tools on each path.
The binary’s flags
main reads only its first argument:
| Argument | Prints | Exit status |
|---|---|---|
--version or -V | <name> <version>, such as mcp-planner 1.4.0 | 0 |
--help or -h | usage: <name> [--version | --healthcheck], then All configuration is read from environment variables., or …environment variables; see <docs_url> when docs_url is set | 0 |
--healthcheck | Nothing when healthy, healthcheck failed on stderr otherwise | 0 when GET /healthz on 127.0.0.1 at the BIND_ADDR port answers 200 within 5 seconds, 1 otherwise |
| anything else | unknown argument: <arg> and the usage, on stderr | 2 |
| none | Runs the server. Configuration errors are printed as configuration error: <message>, one per line | 1 on configuration errors or a fatal error while serving (error: <message>), 0 after a graceful shutdown |
--healthcheck reads BIND_ADDR and INSECURE_HTTP from the environment, so run it with the server’s environment. It speaks TLS unless INSECURE_HTTP is set and accepts any certificate, since it only talks to itself. The same check is public as app::healthcheck(), for a main of your own. In a container image:
HEALTHCHECK CMD ["/usr/local/bin/mcp-planner", "--healthcheck"]
TLS and deployment covers containers, shutdown and replicas.
Next: Several services and /mcp, or Sign-in modes to let people sign in with their own credentials.
Several services and /mcp
One server can run several services. This page explains how they are mounted, how the combined /mcp endpoint offers all of their tools in one connector, and how each path stays its own OAuth resource.
One server, several services
Register each service with the Server builder:
use mcp_server_core::app::{Server, SignIn};
use mcp_server_core::service::{Service, ServiceEnv};
use std::sync::Arc;
fn tasks(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> { None }
fn calendar(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> { None }
#[tokio::main]
async fn main() -> std::process::ExitCode {
Server::new("mcp-planner", env!("CARGO_PKG_VERSION"))
.env_prefix("PLANNER")
.service("tasks", tasks)
.service("calendar", calendar)
.sign_in(SignIn::OwnerPassword)
.main()
.await
}
With PUBLIC_URL=https://mcp.example.com, the server answers on:
| Path | Serves |
|---|---|
/tasks | The tasks service: its tools, prompts and, if its router serves them, resources |
/calendar | The calendar service |
/mcp | Every enabled service’s tools and prompts, each name prefixed with its service |
PLANNER_SERVICES=tasks runs only some of the registered services; an unselected service is not mounted, is not on /mcp and reads none of its configuration. Services are mounted, and listed on /mcp, in registration order, or in the order PLANNER_SERVICES names them when it is set. See the configuration reference for <PREFIX>_SERVICES.
The combined endpoint
/mcp is one MCP server built from every enabled service’s handler. A client connected to it sees every service at once, with one sign-in.
Tool names
Each tool is offered as <service>_<tool>: the tasks service’s add_task is tasks_add_task on /mcp, and calendar’s list_events is calendar_list_events. A tool’s description, input schema and annotations are unchanged.
A call is routed by its prefix. Service names never contain _, so the first _ ends the prefix; the call reaches that service’s handler under the tool’s own name, add_task. Tool names themselves may contain _. A name with no enabled service as its prefix is answered with a JSON-RPC invalid_params error, tool not found.
What initialize returns
| Field | Value on /mcp |
|---|---|
serverInfo | The server’s name and version from Server::new, and its icons from Server::icon |
capabilities | Tools always; prompts when any enabled service declares them; never resources |
instructions | A short guide to the prefixes, then each service’s own instructions under its name |
The instructions start with a fixed paragraph naming the prefixes, and add each service’s instructions, trimmed, after a line with its name. Services without instructions, or with blank ones, are left out:
#![allow(unused)]
fn main() {
use mcp_server_core::combined::{Combined, DynHandler};
use mcp_server_core::rmcp::ServerHandler;
use mcp_server_core::rmcp::model::{Implementation, ServerCapabilities, ServerConfig};
#[derive(Clone)]
struct Tools(&'static str);
impl ServerHandler for Tools {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
.with_instructions(self.0)
}
}
let combined = Combined::new(
Implementation::new("mcp-planner", "1.0.0"),
vec![
("tasks", DynHandler::new(Tools("Keeps a task list. Dates are YYYY-MM-DD.\n"))),
("calendar", DynHandler::new(Tools("Times are in UTC."))),
],
);
assert_eq!(
combined.get_info().instructions.unwrap(),
"This server combines several services. Each tool and prompt name starts with its \
service: tasks_, calendar_. The notes below, tool descriptions and error messages \
name tools without that prefix.\n\
\n\
tasks:\n\
Keeps a task list. Dates are YYYY-MM-DD.\n\
\n\
calendar:\n\
Times are in UTC."
);
}
Write your service’s instructions and tool descriptions for its own path, naming tools without a prefix; the first paragraph tells the model how to read them on /mcp.
Prompts and resources
Prompts are offered as <service>_<prompt>, and tool names in a prompt’s text are prefixed for you. Prompts has the details.
Resources are served on each service’s own path only. /mcp forwards tools and prompts, nothing else.
Read-only services and the audit log
Each service keeps its own read-only rule on /mcp. With PLANNER_READ_ONLY=calendar:
/mcplists everytasks_tool, but only thecalendar_tools markedread_only_hint = true;- calling a hidden
calendar_write tool returns the tool errorread_only: the calendar service is read-only on this server; tasks_write tools work as on/tasks.
Every write tool call on /mcp is audited as on the service’s own path, with endpoint set to /mcp, service to the service and tool to its own name without the prefix, such as add_task. See Read-only mode and the audit log.
Who is calling
A call forwarded from /mcp keeps its request context, so a tool reads the Caller and the person’s Credential from the request extensions exactly as on its own path.
Turning /mcp off
/mcp is served whenever at least one service is enabled, even a single one. Set <PREFIX>_COMBINED=false (PLANNER_COMBINED=false here) to turn it off; it accepts true, false, 1, 0, yes, no, on and off in any case, and anything else stops startup with PLANNER_COMBINED must be true or false, got "<value>". Then /mcp and its metadata document answer 404, and mcp is no longer listed in the authorization server’s scopes_supported.
Keep it on when people want one connector for everything. Turn it off when every client should be given one service at a time: a token for /tasks never works on /calendar, while a token for /mcp reaches every service.
Service names
Because the name is the path, the OAuth resource and the prefix on /mcp, a service name must be lowercase ASCII letters, digits and -, never mcp, and unique. _ is excluded so a prefixed name can always be split, and mcp is the combined endpoint itself. Server::service panics on a name that breaks these rules; see Names for the messages.
Each path is its own OAuth resource
Every path, /mcp included, is a separate OAuth 2.1 protected resource:
For /tasks | For /mcp | |
|---|---|---|
| Resource | https://mcp.example.com/tasks | https://mcp.example.com/mcp |
| Metadata document | /.well-known/oauth-protected-resource/tasks | /.well-known/oauth-protected-resource/mcp |
scopes_supported in it | ["tasks"] | ["mcp"] |
| Sign-in page says | “the tasks service on this server” | “every service on this server, through /mcp” |
- A request without a token gets
401with aWWW-Authenticateheader naming that path’s metadata document, so a client signs in for the path it was given. - An access token is bound to the resource it was issued for (RFC 8707). A token for
/mcpis refused on/tasksand the other way round, with401anderror="invalid_token". A refresh keeps the resource; asking for another one fails withinvalid_target. - One sign-in page, and one password or credential, covers every path.
- A client that sends no
resourceparameter when it signs in gets the only service when there is exactly one;/mcpis never chosen for it. With several services such a request fails withinvalid_target:resource is required: name the URL of the service, or of /mcp for every service. - The static token (
MCP_AUTH_TOKEN) and a person’s credential sent directly as the bearer token are not bound to a path: they work on every path. - MCP sessions belong to the path that opened them, and each path keeps its own session table and caps; see Limits and abuse protection.
Resource indicators and audiences and Choosing the resource explain the tokens in full, and Which URL to use which URL to give each client.
Next: Prompts.
Prompts
MCP prompts are ready-made instructions a client offers the person, such as “plan my week”, which tell the model which tools to call and how. This page covers writing prompts for a service, the helpers in the prompt module, and how prompts behave on /mcp and on read-only services.
The problem prompts have
A prompt that names tools must name them as the client sees them. On a service’s own path the tasks service’s tool is list_tasks; on the combined /mcp endpoint it is tasks_list_tasks. A prompt that says “call list_tasks” would send the model looking for a tool that /mcp does not have.
The crate solves this twice over:
tool_prefixtells a prompt the prefix of the endpoint it is served from, so it can name tools exactly./mcpprefixes the service’s tool names that are still bare in a prompt’s text, so a prompt written for the service’s own path works on/mcpunchanged.
Writing prompts
A service offers prompts by declaring the prompts capability in get_info and answering prompts/list and prompts/get. Keep the prompts in a module of plain functions, as mcp-icloud does: they are then easy to test without a server.
#![allow(unused)]
fn main() {
use mcp_server_core::prompt::{UNAVAILABLE, argument, not_found, number_argument, user_prompt};
use mcp_server_core::rmcp::ErrorData as McpError;
use mcp_server_core::rmcp::model::{GetPromptResult, JsonObject, Prompt, PromptArgument};
use serde_json::json;
const PLAN_WEEK: &str = "plan_week";
const PLAN_WEEK_DESCRIPTION: &str = "Plan the coming days from the open tasks.";
/// Every prompt of the tasks service.
pub fn list() -> Vec<Prompt> {
vec![
Prompt::new(
PLAN_WEEK,
Some(PLAN_WEEK_DESCRIPTION),
Some(vec![
PromptArgument::new("days")
.with_description("How many days to plan, 1 to 14. Default 7.")
.with_required(false),
PromptArgument::new("project")
.with_description("Only this project. Default: every project.")
.with_required(false),
]),
)
.with_title("Plan the week"),
]
}
/// Renders prompt `name`, naming tools as `<p><tool>`.
pub fn get(name: &str, arguments: Option<&JsonObject>, p: &str) -> Result<GetPromptResult, McpError> {
match name {
PLAN_WEEK => {
let days = number_argument(arguments, "days", 7, 1..=14)?;
let scope = match argument(arguments, "project")? {
Some(project) => format!("in the {project} project"),
None => "in every project".to_string(),
};
let text = format!(
"Plan my next {days} days.\n\n\
1. Call `{p}list_tasks` and keep the open tasks {scope}.\n\
2. Spread them over the days, the ones due soonest first.\n\
3. Offer to add any task I mention with `{p}add_task`, only after I confirm.\n\n\
{UNAVAILABLE}"
);
Ok(user_prompt(PLAN_WEEK_DESCRIPTION, text))
}
_ => Err(not_found(name)),
}
}
// On /tasks the prefix is empty; on /mcp it is "tasks_".
let args = json!({"days": " 3 ", "project": "home"}).as_object().cloned();
let own = get(PLAN_WEEK, args.as_ref(), "").unwrap();
assert!(own.messages[0].content.as_text().unwrap().text.contains("Call `list_tasks`"));
let combined = get(PLAN_WEEK, args.as_ref(), "tasks_").unwrap();
let text = &combined.messages[0].content.as_text().unwrap().text;
assert!(text.starts_with("Plan my next 3 days."));
assert!(text.contains("Call `tasks_list_tasks` and keep the open tasks in the home project."));
// Arguments are checked, and unknown prompts get the message rmcp's prompt router uses.
let bad = json!({"days": "30"}).as_object().cloned();
assert_eq!(get(PLAN_WEEK, bad.as_ref(), "").unwrap_err().message, "days must be a whole number from 1 to 14");
assert_eq!(get("nope", None, "").unwrap_err().message, "prompt 'nope' not found");
}
The handler declares the capability and hands the requests to that module, passing the prefix for the current request:
#![allow(unused)]
fn main() {
use mcp_server_core::rmcp;
use mcp_server_core::prompt::tool_prefix;
use mcp_server_core::rmcp::handler::server::router::tool::ToolRouter;
use mcp_server_core::rmcp::model::{
CallToolResult, ContentBlock, GetPromptRequestParams, GetPromptResponse, ListPromptsResult,
PaginatedRequestParams, ServerCapabilities, ServerConfig,
};
use mcp_server_core::rmcp::service::{RequestContext, RoleServer};
use mcp_server_core::rmcp::{ErrorData as McpError, ServerHandler, tool, tool_handler, tool_router};
mod prompts {
use mcp_server_core::rmcp::ErrorData as McpError;
use mcp_server_core::rmcp::model::{GetPromptResult, JsonObject, Prompt};
pub fn list() -> Vec<Prompt> { Vec::new() }
pub fn get(name: &str, _: Option<&JsonObject>, _: &str) -> Result<GetPromptResult, McpError> {
Err(mcp_server_core::prompt::not_found(name))
}
}
#[derive(Clone)]
struct TasksTools {
tool_router: ToolRouter<Self>,
}
#[tool_router]
impl TasksTools {
#[tool(description = "List the open tasks.", annotations(read_only_hint = true))]
async fn list_tasks(&self) -> Result<CallToolResult, McpError> {
Ok(CallToolResult::success(vec![ContentBlock::text("Buy milk")]))
}
}
#[tool_handler(router = self.tool_router)]
impl ServerHandler for TasksTools {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().enable_prompts().build())
}
async fn list_prompts(
&self,
_request: Option<PaginatedRequestParams>,
_context: RequestContext<RoleServer>,
) -> Result<ListPromptsResult, McpError> {
Ok(ListPromptsResult::with_all_items(prompts::list()))
}
async fn get_prompt(
&self,
request: GetPromptRequestParams,
context: RequestContext<RoleServer>,
) -> Result<GetPromptResponse, McpError> {
let prefix = tool_prefix(&context);
prompts::get(&request.name, request.arguments.as_ref(), prefix).map(Into::into)
}
}
}
With rmcp’s prompt macros
rmcp’s #[prompt_router], #[prompt] and #[prompt_handler] work too. Like the tool macros, they need use mcp_server_core::rmcp; in the file (see Writing tools with rmcp). A #[prompt] method can take the RequestContext<RoleServer> as an argument to read the prefix:
#![allow(unused)]
fn main() {
use mcp_server_core::rmcp;
use mcp_server_core::prompt::{UNAVAILABLE, tool_prefix, user_prompt};
use mcp_server_core::rmcp::handler::server::router::prompt::PromptRouter;
use mcp_server_core::rmcp::handler::server::router::tool::ToolRouter;
use mcp_server_core::rmcp::model::{
CallToolResult, ContentBlock, GetPromptResult, ServerCapabilities, ServerConfig,
};
use mcp_server_core::rmcp::service::{RequestContext, RoleServer};
use mcp_server_core::rmcp::{
ErrorData as McpError, ServerHandler, prompt, prompt_handler, prompt_router, tool,
tool_handler, tool_router,
};
#[derive(Clone)]
struct TasksTools {
tool_router: ToolRouter<Self>,
prompt_router: PromptRouter<Self>,
}
impl TasksTools {
fn new() -> Self {
Self { tool_router: Self::tool_router(), prompt_router: Self::prompt_router() }
}
}
#[tool_router]
impl TasksTools {
#[tool(description = "List the open tasks.", annotations(read_only_hint = true))]
async fn list_tasks(&self) -> Result<CallToolResult, McpError> {
Ok(CallToolResult::success(vec![ContentBlock::text("Buy milk")]))
}
}
#[prompt_router]
impl TasksTools {
#[prompt(name = "review", description = "Review the open tasks.")]
async fn review(&self, context: RequestContext<RoleServer>) -> GetPromptResult {
let p = tool_prefix(&context);
user_prompt(
"Review the open tasks.",
format!("Call `{p}list_tasks` and point out anything overdue. {UNAVAILABLE}"),
)
}
}
#[tool_handler(router = self.tool_router)]
#[prompt_handler(router = self.prompt_router)]
impl ServerHandler for TasksTools {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().enable_prompts().build())
}
}
let _ = TasksTools::new();
}
The prompt module
Everything in mcp_server_core::prompt:
| Item | What it does |
|---|---|
tool_prefix(&context) -> &str | The tool-name prefix of the endpoint this request came to: "" on the service’s own path, "<service>_" on /mcp. |
ToolPrefix(pub String) | The request extension /mcp sets on a prompts/get it forwards, which tool_prefix reads. Insert it yourself only in tests or in a combined handler of your own. |
UNAVAILABLE | A sentence for the end of any prompt that names tools, telling the model what to do when one is missing. |
user_prompt(description, text) -> GetPromptResult | A rendered prompt: one user message holding text, with description. |
argument(arguments, name) -> Result<Option<String>, McpError> | A string argument, trimmed. Missing, null, empty or blank is None, so the default applies. Any other non-string value is an invalid_params error: <name> must be a string. |
number_argument(arguments, name, default, range) -> Result<u32, McpError> | A whole number within range (a RangeInclusive<u32>), given as a string, default when missing, null or blank. A non-string value is the invalid_params error <name> must be a string; text that is not a whole number in range is <name> must be a whole number from <start> to <end>. |
not_found(name) -> McpError | The error for a prompt the service does not have, invalid_params with prompt '<name>' not found and no data. rmcp’s own prompt router uses the same message, and adds the names of the available prompts as data. |
UNAVAILABLE reads, in full:
If a tool named here is not available on this server (for example because the service is read-only or the tool is turned off), say so and stop that step.
MCP sends prompt arguments as strings, which is why number_argument parses text: " 3 " is 3.
Prompts on /mcp
On the combined endpoint:
- Names. Each prompt is listed as
<service>_<prompt>:plan_weekistasks_plan_week. Its title, description and arguments are unchanged. - Capability.
/mcpdeclares the prompts capability when any enabled service declares it. - Routing.
prompts/getfortasks_plan_weekreaches thetasksservice asplan_week, withToolPrefix("tasks_")set, sotool_prefixreturns"tasks_". - Unknown prompts. When the service answers with exactly
not_foundfor its own name,/mcprewords it with the name the client sent:prompt 'tasks_nope' not found. A name without an enabled service’s prefix gets the same error. Other errors pass through unchanged, and that includes the error of rmcp’s#[prompt_handler]: itsdatamakes it differ fromnot_found, so on/mcpit names the prompt without the prefix,prompt 'nope' not found.
Tool names are prefixed for you
After the service renders a prompt, /mcp rewrites the text of each message: every whole identifier that is one of the service’s tool names gets the service’s prefix. An identifier is a run of ASCII letters, digits and _, so only exact names change:
| In the prompt’s text | On /mcp |
|---|---|
Call `list_tasks` | Call `tasks_list_tasks` |
list_tasks_due (a longer identifier) | unchanged |
my_list_tasks | unchanged |
tasks_list_tasks (already prefixed, for example by tool_prefix) | unchanged |
So a prompt that names its tools bare works on both paths, and one that uses tool_prefix is not prefixed twice. Some limits of the rewriting:
- Any whole word equal to a tool name is prefixed wherever it appears, prose included. A tool called
searchwould turn “search the tasks” into “tasks_search the tasks”. Give tools names that are not ordinary words, such assearch_tasks. - Only the service’s own tool names are prefixed. A prompt that mentions another service’s tools must name them itself.
- The names are those the service lists to this client. On a read-only service that is its read-only tools only, so a bare name of a hidden write tool stays bare. The tool is not available on
/mcpeither way. - Only the text content of a completed prompt is rewritten. Images, embedded resources, other content and the prompt’s description pass through unchanged.
Prompts on read-only services
Read-only mode hides and refuses write tools, but never prompts: a read-only service lists and renders its prompts as usual, on its own path and on /mcp. A prompt step that needs a write tool then cannot be done. End every prompt that names tools with UNAVAILABLE, so the model says so and stops that step instead of guessing at another tool.
Next: Examples.
Examples
The repository has two complete servers in examples/. This page says what each one shows, how to run it, and what to try against it.
| Example | Sign-in | Shows |
|---|---|---|
notes | The owner’s password | A read tool and a write tool, tool arguments, tool errors, read-only mode, the static token and the audit log |
api_keys | Each person’s own API key | A CredentialVerifier, a tool that reads the caller’s key, keys sent directly as bearer tokens, sessions bound to a key |
With the commands below, both listen on 0.0.0.0:8443 and serve plain HTTP for localhost, so nothing needs a certificate. Run them from a clone of the repository:
git clone https://github.com/Trozz/mcp-server-core-rs
cd mcp-server-core-rs
notes: a server for its owner
examples/notes.rs keeps short notes for one person. It is the quick start server with more in it:
- The service
notes, at/notes, with environment prefixNOTES. list_notes, markedread_only_hint = true, andadd_note, markedread_only_hint = false, which takes atextargument throughParameters<AddNote>.add_notereturns the tool errorinvalid_argument: text is emptyfor blank text, so the audit log records the kindinvalid_argument.- The notes live in an
Arc<Mutex<Vec<String>>>held by the service and cloned into each session’s handler, so every session sees the same notes. They are lost when the server stops. tool_nameslists both tools for the startup log, and the handler sets the instructionsKeeps short notes.
Run it:
PUBLIC_URL=http://localhost:8443 INSECURE_HTTP=true \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) OAUTH_ADMIN_PASSWORD='a long password' \
LOG_FORMAT=pretty cargo run --example notes
Then add http://localhost:8443/notes to an MCP client, or open the MCP Inspector with npx @modelcontextprotocol/inspector and connect to that URL over Streamable HTTP. The client registers itself and opens the sign-in page in your browser; enter a long password. Ask it to add a note and list them.
Things to try with notes
Every tool on one path. Connect to http://localhost:8443/mcp instead. The tools are notes_add_note and notes_list_notes, and the instructions start with the paragraph about prefixes described in Several services and /mcp.
Read-only mode. Restart with NOTES_READ_ONLY=notes. tools/list now offers only list_notes (notes_list_notes on /mcp), and calling add_note anyway returns the tool error:
read_only: the notes service is read-only on this server
The static token and curl. Restart with a static token and an audit log:
export MCP_AUTH_TOKEN=$(openssl rand -hex 32)
PUBLIC_URL=http://localhost:8443 INSECURE_HTTP=true \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) OAUTH_ADMIN_PASSWORD='a long password' \
AUDIT_LOG_PATH=./audit.jsonl LOG_FORMAT=pretty cargo run --example notes
In another terminal with the same MCP_AUTH_TOKEN, open a session and call the tools. Each request after initialize names the session in Mcp-Session-Id:
URL=http://localhost:8443/notes
H=(-H "Authorization: Bearer $MCP_AUTH_TOKEN" -H 'Content-Type: application/json'
-H 'Accept: application/json, text/event-stream')
SESSION=$(curl -s -D - -o /dev/null "${H[@]}" $URL \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}' \
| awk 'tolower($1) == "mcp-session-id:" {print $2}' | tr -d '\r')
H+=(-H "Mcp-Session-Id: $SESSION" -H 'MCP-Protocol-Version: 2025-06-18')
curl -s "${H[@]}" $URL -d '{"jsonrpc":"2.0","method":"notifications/initialized"}'
curl -s "${H[@]}" $URL \
-d '{"jsonrpc":"2.0","id":2,"method":"tools/call","params":{"name":"add_note","arguments":{"text":"Buy milk"}}}'
curl -s "${H[@]}" $URL \
-d '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"add_note","arguments":{"text":" "}}}'
curl -s "${H[@]}" $URL \
-d '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"list_notes","arguments":{}}}'
Each answer is a short server-sent event stream whose last data: line holds the JSON-RPC response, such as {"jsonrpc":"2.0","id":2,"result":{"content":[{"type":"text","text":"added"}],"isError":false}}. audit.jsonl now has one line for each add_note call, and none for list_notes, which only reads:
{"ts":"2026-10-18T13:49:04.714Z","service":"notes","endpoint":"/notes","tool":"add_note","outcome":"ok","error_kind":null,"caller":"static","subject":"static","elapsed_ms":0}
{"ts":"2026-10-18T13:49:04.724Z","service":"notes","endpoint":"/notes","tool":"add_note","outcome":"error","error_kind":"invalid_argument","caller":"static","subject":"static","elapsed_ms":0}
A call signed in through OAuth records caller as oauth:<client_id> and subject as owner. Read-only mode and the audit log explains every field.
The binary’s flags and configuration errors. cargo run --example notes -- --version prints the name and version, such as mcp-notes 0.4.0. Run it without any environment and it lists every missing variable, then exits with status 1:
configuration error: PUBLIC_URL is required
configuration error: OAUTH_SIGNING_KEY is required
configuration error: OAUTH_ADMIN_PASSWORD is required
api_keys: a server shared by many people
examples/api_keys.rs is a server where each person signs in with their own key for an upstream API, so one deployment serves many people without holding anyone’s key. The “upstream API” is imaginary: it accepts any key that starts with demo- and has something after it.
-
SignIn::ServiceCredential, with environment prefixDEMO. There is no owner’s password, soOAUTH_ADMIN_PASSWORDis not needed. -
The service
account, at/account, returns aCredentialVerifierfromcredential_verifier:Method In the example labelDemo API key, shown on the sign-in pagehelpAny key starting demo- works, such as demo-1234., shown under the fieldplausibleStarts with demo-and is at most 64 bytes. Anything else is refused locally, without asking upstream and without counting as a failed attemptcheckValidwhen something followsdemo-, otherwiseInvalidwith the reasonThat key is empty after demo-.A real verifier makes one cheap authenticated request upstream here, and answersUnavailablewhen the upstream cannot be reached -
The tool
whoamitakesExtension<Parts>and reads the caller’s key as aCredential, answering with its last four characters.
Run it:
PUBLIC_URL=http://localhost:8443 INSECURE_HTTP=true \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) LOG_FORMAT=pretty \
cargo run --example api_keys
Then add http://localhost:8443/account to an MCP client and sign in with demo-1234. Calling whoami answers You are using the key ending 1234.
Things to try with api_keys
The sign-in page. It asks for a “Demo API key” and says the key is checked once and then kept only in encrypted form inside the connection’s tokens. Enter abc and it answers That is not a Demo API key., without counting the attempt. Enter demo- and it shows the verifier’s reason, That key is empty after demo-.; that one counts. After five rejected attempts from your address within a minute, the next is refused with 429: Too many attempts from this address: credentials were rejected, or several are being checked at once. Wait a little and try again. See Limits and abuse protection.
The key as the bearer token. A client that can send a header may skip OAuth and send the key itself:
claude mcp add --transport http account http://localhost:8443/account \
--header "Authorization: Bearer demo-1234"
The server checks the key with the verifier and remembers the verdict for a while under the key’s SHA-256 (ten minutes for a valid key, one minute for a rejected one), so it does not ask upstream on every request (see Credentials sent as bearer tokens). A rejected or implausible key gets 401 with a WWW-Authenticate header naming the service’s metadata and error="invalid_token".
Sessions belong to a key. Open a session with demo-1234, then send a request in that session (the same Mcp-Session-Id) with demo-9999: it gets 404, as if the session did not exist, so one person can never use another’s session.
No static token. Start it with MCP_AUTH_TOKEN set and it refuses:
configuration error: MCP_AUTH_TOKEN cannot be used when people sign in with their own Demo API key
Requests made with a fixed token would carry no key for the tools to call upstream with. The static token explains the rules.
From an example to your own server
Copy the example closest to what you need, rename the service and the prefix, and replace the tools. Each example starts with use mcp_server_core::rmcp; so rmcp’s macros find the crate in your own project too (see Writing tools with rmcp); for notes, also cargo add serde --features derive. Writing a service covers reading your service’s configuration, and The CredentialVerifier trait writing a verifier for a real upstream API. The two servers built on this crate are larger examples of the same shapes: mcp-icloud signs its owner in with a password, and mcp-companies-house signs each person in with their own Companies House API key.
Next: Sign-in modes.
Sign-in modes
This page covers who may use a server and what your tools receive about them: the three sign-in modes, the CredentialVerifier trait behind them, sealed credentials, credentials sent directly as bearer tokens, the static token and the Caller every request carries. The OAuth flow itself is on OAuth and tokens.
Choosing a mode
You choose how people sign in with Server::sign_in and an app::SignIn:
| Mode | Who signs in | What tools get | Use it for |
|---|---|---|---|
SignIn::OwnerPassword (the default) | One person, with OAUTH_ADMIN_PASSWORD. MCP_AUTH_TOKEN can also be set for clients that cannot do OAuth. | Nothing about the person: tools act with the server’s own upstream configuration, such as an app password in the environment. | A personal server, such as mcp-icloud. |
SignIn::ServiceCredential | Anyone with a credential the upstream service accepts, checked by the verifier one of your services returns from Service::credential_verifier. | The person’s own credential, as a Credential in the request extensions. | One deployment shared by many people, each with their own API key, such as mcp-companies-house. |
SignIn::Custom(fn) | Whoever the CredentialVerifier your function builds accepts. | Either of the above, depending on the verifier’s carried(). | Sign-in that needs its own configuration or does not belong to one service. |
Every mode uses the same sign-in page and the same OAuth flow. Only the field on the page, the check behind it and what the tokens carry differ.
#![allow(unused)]
fn main() {
use mcp_server_core::service::{Service, ServiceEnv};
use std::sync::Arc;
fn notes(_: &mut ServiceEnv) -> Option<Arc<dyn Service>> { None }
use mcp_server_core::app::{Server, SignIn};
let server = Server::new("mcp-notes", "1.0.0")
.env_prefix("NOTES")
.service("notes", notes)
.sign_in(SignIn::OwnerPassword);
let _ = server;
}
SignIn is #[non_exhaustive], so a later version can add modes without a breaking change.
The owner’s password
With SignIn::OwnerPassword the server reads OAUTH_ADMIN_PASSWORD and builds a PasswordVerifier from it.
- The password must be at least 12 characters (
app::MIN_ADMIN_PASSWORD_CHARS) and not only white space. Otherwise the server stops withOAUTH_ADMIN_PASSWORD must be at least 12 characters, not only spaces, orOAUTH_ADMIN_PASSWORD is requiredwhen it is unset. - A password of 12 to 14 characters starts the server with a warning (
app::RECOMMENDED_ADMIN_PASSWORD_CHARSis 15):OAUTH_ADMIN_PASSWORD is shorter than 15 characters: a longer passphrase is much harder to guess. - It can be given as a file with
OAUTH_ADMIN_PASSWORD_FILE, like every other variable; see Configuration reference. - It is compared exactly as typed, spaces included, in constant time. Empty input, or input longer than 1,024 bytes (
credential::MAX_PASSWORD_LEN), is refused without a comparison. - It only proves who is signing in. It never enters a token and is never accepted as a bearer token.
- Changing it ends every earlier sign-in: each connector asks the person to sign in again, without being added again (see What ends a grant).
Generate a passphrase rather than a word, for example with a password manager. One shared secret guards everything, so the server treats a burst of failures differently from per-person sign-in; see Limits and abuse protection.
Each person’s own credential
With SignIn::ServiceCredential each person signs in with their own credential for the upstream API your tools call. The server:
- asks the person for it on the sign-in page, named by the verifier’s label (“Sign in with your own Example API key”);
- checks it once upstream with the verifier;
- seals it into the person’s OAuth tokens (see Sealed credentials);
- opens it again on every request and hands it to your tools as a
Credential.
OAUTH_ADMIN_PASSWORD is not read in this mode. Clients that can set a header may skip OAuth and send the credential itself as their bearer token (see Credentials sent as bearer tokens).
The verifier comes from the service that defines how people sign in:
use mcp_server_core::app::{Server, SignIn};
use mcp_server_core::combined::DynHandler;
use mcp_server_core::credential::CredentialVerifier;
use mcp_server_core::service::{Service, ServiceEnv};
use std::sync::Arc;
use mcp_server_core::credential::{CheckFuture, CredentialCheck};
#[derive(Clone)]
struct ExampleTools;
impl mcp_server_core::rmcp::ServerHandler for ExampleTools {}
struct ExampleKeys;
impl CredentialVerifier for ExampleKeys {
fn label(&self) -> &str { "Example API key" }
fn check<'a>(&'a self, _: &'a str) -> CheckFuture<'a> { Box::pin(async { CredentialCheck::Valid }) }
}
struct ExampleService;
impl Service for ExampleService {
fn name(&self) -> &'static str {
"example"
}
fn handler(&self) -> DynHandler {
DynHandler::new(ExampleTools)
}
fn credential_verifier(&self) -> Option<Arc<dyn CredentialVerifier>> {
Some(Arc::new(ExampleKeys))
}
}
fn example(_env: &mut ServiceEnv) -> Option<Arc<dyn Service>> {
Some(Arc::new(ExampleService))
}
#[tokio::main]
async fn main() -> std::process::ExitCode {
Server::new("mcp-example", env!("CARGO_PKG_VERSION"))
.env_prefix("EXAMPLE")
.service("example", example)
.sign_in(SignIn::ServiceCredential)
.main()
.await
}
Every service on the server receives the credential, including services that do not define a verifier, and so does the combined /mcp endpoint.
Only one service may define sign-in
With SignIn::ServiceCredential, exactly one enabled service must return a verifier from Service::credential_verifier:
| Enabled services with a verifier | Result |
|---|---|
| None | The server stops with no enabled service defines how people sign in. |
| One | Its verifier decides who signs in on every path. |
| More than one | The server stops with more than one enabled service defines how people sign in (a, b): enable one of them. |
The rule exists because there is one sign-in page and one credential per person. With two verifiers, each service’s tools would receive a credential meant for another upstream. The check counts only enabled services, so you can register several services that each define a verifier and run one at a time with <PREFIX>_SERVICES.
A verifier of your own
SignIn::Custom takes a function that builds the verifier from the environment, the same way a service factory does. Record every problem in env.errors and return None only after recording why, so the server reports it with every other configuration error.
#![allow(unused)]
fn main() {
use mcp_server_core::app::{Server, SignIn};
use mcp_server_core::credential::{CheckFuture, CredentialCheck, CredentialVerifier};
use mcp_server_core::service::ServiceEnv;
use std::sync::Arc;
async fn check_upstream(_api_url: &str, _key: &str) -> CredentialCheck { CredentialCheck::Valid }
/// Keys for an API whose address is configured, say a sandbox while testing.
struct ExampleKeys {
api_url: String,
}
impl CredentialVerifier for ExampleKeys {
fn label(&self) -> &str {
"Example API key"
}
fn check<'a>(&'a self, key: &'a str) -> CheckFuture<'a> {
// One cheap authenticated request to the configured API decides.
Box::pin(check_upstream(&self.api_url, key))
}
/// A sandbox key is no key for production: pointing elsewhere signs everyone out.
fn generation(&self) -> &[u8] {
self.api_url.as_bytes()
}
}
fn sign_in(env: &mut ServiceEnv) -> Option<Arc<dyn CredentialVerifier>> {
let api_url = env.required("EXAMPLE_API_URL")?;
if !api_url.starts_with("https://") {
env.errors.push("EXAMPLE_API_URL must be an https URL".into());
return None;
}
Some(Arc::new(ExampleKeys { api_url }))
}
let server = Server::new("mcp-example", "1.0.0").sign_in(SignIn::Custom(sign_in));
let _ = server;
}
Use Custom when sign-in needs configuration that is not any one service’s, or when you want a password with a different label or variable than the owner’s password. A custom verifier whose carried() is false behaves like the owner’s password: nothing about it enters tokens and tools get no Credential.
Signing in through an upstream provider
When the upstream service has OAuth of its own, such as FreeAgent, GitHub or Google, people can sign in there instead of pasting a key. The server acts as the provider’s OAuth client: a verifier whose upstream method returns an UpstreamSignIn turns the sign-in page into a consent page with a Continue to button, and the credential the provider grants, usually its refresh token, is sealed into the person’s tokens like any carried credential. UpstreamVerifier builds such a verifier around your provider; return it from Service::credential_verifier with SignIn::ServiceCredential, or from a SignIn::Custom function.
#![allow(unused)]
fn main() {
use mcp_server_core::credential::CredentialVerifier;
use mcp_server_core::upstream::{Exchange, ExchangeFuture, UpstreamGrant, UpstreamSignIn, UpstreamVerifier};
use std::sync::Arc;
struct Ledger;
impl UpstreamSignIn for Ledger {
fn provider(&self) -> &str {
"Ledger"
}
fn authorize_url(&self, redirect_uri: &str, state: &str) -> String {
let mut url = url::Url::parse("https://ledger.example.com/oauth/authorize").unwrap();
url.query_pairs_mut()
.append_pair("response_type", "code")
.append_pair("client_id", "this-server")
.append_pair("redirect_uri", redirect_uri)
.append_pair("state", state);
url.into()
}
fn exchange<'a>(&'a self, code: &'a str, redirect_uri: &'a str) -> ExchangeFuture<'a> {
Box::pin(async move {
// POST code and redirect_uri to the token endpoint; on success:
let _ = (code, redirect_uri);
Exchange::Granted(UpstreamGrant::new("the refresh token").with_subject("ledger:user:42"))
})
}
}
fn verifier() -> Arc<dyn CredentialVerifier> {
Arc::new(UpstreamVerifier::new("Ledger account", Ledger).with_generation(b"live".to_vec()))
}
let _ = verifier();
}
The flow, with nothing stored on the server:
GET /authorizeshows which client is asking and where it will be sent, as the ordinary sign-in page does. Consent is asked here for every client: all of them reach the provider under this server’s one OAuth client id, so the provider’s own consent screen cannot tell them apart.- The button posts the form, which sets a cookie holding the pending request, encrypted under a key derived from
OAUTH_SIGNING_KEYand bound to a randomstate, and sends the browser toauthorize_url. The cookie isHttpOnly,SameSite=Lax, limited to/callback,Secureover https, and lasts 10 minutes. - The provider sends the browser back to
PUBLIC_URL/callback. The server checksstateagainst the cookie, callsexchange(timed out, at most 16 at once) and sends the browser on to the client with an authorization code carrying the sealed credential. A declined approval reaches the client asaccess_denied.
Register PUBLIC_URL/callback with the provider as a redirect URI; for local use, http://localhost:<port>/callback. No service may be named callback on such a server. An exchange the provider refuses counts as a failed sign-in attempt; one it cannot answer does not. UpstreamGrant::with_subject names the person, say by the provider’s user id, so their subject stays the same across sign-ins; without it, the subject is derived from the credential. Tools receive the credential as a Credential and exchange it for access tokens as they need them; a provider that rotates refresh tokens on every use cannot be used this way, because the sealed credential never changes.
Single sign-on and many named users
The modes are deliberately few. For single sign-on, multi-factor authentication or many named users, put an identity-aware gateway such as Cloudflare Access or oauth2-proxy in front of /authorize. It is the only page a person’s browser opens.
The CredentialVerifier trait
A CredentialVerifier decides what the sign-in page asks for and checks it. The server asks it when someone submits the sign-in page and, when it accepts bearer credentials, for bearer tokens that are not this server’s own tokens.
| Method | Default | What it does |
|---|---|---|
label(&self) -> &str | required | The credential’s name in lower case, as it reads in a sentence: password, Companies House API key. It names the field and appears in messages. It is also part of the sign-in version, so changing it signs everyone out. |
help(&self) -> &str | "" | One sentence of plain-text help under the field: what the credential is and where to get one. |
prepare(&self, entered) -> &str | trims surrounding whitespace | Turns what was typed, or sent as a bearer token, into the credential to check. Pasted keys often carry spaces; PasswordVerifier keeps them. |
plausible(&self, credential) -> bool | credential::plausible | Whether the input has the shape of a credential. Implausible input is refused locally: it is never sent upstream and does not count as a failed attempt. |
check(&self, credential) -> CheckFuture | required | Checks the credential, typically with one cheap authenticated request upstream. |
carried(&self) -> bool | true | Whether the credential is the person’s own key to the upstream service: sealed into their tokens and handed to tools. false for a password that only proves who may sign in. |
accepts_bearer(&self) -> bool | carried() | Whether a client may send the credential itself as its bearer token instead of signing in with OAuth. |
subject(&self, credential) -> Option<String> | None | Who signed in, as tokens, logs and the audit log name them. None lets the server name them (see Subjects). It must not reveal the credential. |
generation(&self) -> &[u8] | empty | Bytes that change whenever every earlier sign-in should end, such as a hash of a password or the upstream environment. They go into the sign-in version with the label. |
upstream(&self) -> Option<&dyn UpstreamSignIn> | None | An upstream OAuth provider people sign in through instead of typing a credential. See Signing in through an upstream provider. |
The default plausible accepts 1 to 256 bytes (credential::MAX_CREDENTIAL_LEN) of visible ASCII without spaces. Narrow it when the upstream service’s credentials have a known form, so other tokens are refused without asking upstream:
#![allow(unused)]
fn main() {
use mcp_server_core::credential::{CheckFuture, CredentialCheck, CredentialVerifier};
async fn whoami(_key: &str) -> Result<bool, String> { Ok(true) }
/// Keys for the Example API: `ex_` and 32 letters or digits.
struct ExampleKeys;
impl CredentialVerifier for ExampleKeys {
fn label(&self) -> &str {
"Example API key"
}
fn help(&self) -> &str {
"Create one under Settings, API keys at example.com."
}
fn plausible(&self, key: &str) -> bool {
key.len() == 35
&& key.starts_with("ex_")
&& key[3..].bytes().all(|b| b.is_ascii_alphanumeric())
}
fn check<'a>(&'a self, key: &'a str) -> CheckFuture<'a> {
Box::pin(async move {
// For example GET /v1/me with the key: 200, 401, or the API is down.
match whoami(key).await {
Ok(true) => CredentialCheck::Valid,
Ok(false) => CredentialCheck::Invalid(None),
Err(why) => CredentialCheck::Unavailable(why),
}
})
}
}
assert!(ExampleKeys.plausible("ex_0123456789abcdef0123456789abcdef"));
assert!(!ExampleKeys.plausible("ghp_0123456789abcdef0123456789abcdef"));
}
The api_keys example is a complete server built this way.
Verdicts
check returns a CredentialCheck:
| Verdict | Meaning | On the sign-in page | On a bearer request | Counts as a failed attempt |
|---|---|---|---|---|
Valid | Accepted. | Signs the person in. | Lets the request through. | No |
Invalid(reason) | Rejected. reason is shown when it is more useful than the default. | 401 with the reason, or That <label> was not accepted. | 401 | Yes |
Unavailable(why) | Could not be checked now: upstream down or rate limited. | 503 with Your <label> could not be checked right now: <why> | 503 with the same text | No |
Both 503 answers carry Retry-After: 30. On a bearer request, Valid and Invalid verdicts are remembered for a while and Unavailable is not; how long is on Limits and abuse protection.
Input refused by plausible gets a 401 and That is not a <label>. on the sign-in page, and a 401 on a bearer request. CredentialCheck is #[non_exhaustive].
Checks run with a timeout, with a cap on how many run at once, and once at a time per credential: requests that arrive while a credential is being checked share that check. A check that times out is Unavailable("the check timed out"), and one that cannot get a slot is Unavailable("the server is checking too many credentials at once"). The numbers, and how attempts count towards the sign-in limits, are on Limits and abuse protection.
PasswordVerifier
PasswordVerifier::new(password) takes a secrecy::SecretString, which .into() makes from a String, and accepts exactly that password, compared in constant time. It is what SignIn::OwnerPassword builds, and you can build one yourself in a SignIn::Custom function. Its behaviour differs from the defaults:
| Method | PasswordVerifier |
|---|---|
label | password |
prepare | Keeps the input as typed. |
plausible | Non-empty and at most 1,024 bytes. |
carried | false, so accepts_bearer is false too. |
generation | A SHA-256 hash of the password, so a new password ends every earlier grant. |
It keeps the defaults for help (none) and subject (None, so the server names the person owner). Its Debug output is PasswordVerifier(..).
Sealed credentials
With a carried credential the server stores nothing. The credential is checked once, then sealed into the person’s tokens by a Sealer:
- Cipher: ChaCha20-Poly1305, with a fresh random nonce for every seal.
- Key: derived from
OAUTH_SIGNING_KEYwith HKDF-SHA256, so whoever holds the signing key can open every sealed credential. Keep it secret. - Where: the
credentialclaim of the authorization code, the access token and the refresh token. Anyone holding a token can read its claims, but not the sealed credential. - Rotation: changing
OAUTH_SIGNING_KEYmakes every sealed credential unreadable, along with every token.
On each request the bearer guard opens the sealed credential and adds it to the request as a Credential. An access token whose credential does not open is refused with 401. At the token endpoint, a code or refresh token whose credential is missing or does not open gets invalid_grant with grant has no credential.
A sealed value is base64url(nonce || ciphertext || tag). Sealer::new(signing_key), seal(&str) and open(&str) are public, for tests and lower-level servers; seal and open fail with a SealError (sealing failed, or the sealed credential is invalid). AuthState::sealer returns the server’s own.
A password that is not carried, such as the owner’s, never enters a token: it only decides whether the code is issued.
Reading the credential in a tool
A tool takes rmcp’s Extension<Parts> argument and reads the Credential from the request extensions:
use mcp_server_core::rmcp;
use mcp_server_core::axum::http::request::Parts;
use mcp_server_core::credential::Credential;
use mcp_server_core::rmcp::handler::server::router::tool::ToolRouter;
use mcp_server_core::rmcp::handler::server::tool::Extension;
use mcp_server_core::rmcp::model::{CallToolResult, ContentBlock, ServerCapabilities, ServerConfig};
use mcp_server_core::rmcp::{ErrorData as McpError, ServerHandler, tool, tool_handler, tool_router};
#[derive(Clone)]
struct AccountTools {
tool_router: ToolRouter<Self>,
}
#[tool_router]
impl AccountTools {
fn new() -> Self {
Self { tool_router: Self::tool_router() }
}
#[tool(description = "Show which key this connection uses.", annotations(read_only_hint = true))]
async fn whoami(&self, Extension(parts): Extension<Parts>) -> Result<CallToolResult, McpError> {
let Some(key) = parts.extensions.get::<Credential>() else {
return Ok(CallToolResult::error(vec![ContentBlock::text("unauthenticated: no key")]));
};
// Send key.expose() upstream. Never log it.
let shown = &key.expose()[key.expose().len().saturating_sub(4)..];
Ok(CallToolResult::success(vec![ContentBlock::text(format!(
"You are using the key ending {shown}."
))]))
}
}
#[tool_handler(router = self.tool_router)]
impl ServerHandler for AccountTools {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
}
}
fn main() { let _ = AccountTools::new(); }
Credential item | Returns |
|---|---|
Credential::new(secret) | A credential wrapping secret, for tests or middleware of your own. |
expose() | The secret, to send upstream. Never log it. |
fingerprint() | Its SHA-256 as [u8; 32], safe as a map key, for example to keep one upstream client per person. Not for logs. credential::fingerprint(&str) computes the same for any string. |
Its Debug output is Credential(..), so the secret cannot leak through a stray {:?}. A request has a Credential only when the verifier carries credentials. Requests made with the owner’s password or the static token have none.
Credentials sent as bearer tokens
When the verifier’s accepts_bearer() is true (the default for carried credentials), a client may skip OAuth and send the credential itself:
POST /example HTTP/1.1
Host: mcp.example.com
Authorization: Bearer ex_0123456789abcdef0123456789abcdef
The bearer guard works through a token in this order:
- This server’s own token. A token shaped like a JWT is verified as an access token for the path. If it is not one but names this server as its issuer, for example an expired token or one for another service, it is refused with 401. This server’s tokens are never sent upstream and never count as failed attempts. When the verifier does not accept bearer credentials, every other token shaped like a JWT is refused the same way.
- The static token, when
MCP_AUTH_TOKENis set (never alongside a verifier that accepts bearer credentials). - The person’s credential. The guard applies
prepareandplausible, then looks the credential up in a short cache of recent verdicts, keyed by its SHA-256. On a miss it runscheck. The attempt counts towards the sign-in limits while the check runs, and afterwards only if the credential was rejected.
A valid credential gets a Caller with Via::Credential and, when the verifier carries credentials, the same Credential extension as an OAuth token. Any other answer is a 401, except Unavailable, which is a 503, and a refusal by the sign-in limits, which is a 429 (or a 503 while the server refuses new addresses under heavy load). A credential that has the shape of a JWT but was not issued here is checked as a credential. A credential found valid recently is let in even from an address that is blocked for too many failures: its holder has already proved possession.
To allow OAuth only, override accepts_bearer to return false.
The static token
MCP_AUTH_TOKEN is a fixed bearer token for clients that can send a header, such as Claude Code. It is accepted on every service path and on /mcp.
MCP_AUTH_TOKEN=$(openssl rand -hex 32)
| Rule | Error or warning |
|---|---|
| Only when sign-in does not carry credentials and does not accept them as bearer tokens. Requests made with it would lack the credential tools expect, and wrong tokens could be tried upstream as credentials. | MCP_AUTH_TOKEN cannot be used when people sign in with their own <label> |
| Must not have the shape of a JWT: exactly two dots. | MCP_AUTH_TOKEN must not have the shape of a JWT (three dot-separated parts) |
Should be at least 32 characters (app::RECOMMENDED_STATIC_TOKEN_CHARS). | Warning: MCP_AUTH_TOKEN is shorter than 32 characters: use a long random value |
Both errors stop the server at startup, listed with the other configuration errors. They are checked only once the core settings, such as PUBLIC_URL and OAUTH_SIGNING_KEY, are valid, and the first only once the verifier has been built. AuthState::new panics with the same messages if you build a server without app::Server.
How it behaves:
- It is compared in constant time.
- Every bearer token that does not have the shape of a JWT counts towards the sign-in limits before it is compared, which bounds how fast anyone can guess the static token. A blocked address cannot use even the right token until the limit clears; OAuth tokens already issued keep working. Tokens shaped like a JWT cannot be the static token and are refused without counting.
- Requests made with it have the subject
static, noCredentialand no OAuth claims. The audit log records them as callerstatic. - It is not part of the sign-in version: changing it does not end OAuth grants, and changing
OAUTH_ADMIN_PASSWORDdoes not change it.
Treat it like the owner’s password. Leave it unset if every client signs in with OAuth: then, on an owner’s-password server, bearer tokens that are not this server’s are refused without counting, so junk cannot lock anyone out.
Who made a request
The bearer guard adds a caller::Caller to every request it lets through. It has two fields:
subject: who signed in.via: how the request was authenticated, aVia.
Via | Meaning | Audit log caller |
|---|---|---|
OAuth { client_id } | An access token this server issued, to this client. | oauth:<client_id>, or oauth without a client id |
Credential | The person’s credential sent as the bearer token. | credential |
StaticToken | MCP_AUTH_TOKEN. | static |
Caller::audit_label() returns the audit log’s form. A request with an OAuth token also carries the token’s jwt::Claims. Both Caller and Via are #[non_exhaustive]; Caller::new builds one for your own middleware or tests.
Subjects
| Subject | When |
|---|---|
owner | The owner’s password, or any verifier that does not carry credentials and names no subject. |
key: and 16 hex digits | A carried credential, when the verifier names no subject. The digits are a hash of the credential keyed by OAUTH_SIGNING_KEY, so the subject identifies one person without letting anyone who sees it guess the credential offline. Rotating the key changes every such subject. |
static | The static token. |
| anything else | What your verifier’s subject() returns. |
The subject is the sub claim of the person’s code, access and refresh tokens, and it is kept through refreshes. Logs and the audit log use it, never the credential. AuthState::subject_of returns the subject the server gives a credential.
Reading it in a tool, for example to attribute a change:
#![allow(unused)]
fn main() {
use mcp_server_core::axum::http::request::Parts;
use mcp_server_core::caller::{Caller, Via};
fn changed_by(parts: &Parts) -> String {
let Some(caller) = parts.extensions.get::<Caller>() else {
return "unknown".into();
};
let how = match &caller.via {
Via::OAuth { client_id: Some(id) } => format!("OAuth client {id}"),
Via::OAuth { client_id: None } => "OAuth".into(),
Via::Credential => "their own key".into(),
Via::StaticToken => "the static token".into(),
_ => "another way".into(),
};
format!("{} via {how}", caller.subject)
}
let (mut parts, ()) = mcp_server_core::axum::http::Request::new(()).into_parts();
parts.extensions.insert(Caller::new("owner", Via::OAuth { client_id: Some("c1".into()) }));
assert_eq!(changed_by(&parts), "owner via OAuth client c1");
}
The OAuth client id is a long signed token; record it only where its length does not matter.
Next: OAuth and tokens.
OAuth and tokens
Every server built on mcp-server-core is its own OAuth 2.1 authorization server, built for MCP clients such as claude.ai. This page follows a sign-in from the first 401 to a refreshed token, and explains every token the server issues, how long each lasts and what ends a grant. How people prove who they are on the sign-in page is on Sign-in modes; the routes and their responses are listed on Endpoints.
Overview
The server plays both OAuth roles. It is the authorization server that signs people in and issues tokens, and every service path is a protected resource that accepts them.
- Standards: OAuth 2.1 with the authorization code grant and PKCE (S256), dynamic client registration (RFC 7591), authorization-server metadata (RFC 8414), protected-resource metadata (RFC 9728), resource indicators (RFC 8707) and the
issauthorization response parameter (RFC 9207). This is what the MCP authorization specification asks for. - Public clients only: clients register without a secret and do not authenticate at the token endpoint. PKCE protects the code instead.
- Stateless: client registrations, sign-in forms, codes, access tokens and refresh tokens are all HS256 JWTs signed with
OAUTH_SIGNING_KEY. Nothing needs storing, so restarts and extra replicas sign nobody out. See What statelessness means. - One resource per service: each service path, and
/mcp, is its own protected resource, and an access token works only on the path it was issued for.
The flow
A client connecting to a service called weather on https://mcp.example.com:
sequenceDiagram
participant C as MCP client
participant S as Server
participant P as Person (browser)
C->>S: POST /weather (no token)
S-->>C: 401, WWW-Authenticate with resource_metadata
C->>S: GET /.well-known/oauth-protected-resource/weather
S-->>C: resource and authorization server
C->>S: GET /.well-known/oauth-authorization-server
S-->>C: endpoints, S256, grant types
C->>S: POST /register (redirect_uris, client_name)
S-->>C: 201 with client_id
C->>P: open /authorize (PKCE S256, resource, state)
P->>S: GET /authorize
S-->>P: sign-in page, bound to this request
P->>S: POST /authorize with the credential
S->>S: check it (upstream for a personal key)
S-->>P: 303 to redirect_uri with code, state and iss
P->>C: code
C->>S: POST /token (code, code_verifier)
S-->>C: access token (1 hour) and refresh token (30 days)
C->>S: POST /weather with Bearer access token
S-->>C: MCP response
loop Every hour, until the grant ends
C->>S: POST /token (refresh_token)
S-->>C: new access and refresh tokens
end
The person sees one page: the sign-in form. Everything else happens between the client and the server.
Discovery
A request to a service path without a token gets a 401 whose WWW-Authenticate header names the service’s protected-resource metadata:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/weather"
That document names the resource (https://mcp.example.com/weather) and the authorization server (https://mcp.example.com). The authorization-server metadata at /.well-known/oauth-authorization-server then lists the registration, authorization and token endpoints and what they support. Every field of both documents is on Endpoints.
All endpoints live at the root of PUBLIC_URL, which is also the issuer. PUBLIC_URL cannot have a path, so the well-known locations are always at the host’s root.
Dynamic client registration
A client registers itself by posting JSON to /register:
POST /register HTTP/1.1
Host: mcp.example.com
Content-Type: application/json
{"redirect_uris": ["https://claude.ai/api/mcp/auth_callback"], "client_name": "Claude"}
{
"client_id": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"client_id_issued_at": 1792317600,
"client_name": "Claude",
"redirect_uris": ["https://claude.ai/api/mcp/auth_callback"],
"token_endpoint_auth_method": "none",
"grant_types": ["authorization_code", "refresh_token"],
"response_types": ["code"]
}
The answer is 201 Created. The client_id is itself a signed token that holds the redirect URIs and the name, so nothing is stored and a registration never expires. It stops working only when OAUTH_SIGNING_KEY or PUBLIC_URL changes. Only redirect_uris and client_name are read; other fields of the request are ignored, and every client is public. client_name is null in the answer when none was sent.
Registration is open to anyone, so its input is capped:
| What | Limit | Error (400) |
|---|---|---|
| Body | A JSON object, sent as Content-Type: application/json, whose fields have the right types | invalid_client_metadata: send a JSON client registration with redirect_uris |
| Number of redirect URIs | 1 to 10; a body without redirect_uris has none | invalid_redirect_uri |
| Length of each redirect URI | at most 2,048 bytes | invalid_redirect_uri |
| Redirect URI scheme | https with a host, or http only on localhost, 127.0.0.1 or [::1] (native apps, RFC 8252) | invalid_redirect_uri |
| Redirect URI parts | no fragment, no user name or password | invalid_redirect_uri |
client_name | optional; at most 200 characters, without control characters | invalid_client_metadata: client_name must be at most 200 characters, without control characters |
Every invalid_redirect_uri error has the description redirect_uris must be 1 to 10 https URIs (http only on a loopback host), at most 2048 bytes each, without fragments or userinfo. client_name is checked first. A body over the body limit gets 413 instead. The caps are public as oauth::MAX_REDIRECT_URIS, MAX_REDIRECT_URI_LEN and MAX_CLIENT_NAME_CHARS, and oauth::validate_redirect_uri applies the redirect URI rules.
The client’s name is self-reported. The sign-in page shows it marked as unverified, next to the host the person will be sent back to.
Client ID Metadata Documents, which the MCP authorization specification now prefers to dynamic registration, are planned.
The authorization request
The client sends the person’s browser to /authorize with these query parameters:
| Parameter | Required | Value |
|---|---|---|
response_type | yes | code |
client_id | yes | The client_id from registration. |
redirect_uri | yes | Exactly one of the registered redirect URIs. |
code_challenge | yes | The PKCE S256 challenge: 43 characters. |
code_challenge_method | yes | S256 |
state | no | Returned unchanged with the code. An empty value counts as absent. |
resource | see below | The URL of the service, such as https://mcp.example.com/weather, or of /mcp. |
scope | no | Ignored: the resource decides what is granted. |
Choosing the resource
resource must be exactly PUBLIC_URL/<service>: no trailing slash, no other host. Without it, a server with exactly one service grants that service, which keeps clients written before the 2025-06-18 MCP authorization specification working. The combined /mcp endpoint is never chosen by default, and a server with several services needs resource.
Errors
Problems with the client or the redirect URI are shown in the browser and never redirected, because the redirect URI cannot be trusted yet:
| Problem | Response |
|---|---|
No client_id | 400 page: missing client_id |
client_id that this server did not sign | 400 page: unknown client |
No redirect_uri | 400 page: missing redirect_uri |
redirect_uri not registered | 400 page: redirect_uri is not registered for this client |
Other problems are sent back to the redirect URI with error, error_description, state (when there is one) and iss. The redirect is 302 Found from the GET, and 303 See Other when the sign-in form was posted:
| Problem | error | error_description |
|---|---|---|
response_type is not code | unsupported_response_type | response_type must be code |
code_challenge_method is not S256 | invalid_request | code_challenge_method must be S256 |
No code_challenge, or not 43 characters | invalid_request | code_challenge is required |
No resource on a server with several services | invalid_target | resource is required: name the URL of the service, or of /mcp for every service |
resource is not a service on this server | invalid_target | resource is not a service on this server |
The sign-in page
GET /authorize with a valid request shows the sign-in page. It tells the person:
- what is asking: “An MCP client is requesting access to the weather service on this server”, or to “every service on this server, through
/mcp”; - the client’s name, as “self-reported, unverified”, when it registered one;
- where they will be sent: “After you authorize, you will be sent to claude.ai.”;
- what to enter, named by the verifier’s label, with its help text. For a personal credential the page explains that it is checked once and kept only in encrypted form inside the connection’s tokens, and turns autocomplete off. For a password it allows password managers to fill the field.
Every value on the page is HTML-escaped.
The form is bound to its request
The form carries the request’s parameters as hidden fields and a signed token (kind csrf) that holds a hash of the client id, redirect URI, PKCE challenge, state, granted service and resource. The token is valid for 10 minutes. When the form is posted, the server validates the request again and compares the hash in constant time, so a form cannot be replayed with any parameter changed. An expired or altered form gets a 400 page: The login form expired or was modified. Start the connection again.
Page headers
Every page /authorize renders, the sign-in page and its error pages, is sent with:
| Header | Value | Why |
|---|---|---|
X-Frame-Options | DENY | No other site can frame the page to trick a click. |
Content-Security-Policy | default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none' | No scripts, images or other loads; inline styles only; no framing. |
Cache-Control | no-store | Nothing is cached. |
Referrer-Policy | no-referrer | The page’s URL and parameters never leak in a Referer header. |
A 429 or 503 page also carries Retry-After: 30.
Posting the form
POST /authorize checks, in order: the sign-in limits for the client’s address, the request, the form binding, the credential’s shape, and then the credential itself.
| Outcome | Response |
|---|---|
| The address is refused by the sign-in limits | 429 page (or 503 while the server refuses new addresses under heavy load), with Retry-After: 30 |
| The input is not plausible for the verifier | 401, the page again with That is not a <label>. Not counted as a failed attempt. |
| The credential is rejected | 401, the page again with the verifier’s reason or That <label> was not accepted. Counted as a failed attempt. |
| The credential could not be checked | 503, the page again with Your <label> could not be checked right now: <why>, and Retry-After: 30. Not counted. |
| The credential is accepted | 303 See Other to the redirect URI with code, state and iss, and Cache-Control: no-store |
A successful redirect looks like this:
HTTP/1.1 303 See Other
Location: https://claude.ai/api/mcp/auth_callback?code=eyJ0eXAi...&state=af0ifjsl&iss=https%3A%2F%2Fmcp.example.com
Cache-Control: no-store
- 303, not 302, so no browser re-sends the form body, which holds the credential, to the client’s redirect URI (RFC 9700).
issnames this server, so a client talking to several authorization servers can tell which one answered (RFC 9207). Error redirects carry it too, and the metadata advertises it withauthorization_response_iss_parameter_supported.- The code is valid for 60 seconds and can be used once. It is bound to the client, the redirect URI, the PKCE challenge and the resource, and carries who signed in, the sign-in version, the sign-in time and, for a personal credential, the sealed credential.
PKCE
PKCE (RFC 7636) is required, with the S256 method only; plain is refused.
- The
code_challengesent to/authorizemust be 43 characters, the length of a base64url SHA-256. - The
code_verifiersent to/tokenmust be 43 to 128 characters fromA-Z,a-z,0-9,-,.,_and~. - The server computes
BASE64URL(SHA256(code_verifier))and compares it with the challenge in constant time. A mismatch isinvalid_grantwithPKCE verification failed.
Because the code is useless without the verifier, which never leaves the client, an intercepted code cannot be exchanged by anyone else.
The token endpoint
POST /token takes a form (application/x-www-form-urlencoded) with each parameter at most once. There is no client authentication: client_id names the client, and the code or refresh token must have been issued to it.
Exchanging a code
| Parameter | Value |
|---|---|
grant_type | authorization_code |
code | The code from the redirect. |
client_id | The client the code was issued to. |
code_verifier | The PKCE verifier. |
redirect_uri | The redirect URI the code was issued for. |
resource | Optional. If sent, it must be the resource of the grant. |
curl -s https://mcp.example.com/token \
-d grant_type=authorization_code \
-d code="$CODE" \
-d client_id="$CLIENT_ID" \
-d code_verifier="$CODE_VERIFIER" \
--data-urlencode redirect_uri=https://app.example.com/callback
Refreshing
| Parameter | Value |
|---|---|
grant_type | refresh_token |
refresh_token | The refresh token. |
client_id | The client the refresh token was issued to. |
resource | Optional. If sent, it must be the resource of the grant. |
A refresh returns a new access token and a new refresh token for the same grant. The old refresh token keeps working until it expires; see What statelessness means.
The response
Both grants answer 200 with Cache-Control: no-store:
{
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"token_type": "Bearer",
"expires_in": 3600,
"refresh_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9...",
"scope": "weather"
}
scope is the granted service’s name (mcp for the combined endpoint). expires_in is 3600 unless the grant ends sooner.
Errors
Every error is a 400 with a JSON body such as {"error": "invalid_grant", "error_description": "sign in again"} and Cache-Control: no-store:
error | error_description | Cause |
|---|---|---|
invalid_request | send a form with grant_type and each parameter at most once | Not a form, no grant_type, or a repeated parameter. |
unsupported_grant_type | use authorization_code or refresh_token | Any other grant type. |
invalid_request | code, client_id, code_verifier and redirect_uri are required | A parameter of the code exchange is missing. |
invalid_grant | invalid or expired code | Not a code from this server, or older than 60 seconds. |
invalid_grant | code was issued to a different client or redirect_uri | client_id or redirect_uri differ from the authorization request. |
invalid_grant | PKCE verification failed | The verifier is malformed or does not match the challenge. |
invalid_grant | code already used | The code was exchanged before. |
invalid_request | refresh_token and client_id are required | A parameter of the refresh is missing. |
invalid_grant | invalid or expired refresh token | Not a refresh token from this server, or expired. |
invalid_grant | refresh token has no client | The refresh token names no client. |
invalid_grant | refresh token was issued to a different client | client_id differs from the one the token was issued to. |
invalid_client | unknown client | The client_id is not a registration this server signed. |
invalid_grant | grant has no resource | The code or refresh token names no resource. |
invalid_target | resource does not match the grant | A resource parameter names another resource. |
invalid_target | resource is not a service on this server | The granted service is no longer enabled. |
invalid_grant | grant has no credential | Personal credentials are in use, and the grant carries none that opens with the current key. |
invalid_grant | sign in again | The grant has ended: see What ends a grant. |
A body larger than the body limit gets 413 instead.
Resource indicators and audiences
Every service is its own protected resource, PUBLIC_URL/<service>, and so is /mcp when the combined endpoint is on. A person signs in for one resource at a time, and the access token’s audience (aud) is that resource’s URL:
- A token issued for
/weatheris refused on/tides, and on/mcp. - A token issued for
/mcpis refused on/weather. - Codes, refresh tokens, registrations and form tokens have the authorization server itself,
PUBLIC_URL, as their audience, so none of them is ever accepted on a service path.
Each connector added for a service is therefore a separate sign-in. To use every service through one sign-in, connect to /mcp. The OAuth scope follows the resource: the token response and the metadata name services, and a scope sent by the client is ignored.
Tokens
The server issues five kinds of token. All are JWTs signed with HS256 under OAUTH_SIGNING_KEY, with PUBLIC_URL as issuer. The kind is in the typ claim, and a token of one kind is never accepted as another.
Kind (typ) | Audience | Subject | Lifetime | Carries |
|---|---|---|---|---|
client | PUBLIC_URL | server | none | redirect_uris, client_name |
csrf | PUBLIC_URL | server | 10 minutes | binding: the hash of the authorization request |
code | PUBLIC_URL | who signed in | 60 seconds, used once | client_id, redirect_uri, code_challenge, scope, resource, credential, ver, auth_time |
access | PUBLIC_URL/<service> | who signed in | 1 hour, never past the grant | client_id, scope, resource, credential, ver, auth_time |
refresh | PUBLIC_URL | who signed in | 30 days, never past the grant | the same as access |
Every token also has iss, aud, sub, typ, a random 128-bit jti and iat; every kind except client has exp. Expiry allows 5 seconds of clock skew. credential is present only when people sign in with their own credential, and is sealed. The subject is described under Subjects. The claims are documented on jwt::Claims and jwt::Payload.
A grant is everything one sign-in leads to: its code, and every access and refresh token issued from it through refreshes. Every token of a grant carries the same sub, ver and auth_time.
ver: the sign-in version
ver is a keyed hash, under OAUTH_SIGNING_KEY, of how people sign in: whether credentials are carried, the verifier’s label and its generation (see the CredentialVerifier trait). For the owner’s password the generation is a hash of the password.
Every code, access and refresh token must carry the current ver, and must carry a sealed credential exactly when credentials are carried. Otherwise an access token is refused with 401, and a code or refresh token gets invalid_grant with sign in again (or with grant has no credential, when credentials are carried and the token has none that opens). So:
- changing the owner’s password ends every earlier grant;
- switching sign-in mode, or to a verifier with another label or generation, ends every earlier grant;
- a token minted for one sign-in mode or upstream service is refused by a server using another, even with the same key and URL, so a sealed credential never reaches the wrong upstream.
AuthState::sign_in_version returns the current value, and oauth::sign_in_version(signing_key, verifier) computes it without an AuthState.
auth_time and the 90-day limit
auth_time is when the person signed in, in Unix seconds. It is set on the code and copied into every token of the grant, however often it is refreshed. A grant holds while it is less than 90 days old (MAX_GRANT_AGE). A time ahead of this replica’s clock, as another replica may set it, is accepted: only the age is checked, and auth_time is signed.
No token outlives its grant. An access token lasts 1 hour or until the grant ends, whichever is sooner, and a refresh token 30 days or until the grant ends. A client that refreshes at least once every 30 days stays signed in until the 90 days are up; then the person signs in again. The client keeps its registration, so a connector does not need to be added again.
What ends a grant
| Event | Effect | What the person does |
|---|---|---|
| The access token is an hour old | 401 on the service path | Nothing: the client refreshes. |
| The client has not refreshed for 30 days | Its refresh token has expired: invalid_grant: invalid or expired refresh token | Signs in again. |
| 90 days since sign-in | The grant’s last access and refresh tokens expire with it: 401 on the service path, and invalid_grant on refresh (invalid or expired refresh token, or sign in again). | Signs in again. |
OAUTH_ADMIN_PASSWORD changes | Every grant ends (ver changes). | Signs in again with the new password. Connectors are not added again. |
| The sign-in mode, or the verifier’s label or generation, changes | Every grant ends (ver changes). | Signs in again. |
OAUTH_SIGNING_KEY changes | Every token, client registration and sealed credential stops working. | Clients register again: in claude.ai, remove the connector and add it again. |
PUBLIC_URL changes | Every token and client registration names the old issuer and is refused. | As for a new key, at the new URL. |
| The service is no longer enabled | Its path is gone; a refresh gets invalid_target: resource is not a service on this server. | Connects to a service that is enabled. |
Restarts, extra replicas and changes to MCP_AUTH_TOKEN end nothing.
What statelessness means
The server keeps no lasting record of clients, sign-ins or tokens; only codes recently exchanged are remembered, in memory. Each replica needs only the same configuration, above all the same OAUTH_SIGNING_KEY, and there is no database or volume to back up. The price:
- No revoking one person or one client. Revocation is all or nothing: rotate
OAUTH_SIGNING_KEY(everyone signs in again and clients register again) or, with the owner’s password, change the password (everyone signs in again). With personal credentials, revoking a key upstream stops it working through the server as well: the tokens still open, but the upstream service refuses the key. - No refresh-token reuse detection. OAuth 2.1 asks an authorization server to notice when an old refresh token is used again and revoke the grant, which needs a record of every grant. A stolen refresh token works until it expires, the grant reaches 90 days, the owner’s password changes or the key is rotated.
- One-time codes are remembered per replica. Each replica remembers the codes it has exchanged, in memory, until they expire. Behind several replicas, or across a restart, a code could be exchanged once more within its 60 seconds; the exchange still needs the PKCE verifier, which only the client has.
The other state kept in memory, such as the sign-in limits, is described on Architecture and Limits and abuse protection. The threat model is on Security model.
Minting a token in a test
To test a service behind the real bearer guard, mint an access token with the server’s own AuthState. It must carry the current ver and an auth_time, or the guard refuses it:
#![allow(unused)]
fn main() {
use mcp_server_core::credential::PasswordVerifier;
use mcp_server_core::jwt::{Payload, TokenKind};
use mcp_server_core::oauth::{AuthState, OAuthSettings};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
let st = AuthState::new(
OAuthSettings {
public_url: "https://mcp.example.com".into(),
signing_key: "0123456789abcdef0123456789abcdef".to_string().into(),
trusted_proxies: Vec::new(),
static_token: None,
},
&["weather"],
Arc::new(PasswordVerifier::new("a long password".to_string().into())),
);
let now = SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs();
let resource = st.resource("weather");
let access = st.jwt().issue_as(
TokenKind::Access,
Some(Duration::from_secs(3600)),
Payload {
client_id: Some("test-client".into()),
scope: Some("weather".into()),
resource: Some(resource.clone()),
ver: Some(st.sign_in_version().to_string()),
auth_time: Some(now),
..Default::default()
},
&resource,
"owner",
)?;
// Send `Authorization: Bearer <access>` to the router built with `st`.
let claims = st.jwt().verify_for(&access, TokenKind::Access, "https://mcp.example.com/weather")?;
assert_eq!(claims.aud, "https://mcp.example.com/weather");
assert_eq!(claims.sub, "owner");
assert!(st.jwt().verify_for(&access, TokenKind::Access, "https://mcp.example.com/tides").is_err());
Ok::<(), Box<dyn std::error::Error>>(())
}
With personal credentials, put st.sealer().seal(key)? in credential as well. server::build_app builds a router around an AuthState; see Lower-level API.
Next: Connecting clients.
Connecting clients
This page shows how to add a server to claude.ai, Claude Desktop, Claude mobile, Claude Code and other MCP clients, and which URL to give each. The examples use a server at https://mcp.example.com with two services, weather and tides.
Which URL to use
Each service is a separate MCP server at its own path, and /mcp offers every service together:
| URL | What the client gets |
|---|---|
https://mcp.example.com/weather | The weather service’s tools and prompts under their own names, and its resources if it serves them. |
https://mcp.example.com/tides | The tides service, likewise. |
https://mcp.example.com/mcp | Every service’s tools and prompts in one connector, named <service>_<name>, such as weather_forecast. |
- Each URL is its own sign-in. A token issued for
/weatheris refused on/tidesand on/mcp; see Resource indicators and audiences. A per-service connector is the narrower grant. - Use per-service URLs or
/mcp, not both. With both, every tool appears twice. - Read-only rules are the same on both. A service made read-only with
<PREFIX>_READ_ONLYis read-only on its own path and under/mcp; see Read-only mode and the audit log. - Resources are served on each service’s own path only. Connect to the service’s URL if you need them.
/mcpcan be turned off with<PREFIX>_COMBINED=false; it then answers 404. See Several services and /mcp.
At startup the server logs a service enabled line with the URL of each service, and combined endpoint enabled with the URL of /mcp.
claude.ai, Claude Desktop and Claude mobile
claude.ai connects from Anthropic’s servers, not from your computer. The server must be reachable from the internet at PUBLIC_URL, with a certificate from a public certificate authority. A self-signed certificate or a localhost URL does not work; see TLS and deployment.
- In claude.ai, open Settings, then Connectors, then Add custom connector.
- Enter the URL, for example
https://mcp.example.com/weather, orhttps://mcp.example.com/mcpfor every service. - claude.ai registers itself with the server and opens the sign-in page. The page names the service, or “every service on this server, through
/mcp”, and the host you will be sent back to,claude.ai. - Enter what the page asks for: the owner’s password, or your own key for the upstream service.
The connector then works on its own. Its access token lasts an hour, and it refreshes it without asking you. It asks you to connect again:
- 90 days after you signed in;
- when it has not refreshed for 30 days, so its refresh token has expired;
- when the owner’s password, or the way people sign in, changes.
When OAUTH_SIGNING_KEY or PUBLIC_URL changes, the connector’s registration stops working too: remove the connector and add it again. What ends a grant has the full list.
Connectors added in claude.ai are also available in Claude Desktop and the Claude mobile apps.
Claude Code
Claude Code runs on your computer, so it can also reach a server on your network or on localhost. It can sign in with OAuth or send a header.
Signing in with OAuth
claude mcp add --transport http weather https://mcp.example.com/weather
Then run /mcp inside Claude Code, choose the server and authenticate. Your browser opens the server’s sign-in page. Claude Code registers a redirect URI on localhost, which the server accepts for native apps.
With the static token
On a server that uses the owner’s password and sets MCP_AUTH_TOKEN, skip OAuth by sending the token as a header:
claude mcp add --transport http sea https://mcp.example.com/mcp \
--header "Authorization: Bearer $MCP_AUTH_TOKEN"
The static token is accepted on every service path and on /mcp, so the same header works for https://mcp.example.com/weather. See The static token for its rules.
With your own key
On a server where each person signs in with their own credential, send yours directly, if the server accepts credentials as bearer tokens (the default):
claude mcp add --transport http example https://mcp.example.com/example \
--header "Authorization: Bearer $EXAMPLE_API_KEY"
The server checks the key upstream the first time and remembers the verdict briefly. See Credentials sent as bearer tokens.
Claude Code stores the header with the server’s configuration. Avoid --scope project for a header that holds a secret: that scope writes it to .mcp.json in the project, which is often committed.
Other MCP clients
Any client that speaks the MCP Streamable HTTP transport works, in one of two ways:
- OAuth. The client follows the MCP authorization specification: it reads the
WWW-Authenticateheader of the first 401, fetches the metadata, registers itself, and signs in with the authorization code grant and PKCE (S256). It must sendresourcewith the URL it connects to when the server has more than one service, and register anhttpsredirect URI or anhttpone onlocalhost,127.0.0.1or[::1]. OAuth and tokens describes every step. - A bearer header. The client sends
Authorization: Bearerwith the static token, or with the person’s own credential where the server accepts it.
To try a server interactively, run the MCP Inspector with npx @modelcontextprotocol/inspector, choose the Streamable HTTP transport, enter the URL, and either sign in with OAuth or add an Authorization header.
Checking a connection by hand
An initialize request with curl shows whether the token, the host and the service work, without a client in the way:
curl -si https://mcp.example.com/weather \
-H "Authorization: Bearer $MCP_AUTH_TOKEN" \
-H "Content-Type: application/json" \
-H "Accept: application/json, text/event-stream" \
-d '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"curl","version":"1"}}}'
A 200 with an Mcp-Session-Id header and the initialize result means everything works. Other answers point to the cause:
| Response | Meaning |
|---|---|
401 with WWW-Authenticate | No token, or one this path does not accept. With error="invalid_token", a token was sent and refused. See Endpoints. |
403 Forbidden: Host header is not allowed | The request reached the server under another host name than PUBLIC_URL’s, often because a proxy rewrote Host. See Host and Origin checks. |
403 Forbidden: Origin header is not allowed | A browser-based client on another origin. Add it to ALLOWED_ORIGINS; see Configuration reference. |
404 | No such path: a service that is not enabled, or /mcp turned off. |
406 or 415 | The Accept or Content-Type header is missing or wrong. |
429 or 503 with Retry-After | Refused by the sign-in limits after wrong static tokens or credentials from this address, a credential that could not be checked upstream, or too many open sessions. See Limits and abuse protection. |
Troubleshooting covers these and the problems a client reports in its own words.
Trying it locally
Claude Code and the MCP Inspector can connect to a server on your own computer, with PUBLIC_URL=http://localhost:8443 and INSECURE_HTTP=true. Quick start has the exact commands. claude.ai cannot reach localhost.
Next: Configuration reference, to run a server of your own.
Configuration reference
A server built with app::Server is configured entirely with environment variables. This page lists every variable the server itself reads, how values are read, and how they are checked. Your services read their own variables in the same way.
The server checks its configuration at startup and, if anything is wrong, prints every problem it found and exits without starting, so a typo never leaves it half configured. A few checks wait until others pass; see Validation.
How values are read
- An empty value counts as unset.
MCP_AUTH_TOKEN=is the same as not setting it. - Any variable can be read from a file by appending
_FILEto its name, such asOAUTH_SIGNING_KEY_FILE=/run/secrets/oauth_signing_key. Use it for secrets with Docker or Kubernetes secrets. A value set directly wins over the file. Trailing newlines (\nand\r) are removed from the file’s contents, and an empty file counts as unset. A file that cannot be read is a configuration error:OAUTH_SIGNING_KEY_FILE: cannot read /run/secrets/oauth_signing_key: No such file or directory (os error 2). - Booleans accept
true,false,1,0,yes,no,onandoff, in any case. Anything else is an error, such asINSECURE_HTTP must be true or false, got "maybe". - Lists are comma separated. Spaces around entries are ignored, and so are empty entries:
" a, b ,,c "isa,bandc. - Addresses (
BIND_ADDR,METRICS_ADDR) are an IP address and a port, such as0.0.0.0:8443or[::]:8443. Host names are not accepted. - Error messages never contain secret values. A rejected
OAUTH_SIGNING_KEYis reported by name and rule, never by its value.
The prefix
Three variables belong to one server and carry its prefix: <PREFIX>_SERVICES, <PREFIX>_COMBINED and <PREFIX>_READ_ONLY. The prefix is MCP unless the server sets another with Server::env_prefix, which removes trailing underscores and converts it to upper case:
#![allow(unused)]
fn main() {
use mcp_server_core::app::Server;
let server = Server::new("mcp-weather", "1.0.0").env_prefix("weather_");
assert_eq!(server.var("SERVICES"), "WEATHER_SERVICES");
let default = Server::new("mcp-weather", "1.0.0");
assert_eq!(default.var("READ_ONLY"), "MCP_READ_ONLY");
}
Every other variable on this page has a fixed name, whatever the prefix. MCP_AUTH_TOKEN is always MCP_AUTH_TOKEN. A server’s own documentation should give its prefix; mcp-icloud uses ICLOUD, for example ICLOUD_SERVICES.
Public address and listening
| Variable | Default | Example | Meaning |
|---|---|---|---|
PUBLIC_URL | required | https://mcp.example.com | The external URL clients use, without a path. It must be https://; http:// is accepted only when the host is localhost, 127.0.0.1 or [::1]. A port is allowed, a trailing / is removed, and a path, query or fragment is an error. It is the OAuth issuer, the prefix of every service’s URL and the host the MCP endpoints accept; see TLS and deployment. |
BIND_ADDR | 0.0.0.0:8443 | 127.0.0.1:8443 | The address and port to listen on. --healthcheck connects to 127.0.0.1 on this port, so the address must accept loopback connections; 0.0.0.0 does. |
TLS_CERT_PATH | none | /certs/fullchain.pem | A PEM certificate chain, leaf first. Set it together with TLS_KEY_PATH; setting only one is an error. The server checks both files every 30 seconds and reloads them when either changes. Without either, the server generates a self-signed certificate. See TLS and deployment. |
TLS_KEY_PATH | none | /certs/privkey.pem | The PEM private key for TLS_CERT_PATH. |
INSECURE_HTTP | false | true | Serve plain HTTP, for a reverse proxy or tunnel that terminates TLS in front of the server. It wins over TLS_CERT_PATH and TLS_KEY_PATH, which are then ignored. --healthcheck reads it too. |
TRUSTED_PROXIES | none | 10.0.0.2,10.0.0.3 | Comma-separated IP addresses of reverse proxies you run. A request from one of them is limited by the client address in its X-Forwarded-For header instead of the proxy’s. Single addresses only, not ranges; an invalid entry is an error. See Reverse proxies. |
ALLOWED_ORIGINS | none | http://localhost:6274 | Comma-separated browser origins, besides PUBLIC_URL’s own, allowed to call the MCP endpoints. Each is scheme://host with an optional :port, or :* for any port. Entries are passed to rmcp as written and not checked at startup: one that does not parse matches nothing. See Host and Origin checks. |
Sign-in and tokens
| Variable | Default | Example | Meaning |
|---|---|---|---|
OAUTH_SIGNING_KEY | required | output of openssl rand -hex 32 | Signs every token the server issues and derives the key that seals people’s credentials into their tokens. At least 32 bytes; the value is used as text, so 64 hex characters are 64 bytes. Changing it signs everyone out and every client must register again. Keep it secret: whoever has it can mint tokens and open sealed credentials. |
OAUTH_ADMIN_PASSWORD | required with SignIn::OwnerPassword | a passphrase | The owner’s password for the sign-in page. At least 12 characters and not only spaces; shorter than 15 gets a warning at startup. It is compared exactly as typed, spaces included, and the sign-in page accepts at most 1024 bytes. Changing it ends every grant. Not read with the other sign-in modes. See Sign-in modes. |
MCP_AUTH_TOKEN | none | output of openssl rand -hex 32 | A fixed bearer token accepted on every path, for clients that cannot sign in with OAuth. It must not have the shape of a JWT (three dot-separated parts), and cannot be used when people sign in with their own credential, or when the verifier accepts credentials as bearer tokens. Shorter than 32 characters gets a warning. Wrong tokens count towards the sign-in limits. See The static token. |
Services
| Variable | Default | Example | Meaning |
|---|---|---|---|
<PREFIX>_SERVICES | every registered service | weather,tides | The services to run, comma separated. An unknown name, or a list with no names, is an error. A service that is not selected is not mounted and never reads its own variables, so they need not be set. Selected services are built, mounted and listed on /mcp in the order this variable names them. |
<PREFIX>_COMBINED | true | false | Serve every selected service’s tools and prompts together at /mcp, as <service>_<name>. With false, /mcp answers 404. See Several services and /mcp. |
<PREFIX>_READ_ONLY | none | tides or all | Services whose write tools are hidden and refused, on their own path and under /mcp. Comma separated, or all for every registered service. An unknown name is an error; a registered service that is not selected is accepted and has no effect. See Read-only mode and the audit log. |
AUDIT_LOG_PATH | none | /audit/audit.jsonl | A file to append one JSON line to for every write tool call, made or refused. It is opened on the first write. On Unix it is created with mode 0600, and an existing file is narrowed to 0600. Audit lines are logged on the audit target whether or not this is set. See The audit file. |
Logs, metrics and traces
| Variable | Default | Example | Meaning |
|---|---|---|---|
LOG_LEVEL | info | info,mcp_weather=debug | A tracing filter: a level for everything, then target=level directives. It is not checked with the other variables: an invalid filter stops the server right after them, with an error: line. See Logs. |
LOG_FORMAT | json | pretty | json for one JSON object per line, or pretty for multi-line, coloured output (without colour when the NO_COLOR environment variable is set and not empty). Any case. |
DEBUG | false | true | Debug logs for your own crates and this one, without content. See DEBUG. |
DEBUG_UNSAFE_LOG_CONTENT | false | true | Lets services log content, such as the text people send and read, and turns on DEBUG too. A warning is logged at startup. Never in production. See Content in logs. |
METRICS_ADDR | none | 0.0.0.0:9090 | Serve Prometheus metrics on a separate plain HTTP listener at this address. Keep it on an internal network. Needs the prometheus feature (on by default); without it the server logs a warning. See Metrics. |
OTEL_EXPORTER_OTLP_ENDPOINT | none | http://otel-collector:4318 | Export traces over OTLP/HTTP to this collector. Only this variable turns export on: OTEL_EXPORTER_OTLP_TRACES_ENDPOINT on its own does not. The standard OTEL_* variables apply. Needs the otel feature (on by default); without it the server logs a warning. See Traces. |
Those are all the variables the server reads while loading its configuration. Two other readers exist:
- The OpenTelemetry exporter reads the standard OpenTelemetry variables itself when traces are on, such as
OTEL_EXPORTER_OTLP_HEADERS,OTEL_EXPORTER_OTLP_TRACES_ENDPOINTandOTEL_EXPORTER_OTLP_TIMEOUT. It reads them directly from the environment, so they have no_FILEvariants. That includesOTEL_EXPORTER_OTLP_ENDPOINT: set it directly, because the_FILEform turns export on but the exporter itself does not see the address. --healthcheckreadsBIND_ADDRandINSECURE_HTTP(or their_FILEvariants), and nothing else. Run it with the server’s environment.
Services’ own variables
Each service reads its own variables in its factory, through the ServiceEnv it is given. They follow the same rules as the server’s: empty means unset, _FILE variants, the same booleans and lists, and problems recorded rather than returned one at a time. A server’s documentation lists them; Reading configuration with ServiceEnv shows how to write a factory.
Name a service’s variables after the service, such as WEATHER_API_URL, unless two services share one on purpose. A problem with a shared variable is reported once.
Validation
Server::load reads the core variables, then the sign-in settings, then <PREFIX>_SERVICES, <PREFIX>_READ_ONLY, AUDIT_LOG_PATH and <PREFIX>_COMBINED, then each selected service’s variables, all into one list of problems. Each message appears once, even when two services report the same one. When the list is not empty the binary prints each problem on its own line and exits with status 1:
configuration error: PUBLIC_URL must be an https URL (http is only allowed for localhost)
configuration error: OAUTH_SIGNING_KEY must be at least 32 bytes
configuration error: TLS_CERT_PATH and TLS_KEY_PATH must be set together
configuration error: OAUTH_ADMIN_PASSWORD is required
configuration error: WEATHER_API_KEY is required
What is checked:
| Variable | Rule |
|---|---|
PUBLIC_URL | Set; a URL with a host; https, or http for a loopback host; no path, query or fragment. |
OAUTH_SIGNING_KEY | Set; at least 32 bytes. |
OAUTH_ADMIN_PASSWORD | With SignIn::OwnerPassword: set; at least 12 characters; not only spaces. |
MCP_AUTH_TOKEN | Not shaped like a JWT; not next to a verifier that carries credentials or accepts them as bearer tokens. |
TRUSTED_PROXIES | Every entry an IP address. |
BIND_ADDR | An IP address and port. |
METRICS_ADDR | An IP address and port. |
INSECURE_HTTP | A boolean. |
DEBUG | A boolean. |
DEBUG_UNSAFE_LOG_CONTENT | A boolean. |
LOG_FORMAT | json or pretty. |
TLS_CERT_PATH | Set together with TLS_KEY_PATH, unless INSECURE_HTTP is on. The files themselves are read when the server starts serving. |
<PREFIX>_SERVICES | Only registered names, at least one. |
<PREFIX>_READ_ONLY | Only registered names, or all. |
<PREFIX>_COMBINED | A boolean. |
The sign-in mode adds rules of its own. With SignIn::ServiceCredential, exactly one enabled service must define how people sign in; see Only one service may define sign-in.
A few checks can only run once others pass, so fixing one round of errors can reveal another:
- The checks on
MCP_AUTH_TOKENrun oncePUBLIC_URL,OAUTH_SIGNING_KEYand the other server variables are valid. - Services read their variables only once
<PREFIX>_SERVICESis valid, since until then the server does not know which services to build. LOG_LEVEL, the OpenTelemetry endpoint’s address, the TLS files and the listening addresses are used when the server starts serving, after the configuration has loaded. A problem with them ends the server with anerror:line instead ofconfiguration error:.
Troubleshooting quotes every message with its fix.
Warnings
Some settings work but are weak. The server starts and logs a warning for each, straight after its starting line:
| Setting | Warning |
|---|---|
OAUTH_ADMIN_PASSWORD of 12 to 14 characters | OAUTH_ADMIN_PASSWORD is shorter than 15 characters: a longer passphrase is much harder to guess |
MCP_AUTH_TOKEN shorter than 32 characters | MCP_AUTH_TOKEN is shorter than 32 characters: use a long random value |
Other warnings at startup describe how the server runs rather than a weak value: plain HTTP, a self-signed certificate, DEBUG_UNSAFE_LOG_CONTENT, an ALLOWED_ORIGINS entry without a port, and METRICS_ADDR or OTEL_EXPORTER_OTLP_ENDPOINT set in a build without the feature. Troubleshooting lists them.
A complete example
A server with the prefix SEA, two services, its secrets in files and a TLS-terminating proxy in front:
PUBLIC_URL=https://sea.example.com
BIND_ADDR=0.0.0.0:8443
INSECURE_HTTP=true
TRUSTED_PROXIES=10.0.0.2
OAUTH_SIGNING_KEY_FILE=/run/secrets/oauth_signing_key
OAUTH_ADMIN_PASSWORD_FILE=/run/secrets/oauth_admin_password
MCP_AUTH_TOKEN_FILE=/run/secrets/mcp_auth_token
SEA_SERVICES=weather,tides
SEA_READ_ONLY=tides
SEA_COMBINED=true
AUDIT_LOG_PATH=/audit/audit.jsonl
LOG_LEVEL=info
LOG_FORMAT=json
METRICS_ADDR=0.0.0.0:9090
To create the secrets:
mkdir -p secrets
openssl rand -hex 32 > secrets/oauth_signing_key
openssl rand -hex 32 > secrets/mcp_auth_token
printf '%s' 'a long passphrase you will remember' > secrets/oauth_admin_password
chmod 600 secrets/*
TLS and deployment shows settings like these in a container, with the secrets mounted as files.
TLS and deployment
This page covers how a server listens (certificate files, a self-signed certificate or plain HTTP), what PUBLIC_URL decides, running behind a reverse proxy, the Host and Origin checks, containers, shutdown and running several replicas.
claude.ai connects to your server from Anthropic’s infrastructure, so for claude.ai the server must be reachable from the internet at PUBLIC_URL, over HTTPS, with a certificate from a public certificate authority. Claude Code and other clients on your own machine can also use a certificate you trust yourself, or plain HTTP on localhost.
Choosing how the server listens
The server picks one of three modes at startup, in this order:
| Settings | Mode | Strict-Transport-Security |
|---|---|---|
INSECURE_HTTP=true | Plain HTTP. TLS_CERT_PATH and TLS_KEY_PATH are ignored. | not sent |
TLS_CERT_PATH and TLS_KEY_PATH both set | HTTPS with the certificate and key from those files, reloaded when they change. | max-age=31536000 |
| neither set | HTTPS with a self-signed certificate generated in memory. | not sent |
Setting only one of TLS_CERT_PATH and TLS_KEY_PATH stops startup with TLS_CERT_PATH and TLS_KEY_PATH must be set together. With TLS, the server speaks HTTP/1.1 and HTTP/2, chosen by ALPN.
Certificate files
Give the server a PEM certificate chain, leaf certificate first, and its private key, as Let’s Encrypt and most certificate authorities provide them:
TLS_CERT_PATH=/etc/letsencrypt/live/mcp.example.com/fullchain.pem
TLS_KEY_PATH=/etc/letsencrypt/live/mcp.example.com/privkey.pem
- At startup both files are read. If either is missing, unreadable or invalid, the server stops with
error: cannot load TLS certificate <cert> / key <key>: <reason>. It never falls back to a self-signed certificate. - Renewals are picked up without a restart. Every 30 seconds the server compares the modification times of both files. When either has changed it loads the pair again and logs
tls certificate reloaded. New connections get the new certificate; open connections keep the one they started with. - A failed reload keeps the old certificate. If the new files do not load, for example because the certificate was replaced before the key, the server logs the warning
tls certificate reload failed, keeping previous certificateand tries again 30 seconds later. - Symbolic links are followed, so certbot’s
live/directory, whose files link intoarchive/, works. Mount the whole/etc/letsencryptdirectory into a container, not onlylive/, or the links break. - The files must be readable by the server’s user. certbot writes private keys readable by root only; a container running as another user needs a copy or a group it can read.
With certificate files, every response carries Strict-Transport-Security: max-age=31536000; see HSTS.
A self-signed certificate
With neither path set, the server generates a certificate at startup for the PUBLIC_URL host, localhost, 127.0.0.1 and ::1. It is kept in memory, never written to disk, and new on every start. The server logs it as a warning, with its SHA-256 fingerprint (shortened here):
{"timestamp":"2026-10-18T14:41:33.077562Z","level":"WARN","message":"no TLS_CERT_PATH/TLS_KEY_PATH set: serving HTTPS with an in-memory self-signed certificate (not trusted by claude.ai)","addr":"0.0.0.0:8443","fingerprint_sha256":"8B:47:0E:...:0B:25","sans":"[\"mcp.example.com\", \"localhost\", \"127.0.0.1\", \"::1\"]","target":"mcp_server_core::tls"}
claude.ai does not trust it, and neither does any client by default. It is useful:
- for trying the server on your own machine (
curl -k); - to encrypt the hop from a reverse proxy or tunnel that does not verify the certificate of the server behind it. nginx does not verify upstream certificates unless you turn it on; Cloudflare Tunnel has a No TLS Verify setting;
- with a client you configure to pin the logged fingerprint. It changes on every restart.
Plain HTTP
INSECURE_HTTP=true serves plain HTTP and logs INSECURE_HTTP=true: serving plaintext HTTP without TLS at startup. Use it in two cases only:
- on your own machine, with
PUBLIC_URL=http://localhost:8443, as in the quick start; - behind a reverse proxy or tunnel that terminates TLS, on a network you trust.
PUBLIC_URLis then the proxy’shttps://address.
Tokens, passwords and credentials cross the hop from the proxy to the server in clear text, so the proxy and the server should share a host or a private network.
A trusted certificate for local use
For Claude Code or other clients on your own machine, a locally trusted certificate avoids INSECURE_HTTP. With mkcert:
mkcert -install
mkcert -cert-file cert.pem -key-file key.pem localhost 127.0.0.1 ::1
PUBLIC_URL=https://localhost:8443 TLS_CERT_PATH=$PWD/cert.pem TLS_KEY_PATH=$PWD/key.pem \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) OAUTH_ADMIN_PASSWORD='a long password' \
cargo run
Clients built on Node.js read extra trusted certificates from NODE_EXTRA_CA_CERTS, such as NODE_EXTRA_CA_CERTS="$(mkcert -CAROOT)/rootCA.pem".
HSTS
When the server serves certificate files, every response, including refusals and routes added with Server::wrap_router, carries:
Strict-Transport-Security: max-age=31536000
It tells browsers to use HTTPS for the host for a year. It has no includeSubDomains or preload, so it never affects other names under your domain. With a self-signed certificate or plain HTTP the server sends no HSTS header: either the server is on your own machine, or a proxy in front holds the real certificate and sets its own policy. If your proxy should send one, add it there, as in the nginx example.
server::build_app on its own sends no HSTS header; see Lower-level API.
PUBLIC_URL
PUBLIC_URL is the address clients use, and the server builds everything a client sees from it:
| What | Built from PUBLIC_URL |
|---|---|
| Each service’s URL and OAuth resource | https://mcp.example.com/<service>, and /mcp |
| The OAuth issuer | https://mcp.example.com, in every token and in the metadata |
| The metadata documents’ endpoints | https://mcp.example.com/authorize, /token, /register |
The WWW-Authenticate challenge on 401 | https://mcp.example.com/.well-known/oauth-protected-resource/<service> |
The Host names the MCP endpoints accept | mcp.example.com, besides the loopback names |
The Origin always allowed | https://mcp.example.com:443 |
| The self-signed certificate’s names | mcp.example.com, besides the loopback names |
So it must be exactly what clients type: the same scheme, host and port. If clients use https://mcp.example.com through a proxy while the server is told https://mcp.example.com:8443, the metadata sends them to the wrong address and their tokens name the wrong resource.
It cannot have a path. The OAuth routes and metadata live at the root (/authorize, /.well-known/...), so a server cannot share a host name with something else under a sub-path such as https://example.com/mcp-server. Give it its own host name.
Changing PUBLIC_URL invalidates every token and every client registration, since each names the old issuer. Clients must remove the connector and add it again; see What ends a grant.
Reverse proxies and TRUSTED_PROXIES
A reverse proxy in front of the server must:
- terminate TLS with a publicly trusted certificate;
- forward to
https://<server>:8443(the server’s self-signed certificate, not verified), or tohttp://<server>:8443withINSECURE_HTTP=trueon a network you trust; - keep the
Hostheader as the public host name. The MCP endpoints refuse other names with403 Forbidden: Host header is not allowed; see Host and Origin checks; - not buffer responses. MCP answers with server-sent event streams, which must reach the client as they are written. rmcp sends a keep-alive on each event stream every 15 seconds, so an idle timeout longer than that keeps quiet streams open;
- allow request bodies of 1 MiB, the server’s own limit;
- pass the client’s address in
X-Forwarded-For, and be listed inTRUSTED_PROXIES.
How X-Forwarded-For is read
The server uses a client’s address for one thing: the sign-in limits, which count failed sign-ins, wrong static tokens and rejected credentials per address. It also appears as ip in the warnings those failures log. Behind a proxy every request comes from the proxy, so without TRUSTED_PROXIES every client shares the proxy’s address, and one person’s failed attempts block everyone.
With TRUSTED_PROXIES set:
X-Forwarded-Foris believed only on a connection from an address in the list. From any other address it is ignored.- Every
X-Forwarded-Forheader is read, its entries from right to left. The first entry that is not itself a trusted proxy is the client. Entries left of it, which the client could have written itself, are ignored. - An entry may carry a port:
203.0.113.7:5000and[2001:db8::7]:443are read as their addresses. - A malformed entry met before the client’s, no header at all, or a header listing only trusted proxies means the proxy’s own address is used.
- IPv4-mapped IPv6 addresses (
::ffff:10.0.0.2, as a dual-stack listener reports IPv4 peers) count as the IPv4 address, in the list, the header and the connection alike.
| Connection from | X-Forwarded-For | TRUSTED_PROXIES | Limited as |
|---|---|---|---|
10.0.0.2 | 198.51.100.7 | unset | 10.0.0.2 |
10.0.0.2 | 198.51.100.7 | 10.0.0.2 | 198.51.100.7 |
10.0.0.2 | 1.1.1.1, 198.51.100.7, 10.0.0.3 | 10.0.0.2,10.0.0.3 | 198.51.100.7 |
10.0.0.2 | not-an-address | 10.0.0.2 | 10.0.0.2 |
203.0.113.9 | 198.51.100.7 | 10.0.0.2 | 203.0.113.9 |
List only proxies you run. A client that can connect from a trusted address can choose the address it is limited as. Entries are single addresses, not ranges: a content delivery network with many edge addresses cannot be listed, and the server then limits by the edge address your own proxy reports.
nginx
nginx terminating TLS on the same host, forwarding to the server on 127.0.0.1:8443 with its self-signed certificate:
upstream mcp {
server 127.0.0.1:8443;
}
# Request rate limits: per bearer token, and per address only on the sign-in page.
limit_req_zone $http_authorization zone=per_token:10m rate=20r/s;
limit_req_zone $binary_remote_addr zone=sign_in:10m rate=10r/m;
server {
listen 443 ssl;
server_name mcp.example.com;
ssl_certificate /etc/letsencrypt/live/mcp.example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/mcp.example.com/privkey.pem;
add_header Strict-Transport-Security "max-age=31536000" always;
client_max_body_size 1m;
proxy_http_version 1.1;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Connection "";
proxy_buffering off;
proxy_cache off;
location /authorize {
limit_req zone=sign_in burst=10;
proxy_pass https://mcp;
}
location / {
limit_req zone=per_token burst=40;
proxy_pass https://mcp;
}
}
and the server’s side:
PUBLIC_URL=https://mcp.example.com
BIND_ADDR=127.0.0.1:8443
TRUSTED_PROXIES=127.0.0.1
BIND_ADDR=127.0.0.1:8443keeps the server off the network;--healthcheckstill reaches it.proxy_pass https://mcpencrypts the hop with the self-signed certificate. For plain HTTP, setINSECURE_HTTP=trueand useproxy_pass http://mcp.$proxy_add_x_forwarded_forappends the address nginx sees to whatever the client sent, so the rightmost entry is the real client.
About the rate limits. The server limits sign-in guesses and upstream credential checks itself, but not the rate of requests; that is your proxy’s job (What a stateless server cannot do). Hosted clients such as claude.ai reach the server from a few shared addresses, so do not limit /mcp, /<service>, /token or /register per client address: one busy person would block everyone. Limit per bearer token, as above, and per address only on /authorize, the page a person’s browser opens. nginx does not count requests whose key is empty, so /token and /register, which carry no Authorization header, are not limited by the per-token zone. You can also add your own tower layer with Server::wrap_router.
Tunnels
A tunnel, such as Cloudflare Tunnel, gives the server a public address with a trusted certificate without opening a port. To the server it is a reverse proxy:
- Point the tunnel at
https://<server>:8443with certificate verification off (Cloudflare’s No TLS Verify), or athttp://<server>:8443withINSECURE_HTTP=true. - Set
PUBLIC_URLto the tunnel’s public host name, such ashttps://mcp.example.com. - If the tunnel’s connector passes the client’s address in
X-Forwarded-For, setTRUSTED_PROXIESto the address the connector connects from. In Docker, give the connector a fixed address on its network so the setting stays true.
Host and Origin checks
The MCP endpoints, /<service> and /mcp, check two headers to protect against DNS rebinding and cross-site requests from browsers. The checks come from rmcp’s Streamable HTTP transport, configured by the server, and run after the bearer check: a request without a usable token gets 401 first. The OAuth routes and /healthz are not checked.
Host must be the PUBLIC_URL host, localhost, 127.0.0.1 or ::1, on any port. Anything else gets 403 Forbidden: Host header is not allowed, and rmcp logs the warning rejected request with disallowed Host header (possible DNS rebinding attempt). A Host header that is not a valid host name gets 400 Bad Request: Invalid Host header. Without this check, a web page could point a name it controls at your server’s address and have a visitor’s browser call it.
Origin is checked only when a request carries one. Browsers send it; clients that run on a server or the command line usually do not. A request with an Origin must come from PUBLIC_URL’s own origin (scheme, host and port: https://mcp.example.com means port 443) or match an entry of ALLOWED_ORIGINS. Otherwise it gets 403 Forbidden: Origin header is not allowed, and rmcp logs rejected request with disallowed Origin header (possible cross-origin attack). An Origin that does not parse gets 403 Forbidden: Invalid Origin header (Forbidden: Invalid Origin header encoding when it is not UTF-8), and rmcp logs rejected request with malformed Origin header.
Add an origin to ALLOWED_ORIGINS when a browser-based MCP client calls the server directly, for example the MCP Inspector’s page on http://localhost:6274. Entries take these forms:
| Entry | Matches |
|---|---|
https://app.example.com:443 | That origin exactly. |
http://localhost:* | http://localhost on any port. |
https://app.example.com | That host on any port, for now. rmcp logs a warning at startup for such an entry, once for each path, beginning allowed origin without a port matches any port: a later rmcp release will match only the scheme’s default port. Write a port or :* instead. |
null | Origin: null, which browsers send from sandboxed pages and file: URLs. |
Body limits
The server’s routes (/healthz, the OAuth routes and the MCP endpoints) refuse a request body larger than 1 MiB (1,048,576 bytes). A request whose Content-Length declares more gets 413 Payload Too Large with the body length limit exceeded, before the body is read. A larger body sent without a declared length (chunked) is cut off at the limit: the OAuth endpoints then answer 413 with Failed to buffer the request body: length limit exceeded, and the MCP endpoints answer 500 Internal Server Error with Failed to read request body: length limit exceeded. MCP messages are far smaller. Set your proxy’s limit to the same size; nginx’s client_max_body_size 1m is exactly that. See Limits and abuse protection for every other limit.
Routes you add with Server::wrap_router, and /favicon.ico, are outside that limit, the request metrics and the request tracing span. Wrapped routes get axum’s own default limit of 2 MB on extractors such as Bytes and Json. If they read bodies, add DefaultBodyLimit::max(1_048_576) from the re-exported mcp_server_core::axum::extract to them.
Containers
The binary needs nothing but its environment: no configuration file, no writable directory apart from the audit log’s, and no state to keep. A multi-stage Dockerfile for a server called mcp-sea:
FROM rust:1.88-slim-bookworm AS build
WORKDIR /src
COPY . .
RUN cargo build --release --locked
FROM gcr.io/distroless/cc-debian12:nonroot
COPY --from=build /src/target/release/mcp-sea /mcp-sea
EXPOSE 8443
HEALTHCHECK --interval=30s --timeout=5s --start-period=10s --retries=3 CMD ["/mcp-sea", "--healthcheck"]
ENTRYPOINT ["/mcp-sea"]
The nonroot image runs as UID 65532. The default port, 8443, needs no privileges. The build image needs Rust 1.88 or later, the crate’s minimum supported version; use a newer one if your own code needs it.
The healthcheck
/mcp-sea --healthcheck connects to 127.0.0.1 on the BIND_ADDR port, requests GET /healthz, and exits 0 on a 200 within 5 seconds, or prints healthcheck failed and exits 1. It speaks TLS unless INSECURE_HTTP is set, accepting any certificate since it only talks to itself. It reads BIND_ADDR and INSECURE_HTTP from the environment, which a container’s HEALTHCHECK shares with the server.
/healthz shows only that the process is serving. It does not contact upstream services, so an upstream outage does not get the container restarted.
In Kubernetes, use the same command as an exec probe, or an httpGet probe on /healthz with scheme: HTTPS (the kubelet does not verify probe certificates) or scheme: HTTP with INSECURE_HTTP.
Docker Compose
With its secrets in files, certificates from the host’s certbot and a volume for the audit log:
services:
mcp-sea:
image: ghcr.io/example/mcp-sea:1.0.0
restart: unless-stopped
ports:
- "443:8443"
environment:
PUBLIC_URL: https://sea.example.com
TLS_CERT_PATH: /etc/letsencrypt/live/sea.example.com/fullchain.pem
TLS_KEY_PATH: /etc/letsencrypt/live/sea.example.com/privkey.pem
OAUTH_SIGNING_KEY_FILE: /run/secrets/oauth_signing_key
OAUTH_ADMIN_PASSWORD_FILE: /run/secrets/oauth_admin_password
AUDIT_LOG_PATH: /audit/audit.jsonl
secrets:
- oauth_signing_key
- oauth_admin_password
volumes:
- /etc/letsencrypt:/etc/letsencrypt:ro
- ./audit:/audit
read_only: true
stop_grace_period: 15s
secrets:
oauth_signing_key:
file: ./secrets/oauth_signing_key
oauth_admin_password:
file: ./secrets/oauth_admin_password
- Every file the server reads, the secrets and the certificate and key, must be readable by UID 65532, and the audit directory writable by it (
sudo chown 65532:65532 audit). If the audit file cannot be written, tool calls still work and the server logscould not write the audit logat most once a minute. read_only: trueworks: the server writes nothing else.stop_grace_periodgives the server time to drain connections; see Graceful shutdown.
Configuration reference shows how to create the secrets.
Graceful shutdown
On SIGTERM (or Ctrl-C), the server:
- logs
shutdown signal received; - stops accepting connections, ends its MCP sessions and stops watching the certificate files;
- waits up to 10 seconds for open connections to finish;
- exits with status 0, after flushing any traces it has not yet exported.
Give the server more than 10 seconds before your platform kills it. Docker waits 10 seconds by default, so set stop_grace_period: 15s (Compose) or --stop-timeout 15 (docker run). Kubernetes waits 30 seconds by default.
Clients notice nothing lasting. Their tokens remain valid on the new process, since nothing is stored; their MCP session is gone, so their next request gets 404 and they open a new session.
Replicas
Every token is a signed JWT, so any replica can verify a token another issued, and the OAuth flow works with registration, sign-in and token requests landing on different replicas. Replicas must agree on what goes into a token:
| Setting | Why it must be the same on every replica |
|---|---|
OAUTH_SIGNING_KEY | Signs and verifies every token and seals every credential. |
PUBLIC_URL | The issuer and the resources every token names. |
OAUTH_ADMIN_PASSWORD, the sign-in mode and the verifier | Every token carries a sign-in version derived from them; a replica with another version refuses the token. |
<PREFIX>_SERVICES and <PREFIX>_COMBINED | A replica answers 404 on a path it does not serve, and refuses to refresh a token for it. |
MCP_AUTH_TOKEN | Accepted only where it is set. |
Everything else lives in each replica’s memory, starts empty and is lost on restart:
| Kept per replica | Effect |
|---|---|
| Sign-in limits | Each replica counts failed attempts on its own, so with three replicas an address can make up to three times the attempts. |
| The memory of used authorization codes | A code is refused a second time by the replica that redeemed it, not by the others. Codes live 60 seconds and need the client’s PKCE verifier. |
| Verdicts on credentials sent as bearer tokens, and the cap of 16 checks at once | Each replica checks a credential upstream once and caches the verdict itself. |
| MCP sessions and the session tables | A session lives on the replica that opened it. |
| The audit file | Each replica writes its own AUDIT_LOG_PATH. Collect the audit log target if you want one record. |
Because sessions are per replica, a load balancer must send every request of a session to the replica that opened it. Otherwise the request gets 404, and the client starts a new session each time it lands elsewhere. Route on the Mcp-Session-Id header, which every request after initialize carries; requests without one can go to any replica. With nginx:
upstream mcp {
hash $http_mcp_session_id consistent;
server 10.0.0.11:8443;
server 10.0.0.12:8443;
}
Keep the replicas’ clocks synchronised. Tokens are accepted for 5 seconds after they expire to allow for skew, and a sign-in time ahead of a replica’s clock is accepted as another replica’s.
Before going live
PUBLIC_URLis exactly the address clients use, and the certificate is publicly trusted.OAUTH_SIGNING_KEYis random (openssl rand -hex 32), kept in a file, and known to nobody else.OAUTH_ADMIN_PASSWORDis 15 characters or more;MCP_AUTH_TOKENis unset or long and random.TRUSTED_PROXIESlists your proxies and nothing else.- Requests are rate limited in front of the server, per token rather than per address.
METRICS_ADDR, if set, is reachable only from your monitoring network.DEBUG_UNSAFE_LOG_CONTENTis off, andLOG_LEVELdoes not setdebugortracefor everything; see Observability.- The audit file’s directory is writable, and the healthcheck and stop grace period are set.
- Security model has been read, including what a stateless server cannot do.
Read-only mode and the audit log
Every service gets two safety features from the same source, each tool’s read_only_hint annotation: a read-only mode you switch on per service, and an audit log of every call to a tool that can change something. This page covers how tools are classified, what clients see on a read-only service, every field of the audit log and the policy module behind both.
Reads and writes
The server classifies each tool by its read_only_hint annotation alone:
| The tool declares | The server treats it as |
|---|---|
annotations(read_only_hint = true) | A read |
annotations(read_only_hint = false) | A write |
Annotations without read_only_hint | A write |
| No annotations at all | A write |
| A name the service does not have | A write |
Reads are never refused and never audited. Writes are hidden and refused on a read-only service, and every call to one is audited, made or refused. Treating anything unmarked as a write means a forgotten annotation fails safe: the tool disappears on a read-only service instead of slipping through.
Mark every tool explicitly:
#![allow(unused)]
fn main() {
use mcp_server_core::rmcp;
use mcp_server_core::rmcp::handler::server::router::tool::ToolRouter;
use mcp_server_core::rmcp::model::{CallToolResult, ContentBlock};
use mcp_server_core::rmcp::{ErrorData as McpError, ServerHandler, tool, tool_handler, tool_router};
#[derive(Clone)]
struct NotesTools {
tool_router: ToolRouter<Self>,
}
#[tool_router]
impl NotesTools {
fn new() -> Self {
Self { tool_router: Self::tool_router() }
}
// A read: listed and callable on a read-only service, never audited.
#[tool(description = "List every note.", annotations(read_only_hint = true))]
async fn list_notes(&self) -> Result<CallToolResult, McpError> {
Ok(CallToolResult::success(vec![ContentBlock::text("")]))
}
// A write: hidden and refused on a read-only service, audited on every call.
#[tool(
description = "Delete every note.",
annotations(read_only_hint = false, destructive_hint = true)
)]
async fn clear_notes(&self) -> Result<CallToolResult, McpError> {
Ok(CallToolResult::success(vec![ContentBlock::text("cleared")]))
}
}
#[tool_handler(router = self.tool_router)]
impl ServerHandler for NotesTools {}
let _ = NotesTools::new();
}
The server looks the tool up with the handler’s get_tool, which #[tool_handler] generates. A ServerHandler written by hand without get_tool has no tool the server can find, so every call to it counts as a write. The other annotations, such as destructive_hint, are for clients; the server ignores them. Annotations lists them.
Making a service read-only
Set <PREFIX>_READ_ONLY to the services whose write tools should be hidden and refused, with <PREFIX> from Server::env_prefix. The notes example uses the prefix NOTES:
PUBLIC_URL=http://localhost:8443 INSECURE_HTTP=true \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) OAUTH_ADMIN_PASSWORD='a long password' \
NOTES_READ_ONLY=notes cargo run --example notes
| Value | Effect |
|---|---|
| unset or empty | No service is read-only. |
notes | notes is read-only. |
notes, tasks | Both are. Names are comma separated; spaces around them, empty entries and repeated names are ignored. |
all | Every registered service is read-only. Names before all must still be known; names after it are not checked. |
| a registered service that is not selected | Accepted, and has no effect while the service is not running. |
| any other name | The server refuses to start. |
An unknown name stops startup with an error that lists the names it accepts, for example:
configuration error: NOTES_READ_ONLY contains an unknown service: note (known: all, notes)
mcp is not a service, so it is never accepted; making each service read-only also covers it on /mcp. At startup the server logs a service enabled line for each service with a read_only field, which shows the rule in force. The Configuration reference lists the variable with the others.
What clients see on a read-only service
| Request | On a read-only service |
|---|---|
tools/list | Only the tools marked read_only_hint = true. |
tools/call of a read | Runs as usual, and is not audited. |
tools/call of a write, or of a name the service does not have | Refused before the tool runs, even with invalid arguments, and audited with outcome refused. |
prompts/list, prompts/get | Unchanged: prompts stay listed. See Prompts on read-only services. |
| Resources | Unchanged. |
A refused call is a tool error, not a JSON-RPC error, so the model reads why and can tell the person. On the notes example with NOTES_READ_ONLY=notes, calling add_note returns:
{"jsonrpc":"2.0","id":3,"result":{"content":[{"type":"text","text":"read_only: the notes service is read-only on this server"}],"isError":true}}
The text is always read_only: the <service> service is read-only on this server. Its read_only: prefix is the error kind the audit log records.
The rule follows the service everywhere it is served. On /mcp each service keeps its own rule, so a read-only service’s write tools are missing from /mcp as well, while the other services’ tools work as usual; see Read-only services and the audit log on the combined endpoint page. A name on /mcp that does not start with a known <service>_ prefix belongs to no service: it gets the JSON-RPC error tool not found and is not audited.
Read-only mode is enforced by service::mcp_service, which the default Service::router uses. If you override router, build it with mcp_service as Overriding the router shows; a router built without it gets neither read-only mode nor the audit log on the service’s own path.
The audit log
Every call to a write tool produces one audit record, whether it succeeds, fails or is refused. Calls to reads produce none. A request that never reaches the tools, such as one refused with 401 by the bearer check, is not a tool call and is not recorded.
A call to add_note on the notes example, made with MCP_AUTH_TOKEN, is recorded as this JSON line:
{"ts":"2026-10-18T13:59:42.304Z","service":"notes","endpoint":"/notes","tool":"add_note","outcome":"ok","error_kind":null,"caller":"static","subject":"static","elapsed_ms":0}
A failed call to the same tool through /mcp, on a server where people send their own key as the bearer token, would look like this:
{"ts":"2026-10-18T14:02:10.877Z","service":"notes","endpoint":"/mcp","tool":"add_note","outcome":"error","error_kind":"invalid_argument","caller":"credential","subject":"key:3f9a1c0e5b7d2468","elapsed_ms":3}
Fields
Every line has every field, in this order:
| Field | Meaning |
|---|---|
ts | When the call finished: RFC 3339 in UTC with milliseconds, such as 2026-10-18T13:59:42.304Z. |
service | The service the tool belongs to. |
endpoint | The path the call arrived on: /<service> or /mcp. |
tool | The tool’s own name, without the <service>_ prefix /mcp adds, so the same tool has the same name on both paths. A call to a name the service does not have records that name. |
outcome | ok, error or refused. |
error_kind | null for ok. For error: the kind at the start of the tool error’s first text block (invalid_argument for invalid_argument: text is empty), protocol when the call failed with a JSON-RPC error, or null when the tool error has no kind. For refused: read_only. |
caller | How the request was authenticated: oauth:<client_id> for an OAuth access token, oauth for one without a client id, credential for a person’s credential sent as the bearer token, static for MCP_AUTH_TOKEN. |
subject | Who signed in: owner, key: and 16 hex digits for a person’s own credential, static, or what a custom verifier names. See Subjects. |
elapsed_ms | How long the call took, in whole milliseconds, rounded down. A refusal never runs the tool, so it records 0 in practice. |
A kind is one or more lowercase ASCII letters or _ at the start of the first content block, which must be text, followed by : . Anything else, such as Something: else, gives no kind. Results and errors shows how to write tool errors with kinds. Calling a name the service does not have on a writable service gives error with protocol, because the tool router answers with a JSON-RPC error.
The OAuth client id is the client’s registration, a signed token, so an oauth: caller can run to several hundred characters. Every token issued to one connector carries the same client id, so it still identifies the connector.
Behind app::Server, caller and subject are always set. A handler served without the bearer guard in front, as with mcp_service mounted on its own, has no caller to record: subject is null and caller reads static.
What is never recorded
Tool arguments, ids, results and error details beyond the kind are never written, and neither are credentials, access or refresh tokens, or session ids. The only token-like value is the OAuth client id in caller, which is a public client registration, not a secret. The audit log shows that subject called add_note at a given time with a given outcome, never what the note said. If you need the content of changes, record it in your service, and only where its sensitivity allows.
Where the lines go
Each record goes to two places:
-
The
auditlog target, always. The server keeps this target atinfowhateverLOG_LEVELsays, evenLOG_LEVEL=off, so the audit trail cannot be switched off by accident. The event’s message istool write, and its fields are those of the line exceptts, since the log has its own timestamp. A field that would benull, such aserror_kindon a success, is left out. WithLOG_FORMAT=jsonand the defaultLOG_LEVEL=info(withLOG_LEVEL=offthespanandspansfields are absent):{"timestamp":"2026-10-18T13:59:42.304855Z","level":"INFO","message":"tool write","service":"notes","endpoint":"/notes","tool":"add_note","outcome":"ok","caller":"static","subject":"static","elapsed_ms":0,"target":"audit","span":{"name":"serve_inner"},"spans":[{"name":"serve_inner"}]}To collect only audit events from the process output, filter on
"target":"audit". Observability describes the logs in full. -
The file named by
AUDIT_LOG_PATH, when it is set: one JSON object per line, as shown above.
The audit file
AUDIT_LOG_PATH=/var/lib/notes/audit.jsonl
- The file is opened on the first write, not at startup, and appended to. The server never truncates or rotates it.
- On Unix it is created with mode
0600, and an existing file is narrowed to0600when it is opened, so only the server’s user can read it. - The directory must exist; the server creates the file, not its directory. In a container, mount a volume for the directory so the file outlives the container, for example
./audit:/auditwithAUDIT_LOG_PATH=/audit/audit.jsonl. - The server keeps the file open between writes. To rotate it, use a method that keeps the same file, such as logrotate’s
copytruncate; a file renamed away keeps receiving lines until the server reopens it, which happens only after a failed write or a restart. - Lines are written one at a time under a lock, so concurrent calls never interleave.
- Give each replica a file of its own and collect them, or rely on the
auditlog target, which reaches your log collector from every replica.
When the file cannot be written
A failed write never fails the tool call: by then the tool has run, and an error would tell the model that a change failed when it was made. Instead:
- the line still goes to the
auditlog target; - the server logs a warning,
could not write the audit log, with the path and the error, at most once a minute however many writes fail; - the next write opens the file afresh, so the file recovers on its own once, say, the missing directory exists or the disk has space again.
Lines that failed to reach the file are not written to it later. Watch for the warning, or treat the log target as the copy of record.
The policy module
mcp_server_core::policy implements both features. app::Server wires it up for you; use it directly when you build the application yourself.
| Item | What it is |
|---|---|
ToolPolicy | What applies to one service’s tools on one path: service, endpoint, read_only and the audit log, all public fields. |
AuditLog | AuditLog::new(path) with the AUDIT_LOG_PATH file or None; record(&line) writes a line to the log target and the file. Share one in an Arc. |
AuditLine | One record, with the fields above as public fields. Serialises to the file’s JSON. |
Guarded | An rmcp ServerHandler that wraps another and applies a policy to tools/list and tools/call, forwarding everything else unchanged. Guarded::new(handler) reads the policy from each request; Guarded::with_policy(handler, policy) uses the one given. Without a policy it changes nothing. |
is_read_only | is_read_only(tool: Option<&Tool>) -> bool: true only for a tool with read_only_hint = true. |
visible_tools | visible_tools(tools, read_only): all of tools, or only the reads when read_only. |
AUDIT_TARGET | "audit", the log target. |
app::Safety | The read-only services and the audit log of a loaded server, the safety field of app::Loaded: public fields read_only (Vec<&'static str>) and audit (Arc<AuditLog>), with is_read_only(service) and policy(service), the ToolPolicy for /<service>. |
How app::Server uses them:
- It builds one
AuditLogfromAUDIT_LOG_PATH, shared by every service. - Each service’s router gets its
ToolPolicy(endpoint/<service>) as anaxum::Extension.mcp_servicewraps every handler it serves inGuarded::new, which finds the policy in the HTTP request parts that rmcp passes to each request. - For
/mcp, each service’s handler is wrapped inGuarded::with_policywith that service’s rule and endpoint/mcp, before the handlers are combined. The combined endpoint strips the<service>_prefix before the call reaches the service, which is whytoolis the tool’s own name. - When it starts logging, it adds
audit=infoto the log filter withobservability::log_filter. If you install logging yourself, pass&[AUDIT_TARGET]as itsalways_onargument to keep the audit target on.
Attaching a policy to a service you mount yourself, for example with server::build_app:
use mcp_server_core::rmcp::ServerHandler;
#[derive(Clone)]
struct NotesTools;
impl NotesTools { fn new() -> Self { NotesTools } }
impl ServerHandler for NotesTools {}
use mcp_server_core::axum::Extension;
use mcp_server_core::policy::{AuditLog, ToolPolicy};
use mcp_server_core::service::{HttpSettings, ServiceContext, mcp_service};
use std::sync::Arc;
#[tokio::main]
async fn main() {
let ctx = ServiceContext {
http: HttpSettings {
public_url: "https://mcp.example.com".into(),
public_host: "mcp.example.com".into(),
allowed_origins: Vec::new(),
},
shutdown: mcp_server_core::shutdown_signal(),
};
let audit = Arc::new(AuditLog::new(Some("/var/lib/notes/audit.jsonl".into())));
let policy = ToolPolicy {
service: "notes".into(),
endpoint: "/notes".into(),
read_only: true,
audit,
};
// mcp_service wraps the handler in Guarded::new, which reads this extension.
let notes = mcp_service(&ctx, || Ok(NotesTools::new())).layer(Extension(policy));
// Mount `notes` at /notes behind the bearer guard; see the lower-level API page.
let _ = notes;
}
Lower-level API shows the rest of a server built this way.
An AuditLog of your own writes the same format, for example to audit a change your service makes outside a tool call, such as a scheduled job:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let dir = tempfile::tempdir()?;
let path = dir.path().join("audit.jsonl");
use mcp_server_core::policy::{AuditLine, AuditLog};
let audit = AuditLog::new(Some(path.clone()));
audit.record(&AuditLine {
ts: "2026-10-18T10:00:00.000Z".into(),
service: "notes".into(),
endpoint: "/notes".into(),
tool: "nightly_cleanup".into(),
outcome: "ok",
error_kind: None,
caller: None,
subject: Some("owner".into()),
elapsed_ms: 12,
});
let written = std::fs::read_to_string(&path)?;
assert_eq!(
written,
"{\"ts\":\"2026-10-18T10:00:00.000Z\",\"service\":\"notes\",\"endpoint\":\"/notes\",\
\"tool\":\"nightly_cleanup\",\"outcome\":\"ok\",\"error_kind\":null,\"caller\":null,\
\"subject\":\"owner\",\"elapsed_ms\":12}\n"
);
Ok(())
}
record also logs the line on the audit target. The server’s own AuditLog is not handed to services, so give yours a file of its own: two logs appending to one file each keep their own lock, and their lines could interleave.
Next: Observability.
Observability
This page covers the server’s logs (format, filters, targets, caps and what is kept out of them), its Prometheus metrics and its OpenTelemetry traces, and the feature flags behind the last two.
All three are configured with environment variables; the configuration reference lists them with their defaults.
Logs
The server writes logs to standard output. LOG_FORMAT=json, the default, writes one JSON object per line for a log collector:
{"timestamp":"2026-10-18T13:55:55.909869Z","level":"INFO","message":"service enabled","service":"notes","url":"https://mcp.example.com/notes","read_only":false,"tools":"[\"add_note\", \"list_notes\"]","target":"mcp_server_core::app"}
| Field | Meaning |
|---|---|
timestamp | When, in UTC, RFC 3339 with microseconds. |
level | ERROR, WARN, INFO, DEBUG or TRACE. |
message | What happened. |
target | Where it came from, usually a Rust module path such as mcp_server_core::app. Filters select by target. |
span, spans | The span the event happened in, and every enclosing span, with their fields. An event during an HTTP request is in the request span, with method and path. |
| anything else | The event’s own fields, such as url and read_only above. |
LOG_FORMAT=pretty writes multi-line, coloured output with the source location of each event, for reading in a terminal. It writes colour codes even when its output is not a terminal, unless the NO_COLOR environment variable is set and not empty, so use json for files and collectors.
LOG_LEVEL
LOG_LEVEL is a tracing filter: comma-separated directives, each either a level for everything or target=level for one target and everything under it. Levels, from quietest: off, error, warn, info, debug, trace. The default is info.
LOG_LEVEL | Effect |
|---|---|
info | Everything at info and above. |
warn | Warnings and errors only, plus audit lines, which stay on. |
info,mcp_weather=debug | Everything at info, and your crate mcp_weather at debug. |
info,tower_http=debug | Everything at info, and each HTTP request’s start and finish, with its status and latency. |
debug,rmcp=info | debug for everything except rmcp, which stays at info. |
A target matches by prefix: mcp_weather also covers mcp_weather::client and a crate named mcp_weather_api.
- Always include a level for everything.
LOG_LEVEL=mcp_weather=debugon its own logsmcp_weatherand audit lines and nothing else: not the startup lines, not warnings. A word that is not a level, such asverbose, is read as a target name, with the same result. - A filter that does not parse stops the server right after the configuration loads, before logging starts, with an
error:line:error: error parsing level filter: expected one of "off", "error", "warn", "info", "debug", "trace", or a number 0-5: ...for a bad level such asmcp_weather=verbose, orerror: invalid filter directivefor a directive such as=debug. - Some directives are replaced. Directives for the audit target, for capped targets and for rmcp’s session targets are dropped and set by the server instead. Span-scoped directives, such as
[request]=debug, are dropped too, because they could re-enable a capped target.
DEBUG
DEBUG=true adds two directives after LOG_LEVEL: your crates at debug, and mcp_server_core at debug. Your crates are the server’s crate target, which is the server’s name with - replaced by _ (mcp-weather gives mcp_weather), or what you set with Server::crate_target. By prefix, it covers crates such as mcp_weather_api too.
DEBUG is the safe way to get more detail:
- It leaves dependencies at
LOG_LEVEL, so rmcp does not start logging requests and responses (see Content in logs). - Capped targets stay capped, even under your crate target.
- Your services can ask whether it is on with
observability::debug_enabled, for example before doing work only a debug line needs.
This crate’s own messages are at info, warn and error, so for it DEBUG mostly matters to the services you write.
Targets
| Target | What it logs |
|---|---|
mcp_server_core::app | Startup: starting, warnings about weak settings, service enabled, combined endpoint enabled, listening. A fatal error while serving. |
mcp_server_core::tls | How the server listens; certificate reloads. |
mcp_server_core::observability | The metrics listener; features missing from the build; the content-logging warning. |
mcp_server_core::oauth::register | Client registrations. |
mcp_server_core::oauth::authorize | Sign-ins granted, rejected or not checkable. |
mcp_server_core::oauth::middleware | Rejected static tokens and bearer credentials. |
mcp_server_core::oauth::token | Authorization codes used twice. |
mcp_server_core::policy | Audit file write failures. |
mcp_server_core | The shutdown signal. |
audit | One line per write tool call. Always on at info, whatever LOG_LEVEL says. See The audit log. |
rmcp::… | rmcp’s own logs: MCP sessions starting and ending, and refused Host and Origin headers. |
tower_http::trace::… | Each request’s start and finish at debug, and response failed at error for every 5xx response. |
| your crate target | Your services. |
What the server logs
At startup, in this order:
| Level | Message | Fields |
|---|---|---|
WARN | OTEL_EXPORTER_OTLP_ENDPOINT is set but this build has no OpenTelemetry support (feature `otel`): traces are not exported | Only in a build without otel. |
INFO | prometheus metrics listener started | addr. Only with METRICS_ADDR. |
WARN | METRICS_ADDR is set but this build has no Prometheus support (feature `prometheus`): metrics are not served | addr. Only in a build without prometheus, instead of the line above. |
WARN | DEBUG_UNSAFE_LOG_CONTENT is enabled: message content WILL be written to logs | Only with DEBUG_UNSAFE_LOG_CONTENT. |
INFO | starting <name> | version |
WARN | weak settings, such as OAUTH_ADMIN_PASSWORD is shorter than 15 characters: a longer passphrase is much harder to guess | |
INFO | service enabled, once per service | service, url, read_only, tools |
INFO | combined endpoint enabled | url, tools (how many) |
WARN | allowed origin without a port matches any port; a future release will match only the scheme default port. Use `:*` or an explicit port instead, from rmcp, once per path for each such ALLOWED_ORIGINS entry | allowed_origin |
INFO | listening | addr |
INFO or WARN | serving HTTPS with certificate from files, or the self-signed or plain HTTP warning | addr; fingerprint_sha256 and sans for a self-signed certificate |
While running:
| Level | Message | Fields |
|---|---|---|
INFO | oauth client registered | client_name, as the client reported it |
INFO | oauth authorization granted | subject |
WARN | oauth login failed: credential rejected | ip |
WARN | oauth login: credential could not be checked | ip, reason |
WARN | wrong static token rejected | ip |
WARN | bearer credential rejected | ip |
WARN | bearer credential could not be checked | reason |
WARN | authorization code replay rejected | |
INFO | tool write, on the audit target | service, endpoint, tool, outcome, error_kind, caller, subject, elapsed_ms |
WARN | could not write the audit log, at most once a minute | path, error |
INFO | tls certificate reloaded | |
WARN | tls certificate reload failed, keeping previous certificate | error |
WARN | rejected request with disallowed Host header (possible DNS rebinding attempt), from rmcp | host |
WARN | rejected request with malformed Host header, from rmcp | host |
WARN | rejected request with disallowed Origin header (possible cross-origin attack), from rmcp | origin |
WARN | rejected request with malformed Origin header, from rmcp | origin |
ERROR | response failed, from tower_http, for every 5xx response | classification, latency |
INFO | shutdown signal received | |
ERROR | fatal | error |
rmcp also logs at info when an MCP session starts (Service initialized as server, with the client’s initialize parameters: its name, version and capabilities), when the client finishes initialising (client initialized, unless the handler overrides on_initialized) and when a session ends (serve finished).
Every HTTP request to /healthz, the OAuth routes and the MCP endpoints runs in a request span with its method and path. /favicon.ico and routes added with Server::wrap_router sit outside it. The path never includes the query string, so the parameters of a sign-in request are not logged.
Log caps
Some dependencies can reveal secrets at debug or trace, typically an HTTP client that logs request headers. A service names those targets in Service::log_caps, and the server caps each of them, and everything under it, at info. A cap is never above the level LOG_LEVEL sets for everything: with LOG_LEVEL=error a capped target logs errors only.
The server builds the final filter with observability::log_filter. With reqwest capped:
#![allow(unused)]
fn main() {
use mcp_server_core::observability::log_filter;
assert_eq!(
log_filter("trace,reqwest=trace", &["reqwest"], &["audit"]),
"trace,reqwest=info,audit=info,\
rmcp::transport::streamable_http_server=warn,rmcp::transport::worker=warn"
);
assert_eq!(
log_filter("error", &["reqwest"], &["audit"]),
"error,reqwest=error,audit=info,\
rmcp::transport::streamable_http_server=error,rmcp::transport::worker=error"
);
}
The reqwest=trace that LOG_LEVEL asked for is dropped, reqwest is capped, the audit target is switched on at info and rmcp’s session targets are capped at warn. DEBUG then appends its two directives.
rmcp session targets
rmcp’s Streamable HTTP server logs MCP session ids at info and in error messages, and its transport workers carry them in the name field of a trace span. Session ids should stay out of logs and traces, so two targets, service::QUIET_LOG_TARGETS, are kept at warn whatever LOG_LEVEL says (lower if LOG_LEVEL is quieter):
rmcp::transport::streamable_http_serverrmcp::transport::worker
Their warnings, such as refused Host headers, still appear.
Content in logs
This crate never logs content: not tool arguments or results, not prompts, not anything a person sent or read. The audit log records which tool was called and how it ended, never its arguments, ids or results.
DEBUG_UNSAFE_LOG_CONTENT=true lets your services log content, for a short investigation on a server you control. It turns on DEBUG too, and logs a warning at startup. Services decide with observability::content_logging_enabled, which they should check before logging anything a person wrote or read:
#![allow(unused)]
fn main() {
use mcp_server_core::observability::content_logging_enabled;
fn log_search(query: &str, hits: usize) {
if content_logging_enabled() {
tracing::debug!(query, hits, "search");
} else {
tracing::debug!(query_len = query.len(), hits, "search");
}
}
log_search("tide times", 3);
}
rmcp logs content at debug. At debug its rmcp::service target logs every request and response in full (received request, response message), tool arguments and results included, whatever DEBUG_UNSAFE_LOG_CONTENT says. So:
- do not set
LOG_LEVELtodebugortracefor everything on a server people use; - use
DEBUG=true, or raise only the targets you need, such asinfo,mcp_weather=debug; - if you need
debugfor everything, keep rmcp atinfo:LOG_LEVEL=debug,rmcp=info.
At trace, other dependencies log protocol detail too. Keep it brief, on a server only you use.
Metrics
With METRICS_ADDR set, such as METRICS_ADDR=0.0.0.0:9090, the server serves Prometheus metrics on a separate listener at that address:
- It is plain HTTP without authentication. Keep it on a network only your monitoring can reach, and never publish its port.
- Any path answers with the metrics in the Prometheus text format, so scrape
/metrics./healthanswersOK. - It starts before the main listener and logs
prometheus metrics listener started. If it cannot bind, the server stops witherror: failed to create HTTP listener: <reason>. - A metric appears once something has recorded it, so a fresh server shows few.
It needs the prometheus feature, on by default. In a build without it, METRICS_ADDR is still checked as an address, and the server logs METRICS_ADDR is set but this build has no Prometheus support (feature `prometheus`): metrics are not served instead of serving.
Metric names
| Metric | Labels | What it counts |
|---|---|---|
http_requests_total | route, status | HTTP requests to /healthz, the OAuth routes and the MCP endpoints. route is the matched route pattern, such as /healthz, /token, /weather, /mcp or /.well-known/oauth-protected-resource/{service}, or unmatched for a path no route matches; status is the status code, such as 200 or 401. |
oauth_requests_total | endpoint, outcome | Requests to the OAuth endpoints, by result. endpoint="register": ok, invalid. endpoint="authorize": ok, rate_limited, unavailable. endpoint="token": ok, or the OAuth error code, such as invalid_grant, invalid_request, invalid_client, invalid_target or unsupported_grant_type. |
oauth_login_failures_total | none | Sign-ins on the sign-in page whose credential was checked and rejected. Input that cannot be a credential, refusals by the limits and checks that could not run are not counted. |
bearer_credential_checks_total | outcome | Requests whose bearer token is a person’s own credential, decided by a check rather than the cache: valid, invalid or unavailable. rate_limited counts requests refused by the sign-in limits before a check, including requests with the static token. |
http_requests_total covers /healthz, the OAuth routes and the MCP endpoints; /favicon.ico and routes you add with Server::wrap_router are not counted. Nor is a request refused with 413 because its declared Content-Length is over the body limit: it is refused before it reaches the counter.
Your own metrics
With METRICS_ADDR set, the server installs a global recorder for the metrics crate, so metrics your services record with it are served on the same listener. Add metrics = "0.24" to your crate:
#![allow(unused)]
fn main() {
fn record_upstream_call(status: u16, seconds: f64) {
metrics::counter!("weather_api_requests_total", "status" => status.to_string()).increment(1);
metrics::histogram!("weather_api_request_duration_seconds").record(seconds);
}
record_upstream_call(200, 0.12);
}
Histograms are exported with these buckets, in seconds: 0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10 and 30.
Scraping
scrape_configs:
- job_name: mcp-weather
static_configs:
- targets: ["mcp-weather:9090"]
Some queries worth watching:
| Query | Shows |
|---|---|
sum(rate(oauth_login_failures_total[5m])) | Failed sign-ins: someone guessing, or a person with a wrong password or key. |
sum by (outcome) (rate(bearer_credential_checks_total[5m])) | Credentials sent as bearer tokens; a rise in unavailable means the upstream service is down or slow. |
sum(rate(http_requests_total{status="429"}[5m])) | Requests refused by the sign-in limits. |
sum(rate(http_requests_total{status="503"}[5m])) | Checks that could not run, the server refusing new addresses, or full session tables. |
sum by (route) (rate(http_requests_total{status="401"}[5m])) | Requests without a usable token, by path. |
Refusals: 429 and 503 explains when the server answers each.
Traces
With OTEL_EXPORTER_OTLP_ENDPOINT set, the server exports traces over OTLP/HTTP (protobuf) to a collector, batched in the background:
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
- Spans go to
<endpoint>/v1/traces. The server’s name, the first argument ofServer::new, is theservice.nameresource attribute. - The exporter reads the standard OpenTelemetry variables itself, such as
OTEL_EXPORTER_OTLP_HEADERSfor a collector that needs an API key,OTEL_EXPORTER_OTLP_TRACES_ENDPOINTfor a full URL used as given, andOTEL_EXPORTER_OTLP_TIMEOUT(10 seconds by default). These have no_FILEvariants, and neither does the endpoint itself: set it directly. - Export is on only when
OTEL_EXPORTER_OTLP_ENDPOINTis set;OTEL_EXPORTER_OTLP_TRACES_ENDPOINTon its own does not turn it on. - An endpoint the exporter cannot parse stops the server at startup, before logging starts, with an
error:line such aserror: invalid exporter configuration: OTEL_EXPORTER_OTLP_ENDPOINT: invalid endpoint 'http://bad host': invalid uri character. - Spans not yet sent are flushed when the server shuts down.
One filter, LOG_LEVEL with its caps, decides both what is logged and what is traced. So the exported spans are:
request, for every HTTP request to/healthz, the OAuth routes and the MCP endpoints, withmethodandpath;- rmcp’s spans for MCP sessions, apart from the session targets kept at
warn; - the spans of your own code, such as functions marked
#[tracing::instrument], at the levelsLOG_LEVELallows.
Log events inside a span are attached to it as span events.
It needs the otel feature, on by default. In a build without it the server logs OTEL_EXPORTER_OTLP_ENDPOINT is set but this build has no OpenTelemetry support (feature `otel`): traces are not exported.
Feature flags
| Feature | Default | What it adds |
|---|---|---|
otel | on | Trace export over OTLP/HTTP, with the OpenTelemetry crates and an HTTP client. |
prometheus | on | The Prometheus metrics listener. |
Without them the crate pulls in fewer dependencies. Metrics are still recorded through the metrics crate but go nowhere, and setting METRICS_ADDR or OTEL_EXPORTER_OTLP_ENDPOINT only logs a warning. To keep metrics and leave out traces:
[dependencies]
mcp-server-core = { version = "0.4", default-features = false, features = ["prometheus"] }
What is never logged
| Never logged | How |
|---|---|
OAUTH_SIGNING_KEY, the owner’s password, MCP_AUTH_TOKEN | Configuration errors about them name the variable and the rule, never the value. The settings’ Debug output hides them. |
| People’s upstream credentials | They are held as secrets whose Debug output is Credential(..). Logs, audit lines and tokens name the person by a subject: unless the verifier names them itself, key: and 16 hex digits of a hash keyed by OAUTH_SIGNING_KEY, which cannot be used to guess the credential. |
| Bearer tokens, authorization codes and refresh tokens | Never logged, at any level, trace included. |
| The sign-in page’s parameters | The request span records the path, not the query string, and form bodies are never logged. |
| MCP session ids | rmcp’s session targets are kept at warn. |
| Tool arguments and results, prompts, anything a person sent or read | Never logged by this crate, nor by rmcp below debug. Your services log them only when content_logging_enabled() is true. |
What is logged, and may count as personal data where you are: client IP addresses on failed sign-ins and rejected tokens (ip), the names clients give themselves when they register, OAuth client ids in audit lines (caller), and subjects (owner, static, key:… or a custom verifier’s names).
Next: Troubleshooting.
Troubleshooting
This page lists every error the server can stop with at startup, quoted as the server prints it, with its fix; then the problems that show up while it runs, such as 401, 429 and 503 answers, refused Host and Origin headers and claude.ai failing to connect; and how to investigate.
The server does not start
Configuration errors
The server reads its whole configuration before it starts and prints every problem it found, each on its own line starting configuration error:, then exits with status 1. Fix them all and start it again. A few checks only run once others pass (see Validation), so a second run can show more.
In the messages below, <PREFIX> is the server’s prefix, MCP unless it sets another.
| Message | Fix |
|---|---|
PUBLIC_URL is required | Set PUBLIC_URL to the external address clients use, such as https://mcp.example.com. |
PUBLIC_URL must be an https URL | The value is not a URL with a host. Include the scheme: https://mcp.example.com, not mcp.example.com. |
PUBLIC_URL must be an https URL (http is only allowed for localhost) | Use https://. http:// is accepted only for localhost, 127.0.0.1 and [::1]. Behind a proxy that terminates TLS, PUBLIC_URL is still the proxy’s https:// address. |
PUBLIC_URL must not contain a path | Remove the path: https://mcp.example.com, not https://mcp.example.com/mcp. The server cannot live under a sub-path; see PUBLIC_URL. |
PUBLIC_URL must not contain a query or fragment | Remove everything from ? or #. |
OAUTH_SIGNING_KEY is required | Set it, or OAUTH_SIGNING_KEY_FILE, to a random value: openssl rand -hex 32. |
OAUTH_SIGNING_KEY must be at least 32 bytes | Use a longer key. openssl rand -hex 32 gives 64 characters. |
OAUTH_ADMIN_PASSWORD is required | The server signs in its owner with a password (SignIn::OwnerPassword, the default). Set OAUTH_ADMIN_PASSWORD or OAUTH_ADMIN_PASSWORD_FILE. |
OAUTH_ADMIN_PASSWORD must be at least 12 characters, not only spaces | Choose a longer passphrase. From 15 characters the startup warning goes too. |
MCP_AUTH_TOKEN must not have the shape of a JWT (three dot-separated parts) | Use a value without exactly two dots; openssl rand -hex 32 has none. |
MCP_AUTH_TOKEN cannot be used when people sign in with their own <label> | The server signs people in with their own credential, or accepts credentials sent as bearer tokens, and a static token would reach tools without one. Unset MCP_AUTH_TOKEN; when the verifier accepts it, a client that can send a header can send its own credential as the bearer token instead. See The static token. |
TRUSTED_PROXIES contains an invalid IP address: <entry> | List single IP addresses, comma separated. Ranges such as 10.0.0.0/8 and host names are not accepted. |
BIND_ADDR has an invalid value | Use an IP address and port, such as 0.0.0.0:8443 or [::]:8443. Host names such as localhost:8443 are not accepted. |
METRICS_ADDR has an invalid value | Use an IP address and port, such as 0.0.0.0:9090. |
LOG_FORMAT has an invalid value | Use json or pretty. |
INSECURE_HTTP must be true or false, got "<value>" | Use true, false, 1, 0, yes, no, on or off. The same message names DEBUG, DEBUG_UNSAFE_LOG_CONTENT, <PREFIX>_COMBINED or a service’s own boolean. |
TLS_CERT_PATH and TLS_KEY_PATH must be set together | Set both, or neither for a self-signed certificate. See Choosing how the server listens. |
<NAME>_FILE: cannot read <path>: <reason> | The file named by a _FILE variable is missing or unreadable by the server’s user. In a container, check the mount and that the file is readable by the container’s user, such as UID 65532. |
<NAME> is required | A service needs this variable. Set it, or leave the service out of <PREFIX>_SERVICES if you do not use it. |
<NAME> has an invalid value | A service’s variable does not parse as the type it expects. The server’s own documentation gives the format. |
<PREFIX>_SERVICES contains an unknown service: <name> (known: <names>) | Use names from the list. Service names are lower case. |
<PREFIX>_SERVICES must name at least one service (known: <names>) | The list has only commas or spaces. Name a service, or unset the variable to run them all. |
<PREFIX>_READ_ONLY contains an unknown service: <name> (known: all, <names>) | Use registered names, or all. |
no enabled service defines how people sign in | With SignIn::ServiceCredential, enable the service whose credential_verifier defines the sign-in, or fix the errors that stopped it from building. See Only one service may define sign-in. |
more than one enabled service defines how people sign in (<names>): enable one of them | Run only one of the named services on this server, with <PREFIX>_SERVICES. Each would hand its tools a credential meant for another upstream. |
the service registered as <name> is named <other> | A programming error: the factory registered as <name> built a service whose name() returns <other>. Make them match. |
Errors when the server starts serving
These come after the configuration has loaded. The server prints the error on its own line starting error: and exits with status 1. Once logging has started it also logs fatal with the error; a bad LOG_LEVEL or OpenTelemetry endpoint stops it before then.
| Message | Fix |
|---|---|
cannot load TLS certificate <cert> / key <key>: <reason> | A file is missing, unreadable by the server’s user, not PEM, or the key does not match the certificate. The server never falls back to a self-signed certificate. See Certificate files. |
Address already in use (os error 98) | Something else listens on BIND_ADDR, often an earlier copy of the server. Stop it or choose another port. |
Permission denied (os error 13) | A port below 1024 needs privileges on most Linux systems. Listen on 8443 and map or proxy port 443 to it. |
Cannot assign requested address (os error 99) | The IP address in BIND_ADDR is not one of this machine’s. Use 0.0.0.0, or an address the machine has. |
failed to create HTTP listener: <reason> | The metrics listener could not bind METRICS_ADDR, for the same reasons as above. |
error parsing level filter: ..., or invalid filter directive | LOG_LEVEL does not parse. Use a level, then target=level directives: info,mcp_weather=debug. See LOG_LEVEL. |
invalid exporter configuration: OTEL_EXPORTER_OTLP_ENDPOINT: invalid endpoint '<value>': <reason> | The collector address is not a URL. Use one such as http://otel-collector:4318. See Traces. |
The operating system’s messages above are Linux’s; other systems word them differently.
Panics while building the server
Server::service panics on a name it cannot serve, before any configuration is read. These are programming errors, found the first time the binary runs:
service name "<name>" must be lowercase letters, digits and '-'service name "mcp" is reserved for the combined endpointservice "<name>" is registered twice
See Names.
Warnings at startup
The server starts, and logs a warning:
| Warning | Meaning |
|---|---|
OAUTH_ADMIN_PASSWORD is shorter than 15 characters: a longer passphrase is much harder to guess | The password is accepted, but a longer one is much harder to guess. |
MCP_AUTH_TOKEN is shorter than 32 characters: use a long random value | Use openssl rand -hex 32. |
INSECURE_HTTP=true: serving plaintext HTTP without TLS | Expected behind a TLS-terminating proxy or on localhost; otherwise remove INSECURE_HTTP. |
no TLS_CERT_PATH/TLS_KEY_PATH set: serving HTTPS with an in-memory self-signed certificate (not trusted by claude.ai) | Fine locally or behind a proxy that does not verify it. For claude.ai directly, set TLS_CERT_PATH and TLS_KEY_PATH. |
DEBUG_UNSAFE_LOG_CONTENT is enabled: message content WILL be written to logs | Turn it off once you have what you need. |
METRICS_ADDR is set but this build has no Prometheus support (feature `prometheus`): metrics are not served | The binary was built without the prometheus feature. |
OTEL_EXPORTER_OTLP_ENDPOINT is set but this build has no OpenTelemetry support (feature `otel`): traces are not exported | The binary was built without the otel feature. |
allowed origin without a port matches any port; a future release will match only the scheme default port. Use `:*` or an explicit port instead | From rmcp, once for each path, for an ALLOWED_ORIGINS entry without a port. Add the port, or :*. |
Requests are refused
The refusals below are counted in http_requests_total by route and status, except a 413 for a body whose declared Content-Length is too large, which is refused before it is counted; see Metrics.
401 Unauthorized
A request to /<service> or /mcp without a token the path accepts gets 401 and a WWW-Authenticate header naming the path’s metadata document. That is the normal first step of signing in: a client follows it to discovery. The challenge carries error="invalid_token" when a token was sent and refused, and never says why.
| Cause | What to do |
|---|---|
No Authorization: Bearer header. No error in the challenge. | The client has not signed in yet, or sends its token another way. Only the Authorization header is read. |
| The access token expired. They last one hour. | The client refreshes it. If refreshing fails, see Token errors. |
| The token was issued for another path. | Each path is its own resource: a token for /weather is refused on /tides and /mcp. Sign in to the path you use; see Each path is its own OAuth resource. |
| The grant has ended: 90 days since sign-in, a new owner’s password, or another sign-in mode or verifier. | Sign in again. See What ends a grant. |
OAUTH_SIGNING_KEY or PUBLIC_URL changed. | Every token and client registration is invalid. Remove the connector and add it again. |
A wrong static token. The server logs wrong static token rejected with the ip. | Check MCP_AUTH_TOKEN on both sides. The server trims spaces around the token a client sends but not around its own value, so a stray space at the end of the server’s setting never matches. Wrong tokens count towards the sign-in limits. |
| A token from somewhere else on a server that signs in its owner by password, without a static token. | Nothing could accept it: the client is sending the wrong token. It is refused without counting. |
The person’s own credential, sent as the bearer token, was rejected upstream. The server logs bearer credential rejected. | Check the credential with the upstream service. A rejection is remembered for 60 seconds, so a key fixed upstream moments ago is refused for up to a minute. |
| A credential that cannot be one, such as one with spaces or longer than 256 bytes. | Nothing is logged and nothing is sent upstream. Check what the client sends. |
A credential found valid is trusted for 10 minutes without asking upstream again, so a key revoked upstream keeps working as a bearer token for up to 10 minutes.
To see what a token holds, decode its middle part. The server’s tokens are signed, not encrypted; only a sealed credential inside is encrypted.
cut -d. -f2 <<<"$TOKEN" | python3 -c 'import base64, json, sys; p = sys.stdin.read().strip(); print(json.dumps(json.loads(base64.urlsafe_b64decode(p + "=" * (-len(p) % 4))), indent=2))'
Compare iss with PUBLIC_URL, aud with the URL of the path (PUBLIC_URL/<service>), exp with the current Unix time, and auth_time with 90 days ago. Tokens describes every claim.
403 Forbidden
The MCP endpoints check the Host and Origin headers; see Host and Origin checks. rmcp logs each refusal as a warning.
| Body | Cause and fix |
|---|---|
Forbidden: Host header is not allowed | The request named a host other than PUBLIC_URL’s, localhost, 127.0.0.1 or ::1. Usually a proxy replaced Host with the upstream’s name: keep it (proxy_set_header Host $host in nginx). Or PUBLIC_URL names another host than the one clients use. |
Forbidden: Origin header is not allowed | A browser-based client on another origin. Add its origin, with a port or :*, to ALLOWED_ORIGINS. |
Forbidden: Invalid Origin header, or Forbidden: Invalid Origin header encoding | The Origin header does not parse, or is not UTF-8. |
A Host header that is not a valid host name gets 400 Bad Request with Bad Request: Invalid Host header instead, and rmcp logs rejected request with malformed Host header.
404 Not Found
| Where | Cause |
|---|---|
/<service> | The service is not running: not in <PREFIX>_SERVICES, or misspelt. The service enabled lines at startup list what runs. |
/mcp | <PREFIX>_COMBINED=false. |
/.well-known/oauth-protected-resource/<service> | The same: no such path on this server. |
An MCP request answered Session not found (or Not Found: Session not found) | The session named in Mcp-Session-Id has ended. rmcp ends a session after 5 minutes without activity; a restart ends them all; with several replicas, another replica opened it (Replicas); and a person’s credential opening more than 50 sessions on one path closes its least recently used. A session opened with another credential gets the same answer. Clients open a new session, so this is only a problem if it happens on every request. |
429 Too Many Requests
Sign-in attempts are limited, and a refusal answers 429 with Retry-After: 30. On an MCP endpoint the body is Too many attempts from this address: credentials or tokens were rejected, or several are being checked at once. Try again shortly.; the sign-in page says Too many attempts from this address: credentials were rejected, or several are being checked at once. Wait a little and try again.
What counts is a failed sign-in, a wrong static token or a rejected credential sent as a bearer token, and every check still running. The limits, per minute:
| Limit | Count |
|---|---|
| Per address (IPv4 address, or IPv6 /64) | 5 attempts |
| Per block (IPv4 /24, or IPv6 /48) | 25 attempts |
| Across all addresses | 30 rejections. With a sign-in that does not carry credentials, such as the owner’s password, this refuses everyone, the owner included, until the minute passes; with people’s own credentials, only addresses that failed themselves. |
Clients that already hold an OAuth token are not affected: the server’s own tokens never count. What to check:
- Everyone is refused at once, behind a proxy. Without
TRUSTED_PROXIESevery client shares the proxy’s address. Set it; see Reverse proxies. - Who is failing. The warnings
oauth login failed: credential rejected,wrong static token rejectedandbearer credential rejectedcarry theip. - A client retrying a wrong static token or key in a loop locks out its own address. Fix the client’s configuration, then wait a minute.
Sign-in attempts explains every limit in full.
503 Service Unavailable
Every 503 carries Retry-After: 30, and tower_http logs response failed at error for each.
| Body | Cause |
|---|---|
Your <label> could not be checked right now: <why> | A person’s credential could not be checked. <why> is the verifier’s own reason (upstream down or rate limiting), the check timed out (15 seconds), the server is checking too many credentials at once (16 checks running, and no slot within 5 seconds), too many attempts from this address; try again shortly for a request that was waiting on the same credential’s check when that check was refused by the limits, or, rarely, the check was abandoned or the check stopped unexpectedly. The server logs bearer credential could not be checked or oauth login: credential could not be checked with the reason. It does not count as a failed attempt. |
Your <label> could not be checked right now: the server is refusing new addresses while it is under heavy load; try again shortly | Only when credentials are carried, as when people sign in with their own (Ceiling::BlockFailing). Failures have reached the overall ceiling, the server already tracks 10,000 addresses and 10,000 blocks with recent attempts, and the new address’s block is not among them, so it cannot be told apart from the attack. It clears as the minute passes. The sign-in page says This server is refusing new addresses while it is under heavy load. Try again shortly. |
This server has too many open sessions. Try again shortly. | The path holds 10,000 MCP sessions, still after entries unused for 360 seconds and sessions rmcp has ended are cleared, and none can fairly make room: with the owner’s password or the static token, whenever the table is full; with people’s own credentials, only for a credential that holds no session yet, when nobody else holds more than one. See MCP sessions. |
413 Payload Too Large
The body length limit exceeded means the request declared a body over 1 MiB. A body sent without a declared length is cut off at 1 MiB instead: the OAuth endpoints answer 413 with Failed to buffer the request body: length limit exceeded, and the MCP endpoints answer 500 with Failed to read request body: length limit exceeded. MCP messages are far smaller; check the client, or a proxy adding to the body. See Body limits.
Sign-in fails
On the sign-in page
| The page says | Cause |
|---|---|
unknown client | The client’s id was not issued by this server under its current OAUTH_SIGNING_KEY and PUBLIC_URL. Remove the connector and add it again, so it registers afresh. |
missing client_id, missing redirect_uri | The client’s request is incomplete. |
redirect_uri is not registered for this client | The client asked to be sent somewhere it did not register. |
The login form expired or was modified. Start the connection again. | The form is valid for 10 minutes. Start again from the client. |
That is not a <label>. | The input cannot be the credential: empty, too long, or a key with spaces inside. |
That <label> was not accepted., or the verifier’s own reason | Wrong password or key. It counts towards the limits. |
Your <label> could not be checked right now: <why> | See 503. |
When the request itself is wrong, the server sends the browser back to the client with an OAuth error, which the client may show:
| Error | Description | Cause |
|---|---|---|
invalid_target | resource is required: name the URL of the service, or of /mcp for every service | The client sent no resource and the server has several services. Use a client that sends resource; only a server with a single service can do without it. |
invalid_target | resource is not a service on this server | The URL the client was given does not match PUBLIC_URL exactly, the service is not running, /mcp is off, or the URL has a trailing /. |
invalid_request | code_challenge_method must be S256, code_challenge is required | The client does not use PKCE with S256. |
unsupported_response_type | response_type must be code | The client asked for another flow. |
Token errors
POST /token answers 400 with a JSON OAuth error. The common ones:
error | error_description | Cause |
|---|---|---|
invalid_grant | sign in again | The grant has ended; see What ends a grant. The client should start a new sign-in. |
invalid_grant | invalid or expired refresh token | Refresh tokens last 30 days, and none outlives its grant. Or OAUTH_SIGNING_KEY changed. |
invalid_grant | invalid or expired code | Codes last 60 seconds. |
invalid_grant | code already used | A code works once. |
invalid_grant | PKCE verification failed | The client’s verifier does not match its challenge. |
invalid_client | unknown client | OAUTH_SIGNING_KEY or PUBLIC_URL changed since the client registered. Remove the connector and add it again. |
invalid_target | resource is not a service on this server | The service the grant is for no longer runs. |
The token endpoint lists every error.
claude.ai cannot connect
Work through these from a machine outside your network:
- The server is reachable with a trusted certificate.
curl https://mcp.example.com/healthzanswersokwithout-k. A self-signed certificate is not trusted by claude.ai; see TLS and deployment. PUBLIC_URLis the address you gave claude.ai.curl https://mcp.example.com/.well-known/oauth-protected-resource/weatherreturns"resource":"https://mcp.example.com/weather", exactly the URL entered in claude.ai, with the same scheme, host and port.- The path answers with a challenge.
curl -i https://mcp.example.com/weatheranswers 401 with aWWW-Authenticateheader naming the metadata document on the same host. A 404 means the service is not running there. - The proxy keeps
Hostand streams responses. A 403Forbidden: Host header is not allowedin the server’s log, or tool calls that hang, point at the proxy; see Reverse proxies. - Nothing in front limits per address. claude.ai reaches the server from a few shared addresses, so a per-address rate limit at the proxy or firewall blocks it.
- The connector predates a change. After
OAUTH_SIGNING_KEYorPUBLIC_URLchanged, remove the connector and add it again.
If the sign-in page appears but connecting still fails, follow the steps: oauth client registered and then oauth authorization granted in the log, then the metric oauth_requests_total{endpoint="token"} by outcome. The first step missing tells you where it stopped.
Other problems
| Problem | Cause |
|---|---|
Write tools are missing, or answer read_only: the <service> service is read-only on this server | The service is in <PREFIX>_READ_ONLY. A tool without read_only_hint = true counts as a write. See Read-only mode and the audit log. |
| Every tool appears twice | The client is connected to a service’s path and to /mcp. Use one or the other. |
--healthcheck prints healthcheck failed | It connects to 127.0.0.1 on the BIND_ADDR port within 5 seconds. Check that BIND_ADDR accepts loopback connections (0.0.0.0 does, an external address does not), that INSECURE_HTTP is the same as the server’s, and that the server has finished starting. |
| No logs at all, or no startup lines | LOG_LEVEL has no level for everything, such as mcp_weather=debug on its own. Use info,mcp_weather=debug. |
| Log files full of colour codes | LOG_FORMAT=pretty writes them even to files. Use json, or set NO_COLOR=1. |
could not write the audit log | The file’s directory does not exist or is not writable by the server’s user. Tool calls still work, and the audit lines are still logged on the audit target. See When the file cannot be written. |
tls certificate reload failed, keeping previous certificate | The renewed files do not load yet, often the certificate written before its key. The server tries again every 30 seconds and keeps serving the old certificate meanwhile. |
Investigating
- Read the warnings first. Refusals log a warning with the address (
ip) or the reason, and the startup lines say what runs where. - See every request.
LOG_LEVEL=info,tower_http=debuglogs each request’s start and finish with its status and latency, without content. - Raise your own crates with
DEBUG=true. AvoidLOG_LEVEL=debugfor everything on a server people use: rmcp then logs tool arguments and results. See Content in logs. - Watch the counters.
http_requests_totalby route and status shows where requests fail; see Metrics. - Check by hand. Checking a connection by hand opens an MCP session with curl.
When you report a bug, include the server’s version (--version), the version of mcp-server-core, and the log lines around the problem. The logs contain no secrets, but check them for IP addresses and, if DEBUG_UNSAFE_LOG_CONTENT was on or LOG_LEVEL set debug or trace for everything, for content. Report security problems privately, as Reporting a vulnerability describes, not in a public issue.
Security model
mcp-server-core is meant to be exposed to the internet, in front of tools that act on someone’s behalf. This page sets out what it defends against and how, what a server that stores nothing cannot do, what remains your responsibility, and how to report a vulnerability. The numbers behind the defences are on Limits and abuse protection.
What is at stake
| Secret | Held by | What it gives whoever has it |
|---|---|---|
OAUTH_SIGNING_KEY | The server | Any token for any path, and the contents of every sealed credential. |
OAUTH_ADMIN_PASSWORD | The owner | Sign-in to every service, on a server where the owner signs in. |
MCP_AUTH_TOKEN | The owner’s clients | Every service path, without OAuth. |
| A person’s upstream credential, such as an API key | That person, and sealed inside their tokens | Their account with the upstream service, through your tools or directly. |
| An access token | An MCP client | One path, for up to an hour. |
| A refresh token | An MCP client | New access tokens for one path, for up to 30 days at a time and no more than 90 days after sign-in. |
The server’s job is to let through only requests that carry one of these legitimately, to keep the long-lived secrets out of reach, and to make guessing a password, token or key too slow to pay off.
Threat model
The server defends against the following.
Unauthenticated access
Every service path, /mcp included, requires one of:
- an OAuth access token issued for that path, whose audience is the path’s own resource URL (RFC 8707), so a token for
/weatheris refused on/tides; - the static token,
MCP_AUTH_TOKEN, when one is set; - a credential the verifier accepts, sent directly as the bearer token, when the verifier accepts bearer credentials (by default, whenever people sign in with their own credentials).
Anything else gets 401 with a WWW-Authenticate header that names the path’s metadata, adds error="invalid_token" when a token was sent, and never says why the token was refused; see The 401 challenge. Access tokens are checked for their signature (HS256 under OAUTH_SIGNING_KEY), issuer, audience, kind and expiry, with 5 seconds of leeway, and for a grant that still holds. A token of one kind, such as a refresh token or a client registration, is never accepted as another.
The routes open without a token, /healthz, the metadata documents, /register, /authorize, /token and /favicon.ico (when the server has an icon), give no access to tools; Endpoints lists them. Routes you add with Server::wrap_router are outside the bearer guard, so protect them yourself.
Guessing
Everything a person can guess at is counted:
- Failed sign-ins on the sign-in page, rejected bearer credentials and wrong static tokens count towards a per-address limit (5 a minute; IPv6 by /64) and a per-block limit (25 a minute per IPv4 /24 or IPv6 /48), from the moment a check starts, so concurrent guesses gain nothing.
- A blocked address cannot sign in or use the static token, even correctly, until the limit clears.
- Failures across all addresses are capped at 30 a minute too. When the credential is not carried, as with one shared secret (the owner’s password, and the static token beside it), reaching that cap blocks everyone, the owner included, while the attack lasts, so a botnet gains nothing from more addresses; clients that already hold an OAuth token keep working. When credentials are carried, as with per-person credentials, the cap blocks only addresses that have failed themselves, so an attacker cannot lock out people on other networks. People sharing the attacker’s /24 or /48 can be held up by its block limit. The mode follows the verifier’s
carried()alone. - This server’s own tokens, even expired, never count. When the verifier does not accept bearer credentials and no static token is set, as on an owner’s-password server without
MCP_AUTH_TOKEN, other bearer tokens could not be a guess at anything and are refused without counting. When it does accept them (by default, whenever credentials are carried), any other token of a plausible shape is checked as a credential, and a rejection counts.
Secrets are compared in constant time: the owner’s password, the static token, the sign-in form’s binding, the sign-in version in tokens and the PKCE challenge are compared through their SHA-256 digests, so neither their content nor their length leaks through timing. Weak secrets are refused or flagged at startup:
OAUTH_SIGNING_KEYmust be at least 32 bytes.OAUTH_ADMIN_PASSWORDmust be at least 12 characters and not only spaces, and gets a warning below 15.MCP_AUTH_TOKENgets a warning below 32 characters. It is refused when shaped like a JWT (three dot-separated parts), and next to a verifier that carries credentials or accepts them as bearer tokens.
Sign-in attempts lists exactly what counts, and The global ceiling the two modes.
Abusing the upstream service through the server
When people sign in with their own credentials, each check is a request to the upstream service, and the server must not become a way to flood it:
- Credentials of an implausible shape are refused locally, without a check.
- At most 16 checks run at once, a check waits at most 5 seconds for a free slot, each is timed out after 15 seconds, and concurrent requests presenting the same credential share one check.
- Verdicts on bearer credentials are cached under the credential’s SHA-256: a valid one for 10 minutes, a rejected one for 60 seconds.
- Checks count towards the per-address and per-block limits from the moment they start, so one network can make at most 25 rejected checks a minute.
There is deliberately no global cap on new checks: anyone with enough networks could use one up to keep everyone else from signing in. An attacker with many networks can therefore still have the server send many junk credentials upstream; limit that at the network if it matters. A credential found valid in the last ten minutes is let in even from a blocked address: its holder has already proved possession, and blocking it would only hurt people behind a shared address. Credential checks and Verdict cache have the details.
Grants outliving the sign-in
Every code, access and refresh token carries a keyed hash of how people sign in (ver: the sign-in mode, the verifier’s label and its generation) and when this person signed in (auth_time). So:
- changing the owner’s password, switching sign-in mode, or changing the verifier’s label or generation ends every earlier grant;
- every grant ends 90 days after sign-in however often it is refreshed, and neither its access nor its refresh token outlives it;
- a token minted for one sign-in mode or upstream service is refused by a server using another, even with the same key and URL, so a sealed credential never reaches the wrong upstream.
For the owner’s password, the generation is a hash of the password, and ver is a keyed hash of that under OAUTH_SIGNING_KEY, so a token reveals nothing usable about the password. What ends a grant lists every event and its effect.
Authorization code interception and CSRF
- PKCE with S256 is required;
plainand requests without a challenge are refused. - Codes are one-time and last 60 seconds.
- The sign-in form is bound to its exact request: a form token, valid for 10 minutes, carries a hash of the client, redirect URI, PKCE challenge,
state, scope and resource, and a form whose fields were changed is refused. - Redirect URIs must be registered by the client and match exactly, must be
https(orhttpon a loopback host, for native apps), carry no fragment or user information, and are capped at 10 per client and 2,048 bytes each. An unknown client or an unregistered redirect URI gets an error page, never a redirect. - Responses to the client carry
iss(RFC 9207), so a client talking to several authorization servers can tell which one answered. - A successful sign-in answers
303 See Other, so no browser re-sends the form, and with it the password, to the client’s redirect URI.
The sign-in page and PKCE describe the flow.
Clickjacking and leaks from the sign-in page
The sign-in page is the one page a person’s browser opens, and the one place they type a secret. It:
- sends
X-Frame-Options: DENYand a strictContent-Security-Policy(default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'), so it cannot be framed and runs no script; - sends
Cache-Control: no-storeandReferrer-Policy: no-referrer, so neither the page nor its URL is kept or passed on; - escapes every value it shows;
- shows the host the person will be sent to after signing in;
- shows the client’s name, capped at 200 characters and free of control characters, marked as self-reported and unverified.
Every response from app::Server sends X-Content-Type-Options: nosniff, and Strict-Transport-Security: max-age=31536000 when it serves certificate files (TLS_CERT_PATH). With a self-signed certificate or plain HTTP, the proxy in front sets its own policy. server::build_app on its own sends nosniff only. Security headers lists every header.
DNS rebinding and cross-site requests
The MCP endpoints check Host and Origin, so a web page cannot use a person’s browser to reach a server on their machine or network:
Hostmust be the host ofPUBLIC_URL,localhost,127.0.0.1or::1, on any port. Anything else gets 403 with the bodyForbidden: Host header is not allowed.- An
Origin, when one is sent, must be the origin ofPUBLIC_URLor one listed inALLOWED_ORIGINS. Anything else gets 403 with the bodyForbidden: Origin header is not allowed. Requests without anOrigin, as from hosted and command-line clients, pass.
Behind a reverse proxy, pass the original Host on. Host and Origin checks covers proxies and ALLOWED_ORIGINS.
One person reaching another’s session
When credentials are carried, as when people sign in with their own credentials, MCP sessions are bound to the credential that opened them, by its SHA-256: a session id is useless with any other credential, and a request that names someone else’s session gets the same 404 Session not found as one for a session that does not exist. Nobody can read from or end another person’s session, even knowing its id.
One credential holds at most 50 sessions on a path, and opening more replaces its own oldest. When a path’s session table is full, a newcomer takes a slot from whoever holds the most, so nobody is pushed out by someone holding fewer. MCP sessions has the rules.
Without carried credentials, as with the owner’s password or the static token, every session on a path has the same owner. On a server where only the owner signs in there is one person, so nothing is lost. A custom verifier whose carried() is false but which lets several people sign in gets no separation between their sessions: anyone signed in who learns a session id can use it.
Credential exposure
- Upstream credentials are never stored. A person’s credential is checked once, then sealed into their tokens with ChaCha20-Poly1305, under a key derived from
OAUTH_SIGNING_KEYwith HKDF-SHA256 and a fresh random nonce each time. It is opened again on every request, and a sealed credential that has been altered does not open. Sealed credentials describes the format. - They never reach the logs. Credentials are never logged, the
Credentialtype prints asCredential(..)inDebugoutput, configuration errors never contain secret values, and caches and session tables key credentials by their SHA-256, never the credential. - People are named without revealing their credential. Logs and the audit log name people by a subject such as
key:and 16 hex digits of an HMAC-SHA256 of the credential under a key derived fromOAUTH_SIGNING_KEY, never the credential, so a subject seen in a token or log line cannot be used to guess the credential offline. See Subjects. - Session ids stay out of logs. rmcp’s targets that log MCP session ids are capped at
warnwhateverLOG_LEVELsays.
The crate never logs what people read or write through tools. Services should log such content only when observability::content_logging_enabled() says the operator set DEBUG_UNSAFE_LOG_CONTENT; Observability lists what is never logged.
What a stateless server cannot do
Nothing is stored, so restarts and replicas need only the configuration: there is no database or volume to protect, back up or keep in step. The price:
- No refresh-token reuse detection. OAuth 2.1 asks an authorization server to notice when an old refresh token is used again and revoke the grant; that needs a record of every grant. A stolen refresh token works until it expires, the grant reaches its 90 days, the owner’s password changes or
OAUTH_SIGNING_KEYis rotated. - No revoking one person or one client. Revocation is all or nothing: rotate
OAUTH_SIGNING_KEY(everyone signs in again, and clients register again) or, with the owner’s password, change the password (everyone signs in again). With per-person credentials, revoking a key at the upstream service also stops it working through the server, since the upstream service refuses it. - Limits are per replica. Each replica keeps its own sign-in limits, one-time-code memory, verdict cache and MCP session tables. Behind several replicas an address gets its allowance on each, and a code could be exchanged once on each within its 60 seconds; the exchange still needs the PKCE verifier, which only the client has. Replicas covers running several.
- No request rate limiting. Limit request rates at your reverse proxy or with a tower layer added through
Server::wrap_router. Do not limit/mcp,/<service>,/tokenor/registerper client address if hosted clients such as claude.ai use the server: they reach it from a few shared addresses, so one busy person would block everyone.
For single sign-on, MFA or many named users, put an identity-aware gateway (Cloudflare Access, oauth2-proxy and the like) in front of /authorize; that is the only page a person’s browser opens. What statelessness means explains the trade-off from the OAuth side.
Out of scope: your responsibilities
The server cannot do these for you:
-
Keep
OAUTH_SIGNING_KEYsecret. Whoever has it can mint tokens and open every sealed credential. Generate it at random and give it to the server as a secret file rather than a plain variable:openssl rand -hex 32 > /run/secrets/oauth_signing_key export OAUTH_SIGNING_KEY_FILE=/run/secrets/oauth_signing_keyRotating it is also how you revoke everything at once.
-
Serve over TLS. Use certificate files, or a proxy in front that terminates TLS. Set
TRUSTED_PROXIESonly to proxies you run; otherwise clients can choose the address they are rate limited as. TLS and deployment covers both. -
Choose strong secrets. Use a passphrase for
OAUTH_ADMIN_PASSWORD(the server warns below 15 characters) and a long randomMCP_AUTH_TOKEN(it warns below 32), or leaveMCP_AUTH_TOKENunset if every client can use OAuth. -
Mark your tools. What your tools do with the access they are given is up to you. Mark tools that only read with
read_only_hint = true, so read-only mode and the audit log treat the rest as writes; then start cautious services read-only. See Read-only mode and the audit log. -
Limit request rates in front of the server, as described above.
-
Keep the metrics listener private.
METRICS_ADDRserves plain HTTP without authentication; bind it to an internal network. -
Never debug with content in production.
DEBUG_UNSAFE_LOG_CONTENTturns on debug logs and lets services write what people read and write into the logs; the server warns at startup while it is set. -
Treat logs as personal data. Warnings about rejected attempts record the client’s address, and the audit log records who changed what and when. Keep the audit file (created with mode
0600) and your logs accordingly. -
Keep the crate up to date. Until 1.0 only the latest minor version receives security fixes; see Releases and versioning.
Reporting a vulnerability
Please report vulnerabilities privately through GitHub: on the repository’s Security tab, choose Report a vulnerability. Do not open a public issue.
You should get a reply within a week. Fixes are released as patch versions and announced in a GitHub security advisory once a fixed version is available. Only the latest minor version receives security fixes until 1.0.
The policy is also in the repository as SECURITY.md.
Limits and abuse protection
The server limits what one address, one network and everyone together can cost it: failed sign-ins, upstream credential checks, MCP sessions, request bodies and client registrations. This page gives every limit with its exact number and window, what counts towards it, and what a client sees when it is refused.
Every limit at a glance
| Limit | Value | Constant |
|---|---|---|
| Attempts per address (IPv4 address, IPv6 /64) | 5 in any 60 seconds | oauth::LOGIN_ATTEMPTS, oauth::LOGIN_WINDOW |
| Attempts per block (IPv4 /24, IPv6 /48) | 25 in any 60 seconds | guards::BLOCK_MAX_ATTEMPTS |
| Global ceiling: rejections across all addresses | 30 in any 60 seconds | guards::GLOBAL_MAX_FAILURES |
| Addresses, and separately blocks, tracked at once | 10,000 each | not public |
| Credential checks running at once | 16 | oauth::MAX_RUNNING_CHECKS |
| Longest a check may run | 15 seconds | oauth::CHECK_TIMEOUT |
| Longest a check waits for a free slot | 5 seconds | oauth::CHECK_SLOT_WAIT |
| A bearer credential found valid is trusted for | 10 minutes | oauth::BEARER_VALID_FOR |
| A rejected bearer credential is remembered for | 60 seconds | oauth::BEARER_INVALID_FOR |
| Verdicts cached at once | 10,000 | not public |
| Longest credential (default shape check) | 256 bytes of visible ASCII | credential::MAX_CREDENTIAL_LEN |
| Longest owner’s password considered | 1,024 bytes | credential::MAX_PASSWORD_LEN |
| MCP sessions per credential, on each path | 50 | not public |
| MCP sessions on each path | 10,000 | not public |
| A session’s entry is treated as idle after | 360 seconds | not public |
Request body, on /healthz, the OAuth routes and the MCP endpoints | 1 MiB (1,048,576 bytes) | server::BODY_LIMIT |
| Redirect URIs per registered client | 1 to 10 | oauth::MAX_REDIRECT_URIS |
| Length of one redirect URI | 2,048 bytes | oauth::MAX_REDIRECT_URI_LEN |
| Length of a client name | 200 characters | oauth::MAX_CLIENT_NAME_CHARS |
Retry-After on every 429 and 503 | 30 seconds | not public |
Token lifetimes and the 90-day grant limit are on OAuth and tokens. Counts, caches and session tables live in memory, and each replica keeps its own.
Your code can read the public numbers from the constants:
#![allow(unused)]
fn main() {
use mcp_server_core::credential::{MAX_CREDENTIAL_LEN, MAX_PASSWORD_LEN};
use mcp_server_core::guards::{BLOCK_MAX_ATTEMPTS, GLOBAL_MAX_FAILURES};
use mcp_server_core::oauth::{
BEARER_INVALID_FOR, BEARER_VALID_FOR, CHECK_SLOT_WAIT, CHECK_TIMEOUT, LOGIN_ATTEMPTS,
LOGIN_WINDOW, MAX_CLIENT_NAME_CHARS, MAX_REDIRECT_URI_LEN, MAX_REDIRECT_URIS,
MAX_RUNNING_CHECKS,
};
use mcp_server_core::server::BODY_LIMIT;
use std::time::Duration;
assert_eq!(LOGIN_ATTEMPTS, 5);
assert_eq!(LOGIN_WINDOW, Duration::from_secs(60));
assert_eq!(BLOCK_MAX_ATTEMPTS, 25);
assert_eq!(GLOBAL_MAX_FAILURES, 30);
assert_eq!(MAX_RUNNING_CHECKS, 16);
assert_eq!(CHECK_TIMEOUT, Duration::from_secs(15));
assert_eq!(CHECK_SLOT_WAIT, Duration::from_secs(5));
assert_eq!(BEARER_VALID_FOR, Duration::from_secs(600));
assert_eq!(BEARER_INVALID_FOR, Duration::from_secs(60));
assert_eq!(MAX_CREDENTIAL_LEN, 256);
assert_eq!(MAX_PASSWORD_LEN, 1024);
assert_eq!(BODY_LIMIT, 1024 * 1024);
assert_eq!(MAX_REDIRECT_URIS, 10);
assert_eq!(MAX_REDIRECT_URI_LEN, 2048);
assert_eq!(MAX_CLIENT_NAME_CHARS, 200);
}
Sign-in attempts
One limiter guards everything a person can guess at: the sign-in page, credentials sent as bearer tokens and the static token. It counts attempts per address, per block of addresses and across all of them.
What counts as an attempt
An attempt is counted when its check starts, so concurrent attempts share the limits too. When the check ends, a rejection keeps counting and anything else is given back.
| Request | Counts? |
|---|---|
A credential submitted on the sign-in page (POST /authorize) | Yes, from when its check starts. Kept if rejected; given back if accepted or if it could not be checked. |
| A credential sent as the bearer token, with no cached verdict | Yes, in the same way. |
A bearer token on a server with MCP_AUTH_TOKEN set, when the token is not shaped like a JWT | Yes, before it is compared. Kept if it is wrong; given back if it is the static token. |
| This server’s own tokens, including expired ones, ones for another path and ones from a grant that has ended | Never. They get 401 and are never sent upstream. |
| A token shaped like a JWT, when the verifier does not accept bearer credentials | Never. It gets 401. |
Any bearer token on a server that accepts neither bearer credentials nor a static token, such as an owner’s-password server without MCP_AUTH_TOKEN | Never. It could not be a guess at anything, so it gets 401 without counting and cannot lock anyone out. |
| Input that cannot be a credential: empty, too long or, for the default shape check, not visible ASCII | Never. It is refused locally; the sign-in page says That is not a <label>. |
| A request with the same credential as a check already running | Never. It waits for that check and shares its verdict. |
| A bearer credential with a cached verdict | Never. A valid one passes; a rejected one gets 401 without counting again. |
| A request with an OAuth access token | Never, and the limits never refuse it. |
GET /authorize, /token, /register, the metadata documents, /healthz | Never. |
The verifier decides the shape check through plausible, and the owner’s password accepts anything from 1 to 1,024 bytes. The CredentialVerifier trait describes plausible, and Credentials sent as bearer tokens the order in which the bearer check tries a token.
A check runs in a task of its own, so a client that disconnects in the middle does not stop it: the attempt is still kept or given back, and a bearer credential’s verdict is still cached.
Per address
An address is an IPv4 address or an IPv6 /64, since one IPv6 host usually holds a whole /64. An IPv4-mapped IPv6 address, such as ::ffff:203.0.113.7 from a dual-stack listener, counts as its IPv4 address.
Each address may have at most 5 attempts in any 60 seconds, counting rejected ones and those still being checked. Each attempt stops counting 60 seconds after its check started. The sixth is refused with 429, and so is every further attempt from that address until one ages out:
- the sign-in page refuses it before looking at the request, even with the right password or credential;
- the static token is refused, even the right one;
- a credential sent as the bearer token is refused, unless it was found valid in the last 10 minutes: its holder has already proved possession, and refusing it would only hurt people behind a shared address.
OAuth access tokens already issued keep working throughout. A person who has connected a client is never locked out by the limits; only signing in again, or using the static token, waits.
Five checks in flight from one address also use up its allowance, so a sixth concurrent check is refused rather than queued.
Per block
A block is an IPv4 /24 or an IPv6 /48: the allocation one network usually controls. Each block may have at most 25 attempts in any 60 seconds, rejected or in flight, whatever addresses within it they come from. The 26th is refused with 429 for every address in the block.
Without it, a network holding a /48 could try 5 guesses from each of its 65,536 /64s. With it, one network can make at most 25 rejected checks a minute. People who share a block with an attacker can be held up by the block limit while the attack lasts.
The global ceiling
Across all addresses, the server counts rejections (not attempts in flight, so a busy server never trips it by itself). When 30 rejections have been recorded in the last 60 seconds, the ceiling is reached, and what happens next depends on how people sign in. The mode is guards::Ceiling, chosen by the verifier’s carried():
| Mode | Chosen when | Once the ceiling is reached |
|---|---|---|
Ceiling::BlockEveryone | Credentials are not carried: the owner’s password, or any verifier whose carried() is false | Every attempt from every address is refused with 429, the owner’s included, until fewer than 30 rejections remain in the last 60 seconds. |
Ceiling::BlockFailing | Credentials are carried: the verifier’s carried() is true, its default, as for a typical SignIn::ServiceCredential or custom verifier | Only addresses with a rejection of their own in the last 60 seconds are refused, even after a single one. Everyone else signs in as usual, apart from the case below. |
The difference follows from what a guess is worth:
- One shared secret. With the owner’s password, or the static token beside it, one right guess gives everything away. Blocking everyone keeps the total guessing rate at 30 a minute however many addresses an attacker controls, so a botnet gains nothing from more addresses. The price: someone who keeps failing can keep the owner out of the sign-in page and the static token for as long as they keep it up. Clients that already hold OAuth tokens keep working.
- Per-person credentials. Each guess is against one key among many, checked upstream. Blocking everyone would let an attacker lock out every other person, so only addresses that failed themselves wait.
When very many addresses are failing
The limiter tracks at most 10,000 addresses and 10,000 blocks that have attempts in the last 60 seconds, and forgets each one once its attempts age out (it sweeps at most once a second). When the address table is full, an address it is not already tracking is not counted on its own: it is limited by its block’s 25 alone, when the block can be tracked. Once the global ceiling is also reached:
- it is refused with 429 if its block has a rejection in the last 60 seconds;
- if the block table is full too and its block is not tracked, it is refused with 503: the server is under attack from so many networks that it cannot tell a new address apart, and refuses new ones until the attack calms down.
Below the ceiling, a full table refuses nothing extra. In practice this matters only in Ceiling::BlockFailing mode: in Ceiling::BlockEveryone mode the ceiling has already refused everyone.
Which address
The address is the TCP peer, unless the peer is listed in TRUSTED_PROXIES. Then it is the client address the proxy reports in X-Forwarded-For, read from the right; How X-Forwarded-For is read gives the exact rules, with examples. IPv4-mapped IPv6 addresses count as their IPv4 address.
Behind a reverse proxy, set TRUSTED_PROXIES to the proxy’s address. Otherwise every request arrives from the proxy, every client shares one address’s allowance, and five failures anywhere lock out everyone. Never list an address you do not run: a client that can set X-Forwarded-For through a trusted address chooses the address it is limited as. TLS and deployment covers proxies.
Credential checks
Every credential the verifier checks, on the sign-in page or as a bearer token, goes through one runner. For a verifier that asks an upstream service, this bounds how much work the server can be made to send there.
| Rule | Effect |
|---|---|
| At most 16 checks run at once | Across the sign-in page and bearer credentials together. |
| A check waits up to 5 seconds for a free slot | Then it gives up as unavailable: the server is checking too many credentials at once. |
| A running check may take up to 15 seconds | Then it is unavailable: the check timed out. |
| One check at a time per credential | Requests with a credential that is already being checked wait for that check and share its verdict. Only the first counts towards the limits, and only it calls the verifier. |
Checks in progress are keyed by the credential’s SHA-256, never the credential itself. An unavailable verdict is never held against the person: the attempt is given back, nothing is cached, and the client is told to try again. If the first request for a credential is refused by the limits, the requests waiting on it are told too many attempts from this address; try again shortly, as an unavailable verdict. A waiting request whose leading check went away without a verdict is told the check was abandoned, and a check whose task failed gives the check stopped unexpectedly.
There is deliberately no global cap on new checks. Anyone with enough networks could use such a cap up to keep everyone else from signing in. An attacker with many networks can therefore still make the server send many junk credentials upstream, 25 a minute from each block; if that matters, limit it at the network. Narrowing plausible to the upstream service’s real credential format means junk of another shape is refused locally without a check.
Verdict cache
Verdicts on credentials sent as bearer tokens are cached under the credential’s SHA-256, so a client that sends its key on every request is not checked upstream every time. The sign-in page always checks.
| Verdict | Cached for | While cached |
|---|---|---|
| Valid | 10 minutes | The credential passes without a check, even from an address the limits are refusing. |
| Rejected | 60 seconds | The credential gets 401 without a check and without counting again. |
| Unavailable | not cached | The next request checks again. |
The cache holds at most 10,000 verdicts. When it is full, expired entries go first, then rejected ones; if every entry is a current valid one, a new rejection is not cached and a new valid verdict replaces the one closest to expiry. A burst of junk keys can never push out keys that work.
One consequence: a key revoked upstream keeps passing the bearer check for up to 10 minutes. It gains nothing by it, since the upstream service refuses the key when a tool uses it.
MCP sessions
An MCP session starts with initialize and is named by the Mcp-Session-Id header after that. Each path, every /<service> and /mcp, keeps its own table of sessions and its own limits, so a person using /notes and /mcp has an allowance on each.
When credentials are carried, as when people sign in with their own credentials, each session belongs to the credential that opened it (the Credential the bearer guard added), by its SHA-256:
- A request that names a session opened with another credential gets
404 Session not found, exactly as for a session that does not exist, so the client starts a new one. Nobody can use or end someone else’s session, even knowing its id. - One credential may hold 50 sessions on a path. Opening a 51st closes that credential’s least recently used session.
- A path holds 10,000 sessions. When the table is full, the server first clears entries unused for 360 seconds and sessions rmcp has already ended (at most once a second). If it is still full, the credential holding the most sessions gives up its least recently used one, provided it holds at least two more than the newcomer. Otherwise a newcomer that already holds sessions replaces its own oldest. A newcomer with no sessions is refused only when nobody else holds more than one, with 503 and
This server has too many open sessions. Try again shortly.
Fair shares mean nobody is pushed out by someone holding fewer sessions, and a few hundred credentials opening sessions cannot lock everyone else out. When the table is full and was swept less than a second ago, a refusal is decided before rmcp builds the session, so refused requests cost little.
An entry unused for 360 seconds, a little longer than rmcp’s own five-minute idle timeout, is checked against rmcp when it is next used: if rmcp still holds the session, as during a long tool call, it carries on; otherwise the request gets 404. A successful DELETE removes the session from the table.
Without carried credentials, as with the owner’s password or the static token, every session on a path has the same owner: there is no per-credential cap, and only the 10,000 sessions per path and the sweep apply. When all 10,000 are in use after the sweep, new sessions are refused with 503 until some go idle or end. With the owner’s password there is one person, so this costs nothing; a custom verifier whose carried() is false but which lets several people sign in gets neither the separation nor the fair shares.
Request bodies
Every route server::build_app mounts, /healthz, /register, /token, /authorize and the MCP endpoints, refuses a request body larger than 1 MiB (1,048,576 bytes). A request whose Content-Length declares more gets 413 Payload Too Large with the body length limit exceeded, before the body is read. A longer body sent without a declared length is cut off at the limit: the OAuth routes answer 413, and the MCP endpoints answer 500. rmcp’s transport is configured with the same limit for the JSON it reads. Routes you add with Server::wrap_router, and /favicon.ico, are outside this layer, so give them a limit of their own. Body limits quotes every answer and shows how to match the limit at your proxy.
Client registration
POST /register is open to anyone, as dynamic client registration requires. It stores nothing: a registration is a token signed by the server, so it costs one signature, and the server caps what one may contain. A refusal is 400 Bad Request with a JSON error and error_description, checked in this order:
| Field | Limit | Refused with |
|---|---|---|
| the body | a JSON client registration | invalid_client_metadata: send a JSON client registration with redirect_uris |
client_name | optional; at most 200 characters, no control characters | invalid_client_metadata: client_name must be at most 200 characters, without control characters |
redirect_uris | 1 to 10 URIs, each at most 2,048 bytes, https with a host or http on localhost, 127.0.0.1 or [::1], without a fragment or user information | invalid_redirect_uri: redirect_uris must be 1 to 10 https URIs (http only on a loopback host), at most 2048 bytes each, without fragments or userinfo |
A body over 1 MiB gets 413 instead.
The sign-in page shows the client name marked as self-reported and unverified. Dynamic client registration describes the endpoint.
Refusals: 429 and 503
Every 429 and 503 carries Retry-After: 30. It is a hint, not the exact time: an address’s attempts age out one by one, up to 60 seconds after each started.
| Status | Body | Cause | What to do |
|---|---|---|---|
| 429 | Too many attempts from this address: credentials or tokens were rejected, or several are being checked at once. Try again shortly. | A bearer token or credential from an address or block over its limit, or any attempt once the ceiling blocks everyone. | Wait. Find out who is failing from the warnings in the log. |
| 429 | Sign-in page: Too many attempts from this address: credentials were rejected, or several are being checked at once. Wait a little and try again. | The same, on the sign-in page. | Wait, then sign in again. |
| 503 | Your <label> could not be checked right now: <why> (the sign-in page shows the same sentence above the form) | The credential could not be checked: the verifier said so, the check timed out, every slot stayed busy for 5 seconds, or the check this request was waiting on was refused. | Try again. If it persists, check the upstream service. |
| 503 | Your <label> could not be checked right now: the server is refusing new addresses while it is under heavy load; try again shortly (sign-in page: This server is refusing new addresses while it is under heavy load. Try again shortly.) | The server is under attack from too many networks to track. | Wait for the attack to pass, or filter it at the network. |
| 503 | This server has too many open sessions. Try again shortly. | The path’s session table is full, and no session can fairly make room; see MCP sessions. | Try again; idle sessions are cleared after 360 seconds. |
| 413 | length limit exceeded when Content-Length is over the limit | A request body over 1 MiB; see Request bodies for a body without a declared length. No Retry-After. | Send less. |
In short, 429 is about attempts: too many from this address or its block were rejected or are still being checked, or, in Ceiling::BlockEveryone mode (the owner’s password), too many from everyone were rejected. Waiting is the answer. 503 means the server or the upstream service cannot take the request now, through no fault of the caller. <label> is the verifier’s name for the credential, such as password or Example API key, and <why> is the verifier’s reason or one of the reasons in Credential checks.
To see the limits at work:
| Metric | Counts |
|---|---|
bearer_credential_checks_total{outcome="rate_limited"} | Bearer tokens and static tokens refused by the limits. outcome is also valid, invalid or unavailable for checked credentials. |
oauth_requests_total{endpoint="authorize",outcome="rate_limited"} | Sign-in attempts refused by the limits. outcome is also unavailable or ok. |
oauth_login_failures_total | Rejected sign-ins on the sign-in page. |
http_requests_total{route,status} | Responses of server::build_app’s routes by matched route and status code, so 429 and 503 responses show here too. A 413 refused on its Content-Length is answered before this counter. |
The log records each rejection as a warning with the client’s address: wrong static token rejected, bearer credential rejected and oauth login failed: credential rejected. A credential that could not be checked is logged as bearer credential could not be checked, with its reason, or on the sign-in page as oauth login: credential could not be checked, with the address and the reason. Refusals by the limits themselves are not logged; watch the rate_limited metrics. Observability has every metric and log line, and Troubleshooting how to work from them.
What the server does not limit
- Request rates. The server limits guesses and credential checks, not how often a signed-in client calls tools. Limit request rates at your reverse proxy, or with a tower layer added through
Server::wrap_router. Do not limit/mcp,/<service>,/tokenor/registerper client address if hosted clients such as claude.ai use the server: they reach it from a few shared addresses, so one busy person would block everyone. Limit per bearer token instead, and per address only on/authorize, the page a person’s browser opens. nginx has a configuration that does this. - Across replicas. Each replica keeps its own counts, caches and session tables. Behind a load balancer with three replicas, an address can make 5 attempts a minute on each.
- What tools do upstream. A signed-in person can call tools as often as the request rate allows; your service and the upstream service’s own limits decide what that costs.
Using the limiter yourself
The server’s limiter is internal, but the type is public, in guards, for a route of your own that checks something guessable, such as one added with Server::wrap_router. Reserve an attempt before checking, then settle it:
#![allow(unused)]
fn main() {
use mcp_server_core::guards::{Ceiling, LoginLimiter, Refusal};
use std::net::{IpAddr, Ipv6Addr};
use std::time::Duration;
/// Counts the attempt before checking, then keeps it only if it was wrong.
fn try_code(limiter: &LoginLimiter, client: IpAddr, right: bool) -> Result<bool, Refusal> {
let attempt = limiter.try_reserve(client)?;
if right {
limiter.refund(attempt);
} else {
limiter.fail(attempt);
}
Ok(right)
}
let limiter = LoginLimiter::new(5, Duration::from_secs(60), Ceiling::BlockEveryone);
// Five wrong codes from five addresses in one IPv6 /64: one client, so its allowance is spent.
for host in 1..=5 {
let client = IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 1, 2, 0, 0, 0, host));
assert_eq!(try_code(&limiter, client, false), Ok(false));
}
let same_client: IpAddr = "2001:db8:1:2::99".parse().unwrap();
assert_eq!(try_code(&limiter, same_client, true), Err(Refusal::TooMany));
// Another /64 is another client.
let neighbour: IpAddr = "2001:db8:1:3::1".parse().unwrap();
assert_eq!(try_code(&limiter, neighbour, true), Ok(true));
}
LoginLimiter::new takes the per-address allowance, the window and the ceiling mode; the block limit of 25, the ceiling of 30 rejections and the 10,000 tracked addresses and blocks are fixed. refusal(ip) and is_blocked(ip) ask without counting, and record_failure(ip) records a rejection that was not reserved first. Settle every reservation with fail or refund: one that is dropped keeps counting until its window passes.
Endpoints
This page lists every HTTP route a server built with app::Server serves: who may call it, what it is for and what it answers, the fields of the two metadata documents, the security headers and the 401 challenge. Every route is at the root of PUBLIC_URL.
Routes
| Method | Path | Authentication | Purpose |
|---|---|---|---|
GET | /healthz | none | Liveness check: answers ok. |
GET | /favicon.ico | none | The server’s icon, when Server::icon is set. |
GET | /.well-known/oauth-protected-resource/<service> | none | Protected-resource metadata of one service, or of mcp (RFC 9728). |
GET | /.well-known/oauth-authorization-server | none | Authorization-server metadata (RFC 8414). |
POST | /register | none | Dynamic client registration (RFC 7591). |
GET | /authorize | none | The sign-in page. |
POST | /authorize | the credential, in the form | Signs the person in and redirects to the client with a code. |
POST | /token | a code and its PKCE verifier, or a refresh token | Issues access and refresh tokens. |
GET | /callback | the pending sign-in’s cookie and state | Only when people sign in through an upstream provider: where the provider sends them back. Redirects to the client with a code. |
POST, GET, DELETE | /<service> | bearer token | One service’s MCP endpoint (Streamable HTTP). |
POST, GET, DELETE | /mcp | bearer token | Every service together, while <PREFIX>_COMBINED is true and at least one service is enabled. See Several services and /mcp. |
- A path outside these routes answers 404, for example a service that is not enabled, or
/mcpwhen it is turned off. A known path called with another method answers 405. - Routes you add with
Server::wrap_routerare served as you define them, without the bearer guard, the body limit or the request metrics. Protect them yourself if they need it. - Prometheus metrics are served on a separate listener,
METRICS_ADDR, not on these routes; see Observability. /healthz, the OAuth routes and the MCP endpoints refuse a request body larger than 1 MiB: with 413 when itsContent-Lengthdeclares more, and as Body limits describes when it is sent without a declared length.
The MCP endpoints
Each service is mounted at /<service>, and /mcp serves every service’s tools and prompts together. The transport is rmcp’s Streamable HTTP server:
| Method | Request | Answer |
|---|---|---|
POST | A JSON-RPC message, with Content-Type: application/json and Accept: application/json, text/event-stream. | The response as JSON or as a server-sent event stream. The answer to initialize carries the new session’s Mcp-Session-Id header, which later requests send back. |
GET | Accept: text/event-stream and the Mcp-Session-Id header. | The session’s stream of server-sent events. |
DELETE | The Mcp-Session-Id header. | Ends the session: 202. |
Sessions exist only on protocol versions before 2026-07-28, where initialize starts one. rmcp serves requests that use the 2026-07-28 revision without a session: for them only POST applies, and GET and DELETE answer 405. When credentials are carried, every session is bound to the credential that opened it; see MCP sessions for the binding and the session caps.
Authentication
Every request needs Authorization: Bearer <token>; the scheme name is case-insensitive. The token is one of:
| Token | Accepted when |
|---|---|
| An access token this server issued for this path | Its grant still holds; see OAuth and tokens. A token for another path is refused. |
MCP_AUTH_TOKEN | It is set. See The static token. |
| The person’s own credential | People sign in with their own credential and the verifier accepts it as a bearer token. See Credentials sent as bearer tokens. |
A request let through carries a Caller and, when credentials are carried, the person’s Credential.
The 401 challenge
A request without a usable token gets 401 Unauthorized with an empty body and a WWW-Authenticate header that names the path’s protected-resource metadata, where an MCP client starts discovery:
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/weather"
When a token was sent and refused, the challenge adds error="invalid_token":
HTTP/1.1 401 Unauthorized
WWW-Authenticate: Bearer resource_metadata="https://mcp.example.com/.well-known/oauth-protected-resource/weather", error="invalid_token"
A token is refused when it is expired, issued for another path, from a grant that has ended, signed under another key, or a wrong static token or credential. The challenge never says which. Troubleshooting explains how to find out.
Responses
| Status | When |
|---|---|
200 | A request answered, as JSON or as an event stream. |
202 | A notification or response from the client accepted, or a session ended with DELETE. |
400 | A malformed MCP request, such as an unsupported MCP-Protocol-Version header (Bad Request: Unsupported MCP-Protocol-Version: <version>) or a GET or DELETE without a session id (Bad Request: Session ID is required). |
401 | No usable token: see The 401 challenge. |
403 | Forbidden: Host header is not allowed: the Host is not PUBLIC_URL’s host, localhost, 127.0.0.1 or ::1. Forbidden: Origin header is not allowed: an Origin that is neither PUBLIC_URL’s nor in ALLOWED_ORIGINS. Both protect against DNS rebinding and cross-site requests; see TLS and deployment. |
404 | The Mcp-Session-Id names a session that does not exist, has ended, or was opened with another credential (Session not found, or rmcp’s Not Found: Session not found). The client starts a new session. On the 2026-07-28 revision, rmcp also answers 404 for a JSON-RPC method the server does not have. |
405 | Any method other than POST, GET and DELETE, or a GET or DELETE on the 2026-07-28 revision. |
406 | The Accept header lacks application/json or text/event-stream on a POST, or text/event-stream on a GET. |
413 | The Content-Length declares a body over 1 MiB (length limit exceeded). A longer body sent without a declared length is cut off at the limit and answered 500 (Failed to read request body: length limit exceeded); see Body limits. |
415 | A POST whose Content-Type is not application/json, or whose body is not JSON. |
422 | On a protocol version before 2026-07-28, a POST without a session id that is not initialize (Unexpected message, expect initialize request). |
429 | Too many failed attempts from this address, with Retry-After: 30: Too many attempts from this address: credentials or tokens were rejected, or several are being checked at once. Try again shortly. |
503 | With Retry-After: 30: the person’s credential could not be checked (Your <label> could not be checked right now: <why>), the server is refusing new addresses under heavy load, or the path holds too many sessions (This server has too many open sessions. Try again shortly.). |
The bearer check runs first, so a request without a usable token gets 401 whatever its Host. The Host and Origin checks apply to the MCP endpoints only. The limits behind 429, 503 and the session table are on Limits and abuse protection.
Metadata documents
Both documents are public JSON, served with 200.
Protected-resource metadata
GET /.well-known/oauth-protected-resource/<service>, for each enabled service and for mcp while the combined endpoint is on:
{
"resource": "https://mcp.example.com/weather",
"authorization_servers": ["https://mcp.example.com"],
"bearer_methods_supported": ["header"],
"scopes_supported": ["weather"]
}
| Field | Value |
|---|---|
resource | PUBLIC_URL/<service>: the value clients send as resource, and the audience of its access tokens. |
authorization_servers | PUBLIC_URL, the only authorization server. |
bearer_methods_supported | header: tokens go in the Authorization header only. |
scopes_supported | The service’s name. |
Any other name, and /.well-known/oauth-protected-resource itself, answers 404.
Authorization-server metadata
GET /.well-known/oauth-authorization-server:
{
"issuer": "https://mcp.example.com",
"authorization_endpoint": "https://mcp.example.com/authorize",
"token_endpoint": "https://mcp.example.com/token",
"registration_endpoint": "https://mcp.example.com/register",
"response_types_supported": ["code"],
"grant_types_supported": ["authorization_code", "refresh_token"],
"code_challenge_methods_supported": ["S256"],
"token_endpoint_auth_methods_supported": ["none"],
"authorization_response_iss_parameter_supported": true,
"scopes_supported": ["weather", "tides", "mcp"]
}
| Field | Value |
|---|---|
issuer | PUBLIC_URL. Every token’s iss, and the iss parameter on authorization responses. |
authorization_endpoint | PUBLIC_URL/authorize |
token_endpoint | PUBLIC_URL/token |
registration_endpoint | PUBLIC_URL/register |
response_types_supported | code |
grant_types_supported | authorization_code and refresh_token |
code_challenge_methods_supported | S256 |
token_endpoint_auth_methods_supported | none: public clients, without a secret. |
authorization_response_iss_parameter_supported | true (RFC 9207). |
scopes_supported | The enabled services’ names, then mcp while the combined endpoint is on. |
There is no revocation, introspection or JWKS endpoint: tokens are signed with a shared secret (HS256) and verified only by servers that hold it. See What statelessness means.
OAuth endpoints
How each step works, and every error message, is on OAuth and tokens. In short:
| Route | Answers |
|---|---|
POST /register | 201 with the client’s registration as JSON. 400 with invalid_client_metadata or invalid_redirect_uri for input outside the registration caps. |
GET /authorize | 200 with the sign-in page. 400 with an error page for an unknown client or redirect URI. 302 to the redirect URI with error for other invalid requests. |
POST /authorize | With an upstream provider, 303 to the provider with a pending sign-in cookie. Otherwise 303 to the redirect URI with code, state and iss on success, or with error for an invalid request. 400 with an error page for an unknown client or redirect URI, or when the form expired or was altered. 401 with the page again for input that is not plausible or a rejected credential. 429 or 503 when the sign-in limits refuse the address, and 503 when the credential could not be checked. See The sign-in page. |
GET /callback | 303 to the redirect URI with code, state and iss, or with error=access_denied when the person declined at the provider. 400 with an error page when the sign-in expired or was started in another browser, 401 when the provider refused the code, 503 when it could not be reached, 429 when the sign-in limits refuse the address. |
POST /token | 200 with tokens as JSON. 400 with an OAuth error as JSON. 413 for a body over the limit. See The token endpoint. |
/register reads JSON; /token and POST /authorize read forms (application/x-www-form-urlencoded).
Health and icon
GET /healthz answers 200 with the body ok, without authentication. It shows the process is serving, nothing more: it does not contact upstream services. The binary’s --healthcheck flag requests it on 127.0.0.1 at the BIND_ADDR port; see TLS and deployment.
GET /favicon.ico answers 200 with the 128x128 PNG given to Server::icon, as image/png. Without an icon the route does not exist.
Security headers
| Header | Value | Sent on |
|---|---|---|
X-Content-Type-Options | nosniff | Every response, including refusals such as 413 and routes added with Server::wrap_router. |
Strict-Transport-Security | max-age=31536000 | Every response, when the server serves certificate files (TLS_CERT_PATH and TLS_KEY_PATH). Not with a self-signed certificate or plain HTTP; see TLS and deployment. |
X-Frame-Options | DENY | Pages from /authorize. |
Content-Security-Policy | default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none' | Pages from /authorize. |
Referrer-Policy | no-referrer | Pages from /authorize. |
Cache-Control | no-store | Pages from /authorize, the redirect after a successful sign-in and every JSON answer from /token. |
Retry-After | 30 | Every 429 and 503 this crate sends: from the bearer guard, the sign-in page and the session table. |
Why the sign-in page sends its headers is explained under Page headers. If you build the application with server::build_app instead of app::Server, it sends nosniff but never Strict-Transport-Security; see Lower-level API.
Lower-level API
app::Server is a thin layer over public modules. This page maps those modules, shows how to build and serve a server from them without app::Server, and explains the re-exports, feature flags and what the crate’s version numbers promise. Every item is documented in full on docs.rs.
When to use it
Most servers need only app::Server. Reach for the modules below when you need a different shape:
- your configuration comes from somewhere other than environment variables;
- you serve with your own listener, or alongside routes of an existing axum application;
- you want one piece on its own, such as the hardened MCP transport, the token issuer in a test, or the sign-in limiter.
There is a middle way too: Server::load and Server::router give you the whole application as an axum::Router without serving it, as Testing a whole server shows. Serve that router however you like, as long as handlers see the peer address (see Serving with your own listener).
Module map
| Module | What it holds |
|---|---|
app | Server, the builder for a whole binary; SignIn; Loaded, a checked configuration with its services built; Safety, the read-only services and the audit log; healthcheck(), the --healthcheck probe; MIN_ADMIN_PASSWORD_CHARS, RECOMMENDED_ADMIN_PASSWORD_CHARS, RECOMMENDED_STATIC_TOKEN_CHARS |
caller | Caller and Via: who made a request and how they proved it; STATIC_SUBJECT |
combined | Combined, several handlers served as one MCP server (/mcp); DynHandler, a type-erased handler; ToolHandler, the trait behind it; prefixed_name; COMBINED ("mcp") |
config | EnvReader, which reads variables and collects every error; CoreConfig, the settings every server shares |
credential | CredentialVerifier, CredentialCheck and CheckFuture; PasswordVerifier; Credential, the caller’s credential in the request extensions; Sealer and SealError; fingerprint, plausible, MAX_CREDENTIAL_LEN, MAX_PASSWORD_LEN |
guards | LoginLimiter, Ceiling, Refusal and Reservation: the sign-in limits; ReplayGuard, one-time use of codes; GLOBAL_MAX_FAILURES, BLOCK_MAX_ATTEMPTS |
jwt | Jwt, which issues and verifies the server’s tokens; Claims, Payload, TokenKind, JwtError; LEEWAY_SECS, SERVER_SUBJECT |
oauth | AuthState, the authorization server’s state; OAuthSettings; oauth_router, its routes; require_bearer, the bearer guard; client_ip; validate_redirect_uri; sign_in_version; the limit and lifetime constants |
observability | init, ObservabilityConfig, ObservabilityGuard and LogFormat; log_filter and build_filter; debug_enabled and content_logging_enabled |
pkce | s256, verify and ct_eq, the constant-time comparison every secret goes through |
policy | Guarded, the wrapper that applies read-only mode and the audit log; ToolPolicy; AuditLog and AuditLine; is_read_only, visible_tools; AUDIT_TARGET |
prompt | tool_prefix and ToolPrefix; UNAVAILABLE; argument, number_argument, user_prompt, not_found |
server | build_app, the HTTP application; http_metrics; BODY_LIMIT |
service | Service, ServiceFactory and ServiceEnv; ServiceContext and HttpSettings; mcp_service, the hardened Streamable HTTP transport; icons; QUIET_LOG_TARGETS |
tls | serve; TlsMode; generate_self_signed and SelfSigned; healthcheck |
At the crate root:
| Item | What it is |
|---|---|
install_crypto_provider() | Installs rustls’ ring provider as the process default. Call it once before serving TLS; later calls do nothing. Server::main calls it for you. |
shutdown_signal() | A CancellationToken cancelled on Ctrl-C, or SIGTERM on Unix. Call it inside a Tokio runtime. |
axum, rmcp | The two crates whose types appear in this crate’s API, re-exported. See Re-exports. |
Architecture explains how the modules work together on a request.
Public constants
| Constant | Value | Explained on |
|---|---|---|
app::MIN_ADMIN_PASSWORD_CHARS | 12 | Configuration reference |
app::RECOMMENDED_ADMIN_PASSWORD_CHARS | 15 | Configuration reference |
app::RECOMMENDED_STATIC_TOKEN_CHARS | 32 | Configuration reference |
caller::STATIC_SUBJECT | "static" | Sign-in modes |
combined::COMBINED | "mcp" | Several services and /mcp |
credential::MAX_CREDENTIAL_LEN | 256 bytes | Sign-in modes |
credential::MAX_PASSWORD_LEN | 1024 bytes | Sign-in modes |
guards::GLOBAL_MAX_FAILURES | 30 | Limits |
guards::BLOCK_MAX_ATTEMPTS | 25 | Limits |
jwt::LEEWAY_SECS | 5 | OAuth and tokens |
jwt::SERVER_SUBJECT | "server" | OAuth and tokens |
oauth::LOGIN_ATTEMPTS | 5 | Limits |
oauth::LOGIN_WINDOW | 60 seconds | Limits |
oauth::MAX_RUNNING_CHECKS | 16 | Limits |
oauth::CHECK_TIMEOUT | 15 seconds | Limits |
oauth::CHECK_SLOT_WAIT | 5 seconds | Limits |
oauth::BEARER_VALID_FOR | 600 seconds | Limits |
oauth::BEARER_INVALID_FOR | 60 seconds | Limits |
oauth::MAX_GRANT_AGE | 90 days | OAuth and tokens |
oauth::MAX_REDIRECT_URIS | 10 | Limits |
oauth::MAX_REDIRECT_URI_LEN | 2048 bytes | Limits |
oauth::MAX_CLIENT_NAME_CHARS | 200 | Limits |
policy::AUDIT_TARGET | "audit" | Read-only mode and the audit log |
prompt::UNAVAILABLE | A sentence for the end of a prompt that names tools: "If a tool named here is not available on this server (for example because the service is read-only or the tool is turned off), say so and stop that step." | Prompts |
server::BODY_LIMIT | 1,048,576 bytes (1 MiB) | Limits |
service::QUIET_LOG_TARGETS | rmcp::transport::streamable_http_server, rmcp::transport::worker | Observability |
What app::Server does
Before you replace app::Server, know what it does, so you keep what you need. Server::main:
- handles
--version(or-V),--help(or-h) and--healthcheck, and exits with status 2 on any other argument; otherwise it callsinstall_crypto_provider(); - reads the configuration with
Server::load:CoreConfig::from_env, the sign-in verifier (forSignIn::OwnerPassword,OAUTH_ADMIN_PASSWORDof at least 12 characters, not only spaces; forSignIn::Custom, your function’s),<PREFIX>_SERVICES,<PREFIX>_READ_ONLY,AUDIT_LOG_PATHand<PREFIX>_COMBINED, then each selected service’s factory. ForSignIn::ServiceCredentialit then takes the verifier of the one enabled service that defines one. It reports a static token that cannot be used (shaped like a JWT, or next to a verifier that takes people’s own credentials) as a configuration error, collects the startup warnings and removes duplicate errors; - rewrites
LOG_LEVELwithobservability::log_filter, applying every service’s log caps, quietening rmcp’s session targets and keeping theaudittarget on, then callsobservability::init; - logs the startup warnings, each enabled service with its URL, read-only state and tools, and the combined endpoint with its number of tools;
- builds the application with
Server::router: anAuthStatewhose resources are the services (andmcpwhen the combined endpoint is on), each service’s router with itsToolPolicyattached, the combined endpoint,server::build_app,/favicon.ico, yourwrap_routerfunction, and a last layer that addsX-Content-Type-Options: nosniffto every response andStrict-Transport-Security: max-age=31536000when serving certificate files; - serves it with
tls::serveuntilshutdown_signal()fires.
Anything you leave out is absent. In particular:
- without a
ToolPolicyon a service’s router, the policy wrapper changes nothing: no read-only mode and no audit lines; build_appsendsnosniffbut never HSTS;AuthState::newpanics on a static token it cannot use, whereServer::loadwould report it with the other errors;PasswordVerifier::newtakes a password of any length; the 12-character minimum is checked byServer::load;- without
log_filter, aLOG_LEVELofinfoor more verbose lets rmcp log MCP session ids, and aLOG_LEVELofwarnor quieter drops the audit lines from the logs (the audit file, if any, is still written).
A server without app::Server
This builds one service, tools, behind the owner’s password, from the same environment variables app::Server reads, with read-only mode and the audit log wired in:
use mcp_server_core::axum::Extension;
use mcp_server_core::config::{CoreConfig, EnvReader};
use mcp_server_core::credential::PasswordVerifier;
use mcp_server_core::oauth::AuthState;
use mcp_server_core::policy::{AUDIT_TARGET, AuditLog, ToolPolicy};
use mcp_server_core::rmcp::ServerHandler;
use mcp_server_core::server::build_app;
use mcp_server_core::service::{HttpSettings, ServiceContext, mcp_service};
use mcp_server_core::{install_crypto_provider, observability, shutdown_signal, tls};
use std::sync::Arc;
/// Your MCP server: in practice a `#[tool_router]` with your tools.
#[derive(Clone)]
struct Tools;
impl ServerHandler for Tools {}
#[tokio::main]
async fn main() -> anyhow::Result<()> {
install_crypto_provider();
// 1. Configuration: the core settings and the owner's password, every error at once.
let mut env = EnvReader::from_process();
let core = CoreConfig::from_env(&mut env, "mcp-tools", "mcp_tools");
let password = env.secret_required("OAUTH_ADMIN_PASSWORD");
let (Some(core), Some(password)) = (core, password) else {
for e in &env.errors {
eprintln!("configuration error: {e}");
}
std::process::exit(1);
};
// 2. Logs, metrics and traces, keeping session ids out and the audit target on.
let mut obs = core.observability.clone();
obs.log_level = observability::log_filter(&obs.log_level, &[], &[AUDIT_TARGET]);
let _guard = observability::init(&obs)?;
// 3. The authorization server, with one protected resource: PUBLIC_URL/tools.
let auth = AuthState::new(
core.oauth.clone(),
&["tools"],
Arc::new(PasswordVerifier::new(password)),
);
// 4. The service on the hardened transport, with its read-only rule and audit log.
let shutdown = shutdown_signal();
let ctx = ServiceContext {
http: HttpSettings::from_core(&core),
shutdown: shutdown.clone(),
};
let policy = ToolPolicy {
service: "tools".into(),
endpoint: "/tools".into(),
read_only: false,
audit: Arc::new(AuditLog::new(None)),
};
let tools = mcp_service(&ctx, || Ok(Tools)).layer(Extension(policy));
// 5. /healthz, the OAuth routes and /tools behind its bearer guard. Serve until SIGTERM.
let app = build_app(auth, vec![("tools", tools)]);
tls::serve(app, core.bind_addr, core.tls.clone(), shutdown).await
}
It needs anyhow and tokio (with macros and rt-multi-thread) as dependencies of your own. The sections below take each step in turn.
Configuration: CoreConfig
CoreConfig::from_env(env, service_name, crate_target) reads the variables every server shares, from PUBLIC_URL to OTEL_EXPORTER_OTLP_ENDPOINT. It returns None when it recorded any error in env.errors, so read the rest of your configuration from the same EnvReader before you report. service_name names the server in traces; crate_target is the tracing target DEBUG raises to debug.
It does not read OAUTH_ADMIN_PASSWORD, AUDIT_LOG_PATH or the <PREFIX>_ variables: those belong to app::Server. The configuration reference says which variable is read where.
| Field | Type | Holds |
|---|---|---|
public_url | String | PUBLIC_URL without a trailing slash |
public_host | String | Its host, IPv6 without brackets |
oauth | OAuthSettings | public_url, signing_key (OAUTH_SIGNING_KEY), trusted_proxies (TRUSTED_PROXIES) and static_token (MCP_AUTH_TOKEN) |
allowed_origins | Vec<String> | ALLOWED_ORIGINS |
bind_addr | SocketAddr | BIND_ADDR, default 0.0.0.0:8443 |
tls | TlsMode | Insecure, Files { cert, key } or SelfSigned { sans }, chosen by TlsMode::select |
observability | ObservabilityConfig | LOG_LEVEL, LOG_FORMAT, DEBUG, DEBUG_UNSAFE_LOG_CONTENT, METRICS_ADDR, whether OTEL_EXPORTER_OTLP_ENDPOINT is set, and the service_name and crate_target given to from_env |
core.service_url("tools") is PUBLIC_URL/tools. You can also fill the structs yourself: CoreConfig, OAuthSettings and HttpSettings have public fields. EnvReader works with any lookup function, EnvReader::new(|name: &str| ...), and its methods are described under Reading configuration with ServiceEnv.
PUBLIC_URL cannot have a path, and the OAuth metadata lives at /.well-known/... on its root. Serve the application at the root of its host: merge other routes into it rather than nesting it under a prefix.
The authorization server: AuthState
AuthState::new(settings, services, verifier) returns an Arc<AuthState> shared by the OAuth routes and every bearer guard.
servicesare the protected resources, eachPUBLIC_URL/<name>. List every path you will guard, andcombined::COMBINED(mcp) if you serve the combined endpoint. They also appear asscopes_supportedin the metadata.verifierdecides who may sign in: aPasswordVerifier, or your ownCredentialVerifier.- It panics if
settings.static_tokenis set while the verifier carries credentials or accepts them as bearer tokens, or when the token has the shape of a JWT. Check those before calling it if the values come from outside.
It holds the token issuer, the credential sealer, the sign-in limiter, the replay guard, the verdict cache and the check runner; Architecture lists what each keeps. Its public methods:
| Method | Returns |
|---|---|
sign_in_version() | The ver every code, access and refresh token must carry |
subject_of(credential) | Who signed in with credential: the verifier’s own subject if it names one, else owner when credentials are not carried, else key: and 16 hex digits of a hash keyed by OAUTH_SIGNING_KEY |
settings() | The OAuthSettings it was built with |
jwt() | The Jwt that issues and verifies tokens, for minting one in a test |
sealer() | The Sealer for carried credentials |
verifier() | The verifier |
services(), has_service(name) | The protected resources’ names |
resource(name) | PUBLIC_URL/<name> |
resource_metadata_url(name) | PUBLIC_URL/.well-known/oauth-protected-resource/<name> |
service_for_resource(url) | The name whose resource URL is exactly url |
oauth_router(state) returns the five OAuth routes listed on Endpoints; build_app merges it for you. require_bearer is the bearer guard, a middleware whose state is the AuthState and the path’s name: axum::middleware::from_fn_with_state((auth.clone(), "tools".to_string()), require_bearer) guards a router as build_app does. client_ip(peer, headers, trusted) gives the address the limiter uses, which a rate-limiting layer of your own can use too.
Services: mcp_service
service::mcp_service(ctx, factory) serves any rmcp ServerHandler over Streamable HTTP and returns an axum::Router to mount at a path. factory is Fn() -> Result<S, std::io::Error> and runs once per MCP session, so it should only clone Arcs. Around the handler it adds:
- Host and Origin checks: the
PUBLIC_URLhost andlocalhost,127.0.0.1and::1; thePUBLIC_URLorigin andALLOWED_ORIGINS(see Host and Origin checks); - the 1 MiB limit on each request body rmcp reads, and the shutdown token from
ctx, which ends open sessions; - the policy wrapper,
policy::Guarded, which reads aToolPolicyfrom the request; - sessions bound to the credential that opened them when the request carries a
Credential, with the caps described under MCP sessions.
ctx is a ServiceContext: HttpSettings::from_core(&core) and the shutdown token you serve with.
Read-only mode and the audit log
The policy wrapper looks for a ToolPolicy in the request extensions. Attach one to each service’s router with axum::Extension, as the example does:
| Field | Holds |
|---|---|
service | The service name recorded in audit lines and named in the refusal |
endpoint | The path recorded in audit lines, such as /tools |
read_only | Hide and refuse the tools not marked read_only_hint = true |
audit | An Arc<AuditLog>. AuditLog::new(Some(path)) also appends JSON lines to path; share one AuditLog between services. |
Without a ToolPolicy, tools are served unchanged. app::Server builds each service’s policy with Safety::policy(name), which records the endpoint as /<name>. Read-only mode and the audit log describes the module.
The combined endpoint
app::Server serves every service’s tools together at /mcp. To do the same, give each handler its policy with Guarded::with_policy, recording /mcp as the endpoint, and combine them:
#![allow(unused)]
fn main() {
use mcp_server_core::axum::Router;
use mcp_server_core::combined::{COMBINED, Combined, DynHandler};
use mcp_server_core::policy::{AuditLog, Guarded, ToolPolicy};
use mcp_server_core::rmcp::ServerHandler;
use mcp_server_core::rmcp::model::Implementation;
use mcp_server_core::service::{ServiceContext, mcp_service};
use std::sync::Arc;
#[derive(Clone)]
struct Tools;
impl ServerHandler for Tools {}
/// `/mcp` over one service, `tools`: its tools appear as `tools_<tool>`.
fn combined(ctx: &ServiceContext, audit: Arc<AuditLog>) -> Router {
mcp_service(ctx, move || {
let policy = ToolPolicy {
service: "tools".into(),
endpoint: format!("/{COMBINED}"),
read_only: false,
audit: audit.clone(),
};
let handlers = vec![("tools", DynHandler::new(Guarded::with_policy(Tools, policy)))];
Ok(Combined::new(Implementation::new("mcp-tools", "1.0.0"), handlers))
})
}
}
Then include COMBINED in the names given to AuthState::new and pass (COMBINED, combined(&ctx, audit)) to build_app. Service names must not contain _, which separates the service from the tool name; Several services and /mcp describes the endpoint.
The application: build_app
server::build_app(auth, services) takes the AuthState and a list of (name, router) pairs and returns the application:
GET /healthz, answeringok;- the OAuth routes;
- each router nested at
/<name>behind its own bearer guard; - around all of these:
http_requests_totalmetrics, the 1 MiB body limit, arequesttracing span andX-Content-Type-Options: nosniff.
It panics with service <name> is not registered with AuthState when a name was not given to AuthState::new. It does not add /favicon.ico, the combined endpoint or HSTS. To send HSTS as app::Server does when it serves certificate files, add a layer:
#![allow(unused)]
fn main() {
use mcp_server_core::axum::Router;
use mcp_server_core::axum::http::{HeaderValue, header};
use mcp_server_core::axum::middleware::map_response;
use mcp_server_core::axum::response::Response;
fn with_hsts(app: Router) -> Router {
app.layer(map_response(|mut res: Response| async move {
res.headers_mut().insert(
header::STRICT_TRANSPORT_SECURITY,
HeaderValue::from_static("max-age=31536000"),
);
res
}))
}
}
Routes you add after build_app are outside its layers. Add server::http_metrics to them with axum::middleware::from_fn(http_metrics) to count them in http_requests_total.
Serving: tls::serve
tls::serve(app, addr, mode, shutdown) serves the application on addr until shutdown is cancelled, then gives open connections up to 10 seconds to finish. mode is a TlsMode:
| Mode | Serves |
|---|---|
TlsMode::Insecure | Plain HTTP, with a warning in the log |
TlsMode::Files { cert, key } | HTTPS with a PEM chain and key, checked for changes every 30 seconds and reloaded |
TlsMode::SelfSigned { sans } | HTTPS with a certificate generated in memory for sans, its SHA-256 fingerprint logged |
TlsMode::select(insecure, cert, key, public_host) chooses as CoreConfig does, and is_tls() says whether the mode speaks TLS. generate_self_signed(sans) returns the certificate and key as PEM with the fingerprint, and tls::healthcheck(port, tls) is the probe behind --healthcheck. Call install_crypto_provider() before serving TLS. TLS and deployment explains the modes for operators.
Logs, metrics and traces
observability::init(&config) installs the global tracing subscriber, the Prometheus listener when METRICS_ADDR is set and the OTLP exporter when OTEL_EXPORTER_OTLP_ENDPOINT is set. Call it once and keep the returned guard for the life of the process: dropping it flushes traces. It fails if a global subscriber is already installed. If your application has its own, skip init and pass your filter through log_filter(level, caps, always_on), which caps the targets in caps at info and those in QUIET_LOG_TARGETS at warn (never above the level LOG_LEVEL sets for everything), and keeps the targets in always_on at info. Only init turns on DEBUG and DEBUG_UNSAFE_LOG_CONTENT: without it, debug_enabled() and content_logging_enabled() stay false. Observability describes the logs and metrics themselves.
Serving with your own listener
tls::serve is optional. Any server works if handlers can see the peer address as ConnectInfo<SocketAddr>: the bearer guard and the sign-in page use it for the sign-in limits, and without it every client counts as 0.0.0.0 and shares one allowance. With axum’s own server, over plain HTTP:
#![allow(unused)]
fn main() {
async fn run(app: mcp_server_core::axum::Router) -> std::io::Result<()> {
use mcp_server_core::axum;
use std::net::SocketAddr;
let shutdown = mcp_server_core::shutdown_signal();
let listener = tokio::net::TcpListener::bind("127.0.0.1:8080").await?;
axum::serve(
listener,
app.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(shutdown.cancelled_owned())
.await
}
}
Use the same token for ServiceContext::shutdown, so open MCP sessions end when the server stops. Behind a proxy, TRUSTED_PROXIES still decides whose X-Forwarded-For is believed; see How X-Forwarded-For is read.
Re-exports
| Path | Crate | Version |
|---|---|---|
mcp_server_core::axum | axum | 0.8 |
mcp_server_core::rmcp | rmcp | 3.9, with the server, macros and transport-streamable-http-server features |
Both appear in this crate’s API: axum::Router in Service::router, build_app and wrap_router; rmcp’s ServerHandler, models and request context in DynHandler, Guarded, Combined and the prompt helpers. Use them through these paths, so your types are the ones the crate expects. A second copy of rmcp or axum at another version in your dependency tree gives types that do not match, and errors that are hard to read.
rmcp’s macros (#[tool_router], #[tool], #[tool_handler] and the prompt macros) expand to paths that start with rmcp::. In a crate that does not depend on rmcp itself, bring the re-export into scope under that name, or the expansion fails with cannot find module or crate `rmcp` in this scope:
#![allow(unused)]
fn main() {
use mcp_server_core::rmcp;
use mcp_server_core::rmcp::handler::server::router::tool::ToolRouter;
use mcp_server_core::rmcp::model::{CallToolResult, ContentBlock, ServerCapabilities, ServerConfig};
use mcp_server_core::rmcp::{ErrorData as McpError, ServerHandler, tool, tool_handler, tool_router};
#[derive(Clone)]
struct Hello {
tool_router: ToolRouter<Self>,
}
#[tool_router]
impl Hello {
#[tool(description = "Say hello.", annotations(read_only_hint = true))]
async fn hello(&self) -> Result<CallToolResult, McpError> {
Ok(CallToolResult::success(vec![ContentBlock::text("Hello!")]))
}
}
#[tool_handler(router = self.tool_router)]
impl ServerHandler for Hello {
fn get_info(&self) -> ServerConfig {
ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
}
}
}
The same goes for schemars, which rmcp re-exports for tool arguments: use mcp_server_core::rmcp::schemars::{self, JsonSchema}; lets #[derive(JsonSchema)] find it, as examples/notes.rs does. The repository’s examples and this site’s doctests compile without the first line only because they can see rmcp as a dependency of the crate itself.
One form does not work this way: #[tool_router(server_handler)], which writes the ServerHandler impl for you, expands to absolute ::rmcp:: paths, and no use line satisfies those. Write the #[tool_handler] impl yourself, as above.
Feature flags
| Feature | Default | Adds |
|---|---|---|
otel | on | OpenTelemetry trace export over OTLP/HTTP when OTEL_EXPORTER_OTLP_ENDPOINT is set |
prometheus | on | The Prometheus listener on METRICS_ADDR |
Without them the crate pulls in fewer dependencies. The public API is the same either way; setting the variable of a missing feature only logs a warning, as Observability describes. To turn both off:
[dependencies]
mcp-server-core = { version = "0.4", default-features = false }
or to keep only metrics, add features = ["prometheus"]. CI builds and lints the crate with every feature and with none.
Stability and semver
The crate follows semantic versioning. Before 1.0, a minor version (0.1 to 0.2) may change the API, and a patch version (0.1.0 to 0.1.1) does not. Because rmcp and axum types are part of the API, a new minor version of either reaches you as a new minor version of this crate. Releases and versioning has the details.
non_exhaustive types
These types are #[non_exhaustive], so later versions can add variants or fields without a breaking change:
| Type | Kind | What it means for you |
|---|---|---|
app::SignIn | enum | A match on it needs a _ arm. |
app::Loaded | struct | Built only by Server::load; read its fields. |
caller::Caller | struct | Build one with Caller::new(subject, via), for your own middleware or tests. |
caller::Via | enum | A match needs a _ arm. |
credential::CredentialCheck | enum | Return its variants freely; a match needs a _ arm. |
credential::SealError | enum | A match needs a _ arm. |
guards::Ceiling | enum | A match needs a _ arm. |
guards::Refusal | enum | A match needs a _ arm. |
jwt::TokenKind | enum | A match needs a _ arm. |
jwt::JwtError | enum | A match needs a _ arm. |
tls::TlsMode | enum | A match needs a _ arm. |
Other structs with public fields, such as ServiceContext, HttpSettings, OAuthSettings, ToolPolicy and jwt::Payload, are built with struct literals, as on this page. A new field in one of them is a breaking change, so it comes only in a minor version. Payload implements Default: build it with ..Default::default(), as the crate’s own code does.
API documentation
docs.rs builds the API documentation with every feature on:
- mcp_server_core on docs.rs, the latest release;
https://docs.rs/mcp-server-core/<version>/mcp_server_core/for a given release, such as 0.1.0.
Run cargo doc --open --all-features in the repository for the documentation of the code you have checked out.
Changelog
All notable changes to this crate are documented here. The format follows Keep a Changelog, and the crate follows Semantic Versioning (before 1.0, a minor version may change the API).
[Unreleased]
0.4.0 - 2026-11-09
Added
- The policy wrapper forwards rmcp 3.9’s Skills extension (SEP-2640):
skills/list,skills/getandresources/directory/readreach a service’s handler. Without the forwards a service that declared skills would have answered “method not found”.
Changed
- Breaking: the re-exported
rmcpmoves from 3.8 to 3.9 (~3.9.0). Servers that namermcptypes directly, or pin their ownrmcp, should move it to 3.9 as well.
Security
- rmcp 3.9.0 fixes RUSTSEC-2026-0462 (unbounded response body buffering in Streamable HTTP
clients). This crate enables only rmcp’s server features, so it was not affected, but
cargo deny checkreports the advisory for any lockfile with rmcp 3.8. Moving to 0.4 lets your servers take rmcp 3.9 and drop any ignore added for it.
0.3.0 - 2026-10-29
Changed
- Breaking: the re-exported
rmcpmoves from 3.5 to 3.8 (~3.8.0).ServerHandleris unchanged, so the policy wrapper still forwards every method; servers that namermcptypes directly should move their ownrmcpdependency to 3.8 as well. - The lockfile takes tokio 1.54.1 and the latest compatible versions of other dependencies.
0.2.0 - 2026-10-28
Nothing changes for servers that already run on 0.1: their sign-in, tokens and configuration work as before, and nobody is signed out by upgrading.
Added
-
Sign-in through the upstream service’s own OAuth (
upstreammodule). A verifier whose newCredentialVerifier::upstreammethod returns anUpstreamSignIn, such as anUpstreamVerifier, turns the sign-in page into a consent page that continues to the provider; the provider sends people back toPUBLIC_URL/callback, the code is exchanged and the credential it grants is sealed into their tokens. The pending request is kept in an encrypted, browser-bound cookie, so nothing is stored.AuthState::callback_urlgives the redirect URI to register with the provider. A service cannot be namedcallbackon such a server. -
A documentation site, https://trozz.github.io/mcp-server-core-rs/, built with mdBook from
docs/and published frommain. Its Rust examples are compiled as doctests.
Security
- The lockfile takes rustls-webpki 0.103.16 and webpki-root-certs 1.0.11, which stop trusting
distrusted certificate intermediates (RUSTSEC-2026-0382, RUSTSEC-2026-0383). Run
cargo update -p rustls-webpki -p webpki-root-certsin your own servers too.
Fixed
- The README quick start and the examples import
mcp_server_core::rmcp. rmcp’s macros name the cratermcp, so a project that copied them without depending on rmcp directly did not compile. - Doc comments, the README and SECURITY.md now match the code where they had drifted.
- The CI
msrvjob checks on the minimum supported Rust version;rust-toolchain.tomlhad made it run on the pinned toolchain instead.
0.1.0 - 2026-10-18
The first release, extracted from the servers behind mcp-icloud and mcp-companies-house, which each carried a copy of this code.
Added
-
app::Server: a whole MCP server binary from a list of services, with--version,--helpand--healthcheck, service selection (<PREFIX>_SERVICES), the combined/mcpendpoint (<PREFIX>_COMBINED), read-only services (<PREFIX>_READ_ONLY) and the audit log (AUDIT_LOG_PATH). -
app::SignIn: sign in with the owner’s password (OAUTH_ADMIN_PASSWORD, optionallyMCP_AUTH_TOKEN), with each person’s own credential for the upstream service, or with your ownCredentialVerifier. -
An OAuth 2.1 authorization server with dynamic client registration, PKCE (S256), resource indicators and protected-resource metadata, every service its own protected resource.
-
Per-person credentials sealed into tokens (ChaCha20-Poly1305 under a key derived from
OAUTH_SIGNING_KEY), or sent directly as bearer tokens with cached verdicts. -
Abuse limits: per-address (IPv6 by /64) and global sign-in limits, shared and capped credential checks, MCP sessions bound to the person’s credential that opened them and capped per credential.
-
A read-only rule and write audit log for every service, from tools’
read_only_hint. -
TLS from files with hot reload, self-signed certificates or plain HTTP; graceful shutdown; JSON logs; Prometheus metrics (feature
prometheus); OpenTelemetry traces (featureotel). -
Configuration from environment variables with
_FILEvariants and every error reported at once. -
Service::routernow has a default that servesService::handler, so a service implements justnameandhandler. -
MCP prompts: each service’s prompts are offered on
/mcpas<service>_<prompt>, andprompt::tool_prefixlets a prompt name tools as the endpoint calls them (from mcp-icloud). -
caller::Calleron every authenticated request (who signed in and how), recorded in the audit log assubject, andServer::wrap_routerto add your own layers. -
Tokens carry who signed in (
sub), a keyed sign-in version (ver, from the sign-in mode, the verifier’s label and itsgeneration) and the sign-in time (auth_time): changing the owner’s password, the sign-in mode or the verifier ends every earlier grant, and a grant ends 90 days after sign-in however often it is refreshed; neither its access nor its refresh token outlives it. A person signing in with their own credential is namedkey:and a short hash keyed byOAUTH_SIGNING_KEY(AuthState::subject_of; a verifier can name them itself). -
Authorization responses carry
iss(RFC 9207). Client registration is capped (10 redirect URIs of up to 2048 bytes, a client name of up to 200 characters). Malformed/tokenand/registerrequests get OAuth JSON errors (400). Every response sendsX-Content-Type-Options: nosniff, and HSTS when the server serves certificate files. -
A limit per wider block (IPv4 /24, IPv6 /48) of 25 attempts a minute next to the per-address one, so one allocation cannot spread guesses over thousands of addresses. Attempts still being checked count towards both, never towards the global ceiling. Once the global ceiling is reached while 10,000 addresses are tracked, a new one is judged by its block, and refused as busy (503) only when blocks cannot be tracked either (from mcp-companies-house).
-
Fair session shares: when a path’s session table is full, idle and ended sessions are cleared first, then a newcomer takes a slot from whoever holds the most, so a few hundred credentials cannot lock everyone out. A refusal is decided before rmcp builds the session (from mcp-companies-house).
-
Prompts on
/mcpthat name a service’s tools get those names prefixed automatically, as well as throughprompt::tool_prefix(from mcp-companies-house).
Changed, compared with the copies in the two servers
-
Tokens issued before this version lack the new claims, so everyone signs in once more after upgrading.
-
On an owner’s-password server without a static token, bearer tokens that are not this server’s are refused without counting towards the sign-in limits, so they cannot lock the owner out. A static token is refused at startup next to a verifier that takes bearer credentials, or when shaped like a JWT, reported with the other configuration errors once the core settings load.
-
A credential that has the shape of a JWT but was not issued here is checked as a credential; this server’s own tokens, even expired, are never sent upstream.
-
More than one enabled service defining how people sign in is a startup error, as is an owner’s password of only spaces. A short password or static token is warned about.
-
X-Forwarded-Forentries with a port are understood, and IPv4-mapped IPv6 addresses (::ffff:10.0.0.1, as a dual-stack listener reports IPv4 peers) matchTRUSTED_PROXIESand share limits with the IPv4 address. -
Log caps (
Service::log_caps) never raise a target aboveLOG_LEVEL, and the audit target stays on atinfowhatever the level. -
SignIn,CredentialCheck,Ceiling,Refusal,TlsMode,TokenKind,JwtError,SealError,Caller,Viaandapp::Loadedare#[non_exhaustive], so later versions can add to them. -
Wrong static tokens count towards the sign-in limits, and a blocked address cannot use the static token until the limit clears, so
MCP_AUTH_TOKENcannot be guessed. This server’s own tokens, even expired, never count. -
The global sign-in ceiling depends on how people sign in: with the owner’s password it blocks everyone (as mcp-icloud did); with per-person credentials only addresses that failed themselves (as mcp-companies-house did). See
guards::Ceiling. -
Successful sign-in answers
303 See Other(RFC 9700), not302 Found. -
The owner’s password is compared exactly as typed; credentials for upstream services are trimmed.
-
Random token ids no longer need the
uuidcrate.
Planned
- Client ID Metadata Documents, which the MCP authorization spec now prefers to dynamic client registration.
Architecture
This page shows how the crate is put together: the layers a request passes through, what happens inside the server during a sign-in, which module is responsible for what, and the little state the server keeps in memory. It describes a server built with app::Server; Lower-level API shows how to assemble the same pieces yourself.
The request path
Every request passes through the layers below, from top to bottom. The response travels back up the same way, which is how the outer layers add headers to every response, refusals included.
flowchart TB
C["MCP client or browser"] --> L["Listener: tls::serve<br/>TLS or plain HTTP, peer address"]
L --> R{"Routing by path<br/>before any layer runs"}
R --> H["Security headers: app::Server<br/>nosniff, HSTS with certificate files"]
H --> W["Your wrap_router layers"]
W --> X["Your own routes<br/>and /favicon.ico"]
W --> N
subgraph B["server::build_app"]
direction TB
N["nosniff"] --> S["request span"]
S --> BL["Body limit, 1 MiB"]
BL --> M["http_requests_total"]
M --> HZ["GET /healthz"]
M --> OA["OAuth routes<br/>metadata, register, authorize, token"]
M --> NF["No route: 404"]
M --> G["Bearer guard<br/>one per path"]
end
G -->|"/notes"| TP["ToolPolicy extension"]
G -->|"/mcp"| SB
TP --> SB
subgraph MS["service::mcp_service, one per path"]
direction TB
SB["Session binding<br/>owner and caps"] --> RT["rmcp Streamable HTTP<br/>Host, Origin, body size, sessions"]
RT --> GD["policy::Guarded"]
end
GD -->|"/notes"| SH["Service handler<br/>your tools"]
GD -->|"/mcp"| CB["combined::Combined<br/>routes by name prefix"]
CB --> GP["policy::Guarded per service<br/>endpoint /mcp"]
GP --> SH
Layer by layer, in the order a request meets them:
| # | Layer | In the code | What it does | What it refuses |
|---|---|---|---|---|
| 1 | Listener | tls::serve | Accepts the connection over TLS (certificate files, checked for changes every 30 seconds, or a self-signed certificate) or plain HTTP, and hands every handler the peer address as ConnectInfo<SocketAddr>. On shutdown, gives open connections 10 seconds. | |
| 2 | Routing | axum::Router | Picks the route by path first: axum runs the middleware added with Router::layer after routing, on the route it chose. The routes are /healthz, the OAuth routes from oauth::oauth_router, each service path nested at /<name>, /favicon.ico when the server has an icon, and yours. A path with no route goes to axum’s fallback, which answers 404 through the same layers. | 404 |
| 3 | Security headers | Server::router, the last layer it adds | Adds X-Content-Type-Options: nosniff to every response, and Strict-Transport-Security: max-age=31536000 when serving certificate files. | |
| 4 | Your layers | Server::wrap_router | Whatever you add, such as a request rate limiter. Routes you add here, and /favicon.ico, are answered at this level and skip the layers of build_app below. | Whatever you refuse |
| 5 | nosniff | build_app, its outermost layer | Adds nosniff again, so an application built with build_app alone has it too, refusals from the layers below included. | |
| 6 | Request span | build_app, TraceLayer | Opens a request tracing span with the method and path. | |
| 7 | Body limit | build_app, RequestBodyLimitLayer | Refuses a request whose Content-Length is over BODY_LIMIT, 1 MiB, and cuts off a longer body as it is read. axum’s own default extractor limit is turned off on these routes, so this limit applies instead; rmcp reads its JSON with the same limit. | 413 |
| 8 | Request metrics | server::http_metrics | Counts every response that reaches it in http_requests_total, by matched route (unmatched for a path with no route) and status. | |
| 9 | Bearer guard | oauth::require_bearer, one per service path | Accepts an access token issued for this path whose grant still holds, the static token, or a person’s own credential sent directly. Adds Caller to the request, Claims for an OAuth token and Credential when credentials are carried. Counts wrong static tokens and rejected credentials towards the sign-in limits. /healthz and the OAuth routes have no bearer guard. | 401 with WWW-Authenticate; 429 or 503 from the limits |
| 10 | Tool policy | Server::router, axum::Extension | Attaches the service’s ToolPolicy (read-only or not, the audit log, the endpoint) to requests on its own path. /mcp has none: its policies are fixed per service in step 14. | |
| 11 | Session binding | mcp_service | Lets a request name an MCP session only with the credential that opened it, and caps sessions per credential and per path. | 404 Session not found; 503 when the table is full |
| 12 | MCP transport | rmcp’s StreamableHttpService, configured by mcp_service | Checks Host against the PUBLIC_URL host and loopback names and Origin against the PUBLIC_URL origin and ALLOWED_ORIGINS, limits each request body it reads to 1 MiB, and keeps the MCP sessions, building a handler for each with the service’s factory. | 403 for a bad Host or Origin |
| 13 | Policy wrapper | policy::Guarded | On a service path, reads the ToolPolicy from step 10: hides write tools on a read-only service, refuses calls to them, and writes an audit line for every call of a tool not marked read_only_hint = true. Without a policy it changes nothing. | A tool error read_only: ... |
| 14 | Combined endpoint | combined::Combined, on /mcp only | Lists every service’s tools and prompts as <service>_<name> and routes each call to its service by that prefix, through a Guarded with that service’s policy and the endpoint /mcp. | |
| 15 | Your handler | Service::handler | Your rmcp tools and prompts. The HTTP request parts in the request context carry the Caller, the Claims for an OAuth token and the Credential when credentials are carried; on /mcp, a forwarded prompts/get also carries the ToolPrefix. | Your tool errors |
Some consequences of this order:
- A request whose
Content-Lengthis over 1 MiB is refused with 413 before the bearer guard looks at it, so even an unauthenticated one gets 413 rather than 401. That 413 is answered outside the request metrics, so it is not counted inhttp_requests_total. - The bearer guard runs before the Host and Origin checks, so a request without a token gets 401 whatever its
Host. - Session binding runs before rmcp sees a session id, so a session opened by someone else looks exactly like one that does not exist.
- Routes added through
wrap_routerare not counted inhttp_requests_total, have norequestspan and get axum’s default body limit; Body limits shows how to limit them.
Endpoints lists every route with its responses, and Limits and abuse protection every refusal.
A sign-in, inside the server
OAuth and tokens follows a sign-in from the client’s side. Inside the server, the person’s POST /authorize and the client’s POST /token that follows go like this:
sequenceDiagram
participant B as Browser
participant A as POST /authorize
participant L as LoginLimiter
participant R as CheckRunner
participant V as CredentialVerifier
participant T as POST /token
participant G as ReplayGuard
B->>A: request parameters, csrf, credential
A->>L: is this address refused?
A->>A: validate the request, check the form's binding
A->>A: prepare, then plausible?
A->>R: join the check of SHA-256(credential)
alt a check of this credential is already running
R-->>A: follow it and share its verdict, uncounted
else this request leads
A->>L: reserve an attempt for the address and its block
R->>R: wait up to 5 s for one of 16 slots
R->>V: check(credential), at most 15 s
V-->>R: Valid, Invalid or Unavailable
R-->>A: verdict, also sent to followers
A->>L: keep the attempt if Invalid, give it back otherwise
end
A->>A: seal the credential if carried, sign a code (60 s)
A-->>B: 303 to redirect_uri with code, state and iss
Note over B,T: the client exchanges the code
T->>T: verify code, client, PKCE, resource, ver and auth_time
T->>G: first use of this code's jti?
G-->>T: yes
T->>T: sign access (1 h) and refresh (30 d) tokens, never past 90 days from sign-in
What the diagram compresses:
- Nothing is stored. The client’s registration, the form’s CSRF token, the code and both tokens are JWTs signed with
OAUTH_SIGNING_KEY. The code carries the client id, the redirect URI, the PKCE challenge, the resource, the sign-in version (ver), the sign-in time (auth_time) and, for a personal credential, the credential sealed with ChaCha20-Poly1305. Apart from the memory of used codes, the token endpoint needs nothing but the request: the code, the client id, the redirect URI and the PKCE verifier. - Refusals end it early. An address the limiter refuses gets a 429 page, or 503 while the server is refusing new addresses, before any check. A rejected credential shows the form again with 401, and a check that could not run shows it with 503; neither issues a code.
- The check runs in a task of its own, so the attempt is settled (kept as a failure, or given back) and followers get the verdict even if the browser goes away mid-check.
- Only a lead calls upstream. Requests that arrive while the same credential is being checked follow that check and are not counted again, so a client cannot multiply upstream calls by sending the same credential many times.
- A password is never carried. With the owner’s password, the code carries no credential, and tools act with the server’s own upstream configuration.
The same checks guard a credential sent directly as a bearer token, in step 9 of the request path, with a verdict cache in front. Sign-in modes describes the verifiers, and Limits and abuse protection what is counted.
Module responsibilities
An arrow points from a module to one whose items it uses:
flowchart LR
app --> server
app --> service
app --> combined
app --> policy
app --> oauth
app --> credential
app --> config
app --> tls
app --> observability
server --> oauth
service --> server
service --> combined
service --> policy
service --> credential
service --> config
combined --> prompt
config --> oauth
config --> tls
config --> observability
observability --> service
oauth --> combined
oauth --> credential
oauth --> guards
oauth --> jwt
oauth --> pkce
oauth --> caller
policy --> caller
policy --> credential
policy --> jwt
credential --> pkce
guards --> jwt
| Area | Modules | Responsible for |
|---|---|---|
| Building a binary | app | Command-line flags, reading and checking the whole configuration, choosing services and the sign-in verifier, assembling the application, logging startup, serving until shutdown. |
| The HTTP application | server | /healthz, merging the OAuth routes, nesting each service behind its bearer guard, the body limit, request metrics, the request span and nosniff. |
| Hosting MCP | service, combined, prompt | The Service trait; the hardened Streamable HTTP transport with Host and Origin checks and session binding; the combined /mcp endpoint that prefixes and routes names; helpers for prompts that name tools. |
| Signing people in | oauth, credential, jwt, pkce, caller | The authorization server’s routes and the bearer guard; verifiers, sealed credentials and the shared, capped credential checks; issuing and verifying tokens; PKCE and constant-time comparison; who made each request. |
| Abuse limits | guards | Sign-in attempts per address, per block and overall, and the one-time use of codes. |
| Read-only mode and audit | policy | Hiding and refusing write tools, and recording every write call. |
| Running | config, tls, observability | Environment variables and their errors; listening, certificates and the healthcheck; logs, metrics and traces. |
Services never depend on each other. Anything that combines them, such as /mcp, lives in this crate and works from each service’s name and handler alone. Lower-level API lists every public item by module.
State in memory
The server keeps no database and writes nothing to disk except the audit file. What it does keep lives in memory, per process:
| State | Where | Holds | Bounds | After a restart |
|---|---|---|---|---|
| Sign-in limits | AuthState, a guards::LoginLimiter | Attempts in the last 60 seconds per address (IPv4 address, IPv6 /64) and per block (IPv4 /24, IPv6 /48), and the times of recent rejections for the global ceiling | 10,000 addresses and 10,000 blocks; old entries swept at most once a second | Counting starts again |
| Used codes | AuthState, a guards::ReplayGuard | The jti of every authorization code exchanged, with its expiry | Each until it expires, plus the 5-second leeway; codes live 60 seconds | A code from before the restart could be exchanged once more within its 60 seconds, still needing the client’s PKCE verifier |
| Verdict cache | AuthState | The SHA-256 of each credential sent as a bearer token, and whether it was accepted | 10,000 entries; accepted ones for 600 seconds, rejected ones for 60 | Credentials are checked upstream again |
| Running checks | AuthState | The checks in flight, by SHA-256 of the credential, and 16 slots | Only while a check runs | Nothing is lost |
| Session tables | One per path, in mcp_service | Each MCP session’s id, the SHA-256 of the credential that opened it and when it was last used | 10,000 sessions per path and, when credentials are carried, 50 per credential; entries idle for 360 seconds swept | Clients get 404 and open a new session |
| MCP sessions | One rmcp session manager per path | The live sessions, each with its own handler built by the service’s factory | Ended by rmcp after 300 seconds idle, or by session binding | As above |
| Audit file | policy::AuditLog | The open file, and when a failed write last warned | One handle | Reopened on the next write |
| Certificate | tls::serve | The current certificate and key | Reloaded when the files change | Read from the files again |
| Your services | Your handlers | Whatever your services keep, such as the notes in the notes example | Up to you | Up to you |
Apart from the used codes, nothing in this table is needed to accept a token. Every token is a JWT, signed with HS256 under OAUTH_SIGNING_KEY, and carries what the server needs to accept it: its kind, audience, expiry, client, resource, sign-in version and sign-in time, and the sealed credential. Whether a grant still holds is computed from those claims and the current configuration, never looked up. That is why:
- a restart signs nobody out, and any replica with the same configuration accepts any other replica’s tokens;
- there is nothing to back up, migrate or share between replicas except the configuration;
- the server cannot revoke one person or client, or notice a refresh token used twice. What statelessness means explains the trade-off, and Replicas what each replica keeps on its own.
Design choices
- One key for everything.
OAUTH_SIGNING_KEYsigns every token, derives the key that seals credentials (HKDF-SHA256), keys the hash behindkey:subjects, and the sign-in version. Rotating it ends every grant and every registration at once. - Grants end by changing their inputs. The sign-in version is a keyed hash of the sign-in mode, the verifier’s label and its generation, such as a hash of the owner’s password. Changing any of them ends every earlier grant without a list of grants to revoke.
- The limits fit the secret. When credentials are not carried, as with the owner’s password and the static token beside it, one shared secret guards everything, and reaching the global ceiling blocks everyone, so guessing from many addresses gains nothing. When they are carried, as with per-person credentials, it blocks only addresses that failed themselves, so one attacker cannot lock other people out. The global ceiling has the details.
- Refuse cheaply, before anything costly. Implausible credentials are refused before any upstream call, a session table that is full and was swept moments ago refuses before rmcp builds a session, and this server’s own tokens, even expired ones, are never sent upstream or counted as guesses.
- Every secret compared in constant time.
pkce::ct_eqcompares the SHA-256 digests of both sides, so neither content nor length leaks through timing. - rmcp does MCP. The crate wraps rmcp’s handler and transport instead of reimplementing them. The policy wrapper forwards every
ServerHandlermethod, which is why the crate pins rmcp to one minor version; see Releases and versioning. - Configuration fails whole. Every variable is read and every problem reported in one run, and the server does not start until there are none.
Contributing
Bug reports, questions and pull requests are all welcome. This page explains how to report a problem, set up the repository, run the checks CI runs, try a change against a real client, build this site and send a pull request. The repository’s CONTRIBUTING.md is the short version.
Reporting problems
- Security problems: do not open an issue. Report them privately, as described under Reporting a vulnerability.
- Bugs: open an issue with what you did, what you expected and what happened, the crate and Rust versions, and logs with secrets removed.
- Ideas: open an issue before a large change, so the shape can be agreed first.
Setting up
git clone https://github.com/Trozz/mcp-server-core-rs
cd mcp-server-core-rs
cargo test --all-features
The toolchain is pinned in rust-toolchain.toml to Rust 1.99.1 with rustfmt and clippy; rustup installs it the first time you run cargo in the repository. The crate itself supports Rust 1.88 and later; see Minimum supported Rust version.
You also need:
openssl, or another source of random bytes, to make a signing key when running the examples;- cargo-deny for
cargo deny check(cargo install --locked cargo-deny); - the documentation tools, only to build this site; see Building this site.
Checks
Run these before opening a pull request:
cargo fmt --all
cargo clippy --all-targets --all-features -- -D warnings
cargo clippy --all-targets --no-default-features -- -D warnings
cargo test --all-features
RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --all-features
cargo deny check
cargo test --all-features runs the unit tests, the integration tests in tests/ and every doctest: the examples in the API documentation, the README and this site.
What CI runs
The ci workflow (.github/workflows/ci.yml) runs on every pull request and every push to main. A newer push to the same pull request cancels the run in progress.
| Job | Runs on | Command |
|---|---|---|
fmt | Ubuntu 24.04 | cargo fmt --all --check |
clippy (--all-features), clippy (--no-default-features) | Ubuntu 24.04 | cargo clippy --all-targets --locked <features> -- -D warnings |
test (ubuntu-24.04), test (macos-15) | Ubuntu 24.04 and macOS 15 | cargo test --all-features --locked |
build (windows) | Windows Server 2025 | cargo build --all-targets --all-features --locked |
msrv | Ubuntu 24.04 | Installs the Rust version in rust-version, then cargo check --lib --locked on it (RUSTUP_TOOLCHAIN) with every feature and with none |
docs | Ubuntu 24.04 | cargo doc --no-deps --all-features --locked with RUSTDOCFLAGS=-D warnings |
book | Ubuntu 24.04 | scripts/install-docs-tools.sh, then scripts/build-docs.sh |
cargo-deny | Ubuntu 24.04 | cargo deny check |
package | Ubuntu 24.04 | cargo package --locked |
The other jobs that compile the crate install the pinned Rust 1.99.1. Inside the repository rust-toolchain.toml takes precedence over rustup’s default toolchain, so the msrv job names its toolchain with RUSTUP_TOOLCHAIN; to check the library on the minimum supported version yourself, name the toolchain, as Minimum supported Rust version shows. --locked means Cargo.lock must be up to date: commit it with any dependency change.
Lints
Cargo.toml sets the crate’s lints, and -D warnings turns every warning into an error in CI:
| Lint | Level | Effect |
|---|---|---|
unsafe_code | forbid | No unsafe anywhere. |
missing_docs | warn | Every public item needs a doc comment. |
clippy::dbg_macro | warn | No dbg! left behind. |
clippy::todo | warn | No todo! left behind. |
unexpected_cfgs | warn | Only known cfg names; docsrs, which docs.rs sets, is declared. |
cargo-deny
deny.toml checks every dependency, with all features on:
- Advisories: known vulnerabilities and yanked crates fail the check. One advisory is ignored,
RUSTSEC-2023-0071inrsa, whichjsonwebtokenpulls in although only HS256 is used, with the reason written next to it. - Licences: only MIT, Apache-2.0 (also with the LLVM exception), BSD-2-Clause, BSD-3-Clause, ISC, Unicode-3.0, Zlib, CDLA-Permissive-2.0, 0BSD and MPL-2.0.
- Bans:
openssl,openssl-sys,native-tls,aws-lc-rsandaws-lc-sys. TLS is rustls with theringprovider throughout. - Sources: crates.io only; no git dependencies.
Tests
Unit tests sit next to the code in src/. The integration tests in tests/ drive the HTTP application in memory, without a network, except for TLS:
| File | Covers |
|---|---|
abuse_limits.rs | Limits on bearer credentials: per-address, per-block and global failure limits, shared checks |
app_e2e.rs | A whole server built with app::Server from environment variables, as main would build it |
docs_consistency.rs | The configuration reference against the variables the server reads |
hardening.rs | Grants ending when the sign-in changes or grows old, tokens not crossing sign-in modes, registration caps, the issuer and security headers |
oauth_authorize.rs | The sign-in page and POST /authorize, for both kinds of sign-in |
oauth_flow.rs | The bearer guard in front of services, and the whole OAuth flow end to end |
oauth_metadata.rs | Authorization-server and protected-resource metadata, and client registration |
oauth_token.rs | The token endpoint: code exchange and refresh |
prompts_e2e.rs | Prompts on a service’s own endpoint and on the combined endpoint |
service_mount.rs | Host and Origin checks of a mounted MCP service |
session_binding.rs | MCP sessions bound to the credential that opened them |
tls_serve.rs | Serving over TLS and plain HTTP, and the healthcheck |
tool_policy.rs | The read-only rule and the audit log, through the same HTTP stack the binary serves |
tests/oauth_support/mod.rs holds what the OAuth tests share: a TestVerifier that accepts listed credentials and counts its checks, and constants such as the public URL, password and keys. Run one file with cargo test --all-features --test oauth_flow.
Running the examples
To try a change against a real MCP client, run an example. The owner’s-password server:
PUBLIC_URL=http://localhost:8443 INSECURE_HTTP=true \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) OAUTH_ADMIN_PASSWORD='a long password' \
LOG_FORMAT=pretty cargo run --example notes
The server where each person signs in with their own key:
PUBLIC_URL=http://localhost:8443 INSECURE_HTTP=true \
OAUTH_SIGNING_KEY=$(openssl rand -hex 32) LOG_FORMAT=pretty \
cargo run --example api_keys
Then connect a client, or npx @modelcontextprotocol/inspector, to http://localhost:8443/notes or http://localhost:8443/account. Examples describes what each shows and what to try.
Building this site
The site is an mdBook in docs/:
| Path | Holds |
|---|---|
docs/book.toml | The book’s settings, including the mdbook-mermaid preprocessor. create-missing = false, so every page listed in the summary must exist. |
docs/src/SUMMARY.md | The table of contents: every page, in order. |
docs/src/*.md | The pages. |
docs/theme/ | The favicon. |
docs/book/ | The built site (not committed). |
Tools
The tools are pinned: mdBook 0.5.4, mdbook-mermaid 0.17.1 and lychee 0.24.2. On Linux x86_64, as CI does, install them into a directory on your PATH; the script downloads the release archives and checks their SHA-256 sums:
bash scripts/install-docs-tools.sh "$HOME/.local/bin"
On other platforms, build them with Cargo:
cargo install --locked mdbook@0.5.4 mdbook-mermaid@0.17.1 lychee@0.24.2
Building and previewing
bash scripts/build-docs.sh
mdbook serve docs --open
scripts/build-docs.sh installs mdbook-mermaid’s scripts into docs/ (mermaid.min.js and mermaid-init.js, which are not committed), builds the site into docs/book, then runs lychee offline over the built pages to check every internal link and anchor. External links are not checked. Run it before mdbook serve the first time, so the diagrams render.
Rust examples are tests
Every page is compiled as rustdoc doctests. src/lib.rs includes each page under #[cfg(doctest)] in a module book, one struct per page named after its file in CamelCase:
#[cfg(doctest)]
mod book {
#[doc = include_str!("../docs/src/quick-start.md")]
struct QuickStart;
// ... one struct for every page
}
cargo test --all-features runs them with the other tests. To check one page while you edit it:
cargo test --doc --all-features book::QuickStart
So that pages read well in mdBook and still compile:
- Give every fenced code block a language:
rust,sh,toml,json,yaml,nginx,dockerfile,http,textormermaid. rustdoc treats a block without one as Rust and fails on it. - Never indent code by four spaces to make a code block: rustdoc compiles those too.
- Use
rust,no_runfor code that would start a server or reach the network: it is compiled but not run. - Hide setup with lines starting
#. mdBook hides them from readers, and rustdoc still compiles them. - Use
rust,ignoreonly for a deliberate fragment that cannot compile on its own, as above. - Adapt code that already compiles, from the README, the API documentation or
examples/, where you can.
Adding a page
- Create
docs/src/<name>.md, starting with#and its title. - List it in
docs/src/SUMMARY.md. - Add a struct for it to
mod bookinsrc/lib.rs, so its examples are tested.
A new environment variable belongs in the configuration reference. tests/docs_consistency.rs records every variable Server::load reads and fails until the reference has a table row for it, with its name in backticks in the first column (prefixed ones written as <PREFIX>_SERVICES and so on). It fails too if the reference names a variable the server does not read.
Cargo.toml lists docs/src/**/*.md under include, so the pages ship in the crate package with src/lib.rs, which includes them.
Writing style
The site is written in British English, in the present tense and the second person, in short sentences. Each topic has one page; other pages link to it rather than repeat it. Numbers, defaults, variable names and error messages are copied from the code, and an error message is quoted exactly.
Guidelines
- Keep the public API small and documented. Every public item needs a doc comment, and examples in the API documentation, the README and this site are compiled as tests.
- Security-relevant behaviour (sign-in, tokens, limits, logging) needs a test that would fail without the change.
- Never log secrets, credentials, session ids or content. Content may be logged only when
observability::content_logging_enabled()is true. - No
unsafecode. - Add an entry to
CHANGELOG.mdunder## [Unreleased]. - Write commit messages in the Conventional Commits style, such as
fix: count wrong static tokens towards the sign-in limit.
Pull requests
Open pull requests against main. CI must pass. Releases are tagged from main, as Releases and versioning describes.
Licence
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 licence, shall be dual licensed under the MIT and Apache-2.0 licences, without any additional terms or conditions.
Releases and versioning
This page explains what the crate’s version numbers promise, which Rust versions it supports, how a release is made and published, how this site is published, and which versions receive fixes. What changed in each version is in the changelog.
Versioning
mcp-server-core follows Semantic Versioning, and its changelog follows Keep a Changelog.
| Version change | Before 1.0 | Example |
|---|---|---|
| Minor | May change the API | 0.1.0 to 0.2.0 |
| Patch | Does not change the API in a way that breaks your code | 0.1.0 to 0.1.1 |
From 1.0, only a major version may break the API. Until then, depend on a minor version and read the changelog before moving to the next:
[dependencies]
mcp-server-core = "0.4"
Cargo reads "0.4" as >=0.4.0, <0.5.0: you get patch releases with cargo update, and never a new minor version without changing the requirement.
An upgrade can affect a running server as well as your code. The 0.1.0 entry, for example, says that tokens issued by the servers’ earlier copies of this code lack the new claims, so everyone signs in once more after upgrading. Read the Changed section before upgrading a deployed server.
Lower-level API lists the #[non_exhaustive] types, which later versions can extend without a breaking change.
rmcp and axum
The crate’s API includes types from rmcp and axum, re-exported as mcp_server_core::rmcp and mcp_server_core::axum. Their versions are part of this crate’s compatibility:
| Dependency | Requirement in Cargo.toml | Accepts |
|---|---|---|
| rmcp | ~3.9.0 | 3.9.0 and later 3.9 patch releases, never 3.10 |
| axum | 0.8.9 | 0.8.9 and later 0.8 releases, never 0.9 |
rmcp is held to one minor version on purpose. The policy wrapper forwards every method of rmcp’s ServerHandler trait to your handler, so a new rmcp minor version, which may add or change methods, needs a release of this crate that forwards them too. This crate therefore follows rmcp’s minor versions: moving to a new one is a new minor version here. Use rmcp through the re-export rather than adding it to your own Cargo.toml, so the versions always match.
Minimum supported Rust version
The minimum supported Rust version (MSRV) is 1.88, set as rust-version in Cargo.toml. The crate uses the 2024 edition, which needs Rust 1.85, and let chains (if let ... && let ...), which need Rust 1.88.
The msrv CI job runs on every pull request and every push to main. It reads rust-version from Cargo.toml, installs that toolchain and runs, with RUSTUP_TOOLCHAIN set to it:
cargo check --lib --all-features --locked
cargo check --lib --no-default-features --locked
Inside the repository, rust-toolchain.toml pins Rust 1.99.1 and takes precedence over rustup’s default toolchain, which is why the job sets RUSTUP_TOOLCHAIN. To check the library on the minimum supported version yourself, name the toolchain, which also takes precedence over the file:
rustup toolchain install 1.88
cargo +1.88 check --lib --all-features --locked
cargo +1.88 check --lib --no-default-features --locked
Only the library is meant to build at the MSRV. Tests, examples and the development tools use the toolchain pinned in rust-toolchain.toml, currently Rust 1.99.1, which rustup installs when you build in the repository.
Supported versions
Until 1.0, only the latest minor version receives security fixes. Fixes are released as patch versions and announced in a GitHub security advisory once a fixed version is available.
| Version | Supported |
|---|---|
| 0.4.x | Yes |
To report a vulnerability, see Security model.
The release process
A release is a version bump merged to main. The steps, from the repository’s CONTRIBUTING.md:
- Move the entries under
## [Unreleased]inCHANGELOG.mdto a new heading## [X.Y.Z] - YYYY-MM-DDwith today’s date (and, as for[0.1.0], a link for it at the bottom), and setversioninCargo.tomltoX.Y.Z. - Merge the change to
main. The release workflow tags the merge commitvX.Y.Zand releases it.
Pushing a vX.Y.Z tag by hand also starts a release, for example to release a commit other than the head of main:
git tag v0.1.1
git push origin v0.1.1
What the release workflow does
The release workflow (.github/workflows/release.yml) starts on a push to main that changes Cargo.toml, on a pushed tag that matches v*.*.*, and by hand from the Actions tab (Run workflow on main), for example to retry a failed release. On Ubuntu with Rust 1.99.1, it:
| Step | What happens | Fails with |
|---|---|---|
| Version to release | The tag is v followed by version from Cargo.toml. On main, when the GitHub release and the crates.io version both exist, the workflow stops here: <tag> is already released: nothing to do. On a pushed tag, the tag must match. | tag <tag> does not match Cargo.toml version <version>, or releases run only from main or a tag for a manual run on another branch |
| Tests | cargo test --all-features --locked. | Any failing test |
| Release notes | Takes the section of CHANGELOG.md under ## [X.Y.Z], up to the next ## [ heading or the link definitions at the bottom. | no CHANGELOG.md section for <tag> when the section is missing or empty |
| GitHub release | gh release create titled with the tag, with those notes. On a push to main this also creates the tag on the merge commit. When a release for the tag already exists, for example on a re-run, it says so and goes on. | A gh error |
| crates.io | Gets a short-lived token through trusted publishing (rust-lang/crates-io-auth-action), then cargo publish --locked. | An auth error when the crate has no trusted publisher for this workflow |
The crates.io steps skip themselves when crates.io already has the version (X.Y.Z is already on crates.io: skipping). If the workflow fails after the GitHub release was created, re-run it: the release step and, once the version is on crates.io, the publish step both skip what is already done.
The package contains src/, examples/, the pages of this site, the README, changelog, security policy and both licences, as listed under include in Cargo.toml. CI runs cargo package --locked on every pull request and push to main, so a packaging problem shows up before a release is tagged.
After publishing
docs.rs builds the API documentation for the new version by itself, with every feature on ([package.metadata.docs.rs] in Cargo.toml). Each version stays available at https://docs.rs/mcp-server-core/<version>/.
This site
This site is built from docs/ with mdBook and published to GitHub Pages at https://trozz.github.io/mcp-server-core-rs/ by the docs workflow (.github/workflows/docs.yml):
- It runs on every push to
main, and can be started by hand; it builds only frommain. - It installs the pinned tools with
scripts/install-docs-tools.sh, builds withscripts/build-docs.sh, which also checks every internal link and anchor, and deploysdocs/bookto thegithub-pagesenvironment. - A run in progress is never cancelled: a newer push waits for it, and GitHub keeps only the newest waiting run, so the last push to
mainis the one published.
The site therefore describes main, which can be ahead of the latest release on crates.io. For the exact API of the version you depend on, use its docs.rs page. Contributing explains how to build the site locally.
Repository setup (maintainers)
- crates.io: in the crate’s settings on crates.io, add a trusted publisher for GitHub with owner
Trozz, repositorymcp-server-core-rsand workflowrelease.yml. No token secret is needed. - Workflow permissions: every workflow defaults to
contents: read. The release job requestscontents: writeto create the tag and GitHub release,id-token: writefor trusted publishing, and the docs deploy jobpages: writeandid-token: write. - GitHub Pages: under Settings > Pages, the source must be GitHub Actions for the docs workflow to publish.