mcp-probe-core 0.3.0

Core MCP (Model Context Protocol) types, traits, and transport implementations
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
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
//! Streamable HTTP transport implementation for MCP communication.
//!
//! This transport implements the MCP Streamable HTTP specification:
//! - HTTP POST requests to base URL for client-to-server communication
//! - Session management via Mcp-Session-Id headers
//! - Support for single JSON responses and SSE streams
//! - Automatic session extraction and inclusion
//! - Resumable connections with Last-Event-ID support
//! - Security validations and localhost binding

use std::sync::{Arc, Mutex};
use std::time::Duration;

use async_trait::async_trait;
use eventsource_stream::Eventsource;
use futures::StreamExt;
use reqwest::header::{HeaderMap, HeaderValue, CONTENT_TYPE};
use reqwest::{Client, Response, Url};
use tokio::sync::mpsc;
use tokio::time::timeout;

use super::{Transport, TransportConfig, TransportInfo};
use crate::error::{McpResult, TransportError};
use crate::messages::{JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse};

/// SSE event with ID for resumability
/// This infrastructure supports resumable connections per MCP spec
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct SseEvent {
    id: Option<String>,
    event_type: Option<String>,
    data: String,
    retry: Option<u64>,
}

/// Streamable HTTP transport for MCP communication.
///
/// This transport implements the official MCP Streamable HTTP specification:
/// - Every client-to-server message is sent as HTTP POST to the base URL
/// - Server assigns session ID via Mcp-Session-Id header during initialization  
/// - Client includes session ID in all subsequent requests
/// - Server responds with either single JSON or SSE stream based on Content-Type
/// - Supports resumable connections and message replay via Last-Event-ID
/// - Implements security best practices for Origin validation and localhost binding
pub struct HttpSseTransport {
    config: TransportConfig,
    http_client: Client,
    info: TransportInfo,
    session_id: Option<String>,
    base_url: Url,
    sse_receiver: Option<mpsc::UnboundedReceiver<JsonRpcMessage>>,
    _sse_task_handle: Option<tokio::task::JoinHandle<()>>,
    last_event_id: Option<String>,
    security_config: SecurityConfig,
    session_manager: SessionManager,
}

/// MCP protocol version for transport compatibility
#[derive(Debug, Clone, PartialEq)]
enum McpProtocolVersion {
    /// Modern Streamable HTTP (2025-03-26) - single /mcp endpoint, Mcp-Session-Id header
    StreamableHttp,
    /// Legacy HTTP+SSE (2024-11-05) - dual endpoints, sessionId query parameters  
    HttpSse,
    /// Auto-detect based on server behavior
    AutoDetect,
}

/// Generic session management for MCP SSE servers
#[derive(Debug, Clone)]
struct SessionManager {
    /// Whether to automatically discover sessions
    auto_discover: bool,
    /// Known session discovery endpoints (relative to base URL)
    discovery_endpoints: Vec<String>,
    /// Session timeout for renewal
    #[allow(dead_code)]
    session_timeout: Duration,
    /// Current session URL if different from base URL
    #[allow(dead_code)]
    active_session_url: Option<Url>,
    /// Session discovery task handle for background monitoring
    _discovery_task: Option<Arc<tokio::task::JoinHandle<()>>>,
    /// Receiver for fresh session IDs from background task
    session_receiver: Option<Arc<Mutex<tokio::sync::mpsc::UnboundedReceiver<String>>>>,
    /// Receiver for JSON-RPC messages from session monitor
    jsonrpc_receiver: Option<Arc<Mutex<tokio::sync::mpsc::UnboundedReceiver<JsonRpcMessage>>>>,
    /// Detected or configured protocol version
    protocol_version: McpProtocolVersion,
}

impl Default for SessionManager {
    fn default() -> Self {
        Self {
            auto_discover: true, // Enable continuous session monitoring
            discovery_endpoints: vec![
                "/events".to_string(),
                "/session".to_string(),
                "/discover".to_string(),
            ],
            session_timeout: Duration::from_secs(300), // 5 minutes default
            active_session_url: None,
            _discovery_task: None,
            session_receiver: None,
            jsonrpc_receiver: None,
            protocol_version: McpProtocolVersion::AutoDetect,
        }
    }
}

/// Security configuration for Streamable HTTP transport
#[derive(Debug, Clone)]
struct SecurityConfig {
    /// Validate Origin headers to prevent DNS rebinding attacks
    validate_origin: bool,
    /// Only allow connections to localhost for local servers
    enforce_localhost: bool,
    /// Require HTTPS in production environments
    require_https: bool,
    /// Validate session ID format and security
    validate_session_ids: bool,
    /// Allowed origins for CORS (used for SSE security validation)
    #[allow(dead_code)]
    allowed_origins: Vec<String>,
}

impl Default for SecurityConfig {
    fn default() -> Self {
        Self {
            validate_origin: true,
            enforce_localhost: true,
            require_https: false, // Allow HTTP for local development
            validate_session_ids: true,
            allowed_origins: vec![
                "http://localhost".to_string(),
                "https://localhost".to_string(),
            ],
        }
    }
}

impl HttpSseTransport {
    /// Create a new Streamable HTTP transport instance.
    ///
    /// # Arguments
    ///
    /// * `config` - Transport configuration containing HTTP settings
    ///
    /// # Returns
    ///
    /// A new transport instance ready for connection.
    pub fn new(config: TransportConfig) -> McpResult<Self> {
        let (http_client, base_url) = Self::build_http_client(&config)?;
        let info = TransportInfo::new("streamable-http");
        let security_config = Self::build_security_config(&config, &base_url)?;

        Ok(Self {
            config,
            http_client,
            info,
            session_id: None,
            base_url,
            sse_receiver: None,
            _sse_task_handle: None,
            last_event_id: None,
            security_config,
            session_manager: SessionManager::default(),
        })
    }

    /// Build security configuration based on transport config and URL
    fn build_security_config(
        _config: &TransportConfig,
        base_url: &Url,
    ) -> McpResult<SecurityConfig> {
        let mut security_config = SecurityConfig::default();

        // Enforce HTTPS for non-localhost URLs
        if base_url.host_str() != Some("localhost") && base_url.host_str() != Some("127.0.0.1") {
            security_config.require_https = true;
        }

        // Validate HTTPS requirement
        if security_config.require_https && base_url.scheme() != "https" {
            return Err(TransportError::InvalidConfig {
                transport_type: "streamable-http".to_string(),
                reason: format!("HTTPS required for non-localhost URL: {}", base_url),
            }
            .into());
        }

        // Validate localhost binding for local URLs
        if security_config.enforce_localhost {
            if let Some(host) = base_url.host_str() {
                if host != "localhost" && host != "127.0.0.1" && host != "::1" {
                    tracing::warn!(
                        "Connecting to non-localhost URL: {} - ensure this is intended",
                        base_url
                    );
                }
            }
        }

        Ok(security_config)
    }

    /// Build the HTTP client with appropriate configuration.
    fn build_http_client(config: &TransportConfig) -> McpResult<(Client, Url)> {
        if let TransportConfig::HttpSse(sse_config) = config {
            let mut builder = Client::builder();
            builder = builder.timeout(sse_config.timeout);

            // Add custom headers if specified
            if !sse_config.headers.is_empty() {
                let mut headers = HeaderMap::new();
                for (key, value) in &sse_config.headers {
                    if let (Ok(header_name), Ok(header_value)) = (
                        key.parse::<reqwest::header::HeaderName>(),
                        HeaderValue::from_str(value),
                    ) {
                        headers.insert(header_name, header_value);
                    }
                }
                builder = builder.default_headers(headers);
            }

            let client = builder.build().map_err(|e| TransportError::InvalidConfig {
                transport_type: "streamable-http".to_string(),
                reason: format!("Failed to build HTTP client: {}", e),
            })?;

            Ok((client, sse_config.base_url.clone()))
        } else {
            Err(TransportError::InvalidConfig {
                transport_type: "streamable-http".to_string(),
                reason: "Invalid configuration type".to_string(),
            }
            .into())
        }
    }

    /// Validate Origin header to prevent DNS rebinding attacks
    fn validate_origin(&self, _request_builder: &reqwest::RequestBuilder) -> McpResult<()> {
        if !self.security_config.validate_origin {
            return Ok(());
        }

        // For local connections, we should validate the origin
        if self.base_url.host_str() == Some("localhost")
            || self.base_url.host_str() == Some("127.0.0.1")
        {
            // Origin validation is important for localhost to prevent DNS rebinding
            tracing::debug!("Origin validation enabled for localhost connection");
        }

        Ok(())
    }

    /// Validate session ID security
    fn validate_session_id(&self, session_id: &str) -> McpResult<()> {
        if !self.security_config.validate_session_ids {
            return Ok(());
        }

        // Check session ID format (should be cryptographically secure)
        if session_id.len() < 16 {
            return Err(TransportError::InvalidConfig {
                transport_type: "streamable-http".to_string(),
                reason: "Session ID too short - security risk".to_string(),
            }
            .into());
        }

        // Check for basic format (alphanumeric and hyphens)
        if !session_id.chars().all(|c| c.is_alphanumeric() || c == '-') {
            return Err(TransportError::InvalidConfig {
                transport_type: "streamable-http".to_string(),
                reason: "Session ID contains invalid characters".to_string(),
            }
            .into());
        }

        Ok(())
    }

    /// Detect MCP protocol version based on endpoint and server behavior
    fn detect_protocol_version(&mut self) -> McpProtocolVersion {
        if self.session_manager.protocol_version != McpProtocolVersion::AutoDetect {
            return self.session_manager.protocol_version.clone();
        }

        // Auto-detect based on endpoint patterns
        match self.base_url.path() {
            "/mcp" => {
                tracing::info!(
                    "Detected Modern Streamable HTTP protocol (2025-03-26) - /mcp endpoint"
                );
                self.session_manager.protocol_version = McpProtocolVersion::StreamableHttp;
                McpProtocolVersion::StreamableHttp
            }
            "/sse" => {
                tracing::info!("Detected Legacy HTTP+SSE protocol (2024-11-05) - /sse endpoint");
                self.session_manager.protocol_version = McpProtocolVersion::HttpSse;
                McpProtocolVersion::HttpSse
            }
            path => {
                tracing::warn!(
                    "Unknown endpoint pattern: {}, defaulting to Modern Streamable HTTP",
                    path
                );
                self.session_manager.protocol_version = McpProtocolVersion::StreamableHttp;
                McpProtocolVersion::StreamableHttp
            }
        }
    }

    /// Send a request and handle both JSON and SSE responses according to MCP spec.
    async fn send_mcp_request(
        &mut self,
        message: JsonRpcMessage,
    ) -> McpResult<Option<JsonRpcResponse>> {
        // Get the freshest session ID available
        self.get_fresh_session_id().await;

        // Detect protocol version and route accordingly
        let protocol_version = self.detect_protocol_version();
        match protocol_version {
            McpProtocolVersion::StreamableHttp => {
                tracing::info!("Using Modern Streamable HTTP protocol (header-based sessions)");
                self.send_streamable_http_request(message).await
            }
            McpProtocolVersion::HttpSse => {
                tracing::info!("Using Legacy HTTP+SSE protocol (query parameter sessions)");
                self.send_legacy_sse_request(message).await
            }
            McpProtocolVersion::AutoDetect => {
                // This shouldn't happen after detection, but fallback to modern
                tracing::warn!(
                    "Protocol auto-detection failed, falling back to Modern Streamable HTTP"
                );
                self.send_streamable_http_request(message).await
            }
        }
    }

    /// Send request using Modern Streamable HTTP protocol (2025-03-26)
    async fn send_streamable_http_request(
        &mut self,
        message: JsonRpcMessage,
    ) -> McpResult<Option<JsonRpcResponse>> {
        let mut request_builder = self
            .http_client
            .post(self.base_url.clone())
            .header(CONTENT_TYPE, "application/json")
            .header("Accept", "application/json, text/event-stream");

        // Validate Origin header for security
        self.validate_origin(&request_builder)?;

        // Include session ID in Mcp-Session-Id header (Modern protocol)
        if let Some(ref session_id) = self.session_id {
            request_builder = request_builder.header("Mcp-Session-Id", session_id);
            tracing::info!("Using session ID in header (Modern): {}", session_id);
        }

        // Include Last-Event-ID for resumability
        if let Some(ref last_event_id) = self.last_event_id {
            request_builder = request_builder.header("Last-Event-ID", last_event_id);
            tracing::debug!("Resuming from last event ID: {}", last_event_id);
        }

        // Send the request
        let response = request_builder.json(&message).send().await.map_err(|e| {
            TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Modern HTTP request failed: {}", e),
            }
        })?;

        // Extract session ID from response header (for initialization)
        if let Some(session_header) = response.headers().get("mcp-session-id") {
            if let Ok(session_str) = session_header.to_str() {
                self.validate_session_id(session_str)?;
                tracing::info!("Extracted session ID from Modern response: {}", session_str);
                self.session_id = Some(session_str.to_string());
            }
        }

        // Handle response based on Content-Type
        let content_type = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|ct| ct.to_str().ok())
            .unwrap_or("application/json");

        tracing::info!("=== MODERN HTTP RESPONSE DEBUG ===");
        tracing::info!("Status: {}", response.status());
        tracing::info!("Content-Type: {}", content_type);
        tracing::info!("Headers: {:?}", response.headers());

        match content_type {
            ct if ct.contains("application/json") => {
                // Single JSON response - standard case
                let response_text =
                    response
                        .text()
                        .await
                        .map_err(|e| TransportError::SerializationError {
                            transport_type: "streamable-http".to_string(),
                            reason: format!("Failed to get Modern response text: {}", e),
                        })?;

                tracing::info!("=== MODERN JSON RESPONSE ===");
                tracing::info!("{}", response_text);

                let json_response: JsonRpcResponse =
                    serde_json::from_str(&response_text).map_err(|e| {
                        TransportError::SerializationError {
                            transport_type: "streamable-http".to_string(),
                            reason: format!("Failed to parse Modern JSON response: {}", e),
                        }
                    })?;
                Ok(Some(json_response))
            }
            ct if ct.contains("text/event-stream") => {
                // SSE stream response - for multiple messages
                tracing::info!("Modern protocol returned SSE stream");
                self.handle_sse_response(response).await?;

                // Wait for response via SSE stream
                if let JsonRpcMessage::Request(req) = message {
                    tracing::info!("Waiting for Modern SSE response to request ID: {}", req.id);
                    return Ok(Some(
                        self.wait_for_sse_response(&req.id.to_string(), Duration::from_secs(10))
                            .await?,
                    ));
                }
                Ok(None)
            }
            _ => Err(TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Unexpected Modern content type: {}", content_type),
            }
            .into()),
        }
    }

    /// Send request using Legacy HTTP+SSE protocol (2024-11-05)
    async fn send_legacy_sse_request(
        &mut self,
        message: JsonRpcMessage,
    ) -> McpResult<Option<JsonRpcResponse>> {
        tracing::info!("Sending request using Legacy HTTP+SSE protocol");

        // Wait for a fresh session ID before sending request
        let mut attempts = 0;
        while self.session_id.is_none() && attempts < 50 {
            self.get_fresh_session_id().await;
            if self.session_id.is_none() {
                tokio::time::sleep(Duration::from_millis(100)).await;
                attempts += 1;
            }
        }

        // Build URL with session ID in query parameters (Legacy protocol)
        let mut request_url = self.base_url.clone();
        if let Some(ref session_id) = self.session_id {
            request_url.set_query(Some(&format!("sessionId={}", session_id)));
            tracing::info!(
                "Using session ID in query parameter (Legacy): {}",
                session_id
            );
        } else {
            tracing::warn!("No session ID available for Legacy request after waiting");
        }

        tracing::info!("Sending Legacy POST request to: {}", request_url);

        let request_builder = self
            .http_client
            .post(request_url)
            .header(CONTENT_TYPE, "application/json")
            .header("Accept", "application/json, text/event-stream");

        // Send the JSON-RPC request
        let response = request_builder.json(&message).send().await.map_err(|e| {
            TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Legacy HTTP+SSE request failed: {}", e),
            }
        })?;

        let content_type = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|ct| ct.to_str().ok())
            .unwrap_or("");

        tracing::info!("=== LEGACY HTTP+SSE RESPONSE DEBUG ===");
        tracing::info!("Status: {}", response.status());
        tracing::info!("Content-Type: {}", content_type);
        tracing::info!("Headers: {:?}", response.headers());

        // Handle response based on Status and Content-Type
        match (response.status().as_u16(), content_type) {
            (202, _) => {
                // 202 Accepted - Legacy protocol, response will come via SSE stream
                tracing::info!("Legacy protocol: Request accepted (202), waiting for SSE response");

                // Wait for response via SSE stream
                if let JsonRpcMessage::Request(req) = message {
                    tracing::info!("Waiting for Legacy SSE response to request ID: {}", req.id);
                    return Ok(Some(
                        self.wait_for_sse_response(&req.id.to_string(), Duration::from_secs(10))
                            .await?,
                    ));
                }
                Ok(None)
            }
            (_, ct) if ct.contains("application/json") => {
                // Direct JSON response
                let response_text =
                    response
                        .text()
                        .await
                        .map_err(|e| TransportError::SerializationError {
                            transport_type: "streamable-http".to_string(),
                            reason: format!("Failed to get Legacy response text: {}", e),
                        })?;

                tracing::info!("=== LEGACY JSON RESPONSE ===");
                tracing::info!("{}", response_text);

                let json_response: JsonRpcResponse =
                    serde_json::from_str(&response_text).map_err(|e| {
                        TransportError::SerializationError {
                            transport_type: "streamable-http".to_string(),
                            reason: format!("Failed to parse Legacy JSON response: {}", e),
                        }
                    })?;
                Ok(Some(json_response))
            }
            (_, ct) if ct.contains("text/event-stream") => {
                // SSE stream response
                tracing::info!("Legacy protocol returned SSE stream");
                self.handle_sse_response(response).await?;

                // Wait for response via SSE stream
                if let JsonRpcMessage::Request(req) = message {
                    tracing::info!("Waiting for Legacy SSE response to request ID: {}", req.id);
                    return Ok(Some(
                        self.wait_for_sse_response(&req.id.to_string(), Duration::from_secs(10))
                            .await?,
                    ));
                }
                Ok(None)
            }
            (status, ct) => Err(TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!(
                    "Unexpected Legacy response - Status: {}, Content-Type: {}",
                    status, ct
                ),
            }
            .into()),
        }
    }

    /// Parse SSE event with ID tracking for resumability
    /// This infrastructure supports resumable connections per MCP spec
    #[allow(dead_code)]
    fn parse_sse_event(&self, event: &eventsource_stream::Event) -> Option<SseEvent> {
        Some(SseEvent {
            id: Some(event.id.clone()),
            event_type: Some(event.event.clone()),
            data: event.data.clone(),
            retry: event.retry.map(|d| d.as_millis() as u64),
        })
    }

    /// Handle SSE stream responses for server-to-client communication with resumability.
    async fn handle_sse_response(&mut self, response: Response) -> McpResult<()> {
        let event_stream = response.bytes_stream().eventsource();
        let (sender, receiver) = mpsc::unbounded_channel();
        self.sse_receiver = Some(receiver);

        // Track last event ID for resumability
        let current_last_event_id = self.last_event_id.clone();

        // Spawn task to handle SSE events
        let task_handle = tokio::spawn(async move {
            let mut stream = event_stream;
            let mut event_count = 0u64;
            let mut last_event_id = current_last_event_id;

            while let Some(event) = stream.next().await {
                match event {
                    Ok(event) => {
                        event_count += 1;

                        // Track event ID for resumability
                        if !event.id.is_empty() {
                            last_event_id = Some(event.id.clone());
                            tracing::trace!("Received SSE event with ID: {}", event.id);
                        }

                        // Parse event data as JSON-RPC message (skip session announcements)
                        if event.data.starts_with("/sse?sessionId=")
                            || event.data.starts_with("/mcp?sessionId=")
                        {
                            tracing::debug!("Skipping session announcement: {}", event.data);
                        } else if let Ok(message) =
                            serde_json::from_str::<JsonRpcMessage>(&event.data)
                        {
                            tracing::info!("Parsed JSON-RPC message from SSE: {:?}", message);
                            if sender.send(message).is_err() {
                                tracing::debug!(
                                    "SSE receiver dropped, stopping stream after {} events",
                                    event_count
                                );
                                break;
                            }
                        } else {
                            tracing::warn!("Failed to parse SSE message: {}", event.data);
                        }

                        // Handle retry directive from server
                        if let Some(retry_ms) = event.retry {
                            tracing::debug!(
                                "Server requested retry interval: {}ms",
                                retry_ms.as_millis()
                            );
                        }
                    }
                    Err(e) => {
                        tracing::error!("SSE stream error after {} events: {}", event_count, e);

                        // For network errors, we might want to retry with Last-Event-ID
                        if let Some(ref last_id) = last_event_id {
                            tracing::info!(
                                "Connection lost - can resume from event ID: {}",
                                last_id
                            );
                        }
                        break;
                    }
                }
            }
            tracing::debug!("SSE stream ended after {} events", event_count);
        });

        self._sse_task_handle = Some(task_handle);
        Ok(())
    }

    /// Resume SSE connection from last event ID
    pub async fn resume_sse_connection(&mut self) -> McpResult<()> {
        if let Some(ref last_event_id) = self.last_event_id {
            tracing::info!("Resuming SSE connection from event ID: {}", last_event_id);

            // Make a GET request to establish SSE connection with Last-Event-ID
            let mut request_builder = self
                .http_client
                .get(self.base_url.clone())
                .header("Accept", "text/event-stream")
                .header("Last-Event-ID", last_event_id);

            // Include session ID if we have one
            if let Some(ref session_id) = self.session_id {
                request_builder = request_builder.header("Mcp-Session-Id", session_id);
            }

            let response =
                request_builder
                    .send()
                    .await
                    .map_err(|e| TransportError::NetworkError {
                        transport_type: "streamable-http".to_string(),
                        reason: format!("Failed to resume SSE connection: {}", e),
                    })?;

            if response
                .headers()
                .get(CONTENT_TYPE)
                .and_then(|ct| ct.to_str().ok())
                == Some("text/event-stream")
            {
                self.handle_sse_response(response).await?;
                tracing::info!("SSE connection resumed successfully");
            } else {
                return Err(TransportError::NetworkError {
                    transport_type: "streamable-http".to_string(),
                    reason: "Server did not respond with SSE stream for resume request".to_string(),
                }
                .into());
            }
        }

        Ok(())
    }

    /// Get current session ID for debugging.
    pub fn session_id(&self) -> Option<&str> {
        self.session_id.as_deref()
    }

    /// Get last event ID for resumability
    pub fn last_event_id(&self) -> Option<&str> {
        self.last_event_id.as_deref()
    }

    /// Check if transport can resume from disconnection
    pub fn can_resume(&self) -> bool {
        self.last_event_id.is_some()
    }

    /// Start continuous session monitoring for MCP servers with ephemeral sessions
    async fn start_continuous_session_monitoring(&mut self) -> McpResult<()> {
        if !self.session_manager.auto_discover {
            return Ok(());
        }

        // Check if this is a Modern protocol endpoint that doesn't need session monitoring
        if self.base_url.path() == "/mcp" {
            tracing::info!(
                "Modern Streamable HTTP protocol detected - skipping session monitoring"
            );
            self.session_manager.protocol_version = McpProtocolVersion::StreamableHttp;
            return Ok(());
        }

        tracing::info!("Starting continuous session monitoring for MCP server");

        // Try each discovery endpoint to find one that works
        for endpoint in &self.session_manager.discovery_endpoints.clone() {
            if let Ok(Some(_)) = self.start_session_monitor_for_endpoint(endpoint).await {
                tracing::info!(
                    "Started continuous session monitoring via endpoint: {}",
                    endpoint
                );
                return Ok(());
            }
        }

        tracing::info!("No session monitoring endpoints available - proceeding without session");
        Ok(())
    }

    /// Start background monitoring for a specific endpoint
    async fn start_session_monitor_for_endpoint(
        &mut self,
        endpoint: &str,
    ) -> McpResult<Option<()>> {
        // For SSE endpoints, we need to discover sessions via /events, not the SSE endpoint itself
        let discovery_endpoint = if endpoint == "/sse" {
            "/events"
        } else {
            endpoint
        };

        let discovery_url =
            self.base_url
                .join(discovery_endpoint)
                .map_err(|e| TransportError::InvalidConfig {
                    transport_type: "streamable-http".to_string(),
                    reason: format!("Invalid discovery endpoint {}: {}", discovery_endpoint, e),
                })?;

        tracing::info!("Starting session monitor at: {}", discovery_url);

        // Test if endpoint responds with SSE
        let test_response = self
            .http_client
            .get(discovery_url.clone())
            .header("Accept", "text/event-stream")
            .send()
            .await
            .map_err(|e| TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Session monitor test failed: {}", e),
            })?;

        let content_type = test_response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|ct| ct.to_str().ok())
            .unwrap_or("");

        if !content_type.contains("text/event-stream") {
            tracing::debug!(
                "Endpoint {} does not provide SSE stream",
                discovery_endpoint
            );
            return Ok(None);
        }

        // Start background session monitoring task
        let (session_sender, session_receiver) = tokio::sync::mpsc::unbounded_channel();
        self.session_manager.session_receiver = Some(Arc::new(Mutex::new(session_receiver)));

        // Create JSON-RPC message channel for routing responses
        let (jsonrpc_sender, jsonrpc_receiver) = tokio::sync::mpsc::unbounded_channel();
        self.session_manager.jsonrpc_receiver = Some(Arc::new(Mutex::new(jsonrpc_receiver)));

        let client = self.http_client.clone();
        let url = discovery_url.clone();

        let task_handle = tokio::spawn(async move {
            tracing::info!("Background session monitor started for: {}", url);

            loop {
                match client
                    .get(url.clone())
                    .header("Accept", "text/event-stream")
                    .send()
                    .await
                {
                    Ok(response) => {
                        let event_stream = response.bytes_stream().eventsource();
                        let mut stream = event_stream;

                        while let Some(event_result) = stream.next().await {
                            match event_result {
                                Ok(event) => {
                                    tracing::info!(
                                        "Session monitor received: {} -> {}",
                                        event.event,
                                        event.data
                                    );

                                    // Try to parse as JSON-RPC message first
                                    if let Ok(json_rpc_message) =
                                        serde_json::from_str::<JsonRpcMessage>(&event.data)
                                    {
                                        tracing::info!(
                                            "JSON-RPC message received via session monitor: {:?}",
                                            json_rpc_message
                                        );

                                        // Send JSON-RPC message to main transport for correlation
                                        if jsonrpc_sender.send(json_rpc_message).is_err() {
                                            tracing::debug!(
                                                "JSON-RPC receiver dropped, stopping monitor"
                                            );
                                            return;
                                        }
                                    } else if let Some(session_info) =
                                        Self::extract_session_from_event_data_static(&event.data)
                                    {
                                        tracing::info!(
                                            "Fresh session discovered: {}",
                                            session_info
                                        );

                                        // Send fresh session to the transport
                                        if session_sender.send(session_info).is_err() {
                                            tracing::debug!(
                                                "Session receiver dropped, stopping monitor"
                                            );
                                            return;
                                        }
                                    }
                                }
                                Err(e) => {
                                    tracing::warn!("Session monitor stream error: {}", e);
                                    break;
                                }
                            }
                        }
                    }
                    Err(e) => {
                        tracing::warn!("Session monitor connection failed: {}", e);
                        tokio::time::sleep(Duration::from_secs(5)).await;
                    }
                }

                // Small delay before reconnecting
                tokio::time::sleep(Duration::from_secs(1)).await;
            }
        });

        self.session_manager._discovery_task = Some(Arc::new(task_handle));
        Ok(Some(()))
    }

    /// Static version of session extraction for use in background task
    fn extract_session_from_event_data_static(data: &str) -> Option<String> {
        // Pattern 1: Full URL path with session (/sse?sessionId=...) - preferred
        if let Some(url_start) = data.find("/sse?sessionId=") {
            let session_path = &data[url_start..];
            if let Some(session_end) = session_path.find(|c: char| c.is_whitespace() || c == '\n') {
                return Some(session_path[..session_end].to_string());
            } else {
                return Some(session_path.to_string());
            }
        }

        // Pattern 2: Direct sessionId=value format - extract just the ID
        if let Some(captures) = regex::Regex::new(r"sessionId=([a-fA-F0-9\-]+)")
            .ok()
            .and_then(|re| re.captures(data))
        {
            if let Some(session_match) = captures.get(1) {
                return Some(session_match.as_str().to_string());
            }
        }

        None
    }

    /// Send JSON-RPC request to SSE endpoint with session management (Legacy HTTP+SSE protocol)
    #[allow(dead_code)]
    async fn establish_sse_connection_with_message(
        &mut self,
        message: JsonRpcMessage,
    ) -> McpResult<Option<JsonRpcResponse>> {
        tracing::info!(
            "Sending JSON-RPC request to SSE endpoint (Legacy HTTP+SSE): {}",
            self.base_url
        );

        // Wait for a fresh session ID before sending request
        let mut attempts = 0;
        while self.session_id.is_none() && attempts < 50 {
            self.get_fresh_session_id().await;
            if self.session_id.is_none() {
                tokio::time::sleep(Duration::from_millis(100)).await;
                attempts += 1;
            }
        }

        // For legacy HTTP+SSE protocol, we need to use query parameters, not headers
        let mut request_url = self.base_url.clone();
        if let Some(ref session_id) = self.session_id {
            request_url.set_query(Some(&format!("sessionId={}", session_id)));
            tracing::info!(
                "Using session ID in query parameter for legacy SSE request: {}",
                session_id
            );
        } else {
            tracing::warn!("No session ID available for SSE request after waiting");
        }

        tracing::info!("Sending POST request to: {}", request_url);

        let request_builder = self
            .http_client
            .post(request_url)
            .header(CONTENT_TYPE, "application/json")
            .header("Accept", "application/json, text/event-stream");

        // Send the JSON-RPC request
        let response = request_builder.json(&message).send().await.map_err(|e| {
            TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Legacy SSE JSON-RPC request failed: {}", e),
            }
        })?;

        let content_type = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|ct| ct.to_str().ok())
            .unwrap_or("");

        tracing::info!(
            "SSE JSON-RPC Response - Status: {}, Content-Type: {}",
            response.status(),
            content_type
        );

        // Handle response based on Content-Type (same as /mcp endpoint)
        match content_type {
            ct if ct.contains("application/json") => {
                // Direct JSON response
                let response_text =
                    response
                        .text()
                        .await
                        .map_err(|e| TransportError::SerializationError {
                            transport_type: "streamable-http".to_string(),
                            reason: format!("Failed to get SSE response text: {}", e),
                        })?;

                tracing::info!("=== SSE JSON RESPONSE ===");
                tracing::info!("{}", response_text);

                let json_response: JsonRpcResponse =
                    serde_json::from_str(&response_text).map_err(|e| {
                        TransportError::SerializationError {
                            transport_type: "streamable-http".to_string(),
                            reason: format!("Failed to parse SSE JSON response: {}", e),
                        }
                    })?;
                Ok(Some(json_response))
            }
            ct if ct.contains("text/event-stream") => {
                // SSE stream response
                tracing::info!("SSE endpoint returned event stream - handling SSE response");
                self.handle_sse_response(response).await?;

                // Wait for response via SSE stream
                if let JsonRpcMessage::Request(req) = message {
                    tracing::info!("Waiting for SSE response to request ID: {}", req.id);
                    return Ok(Some(
                        self.wait_for_sse_response(&req.id.to_string(), Duration::from_secs(10))
                            .await?,
                    ));
                }
                Ok(None)
            }
            _ => Err(TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Unexpected SSE response content type: {}", content_type),
            }
            .into()),
        }
    }

    /// Send JSON-RPC request to SSE endpoint using GET with session parameters
    #[allow(dead_code)]
    async fn send_sse_get_request(
        &mut self,
        message: JsonRpcMessage,
    ) -> McpResult<Option<JsonRpcResponse>> {
        tracing::info!("Sending JSON-RPC to SSE endpoint via GET request");

        // Wait for a fresh session ID before sending request
        let mut attempts = 0;
        while self.session_id.is_none() && attempts < 50 {
            self.get_fresh_session_id().await;
            if self.session_id.is_none() {
                tokio::time::sleep(Duration::from_millis(100)).await;
                attempts += 1;
            }
        }

        // Build URL with session ID in query parameters (legacy HTTP+SSE protocol)
        let mut request_url = self.base_url.clone();
        if let Some(ref session_id) = self.session_id {
            request_url.set_query(Some(&format!("sessionId={}", session_id)));
            tracing::info!(
                "Using session ID in query parameter for SSE GET: {}",
                session_id
            );
        } else {
            tracing::warn!("No session ID available for SSE GET request after waiting");
        }

        tracing::info!("Sending GET request to: {}", request_url);

        // Send GET request to establish SSE connection with session
        let response = self
            .http_client
            .get(request_url)
            .header("Accept", "text/event-stream")
            .send()
            .await
            .map_err(|e| TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("SSE GET request failed: {}", e),
            })?;

        let content_type = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|ct| ct.to_str().ok())
            .unwrap_or("");

        tracing::info!(
            "SSE GET Response - Status: {}, Content-Type: {}",
            response.status(),
            content_type
        );

        if content_type.contains("text/event-stream") {
            tracing::info!("SSE connection established via GET - handling SSE stream");
            self.handle_sse_response(response).await?;

            // For SSE connections, we need to wait for the response to our message
            if let JsonRpcMessage::Request(req) = message {
                tracing::info!("Waiting for SSE response to request ID: {}", req.id);
                return Ok(Some(
                    self.wait_for_sse_response(&req.id.to_string(), Duration::from_secs(10))
                        .await?,
                ));
            }

            Ok(None)
        } else {
            Err(TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Expected SSE stream but got: {}", content_type),
            }
            .into())
        }
    }

    /// Get the most recent session ID from the background monitor (only for Legacy protocol)
    async fn get_fresh_session_id(&mut self) -> Option<String> {
        // For Modern protocol, don't use session monitor - use response headers instead
        if self.session_manager.protocol_version == McpProtocolVersion::StreamableHttp {
            return self.session_id.clone();
        }

        if let Some(ref receiver_arc) = self.session_manager.session_receiver {
            if let Ok(mut receiver) = receiver_arc.lock() {
                // Try to get the most recent session (non-blocking)
                while let Ok(session_info) = receiver.try_recv() {
                    tracing::info!("Received fresh session: {}", session_info);

                    // Extract session ID from either URL format or direct ID
                    if session_info.starts_with("/sse?sessionId=") {
                        // Extract session ID from URL format
                        if let Some(session_id) = session_info.split("sessionId=").nth(1) {
                            self.session_id = Some(session_id.to_string());
                            tracing::info!("Extracted session ID from URL: {}", session_id);
                        }
                    } else {
                        // Direct session ID
                        self.session_id = Some(session_info.clone());
                        tracing::info!("Updated to fresh session ID: {}", session_info);
                    }
                }
            }
        }
        self.session_id.clone()
    }

    /// Try to discover session information from a specific endpoint
    #[allow(dead_code)]
    async fn try_discover_session_from_endpoint(
        &mut self,
        endpoint: &str,
    ) -> McpResult<Option<String>> {
        let discovery_url =
            self.base_url
                .join(endpoint)
                .map_err(|e| TransportError::InvalidConfig {
                    transport_type: "streamable-http".to_string(),
                    reason: format!("Invalid discovery endpoint {}: {}", endpoint, e),
                })?;

        tracing::debug!("Trying session discovery at: {}", discovery_url);

        // Try to get session information via SSE stream
        let response = self
            .http_client
            .get(discovery_url.clone())
            .header("Accept", "text/event-stream, application/json")
            .send()
            .await
            .map_err(|e| TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Discovery request failed: {}", e),
            })?;

        let content_type = response
            .headers()
            .get(CONTENT_TYPE)
            .and_then(|ct| ct.to_str().ok())
            .unwrap_or("");

        match content_type {
            ct if ct.contains("text/event-stream") => self.parse_session_from_sse(response).await,
            ct if ct.contains("application/json") => self.parse_session_from_json(response).await,
            _ => {
                tracing::debug!(
                    "Unexpected content type for session discovery: {}",
                    content_type
                );
                Ok(None)
            }
        }
    }

    /// Parse session information from SSE stream (e.g., Playwright-style)
    #[allow(dead_code)]
    async fn parse_session_from_sse(&mut self, response: Response) -> McpResult<Option<String>> {
        use futures::StreamExt;

        let event_stream = response.bytes_stream().eventsource();
        let mut stream = event_stream;

        // Listen for the first few events to find session information
        let timeout_duration = Duration::from_secs(5);
        let deadline = tokio::time::Instant::now() + timeout_duration;

        while let Ok(Some(event_result)) = tokio::time::timeout_at(deadline, stream.next()).await {
            match event_result {
                Ok(event) => {
                    tracing::debug!("Discovery SSE event: {} -> {}", event.event, event.data);

                    // Look for session information in various formats
                    if let Some(session_info) = self.extract_session_from_event_data(&event.data) {
                        return Ok(Some(session_info));
                    }
                }
                Err(e) => {
                    tracing::debug!("SSE discovery error: {}", e);
                    break;
                }
            }
        }

        Ok(None)
    }

    /// Parse session information from JSON response
    #[allow(dead_code)]
    async fn parse_session_from_json(&mut self, response: Response) -> McpResult<Option<String>> {
        let json_text = response
            .text()
            .await
            .map_err(|e| TransportError::SerializationError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Failed to read JSON discovery response: {}", e),
            })?;

        // Try to parse as JSON and look for session information
        if let Ok(value) = serde_json::from_str::<serde_json::Value>(&json_text) {
            // Look for session info in common JSON patterns
            if let Some(session_id) = value
                .get("sessionId")
                .or_else(|| value.get("session_id"))
                .or_else(|| value.get("session"))
                .and_then(|v| v.as_str())
            {
                return Ok(Some(session_id.to_string()));
            }

            // Look for endpoint URL patterns
            if let Some(endpoint) = value
                .get("endpoint")
                .or_else(|| value.get("url"))
                .and_then(|v| v.as_str())
            {
                if let Some(session_info) = self.extract_session_from_event_data(endpoint) {
                    return Ok(Some(session_info));
                }
            }
        }

        Ok(None)
    }

    /// Extract session information from event data (handles multiple formats)
    #[allow(dead_code)]
    fn extract_session_from_event_data(&self, data: &str) -> Option<String> {
        // Pattern 1: Full URL path with session (/sse?sessionId=...) - preferred
        if let Some(url_start) = data.find("/sse?sessionId=") {
            let session_path = &data[url_start..];
            if let Some(session_end) = session_path.find(|c: char| c.is_whitespace() || c == '\n') {
                return Some(session_path[..session_end].to_string());
            } else {
                return Some(session_path.to_string());
            }
        }

        // Pattern 2: Direct sessionId=value format (like Playwright) - extract just the ID
        if let Some(captures) = regex::Regex::new(r"sessionId=([a-fA-F0-9\-]+)")
            .ok()
            .and_then(|re| re.captures(data))
        {
            if let Some(session_match) = captures.get(1) {
                return Some(session_match.as_str().to_string());
            }
        }

        // Pattern 3: JSON-like format
        if let Ok(value) = serde_json::from_str::<serde_json::Value>(data) {
            if let Some(session_id) = value
                .get("sessionId")
                .or_else(|| value.get("session_id"))
                .and_then(|v| v.as_str())
            {
                return Some(session_id.to_string());
            }
        }

        None
    }

    /// Update session information from discovered data  
    #[allow(dead_code)]
    fn apply_discovered_session(&mut self, session_info: &str) -> McpResult<()> {
        // If the session info looks like a complete URL path, update base URL for /sse endpoint
        if session_info.starts_with('/') && session_info.contains("sse") {
            match self.base_url.join(session_info) {
                Ok(new_url) => {
                    tracing::info!(
                        "Updated base URL to use discovered session endpoint: {}",
                        new_url
                    );
                    self.session_manager.active_session_url = Some(new_url.clone());
                    self.base_url = new_url;

                    // Also extract session ID for any header usage
                    if let Some(session_start) = session_info.find("sessionId=") {
                        let id_part = &session_info[session_start + 10..]; // Skip "sessionId="
                        if let Some(id_end) =
                            id_part.find(|c: char| !c.is_alphanumeric() && c != '-')
                        {
                            self.session_id = Some(id_part[..id_end].to_string());
                        } else {
                            self.session_id = Some(id_part.to_string());
                        }
                    }
                }
                Err(e) => {
                    tracing::warn!(
                        "Failed to update URL with session path {}: {}",
                        session_info,
                        e
                    );
                    return Ok(());
                }
            }
        } else {
            // Use as session ID directly for header-based sessions (like /mcp endpoint)
            tracing::info!(
                "Using session ID for header-based requests: {}",
                session_info
            );
            self.session_id = Some(session_info.to_string());
        }

        Ok(())
    }

    /// Wait for a specific response from the SSE stream or session monitor
    async fn wait_for_sse_response(
        &mut self,
        request_id: &str,
        timeout_duration: Duration,
    ) -> McpResult<JsonRpcResponse> {
        tracing::debug!("Waiting for response to request ID: {}", request_id);

        // For Legacy protocol, check session monitor's JSON-RPC receiver first
        if let Some(ref jsonrpc_receiver_arc) = self.session_manager.jsonrpc_receiver {
            tracing::debug!("Checking session monitor for Legacy protocol response");

            let deadline = tokio::time::Instant::now() + timeout_duration;

            while tokio::time::Instant::now() < deadline {
                if let Ok(mut receiver) = jsonrpc_receiver_arc.lock() {
                    match receiver.try_recv() {
                        Ok(message) => {
                            tracing::info!("Received message from session monitor: {:?}", message);
                            match message {
                                JsonRpcMessage::Response(response) => {
                                    if response.id.to_string() == request_id {
                                        tracing::info!("Found matching response via session monitor for request ID: {}", request_id);
                                        self.info.increment_responses_received();
                                        return Ok(response);
                                    } else {
                                        tracing::debug!(
                                            "Response for different request ID: {} (expected: {})",
                                            response.id,
                                            request_id
                                        );
                                    }
                                }
                                _ => {
                                    tracing::debug!("Non-response message from session monitor");
                                }
                            }
                        }
                        Err(tokio::sync::mpsc::error::TryRecvError::Empty) => {
                            // No message available, continue checking
                        }
                        Err(tokio::sync::mpsc::error::TryRecvError::Disconnected) => {
                            tracing::warn!("Session monitor JSON-RPC channel disconnected");
                            break;
                        }
                    }
                }

                // Small delay before checking again
                tokio::time::sleep(Duration::from_millis(50)).await;
            }
        }

        // Fallback to main SSE receiver for Modern protocol
        if let Some(receiver) = self.sse_receiver.as_mut() {
            tracing::debug!("Checking main SSE receiver for Modern protocol response");

            let deadline = tokio::time::Instant::now() + timeout_duration;

            loop {
                let remaining_time =
                    deadline.saturating_duration_since(tokio::time::Instant::now());
                if remaining_time.is_zero() {
                    break;
                }

                let message = timeout(remaining_time, receiver.recv())
                    .await
                    .map_err(|_| TransportError::TimeoutError {
                        transport_type: "streamable-http".to_string(),
                        reason: format!("SSE response timeout for request ID: {}", request_id),
                    })?
                    .ok_or_else(|| TransportError::DisconnectedError {
                        transport_type: "streamable-http".to_string(),
                        reason: "SSE stream closed while waiting for response".to_string(),
                    })?;

                match message {
                    JsonRpcMessage::Response(response) => {
                        if response.id.to_string() == request_id {
                            tracing::info!(
                                "Found matching response via main SSE for request ID: {}",
                                request_id
                            );
                            self.info.increment_responses_received();
                            return Ok(response);
                        } else {
                            tracing::debug!(
                                "Response for different request ID: {} (expected: {})",
                                response.id,
                                request_id
                            );
                        }
                    }
                    _ => {
                        tracing::debug!("Non-response message from main SSE");
                    }
                }
            }
        }

        Err(TransportError::TimeoutError {
            transport_type: "streamable-http".to_string(),
            reason: format!("Timeout waiting for response to request ID: {}", request_id),
        }
        .into())
    }
}

#[async_trait]
impl Transport for HttpSseTransport {
    async fn connect(&mut self) -> McpResult<()> {
        tracing::info!("Connecting Streamable HTTP transport to: {}", self.base_url);

        // Step 1: Start continuous session monitoring for MCP servers that require it
        self.start_continuous_session_monitoring().await?;

        // Step 2: Test connectivity with a simple request
        let test_response = self.http_client.head(self.base_url.clone()).send().await;

        match test_response {
            Ok(_) => {
                self.info.mark_connected();
                tracing::info!("Streamable HTTP transport connected successfully");
                Ok(())
            }
            Err(e) => Err(TransportError::ConnectionError {
                transport_type: "streamable-http".to_string(),
                reason: format!("Failed to connect to server: {}", e),
            }
            .into()),
        }
    }

    async fn disconnect(&mut self) -> McpResult<()> {
        tracing::info!("Disconnecting Streamable HTTP transport");

        // Terminate session if we have one
        if let Some(ref session_id) = self.session_id {
            let _ = self
                .http_client
                .delete(self.base_url.clone())
                .header("Mcp-Session-Id", session_id)
                .send()
                .await;
        }

        // Clean up SSE resources
        self.sse_receiver = None;
        if let Some(handle) = self._sse_task_handle.take() {
            handle.abort();
        }

        self.session_id = None;
        self.info.mark_disconnected();

        tracing::info!("Streamable HTTP transport disconnected");
        Ok(())
    }

    fn is_connected(&self) -> bool {
        self.info.connected
    }

    async fn send_request(
        &mut self,
        request: JsonRpcRequest,
        timeout_duration: Option<Duration>,
    ) -> McpResult<JsonRpcResponse> {
        if !self.is_connected() {
            return Err(TransportError::NotConnected {
                transport_type: "streamable-http".to_string(),
                reason: "Transport not connected".to_string(),
            }
            .into());
        }

        let request_id = request.id.to_string();
        tracing::debug!(
            "HTTP SSE transport sending request: {} with ID: {}",
            request.method,
            request_id
        );
        let timeout_duration = timeout_duration.unwrap_or(Duration::from_secs(30));

        // Send request with timeout
        let response = timeout(
            timeout_duration,
            self.send_mcp_request(JsonRpcMessage::Request(request)),
        )
        .await
        .map_err(|_| TransportError::TimeoutError {
            transport_type: "streamable-http".to_string(),
            reason: format!("Request timed out after {:?}", timeout_duration),
        })??;

        self.info.increment_requests_sent();

        match response {
            Some(json_response) => {
                tracing::debug!(
                    "HTTP SSE transport received direct JSON response for request ID: {}",
                    json_response.id
                );
                self.info.increment_responses_received();
                Ok(json_response)
            }
            None => {
                // Response will come via SSE stream - wait for it
                tracing::debug!(
                    "HTTP SSE transport: waiting for response via SSE stream for request ID: {}",
                    request_id
                );
                self.wait_for_sse_response(&request_id, timeout_duration)
                    .await
            }
        }
    }

    async fn send_notification(&mut self, notification: JsonRpcNotification) -> McpResult<()> {
        if !self.is_connected() {
            return Err(TransportError::NotConnected {
                transport_type: "streamable-http".to_string(),
                reason: "Transport not connected".to_string(),
            }
            .into());
        }

        tracing::debug!(
            "HTTP SSE transport sending notification: {}",
            notification.method
        );

        // Notifications don't expect responses - send directly without parsing response
        let mut request_builder = self
            .http_client
            .post(self.base_url.clone())
            .header(CONTENT_TYPE, "application/json")
            .header("Accept", "application/json, text/event-stream");

        // Validate Origin header for security
        self.validate_origin(&request_builder)?;

        // Include session ID if we have one
        if let Some(ref session_id) = self.session_id {
            request_builder = request_builder.header("Mcp-Session-Id", session_id);
        }

        // Send the notification - ignore response content
        let _response = request_builder
            .json(&JsonRpcMessage::Notification(notification))
            .send()
            .await
            .map_err(|e| TransportError::NetworkError {
                transport_type: "streamable-http".to_string(),
                reason: format!("HTTP notification failed: {}", e),
            })?;

        self.info.increment_notifications_sent();
        tracing::debug!("HTTP SSE transport notification sent successfully");
        Ok(())
    }

    async fn receive_message(
        &mut self,
        timeout_duration: Option<Duration>,
    ) -> McpResult<JsonRpcMessage> {
        if !self.is_connected() {
            return Err(TransportError::NotConnected {
                transport_type: "streamable-http".to_string(),
                reason: "Transport not connected".to_string(),
            }
            .into());
        }

        let receiver = self
            .sse_receiver
            .as_mut()
            .ok_or_else(|| TransportError::NotConnected {
                transport_type: "streamable-http".to_string(),
                reason: "No SSE stream available - server uses single JSON responses".to_string(),
            })?;

        let message = if let Some(timeout_duration) = timeout_duration {
            timeout(timeout_duration, receiver.recv())
                .await
                .map_err(|_| TransportError::TimeoutError {
                    transport_type: "streamable-http".to_string(),
                    reason: format!("Message receive timed out after {:?}", timeout_duration),
                })?
                .ok_or_else(|| TransportError::DisconnectedError {
                    transport_type: "streamable-http".to_string(),
                    reason: "SSE stream closed".to_string(),
                })?
        } else {
            receiver
                .recv()
                .await
                .ok_or_else(|| TransportError::DisconnectedError {
                    transport_type: "streamable-http".to_string(),
                    reason: "SSE stream closed".to_string(),
                })?
        };

        // Update statistics
        match &message {
            JsonRpcMessage::Request(_) => {
                // Server-to-client request via SSE
            }
            JsonRpcMessage::Response(_) => {
                self.info.increment_responses_received();
            }
            JsonRpcMessage::Notification(_) => {
                self.info.increment_notifications_received();
            }
        }

        Ok(message)
    }

    fn get_info(&self) -> TransportInfo {
        let mut info = self.info.clone();

        // Add Streamable HTTP specific metadata
        info.add_metadata("base_url", serde_json::json!(self.base_url.to_string()));
        info.add_metadata("session_id", serde_json::json!(self.session_id));
        info.add_metadata(
            "has_sse_stream",
            serde_json::json!(self.sse_receiver.is_some()),
        );
        info.add_metadata("last_event_id", serde_json::json!(self.last_event_id));
        info.add_metadata("can_resume", serde_json::json!(self.can_resume()));
        info.add_metadata(
            "security_enabled",
            serde_json::json!(self.security_config.validate_origin),
        );

        if let TransportConfig::HttpSse(config) = &self.config {
            info.add_metadata("timeout", serde_json::json!(config.timeout.as_secs()));
            info.add_metadata("headers", serde_json::json!(config.headers));
            info.add_metadata("has_auth", serde_json::json!(config.auth.is_some()));
            info.add_metadata(
                "enforce_https",
                serde_json::json!(self.security_config.require_https),
            );
            info.add_metadata(
                "localhost_only",
                serde_json::json!(self.security_config.enforce_localhost),
            );
        }

        info
    }

    fn get_config(&self) -> &TransportConfig {
        &self.config
    }
}

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

    #[test]
    fn test_streamable_http_transport_creation() {
        let config = TransportConfig::http_sse("https://example.com/mcp").unwrap();
        let transport = HttpSseTransport::new(config).unwrap();

        assert_eq!(transport.get_info().transport_type, "streamable-http");
        assert!(!transport.is_connected());
        assert!(transport.session_id().is_none());
    }

    #[test]
    fn test_base_url_extraction() {
        let config = TransportConfig::http_sse("https://example.com/mcp").unwrap();
        let transport = HttpSseTransport::new(config).unwrap();

        assert_eq!(transport.base_url.to_string(), "https://example.com/mcp");
    }

    #[test]
    fn test_transport_info_metadata() {
        let config = TransportConfig::http_sse("https://example.com/mcp").unwrap();
        let transport = HttpSseTransport::new(config).unwrap();

        let info = transport.get_info();
        assert!(info.metadata.contains_key("base_url"));
        assert!(info.metadata.contains_key("session_id"));
        assert!(info.metadata.contains_key("has_sse_stream"));
        assert!(info.metadata.contains_key("last_event_id"));
        assert!(info.metadata.contains_key("can_resume"));
        assert!(info.metadata.contains_key("security_enabled"));
    }

    #[test]
    fn test_security_config_https_enforcement() {
        // Should require HTTPS for non-localhost
        let config = TransportConfig::http_sse("http://example.com/mcp").unwrap();
        let result = HttpSseTransport::new(config);
        assert!(result.is_err());

        // Should allow HTTP for localhost
        let config = TransportConfig::http_sse("http://localhost:3000/mcp").unwrap();
        let result = HttpSseTransport::new(config);
        assert!(result.is_ok());
    }

    #[test]
    fn test_session_id_validation() {
        let config = TransportConfig::http_sse("http://localhost:3000/mcp").unwrap();
        let transport = HttpSseTransport::new(config).unwrap();

        // Valid session ID
        assert!(transport
            .validate_session_id("550e8400-e29b-41d4-a716-446655440000")
            .is_ok());

        // Invalid session ID (too short)
        assert!(transport.validate_session_id("short").is_err());

        // Invalid session ID (invalid characters)
        assert!(transport.validate_session_id("invalid@session!id").is_err());
    }

    #[test]
    fn test_resumability_features() {
        let config = TransportConfig::http_sse("http://localhost:3000/mcp").unwrap();
        let transport = HttpSseTransport::new(config).unwrap();

        // Initially no resumability
        assert!(!transport.can_resume());
        assert!(transport.last_event_id().is_none());
    }
}