1use crate::companion::{CompanionTasks, StartTaskInput, TaskInput, TaskSnapshot};
9use crate::error::{Result as WebmcpResult, WebmcpError};
10use crate::runtime::RuntimeAdapter;
11use axum::Router;
12use axum::body::{self, Body};
13use axum::extract::{Path, Request, State};
14use axum::http::header::{
15 ACCEPT, AUTHORIZATION, CACHE_CONTROL, CONTENT_TYPE, HOST, ORIGIN, PROXY_AUTHORIZATION, WWW_AUTHENTICATE,
16};
17use axum::http::{HeaderMap, HeaderValue, Method, StatusCode};
18use axum::middleware::{self, Next};
19use axum::response::sse::{Event, KeepAlive, Sse};
20use axum::response::{IntoResponse, Json as AxumJson, Response};
21use axum::routing::{get, post};
22use futures::stream;
23use futures::{Sink, Stream, StreamExt};
24use rmcp::handler::server::router::tool::ToolRouter;
25use rmcp::handler::server::wrapper::Parameters;
26use rmcp::model::{ClientJsonRpcMessage, Implementation, ServerCapabilities, ServerConfig, ServerJsonRpcMessage, Tool};
27use rmcp::transport::sink_stream::SinkStreamTransport;
28use rmcp::transport::streamable_http_server::session::local::LocalSessionManager;
29use rmcp::transport::streamable_http_server::{StreamableHttpServerConfig, StreamableHttpService};
30use rmcp::{Json, ServerHandler, ServiceExt, tool, tool_handler, tool_router};
31use std::collections::BTreeMap;
32use std::error::Error;
33use std::fmt::{Display, Formatter};
34use std::pin::Pin;
35use std::sync::Arc;
36use std::task::{Context, Poll};
37use std::time::{Duration, Instant};
38use tokio::sync::{Mutex, mpsc};
39use tokio::time::sleep;
40use tokio_stream::wrappers::ReceiverStream;
41use tokio_util::sync::{CancellationToken, DropGuard};
42use url::Url;
43use uuid::Uuid;
44use vtcode_commons::validation::is_valid_origin;
45
46const DEFAULT_MAX_RESULTS: usize = 20;
47const DEFAULT_MAX_SCAN_FILES: usize = 256;
48const DEFAULT_MAX_SCAN_BYTES: usize = 16 * 1024 * 1024;
49const DEFAULT_MAX_REQUEST_BODY_BYTES: usize = 1024 * 1024;
50const DEFAULT_SESSION_TTL: Duration = Duration::from_secs(300);
51const MAX_LEGACY_SESSIONS: usize = 64;
52const LEGACY_INPUT_QUEUE_CAPACITY: usize = 16;
53const MAX_QUERY_BYTES: usize = 4096;
54const MAX_FILE_ID_BYTES: usize = 4096;
55const LEGACY_KEEP_ALIVE: Duration = Duration::from_secs(15);
56const PROTECTED_RESOURCE_METADATA_PATH: &str = "/.well-known/oauth-protected-resource";
57
58mod types;
59
60pub use types::{FetchInput, FetchOutput, SearchInput, SearchOutput, SearchResult};
61
62#[derive(Clone)]
67pub struct RemoteMcpServerConfig {
68 pub public_url: Url,
70 pub authorization_server: Url,
72 proxy_bearer_token: Arc<str>,
73 pub citation_url_prefix: Option<Url>,
75 pub allowed_origins: Vec<String>,
77 pub max_results: usize,
79 pub max_scan_files: usize,
81 pub max_scan_bytes: usize,
83 pub max_request_body_bytes: usize,
85 pub session_ttl: Duration,
87 pub companion: Option<Arc<dyn CompanionTasks>>,
89}
90
91impl std::fmt::Debug for RemoteMcpServerConfig {
92 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
93 formatter
94 .debug_struct("RemoteMcpServerConfig")
95 .field("public_url", &self.public_url)
96 .field("authorization_server", &self.authorization_server)
97 .field("proxy_bearer_token", &"<redacted>")
98 .field("citation_url_prefix", &self.citation_url_prefix)
99 .field("allowed_origins", &self.allowed_origins)
100 .field("max_results", &self.max_results)
101 .field("max_scan_files", &self.max_scan_files)
102 .field("max_scan_bytes", &self.max_scan_bytes)
103 .field("max_request_body_bytes", &self.max_request_body_bytes)
104 .field("session_ttl", &self.session_ttl)
105 .finish()
106 }
107}
108
109impl RemoteMcpServerConfig {
110 pub fn new(
112 public_url: impl AsRef<str>,
113 authorization_server: impl AsRef<str>,
114 proxy_bearer_token: impl Into<String>,
115 ) -> WebmcpResult<Self> {
116 let public_url = Url::parse(public_url.as_ref())
117 .map_err(|_error| WebmcpError::InvalidRequest("remote MCP public URL is invalid".to_string()))?;
118 let authorization_server = Url::parse(authorization_server.as_ref()).map_err(|_error| {
119 WebmcpError::InvalidRequest("remote MCP authorization-server URL is invalid".to_string())
120 })?;
121 let proxy_bearer_token: Arc<str> = proxy_bearer_token.into().into();
122 let config = Self {
123 public_url,
124 authorization_server,
125 proxy_bearer_token,
126 citation_url_prefix: None,
127 allowed_origins: Vec::new(),
128 max_results: DEFAULT_MAX_RESULTS,
129 max_scan_files: DEFAULT_MAX_SCAN_FILES,
130 max_scan_bytes: DEFAULT_MAX_SCAN_BYTES,
131 max_request_body_bytes: DEFAULT_MAX_REQUEST_BODY_BYTES,
132 session_ttl: DEFAULT_SESSION_TTL,
133 companion: None,
134 };
135 config.validate()?;
136 Ok(config)
137 }
138
139 pub fn validate(&self) -> WebmcpResult<()> {
141 if !is_valid_https_url(&self.public_url) {
142 return Err(WebmcpError::InvalidRequest(
143 "remote MCP public URL must be absolute HTTPS without credentials, query, or fragment".to_string(),
144 ));
145 }
146 if !is_valid_https_url(&self.authorization_server) {
147 return Err(WebmcpError::InvalidRequest(
148 "remote MCP authorization-server URL must be absolute HTTPS without credentials, query, or fragment"
149 .to_string(),
150 ));
151 }
152 if self.proxy_bearer_token.is_empty()
153 || !self.proxy_bearer_token.is_ascii()
154 || self.proxy_bearer_token.chars().any(|character| character.is_ascii_whitespace())
155 {
156 return Err(WebmcpError::InvalidRequest(
157 "remote MCP proxy bearer token must be a non-empty ASCII token".to_string(),
158 ));
159 }
160 if let Some(prefix) = self.citation_url_prefix.as_ref()
161 && !is_valid_citation_url_prefix(prefix)
162 {
163 return Err(WebmcpError::InvalidRequest(
164 "remote MCP citation URL prefix must be an absolute HTTP(S) URL without credentials, query, or fragment"
165 .to_string(),
166 ));
167 }
168 if self.allowed_origins.iter().any(|origin| !is_valid_origin(origin)) {
169 return Err(WebmcpError::InvalidRequest("remote MCP origins must be explicit HTTP(S) origins".to_string()));
170 }
171 if self.max_results == 0 || self.max_results > 100 {
172 return Err(WebmcpError::LimitExceeded);
173 }
174 if self.max_scan_files == 0 || self.max_scan_files > 4096 {
175 return Err(WebmcpError::LimitExceeded);
176 }
177 if self.max_scan_bytes == 0 || self.max_scan_bytes > 64 * 1024 * 1024 {
178 return Err(WebmcpError::LimitExceeded);
179 }
180 if self.max_request_body_bytes == 0 || self.max_request_body_bytes > 16 * 1024 * 1024 {
181 return Err(WebmcpError::LimitExceeded);
182 }
183 if self.session_ttl.is_zero() || self.session_ttl > Duration::from_secs(3600) {
184 return Err(WebmcpError::InvalidRequest(
185 "remote MCP session TTL must be between 1 and 3600 seconds".to_string(),
186 ));
187 }
188 Ok(())
189 }
190
191 pub fn with_citation_url_prefix(mut self, prefix: Option<Url>) -> WebmcpResult<Self> {
193 self.citation_url_prefix = prefix;
194 self.validate()?;
195 Ok(self)
196 }
197
198 pub fn with_allowed_origins(mut self, origins: Vec<String>) -> WebmcpResult<Self> {
200 self.allowed_origins = origins;
201 self.validate()?;
202 Ok(self)
203 }
204
205 pub fn with_limits(
207 mut self,
208 max_results: usize,
209 max_scan_files: usize,
210 max_scan_bytes: usize,
211 max_request_body_bytes: usize,
212 session_ttl: Duration,
213 ) -> WebmcpResult<Self> {
214 self.max_results = max_results;
215 self.max_scan_files = max_scan_files;
216 self.max_scan_bytes = max_scan_bytes;
217 self.max_request_body_bytes = max_request_body_bytes;
218 self.session_ttl = session_ttl;
219 self.validate()?;
220 Ok(self)
221 }
222
223 fn proxy_bearer_token(&self) -> &str {
224 &self.proxy_bearer_token
225 }
226
227 fn metadata_url(&self) -> Url {
228 let mut metadata_url = self.public_url.clone();
229 metadata_url.set_path(PROTECTED_RESOURCE_METADATA_PATH);
230 metadata_url.set_query(None);
231 metadata_url.set_fragment(None);
232 metadata_url
233 }
234}
235
236fn is_valid_https_url(url: &Url) -> bool {
237 url.scheme() == "https"
238 && url.host_str().is_some_and(|host| !host.is_empty())
239 && url.username().is_empty()
240 && url.password().is_none()
241 && url.query().is_none()
242 && url.fragment().is_none()
243}
244
245fn is_valid_citation_url_prefix(url: &Url) -> bool {
246 matches!(url.scheme(), "http" | "https")
247 && url.host_str().is_some_and(|host| !host.is_empty())
248 && url.username().is_empty()
249 && url.password().is_none()
250 && url.query().is_none()
251 && url.fragment().is_none()
252}
253
254#[derive(Clone)]
256pub struct RemoteMcpHandler {
257 adapter: Arc<dyn RuntimeAdapter>,
258 max_results: usize,
259 max_scan_files: usize,
260 max_scan_bytes: usize,
261 citation_url_prefix: Option<Url>,
262 companion: Option<Arc<dyn CompanionTasks>>,
263 tool_router: ToolRouter<Self>,
264}
265
266impl std::fmt::Debug for RemoteMcpHandler {
267 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
268 formatter
269 .debug_struct("RemoteMcpHandler")
270 .field("max_results", &self.max_results)
271 .field("companion_enabled", &self.companion.is_some())
272 .finish_non_exhaustive()
273 }
274}
275
276#[tool_router]
277impl RemoteMcpHandler {
278 pub fn new(adapter: Arc<dyn RuntimeAdapter>, config: Arc<RemoteMcpServerConfig>) -> Self {
280 let mut handler = Self::local(adapter, config.companion.clone());
281 handler.max_results = config.max_results;
282 handler.max_scan_files = config.max_scan_files;
283 handler.max_scan_bytes = config.max_scan_bytes;
284 handler.citation_url_prefix = config.citation_url_prefix.clone();
285 handler
286 }
287
288 pub fn local(adapter: Arc<dyn RuntimeAdapter>, companion: Option<Arc<dyn CompanionTasks>>) -> Self {
291 let mut tool_router = Self::tool_router();
292 if companion.is_none() {
293 for name in ["start_task", "get_task", "cancel_task"] {
294 tool_router.remove_route(name);
295 }
296 }
297 Self {
298 adapter,
299 max_results: DEFAULT_MAX_RESULTS,
300 max_scan_files: DEFAULT_MAX_SCAN_FILES,
301 max_scan_bytes: DEFAULT_MAX_SCAN_BYTES,
302 citation_url_prefix: None,
303 companion,
304 tool_router,
305 }
306 }
307
308 pub async fn serve_stdio(self, cancellation: CancellationToken) -> WebmcpResult<()> {
310 let service = self
311 .serve_with_ct(rmcp::transport::stdio(), cancellation)
312 .await
313 .map_err(|error| WebmcpError::Adapter(format!("local MCP initialization failed: {error}")))?;
314 let reason = service
315 .waiting()
316 .await
317 .map_err(|error| WebmcpError::Adapter(format!("local MCP service stopped: {error}")))?;
318 if let rmcp::service::QuitReason::JoinError(error) = reason {
319 return Err(WebmcpError::Adapter(format!("local MCP worker failed: {error}")));
320 }
321 Ok(())
322 }
323
324 pub fn tool_definitions(&self) -> Vec<Tool> {
326 self.tool_router.list_all()
327 }
328
329 #[tool(
331 name = "search",
332 description = "Search visible UTF-8 workspace files by case-insensitive substring.",
333 annotations(
334 title = "Search workspace files",
335 read_only_hint = true,
336 destructive_hint = false,
337 idempotent_hint = true,
338 open_world_hint = false
339 )
340 )]
341 pub async fn search(&self, Parameters(input): Parameters<SearchInput>) -> Result<Json<SearchOutput>, String> {
342 let query = input.query.trim();
343 if query.is_empty() {
344 return Ok(Json(SearchOutput { results: Vec::new() }));
345 }
346 if query.len() > MAX_QUERY_BYTES {
347 return Err("search query exceeds the configured input limit".to_string());
348 }
349 let query = query.to_lowercase();
350 let mut files = self
351 .adapter
352 .list_files()
353 .await
354 .map_err(|_error| "workspace search is unavailable".to_string())?;
355 files.sort_unstable_by(|left, right| left.path.cmp(&right.path));
356
357 let mut results = Vec::with_capacity(self.max_results.min(DEFAULT_MAX_RESULTS));
358 let mut scanned_bytes = 0usize;
359 for file in files.into_iter().take(self.max_scan_files) {
360 let path_lower = file.path.to_lowercase();
361 let path_matches = path_lower.contains(&query);
362 if path_matches {
363 results.push(self.search_result(&file.path));
364 if results.len() >= self.max_results {
365 break;
366 }
367 continue;
368 }
369
370 let declared_size = match usize::try_from(file.size_bytes) {
371 Ok(size) => size,
372 Err(_) => continue,
373 };
374 let remaining_bytes = self.max_scan_bytes.saturating_sub(scanned_bytes);
375 if declared_size > remaining_bytes {
376 continue;
377 }
378 let snapshot = match self.adapter.read_file(&file.path).await {
379 Ok(snapshot) if snapshot.path == file.path => snapshot,
380 Ok(_) | Err(_) => continue,
381 };
382 if snapshot.content.len() > remaining_bytes {
383 continue;
384 }
385 scanned_bytes = scanned_bytes.saturating_add(snapshot.content.len());
386 if snapshot.content.to_lowercase().contains(&query) {
387 results.push(self.search_result(&file.path));
388 if results.len() >= self.max_results {
389 break;
390 }
391 }
392 }
393 Ok(Json(SearchOutput { results }))
394 }
395
396 #[tool(
398 name = "fetch",
399 description = "Fetch the UTF-8 text of one visible workspace file by ID.",
400 annotations(
401 title = "Fetch workspace file",
402 read_only_hint = true,
403 destructive_hint = false,
404 idempotent_hint = true,
405 open_world_hint = false
406 )
407 )]
408 pub async fn fetch(&self, Parameters(input): Parameters<FetchInput>) -> Result<Json<FetchOutput>, String> {
409 let id = input.id.as_str();
410 if id.trim().is_empty() {
411 return Err("file id is required".to_string());
412 }
413 if id.len() > MAX_FILE_ID_BYTES {
414 return Err("file id exceeds the configured input limit".to_string());
415 }
416 let visible = self
417 .adapter
418 .list_files()
419 .await
420 .map_err(|_error| "workspace file listing is unavailable".to_string())?;
421 if !visible.iter().any(|file| file.path == id) {
422 return Err("requested workspace file is unavailable".to_string());
423 }
424 let snapshot = self
425 .adapter
426 .read_file(id)
427 .await
428 .map_err(|_error| "requested workspace file is unavailable".to_string())?;
429 if snapshot.path != id {
430 return Err("requested workspace file is unavailable".to_string());
431 }
432 let canonical_id = snapshot.path;
433 Ok(Json(FetchOutput {
434 id: canonical_id.clone(),
435 title: canonical_id.clone(),
436 text: snapshot.content,
437 url: self.citation_url(&canonical_id),
438 metadata: None,
439 }))
440 }
441
442 #[tool(
444 name = "start_task",
445 description = "Start a VT Code task. Defaults to read-only planning. Implementation requires a completed plan_task_id and an explicit user request.",
446 annotations(
447 read_only_hint = false,
448 destructive_hint = true,
449 idempotent_hint = false,
450 open_world_hint = true
451 )
452 )]
453 pub async fn start_task(
454 &self,
455 Parameters(input): Parameters<StartTaskInput>,
456 ) -> Result<Json<TaskSnapshot>, String> {
457 self.companion()?.start(input).await.map(Json)
458 }
459
460 #[tool(
462 name = "get_task",
463 description = "Inspect task state, attributed changes, scoped runtime verification, and bounded historical command_results. Command exit zero does not establish unrelated task assertions. Missing proof remains unverified.",
464 annotations(
465 read_only_hint = true,
466 destructive_hint = false,
467 idempotent_hint = true,
468 open_world_hint = false
469 )
470 )]
471 pub async fn get_task(&self, Parameters(input): Parameters<TaskInput>) -> Result<Json<TaskSnapshot>, String> {
472 self.companion()?.get(&input.task_id).await.map(Json)
473 }
474
475 #[tool(
477 name = "cancel_task",
478 description = "Request cancellation of an owned VT Code task. Poll get_task until terminal cleanup completes.",
479 annotations(
480 read_only_hint = false,
481 destructive_hint = true,
482 idempotent_hint = true,
483 open_world_hint = false
484 )
485 )]
486 pub async fn cancel_task(&self, Parameters(input): Parameters<TaskInput>) -> Result<Json<bool>, String> {
487 self.companion()?.cancel(&input.task_id).await.map(Json)
488 }
489
490 fn companion(&self) -> Result<&dyn CompanionTasks, String> {
491 self.companion
492 .as_deref()
493 .ok_or_else(|| "companion execution is disabled".into())
494 }
495
496 fn search_result(&self, path: &str) -> SearchResult {
497 SearchResult {
498 id: path.to_string(),
499 title: path.to_string(),
500 url: self.citation_url(path),
501 }
502 }
503
504 fn citation_url(&self, path: &str) -> String {
505 let Some(prefix) = self.citation_url_prefix.as_ref() else {
506 return String::new();
507 };
508 let mut url = prefix.clone();
509 if let Ok(mut segments) = url.path_segments_mut() {
510 let _ = segments.pop_if_empty();
511 for segment in path.split('/') {
512 let _ = segments.push(segment);
513 }
514 }
515 url.to_string()
516 }
517}
518
519#[tool_handler(router = self.tool_router)]
520impl ServerHandler for RemoteMcpHandler {
521 fn get_info(&self) -> ServerConfig {
522 ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
523 .with_server_info(Implementation::new("vtcode-webmcp", env!("CARGO_PKG_VERSION")))
524 .with_instructions(
525 if self.companion.is_some() {
526 "This server exposes workspace search/fetch and opt-in VT Code tasks. Plan first; implement only on explicit user request. Poll task results and report verification evidence accurately."
527 } else {
528 "This server exposes only read-only search and fetch tools over the configured workspace."
529 },
530 )
531 }
532}
533
534pub struct RemoteMcpEndpoint {
536 config: Arc<RemoteMcpServerConfig>,
537 handler: RemoteMcpHandler,
538 streamable: StreamableHttpService<RemoteMcpHandler, LocalSessionManager>,
539 legacy_sessions: LegacySessionStore,
540}
541
542impl std::fmt::Debug for RemoteMcpEndpoint {
543 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
544 formatter
545 .debug_struct("RemoteMcpEndpoint")
546 .field("config", &self.config)
547 .finish_non_exhaustive()
548 }
549}
550
551impl RemoteMcpEndpoint {
552 pub fn new(adapter: Arc<dyn RuntimeAdapter>, config: RemoteMcpServerConfig) -> WebmcpResult<Self> {
554 config.validate()?;
555 let config = Arc::new(config);
556 let service_config = StreamableHttpServerConfig::default()
557 .with_json_response(true)
558 .with_legacy_session_mode(false)
559 .with_allowed_hosts(allowed_hosts(&config.public_url))
560 .with_allowed_origins(config.allowed_origins.clone())
561 .with_max_request_body_bytes(config.max_request_body_bytes);
562 let handler = RemoteMcpHandler::new(Arc::clone(&adapter), Arc::clone(&config));
563 let handler_adapter = Arc::clone(&adapter);
564 let handler_config = Arc::clone(&config);
565 let streamable = StreamableHttpService::new(
566 move || Ok(RemoteMcpHandler::new(Arc::clone(&handler_adapter), Arc::clone(&handler_config))),
567 Arc::new(LocalSessionManager::default()),
568 service_config,
569 );
570 Ok(Self {
571 legacy_sessions: LegacySessionStore::new(config.session_ttl),
572 config,
573 handler,
574 streamable,
575 })
576 }
577
578 pub fn config(&self) -> &RemoteMcpServerConfig {
580 &self.config
581 }
582
583 pub fn tool_definitions(&self) -> Vec<Tool> {
585 self.handler.tool_definitions()
586 }
587
588 pub fn routes(self: &Arc<Self>) -> Router<Arc<Self>> {
590 Router::new()
591 .nest_service("/mcp", self.streamable.clone())
592 .route("/sse/", get(legacy_sse_handler))
593 .route("/sse", get(legacy_sse_handler))
594 .route("/messages/{session_id}", post(legacy_message_handler))
595 .route(PROTECTED_RESOURCE_METADATA_PATH, get(protected_resource_metadata))
596 .layer(middleware::from_fn_with_state(self.clone(), authenticate_request))
597 }
598
599 async fn create_legacy_session(
600 &self,
601 ) -> WebmcpResult<(
602 String,
603 mpsc::Receiver<ClientJsonRpcMessage>,
604 mpsc::Receiver<ServerJsonRpcMessage>,
605 mpsc::Sender<ServerJsonRpcMessage>,
606 CancellationToken,
607 )> {
608 self.legacy_sessions.create().await
609 }
610
611 async fn legacy_sender(&self, session_id: &str) -> Option<mpsc::Sender<ClientJsonRpcMessage>> {
612 self.legacy_sessions.sender(session_id).await
613 }
614
615 fn authentication_failure(&self, request: &Request<Body>, metadata: bool) -> Option<Response> {
616 if !host_is_allowed(request.headers(), &self.config.public_url) {
617 return Some((StatusCode::FORBIDDEN, "MCP Host header is not allowed").into_response());
618 }
619 match request.headers().get(ORIGIN) {
620 None => {}
621 Some(origin) => {
622 let Ok(origin) = origin.to_str() else {
623 return Some((StatusCode::BAD_REQUEST, "invalid MCP Origin header").into_response());
624 };
625 if !self.config.allowed_origins.iter().any(|allowed| allowed == origin) {
626 return Some((StatusCode::FORBIDDEN, "MCP Origin is not allowed").into_response());
627 }
628 }
629 }
630 if metadata {
631 return None;
632 }
633 let authorized = request
634 .headers()
635 .get(AUTHORIZATION)
636 .and_then(|value| value.to_str().ok())
637 .and_then(|value| value.split_once(' '))
638 .is_some_and(|(scheme, token)| {
639 scheme.eq_ignore_ascii_case("Bearer") && token == self.config.proxy_bearer_token()
640 });
641 if authorized {
642 None
643 } else {
644 Some(self.unauthorized_response())
645 }
646 }
647
648 fn unauthorized_response(&self) -> Response {
649 let metadata_url = self.config.metadata_url().to_string();
650 let challenge = format!("Bearer resource_metadata=\"{}\"", quote_header_value(&metadata_url));
651 let mut response = (StatusCode::UNAUTHORIZED, "MCP authentication required").into_response();
652 if let Ok(value) = HeaderValue::from_str(&challenge) {
653 let _ = response.headers_mut().insert(WWW_AUTHENTICATE, value);
654 }
655 response
656 }
657}
658
659async fn authenticate_request(
660 State(endpoint): State<Arc<RemoteMcpEndpoint>>,
661 mut request: Request,
662 next: Next,
663) -> Response {
664 let metadata = request.uri().path() == PROTECTED_RESOURCE_METADATA_PATH;
665 if let Some(response) = endpoint.authentication_failure(&request, metadata) {
666 return response;
667 }
668 let _ = request.headers_mut().remove(AUTHORIZATION);
669 let _ = request.headers_mut().remove(PROXY_AUTHORIZATION);
670 next.run(request).await
671}
672
673async fn protected_resource_metadata(State(endpoint): State<Arc<RemoteMcpEndpoint>>) -> Response {
674 let body = serde_json::json!({
675 "resource": endpoint.config.public_url.as_str(),
676 "authorization_servers": [endpoint.config.authorization_server.as_str()],
677 "bearer_methods_supported": ["header"],
678 });
679 let mut response = AxumJson(body).into_response();
680 let _ = response
681 .headers_mut()
682 .insert(CACHE_CONTROL, HeaderValue::from_static("no-store"));
683 response
684}
685
686async fn legacy_sse_handler(State(endpoint): State<Arc<RemoteMcpEndpoint>>, headers: HeaderMap) -> Response {
687 let accepts_sse = headers.get(ACCEPT).and_then(|value| value.to_str().ok()).is_some_and(|value| {
688 value
689 .split(',')
690 .any(|part| part.trim().eq_ignore_ascii_case("text/event-stream"))
691 });
692 if !accepts_sse {
693 return (StatusCode::NOT_ACCEPTABLE, "legacy MCP SSE requires Accept: text/event-stream").into_response();
694 }
695 let (session_id, input_receiver, output_receiver, output_sender, cancellation) =
696 match endpoint.create_legacy_session().await {
697 Ok(session) => session,
698 Err(WebmcpError::LimitExceeded) => {
699 return (StatusCode::TOO_MANY_REQUESTS, "MCP session limit reached").into_response();
700 }
701 Err(_) => return (StatusCode::INTERNAL_SERVER_ERROR, "MCP session creation failed").into_response(),
702 };
703 spawn_legacy_server(endpoint.handler.clone(), input_receiver, output_sender, cancellation.clone());
704 let endpoint_event = Event::default().event("endpoint").data(format!("/messages/{session_id}"));
705 let guard = cancellation.drop_guard();
708 let message_stream = legacy_event_stream(output_receiver, guard, endpoint_event);
709 Sse::new(message_stream)
710 .keep_alive(KeepAlive::new().interval(LEGACY_KEEP_ALIVE).text("keep-alive"))
711 .into_response()
712}
713
714async fn legacy_message_handler(
715 State(endpoint): State<Arc<RemoteMcpEndpoint>>,
716 Path(session_id): Path<String>,
717 request: Request,
718) -> Response {
719 if request.method() != Method::POST {
720 return (StatusCode::METHOD_NOT_ALLOWED, "MCP messages require POST").into_response();
721 }
722 let content_type = request
723 .headers()
724 .get(CONTENT_TYPE)
725 .and_then(|value| value.to_str().ok())
726 .and_then(|value| value.split(';').next())
727 .is_some_and(|value| value.trim().eq_ignore_ascii_case("application/json"));
728 if !content_type {
729 return (StatusCode::UNSUPPORTED_MEDIA_TYPE, "MCP messages require application/json").into_response();
730 }
731 let body = match body::to_bytes(request.into_body(), endpoint.config.max_request_body_bytes).await {
732 Ok(body) => body,
733 Err(_) => return (StatusCode::PAYLOAD_TOO_LARGE, "MCP request body is too large").into_response(),
734 };
735 let message = match serde_json::from_slice::<ClientJsonRpcMessage>(&body) {
736 Ok(message) => message,
737 Err(_) => return (StatusCode::BAD_REQUEST, "invalid MCP JSON-RPC message").into_response(),
738 };
739 let Some(sender) = endpoint.legacy_sender(&session_id).await else {
740 return (StatusCode::NOT_FOUND, "MCP session is unknown or expired").into_response();
741 };
742 match sender.try_send(message) {
743 Ok(()) => StatusCode::ACCEPTED.into_response(),
744 Err(mpsc::error::TrySendError::Full(_)) => {
745 (StatusCode::TOO_MANY_REQUESTS, "MCP session input queue is full").into_response()
746 }
747 Err(mpsc::error::TrySendError::Closed(_)) => (StatusCode::NOT_FOUND, "MCP session is closed").into_response(),
748 }
749}
750
751fn allowed_hosts(public_url: &Url) -> Vec<String> {
752 let mut hosts = vec!["localhost".to_string(), "127.0.0.1".to_string(), "::1".to_string()];
753 if let Some(host) = public_url.host_str()
754 && !hosts.iter().any(|allowed| allowed.eq_ignore_ascii_case(host))
755 {
756 hosts.push(host.to_string());
757 }
758 hosts
759}
760
761fn host_is_allowed(headers: &HeaderMap, public_url: &Url) -> bool {
762 let Some(value) = headers.get(HOST).and_then(|value| value.to_str().ok()) else {
763 return false;
764 };
765 let Ok(authority) = http::uri::Authority::try_from(value) else {
766 return false;
767 };
768 let host = authority.host().trim_matches(['[', ']']).to_ascii_lowercase();
769 let port = authority.port_u16();
770 if matches!(host.as_str(), "localhost" | "127.0.0.1" | "::1") {
771 return true;
772 }
773 let Some(public_host) = public_url.host_str() else {
774 return false;
775 };
776 host == public_host.to_ascii_lowercase() && public_url.port().is_none_or(|expected| port == Some(expected))
777}
778
779fn quote_header_value(value: &str) -> String {
780 value.replace('\\', "\\\\").replace('"', "\\\"")
781}
782
783fn legacy_event_stream(
784 receiver: mpsc::Receiver<ServerJsonRpcMessage>,
785 guard: DropGuard,
786 endpoint_event: Event,
787) -> impl Stream<Item = Result<Event, !>> + Send + 'static {
788 let first = stream::once(async move { Ok(endpoint_event) });
789 let messages = stream::unfold((receiver, guard), |(mut receiver, guard)| async move {
790 let message = receiver.recv().await?;
791 let data = serde_json::to_string(&message).unwrap_or_else(|_| "{}".to_string());
792 let event = Event::default().event("message").data(data);
793 Some((Ok(event), (receiver, guard)))
794 });
795 first.chain(messages)
796}
797
798#[derive(Clone)]
799struct LegacySessionStore {
800 sessions: Arc<Mutex<BTreeMap<String, LegacySession>>>,
801 ttl: Duration,
802}
803
804struct LegacySession {
805 sender: mpsc::Sender<ClientJsonRpcMessage>,
806 cancellation: CancellationToken,
807 expires_at: Instant,
808}
809
810impl LegacySessionStore {
811 fn new(ttl: Duration) -> Self {
812 Self {
813 sessions: Arc::new(Mutex::new(BTreeMap::new())),
814 ttl,
815 }
816 }
817
818 async fn create(
819 &self,
820 ) -> WebmcpResult<(
821 String,
822 mpsc::Receiver<ClientJsonRpcMessage>,
823 mpsc::Receiver<ServerJsonRpcMessage>,
824 mpsc::Sender<ServerJsonRpcMessage>,
825 CancellationToken,
826 )> {
827 let now = Instant::now();
828 let mut sessions = self.sessions.lock().await;
829 sessions.retain(|_, session| session.expires_at > now && !session.cancellation.is_cancelled());
830 if sessions.len() >= MAX_LEGACY_SESSIONS {
831 return Err(WebmcpError::LimitExceeded);
832 }
833 let session_id = Uuid::new_v4().simple().to_string();
834 let (input_sender, input_receiver) = mpsc::channel(LEGACY_INPUT_QUEUE_CAPACITY);
835 let (output_sender, output_receiver) = mpsc::channel(LEGACY_INPUT_QUEUE_CAPACITY);
836 let cancellation = CancellationToken::new();
837 let _ = sessions.insert(
838 session_id.clone(),
839 LegacySession {
840 sender: input_sender,
841 cancellation: cancellation.clone(),
842 expires_at: now + self.ttl,
843 },
844 );
845 drop(sessions);
846
847 let expiration_store = self.clone();
848 let expiration_id = session_id.clone();
849 let expiration_token = cancellation.clone();
850 drop(tokio::spawn(async move {
854 expiration_store.expire_when_idle(expiration_id, expiration_token).await;
855 }));
856
857 Ok((session_id, input_receiver, output_receiver, output_sender, cancellation))
858 }
859
860 async fn sender(&self, session_id: &str) -> Option<mpsc::Sender<ClientJsonRpcMessage>> {
861 let now = Instant::now();
862 let mut sessions = self.sessions.lock().await;
863 let session = sessions.get_mut(session_id)?;
864 if session.expires_at <= now || session.cancellation.is_cancelled() {
865 let session = sessions.remove(session_id)?;
866 session.cancellation.cancel();
867 return None;
868 }
869 session.expires_at = now + self.ttl;
870 Some(session.sender.clone())
871 }
872
873 async fn remove(&self, session_id: &str) {
874 if let Some(session) = self.sessions.lock().await.remove(session_id) {
875 session.cancellation.cancel();
876 }
877 }
878
879 async fn expire_when_idle(&self, session_id: String, cancellation: CancellationToken) {
880 loop {
881 let Some(remaining) = self.remaining(&session_id).await else {
882 return;
883 };
884 tokio::select! {
885 _ = sleep(remaining) => {}
886 _ = cancellation.cancelled() => {
889 self.remove(&session_id).await;
890 return;
891 }
892 }
893 let expired = self
894 .sessions
895 .lock()
896 .await
897 .get(&session_id)
898 .is_some_and(|session| session.expires_at <= Instant::now());
899 if expired {
900 self.remove(&session_id).await;
901 return;
902 }
903 }
904 }
905
906 async fn remaining(&self, session_id: &str) -> Option<Duration> {
907 self.sessions
908 .lock()
909 .await
910 .get(session_id)
911 .map(|session| session.expires_at.saturating_duration_since(Instant::now()))
912 }
913}
914
915#[derive(Debug)]
916struct LegacyTransportError;
917
918impl Display for LegacyTransportError {
919 fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result {
920 formatter.write_str("legacy MCP SSE output channel is closed")
921 }
922}
923
924impl Error for LegacyTransportError {}
925
926struct LegacyMessageSink {
927 sender: mpsc::Sender<ServerJsonRpcMessage>,
928}
929
930impl Sink<ServerJsonRpcMessage> for LegacyMessageSink {
931 type Error = LegacyTransportError;
932
933 fn poll_ready(self: Pin<&mut Self>, _context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
934 if self.get_mut().sender.is_closed() {
935 Poll::Ready(Err(LegacyTransportError))
936 } else {
937 Poll::Ready(Ok(()))
938 }
939 }
940
941 fn start_send(self: Pin<&mut Self>, item: ServerJsonRpcMessage) -> Result<(), Self::Error> {
942 self.get_mut().sender.try_send(item).map_err(|_error| LegacyTransportError)
943 }
944
945 fn poll_flush(self: Pin<&mut Self>, _context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
946 Poll::Ready(Ok(()))
947 }
948
949 fn poll_close(self: Pin<&mut Self>, _context: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
950 Poll::Ready(Ok(()))
951 }
952}
953
954fn spawn_legacy_server(
955 handler: RemoteMcpHandler,
956 input_receiver: mpsc::Receiver<ClientJsonRpcMessage>,
957 output_sender: mpsc::Sender<ServerJsonRpcMessage>,
958 cancellation: CancellationToken,
959) {
960 drop(tokio::spawn(async move {
961 let transport =
962 SinkStreamTransport::new(LegacyMessageSink { sender: output_sender }, ReceiverStream::new(input_receiver));
963 if let Ok(service) = handler.serve_with_ct(transport, cancellation.clone()).await {
964 drop(service.waiting().await);
965 }
966 cancellation.cancel();
967 }));
968}
969
970#[cfg(test)]
971mod tests;