1use std::net::SocketAddr;
6use std::sync::Arc;
7
8use axum::extract::{Request, State};
9use axum::http::{HeaderMap, StatusCode, Uri, header};
10use axum::middleware::{self, Next};
11use axum::response::{IntoResponse as _, Response};
12use rmcp::ServerHandler;
13use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
14use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
15use tokio::net::TcpListener;
16
17pub use axum::Router;
18
19pub type Verifier = Arc<dyn Fn(&str) -> bool + Send + Sync>;
21
22#[derive(Debug, thiserror::Error)]
24#[non_exhaustive]
25pub enum HttpError {
26 #[error("{0} is not a loopback address; the local daemon only listens on 127.0.0.1 or ::1")]
28 NotLoopback(SocketAddr),
29 #[error("could not use the HTTP socket: {0}")]
31 Io(#[from] std::io::Error),
32}
33
34pub fn check_loopback(addr: SocketAddr) -> Result<SocketAddr, HttpError> {
40 if addr.ip().is_loopback() {
41 Ok(addr)
42 } else {
43 Err(HttpError::NotLoopback(addr))
44 }
45}
46
47pub async fn bind_loopback(addr: SocketAddr) -> Result<TcpListener, HttpError> {
53 Ok(TcpListener::bind(check_loopback(addr)?).await?)
54}
55
56#[must_use]
59pub fn base_config() -> StreamableHttpServerConfig {
60 StreamableHttpServerConfig::default()
61 .with_legacy_session_mode(true)
62 .with_json_response(true)
63}
64
65pub fn mcp_service<S>(
67 factory: impl Fn() -> S + Send + Sync + 'static,
68 config: StreamableHttpServerConfig,
69) -> StreamableHttpService<S, LocalSessionManager>
70where
71 S: ServerHandler + Send + 'static,
72{
73 StreamableHttpService::new(move || Ok(factory()), Arc::default(), config)
74}
75
76pub fn local_router<S>(
82 service: StreamableHttpService<S, LocalSessionManager>,
83 verify: Verifier,
84) -> Router
85where
86 S: ServerHandler + Send + 'static,
87{
88 Router::new()
89 .nest_service("/mcp", service)
90 .layer(middleware::from_fn_with_state(verify, require_bearer))
91 .layer(middleware::from_fn(require_loopback_origin))
92}
93
94async fn require_loopback_origin(request: Request, next: Next) -> Response {
98 match request.headers().get(header::ORIGIN) {
99 None => next.run(request).await,
100 Some(origin) if origin.to_str().is_ok_and(is_loopback_origin) => next.run(request).await,
101 Some(_) => (StatusCode::FORBIDDEN, "Forbidden: Origin is not allowed").into_response(),
102 }
103}
104
105fn is_loopback_origin(origin: &str) -> bool {
106 let Ok(uri) = origin.parse::<Uri>() else {
107 return false;
108 };
109 let web = matches!(uri.scheme_str(), Some("http" | "https"));
110 let bare = uri.path_and_query().is_none_or(|path| path.as_str() == "/");
111 let host = uri.authority().is_some_and(|authority| {
112 !authority.as_str().contains('@')
114 && matches!(authority.host(), "localhost" | "127.0.0.1" | "[::1]")
115 });
116 web && bare && host
117}
118
119async fn require_bearer(State(verify): State<Verifier>, request: Request, next: Next) -> Response {
121 if bearer_token(request.headers()).is_some_and(|token| verify(token)) {
122 next.run(request).await
123 } else {
124 (
125 StatusCode::UNAUTHORIZED,
126 [(header::WWW_AUTHENTICATE, "Bearer")],
127 "Unauthorized",
128 )
129 .into_response()
130 }
131}
132
133fn bearer_token(headers: &HeaderMap) -> Option<&str> {
134 let value = headers.get(header::AUTHORIZATION)?.to_str().ok()?;
135 let (scheme, token) = value.split_once(' ')?;
136 scheme.eq_ignore_ascii_case("Bearer").then_some(token)
137}
138
139pub async fn serve(
145 listener: TcpListener,
146 app: Router,
147 shutdown: impl Future<Output = ()> + Send + 'static,
148) -> Result<(), HttpError> {
149 axum::serve(listener, app)
150 .with_graceful_shutdown(shutdown)
151 .await?;
152 Ok(())
153}