solidmcp 0.4.0

A high-level Rust toolkit for building Model Context Protocol (MCP) servers with type safety and minimal boilerplate. Supports tools, resources, and prompts with automatic JSON schema generation.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
//! MCP HTTP Handler
//!
//! HTTP transport for MCP protocol messages with intelligent transport negotiation.

use {
    super::shared::McpProtocolEngine,
    super::transport::{
        cors_headers, transport_capabilities, TransportCapabilities, TransportInfo,
        TransportNegotiation,
    },
    super::validation::McpValidator,
    anyhow::Result,
    serde_json::{json, Value},
    std::sync::Arc,
    tracing::{debug, error, info, warn},
    warp::http::{HeaderValue, StatusCode},
    warp::{reply, Filter, Rejection, Reply},
};

// === MCP PROGRESS NOTIFICATION SUPPORT ===
// This implements proper MCP progress notifications as separate JSON-RPC messages

#[derive(Debug, Clone)]
pub struct ProgressNotification {
    pub progress_token: Value,
    pub progress: f64,
    pub total: Option<f64>,
    pub message: Option<String>,
}

impl ProgressNotification {
    pub fn to_json_rpc(&self) -> Value {
        json!({
            "jsonrpc": "2.0",
            "method": "notifications/progress",
            "params": {
                "progressToken": self.progress_token,
                "progress": self.progress,
                "total": self.total,
                "message": self.message
            }
        })
    }
}

pub struct HttpMcpHandler {
    protocol_engine: Arc<McpProtocolEngine>,
}

impl HttpMcpHandler {
    pub fn new(protocol_engine: Arc<McpProtocolEngine>) -> Self {
        Self { protocol_engine }
    }

    pub fn route(&self) -> impl Filter<Extract = impl Reply, Error = Rejection> + Clone {
        let options_route = warp::path!("mcp")
            .and(warp::options())
            .and(transport_capabilities())
            .and(with_handler(self.protocol_engine.clone()))
            .and_then(handle_mcp_options);

        let get_route = warp::path!("mcp")
            .and(warp::get())
            .and(transport_capabilities())
            .and(with_handler(self.protocol_engine.clone()))
            .and_then(handle_mcp_get);

        // SSE endpoint - returns proper error when SSE is not implemented
        let sse_route = warp::path!("mcp")
            .and(warp::get())
            .and(warp::header::optional::<String>("accept"))
            .and(warp::header::optional::<String>("cache-control"))
            .and(with_handler(self.protocol_engine.clone()))
            .and_then(handle_mcp_sse_fallback);

        let post_route = warp::path!("mcp")
            .and(warp::post())
            .and(transport_capabilities())
            .and(warp::body::json())
            .and(warp::header::optional::<String>("cookie"))
            .and(with_handler(self.protocol_engine.clone()))
            .and_then(handle_mcp_enhanced_post);

        let legacy_route = warp::path!("mcp")
            .and(warp::post())
            .and(warp::body::json())
            .and(warp::header::optional::<String>("content-type"))
            .and(warp::header::optional::<String>("accept"))
            .and(warp::header::optional::<String>("connection"))
            .and(warp::header::optional::<String>("cookie"))
            .and(with_handler(self.protocol_engine.clone()))
            .and_then(handle_mcp_http);

        // Try enhanced routes first, then SSE fallback, then legacy for backward compatibility
        options_route
            .or(get_route)
            .or(sse_route)
            .or(post_route)
            .or(legacy_route)
    }
}

fn with_handler(
    handler: Arc<McpProtocolEngine>,
) -> impl Filter<Extract = (Arc<McpProtocolEngine>,), Error = std::convert::Infallible> + Clone {
    warp::any().map(move || handler.clone())
}

async fn handle_mcp_http(
    message: Value,
    content_type: Option<String>,
    accept: Option<String>,
    connection: Option<String>,
    cookie: Option<String>,
    handler: Arc<McpProtocolEngine>,
) -> Result<impl Reply, Rejection> {
    use std::time::Instant;
    use uuid::Uuid;

    // === COMPREHENSIVE MCP PROTOCOL INSTRUMENTATION ===
    let request_start = Instant::now();
    let request_id = Uuid::new_v4().to_string();
    let content_type = content_type.unwrap_or_else(|| "application/json".to_string());
    let accept = accept.unwrap_or_else(|| "application/json".to_string());
    let connection = connection.unwrap_or_else(|| "close".to_string());

    // === PROTOCOL ANALYSIS LOGGING ===
    info!("🚀 === MCP REQUEST ANALYSIS START ===");
    info!("   Request ID: {}", request_id);
    info!("   Timestamp: {:?}", request_start);
    info!("   Content-Type: {}", content_type);
    info!("   Accept: {}", accept);
    info!("   Connection: {}", connection);
    info!("   Cookie: {:?}", cookie);

    // Detect Cursor client from User-Agent patterns in headers
    let is_cursor_client = content_type.contains("Cursor")
        || accept.contains("Cursor")
        || cookie.as_ref().map_or(false, |c| c.contains("Cursor"));

    if is_cursor_client {
        warn!("🎯 === CURSOR CLIENT DETECTED ===");
        warn!("   Applying enhanced Cursor-specific protocol analysis");
        warn!("   Request ID: {}", request_id);
    }

    // === MESSAGE STRUCTURE ANALYSIS ===
    let method = message
        .get("method")
        .and_then(|m| m.as_str())
        .unwrap_or("unknown");
    let msg_id = message.get("id").cloned().unwrap_or(json!(null));
    let has_params = message.get("params").is_some();
    let has_meta = message.get("params").and_then(|p| p.get("_meta")).is_some();
    let has_progress_token = message
        .get("params")
        .and_then(|p| p.get("_meta"))
        .and_then(|m| m.get("progressToken"))
        .is_some();

    info!("🔍 === MESSAGE STRUCTURE ===");
    info!("   Method: {}", method);
    info!("   ID: {:?}", msg_id);
    info!("   Has Params: {}", has_params);
    info!("   Has Meta: {}", has_meta);
    info!("   Has Progress Token: {}", has_progress_token);

    if has_progress_token {
        let progress_token = message
            .get("params")
            .and_then(|p| p.get("_meta"))
            .and_then(|m| m.get("progressToken"));
        warn!("⚡ PROGRESS TOKEN DETECTED: {:?}", progress_token);
        warn!("   This indicates client expects streaming updates!");

        if is_cursor_client {
            warn!("🎯 CURSOR + PROGRESS TOKEN: Critical protocol path!");
        }
    }

    // === MESSAGE SIZE ANALYSIS ===
    let message_json = serde_json::to_string(&message).unwrap_or_default();
    let request_size = message_json.len();

    info!("📊 === REQUEST SIZE ANALYSIS ===");
    info!("   Request Size: {} bytes", request_size);
    info!("   Request Size KB: {:.2} KB", request_size as f64 / 1024.0);

    if request_size > 10000 {
        warn!(
            "⚠️  LARGE REQUEST: {} bytes may cause processing issues",
            request_size
        );
    }

    info!(
        "📥 MCP HTTP request - Content-Type: {}, Accept: {}, Connection: {}",
        content_type, accept, connection
    );
    info!("📥 INCOMING MCP REQUEST:");
    info!(
        "   📋 Raw request body: {}",
        serde_json::to_string(&message).unwrap_or_else(|_| "invalid json".to_string())
    );
    info!(
        "   📋 Raw request body (hex): {:?}",
        serde_json::to_string(&message)
            .unwrap_or_else(|_| "invalid json".to_string())
            .as_bytes()
    );
    info!("   📋 Content-Type: {}", content_type);
    info!("   📋 Accept: {}", accept);
    info!("   📋 Connection: {}", connection);
    info!("   📋 Cookie: {:?}", cookie);

    // Extract session ID from cookie
    let session_id = extract_session_id_from_cookie(&cookie);

    // Extract method for session ID logic
    let method = message.get("method").and_then(|m| m.as_str()).unwrap_or("");

    // For HTTP clients that don't handle cookies properly (like Claude), we need a fallback
    // Use a consistent session ID for the duration of the server process
    let effective_session_id = if method == "initialize" {
        // Always use a consistent session for initialize requests
        Some("http_default_session".to_string())
    } else if session_id.is_none() {
        // Fallback: for clients that don't send cookies, use the same default session
        // This allows stateless HTTP clients to work with the MCP protocol
        warn!(
            "⚠️  No session cookie found for method '{}'. Using default HTTP session.",
            method
        );
        Some("http_default_session".to_string())
    } else {
        session_id.clone()
    };

    info!("🔍 SESSION DEBUG:");
    info!(
        "   📋 Method: {}",
        message.get("method").and_then(|m| m.as_str()).unwrap_or("")
    );
    info!("   📋 Cookie header: {:?}", cookie);
    info!("   📋 Extracted session: {:?}", session_id);
    info!("   📋 Effective session: {:?}", effective_session_id);
    info!("   📋 Message ID: {:?}", message.get("id"));

    // Validate the message
    if let Err(e) = McpValidator::validate_message(&message) {
        error!("❌ MCP message validation failed: {:?}", e);
        let error_response = json!({
            "jsonrpc": "2.0",
            "id": null,
            "error": {
                "code": -32600,
                "message": format!("Invalid request: {:?}", e)
            }
        });
        return Ok(create_error_reply(error_response, StatusCode::BAD_REQUEST));
    }

    info!("✅ MCP message validation passed");

    // Check content type
    if !content_type.contains("application/json") {
        error!("❌ Invalid Content-Type: {}", content_type);
        let error_response = json!({
            "jsonrpc": "2.0",
            "id": null,
            "error": {
                "code": -32600,
                "message": format!("Invalid Content-Type: {}", content_type)
            }
        });
        debug!(
            "📤 Sending error response for invalid content-type: {:?}",
            error_response
        );
        return Ok(create_error_reply(error_response, StatusCode::BAD_REQUEST));
    }

    // Extract message ID before moving the message
    let message_id = message.get("id").unwrap_or(&json!(null)).clone();
    debug!(
        "📥 Parsed MCP message: id={:?}, method={:?}",
        message_id, method
    );
    let message_clone = message.clone();

    debug!("🍪 Session ID from cookie: {:?}", session_id);
    debug!("🍪 Effective session ID: {:?}", effective_session_id);

    // Check if this is a tools/call with progress token
    let has_progress_token = message
        .get("params")
        .and_then(|p| p.get("_meta"))
        .and_then(|m| m.get("progressToken"))
        .is_some();

    // === HTTP ENCODING STRATEGY ===
    // Use chunked encoding ONLY when we have progress tokens
    // This prevents HTTP protocol violations and ensures compatibility
    let use_chunked = has_progress_token;

    info!("🔧 HTTP encoding strategy:");
    info!(
        "   Has Progress Token: {} (Accept: {}, Connection: {})",
        has_progress_token, accept, connection
    );
    info!(
        "   Using Chunked Encoding: {} ({})",
        use_chunked,
        if use_chunked {
            "for streaming progress"
        } else {
            "standard Content-Length"
        }
    );

    // === STRATEGY 1: MCP PROGRESS TOKEN HANDLING (OPTIMAL APPROACH) ===
    // Based on successful testing, always implement immediate progress notifications
    // when a progress token is detected, using chunked encoding for streaming
    let progress_token = if has_progress_token {
        let token = message
            .get("params")
            .and_then(|p| p.get("_meta"))
            .and_then(|m| m.get("progressToken"))
            .cloned();

        warn!("🎯 === MCP PROGRESS TOKEN DETECTED (STRATEGY 1) ===");
        warn!("   Progress Token: {:?}", token);
        warn!("   IMPLEMENTING IMMEDIATE PROGRESS NOTIFICATIONS");
        warn!("   Using Strategy 1: Immediate progress with chunked encoding");

        token
    } else {
        None
    };

    if has_progress_token {
        warn!("🚀 STRATEGY 1: ENABLING CHUNKED ENCODING for MCP Streamable HTTP transport");
        warn!("   Using immediate progress notifications with chunked encoding");
        warn!("   This approach has been tested and proven to work with Cursor");
    }

    // Handle the message with Strategy 1: Immediate progress with chunked encoding
    let (result, _progress_notifications) = if has_progress_token {
        // === STRATEGY 1: IMMEDIATE PROGRESS NOTIFICATION HANDLING ===
        warn!("📡 STRATEGY 1: PROCESSING WITH IMMEDIATE PROGRESS NOTIFICATIONS");

        let mut notifications = Vec::new();

        // Strategy 1: Send immediate progress notification
        if let Some(ref token) = progress_token {
            let start_notification = ProgressNotification {
                progress_token: token.clone(),
                progress: 0.0,
                total: Some(100.0),
                message: Some("Starting request processing...".to_string()),
            };

            warn!(
                "📡 STRATEGY 1: QUEUING IMMEDIATE PROGRESS NOTIFICATION: {:?}",
                start_notification.to_json_rpc()
            );
            notifications.push(start_notification);
        }

        // Process the message normally
        let start_time = std::time::Instant::now();
        let response_result = handler
            .handle_message(message_clone, effective_session_id.clone())
            .await;

        // Strategy 1: Send completion progress notification
        if let Some(ref token) = progress_token {
            let duration = start_time.elapsed();
            let completion_notification = ProgressNotification {
                progress_token: token.clone(),
                progress: 100.0,
                total: Some(100.0),
                message: Some(format!(
                    "Request completed in {:.2}ms",
                    duration.as_secs_f64() * 1000.0
                )),
            };

            warn!(
                "📡 STRATEGY 1: QUEUING COMPLETION NOTIFICATION: {:?}",
                completion_notification.to_json_rpc()
            );
            notifications.push(completion_notification);
        }

        (response_result, Some(notifications))
    } else {
        // Standard processing without progress notifications
        let response_result = handler
            .handle_message(message_clone, effective_session_id.clone())
            .await;
        (response_result, None)
    };

    match result {
        Ok(response) => {
            let response_processing_time = request_start.elapsed();
            debug!("📤 HTTP MCP response: {:?}", response);

            // === COMPREHENSIVE RESPONSE ANALYSIS ===
            let response_json = serde_json::to_string(&response).unwrap_or_default();
            let response_size = response_json.len();

            info!("🎉 === MCP RESPONSE ANALYSIS ===");
            info!("   Request ID: {}", request_id);
            info!("   Processing Time: {:?}", response_processing_time);
            info!("   Response Size: {} bytes", response_size);
            info!("   Response KB: {:.2} KB", response_size as f64 / 1024.0);
            info!("   Method: {}", method);
            info!("   Message ID: {:?}", msg_id);

            // === CURSOR-SPECIFIC ANALYSIS ===
            if is_cursor_client {
                warn!("🎯 === CURSOR RESPONSE ANALYSIS ===");
                warn!("   Request ID: {}", request_id);
                warn!("   Processing Time: {:?}", response_processing_time);
                warn!("   Response Size: {} bytes", response_size);

                // Critical analysis for Cursor timeouts
                if response_size > 10000 {
                    warn!("⚠️  CURSOR LARGE RESPONSE WARNING: {} bytes", response_size);
                    warn!("   This may cause Cursor client timeout - consider optimization!");
                }

                if response_processing_time.as_millis() > 5000 {
                    warn!(
                        "⚠️  CURSOR SLOW RESPONSE WARNING: {:?}",
                        response_processing_time
                    );
                    warn!("   This may cause Cursor client timeout!");
                }

                if has_progress_token {
                    warn!("🎯 CURSOR + PROGRESS TOKEN RESPONSE");
                    warn!("   Cursor expects this to support streaming updates");
                    warn!("   Current implementation: Single response (not streaming)");
                }
            }

            // === RESPONSE CONTENT ANALYSIS ===
            let has_result = response.get("result").is_some();
            let has_error = response.get("error").is_some();
            let result_type = if has_result {
                "success"
            } else if has_error {
                "error"
            } else {
                "unknown"
            };

            info!("📋 === RESPONSE CONTENT ===");
            info!("   Type: {}", result_type);
            info!("   Has Result: {}", has_result);
            info!("   Has Error: {}", has_error);

            if has_result {
                if let Some(result) = response.get("result") {
                    if let Some(tools) = result.get("tools") {
                        if let Some(tools_array) = tools.as_array() {
                            info!("   Tools Count: {}", tools_array.len());
                        }
                    }
                    if let Some(results) = result.get("results") {
                        if let Some(results_array) = results.as_array() {
                            info!("   Results Count: {}", results_array.len());
                        }
                    }
                }
            }

            warn!("🔍 RESPONSE DEBUG:");
            warn!("   📊 Response size: {} bytes", response_size);
            warn!("   📊 Response KB: {:.2} KB", response_size as f64 / 1024.0);
            warn!("   📋 Method: {:?}", method);
            warn!("   📋 Message ID: {:?}", message_id);

            // Check if this is a tools/call with progress token
            let has_progress_token = message
                .get("params")
                .and_then(|p| p.get("_meta"))
                .and_then(|m| m.get("progressToken"))
                .is_some();

            if has_progress_token {
                warn!("⚡ REQUEST HAS PROGRESS TOKEN - Client expects streaming updates");
                let progress_token = message
                    .get("params")
                    .and_then(|p| p.get("_meta"))
                    .and_then(|m| m.get("progressToken"));
                warn!("   🎯 Progress Token: {:?}", progress_token);
            }

            if response_size > 10000 {
                warn!(
                    "⚠️  LARGE RESPONSE WARNING: {} bytes might cause client timeout",
                    response_size
                );
                warn!("⚠️  This could be the ROOT CAUSE of MCP client timeouts!");
            }

            // Check if response contains massive debug sections
            if response_json.contains("debug") && response_json.len() > 5000 {
                warn!("🐛 LARGE DEBUG SECTION DETECTED - This may be causing timeout issues");
            }

            debug!(
                "🍪 [SESSION] Used session_id for message handling: {:?}",
                effective_session_id
            );
            // Always return 200 OK for MCP responses, even for protocol errors
            // MCP uses JSON-RPC error codes in the body, not HTTP status codes
            let status = StatusCode::OK;

            // Note: use_chunked is already determined earlier in the function

            // Determine connection header based on encoding
            let connection_header = if use_chunked {
                warn!("🔄 Using chunked transfer encoding for streaming client");
                "keep-alive"
            } else {
                warn!("📦 Using standard HTTP response (Content-Length)");
                "close"
            };

            // === COMPREHENSIVE HTTP HEADER ANALYSIS ===
            info!("🔧 === HTTP RESPONSE HEADERS ANALYSIS ===");
            info!("   Request ID: {}", request_id);
            info!("   Use Chunked: {}", use_chunked);
            info!("   Has Progress Token: {}", has_progress_token);
            info!("   Connection Header: {}", connection_header);

            if is_cursor_client {
                warn!("🎯 === CURSOR HTTP HEADERS ===");
                warn!("   Chunked Encoding: {}", use_chunked);
                warn!("   This is critical for Cursor compatibility!");

                if !use_chunked && has_progress_token {
                    warn!("🧪 EXPERIMENTAL FIX: Content-Length + Progress Token");
                    warn!("   Using standard HTTP response instead of chunked encoding");
                    warn!("   Testing if MCP client prefers this approach");
                }
            }

            // === PROTOCOL VIOLATION PREVENTION ===
            // CRITICAL: Prevent the HTTP protocol violation that causes client timeouts
            info!("🛡️  === PROTOCOL COMPLIANCE CHECK ===");
            if use_chunked {
                warn!("🔄 Using chunked transfer encoding");
                warn!("   Will NOT set Content-Length (prevents protocol violation)");
            } else {
                warn!("📏 Using Content-Length: {} bytes", response_size);
                warn!("   Will NOT set Transfer-Encoding (prevents protocol violation)");
            }

            // Create the response - CRITICAL: Never set both Content-Length and Transfer-Encoding
            let base_reply = if use_chunked {
                // === CHUNKED ENCODING FOR PROGRESS TOKENS ===
                warn!("🔄 Using Transfer-Encoding: chunked for progress support");
                warn!(
                    "   Response size: {} bytes (no Content-Length header)",
                    response_size
                );

                // IMPORTANT: Do NOT set Content-Length when using chunked encoding
                reply::with_header(
                    reply::with_header(
                        reply::with_status(
                            warp::reply::Response::new(response_json.into()),
                            status,
                        ),
                        "content-type",
                        "application/json; charset=utf-8",
                    ),
                    "transfer-encoding",
                    "chunked",
                )
            } else {
                // === STANDARD RESPONSE WITH CONTENT-LENGTH ===
                warn!(
                    "📏 Using Content-Length: {} bytes (no Transfer-Encoding)",
                    response_size
                );

                // IMPORTANT: Do NOT set Transfer-Encoding when using Content-Length
                reply::with_header(
                    reply::with_header(
                        reply::with_status(
                            warp::reply::Response::new(response_json.into()),
                            status,
                        ),
                        "content-type",
                        "application/json",
                    ),
                    "content-length",
                    response_size.to_string(),
                )
            };

            // Add connection header
            let base_reply = reply::with_header(base_reply, "connection", connection_header);

            // Set session cookie for initialize responses
            let set_cookie_value = if method == "initialize" && response.get("result").is_some() {
                let cookie_value = format!(
                    "mcp_session={}; Path=/mcp; HttpOnly; SameSite=Strict",
                    effective_session_id
                        .as_ref()
                        .unwrap_or(&"default".to_string())
                );
                info!(
                    "🍪 Set session cookie: {}",
                    effective_session_id
                        .as_ref()
                        .unwrap_or(&"default".to_string())
                );
                debug!(
                    "🍪 [COOKIE] Set session cookie value: {}",
                    effective_session_id
                        .as_ref()
                        .unwrap_or(&"default".to_string())
                );
                debug!(
                    "🍪 [COOKIE] Incoming session_id from cookie: {:?}",
                    session_id
                );
                debug!(
                    "🍪 [COOKIE] Effective session_id: {:?}",
                    effective_session_id
                );
                cookie_value
            } else {
                "".to_string()
            };

            let final_reply = reply::with_header(base_reply, "set-cookie", set_cookie_value);

            // === FINAL RESPONSE SUMMARY ===
            let total_request_time = request_start.elapsed();

            warn!("📤 === FINAL RESPONSE HEADERS ===");
            warn!("   Request ID: {}", request_id);
            warn!("   Content-Type: application/json");
            warn!(
                "   Content-Length: {} bytes",
                if use_chunked { 0 } else { response_size }
            );
            warn!(
                "   Transfer-Encoding: {}",
                if use_chunked { "chunked" } else { "none" }
            );
            warn!("   Connection: {}", connection_header);
            warn!("   Status: {}", status);
            warn!("   Total Time: {:?}", total_request_time);

            info!("📤 === MCP REQUEST COMPLETE ===");
            info!("   Request ID: {}", request_id);
            info!("   Method: {}", method);
            info!("   Total Processing Time: {:?}", total_request_time);
            info!("   Request Size: {} bytes", request_size);
            info!("   Response Size: {} bytes", response_size);
            info!("   Status: SUCCESS");

            if is_cursor_client {
                warn!("🎯 === CURSOR REQUEST COMPLETE ===");
                warn!("   Request ID: {}", request_id);
                warn!("   Total Time: {:?}", total_request_time);
                warn!("   Response Size: {} bytes", response_size);
                warn!(
                    "   Headers: {}",
                    if use_chunked {
                        "Chunked"
                    } else {
                        "Content-Length"
                    }
                );
                warn!("   Protocol Compliance: ✅ (No dual headers)");

                // Performance recommendations for Cursor
                if response_size > 5000 && total_request_time.as_millis() > 1000 {
                    warn!("💡 CURSOR OPTIMIZATION OPPORTUNITY:");
                    warn!("   Consider response compression or pagination");
                    warn!("   Large responses may impact Cursor user experience");
                }
            }

            info!("📤 Sending HTTP MCP response with status: {}", status);

            // Add a small delay to see if it helps with client timeouts
            // Especially important for Cursor client stability
            let delay_ms = if is_cursor_client && response_size > 5000 {
                15
            } else {
                10
            };
            tokio::time::sleep(tokio::time::Duration::from_millis(delay_ms)).await;

            info!("✅ === REQUEST {} COMPLETE ===", request_id);
            Ok(final_reply.into_response())
        }
        Err(e) => {
            error!(
                "❌ HTTP MCP error: {} (id={:?}, method={:?})",
                e, message_id, method
            );
            // Create error response with JSON-RPC error codes
            // Always return 200 OK status, let JSON-RPC handle the error details
            let error_code = match e.to_string() {
                s if s.contains("Not initialized") => -32002,
                s if s.contains("Unknown method") || s.contains("Method not found") => -32601,
                s if s.contains("Invalid params") => -32602,
                _ => -32603,
            };
            let error_response = json!({
                "jsonrpc": "2.0",
                "id": message_id,
                "error": {
                    "code": error_code,
                    "message": format!("{}", e)
                }
            });
            debug!("📤 Sending error response: {:?}", error_response);
            Ok(create_error_reply(error_response, StatusCode::OK))
        }
    }
}

/// Enhanced handler for OPTIONS requests (CORS and capability discovery)
async fn handle_mcp_options(
    capabilities: TransportCapabilities,
    _handler: Arc<McpProtocolEngine>,
) -> Result<warp::reply::Response, Rejection> {
    info!("🌐 OPTIONS request with capabilities: {:?}", capabilities);

    let info = TransportInfo::new(&capabilities, "SolidMCP", "0.1.0", "/mcp");
    let response = info.to_json();

    let mut headers = cors_headers();
    headers.insert("content-type", HeaderValue::from_static("application/json"));

    let mut response = reply::with_status(reply::json(&response), StatusCode::OK).into_response();
    for (key, value) in headers.iter() {
        response.headers_mut().insert(key.clone(), value.clone());
    }

    Ok(response)
}

/// Enhanced handler for GET requests (transport discovery and WebSocket upgrade)
async fn handle_mcp_get(
    capabilities: TransportCapabilities,
    _handler: Arc<McpProtocolEngine>,
) -> Result<warp::reply::Response, Rejection> {
    info!("🌐 GET request with capabilities: {:?}", capabilities);

    let negotiation =
        TransportNegotiation::negotiate("GET", &capabilities, false, "SolidMCP", "0.1.0", "/mcp");

    match negotiation {
        TransportNegotiation::WebSocketUpgrade => {
            // Return transport info instead of error for WebSocket requests
            // This allows clients to discover available transports even when sending WS headers
            info!("WebSocket headers detected, returning transport discovery info");
            let info = TransportInfo::new(&capabilities, "SolidMCP", "0.1.0", "/mcp");
            let response = info.to_json();
            let mut headers = cors_headers();
            headers.insert("content-type", HeaderValue::from_static("application/json"));
            let mut resp =
                reply::with_status(reply::json(&response), StatusCode::OK).into_response();
            for (key, value) in headers.iter() {
                resp.headers_mut().insert(key.clone(), value.clone());
            }
            Ok(resp)
        }
        TransportNegotiation::InfoResponse(info) => {
            let response = info.to_json();
            let mut headers = cors_headers();
            headers.insert("content-type", HeaderValue::from_static("application/json"));

            let mut resp =
                reply::with_status(reply::json(&response), StatusCode::OK).into_response();
            for (key, value) in headers.iter() {
                resp.headers_mut().insert(key.clone(), value.clone());
            }

            Ok(resp)
        }
        TransportNegotiation::UnsupportedTransport { error, supported } => {
            let error_response = json!({
                "error": {
                    "code": -32600,
                    "message": error,
                    "data": {
                        "supported_transports": supported,
                        "client_capabilities": capabilities
                    }
                }
            });
            Ok(
                reply::with_status(reply::json(&error_response), StatusCode::BAD_REQUEST)
                    .into_response(),
            )
        }
        _ => {
            let error_response = json!({
                "error": {
                    "code": -32600,
                    "message": "Unexpected negotiation result for GET request"
                }
            });
            Ok(reply::with_status(
                reply::json(&error_response),
                StatusCode::INTERNAL_SERVER_ERROR,
            )
            .into_response())
        }
    }
}

/// Enhanced handler for POST requests with transport capability detection
async fn handle_mcp_enhanced_post(
    capabilities: TransportCapabilities,
    message: Value,
    cookie: Option<String>,
    handler: Arc<McpProtocolEngine>,
) -> Result<warp::reply::Response, Rejection> {
    info!(
        "🌐 Enhanced POST request with capabilities: {:?}",
        capabilities
    );

    let negotiation =
        TransportNegotiation::negotiate("POST", &capabilities, true, "SolidMCP", "0.1.0", "/mcp");

    match negotiation {
        TransportNegotiation::HttpJsonRpc => {
            // Use the existing HTTP handler logic but with enhanced logging
            info!(
                "📡 Using HTTP JSON-RPC transport (preferred: {})",
                capabilities.preferred_transport()
            );

            // Log client information
            if let Some(client_info) = &capabilities.client_info {
                info!("🔍 Client: {}", client_info);
            }
            if let Some(protocol_version) = &capabilities.protocol_version {
                info!("🔍 Requested protocol version: {}", protocol_version);
            }

            // Call the existing handler with converted parameters
            match handle_mcp_http(
                message,
                Some("application/json".to_string()),
                Some("application/json".to_string()),
                Some("close".to_string()),
                cookie,
                handler,
            )
            .await
            {
                Ok(reply) => {
                    // Add CORS headers to the response
                    let mut response = reply.into_response();
                    let cors = cors_headers();
                    for (key, value) in cors.iter() {
                        response.headers_mut().insert(key.clone(), value.clone());
                    }
                    Ok(response)
                },
                Err(e) => Err(e),
            }
        }
        TransportNegotiation::UnsupportedTransport { error, supported } => {
            warn!("🚫 Unsupported transport: {}", error);
            let error_response = json!({
                "jsonrpc": "2.0",
                "id": message.get("id"),
                "error": {
                    "code": -32600,
                    "message": error,
                    "data": {
                        "supported_transports": supported,
                        "client_capabilities": capabilities
                    }
                }
            });
            Ok(
                reply::with_status(reply::json(&error_response), StatusCode::BAD_REQUEST)
                    .into_response(),
            )
        }
        _ => {
            let error_response = json!({
                "jsonrpc": "2.0",
                "id": message.get("id"),
                "error": {
                    "code": -32600,
                    "message": "Unexpected negotiation result for POST request"
                }
            });
            Ok(reply::with_status(
                reply::json(&error_response),
                StatusCode::INTERNAL_SERVER_ERROR,
            )
            .into_response())
        }
    }
}

/// Enhanced handler for SSE fallback (when client requests SSE but server doesn't support it)
async fn handle_mcp_sse_fallback(
    accept: Option<String>,
    _cache_control: Option<String>,
    _handler: Arc<McpProtocolEngine>,
) -> Result<warp::reply::Response, Rejection> {
    info!("🌐 SSE fallback request with Accept: {:?}", accept);

    // Check if this is actually an SSE request
    if let Some(accept_header) = &accept {
        if accept_header.contains("text/event-stream") {
            warn!("Client requested SSE but server doesn't support it, returning helpful error");

            let error_response = json!({
                "error": {
                    "code": -32600,
                    "message": "Server-Sent Events (SSE) transport not implemented",
                    "data": {
                        "supported_transports": ["http_post", "websocket"],
                        "instructions": "Use HTTP POST with JSON-RPC or WebSocket for real-time communication",
                        "fallback_suggestion": "Try connecting with HTTP POST transport"
                    }
                }
            });

            let mut headers = cors_headers();
            headers.insert("content-type", HeaderValue::from_static("application/json"));

            let mut response =
                reply::with_status(reply::json(&error_response), StatusCode::OK).into_response();
            for (key, value) in headers.iter() {
                response.headers_mut().insert(key.clone(), value.clone());
            }

            return Ok(response);
        }
    }

    // If not an SSE request, fall through to other handlers
    Err(warp::reject::not_found())
}

/// Extract session ID from cookie header
fn extract_session_id_from_cookie(cookie: &Option<String>) -> Option<String> {
    if let Some(cookie_str) = cookie {
        for cookie_pair in cookie_str.split(';') {
            let trimmed = cookie_pair.trim();
            if trimmed.starts_with("mcp_session=") {
                let session_id = trimmed[12..].trim(); // Remove "mcp_session="
                if !session_id.is_empty() {
                    return Some(session_id.to_string());
                }
            }
        }
    }
    None
}

/// Generate a new session ID
fn generate_session_id() -> String {
    use std::sync::atomic::{AtomicU64, Ordering};
    use std::time::{Duration, SystemTime, UNIX_EPOCH};

    static COUNTER: AtomicU64 = AtomicU64::new(0);

    let timestamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .unwrap_or_else(|_| Duration::from_secs(0))
        .as_millis();
    let count = COUNTER.fetch_add(1, Ordering::SeqCst);
    format!("session_{timestamp}_{count}")
}

/// Create an error reply with proper headers
/// Note: MCP uses JSON-RPC error codes in the body, not HTTP status codes
/// So we always return 200 OK status even for protocol errors
fn create_error_reply(error_response: Value, status: StatusCode) -> warp::reply::Response {
    let base_reply = reply::with_status(reply::json(&error_response), status);
    reply::with_header(base_reply, "content-type", "application/json").into_response()
}

pub mod session;

#[cfg(test)]
mod tests {
    use super::*;
    use serde_json::json;

    #[test]
    fn test_extract_session_id_from_cookie() {
        // Test with valid session cookie
        let cookie = Some("mcp_session=test_session_123; other=value".to_string());
        assert_eq!(
            extract_session_id_from_cookie(&cookie),
            Some("test_session_123".to_string())
        );

        // Test with session cookie only
        let cookie = Some("mcp_session=simple_session".to_string());
        assert_eq!(
            extract_session_id_from_cookie(&cookie),
            Some("simple_session".to_string())
        );

        // Test with no session cookie
        let cookie = Some("other=value; another=test".to_string());
        assert_eq!(extract_session_id_from_cookie(&cookie), None);

        // Test with empty cookie
        let cookie = Some("".to_string());
        assert_eq!(extract_session_id_from_cookie(&cookie), None);

        // Test with None
        assert_eq!(extract_session_id_from_cookie(&None), None);

        // Test with spaces around session value
        let cookie = Some("mcp_session=  spaced_session  ; other=value".to_string());
        assert_eq!(
            extract_session_id_from_cookie(&cookie),
            Some("spaced_session".to_string())
        );
    }

    #[test]
    fn test_generate_session_id_format() {
        let session_id = generate_session_id();

        // Should start with "session_"
        assert!(session_id.starts_with("session_"));

        // Should have reasonable length
        assert!(session_id.len() > 8);
        assert!(session_id.len() < 30);

        // Should contain only alphanumeric and underscore
        assert!(session_id.chars().all(|c| c.is_alphanumeric() || c == '_'));
    }

    #[test]
    fn test_generate_session_id_uniqueness() {
        // Generate multiple session IDs
        let ids: Vec<String> = (0..100).map(|_| generate_session_id()).collect();

        // All should be unique
        let unique_count = ids.iter().collect::<std::collections::HashSet<_>>().len();
        assert_eq!(unique_count, ids.len());
    }

    #[test]
    fn test_create_error_reply_format() {
        let error = json!({
            "jsonrpc": "2.0",
            "id": null,
            "error": {
                "code": -32600,
                "message": "Invalid Request"
            }
        });

        let response = create_error_reply(error.clone(), StatusCode::OK);

        // Should have correct status
        assert_eq!(response.status(), StatusCode::OK);

        // Should have correct content type header
        let headers = response.headers();
        assert_eq!(
            headers.get("content-type").and_then(|v| v.to_str().ok()),
            Some("application/json")
        );
    }

    #[test]
    fn test_effective_session_id_logic() {
        // Test initialize method without session
        let method = "initialize";
        let session_id: Option<String> = None;

        let effective_session_id = if method == "initialize" {
            Some("http_default_session".to_string())
        } else if session_id.is_none() {
            Some("http_default_session".to_string())
        } else {
            session_id.clone()
        };

        assert_eq!(
            effective_session_id,
            Some("http_default_session".to_string())
        );

        // Test non-initialize method without session
        let method = "tools/list";
        let session_id: Option<String> = None;

        let effective_session_id = if method == "initialize" {
            Some("http_default_session".to_string())
        } else if session_id.is_none() {
            Some("http_default_session".to_string())
        } else {
            session_id.clone()
        };

        assert_eq!(
            effective_session_id,
            Some("http_default_session".to_string())
        );

        // Test with existing session
        let method = "tools/list";
        let session_id = Some("existing_session".to_string());

        let effective_session_id = if method == "initialize" {
            Some("http_default_session".to_string())
        } else if session_id.is_none() {
            Some("http_default_session".to_string())
        } else {
            session_id.clone()
        };

        assert_eq!(effective_session_id, Some("existing_session".to_string()));
    }
}