Skip to main content

turul_http_mcp_server/
streamable_http.rs

1//! Streamable HTTP transport handler for MCP (2026-07-28 stateless core and the opt-in 2025-11-25 lane).
2//!
3//! This module implements the "Streamable HTTP" transport mechanism introduced
4//! in MCP 2025-03-26, which replaces the previous HTTP+SSE approach from 2024-11-05.
5//!
6//! ## Key Improvements over HTTP+SSE
7//! - **Serverless Compatibility**: Enables deployment on AWS Lambda, Google Cloud Run
8//! - **Improved Scalability**: Supports chunked transfer encoding and progressive delivery
9//! - **Session Management**: Cryptographically secure session IDs for connection tracking
10//! - **Enterprise Network Friendly**: No long-lived connections or polling requirements
11
12use std::collections::HashMap;
13use std::sync::Arc;
14
15use bytes::Bytes;
16use http_body::Body;
17use http_body_util::{BodyExt, Full};
18use hyper::header::{ACCEPT, CONTENT_TYPE};
19use hyper::{HeaderMap, Method, Request, Response, StatusCode};
20use serde_json::Value;
21use tracing::{debug, error, info, warn};
22use turul_mcp_session_storage::SessionView;
23
24use crate::ServerConfig;
25use crate::protocol::{McpProtocolVersion, normalize_header_value};
26
27/// Streamable HTTP request context
28#[derive(Debug, Clone)]
29pub struct StreamableHttpContext {
30    /// Protocol version negotiated
31    pub protocol_version: McpProtocolVersion,
32    /// Session ID if provided
33    pub session_id: Option<String>,
34    /// Whether client wants SSE stream (text/event-stream)
35    pub wants_sse_stream: bool,
36    /// Whether client also accepts JSON (application/json or */*)
37    pub accepts_json: bool,
38    /// Whether client accepts stream frames (application/json, text/event-stream, or */*)
39    pub accepts_stream_frames: bool,
40    /// Additional request headers
41    pub headers: HashMap<String, String>,
42}
43
44impl StreamableHttpContext {
45    /// Parse context from HTTP request headers
46    pub fn from_request<T>(req: &Request<T>) -> Self {
47        let headers = req.headers();
48
49        // Parse protocol version from MCP-Protocol-Version header
50        let protocol_version = headers
51            .get("MCP-Protocol-Version")
52            .and_then(|h| h.to_str().ok())
53            .and_then(McpProtocolVersion::parse_version)
54            .unwrap_or_default();
55
56        // Extract session ID from Mcp-Session-Id header (note capitalization)
57        #[cfg(feature = "protocol-2025-11-25")]
58        let session_id = headers
59            .get("Mcp-Session-Id")
60            .and_then(|h| h.to_str().ok())
61            .map(|s| s.to_string());
62
63        // 2026-07-28 stateless core: an `Mcp-Session-Id` header on a request is
64        // ignored — the server neither honors nor echoes session ids
65        // (streamable-http §Backward Compatibility).
66        #[cfg(feature = "protocol-2026-07-28")]
67        let session_id = None;
68
69        // Check Accept header for streaming and JSON support
70        let accept_header = headers
71            .get(ACCEPT)
72            .and_then(|h| h.to_str().ok())
73            .map(normalize_header_value)
74            .unwrap_or_default();
75
76        let wants_sse_stream = accept_header.contains("text/event-stream");
77        let accepts_json =
78            accept_header.contains("application/json") || accept_header.contains("*/*");
79        let accepts_stream_frames = accepts_json || accept_header.contains("text/event-stream");
80
81        // Collect additional headers for debugging/logging
82        let mut header_map = HashMap::new();
83        for (name, value) in headers.iter() {
84            if let Ok(value_str) = value.to_str() {
85                header_map.insert(name.to_string(), value_str.to_string());
86            }
87        }
88
89        Self {
90            protocol_version,
91            session_id,
92            wants_sse_stream,
93            accepts_json,
94            accepts_stream_frames,
95            headers: header_map,
96        }
97    }
98
99    /// Whether client wants SSE stream
100    pub fn wants_sse_stream(&self) -> bool {
101        self.wants_sse_stream
102    }
103
104    /// Choose SSE vs JSON response framing for a single request.
105    ///
106    /// The server may answer a request with either a single JSON object or an
107    /// SSE stream, and the client must support both — so this is a choice, not
108    /// a conformance requirement:
109    ///
110    /// - Client only accepts `text/event-stream` → SSE
111    /// - Client only accepts `application/json` → JSON
112    /// - Client accepts both → SSE only when the request opted into
113    ///   request-scoped notifications, via `_meta.progressToken` or
114    ///   `_meta."io.modelcontextprotocol/logLevel"`
115    ///
116    /// Those two keys are the only per-request opt-ins for server→client
117    /// notifications on a response stream, and both are gated on the request
118    /// having asked: `ProgressNotificationParams.progressToken` is required and
119    /// must be the token given in the originating request, and a server must not
120    /// emit `notifications/message` for a request that declared no log level. A
121    /// request carrying neither cannot legally be sent either notification, so
122    /// SSE framing would buy it nothing while costing interoperability — plain
123    /// JSON is the broader-support path, and it is the only path that can carry
124    /// the `-32020`/`-32021` header/capability errors on HTTP 400 as their
125    /// schemas require (chunked SSE commits 200 before dispatch).
126    ///
127    /// `subscriptions/listen` is unaffected: it is handled on its own path,
128    /// which independently requires `Accept: text/event-stream`.
129    pub fn should_use_sse(&self, request: &turul_rpc::JsonRpcRequest) -> bool {
130        if !self.wants_sse_stream {
131            return false;
132        }
133        if !self.accepts_json {
134            return true;
135        }
136        // 2025-11-25 keeps its historical method-name heuristic: that lane is a
137        // frozen spec snapshot and its clients were built against always-SSE
138        // `tools/call`. The per-request rule below is a 2026-07-28 change.
139        #[cfg(not(feature = "protocol-2026-07-28"))]
140        return matches!(
141            request.method.as_str(),
142            "tools/call" | "sampling/createMessage" | "elicitation/create"
143        );
144
145        #[cfg(feature = "protocol-2026-07-28")]
146        {
147            let Some(meta) = request.get_param("_meta") else {
148                return false;
149            };
150            if meta.get("progressToken").is_some() {
151                return true;
152            }
153            // Per-request log level is a 2026-07-28 key; the 2025-11-25 lane sets
154            // levels with `logging/setLevel` instead, so there is nothing to opt in
155            // to here and the alias crate does not export the constant.
156            // The key is deprecated with the rest of the Logging surface, but a
157            // request that declares it must still be able to receive what it asked
158            // for while the feature remains in the spec.
159            #[allow(deprecated)]
160            let opted_in = meta.get(turul_mcp_protocol::META_KEY_LOG_LEVEL).is_some();
161            opted_in
162        }
163    }
164
165    /// Whether client wants streaming POST responses
166    pub fn wants_streaming_post(&self) -> bool {
167        self.accepts_stream_frames && self.wants_sse_stream
168    }
169
170    /// Check if request is compatible with streamable HTTP
171    pub fn is_streamable_compatible(&self) -> bool {
172        self.protocol_version.supports_streamable_http() && self.accepts_stream_frames
173    }
174
175    /// Validate request for MCP compliance
176    pub fn validate(&self, method: &Method) -> std::result::Result<(), String> {
177        if !self.accepts_stream_frames {
178            return Err(
179                "Accept header must include application/json, text/event-stream, or */*"
180                    .to_string(),
181            );
182        }
183
184        if self.wants_sse_stream && !self.protocol_version.supports_streamable_http() {
185            return Err(format!(
186                "Protocol version {} does not support streamable HTTP",
187                self.protocol_version.as_str()
188            ));
189        }
190
191        // Only enforce session_id for GET requests with SSE streams
192        // POST requests will validate session based on the JSON-RPC method (initialize vs others)
193        if *method == Method::GET && self.wants_sse_stream && self.session_id.is_none() {
194            return Err("Mcp-Session-Id header required for SSE streaming connections".to_string());
195        }
196
197        Ok(())
198    }
199
200    /// Create response headers for this context
201    pub fn response_headers(&self) -> HeaderMap {
202        let mut headers = HeaderMap::new();
203
204        // Always include protocol version in response
205        headers.insert(
206            "MCP-Protocol-Version",
207            self.protocol_version.as_str().parse().unwrap(),
208        );
209
210        // Include session ID if present
211        if let Some(session_id) = &self.session_id {
212            headers.insert("Mcp-Session-Id", session_id.parse().unwrap());
213        }
214
215        // Add capabilities header showing supported features
216        let features = self.protocol_version.supported_features();
217        if !features.is_empty() {
218            headers.insert("MCP-Capabilities", features.join(",").parse().unwrap());
219        }
220
221        headers
222    }
223}
224
225/// Why session validation failed — determines the HTTP status code.
226///
227/// MCP 2025-11-25 § Session Management:
228/// - Missing `Mcp-Session-Id` header (different code path, see POST handler) → 400 Bad Request
229/// - Terminated or unknown session ID → 404 Not Found (MUST)
230/// - Auth failures (OAuth middleware, different layer) → 401 Unauthorized
231enum SessionValidationError {
232    /// Session ID not found or session has been terminated → 404 Not Found
233    NotFound(String),
234    /// Storage backend error → 500 Internal Server Error
235    StorageError(String),
236    /// Mandatory notification persistence failed → 500 Internal Server Error
237    NotificationFailed(String),
238}
239
240impl SessionValidationError {
241    fn status_code(&self) -> StatusCode {
242        match self {
243            Self::NotFound(_) => StatusCode::NOT_FOUND,
244            Self::StorageError(_) => StatusCode::INTERNAL_SERVER_ERROR,
245            Self::NotificationFailed(_) => StatusCode::INTERNAL_SERVER_ERROR,
246        }
247    }
248
249    fn message(&self) -> &str {
250        match self {
251            Self::NotFound(msg) | Self::StorageError(msg) | Self::NotificationFailed(msg) => msg,
252        }
253    }
254}
255
256/// Streamable HTTP response types
257pub enum StreamableResponse {
258    /// Single JSON response
259    Json(Value),
260    /// Error response
261    Error {
262        /// HTTP status code of the response.
263        status: StatusCode,
264        /// Human-readable error message returned in the response.
265        message: String,
266    },
267}
268
269impl std::fmt::Debug for StreamableResponse {
270    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
271        match self {
272            Self::Json(value) => f.debug_tuple("Json").field(value).finish(),
273            Self::Error { status, message } => f
274                .debug_struct("Error")
275                .field("status", status)
276                .field("message", message)
277                .finish(),
278        }
279    }
280}
281
282impl StreamableResponse {
283    /// Convert to HTTP response
284    pub fn into_response(self, context: &StreamableHttpContext) -> Response<Full<Bytes>> {
285        let mut response_headers = context.response_headers();
286
287        match self {
288            StreamableResponse::Json(json) => {
289                response_headers.insert(CONTENT_TYPE, "application/json".parse().unwrap());
290
291                let body = serde_json::to_string(&json)
292                    .unwrap_or_else(|_| r#"{"error": "Failed to serialize response"}"#.to_string());
293
294                Response::builder()
295                    .status(StatusCode::OK)
296                    .body(Full::new(Bytes::from(body)))
297                    .unwrap()
298            }
299
300            StreamableResponse::Error { status, message } => {
301                response_headers.insert(CONTENT_TYPE, "application/json".parse().unwrap());
302
303                let error_json = serde_json::json!({
304                    "error": {
305                        "code": status.as_u16(),
306                        "message": message
307                    }
308                });
309
310                let body = serde_json::to_string(&error_json).unwrap_or_else(|_| {
311                    r#"{"error": {"code": 500, "message": "Internal server error"}}"#.to_string()
312                });
313
314                Response::builder()
315                    .status(status)
316                    .body(Full::new(Bytes::from(body)))
317                    .unwrap()
318            }
319        }
320    }
321
322    /// Convert to HTTP response with UnsyncBoxBody for streaming compatibility
323    pub fn into_boxed_response(
324        self,
325        context: &StreamableHttpContext,
326    ) -> Response<http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>> {
327        self.into_response(context)
328            .map(|body| body.map_err(|never| match never {}).boxed_unsync())
329    }
330}
331
332/// Streamable HTTP transport handler
333#[derive(Clone)]
334pub struct StreamableHttpHandler {
335    config: Arc<ServerConfig>,
336    dispatcher: Arc<turul_rpc::JsonRpcDispatcher<turul_mcp_protocol::McpError>>,
337    session_storage: Arc<turul_mcp_session_storage::BoxedSessionStorage>,
338    stream_manager: Arc<crate::StreamManager>,
339    server_capabilities: turul_mcp_protocol::ServerCapabilities,
340    pub(crate) middleware_stack: Arc<crate::middleware::MiddlewareStack>,
341    tool_fingerprint: Option<String>,
342    tool_notifier: Option<Arc<dyn crate::ToolChangeNotifier>>,
343    /// Identity stamped into every successful result's
344    /// `_meta.io.modelcontextprotocol/serverInfo`. `None` leaves the key off.
345    server_info: Option<turul_mcp_protocol::Implementation>,
346    /// A buffered transport (Lambda) cannot hold a stream open, so
347    /// `subscriptions/listen` is answered like any unimplemented method.
348    listen_unsupported: bool,
349}
350
351impl StreamableHttpHandler {
352    /// Creates a handler from the server configuration, JSON-RPC dispatcher, session storage, stream manager, advertised server capabilities, middleware stack and optional tool fingerprint.
353    pub fn new(
354        config: Arc<ServerConfig>,
355        dispatcher: Arc<turul_rpc::JsonRpcDispatcher<turul_mcp_protocol::McpError>>,
356        session_storage: Arc<turul_mcp_session_storage::BoxedSessionStorage>,
357        stream_manager: Arc<crate::StreamManager>,
358        server_capabilities: turul_mcp_protocol::ServerCapabilities,
359        middleware_stack: Arc<crate::middleware::MiddlewareStack>,
360        tool_fingerprint: Option<String>,
361    ) -> Self {
362        Self {
363            config,
364            dispatcher,
365            session_storage,
366            stream_manager,
367            server_capabilities,
368            middleware_stack,
369            tool_fingerprint,
370            tool_notifier: None,
371            server_info: None,
372            listen_unsupported: false,
373        }
374    }
375
376    /// Refuse `subscriptions/listen` at once (HTTP 404 + `-32601`) instead of
377    /// holding an SSE stream open. For transports that buffer the response.
378    pub fn without_subscriptions_listen(mut self) -> Self {
379        self.listen_unsupported = true;
380        self
381    }
382
383    /// Set the identity reported in each result's `_meta.serverInfo`.
384    pub fn with_server_info(mut self, info: turul_mcp_protocol::Implementation) -> Self {
385        self.server_info = Some(info);
386        self
387    }
388
389    /// Sets the notifier called when a session's stored tool fingerprint differs from the server's, so the session receives `notifications/tools/list_changed`.
390    pub fn with_tool_notifier(mut self, notifier: Arc<dyn crate::ToolChangeNotifier>) -> Self {
391        self.tool_notifier = Some(notifier);
392        self
393    }
394
395    /// Handle incoming HTTP request with streamable HTTP support
396    pub async fn handle_request<T>(
397        &self,
398        req: Request<T>,
399    ) -> Response<http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>>
400    where
401        T: Body + Send + 'static,
402        T::Data: Send,
403        T::Error: Into<Box<dyn std::error::Error + Send + Sync>>,
404    {
405        debug!(
406            "Streamable handler request: method={}, uri={}",
407            req.method(),
408            req.uri()
409        );
410        // Parse streamable HTTP context from request
411        let context = StreamableHttpContext::from_request(&req);
412
413        debug!(
414            "Streamable handler entry: method={}, protocol={}, session={:?}, accepts_stream_frames={}, wants_sse_stream={}",
415            req.method(),
416            context.protocol_version.as_str(),
417            context.session_id,
418            context.accepts_stream_frames,
419            context.wants_sse_stream()
420        );
421
422        // Handle OPTIONS preflight before validation (no Accept header required).
423        // CORS headers are added by CorsLayer in server.rs — not here.
424        if *req.method() == Method::OPTIONS {
425            return Response::builder()
426                .status(StatusCode::OK)
427                .body(Full::new(Bytes::new()))
428                .unwrap()
429                .map(|body| body.map_err(|never| match never {}).boxed_unsync());
430        }
431
432        // DNS-rebinding protection: "If the `Origin` header is
433        // present and invalid, servers MUST respond with HTTP 403 Forbidden."
434        // OPTIONS preflight (handled above) is exempt; the actual request is
435        // gated here, ahead of validation, auth, and body parsing.
436        if let Err(origin) =
437            crate::origin::validate_origin(req.headers(), &self.config.origin_policy)
438        {
439            warn!("Rejecting request with disallowed Origin: {origin}");
440            return Response::builder()
441                .status(StatusCode::FORBIDDEN)
442                .header("Content-Type", "text/plain")
443                .body(Full::new(Bytes::from_static(
444                    b"Forbidden: Origin not allowed",
445                )))
446                .unwrap()
447                .map(|body| body.map_err(|never| match never {}).boxed_unsync());
448        }
449
450        // 2026-07-28 stateless core: the MCP endpoint accepts POST only. Legacy-era
451        // GET (standalone SSE stream, optionally resumed via Last-Event-ID) and
452        // DELETE (session termination) get 405 Method Not Allowed
453        // (streamable-http §Backward Compatibility). Gated ahead of validate() so
454        // legacy-shaped requests get 405, not an Accept/session 400.
455        #[cfg(feature = "protocol-2026-07-28")]
456        if matches!(*req.method(), Method::GET | Method::DELETE) {
457            return Response::builder()
458                .status(StatusCode::METHOD_NOT_ALLOWED)
459                .header("Allow", "POST, OPTIONS")
460                .header("MCP-Protocol-Version", context.protocol_version.as_str())
461                .body(Full::new(Bytes::new()))
462                .unwrap()
463                .map(|body| body.map_err(|never| match never {}).boxed_unsync());
464        }
465
466        // Validate request
467        if let Err(error) = context.validate(req.method()) {
468            warn!("Invalid streamable HTTP request: {}", error);
469            return StreamableResponse::Error {
470                status: StatusCode::BAD_REQUEST,
471                message: error,
472            }
473            .into_boxed_response(&context);
474        }
475
476        // Route based on MCP 2025-11-25 specification
477        match *req.method() {
478            Method::POST => {
479                // ALL client messages (requests, notifications, responses) come via POST
480                // Server decides whether to respond with JSON or SSE stream
481                self.handle_client_message(req, context).await
482            }
483            Method::GET => {
484                // Optional SSE stream for server-initiated messages
485                self.handle_get_sse_notifications(req, context).await
486            }
487            Method::DELETE => {
488                // Optional session cleanup
489                self.handle_session_delete(req, context).await
490            }
491            _ => StreamableResponse::Error {
492                status: StatusCode::METHOD_NOT_ALLOWED,
493                message: "Method not allowed for this endpoint".to_string(),
494            }
495            .into_boxed_response(&context),
496        }
497    }
498
499    /// Handle GET request for long-lived server-initiated notifications (GET SSE)
500    ///
501    /// This is traditional Server-Sent Events - a long-lived GET connection for
502    /// server-initiated notifications unrelated to specific client requests.
503    /// NOT used for tool progress (that's POST Streamable HTTP).
504    async fn handle_get_sse_notifications<T>(
505        &self,
506        req: Request<T>,
507        context: StreamableHttpContext,
508    ) -> Response<http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>>
509    where
510        T: Body + Send + 'static,
511    {
512        debug!(
513            "Opening streaming connection for session: {:?}",
514            context.session_id
515        );
516
517        // 1. Validate session exists and is authorized
518        let session_id = match context.session_id {
519            Some(ref id) => id.clone(),
520            None => {
521                warn!("Missing session ID for streaming GET request");
522                return StreamableResponse::Error {
523                    status: StatusCode::BAD_REQUEST,
524                    message: "Mcp-Session-Id header required for streaming connection".to_string(),
525                }
526                .into_boxed_response(&context);
527            }
528        };
529
530        // Validate session exists (do NOT create if missing)
531        match self.validate_session_exists(&session_id).await {
532            Ok(_) => {
533                debug!(
534                    "Session validation successful for streaming GET: {}",
535                    session_id
536                );
537            }
538            Err(err) => {
539                error!(
540                    "Session validation failed for streaming GET {}: {}",
541                    session_id,
542                    err.message()
543                );
544                return StreamableResponse::Error {
545                    status: err.status_code(),
546                    message: format!("Session validation failed: {}", err.message()),
547                }
548                .into_boxed_response(&context);
549            }
550        }
551
552        // 2. Create bi-directional stream with chunked transfer encoding
553        // For MCP Streamable HTTP, we create a stream that can handle bidirectional JSON-RPC
554        // Unlike SSE which is unidirectional server->client, this supports client->server and server->client
555
556        // Extract Last-Event-ID for resumability (if client supports it)
557        let last_event_id = req
558            .headers()
559            .get("Last-Event-ID")
560            .and_then(|h| h.to_str().ok())
561            .and_then(|s| s.parse::<u64>().ok());
562
563        // Generate unique connection ID for tracking this stream
564        let connection_id = uuid::Uuid::now_v7().as_simple().to_string();
565
566        debug!(
567            "Creating streamable HTTP connection: session={}, connection={}, last_event_id={:?}",
568            session_id, connection_id, last_event_id
569        );
570
571        // 3. Return streaming response supporting progressive message delivery
572        // Return the actual streaming response from StreamManager
573        // This preserves event replay, resumability, and live streaming capabilities
574        match self
575            .stream_manager
576            .handle_sse_connection(session_id.clone(), connection_id.clone(), last_event_id)
577            .await
578        {
579            Ok(mut streaming_response) => {
580                debug!(
581                    "Streamable HTTP connection established: session={}, connection={}",
582                    session_id, connection_id
583                );
584
585                // Merge MCP headers from context.response_headers()
586                let mcp_headers = context.response_headers();
587                for (key, value) in mcp_headers.iter() {
588                    streaming_response.headers_mut().insert(key, value.clone());
589                }
590
591                // Return the streaming response with MCP headers
592                // This maintains event replay from session storage and live streaming
593                streaming_response
594            }
595            Err(err) => {
596                error!("Failed to create streamable HTTP connection: {}", err);
597                StreamableResponse::Error {
598                    status: StatusCode::INTERNAL_SERVER_ERROR,
599                    message: format!("Streaming connection failed: {}", err),
600                }
601                .into_boxed_response(&context)
602            }
603        }
604    }
605
606    /// Validate that a session exists and is not terminated — do NOT create if missing.
607    ///
608    /// Returns typed errors so callers can map to the correct HTTP status:
609    /// - `NotFound` → 404 (MCP spec: terminated sessions MUST return 404)
610    /// - `StorageError` → 500
611    async fn validate_session_exists(
612        &self,
613        session_id: &str,
614    ) -> std::result::Result<(), SessionValidationError> {
615        match self.session_storage.get_session(session_id).await {
616            Ok(Some(session_info)) => {
617                if session_info.is_terminated() {
618                    error!("Session '{}' has been terminated", session_id);
619                    return Err(SessionValidationError::NotFound(format!(
620                        "Session '{}' has been terminated. Create a new session to continue.",
621                        session_id
622                    )));
623                }
624                // Check tool fingerprint — mismatch means tools changed
625                if let Some(ref current_fp) = self.tool_fingerprint {
626                    if let Some(stored_fp) = session_info.state.get("mcp:tool_fingerprint") {
627                        if stored_fp.as_str() != Some(current_fp.as_str()) {
628                            // Fingerprint mismatch — tools changed since this session was created.
629                            // Session is still valid. Update the stored fingerprint and continue.
630                            info!(
631                                "Tool fingerprint updated for session '{}' (tools changed since session created)",
632                                session_id
633                            );
634                            let _ = self
635                                .session_storage
636                                .set_session_state(
637                                    session_id,
638                                    "mcp:tool_fingerprint",
639                                    serde_json::json!(current_fp),
640                                )
641                                .await;
642
643                            // Emit notifications/tools/list_changed via the notifier
644                            // (backed by SessionManager → dispatcher → guaranteed persistence)
645                            if let Some(ref notifier) = self.tool_notifier {
646                                notifier
647                                    .notify_tools_changed(session_id)
648                                    .await
649                                    .map_err(|e| {
650                                        SessionValidationError::NotificationFailed(format!(
651                                            "session {}: {}",
652                                            session_id, e
653                                        ))
654                                    })?;
655                            }
656                        }
657                    } else {
658                        // Missing fingerprint (pre-feature sessions) — store current fingerprint
659                        info!(
660                            "Session '{}' has no tool fingerprint, storing current",
661                            session_id
662                        );
663                        let _ = self
664                            .session_storage
665                            .set_session_state(
666                                session_id,
667                                "mcp:tool_fingerprint",
668                                serde_json::json!(current_fp),
669                            )
670                            .await;
671                    }
672                }
673                debug!("Session validation successful: {}", session_id);
674                Ok(())
675            }
676            Ok(None) => {
677                error!("Session not found: {}", session_id);
678                Err(SessionValidationError::NotFound(format!(
679                    "Session '{}' not found. Sessions must be created via initialize request first.",
680                    session_id
681                )))
682            }
683            Err(err) => {
684                error!("Failed to validate session {}: {}", session_id, err);
685                Err(SessionValidationError::StorageError(format!(
686                    "Session validation failed: {}",
687                    err
688                )))
689            }
690        }
691    }
692
693    /// Handle DELETE request for session cleanup
694    async fn handle_session_delete<T>(
695        &self,
696        _req: Request<T>,
697        context: StreamableHttpContext,
698    ) -> Response<http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>>
699    where
700        T: Body + Send + 'static,
701    {
702        if let Some(session_id) = &context.session_id {
703            debug!("Deleting session: {}", session_id);
704
705            // Implement proper session cleanup for Streamable HTTP
706            // 1. Close any active streaming connections for this session
707            let closed_connections = self
708                .stream_manager
709                .close_session_connections(session_id)
710                .await;
711            debug!(
712                "Closed {} streaming connections for session: {}",
713                closed_connections, session_id
714            );
715
716            // 2. Mark session as terminated instead of immediate deletion (for proper lifecycle management)
717            match self.session_storage.get_session(session_id).await {
718                Ok(Some(mut session_info)) => {
719                    // Mark session as terminated in state
720                    session_info
721                        .state
722                        .insert("terminated".to_string(), serde_json::Value::Bool(true));
723                    session_info.state.insert(
724                        "terminated_at".to_string(),
725                        serde_json::Value::Number(serde_json::Number::from(
726                            chrono::Utc::now().timestamp_millis(),
727                        )),
728                    );
729                    session_info.touch();
730
731                    // 3. Update session with termination markers
732                    match self.session_storage.update_session(session_info).await {
733                        Ok(()) => {
734                            debug!(
735                                "Session {} marked as terminated (TTL will handle cleanup)",
736                                session_id
737                            );
738
739                            // Return success response with proper headers
740                            Response::builder()
741                                .status(StatusCode::OK)
742                                .header(CONTENT_TYPE, "application/json")
743                                .header("MCP-Protocol-Version", context.protocol_version.as_str())
744                                .header("Mcp-Session-Id", session_id)
745                                .body(Full::new(Bytes::from(
746                                    serde_json::to_string(&serde_json::json!({
747                                        "status": "session_terminated",
748                                        "session_id": session_id,
749                                        "closed_connections": closed_connections,
750                                        "message": "Session marked for cleanup"
751                                    }))
752                                    .unwrap_or_else(|_| {
753                                        r#"{"status":"session_terminated"}"#.to_string()
754                                    }),
755                                )))
756                                .unwrap()
757                                .map(|body| body.map_err(|never| match never {}).boxed_unsync())
758                        }
759                        Err(err) => {
760                            error!(
761                                "Error marking session {} as terminated: {}",
762                                session_id, err
763                            );
764                            // Fallback to deletion if update fails
765                            match self.session_storage.delete_session(session_id).await {
766                                Ok(_) => {
767                                    debug!("Session {} deleted as fallback", session_id);
768                                    Response::builder()
769                                        .status(StatusCode::OK)
770                                        .header(CONTENT_TYPE, "application/json")
771                                        .header(
772                                            "MCP-Protocol-Version",
773                                            context.protocol_version.as_str(),
774                                        )
775                                        .body(Full::new(Bytes::from(
776                                            serde_json::to_string(&serde_json::json!({
777                                                "status": "session_deleted",
778                                                "session_id": session_id,
779                                                "closed_connections": closed_connections,
780                                                "message": "Session removed"
781                                            }))
782                                            .unwrap_or_else(|_| {
783                                                r#"{"status":"session_deleted"}"#.to_string()
784                                            }),
785                                        )))
786                                        .unwrap()
787                                        .map(|body| {
788                                            body.map_err(|never| match never {}).boxed_unsync()
789                                        })
790                                }
791                                Err(delete_err) => {
792                                    error!(
793                                        "Error deleting session {} as fallback: {}",
794                                        session_id, delete_err
795                                    );
796                                    StreamableResponse::Error {
797                                        status: StatusCode::INTERNAL_SERVER_ERROR,
798                                        message: "Session termination error".to_string(),
799                                    }
800                                    .into_boxed_response(&context)
801                                }
802                            }
803                        }
804                    }
805                }
806                Ok(None) => {
807                    // Session not found
808                    Response::builder()
809                        .status(StatusCode::NOT_FOUND)
810                        .header(CONTENT_TYPE, "application/json")
811                        .header("MCP-Protocol-Version", context.protocol_version.as_str())
812                        .body(Full::new(Bytes::from(
813                            serde_json::to_string(&serde_json::json!({
814                                "status": "session_not_found",
815                                "session_id": session_id,
816                                "message": "Session not found"
817                            }))
818                            .unwrap_or_else(|_| r#"{"status":"session_not_found"}"#.to_string()),
819                        )))
820                        .unwrap()
821                        .map(|body| body.map_err(|never| match never {}).boxed_unsync())
822                }
823                Err(err) => {
824                    error!(
825                        "Error retrieving session {} for termination: {}",
826                        session_id, err
827                    );
828                    StreamableResponse::Error {
829                        status: StatusCode::INTERNAL_SERVER_ERROR,
830                        message: "Session lookup error".to_string(),
831                    }
832                    .into_boxed_response(&context)
833                }
834            }
835        } else {
836            StreamableResponse::Error {
837                status: StatusCode::BAD_REQUEST,
838                message: "Mcp-Session-Id header required for session deletion".to_string(),
839            }
840            .into_boxed_response(&context)
841        }
842    }
843
844    /// Handle POST with tool progress notifications (POST Streamable HTTP)
845    ///
846    /// Implements MCP 2025-11-25 Streamable HTTP where POST requests receive
847    /// chunked responses containing both progress notifications AND final result.
848    /// This is request-response, NOT a long-lived connection (that's GET SSE).
849    ///
850    /// Uses hyper::Body::channel() for chunked transfer encoding with background
851    /// task forwarding (works for long-running servers, BROKEN in Lambda).
852    async fn handle_post_streamable_http<T>(
853        &self,
854        req: Request<T>,
855        // Mutated only by the 2025-11-25 session lifecycle (initialize mints a
856        // session into the context); the 2026 stateless path never writes it.
857        #[cfg_attr(feature = "protocol-2026-07-28", allow(unused_mut))]
858        mut context: StreamableHttpContext,
859    ) -> Response<http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>>
860    where
861        T: Body + Send + 'static,
862    {
863        debug!("Streaming handler called - using true streaming POST");
864
865        // Parse request body (still need to collect for JSON-RPC parsing)
866        let body_bytes = match req.into_body().collect().await {
867            Ok(collected) => collected.to_bytes(),
868            Err(_err) => {
869                error!("Failed to read streaming POST request body");
870                return StreamableResponse::Error {
871                    status: StatusCode::BAD_REQUEST,
872                    message: "Failed to read request body".to_string(),
873                }
874                .into_boxed_response(&context);
875            }
876        };
877
878        // Check body size
879        if body_bytes.len() > self.config.max_body_size {
880            warn!(
881                "Streaming POST request body too large: {} bytes",
882                body_bytes.len()
883            );
884            return StreamableResponse::Error {
885                status: StatusCode::PAYLOAD_TOO_LARGE,
886                message: "Request body too large".to_string(),
887            }
888            .into_boxed_response(&context);
889        }
890
891        // Parse as UTF-8
892        let body_str = match std::str::from_utf8(&body_bytes) {
893            Ok(s) => s,
894            Err(err) => {
895                error!("Invalid UTF-8 in streaming POST request body: {}", err);
896                return StreamableResponse::Error {
897                    status: StatusCode::BAD_REQUEST,
898                    message: "Request body must be valid UTF-8".to_string(),
899                }
900                .into_boxed_response(&context);
901            }
902        };
903
904        debug!("Streaming POST received JSON-RPC request: {}", body_str);
905
906        // Parse JSON-RPC message
907        use turul_rpc::dispatch::{JsonRpcMessage, parse_json_rpc_message};
908        // Feeds only the 2025-11-25 missing-session 400 path; the stateless 2026 core
909        // mints an ephemeral session instead, so the import is unused there.
910        #[cfg(feature = "protocol-2025-11-25")]
911        use turul_rpc::error::JsonRpcErrorObject;
912
913        let message = match parse_json_rpc_message(body_str) {
914            Ok(msg) => msg,
915            Err(rpc_err) => {
916                error!("JSON-RPC parse error in streaming POST: {}", rpc_err);
917                let error_json =
918                    serde_json::to_string(&rpc_err).unwrap_or_else(|_| "{}".to_string());
919
920                // Return error with MCP headers (no session header for parse errors).
921                // A body the transport cannot parse as a JSON-RPC message (malformed
922                // JSON, a batch array, or any other envelope violation) never reaches
923                // dispatch, so it takes the same pre-dispatch 400 as the null-id and
924                // header-validation checks below, not the 200 used for a well-formed
925                // request that fails inside a handler.
926                return Response::builder()
927                    .status(StatusCode::BAD_REQUEST)
928                    .header(CONTENT_TYPE, "application/json")
929                    .header("MCP-Protocol-Version", context.protocol_version.as_str())
930                    .body(
931                        Full::new(Bytes::from(error_json))
932                            .map_err(|never| match never {})
933                            .boxed_unsync(),
934                    )
935                    .unwrap();
936            }
937        };
938
939        // MCP forbids null request ids ("Unlike base JSON-RPC, the ID MUST
940        // NOT be null") — reject before any dispatch. turul-rpc's RequestId
941        // retains a Null variant for base-JSON-RPC compatibility, so the MCP
942        // transport enforces the stricter contract here.
943        if let JsonRpcMessage::Request(req) = &message
944            && matches!(req.id, turul_rpc::RequestId::Null)
945        {
946            let err = turul_rpc::JsonRpcError::new(
947                Some(req.id.clone()),
948                turul_rpc::error::JsonRpcErrorObject::invalid_request(Some(serde_json::json!(
949                    "request id MUST NOT be null (MCP basic §Requests)"
950                ))),
951            );
952            let body = serde_json::to_string(&err).unwrap_or_else(|_| "{}".to_string());
953            return Response::builder()
954                .status(StatusCode::BAD_REQUEST)
955                .header(CONTENT_TYPE, "application/json")
956                .header("MCP-Protocol-Version", context.protocol_version.as_str())
957                .body(
958                    Full::new(Bytes::from(body))
959                        .map_err(|never| match never {})
960                        .boxed_unsync(),
961                )
962                .unwrap();
963        }
964
965        // --- Pre-session auth phase ---
966        // Extract Bearer token using hardened parser. A present-but-
967        // unparseable Authorization header is flagged so auth middleware can
968        // answer 400 invalid_request (RFC 6750 §3.1) instead of 401.
969        let auth_header = context.headers.get("authorization");
970        let bearer_token = auth_header.and_then(|v| extract_bearer_token(v));
971        let authorization_malformed = auth_header.is_some() && bearer_token.is_none();
972
973        // Run pre-session middleware if any are registered
974        let pre_session_extensions = if self.middleware_stack.has_pre_session_middleware() {
975            let method_name = match &message {
976                JsonRpcMessage::Request(req) => req.method.as_str(),
977                JsonRpcMessage::Notification(notif) => notif.method.as_str(),
978            };
979            let mut pre_ctx = crate::middleware::RequestContext::new(method_name, None);
980            if let Some(ref token) = bearer_token {
981                pre_ctx.set_bearer_token(token.clone());
982            }
983            pre_ctx.set_authorization_malformed(authorization_malformed);
984            // Copy headers to metadata, excluding Bearer authorization
985            for (k, v) in &context.headers {
986                if k.eq_ignore_ascii_case("authorization") && is_bearer_scheme(v) {
987                    continue;
988                }
989                pre_ctx.add_metadata(k.clone(), serde_json::json!(v));
990            }
991            match self
992                .middleware_stack
993                .execute_before_session(&mut pre_ctx)
994                .await
995            {
996                Ok(()) => Some(pre_ctx.take_extensions()),
997                Err(crate::middleware::MiddlewareError::HttpChallenge {
998                    status,
999                    www_authenticate,
1000                    body,
1001                }) => {
1002                    return build_http_challenge_response(
1003                        status,
1004                        &www_authenticate,
1005                        body.as_deref(),
1006                        &context,
1007                    );
1008                }
1009                Err(other_err) => {
1010                    // Non-challenge pre-session errors → JSON-RPC error
1011                    if let JsonRpcMessage::Request(ref req) = message {
1012                        let response = crate::middleware::error::map_middleware_error_to_jsonrpc(
1013                            other_err,
1014                            req.id.clone(),
1015                        );
1016                        let response_value =
1017                            serde_json::to_value(&response).unwrap_or(serde_json::json!({}));
1018                        return StreamableResponse::Json(response_value)
1019                            .into_boxed_response(&context);
1020                    } else {
1021                        // Notification — can't return JSON-RPC error, just reject
1022                        return Response::builder()
1023                            .status(StatusCode::FORBIDDEN)
1024                            .body(
1025                                Full::new(Bytes::from(other_err.to_string()))
1026                                    .map_err(|never| match never {})
1027                                    .boxed_unsync(),
1028                            )
1029                            .unwrap();
1030                    }
1031                }
1032            }
1033        } else {
1034            None
1035        };
1036
1037        // Handle sessionless ping (pre-init ping support per MCP 2025-11-25).
1038        // Clients are permitted to send pings before initialization completes.
1039        // The bypass waives the SESSION requirement only — it runs AFTER the
1040        // pre-session auth phase above, so servers that implement
1041        // authorization still verify pings ("MUST verify all inbound
1042        // requests", security best practices). 2026-07-28 has no ping
1043        // (absent from the schema): the bypass is 2025-only.
1044        #[cfg(feature = "protocol-2025-11-25")]
1045        let is_sessionless_ping = match &message {
1046            JsonRpcMessage::Request(req) => req.method == "ping",
1047            JsonRpcMessage::Notification(notif) => notif.method == "ping",
1048        } && context.session_id.is_none()
1049            && self.config.allow_unauthenticated_ping;
1050        #[cfg(feature = "protocol-2026-07-28")]
1051        let is_sessionless_ping = false;
1052
1053        if is_sessionless_ping {
1054            return match message {
1055                JsonRpcMessage::Request(request) => {
1056                    // Sessionless ping request: shared dispatch path
1057                    let (response, _) = self
1058                        .run_middleware_and_dispatch(
1059                            request,
1060                            context.headers.clone(),
1061                            None,
1062                            pre_session_extensions.clone(),
1063                        )
1064                        .await;
1065                    let response_value =
1066                        serde_json::to_value(&response).unwrap_or(serde_json::json!({}));
1067                    StreamableResponse::Json(response_value).into_boxed_response(&context)
1068                }
1069                JsonRpcMessage::Notification(notification) => {
1070                    // Sessionless ping notification: dispatch and return 202 Accepted
1071                    let dispatcher = Arc::clone(&self.dispatcher);
1072                    tokio::spawn(async move {
1073                        if let Err(e) = dispatcher
1074                            .handle_notification_with_context(notification, None)
1075                            .await
1076                        {
1077                            error!("Failed to process sessionless ping notification: {}", e);
1078                        }
1079                    });
1080
1081                    Response::builder()
1082                        .status(StatusCode::ACCEPTED)
1083                        .header("MCP-Protocol-Version", context.protocol_version.as_str())
1084                        .body(
1085                            Full::new(Bytes::new())
1086                                .map_err(|never| match never {})
1087                                .boxed_unsync(),
1088                        )
1089                        .unwrap()
1090                }
1091            };
1092        }
1093
1094        // 2026-07-28 §Server Validation: required request-metadata headers. Runs
1095        // AFTER the pre-session auth phase so authentication challenges (401)
1096        // take precedence over header-validation failures (400).
1097        // Every POST MUST carry MCP-Protocol-Version (this build supports no
1098        // pre-2025-06-18 clients, so an absent header is rejected) and Mcp-Method
1099        // matching the body method; tools/call, resources/read, and prompts/get
1100        // additionally require Mcp-Name matching params.name / params.uri.
1101        // Failures → HTTP 400 + JSON-RPC -32020 HeaderMismatch (id-less when the
1102        // body is a notification). Header names compare case-insensitively
1103        // (hyper lowercases them in `context.headers`); values are case-sensitive.
1104        #[cfg(feature = "protocol-2026-07-28")]
1105        {
1106            let body_method = match &message {
1107                JsonRpcMessage::Request(r) => r.method.as_str(),
1108                JsonRpcMessage::Notification(n) => n.method.as_str(),
1109            };
1110            let header = |name: &str| context.headers.get(name).map(String::as_str);
1111            let mut failure: Option<String> = None;
1112
1113            // Version negotiation: a requested version this build does not
1114            // implement (unknown or known-but-unsupported) → 400 +
1115            // UnsupportedProtocolVersionError (-32022) listing the supported set.
1116            if let Some(requested) = header("mcp-protocol-version")
1117                && requested != turul_mcp_protocol::MCP_VERSION
1118            {
1119                warn!(
1120                    "Rejecting 2026 request: unsupported MCP-Protocol-Version '{}'",
1121                    requested
1122                );
1123                let id = match &message {
1124                    JsonRpcMessage::Request(r) => Some(r.id.clone()),
1125                    JsonRpcMessage::Notification(_) => None,
1126                };
1127                let err_obj = turul_mcp_protocol::McpError::UnsupportedProtocolVersion {
1128                    supported: vec![turul_mcp_protocol::MCP_VERSION.to_string()],
1129                    requested: requested.to_string(),
1130                }
1131                .to_error_object();
1132                let err = turul_rpc::JsonRpcError::new(id, err_obj);
1133                let body = serde_json::to_string(&err).unwrap_or_else(|_| "{}".to_string());
1134                return Response::builder()
1135                    .status(StatusCode::BAD_REQUEST)
1136                    .header(CONTENT_TYPE, "application/json")
1137                    .header("MCP-Protocol-Version", turul_mcp_protocol::MCP_VERSION)
1138                    .body(
1139                        Full::new(Bytes::from(body))
1140                            .map_err(|never| match never {})
1141                            .boxed_unsync(),
1142                    )
1143                    .unwrap();
1144            }
1145
1146            if header("mcp-protocol-version").is_none() {
1147                failure = Some("missing required MCP-Protocol-Version header".to_string());
1148            } else {
1149                match header("mcp-method") {
1150                    None => {
1151                        failure = Some("missing required Mcp-Method header".to_string());
1152                    }
1153                    Some(method_header) if method_header != body_method => {
1154                        failure = Some(format!(
1155                            "Mcp-Method header value '{method_header}' does not match body method '{body_method}'"
1156                        ));
1157                    }
1158                    Some(_) => {
1159                        // Mcp-Name mirrors params.name (tools/call, prompts/get)
1160                        // or params.uri (resources/read).
1161                        let body_name = if let JsonRpcMessage::Request(r) = &message {
1162                            let params =
1163                                serde_json::to_value(&r.params).unwrap_or(serde_json::Value::Null);
1164                            match body_method {
1165                                "tools/call" | "prompts/get" => params
1166                                    .get("name")
1167                                    .and_then(|v| v.as_str())
1168                                    .map(String::from),
1169                                "resources/read" => {
1170                                    params.get("uri").and_then(|v| v.as_str()).map(String::from)
1171                                }
1172                                // Tasks extension (SEP-2663): the addressed
1173                                // entity is the task, so Mcp-Name mirrors
1174                                // params.taskId. Omitting these arms let a
1175                                // mismatched Mcp-Name through on the whole
1176                                // tasks surface while the tools surface
1177                                // rejected it — one rule, two behaviours.
1178                                "tasks/get" | "tasks/update" | "tasks/cancel" => params
1179                                    .get("taskId")
1180                                    .and_then(|v| v.as_str())
1181                                    .map(String::from),
1182                                _ => None,
1183                            }
1184                        } else {
1185                            None
1186                        };
1187                        // Core methods REQUIRE Mcp-Name. Extension methods are
1188                        // validated only when the header is present: this
1189                        // transport cannot see whether the tasks extension is
1190                        // registered, and demanding the header for a method the
1191                        // server does not implement would answer -32020 where
1192                        // -32601/404 is correct — it would also leak that the
1193                        // method is recognised. Mismatch is still rejected,
1194                        // which is what SEP-2243 is protecting against.
1195                        let name_required =
1196                            !matches!(body_method, "tasks/get" | "tasks/update" | "tasks/cancel");
1197                        if let Some(expected) = body_name {
1198                            match header("mcp-name") {
1199                                None if !name_required => {}
1200                                None => {
1201                                    failure = Some(format!(
1202                                        "missing required Mcp-Name header for {body_method}"
1203                                    ));
1204                                }
1205                                Some(name_header) => {
1206                                    match turul_mcp_protocol::headers::decode_param_value(
1207                                        name_header,
1208                                    ) {
1209                                        Err(e) => {
1210                                            failure = Some(format!("Mcp-Name: {e}"));
1211                                        }
1212                                        Ok(decoded) if decoded != expected => {
1213                                            failure = Some(format!(
1214                                                "Mcp-Name header value '{decoded}' does not match body value '{expected}'"
1215                                            ));
1216                                        }
1217                                        Ok(_) => {}
1218                                    }
1219                                }
1220                            }
1221                        }
1222                    }
1223                }
1224            }
1225
1226            if let Some(reason) = failure {
1227                warn!("Rejecting 2026 request (header validation): {}", reason);
1228                let id = match &message {
1229                    JsonRpcMessage::Request(r) => Some(r.id.clone()),
1230                    JsonRpcMessage::Notification(_) => None,
1231                };
1232                // Versioning §Backward Compatibility: name the supported
1233                // versions in any error returned to an initialize request —
1234                // a true legacy client (no MCP-Protocol-Version header)
1235                // lands here and this may be its only diagnostic.
1236                let data = (body_method == "initialize")
1237                    .then(|| serde_json::json!({ "supported": [turul_mcp_protocol::MCP_VERSION] }));
1238                let err = turul_rpc::JsonRpcError::new(
1239                    id,
1240                    turul_rpc::error::JsonRpcErrorObject::server_error(
1241                        turul_mcp_protocol::headers::ERROR_CODE_HEADER_MISMATCH,
1242                        &format!("Header mismatch: {reason}"),
1243                        data,
1244                    ),
1245                );
1246                let body = serde_json::to_string(&err).unwrap_or_else(|_| "{}".to_string());
1247                return Response::builder()
1248                    .status(StatusCode::BAD_REQUEST)
1249                    .header(CONTENT_TYPE, "application/json")
1250                    .header("MCP-Protocol-Version", context.protocol_version.as_str())
1251                    .body(
1252                        Full::new(Bytes::from(body))
1253                            .map_err(|never| match never {})
1254                            .boxed_unsync(),
1255                    )
1256                    .unwrap();
1257            }
1258        }
1259
1260        // Validate session requirements based on method (2025-11-25 stateful lifecycle).
1261        #[cfg(feature = "protocol-2025-11-25")]
1262        let session_id = match &message {
1263            JsonRpcMessage::Request(req) if req.method == "initialize" => {
1264                // Initialize can create session if none exists
1265                if let Some(existing_id) = &context.session_id {
1266                    // Validate existing session for initialize
1267                    if let Err(err) = self.validate_session_exists(existing_id).await {
1268                        warn!(
1269                            "Invalid session ID {} during initialize: {}",
1270                            existing_id,
1271                            err.message()
1272                        );
1273                        return StreamableResponse::Error {
1274                            status: err.status_code(),
1275                            message: format!("Invalid or expired session: {}", err.message()),
1276                        }
1277                        .into_boxed_response(&context);
1278                    }
1279                    existing_id.clone()
1280                } else {
1281                    // Create new session for initialize
1282                    match self
1283                        .session_storage
1284                        .create_session(self.server_capabilities.clone())
1285                        .await
1286                    {
1287                        Ok(session_info) => {
1288                            debug!(
1289                                "Created new session for initialize: {}",
1290                                session_info.session_id
1291                            );
1292                            context.session_id = Some(session_info.session_id.clone());
1293                            session_info.session_id
1294                        }
1295                        Err(err) => {
1296                            error!("Failed to create session during initialize: {}", err);
1297                            return StreamableResponse::Error {
1298                                status: StatusCode::INTERNAL_SERVER_ERROR,
1299                                message: "Failed to create session".to_string(),
1300                            }
1301                            .into_boxed_response(&context);
1302                        }
1303                    }
1304                }
1305            }
1306            JsonRpcMessage::Request(_) | JsonRpcMessage::Notification(_) => {
1307                // All other methods REQUIRE session ID
1308                if let Some(existing_id) = &context.session_id {
1309                    // Validate existing session
1310                    if let Err(err) = self.validate_session_exists(existing_id).await {
1311                        warn!("Invalid session ID {}: {}", existing_id, err.message());
1312                        return StreamableResponse::Error {
1313                            status: err.status_code(),
1314                            message: format!("Invalid or expired session: {}", err.message()),
1315                        }
1316                        .into_boxed_response(&context);
1317                    }
1318                    existing_id.clone()
1319                } else {
1320                    // Per MCP 2025-11-25 § Session Management: "Servers that require a session ID
1321                    // SHOULD respond to requests without an MCP-Session-Id header (other than
1322                    // initialization) with HTTP 400 Bad Request." This covers non-initialize,
1323                    // non-allowed-ping requests. The pre-init ping bypass at the top of this
1324                    // function still applies; with allow_unauthenticated_ping=false the ping
1325                    // rejection also lands here and correctly returns 400.
1326                    // Stale sessions are a different code path (→ 404). Auth failures live in
1327                    // OAuth middleware (→ 401).
1328                    let method_name = match &message {
1329                        JsonRpcMessage::Request(req) => &req.method,
1330                        JsonRpcMessage::Notification(notif) => &notif.method,
1331                    };
1332                    let request_id = match &message {
1333                        JsonRpcMessage::Request(req) => Some(req.id.clone()),
1334                        JsonRpcMessage::Notification(_) => None,
1335                    };
1336
1337                    // A 2026-07-28 client probes `server/discover` to detect the spec;
1338                    // this 2025-11-25 server has no such method. Answer with the trusted
1339                    // JSON-RPC method-not-found (-32601) at HTTP 200 so the bilingual
1340                    // client downgrades via its secure signal path — it deliberately does
1341                    // not treat a bare 400 as a version cue (a downgrade-attack vector).
1342                    if method_name == "server/discover" {
1343                        let not_found = turul_rpc::JsonRpcError::new(
1344                            request_id.clone(),
1345                            JsonRpcErrorObject::method_not_found("server/discover"),
1346                        );
1347                        let body =
1348                            serde_json::to_string(&not_found).unwrap_or_else(|_| "{}".to_string());
1349                        return Response::builder()
1350                            .status(StatusCode::OK)
1351                            .header(CONTENT_TYPE, "application/json")
1352                            .header("MCP-Protocol-Version", context.protocol_version.as_str())
1353                            .body(
1354                                Full::new(Bytes::from(body))
1355                                    .map_err(|never| match never {})
1356                                    .boxed_unsync(),
1357                            )
1358                            .unwrap();
1359                    }
1360
1361                    warn!("Missing session ID for method: {}", method_name);
1362
1363                    let error_response = turul_rpc::JsonRpcError::new(
1364                        request_id,
1365                        JsonRpcErrorObject::server_error(
1366                            -32001,
1367                            "Missing Mcp-Session-Id header. Call initialize first.",
1368                            None::<serde_json::Value>,
1369                        ),
1370                    );
1371
1372                    let error_json =
1373                        serde_json::to_string(&error_response).unwrap_or_else(|_| "{}".to_string());
1374
1375                    return Response::builder()
1376                        .status(StatusCode::BAD_REQUEST)
1377                        .header(CONTENT_TYPE, "application/json")
1378                        .header("MCP-Protocol-Version", context.protocol_version.as_str())
1379                        .body(
1380                            Full::new(Bytes::from(error_json))
1381                                .map_err(|never| match never {})
1382                                .boxed_unsync(),
1383                        )
1384                        .unwrap();
1385                }
1386            }
1387        };
1388
1389        // 2026-07-28: every request MUST carry a per-request `_meta`
1390        // (RequestMetaObject) with protocolVersion and clientCapabilities
1391        // (schema: RequestParams._meta is required). Missing/incomplete `_meta`
1392        // → -32602 (HTTP 400); a `_meta` protocolVersion that disagrees with the
1393        // (already validated) header is a header-validation failure → -32020
1394        // HeaderMismatch (HTTP 400).
1395        //
1396        // `clientInfo` is deliberately NOT checked: the schema marks it optional
1397        // and tells servers not to key behavior or security decisions on it, so a
1398        // client configured not to report itself MUST still be served. A present
1399        // but malformed value is rejected later, when the params deserialize.
1400        #[cfg(feature = "protocol-2026-07-28")]
1401        if let JsonRpcMessage::Request(req) = &message {
1402            let v = serde_json::to_value(req).unwrap_or(serde_json::Value::Null);
1403            let header_version = context.protocol_version.as_str();
1404            // (reason, is_header_mismatch)
1405            let reason = match v.get("params").and_then(|p| p.get("_meta")) {
1406                Some(meta) if meta.is_object() => {
1407                    let pv = meta
1408                        .get("io.modelcontextprotocol/protocolVersion")
1409                        .and_then(|x| x.as_str());
1410                    if pv.is_none() {
1411                        Some((
1412                            "missing required _meta.io.modelcontextprotocol/protocolVersion"
1413                                .to_string(),
1414                            false,
1415                        ))
1416                    } else if meta
1417                        .get("io.modelcontextprotocol/clientCapabilities")
1418                        .is_none()
1419                    {
1420                        Some((
1421                            "missing required _meta.io.modelcontextprotocol/clientCapabilities"
1422                                .to_string(),
1423                            false,
1424                        ))
1425                    } else if pv != Some(header_version) {
1426                        Some((
1427                            format!(
1428                                "_meta protocolVersion '{}' does not match MCP-Protocol-Version header '{}'",
1429                                pv.unwrap_or(""),
1430                                header_version
1431                            ),
1432                            true,
1433                        ))
1434                    } else {
1435                        None
1436                    }
1437                }
1438                _ => Some((
1439                    "missing required params._meta (RequestMetaObject)".to_string(),
1440                    false,
1441                )),
1442            };
1443            if let Some((reason, is_header_mismatch)) = reason {
1444                warn!("Rejecting 2026 request (method={}): {}", req.method, reason);
1445                let err_obj = if is_header_mismatch {
1446                    turul_rpc::error::JsonRpcErrorObject::server_error(
1447                        turul_mcp_protocol::headers::ERROR_CODE_HEADER_MISMATCH,
1448                        &format!("Header mismatch: {reason}"),
1449                        None::<serde_json::Value>,
1450                    )
1451                } else {
1452                    turul_rpc::error::JsonRpcErrorObject::invalid_params(&reason)
1453                };
1454                let err = turul_rpc::JsonRpcError::new(Some(req.id.clone()), err_obj);
1455                let body = serde_json::to_string(&err).unwrap_or_else(|_| "{}".to_string());
1456                return Response::builder()
1457                    .status(StatusCode::BAD_REQUEST)
1458                    .header(CONTENT_TYPE, "application/json")
1459                    .header("MCP-Protocol-Version", header_version)
1460                    .body(
1461                        Full::new(Bytes::from(body))
1462                            .map_err(|never| match never {})
1463                            .boxed_unsync(),
1464                    )
1465                    .unwrap();
1466            }
1467        }
1468
1469        // 2026-07-28: a request for a method this server does not implement →
1470        // HTTP 404 + JSON-RPC -32601 (the error body distinguishes this from a
1471        // legacy HTTP+SSE server's 404). Methods absent from the 2026 schema
1472        // (ping, initialize, tasks/*, logging/setLevel, resources/subscribe) are
1473        // simply never registered on a 2026 build, so they land here too.
1474        // subscriptions/listen is transport-handled below, not dispatcher-routed.
1475        #[cfg(feature = "protocol-2026-07-28")]
1476        if let JsonRpcMessage::Request(req) = &message
1477            && (req.method != turul_mcp_protocol::subscriptions::SUBSCRIPTIONS_LISTEN_METHOD
1478                || self.listen_unsupported)
1479            && !self.dispatcher.handlers.contains_key(&req.method)
1480            && self.dispatcher.default_handler.is_none()
1481        {
1482            debug!("Unknown 2026 method '{}' → 404 + -32601", req.method);
1483            // Versioning §Backward Compatibility: "A server that supports only
1484            // modern versions SHOULD name the protocol versions it supports in
1485            // any error it returns to an initialize request" — legacy clients
1486            // have no fall-forward mechanism; this may be their only
1487            // diagnostic.
1488            let mut error_object =
1489                turul_rpc::error::JsonRpcErrorObject::method_not_found(&req.method);
1490            if req.method == "initialize" {
1491                error_object.data = Some(serde_json::json!({
1492                    "supported": [turul_mcp_protocol::MCP_VERSION]
1493                }));
1494            }
1495            let err = turul_rpc::JsonRpcError::new(Some(req.id.clone()), error_object);
1496            let body = serde_json::to_string(&err).unwrap_or_else(|_| "{}".to_string());
1497            return Response::builder()
1498                .status(StatusCode::NOT_FOUND)
1499                .header(CONTENT_TYPE, "application/json")
1500                .header("MCP-Protocol-Version", context.protocol_version.as_str())
1501                .body(
1502                    Full::new(Bytes::from(body))
1503                        .map_err(|never| match never {})
1504                        .boxed_unsync(),
1505                )
1506                .unwrap();
1507        }
1508
1509        // The stateless core has no Mcp-Session-Id handshake, so a request is never
1510        // rejected for lacking a session. Mint an ephemeral per-request session so
1511        // the dispatch pipeline (which carries a SessionContext) proceeds unchanged.
1512        // The id is internal only: it is never read from the request (inbound
1513        // Mcp-Session-Id is ignored at parse time) and never written to
1514        // `context.session_id`, so no response ever echoes a session header.
1515        #[cfg(feature = "protocol-2026-07-28")]
1516        let session_id = match self
1517            .session_storage
1518            .create_session(self.server_capabilities.clone())
1519            .await
1520        {
1521            Ok(session_info) => session_info.session_id,
1522            Err(err) => {
1523                error!("Failed to create stateless session: {}", err);
1524                return StreamableResponse::Error {
1525                    status: StatusCode::INTERNAL_SERVER_ERROR,
1526                    message: "Failed to create session".to_string(),
1527                }
1528                .into_boxed_response(&context);
1529            }
1530        };
1531
1532        debug!("Processing streaming request with session: {}", session_id);
1533
1534        // Create streaming response using hyper::Body::channel()
1535        match message {
1536            JsonRpcMessage::Request(request) => {
1537                debug!(
1538                    "Processing streaming JSON-RPC request: method={}",
1539                    request.method
1540                );
1541
1542                // subscriptions/listen is a transport concern: its "response" is a
1543                // long-lived SSE stream, not a JSON-RPC result, so it never enters
1544                // the dispatcher.
1545                #[cfg(feature = "protocol-2026-07-28")]
1546                if request.method == turul_mcp_protocol::subscriptions::SUBSCRIPTIONS_LISTEN_METHOD
1547                {
1548                    return self
1549                        .handle_subscriptions_listen(request, session_id, context)
1550                        .await;
1551                }
1552
1553                self.create_streaming_response(
1554                    request,
1555                    session_id,
1556                    context,
1557                    pre_session_extensions.clone(),
1558                )
1559                .await
1560            }
1561            JsonRpcMessage::Notification(notification) => {
1562                debug!(
1563                    "Processing streaming JSON-RPC notification: method={}",
1564                    notification.method
1565                );
1566
1567                // Create session context with notification broadcaster for notifications
1568                use crate::notification_bridge::StreamManagerNotificationBroadcaster;
1569                use turul_rpc::SessionContext;
1570
1571                let broadcaster = Arc::new(StreamManagerNotificationBroadcaster::new(Arc::clone(
1572                    &self.stream_manager,
1573                )));
1574                let broadcaster_any = Arc::new(broadcaster) as Arc<dyn std::any::Any + Send + Sync>;
1575
1576                let session_context = SessionContext {
1577                    session_id: session_id.clone(),
1578                    metadata: std::collections::HashMap::new(),
1579                    broadcaster: Some(broadcaster_any),
1580                    timestamp: chrono::Utc::now().timestamp_millis() as u64,
1581                    extensions: std::collections::HashMap::new(),
1582                };
1583
1584                // Process notification through dispatcher (notifications don't return responses)
1585                let dispatcher = Arc::clone(&self.dispatcher);
1586                let notification_clone = notification.clone();
1587
1588                // `notifications/initialized` must be dispatched synchronously before
1589                // returning 202 — otherwise the next request (tools/list) can race
1590                // ahead of the is_initialized state write. Other notifications are
1591                // fire-and-forget and can be processed asynchronously.
1592                //
1593                // This ordering constraint belongs to the 2025-11-25 handshake only.
1594                // 2026-07-28 removed `initialize`/`notifications/initialized`, so there
1595                // is no initialization state to order against and every notification
1596                // takes the asynchronous path.
1597                //
1598                // Notifications always return 202 even on failure. If processing
1599                // fails, we log the error — the next request will fail with
1600                // "session not initialized" which points operators to the
1601                // initialization failure in logs.
1602                #[cfg(feature = "protocol-2025-11-25")]
1603                let dispatch_synchronously =
1604                    notification_clone.method == "notifications/initialized";
1605                #[cfg(not(feature = "protocol-2025-11-25"))]
1606                let dispatch_synchronously = false;
1607
1608                if dispatch_synchronously {
1609                    if let Err(e) = dispatcher
1610                        .handle_notification_with_context(notification_clone, Some(session_context))
1611                        .await
1612                    {
1613                        error!(
1614                            "Failed to process notifications/initialized: {}. \
1615                             Session will remain uninitialized — subsequent requests will fail.",
1616                            e
1617                        );
1618                    }
1619                } else {
1620                    tokio::spawn(async move {
1621                        if let Err(e) = dispatcher
1622                            .handle_notification_with_context(
1623                                notification_clone,
1624                                Some(session_context),
1625                            )
1626                            .await
1627                        {
1628                            error!("Failed to process notification: {}", e);
1629                        }
1630                    });
1631                }
1632
1633                // Return 202 Accepted with MCP headers. The stateless 2026 core
1634                // never echoes session ids; the 2025 lane keeps the session header.
1635                let builder = Response::builder()
1636                    .status(StatusCode::ACCEPTED)
1637                    .header("MCP-Protocol-Version", context.protocol_version.as_str());
1638                #[cfg(feature = "protocol-2025-11-25")]
1639                let builder = builder.header("Mcp-Session-Id", &session_id);
1640                builder
1641                    .body(
1642                        Full::new(Bytes::new())
1643                            .map_err(|never| match never {})
1644                            .boxed_unsync(),
1645                    )
1646                    .unwrap()
1647            }
1648        }
1649    }
1650
1651    /// Open a long-lived `subscriptions/listen` SSE stream (2026-07-28).
1652    ///
1653    /// Subscriptions pattern contract:
1654    /// - The acknowledgement (`notifications/subscriptions/acknowledged`) is the
1655    ///   FIRST message on the stream and echoes the honored filter subset —
1656    ///   requested types the server does not support are omitted.
1657    /// - Only opted-in notification types are delivered; `resources/updated` is
1658    ///   additionally filtered to the subscribed URIs.
1659    /// - Every delivered notification carries
1660    ///   `io.modelcontextprotocol/subscriptionId` in `_meta`, set to the JSON-RPC
1661    ///   id of the listen request.
1662    /// - Client-initiated cancellation (closing the stream) carries no JSON-RPC
1663    ///   result. Schema also defines `SubscriptionsListenResult` for a
1664    ///   server-initiated graceful teardown (e.g. shutdown) — this handler has
1665    ///   no such teardown path yet, so that result is never emitted; see
1666    ///   `turul_mcp_protocol::subscriptions::SubscriptionsListenResult`.
1667    #[cfg(feature = "protocol-2026-07-28")]
1668    async fn handle_subscriptions_listen(
1669        &self,
1670        request: turul_rpc::JsonRpcRequest,
1671        session_id: String,
1672        context: StreamableHttpContext,
1673    ) -> Response<http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>> {
1674        use http_body_util::StreamBody;
1675        use tokio_stream::StreamExt;
1676        use tokio_stream::wrappers::ReceiverStream;
1677        use turul_mcp_protocol::meta::META_KEY_SUBSCRIPTION_ID;
1678        use turul_mcp_protocol::subscriptions::{
1679            SUBSCRIPTIONS_ACKNOWLEDGED_METHOD, SubscriptionFilter, SubscriptionsListenRequestParams,
1680        };
1681        use turul_rpc::error::JsonRpcErrorObject;
1682
1683        let reject_400 = |id: turul_rpc::RequestId, err_obj: JsonRpcErrorObject, version: &str| {
1684            let err = turul_rpc::JsonRpcError::new(Some(id), err_obj);
1685            let body = serde_json::to_string(&err).unwrap_or_else(|_| "{}".to_string());
1686            Response::builder()
1687                .status(StatusCode::BAD_REQUEST)
1688                .header(CONTENT_TYPE, "application/json")
1689                .header("MCP-Protocol-Version", version)
1690                .body(
1691                    Full::new(Bytes::from(body))
1692                        .map_err(|never| match never {})
1693                        .boxed_unsync(),
1694                )
1695                .unwrap()
1696        };
1697
1698        // The response IS an SSE stream — the client must be able to consume one.
1699        if !context.wants_sse_stream {
1700            return reject_400(
1701                request.id.clone(),
1702                JsonRpcErrorObject::invalid_request(Some(serde_json::json!(
1703                    "subscriptions/listen requires Accept: text/event-stream"
1704                ))),
1705                context.protocol_version.as_str(),
1706            );
1707        }
1708
1709        // Typed params parse (the generic 2026 `_meta` gate already ran upstream).
1710        let params_value = request
1711            .params
1712            .as_ref()
1713            .map(|p| serde_json::to_value(p).unwrap_or(serde_json::Value::Null))
1714            .unwrap_or(serde_json::Value::Null);
1715        let parsed: SubscriptionsListenRequestParams = match serde_json::from_value(params_value) {
1716            Ok(p) => p,
1717            Err(e) => {
1718                return reject_400(
1719                    request.id.clone(),
1720                    JsonRpcErrorObject::invalid_params(&format!(
1721                        "invalid subscriptions/listen params: {e}"
1722                    )),
1723                    context.protocol_version.as_str(),
1724                );
1725            }
1726        };
1727
1728        // Honored subset: keep a requested type only when the server actually has
1729        // the corresponding feature surface (capability section present).
1730        let caps = &self.server_capabilities;
1731        let requested = parsed.notifications;
1732        let honored = SubscriptionFilter {
1733            tools_list_changed: requested
1734                .tools_list_changed
1735                .filter(|&v| v && caps.tools.is_some()),
1736            prompts_list_changed: requested
1737                .prompts_list_changed
1738                .filter(|&v| v && caps.prompts.is_some()),
1739            resources_list_changed: requested
1740                .resources_list_changed
1741                .filter(|&v| v && caps.resources.is_some()),
1742            resource_subscriptions: requested
1743                .resource_subscriptions
1744                .filter(|uris| !uris.is_empty() && caps.resources.is_some()),
1745        };
1746
1747        // Tasks-extension filter addition (`taskIds`): rides the same
1748        // `notifications` object but is not a core-schema field, so it is read
1749        // from the raw params. Honored only when the server advertises the
1750        // extension; when it does, tasks.md §Task Status Notifications requires
1751        // `-32021` for a client that asks without declaring it.
1752        let tasks_extension_advertised = turul_mcp_ext_tasks::declared_by_server(caps);
1753        let raw_params = request
1754            .params
1755            .as_ref()
1756            .and_then(|p| serde_json::to_value(p).ok());
1757        let requested_task_ids: Vec<String> = raw_params
1758            .as_ref()
1759            .and_then(|v| v.pointer("/notifications/taskIds"))
1760            .and_then(|v| v.as_array())
1761            .map(|ids| {
1762                ids.iter()
1763                    .filter_map(|i| i.as_str().map(String::from))
1764                    .collect()
1765            })
1766            .unwrap_or_default();
1767        if tasks_extension_advertised && !requested_task_ids.is_empty() {
1768            let client_caps = raw_params
1769                .as_ref()
1770                .and_then(|v| v.get("_meta"))
1771                .and_then(|m| m.get(turul_mcp_protocol::meta::META_KEY_CLIENT_CAPABILITIES))
1772                .cloned()
1773                .and_then(|c| serde_json::from_value(c).ok())
1774                .unwrap_or_default();
1775            if !turul_mcp_ext_tasks::declared_by_client(&client_caps) {
1776                return reject_400(
1777                    request.id.clone(),
1778                    turul_mcp_ext_tasks::missing_capability_error().to_error_object(),
1779                    context.protocol_version.as_str(),
1780                );
1781            }
1782        }
1783        let honored_task_ids: Option<Vec<String>> =
1784            Some(requested_task_ids).filter(|ids| !ids.is_empty() && tasks_extension_advertised);
1785
1786        // Gate delivery at the broadcast layer: the subscription registry entry is
1787        // created even when empty, so an empty filter delivers nothing (the
1788        // registry's no-entry default is allow-all).
1789        let mut allowed_types = Vec::new();
1790        if honored.tools_list_changed == Some(true) {
1791            allowed_types.push("notifications/tools/list_changed".to_string());
1792        }
1793        if honored.prompts_list_changed == Some(true) {
1794            allowed_types.push("notifications/prompts/list_changed".to_string());
1795        }
1796        if honored.resources_list_changed == Some(true) {
1797            allowed_types.push("notifications/resources/list_changed".to_string());
1798        }
1799        if honored.resource_subscriptions.is_some() {
1800            allowed_types.push("notifications/resources/updated".to_string());
1801        }
1802        if honored_task_ids.is_some() {
1803            allowed_types.push("notifications/tasks".to_string());
1804        }
1805        self.stream_manager
1806            .subscribe_to_notifications(&session_id, allowed_types)
1807            .await;
1808
1809        let connection_id = format!("listen-{}", uuid::Uuid::now_v7().as_simple());
1810        let (tx, rx) = tokio::sync::mpsc::channel::<turul_mcp_session_storage::SseEvent>(64);
1811        if let Err(e) = self
1812            .stream_manager
1813            .register_streaming_connection(&session_id, connection_id, tx)
1814            .await
1815        {
1816            error!("Failed to register subscriptions/listen connection: {}", e);
1817            return StreamableResponse::Error {
1818                status: StatusCode::INTERNAL_SERVER_ERROR,
1819                message: "Failed to register subscription stream".to_string(),
1820            }
1821            .into_boxed_response(&context);
1822        }
1823
1824        // The subscription id is the JSON-RPC id of the listen request.
1825        let subscription_id = request.id.to_string();
1826
1827        // Acknowledgement — wire-complete JSON-RPC notification, first frame.
1828        let mut ack_params = std::collections::HashMap::new();
1829        let mut honored_value = serde_json::to_value(&honored).unwrap_or_default();
1830        if let (Some(obj), Some(ids)) = (honored_value.as_object_mut(), honored_task_ids.as_ref()) {
1831            obj.insert("taskIds".to_string(), serde_json::json!(ids));
1832        }
1833        ack_params.insert("notifications".to_string(), honored_value);
1834        ack_params.insert(
1835            "_meta".to_string(),
1836            serde_json::json!({ META_KEY_SUBSCRIPTION_ID: subscription_id }),
1837        );
1838        let ack = turul_rpc::JsonRpcNotification::new_with_object_params(
1839            SUBSCRIPTIONS_ACKNOWLEDGED_METHOD.to_string(),
1840            ack_params,
1841        );
1842        let ack_frame = format!(
1843            "event: message\ndata: {}\n\n",
1844            serde_json::to_string(&ack).unwrap_or_else(|_| "{}".to_string())
1845        );
1846
1847        // Live tail: filter to the honored types (the broadcast-layer gate already
1848        // drops the rest — this is the per-URI filter plus defense in depth) and
1849        // stamp the subscription id into every delivered notification.
1850        let filter = honored;
1851        let filter_task_ids = honored_task_ids;
1852        let sub_id = subscription_id;
1853        let live = ReceiverStream::new(rx).filter_map(move |ev| {
1854            let mut data = ev.data;
1855            let method = data
1856                .get("method")
1857                .and_then(|m| m.as_str())
1858                .unwrap_or_default();
1859            let allowed = match method {
1860                "notifications/tools/list_changed" => filter.tools_list_changed == Some(true),
1861                "notifications/prompts/list_changed" => filter.prompts_list_changed == Some(true),
1862                "notifications/resources/list_changed" => {
1863                    filter.resources_list_changed == Some(true)
1864                }
1865                "notifications/resources/updated" => {
1866                    let uri = data
1867                        .get("params")
1868                        .and_then(|p| p.get("uri"))
1869                        .and_then(|u| u.as_str());
1870                    match (uri, &filter.resource_subscriptions) {
1871                        (Some(u), Some(uris)) => uris.iter().any(|x| x == u),
1872                        _ => false,
1873                    }
1874                }
1875                // Tasks extension (SEP-2663): per-taskId delivery.
1876                "notifications/tasks" => {
1877                    let task_id = data
1878                        .get("params")
1879                        .and_then(|p| p.get("taskId"))
1880                        .and_then(|t| t.as_str());
1881                    match (task_id, &filter_task_ids) {
1882                        (Some(id), Some(ids)) => ids.iter().any(|x| x == id),
1883                        _ => false,
1884                    }
1885                }
1886                _ => false,
1887            };
1888            if !allowed {
1889                return None;
1890            }
1891            if let Some(obj) = data.as_object_mut() {
1892                let params = obj
1893                    .entry("params")
1894                    .or_insert_with(|| serde_json::Value::Object(Default::default()));
1895                if let Some(pobj) = params.as_object_mut() {
1896                    let meta = pobj
1897                        .entry("_meta")
1898                        .or_insert_with(|| serde_json::Value::Object(Default::default()));
1899                    if let Some(mobj) = meta.as_object_mut() {
1900                        mobj.insert(
1901                            META_KEY_SUBSCRIPTION_ID.to_string(),
1902                            serde_json::Value::String(sub_id.clone()),
1903                        );
1904                    }
1905                }
1906            }
1907            Some(Ok::<_, hyper::Error>(http_body::Frame::data(Bytes::from(
1908                format!("id: {}\nevent: message\ndata: {}\n\n", ev.id, data),
1909            ))))
1910        });
1911
1912        let ack_stream = tokio_stream::once(Ok::<_, hyper::Error>(http_body::Frame::data(
1913            Bytes::from(ack_frame),
1914        )));
1915        let body = StreamBody::new(ack_stream.chain(live));
1916
1917        Response::builder()
1918            .status(StatusCode::OK)
1919            .header(CONTENT_TYPE, "text/event-stream")
1920            .header("Cache-Control", "no-cache")
1921            .header("X-Accel-Buffering", "no")
1922            .header("MCP-Protocol-Version", context.protocol_version.as_str())
1923            .body(http_body_util::BodyExt::boxed_unsync(body))
1924            .unwrap()
1925    }
1926
1927    /// Create a streaming response using hyper::Body::channel()
1928    /// This enables true progressive responses with Transfer-Encoding: chunked
1929    async fn create_streaming_response(
1930        &self,
1931        request: turul_rpc::JsonRpcRequest,
1932        session_id: String,
1933        context: StreamableHttpContext,
1934        pre_session_extensions: Option<HashMap<String, serde_json::Value>>,
1935    ) -> Response<http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>> {
1936        debug!(
1937            "Creating streaming response for method: {}, session: {}",
1938            request.method, session_id
1939        );
1940        // Create channel for streaming response
1941        use http_body_util::StreamBody;
1942        use tokio_stream::StreamExt;
1943        use tokio_stream::wrappers::UnboundedReceiverStream; // Add StreamExt for map method
1944
1945        let (tx, rx) = tokio::sync::mpsc::unbounded_channel::<Result<bytes::Bytes, hyper::Error>>();
1946        let body_stream =
1947            UnboundedReceiverStream::new(rx).map(|item| item.map(http_body::Frame::data));
1948        let body = StreamBody::new(body_stream);
1949
1950        // Create session context with notification broadcaster (same pattern as SessionMcpHandler)
1951        use crate::notification_bridge::{
1952            SharedNotificationBroadcaster, StreamManagerNotificationBroadcaster,
1953        };
1954        use turul_rpc::SessionContext;
1955
1956        let broadcaster: SharedNotificationBroadcaster = Arc::new(
1957            StreamManagerNotificationBroadcaster::new(Arc::clone(&self.stream_manager)),
1958        );
1959        let broadcaster_any = Arc::new(broadcaster) as Arc<dyn std::any::Any + Send + Sync>;
1960
1961        // 2026: surface the request headers to handlers — Mcp-Param-* validation
1962        // happens at the tools/call handler, the only layer that knows the
1963        // tool's inputSchema annotations.
1964        #[cfg(feature = "protocol-2026-07-28")]
1965        let handler_metadata: std::collections::HashMap<String, serde_json::Value> = context
1966            .headers
1967            .iter()
1968            .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
1969            .collect();
1970        #[cfg(feature = "protocol-2025-11-25")]
1971        let handler_metadata = std::collections::HashMap::new();
1972
1973        let session_context = SessionContext {
1974            session_id: session_id.clone(),
1975            metadata: handler_metadata,
1976            broadcaster: Some(broadcaster_any),
1977            timestamp: chrono::Utc::now().timestamp_millis() as u64,
1978            extensions: std::collections::HashMap::new(),
1979        };
1980
1981        // Register streaming POST connection with StreamManager for progress events
1982        // Transport policy: prefer JSON for non-streaming methods when client accepts both
1983        let wants_sse = context.should_use_sse(&request);
1984        let connection_id = format!("post-{}", uuid::Uuid::now_v7().as_simple());
1985
1986        // 2026 + JSON framing: dispatch inline so the HTTP status can reflect
1987        // the JSON-RPC outcome. MissingRequiredClientCapabilityError (-32021)
1988        // MUST ride HTTP 400 per its schema; the chunked-channel path below
1989        // commits 200 before dispatch completes and cannot retro-status.
1990        // (SSE-framed responses inherently stay 200 — errors ride the stream.)
1991        #[cfg(feature = "protocol-2026-07-28")]
1992        if !wants_sse {
1993            let (response, _) = self
1994                .run_middleware_and_dispatch(
1995                    request,
1996                    context.headers.clone(),
1997                    Some(session_context),
1998                    pre_session_extensions,
1999                )
2000                .await;
2001            let status = match &response {
2002                // -32021 MissingRequiredClientCapability and -32020
2003                // HeaderMismatch both mandate HTTP 400.
2004                turul_rpc::JsonRpcResponse::Error(err)
2005                    if matches!(
2006                        err.error.code,
2007                        turul_mcp_protocol::headers::ERROR_CODE_HEADER_MISMATCH | -32021
2008                    ) =>
2009                {
2010                    StatusCode::BAD_REQUEST
2011                }
2012                _ => StatusCode::OK,
2013            };
2014            let body_json = serde_json::to_string(&response).unwrap_or_else(|_| "{}".to_string());
2015            let mut http_response = Response::builder()
2016                .status(status)
2017                .header(CONTENT_TYPE, "application/json")
2018                .body(
2019                    Full::new(Bytes::from(body_json))
2020                        .map_err(|never| match never {})
2021                        .boxed_unsync(),
2022                )
2023                .unwrap();
2024            let mcp_headers = context.response_headers();
2025            for (key, value) in mcp_headers.iter() {
2026                http_response.headers_mut().insert(key, value.clone());
2027            }
2028            return http_response;
2029        }
2030
2031        // Progress forwarding only for SSE clients
2032        let (shutdown_tx, completion_rx) = if wants_sse {
2033            // Create shutdown signal for progress task (critical for no-progress-events case)
2034            let (shutdown_tx, mut shutdown_rx) = tokio::sync::oneshot::channel::<()>();
2035            let (completion_tx, completion_rx) = tokio::sync::oneshot::channel::<()>();
2036            let (progress_tx, mut progress_rx) = tokio::sync::mpsc::channel(100);
2037
2038            // Register with StreamManager to receive progress events
2039            let registration_result = self
2040                .stream_manager
2041                .register_streaming_connection(&session_id, connection_id.clone(), progress_tx)
2042                .await;
2043
2044            if let Err(e) = registration_result {
2045                error!("Failed to register POST streaming connection: {}", e);
2046                // Continue without streaming - will still work as regular POST
2047                (None, None)
2048            } else {
2049                debug!(
2050                    "Registered SSE streaming connection for session: {}",
2051                    session_id
2052                );
2053
2054                // Spawn task to forward progress events to HTTP response
2055                let sender_clone = tx.clone();
2056                let session_id_clone = session_id.clone();
2057                let connection_id_clone = connection_id.clone();
2058                let stream_manager_clone = Arc::clone(&self.stream_manager);
2059
2060                tokio::spawn(async move {
2061                    debug!(
2062                        "Starting progress forwarding task for session: {}",
2063                        session_id_clone
2064                    );
2065
2066                    // No replay needed: the POST SSE connection is registered BEFORE
2067                    // dispatch, so all events emitted during request execution are
2068                    // delivered live via progress_tx. Replay would double-deliver them.
2069                    // (GET SSE resumability uses Last-Event-ID separately.)
2070
2071                    // CRITICAL: Use select to handle both progress events AND explicit shutdown
2072                    loop {
2073                        debug!(
2074                            "🔍 Progress task entering select loop for session: {}",
2075                            session_id_clone
2076                        );
2077                        tokio::select! {
2078                            // Handle progress events if they arrive
2079                            maybe_event = progress_rx.recv() => {
2080                                debug!("🔍 Progress task: progress_rx.recv() branch fired for session: {}", session_id_clone);
2081                                match maybe_event {
2082                                    Some(sse_event) => {
2083                                        debug!("🔍 Forwarding progress event to POST response: session={}, event={:?}", session_id_clone, sse_event.event_type);
2084
2085                                        // Convert SSE event to fully-formatted SSE chunk with event metadata
2086                                        let sse_chunk = sse_event.format();
2087
2088                                        if let Err(e) = sender_clone.send(Ok(Bytes::from(sse_chunk))) {
2089                                            error!("Failed to send progress event to POST response: {}", e);
2090                                            break;
2091                                        }
2092                                    }
2093                                    None => {
2094                                        // Progress channel closed naturally
2095                                        debug!("🔍 Progress channel closed naturally for session: {}", session_id_clone);
2096                                        break;
2097                                    }
2098                                }
2099                            }
2100                            // Handle explicit shutdown signal from main task
2101                            _ = &mut shutdown_rx => {
2102                                debug!("🔍 Progress task: shutdown_rx branch fired! Received explicit shutdown signal for session: {}", session_id_clone);
2103                                // Flush events already queued: request-scoped
2104                                // notifications were emitted (and awaited)
2105                                // before the tool returned, so they must reach
2106                                // the wire ahead of the final response frame.
2107                                while let Ok(sse_event) = progress_rx.try_recv() {
2108                                    let sse_chunk = sse_event.format();
2109                                    if sender_clone.send(Ok(Bytes::from(sse_chunk))).is_err() {
2110                                        break;
2111                                    }
2112                                }
2113                                break;
2114                            }
2115                        }
2116                    }
2117
2118                    // Clean up: Unregister from StreamManager to close progress_tx
2119                    debug!(
2120                        "Progress task unregistering connection for session: {}",
2121                        session_id_clone
2122                    );
2123                    stream_manager_clone
2124                        .unregister_connection(&session_id_clone, &connection_id_clone)
2125                        .await;
2126
2127                    // CRITICAL: Drop the sender to ensure stream can close
2128                    debug!(
2129                        "🔍 Progress task: dropping sender_clone for session: {}",
2130                        session_id_clone
2131                    );
2132                    drop(sender_clone);
2133
2134                    // Signal completion to main task
2135                    debug!(
2136                        "🔍 Progress task: signaling completion for session: {}",
2137                        session_id_clone
2138                    );
2139                    if completion_tx.send(()).is_err() {
2140                        debug!(
2141                            "🔍 Progress task: main task already dropped completion_rx for session: {}",
2142                            session_id_clone
2143                        );
2144                    }
2145
2146                    debug!(
2147                        "🔍 Progress forwarding task completed for session: {}",
2148                        session_id_clone
2149                    );
2150                });
2151
2152                // Return shutdown_tx and completion_rx for later use
2153                (Some(shutdown_tx), Some(completion_rx))
2154            }
2155        } else {
2156            // No SSE, no shutdown signal needed
2157            (None, None)
2158        };
2159
2160        // Spawn task to handle streaming dispatch
2161        let request_id = request.id.clone();
2162        let sender = tx; // Rename for clarity
2163
2164        // Capture headers for middleware (clone before move into spawn)
2165        let headers = context.headers.clone();
2166        let self_clone = self.clone();
2167
2168        tokio::spawn(async move {
2169            debug!(
2170                "Spawning streaming task for request ID: {:?}, wants_sse: {}",
2171                request_id, wants_sse
2172            );
2173
2174            // Process the request through the middleware pipeline, racing the
2175            // client connection. Streamable HTTP §Cancellation: "Closing the
2176            // SSE response stream MUST be treated by the server as
2177            // cancellation of that request. The server SHOULD stop work …
2178            // and MUST NOT send any further messages for it." Dropping the
2179            // dispatch future stops the handler at its next await point;
2180            // returning here guarantees nothing further is sent.
2181            let mut shutdown_tx = shutdown_tx;
2182            let dispatch = self_clone.run_middleware_and_dispatch(
2183                request,
2184                headers,
2185                Some(session_context),
2186                pre_session_extensions,
2187            );
2188            tokio::pin!(dispatch);
2189            let (response, _) = tokio::select! {
2190                result = &mut dispatch => result,
2191                _ = sender.closed() => {
2192                    debug!(
2193                        "Client closed the response stream — cancelling request {:?}",
2194                        request_id
2195                    );
2196                    if let Some(shutdown_tx) = shutdown_tx.take() {
2197                        let _ = shutdown_tx.send(());
2198                    }
2199                    return;
2200                }
2201            };
2202
2203            // Send final result - format depends on client type
2204            if wants_sse {
2205                // For SSE clients, send as streaming frame with SSE framing
2206                let final_frame = match response {
2207                    turul_rpc::JsonRpcResponse::Success(resp) => {
2208                        turul_rpc::JsonRpcFrame::FinalResult {
2209                            request_id: request_id.clone(),
2210                            result: match resp.result {
2211                                turul_rpc::response::ResponseResult::Success(val) => val,
2212                                turul_rpc::response::ResponseResult::Null => {
2213                                    serde_json::Value::Null
2214                                }
2215                            },
2216                        }
2217                    }
2218                    turul_rpc::JsonRpcResponse::Error(err) => turul_rpc::JsonRpcFrame::Error {
2219                        request_id: request_id.clone(),
2220                        error: turul_rpc::error::JsonRpcErrorObject {
2221                            code: err.error.code,
2222                            message: err.error.message,
2223                            data: err.error.data,
2224                        },
2225                    },
2226                };
2227
2228                let final_json = final_frame.to_json();
2229                // SSE framing: data: {json}\n\n
2230                let final_chunk =
2231                    format!("data: {}\n\n", serde_json::to_string(&final_json).unwrap());
2232
2233                // Shut down (and flush) the progress forwarding task BEFORE the
2234                // final frame goes out: request-scoped notifications precede the
2235                // final response on the wire, and the final response terminates
2236                // the stream.
2237                if let Some(shutdown_tx) = shutdown_tx.take() {
2238                    debug!(
2239                        "🔍 Main task sending shutdown signal to progress task for request: {:?}",
2240                        request_id
2241                    );
2242                    match shutdown_tx.send(()) {
2243                        Ok(()) => {
2244                            debug!(
2245                                "🔍 Main task: shutdown signal sent successfully for request: {:?}",
2246                                request_id
2247                            );
2248
2249                            // CRITICAL: Wait for progress task to complete and drop its sender_clone
2250                            // This ensures both senders are dropped before the stream tries to close
2251                            if let Some(completion_rx) = completion_rx {
2252                                match tokio::time::timeout(
2253                                    tokio::time::Duration::from_millis(100),
2254                                    completion_rx,
2255                                )
2256                                .await
2257                                {
2258                                    Ok(Ok(())) => {
2259                                        debug!(
2260                                            "🔍 Main task: progress task completed successfully for request: {:?}",
2261                                            request_id
2262                                        );
2263                                    }
2264                                    Ok(Err(_)) => {
2265                                        debug!(
2266                                            "🔍 Main task: progress task completion signal dropped for request: {:?}",
2267                                            request_id
2268                                        );
2269                                    }
2270                                    Err(_) => {
2271                                        debug!(
2272                                            "🔍 Main task: progress task completion timeout for request: {:?}",
2273                                            request_id
2274                                        );
2275                                    }
2276                                }
2277                            }
2278                        }
2279                        Err(_) => {
2280                            debug!(
2281                                "🔍 Main task: progress task already completed (shutdown_rx dropped) for request: {:?}",
2282                                request_id
2283                            );
2284                        }
2285                    }
2286                } else {
2287                    debug!(
2288                        "🔍 Main task: no shutdown_tx available (not SSE client) for request: {:?}",
2289                        request_id
2290                    );
2291                }
2292
2293                if let Err(err) = sender.send(Ok(Bytes::from(final_chunk))) {
2294                    error!("Failed to send SSE final chunk: {}", err);
2295                }
2296            } else {
2297                // For JSON-only clients, send as regular JSON-RPC response (no streaming frames)
2298                let final_json = serde_json::to_string(&response).unwrap();
2299
2300                if let Err(err) = sender.send(Ok(Bytes::from(final_json))) {
2301                    error!("Failed to send final JSON response: {}", err);
2302                }
2303            }
2304
2305            debug!(
2306                "🔍 Main task: streaming task completed for request ID: {:?}",
2307                request_id
2308            );
2309
2310            // CRITICAL: Drop the sender to close the stream and signal completion to client
2311            debug!(
2312                "🔍 Main task: dropping main sender for request ID: {:?}",
2313                request_id
2314            );
2315            drop(sender);
2316        });
2317
2318        // Build response with MCP headers merged from context
2319        // Content-Type must match the framing decision made by wants_sse above
2320        let content_type = if wants_sse {
2321            "text/event-stream"
2322        } else {
2323            "application/json"
2324        };
2325
2326        let mut response = Response::builder()
2327            .status(StatusCode::OK)
2328            .header(CONTENT_TYPE, content_type)
2329            .header("Transfer-Encoding", "chunked") // Key: Enable chunked encoding!
2330            // nginx-family proxies buffer streaming responses by default,
2331            // which holds SSE frames back from the client until the stream
2332            // closes — defeating request-scoped notifications.
2333            .header("X-Accel-Buffering", "no")
2334            .header("Cache-Control", "no-cache")
2335            .body(http_body_util::BodyExt::boxed_unsync(body))
2336            .unwrap();
2337
2338        // Merge MCP headers from context.response_headers()
2339        let mcp_headers = context.response_headers();
2340        for (key, value) in mcp_headers.iter() {
2341            response.headers_mut().insert(key, value.clone());
2342        }
2343
2344        response
2345    }
2346
2347    /// Handles a POST request: the unified handler for all client messages.
2348    /// Processes JSON-RPC requests, notifications, and responses
2349    /// Server decides whether to respond with JSON or SSE stream based on message type
2350    async fn handle_client_message<T>(
2351        &self,
2352        req: Request<T>,
2353        context: StreamableHttpContext,
2354    ) -> Response<http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>>
2355    where
2356        T: Body + Send + 'static,
2357    {
2358        debug!("Handling client message via POST (MCP 2025-11-25)");
2359
2360        // Reject POST if accepts_stream_frames is false
2361        // Per MCP spec: "Include Accept header with application/json and text/event-stream"
2362        if !context.accepts_stream_frames {
2363            warn!("Client POST missing application/json in Accept header");
2364            return StreamableResponse::Error {
2365                status: StatusCode::BAD_REQUEST,
2366                message: "Accept header must include application/json, text/event-stream, or */*"
2367                    .to_string(),
2368            }
2369            .into_boxed_response(&context);
2370        }
2371
2372        // Check content type
2373        let content_type = req
2374            .headers()
2375            .get(CONTENT_TYPE)
2376            .and_then(|ct| ct.to_str().ok())
2377            .map(normalize_header_value)
2378            .unwrap_or_default();
2379        if !content_type.starts_with("application/json") {
2380            warn!("Invalid content type for POST: {}", content_type);
2381            return StreamableResponse::Error {
2382                status: StatusCode::BAD_REQUEST,
2383                message: "Content-Type must be application/json".to_string(),
2384            }
2385            .into_boxed_response(&context);
2386        }
2387
2388        // Use streaming for all POST requests, but adapt based on client needs
2389        // For simple JSON clients, streaming will send only the final result (no progress frames)
2390        debug!("Using streaming POST handler for all requests");
2391        return self.handle_post_streamable_http(req, context).await;
2392    }
2393
2394    /// Run middleware stack around dispatcher call
2395    ///
2396    /// This helper:
2397    /// 1. Fast-paths when middleware stack is empty
2398    /// 2. Normalizes headers to lowercase String keys
2399    /// 3. Builds RequestContext with method + headers
2400    /// 4. Executes before_dispatch
2401    /// 5. Applies or stashes SessionInjection
2402    /// 6. Calls dispatcher
2403    /// 7. Executes after_dispatch
2404    ///
2405    /// Returns (JsonRpcMessage, Option<SessionInjection>) where the injection
2406    /// is Some when session was None (initialize case) and needs to be applied
2407    /// after session creation.
2408    ///
2409    /// Every successful result leaving this handler is stamped with the server's
2410    /// identity here — the one place it happens, so the JSON, SSE and
2411    /// subscription-close paths cannot drift apart. The inner function has
2412    /// several tails; wrapping it keeps the stamp from being duplicated per-tail.
2413    async fn run_middleware_and_dispatch(
2414        &self,
2415        request: turul_rpc::JsonRpcRequest,
2416        headers: HashMap<String, String>,
2417        session: Option<turul_rpc::SessionContext>,
2418        pre_session_extensions: Option<HashMap<String, serde_json::Value>>,
2419    ) -> (
2420        turul_rpc::JsonRpcResponse,
2421        Option<crate::middleware::SessionInjection>,
2422    ) {
2423        let (response, injection) = self
2424            .run_middleware_and_dispatch_inner(request, headers, session, pre_session_extensions)
2425            .await;
2426        #[cfg(feature = "protocol-2026-07-28")]
2427        let response = self.stamp_server_info(response);
2428        (response, injection)
2429    }
2430
2431    /// Add `_meta.io.modelcontextprotocol/serverInfo` to a successful result.
2432    ///
2433    /// Scope is deliberately narrow: only the top-level object result of a
2434    /// success response. Nested `_meta` objects are plain `MetaObject`s in the
2435    /// schema, error responses carry no result at all, and results produced by
2436    /// the *client* (sampling, elicitation, roots) never pass through here. A
2437    /// handler that already set the key keeps its value.
2438    #[cfg(feature = "protocol-2026-07-28")]
2439    fn stamp_server_info(
2440        &self,
2441        response: turul_rpc::JsonRpcResponse,
2442    ) -> turul_rpc::JsonRpcResponse {
2443        let Some(info) = self.server_info.as_ref() else {
2444            return response;
2445        };
2446        let turul_rpc::JsonRpcResponse::Success(mut resp) = response else {
2447            return response;
2448        };
2449
2450        if let turul_rpc::response::ResponseResult::Success(serde_json::Value::Object(
2451            ref mut result,
2452        )) = resp.result
2453        {
2454            let meta = result
2455                .entry("_meta")
2456                .or_insert_with(|| serde_json::Value::Object(Default::default()));
2457            if let Some(meta) = meta.as_object_mut()
2458                && !meta.contains_key(turul_mcp_protocol::meta::META_KEY_SERVER_INFO)
2459                && let Ok(value) = serde_json::to_value(info)
2460            {
2461                meta.insert(
2462                    turul_mcp_protocol::meta::META_KEY_SERVER_INFO.to_string(),
2463                    value,
2464                );
2465            }
2466        }
2467        turul_rpc::JsonRpcResponse::Success(resp)
2468    }
2469
2470    async fn run_middleware_and_dispatch_inner(
2471        &self,
2472        request: turul_rpc::JsonRpcRequest,
2473        headers: HashMap<String, String>,
2474        session: Option<turul_rpc::SessionContext>,
2475        pre_session_extensions: Option<HashMap<String, serde_json::Value>>,
2476    ) -> (
2477        turul_rpc::JsonRpcResponse,
2478        Option<crate::middleware::SessionInjection>,
2479    ) {
2480        // Fast path: if middleware stack is empty, dispatch directly
2481        if self.middleware_stack.is_empty() {
2482            let result = if let Some(session_ctx) = session {
2483                self.dispatcher
2484                    .handle_request_with_context(request, session_ctx)
2485                    .await
2486            } else {
2487                self.dispatcher.handle_request(request).await
2488            };
2489            return (result, None);
2490        }
2491
2492        // Normalize headers: lowercase String keys
2493        let normalized_headers: HashMap<String, String> = headers
2494            .iter()
2495            .map(|(k, v)| (k.to_lowercase(), v.clone()))
2496            .collect();
2497
2498        // Build RequestContext with method and headers
2499        let method = request.method.clone();
2500
2501        // Convert params to Option<Value>
2502        let params = request.params.clone().map(|p| match p {
2503            turul_rpc::RequestParams::Object(map) => {
2504                serde_json::Value::Object(map.into_iter().collect())
2505            }
2506            turul_rpc::RequestParams::Array(arr) => serde_json::Value::Array(arr),
2507        });
2508        let mut ctx = crate::middleware::RequestContext::new(&method, params);
2509
2510        // Seed extensions from pre-session phase (auth claims etc.)
2511        if let Some(ext) = pre_session_extensions {
2512            for (k, v) in ext {
2513                ctx.set_extension(k, v);
2514            }
2515        }
2516
2517        for (k, v) in normalized_headers {
2518            // Bearer scheme NEVER enters metadata, even if token is malformed
2519            if k == "authorization" && is_bearer_scheme(&v) {
2520                continue;
2521            }
2522            ctx.add_metadata(k, serde_json::json!(v));
2523        }
2524
2525        // Create SessionView adapter if session is available
2526        let session_view = session.as_ref().map(|s| {
2527            crate::middleware::StorageBackedSessionView::new(
2528                s.session_id.clone(),
2529                Arc::clone(&self.session_storage),
2530            )
2531        });
2532
2533        // Execute before_dispatch with SessionView (None if sessionless)
2534        let injection = match self
2535            .middleware_stack
2536            .execute_before(
2537                &mut ctx,
2538                session_view.as_ref().map(|v| v as &dyn SessionView),
2539            )
2540            .await
2541        {
2542            Ok(inj) => inj,
2543            Err(err) => {
2544                return (
2545                    crate::middleware::error::map_middleware_error_to_jsonrpc(err, request.id),
2546                    None,
2547                );
2548            }
2549        };
2550
2551        // Apply injection to session storage (only if session exists)
2552        if !injection.is_empty()
2553            && let Some(ref sv) = session_view
2554        {
2555            for (key, value) in injection.state() {
2556                if let Err(e) = sv.set_state(key, value.clone()).await {
2557                    tracing::warn!("Failed to apply injection state '{}': {}", key, e);
2558                }
2559            }
2560            for (key, value) in injection.metadata() {
2561                if let Err(e) = sv.set_metadata(key, value.clone()).await {
2562                    tracing::warn!("Failed to apply injection metadata '{}': {}", key, e);
2563                }
2564            }
2565        }
2566
2567        // Thread extensions from RequestContext → JSON-RPC SessionContext
2568        let session = session.map(|mut s| {
2569            s.extensions = ctx.extensions().clone();
2570            s
2571        });
2572
2573        // Save request ID before dispatch consumes the request
2574        let request_id = request.id.clone();
2575
2576        // Dispatch the request
2577        let result = if let Some(session_ctx) = session {
2578            self.dispatcher
2579                .handle_request_with_context(request, session_ctx)
2580                .await
2581        } else {
2582            self.dispatcher.handle_request(request).await
2583        };
2584
2585        // Execute after_dispatch
2586        let mut dispatcher_result = match &result {
2587            turul_rpc::JsonRpcResponse::Success(resp) => match &resp.result {
2588                turul_rpc::response::ResponseResult::Success(val) => {
2589                    crate::middleware::DispatcherResult::Success(val.clone())
2590                }
2591                turul_rpc::response::ResponseResult::Null => {
2592                    crate::middleware::DispatcherResult::Success(serde_json::Value::Null)
2593                }
2594            },
2595            turul_rpc::JsonRpcResponse::Error(err) => {
2596                crate::middleware::DispatcherResult::Error(err.error.message.clone())
2597            }
2598        };
2599
2600        match self
2601            .middleware_stack
2602            .execute_after(&ctx, &mut dispatcher_result)
2603            .await
2604        {
2605            Ok(()) => {
2606                let result = Self::apply_dispatcher_result(result, dispatcher_result);
2607                (result, None)
2608            }
2609            Err(middleware_err) => (
2610                crate::middleware::error::map_middleware_error_to_jsonrpc(
2611                    middleware_err,
2612                    request_id,
2613                ),
2614                None,
2615            ),
2616        }
2617    }
2618
2619    /// Apply potentially-mutated `DispatcherResult` back into the `JsonRpcResponse`.
2620    ///
2621    /// Handles all four mutation paths per the middleware contract:
2622    /// - Success → Success: value mutated in place
2623    /// - Success → Error: middleware rejected response (INTERNAL_ERROR -32603)
2624    /// - Error → Success: middleware recovered (only when error has request ID)
2625    /// - Error → Error: error message mutated
2626    fn apply_dispatcher_result(
2627        result: turul_rpc::JsonRpcResponse,
2628        dispatcher_result: crate::middleware::DispatcherResult,
2629    ) -> turul_rpc::JsonRpcResponse {
2630        match dispatcher_result {
2631            crate::middleware::DispatcherResult::Success(val) => match result {
2632                turul_rpc::JsonRpcResponse::Success(mut resp) => {
2633                    resp.result = turul_rpc::response::ResponseResult::Success(val);
2634                    turul_rpc::JsonRpcResponse::Success(resp)
2635                }
2636                turul_rpc::JsonRpcResponse::Error(err) => {
2637                    // Error→Success recovery: only when error has a request ID
2638                    match err.id {
2639                        Some(id) => turul_rpc::JsonRpcResponse::success(id, val.into()),
2640                        None => turul_rpc::JsonRpcResponse::Error(err),
2641                    }
2642                }
2643            },
2644            crate::middleware::DispatcherResult::Error(msg) => match result {
2645                turul_rpc::JsonRpcResponse::Success(resp) => {
2646                    turul_rpc::JsonRpcResponse::Error(turul_rpc::error::JsonRpcError::new(
2647                        Some(resp.id),
2648                        turul_rpc::error::JsonRpcErrorObject::internal_error(Some(msg)),
2649                    ))
2650                }
2651                turul_rpc::JsonRpcResponse::Error(mut err) => {
2652                    err.error.message = msg;
2653                    turul_rpc::JsonRpcResponse::Error(err)
2654                }
2655            },
2656        }
2657    }
2658}
2659
2660use crate::middleware::bearer::{extract_bearer_token, is_bearer_scheme};
2661
2662/// Build an HTTP challenge response (401/403 with WWW-Authenticate header).
2663///
2664/// Returns a raw HTTP response — never enters the JSON-RPC layer.
2665fn build_http_challenge_response(
2666    status: u16,
2667    www_authenticate: &str,
2668    body: Option<&str>,
2669    context: &StreamableHttpContext,
2670) -> Response<http_body_util::combinators::UnsyncBoxBody<Bytes, hyper::Error>> {
2671    let status_code = StatusCode::from_u16(status).unwrap_or(StatusCode::UNAUTHORIZED);
2672    let body_bytes = body.unwrap_or("").to_string();
2673
2674    Response::builder()
2675        .status(status_code)
2676        .header("WWW-Authenticate", www_authenticate)
2677        .header("Cache-Control", "no-store")
2678        .header("Content-Type", "application/json")
2679        .header("MCP-Protocol-Version", context.protocol_version.as_str())
2680        .body(
2681            http_body_util::Full::new(Bytes::from(body_bytes))
2682                .map_err(|never| match never {})
2683                .boxed_unsync(),
2684        )
2685        .unwrap()
2686}
2687
2688#[cfg(test)]
2689mod tests {
2690    use super::*;
2691
2692    #[test]
2693    fn test_version_parsing() {
2694        assert_eq!(
2695            McpProtocolVersion::parse_version("2024-11-05"),
2696            Some(McpProtocolVersion::V2024_11_05)
2697        );
2698        assert_eq!(
2699            McpProtocolVersion::parse_version("2025-03-26"),
2700            Some(McpProtocolVersion::V2025_03_26)
2701        );
2702        assert_eq!(
2703            McpProtocolVersion::parse_version("2025-06-18"),
2704            Some(McpProtocolVersion::V2025_06_18)
2705        );
2706        assert_eq!(McpProtocolVersion::parse_version("invalid"), None);
2707    }
2708
2709    #[test]
2710    fn test_version_capabilities() {
2711        let v1 = McpProtocolVersion::V2024_11_05;
2712        assert!(!v1.supports_streamable_http());
2713        assert!(!v1.supports_meta_fields());
2714
2715        let v2 = McpProtocolVersion::V2025_03_26;
2716        assert!(v2.supports_streamable_http());
2717        assert!(!v2.supports_meta_fields());
2718
2719        let v3 = McpProtocolVersion::V2025_06_18;
2720        assert!(v3.supports_streamable_http());
2721        assert!(v3.supports_meta_fields());
2722        assert!(v3.supports_cursors());
2723        assert!(v3.supports_progress_tokens());
2724        assert!(v3.supports_elicitation());
2725    }
2726
2727    #[test]
2728    fn test_context_validation() {
2729        let mut context = StreamableHttpContext {
2730            protocol_version: McpProtocolVersion::V2025_06_18,
2731            session_id: Some("test-session".to_string()),
2732            wants_sse_stream: true,
2733            accepts_json: true,
2734            accepts_stream_frames: true,
2735            headers: HashMap::new(),
2736        };
2737
2738        // POST with session should be valid
2739        assert!(context.validate(&Method::POST).is_ok());
2740        // GET with session should be valid
2741        assert!(context.validate(&Method::GET).is_ok());
2742
2743        // Test invalid cases
2744        context.accepts_stream_frames = false;
2745        assert!(context.validate(&Method::POST).is_err());
2746
2747        context.accepts_stream_frames = true;
2748        context.protocol_version = McpProtocolVersion::V2024_11_05;
2749        context.wants_sse_stream = true;
2750        assert!(context.validate(&Method::POST).is_err());
2751
2752        context.protocol_version = McpProtocolVersion::V2025_06_18;
2753        context.session_id = None;
2754        // POST without session should be OK (for initialize)
2755        assert!(context.validate(&Method::POST).is_ok());
2756        // GET without session should fail
2757        assert!(context.validate(&Method::GET).is_err());
2758    }
2759
2760    // Bearer extraction tests are in middleware::bearer::tests
2761    // Transport-level integration tests:
2762
2763    #[test]
2764    fn test_non_bearer_preserved_in_metadata() {
2765        // Non-bearer auth headers pass through, Bearer excluded
2766        let mut ctx = crate::middleware::RequestContext::new("test/method", None);
2767
2768        let headers = vec![
2769            (
2770                "authorization".to_string(),
2771                "Basic dXNlcjpwYXNz".to_string(),
2772            ),
2773            ("x-custom".to_string(), "value".to_string()),
2774        ];
2775
2776        for (k, v) in &headers {
2777            if k == "authorization" && is_bearer_scheme(v) {
2778                continue;
2779            }
2780            ctx.add_metadata(k.clone(), serde_json::json!(v));
2781        }
2782
2783        assert!(ctx.metadata().contains_key("authorization"));
2784        assert!(ctx.metadata().contains_key("x-custom"));
2785
2786        // Bearer exclusion
2787        let mut ctx2 = crate::middleware::RequestContext::new("test/method", None);
2788        let bearer_headers = vec![
2789            ("authorization".to_string(), "Bearer abc123".to_string()),
2790            ("x-custom".to_string(), "value".to_string()),
2791        ];
2792
2793        for (k, v) in &bearer_headers {
2794            if k == "authorization" && is_bearer_scheme(v) {
2795                continue;
2796            }
2797            ctx2.add_metadata(k.clone(), serde_json::json!(v));
2798        }
2799
2800        assert!(!ctx2.metadata().contains_key("authorization"));
2801        assert!(ctx2.metadata().contains_key("x-custom"));
2802    }
2803
2804    #[test]
2805    fn test_malformed_bearer_excluded_from_metadata() {
2806        // Even malformed Bearer tokens are excluded from metadata
2807        let mut ctx = crate::middleware::RequestContext::new("test/method", None);
2808
2809        let headers = vec![("authorization".to_string(), "Bearer ".to_string())];
2810
2811        for (k, v) in &headers {
2812            if k == "authorization" && is_bearer_scheme(v) {
2813                continue;
2814            }
2815            ctx.add_metadata(k.clone(), serde_json::json!(v));
2816        }
2817
2818        assert!(!ctx.metadata().contains_key("authorization"));
2819    }
2820}