tower-mcp 0.24.0

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
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
//! Integration tests for HttpClientTransport.
//!
//! These tests spin up an in-process HTTP server and connect to it
//! using HttpClientTransport + McpClient.

#![cfg(all(feature = "http", feature = "http-client"))]

use async_trait::async_trait;
use schemars::JsonSchema;
use serde::Deserialize;
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tower_mcp::{
    CallToolResult, ClientHandler, CompleteParams, CompleteResult, CompletionReference, Content,
    ContentRole, CreateMessageParams, CreateMessageResult, ElicitFieldValue, ElicitRequestParams,
    ElicitResult, GetPromptResult, HttpTransport, LogLevel, LoggingMessageParams, McpClientBuilder,
    McpRouter, NoParams, NotificationHandler, PromptBuilder, PromptMessage, PromptRole,
    ReadResourceResult, ResourceBuilder, ResourceContent, ResourceTemplateBuilder, Root,
    SamplingContent, SamplingContentOrArray, SamplingMessage, SubscriptionFilter, ToolBuilder,
    client::{HttpClientConfig, HttpClientTransport, HttpStatusDetails, McpClient},
    extract::{Context, RawArgs},
    transport::http::SessionConfig,
};
use tower_mcp_types::JsonRpcError;

#[derive(Debug, Deserialize, JsonSchema)]
struct EchoInput {
    message: String,
}

#[derive(Debug, Deserialize, JsonSchema)]
struct AddInput {
    a: i64,
    b: i64,
}

/// Create a test router with basic tools and resources.
fn test_router() -> McpRouter {
    let echo = ToolBuilder::new("echo")
        .description("Echo a message")
        .handler(|input: EchoInput| async move { Ok(CallToolResult::text(input.message)) })
        .build();

    let add = ToolBuilder::new("add")
        .description("Add two numbers")
        .handler(|input: AddInput| async move {
            Ok(CallToolResult::text(format!("{}", input.a + input.b)))
        })
        .build();

    let config = ResourceBuilder::new("config://app")
        .name("App Config")
        .description("Application configuration")
        .text(r#"{"debug": true}"#);

    McpRouter::new()
        .server_info("test-http-server", "1.0.0")
        .tool(echo)
        .tool(add)
        .resource(config)
}

/// Start an HTTP server on a random available port and return the URL.
async fn start_server() -> (String, tokio::task::JoinHandle<()>) {
    let router = test_router();
    let transport = HttpTransport::new(router).disable_origin_validation();
    let axum_router = transport.into_router();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, axum_router).await.unwrap();
    });

    // Give the server a moment to start
    tokio::time::sleep(Duration::from_millis(50)).await;

    (url, handle)
}

#[tokio::test]
async fn test_http_client_initialize() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();

    let info = client.initialize("test-client", "1.0.0").await.unwrap();
    assert_eq!(info.server_info.name, "test-http-server");
    assert_eq!(info.server_info.version, "1.0.0");
    assert!(client.is_initialized());

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_list_tools() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let tools = client.list_tools().await.unwrap();
    assert_eq!(tools.tools.len(), 2);

    let tool_names: Vec<&str> = tools.tools.iter().map(|t| t.name.as_str()).collect();
    assert!(tool_names.contains(&"echo"));
    assert!(tool_names.contains(&"add"));

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_call_tool() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Call echo
    let result = client
        .call_tool(
            "echo",
            serde_json::json!({"message": "Hello from HTTP client!"}),
        )
        .await
        .unwrap();
    assert!(!result.content.is_empty());

    // Call add
    let result = client
        .call_tool("add", serde_json::json!({"a": 42, "b": 58}))
        .await
        .unwrap();
    assert!(!result.content.is_empty());

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_list_resources() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let resources = client.list_resources().await.unwrap();
    assert_eq!(resources.resources.len(), 1);
    assert_eq!(resources.resources[0].uri, "config://app");

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_read_resource() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let result = client.read_resource("config://app").await.unwrap();
    assert_eq!(result.contents.len(), 1);
    assert!(
        result.contents[0]
            .text
            .as_deref()
            .unwrap()
            .contains("debug")
    );

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_ping() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    client.ping().await.unwrap();

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_shutdown_sends_delete() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Shutdown should send DELETE and close cleanly
    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_with_custom_config() {
    let (url, _server) = start_server().await;

    let config = tower_mcp::client::HttpClientConfig {
        request_timeout: Duration::from_secs(10),
        sse_reconnect: false,
        ..Default::default()
    };
    let transport = HttpClientTransport::with_config(&url, config);
    let client = McpClient::connect(transport).await.unwrap();

    let info = client.initialize("test-client", "1.0.0").await.unwrap();
    assert_eq!(info.server_info.name, "test-http-server");

    client.shutdown().await.unwrap();
}

/// Start an HTTP server with bearer token auth middleware on a random port.
async fn start_auth_server(valid_token: &str) -> (String, tokio::task::JoinHandle<()>) {
    use axum::{extract::Request, http::StatusCode, middleware, response::Response};

    let router = test_router();
    let transport = HttpTransport::new(router).disable_origin_validation();
    let mcp_router = transport.into_router();

    let token = valid_token.to_string();
    let app = mcp_router.layer(middleware::from_fn(
        move |request: Request, next: middleware::Next| {
            let token = token.clone();
            async move {
                let auth = request
                    .headers()
                    .get("Authorization")
                    .and_then(|v| v.to_str().ok())
                    .map(|s| s.to_string());
                let expected = format!("Bearer {}", token);
                if auth.as_deref() == Some(&expected) {
                    Ok::<Response, (StatusCode, String)>(next.run(request).await)
                } else {
                    Err((StatusCode::UNAUTHORIZED, "Unauthorized".to_string()))
                }
            }
        },
    ));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    (url, handle)
}

#[tokio::test]
async fn test_http_client_bearer_auth() {
    let (url, _server) = start_auth_server("sk-valid-key").await;

    let transport = HttpClientTransport::new(&url).bearer_token("sk-valid-key");
    let client = McpClient::connect(transport).await.unwrap();

    let info = client.initialize("test-client", "1.0.0").await.unwrap();
    assert_eq!(info.server_info.name, "test-http-server");

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_bearer_auth_rejected() {
    let (url, _server) = start_auth_server("sk-valid-key").await;

    let transport = HttpClientTransport::new(&url).bearer_token("sk-wrong-key");
    let client = McpClient::connect(transport).await.unwrap();

    let result = client.initialize("test-client", "1.0.0").await;
    assert!(result.is_err());
}

// ---------------------------------------------------------------------------
// Extended test router with prompts, resource templates, and completions
// ---------------------------------------------------------------------------

/// Create a test router with prompts, resource templates, and completions.
fn extended_test_router() -> McpRouter {
    let echo = ToolBuilder::new("echo")
        .description("Echo a message")
        .handler(|input: EchoInput| async move { Ok(CallToolResult::text(input.message)) })
        .build();

    let add = ToolBuilder::new("add")
        .description("Add two numbers")
        .handler(|input: AddInput| async move {
            Ok(CallToolResult::text(format!("{}", input.a + input.b)))
        })
        .build();

    let config = ResourceBuilder::new("config://app")
        .name("App Config")
        .description("Application configuration")
        .text(r#"{"debug": true}"#);

    let greeting = PromptBuilder::new("greeting")
        .description("Generate a greeting")
        .required_arg("name", "Name to greet")
        .handler(|args: HashMap<String, String>| async move {
            let name = args.get("name").cloned().unwrap_or_default();
            Ok(GetPromptResult {
                description: Some("A greeting prompt".to_string()),
                messages: vec![PromptMessage {
                    role: PromptRole::User,
                    content: Content::text(format!("Hello, {}!", name)),
                    meta: None,
                }],
                meta: None,
            })
        })
        .build();

    let farewell = PromptBuilder::new("farewell")
        .description("Generate a farewell")
        .optional_arg("name", "Name to bid farewell")
        .handler(|args: HashMap<String, String>| async move {
            let name = args
                .get("name")
                .cloned()
                .unwrap_or_else(|| "friend".to_string());
            Ok(GetPromptResult {
                description: Some("A farewell prompt".to_string()),
                messages: vec![PromptMessage {
                    role: PromptRole::User,
                    content: Content::text(format!("Goodbye, {}!", name)),
                    meta: None,
                }],
                meta: None,
            })
        })
        .build();

    let file_template = ResourceTemplateBuilder::new("file:///{+path}")
        .name("Project Files")
        .description("Read project files by path")
        .mime_type("text/plain")
        .handler(|uri: String, vars: HashMap<String, String>| async move {
            let path = vars.get("path").cloned().unwrap_or_default();
            Ok(ReadResourceResult {
                contents: vec![ResourceContent {
                    uri,
                    mime_type: Some("text/plain".to_string()),
                    text: Some(format!("Contents of {}", path)),
                    blob: None,
                    meta: None,
                }],
                meta: None,
                ..Default::default()
            })
        });

    McpRouter::new()
        .server_info("test-extended-server", "1.0.0")
        .tool(echo)
        .tool(add)
        .resource(config)
        .prompt(greeting)
        .prompt(farewell)
        .resource_template(file_template)
        .completion_handler(|params: CompleteParams| async move {
            match &params.reference {
                CompletionReference::Prompt { name } if name == "greeting" => {
                    let prefix = &params.argument.value;
                    let names = vec!["Alice", "Bob", "Charlie"];
                    let matches: Vec<String> = names
                        .into_iter()
                        .filter(|n| n.to_lowercase().starts_with(&prefix.to_lowercase()))
                        .map(String::from)
                        .collect();
                    Ok(CompleteResult::new(matches))
                }
                CompletionReference::Resource { uri } if uri.contains("file") => {
                    let prefix = &params.argument.value;
                    let paths = vec!["src/main.rs", "src/lib.rs", "Cargo.toml"];
                    let matches: Vec<String> = paths
                        .into_iter()
                        .filter(|p| p.starts_with(prefix.as_str()))
                        .map(String::from)
                        .collect();
                    Ok(CompleteResult::new(matches))
                }
                _ => Ok(CompleteResult::new(vec![])),
            }
        })
}

/// Start an extended HTTP server with prompts, templates, and completions.
async fn start_extended_server() -> (String, tokio::task::JoinHandle<()>) {
    let router = extended_test_router();
    let transport = HttpTransport::new(router).disable_origin_validation();
    let axum_router = transport.into_router();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, axum_router).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    (url, handle)
}

// ---------------------------------------------------------------------------
// Prompts E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_list_prompts() {
    let (url, _server) = start_extended_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let prompts = client.list_prompts().await.unwrap();
    assert_eq!(prompts.prompts.len(), 2);

    let names: Vec<&str> = prompts.prompts.iter().map(|p| p.name.as_str()).collect();
    assert!(names.contains(&"greeting"));
    assert!(names.contains(&"farewell"));

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_get_prompt_with_args() {
    let (url, _server) = start_extended_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let mut args = HashMap::new();
    args.insert("name".to_string(), "World".to_string());
    let result = client.get_prompt("greeting", Some(args)).await.unwrap();

    assert_eq!(result.description.as_deref(), Some("A greeting prompt"));
    assert_eq!(result.messages.len(), 1);
    assert!(matches!(result.messages[0].role, PromptRole::User));

    // Verify the message content contains our argument
    let text = match &result.messages[0].content {
        Content::Text { text, .. } => text.as_str(),
        _ => panic!("Expected text content"),
    };
    assert_eq!(text, "Hello, World!");

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_get_prompt_optional_arg() {
    let (url, _server) = start_extended_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Call farewell without the optional name arg
    let result = client.get_prompt("farewell", None).await.unwrap();
    assert_eq!(result.messages.len(), 1);

    let text = match &result.messages[0].content {
        Content::Text { text, .. } => text.as_str(),
        _ => panic!("Expected text content"),
    };
    assert_eq!(text, "Goodbye, friend!");

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Resource Templates E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_list_resource_templates() {
    let (url, _server) = start_extended_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let templates = client.list_resource_templates().await.unwrap();
    assert_eq!(templates.resource_templates.len(), 1);
    assert_eq!(
        templates.resource_templates[0].uri_template,
        "file:///{+path}"
    );
    assert_eq!(templates.resource_templates[0].name, "Project Files");

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_read_resource_template() {
    let (url, _server) = start_extended_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let result = client.read_resource("file:///src/main.rs").await.unwrap();
    assert_eq!(result.contents.len(), 1);
    assert_eq!(
        result.contents[0].text.as_deref().unwrap(),
        "Contents of src/main.rs"
    );
    assert_eq!(result.contents[0].mime_type.as_deref(), Some("text/plain"));

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// call_tool_text() E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_call_tool_text() {
    let (url, _server) = start_extended_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let text = client
        .call_tool_text("echo", serde_json::json!({"message": "hello"}))
        .await
        .unwrap();
    assert_eq!(text, "hello");

    let text = client
        .call_tool_text("add", serde_json::json!({"a": 10, "b": 20}))
        .await
        .unwrap();
    assert_eq!(text, "30");

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Completion API E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_complete_prompt_arg() {
    let (url, _server) = start_extended_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Complete with "A" prefix -- should match "Alice"
    let result = client
        .complete_prompt_arg("greeting", "name", "A")
        .await
        .unwrap();
    assert_eq!(result.completion.values, vec!["Alice"]);

    // Complete with "b" prefix -- should match "Bob" (case-insensitive)
    let result = client
        .complete_prompt_arg("greeting", "name", "b")
        .await
        .unwrap();
    assert_eq!(result.completion.values, vec!["Bob"]);

    // Complete with "z" prefix -- no matches
    let result = client
        .complete_prompt_arg("greeting", "name", "z")
        .await
        .unwrap();
    assert!(result.completion.values.is_empty());

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_complete_resource_uri() {
    let (url, _server) = start_extended_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Complete with "src/" prefix
    let result = client
        .complete_resource_uri("file:///{+path}", "path", "src/")
        .await
        .unwrap();
    assert_eq!(result.completion.values.len(), 2);
    assert!(
        result
            .completion
            .values
            .contains(&"src/main.rs".to_string())
    );
    assert!(result.completion.values.contains(&"src/lib.rs".to_string()));

    // Complete with "C" prefix
    let result = client
        .complete_resource_uri("file:///{+path}", "path", "C")
        .await
        .unwrap();
    assert_eq!(result.completion.values, vec!["Cargo.toml"]);

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Pagination E2E
// ---------------------------------------------------------------------------

/// Create a test router with many items and small page size for pagination testing.
fn pagination_test_router() -> McpRouter {
    let mut router = McpRouter::new()
        .server_info("test-pagination-server", "1.0.0")
        .page_size(2);

    for i in 0..5 {
        let tool = ToolBuilder::new(format!("tool_{i}"))
            .description(format!("Tool {i}"))
            .handler(|_: NoParams| async move { Ok(CallToolResult::text("ok")) })
            .build();
        router = router.tool(tool);
    }

    for i in 0..3 {
        let resource = ResourceBuilder::new(format!("res://item_{i}"))
            .name(format!("Resource {i}"))
            .text(format!("content_{i}"));
        router = router.resource(resource);
    }

    for i in 0..3 {
        let prompt = PromptBuilder::new(format!("prompt_{i}"))
            .description(format!("Prompt {i}"))
            .handler(|_: HashMap<String, String>| async move {
                Ok(GetPromptResult {
                    description: None,
                    messages: vec![],
                    meta: None,
                })
            })
            .build();
        router = router.prompt(prompt);
    }

    router
}

async fn start_pagination_server() -> (String, tokio::task::JoinHandle<()>) {
    let router = pagination_test_router();
    let transport = HttpTransport::new(router).disable_origin_validation();
    let axum_router = transport.into_router();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, axum_router).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    (url, handle)
}

#[tokio::test]
async fn test_http_client_pagination_list_all_tools() {
    let (url, _server) = start_pagination_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let tools = client.list_all_tools().await.unwrap();
    assert_eq!(tools.len(), 5);

    let names: Vec<&str> = tools.iter().map(|t| t.name.as_str()).collect();
    for i in 0..5 {
        assert!(names.contains(&format!("tool_{i}").as_str()));
    }

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_pagination_manual_cursor() {
    let (url, _server) = start_pagination_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Page 1: 2 tools + cursor
    let page1 = client.list_tools_with_cursor(None).await.unwrap();
    assert_eq!(page1.tools.len(), 2);
    assert!(page1.next_cursor.is_some());

    // Page 2: 2 tools + cursor
    let page2 = client
        .list_tools_with_cursor(page1.next_cursor)
        .await
        .unwrap();
    assert_eq!(page2.tools.len(), 2);
    assert!(page2.next_cursor.is_some());

    // Page 3: 1 tool + no cursor
    let page3 = client
        .list_tools_with_cursor(page2.next_cursor)
        .await
        .unwrap();
    assert_eq!(page3.tools.len(), 1);
    assert!(page3.next_cursor.is_none());

    // Verify all 5 unique tools were returned
    let mut all_names: Vec<String> = Vec::new();
    all_names.extend(page1.tools.iter().map(|t| t.name.clone()));
    all_names.extend(page2.tools.iter().map(|t| t.name.clone()));
    all_names.extend(page3.tools.iter().map(|t| t.name.clone()));
    all_names.sort();
    assert_eq!(all_names.len(), 5);

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_pagination_list_all_prompts() {
    let (url, _server) = start_pagination_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let prompts = client.list_all_prompts().await.unwrap();
    assert_eq!(prompts.len(), 3);

    let names: Vec<&str> = prompts.iter().map(|p| p.name.as_str()).collect();
    for i in 0..3 {
        assert!(names.contains(&format!("prompt_{i}").as_str()));
    }

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Bidirectional communication infrastructure
// ---------------------------------------------------------------------------

/// Create a test router with tools that exercise sampling, elicitation, and logging.
fn bidirectional_test_router() -> McpRouter {
    let sampling_tool = ToolBuilder::new("test_sampling")
        .description("Calls ctx.sample() and returns the LLM response")
        .extractor_handler((), |ctx: Context, _: RawArgs| async move {
            let params =
                CreateMessageParams::new(vec![SamplingMessage::user("Test sampling request")], 100);
            match ctx.sample(params).await {
                Ok(result) => {
                    let text = result.first_text().unwrap_or("no text").to_string();
                    Ok(CallToolResult::text(text))
                }
                Err(e) => Ok(CallToolResult::error(format!("sampling failed: {e}"))),
            }
        })
        .build();

    let confirm_tool = ToolBuilder::new("test_confirm")
        .description("Calls ctx.confirm() and returns the result")
        .extractor_handler((), |ctx: Context, _: RawArgs| async move {
            match ctx.confirm("proceed?").await {
                Ok(true) => Ok(CallToolResult::text("confirmed")),
                Ok(false) => Ok(CallToolResult::text("declined")),
                Err(e) => Ok(CallToolResult::error(format!("elicitation failed: {e}"))),
            }
        })
        .build();

    let log_tool = ToolBuilder::new("test_log")
        .description("Sends a log notification and returns")
        .extractor_handler((), |ctx: Context, _: RawArgs| async move {
            ctx.send_log(LoggingMessageParams::new(
                LogLevel::Info,
                serde_json::json!("test log message"),
            ));
            Ok(CallToolResult::text("logged"))
        })
        .build();

    let roots_tool = ToolBuilder::new("test_roots")
        .description("Requests the client's roots")
        .extractor_handler((), |ctx: Context, _: RawArgs| async move {
            match ctx.request_raw("roots/list", serde_json::json!({})).await {
                Ok(result) => {
                    let uri = result
                        .pointer("/roots/0/uri")
                        .and_then(serde_json::Value::as_str)
                        .unwrap_or("no root");
                    Ok(CallToolResult::text(uri))
                }
                Err(error) => Ok(CallToolResult::error(format!(
                    "roots request failed: {error}"
                ))),
            }
        })
        .build();

    McpRouter::new()
        .server_info("test-bidirectional-server", "1.0.0")
        .tool(sampling_tool)
        .tool(confirm_tool)
        .tool(log_tool)
        .tool(roots_tool)
}

/// Start a bidirectional HTTP server with sampling enabled.
async fn start_bidirectional_server() -> (String, tokio::task::JoinHandle<()>) {
    let router = bidirectional_test_router();
    let transport = HttpTransport::new(router)
        .with_sampling()
        .disable_origin_validation();
    let axum_router = transport.into_router();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, axum_router).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    (url, handle)
}

// ---------------------------------------------------------------------------
// Notification Handler via SSE E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_notification_log_message() {
    let (url, _server) = start_bidirectional_server().await;

    let captured: Arc<Mutex<Vec<LoggingMessageParams>>> = Arc::new(Mutex::new(Vec::new()));
    let captured_clone = captured.clone();

    let handler = NotificationHandler::new().on_log_message(move |params| {
        captured_clone.lock().unwrap().push(params);
    });

    let transport = HttpClientTransport::new(&url);
    let client = McpClientBuilder::new()
        .with_sampling()
        .connect(transport, handler)
        .await
        .unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Call the tool that sends a log notification
    let result = client
        .call_tool("test_log", serde_json::json!({}))
        .await
        .unwrap();
    assert_eq!(result.first_text(), Some("logged"));

    // Wait for the notification to arrive via SSE
    let received = tokio::time::timeout(Duration::from_secs(3), async {
        loop {
            if !captured.lock().unwrap().is_empty() {
                return true;
            }
            tokio::time::sleep(Duration::from_millis(50)).await;
        }
    })
    .await
    .unwrap_or(false);

    assert!(received, "Expected to receive log notification via SSE");

    {
        let logs = captured.lock().unwrap();
        assert_eq!(logs.len(), 1);
        assert!(matches!(logs[0].level, LogLevel::Info));
        assert_eq!(logs[0].data, serde_json::json!("test log message"));
    }

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Server-initiated Sampling E2E
// ---------------------------------------------------------------------------

struct MockSamplingHandler;

#[async_trait]
impl ClientHandler for MockSamplingHandler {
    async fn handle_create_message(
        &self,
        _params: CreateMessageParams,
    ) -> Result<CreateMessageResult, JsonRpcError> {
        Ok(CreateMessageResult {
            content: SamplingContentOrArray::Single(SamplingContent::Text {
                text: "mock-llm-response".into(),
                annotations: None,
                meta: None,
            }),
            model: "test-model".into(),
            role: ContentRole::Assistant,
            stop_reason: Some("end_turn".into()),
            meta: None,
        })
    }
}

#[tokio::test]
async fn test_http_client_sampling_round_trip() {
    let (url, _server) = start_bidirectional_server().await;

    let transport = HttpClientTransport::with_config(
        &url,
        HttpClientConfig {
            auto_sse: false,
            ..Default::default()
        },
    );
    let client = McpClientBuilder::new()
        .with_sampling()
        .connect(transport, MockSamplingHandler)
        .await
        .unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Call the tool that triggers server-side sampling
    // Flow: client -> call_tool -> server ctx.sample() -> originating POST SSE ->
    //       client MockSamplingHandler -> POST response -> server returns result
    let result = client
        .call_tool("test_sampling", serde_json::json!({}))
        .await
        .unwrap();

    assert_eq!(result.first_text(), Some("mock-llm-response"));

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Server-initiated Elicitation E2E
// ---------------------------------------------------------------------------

struct MockElicitationHandler;

#[async_trait]
impl ClientHandler for MockElicitationHandler {
    async fn handle_elicit(
        &self,
        _params: ElicitRequestParams,
    ) -> Result<ElicitResult, JsonRpcError> {
        let mut content = HashMap::new();
        content.insert("confirm".to_string(), ElicitFieldValue::Boolean(true));
        Ok(ElicitResult::accept(content))
    }
}

#[tokio::test]
async fn test_http_client_elicitation_confirm() {
    let (url, _server) = start_bidirectional_server().await;

    let transport = HttpClientTransport::with_config(
        &url,
        HttpClientConfig {
            auto_sse: false,
            ..Default::default()
        },
    );
    let client = McpClientBuilder::new()
        .with_elicitation()
        .with_sampling()
        .connect(transport, MockElicitationHandler)
        .await
        .unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Call the tool that triggers server-side elicitation via ctx.confirm()
    // Flow: client -> call_tool -> server ctx.confirm("proceed?") -> originating POST SSE ->
    //       client MockElicitationHandler -> POST response -> server returns "confirmed"
    let result = client
        .call_tool("test_confirm", serde_json::json!({}))
        .await
        .unwrap();

    assert_eq!(result.first_text(), Some("confirmed"));

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_roots_request_uses_originating_post() {
    let (url, _server) = start_bidirectional_server().await;

    let transport = HttpClientTransport::with_config(
        &url,
        HttpClientConfig {
            auto_sse: false,
            ..Default::default()
        },
    );
    let client = McpClientBuilder::new()
        .with_roots(vec![Root::new("file:///associated")])
        .connect_simple(transport)
        .await
        .unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let result = client
        .call_tool("test_roots", serde_json::json!({}))
        .await
        .unwrap();
    assert_eq!(result.first_text(), Some("file:///associated"));

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn concurrent_associated_posts_use_unique_server_request_ids() {
    let (url, _server) = start_bidirectional_server().await;

    let transport = HttpClientTransport::with_config(
        &url,
        HttpClientConfig {
            auto_sse: false,
            ..Default::default()
        },
    );
    let client = McpClientBuilder::new()
        .with_sampling()
        .connect(transport, MockSamplingHandler)
        .await
        .unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let (first, second) = tokio::time::timeout(Duration::from_secs(3), async {
        tokio::join!(
            client.call_tool("test_sampling", serde_json::json!({})),
            client.call_tool("test_sampling", serde_json::json!({})),
        )
    })
    .await
    .expect("concurrent associated requests must not cross-talk or hang");

    assert_eq!(first.unwrap().first_text(), Some("mock-llm-response"));
    assert_eq!(second.unwrap().first_text(), Some("mock-llm-response"));

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Root Management E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_root_management() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClientBuilder::new()
        .with_roots(vec![Root::new("file:///project")])
        .connect_simple(transport)
        .await
        .unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Initial roots
    let roots = client.list_roots().await;
    assert_eq!(roots.roots.len(), 1);
    assert_eq!(roots.roots[0].uri, "file:///project");

    // Add a root
    client.add_root(Root::new("file:///other")).await.unwrap();
    let roots = client.list_roots().await;
    assert_eq!(roots.roots.len(), 2);

    // Remove the first root
    let removed = client.remove_root("file:///project").await.unwrap();
    assert!(removed);
    let roots = client.list_roots().await;
    assert_eq!(roots.roots.len(), 1);
    assert_eq!(roots.roots[0].uri, "file:///other");

    // Remove nonexistent root returns false
    let removed = client.remove_root("file:///nonexistent").await.unwrap();
    assert!(!removed);

    // Set roots replaces all
    client
        .set_roots(vec![Root::new("file:///new_a"), Root::new("file:///new_b")])
        .await
        .unwrap();
    let roots = client.list_roots().await;
    assert_eq!(roots.roots.len(), 2);
    let uris: Vec<&str> = roots.roots.iter().map(|r| r.uri.as_str()).collect();
    assert!(uris.contains(&"file:///new_a"));
    assert!(uris.contains(&"file:///new_b"));

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Token Provider E2E
// ---------------------------------------------------------------------------

#[cfg(feature = "oauth-client")]
mod token_provider_tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tower_mcp::{
        OAuthClientError, OAuthScopeEscalationConfig, OAuthScopeEscalationHandler,
        OAuthScopeEscalationRequest, TokenProvider,
    };

    struct StaticTokenProvider(String);

    #[async_trait]
    impl TokenProvider for StaticTokenProvider {
        async fn get_token(&self) -> Result<String, OAuthClientError> {
            Ok(self.0.clone())
        }
    }

    struct EscalatingTokenProvider {
        token: Arc<tokio::sync::RwLock<String>>,
        requests: Arc<Mutex<Vec<OAuthScopeEscalationRequest>>>,
        reauthorization_delay: Duration,
    }

    #[async_trait]
    impl TokenProvider for EscalatingTokenProvider {
        async fn get_token(&self) -> Result<String, OAuthClientError> {
            Ok(self.token.read().await.clone())
        }
    }

    #[async_trait]
    impl OAuthScopeEscalationHandler for EscalatingTokenProvider {
        async fn reauthorize(
            &self,
            request: OAuthScopeEscalationRequest,
        ) -> Result<(), OAuthClientError> {
            self.requests.lock().unwrap().push(request);
            tokio::time::sleep(self.reauthorization_delay).await;
            *self.token.write().await = "escalated-token".to_string();
            Ok(())
        }
    }

    async fn start_scope_challenge_server(
        always_reject: bool,
    ) -> (String, Arc<AtomicUsize>, tokio::task::JoinHandle<()>) {
        use axum::{
            extract::Request,
            http::{HeaderValue, StatusCode, header::WWW_AUTHENTICATE},
            middleware,
            response::IntoResponse,
        };

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let url = format!("http://127.0.0.1:{}", addr.port());
        let challenge = format!(
            r#"Bearer error="insufficient_scope", scope="tools.read", resource_metadata="{url}/.well-known/oauth-protected-resource", error_description="tools/list requires tools.read""#
        );
        let request_count = Arc::new(AtomicUsize::new(0));

        let transport = HttpTransport::new(test_router()).disable_origin_validation();
        let count = request_count.clone();
        let app = transport.into_router().layer(middleware::from_fn(
            move |request: Request, next: middleware::Next| {
                let count = count.clone();
                let challenge = challenge.clone();
                async move {
                    let method = request
                        .headers()
                        .get("mcp-method")
                        .and_then(|value| value.to_str().ok());
                    let is_tools_list = method == Some("tools/list");
                    if is_tools_list {
                        count.fetch_add(1, Ordering::SeqCst);
                    }
                    let escalated = request
                        .headers()
                        .get("authorization")
                        .and_then(|value| value.to_str().ok())
                        == Some("Bearer escalated-token");

                    if is_tools_list && (always_reject || !escalated) {
                        let mut response = StatusCode::FORBIDDEN.into_response();
                        response
                            .headers_mut()
                            .insert(WWW_AUTHENTICATE, HeaderValue::from_str(&challenge).unwrap());
                        response
                    } else {
                        next.run(request).await
                    }
                }
            },
        ));

        let handle = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });
        tokio::time::sleep(Duration::from_millis(50)).await;
        (url, request_count, handle)
    }

    #[tokio::test]
    async fn test_http_client_with_token_provider() {
        let (url, _server) = start_auth_server("dynamic-test-token").await;

        let transport = HttpClientTransport::new(&url)
            .with_token_provider(StaticTokenProvider("dynamic-test-token".into()));
        let client = McpClient::connect(transport).await.unwrap();

        let info = client.initialize("test-client", "1.0.0").await.unwrap();
        assert_eq!(info.server_info.name, "test-http-server");

        // Verify we can make further requests with the dynamic token
        let tools = client.list_tools().await.unwrap();
        assert_eq!(tools.tools.len(), 2);

        client.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_http_client_token_provider_rejected() {
        let (url, _server) = start_auth_server("dynamic-test-token").await;

        let transport = HttpClientTransport::new(&url)
            .with_token_provider(StaticTokenProvider("wrong-token".into()));
        let client = McpClient::connect(transport).await.unwrap();

        let result = client.initialize("test-client", "1.0.0").await;
        assert!(result.is_err());
    }

    #[tokio::test]
    async fn scope_challenge_reauthorizes_and_retries_operation() {
        let (url, request_count, _server) = start_scope_challenge_server(false).await;
        let token = Arc::new(tokio::sync::RwLock::new("initial-token".to_string()));
        let requests = Arc::new(Mutex::new(Vec::new()));
        let provider = EscalatingTokenProvider {
            token,
            requests: requests.clone(),
            reauthorization_delay: Duration::ZERO,
        };
        let transport = HttpClientTransport::new(&url)
            .with_scope_aware_token_provider(provider, OAuthScopeEscalationConfig::new(["openid"]));
        let client = McpClient::connect(transport).await.unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let tools = client.list_tools().await.unwrap();
        assert_eq!(tools.tools.len(), 2);
        assert_eq!(request_count.load(Ordering::SeqCst), 2);

        {
            let recorded = requests.lock().unwrap();
            assert_eq!(recorded.len(), 1);
            assert_eq!(recorded[0].resource, url);
            assert_eq!(recorded[0].operation, "tools/list");
            assert_eq!(recorded[0].previous_scopes, ["openid"]);
            assert_eq!(recorded[0].requested_scopes, ["openid", "tools.read"]);
            assert_eq!(recorded[0].challenge.required_scopes, ["tools.read"]);
            assert!(recorded[0].challenge.resource_metadata.is_some());
            assert_eq!(recorded[0].attempt, 1);
        }

        client.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn repeated_scope_challenge_stops_at_configured_retry_limit() {
        let (url, request_count, _server) = start_scope_challenge_server(true).await;
        let requests = Arc::new(Mutex::new(Vec::new()));
        let provider = EscalatingTokenProvider {
            token: Arc::new(tokio::sync::RwLock::new("initial-token".to_string())),
            requests: requests.clone(),
            reauthorization_delay: Duration::ZERO,
        };
        let transport = HttpClientTransport::new(&url).with_scope_aware_token_provider(
            provider,
            OAuthScopeEscalationConfig::new(["openid"]).max_attempts(3),
        );
        let client = McpClient::connect(transport).await.unwrap();

        client.initialize("test-client", "1.0.0").await.unwrap();
        let error = client.list_tools().await.unwrap_err().to_string();

        assert!(error.contains("insufficient_scope"));
        assert!(error.contains("tools.read"));
        assert_eq!(request_count.load(Ordering::SeqCst), 4);
        assert_eq!(requests.lock().unwrap().len(), 3);
    }

    #[tokio::test]
    async fn concurrent_scope_challenges_share_one_reauthorization() {
        let (url, request_count, _server) = start_scope_challenge_server(false).await;
        let requests = Arc::new(Mutex::new(Vec::new()));
        let provider = EscalatingTokenProvider {
            token: Arc::new(tokio::sync::RwLock::new("initial-token".to_string())),
            requests: requests.clone(),
            reauthorization_delay: Duration::from_millis(50),
        };
        let transport = HttpClientTransport::new(&url)
            .with_scope_aware_token_provider(provider, OAuthScopeEscalationConfig::new(["openid"]));
        let client = McpClient::connect(transport).await.unwrap();
        client.initialize("test-client", "1.0.0").await.unwrap();

        let (first, second) = tokio::join!(client.list_tools(), client.list_tools());

        assert_eq!(first.unwrap().tools.len(), 2);
        assert_eq!(second.unwrap().tools.len(), 2);
        assert_eq!(requests.lock().unwrap().len(), 1);
        assert!((3..=4).contains(&request_count.load(Ordering::SeqCst)));
        client.shutdown().await.unwrap();
    }
}

// ---------------------------------------------------------------------------
// Auth: API key header E2E
// ---------------------------------------------------------------------------

/// Start an HTTP server that validates a custom header.
async fn start_custom_header_auth_server(
    header_name: &str,
    expected_value: &str,
) -> (String, tokio::task::JoinHandle<()>) {
    use axum::{extract::Request, http::StatusCode, middleware, response::Response};

    let router = test_router();
    let transport = HttpTransport::new(router).disable_origin_validation();
    let mcp_router = transport.into_router();

    let name = header_name.to_string();
    let value = expected_value.to_string();
    let app = mcp_router.layer(middleware::from_fn(
        move |request: Request, next: middleware::Next| {
            let name = name.clone();
            let value = value.clone();
            async move {
                let actual = request
                    .headers()
                    .get(&name)
                    .and_then(|v| v.to_str().ok())
                    .map(|s| s.to_string());
                if actual.as_deref() == Some(&value) {
                    Ok::<Response, (StatusCode, String)>(next.run(request).await)
                } else {
                    Err((StatusCode::UNAUTHORIZED, "Unauthorized".to_string()))
                }
            }
        },
    ));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    (url, handle)
}

#[tokio::test]
async fn test_http_client_api_key_header() {
    let (url, _server) = start_custom_header_auth_server("X-API-Key", "my-secret-key").await;

    let transport = HttpClientTransport::new(&url).api_key_header("X-API-Key", "my-secret-key");
    let client = McpClient::connect(transport).await.unwrap();

    let info = client.initialize("test-client", "1.0.0").await.unwrap();
    assert_eq!(info.server_info.name, "test-http-server");

    let tools = client.list_tools().await.unwrap();
    assert_eq!(tools.tools.len(), 2);

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_api_key_header_rejected() {
    let (url, _server) = start_custom_header_auth_server("X-API-Key", "my-secret-key").await;

    let transport = HttpClientTransport::new(&url).api_key_header("X-API-Key", "wrong-key");
    let client = McpClient::connect(transport).await.unwrap();

    let result = client.initialize("test-client", "1.0.0").await;
    assert!(result.is_err());
}

// ---------------------------------------------------------------------------
// Auth: Basic auth E2E
// ---------------------------------------------------------------------------

/// Start an HTTP server that validates Basic auth credentials.
async fn start_basic_auth_server(
    expected_user: &str,
    expected_pass: &str,
) -> (String, tokio::task::JoinHandle<()>) {
    use axum::{extract::Request, http::StatusCode, middleware, response::Response};
    use base64::Engine;

    let router = test_router();
    let transport = HttpTransport::new(router).disable_origin_validation();
    let mcp_router = transport.into_router();

    let expected = format!(
        "Basic {}",
        base64::engine::general_purpose::STANDARD
            .encode(format!("{}:{}", expected_user, expected_pass))
    );
    let app = mcp_router.layer(middleware::from_fn(
        move |request: Request, next: middleware::Next| {
            let expected = expected.clone();
            async move {
                let auth = request
                    .headers()
                    .get("Authorization")
                    .and_then(|v| v.to_str().ok())
                    .map(|s| s.to_string());
                if auth.as_deref() == Some(&expected) {
                    Ok::<Response, (StatusCode, String)>(next.run(request).await)
                } else {
                    Err((StatusCode::UNAUTHORIZED, "Unauthorized".to_string()))
                }
            }
        },
    ));

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, app).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;

    (url, handle)
}

#[tokio::test]
async fn test_http_client_basic_auth() {
    let (url, _server) = start_basic_auth_server("admin", "password123").await;

    let transport = HttpClientTransport::new(&url).basic_auth("admin", "password123");
    let client = McpClient::connect(transport).await.unwrap();

    let info = client.initialize("test-client", "1.0.0").await.unwrap();
    assert_eq!(info.server_info.name, "test-http-server");

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_basic_auth_rejected() {
    let (url, _server) = start_basic_auth_server("admin", "password123").await;

    let transport = HttpClientTransport::new(&url).basic_auth("admin", "wrong");
    let client = McpClient::connect(transport).await.unwrap();

    let result = client.initialize("test-client", "1.0.0").await;
    assert!(result.is_err());
}

// ---------------------------------------------------------------------------
// Auth: Custom header E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_custom_header() {
    let (url, _server) = start_custom_header_auth_server("X-Custom-Auth", "custom-value-123").await;

    let transport = HttpClientTransport::new(&url).header("X-Custom-Auth", "custom-value-123");
    let client = McpClient::connect(transport).await.unwrap();

    let info = client.initialize("test-client", "1.0.0").await.unwrap();
    assert_eq!(info.server_info.name, "test-http-server");

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Auth: OAuthClientCredentials E2E
// ---------------------------------------------------------------------------

#[cfg(feature = "oauth-client")]
mod oauth_client_credentials_tests {
    use super::*;
    use tower_mcp::OAuthClientCredentials;

    /// Start a mock OAuth token endpoint that returns access tokens.
    async fn start_mock_token_server(
        expected_client_id: &str,
        expected_client_secret: &str,
        issued_token: &str,
    ) -> (String, tokio::task::JoinHandle<()>) {
        use axum::{Router, extract::Request, http::StatusCode, routing::post};
        use base64::Engine;

        let expected_auth = format!(
            "Basic {}",
            base64::engine::general_purpose::STANDARD
                .encode(format!("{}:{}", expected_client_id, expected_client_secret))
        );
        let token = issued_token.to_string();

        let app = Router::new().route(
            "/token",
            post(move |request: Request| {
                let expected_auth = expected_auth.clone();
                let token = token.clone();
                async move {
                    let auth = request
                        .headers()
                        .get("Authorization")
                        .and_then(|v| v.to_str().ok())
                        .map(|s| s.to_string());
                    if auth.as_deref() != Some(&expected_auth) {
                        return (
                            StatusCode::UNAUTHORIZED,
                            axum::Json(serde_json::json!({"error": "invalid_client"})),
                        );
                    }
                    (
                        StatusCode::OK,
                        axum::Json(serde_json::json!({
                            "access_token": token,
                            "token_type": "bearer",
                            "expires_in": 3600
                        })),
                    )
                }
            }),
        );

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let url = format!("http://127.0.0.1:{}", addr.port());

        let handle = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        tokio::time::sleep(Duration::from_millis(50)).await;

        (url, handle)
    }

    #[tokio::test]
    async fn test_http_client_oauth_client_credentials() {
        let issued_token = "oauth-access-token-xyz";

        // Start the mock token server
        let (token_url, _token_server) =
            start_mock_token_server("my-client", "my-secret", issued_token).await;

        // Start the MCP server that validates bearer tokens
        let (mcp_url, _mcp_server) = start_auth_server(issued_token).await;

        // Build the OAuth provider pointing at our mock token endpoint
        let provider = OAuthClientCredentials::builder()
            .client_id("my-client")
            .client_secret("my-secret")
            .token_endpoint(format!("{}/token", token_url))
            .resource(&mcp_url)
            .build()
            .unwrap();

        let transport = HttpClientTransport::new(&mcp_url).with_token_provider(provider);
        let client = McpClient::connect(transport).await.unwrap();

        let info = client.initialize("test-client", "1.0.0").await.unwrap();
        assert_eq!(info.server_info.name, "test-http-server");

        // Verify subsequent requests also work (token is cached and reused)
        let tools = client.list_tools().await.unwrap();
        assert_eq!(tools.tools.len(), 2);

        client.shutdown().await.unwrap();
    }

    #[tokio::test]
    async fn test_http_client_oauth_client_credentials_bad_secret() {
        let (token_url, _token_server) =
            start_mock_token_server("my-client", "my-secret", "token").await;

        let (mcp_url, _mcp_server) = start_auth_server("token").await;

        // Wrong secret should fail at token acquisition
        let provider = OAuthClientCredentials::builder()
            .client_id("my-client")
            .client_secret("wrong-secret")
            .token_endpoint(format!("{}/token", token_url))
            .resource(&mcp_url)
            .build()
            .unwrap();

        let transport = HttpClientTransport::new(&mcp_url).with_token_provider(provider);
        let client = McpClient::connect(transport).await.unwrap();

        let result = client.initialize("test-client", "1.0.0").await;
        assert!(result.is_err());
    }
}

// ---------------------------------------------------------------------------
// Config: auto_sse disabled E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_auto_sse_disabled() {
    let (url, _server) = start_server().await;

    let config = tower_mcp::client::HttpClientConfig {
        auto_sse: false,
        ..Default::default()
    };
    let transport = HttpClientTransport::with_config(&url, config);
    let client = McpClient::connect(transport).await.unwrap();

    let info = client.initialize("test-client", "1.0.0").await.unwrap();
    assert_eq!(info.server_info.name, "test-http-server");

    // Basic request/response still works without SSE
    let tools = client.list_tools().await.unwrap();
    assert_eq!(tools.tools.len(), 2);

    let result = client
        .call_tool("echo", serde_json::json!({"message": "no sse"}))
        .await
        .unwrap();
    assert_eq!(result.first_text(), Some("no sse"));

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Edge Cases: Concurrent requests E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_concurrent_requests() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // Fire off multiple call_tool requests concurrently
    let mut handles = Vec::new();
    for i in 0..5 {
        let client_ref = &client;
        handles.push(async move {
            client_ref
                .call_tool("add", serde_json::json!({"a": i, "b": i * 10}))
                .await
        });
    }

    let results: Vec<_> = futures::future::join_all(handles).await;
    for result in &results {
        assert!(result.is_ok(), "Concurrent request failed: {:?}", result);
    }

    // Verify all results are correct (order may vary)
    let mut texts: Vec<String> = results
        .into_iter()
        .map(|r| r.unwrap().first_text().unwrap().to_string())
        .collect();
    texts.sort();
    assert_eq!(texts, vec!["0", "11", "22", "33", "44"]);

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Edge Cases: Error responses E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_tool_not_found_error() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let result = client
        .call_tool("nonexistent_tool", serde_json::json!({}))
        .await;
    assert!(result.is_err());

    let err = result.unwrap_err();
    let err_msg = err.to_string();
    assert!(
        err_msg.contains("not found") || err_msg.contains("Unknown tool"),
        "Expected tool-not-found error, got: {}",
        err_msg
    );

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_invalid_tool_arguments() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    // "add" expects {a: i64, b: i64}, send wrong types
    let result = client
        .call_tool("add", serde_json::json!({"a": "not_a_number", "b": 1}))
        .await;

    // The server should return an error (either JSON-RPC error or isError in CallToolResult)
    match result {
        Ok(call_result) => {
            assert!(
                call_result.is_error,
                "Expected error flag in CallToolResult"
            );
        }
        Err(_) => {
            // JSON-RPC error is also acceptable
        }
    }

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_prompt_not_found_error() {
    let (url, _server) = start_extended_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let result = client.get_prompt("nonexistent_prompt", None).await;
    assert!(result.is_err());

    client.shutdown().await.unwrap();
}

#[tokio::test]
async fn test_http_client_resource_not_found_error() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("test-client", "1.0.0").await.unwrap();

    let result = client.read_resource("nonexistent://resource").await;
    assert!(result.is_err());

    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Edge Cases: Shutdown without initialize E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_shutdown_without_initialize() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();

    // Shutdown without ever calling initialize -- should not panic
    client.shutdown().await.unwrap();
}

// ---------------------------------------------------------------------------
// Edge Cases: Requests before initialize E2E
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_request_before_initialize() {
    let (url, _server) = start_server().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();

    // Attempting to list tools before initialize should fail
    let result = client.list_tools().await;
    assert!(result.is_err());

    let err_msg = result.unwrap_err().to_string();
    assert!(
        err_msg.contains("not initialized"),
        "Expected not-initialized error, got: {}",
        err_msg
    );
}

// ---------------------------------------------------------------------------
// SSE Event Replay on Reconnect E2E (#509)
// ---------------------------------------------------------------------------

#[tokio::test]
async fn test_http_client_sse_event_replay_on_reconnect() {
    let (url, _server) = start_bidirectional_server().await;
    let client = reqwest::Client::new();

    // 1. Initialize a session
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json, text/event-stream")
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "initialize",
                "params": {
                    "protocolVersion": "2025-11-25",
                    "capabilities": { "sampling": {} },
                    "clientInfo": { "name": "test-sse", "version": "1.0.0" }
                }
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let session_id = resp
        .headers()
        .get("mcp-session-id")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();

    // 1b. Send notifications/initialized before any other requests (spec requirement)
    client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json, text/event-stream")
        .header("mcp-session-id", &session_id)
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "method": "notifications/initialized"
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    // 2. Open SSE stream and start consuming in a background task.
    //    This ensures the server's broadcast subscriber is active before we
    //    trigger notifications.
    let sse_resp = client
        .get(&url)
        .header("Accept", "text/event-stream")
        .header("mcp-session-id", &session_id)
        .send()
        .await
        .unwrap();
    assert_eq!(sse_resp.status(), 200);

    let (collected_tx, collected_rx) = tokio::sync::oneshot::channel();
    let sse_task = tokio::spawn(async move {
        let mut text = String::new();
        let mut stream = sse_resp.bytes_stream();
        use futures::StreamExt;
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.unwrap();
            text.push_str(&String::from_utf8_lossy(&chunk));
            // Wait until we have at least 2 events with IDs
            let id_count = text.lines().filter(|l| l.starts_with("id:")).count();
            if id_count >= 2 {
                break;
            }
        }
        let _ = collected_tx.send(text);
    });

    // Give the SSE subscription time to be established
    tokio::time::sleep(Duration::from_millis(100)).await;

    // 3. Send two tool calls to trigger two log notifications
    for req_id in [2, 3] {
        let _resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json, text/event-stream")
            .header("mcp-session-id", &session_id)
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": req_id,
                    "method": "tools/call",
                    "params": { "name": "test_log", "arguments": {} }
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();
    }

    // 4. Wait for background task to collect both events
    let sse_text = tokio::time::timeout(Duration::from_secs(5), collected_rx)
        .await
        .expect("timed out waiting for SSE events")
        .expect("SSE task dropped sender");

    // Parse event IDs from the collected SSE data
    let event_ids: Vec<u64> = sse_text
        .lines()
        .filter(|l| l.starts_with("id:"))
        .filter_map(|l| l.trim_start_matches("id:").trim().parse().ok())
        .collect();

    assert!(
        event_ids.len() >= 2,
        "Expected at least 2 events, got: {event_ids:?}"
    );

    let first_id = event_ids[0];

    // 5. SSE task has finished; stream is dropped (connection closed)
    let _ = sse_task.await;

    // 6. Open new SSE stream with Last-Event-ID = first event ID.
    //    The server should replay buffered events after that ID.
    let sse_resp2 = client
        .get(&url)
        .header("Accept", "text/event-stream")
        .header("mcp-session-id", &session_id)
        .header("Last-Event-ID", first_id.to_string())
        .send()
        .await
        .unwrap();
    assert_eq!(sse_resp2.status(), 200);

    // 7. Read replayed events
    let replay_text = tokio::time::timeout(Duration::from_secs(2), async {
        let mut text = String::new();
        let mut stream = sse_resp2.bytes_stream();
        use futures::StreamExt;
        while let Some(chunk) = stream.next().await {
            let chunk = chunk.unwrap();
            text.push_str(&String::from_utf8_lossy(&chunk));
            if text.lines().any(|l| l.starts_with("id:")) {
                break;
            }
        }
        text
    })
    .await
    .unwrap_or_default();

    // Parse replayed event IDs -- they should all be > first_id
    let replayed_ids: Vec<u64> = replay_text
        .lines()
        .filter(|l| l.starts_with("id:"))
        .filter_map(|l| l.trim_start_matches("id:").trim().parse().ok())
        .collect();

    assert!(
        !replayed_ids.is_empty(),
        "Expected replayed events after reconnection with Last-Event-ID"
    );
    for id in &replayed_ids {
        assert!(
            *id > first_id,
            "Replayed event ID {id} should be > last seen ID {first_id}",
        );
    }
}

// ---------------------------------------------------------------------------
// Session Expiry E2E (#510)
// ---------------------------------------------------------------------------

/// Start a server with very short session TTL for expiry testing.
async fn start_expiring_server() -> (String, tokio::task::JoinHandle<()>) {
    let router = test_router();
    let config = SessionConfig::with_ttl(Duration::from_millis(100))
        .cleanup_interval(Duration::from_millis(20));
    let transport = HttpTransport::new(router)
        .disable_origin_validation()
        .session_config(config);
    let axum_router = transport.into_router();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, axum_router).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;
    (url, handle)
}

#[tokio::test]
async fn test_http_client_session_expiry_error() {
    let (url, _server) = start_expiring_server().await;
    let client = reqwest::Client::new();

    // Initialize a session
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json, text/event-stream")
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "initialize",
                "params": {
                    "protocolVersion": "2025-11-25",
                    "capabilities": {},
                    "clientInfo": { "name": "test-expiry", "version": "1.0.0" }
                }
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let session_id = resp
        .headers()
        .get("mcp-session-id")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();

    // Send notifications/initialized before any other requests (spec requirement)
    client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json, text/event-stream")
        .header("mcp-session-id", &session_id)
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "method": "notifications/initialized"
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    // Verify the session works before expiry
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")
        .header("mcp-session-id", &session_id)
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 2,
                "method": "tools/list",
                "params": {}
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert!(
        body.get("result").is_some(),
        "Expected successful tools/list response, got: {body}"
    );

    // Wait for session to expire and cleanup to run
    tokio::time::sleep(Duration::from_millis(200)).await;

    // Session should be expired -- next request should return a JSON-RPC error
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")
        .header("mcp-session-id", &session_id)
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 3,
                "method": "tools/list",
                "params": {}
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    let body: serde_json::Value = resp.json().await.unwrap();
    let error = body
        .get("error")
        .expect("Expected JSON-RPC error after session expiry");
    assert_eq!(
        error["code"].as_i64().unwrap(),
        -32005,
        "Expected SessionNotFound error code (-32005)"
    );
}

// ---------------------------------------------------------------------------
// Session handling -- optional by default, strict via require_sessions()
// ---------------------------------------------------------------------------

/// Start a server with require_sessions() for strict session enforcement.
async fn start_required_sessions_server() -> (String, tokio::task::JoinHandle<()>) {
    let router = test_router();
    let transport = HttpTransport::new(router)
        .disable_origin_validation()
        .require_sessions();
    let axum_router = transport.into_router();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, axum_router).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;
    (url, handle)
}

/// Start a server with optional sessions (the default).
async fn start_optional_sessions_server() -> (String, tokio::task::JoinHandle<()>) {
    let router = test_router();
    let transport = HttpTransport::new(router).disable_origin_validation();
    let axum_router = transport.into_router();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let handle = tokio::spawn(async move {
        axum::serve(listener, axum_router).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;
    (url, handle)
}

/// Simulate Codex CLI behavior: initialize + tools/list during setup,
/// then tools/call without session ID on a fresh connection.
#[tokio::test]
async fn test_optional_sessions_codex_pattern() {
    let (url, _server) = start_optional_sessions_server().await;
    let client = reqwest::Client::new();

    // Phase 1: Setup -- Codex initializes and discovers tools (normal flow)
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json, text/event-stream")
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "initialize",
                "params": {
                    "protocolVersion": "2025-11-25",
                    "capabilities": {},
                    "clientInfo": { "name": "codex-cli", "version": "0.1.0" }
                }
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let session_id = resp
        .headers()
        .get("mcp-session-id")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();

    // Send notifications/initialized before any other requests (spec requirement)
    client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json, text/event-stream")
        .header("mcp-session-id", &session_id)
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "method": "notifications/initialized"
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    // tools/list with session ID (setup phase)
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")
        .header("mcp-session-id", &session_id)
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 2,
                "method": "tools/list",
                "params": {}
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    let body: serde_json::Value = resp.json().await.unwrap();
    let tools = body["result"]["tools"].as_array().unwrap();
    assert_eq!(tools.len(), 2, "Should discover echo and add tools");

    // Phase 2: Execution -- Codex sends tools/call WITHOUT session ID
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")
        // No mcp-session-id header!
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 3,
                "method": "tools/call",
                "params": {
                    "name": "echo",
                    "arguments": { "message": "hello from codex" }
                }
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert!(
        body.get("error").is_none(),
        "tools/call without session ID should succeed with optional_sessions, got: {body}"
    );
    let content = &body["result"]["content"][0]["text"];
    assert_eq!(content.as_str().unwrap(), "hello from codex");
}

/// Simulate Cursor behavior: tools/list without session ID.
#[tokio::test]
async fn test_optional_sessions_cursor_tools_list_no_session() {
    let (url, _server) = start_optional_sessions_server().await;
    let client = reqwest::Client::new();

    // Cursor sends tools/list directly without initializing or session ID
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")
        // No mcp-session-id header!
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "tools/list",
                "params": {}
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert!(
        body.get("error").is_none(),
        "tools/list without session ID should succeed with optional_sessions, got: {body}"
    );
    let tools = body["result"]["tools"].as_array().unwrap();
    assert_eq!(tools.len(), 2);
}

/// Multiple sessionless requests should each work independently.
#[tokio::test]
async fn test_optional_sessions_multiple_stateless_calls() {
    let (url, _server) = start_optional_sessions_server().await;
    let client = reqwest::Client::new();

    // Send multiple tools/call requests without session IDs
    for i in 0..3 {
        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": i + 1,
                    "method": "tools/call",
                    "params": {
                        "name": "add",
                        "arguments": { "a": i, "b": 10 }
                    }
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        assert_eq!(resp.status(), 200);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert!(
            body.get("error").is_none(),
            "Stateless call {i} failed: {body}"
        );
        let expected = format!("{}", i + 10);
        assert_eq!(
            body["result"]["content"][0]["text"].as_str().unwrap(),
            expected
        );
    }
}

/// With require_sessions(), missing session ID should be rejected.
#[tokio::test]
async fn test_sessions_required_rejects_without_session_id() {
    let (url, _server) = start_required_sessions_server().await;
    let client = reqwest::Client::new();

    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")
        // No mcp-session-id header!
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "tools/list",
                "params": {}
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    let body: serde_json::Value = resp.json().await.unwrap();
    let error = body
        .get("error")
        .expect("Expected JSON-RPC error when session ID is missing");
    assert_eq!(
        error["code"].as_i64().unwrap(),
        -32006,
        "Expected SessionRequired error code (-32006)"
    );
}

/// With optional_sessions, clients that DO send session IDs should still work.
#[tokio::test]
async fn test_optional_sessions_with_session_id_still_works() {
    let (url, _server) = start_optional_sessions_server().await;
    let client = reqwest::Client::new();

    // Initialize normally
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json, text/event-stream")
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "initialize",
                "params": {
                    "protocolVersion": "2025-11-25",
                    "capabilities": {},
                    "clientInfo": { "name": "good-client", "version": "1.0.0" }
                }
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    let session_id = resp
        .headers()
        .get("mcp-session-id")
        .unwrap()
        .to_str()
        .unwrap()
        .to_string();

    // Send initialized notification
    let _resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")
        .header("mcp-session-id", &session_id)
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "method": "notifications/initialized",
                "params": {}
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    // Use session normally
    let resp = client
        .post(&url)
        .header("Content-Type", "application/json")
        .header("Accept", "application/json")
        .header("mcp-session-id", &session_id)
        .body(
            serde_json::json!({
                "jsonrpc": "2.0",
                "id": 2,
                "method": "tools/call",
                "params": {
                    "name": "echo",
                    "arguments": { "message": "session works" }
                }
            })
            .to_string(),
        )
        .send()
        .await
        .unwrap();

    assert_eq!(resp.status(), 200);
    let body: serde_json::Value = resp.json().await.unwrap();
    assert!(
        body.get("error").is_none(),
        "Session-based call should work: {body}"
    );
    assert_eq!(
        body["result"]["content"][0]["text"].as_str().unwrap(),
        "session works"
    );
}

// =============================================================================
// SEP-1442 Stateless mode tests
// =============================================================================

#[cfg(feature = "stateless")]
mod stateless_tests {
    use super::*;
    use axum::extract::State;
    use axum::http::{HeaderMap, StatusCode};
    use axum::response::sse::{Event, Sse};
    use axum::response::{IntoResponse, Response};
    use axum::routing::post;
    use axum::{Json, Router};
    use std::convert::Infallible;
    use std::sync::atomic::{AtomicUsize, Ordering};
    use tower_mcp::stateless::StatelessConfig;

    /// Start a server with stateless mode enabled.
    async fn start_stateless_server() -> (String, tokio::task::JoinHandle<()>) {
        let router = test_router();
        let transport = HttpTransport::new(router)
            .disable_origin_validation()
            .stateless(StatelessConfig::new());
        let axum_router = transport.into_router();

        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let addr = listener.local_addr().unwrap();
        let url = format!("http://127.0.0.1:{}", addr.port());

        let handle = tokio::spawn(async move {
            axum::serve(listener, axum_router).await.unwrap();
        });

        tokio::time::sleep(Duration::from_millis(50)).await;
        (url, handle)
    }

    #[derive(Clone, Default)]
    struct StaleSchemaState {
        list_calls: Arc<AtomicUsize>,
        tool_calls: Arc<AtomicUsize>,
        mirrored_headers: Arc<Mutex<Vec<(bool, bool)>>>,
    }

    async fn stale_schema_endpoint(
        State(state): State<StaleSchemaState>,
        headers: HeaderMap,
        Json(body): Json<serde_json::Value>,
    ) -> Response {
        let id = body.get("id").cloned().unwrap_or(serde_json::Value::Null);
        match body
            .get("method")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default()
        {
            "server/discover" => (
                StatusCode::OK,
                Json(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "result": {
                        "resultType": "complete",
                        "supportedVersions": ["2026-07-28"],
                        "capabilities": {},
                        "ttlMs": 0,
                        "cacheScope": "private"
                    }
                })),
            )
                .into_response(),
            "tools/list" => {
                let suffix = if state.list_calls.fetch_add(1, Ordering::SeqCst) == 0 {
                    "Region"
                } else {
                    "Zone"
                };
                (
                    StatusCode::OK,
                    Json(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": id,
                        "result": {
                            "resultType": "complete",
                            "tools": [{
                                "name": "changing-tool",
                                "inputSchema": {
                                    "type": "object",
                                    "properties": {
                                        "region": {
                                            "type": "string",
                                            "x-mcp-header": suffix
                                        }
                                    }
                                }
                            }],
                            "ttlMs": 60_000,
                            "cacheScope": "private"
                        }
                    })),
                )
                    .into_response()
            }
            "tools/call" => {
                state.mirrored_headers.lock().unwrap().push((
                    headers.contains_key("mcp-param-region"),
                    headers.contains_key("mcp-param-zone"),
                ));
                if state.tool_calls.fetch_add(1, Ordering::SeqCst) == 0 {
                    (
                        StatusCode::BAD_REQUEST,
                        Json(serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": id,
                            "error": {
                                "code": -32020,
                                "message": "cached tool schema is stale"
                            }
                        })),
                    )
                        .into_response()
                } else {
                    (
                        StatusCode::OK,
                        Json(serde_json::json!({
                            "jsonrpc": "2.0",
                            "id": id,
                            "result": {
                                "resultType": "complete",
                                "content": [{
                                    "type": "text",
                                    "text": "fresh headers"
                                }]
                            }
                        })),
                    )
                        .into_response()
                }
            }
            _ => (
                StatusCode::NOT_FOUND,
                Json(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "error": {"code": -32601, "message": "unknown method"}
                })),
            )
                .into_response(),
        }
    }

    #[derive(Clone, Default)]
    struct SubscriptionClientState {
        active_streams: Arc<AtomicUsize>,
        dropped_streams: Arc<AtomicUsize>,
        tools_list_calls: Arc<AtomicUsize>,
        cancellation_posts: Arc<AtomicUsize>,
    }

    enum SubscriptionStreamMode {
        LongLived,
        Graceful,
        Abrupt,
        BeforeAcknowledgment,
        MismatchedId,
    }

    struct SubscriptionStream {
        phase: u8,
        id: serde_json::Value,
        notifications: serde_json::Value,
        mode: SubscriptionStreamMode,
        state: SubscriptionClientState,
    }

    impl Drop for SubscriptionStream {
        fn drop(&mut self) {
            self.state.active_streams.fetch_sub(1, Ordering::SeqCst);
            self.state.dropped_streams.fetch_add(1, Ordering::SeqCst);
        }
    }

    async fn subscription_client_endpoint(
        State(state): State<SubscriptionClientState>,
        headers: HeaderMap,
        Json(body): Json<serde_json::Value>,
    ) -> Response {
        let id = body.get("id").cloned().unwrap_or(serde_json::Value::Null);
        let method = body
            .get("method")
            .and_then(serde_json::Value::as_str)
            .unwrap_or_default();
        match method {
            "server/discover" => (
                StatusCode::OK,
                Json(serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": id,
                    "result": {
                        "resultType": "complete",
                        "supportedVersions": ["2026-07-28"],
                        "capabilities": {},
                        "ttlMs": 0,
                        "cacheScope": "private"
                    }
                })),
            )
                .into_response(),
            "tools/list" => {
                state.tools_list_calls.fetch_add(1, Ordering::SeqCst);
                (
                    StatusCode::OK,
                    Json(serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": id,
                        "result": {
                            "resultType": "complete",
                            "tools": [],
                            "ttlMs": 0,
                            "cacheScope": "private"
                        }
                    })),
                )
                    .into_response()
            }
            "subscriptions/listen" => {
                if headers
                    .get("mcp-protocol-version")
                    .and_then(|value| value.to_str().ok())
                    != Some("2026-07-28")
                    || headers
                        .get("mcp-method")
                        .and_then(|value| value.to_str().ok())
                        != Some("subscriptions/listen")
                    || body.pointer("/params/_meta/io.modelcontextprotocol~1protocolVersion")
                        != Some(&serde_json::json!("2026-07-28"))
                {
                    return StatusCode::BAD_REQUEST.into_response();
                }

                let notifications = body["params"]["notifications"].clone();
                let mode = if notifications["resourcesListChanged"] == serde_json::Value::Bool(true)
                {
                    SubscriptionStreamMode::Graceful
                } else if notifications["promptsListChanged"] == serde_json::Value::Bool(true) {
                    SubscriptionStreamMode::Abrupt
                } else if notifications["resourceSubscriptions"][0]
                    == serde_json::json!("before-ack")
                {
                    SubscriptionStreamMode::BeforeAcknowledgment
                } else if notifications["resourceSubscriptions"][0] == serde_json::json!("wrong-id")
                {
                    SubscriptionStreamMode::MismatchedId
                } else {
                    SubscriptionStreamMode::LongLived
                };
                state.active_streams.fetch_add(1, Ordering::SeqCst);
                let stream = futures::stream::unfold(
                    SubscriptionStream {
                        phase: 0,
                        id,
                        notifications,
                        mode,
                        state,
                    },
                    |mut stream| async move {
                        let message = match stream.phase {
                            0 => match stream.mode {
                                SubscriptionStreamMode::BeforeAcknowledgment => {
                                    serde_json::json!({
                                        "jsonrpc": "2.0",
                                        "method": "notifications/tools/list_changed",
                                        "params": {
                                            "_meta": {
                                                "io.modelcontextprotocol/subscriptionId": stream.id
                                            }
                                        }
                                    })
                                }
                                SubscriptionStreamMode::MismatchedId => serde_json::json!({
                                    "jsonrpc": "2.0",
                                    "method": "notifications/subscriptions/acknowledged",
                                    "params": {
                                        "_meta": {
                                            "io.modelcontextprotocol/subscriptionId": 999
                                        },
                                        "notifications": stream.notifications
                                    }
                                }),
                                _ => serde_json::json!({
                                    "jsonrpc": "2.0",
                                    "method": "notifications/subscriptions/acknowledged",
                                    "params": {
                                        "_meta": {
                                            "io.modelcontextprotocol/subscriptionId": stream.id
                                        },
                                        "notifications": stream.notifications
                                    }
                                }),
                            },
                            1 => match stream.mode {
                                SubscriptionStreamMode::LongLived => serde_json::json!({
                                    "jsonrpc": "2.0",
                                    "method": "notifications/tools/list_changed",
                                    "params": {
                                        "_meta": {
                                            "io.modelcontextprotocol/subscriptionId": stream.id
                                        }
                                    }
                                }),
                                SubscriptionStreamMode::Graceful => serde_json::json!({
                                    "jsonrpc": "2.0",
                                    "id": stream.id,
                                    "result": {
                                        "resultType": "complete",
                                        "_meta": {
                                            "io.modelcontextprotocol/subscriptionId": stream.id
                                        }
                                    }
                                }),
                                SubscriptionStreamMode::Abrupt => return None,
                                SubscriptionStreamMode::BeforeAcknowledgment
                                | SubscriptionStreamMode::MismatchedId => {
                                    std::future::pending::<()>().await;
                                    unreachable!()
                                }
                            },
                            _ => match stream.mode {
                                SubscriptionStreamMode::LongLived => {
                                    std::future::pending::<()>().await;
                                    unreachable!()
                                }
                                SubscriptionStreamMode::Graceful
                                | SubscriptionStreamMode::Abrupt => return None,
                                SubscriptionStreamMode::BeforeAcknowledgment
                                | SubscriptionStreamMode::MismatchedId => unreachable!(),
                            },
                        };
                        stream.phase += 1;
                        Some((
                            Ok::<_, Infallible>(Event::default().data(message.to_string())),
                            stream,
                        ))
                    },
                );
                Sse::new(stream).into_response()
            }
            "notifications/cancelled" => {
                state.cancellation_posts.fetch_add(1, Ordering::SeqCst);
                StatusCode::ACCEPTED.into_response()
            }
            _ => StatusCode::NOT_FOUND.into_response(),
        }
    }

    async fn wait_for_counter(counter: &AtomicUsize, expected: usize) {
        tokio::time::timeout(Duration::from_secs(2), async {
            while counter.load(Ordering::SeqCst) != expected {
                tokio::task::yield_now().await;
            }
        })
        .await
        .unwrap();
    }

    #[tokio::test]
    async fn final_http_client_manages_concurrent_subscription_streams() {
        let state = SubscriptionClientState::default();
        let app = Router::new()
            .route("/", post(subscription_client_endpoint))
            .with_state(state.clone());
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        let tools_changed = Arc::new(AtomicUsize::new(0));
        let handler = NotificationHandler::new().on_tools_changed({
            let tools_changed = tools_changed.clone();
            move || {
                tools_changed.fetch_add(1, Ordering::SeqCst);
            }
        });
        let config = HttpClientConfig {
            request_timeout: Duration::from_millis(100),
            sse_reconnect: false,
            ..Default::default()
        };
        let client = McpClient::builder()
            .protocol_support(tower_mcp::ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect(HttpClientTransport::with_config(url, config), handler)
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        let filter = SubscriptionFilter {
            tools_list_changed: Some(true),
            ..Default::default()
        };
        let mut first = client.listen_subscriptions(filter.clone()).await.unwrap();
        let mut second = client.listen_subscriptions(filter).await.unwrap();
        assert_ne!(first.id(), second.id());
        assert_eq!(
            first.acknowledged().await.unwrap().tools_list_changed,
            Some(true)
        );
        assert_eq!(
            second.acknowledged().await.unwrap().tools_list_changed,
            Some(true)
        );
        wait_for_counter(&state.active_streams, 2).await;
        wait_for_counter(&tools_changed, 2).await;

        tokio::time::sleep(Duration::from_millis(200)).await;
        assert_eq!(state.dropped_streams.load(Ordering::SeqCst), 0);
        client.list_tools().await.unwrap();

        first.cancel().await.unwrap();
        wait_for_counter(&state.active_streams, 1).await;
        client.list_tools().await.unwrap();
        second.cancel().await.unwrap();
        wait_for_counter(&state.active_streams, 0).await;
        assert_eq!(state.dropped_streams.load(Ordering::SeqCst), 2);
        assert_eq!(state.tools_list_calls.load(Ordering::SeqCst), 2);
        assert_eq!(state.cancellation_posts.load(Ordering::SeqCst), 0);

        let mut graceful = client
            .listen_subscriptions(SubscriptionFilter {
                resources_list_changed: Some(true),
                ..Default::default()
            })
            .await
            .unwrap();
        assert_eq!(
            graceful
                .acknowledged()
                .await
                .unwrap()
                .resources_list_changed,
            Some(true)
        );
        let graceful_id = graceful.id().clone();
        let result = graceful.wait().await.unwrap();
        assert_eq!(result.meta.subscription_id, graceful_id);

        let mut abrupt = client
            .listen_subscriptions(SubscriptionFilter {
                prompts_list_changed: Some(true),
                ..Default::default()
            })
            .await
            .unwrap();
        assert_eq!(
            abrupt.acknowledged().await.unwrap().prompts_list_changed,
            Some(true)
        );
        let error = tokio::time::timeout(Duration::from_secs(2), abrupt.wait())
            .await
            .expect("abrupt close should not leave the subscription pending")
            .unwrap_err();
        assert!(
            error
                .to_string()
                .contains("closed the response stream before the final reply")
        );

        for (resource, expected) in [
            (
                "before-ack",
                "subscription notification arrived before acknowledgment",
            ),
            (
                "wrong-id",
                "subscription notification carried a missing or mismatched subscription ID",
            ),
        ] {
            let invalid = client
                .listen_subscriptions(SubscriptionFilter {
                    resource_subscriptions: Some(vec![resource.to_string()]),
                    ..Default::default()
                })
                .await
                .unwrap();
            let error = tokio::time::timeout(Duration::from_secs(2), invalid.wait())
                .await
                .expect("protocol violation should end the subscription")
                .unwrap_err();
            assert!(error.to_string().contains(expected), "{error}");
        }

        client.shutdown().await.unwrap();
        server.abort();
    }

    #[tokio::test]
    async fn final_client_refreshes_headers_after_stale_schema_rejection() {
        let state = StaleSchemaState::default();
        let app = Router::new()
            .route("/", post(stale_schema_endpoint))
            .with_state(state.clone());
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        let client = McpClient::builder()
            .protocol_support(tower_mcp::ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect_simple(HttpClientTransport::new(url))
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();
        client.list_tools().await.unwrap();

        let result = client
            .call_tool("changing-tool", serde_json::json!({"region": "us-west1"}))
            .await
            .unwrap();
        assert_eq!(result.first_text(), Some("fresh headers"));
        assert_eq!(state.list_calls.load(Ordering::SeqCst), 2);
        assert_eq!(state.tool_calls.load(Ordering::SeqCst), 2);
        assert_eq!(
            *state.mirrored_headers.lock().unwrap(),
            [(true, false), (false, true)]
        );

        server.abort();
    }

    /// A 404 on a 2026-07-28 request carries no session meaning: the server
    /// answers an unknown method with 404 and -32601, and that must surface
    /// as method-not-found rather than start a re-initialize (#1556).
    #[tokio::test]
    async fn final_unknown_method_404_is_method_not_found_not_session_expiry() {
        let app = Router::new()
            .route("/", post(stale_schema_endpoint))
            .with_state(StaleSchemaState::default());
        let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
        let url = format!("http://{}", listener.local_addr().unwrap());
        let server = tokio::spawn(async move {
            axum::serve(listener, app).await.unwrap();
        });

        let client = McpClient::builder()
            .protocol_support(tower_mcp::ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect_simple(HttpClientTransport::new(url))
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        let error = tokio::time::timeout(Duration::from_secs(5), client.list_resources())
            .await
            .expect("list_resources hung")
            .expect_err("the unknown method must fail");
        match &error {
            tower_mcp::Error::JsonRpc(rpc) => assert_eq!(rpc.code, -32601, "{error:?}"),
            other => panic!("expected method-not-found, got: {other:?}"),
        }

        tokio::time::timeout(Duration::from_secs(5), client.list_tools())
            .await
            .expect("list_tools after the 404 hung")
            .expect("the transport must stay open after an in-band 404");

        server.abort();
    }

    /// With no session to expire, a bare 404 on a 2026-07-28 request still
    /// means the endpoint is gone and closes the transport (#1553, #1556).
    #[tokio::test]
    async fn final_bare_404_still_closes_the_transport() {
        let url = spawn_raw_server(|req| {
            if raw_is(req, "server/discover") {
                let body = format!(
                    r#"{{"jsonrpc":"2.0","id":{},"result":{{"resultType":"complete","supportedVersions":["2026-07-28"],"capabilities":{{}},"ttlMs":0,"cacheScope":"private"}}}}"#,
                    raw_request_id(req)
                );
                raw_response("200 OK", RAW_JSON, &body)
            } else {
                raw_response("404 Not Found", "", "")
            }
        })
        .await;

        let client = McpClient::builder()
            .protocol_support(tower_mcp::ProtocolSupport::try_new(["2026-07-28"]).unwrap())
            .connect_simple(HttpClientTransport::with_config(url, raw_client_config()))
            .await
            .unwrap();
        client.discover("test-client", "1.0.0").await.unwrap();

        let error = tokio::time::timeout(Duration::from_secs(5), client.list_tools())
            .await
            .expect("list_tools hung")
            .expect_err("the 404 must fail the request");
        assert!(
            !matches!(error, tower_mcp::Error::SessionExpired),
            "a sessionless 404 is not session expiry: {error:?}"
        );

        tokio::time::timeout(Duration::from_secs(3), async {
            // The closed flag reaches the client after the failed request's
            // error, so poll until a call reports the closed connection.
            while !client
                .list_tools()
                .await
                .is_err_and(|error| error.to_string().contains("Connection closed"))
            {
                tokio::time::sleep(Duration::from_millis(10)).await;
            }
        })
        .await
        .expect("a sessionless 404 must keep closing the transport");
    }

    /// tools/list works without initialize or session, just protocol version header.
    #[tokio::test]
    async fn test_stateless_tools_list() {
        let (url, _server) = start_stateless_server().await;
        let client = reqwest::Client::new();

        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("mcp-protocol-version", "2025-11-25")
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "tools/list",
                    "params": {}
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        assert_eq!(resp.status(), 200);
        // Should echo back the protocol version
        assert_eq!(
            resp.headers()
                .get("mcp-protocol-version")
                .unwrap()
                .to_str()
                .unwrap(),
            "2025-11-25"
        );
        // Should NOT have a session ID
        assert!(resp.headers().get("mcp-session-id").is_none());

        let body: serde_json::Value = resp.json().await.unwrap();
        let tools = body["result"]["tools"].as_array().unwrap();
        assert!(tools.len() >= 2, "Should list tools without session");
    }

    /// tools/call works in stateless mode.
    #[tokio::test]
    async fn test_stateless_tools_call() {
        let (url, _server) = start_stateless_server().await;
        let client = reqwest::Client::new();

        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("mcp-protocol-version", "2025-11-25")
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "tools/call",
                    "params": {
                        "name": "echo",
                        "arguments": { "message": "stateless!" }
                    }
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        assert_eq!(resp.status(), 200);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(
            body["result"]["content"][0]["text"].as_str().unwrap(),
            "stateless!"
        );
    }

    /// Unsupported protocol version returns SEP-2575 error code -32022
    /// with the spec-shape data: `{ supported: [...], requested: "..." }`.
    /// (SEP-1442 draft used -32000 / `supportedVersions`; both were wrong.)
    #[tokio::test]
    async fn test_stateless_unsupported_version() {
        let (url, _server) = start_stateless_server().await;
        let client = reqwest::Client::new();

        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("mcp-protocol-version", "1999-01-01")
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "tools/list",
                    "params": {}
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        assert_eq!(resp.status(), 200);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["error"]["code"].as_i64().unwrap(), -32022);
        assert!(
            body["error"]["data"]["supported"].is_array(),
            "spec data field is 'supported': {body}"
        );
        assert_eq!(body["error"]["data"]["requested"], "1999-01-01");
    }

    /// Protocol version in _meta field (body) works as alternative to header.
    #[tokio::test]
    async fn test_stateless_version_in_meta() {
        let (url, _server) = start_stateless_server().await;
        let client = reqwest::Client::new();

        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            // No mcp-protocol-version header!
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "tools/list",
                    "params": {
                        "_meta": {
                            "modelcontextprotocol.io/mcpProtocolVersion": "2025-11-25"
                        }
                    }
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        assert_eq!(resp.status(), 200);
        let body: serde_json::Value = resp.json().await.unwrap();
        assert!(body["result"]["tools"].is_array());
    }

    /// Stateful clients (with session ID) still work alongside stateless.
    #[tokio::test]
    async fn test_stateless_mixed_mode() {
        let (url, _server) = start_stateless_server().await;
        let client = reqwest::Client::new();

        // Stateful: initialize and get session
        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json, text/event-stream")
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "initialize",
                    "params": {
                        "protocolVersion": "2025-11-25",
                        "capabilities": {},
                        "clientInfo": { "name": "test", "version": "1.0" }
                    }
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        assert_eq!(resp.status(), 200);
        let session_id = resp
            .headers()
            .get("mcp-session-id")
            .unwrap()
            .to_str()
            .unwrap()
            .to_string();

        // Send initialized notification
        client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("mcp-session-id", &session_id)
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "method": "notifications/initialized"
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        // Stateful request with session ID
        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("mcp-session-id", &session_id)
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 2,
                    "method": "tools/list",
                    "params": {}
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        let body: serde_json::Value = resp.json().await.unwrap();
        assert!(body["result"]["tools"].is_array());

        // Stateless request on same server (no session ID, protocol version header)
        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("mcp-protocol-version", "2025-11-25")
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 3,
                    "method": "tools/call",
                    "params": {
                        "name": "add",
                        "arguments": { "a": 10, "b": 20 }
                    }
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        let body: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(body["result"]["content"][0]["text"].as_str().unwrap(), "30");
    }

    /// server/discover works without any session or protocol version.
    #[tokio::test]
    async fn test_stateless_discover() {
        let (url, _server) = start_stateless_server().await;
        let client = reqwest::Client::new();

        // server/discover should work even without protocol version header
        // (it's allowed before initialization per session.rs)
        let resp = client
            .post(&url)
            .header("Content-Type", "application/json")
            .header("Accept", "application/json")
            .header("mcp-protocol-version", "2025-11-25")
            .body(
                serde_json::json!({
                    "jsonrpc": "2.0",
                    "id": 1,
                    "method": "server/discover",
                    "params": {}
                })
                .to_string(),
            )
            .send()
            .await
            .unwrap();

        assert_eq!(resp.status(), 200);
        let body: serde_json::Value = resp.json().await.unwrap();
        let result = &body["result"];
        assert!(result["supportedVersions"].is_array());
        assert!(result["_meta"]["io.modelcontextprotocol/serverInfo"]["name"].is_string());
        assert!(result["capabilities"].is_object());
    }
}

// ---------------------------------------------------------------------------
// Session recovery (#762) -- automatic re-initialization on session expiry
// ---------------------------------------------------------------------------

/// Start a server that returns a handle for session management.
async fn start_server_with_handle() -> (
    String,
    tower_mcp::transport::http::SessionHandle,
    tokio::task::JoinHandle<()>,
) {
    let router = test_router();
    let transport = HttpTransport::new(router).disable_origin_validation();
    let (axum_router, handle) = transport.into_router_with_handle();

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let url = format!("http://127.0.0.1:{}", addr.port());

    let server = tokio::spawn(async move {
        axum::serve(listener, axum_router).await.unwrap();
    });

    tokio::time::sleep(Duration::from_millis(50)).await;
    (url, handle, server)
}

/// Verify that the client automatically recovers from session expiry.
#[tokio::test]
async fn test_session_recovery_after_expiry() {
    let (url, handle, _server) = start_server_with_handle().await;

    let transport = HttpClientTransport::new(&url);
    let client = McpClient::connect(transport).await.unwrap();
    let init_result = client.initialize("test-recovery", "1.0.0").await.unwrap();
    assert_eq!(init_result.server_info.name, "test-http-server");

    // Verify tools work
    let tools = client.list_tools().await.unwrap();
    assert_eq!(tools.tools.len(), 2);

    // Terminate the session to simulate expiry
    let sessions = handle.list_sessions().await;
    assert_eq!(sessions.len(), 1);
    let terminated = handle.terminate_session(&sessions[0].id).await;
    assert!(terminated, "Session should have been terminated");

    // The next request should fail with session expired, but auto-recover
    let tools = client.list_tools().await.unwrap();
    assert_eq!(tools.tools.len(), 2, "Should recover and list tools again");

    // Verify a new session was created
    let sessions = handle.list_sessions().await;
    assert_eq!(sessions.len(), 1, "Should have exactly one new session");
}

/// Verify that session recovery is disabled when configured.
#[tokio::test]
async fn test_session_recovery_disabled() {
    let (url, handle, _server) = start_server_with_handle().await;

    let transport = HttpClientTransport::new(&url).disable_session_recovery();
    let client = McpClient::connect(transport).await.unwrap();
    client
        .initialize("test-no-recovery", "1.0.0")
        .await
        .unwrap();

    // Terminate the session
    let sessions = handle.list_sessions().await;
    handle.terminate_session(&sessions[0].id).await;

    // Without recovery, the next request should fail
    let result = client.list_tools().await;
    assert!(result.is_err(), "Should fail without session recovery");
}

/// #967 regression: `notifications/initialized` must not race the first
/// request after `initialize()`.
///
/// Post-session request POSTs are spawned in background tasks; notification
/// POSTs must be awaited inline so a strict server (`strict_initialization`
/// defaults to true) processes them before the next request arrives. The
/// race depends on network timing, so an in-process server never exhibits
/// it; this test routes the client through a TCP proxy that delays any
/// connection carrying `notifications/initialized` by 200 ms, forcing the
/// reordering. Before the fix the subsequent `tools/list` deterministically
/// failed with -32600; after it, `initialize()` does not return until the
/// notification is acknowledged, so ordering holds.
#[tokio::test]
async fn initialized_notification_ordering_under_strict_server() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let (url, _server) = start_server().await;
    let upstream = url.strip_prefix("http://").unwrap().to_string();

    // Delaying proxy: hold back the connection that carries the
    // initialized notification; pass everything else straight through.
    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let proxy_addr = listener.local_addr().unwrap();
    tokio::spawn(async move {
        loop {
            let Ok((mut client_conn, _)) = listener.accept().await else {
                break;
            };
            let upstream = upstream.clone();
            tokio::spawn(async move {
                let mut first = vec![0u8; 16 * 1024];
                let n = match client_conn.read(&mut first).await {
                    Ok(0) | Err(_) => return,
                    Ok(n) => n,
                };
                if String::from_utf8_lossy(&first[..n]).contains("notifications/initialized") {
                    tokio::time::sleep(Duration::from_millis(200)).await;
                }
                let Ok(mut up) = tokio::net::TcpStream::connect(&upstream).await else {
                    return;
                };
                if up.write_all(&first[..n]).await.is_err() {
                    return;
                }
                let _ = tokio::io::copy_bidirectional(&mut client_conn, &mut up).await;
            });
        }
    });

    let proxied_url = format!("http://{proxy_addr}");
    let transport = HttpClientTransport::new(proxied_url);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("race-test", "1.0.0").await.unwrap();
    let tools = client
        .list_tools()
        .await
        .expect("tools/list must not be rejected: initialized must be acknowledged first");
    assert!(!tools.tools.is_empty());
}

/// #983 regression: a 404 on the very first request (no session yet) is a
/// wrong endpoint path, not an expired session. It must surface as a
/// transport error naming the status and URL, never as SessionExpired.
#[tokio::test]
async fn pre_session_404_reports_endpoint_not_found() {
    let (url, _server) = start_server().await;
    // The MCP endpoint of the test server is the root path; /nope is a 404.
    let transport = HttpClientTransport::new(format!("{url}/nope"));
    let client = McpClient::connect(transport).await.unwrap();
    let err = client
        .initialize("wrong-path", "1.0.0")
        .await
        .expect_err("initialize against a wrong path must fail");
    let msg = err.to_string();
    assert!(
        msg.contains("404") && msg.contains("/nope") && msg.contains("endpoint"),
        "expected an endpoint-not-found transport error, got: {msg}"
    );
    assert!(
        !msg.to_lowercase().contains("session"),
        "must not be reported as a session error, got: {msg}"
    );
}

/// Read one full HTTP/1.1 request (headers + Content-Length body) from a raw
/// connection. Returns the whole request as a string, or `None` on EOF.
#[cfg(test)]
async fn read_http_request(stream: &mut tokio::net::TcpStream) -> Option<String> {
    use tokio::io::AsyncReadExt;
    let mut buf = Vec::new();
    let mut tmp = [0u8; 4096];
    loop {
        if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
            let headers = String::from_utf8_lossy(&buf[..pos]).to_string();
            let content_length = headers
                .lines()
                .find_map(|l| {
                    let (k, v) = l.split_once(':')?;
                    k.trim()
                        .eq_ignore_ascii_case("content-length")
                        .then(|| v.trim().parse::<usize>().ok())
                        .flatten()
                })
                .unwrap_or(0);
            let need = pos + 4 + content_length;
            while buf.len() < need {
                let n = stream.read(&mut tmp).await.ok()?;
                if n == 0 {
                    break;
                }
                buf.extend_from_slice(&tmp[..n]);
            }
            return Some(String::from_utf8_lossy(&buf).to_string());
        }
        let n = stream.read(&mut tmp).await.ok()?;
        if n == 0 {
            return (!buf.is_empty()).then(|| String::from_utf8_lossy(&buf).to_string());
        }
        buf.extend_from_slice(&tmp[..n]);
    }
}

/// Regression: a post-session request whose background POST fails before
/// delivering a response must wake the awaiting caller with an error, never
/// hang it.
///
/// After the session is established, request POSTs are spawned in a background
/// task so the message loop can keep servicing the SSE stream. That task used
/// to drop a handful of failure modes on the floor (network error, timeout,
/// HTTP error with a non-JSON body, empty body, response stream closed with no
/// data), leaving the caller parked on the request id forever. This exercises
/// the empty-body dead-end: the raw server answers `tools/list` with a `200`
/// and no body. `Connection: close` forces a fresh connection per request so
/// each is intercepted deterministically.
#[tokio::test]
async fn post_session_request_failure_wakes_caller() {
    use tokio::io::AsyncWriteExt;

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                break;
            };
            tokio::spawn(async move {
                let Some(req) = read_http_request(&mut stream).await else {
                    return;
                };
                let response = if req.contains("\"method\":\"initialize\"") {
                    let body = serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "result": {
                            "protocolVersion": "2025-11-25",
                            "capabilities": {},
                            "serverInfo": {"name": "raw", "version": "0"}
                        }
                    })
                    .to_string();
                    format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
                         mcp-session-id: raw-session\r\nmcp-protocol-version: 2025-11-25\r\n\
                         Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                        body.len(),
                        body
                    )
                } else if req.contains("notifications/initialized") {
                    "HTTP/1.1 202 Accepted\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"
                        .to_string()
                } else {
                    // tools/list and anything else: a 2xx with an empty body,
                    // the dead-end that used to hang the caller.
                    "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
                     Content-Length: 0\r\nConnection: close\r\n\r\n"
                        .to_string()
                };
                let _ = stream.write_all(response.as_bytes()).await;
                let _ = stream.flush().await;
            });
        }
    });

    let url = format!("http://{addr}");
    let config = HttpClientConfig {
        auto_sse: false,
        request_timeout: Duration::from_secs(5),
        ..Default::default()
    };
    let transport = HttpClientTransport::with_config(url, config);
    let client = McpClient::connect(transport).await.unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    // The bug made this future never resolve; bound it so the test fails as a
    // timeout instead of hanging the whole suite.
    let result = tokio::time::timeout(Duration::from_secs(3), client.list_tools()).await;
    let result = result.expect(
        "list_tools hung: the failed background POST never woke the caller (the bug this guards)",
    );
    assert!(
        result.is_err(),
        "an empty-body response must surface as an error, got: {result:?}"
    );
}

/// Regression: a server that stalls the `notifications/initialized` POST must
/// not freeze the client for the full `request_timeout`.
///
/// The notification is awaited inline to keep it ordered ahead of the first
/// request (#967), which blocks the single message loop for the duration.
/// `notification_timeout` bounds that block independently (#999). Here the raw
/// server reads the notification POST and never answers it; with a short
/// `notification_timeout` the client abandons it quickly.
///
/// Since #1174 the abandoned notification is also an `initialize()` error
/// rather than a silent success: the handshake did not complete, and a strict
/// server would reject every later request with -32600. The caller retries
/// initialization; it no longer proceeds into a poisoned session. The bounded
/// behavior this test originally guarded is asserted the same way, through
/// the outer timeout.
#[tokio::test]
async fn stalled_initialized_notification_does_not_freeze_client() {
    use tokio::io::AsyncWriteExt;

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();

    tokio::spawn(async move {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                break;
            };
            tokio::spawn(async move {
                let Some(req) = read_http_request(&mut stream).await else {
                    return;
                };
                if req.contains("\"method\":\"initialize\"") {
                    let body = serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": 1,
                        "result": {
                            "protocolVersion": "2025-11-25",
                            "capabilities": {},
                            "serverInfo": {"name": "raw", "version": "0"}
                        }
                    })
                    .to_string();
                    let resp = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
                         mcp-session-id: raw-session\r\nmcp-protocol-version: 2025-11-25\r\n\
                         Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                        body.len(),
                        body
                    );
                    let _ = stream.write_all(resp.as_bytes()).await;
                } else if req.contains("notifications/initialized") {
                    // Stall: read the POST but never answer it. The client must
                    // give up after notification_timeout, not request_timeout.
                    tokio::time::sleep(Duration::from_secs(3600)).await;
                } else {
                    // tools/list: respond normally.
                    let body = serde_json::json!({
                        "jsonrpc": "2.0",
                        "id": 2,
                        "result": {"tools": [{"name": "echo", "inputSchema": {"type": "object"}}]}
                    })
                    .to_string();
                    let resp = format!(
                        "HTTP/1.1 200 OK\r\nContent-Type: application/json\r\n\
                         Content-Length: {}\r\nConnection: close\r\n\r\n{}",
                        body.len(),
                        body
                    );
                    let _ = stream.write_all(resp.as_bytes()).await;
                }
                let _ = stream.flush().await;
            });
        }
    });

    let url = format!("http://{addr}");
    let config = HttpClientConfig {
        auto_sse: false,
        request_timeout: Duration::from_secs(20),
        notification_timeout: Duration::from_millis(300),
        ..Default::default()
    };
    let transport = HttpClientTransport::with_config(url, config);
    let client = McpClient::connect(transport).await.unwrap();

    // The stalled notification is abandoned after ~300ms, so this resolves
    // quickly. Before #999 it blocked for the full 20s request_timeout; bound
    // it at 8s so a freeze regression fails as a timeout rather than hanging.
    let error = tokio::time::timeout(
        Duration::from_secs(8),
        client.initialize("raw-client", "1.0.0"),
    )
    .await
    .expect("initialize blocked behind the stalled notification (the bug this guards)")
    .expect_err("a stalled notifications/initialized must fail initialize, not be swallowed");

    assert!(
        error
            .to_string()
            .contains("failed to deliver notifications/initialized"),
        "error should name the handshake step, got: {error}"
    );
}

// ---------------------------------------------------------------------------
// Responses that carry no reply to the request (#1465)
// ---------------------------------------------------------------------------

const RAW_JSON: &str = "Content-Type: application/json\r\n";

/// A raw HTTP/1.1 server that answers every request with `respond(request)`,
/// one connection per request, so malformed replies reach the client exactly
/// as written.
async fn spawn_raw_server<F>(respond: F) -> String
where
    F: Fn(&str) -> String + Send + Sync + 'static,
{
    use tokio::io::AsyncWriteExt;

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let respond = Arc::new(respond);
    tokio::spawn(async move {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                break;
            };
            let respond = respond.clone();
            tokio::spawn(async move {
                let Some(req) = read_http_request(&mut stream).await else {
                    return;
                };
                let _ = stream.write_all(respond(&req).as_bytes()).await;
                let _ = stream.flush().await;
            });
        }
    });
    format!("http://{addr}")
}

fn raw_response(status: &str, headers: &str, body: &str) -> String {
    format!(
        "HTTP/1.1 {status}\r\n{headers}Content-Length: {}\r\nConnection: close\r\n\r\n{body}",
        body.len()
    )
}

/// A response with no declared length: valid only paired with
/// `Connection: close`, which tells the client to read the body until the
/// server closes the socket rather than trusting a `Content-Length`.
fn raw_response_no_length(status: &str, headers: &str, body: &str) -> String {
    format!("HTTP/1.1 {status}\r\n{headers}Connection: close\r\n\r\n{body}")
}

/// The JSON-RPC id of a raw HTTP request, as serialized JSON.
fn raw_request_id(req: &str) -> String {
    req.split_once("\r\n\r\n")
        .and_then(|(_, body)| serde_json::from_str::<serde_json::Value>(body).ok())
        .and_then(|value| value.get("id").cloned())
        .unwrap_or(serde_json::Value::Null)
        .to_string()
}

fn raw_is(req: &str, method: &str) -> bool {
    req.contains(&format!("\"method\":\"{method}\""))
}

/// The session-establishing reply to `initialize`.
fn raw_initialize_ok(req: &str) -> String {
    let body = format!(
        r#"{{"jsonrpc":"2.0","id":{},"result":{{"protocolVersion":"2025-11-25","capabilities":{{}},"serverInfo":{{"name":"raw","version":"0"}}}}}}"#,
        raw_request_id(req)
    );
    raw_response(
        "200 OK",
        &format!("{RAW_JSON}mcp-session-id: raw-session\r\nmcp-protocol-version: 2025-11-25\r\n"),
        &body,
    )
}

fn raw_client_config() -> HttpClientConfig {
    HttpClientConfig {
        auto_sse: false,
        request_timeout: Duration::from_secs(5),
        ..Default::default()
    }
}

/// On an established session, each response below used to leave `list_tools`
/// parked forever. It must fail instead, and the transport must stay usable:
/// a bad reply to one request is not a broken connection.
#[tokio::test]
async fn session_request_without_a_reply_fails_and_client_stays_usable() {
    // (case, status, headers, body); `{id}` in the body becomes the request id.
    let cases = [
        ("202 Accepted", "202 Accepted", "", "", None),
        ("empty JSON object", "200 OK", RAW_JSON, "{}", None),
        ("non-JSON body", "200 OK", RAW_JSON, "hello", None),
        (
            "error with a foreign id",
            "400 Bad Request",
            RAW_JSON,
            r#"{"jsonrpc":"2.0","id":"server-error","error":{"code":-32600,"message":"rejected by gateway"}}"#,
            Some("rejected by gateway"),
        ),
        (
            "error with the request id",
            "400 Bad Request",
            RAW_JSON,
            r#"{"jsonrpc":"2.0","id":{id},"error":{"code":-32600,"message":"rejected by server"}}"#,
            Some("rejected by server"),
        ),
    ];

    for (case, status, headers, body, expected_message) in cases {
        let url = spawn_raw_server(move |req| {
            if raw_is(req, "initialize") {
                raw_initialize_ok(req)
            } else if raw_is(req, "notifications/initialized") {
                raw_response("202 Accepted", "", "")
            } else if raw_is(req, "tools/list") {
                raw_response(status, headers, &body.replace("{id}", &raw_request_id(req)))
            } else {
                let reply = format!(
                    r#"{{"jsonrpc":"2.0","id":{},"result":{{}}}}"#,
                    raw_request_id(req)
                );
                raw_response("200 OK", RAW_JSON, &reply)
            }
        })
        .await;

        let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
            .await
            .unwrap();
        client.initialize("raw-client", "1.0.0").await.unwrap();

        let result = tokio::time::timeout(Duration::from_secs(3), client.list_tools())
            .await
            .unwrap_or_else(|_| panic!("{case}: list_tools hung"));
        let error = result.expect_err(case).to_string();
        if let Some(expected) = expected_message {
            assert!(
                error.contains(expected),
                "{case}: the server's error should surface, got: {error}"
            );
        }

        tokio::time::timeout(Duration::from_secs(3), client.ping())
            .await
            .unwrap_or_else(|_| panic!("{case}: ping after the bad reply hung"))
            .unwrap_or_else(|error| panic!("{case}: client unusable after the bad reply: {error}"));
    }
}

/// Before a session exists, requests go through the synchronous path, which
/// had the same dead ends for `initialize`.
#[tokio::test]
async fn pre_session_request_without_a_reply_fails() {
    let cases = [
        ("202 Accepted", "202 Accepted", "", ""),
        ("empty JSON object", "200 OK", RAW_JSON, "{}"),
        ("empty body", "200 OK", RAW_JSON, ""),
    ];

    for (case, status, headers, body) in cases {
        let url = spawn_raw_server(move |_| raw_response(status, headers, body)).await;
        let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
            .await
            .unwrap();

        let result = tokio::time::timeout(
            Duration::from_secs(3),
            client.initialize("raw-client", "1.0.0"),
        )
        .await
        .unwrap_or_else(|_| panic!("{case}: initialize hung"));
        assert!(result.is_err(), "{case}: expected an error, got {result:?}");
    }
}

/// Gateways and the Python SDK reject `server/discover` with a JSON-RPC error
/// whose id is a literal string rather than the request's id.
#[cfg(feature = "stateless")]
#[tokio::test]
async fn discover_rejected_with_a_foreign_error_id_fails() {
    let url = spawn_raw_server(|_| {
        raw_response(
            "400 Bad Request",
            RAW_JSON,
            r#"{"jsonrpc":"2.0","id":"server-error","error":{"code":-32600,"message":"discover not supported"}}"#,
        )
    })
    .await;
    let client = McpClient::builder()
        .protocol_support(tower_mcp::ProtocolSupport::try_new(["2026-07-28"]).unwrap())
        .connect(
            HttpClientTransport::with_config(url, raw_client_config()),
            NotificationHandler::new(),
        )
        .await
        .unwrap();

    let result = tokio::time::timeout(
        Duration::from_secs(3),
        client.discover("raw-client", "1.0.0"),
    )
    .await
    .expect("discover hung on an error with a foreign id");
    let error = result.expect_err("discover should fail").to_string();
    assert!(
        error.contains("discover not supported"),
        "the server's error should surface, got: {error}"
    );
}

// ---------------------------------------------------------------------------
// Replies to server requests are not client requests (#1466)
// ---------------------------------------------------------------------------

/// Regression: the client's reply to a server-initiated request used to be
/// tracked exactly like one of the client's own requests, keyed by id. Server
/// and client request ids are independent sequences that both start at 1, so
/// a server request pushed while a client request is in flight can collide
/// with it. Before the fix, a failed reply POST injected an error frame
/// carrying that shared id, which incorrectly failed the client's own
/// still-pending request.
///
/// Here the raw server pushes a `ping` on the `tools/list` SSE stream using
/// the same id as the in-flight `tools/list` request, then rejects the
/// client's reply POST with a `500`. The real `tools/list` result is
/// withheld on the same connection until the rejected reply POST has been
/// fully handled, so a spurious error frame reaching the caller first would
/// prove the bug; the fix leaves the caller waiting for the genuine
/// completion instead.
#[tokio::test]
async fn server_request_colliding_with_client_id_reply_failure_does_not_fail_client_request() {
    colliding_reply_rejection_case(|_| raw_response("500 Internal Server Error", "", "")).await;
}

/// As above, but the reply POST is rejected with a JSON-RPC error body that
/// echoes the server request's id, which equals the client request's id. The
/// body must not be forwarded as if it answered the client's request.
#[tokio::test]
async fn reply_rejected_with_an_error_body_does_not_fail_the_colliding_client_request() {
    colliding_reply_rejection_case(|req| {
        let body = format!(
            r#"{{"jsonrpc":"2.0","id":{},"error":{{"code":-32600,"message":"reply rejected"}}}}"#,
            raw_request_id(req)
        );
        raw_response("400 Bad Request", RAW_JSON, &body)
    })
    .await;
}

async fn colliding_reply_rejection_case(reject_reply: fn(&str) -> String) {
    use tokio::io::AsyncWriteExt;

    fn sse_chunk(data: &str) -> String {
        format!("{:x}\r\n{}\r\n", data.len(), data)
    }

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let reply_handled = Arc::new(tokio::sync::Notify::new());

    {
        let reply_handled = reply_handled.clone();
        tokio::spawn(async move {
            loop {
                let Ok((mut stream, _)) = listener.accept().await else {
                    break;
                };
                let reply_handled = reply_handled.clone();
                tokio::spawn(async move {
                    let Some(req) = read_http_request(&mut stream).await else {
                        return;
                    };
                    if raw_is(&req, "initialize") {
                        let _ = stream.write_all(raw_initialize_ok(&req).as_bytes()).await;
                        let _ = stream.flush().await;
                    } else if raw_is(&req, "notifications/initialized") {
                        let _ = stream
                            .write_all(raw_response("202 Accepted", "", "").as_bytes())
                            .await;
                        let _ = stream.flush().await;
                    } else if raw_is(&req, "tools/list") {
                        let id = raw_request_id(&req);
                        let header = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
                                       Transfer-Encoding: chunked\r\nConnection: close\r\n\r\n";
                        let _ = stream.write_all(header.as_bytes()).await;

                        // Push a server-initiated `ping` sharing the client's
                        // own request id.
                        let ping = format!(
                            "data: {{\"jsonrpc\":\"2.0\",\"id\":{id},\"method\":\"ping\",\"params\":{{}}}}\n\n"
                        );
                        let _ = stream.write_all(sse_chunk(&ping).as_bytes()).await;
                        let _ = stream.flush().await;

                        // Withhold the real result until the client's reply
                        // POST below has been received and rejected. If the
                        // bug regresses, its spurious error frame reaches the
                        // message loop first.
                        reply_handled.notified().await;

                        let result = format!(
                            "data: {{\"jsonrpc\":\"2.0\",\"id\":{id},\"result\":{{\"tools\":[]}}}}\n\n"
                        );
                        let _ = stream.write_all(sse_chunk(&result).as_bytes()).await;
                        let _ = stream.write_all(b"0\r\n\r\n").await;
                        let _ = stream.flush().await;
                    } else {
                        // The client's reply to the pushed `ping`: an id with
                        // no method. Reject it, then release the withheld
                        // `tools/list` completion.
                        let response = reject_reply(&req);
                        let _ = stream.write_all(response.as_bytes()).await;
                        let _ = stream.flush().await;
                        reply_handled.notify_one();
                    }
                });
            }
        });
    }

    let url = format!("http://{addr}");
    let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    let result = tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("list_tools hung");
    assert!(
        result.is_ok(),
        "the client's own request must complete normally despite the rejected reply POST, got: {result:?}"
    );
}

// ---------------------------------------------------------------------------
// Bounded response bodies (#1469)
// ---------------------------------------------------------------------------

/// A JSON-RPC response body for `id`, padded with an ignored `_pad` field so
/// its total length is exactly `limit` bytes when possible, or as close to
/// it as a non-negative pad allows. Padding a `tools/list` result keeps the
/// body valid: `_pad` is not a recognized field and is ignored.
fn padded_tools_result(id: &str, limit: usize) -> String {
    let unpadded = format!(r#"{{"jsonrpc":"2.0","id":{id},"result":{{"tools":[],"_pad":""}}}}"#);
    let pad_len = limit.saturating_sub(unpadded.len());
    format!(
        r#"{{"jsonrpc":"2.0","id":{id},"result":{{"tools":[],"_pad":"{}"}}}}"#,
        "x".repeat(pad_len)
    )
}

/// On an established session, a `tools/list` response whose `Content-Length`
/// declares it larger than `max_response_body_size` must fail that request
/// with a transport error naming the limit, checked before any byte of the
/// body is read. The connection itself is fine, so a following request must
/// still succeed.
#[tokio::test]
async fn session_response_oversized_with_content_length_fails_request() {
    let limit = 256;
    let url = spawn_raw_server(move |req| {
        if raw_is(req, "initialize") {
            raw_initialize_ok(req)
        } else if raw_is(req, "notifications/initialized") {
            raw_response("202 Accepted", "", "")
        } else if raw_is(req, "tools/list") {
            let body = padded_tools_result(&raw_request_id(req), limit * 4);
            raw_response("200 OK", RAW_JSON, &body)
        } else {
            let reply = format!(
                r#"{{"jsonrpc":"2.0","id":{},"result":{{}}}}"#,
                raw_request_id(req)
            );
            raw_response("200 OK", RAW_JSON, &reply)
        }
    })
    .await;

    let config = HttpClientConfig {
        max_response_body_size: limit,
        ..raw_client_config()
    };
    let client = McpClient::connect(HttpClientTransport::with_config(url, config))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    let result = tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("list_tools hung on an oversized response instead of failing");
    let error = result
        .expect_err("an oversized response with Content-Length should fail the request")
        .to_string();
    assert!(
        error.contains(&limit.to_string()),
        "error should mention the {limit}-byte limit, got: {error}"
    );

    tokio::time::timeout(Duration::from_secs(3), client.ping())
        .await
        .expect("ping after the oversized reply hung")
        .expect("client should stay usable after an oversized reply");
}

/// As above, but the server declares no length at all (`Connection: close`,
/// read until the socket closes), so the limit must be enforced by counting
/// bytes while streaming rather than by inspecting `Content-Length`.
#[tokio::test]
async fn session_response_oversized_without_content_length_fails_request() {
    let limit = 256;
    let url = spawn_raw_server(move |req| {
        if raw_is(req, "initialize") {
            raw_initialize_ok(req)
        } else if raw_is(req, "notifications/initialized") {
            raw_response("202 Accepted", "", "")
        } else if raw_is(req, "tools/list") {
            let body = padded_tools_result(&raw_request_id(req), limit * 4);
            raw_response_no_length("200 OK", RAW_JSON, &body)
        } else {
            let reply = format!(
                r#"{{"jsonrpc":"2.0","id":{},"result":{{}}}}"#,
                raw_request_id(req)
            );
            raw_response("200 OK", RAW_JSON, &reply)
        }
    })
    .await;

    let config = HttpClientConfig {
        max_response_body_size: limit,
        ..raw_client_config()
    };
    let client = McpClient::connect(HttpClientTransport::with_config(url, config))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    let result = tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("list_tools hung on a length-less oversized response instead of failing");
    let error = result
        .expect_err("an oversized response with no declared length should fail the request")
        .to_string();
    assert!(
        error.contains(&limit.to_string()),
        "error should mention the {limit}-byte limit, got: {error}"
    );

    tokio::time::timeout(Duration::from_secs(3), client.ping())
        .await
        .expect("ping after the oversized reply hung")
        .expect("client should stay usable after an oversized reply");
}

/// A response landing exactly at the limit is not oversized and must still
/// parse normally.
#[tokio::test]
async fn session_response_at_exact_limit_still_parses() {
    let limit = 256;
    let url = spawn_raw_server(move |req| {
        if raw_is(req, "initialize") {
            raw_initialize_ok(req)
        } else if raw_is(req, "notifications/initialized") {
            raw_response("202 Accepted", "", "")
        } else if raw_is(req, "tools/list") {
            let body = padded_tools_result(&raw_request_id(req), limit);
            assert_eq!(
                body.len(),
                limit,
                "test setup: body must land exactly at the limit"
            );
            raw_response("200 OK", RAW_JSON, &body)
        } else {
            let reply = format!(
                r#"{{"jsonrpc":"2.0","id":{},"result":{{}}}}"#,
                raw_request_id(req)
            );
            raw_response("200 OK", RAW_JSON, &reply)
        }
    })
    .await;

    let config = HttpClientConfig {
        max_response_body_size: limit,
        ..raw_client_config()
    };
    let client = McpClient::connect(HttpClientTransport::with_config(url, config))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    let result = tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("list_tools hung on an exact-limit response");
    assert!(
        result.is_ok(),
        "a response exactly at the limit should still parse, got: {result:?}"
    );
}

/// Error bodies are capped independently of `max_response_body_size` at a
/// small fixed size and truncated rather than failed: the request must still
/// fail with the HTTP error itself, not a size-limit error, and the oversized
/// body must not appear in full in the surfaced message.
#[tokio::test]
async fn pre_session_oversized_error_body_is_truncated_not_failed_by_size() {
    let huge_body = "x".repeat(200 * 1024); // well over the 64 KiB error-body cap
    let url =
        spawn_raw_server(move |_| raw_response("500 Internal Server Error", RAW_JSON, &huge_body))
            .await;
    let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
        .await
        .unwrap();

    let result = tokio::time::timeout(
        Duration::from_secs(3),
        client.initialize("raw-client", "1.0.0"),
    )
    .await
    .expect("initialize hung on an oversized error body instead of failing");
    let error = result
        .expect_err("initialize should fail with the HTTP error")
        .to_string();
    assert!(
        error.contains("HTTP 500"),
        "the request should fail with the HTTP error, not a size-limit error, got: {error}"
    );
    assert!(
        error.len() < 200 * 1024,
        "the oversized error body should be truncated in the surfaced message, got {} bytes",
        error.len()
    );
}

/// Before a session exists, `initialize`'s response goes through the
/// synchronous path. An oversized response there must fail `initialize`
/// instead of hanging until the request timeout.
#[tokio::test]
async fn pre_session_oversized_initialize_response_fails_without_hanging() {
    let limit = 256;
    let url = spawn_raw_server(move |req| {
        let id = raw_request_id(req);
        let big = "x".repeat(limit * 4);
        let body = format!(
            r#"{{"jsonrpc":"2.0","id":{id},"result":{{"protocolVersion":"2025-11-25","capabilities":{{}},"serverInfo":{{"name":"raw","version":"{big}"}}}}}}"#
        );
        raw_response(
            "200 OK",
            &format!("{RAW_JSON}mcp-session-id: raw-session\r\nmcp-protocol-version: 2025-11-25\r\n"),
            &body,
        )
    })
    .await;

    let config = HttpClientConfig {
        max_response_body_size: limit,
        ..raw_client_config()
    };
    let client = McpClient::connect(HttpClientTransport::with_config(url, config))
        .await
        .unwrap();

    let result = tokio::time::timeout(
        Duration::from_secs(3),
        client.initialize("raw-client", "1.0.0"),
    )
    .await
    .expect("initialize hung on an oversized response instead of failing");
    let error = result
        .expect_err("an oversized initialize response should fail initialize")
        .to_string();
    assert!(
        error.contains(&limit.to_string()),
        "error should mention the {limit}-byte limit, got: {error}"
    );
}

// ---------------------------------------------------------------------------
// Redirect policy (#1475): custom headers and mcp-session-id must not leak
// to a redirect target reqwest's own sensitive-header stripping doesn't
// cover.
// ---------------------------------------------------------------------------

/// A same-origin `307` (same host:port, different path) is transparent: the
/// client follows it and the request still succeeds.
#[tokio::test]
async fn same_origin_redirect_is_followed() {
    let base = Arc::new(std::sync::OnceLock::new());
    let base_for_server = base.clone();
    let redirected_from_root = Arc::new(std::sync::atomic::AtomicBool::new(false));
    let redirected_from_root_clone = redirected_from_root.clone();
    let url = spawn_raw_server(move |req| {
        if req.starts_with("POST / ") {
            redirected_from_root_clone.store(true, std::sync::atomic::Ordering::SeqCst);
            let base: &String = base_for_server
                .get()
                .expect("base url set before first request");
            raw_response(
                "307 Temporary Redirect",
                &format!("Location: {base}/redirected\r\n"),
                "",
            )
        } else {
            raw_initialize_ok(req)
        }
    })
    .await;
    base.set(url.clone()).unwrap();

    let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
        .await
        .unwrap();

    tokio::time::timeout(
        Duration::from_secs(3),
        client.initialize("raw-client", "1.0.0"),
    )
    .await
    .expect("same-origin redirect should not hang")
    .expect("a same-origin redirect must be followed");

    assert!(
        redirected_from_root.load(std::sync::atomic::Ordering::SeqCst),
        "the request should have hit the redirecting path first"
    );
}

/// A cross-origin `307` (different port, so a different origin on
/// `127.0.0.1`) is not followed by default: the target never sees the
/// request, and the caller fails instead of hanging.
#[tokio::test]
async fn cross_origin_redirect_is_not_followed_by_default() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    let seen_by_target = Arc::new(AtomicUsize::new(0));
    let seen_by_target_clone = seen_by_target.clone();
    let url_target = spawn_raw_server(move |req| {
        seen_by_target_clone.fetch_add(1, Ordering::SeqCst);
        raw_initialize_ok(req)
    })
    .await;

    let redirect_location = format!("{url_target}/redirected");
    let url_origin = spawn_raw_server(move |_req| {
        raw_response(
            "307 Temporary Redirect",
            &format!("Location: {redirect_location}\r\n"),
            "",
        )
    })
    .await;

    let client = McpClient::connect(HttpClientTransport::with_config(
        url_origin,
        raw_client_config(),
    ))
    .await
    .unwrap();

    let result = tokio::time::timeout(
        Duration::from_secs(3),
        client.initialize("raw-client", "1.0.0"),
    )
    .await
    .expect("a blocked cross-origin redirect must fail, not hang");
    let error = result
        .expect_err("a cross-origin redirect must not be followed by default")
        .to_string();
    assert!(
        error.contains(&format!("{url_target}/redirected")),
        "the error should name the redirect target, got: {error}"
    );
    assert_eq!(
        seen_by_target.load(Ordering::SeqCst),
        0,
        "the redirect target must never receive the request"
    );
}

/// With `follow_cross_origin_redirects` set, the same cross-origin `307` is
/// followed and the request succeeds.
#[tokio::test]
async fn cross_origin_redirect_is_followed_when_opted_in() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    let seen_by_target = Arc::new(AtomicUsize::new(0));
    let seen_by_target_clone = seen_by_target.clone();
    let url_target = spawn_raw_server(move |req| {
        seen_by_target_clone.fetch_add(1, Ordering::SeqCst);
        raw_initialize_ok(req)
    })
    .await;

    // Only `initialize` is redirected; `notifications/initialized` is
    // answered directly so the target's request count stays exact.
    let redirect_location = format!("{url_target}/redirected");
    let url_origin = spawn_raw_server(move |req| {
        if raw_is(req, "initialize") {
            raw_response(
                "307 Temporary Redirect",
                &format!("Location: {redirect_location}\r\n"),
                "",
            )
        } else {
            raw_response("202 Accepted", "", "")
        }
    })
    .await;

    let config = HttpClientConfig {
        follow_cross_origin_redirects: true,
        ..raw_client_config()
    };
    let client = McpClient::connect(HttpClientTransport::with_config(url_origin, config))
        .await
        .unwrap();

    tokio::time::timeout(
        Duration::from_secs(3),
        client.initialize("raw-client", "1.0.0"),
    )
    .await
    .expect("an opted-in cross-origin redirect should not hang")
    .expect("an opted-in cross-origin redirect must be followed");

    assert_eq!(
        seen_by_target.load(Ordering::SeqCst),
        1,
        "the redirect target should have received exactly one request"
    );
}

/// The same block applies on the established-session (background task) send
/// path, not just the pre-session synchronous path: a redirected `tools/list`
/// fails instead of hanging. Like any other `reqwest::Error` on that path
/// (network error, timeout, ...), the blocked redirect also marks the
/// transport disconnected -- that part is unrelated to this fix, just the
/// existing behavior for a background POST that fails at the `send()` level
/// rather than with an HTTP-level error.
#[tokio::test]
async fn established_session_cross_origin_redirect_fails_without_hanging() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    let seen_by_target = Arc::new(AtomicUsize::new(0));
    let seen_by_target_clone = seen_by_target.clone();
    let url_target = spawn_raw_server(move |req| {
        seen_by_target_clone.fetch_add(1, Ordering::SeqCst);
        raw_initialize_ok(req)
    })
    .await;

    let redirect_location = format!("{url_target}/redirected");
    let url_origin = spawn_raw_server(move |req| {
        if raw_is(req, "initialize") {
            raw_initialize_ok(req)
        } else if raw_is(req, "notifications/initialized") {
            raw_response("202 Accepted", "", "")
        } else if raw_is(req, "tools/list") {
            raw_response(
                "307 Temporary Redirect",
                &format!("Location: {redirect_location}\r\n"),
                "",
            )
        } else {
            let reply = format!(
                r#"{{"jsonrpc":"2.0","id":{},"result":{{}}}}"#,
                raw_request_id(req)
            );
            raw_response("200 OK", RAW_JSON, &reply)
        }
    })
    .await;

    let client = McpClient::connect(HttpClientTransport::with_config(
        url_origin,
        raw_client_config(),
    ))
    .await
    .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    let result = tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("a blocked cross-origin redirect must fail, not hang the caller");
    let error = result
        .expect_err("a cross-origin redirect must not be followed by default")
        .to_string();
    assert!(
        error.contains(&format!("{url_target}/redirected")),
        "the error should name the redirect target, got: {error}"
    );
    assert_eq!(
        seen_by_target.load(Ordering::SeqCst),
        0,
        "the redirect target must never receive the request"
    );
}

// ---------------------------------------------------------------------------
// Drop aborts background tasks and terminates the session (#1479)
// ---------------------------------------------------------------------------

/// A raw server for the drop tests below: answers `initialize` and
/// `notifications/initialized` normally, holds every SSE `GET` open until the
/// client side closes it (reported on `get_closed_tx`), and records every
/// `DELETE` it receives, including the `mcp-session-id` header line, on
/// `delete_tx`. Returns the URL and both receivers.
async fn spawn_session_drop_server() -> (
    String,
    tokio::sync::mpsc::Receiver<()>,
    tokio::sync::mpsc::Receiver<String>,
) {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let (get_closed_tx, get_closed_rx) = tokio::sync::mpsc::channel::<()>(4);
    let (delete_tx, delete_rx) = tokio::sync::mpsc::channel::<String>(4);

    tokio::spawn(async move {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                break;
            };
            let get_closed_tx = get_closed_tx.clone();
            let delete_tx = delete_tx.clone();
            tokio::spawn(async move {
                let Some(req) = read_http_request(&mut stream).await else {
                    return;
                };
                if req.starts_with("DELETE") {
                    let session_header = req
                        .lines()
                        .find(|l| l.to_lowercase().starts_with("mcp-session-id"))
                        .unwrap_or_default()
                        .to_string();
                    let _ = delete_tx.send(session_header).await;
                    let _ = stream
                        .write_all(raw_response("204 No Content", "", "").as_bytes())
                        .await;
                    let _ = stream.flush().await;
                    return;
                }
                if raw_is(&req, "initialize") {
                    let _ = stream.write_all(raw_initialize_ok(&req).as_bytes()).await;
                    let _ = stream.flush().await;
                    return;
                }
                if raw_is(&req, "notifications/initialized") {
                    let _ = stream
                        .write_all(raw_response("202 Accepted", "", "").as_bytes())
                        .await;
                    let _ = stream.flush().await;
                    return;
                }
                if req.starts_with("GET") {
                    // Hold the SSE stream open (no Content-Length, no body)
                    // and block on a read; the client's Drop-driven close is
                    // what unblocks it with EOF.
                    let header = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
                                   Connection: keep-alive\r\n\r\n";
                    let _ = stream.write_all(header.as_bytes()).await;
                    let _ = stream.flush().await;
                    let mut buf = [0u8; 16];
                    loop {
                        match stream.read(&mut buf).await {
                            Ok(0) | Err(_) => {
                                let _ = get_closed_tx.send(()).await;
                                break;
                            }
                            Ok(_) => continue,
                        }
                    }
                    return;
                }
                let _ = stream
                    .write_all(raw_response("202 Accepted", "", "").as_bytes())
                    .await;
                let _ = stream.flush().await;
            });
        }
    });

    (format!("http://{addr}"), get_closed_rx, delete_rx)
}

/// #1479: dropping a connected session client with the SSE stream open must
/// close that GET connection instead of leaving its task detached. Before the
/// `Drop` impl this connection stayed open until the server's own idle
/// timeout, since nothing ever aborted the SSE background task.
#[tokio::test]
async fn drop_closes_the_open_sse_stream() {
    let (url, mut get_closed_rx, _delete_rx) = spawn_session_drop_server().await;
    let config = HttpClientConfig {
        auto_sse: true,
        request_timeout: Duration::from_secs(5),
        ..Default::default()
    };
    let client = McpClient::connect(HttpClientTransport::with_config(url, config))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    // Let the background SSE GET actually reach the server before dropping;
    // otherwise there is nothing yet open to close.
    tokio::time::sleep(Duration::from_millis(100)).await;

    drop(client);

    tokio::time::timeout(Duration::from_secs(3), get_closed_rx.recv())
        .await
        .expect("server never observed the GET connection close (the bug this guards)")
        .expect("get_closed channel closed unexpectedly");
}

/// #1479: dropping a connected session client must send a best-effort
/// session-termination `DELETE` carrying the session id, the same as an
/// explicit `close()`.
#[tokio::test]
async fn drop_sends_a_session_delete() {
    let (url, _get_closed_rx, mut delete_rx) = spawn_session_drop_server().await;
    let config = HttpClientConfig {
        auto_sse: true,
        request_timeout: Duration::from_secs(5),
        ..Default::default()
    };
    let client = McpClient::connect(HttpClientTransport::with_config(url, config))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    drop(client);

    let session_header = tokio::time::timeout(Duration::from_secs(3), delete_rx.recv())
        .await
        .expect("server never received a session-termination DELETE (the bug this guards)")
        .expect("delete channel closed unexpectedly");
    assert!(
        session_header.to_lowercase().contains("raw-session"),
        "DELETE should carry the session id, got header line: {session_header}"
    );
}

/// #1479: dropping after an explicit `close()` (reached here through
/// `McpClient::shutdown()`, which awaits `close()` before the transport is
/// dropped) must not send a second session-termination `DELETE`. `close()`
/// clears the session id once its own `DELETE` is sent, which is what makes
/// `Drop` a no-op afterward.
#[tokio::test]
async fn drop_after_shutdown_does_not_send_a_second_delete() {
    let (url, _get_closed_rx, mut delete_rx) = spawn_session_drop_server().await;
    let config = HttpClientConfig {
        auto_sse: true,
        request_timeout: Duration::from_secs(5),
        ..Default::default()
    };
    let client = McpClient::connect(HttpClientTransport::with_config(url, config))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    client.shutdown().await.unwrap();

    let first = tokio::time::timeout(Duration::from_secs(3), delete_rx.recv())
        .await
        .expect("shutdown's own close() never sent a DELETE")
        .expect("delete channel closed unexpectedly");
    assert!(first.to_lowercase().contains("raw-session"));

    // `shutdown()` already consumed the client, and its message loop dropped
    // the transport right after `close()` returned, so there is nothing left
    // to drop explicitly here: this bounded wait is what proves the absence
    // of a second DELETE rather than triggering one.
    let second = tokio::time::timeout(Duration::from_millis(300), delete_rx.recv()).await;
    assert!(
        second.is_err(),
        "a second DELETE was sent after close() already terminated the session"
    );
}

/// #1479: the 2026-07-28 stateless path never establishes a session (no
/// `mcp-session-id` is ever assigned; see the `!is_modern_request` guard on
/// every session_id assignment in `send_http_request`), so dropping a
/// stateless connection must not attempt a session-termination `DELETE`.
#[cfg(feature = "stateless")]
#[tokio::test]
async fn drop_sends_no_delete_for_a_stateless_connection() {
    use std::sync::atomic::{AtomicUsize, Ordering};

    let delete_count = Arc::new(AtomicUsize::new(0));
    let delete_count_clone = delete_count.clone();
    let url = spawn_raw_server(move |req| {
        if req.starts_with("DELETE") {
            delete_count_clone.fetch_add(1, Ordering::SeqCst);
            return raw_response("204 No Content", "", "");
        }
        if raw_is(req, "server/discover") {
            let body = format!(
                r#"{{"jsonrpc":"2.0","id":{},"result":{{"supportedVersions":["2026-07-28"],"capabilities":{{}}}}}}"#,
                raw_request_id(req)
            );
            return raw_response("200 OK", RAW_JSON, &body);
        }
        raw_response("202 Accepted", "", "")
    })
    .await;

    let client = McpClient::builder()
        .protocol_support(tower_mcp::ProtocolSupport::try_new(["2026-07-28"]).unwrap())
        .connect(
            HttpClientTransport::with_config(url, raw_client_config()),
            NotificationHandler::new(),
        )
        .await
        .unwrap();
    client.discover("raw-client", "1.0.0").await.unwrap();

    drop(client);

    // Bound the wait so a regression (a wrongly-spawned DELETE) would show up
    // as a nonzero count rather than the test racing ahead of it.
    tokio::time::sleep(Duration::from_millis(300)).await;
    assert_eq!(
        delete_count.load(Ordering::SeqCst),
        0,
        "a stateless connection must never send a session-termination DELETE"
    );
}

// ---------------------------------------------------------------------------
// A transient HTTP status fails one request, not the transport (#1553)
// ---------------------------------------------------------------------------

/// A raw server that answers the first `tools/list` with `status`, `headers`
/// and a plain-text `body`, then answers everything normally.
async fn spawn_flaky_list_server(
    status: &'static str,
    headers: &'static str,
    body: &'static str,
) -> String {
    use std::sync::atomic::{AtomicBool, Ordering};

    let failed_once = Arc::new(AtomicBool::new(false));
    spawn_raw_server(move |req| {
        if raw_is(req, "initialize") {
            raw_initialize_ok(req)
        } else if raw_is(req, "notifications/initialized") {
            raw_response("202 Accepted", "", "")
        } else if raw_is(req, "tools/list") && !failed_once.swap(true, Ordering::SeqCst) {
            raw_response(status, headers, body)
        } else {
            let reply = format!(
                r#"{{"jsonrpc":"2.0","id":{},"result":{{"tools":[]}}}}"#,
                raw_request_id(req)
            );
            raw_response("200 OK", RAW_JSON, &reply)
        }
    })
    .await
}

async fn flaky_list_outcome(
    status: &'static str,
    headers: &'static str,
    body: &'static str,
) -> (tower_mcp::Error, McpClient) {
    let url = spawn_flaky_list_server(status, headers, body).await;
    let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    let error = tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("the failed list_tools hung")
        .expect_err("the first list_tools must fail");
    (error, client)
}

#[tokio::test]
async fn gateway_503_fails_one_request_and_client_stays_usable() {
    let (error, client) = flaky_list_outcome(
        "503 Service Unavailable",
        "Content-Type: text/plain\r\n",
        "upstream unavailable",
    )
    .await;

    let details = HttpStatusDetails::from_error(&error)
        .unwrap_or_else(|| panic!("the error should carry the HTTP status, got: {error:?}"));
    assert_eq!(details.status, 503);
    assert_eq!(details.retry_after, None);
    assert_eq!(details.retry_after_delay(), None);

    tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("list_tools after the 503 hung")
        .expect("the same client must serve the next request");
}

#[tokio::test]
async fn rate_limit_429_exposes_retry_after() {
    let (error, client) = flaky_list_outcome(
        "429 Too Many Requests",
        "Content-Type: text/plain\r\nRetry-After: 7\r\n",
        "slow down",
    )
    .await;

    let details = HttpStatusDetails::from_error(&error)
        .unwrap_or_else(|| panic!("the error should carry the HTTP status, got: {error:?}"));
    assert_eq!(details.status, 429);
    assert_eq!(details.retry_after.as_deref(), Some("7"));
    assert_eq!(details.retry_after_delay(), Some(Duration::from_secs(7)));

    tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("list_tools after the 429 hung")
        .expect("the same client must serve the next request");
}

#[tokio::test]
async fn retry_after_http_date_is_passed_through_raw() {
    let (error, _client) = flaky_list_outcome(
        "503 Service Unavailable",
        "Retry-After: Wed, 21 Oct 2026 07:28:00 GMT\r\n",
        "",
    )
    .await;

    let details = HttpStatusDetails::from_error(&error).expect("status details");
    assert_eq!(
        details.retry_after.as_deref(),
        Some("Wed, 21 Oct 2026 07:28:00 GMT")
    );
    assert_eq!(details.retry_after_delay(), None);
}

// ---------------------------------------------------------------------------
// A 401, 403 or 429 with a JSON-RPC error body keeps its HTTP status (#1555)
// ---------------------------------------------------------------------------

fn jsonrpc_error_body(data: Option<&str>) -> String {
    let data = data.map_or(String::new(), |data| format!(r#","data":{data}"#));
    format!(
        r#"{{"jsonrpc":"2.0","id":null,"error":{{"code":-32001,"message":"denied by policy"{data}}}}}"#
    )
}

/// Leak a test-built body to the `'static` the flaky-server helper takes.
fn leak(body: String) -> &'static str {
    Box::leak(body.into_boxed_str())
}

fn rpc_error(error: &tower_mcp::Error) -> &JsonRpcError {
    match error {
        tower_mcp::Error::JsonRpc(rpc) => rpc,
        other => panic!("expected a JSON-RPC error, got: {other:?}"),
    }
}

#[tokio::test]
async fn forbidden_jsonrpc_error_body_exposes_status_and_keeps_server_data() {
    let body = leak(jsonrpc_error_body(Some(r#"{"reason":"missing scope"}"#)));
    let (error, client) = flaky_list_outcome("403 Forbidden", RAW_JSON, body).await;

    let details = HttpStatusDetails::from_error(&error)
        .unwrap_or_else(|| panic!("the error should carry the HTTP status, got: {error:?}"));
    assert_eq!(details.status, 403);
    assert_eq!(details.www_authenticate, None);

    // The server's own error is what the caller sees, with its data intact.
    let rpc = rpc_error(&error);
    assert_eq!(rpc.code, -32001);
    assert_eq!(rpc.message, "denied by policy");
    let data = rpc.data.as_ref().unwrap();
    assert_eq!(data["reason"], "missing scope");
    assert_eq!(data["httpStatus"], 403);

    tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("list_tools after the 403 hung")
        .expect("the same client must serve the next request");
}

#[tokio::test]
async fn unauthorized_jsonrpc_error_body_exposes_the_challenge() {
    let challenge = r#"Bearer error="invalid_token", resource_metadata="https://example.test/.well-known/oauth-protected-resource""#;
    let headers = leak(format!(
        "{RAW_JSON}WWW-Authenticate: {challenge}
Retry-After: 3
"
    ));
    let (error, _client) =
        flaky_list_outcome("401 Unauthorized", headers, leak(jsonrpc_error_body(None))).await;

    let details = HttpStatusDetails::from_error(&error).expect("status details");
    assert_eq!(details.status, 401);
    assert_eq!(details.www_authenticate.as_deref(), Some(challenge));
    assert_eq!(details.retry_after.as_deref(), Some("3"));
    assert_eq!(rpc_error(&error).code, -32001);
    assert_eq!(rpc_error(&error).message, "denied by policy");
}

#[tokio::test]
async fn unauthorized_without_a_jsonrpc_body_exposes_the_challenge() {
    let (error, _client) = flaky_list_outcome(
        "401 Unauthorized",
        "Content-Type: text/plain\r\nWWW-Authenticate: Bearer realm=\"mcp\"\r\n",
        "unauthorized",
    )
    .await;

    let details = HttpStatusDetails::from_error(&error).expect("status details");
    assert_eq!(details.status, 401);
    assert_eq!(
        details.www_authenticate.as_deref(),
        Some(r#"Bearer realm="mcp""#)
    );
}

#[tokio::test]
async fn server_status_keys_in_error_data_are_not_overwritten() {
    let body = leak(jsonrpc_error_body(Some(r#"{"httpStatus":"upstream"}"#)));
    let (error, _client) = flaky_list_outcome("403 Forbidden", RAW_JSON, body).await;

    let data = rpc_error(&error).data.as_ref().unwrap();
    assert_eq!(data["httpStatus"], "upstream");
}

#[tokio::test]
async fn non_object_error_data_moves_under_server_data() {
    let body = leak(jsonrpc_error_body(Some(r#""policy 7""#)));
    let (error, _client) = flaky_list_outcome("403 Forbidden", RAW_JSON, body).await;

    let details = HttpStatusDetails::from_error(&error).expect("status details");
    assert_eq!(details.status, 403);
    let data = rpc_error(&error).data.as_ref().unwrap();
    assert_eq!(data["serverData"], "policy 7");
}

/// Statuses that are not about authorization or rate limits leave the
/// server's error exactly as sent.
#[tokio::test]
async fn in_band_error_on_a_400_gets_no_status_added() {
    let body = leak(jsonrpc_error_body(None));
    let (error, _client) = flaky_list_outcome("400 Bad Request", RAW_JSON, body).await;

    assert_eq!(rpc_error(&error).code, -32001);
    assert_eq!(rpc_error(&error).data, None);
    assert_eq!(HttpStatusDetails::from_error(&error), None);
}

// ---------------------------------------------------------------------------
// A 404 on a session request recovers the session, whatever the body (#1556)
// ---------------------------------------------------------------------------

/// A raw server that issues a numbered session on each `initialize`, answers
/// the first `tools/list` with a 404 carrying `body`, and answers `tools/list`
/// only for the second session afterwards. Returns the URL and the count of
/// `initialize` requests seen.
async fn spawn_expiring_session_server(
    body: &'static str,
) -> (String, Arc<std::sync::atomic::AtomicUsize>) {
    use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};

    let initializes = Arc::new(AtomicUsize::new(0));
    let expired_once = Arc::new(AtomicBool::new(false));
    let counter = initializes.clone();
    let url = spawn_raw_server(move |req| {
        if raw_is(req, "initialize") {
            let n = counter.fetch_add(1, Ordering::SeqCst) + 1;
            let reply = format!(
                r#"{{"jsonrpc":"2.0","id":{},"result":{{"protocolVersion":"2025-11-25","capabilities":{{}},"serverInfo":{{"name":"raw","version":"0"}}}}}}"#,
                raw_request_id(req)
            );
            raw_response(
                "200 OK",
                &format!(
                    "{RAW_JSON}mcp-session-id: session-{n}\r\nmcp-protocol-version: 2025-11-25\r\n"
                ),
                &reply,
            )
        } else if raw_is(req, "notifications/initialized") {
            raw_response("202 Accepted", "", "")
        } else if raw_is(req, "tools/list") && !expired_once.swap(true, Ordering::SeqCst) {
            raw_response("404 Not Found", if body.is_empty() { "" } else { RAW_JSON }, body)
        } else if req.to_lowercase().contains("mcp-session-id: session-2") {
            let reply = format!(
                r#"{{"jsonrpc":"2.0","id":{},"result":{{"tools":[]}}}}"#,
                raw_request_id(req)
            );
            raw_response("200 OK", RAW_JSON, &reply)
        } else {
            raw_response("404 Not Found", "", "")
        }
    })
    .await;
    (url, initializes)
}

async fn assert_session_404_recovers(body: &'static str) {
    let (url, initializes) = spawn_expiring_session_server(body).await;
    let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    tokio::time::timeout(Duration::from_secs(5), client.list_tools())
        .await
        .expect("list_tools hung")
        .expect("the request must succeed on the re-initialized session");
    assert_eq!(initializes.load(std::sync::atomic::Ordering::SeqCst), 2);

    tokio::time::timeout(Duration::from_secs(3), client.list_tools())
        .await
        .expect("the next list_tools hung")
        .expect("the recovered session must keep serving requests");
}

#[tokio::test]
async fn bare_404_on_a_session_request_recovers_the_session() {
    assert_session_404_recovers("").await;
}

#[tokio::test]
async fn session_404_with_a_32001_body_recovers_the_session() {
    assert_session_404_recovers(
        r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32001,"message":"Session not found"}}"#,
    )
    .await;
}

#[tokio::test]
async fn session_404_with_a_32005_body_still_recovers_the_session() {
    assert_session_404_recovers(
        r#"{"jsonrpc":"2.0","id":null,"error":{"code":-32005,"message":"Session not found"}}"#,
    )
    .await;
}

/// With recovery switched off the 404 is not turned into a session signal:
/// the request fails with the status, and the transport closes as before.
#[tokio::test]
async fn session_404_without_recovery_fails_and_closes_the_transport() {
    let (url, initializes) = spawn_expiring_session_server("").await;
    let client = McpClient::connect(HttpClientTransport::with_config(
        url,
        HttpClientConfig {
            session_recovery: false,
            ..raw_client_config()
        },
    ))
    .await
    .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    let error = tokio::time::timeout(Duration::from_secs(5), client.list_tools())
        .await
        .expect("list_tools hung")
        .expect_err("the 404 must fail the request");
    assert_eq!(
        HttpStatusDetails::from_error(&error).map(|details| details.status),
        Some(404),
        "{error:?}"
    );
    assert_eq!(initializes.load(std::sync::atomic::Ordering::SeqCst), 1);

    tokio::time::timeout(Duration::from_secs(3), async {
        // The closed flag reaches the client after the failed request's
        // error, so poll until a call reports the closed connection.
        while !client
            .list_tools()
            .await
            .is_err_and(|error| error.to_string().contains("Connection closed"))
        {
            tokio::time::sleep(Duration::from_millis(10)).await;
        }
    })
    .await
    .expect("a 404 without recovery must close the transport");
}

// =============================================================================
// Edge cases from #1558
// =============================================================================

/// A server that answers `initialize` with an SSE stream, pings the client on
/// that stream, and withholds the `InitializeResult` until the pong arrives.
/// The client has to answer the ping while the initialize response is still
/// open, which it cannot do if it reads that response to EOF before
/// dispatching anything.
#[tokio::test]
async fn initialize_response_stream_is_dispatched_as_frames_arrive() {
    use tokio::io::AsyncWriteExt;

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let pong_received = Arc::new(tokio::sync::Notify::new());
    let pong_seen = Arc::new(std::sync::atomic::AtomicBool::new(false));

    let (pong_received_server, pong_seen_server) = (pong_received.clone(), pong_seen.clone());
    tokio::spawn(async move {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                break;
            };
            let pong_received = pong_received_server.clone();
            let pong_seen = pong_seen_server.clone();
            tokio::spawn(async move {
                let Some(req) = read_http_request(&mut stream).await else {
                    return;
                };
                if raw_is(&req, "initialize") {
                    let headers = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
                                   mcp-session-id: raw-session\r\n\
                                   mcp-protocol-version: 2025-11-25\r\n\
                                   Connection: close\r\n\r\n";
                    let _ = stream.write_all(headers.as_bytes()).await;
                    let ping =
                        "data: {\"jsonrpc\":\"2.0\",\"id\":\"srv-ping\",\"method\":\"ping\"}\n\n";
                    let _ = stream.write_all(ping.as_bytes()).await;
                    let _ = stream.flush().await;

                    // Hold the InitializeResult until the pong has arrived.
                    let _ = tokio::time::timeout(Duration::from_secs(3), pong_received.notified())
                        .await;
                    if pong_seen.load(std::sync::atomic::Ordering::SeqCst) {
                        let result = format!(
                            "data: {{\"jsonrpc\":\"2.0\",\"id\":{},\"result\":{{\"protocolVersion\":\"2025-11-25\",\"capabilities\":{{}},\"serverInfo\":{{\"name\":\"raw\",\"version\":\"0\"}}}}}}\n\n",
                            raw_request_id(&req)
                        );
                        let _ = stream.write_all(result.as_bytes()).await;
                    }
                    let _ = stream.flush().await;
                    return;
                }
                if req.contains("\"id\":\"srv-ping\"") && req.contains("\"result\"") {
                    pong_seen.store(true, std::sync::atomic::Ordering::SeqCst);
                    pong_received.notify_one();
                }
                let _ = stream
                    .write_all(raw_response("202 Accepted", "", "").as_bytes())
                    .await;
                let _ = stream.flush().await;
            });
        }
    });

    let client = McpClient::connect(HttpClientTransport::with_config(
        format!("http://{addr}"),
        HttpClientConfig {
            request_timeout: Duration::from_secs(10),
            ..raw_client_config()
        },
    ))
    .await
    .unwrap();

    let started = std::time::Instant::now();
    let result = tokio::time::timeout(
        Duration::from_secs(5),
        client.initialize("raw-client", "1.0.0"),
    )
    .await
    .expect("initialize hung waiting on the ping it never answered")
    .expect("initialize must succeed once the ping is answered");
    assert_eq!(result.server_info.name, "raw");
    assert!(
        started.elapsed() < Duration::from_secs(2),
        "initialize should complete as soon as the pong lands, took {:?}",
        started.elapsed()
    );
    assert!(pong_seen.load(std::sync::atomic::Ordering::SeqCst));
}

/// A raw server for the cancellation tests: answers `server/discover` and
/// notifications normally, never answers `tools/call`, and reports the JSON
/// body of every POST it receives on the returned channel. `initialize` is
/// answered with a session, or with an SSE stream that issues the session and
/// then stays silent when `hold_initialize` is set.
async fn spawn_recording_server(
    hold_initialize: bool,
) -> (String, tokio::sync::mpsc::UnboundedReceiver<String>) {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let (body_tx, body_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
    tokio::spawn(async move {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                break;
            };
            let body_tx = body_tx.clone();
            tokio::spawn(async move {
                let Some(req) = read_http_request(&mut stream).await else {
                    return;
                };
                if let Some((_, body)) = req.split_once("\r\n\r\n") {
                    let _ = body_tx.send(body.to_string());
                }
                let hold =
                    (raw_is(&req, "initialize") && hold_initialize) || raw_is(&req, "tools/call");
                if hold {
                    if raw_is(&req, "initialize") {
                        let headers = "HTTP/1.1 200 OK\r\nContent-Type: text/event-stream\r\n\
                                       mcp-session-id: raw-session\r\n\
                                       mcp-protocol-version: 2025-11-25\r\n\
                                       Connection: close\r\n\r\n";
                        let _ = stream.write_all(headers.as_bytes()).await;
                        let _ = stream.flush().await;
                    }
                    // Never answer; hold the connection until the client
                    // closes it.
                    let mut buf = [0u8; 16];
                    while matches!(stream.read(&mut buf).await, Ok(n) if n > 0) {}
                    return;
                }
                if raw_is(&req, "initialize") {
                    let _ = stream.write_all(raw_initialize_ok(&req).as_bytes()).await;
                } else if raw_is(&req, "server/discover") {
                    let body = format!(
                        r#"{{"jsonrpc":"2.0","id":{},"result":{{"supportedVersions":["2026-07-28"],"capabilities":{{}}}}}}"#,
                        raw_request_id(&req)
                    );
                    let _ = stream
                        .write_all(raw_response("200 OK", RAW_JSON, &body).as_bytes())
                        .await;
                } else {
                    let _ = stream
                        .write_all(raw_response("202 Accepted", "", "").as_bytes())
                        .await;
                }
                let _ = stream.flush().await;
            });
        }
    });
    (format!("http://{addr}"), body_rx)
}

/// Read bodies off `rx` until `matches` accepts one, within `limit`.
async fn next_body_matching(
    rx: &mut tokio::sync::mpsc::UnboundedReceiver<String>,
    limit: Duration,
    matches: impl Fn(&serde_json::Value) -> bool,
) -> Option<serde_json::Value> {
    tokio::time::timeout(limit, async {
        while let Some(body) = rx.recv().await {
            if let Ok(value) = serde_json::from_str::<serde_json::Value>(&body)
                && matches(&value)
            {
                return Some(value);
            }
        }
        None
    })
    .await
    .ok()
    .flatten()
}

/// On a 2025-11-25 session a closed connection is not a cancellation, so
/// abandoning a request has to say so with `notifications/cancelled`, as it
/// does on stdio.
#[tokio::test]
async fn dropping_a_session_request_sends_notifications_cancelled() {
    let (url, mut bodies) = spawn_recording_server(false).await;
    let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    // Abandon the call once the server has received it.
    let client = Arc::new(client);
    let call = tokio::spawn({
        let client = client.clone();
        async move {
            let _ = client.call_tool("slow", serde_json::json!({})).await;
        }
    });
    let request = next_body_matching(&mut bodies, Duration::from_secs(3), |v| {
        v["method"] == "tools/call"
    })
    .await
    .expect("the server never received the tools/call");
    let request_id = request["id"].clone();
    call.abort();

    let cancelled = next_body_matching(&mut bodies, Duration::from_secs(3), |v| {
        v["method"] == "notifications/cancelled"
    })
    .await
    .expect("no notifications/cancelled reached the server for the abandoned request");
    assert_eq!(cancelled["params"]["requestId"], request_id);
}

/// The spec forbids cancelling `initialize`, so abandoning one that has
/// already issued a session sends nothing.
#[tokio::test]
async fn dropping_initialize_sends_no_notifications_cancelled() {
    let (url, mut bodies) = spawn_recording_server(true).await;
    let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
        .await
        .unwrap();

    // The server issues the session and then goes quiet, so this times out
    // and drops the initialize future with its request in flight.
    let outcome = tokio::time::timeout(
        Duration::from_millis(300),
        client.initialize("raw-client", "1.0.0"),
    )
    .await;
    assert!(outcome.is_err(), "initialize should still be waiting");

    let cancelled = next_body_matching(&mut bodies, Duration::from_millis(500), |v| {
        v["method"] == "notifications/cancelled"
    })
    .await;
    assert!(cancelled.is_none(), "initialize must not be cancelled");
}

/// On the 2026-07-28 path a disconnect is the cancellation, and there is no
/// session to address a notification to, so none is sent.
#[cfg(feature = "stateless")]
#[tokio::test]
async fn dropping_a_final_request_sends_no_notifications_cancelled() {
    let (url, mut bodies) = spawn_recording_server(false).await;
    let client = McpClient::builder()
        .protocol_support(tower_mcp::ProtocolSupport::try_new(["2026-07-28"]).unwrap())
        .connect(
            HttpClientTransport::with_config(url, raw_client_config()),
            NotificationHandler::new(),
        )
        .await
        .unwrap();
    client.discover("raw-client", "1.0.0").await.unwrap();

    let client = Arc::new(client);
    let call = tokio::spawn({
        let client = client.clone();
        async move {
            let _ = client.call_tool("slow", serde_json::json!({})).await;
        }
    });
    next_body_matching(&mut bodies, Duration::from_secs(3), |v| {
        v["method"] == "tools/call"
    })
    .await
    .expect("the server never received the tools/call");
    call.abort();

    let cancelled = next_body_matching(&mut bodies, Duration::from_millis(500), |v| {
        v["method"] == "notifications/cancelled"
    })
    .await;
    assert!(
        cancelled.is_none(),
        "the final protocol cancels by disconnecting, not by notification"
    );
}

/// A raw server that answers `initialize` with `reply` (which issues the
/// session `raw-session`) and reports the `mcp-session-id` header line of
/// every `DELETE` it receives.
async fn spawn_initialize_server(
    reply: fn(&str) -> String,
) -> (String, tokio::sync::mpsc::UnboundedReceiver<String>) {
    use tokio::io::AsyncWriteExt;

    let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
    let addr = listener.local_addr().unwrap();
    let (delete_tx, delete_rx) = tokio::sync::mpsc::unbounded_channel::<String>();
    tokio::spawn(async move {
        loop {
            let Ok((mut stream, _)) = listener.accept().await else {
                break;
            };
            let delete_tx = delete_tx.clone();
            tokio::spawn(async move {
                let Some(req) = read_http_request(&mut stream).await else {
                    return;
                };
                let response = if req.starts_with("DELETE") {
                    let session_header = req
                        .lines()
                        .find(|l| l.to_lowercase().starts_with("mcp-session-id"))
                        .unwrap_or_default()
                        .to_string();
                    let _ = delete_tx.send(session_header);
                    raw_response("204 No Content", "", "")
                } else if raw_is(&req, "initialize") {
                    reply(&req)
                } else {
                    raw_response("202 Accepted", "", "")
                };
                let _ = stream.write_all(response.as_bytes()).await;
                let _ = stream.flush().await;
            });
        }
    });
    (format!("http://{addr}"), delete_rx)
}

fn session_headers() -> String {
    format!("{RAW_JSON}mcp-session-id: raw-session\r\nmcp-protocol-version: 2025-11-25\r\n")
}

/// Run a failing `initialize` against `reply`, and require exactly one
/// `DELETE` for the session it issued, even after the client is dropped.
async fn assert_failed_initialize_deletes_the_session(reply: fn(&str) -> String) {
    let (url, mut deletes) = spawn_initialize_server(reply).await;
    let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
        .await
        .unwrap();

    tokio::time::timeout(
        Duration::from_secs(3),
        client.initialize("raw-client", "1.0.0"),
    )
    .await
    .expect("initialize hung")
    .expect_err("the handshake must fail");

    let header = tokio::time::timeout(Duration::from_secs(3), deletes.recv())
        .await
        .expect("the failed initialize's session was never deleted")
        .expect("delete channel closed unexpectedly");
    assert!(
        header.to_lowercase().contains("raw-session"),
        "DELETE should carry the session id, got header line: {header}"
    );

    // The session id was cleared, so dropping the client sends no second one.
    drop(client);
    assert!(
        tokio::time::timeout(Duration::from_millis(300), deletes.recv())
            .await
            .is_err(),
        "a second DELETE was sent for the same session"
    );
}

/// #1558: a session issued alongside a JSON-RPC error result is deleted when
/// `initialize` fails, not left until shutdown or the server's idle timeout.
#[tokio::test]
async fn failed_initialize_deletes_the_session_it_was_issued() {
    assert_failed_initialize_deletes_the_session(|req| {
        let body = format!(
            r#"{{"jsonrpc":"2.0","id":{},"error":{{"code":-32603,"message":"init failed"}}}}"#,
            raw_request_id(req)
        );
        raw_response("200 OK", &session_headers(), &body)
    })
    .await;
}

/// #1558: a server that picks a protocol version the client does not accept
/// has `initialize` rejected after the transport already took the session.
#[tokio::test]
async fn initialize_rejecting_the_protocol_version_deletes_the_session() {
    assert_failed_initialize_deletes_the_session(|req| {
        let body = format!(
            r#"{{"jsonrpc":"2.0","id":{},"result":{{"protocolVersion":"1999-01-01","capabilities":{{}},"serverInfo":{{"name":"raw","version":"0"}}}}}}"#,
            raw_request_id(req)
        );
        raw_response("200 OK", &session_headers(), &body)
    })
    .await;
}

/// A successful `initialize` keeps its session until shutdown.
#[tokio::test]
async fn successful_initialize_does_not_delete_the_session() {
    let (url, mut deletes) = spawn_initialize_server(raw_initialize_ok).await;
    let client = McpClient::connect(HttpClientTransport::with_config(url, raw_client_config()))
        .await
        .unwrap();
    client.initialize("raw-client", "1.0.0").await.unwrap();

    assert!(
        tokio::time::timeout(Duration::from_millis(300), deletes.recv())
            .await
            .is_err(),
        "a healthy session was deleted"
    );
}