turbomcp_server/server/core.rs
1//! Core MCP server implementation
2//!
3//! Contains the main McpServer struct and its core functionality including
4//! middleware building, lifecycle management, and server construction.
5
6use std::sync::Arc;
7use tracing::{info, info_span};
8
9use crate::{
10 config::ServerConfig,
11 error::ServerResult,
12 lifecycle::{HealthStatus, ServerLifecycle},
13 metrics::ServerMetrics,
14 registry::HandlerRegistry,
15 routing::RequestRouter,
16 service::McpService,
17};
18
19#[cfg(feature = "middleware")]
20use crate::middleware::MiddlewareStack;
21
22use bytes::Bytes;
23use http::{Request, Response};
24use tokio::time::{Duration, sleep};
25use turbomcp_transport::Transport;
26use turbomcp_transport::core::TransportError;
27
28use super::shutdown::ShutdownHandle;
29
30/// Check if logging should be enabled for STDIO transport
31///
32/// For MCP STDIO transport compliance, logging is disabled by default since stdout
33/// must be reserved exclusively for JSON-RPC messages. This can be overridden by
34/// setting the TURBOMCP_FORCE_LOGGING environment variable.
35pub(crate) fn should_log_for_stdio() -> bool {
36 std::env::var("TURBOMCP_FORCE_LOGGING").is_ok()
37}
38
39/// Main MCP server following the Axum/Tower Clone pattern
40///
41/// ## Sharing Pattern
42///
43/// `McpServer` implements `Clone` like Axum's `Router`. All heavy state is Arc-wrapped
44/// internally, making cloning cheap (just atomic reference count increments).
45///
46/// ```rust,no_run
47/// use turbomcp_server::ServerBuilder;
48///
49/// # async fn example() {
50/// let server = ServerBuilder::new().build();
51///
52/// // Clone for passing to functions (cheap - just Arc increments)
53/// let server1 = server.clone();
54/// let server2 = server.clone();
55///
56/// // Access config and health
57/// let config = server1.config();
58/// println!("Server: {}", config.name);
59///
60/// let health = server2.health().await;
61/// println!("Health: {:?}", health);
62/// # }
63/// ```
64///
65/// ## Architecture Notes
66///
67/// The `service` field contains `BoxCloneService` which is `Send + Clone` but NOT `Sync`.
68/// This is intentional and follows Tower's design - users clone the server instead of
69/// Arc-wrapping it.
70///
71/// **Architecture Note**: The service field provides tower::Service integration for
72/// advanced middleware patterns. The request processing pipeline currently uses the
73/// RequestRouter directly. Tower integration can be added via custom middleware layers
74/// when needed for specific use cases (e.g., custom rate limiting, advanced tracing).
75#[derive(Clone)]
76pub struct McpServer {
77 /// Server configuration (Clone-able)
78 pub(crate) config: ServerConfig,
79 /// Handler registry (Arc-wrapped for cheap cloning)
80 pub(crate) registry: Arc<HandlerRegistry>,
81 /// Request router (Arc-wrapped for cheap cloning)
82 pub(crate) router: Arc<RequestRouter>,
83 /// Tower middleware service stack (Clone but !Sync - this is the Tower pattern)
84 ///
85 /// All requests flow through this service stack, which provides:
86 /// - Timeout enforcement
87 /// - Request validation
88 /// - Authorization checks
89 /// - Rate limiting
90 /// - Audit logging
91 /// - And more middleware layers as configured
92 ///
93 /// See `server/transport.rs` for integration with transport layer.
94 pub(crate) service:
95 tower::util::BoxCloneService<Request<Bytes>, Response<Bytes>, crate::ServerError>,
96 /// Server lifecycle (Arc-wrapped for cheap cloning)
97 pub(crate) lifecycle: Arc<ServerLifecycle>,
98 /// Server metrics (Arc-wrapped for cheap cloning)
99 pub(crate) metrics: Arc<ServerMetrics>,
100}
101
102impl std::fmt::Debug for McpServer {
103 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
104 f.debug_struct("McpServer")
105 .field("config", &self.config)
106 .finish()
107 }
108}
109
110impl McpServer {
111 /// Build comprehensive Tower middleware stack (transport-agnostic)
112 ///
113 /// ## Architecture
114 ///
115 /// This creates a complete Tower service stack with conditional middleware layers:
116 /// - **Timeout Layer**: Request timeout enforcement (tower_http)
117 /// - **Validation Layer**: JSON-RPC structure validation
118 /// - **Authorization Layer**: Resource access control
119 /// - **Core Service**: JSON-RPC routing and handler execution
120 ///
121 /// All middleware is composed using Tower's ServiceBuilder pattern, which provides:
122 /// - Top-to-bottom execution order
123 /// - Type-safe layer composition
124 /// - Zero-cost abstractions
125 /// - Clone-able service instances
126 ///
127 /// ## Integration
128 ///
129 /// The resulting BoxCloneService is stored in `self.service` and called from
130 /// `server/transport.rs` for every incoming request. This ensures ALL requests
131 /// flow through the complete middleware pipeline before reaching handlers.
132 ///
133 /// ## Adding Middleware
134 ///
135 /// To add new middleware, update the match arms below to include your layer.
136 /// Follow the pattern of conditional inclusion based on config flags.
137 #[cfg(feature = "middleware")]
138 fn build_middleware_stack(
139 core_service: McpService,
140 stack: MiddlewareStack,
141 ) -> tower::util::BoxCloneService<Request<Bytes>, Response<Bytes>, crate::ServerError> {
142 // COMPREHENSIVE TOWER COMPOSITION - Conditional Layer Stacking
143 //
144 // This approach builds the middleware stack incrementally, boxing at each step.
145 // While this has a small performance cost from multiple boxing operations,
146 // it provides several critical advantages:
147 //
148 // 1. **Maintainability**: No combinatorial explosion (8 match arms → simple chain)
149 // 2. **Extensibility**: Adding new middleware requires only one new block
150 // 3. **Clarity**: Each layer's purpose and configuration is explicit
151 // 4. **Type Safety**: BoxCloneService provides type erasure while preserving Clone
152 //
153 // Performance note: The boxing overhead is negligible compared to network I/O
154 // and handler execution time. Modern allocators make this essentially free.
155
156 // Start with core service as a boxed service for uniform type handling
157 let mut service: tower::util::BoxCloneService<
158 Request<Bytes>,
159 Response<Bytes>,
160 crate::ServerError,
161 > = tower::util::BoxCloneService::new(core_service);
162
163 // Authorization layer removed in 2.0.0 - handle at application layer
164
165 // Layer 2: Validation
166 // Validates request structure after auth but before processing
167 #[cfg(feature = "middleware")]
168 {
169 if let Some(validation_layer) = stack.validation_layer() {
170 service = tower::util::BoxCloneService::new(
171 tower::ServiceBuilder::new()
172 .layer(validation_layer)
173 .service(service),
174 );
175 }
176 }
177
178 // Layer 3: Timeout (outermost)
179 // Applied last so it can enforce timeout on the entire request pipeline
180 #[cfg(feature = "middleware")]
181 {
182 if let Some(timeout_config) = stack.timeout_config
183 && timeout_config.enabled
184 {
185 service = tower::util::BoxCloneService::new(
186 tower::ServiceBuilder::new()
187 .layer(tower_http::timeout::TimeoutLayer::new(
188 timeout_config.request_timeout,
189 ))
190 .service(service),
191 );
192 }
193 }
194
195 // Future middleware can be added here with similar if-let blocks:
196 // if let Some(auth_config) = stack.auth_config { ... }
197 // if let Some(audit_config) = stack.audit_config { ... }
198 // if let Some(rate_limit_config) = stack.rate_limit_config { ... }
199
200 service
201 }
202
203 /// Create a new server
204 #[must_use]
205 pub fn new(config: ServerConfig) -> Self {
206 Self::new_with_registry(config, HandlerRegistry::new())
207 }
208
209 /// Create a new server with an existing registry (used by ServerBuilder)
210 #[must_use]
211 pub(crate) fn new_with_registry(config: ServerConfig, registry: HandlerRegistry) -> Self {
212 let registry = Arc::new(registry);
213 let metrics = Arc::new(ServerMetrics::new());
214 let router = Arc::new(RequestRouter::new(
215 Arc::clone(®istry),
216 Arc::clone(&metrics),
217 ));
218 // Build middleware stack configuration
219 #[cfg(feature = "middleware")]
220 #[cfg_attr(not(feature = "rate-limiting"), allow(unused_mut))]
221 let mut stack = crate::middleware::MiddlewareStack::new();
222
223 // Auto-install rate limiting if enabled in config
224 #[cfg(feature = "rate-limiting")]
225 if config.rate_limiting.enabled {
226 use crate::middleware::rate_limit::{RateLimitStrategy, RateLimits};
227 use std::num::NonZeroU32;
228 use std::time::Duration;
229
230 let rate_config = crate::middleware::RateLimitConfig {
231 strategy: RateLimitStrategy::Global,
232 limits: RateLimits {
233 requests_per_period: NonZeroU32::new(
234 config.rate_limiting.requests_per_second * 60,
235 )
236 .unwrap(), // Convert per-second to per-minute
237 period: Duration::from_secs(60),
238 burst_size: Some(NonZeroU32::new(config.rate_limiting.burst_capacity).unwrap()),
239 },
240 enabled: true,
241 };
242
243 stack = stack.with_rate_limit(rate_config);
244 }
245
246 // Create core MCP service
247 let core_service = McpService::new(
248 Arc::clone(®istry),
249 Arc::clone(&router),
250 Arc::clone(&metrics),
251 );
252
253 // COMPREHENSIVE TOWER SERVICE COMPOSITION
254 // Build the complete middleware stack with proper type erasure
255 //
256 // This service is called from server/transport.rs for EVERY incoming request:
257 // TransportMessage -> http::Request -> service.call() -> http::Response -> TransportMessage
258 //
259 // The Tower middleware stack provides:
260 // ✓ Timeout enforcement (configurable per-request)
261 // ✓ Request validation (JSON-RPC structure)
262 // ✓ Authorization checks (resource access control)
263 // ✓ Rate limiting (if enabled in config)
264 // ✓ Audit logging (configurable)
265 // ✓ And more layers as configured
266 //
267 // BoxCloneService is Clone but !Sync - this is the Tower pattern
268 #[cfg(feature = "middleware")]
269 let service = Self::build_middleware_stack(core_service, stack);
270
271 #[cfg(not(feature = "middleware"))]
272 let service = tower::util::BoxCloneService::new(core_service);
273
274 let lifecycle = Arc::new(ServerLifecycle::new());
275
276 Self {
277 config,
278 registry,
279 router,
280 service,
281 lifecycle,
282 metrics,
283 }
284 }
285
286 /// Get server configuration
287 #[must_use]
288 pub const fn config(&self) -> &ServerConfig {
289 &self.config
290 }
291
292 /// Get handler registry
293 #[must_use]
294 pub const fn registry(&self) -> &Arc<HandlerRegistry> {
295 &self.registry
296 }
297
298 /// Get request router
299 #[must_use]
300 pub const fn router(&self) -> &Arc<RequestRouter> {
301 &self.router
302 }
303
304 /// Get server lifecycle
305 #[must_use]
306 pub const fn lifecycle(&self) -> &Arc<ServerLifecycle> {
307 &self.lifecycle
308 }
309
310 /// Get server metrics
311 #[must_use]
312 pub const fn metrics(&self) -> &Arc<ServerMetrics> {
313 &self.metrics
314 }
315
316 /// Get the Tower service stack (test accessor)
317 ///
318 /// **Note**: This is primarily for integration testing. Production code should
319 /// use the transport layer which calls the service internally via
320 /// `handle_transport_message()`.
321 ///
322 /// Returns a clone of the Tower service stack, which is cheap (BoxCloneService
323 /// is designed for cloning).
324 #[doc(hidden)]
325 pub fn service(
326 &self,
327 ) -> tower::util::BoxCloneService<Request<Bytes>, Response<Bytes>, crate::ServerError> {
328 self.service.clone()
329 }
330
331 /// Get a shutdown handle for graceful server termination
332 ///
333 /// This handle enables external control over server shutdown, essential for:
334 /// - **Production deployments**: Graceful shutdown on SIGTERM/SIGINT
335 /// - **Container orchestration**: Kubernetes graceful pod termination
336 /// - **Load balancer integration**: Health check coordination
337 /// - **Multi-component systems**: Coordinated shutdown sequences
338 /// - **Maintenance operations**: Planned downtime and updates
339 ///
340 /// # Examples
341 ///
342 /// ## Basic shutdown coordination
343 /// ```no_run
344 /// # use turbomcp_server::ServerBuilder;
345 /// # #[tokio::main]
346 /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
347 /// let server = ServerBuilder::new().build();
348 /// let shutdown_handle = server.shutdown_handle();
349 ///
350 /// // Coordinate with other services
351 /// tokio::spawn(async move {
352 /// // Wait for external shutdown signal
353 /// tokio::signal::ctrl_c().await.expect("Failed to install Ctrl+C handler");
354 /// println!("Shutdown signal received, terminating gracefully...");
355 /// shutdown_handle.shutdown().await;
356 /// });
357 ///
358 /// // Server will gracefully shut down when signaled
359 /// // server.run_stdio().await?;
360 /// # Ok(())
361 /// # }
362 /// ```
363 ///
364 /// ## Container/Kubernetes deployment
365 /// ```no_run
366 /// # use turbomcp_server::ServerBuilder;
367 /// # use std::sync::Arc;
368 /// # #[tokio::main]
369 /// # async fn main() -> Result<(), Box<dyn std::error::Error>> {
370 /// let server = ServerBuilder::new().build();
371 /// let shutdown_handle = server.shutdown_handle();
372 /// let shutdown_handle_clone = shutdown_handle.clone();
373 ///
374 /// // Handle multiple signal types with proper platform support
375 /// tokio::spawn(async move {
376 /// #[cfg(unix)]
377 /// {
378 /// use tokio::signal::unix::{signal, SignalKind};
379 /// let mut sigterm = signal(SignalKind::terminate()).unwrap();
380 /// tokio::select! {
381 /// _ = tokio::signal::ctrl_c() => {
382 /// println!("SIGINT received");
383 /// }
384 /// _ = sigterm.recv() => {
385 /// println!("SIGTERM received");
386 /// }
387 /// }
388 /// }
389 /// #[cfg(not(unix))]
390 /// {
391 /// tokio::signal::ctrl_c().await.expect("Failed to install Ctrl+C handler");
392 /// println!("SIGINT received");
393 /// }
394 /// shutdown_handle_clone.shutdown().await;
395 /// });
396 ///
397 /// // Server handles graceful shutdown automatically
398 /// // server.run_tcp("0.0.0.0:8080").await?;
399 /// # Ok(())
400 /// # }
401 /// ```
402 pub fn shutdown_handle(&self) -> ShutdownHandle {
403 ShutdownHandle::new(self.lifecycle.clone())
404 }
405
406 /// Run the server with STDIO transport
407 ///
408 /// # Errors
409 ///
410 /// Returns [`crate::ServerError::Transport`] if:
411 /// - STDIO transport connection fails
412 /// - Message sending/receiving fails
413 /// - Transport disconnection fails
414 #[tracing::instrument(skip(self), fields(
415 transport = "stdio",
416 service_name = %self.config.name,
417 service_version = %self.config.version
418 ))]
419 pub async fn run_stdio(mut self) -> ServerResult<()> {
420 // For STDIO transport, disable logging unless explicitly overridden
421 // STDIO stdout must be reserved exclusively for JSON-RPC messages per MCP protocol
422 if should_log_for_stdio() {
423 info!("Starting MCP server with STDIO transport");
424 }
425
426 // Start performance monitoring for STDIO server
427 let _perf_span = info_span!("server.run", transport = "stdio").entered();
428 info!("Initializing STDIO transport for MCP server");
429
430 self.lifecycle.start().await;
431
432 // BIDIRECTIONAL STDIO SETUP
433 // Create STDIO dispatcher for server-initiated requests (sampling, elicitation, roots, ping)
434 let (request_tx, request_rx) = tokio::sync::mpsc::unbounded_channel();
435
436 // Use fully-qualified path to avoid ambiguity with the turbomcp crate's runtime module
437 let dispatcher = crate::runtime::StdioDispatcher::new(request_tx);
438
439 // Configure router's bidirectional support with the STDIO dispatcher
440 // SAFETY: We have &mut self, so we can safely get mutable access to the Arc'd router
441 // This is the CRITICAL STEP that was missing - without this, all server→client requests fail
442 let router = Arc::make_mut(&mut self.router);
443 router.set_server_request_dispatcher(dispatcher.clone());
444
445 // Run STDIO with full bidirectional support (MCP 2025-06-18 compliant)
446 // This uses the bidirectional-aware runtime that handles both:
447 // - Client→Server requests (tools, resources, prompts)
448 // - Server→Client requests (sampling, elicitation, roots, ping)
449 crate::runtime::run_stdio_bidirectional(self.router.clone(), dispatcher, request_rx)
450 .await
451 .map_err(|e| crate::ServerError::Handler {
452 message: format!("STDIO bidirectional runtime failed: {}", e),
453 context: Some("run_stdio".to_string()),
454 })
455 }
456
457 /// Get health status
458 pub async fn health(&self) -> HealthStatus {
459 self.lifecycle.health().await
460 }
461
462 /// Run server with HTTP transport using default configuration
463 ///
464 /// This provides a working HTTP server with:
465 /// - Standard HTTP POST/GET/DELETE for MCP protocol at `/mcp`
466 /// - Full MCP 2025-06-18 protocol compliance
467 /// - Graceful shutdown support
468 /// - Default rate limiting (100 req/60s)
469 /// - Default security settings (localhost allowed, CORS disabled)
470 ///
471 /// For custom configuration (rate limits, security, CORS), use `run_http_with_config`.
472 ///
473 /// # Examples
474 ///
475 /// ## Basic usage with default configuration
476 /// ```no_run
477 /// use turbomcp_server::ServerBuilder;
478 ///
479 /// #[tokio::main]
480 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
481 /// let server = ServerBuilder::new()
482 /// .name("my-server")
483 /// .version("1.0.0")
484 /// .build();
485 ///
486 /// server.run_http("127.0.0.1:3000").await?;
487 /// Ok(())
488 /// }
489 /// ```
490 ///
491 /// ## With custom configuration
492 /// ```no_run
493 /// use turbomcp_server::ServerBuilder;
494 /// use turbomcp_transport::streamable_http_v2::StreamableHttpConfigBuilder;
495 /// use std::time::Duration;
496 ///
497 /// #[tokio::main]
498 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
499 /// let server = ServerBuilder::new()
500 /// .name("my-server")
501 /// .version("1.0.0")
502 /// .build();
503 ///
504 /// let config = StreamableHttpConfigBuilder::new()
505 /// .without_rate_limit() // For benchmarking
506 /// .allow_any_origin(true) // Enable CORS
507 /// .build();
508 ///
509 /// server.run_http_with_config("127.0.0.1:3000", config).await?;
510 /// Ok(())
511 /// }
512 /// ```
513 ///
514 /// # Errors
515 ///
516 /// Returns [`crate::ServerError::Transport`] if:
517 /// - Address resolution fails
518 /// - HTTP server fails to start
519 /// - Transport disconnection fails
520 #[cfg(feature = "http")]
521 #[tracing::instrument(skip(self), fields(
522 transport = "http",
523 service_name = %self.config.name,
524 service_version = %self.config.version,
525 addr = ?addr
526 ))]
527 pub async fn run_http<A: std::net::ToSocketAddrs + Send + std::fmt::Debug>(
528 self,
529 addr: A,
530 ) -> ServerResult<()> {
531 use turbomcp_transport::streamable_http_v2::StreamableHttpConfigBuilder;
532
533 // Build default configuration
534 let config = StreamableHttpConfigBuilder::new().build();
535
536 self.run_http_with_config(addr, config).await
537 }
538
539 /// Run server with HTTP transport and custom configuration
540 ///
541 /// This provides full control over HTTP server configuration including:
542 /// - Rate limiting (requests per time window, or disabled entirely)
543 /// - Security settings (CORS, origin validation, authentication)
544 /// - Network settings (bind address, endpoint path, keep-alive)
545 /// - Advanced settings (replay buffer size, etc.)
546 ///
547 /// # Examples
548 ///
549 /// ## Benchmarking configuration (no rate limits)
550 /// ```no_run
551 /// use turbomcp_server::ServerBuilder;
552 /// use turbomcp_transport::streamable_http_v2::StreamableHttpConfigBuilder;
553 ///
554 /// #[tokio::main]
555 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
556 /// let server = ServerBuilder::new()
557 /// .name("benchmark-server")
558 /// .version("1.0.0")
559 /// .build();
560 ///
561 /// let config = StreamableHttpConfigBuilder::new()
562 /// .without_rate_limit() // Disable rate limiting
563 /// .build();
564 ///
565 /// server.run_http_with_config("127.0.0.1:3000", config).await?;
566 /// Ok(())
567 /// }
568 /// ```
569 ///
570 /// ## Production configuration (secure, rate limited)
571 /// ```no_run
572 /// use turbomcp_server::ServerBuilder;
573 /// use turbomcp_transport::streamable_http_v2::StreamableHttpConfigBuilder;
574 /// use std::time::Duration;
575 ///
576 /// #[tokio::main]
577 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
578 /// let server = ServerBuilder::new()
579 /// .name("production-server")
580 /// .version("1.0.0")
581 /// .build();
582 ///
583 /// let config = StreamableHttpConfigBuilder::new()
584 /// .with_rate_limit(1000, Duration::from_secs(60)) // 1000 req/min
585 /// .allow_any_origin(false) // Strict CORS
586 /// .require_authentication(true) // Require auth
587 /// .build();
588 ///
589 /// server.run_http_with_config("127.0.0.1:3000", config).await?;
590 /// Ok(())
591 /// }
592 /// ```
593 ///
594 /// # Errors
595 ///
596 /// Returns [`crate::ServerError::Transport`] if:
597 /// - Address resolution fails
598 /// - HTTP server fails to start
599 /// - Transport disconnection fails
600 #[cfg(feature = "http")]
601 #[tracing::instrument(skip(self, config), fields(
602 transport = "http",
603 service_name = %self.config.name,
604 service_version = %self.config.version,
605 addr = ?addr
606 ))]
607 pub async fn run_http_with_config<A: std::net::ToSocketAddrs + Send + std::fmt::Debug>(
608 self,
609 addr: A,
610 config: turbomcp_transport::streamable_http_v2::StreamableHttpConfig,
611 ) -> ServerResult<()> {
612 use turbomcp_transport::streamable_http_v2::run_server;
613
614 info!("Starting MCP server with HTTP transport");
615 info!(
616 config = ?config,
617 "HTTP configuration loaded"
618 );
619
620 self.lifecycle.start().await;
621
622 // Resolve address to string
623 let socket_addr = addr
624 .to_socket_addrs()
625 .map_err(|e| crate::ServerError::configuration(format!("Invalid address: {}", e)))?
626 .next()
627 .ok_or_else(|| crate::ServerError::configuration("No address resolved"))?;
628
629 info!("Resolved address: {}", socket_addr);
630
631 // Use provided config but override bind_addr with resolved address
632 let mut final_config = config;
633 final_config.bind_addr = socket_addr.to_string();
634
635 info!(
636 bind_addr = %final_config.bind_addr,
637 endpoint_path = %final_config.endpoint_path,
638 "HTTP server configuration finalized"
639 );
640
641 // Run HTTP server with the router
642 // The router implements the required handler trait for HTTP transport
643 run_server(final_config, self.router.clone())
644 .await
645 .map_err(|e| {
646 tracing::error!(error = %e, "HTTP server failed");
647 crate::ServerError::handler(e.to_string())
648 })?;
649
650 info!("HTTP server shutdown complete");
651 Ok(())
652 }
653
654 /// Run server with WebSocket transport (full bidirectional support)
655 ///
656 /// This provides a simple API for WebSocket servers with sensible defaults:
657 /// - Default endpoint: `/mcp/ws`
658 /// - Full MCP 2025-06-18 compliance
659 /// - Bidirectional communication
660 /// - Elicitation support
661 /// - Session management and middleware
662 ///
663 /// For custom configuration, use `run_websocket_with_config()`.
664 ///
665 /// # Example
666 ///
667 /// ```no_run
668 /// use turbomcp_server::ServerBuilder;
669 ///
670 /// #[tokio::main]
671 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
672 /// let server = ServerBuilder::new()
673 /// .name("ws-server")
674 /// .version("1.0.0")
675 /// .build();
676 ///
677 /// server.run_websocket("127.0.0.1:8080").await?;
678 /// Ok(())
679 /// }
680 /// ```
681 #[cfg(all(feature = "websocket", feature = "http"))]
682 #[tracing::instrument(skip(self), fields(
683 transport = "websocket",
684 service_name = %self.config.name,
685 service_version = %self.config.version,
686 addr = ?addr
687 ))]
688 pub async fn run_websocket<A: std::net::ToSocketAddrs + Send + std::fmt::Debug>(
689 self,
690 addr: A,
691 ) -> ServerResult<()> {
692 use turbomcp_transport::websocket_server::WebSocketServerConfig;
693
694 // Build default configuration
695 let config = WebSocketServerConfig::default();
696
697 self.run_websocket_with_config(addr, config).await
698 }
699
700 /// Run server with WebSocket transport and custom configuration
701 ///
702 /// This provides full control over WebSocket server configuration including:
703 /// - Custom endpoint path
704 /// - MCP server settings (middleware, security, etc.)
705 ///
706 /// # Example
707 ///
708 /// ```no_run
709 /// use turbomcp_server::ServerBuilder;
710 /// use turbomcp_transport::websocket_server::WebSocketServerConfig;
711 ///
712 /// #[tokio::main]
713 /// async fn main() -> Result<(), Box<dyn std::error::Error>> {
714 /// let server = ServerBuilder::new()
715 /// .name("custom-ws-server")
716 /// .version("1.0.0")
717 /// .build();
718 ///
719 /// let config = WebSocketServerConfig {
720 /// bind_addr: "0.0.0.0:8080".to_string(),
721 /// endpoint_path: "/custom/ws".to_string(),
722 /// };
723 ///
724 /// server.run_websocket_with_config("127.0.0.1:8080", config).await?;
725 /// Ok(())
726 /// }
727 /// ```
728 #[cfg(all(feature = "websocket", feature = "http"))]
729 #[tracing::instrument(skip(self, config), fields(
730 transport = "websocket",
731 service_name = %self.config.name,
732 service_version = %self.config.version,
733 addr = ?addr
734 ))]
735 pub async fn run_websocket_with_config<A: std::net::ToSocketAddrs + Send + std::fmt::Debug>(
736 self,
737 addr: A,
738 config: turbomcp_transport::websocket_server::WebSocketServerConfig,
739 ) -> ServerResult<()> {
740 use turbomcp_transport::websocket_server::run_websocket_server_with_config;
741
742 info!("Starting MCP server with WebSocket transport");
743 info!(config = ?config, "WebSocket configuration");
744
745 // Resolve address to string
746 let socket_addr = addr
747 .to_socket_addrs()
748 .map_err(|e| crate::ServerError::configuration(format!("Invalid address: {}", e)))?
749 .next()
750 .ok_or_else(|| crate::ServerError::configuration("No address resolved"))?;
751
752 info!("Resolved address: {}", socket_addr);
753
754 // Use provided config but override bind_addr with resolved address
755 let mut final_config = config;
756 final_config.bind_addr = socket_addr.to_string();
757
758 // Run WebSocket server with the router
759 run_websocket_server_with_config(final_config, self.router.clone())
760 .await
761 .map_err(|e| {
762 tracing::error!(error = %e, "WebSocket server failed");
763 crate::ServerError::handler(e.to_string())
764 })?;
765
766 info!("WebSocket server shutdown complete");
767 Ok(())
768 }
769
770 /// Run server with TCP transport (progressive enhancement - runtime configuration)
771 #[cfg(feature = "tcp")]
772 #[tracing::instrument(skip(self), fields(
773 transport = "tcp",
774 service_name = %self.config.name,
775 service_version = %self.config.version,
776 addr = ?addr
777 ))]
778 pub async fn run_tcp<A: std::net::ToSocketAddrs + Send + std::fmt::Debug>(
779 mut self,
780 addr: A,
781 ) -> ServerResult<()> {
782 use turbomcp_transport::TcpTransport;
783
784 // Start performance monitoring for TCP server
785 let _perf_span = info_span!("server.run", transport = "tcp").entered();
786 info!(?addr, "Starting MCP server with TCP transport");
787
788 self.lifecycle.start().await;
789
790 // Convert ToSocketAddrs to SocketAddr
791 let socket_addr = match addr.to_socket_addrs() {
792 Ok(mut addrs) => match addrs.next() {
793 Some(addr) => addr,
794 None => {
795 tracing::error!("No socket address resolved from provided address");
796 self.lifecycle.shutdown().await;
797 return Err(crate::ServerError::configuration("Invalid socket address"));
798 }
799 },
800 Err(e) => {
801 tracing::error!(error = %e, "Failed to resolve socket address");
802 self.lifecycle.shutdown().await;
803 return Err(crate::ServerError::configuration(format!(
804 "Address resolution failed: {e}"
805 )));
806 }
807 };
808
809 let transport = TcpTransport::new_server(socket_addr);
810 if let Err(e) = transport.connect().await {
811 tracing::error!(error = %e, "Failed to connect TCP transport");
812 self.lifecycle.shutdown().await;
813 return Err(e.into());
814 }
815
816 // BIDIRECTIONAL TCP SETUP
817 // Create generic transport dispatcher for server-initiated requests
818 let dispatcher = crate::runtime::TransportDispatcher::new(transport);
819
820 // Configure router's bidirectional support with the TCP dispatcher
821 // This enables ctx.elicit(), ctx.create_message(), ctx.list_roots(), etc.
822 let router = Arc::make_mut(&mut self.router);
823 router.set_server_request_dispatcher(dispatcher.clone());
824
825 // Run TCP with full bidirectional support (MCP 2025-06-18 compliant)
826 // This uses the generic bidirectional runtime that handles both:
827 // - Client→Server requests (tools, resources, prompts)
828 // - Server→Client requests (sampling, elicitation, roots, ping)
829 crate::runtime::run_transport_bidirectional(self.router.clone(), dispatcher)
830 .await
831 .map_err(|e| crate::ServerError::Handler {
832 message: format!("TCP bidirectional runtime failed: {}", e),
833 context: Some("run_tcp".to_string()),
834 })
835 }
836
837 /// Run server with Unix socket transport (progressive enhancement - runtime configuration)
838 #[cfg(all(feature = "unix", unix))]
839 #[tracing::instrument(skip(self), fields(
840 transport = "unix",
841 service_name = %self.config.name,
842 service_version = %self.config.version,
843 path = ?path.as_ref()
844 ))]
845 pub async fn run_unix<P: AsRef<std::path::Path>>(mut self, path: P) -> ServerResult<()> {
846 use std::path::PathBuf;
847 use turbomcp_transport::UnixTransport;
848
849 // Start performance monitoring for Unix server
850 let _perf_span = info_span!("server.run", transport = "unix").entered();
851 info!(path = ?path.as_ref(), "Starting MCP server with Unix socket transport");
852
853 self.lifecycle.start().await;
854
855 let socket_path = PathBuf::from(path.as_ref());
856 let transport = UnixTransport::new_server(socket_path);
857 if let Err(e) = transport.connect().await {
858 tracing::error!(error = %e, "Failed to connect Unix socket transport");
859 self.lifecycle.shutdown().await;
860 return Err(e.into());
861 }
862
863 // BIDIRECTIONAL UNIX SOCKET SETUP
864 // Create generic transport dispatcher for server-initiated requests
865 let dispatcher = crate::runtime::TransportDispatcher::new(transport);
866
867 // Configure router's bidirectional support with the Unix socket dispatcher
868 // This enables ctx.elicit(), ctx.create_message(), ctx.list_roots(), etc.
869 let router = Arc::make_mut(&mut self.router);
870 router.set_server_request_dispatcher(dispatcher.clone());
871
872 // Run Unix Socket with full bidirectional support (MCP 2025-06-18 compliant)
873 // This uses the generic bidirectional runtime that handles both:
874 // - Client→Server requests (tools, resources, prompts)
875 // - Server→Client requests (sampling, elicitation, roots, ping)
876 crate::runtime::run_transport_bidirectional(self.router.clone(), dispatcher)
877 .await
878 .map_err(|e| crate::ServerError::Handler {
879 message: format!("Unix socket bidirectional runtime failed: {}", e),
880 context: Some("run_unix".to_string()),
881 })
882 }
883
884 /// Generic transport runner (DRY principle)
885 /// Used by feature-gated transport methods (http, tcp, websocket, unix)
886 #[allow(dead_code)]
887 #[tracing::instrument(skip(self, transport), fields(
888 service_name = %self.config.name,
889 service_version = %self.config.version
890 ))]
891 async fn run_with_transport<T: Transport>(&self, mut transport: T) -> ServerResult<()> {
892 // Install signal handlers for graceful shutdown (Ctrl+C / SIGTERM)
893 let lifecycle_for_sigint = self.lifecycle.clone();
894 tokio::spawn(async move {
895 if let Err(e) = tokio::signal::ctrl_c().await {
896 tracing::warn!(error = %e, "Failed to install Ctrl+C handler");
897 return;
898 }
899 tracing::info!("Ctrl+C received, initiating shutdown");
900 lifecycle_for_sigint.shutdown().await;
901 });
902
903 #[cfg(unix)]
904 {
905 let lifecycle_for_sigterm = self.lifecycle.clone();
906 tokio::spawn(async move {
907 use tokio::signal::unix::{SignalKind, signal};
908 match signal(SignalKind::terminate()) {
909 Ok(mut sigterm) => {
910 sigterm.recv().await;
911 tracing::info!("SIGTERM received, initiating shutdown");
912 lifecycle_for_sigterm.shutdown().await;
913 }
914 Err(e) => tracing::warn!(error = %e, "Failed to install SIGTERM handler"),
915 }
916 });
917 }
918
919 // Shutdown signal
920 let mut shutdown = self.lifecycle.shutdown_signal();
921
922 // Main message processing loop
923 loop {
924 tokio::select! {
925 _ = shutdown.recv() => {
926 tracing::info!("Shutdown signal received");
927 break;
928 }
929 res = transport.receive() => {
930 match res {
931 Ok(Some(message)) => {
932 if let Err(e) = self.handle_transport_message(&mut transport, message).await {
933 tracing::warn!(error = %e, "Failed to handle transport message");
934 }
935 }
936 Ok(None) => {
937 // No message available; sleep briefly to avoid busy loop
938 sleep(Duration::from_millis(5)).await;
939 }
940 Err(e) => {
941 match e {
942 TransportError::ReceiveFailed(msg) if msg.contains("disconnected") => {
943 tracing::info!("Transport receive channel disconnected; shutting down");
944 break;
945 }
946 _ => {
947 tracing::error!(error = %e, "Transport receive failed");
948 // Backoff on errors
949 sleep(Duration::from_millis(50)).await;
950 }
951 }
952 }
953 }
954 }
955 }
956 }
957
958 // Disconnect transport
959 if let Err(e) = transport.disconnect().await {
960 tracing::warn!(error = %e, "Error while disconnecting transport");
961 }
962
963 tracing::info!("Server shutdown complete");
964 Ok(())
965 }
966}
967
968// Compile-time assertion that McpServer is Send + Clone (Tower pattern)
969// Note: McpServer is Clone but NOT Sync (due to BoxCloneService being !Sync)
970// This is intentional and follows the Axum/Tower design pattern
971#[allow(dead_code)]
972const _: () = {
973 const fn assert_send_clone<T: Send + Clone>() {}
974 const fn check() {
975 assert_send_clone::<crate::server::core::McpServer>();
976 }
977};