use std::sync::Arc;
use axum::extract::{Request, State};
use axum::http::{StatusCode, header};
use axum::middleware::Next;
use axum::response::{IntoResponse, Response};
use rmcp::ServiceExt;
use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
use crate::McpServer;
use crate::server::{BuildError, Handler};
pub const MCP_PATH: &str = "/mcp";
pub type ServeError = Box<dyn std::error::Error + Send + Sync>;
pub const DEFAULT_MAX_REQUEST_BYTES: usize = 4 * 1024 * 1024;
impl McpServer {
#[must_use]
pub fn max_request_bytes(mut self, bytes: usize) -> Self {
self.max_request_bytes = bytes;
self
}
#[must_use]
pub fn bearer_token(mut self, token: impl Into<String>) -> Self {
self.bearer = Some(token.into());
self
}
#[must_use]
pub fn allowed_hosts(mut self, hosts: impl IntoIterator<Item = impl Into<String>>) -> Self {
self.allowed_hosts = Some(hosts.into_iter().map(Into::into).collect());
self
}
pub async fn serve_stdio(self) -> Result<(), ServeError> {
let running = Handler::new(self)?.serve(rmcp::transport::stdio()).await?;
running.waiting().await?;
Ok(())
}
pub async fn serve<T, E, A>(self, transport: T) -> Result<(), ServeError>
where
T: rmcp::transport::IntoTransport<rmcp::RoleServer, E, A>,
E: std::error::Error + Send + Sync + 'static,
{
let running = Handler::new(self)?.serve(transport).await?;
running.waiting().await?;
Ok(())
}
pub fn into_router(self) -> Result<axum::Router, BuildError> {
let expected: Option<Arc<str>> = self
.bearer
.as_ref()
.map(|token| format!("Bearer {token}").into());
let mut config = StreamableHttpServerConfig::default()
.with_max_request_body_bytes(self.max_request_bytes);
if let Some(hosts) = self.allowed_hosts.clone() {
config = config.with_allowed_hosts(hosts);
}
let handler = Handler::new(self)?;
let service = StreamableHttpService::new(
move || Ok(handler.clone()),
Arc::new(LocalSessionManager::default()),
config,
);
Ok(axum::Router::new()
.nest_service(MCP_PATH, service)
.layer(axum::middleware::from_fn_with_state(expected, guard)))
}
}
async fn guard(State(expected): State<Option<Arc<str>>>, request: Request, next: Next) -> Response {
let given = request
.headers()
.get(header::AUTHORIZATION)
.and_then(|value| value.to_str().ok());
match (expected.as_deref(), given) {
(None, _) => next.run(request).await,
(Some(expected), Some(given)) if same(expected, given) => next.run(request).await,
_ => (
StatusCode::UNAUTHORIZED,
[(header::WWW_AUTHENTICATE, "Bearer")],
)
.into_response(),
}
}
fn same(a: &str, b: &str) -> bool {
a.len() == b.len()
&& a.bytes()
.zip(b.bytes())
.fold(0, |acc, (x, y)| acc | (x ^ y))
== 0
}