tower-mcp 0.17.2

Tower-native Model Context Protocol (MCP) implementation
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
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
//! Stdio transport for MCP
//!
//! Reads JSON-RPC messages from stdin and writes responses to stdout.
//! Uses line-delimited JSON format.
//!
//! # Protocol lifecycles
//!
//! Final 2026-07-28 requests carry protocol version and client capabilities
//! inline in each request's `_meta` and can begin with a `server/discover`
//! probe. Requests without that metadata retain the legacy initialize
//! lifecycle, so both eras can coexist on one stdio stream. Use
//! [`StdioTransport::protocol_support`] to set the exact runtime allow-list.
//!
//! # Bidirectional Support
//!
//! For legacy protocols, [`BidirectionalStdioTransport`] enables
//! server-to-client requests like sampling (LLM requests). It multiplexes the
//! stdio streams to handle both incoming requests and outgoing
//! requests/responses. Final 2026-07-28 handlers do not receive a client
//! requester because that protocol does not permit server-initiated requests.
//!
//! # Server Notifications
//!
//! [`StdioTransport`] and [`BidirectionalStdioTransport`] automatically set up
//! notification channels and forward server notifications (progress, logging,
//! resource/tool/prompt list changes) to stdout as JSON-RPC notifications.
//! Once a final `subscriptions/listen` request is accepted, list and resource
//! change notifications use final subscription filtering and ID tagging for
//! the rest of that stream; they are not also broadcast in the legacy
//! untagged form.

use std::collections::HashMap;
use std::io::{self, BufRead, Write};
use std::sync::Arc;

use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::sync::{Mutex, mpsc, oneshot};

use crate::context::{
    ChannelClientRequester, ClientRequesterHandle, NotificationReceiver, OutgoingRequest,
    OutgoingRequestReceiver, ServerNotification, notification_channel, outgoing_request_channel,
};
use tower_service::Service;

use crate::error::{Error, Result};
use crate::jsonrpc::JsonRpcService;
#[cfg(feature = "stateless")]
use crate::protocol::{Implementation, SubscriptionFilter, SubscriptionsListenParams};
use crate::protocol::{
    JsonRpcMessage, JsonRpcNotification, JsonRpcRequest, JsonRpcResponse, JsonRpcResponseMessage,
    McpNotification, RequestId, notifications,
};
use crate::router::{McpRouter, RouterRequest, RouterResponse};
use crate::transport::service::{CatchError, InjectAnnotations};
#[cfg(feature = "stateless")]
use crate::transport::subscriptions::{
    accepted_subscription_filter, subscription_acknowledgment, subscription_complete_response,
    subscription_matches, tagged_subscription_notification,
};
use crate::{ProtocolSupport, ProtocolSupportError};

// ============================================================================
// Shared helpers
// ============================================================================

enum StdioControl {
    #[cfg(feature = "stateless")]
    CloseSubscription(RequestId),
    Shutdown,
}

/// Cloneable control handle for an asynchronous stdio server.
///
/// The handle can gracefully finish one final-protocol subscription without
/// closing the shared stdio channel, or gracefully finish every active
/// subscription and stop the transport.
#[derive(Clone)]
pub struct StdioTransportHandle {
    control_tx: mpsc::UnboundedSender<StdioControl>,
}

impl StdioTransportHandle {
    /// Gracefully finish one active `subscriptions/listen` request.
    ///
    /// The transport writes a `SubscriptionsListenResult` for `request_id`.
    /// Unknown or already-finished IDs are harmless.
    #[cfg(feature = "stateless")]
    pub fn close_subscription(&self, request_id: RequestId) -> Result<()> {
        self.control_tx
            .send(StdioControl::CloseSubscription(request_id))
            .map_err(|_| Error::Transport("stdio transport is not running".to_string()))
    }

    /// Gracefully finish all subscriptions and stop the stdio transport.
    pub fn shutdown(&self) -> Result<()> {
        self.control_tx
            .send(StdioControl::Shutdown)
            .map_err(|_| Error::Transport("stdio transport is not running".to_string()))
    }
}

fn stdio_control_channel() -> (
    mpsc::UnboundedSender<StdioControl>,
    mpsc::UnboundedReceiver<StdioControl>,
) {
    mpsc::unbounded_channel()
}

#[cfg(feature = "stateless")]
#[derive(Default)]
struct StdioSubscriptions {
    active: HashMap<RequestId, SubscriptionFilter>,
    modern_mode: bool,
    server_info: Option<Implementation>,
    /// Whether the served router opted into the Tasks extension. Captured at
    /// startup because the listen handler only sees the generic service.
    tasks_enabled: bool,
}

/// Whether a stdio `subscriptions/listen` request declared the Tasks
/// extension in its per-request `_meta`.
#[cfg(feature = "stateless")]
fn stdio_request_declares_tasks(parsed: &serde_json::Value) -> bool {
    parsed
        .get("params")
        .and_then(crate::stateless::StatelessRequestMeta::from_params)
        .and_then(|meta| meta.client_capabilities)
        .and_then(|capabilities| capabilities.extensions)
        .is_some_and(|declared| {
            declared.contains_key(tower_mcp_types::protocol::TASKS_EXTENSION_ID)
        })
}

#[cfg(feature = "stateless")]
enum StdioSubscriptionInput {
    NotHandled,
    Handled(Vec<String>),
}

#[cfg(feature = "stateless")]
impl StdioSubscriptions {
    fn handle_input<S>(
        &mut self,
        service: &JsonRpcService<S>,
        parsed: &serde_json::Value,
    ) -> Result<StdioSubscriptionInput> {
        let method = parsed.get("method").and_then(serde_json::Value::as_str);

        if method == Some(notifications::CANCELLED) && parsed.get("id").is_none() {
            let notification: JsonRpcNotification = match serde_json::from_value(parsed.clone()) {
                Ok(notification) => notification,
                Err(_) => return Ok(StdioSubscriptionInput::NotHandled),
            };
            let Ok(McpNotification::Cancelled(params)) =
                McpNotification::from_jsonrpc(&notification)
            else {
                return Ok(StdioSubscriptionInput::NotHandled);
            };
            if let Some(request_id) = params.request_id
                && self.active.remove(&request_id).is_some()
            {
                tracing::debug!(?request_id, "Cancelled stdio subscription");
                return Ok(StdioSubscriptionInput::Handled(Vec::new()));
            }
            return Ok(StdioSubscriptionInput::NotHandled);
        }

        if method != Some("subscriptions/listen") || parsed.get("id").is_none() {
            return Ok(StdioSubscriptionInput::NotHandled);
        }

        let claims_modern = parsed
            .pointer("/params/_meta/io.modelcontextprotocol~1protocolVersion")
            .is_some();
        if !claims_modern {
            return Ok(StdioSubscriptionInput::NotHandled);
        }

        let request: JsonRpcRequest = match serde_json::from_value(parsed.clone()) {
            Ok(request) => request,
            Err(error) => {
                let response = parse_error_response(error.to_string());
                return Ok(StdioSubscriptionInput::Handled(vec![
                    serde_json::to_string(&response)?,
                ]));
            }
        };
        let request_id = request.id.clone();
        if let Err(error) = service.validate_request_protocol(&request) {
            let response = JsonRpcResponse::error(Some(request_id), error);
            return Ok(StdioSubscriptionInput::Handled(vec![
                serde_json::to_string(&response)?,
            ]));
        }

        let params = request
            .params
            .clone()
            .ok_or_else(|| {
                crate::error::JsonRpcError::invalid_params("subscriptions/listen requires params")
            })
            .and_then(|value| {
                serde_json::from_value::<SubscriptionsListenParams>(value)
                    .map_err(|error| crate::error::JsonRpcError::invalid_params(error.to_string()))
            });
        let params = match params {
            Ok(params) => params,
            Err(error) => {
                let response = JsonRpcResponse::error(Some(request_id), error);
                return Ok(StdioSubscriptionInput::Handled(vec![
                    serde_json::to_string(&response)?,
                ]));
            }
        };
        let Some(requested) = params.notifications else {
            let response = JsonRpcResponse::error(
                Some(request_id),
                crate::error::JsonRpcError::invalid_params(
                    "subscriptions/listen requires a notifications filter",
                ),
            );
            return Ok(StdioSubscriptionInput::Handled(vec![
                serde_json::to_string(&response)?,
            ]));
        };
        if self.active.contains_key(&request_id) {
            let response = JsonRpcResponse::error(
                Some(request_id),
                crate::error::JsonRpcError::invalid_request(
                    "subscription request id is already active",
                ),
            );
            return Ok(StdioSubscriptionInput::Handled(vec![
                serde_json::to_string(&response)?,
            ]));
        }

        // SEP-2663: asking for task notifications without declaring the
        // extension is answered with the missing-capability error, the same
        // way the three task methods answer it.
        if requested.task_ids.is_some() && !stdio_request_declares_tasks(parsed) {
            let response = JsonRpcResponse::error(
                Some(request_id),
                crate::error::JsonRpcError::missing_required_client_capability(
                    crate::router::tasks_client_capabilities(),
                ),
            );
            return Ok(StdioSubscriptionInput::Handled(vec![
                serde_json::to_string(&response)?,
            ]));
        }

        let accepted = accepted_subscription_filter(requested, self.tasks_enabled);
        let acknowledgment = subscription_acknowledgment(request_id.clone(), accepted.clone());
        let acknowledgment = serde_json::to_string(&acknowledgment)?;
        self.modern_mode = true;
        self.active.insert(request_id, accepted);
        Ok(StdioSubscriptionInput::Handled(vec![acknowledgment]))
    }

    /// Route a subscription-scoped notification and suppress its untagged
    /// form whenever at least one final subscription is active.
    fn route_notification(&self, notification: &ServerNotification) -> Option<Vec<String>> {
        if !self.modern_mode
            || !matches!(
                notification,
                ServerNotification::ResourceUpdated { .. }
                    | ServerNotification::ResourcesListChanged
                    | ServerNotification::ToolsListChanged
                    | ServerNotification::PromptsListChanged
                    | ServerNotification::FinalTaskStatusChanged(_)
            )
        {
            return None;
        }

        Some(
            self.active
                .iter()
                .filter(|(_, filter)| subscription_matches(notification, filter))
                .filter_map(|(id, _)| tagged_subscription_notification(notification, id))
                .collect(),
        )
    }

    fn close(&mut self, request_id: &RequestId) -> Result<Option<String>> {
        if self.active.remove(request_id).is_none() {
            return Ok(None);
        }
        Ok(Some(serde_json::to_string(
            &subscription_complete_response(request_id.clone(), self.server_info.clone()),
        )?))
    }

    fn close_all(&mut self) -> Result<Vec<String>> {
        let ids: Vec<_> = self.active.keys().cloned().collect();
        ids.into_iter()
            .map(|id| {
                self.close(&id)?
                    .ok_or_else(|| Error::Internal("active subscription disappeared".to_string()))
            })
            .collect()
    }
}

/// Strip an optional UTF-8 BOM, then trim whitespace.
///
/// Windows tools sometimes prefix the first stdout line with a UTF-8 BOM
/// (`\u{feff}`). Without stripping it, the JSON parser sees an unexpected
/// character at offset 0 and rejects the whole message.
fn clean_input_line(line: &str) -> &str {
    line.strip_prefix('\u{feff}').unwrap_or(line).trim()
}

/// Build a JSON-RPC parse-error response from a parser/dispatch error message.
///
/// Per JSON-RPC 2.0, a parse error sets `code` to `-32700` and `id` to
/// `null` (the request id cannot be recovered from unparseable input).
/// Returning a single shared constructor keeps every stdio parse-error
/// path consistent and gives the wire-format tests in
/// [`tower_mcp_types::testing`] one stable surface to assert against.
pub(crate) fn parse_error_response(message: impl Into<String>) -> JsonRpcResponse {
    JsonRpcResponse::error(None, crate::error::JsonRpcError::parse_error(message))
}

/// Process a single line of JSON-RPC input
///
/// Returns `Ok(Some(response))` for requests, `Ok(None)` for notifications.
async fn process_line(
    service: &mut JsonRpcService<McpRouter>,
    router: &McpRouter,
    line: &str,
) -> Result<Option<JsonRpcResponseMessage>> {
    // Check if it's a notification (no id field)
    let parsed: serde_json::Value = serde_json::from_str(line)?;
    if let Err(error) =
        service.inspect_incoming_value(&parsed, crate::inspection::McpDirection::ClientToServer)
    {
        return Ok(Some(JsonRpcResponseMessage::Single(
            JsonRpcResponse::error(None, error),
        )));
    }
    if !parsed.is_array()
        && parsed.get("id").is_none()
        && let Ok(notification) = serde_json::from_str::<JsonRpcNotification>(line)
    {
        handle_notification(router, notification)?;
        return Ok(None);
    }

    // Parse and process as a request (single or batch)
    let message: JsonRpcMessage = serde_json::from_str(line)?;
    let response = service.call_message(message).await?;
    Ok(Some(response))
}

/// Handle a JSON-RPC notification
fn handle_notification(router: &McpRouter, notification: JsonRpcNotification) -> Result<()> {
    let mcp_notification = McpNotification::from_jsonrpc(&notification)?;
    router.handle_notification(mcp_notification);
    Ok(())
}

/// Serialize a server notification to a JSON-RPC notification string.
pub(crate) fn serialize_notification(notification: &ServerNotification) -> Option<String> {
    match notification {
        ServerNotification::Progress(params) => {
            let notif = JsonRpcNotification::new(notifications::PROGRESS)
                .with_params(serde_json::to_value(params).unwrap_or_default());
            serde_json::to_string(&notif).ok()
        }
        ServerNotification::LogMessage(params) => {
            let notif = JsonRpcNotification::new(notifications::MESSAGE)
                .with_params(serde_json::to_value(params).unwrap_or_default());
            serde_json::to_string(&notif).ok()
        }
        ServerNotification::ResourceUpdated { uri } => {
            let notif = JsonRpcNotification::new(notifications::RESOURCE_UPDATED)
                .with_params(serde_json::json!({ "uri": uri }));
            serde_json::to_string(&notif).ok()
        }
        ServerNotification::ResourcesListChanged => {
            let notif = JsonRpcNotification::new(notifications::RESOURCES_LIST_CHANGED);
            serde_json::to_string(&notif).ok()
        }
        ServerNotification::ToolsListChanged => {
            let notif = JsonRpcNotification::new(notifications::TOOLS_LIST_CHANGED);
            serde_json::to_string(&notif).ok()
        }
        ServerNotification::PromptsListChanged => {
            let notif = JsonRpcNotification::new(notifications::PROMPTS_LIST_CHANGED);
            serde_json::to_string(&notif).ok()
        }
        ServerNotification::TaskStatusChanged(params) => {
            let notif = JsonRpcNotification::new(notifications::TASK_STATUS_CHANGED)
                .with_params(serde_json::to_value(params).unwrap_or_default());
            serde_json::to_string(&notif).ok()
        }
        ServerNotification::FinalTaskStatusChanged(params) => {
            let notif = JsonRpcNotification::new(notifications::TASK_STATUS_CHANGED)
                .with_params(serde_json::to_value(params).ok()?);
            serde_json::to_string(&notif).ok()
        }
    }
}

/// Write a line to an async writer and flush.
async fn write_line_to_stdout<W>(stdout: &mut W, line: &str) -> Result<()>
where
    W: tokio::io::AsyncWrite + Unpin,
{
    stdout
        .write_all(line.as_bytes())
        .await
        .map_err(|e| Error::Transport(format!("Failed to write to stdout: {}", e)))?;
    stdout
        .write_all(b"\n")
        .await
        .map_err(|e| Error::Transport(format!("Failed to write newline: {}", e)))?;
    stdout
        .flush()
        .await
        .map_err(|e| Error::Transport(format!("Failed to flush stdout: {}", e)))?;
    Ok(())
}

// ============================================================================
// Async stdio transport
// ============================================================================

/// Stdio transport for MCP servers
///
/// Reads JSON-RPC messages from stdin and writes responses to stdout.
/// Supports single requests for every implemented revision and request
/// batches only for an exact negotiated `2025-03-26` connection. Later MCP
/// revisions reject top-level JSON-RPC arrays.
///
/// Server notifications (progress, logging, resource/tool/prompt list changes)
/// are automatically forwarded to stdout as JSON-RPC notifications.
///
/// # Example
///
/// ```rust,no_run
/// use tower_mcp::{BoxError, McpRouter, StdioTransport};
///
/// #[tokio::main]
/// async fn main() -> Result<(), BoxError> {
///     let router = McpRouter::new()
///         .server_info("my-server", "1.0.0");
///
///     let mut transport = StdioTransport::new(router);
///     transport.run().await?;
///     Ok(())
/// }
/// ```
pub struct StdioTransport {
    service: JsonRpcService<McpRouter>,
    router: McpRouter,
    notification_rx: NotificationReceiver,
    control_tx: mpsc::UnboundedSender<StdioControl>,
    control_rx: mpsc::UnboundedReceiver<StdioControl>,
}

impl StdioTransport {
    /// Create a new stdio transport wrapping an MCP router
    pub fn new(router: McpRouter) -> Self {
        let (notif_tx, notification_rx) = notification_channel(256);
        let (control_tx, control_rx) = stdio_control_channel();
        let router = router.with_notification_sender(notif_tx);
        let service = JsonRpcService::new(router.clone());
        Self {
            service,
            router,
            notification_rx,
            control_tx,
            control_rx,
        }
    }

    /// Return a cloneable handle for graceful subscription closure or server
    /// shutdown while [`Self::run`] is active.
    pub fn handle(&self) -> StdioTransportHandle {
        StdioTransportHandle {
            control_tx: self.control_tx.clone(),
        }
    }

    /// Set the exact protocol versions this transport accepts and advertises.
    ///
    /// By default every implementation compiled into `tower-mcp` is enabled.
    /// Final 2026-07-28 requests carry their version and capabilities in each
    /// request's `_meta`; legacy initialize traffic may coexist on the same
    /// stdio stream.
    pub fn protocol_support(mut self, support: ProtocolSupport) -> Self {
        self.service = self.service.protocol_support(support);
        self
    }

    /// Construct and set an exact runtime protocol-version allow-list.
    pub fn protocol_versions<I, V>(
        mut self,
        versions: I,
    ) -> std::result::Result<Self, ProtocolSupportError>
    where
        I: IntoIterator<Item = V>,
        V: Into<String>,
    {
        self.service = self.service.protocol_versions(versions)?;
        Ok(self)
    }

    /// Apply a tower middleware layer to this transport.
    ///
    /// This converts the `StdioTransport` into a [`GenericStdioTransport`] with
    /// the middleware applied, while preserving notification forwarding.
    ///
    /// Use [`tower::ServiceBuilder`] to compose multiple layers:
    ///
    /// ```rust,no_run
    /// use std::time::Duration;
    /// use tower::ServiceBuilder;
    /// use tower::timeout::TimeoutLayer;
    /// use tower_mcp::{BoxError, McpRouter, StdioTransport};
    ///
    /// #[tokio::main]
    /// async fn main() -> Result<(), BoxError> {
    ///     let router = McpRouter::new().server_info("my-server", "1.0.0");
    ///
    ///     let mut transport = StdioTransport::new(router)
    ///         .layer(
    ///             ServiceBuilder::new()
    ///                 .layer(TimeoutLayer::new(Duration::from_secs(5)))
    ///                 .concurrency_limit(10)
    ///                 .into_inner(),
    ///         );
    ///
    ///     transport.run().await?;
    ///     Ok(())
    /// }
    /// ```
    pub fn layer<L>(
        self,
        layer: L,
    ) -> GenericStdioTransport<InjectAnnotations<CatchError<L::Service>>>
    where
        L: tower::Layer<McpRouter>,
        L::Service: Service<RouterRequest, Response = RouterResponse> + Clone + Send + 'static,
        <L::Service as Service<RouterRequest>>::Error: std::fmt::Display + Send,
        <L::Service as Service<RouterRequest>>::Future: Send,
    {
        let protocol_support = self.service.configured_protocol_support().clone();
        let annotations = self.router.tool_annotations_map();
        let wrapped = layer.layer(self.router);
        let service = InjectAnnotations::new(CatchError::new(wrapped), annotations);
        GenericStdioTransport {
            service: JsonRpcService::new(service).protocol_support(protocol_support),
            notification_rx: Some(self.notification_rx),
            control_tx: self.control_tx,
            control_rx: self.control_rx,
        }
    }

    /// Run the transport, processing messages until EOF or error
    ///
    /// This is a thin wrapper around [`Self::run_with_streams`] that wires up
    /// `tokio::io::stdin()` and `tokio::io::stdout()`. Most users want this
    /// method; use [`Self::run_with_streams`] only for in-process testing.
    pub async fn run(&mut self) -> Result<()> {
        self.run_with_streams(tokio::io::stdin(), tokio::io::stdout())
            .await
    }

    /// Run the transport, reading from `reader` and writing to `writer`.
    ///
    /// This is the streams-generic counterpart of [`Self::run`]. The default
    /// `run()` calls this with `tokio::io::stdin()` / `tokio::io::stdout()`.
    ///
    /// Exposing this lets tests drive the full read-eval-write loop with
    /// `tokio::io::duplex()` and assert end-to-end behavior (parse-error
    /// frames, loop continuation across bad input, EOF handling).
    pub async fn run_with_streams<R, W>(&mut self, reader: R, mut writer: W) -> Result<()>
    where
        R: tokio::io::AsyncRead + Unpin + Send,
        W: tokio::io::AsyncWrite + Unpin + Send,
    {
        let mut reader = BufReader::new(reader);
        #[cfg(feature = "stateless")]
        let mut subscriptions = StdioSubscriptions {
            server_info: Some(self.router.implementation()),
            tasks_enabled: self.router.final_tasks_enabled(),
            ..StdioSubscriptions::default()
        };

        tracing::info!("Stdio transport started, waiting for input");

        loop {
            let mut line = String::new();

            tokio::select! {
                // Handle incoming messages from stdin
                result = reader.read_line(&mut line) => {
                    let bytes_read = result.map_err(|e| {
                        Error::Transport(format!("Failed to read from stdin: {}", e))
                    })?;

                    if bytes_read == 0 {
                        // EOF
                        tracing::info!("Stdin closed, shutting down");
                        break;
                    }

                    let trimmed = clean_input_line(&line);
                    if trimmed.is_empty() {
                        continue;
                    }

                    tracing::debug!(input = %trimmed, "Received message");

                    #[cfg(feature = "stateless")]
                    {
                        let parsed: serde_json::Value = match serde_json::from_str(trimmed) {
                            Ok(parsed) => parsed,
                            Err(_) => serde_json::Value::Null,
                        };
                        if let StdioSubscriptionInput::Handled(frames) =
                            subscriptions.handle_input(&self.service, &parsed)?
                        {
                            for frame in frames {
                                write_line_to_stdout(&mut writer, &frame).await?;
                            }
                            continue;
                        }
                    }

                    match process_line(&mut self.service, &self.router, trimmed).await {
                        Ok(Some(response)) => {
                            let response_json = serde_json::to_string(&response).map_err(|e| {
                                Error::Transport(format!("Failed to serialize response: {}", e))
                            })?;
                            tracing::debug!(output = %response_json, "Sending response");
                            write_line_to_stdout(&mut writer, &response_json).await?;
                        }
                        Ok(None) => {
                            // Notification, no response needed
                        }
                        Err(e) => {
                            tracing::error!(error = %e, "Error processing message");
                            let error_response = parse_error_response(e.to_string());
                            let response_json = serde_json::to_string(&error_response).map_err(|e| {
                                Error::Transport(format!("Failed to serialize error: {}", e))
                            })?;
                            write_line_to_stdout(&mut writer, &response_json).await?;
                        }
                    }
                }

                // Forward server notifications to stdout
                Some(notification) = self.notification_rx.recv() => {
                    #[cfg(feature = "stateless")]
                    if let Some(frames) = subscriptions.route_notification(&notification) {
                        for json in frames {
                            tracing::debug!(output = %json, "Sending subscription notification");
                            write_line_to_stdout(&mut writer, &json).await?;
                        }
                        continue;
                    }
                    if let Some(json) = serialize_notification(&notification) {
                        tracing::debug!(output = %json, "Sending notification");
                        write_line_to_stdout(&mut writer, &json).await?;
                    }
                }

                Some(control) = self.control_rx.recv() => {
                    match control {
                        #[cfg(feature = "stateless")]
                        StdioControl::CloseSubscription(request_id) => {
                            if let Some(json) = subscriptions.close(&request_id)? {
                                write_line_to_stdout(&mut writer, &json).await?;
                            }
                        }
                        StdioControl::Shutdown => {
                            #[cfg(feature = "stateless")]
                            for json in subscriptions.close_all()? {
                                write_line_to_stdout(&mut writer, &json).await?;
                            }
                            break;
                        }
                    }
                }
            }
        }

        Ok(())
    }
}

// ============================================================================
// Generic stdio transport for middleware-wrapped services
// ============================================================================

/// Generic stdio transport that works with any tower service.
///
/// This transport accepts a middleware-wrapped service instead of an `McpRouter`
/// directly. Use this when you want to apply tower middleware layers like
/// rate limiting or bulkhead patterns.
///
/// # Server Notifications
///
/// Use [`GenericStdioTransport::with_notifications`] to enable server notification
/// forwarding. Without it, notifications from the router will not reach the client.
///
/// # Example
///
/// ```rust,no_run
/// use std::time::Duration;
/// use tower::ServiceBuilder;
/// use tower::timeout::TimeoutLayer;
/// use tower_mcp::{BoxError, CatchError, McpRouter, GenericStdioTransport};
/// use tower_mcp::context::notification_channel;
///
/// #[tokio::main]
/// async fn main() -> Result<(), BoxError> {
///     // Set up notification channel before wrapping in middleware
///     let (notif_tx, notif_rx) = notification_channel(256);
///     let router = McpRouter::new()
///         .server_info("my-server", "1.0.0")
///         .with_notification_sender(notif_tx);
///
///     let service = CatchError::new(
///         ServiceBuilder::new()
///             .layer(TimeoutLayer::new(Duration::from_secs(5)))
///             .concurrency_limit(10)
///             .service(router),
///     );
///
///     let mut transport = GenericStdioTransport::with_notifications(service, notif_rx);
///     transport.run().await?;
///     Ok(())
/// }
/// ```
pub struct GenericStdioTransport<S>
where
    S: Service<RouterRequest, Response = RouterResponse, Error = std::convert::Infallible>
        + Clone
        + Send
        + 'static,
    S::Future: Send,
{
    service: JsonRpcService<S>,
    notification_rx: Option<NotificationReceiver>,
    control_tx: mpsc::UnboundedSender<StdioControl>,
    control_rx: mpsc::UnboundedReceiver<StdioControl>,
}

impl<S> GenericStdioTransport<S>
where
    S: Service<RouterRequest, Response = RouterResponse, Error = std::convert::Infallible>
        + Clone
        + Send
        + 'static,
    S::Future: Send,
{
    /// Create a new generic stdio transport wrapping any compatible service.
    ///
    /// The service must implement `Service<RouterRequest, Response = RouterResponse>`.
    /// This is typically an `McpRouter` wrapped in tower middleware layers.
    ///
    /// **Note:** This constructor does not set up notification forwarding. Server
    /// notifications (progress, logging, list changes) will not reach the client.
    /// Use [`GenericStdioTransport::with_notifications`] instead to enable them.
    pub fn new(service: S) -> Self {
        let (control_tx, control_rx) = stdio_control_channel();
        Self {
            service: JsonRpcService::new(service),
            notification_rx: None,
            control_tx,
            control_rx,
        }
    }

    /// Create a new generic stdio transport with notification forwarding.
    ///
    /// Pass a `NotificationReceiver` from [`notification_channel()`] to enable
    /// server notifications. Make sure to also call
    /// `router.with_notification_sender(tx)` before wrapping the router in middleware.
    ///
    /// [`notification_channel()`]: crate::context::notification_channel
    pub fn with_notifications(service: S, notification_rx: NotificationReceiver) -> Self {
        let (control_tx, control_rx) = stdio_control_channel();
        Self {
            service: JsonRpcService::new(service),
            notification_rx: Some(notification_rx),
            control_tx,
            control_rx,
        }
    }

    /// Return a cloneable handle for graceful subscription closure or server
    /// shutdown while [`Self::run`] is active.
    pub fn handle(&self) -> StdioTransportHandle {
        StdioTransportHandle {
            control_tx: self.control_tx.clone(),
        }
    }

    /// Set the exact protocol versions this transport accepts and advertises.
    pub fn protocol_support(mut self, support: ProtocolSupport) -> Self {
        self.service = self.service.protocol_support(support);
        self
    }

    /// Construct and set an exact runtime protocol-version allow-list.
    pub fn protocol_versions<I, V>(
        mut self,
        versions: I,
    ) -> std::result::Result<Self, ProtocolSupportError>
    where
        I: IntoIterator<Item = V>,
        V: Into<String>,
    {
        self.service = self.service.protocol_versions(versions)?;
        Ok(self)
    }

    /// Run the transport, processing messages until EOF or error.
    ///
    /// Thin wrapper around [`Self::run_with_streams`] that wires up
    /// `tokio::io::stdin()` / `tokio::io::stdout()`.
    pub async fn run(&mut self) -> Result<()> {
        self.run_with_streams(tokio::io::stdin(), tokio::io::stdout())
            .await
    }

    /// Run the transport, reading from `reader` and writing to `writer`.
    ///
    /// Streams-generic counterpart of [`Self::run`]. Lets tests drive the
    /// read-eval-write loop with in-memory streams (e.g. `tokio::io::duplex()`).
    pub async fn run_with_streams<R, W>(&mut self, reader: R, mut writer: W) -> Result<()>
    where
        R: tokio::io::AsyncRead + Unpin + Send,
        W: tokio::io::AsyncWrite + Unpin + Send,
    {
        let mut reader = BufReader::new(reader);
        #[cfg(feature = "stateless")]
        let mut subscriptions = StdioSubscriptions::default();

        tracing::info!("Generic stdio transport started, waiting for input");

        loop {
            let mut line = String::new();

            // Use select! if we have a notification receiver, otherwise just read
            if let Some(ref mut notif_rx) = self.notification_rx {
                tokio::select! {
                    result = reader.read_line(&mut line) => {
                        let bytes_read = result.map_err(|e| {
                            Error::Transport(format!("Failed to read from stdin: {}", e))
                        })?;

                        if bytes_read == 0 {
                            tracing::info!("Stdin closed, shutting down");
                            break;
                        }

                        Self::process_input(
                            &mut self.service,
                            &line,
                            &mut writer,
                            true,
                            #[cfg(feature = "stateless")]
                            &mut subscriptions,
                        ).await?;
                    }

                    Some(notification) = notif_rx.recv() => {
                        #[cfg(feature = "stateless")]
                        if let Some(frames) = subscriptions.route_notification(&notification) {
                            for json in frames {
                                tracing::debug!(output = %json, "Sending subscription notification");
                                write_line_to_stdout(&mut writer, &json).await?;
                            }
                            continue;
                        }
                        if let Some(json) = serialize_notification(&notification) {
                            tracing::debug!(output = %json, "Sending notification");
                            write_line_to_stdout(&mut writer, &json).await?;
                        }
                    }

                    Some(control) = self.control_rx.recv() => {
                        if Self::handle_control(
                            control,
                            &mut writer,
                            #[cfg(feature = "stateless")]
                            &mut subscriptions,
                        ).await? {
                            break;
                        }
                    }
                }
            } else {
                tokio::select! {
                    result = reader.read_line(&mut line) => {
                        let bytes_read = result.map_err(|e| {
                            Error::Transport(format!("Failed to read from stdin: {}", e))
                        })?;
                        if bytes_read == 0 {
                            tracing::info!("Stdin closed, shutting down");
                            break;
                        }
                        Self::process_input(
                            &mut self.service,
                            &line,
                            &mut writer,
                            false,
                            #[cfg(feature = "stateless")]
                            &mut subscriptions,
                        ).await?;
                    }
                    Some(control) = self.control_rx.recv() => {
                        if Self::handle_control(
                            control,
                            &mut writer,
                            #[cfg(feature = "stateless")]
                            &mut subscriptions,
                        ).await? {
                            break;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    async fn process_input<W>(
        service: &mut JsonRpcService<S>,
        line: &str,
        writer: &mut W,
        subscriptions_enabled: bool,
        #[cfg(feature = "stateless")] subscriptions: &mut StdioSubscriptions,
    ) -> Result<()>
    where
        W: tokio::io::AsyncWrite + Unpin + Send,
    {
        let trimmed = clean_input_line(line);
        if trimmed.is_empty() {
            return Ok(());
        }

        tracing::debug!(input = %trimmed, "Received message");

        // Check if it's a notification (no id field)
        let parsed: serde_json::Value = match serde_json::from_str(trimmed) {
            Ok(v) => v,
            Err(e) => {
                Self::write_error(writer, None, &e.to_string()).await?;
                return Ok(());
            }
        };

        #[cfg(feature = "stateless")]
        if subscriptions_enabled
            && let StdioSubscriptionInput::Handled(frames) =
                subscriptions.handle_input(service, &parsed)?
        {
            for frame in frames {
                write_line_to_stdout(writer, &frame).await?;
            }
            return Ok(());
        }
        #[cfg(not(feature = "stateless"))]
        let _ = subscriptions_enabled;

        if let Err(error) =
            service.inspect_incoming_value(&parsed, crate::inspection::McpDirection::ClientToServer)
        {
            let response = JsonRpcResponse::error(None, error);
            write_line_to_stdout(writer, &serde_json::to_string(&response)?).await?;
            return Ok(());
        }

        if !parsed.is_array() && parsed.get("id").is_none() {
            // Notification - log and ignore since we don't have router access
            tracing::debug!(
                method = parsed.get("method").and_then(|m| m.as_str()),
                "Received notification (ignored in generic transport)"
            );
            return Ok(());
        }

        // Parse and process as a request (single or batch)
        let message: JsonRpcMessage = match serde_json::from_str(trimmed) {
            Ok(m) => m,
            Err(e) => {
                Self::write_error(writer, None, &e.to_string()).await?;
                return Ok(());
            }
        };

        match service.call_message(message).await {
            Ok(response) => {
                let response_json = serde_json::to_string(&response).map_err(|e| {
                    Error::Transport(format!("Failed to serialize response: {}", e))
                })?;
                tracing::debug!(output = %response_json, "Sending response");
                write_line_to_stdout(writer, &response_json).await?;
            }
            Err(e) => {
                tracing::error!(error = %e, "Error processing message");
                Self::write_error(writer, None, &e.to_string()).await?;
            }
        }
        Ok(())
    }

    async fn handle_control<W>(
        control: StdioControl,
        writer: &mut W,
        #[cfg(feature = "stateless")] subscriptions: &mut StdioSubscriptions,
    ) -> Result<bool>
    where
        W: tokio::io::AsyncWrite + Unpin + Send,
    {
        #[cfg(not(feature = "stateless"))]
        let _ = &mut *writer;
        match control {
            #[cfg(feature = "stateless")]
            StdioControl::CloseSubscription(request_id) => {
                if let Some(json) = subscriptions.close(&request_id)? {
                    write_line_to_stdout(writer, &json).await?;
                }
                Ok(false)
            }
            StdioControl::Shutdown => {
                #[cfg(feature = "stateless")]
                for json in subscriptions.close_all()? {
                    write_line_to_stdout(writer, &json).await?;
                }
                Ok(true)
            }
        }
    }

    async fn write_error<W>(
        writer: &mut W,
        id: Option<crate::protocol::RequestId>,
        message: &str,
    ) -> Result<()>
    where
        W: tokio::io::AsyncWrite + Unpin + Send,
    {
        // `id` is currently always `None` from every call site (parse-error
        // path), so use the shared helper; preserve the parameter for callers
        // that may want to surface a known-id error in future.
        let error_response = if let Some(id) = id {
            JsonRpcResponse::error(Some(id), crate::error::JsonRpcError::parse_error(message))
        } else {
            parse_error_response(message)
        };
        let response_json = serde_json::to_string(&error_response)
            .map_err(|e| Error::Transport(format!("Failed to serialize error: {}", e)))?;
        write_line_to_stdout(writer, &response_json).await
    }
}

// ============================================================================
// Synchronous stdio transport
// ============================================================================

/// Synchronous stdio transport for simpler use cases
///
/// This version uses blocking I/O and is suitable for simple CLI tools.
///
/// **Note:** This transport does not support server notification forwarding
/// (progress, logging, list changes) because it uses blocking I/O. Use
/// [`StdioTransport`] for full notification support.
pub struct SyncStdioTransport {
    service: JsonRpcService<McpRouter>,
    router: McpRouter,
}

impl SyncStdioTransport {
    /// Create a new synchronous stdio transport
    pub fn new(router: McpRouter) -> Self {
        let service = JsonRpcService::new(router.clone());
        Self { service, router }
    }

    /// Set the exact protocol versions this transport accepts and advertises.
    pub fn protocol_support(mut self, support: ProtocolSupport) -> Self {
        self.service = self.service.protocol_support(support);
        self
    }

    /// Construct and set an exact runtime protocol-version allow-list.
    pub fn protocol_versions<I, V>(
        mut self,
        versions: I,
    ) -> std::result::Result<Self, ProtocolSupportError>
    where
        I: IntoIterator<Item = V>,
        V: Into<String>,
    {
        self.service = self.service.protocol_versions(versions)?;
        Ok(self)
    }

    /// Run the transport synchronously using a tokio runtime
    pub fn run_blocking(&mut self) -> Result<()> {
        let rt = tokio::runtime::Runtime::new()
            .map_err(|e| Error::Transport(format!("Failed to create runtime: {}", e)))?;

        let stdin = io::stdin();
        let mut stdout = io::stdout();

        tracing::info!("Sync stdio transport started");

        for line in stdin.lock().lines() {
            let line =
                line.map_err(|e| Error::Transport(format!("Failed to read from stdin: {}", e)))?;

            let trimmed = clean_input_line(&line);
            if trimmed.is_empty() {
                continue;
            }

            tracing::debug!(input = %trimmed, "Received message");

            match rt.block_on(process_line(&mut self.service, &self.router, trimmed)) {
                Ok(Some(response)) => {
                    let response_json = serde_json::to_string(&response).map_err(|e| {
                        Error::Transport(format!("Failed to serialize response: {}", e))
                    })?;
                    tracing::debug!(output = %response_json, "Sending response");
                    writeln!(stdout, "{}", response_json).map_err(|e| {
                        Error::Transport(format!("Failed to write to stdout: {}", e))
                    })?;
                    stdout
                        .flush()
                        .map_err(|e| Error::Transport(format!("Failed to flush stdout: {}", e)))?;
                }
                Ok(None) => {
                    // Notification, no response
                }
                Err(e) => {
                    tracing::error!(error = %e, "Error processing message");
                    let error_response = parse_error_response(e.to_string());
                    let response_json = serde_json::to_string(&error_response).map_err(|e| {
                        Error::Transport(format!("Failed to serialize error: {}", e))
                    })?;
                    writeln!(stdout, "{}", response_json)
                        .map_err(|e| Error::Transport(format!("Failed to write error: {}", e)))?;
                    stdout
                        .flush()
                        .map_err(|e| Error::Transport(format!("Failed to flush stdout: {}", e)))?;
                }
            }
        }

        tracing::info!("Stdin closed, shutting down");
        Ok(())
    }
}

// ============================================================================
// Bidirectional stdio transport (with sampling support)
// ============================================================================

/// Pending request waiting for a response
struct PendingRequest {
    response_tx: oneshot::Sender<Result<serde_json::Value>>,
}

/// Bidirectional stdio transport with sampling support
///
/// For legacy protocol requests, this transport supports both incoming
/// requests from clients and outgoing requests to clients (for sampling/LLM
/// requests). It multiplexes stdin/stdout to handle the bidirectional
/// communication. Final 2026-07-28 handlers cannot initiate requests.
///
/// Server notifications (progress, logging, resource/tool/prompt list changes)
/// are automatically forwarded to stdout as JSON-RPC notifications.
///
/// # Example
///
/// ```rust,no_run
/// use tower_mcp::{BoxError, McpRouter, ToolBuilder, CallToolResult};
/// use tower_mcp::transport::stdio::BidirectionalStdioTransport;
/// use tower_mcp::{CreateMessageParams, SamplingMessage};
/// use tower_mcp::extract::{Context, RawArgs};
///
/// #[tokio::main]
/// async fn main() -> Result<(), BoxError> {
///     let tool = ToolBuilder::new("ai-tool")
///         .description("A tool that uses LLM")
///         .extractor_handler((), |ctx: Context, RawArgs(_): RawArgs| async move {
///             // Request LLM completion from the client
///             let params = CreateMessageParams::new(
///                 vec![SamplingMessage::user("Help me with: ...")],
///                 500,
///             );
///             let result = ctx.sample(params).await?;
///             Ok(CallToolResult::text(format!("{:?}", result.content)))
///         })
///         .build();
///
///     let router = McpRouter::new()
///         .server_info("my-server", "1.0.0")
///         .tool(tool);
///
///     let mut transport = BidirectionalStdioTransport::new(router);
///     transport.run().await?;
///     Ok(())
/// }
/// ```
pub struct BidirectionalStdioTransport {
    service: JsonRpcService<McpRouter>,
    router: McpRouter,
    /// Channel for receiving outgoing requests to send to the client
    request_rx: OutgoingRequestReceiver,
    /// Handle for handlers to send requests to the client
    client_requester: ClientRequesterHandle,
    /// Pending requests waiting for responses
    pending_requests: Arc<Mutex<HashMap<RequestId, PendingRequest>>>,
    /// Channel for receiving server notifications to forward to the client
    notification_rx: NotificationReceiver,
    control_tx: mpsc::UnboundedSender<StdioControl>,
    control_rx: mpsc::UnboundedReceiver<StdioControl>,
}

impl BidirectionalStdioTransport {
    /// Create a new bidirectional stdio transport
    pub fn new(router: McpRouter) -> Self {
        let (request_tx, request_rx) = outgoing_request_channel(32);
        let client_requester: ClientRequesterHandle =
            Arc::new(ChannelClientRequester::new(request_tx));

        let (notif_tx, notification_rx) = notification_channel(256);
        let (control_tx, control_rx) = stdio_control_channel();
        let router = router
            .with_notification_sender(notif_tx)
            .with_client_requester(client_requester.clone());

        let service = JsonRpcService::new(router.clone());

        Self {
            service,
            router,
            request_rx,
            client_requester,
            pending_requests: Arc::new(Mutex::new(HashMap::new())),
            notification_rx,
            control_tx,
            control_rx,
        }
    }

    /// Return a cloneable handle for graceful subscription closure or server
    /// shutdown while [`Self::run`] is active.
    pub fn handle(&self) -> StdioTransportHandle {
        StdioTransportHandle {
            control_tx: self.control_tx.clone(),
        }
    }

    /// Set the exact protocol versions this transport accepts and advertises.
    ///
    /// Final handlers never receive the legacy client requester, because the
    /// 2026-07-28 protocol forbids servers from initiating JSON-RPC requests.
    pub fn protocol_support(mut self, support: ProtocolSupport) -> Self {
        self.service = self.service.protocol_support(support);
        self
    }

    /// Construct and set an exact runtime protocol-version allow-list.
    pub fn protocol_versions<I, V>(
        mut self,
        versions: I,
    ) -> std::result::Result<Self, ProtocolSupportError>
    where
        I: IntoIterator<Item = V>,
        V: Into<String>,
    {
        self.service = self.service.protocol_versions(versions)?;
        Ok(self)
    }

    /// Get the client requester handle
    ///
    /// The requester is already wired into the router's request context by
    /// [`Self::new`], so legacy handlers can elicit and sample without further
    /// setup. Final 2026-07-28 handlers do not receive it. This getter exposes
    /// the same handle for advanced callers that want to issue
    /// server-to-client requests directly on legacy connections.
    pub fn client_requester(&self) -> ClientRequesterHandle {
        self.client_requester.clone()
    }

    /// Run the transport, processing messages until EOF or error
    ///
    /// Thin wrapper around [`Self::run_with_streams`] that wires up
    /// `tokio::io::stdin()` / `tokio::io::stdout()`.
    pub async fn run(&mut self) -> Result<()> {
        self.run_with_streams(tokio::io::stdin(), tokio::io::stdout())
            .await
    }

    /// Run the transport, reading from `reader` and writing to `writer`.
    ///
    /// Streams-generic counterpart of [`Self::run`]. The writer is held
    /// behind an `Arc<Mutex<_>>` so the outgoing-request and notification
    /// paths can share it with the incoming-message branch -- the same
    /// concurrency model `run()` has always used, just with the streams
    /// supplied by the caller.
    pub async fn run_with_streams<R, W>(&mut self, reader: R, writer: W) -> Result<()>
    where
        R: tokio::io::AsyncRead + Unpin + Send,
        W: tokio::io::AsyncWrite + Unpin + Send + 'static,
    {
        let writer = Arc::new(Mutex::new(writer));
        let mut reader = BufReader::new(reader);
        #[cfg(feature = "stateless")]
        let mut subscriptions = StdioSubscriptions {
            server_info: Some(self.router.implementation()),
            tasks_enabled: self.router.final_tasks_enabled(),
            ..StdioSubscriptions::default()
        };

        tracing::info!("Bidirectional stdio transport started, waiting for input");

        loop {
            let mut line = String::new();

            tokio::select! {
                // Handle incoming messages from stdin
                result = reader.read_line(&mut line) => {
                    let bytes_read = result.map_err(|e| {
                        Error::Transport(format!("Failed to read from stdin: {}", e))
                    })?;

                    if bytes_read == 0 {
                        tracing::info!("Stdin closed, shutting down");
                        break;
                    }

                    let trimmed = clean_input_line(&line);
                    if trimmed.is_empty() {
                        continue;
                    }

                    self.handle_incoming_message(
                        trimmed,
                        writer.clone(),
                        #[cfg(feature = "stateless")]
                        &mut subscriptions,
                    ).await?;
                }

                // Handle outgoing requests to send to the client
                Some(outgoing) = self.request_rx.recv() => {
                    self.send_outgoing_request(outgoing, writer.clone()).await?;
                }

                // Forward server notifications to the client
                Some(notification) = self.notification_rx.recv() => {
                    #[cfg(feature = "stateless")]
                    if let Some(frames) = subscriptions.route_notification(&notification) {
                        for json in frames {
                            tracing::debug!(output = %json, "Sending subscription notification");
                            self.write_line(&json, writer.clone()).await?;
                        }
                        continue;
                    }
                    if let Some(json) = serialize_notification(&notification) {
                        tracing::debug!(output = %json, "Sending notification");
                        self.write_line(&json, writer.clone()).await?;
                    }
                }

                Some(control) = self.control_rx.recv() => {
                    match control {
                        #[cfg(feature = "stateless")]
                        StdioControl::CloseSubscription(request_id) => {
                            if let Some(json) = subscriptions.close(&request_id)? {
                                self.write_line(&json, writer.clone()).await?;
                            }
                        }
                        StdioControl::Shutdown => {
                            #[cfg(feature = "stateless")]
                            for json in subscriptions.close_all()? {
                                self.write_line(&json, writer.clone()).await?;
                            }
                            break;
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Handle an incoming message from stdin
    async fn handle_incoming_message<W>(
        &mut self,
        line: &str,
        writer: Arc<Mutex<W>>,
        #[cfg(feature = "stateless")] subscriptions: &mut StdioSubscriptions,
    ) -> Result<()>
    where
        W: tokio::io::AsyncWrite + Unpin + Send + 'static,
    {
        tracing::debug!(input = %line, "Received message");

        // Malformed JSON must produce a JSON-RPC parse error response, not
        // tear down the run loop. Per the spec, id is null when the request
        // can't be parsed at all.
        let parsed: serde_json::Value = match serde_json::from_str(line) {
            Ok(v) => v,
            Err(e) => {
                tracing::warn!(error = %e, "Malformed JSON on stdin");
                return self.write_parse_error(&e.to_string(), writer).await;
            }
        };

        if let Err(error) = self
            .service
            .inspect_incoming_value(&parsed, crate::inspection::McpDirection::ClientToServer)
        {
            let response = JsonRpcResponse::error(None, error);
            return self
                .write_line(&serde_json::to_string(&response)?, writer)
                .await;
        }

        // Check if this is a response to one of our pending requests
        if parsed.get("method").is_none()
            && (parsed.get("result").is_some() || parsed.get("error").is_some())
        {
            return self.handle_response(&parsed).await;
        }

        #[cfg(feature = "stateless")]
        if let StdioSubscriptionInput::Handled(frames) =
            subscriptions.handle_input(&self.service, &parsed)?
        {
            for frame in frames {
                self.write_line(&frame, writer.clone()).await?;
            }
            return Ok(());
        }

        // Check if it's a notification (no id field)
        if !parsed.is_array() && parsed.get("id").is_none() {
            if let Ok(notification) = serde_json::from_str::<JsonRpcNotification>(line) {
                handle_notification(&self.router, notification)?;
            }
            return Ok(());
        }

        // Process as a request. The shape parse can also fail (e.g. id of
        // wrong type); treat it the same way so the loop keeps running.
        let message: JsonRpcMessage = match serde_json::from_str(line) {
            Ok(m) => m,
            Err(e) => {
                tracing::warn!(error = %e, "JSON did not match JSON-RPC request shape");
                return self.write_parse_error(&e.to_string(), writer).await;
            }
        };
        // Dispatch the request on a spawned task so the run loop stays free to
        // service outgoing server-to-client requests (elicitation/create,
        // sampling/createMessage) and the client's responses to them while the
        // handler is in flight. Handling the request inline here would deadlock
        // any handler that calls `ctx.elicit_form()` / `ctx.sample()`: the
        // handler awaits the client's response, but that response can only be
        // read by this same loop (#923).
        let mut service = self.service.clone();
        tokio::spawn(async move {
            let response_json = match service.call_message(message).await {
                Ok(response) => serde_json::to_string(&response),
                Err(e) => {
                    tracing::error!(error = %e, "Error processing message");
                    serde_json::to_string(&parse_error_response(e.to_string()))
                }
            };
            match response_json {
                Ok(json) => {
                    tracing::debug!(output = %json, "Sending response");
                    if let Err(e) = write_line_locked(&writer, &json).await {
                        tracing::error!(error = %e, "Failed to write response to stdout");
                    }
                }
                Err(e) => tracing::error!(error = %e, "Failed to serialize response"),
            }
        });

        Ok(())
    }

    async fn write_parse_error<W>(&self, message: &str, writer: Arc<Mutex<W>>) -> Result<()>
    where
        W: tokio::io::AsyncWrite + Unpin + Send,
    {
        let error_response = parse_error_response(message);
        let response_json = serde_json::to_string(&error_response)
            .map_err(|e| Error::Transport(format!("Failed to serialize error: {}", e)))?;
        self.write_line(&response_json, writer).await
    }

    /// Handle a response to one of our pending requests
    async fn handle_response(&self, parsed: &serde_json::Value) -> Result<()> {
        let id = match parsed.get("id") {
            Some(id) => {
                if let Some(n) = id.as_i64() {
                    RequestId::Number(n)
                } else if let Some(s) = id.as_str() {
                    RequestId::String(s.to_string())
                } else {
                    tracing::warn!("Response has invalid id type");
                    return Ok(());
                }
            }
            None => {
                tracing::warn!("Response missing id field");
                return Ok(());
            }
        };

        let pending = {
            let mut pending_requests = self.pending_requests.lock().await;
            pending_requests.remove(&id)
        };

        match pending {
            Some(pending) => {
                let result = if let Some(error) = parsed.get("error") {
                    let code = error.get("code").and_then(|c| c.as_i64()).unwrap_or(-1);
                    let message = error
                        .get("message")
                        .and_then(|m| m.as_str())
                        .unwrap_or("Unknown error");
                    Err(Error::Internal(format!(
                        "Client error ({}): {}",
                        code, message
                    )))
                } else if let Some(result) = parsed.get("result") {
                    Ok(result.clone())
                } else {
                    Err(Error::Internal(
                        "Response has neither result nor error".to_string(),
                    ))
                };

                // Send result to waiter (ignore if they've dropped the receiver)
                let _ = pending.response_tx.send(result);
            }
            None => {
                tracing::warn!(id = ?id, "Received response for unknown request");
            }
        }

        Ok(())
    }

    /// Send an outgoing request to the client
    async fn send_outgoing_request<W>(
        &mut self,
        outgoing: OutgoingRequest,
        writer: Arc<Mutex<W>>,
    ) -> Result<()>
    where
        W: tokio::io::AsyncWrite + Unpin + Send,
    {
        // Build JSON-RPC request
        let request = JsonRpcRequest {
            jsonrpc: "2.0".to_string(),
            id: outgoing.id.clone(),
            method: outgoing.method,
            params: Some(outgoing.params),
        };

        let request_json = serde_json::to_string(&request)
            .map_err(|e| Error::Transport(format!("Failed to serialize request: {}", e)))?;

        tracing::debug!(output = %request_json, "Sending request to client");

        // Store pending request
        {
            let mut pending_requests = self.pending_requests.lock().await;
            pending_requests.insert(
                outgoing.id,
                PendingRequest {
                    response_tx: outgoing.response_tx,
                },
            );
        }

        // Send the request
        self.write_line(&request_json, writer).await?;

        Ok(())
    }

    /// Write a line to the shared writer
    async fn write_line<W>(&self, line: &str, writer: Arc<Mutex<W>>) -> Result<()>
    where
        W: tokio::io::AsyncWrite + Unpin + Send,
    {
        write_line_locked(&writer, line).await
    }
}

/// Write a single newline-terminated line to a shared writer and flush it.
///
/// Free-standing counterpart to [`BidirectionalStdioTransport::write_line`] so
/// spawned request-dispatch tasks can write their responses without borrowing
/// the transport.
async fn write_line_locked<W>(writer: &Arc<Mutex<W>>, line: &str) -> Result<()>
where
    W: tokio::io::AsyncWrite + Unpin + Send,
{
    let mut writer = writer.lock().await;
    writer
        .write_all(line.as_bytes())
        .await
        .map_err(|e| Error::Transport(format!("Failed to write to stdout: {}", e)))?;
    writer
        .write_all(b"\n")
        .await
        .map_err(|e| Error::Transport(format!("Failed to write newline: {}", e)))?;
    writer
        .flush()
        .await
        .map_err(|e| Error::Transport(format!("Failed to flush stdout: {}", e)))?;
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::context::ServerNotification;
    use crate::protocol::{
        LogLevel, LoggingMessageParams, ProgressParams, ProgressToken, TaskStatus, TaskStatusParams,
    };
    use tower_mcp_types::testing::assert_jsonrpc_error_response;

    // =========================================================================
    // parse_error_response tests -- wire-format invariants on the stdio
    // parse-error path (regression coverage for #802 / #803).
    // =========================================================================

    #[test]
    fn parse_error_response_has_null_id_and_code_neg_32700() {
        let resp = parse_error_response("expected value at line 1");
        let json = serde_json::to_value(&resp).unwrap();
        assert_jsonrpc_error_response(&json);
        assert!(
            json["id"].is_null(),
            "id must be null on parse error, got: {json}"
        );
        assert_eq!(json["error"]["code"].as_i64().unwrap(), -32700);
        assert!(
            json["error"]["message"]
                .as_str()
                .unwrap()
                .contains("expected value"),
            "error.message should carry the parser detail, got: {json}"
        );
    }

    #[test]
    fn parse_error_response_serializes_to_single_line_json() {
        // The stdio loop writes responses line-delimited; the body itself
        // must not contain embedded newlines or it would split the frame.
        let resp = parse_error_response("oops\nstill oops");
        let s = serde_json::to_string(&resp).unwrap();
        assert!(
            !s.contains('\n'),
            "serialized parse-error response must be single-line, got: {s:?}"
        );
    }

    // =========================================================================
    // serialize_notification tests
    // =========================================================================

    #[test]
    fn test_serialize_progress_notification() {
        let notification = ServerNotification::Progress(ProgressParams {
            progress_token: ProgressToken::String("tok-1".to_string()),
            progress: 50.0,
            total: Some(100.0),
            message: Some("Halfway there".to_string()),
            meta: None,
        });
        let json = serialize_notification(&notification).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["jsonrpc"], "2.0");
        assert_eq!(parsed["method"], "notifications/progress");
        assert_eq!(parsed["params"]["progressToken"], "tok-1");
        assert_eq!(parsed["params"]["progress"], 50.0);
        assert_eq!(parsed["params"]["total"], 100.0);
        assert!(parsed.get("id").is_none());
    }

    #[test]
    fn test_serialize_log_message_notification() {
        let notification = ServerNotification::LogMessage(LoggingMessageParams {
            level: LogLevel::Warning,
            logger: Some("test-logger".to_string()),
            data: serde_json::json!("something happened"),
            meta: None,
        });
        let json = serialize_notification(&notification).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["method"], "notifications/message");
        assert_eq!(parsed["params"]["level"], "warning");
        assert_eq!(parsed["params"]["logger"], "test-logger");
    }

    #[test]
    fn test_serialize_resource_updated_notification() {
        let notification = ServerNotification::ResourceUpdated {
            uri: "file:///data.json".to_string(),
        };
        let json = serialize_notification(&notification).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["method"], "notifications/resources/updated");
        assert_eq!(parsed["params"]["uri"], "file:///data.json");
    }

    #[test]
    fn test_serialize_resources_list_changed_notification() {
        let notification = ServerNotification::ResourcesListChanged;
        let json = serialize_notification(&notification).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["method"], "notifications/resources/list_changed");
        assert!(parsed.get("params").is_none());
    }

    #[test]
    fn test_serialize_tools_list_changed_notification() {
        let notification = ServerNotification::ToolsListChanged;
        let json = serialize_notification(&notification).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["method"], "notifications/tools/list_changed");
    }

    #[test]
    fn test_serialize_prompts_list_changed_notification() {
        let notification = ServerNotification::PromptsListChanged;
        let json = serialize_notification(&notification).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["method"], "notifications/prompts/list_changed");
    }

    #[test]
    fn test_serialize_task_status_changed_notification() {
        let notification = ServerNotification::TaskStatusChanged(TaskStatusParams {
            task_id: "task-42".to_string(),
            status: TaskStatus::Working,
            status_message: Some("Processing...".to_string()),
            created_at: "2025-01-01T00:00:00Z".to_string(),
            last_updated_at: "2025-01-01T00:01:00Z".to_string(),
            ttl: None,
            poll_interval: None,
            meta: None,
        });
        let json = serialize_notification(&notification).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();

        assert_eq!(parsed["method"], "notifications/tasks");
        assert_eq!(parsed["params"]["taskId"], "task-42");
        assert_eq!(parsed["params"]["status"], "working");
    }

    // =========================================================================
    // process_line tests
    // =========================================================================

    fn make_router() -> McpRouter {
        McpRouter::new().server_info("test-server", "1.0.0")
    }

    async fn init_service(router: &McpRouter) -> JsonRpcService<McpRouter> {
        init_service_for_revision(router, "2025-11-25").await
    }

    async fn init_service_for_revision(
        router: &McpRouter,
        revision: &str,
    ) -> JsonRpcService<McpRouter> {
        let mut service = JsonRpcService::new(router.clone());

        // Initialize the session
        let init_msg = serde_json::json!({
            "jsonrpc": "2.0",
            "id": 0,
            "method": "initialize",
            "params": {
                "protocolVersion": revision,
                "capabilities": {},
                "clientInfo": { "name": "test-client", "version": "1.0.0" }
            }
        });
        let msg: JsonRpcMessage = serde_json::from_value(init_msg).unwrap();
        let _ = service.call_message(msg).await.unwrap();

        // Send initialized notification
        let notif_line = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
        let notif = serde_json::from_str::<JsonRpcNotification>(notif_line).unwrap();
        handle_notification(router, notif).unwrap();

        service
    }

    #[tokio::test]
    async fn test_process_line_valid_request() {
        let router = make_router();
        let mut service = init_service(&router).await;

        let line = r#"{"jsonrpc":"2.0","id":1,"method":"ping"}"#;
        let result = process_line(&mut service, &router, line).await;

        let response = result.unwrap().unwrap();
        let json = serde_json::to_value(&response).unwrap();
        assert_eq!(json["jsonrpc"], "2.0");
        assert_eq!(json["id"], 1);
        assert!(json.get("result").is_some());
    }

    #[tokio::test]
    async fn test_process_line_notification_returns_none() {
        let router = make_router();
        let mut service = init_service(&router).await;

        let line = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
        let result = process_line(&mut service, &router, line).await;

        assert!(result.unwrap().is_none());
    }

    #[tokio::test]
    async fn stdio_accepts_batch_for_2025_03() {
        let router = make_router();
        let mut service = init_service_for_revision(&router, "2025-03-26").await;
        let line = serde_json::json!([
            {"jsonrpc": "2.0", "id": 1, "method": "ping"},
            {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
        ])
        .to_string();

        let response = process_line(&mut service, &router, &line)
            .await
            .unwrap()
            .unwrap();
        let JsonRpcResponseMessage::Batch(responses) = response else {
            panic!("2025-03-26 stdio batch should return a batch");
        };
        assert_eq!(responses.len(), 2);
    }

    #[tokio::test]
    async fn stdio_rejects_batch_for_2025_11() {
        let router = make_router();
        let mut service = init_service(&router).await;
        let line = serde_json::json!([
            {"jsonrpc": "2.0", "id": 1, "method": "ping"},
            {"jsonrpc": "2.0", "id": 2, "method": "tools/list"}
        ])
        .to_string();

        let response = process_line(&mut service, &router, &line)
            .await
            .unwrap()
            .unwrap();
        let JsonRpcResponseMessage::Single(JsonRpcResponse::Error(error)) = response else {
            panic!("2025-11-25 stdio batch should return one error");
        };
        assert_eq!(error.error.code, -32600);
    }

    #[tokio::test]
    async fn test_process_line_malformed_json() {
        let router = make_router();
        let mut service = init_service(&router).await;

        let line = r#"not valid json at all"#;
        let result = process_line(&mut service, &router, line).await;

        assert!(result.is_err());
    }

    // =========================================================================
    // clean_input_line tests
    // =========================================================================

    #[test]
    fn test_clean_input_line_no_bom() {
        assert_eq!(
            clean_input_line(r#"{"jsonrpc":"2.0"}"#),
            r#"{"jsonrpc":"2.0"}"#
        );
    }

    #[test]
    fn test_clean_input_line_strips_leading_bom() {
        let with_bom = "\u{feff}{\"jsonrpc\":\"2.0\"}";
        assert_eq!(clean_input_line(with_bom), r#"{"jsonrpc":"2.0"}"#);
    }

    #[test]
    fn test_clean_input_line_strips_bom_then_trims() {
        // BOM, then whitespace, then content, then trailing newline.
        let input = "\u{feff}   {\"id\":1}\n";
        assert_eq!(clean_input_line(input), r#"{"id":1}"#);
    }

    #[test]
    fn test_clean_input_line_does_not_strip_internal_bom() {
        // Only a *leading* BOM is stripped; one inside the payload stays.
        let input = "{\"text\":\"hi\u{feff}there\"}";
        assert_eq!(clean_input_line(input), input);
    }

    #[test]
    fn test_clean_input_line_empty() {
        assert_eq!(clean_input_line(""), "");
        assert_eq!(clean_input_line("\u{feff}"), "");
        assert_eq!(clean_input_line("   \n\t"), "");
    }

    #[tokio::test]
    async fn test_process_line_with_bom_stripped_input_parses() {
        // After clean_input_line, a BOM-prefixed request should parse like
        // any other request and return a normal response.
        let router = make_router();
        let mut service = init_service(&router).await;

        let raw = "\u{feff}{\"jsonrpc\":\"2.0\",\"id\":7,\"method\":\"tools/list\",\"params\":{}}";
        let cleaned = clean_input_line(raw);
        let result = process_line(&mut service, &router, cleaned).await;

        let response = result.unwrap().unwrap();
        let json = serde_json::to_value(&response).unwrap();
        assert_eq!(json["id"], 7);
        assert!(json["result"]["tools"].is_array());
    }

    #[tokio::test]
    async fn test_process_line_tools_list() {
        let router = make_router();
        let mut service = init_service(&router).await;

        let line = r#"{"jsonrpc":"2.0","id":2,"method":"tools/list","params":{}}"#;
        let result = process_line(&mut service, &router, line).await;

        let response = result.unwrap().unwrap();
        let json = serde_json::to_value(&response).unwrap();
        assert_eq!(json["id"], 2);
        assert!(json["result"]["tools"].is_array());
    }

    #[tokio::test]
    async fn test_process_line_unknown_method() {
        let router = make_router();
        let mut service = init_service(&router).await;

        let line = r#"{"jsonrpc":"2.0","id":3,"method":"nonexistent/method"}"#;
        let result = process_line(&mut service, &router, line).await;

        let response = result.unwrap().unwrap();
        let json = serde_json::to_value(&response).unwrap();
        assert!(json.get("error").is_some());
        assert_eq!(json["error"]["code"], -32601); // Method not found
    }

    // =========================================================================
    // handle_notification tests
    // =========================================================================

    #[test]
    fn test_handle_notification_initialized() {
        let router = make_router();
        let notif_json = r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
        let notif: JsonRpcNotification = serde_json::from_str(notif_json).unwrap();

        let result = handle_notification(&router, notif);
        assert!(result.is_ok());
    }

    #[test]
    fn test_handle_notification_cancelled() {
        let router = make_router();
        let notif_json = r#"{"jsonrpc":"2.0","method":"notifications/cancelled","params":{"requestId":1,"reason":"timeout"}}"#;
        let notif: JsonRpcNotification = serde_json::from_str(notif_json).unwrap();

        let result = handle_notification(&router, notif);
        assert!(result.is_ok());
    }
}