Skip to main content

rig_mcp_server/
transport.rs

1//! Serving an [`McpServer`] over stdio or Streamable HTTP.
2
3use std::sync::Arc;
4
5use axum::extract::{Request, State};
6use axum::http::{StatusCode, header};
7use axum::middleware::Next;
8use axum::response::{IntoResponse, Response};
9use axum::routing::get;
10use rmcp::ServiceExt;
11use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
12use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
13
14use crate::McpServer;
15use crate::server::{BuildError, Handler};
16
17/// Where the Streamable HTTP endpoint is mounted by [`McpServer::into_router`].
18pub const MCP_PATH: &str = "/mcp";
19
20/// The health route [`McpServer::ping_route`] serves.
21const PING_PATH: &str = "/ping";
22
23/// Why a server stopped serving.
24pub type ServeError = Box<dyn std::error::Error + Send + Sync>;
25
26/// The largest HTTP request body by default, in bytes: the limit the MCP SDK
27/// already applied (4 MiB). A larger POST gets 413 Payload Too Large.
28pub const DEFAULT_MAX_REQUEST_BYTES: usize = 4 * 1024 * 1024;
29
30impl McpServer {
31    /// Refuse HTTP request bodies over `bytes` with 413 Payload Too Large,
32    /// before they are parsed. Defaults to [`DEFAULT_MAX_REQUEST_BYTES`].
33    /// HTTP only: over stdio there is no request body to limit.
34    #[must_use]
35    pub fn max_request_bytes(mut self, bytes: usize) -> Self {
36        self.max_request_bytes = bytes;
37        self
38    }
39
40    /// Require `Authorization: Bearer <token>` on the HTTP endpoint; calls
41    /// without it get HTTP 401. (Over stdio the client launched the server
42    /// itself, so there is nothing to check.)
43    #[must_use]
44    pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
45        self.bearer = Some(token.into());
46        self
47    }
48
49    /// Host names the HTTP endpoint answers to. Defaults to `localhost`,
50    /// `127.0.0.1` and `::1` only, which protects a local server from DNS
51    /// rebinding; set the public host name when deploying behind one.
52    #[must_use]
53    pub fn allowed_hosts(mut self, hosts: impl IntoIterator<Item = impl Into<String>>) -> Self {
54        self.allowed_hosts = Some(hosts.into_iter().map(Into::into).collect());
55        self
56    }
57
58    /// Serve over stdin and stdout until the client disconnects: what a
59    /// local MCP client (Claude Code, Cursor, Zed) expects of a server it
60    /// launches. Stdout carries the protocol, so log to stderr only.
61    ///
62    /// # Errors
63    ///
64    /// A [`BuildError`] when two tools, resources or prompts clash, or the transport's error.
65    pub async fn serve_stdio(self) -> Result<(), ServeError> {
66        let running = Handler::new(self)?.serve(rmcp::transport::stdio()).await?;
67        running.waiting().await?;
68        Ok(())
69    }
70
71    /// Serve over any MCP transport (an in-memory duplex, a socket, a custom
72    /// one) until the client disconnects.
73    ///
74    /// # Errors
75    ///
76    /// A [`BuildError`] when two tools, resources or prompts clash, or the transport's error.
77    pub async fn serve<T, E, A>(self, transport: T) -> Result<(), ServeError>
78    where
79        T: rmcp::transport::IntoTransport<rmcp::RoleServer, E, A>,
80        E: std::error::Error + Send + Sync + 'static,
81    {
82        let running = Handler::new(self)?.serve(transport).await?;
83        running.waiting().await?;
84        Ok(())
85    }
86
87    /// The Streamable HTTP endpoint at [`MCP_PATH`], as an Axum router.
88    ///
89    /// # Errors
90    ///
91    /// [`BuildError::DuplicateTool`] when two tools share a name,
92    /// [`BuildError::DuplicateResource`] when two resources share a URI, or
93    /// [`BuildError::DuplicatePrompt`] when two prompts share a name.
94    pub fn into_router(self) -> Result<axum::Router, BuildError> {
95        let expected: Option<Arc<str>> = self
96            .bearer
97            .as_ref()
98            .map(|token| format!("Bearer {token}").into());
99        let mut config = StreamableHttpServerConfig::default()
100            .with_max_request_body_bytes(self.max_request_bytes);
101        if let Some(hosts) = self.allowed_hosts.clone() {
102            config = config.with_allowed_hosts(hosts);
103        }
104        let ping = self.ping;
105        let handler = Handler::new(self)?;
106        let service = StreamableHttpService::new(
107            move || Ok(handler.clone()),
108            Arc::new(LocalSessionManager::default()),
109            config,
110        );
111        let router = axum::Router::new()
112            .nest_service(MCP_PATH, service)
113            .layer(axum::middleware::from_fn_with_state(expected, guard));
114        // Added after the layer, so the bearer guard does not cover it.
115        Ok(if ping {
116            router.route(PING_PATH, get(ping_handler))
117        } else {
118            router
119        })
120    }
121}
122
123/// Answers `GET /ping` for AgentCore Runtime's health probe. See
124/// [`McpServer::ping_route`].
125async fn ping_handler() -> axum::Json<serde_json::Value> {
126    axum::Json(serde_json::json!({"status": "Healthy"}))
127}
128
129/// Answers 401 to a request without the expected `Authorization` header, or
130/// passes every request when no token is set.
131async fn guard(State(expected): State<Option<Arc<str>>>, request: Request, next: Next) -> Response {
132    let given = request
133        .headers()
134        .get(header::AUTHORIZATION)
135        .and_then(|value| value.to_str().ok());
136    match (expected.as_deref(), given) {
137        (None, _) => next.run(request).await,
138        (Some(expected), Some(given)) if same(expected, given) => next.run(request).await,
139        _ => (
140            StatusCode::UNAUTHORIZED,
141            [(header::WWW_AUTHENTICATE, "Bearer")],
142        )
143            .into_response(),
144    }
145}
146
147/// Compares in time independent of where the strings differ.
148fn same(a: &str, b: &str) -> bool {
149    a.len() == b.len()
150        && a.bytes()
151            .zip(b.bytes())
152            .fold(0, |acc, (x, y)| acc | (x ^ y))
153            == 0
154}