turbomcp-server 3.0.9

Production-ready MCP server with zero-boilerplate macros and transport-agnostic design
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
//! Server Builder - SOTA fluent API for MCP server configuration.
//!
//! This module provides a builder pattern for configuring and running MCP servers
//! with full control over transport selection and server integration.
//!
//! # Design Principles
//!
//! 1. **Zero Configuration Required** - Sensible defaults for quick starts
//! 2. **Transport Agnostic** - Choose transport at runtime, not compile time
//! 3. **BYO Server Support** - Integrate with existing Axum/Tower infrastructure
//! 4. **Platform Transparent** - Works on native and WASM without `#[cfg]` in user code
//!
//! # Examples
//!
//! ## Simplest Usage (STDIO default)
//!
//! ```rust,ignore
//! use turbomcp::prelude::*;
//!
//! #[tokio::main]
//! async fn main() {
//!     MyServer.serve().await.unwrap();
//! }
//! ```
//!
//! ## Choose Transport at Runtime
//!
//! ```rust,ignore
//! use turbomcp::prelude::*;
//!
//! #[tokio::main]
//! async fn main() {
//!     let transport = std::env::var("TRANSPORT").unwrap_or("stdio".into());
//!
//!     MyServer.builder()
//!         .transport(match transport.as_str() {
//!             "http" => Transport::http("0.0.0.0:8080"),
//!             "tcp" => Transport::tcp("0.0.0.0:9000"),
//!             _ => Transport::stdio(),
//!         })
//!         .serve()
//!         .await
//!         .unwrap();
//! }
//! ```
//!
//! ## Full Configuration
//!
//! ```rust,ignore
//! use turbomcp::prelude::*;
//!
//! #[tokio::main]
//! async fn main() {
//!     MyServer.builder()
//!         .transport(Transport::http("0.0.0.0:8080"))
//!         .with_rate_limit(100, Duration::from_secs(1))
//!         .with_connection_limit(1000)
//!         .with_graceful_shutdown(Duration::from_secs(30))
//!         .serve()
//!         .await
//!         .unwrap();
//! }
//! ```
//!
//! ## Bring Your Own Server (Axum Integration)
//!
//! ```rust,ignore
//! use axum::Router;
//! use turbomcp::prelude::*;
//!
//! #[tokio::main]
//! async fn main() {
//!     // Get MCP routes as an Axum router
//!     let mcp_router = MyServer.builder().into_axum_router();
//!
//!     // Merge with your existing routes
//!     let app = Router::new()
//!         .route("/health", get(health_check))
//!         .merge(mcp_router);
//!
//!     // Use your own server
//!     let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
//!     axum::serve(listener, app).await?;
//! }
//! ```

use std::time::Duration;

use turbomcp_core::error::McpResult;
use turbomcp_core::handler::McpHandler;

use super::config::{
    ConnectionLimits, ProtocolConfig, RateLimitConfig, ServerConfig, ServerConfigBuilder,
};

/// Transport configuration for the server.
///
/// Use the associated functions to create transport configurations:
/// - `Transport::stdio()` - Standard I/O (default, works with Claude Desktop)
/// - `Transport::http(addr)` - HTTP JSON-RPC
/// - `Transport::websocket(addr)` - WebSocket bidirectional
/// - `Transport::tcp(addr)` - Raw TCP sockets
/// - `Transport::unix(path)` - Unix domain sockets
#[derive(Debug, Clone, Default)]
pub enum Transport {
    /// Standard I/O transport (line-based JSON-RPC).
    /// This is the default and works with Claude Desktop.
    #[default]
    Stdio,

    /// HTTP transport (JSON-RPC over HTTP POST).
    #[cfg(feature = "http")]
    Http {
        /// Bind address (e.g., "0.0.0.0:8080")
        addr: String,
    },

    /// WebSocket transport (bidirectional JSON-RPC).
    #[cfg(feature = "websocket")]
    WebSocket {
        /// Bind address (e.g., "0.0.0.0:8080")
        addr: String,
    },

    /// TCP transport (line-based JSON-RPC over TCP).
    #[cfg(feature = "tcp")]
    Tcp {
        /// Bind address (e.g., "0.0.0.0:9000")
        addr: String,
    },

    /// Unix domain socket transport (line-based JSON-RPC).
    #[cfg(feature = "unix")]
    Unix {
        /// Socket path (e.g., "/tmp/mcp.sock")
        path: String,
    },
}

impl Transport {
    /// Create STDIO transport configuration.
    ///
    /// This is the default transport that works with Claude Desktop
    /// and other MCP clients that communicate via stdin/stdout.
    #[must_use]
    pub fn stdio() -> Self {
        Self::Stdio
    }

    /// Create HTTP transport configuration.
    ///
    /// # Arguments
    ///
    /// * `addr` - Bind address (e.g., "0.0.0.0:8080" or "127.0.0.1:3000")
    #[cfg(feature = "http")]
    #[must_use]
    pub fn http(addr: impl Into<String>) -> Self {
        Self::Http { addr: addr.into() }
    }

    /// Create WebSocket transport configuration.
    ///
    /// # Arguments
    ///
    /// * `addr` - Bind address (e.g., "0.0.0.0:8080")
    #[cfg(feature = "websocket")]
    #[must_use]
    pub fn websocket(addr: impl Into<String>) -> Self {
        Self::WebSocket { addr: addr.into() }
    }

    /// Create TCP transport configuration.
    ///
    /// # Arguments
    ///
    /// * `addr` - Bind address (e.g., "0.0.0.0:9000")
    #[cfg(feature = "tcp")]
    #[must_use]
    pub fn tcp(addr: impl Into<String>) -> Self {
        Self::Tcp { addr: addr.into() }
    }

    /// Create Unix domain socket transport configuration.
    ///
    /// # Arguments
    ///
    /// * `path` - Socket path (e.g., "/tmp/mcp.sock")
    #[cfg(feature = "unix")]
    #[must_use]
    pub fn unix(path: impl Into<String>) -> Self {
        Self::Unix { path: path.into() }
    }
}

/// Server builder for configuring and running MCP servers.
///
/// This builder provides a fluent API for:
/// - Selecting transport at runtime
/// - Configuring rate limits and connection limits
/// - Setting up graceful shutdown
/// - Integrating with existing server infrastructure
///
/// # Example
///
/// ```rust,ignore
/// use turbomcp::prelude::*;
///
/// MyServer.builder()
///     .transport(Transport::http("0.0.0.0:8080"))
///     .with_rate_limit(100, Duration::from_secs(1))
///     .serve()
///     .await?;
/// ```
#[derive(Debug)]
pub struct ServerBuilder<H: McpHandler> {
    handler: H,
    transport: Transport,
    config: ServerConfigBuilder,
    graceful_shutdown: Option<Duration>,
}

impl<H: McpHandler> ServerBuilder<H> {
    /// Create a new server builder wrapping the given handler.
    pub fn new(handler: H) -> Self {
        Self {
            handler,
            transport: Transport::default(),
            config: ServerConfig::builder(),
            graceful_shutdown: None,
        }
    }

    /// Set the transport for this server.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// builder.transport(Transport::http("0.0.0.0:8080"))
    /// ```
    #[must_use]
    pub fn transport(mut self, transport: Transport) -> Self {
        self.transport = transport;
        self
    }

    /// Configure rate limiting.
    ///
    /// # Arguments
    ///
    /// * `requests` - Maximum requests allowed
    /// * `per` - Time window for the limit
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // Allow 100 requests per second
    /// builder.with_rate_limit(100, Duration::from_secs(1))
    /// ```
    #[must_use]
    pub fn with_rate_limit(mut self, max_requests: u32, window: Duration) -> Self {
        self.config = self.config.rate_limit(RateLimitConfig {
            max_requests,
            window,
            per_client: true,
        });
        self
    }

    /// Configure maximum concurrent connections.
    ///
    /// This limit applies to TCP, HTTP, WebSocket, and Unix transports.
    /// STDIO transport always has exactly one connection.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// builder.with_connection_limit(1000)
    /// ```
    #[must_use]
    pub fn with_connection_limit(mut self, max: usize) -> Self {
        self.config = self.config.connection_limits(ConnectionLimits {
            max_tcp_connections: max,
            max_websocket_connections: max,
            max_http_concurrent: max,
            max_unix_connections: max,
        });
        self
    }

    /// Configure graceful shutdown timeout.
    ///
    /// When the server receives a shutdown signal, it will wait up to
    /// this duration for in-flight requests to complete.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// builder.with_graceful_shutdown(Duration::from_secs(30))
    /// ```
    #[must_use]
    pub fn with_graceful_shutdown(mut self, timeout: Duration) -> Self {
        self.graceful_shutdown = Some(timeout);
        self
    }

    /// Configure protocol version negotiation.
    ///
    /// Use `ProtocolConfig::multi_version()` to accept clients requesting
    /// older MCP specification versions (e.g. 2025-06-18) alongside the
    /// latest version.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use turbomcp::prelude::*;
    ///
    /// // Accept both 2025-06-18 and 2025-11-25 clients
    /// MyServer.builder()
    ///     .with_protocol(ProtocolConfig::multi_version())
    ///     .serve()
    ///     .await?;
    /// ```
    #[must_use]
    pub fn with_protocol(mut self, protocol: ProtocolConfig) -> Self {
        self.config = self.config.protocol(protocol);
        self
    }

    /// Configure maximum message size.
    ///
    /// Messages exceeding this size will be rejected.
    /// Default: 10MB.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// // Limit messages to 1MB
    /// builder.with_max_message_size(1024 * 1024)
    /// ```
    #[must_use]
    pub fn with_max_message_size(mut self, size: usize) -> Self {
        self.config = self.config.max_message_size(size);
        self
    }

    /// Apply a custom server configuration.
    ///
    /// This replaces any previously set configuration options.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// let config = ServerConfig::builder()
    ///     .rate_limit(rate_config)
    ///     .connection_limits(limits)
    ///     .build();
    ///
    /// builder.with_config(config)
    /// ```
    #[must_use]
    pub fn with_config(mut self, config: ServerConfig) -> Self {
        let mut builder = ServerConfig::builder()
            .protocol(config.protocol)
            .connection_limits(config.connection_limits)
            .required_capabilities(config.required_capabilities)
            .max_message_size(config.max_message_size);

        if let Some(rate_limit) = config.rate_limit {
            builder = builder.rate_limit(rate_limit);
        }

        self.config = builder;
        self
    }

    /// Run the server with the configured transport.
    ///
    /// This is the main entry point that starts the server and blocks
    /// until shutdown.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// MyServer.builder()
    ///     .transport(Transport::http("0.0.0.0:8080"))
    ///     .serve()
    ///     .await?;
    /// ```
    #[allow(unused_variables)]
    pub async fn serve(self) -> McpResult<()> {
        // Config is used by transport-specific features (http, websocket, tcp, unix)
        // STDIO doesn't use config, so this may be unused if only stdio is enabled
        let config = self.config.build();

        match self.transport {
            Transport::Stdio => {
                #[cfg(feature = "stdio")]
                {
                    super::transport::stdio::run_with_config(&self.handler, &config).await
                }
                #[cfg(not(feature = "stdio"))]
                {
                    Err(turbomcp_core::error::McpError::internal(
                        "STDIO transport not available. Enable the 'stdio' feature.",
                    ))
                }
            }

            #[cfg(feature = "http")]
            Transport::Http { addr } => {
                super::transport::http::run_with_config(&self.handler, &addr, &config).await
            }

            #[cfg(feature = "websocket")]
            Transport::WebSocket { addr } => {
                super::transport::websocket::run_with_config(&self.handler, &addr, &config).await
            }

            #[cfg(feature = "tcp")]
            Transport::Tcp { addr } => {
                super::transport::tcp::run_with_config(&self.handler, &addr, &config).await
            }

            #[cfg(feature = "unix")]
            Transport::Unix { path } => {
                super::transport::unix::run_with_config(&self.handler, &path, &config).await
            }
        }
    }

    /// Get the underlying handler.
    ///
    /// Useful for testing or custom integrations.
    #[must_use]
    pub fn handler(&self) -> &H {
        &self.handler
    }

    /// Consume the builder and return the handler.
    ///
    /// Useful for custom integrations where you need ownership.
    #[must_use]
    pub fn into_handler(self) -> H {
        self.handler
    }

    /// Convert to an Axum router for BYO server integration.
    ///
    /// This allows you to merge MCP routes with your existing Axum application.
    /// Rate limiting configured via `with_rate_limit()` is applied to all requests.
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use axum::Router;
    /// use axum::routing::get;
    ///
    /// let mcp_router = MyServer.builder()
    ///     .with_rate_limit(100, Duration::from_secs(1))
    ///     .into_axum_router();
    ///
    /// let app = Router::new()
    ///     .route("/health", get(|| async { "OK" }))
    ///     .merge(mcp_router);
    ///
    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
    /// axum::serve(listener, app).await?;
    /// ```
    #[cfg(feature = "http")]
    pub fn into_axum_router(self) -> axum::Router {
        use axum::{Router, routing::post};
        use std::sync::Arc;

        let config = self.config.build();
        let handler = Arc::new(self.handler);
        let rate_limiter = config
            .rate_limit
            .as_ref()
            .map(|cfg| Arc::new(crate::config::RateLimiter::new(cfg.clone())));
        let session_manager = crate::transport::http::SessionManager::new();
        let session_versions = Arc::new(tokio::sync::RwLock::new(std::collections::HashMap::<
            String,
            turbomcp_core::types::core::ProtocolVersion,
        >::new()));

        Router::new()
            .route("/", post(handle_json_rpc::<H>))
            .route("/mcp", post(handle_json_rpc::<H>))
            .with_state(AppState {
                handler,
                rate_limiter,
                config: Some(config),
                session_manager,
                session_versions,
            })
    }

    /// Convert to a Tower service for custom server integration.
    ///
    /// This returns a service that can be used with any Tower-compatible
    /// HTTP server (Hyper, Axum, Warp, etc.).
    ///
    /// # Example
    ///
    /// ```rust,ignore
    /// use hyper::server::conn::http1;
    /// use hyper_util::rt::TokioIo;
    ///
    /// let service = MyServer.builder().into_service();
    ///
    /// let listener = tokio::net::TcpListener::bind("0.0.0.0:8080").await?;
    /// loop {
    ///     let (stream, _) = listener.accept().await?;
    ///     let service = service.clone();
    ///     tokio::spawn(async move {
    ///         http1::Builder::new()
    ///             .serve_connection(TokioIo::new(stream), service)
    ///             .await
    ///     });
    /// }
    /// ```
    #[cfg(feature = "http")]
    pub fn into_service(
        self,
    ) -> impl tower::Service<
        axum::http::Request<axum::body::Body>,
        Response = axum::http::Response<axum::body::Body>,
        Error = std::convert::Infallible,
        Future = impl Future<
            Output = Result<axum::http::Response<axum::body::Body>, std::convert::Infallible>,
        > + Send,
    > + Clone
    + Send {
        use tower::ServiceExt;
        self.into_axum_router()
            .into_service()
            .map_err(|e| match e {})
    }
}

/// State for the Axum handler.
#[cfg(feature = "http")]
#[derive(Clone)]
struct AppState<H: McpHandler> {
    handler: std::sync::Arc<H>,
    rate_limiter: Option<std::sync::Arc<crate::config::RateLimiter>>,
    config: Option<crate::config::ServerConfig>,
    /// Session manager for SSE infrastructure. Held here so that BYO Axum
    /// callers can extend the router with SSE routes using the same manager
    /// instance. Not used by the POST handler itself.
    #[allow(dead_code)]
    session_manager: crate::transport::http::SessionManager,
    /// Per-session negotiated protocol version, keyed by mcp-session-id header value.
    session_versions: std::sync::Arc<
        tokio::sync::RwLock<
            std::collections::HashMap<String, turbomcp_core::types::core::ProtocolVersion>,
        >,
    >,
}

/// JSON-RPC request handler for Axum with version-aware routing.
///
/// Note: Rate limiting uses global rate limiting when used via `into_axum_router()`.
/// For per-client rate limiting based on IP, use the full transport which includes
/// `ConnectInfo` extraction.
///
/// Version-aware routing:
/// - `initialize` requests are routed with config-based protocol negotiation, and the
///   negotiated version is stored per session ID (from the `mcp-session-id` header).
/// - Subsequent requests with a known session ID use the stored negotiated version via
///   `route_request_versioned`, enabling per-version response filtering.
/// - Requests without a session ID fall back to config-based routing.
#[cfg(feature = "http")]
async fn handle_json_rpc<H: McpHandler>(
    axum::extract::State(state): axum::extract::State<AppState<H>>,
    headers: axum::http::HeaderMap,
    axum::Json(request): axum::Json<serde_json::Value>,
) -> impl axum::response::IntoResponse {
    use super::context::RequestContext;
    use super::router::{
        parse_request, route_request_versioned, route_request_with_config, serialize_response,
    };

    // Check rate limit if configured (uses global rate limiting for BYO server)
    if let Some(ref limiter) = state.rate_limiter
        && !limiter.check(None)
    {
        return (
            axum::http::StatusCode::TOO_MANY_REQUESTS,
            axum::Json(serde_json::json!({
                "jsonrpc": "2.0",
                "error": {
                    "code": -32000,
                    "message": "Rate limit exceeded"
                },
                "id": null
            })),
        );
    }

    // Extract optional session ID from headers for per-session version tracking.
    let session_id = headers
        .get("mcp-session-id")
        .and_then(|v| v.to_str().ok())
        .map(str::to_owned);

    let request_str = match serde_json::to_string(&request) {
        Ok(s) => s,
        Err(e) => {
            return (
                axum::http::StatusCode::BAD_REQUEST,
                axum::Json(serde_json::json!({
                    "jsonrpc": "2.0",
                    "error": {
                        "code": -32700,
                        "message": format!("Parse error: {}", e)
                    },
                    "id": null
                })),
            );
        }
    };

    let parsed = match parse_request(&request_str) {
        Ok(p) => p,
        Err(e) => {
            return (
                axum::http::StatusCode::BAD_REQUEST,
                axum::Json(serde_json::json!({
                    "jsonrpc": "2.0",
                    "error": {
                        "code": -32700,
                        "message": format!("Parse error: {}", e)
                    },
                    "id": null
                })),
            );
        }
    };

    let ctx = RequestContext::http();
    let core_ctx = ctx.to_core_context();

    let response = if parsed.method == "initialize" {
        // Run config-aware routing for initialize so protocol negotiation fires.
        let resp =
            route_request_with_config(&*state.handler, parsed, &core_ctx, state.config.as_ref())
                .await;

        // On success, extract the negotiated protocolVersion from the response
        // and store it under the session ID so subsequent requests can use versioned routing.
        if resp.result.is_some() {
            let negotiated: Option<turbomcp_core::types::core::ProtocolVersion> = resp
                .result
                .as_ref()
                .and_then(|r| r.get("protocolVersion"))
                .and_then(|v| v.as_str())
                .map(turbomcp_core::types::core::ProtocolVersion::from);

            if let (Some(sid), Some(version)) = (session_id.as_deref(), negotiated) {
                state
                    .session_versions
                    .write()
                    .await
                    .insert(sid.to_owned(), version);
                tracing::debug!(
                    session_id = sid,
                    "Stored negotiated protocol version for BYO Axum session"
                );
            }
        }

        resp
    } else {
        // For non-initialize requests: look up the stored negotiated version for this session.
        let stored_version = match session_id.as_deref() {
            Some(sid) => state.session_versions.read().await.get(sid).cloned(),
            None => None,
        };

        match stored_version {
            Some(version) => {
                // Versioned routing applies the correct response adapter for the
                // protocol version negotiated during the initialize handshake.
                route_request_versioned(&*state.handler, parsed, &core_ctx, &version).await
            }
            None => {
                // No session context — use config-aware routing as a fallback.
                route_request_with_config(&*state.handler, parsed, &core_ctx, state.config.as_ref())
                    .await
            }
        }
    };

    if !response.should_send() {
        return (
            axum::http::StatusCode::NO_CONTENT,
            axum::Json(serde_json::json!(null)),
        );
    }

    match serialize_response(&response) {
        Ok(json_str) => {
            let value: serde_json::Value = serde_json::from_str(&json_str).unwrap_or_default();
            (axum::http::StatusCode::OK, axum::Json(value))
        }
        Err(e) => (
            axum::http::StatusCode::INTERNAL_SERVER_ERROR,
            axum::Json(serde_json::json!({
                "jsonrpc": "2.0",
                "error": {
                    "code": -32603,
                    "message": format!("Internal error: {}", e)
                },
                "id": null
            })),
        ),
    }
}

/// Extension trait for creating server builders from handlers.
///
/// This trait provides the builder pattern for configurable server deployment.
/// For simple cases, use `McpHandlerExt::run()` directly.
///
/// # Design Philosophy
///
/// - **Simple**: `handler.run()` → runs with STDIO (via `McpHandlerExt`)
/// - **Configurable**: `handler.builder().transport(...).serve()` → full control
///
/// # Example
///
/// ```rust,ignore
/// use turbomcp::prelude::*;
///
/// // Simple (no config needed)
/// MyServer.run().await?;
///
/// // Configurable (builder pattern)
/// MyServer.builder()
///     .transport(Transport::http("0.0.0.0:8080"))
///     .with_rate_limit(100, Duration::from_secs(1))
///     .serve()
///     .await?;
///
/// // BYO server (Axum integration)
/// let mcp = MyServer.builder().into_axum_router();
/// ```
pub trait McpServerExt: McpHandler + Sized {
    /// Create a server builder for this handler.
    ///
    /// The builder allows configuring transport, rate limits, connection
    /// limits, and other server options before starting.
    fn builder(self) -> ServerBuilder<Self> {
        ServerBuilder::new(self)
    }
}

/// Blanket implementation for all McpHandler types.
impl<T: McpHandler> McpServerExt for T {}

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::Value;
    use turbomcp_core::context::RequestContext as CoreRequestContext;
    use turbomcp_core::error::McpError;
    use turbomcp_types::{
        Prompt, PromptResult, Resource, ResourceResult, ServerInfo, Tool, ToolResult,
    };

    #[derive(Clone)]
    struct TestHandler;

    #[allow(clippy::manual_async_fn)]
    impl McpHandler for TestHandler {
        fn server_info(&self) -> ServerInfo {
            ServerInfo::new("test", "1.0.0")
        }

        fn list_tools(&self) -> Vec<Tool> {
            vec![Tool::new("test", "Test tool")]
        }

        fn list_resources(&self) -> Vec<Resource> {
            vec![]
        }

        fn list_prompts(&self) -> Vec<Prompt> {
            vec![]
        }

        fn call_tool<'a>(
            &'a self,
            _name: &'a str,
            _args: Value,
            _ctx: &'a CoreRequestContext,
        ) -> impl std::future::Future<Output = McpResult<ToolResult>> + Send + 'a {
            async { Ok(ToolResult::text("ok")) }
        }

        fn read_resource<'a>(
            &'a self,
            uri: &'a str,
            _ctx: &'a CoreRequestContext,
        ) -> impl std::future::Future<Output = McpResult<ResourceResult>> + Send + 'a {
            let uri = uri.to_string();
            async move { Err(McpError::resource_not_found(&uri)) }
        }

        fn get_prompt<'a>(
            &'a self,
            name: &'a str,
            _args: Option<Value>,
            _ctx: &'a CoreRequestContext,
        ) -> impl std::future::Future<Output = McpResult<PromptResult>> + Send + 'a {
            let name = name.to_string();
            async move { Err(McpError::prompt_not_found(&name)) }
        }
    }

    #[test]
    fn test_transport_default_is_stdio() {
        let transport = Transport::default();
        assert!(matches!(transport, Transport::Stdio));
    }

    #[test]
    fn test_builder_creation() {
        let handler = TestHandler;
        let builder = handler.builder();
        assert!(matches!(builder.transport, Transport::Stdio));
    }

    #[test]
    fn test_builder_transport_selection() {
        let handler = TestHandler;

        // Test STDIO
        let builder = handler.clone().builder().transport(Transport::stdio());
        assert!(matches!(builder.transport, Transport::Stdio));
    }

    #[cfg(feature = "http")]
    #[test]
    fn test_builder_http_transport() {
        let handler = TestHandler;
        let builder = handler.builder().transport(Transport::http("0.0.0.0:8080"));
        assert!(matches!(builder.transport, Transport::Http { .. }));
    }

    #[test]
    fn test_builder_rate_limit() {
        let handler = TestHandler;
        let builder = handler
            .builder()
            .with_rate_limit(100, Duration::from_secs(1));

        let config = builder.config.build();
        assert!(config.rate_limit.is_some());
    }

    #[test]
    fn test_builder_connection_limit() {
        let handler = TestHandler;
        let builder = handler.builder().with_connection_limit(500);

        let config = builder.config.build();
        assert_eq!(config.connection_limits.max_tcp_connections, 500);
        assert_eq!(config.connection_limits.max_websocket_connections, 500);
        assert_eq!(config.connection_limits.max_http_concurrent, 500);
        assert_eq!(config.connection_limits.max_unix_connections, 500);
    }

    #[test]
    fn test_builder_graceful_shutdown() {
        let handler = TestHandler;
        let builder = handler
            .builder()
            .with_graceful_shutdown(Duration::from_secs(30));

        assert_eq!(builder.graceful_shutdown, Some(Duration::from_secs(30)));
    }

    #[test]
    fn test_builder_into_handler() {
        let handler = TestHandler;
        let builder = handler.builder();
        let recovered = builder.into_handler();
        assert_eq!(recovered.server_info().name, "test");
    }
}