thoughtjack 0.6.0

Adversarial agent security testing tool
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
//! HTTP transport implementation (TJ-SPEC-002 F-003).
//!
//! Implements the [`Transport`] trait over HTTP using axum. Incoming JSON-RPC
//! requests arrive via `POST /message` (legacy) or `POST /mcp` (Streamable HTTP),
//! responses stream back as chunked HTTP bodies, and server-initiated
//! notifications/requests are broadcast via Server-Sent Events on `GET /sse`
//! (legacy) or `GET /mcp` (Streamable HTTP).

use std::io;
use std::net::SocketAddr;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};

use axum::Router;
use axum::body::Body;
use axum::extract::{ConnectInfo, State};
use axum::http::StatusCode;
use axum::response::sse::{Event as SseEvent, KeepAlive, Sse};
use axum::response::{IntoResponse, Response};
use axum::routing::{get, post};
use bytes::Bytes;
use dashmap::DashMap;
use tokio::net::TcpListener;
use tokio::sync::{broadcast, mpsc};
use tokio::task::JoinHandle;
use tokio::time::Instant;
use tokio_stream::StreamExt;
use tokio_stream::wrappers::ReceiverStream;
use tokio_util::sync::CancellationToken;
use tracing::{debug, info};

use super::{
    ConnectionContext, JsonRpcMessage, JsonRpcRequest, JsonRpcResponse, RawResponseWriter, Result,
    Transport, TransportType,
};
use crate::error::TransportError;

/// Configuration for the HTTP transport.
///
/// Implements: TJ-SPEC-002 F-003
#[derive(Debug, Clone)]
pub struct HttpConfig {
    /// Address to bind to, e.g. `"0.0.0.0:8080"`.
    pub bind_addr: String,
    /// Maximum allowed request body size in bytes.
    pub max_message_size: usize,
}

/// An incoming request received by the `POST /message` handler.
struct IncomingRequest {
    message: JsonRpcMessage,
    response_tx: Option<mpsc::Sender<std::result::Result<Bytes, io::Error>>>,
    connection_id: u64,
    remote_addr: SocketAddr,
    connected_at: Instant,
}

/// Per-connection state tracked while a request is in flight.
pub struct ConnectionState {
    /// Remote address of the client.
    pub remote_addr: SocketAddr,
    /// When this connection was established.
    pub connected_at: Instant,
    /// Running count of requests on this connection.
    pub request_count: AtomicU64,
}

/// Maximum number of concurrent SSE connections.
const MAX_SSE_CONNECTIONS: usize = 16;

/// Shared state between the axum handlers and `HttpTransport`.
struct HttpSharedState {
    incoming_tx: mpsc::Sender<IncomingRequest>,
    sse_tx: broadcast::Sender<String>,
    connections: Arc<DashMap<u64, ConnectionState>>,
    next_connection_id: AtomicU64,
    max_message_size: usize,
    sse_connections: AtomicUsize,
    cancel: CancellationToken,
    // TODO(v0.6): make session ID configurable — auto (UUID, current default),
    // custom (user-provided string), or none (no Mcp-Session-Id header).
    // Deferred: not needed for v0.5 adversarial testing scenarios.
    session_id: String,
    /// Pending server-initiated request/response channels keyed by JSON-RPC request ID.
    ///
    /// When the server sends a request to the client (e.g., `sampling/createMessage`
    /// or `elicitation/create`), a oneshot sender is registered here. The POST handler
    /// routes the client's JSON-RPC Response to the matching oneshot.
    pending_server_requests: tokio::sync::Mutex<
        std::collections::HashMap<String, tokio::sync::oneshot::Sender<JsonRpcMessage>>,
    >,
}

/// RAII guard that removes a connection from the `DashMap` on drop.
///
/// Ensures connection tracking is cleaned up on all exit paths
/// (success, error, panic) in the HTTP handler pipeline.
///
/// Implements: TJ-SPEC-002 F-003
struct ConnectionGuard {
    connections: Arc<DashMap<u64, ConnectionState>>,
    connection_id: u64,
}

impl ConnectionGuard {
    const fn new(connections: Arc<DashMap<u64, ConnectionState>>, connection_id: u64) -> Self {
        Self {
            connections,
            connection_id,
        }
    }
}

impl Drop for ConnectionGuard {
    fn drop(&mut self) {
        self.connections.remove(&self.connection_id);
    }
}

/// HTTP transport implementing the [`Transport`] trait via a channel bridge.
///
/// Axum handlers push requests into an internal channel; [`Transport::receive_message`]
/// reads from the channel. Responses flow back through per-request response channels
/// that drive chunked HTTP response bodies.
///
/// Implements: TJ-SPEC-002 F-003
pub struct HttpTransport {
    shared: Arc<HttpSharedState>,
    incoming_rx: tokio::sync::Mutex<mpsc::Receiver<IncomingRequest>>,
    current_response:
        tokio::sync::Mutex<Option<mpsc::Sender<std::result::Result<Bytes, io::Error>>>>,
    // std::sync::Mutex is intentional: held briefly for field access, never across .await points.
    // Per tokio docs, std::sync::Mutex is preferred when the critical section is short and synchronous.
    current_context: std::sync::Mutex<ConnectionContext>,
    /// RAII guard that cleans up connection tracking on drop.
    // std::sync::Mutex: same rationale as current_context — brief, synchronous access only.
    current_guard: std::sync::Mutex<Option<ConnectionGuard>>,
    /// Retains recent connection guards to prevent premature removal from
    /// the tracking `DashMap`. Without this, replacing `current_guard` drops
    /// the old guard immediately, removing the connection entry while its
    /// response channel may still be in use. Capped at 2 to bound memory.
    previous_guards: std::sync::Mutex<Vec<ConnectionGuard>>,
    _server_handle: JoinHandle<()>,
}

impl HttpTransport {
    /// Binds the HTTP transport to the configured address.
    ///
    /// Returns the transport and the actual bound address (useful when binding
    /// to port 0 in tests).
    ///
    /// # Errors
    ///
    /// Returns a [`TransportError`] if the TCP listener cannot bind.
    ///
    /// Implements: TJ-SPEC-002 F-003
    pub async fn bind(config: HttpConfig, cancel: CancellationToken) -> Result<(Self, SocketAddr)> {
        let (incoming_tx, incoming_rx) = mpsc::channel::<IncomingRequest>(32);
        let (sse_tx, _) = broadcast::channel::<String>(256);

        let listener = TcpListener::bind(&config.bind_addr)
            .await
            .map_err(|e| TransportError::ConnectionFailed(format!("bind failed: {e}")))?;

        let bound_addr = listener
            .local_addr()
            .map_err(|e| TransportError::ConnectionFailed(format!("local_addr failed: {e}")))?;

        let shared = Arc::new(HttpSharedState {
            incoming_tx,
            sse_tx,
            connections: Arc::new(DashMap::new()),
            next_connection_id: AtomicU64::new(1),
            max_message_size: config.max_message_size,
            sse_connections: AtomicUsize::new(0),
            cancel: cancel.clone(),
            session_id: uuid::Uuid::new_v4().to_string(),
            pending_server_requests: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        });

        let router = build_router(Arc::clone(&shared));
        let service = router.into_make_service_with_connect_info::<SocketAddr>();

        let server_cancel = cancel.clone();
        let server_handle = tokio::spawn(async move {
            info!(%bound_addr, "HTTP transport started");
            axum::serve(listener, service)
                .with_graceful_shutdown(async move {
                    server_cancel.cancelled().await;
                })
                .await
                .ok();
            debug!("HTTP transport shut down");
        });

        let transport = Self {
            shared,
            incoming_rx: tokio::sync::Mutex::new(incoming_rx),
            current_response: tokio::sync::Mutex::new(None),
            current_context: std::sync::Mutex::new(ConnectionContext {
                connection_id: 0,
                remote_addr: None,
                is_exclusive: false,
                connected_at: Instant::now(),
            }),
            current_guard: std::sync::Mutex::new(None),
            previous_guards: std::sync::Mutex::new(Vec::new()),
            _server_handle: server_handle,
        };

        Ok((transport, bound_addr))
    }

    /// Gracefully shuts down the HTTP transport.
    ///
    /// Called by library consumers for graceful shutdown.
    ///
    /// Implements: TJ-SPEC-002 F-003
    pub fn shutdown(&self) {
        self.shared.cancel.cancel();
    }

    /// Receives the next incoming request along with a per-request
    /// [`ResponseHandle`] that owns the response channel.
    ///
    /// Unlike [`Transport::receive_message`], this does **not** touch
    /// the shared `current_response` / `current_context` mutexes, making
    /// it safe to call from a concurrent context while other requests are
    /// being processed in spawned tasks.
    ///
    /// Returns `None` on channel close (shutdown).
    ///
    /// Implements: TJ-SPEC-002 F-003
    pub async fn receive_request(&self) -> Option<(JsonRpcMessage, ResponseHandle)> {
        let mut rx = self.incoming_rx.lock().await;
        let incoming = rx.recv().await?;
        drop(rx);

        // Track connection in the shared map
        self.shared.connections.insert(
            incoming.connection_id,
            ConnectionState {
                remote_addr: incoming.remote_addr,
                connected_at: incoming.connected_at,
                request_count: AtomicU64::new(1),
            },
        );

        let context = ConnectionContext {
            connection_id: incoming.connection_id,
            remote_addr: Some(incoming.remote_addr),
            is_exclusive: false,
            connected_at: incoming.connected_at,
        };

        let guard =
            ConnectionGuard::new(Arc::clone(&self.shared.connections), incoming.connection_id);

        let handle = ResponseHandle {
            response_tx: incoming.response_tx,
            context,
            _guard: guard,
        };

        Some((incoming.message, handle))
    }

    /// Sends a server-initiated JSON-RPC request and waits for the response.
    ///
    /// Unlike `send_message()` + `receive_message()`, this uses a dedicated
    /// oneshot channel so the response is routed back without disturbing
    /// `current_response`. This prevents the channel-swap bug where
    /// `receive_message()` replaces the active response channel.
    ///
    /// # Errors
    ///
    /// Returns [`TransportError`] on send failure, timeout, or if the
    /// response channel is dropped.
    ///
    /// Implements: TJ-SPEC-002 F-003
    pub async fn send_server_request(&self, request: &JsonRpcRequest) -> Result<JsonRpcResponse> {
        let request_id =
            serde_json::to_string(&request.id).unwrap_or_else(|_| request.id.to_string());

        let (tx, rx) = tokio::sync::oneshot::channel();

        // Register the pending request in shared state (handler routes responses)
        {
            let mut pending = self.shared.pending_server_requests.lock().await;
            pending.insert(request_id.clone(), tx);
        }

        // Send as SSE event on the current POST response body.
        // The client receives this on the same SSE stream as the tool call
        // response, then sends its response as a new POST.
        let serialized = serde_json::to_string(&JsonRpcMessage::Request(request.clone()))?;
        let sse_data = format!("event: message\ndata: {serialized}\n\n");
        let response_tx = {
            let guard = self.current_response.lock().await;
            guard.as_ref().cloned()
        };
        if let Some(ch) = response_tx {
            if ch.send(Ok(Bytes::from(sse_data))).await.is_err() {
                self.shared
                    .pending_server_requests
                    .lock()
                    .await
                    .remove(&request_id);
                return Err(TransportError::ConnectionClosed(
                    "response channel closed".into(),
                ));
            }
        } else {
            // Fallback to SSE broadcast (shouldn't happen during tool call)
            let _ = self.shared.sse_tx.send(serialized);
        }

        // Wait for response with 30s timeout
        match tokio::time::timeout(std::time::Duration::from_secs(30), rx).await {
            Ok(Ok(JsonRpcMessage::Response(resp))) => Ok(resp),
            Ok(Ok(_)) => Err(TransportError::InternalError(
                "unexpected non-response message for server request".into(),
            )),
            Ok(Err(_)) => Err(TransportError::ConnectionClosed(
                "server request response channel dropped".into(),
            )),
            Err(_) => {
                // Clean up on timeout
                self.shared
                    .pending_server_requests
                    .lock()
                    .await
                    .remove(&request_id);
                Err(TransportError::InternalError(
                    "server request timed out after 30s".into(),
                ))
            }
        }
    }
}

/// Per-request handle for sending an HTTP response.
///
/// Owns the `response_tx` channel sender and the [`ConnectionGuard`].
/// When dropped, the HTTP chunked response is finalized and the
/// connection is removed from tracking.
///
/// Implements: TJ-SPEC-002 F-003
pub struct ResponseHandle {
    response_tx: Option<mpsc::Sender<std::result::Result<Bytes, io::Error>>>,
    context: ConnectionContext,
    _guard: ConnectionGuard,
}

impl ResponseHandle {
    /// Sends raw bytes into the HTTP response body.
    ///
    /// # Errors
    ///
    /// Returns [`TransportError::ConnectionClosed`] if the client disconnected.
    pub async fn send_raw(&self, bytes: &[u8]) -> Result<()> {
        let tx = self
            .response_tx
            .as_ref()
            .ok_or_else(|| TransportError::ConnectionClosed("response already finalized".into()))?;
        tx.send(Ok(Bytes::copy_from_slice(bytes)))
            .await
            .map_err(|_| TransportError::ConnectionClosed("response channel closed".into()))
    }

    /// Sends a JSON-RPC message.
    ///
    /// SSE-frames all messages on the POST response body, matching
    /// `HttpTransport::send_message()` behavior.
    ///
    /// # Errors
    ///
    /// Returns [`TransportError`] on serialization or channel failure.
    // TODO(v0.6): per-request content-type negotiation — put ResponseMode on
    // ResponseHandle so Direct requests can use plain application/json
    // instead of SSE framing. Deferred: SSE framing works for all v0.5 scenarios.
    pub async fn send_message(&self, message: &JsonRpcMessage) -> Result<()> {
        let serialized = serde_json::to_string(message)?;
        let sse_data = format!("event: message\ndata: {serialized}\n\n");
        self.send_raw(sse_data.as_bytes()).await
    }

    /// Finalizes the HTTP response by dropping the body sender.
    ///
    /// The [`ConnectionGuard`] is also dropped (on `ResponseHandle` drop),
    /// removing the connection from tracking.
    pub fn finalize(mut self) {
        self.response_tx.take();
        // _guard is dropped with self
    }

    /// Returns the connection context for this request.
    #[must_use]
    pub const fn connection_context(&self) -> &ConnectionContext {
        &self.context
    }
}

/// Adapter that wraps a [`ResponseHandle`] as a [`Transport`].
///
/// This allows existing [`DeliveryBehavior`](crate::behavior::delivery::DeliveryBehavior)
/// implementations to work unchanged — they accept `&dyn Transport`,
/// and this adapter delegates `send_raw` / `send_message` to the
/// underlying `ResponseHandle`.
///
/// Implements: TJ-SPEC-002 F-003
pub struct ResponseHandleAdapter {
    handle: ResponseHandle,
}

impl ResponseHandleAdapter {
    /// Wraps a [`ResponseHandle`] in a [`Transport`] adapter.
    #[must_use]
    pub const fn new(handle: ResponseHandle) -> Self {
        Self { handle }
    }

    /// Finalizes the HTTP response, consuming the adapter.
    pub fn finalize(self) {
        self.handle.finalize();
    }

    /// Returns the connection context for this request.
    #[must_use]
    pub const fn connection_context(&self) -> &ConnectionContext {
        self.handle.connection_context()
    }
}

#[async_trait::async_trait]
impl Transport for ResponseHandleAdapter {
    async fn send_message(&self, message: &JsonRpcMessage) -> Result<()> {
        self.handle.send_message(message).await
    }

    async fn send_raw(&self, bytes: &[u8]) -> Result<()> {
        self.handle.send_raw(bytes).await
    }

    async fn receive_message(&self) -> Result<Option<JsonRpcMessage>> {
        // Per-request adapters do not receive messages
        Err(TransportError::InternalError(
            "ResponseHandleAdapter does not support receive_message".into(),
        ))
    }

    fn transport_type(&self) -> TransportType {
        TransportType::Http
    }

    async fn finalize_response(&self) -> Result<()> {
        // Finalization happens when the adapter is consumed via finalize()
        Ok(())
    }

    fn connection_context(&self) -> ConnectionContext {
        self.handle.context.clone()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

impl std::fmt::Debug for HttpTransport {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("HttpTransport")
            .field("connections", &self.shared.connections.len())
            .finish_non_exhaustive()
    }
}

#[async_trait::async_trait]
impl Transport for HttpTransport {
    async fn receive_message(&self) -> Result<Option<JsonRpcMessage>> {
        // Note: server-initiated request responses (JSON-RPC Response POSTs) are
        // routed directly to pending oneshot channels in handle_post_message().
        // This method only sees Requests and Notifications.
        let mut rx = self.incoming_rx.lock().await;
        let incoming = rx.recv().await;
        drop(rx);

        let Some(req) = incoming else {
            return Ok(None);
        };

        // Store the response sender for subsequent send_message/send_raw calls
        {
            let mut guard = self.current_response.lock().await;
            (*guard).clone_from(&req.response_tx);
        }

        // Track connection here (not in the handler) to avoid a race where the
        // handler inserts a connection and the ConnectionGuard from a previous
        // request removes the wrong entry.
        self.shared.connections.insert(
            req.connection_id,
            ConnectionState {
                remote_addr: req.remote_addr,
                connected_at: req.connected_at,
                request_count: AtomicU64::new(1),
            },
        );

        // Update connection context using the timestamp captured in the handler
        {
            let mut ctx = self
                .current_context
                .lock()
                .map_err(|_| TransportError::InternalError("context mutex poisoned".into()))?;
            *ctx = ConnectionContext {
                connection_id: req.connection_id,
                remote_addr: Some(req.remote_addr),
                is_exclusive: false,
                connected_at: req.connected_at,
            };
        }

        // Create RAII guard for connection cleanup.
        // Retain old guards to prevent premature DashMap removal while
        // response channels may still be draining. Cap at 2 entries.
        {
            let old_guard = self
                .current_guard
                .lock()
                .map_err(|_| TransportError::InternalError("guard mutex poisoned".into()))?
                .take();
            // Retain old guard so its connection entry stays in the DashMap.
            // Without this, the dropped guard removes the connection from
            // tracking while its response channel may still be draining.
            if let Some(guard) = old_guard {
                let mut prev = self.previous_guards.lock().map_err(|_| {
                    TransportError::InternalError("previous_guards mutex poisoned".into())
                })?;
                prev.push(guard);
                while prev.len() > 2 {
                    prev.remove(0);
                }
                drop(prev);
            }
            *self
                .current_guard
                .lock()
                .map_err(|_| TransportError::InternalError("guard mutex poisoned".into()))? = Some(
                ConnectionGuard::new(Arc::clone(&self.shared.connections), req.connection_id),
            );
        }

        Ok(Some(req.message))
    }

    async fn send_message(&self, message: &JsonRpcMessage) -> Result<()> {
        let serialized = serde_json::to_string(message)?;

        // MCP Streamable HTTP: all messages during a request go on the POST
        // response body as SSE events. If there's an active response channel,
        // send there. Otherwise fall back to the SSE broadcast (for out-of-band
        // notifications when no request is in flight).
        let tx = {
            let guard = self.current_response.lock().await;
            guard.as_ref().cloned()
        };

        if let Some(tx) = tx {
            // SSE frame: event: message\ndata: <JSON>\n\n
            let sse_data = format!("event: message\ndata: {serialized}\n\n");
            tx.send(Ok(Bytes::from(sse_data)))
                .await
                .map_err(|_| TransportError::ConnectionClosed("response channel closed".into()))?;
        } else {
            match message {
                JsonRpcMessage::Notification(_) | JsonRpcMessage::Request(_) => {
                    // Fallback: SSE broadcast (no active POST response)
                    let _ = self.shared.sse_tx.send(serialized);
                }
                JsonRpcMessage::Response(_) => {
                    return Err(TransportError::ConnectionClosed(
                        "no active response channel (send_message called before receive_message)"
                            .into(),
                    ));
                }
            }
        }
        Ok(())
    }

    async fn send_raw(&self, bytes: &[u8]) -> Result<()> {
        let tx = {
            let guard = self.current_response.lock().await;
            guard.as_ref().cloned()
        };
        let Some(tx) = tx else {
            return Err(TransportError::ConnectionClosed(
                "no active response channel (send_raw called before receive_message)".into(),
            ));
        };
        tx.send(Ok(Bytes::copy_from_slice(bytes)))
            .await
            .map_err(|_| TransportError::ConnectionClosed("response channel closed".into()))?;
        Ok(())
    }

    fn transport_type(&self) -> TransportType {
        TransportType::Http
    }

    async fn finalize_response(&self) -> Result<()> {
        // Take the sender — dropping it closes the stream and completes
        // the HTTP chunked response.
        let sender = {
            let mut guard = self.current_response.lock().await;
            guard.take()
        };
        drop(sender);

        // Drop the RAII guard — removes connection from tracking
        let guard = {
            let mut g = self
                .current_guard
                .lock()
                .map_err(|_| TransportError::InternalError("guard mutex poisoned".into()))?;
            g.take()
        };
        drop(guard);

        Ok(())
    }

    async fn capture_raw_writer(&self) -> Result<Option<RawResponseWriter>> {
        let guard = self.current_response.lock().await;
        Ok(guard.as_ref().map(|tx| RawResponseWriter::new(tx.clone())))
    }

    fn connection_context(&self) -> ConnectionContext {
        self.current_context
            .lock()
            .unwrap_or_else(|e| {
                tracing::error!("context mutex poisoned, using default");
                e.into_inner()
            })
            .clone()
    }

    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// ============================================================================
// Axum Router
// ============================================================================

/// Builds the axum router with legacy and Streamable HTTP routes.
///
/// - `POST /message` — legacy MCP 2024-11-05 HTTP+SSE message endpoint
/// - `GET /sse` — legacy MCP 2024-11-05 SSE stream (endpoint event → `/message`)
/// - `POST /mcp` + `GET /mcp` — MCP 2025-03-26 Streamable HTTP unified endpoint
///
/// Implements: TJ-SPEC-002 F-003
fn build_router(shared: Arc<HttpSharedState>) -> Router {
    // Override axum's default 2MB body limit with the configured max_message_size
    // (default 10MB). Without this, requests between 2MB and max_message_size
    // are rejected by axum before reaching the handler's size check.
    let body_limit = axum::extract::DefaultBodyLimit::max(shared.max_message_size);

    // Note: request timeout is NOT applied as a router-level middleware because
    // the POST /message handler returns a streaming response body immediately
    // and fills it asynchronously from the server loop. A tower Timeout layer
    // wraps the response body and can drop it under load before the server
    // finishes processing. The timeout is enforced at the server request
    // processing level instead (via request_timeout_secs on HttpSharedState).
    Router::new()
        // Legacy MCP 2024-11-05 HTTP+SSE endpoints
        .route("/message", post(handle_post_message))
        .route("/sse", get(handle_sse))
        // Modern MCP 2025-03-26 Streamable HTTP unified endpoint
        .route("/mcp", get(handle_sse_streamable).post(handle_post_message))
        .layer(body_limit)
        .with_state(shared)
}

/// `POST /message` handler.
///
/// Parses the request body as a JSON-RPC message, pushes it into the incoming
/// channel, and returns a streaming response body that the transport fills in
/// when `send_message` / `send_raw` is called.
async fn handle_post_message(
    State(shared): State<Arc<HttpSharedState>>,
    ConnectInfo(addr): ConnectInfo<SocketAddr>,
    _headers: axum::http::HeaderMap,
    body: axum::body::Bytes,
) -> Response {
    // EC-TRANS-006: empty body
    if body.is_empty() {
        return (StatusCode::BAD_REQUEST, "empty request body").into_response();
    }

    // F-008: message size limit
    if body.len() > shared.max_message_size {
        return (
            StatusCode::PAYLOAD_TOO_LARGE,
            format!(
                "message too large: {} bytes (limit: {})",
                body.len(),
                shared.max_message_size
            ),
        )
            .into_response();
    }

    // Parse JSON-RPC
    let message: JsonRpcMessage = match serde_json::from_slice(&body) {
        Ok(msg) => msg,
        Err(e) => {
            return (StatusCode::BAD_REQUEST, format!("invalid JSON-RPC: {e}")).into_response();
        }
    };

    // Route based on message type (MCP Streamable HTTP spec):
    // - Response: client responding to server-initiated request → route to oneshot, 202
    // - Notification: client notification (e.g. initialized) → push for driver, 202
    // - Request: normal client request → SSE streaming response
    let is_initialize =
        matches!(&message, JsonRpcMessage::Request(req) if req.method == "initialize");
    match &message {
        JsonRpcMessage::Response(resp) => {
            // Client is responding to a server-initiated request (sampling/elicitation).
            let key = serde_json::to_string(&resp.id).unwrap_or_else(|_| resp.id.to_string());
            let sender = {
                let mut pending = shared.pending_server_requests.lock().await;
                pending.remove(&key)
            };
            if let Some(tx) = sender {
                let _ = tx.send(message);
            } else {
                tracing::debug!(id = ?resp.id, "no pending server request for response");
            }
            return StatusCode::ACCEPTED.into_response();
        }
        JsonRpcMessage::Notification(_) => {
            // Push notification for driver to process, but return 202 immediately.
            let connection_id = shared.next_connection_id.fetch_add(1, Ordering::SeqCst);
            let incoming = IncomingRequest {
                message,
                response_tx: None,
                connection_id,
                remote_addr: addr,
                connected_at: Instant::now(),
            };
            if shared.incoming_tx.send(incoming).await.is_err() {
                return (StatusCode::SERVICE_UNAVAILABLE, "server shutting down").into_response();
            }
            return StatusCode::ACCEPTED.into_response();
        }
        JsonRpcMessage::Request(_) => {
            // Normal request — proceed to SSE streaming response below.
        }
    }

    let connection_id = shared.next_connection_id.fetch_add(1, Ordering::SeqCst);
    let connected_at = Instant::now();

    // Connection tracking is deferred to receive_message to avoid a race where
    // the handler inserts and the ConnectionGuard from the previous request
    // removes the wrong entry.

    // Create response body channel
    let (response_tx, response_rx) = mpsc::channel::<std::result::Result<Bytes, io::Error>>(64);

    let incoming = IncomingRequest {
        message,
        response_tx: Some(response_tx),
        connection_id,
        remote_addr: addr,
        connected_at,
    };

    // Push into the transport channel
    if shared.incoming_tx.send(incoming).await.is_err() {
        return (StatusCode::SERVICE_UNAVAILABLE, "server shutting down").into_response();
    }

    // Return SSE streaming response body (MCP Streamable HTTP).
    // All interleaved messages (notifications, server requests, final response)
    // are sent as `event: message\ndata: <JSON>\n\n` on this stream.
    let stream = ReceiverStream::new(response_rx);
    let body = Body::from_stream(stream);

    let mut builder = Response::builder().header("content-type", "text/event-stream");
    if is_initialize {
        builder = builder.header("mcp-session-id", &shared.session_id);
    }
    builder.body(body).unwrap_or_else(|e| {
        tracing::error!(error = %e, "failed to build HTTP response");
        StatusCode::INTERNAL_SERVER_ERROR.into_response()
    })
}

/// `GET /sse` handler (legacy MCP 2024-11-05).
///
/// Returns a Server-Sent Events stream whose initial endpoint event points
/// to `/message`.
///
/// Implements: TJ-SPEC-002 F-003
async fn handle_sse(State(shared): State<Arc<HttpSharedState>>) -> Response {
    handle_sse_inner(&shared, "/message")
}

/// `GET /mcp` handler (MCP 2025-03-26 Streamable HTTP).
///
/// Returns a Server-Sent Events stream whose initial endpoint event points
/// to `/mcp` (the unified endpoint).
///
/// Implements: TJ-SPEC-002 F-003
async fn handle_sse_streamable(State(shared): State<Arc<HttpSharedState>>) -> Response {
    handle_sse_inner(&shared, "/mcp")
}

/// Shared SSE handler implementation.
///
/// Returns a Server-Sent Events stream that broadcasts all server-initiated
/// notifications and requests. Limits the number of concurrent SSE connections.
/// The `endpoint_path` parameter controls the URL emitted in the initial
/// `endpoint` event.
fn handle_sse_inner(shared: &Arc<HttpSharedState>, endpoint_path: &'static str) -> Response {
    // Enforce SSE connection limit
    let current = shared.sse_connections.fetch_add(1, Ordering::SeqCst);
    if current >= MAX_SSE_CONNECTIONS {
        shared.sse_connections.fetch_sub(1, Ordering::SeqCst);
        return (
            StatusCode::SERVICE_UNAVAILABLE,
            format!("too many SSE connections (limit: {MAX_SSE_CONNECTIONS})"),
        )
            .into_response();
    }

    let rx = shared.sse_tx.subscribe();
    let cancel = shared.cancel.clone();

    // MCP Streamable HTTP: initial endpoint event tells the client where to POST
    let endpoint_event: std::result::Result<SseEvent, std::convert::Infallible> =
        Ok(SseEvent::default().event("endpoint").data(endpoint_path));

    let broadcast_stream = tokio_stream::wrappers::BroadcastStream::new(rx)
        .take_while(move |_| !cancel.is_cancelled())
        .filter_map(|result: std::result::Result<String, _>| match result {
            Ok(data) => {
                let event: std::result::Result<SseEvent, std::convert::Infallible> =
                    Ok(SseEvent::default().event("message").data(data));
                Some(event)
            }
            Err(e) => {
                tracing::warn!(error = %e, "SSE subscriber lagged, dropping missed messages");
                None
            }
        });

    // Chain: endpoint event first, then broadcast stream
    let stream = tokio_stream::once(endpoint_event).chain(broadcast_stream);

    // Wrap in a stream that decrements the counter on drop
    let shared_for_drop = Arc::clone(shared);
    let stream = SseCountedStream {
        inner: Box::pin(stream),
        shared: shared_for_drop,
    };

    Sse::new(stream)
        .keep_alive(KeepAlive::default())
        .into_response()
}

/// Wrapper stream that decrements the SSE connection counter on drop.
struct SseCountedStream<S> {
    inner: std::pin::Pin<Box<S>>,
    shared: Arc<HttpSharedState>,
}

impl<S> tokio_stream::Stream for SseCountedStream<S>
where
    S: tokio_stream::Stream + Unpin,
{
    type Item = S::Item;

    fn poll_next(
        mut self: std::pin::Pin<&mut Self>,
        cx: &mut std::task::Context<'_>,
    ) -> std::task::Poll<Option<Self::Item>> {
        self.inner.as_mut().poll_next(cx)
    }
}

impl<S> Drop for SseCountedStream<S> {
    fn drop(&mut self) {
        self.shared.sse_connections.fetch_sub(1, Ordering::SeqCst);
    }
}

// ============================================================================
// Helpers
// ============================================================================

/// Parses a bind address string into a full `host:port` form.
///
/// Accepts:
/// - `:8080` → `0.0.0.0:8080`
/// - `8080` → `0.0.0.0:8080`
/// - `1.2.3.4:8080` → as-is
///
/// # Errors
///
/// Returns [`TransportError::ConnectionFailed`] if the result cannot be
/// parsed as a valid socket address.
///
/// Implements: TJ-SPEC-002 F-003
pub fn parse_bind_addr(input: &str) -> std::result::Result<String, TransportError> {
    let addr = if input.starts_with(':') {
        format!("0.0.0.0{input}")
    } else if input.parse::<u16>().is_ok() {
        format!("0.0.0.0:{input}")
    } else {
        input.to_string()
    };
    // Validate it can be parsed as a socket address
    addr.parse::<SocketAddr>().map_err(|e| {
        TransportError::ConnectionFailed(format!("invalid bind address \"{input}\": {e}"))
    })?;
    Ok(addr)
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use crate::transport::DEFAULT_MAX_MESSAGE_SIZE;
    use axum::body::Body;
    use axum::http::Request;
    use tower::util::ServiceExt;

    fn test_shared_state() -> Arc<HttpSharedState> {
        let (incoming_tx, _incoming_rx) = mpsc::channel(32);
        let (sse_tx, _) = broadcast::channel(256);
        Arc::new(HttpSharedState {
            incoming_tx,
            sse_tx,
            connections: Arc::new(DashMap::new()),
            next_connection_id: AtomicU64::new(1),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
            sse_connections: AtomicUsize::new(0),
            cancel: CancellationToken::new(),
            session_id: "test-session".to_string(),
            pending_server_requests: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        })
    }

    use axum::extract::connect_info::MockConnectInfo;

    /// Builds a test router with `ConnectInfo` support.
    fn test_router(shared: Arc<HttpSharedState>) -> Router {
        build_router(shared).layer(MockConnectInfo(SocketAddr::from(([127, 0, 0, 1], 9999))))
    }

    // ------------------------------------------------------------------
    // parse_bind_addr
    // ------------------------------------------------------------------

    #[test]
    fn parse_bind_addr_colon_port() {
        assert_eq!(parse_bind_addr(":8080").unwrap(), "0.0.0.0:8080");
    }

    #[test]
    fn parse_bind_addr_port_only() {
        assert_eq!(parse_bind_addr("8080").unwrap(), "0.0.0.0:8080");
    }

    #[test]
    fn parse_bind_addr_full() {
        assert_eq!(parse_bind_addr("1.2.3.4:8080").unwrap(), "1.2.3.4:8080");
    }

    #[test]
    fn parse_bind_addr_localhost() {
        assert_eq!(parse_bind_addr("127.0.0.1:3000").unwrap(), "127.0.0.1:3000");
    }

    #[test]
    fn parse_bind_addr_invalid() {
        assert!(parse_bind_addr("not-an-address").is_err());
    }

    // ------------------------------------------------------------------
    // POST /message error cases
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn post_empty_body_returns_400() {
        let shared = test_shared_state();
        let app = test_router(shared);

        let req = Request::builder()
            .method("POST")
            .uri("/message")
            .header("host", "localhost:3000")
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn post_invalid_json_returns_400() {
        let shared = test_shared_state();
        let app = test_router(shared);

        let req = Request::builder()
            .method("POST")
            .uri("/message")
            .header("content-type", "application/json")
            .header("host", "localhost:3000")
            .body(Body::from("not json"))
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
    }

    #[tokio::test]
    async fn post_oversized_body_returns_413() {
        let (incoming_tx, _rx) = mpsc::channel(32);
        let (sse_tx, _) = broadcast::channel(256);
        let shared = Arc::new(HttpSharedState {
            incoming_tx,
            sse_tx,
            connections: Arc::new(DashMap::new()),
            next_connection_id: AtomicU64::new(1),
            max_message_size: 10, // tiny limit
            sse_connections: AtomicUsize::new(0),
            cancel: CancellationToken::new(),
            session_id: "test-session".to_string(),
            pending_server_requests: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        });
        let app = test_router(shared);

        let body = r#"{"jsonrpc":"2.0","method":"test","id":1}"#;
        let req = Request::builder()
            .method("POST")
            .uri("/message")
            .header("content-type", "application/json")
            .header("host", "localhost:3000")
            .body(Body::from(body))
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::PAYLOAD_TOO_LARGE);
    }

    #[tokio::test]
    async fn post_valid_message_returns_200() {
        let (incoming_tx, mut incoming_rx) = mpsc::channel(32);
        let (sse_tx, _) = broadcast::channel(256);
        let shared = Arc::new(HttpSharedState {
            incoming_tx,
            sse_tx,
            connections: Arc::new(DashMap::new()),
            next_connection_id: AtomicU64::new(1),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
            sse_connections: AtomicUsize::new(0),
            cancel: CancellationToken::new(),
            session_id: "test-session".to_string(),
            pending_server_requests: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        });
        let app = test_router(shared);

        let body = r#"{"jsonrpc":"2.0","method":"initialize","params":{},"id":1}"#;
        let req = Request::builder()
            .method("POST")
            .uri("/message")
            .header("content-type", "application/json")
            .header("host", "localhost:3000")
            .body(Body::from(body))
            .unwrap();

        // Spawn a consumer that sends a response via the channel
        tokio::spawn(async move {
            if let Some(incoming) = incoming_rx.recv().await {
                let response = Bytes::from(r#"{"jsonrpc":"2.0","result":{},"id":1}"#);
                if let Some(tx) = incoming.response_tx {
                    tx.send(Ok(response)).await.ok();
                }
                // Drop sender to close the stream
            }
        });

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // ------------------------------------------------------------------
    // GET /sse
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn sse_endpoint_returns_200() {
        let shared = test_shared_state();
        let app = test_router(shared);

        let req = Request::builder()
            .method("GET")
            .uri("/sse")
            .header("host", "localhost:3000")
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    // ------------------------------------------------------------------
    // Connection tracking
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn connection_tracking() {
        let cancel = CancellationToken::new();
        let config = HttpConfig {
            bind_addr: "127.0.0.1:0".to_string(),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
        };
        let (transport, _addr) = HttpTransport::bind(config, cancel.clone()).await.unwrap();

        // Initially no connections
        assert_eq!(transport.shared.connections.len(), 0);

        // After finalize, connection should be cleaned up
        transport.finalize_response().await.unwrap();
        assert_eq!(transport.shared.connections.len(), 0);

        transport.shutdown();
    }

    // ------------------------------------------------------------------
    // Transport trait basics
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn transport_type_is_http() {
        let cancel = CancellationToken::new();
        let config = HttpConfig {
            bind_addr: "127.0.0.1:0".to_string(),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
        };
        let (transport, _addr) = HttpTransport::bind(config, cancel.clone()).await.unwrap();
        assert_eq!(transport.transport_type(), TransportType::Http);
        transport.shutdown();
    }

    #[tokio::test]
    async fn debug_format() {
        let cancel = CancellationToken::new();
        let config = HttpConfig {
            bind_addr: "127.0.0.1:0".to_string(),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
        };
        let (transport, _addr) = HttpTransport::bind(config, cancel.clone()).await.unwrap();
        let debug = format!("{transport:?}");
        assert!(debug.contains("HttpTransport"));
        transport.shutdown();
    }

    #[tokio::test]
    async fn default_connection_context_is_stdio() {
        let cancel = CancellationToken::new();
        let config = HttpConfig {
            bind_addr: "127.0.0.1:0".to_string(),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
        };
        let (transport, _addr) = HttpTransport::bind(config, cancel.clone()).await.unwrap();
        let ctx = transport.connection_context();
        // Default context before any request is stdio-like (connection_id 0)
        assert_eq!(ctx.connection_id, 0);
        transport.shutdown();
    }

    // ------------------------------------------------------------------
    // ResponseHandle + ResponseHandleAdapter
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn response_handle_send_and_finalize() {
        let (response_tx, mut response_rx) = mpsc::channel(64);
        let connections: Arc<DashMap<u64, ConnectionState>> = Arc::new(DashMap::new());
        connections.insert(
            42,
            ConnectionState {
                remote_addr: SocketAddr::from(([127, 0, 0, 1], 9999)),
                connected_at: Instant::now(),
                request_count: AtomicU64::new(1),
            },
        );

        let handle = ResponseHandle {
            response_tx: Some(response_tx),
            context: ConnectionContext {
                connection_id: 42,
                remote_addr: Some(SocketAddr::from(([127, 0, 0, 1], 9999))),
                is_exclusive: false,
                connected_at: Instant::now(),
            },
            _guard: ConnectionGuard::new(Arc::clone(&connections), 42),
        };

        // send_raw should push bytes
        handle.send_raw(b"hello").await.unwrap();
        let received = response_rx.recv().await.unwrap().unwrap();
        assert_eq!(&received[..], b"hello");

        // finalize drops the sender
        handle.finalize();
        assert!(response_rx.recv().await.is_none());
        // Guard should have cleaned up the connection
        assert_eq!(connections.len(), 0);
    }

    #[tokio::test]
    async fn response_handle_adapter_implements_transport() {
        let (response_tx, mut response_rx) = mpsc::channel(64);
        let connections: Arc<DashMap<u64, ConnectionState>> = Arc::new(DashMap::new());

        let handle = ResponseHandle {
            response_tx: Some(response_tx),
            context: ConnectionContext {
                connection_id: 1,
                remote_addr: None,
                is_exclusive: false,
                connected_at: Instant::now(),
            },
            _guard: ConnectionGuard::new(connections, 1),
        };

        let adapter = ResponseHandleAdapter::new(handle);

        // Transport trait methods
        assert_eq!(adapter.transport_type(), TransportType::Http);

        // send_raw via Transport trait
        adapter.send_raw(b"raw bytes").await.unwrap();
        let received = response_rx.recv().await.unwrap().unwrap();
        assert_eq!(&received[..], b"raw bytes");

        // receive_message should error
        assert!(adapter.receive_message().await.is_err());

        adapter.finalize();
    }

    // ---- New tests ----

    #[tokio::test]
    async fn sse_stream_content_type() {
        let shared = test_shared_state();
        let app = test_router(shared);

        let req = Request::builder()
            .method("GET")
            .uri("/sse")
            .header("host", "localhost:3000")
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        // Verify SSE content-type header
        let content_type = resp
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        assert!(
            content_type.contains("text/event-stream"),
            "Expected text/event-stream, got: {content_type}"
        );
    }

    #[tokio::test]
    async fn concurrent_posts_all_succeed() {
        let (incoming_tx, mut incoming_rx) = mpsc::channel(32);
        let (sse_tx, _) = broadcast::channel(256);
        let shared = Arc::new(HttpSharedState {
            incoming_tx,
            sse_tx,
            connections: Arc::new(DashMap::new()),
            next_connection_id: AtomicU64::new(1),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
            sse_connections: AtomicUsize::new(0),
            cancel: CancellationToken::new(),
            session_id: "test-session".to_string(),
            pending_server_requests: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        });

        let router = build_router(shared);

        // Spawn a consumer that responds to all incoming requests
        tokio::spawn(async move {
            while let Some(incoming) = incoming_rx.recv().await {
                let response = Bytes::from(r#"{"jsonrpc":"2.0","result":{},"id":1}"#);
                if let Some(tx) = incoming.response_tx {
                    tx.send(Ok(response)).await.ok();
                }
            }
        });

        let body = r#"{"jsonrpc":"2.0","method":"test","params":{},"id":1}"#;

        // Send 3 concurrent requests using cloned routers
        let mut handles = Vec::new();
        for _ in 0..3 {
            let app = router
                .clone()
                .layer(MockConnectInfo(SocketAddr::from(([127, 0, 0, 1], 9999))));
            let req = Request::builder()
                .method("POST")
                .uri("/message")
                .header("content-type", "application/json")
                .header("host", "localhost:3000")
                .body(Body::from(body))
                .unwrap();

            handles.push(tokio::spawn(async move {
                app.oneshot(req).await.unwrap().status()
            }));
        }

        for handle in handles {
            let status = handle.await.unwrap();
            assert_eq!(status, StatusCode::OK);
        }
    }

    #[tokio::test]
    async fn session_id_header_on_initialize() {
        let (incoming_tx, mut incoming_rx) = mpsc::channel(32);
        let (sse_tx, _) = broadcast::channel(256);
        let shared = Arc::new(HttpSharedState {
            incoming_tx,
            sse_tx,
            connections: Arc::new(DashMap::new()),
            next_connection_id: AtomicU64::new(1),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
            sse_connections: AtomicUsize::new(0),
            cancel: CancellationToken::new(),
            session_id: "test-session-42".to_string(),
            pending_server_requests: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        });
        let app = test_router(shared);

        // Consume the incoming request to prevent blocking
        tokio::spawn(async move {
            if let Some(incoming) = incoming_rx.recv().await {
                let response = Bytes::from(r#"{"jsonrpc":"2.0","result":{},"id":1}"#);
                if let Some(tx) = incoming.response_tx {
                    tx.send(Ok(response)).await.ok();
                }
            }
        });

        let body = r#"{"jsonrpc":"2.0","method":"initialize","params":{},"id":1}"#;
        let req = Request::builder()
            .method("POST")
            .uri("/message")
            .header("content-type", "application/json")
            .header("host", "localhost:3000")
            .body(Body::from(body))
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        // Check Mcp-Session-Id header is present on initialize
        let session_id = resp
            .headers()
            .get("mcp-session-id")
            .and_then(|v| v.to_str().ok());
        assert_eq!(
            session_id,
            Some("test-session-42"),
            "Expected mcp-session-id header"
        );
    }

    #[tokio::test]
    async fn post_after_cancel_rejected() {
        let cancel = CancellationToken::new();
        let (incoming_tx, _rx) = mpsc::channel(32);
        let (sse_tx, _) = broadcast::channel(256);
        let shared = Arc::new(HttpSharedState {
            incoming_tx,
            sse_tx,
            connections: Arc::new(DashMap::new()),
            next_connection_id: AtomicU64::new(1),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
            sse_connections: AtomicUsize::new(0),
            cancel: cancel.clone(),
            session_id: "test-session".to_string(),
            pending_server_requests: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        });
        let app = test_router(shared);

        // Cancel the token before sending
        cancel.cancel();

        let body = r#"{"jsonrpc":"2.0","method":"test","params":{},"id":1}"#;
        let req = Request::builder()
            .method("POST")
            .uri("/message")
            .header("content-type", "application/json")
            .header("host", "localhost:3000")
            .body(Body::from(body))
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        // After cancel, the incoming_tx sender side is still alive but the
        // receiver may never consume — behavior depends on whether handler
        // checks cancel. At minimum, this should not panic.
        // The handler sends to a channel that nobody reads, so it may timeout
        // or return an error status.
        assert!(
            resp.status().is_client_error()
                || resp.status().is_server_error()
                || resp.status().is_success(),
            "Expected a valid HTTP status, got: {}",
            resp.status()
        );
    }

    #[test]
    fn connection_guard_cleanup_on_drop() {
        let connections: Arc<DashMap<u64, ConnectionState>> = Arc::new(DashMap::new());
        connections.insert(
            42,
            ConnectionState {
                remote_addr: SocketAddr::from(([127, 0, 0, 1], 9999)),
                connected_at: Instant::now(),
                request_count: AtomicU64::new(1),
            },
        );
        assert_eq!(connections.len(), 1);

        // Create guard and drop it
        {
            let _guard = ConnectionGuard::new(Arc::clone(&connections), 42);
        }
        // Connection should be removed after guard drop
        assert_eq!(connections.len(), 0);
    }

    // ------------------------------------------------------------------
    // Streamable HTTP /mcp endpoint
    // ------------------------------------------------------------------

    #[tokio::test]
    async fn mcp_post_returns_sse_response() {
        let (incoming_tx, mut incoming_rx) = mpsc::channel(32);
        let (sse_tx, _) = broadcast::channel(256);
        let shared = Arc::new(HttpSharedState {
            incoming_tx,
            sse_tx,
            connections: Arc::new(DashMap::new()),
            next_connection_id: AtomicU64::new(1),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
            sse_connections: AtomicUsize::new(0),
            cancel: CancellationToken::new(),
            session_id: "test-session".to_string(),
            pending_server_requests: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        });
        let app = test_router(shared);

        tokio::spawn(async move {
            if let Some(incoming) = incoming_rx.recv().await {
                let response = Bytes::from(r#"{"jsonrpc":"2.0","result":{},"id":1}"#);
                if let Some(tx) = incoming.response_tx {
                    tx.send(Ok(response)).await.ok();
                }
            }
        });

        let body = r#"{"jsonrpc":"2.0","method":"initialize","params":{},"id":1}"#;
        let req = Request::builder()
            .method("POST")
            .uri("/mcp")
            .header("content-type", "application/json")
            .header("host", "localhost:3000")
            .body(Body::from(body))
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        let content_type = resp
            .headers()
            .get("content-type")
            .and_then(|v| v.to_str().ok())
            .unwrap_or("");
        assert!(
            content_type.contains("text/event-stream"),
            "Expected text/event-stream on POST /mcp, got: {content_type}"
        );
    }

    #[tokio::test]
    async fn mcp_get_returns_200() {
        let shared = test_shared_state();
        let app = test_router(shared);

        let req = Request::builder()
            .method("GET")
            .uri("/mcp")
            .header("host", "localhost:3000")
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);
    }

    /// Helper: verifies the endpoint event data in an SSE stream response.
    ///
    /// Cancels the token and sends a dummy broadcast after a yield point
    /// so the SSE stream terminates and `to_bytes` can complete.
    async fn assert_endpoint_event(uri: &str, expected_data: &str) {
        let cancel = CancellationToken::new();
        let (incoming_tx, _incoming_rx) = mpsc::channel(32);
        let (sse_tx, _) = broadcast::channel(256);
        let shared = Arc::new(HttpSharedState {
            incoming_tx,
            sse_tx,
            connections: Arc::new(DashMap::new()),
            next_connection_id: AtomicU64::new(1),
            max_message_size: DEFAULT_MAX_MESSAGE_SIZE,
            sse_connections: AtomicUsize::new(0),
            cancel: cancel.clone(),
            session_id: "test-session".to_string(),
            pending_server_requests: tokio::sync::Mutex::new(std::collections::HashMap::new()),
        });
        let app = test_router(shared.clone());

        let req = Request::builder()
            .method("GET")
            .uri(uri)
            .header("host", "localhost:3000")
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        // Cancel and send a dummy broadcast so take_while terminates the stream.
        cancel.cancel();
        let _ = shared.sse_tx.send(String::new());

        let body = axum::body::to_bytes(resp.into_body(), 64 * 1024)
            .await
            .unwrap();
        let text = String::from_utf8_lossy(&body);
        let expected = format!("event: endpoint\ndata: {expected_data}");
        assert!(
            text.contains(&expected),
            "Expected '{expected}' in SSE body, got:\n{text}"
        );
    }

    #[tokio::test]
    async fn mcp_get_endpoint_event_points_to_mcp() {
        assert_endpoint_event("/mcp", "/mcp").await;
    }

    #[tokio::test]
    async fn sse_get_endpoint_event_points_to_message() {
        assert_endpoint_event("/sse", "/message").await;
    }

    #[tokio::test]
    async fn sse_connection_counter_tracks() {
        let shared = test_shared_state();
        assert_eq!(shared.sse_connections.load(Ordering::SeqCst), 0);

        let app = test_router(shared.clone());

        let req = Request::builder()
            .method("GET")
            .uri("/sse")
            .header("host", "localhost:3000")
            .body(Body::empty())
            .unwrap();

        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), StatusCode::OK);

        // SSE connection counter should have been incremented when the
        // handler started (it's decremented on stream drop).
        // After the response is created, the counter reflects the active stream.
        // Note: the exact count depends on whether the stream body is still alive.
        // We just verify we can access the counter without panicking.
        let count = shared.sse_connections.load(Ordering::SeqCst);
        // Stream may be alive (1) or already dropped (0), both are valid
        assert!(count <= 1, "Unexpected SSE connection count: {count}");
    }
}