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
//! MRTR (elicitation) end-to-end over the stateless 2026-07-28 transport.
//!
//! Drives the raw protocol so the two-round wire contract is asserted
//! directly: round 1 `tools/call` -> `input_required` (+ `requestState`),
//! round 2 retry (new id + `inputResponses` + echoed state) -> final result.
#![cfg(all(
    not(feature = "legacy-spec"),
    feature = "http-server-volga",
    feature = "http-client"
))]

use neva::{
    App, Context,
    client::Client,
    error::{Error, ErrorCode},
    types::elicitation::{ElicitRequestParams, ElicitResult},
};

#[tokio::test(flavor = "multi_thread")]
async fn tool_elicits_then_completes_over_two_rounds() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        Ok::<String, Error>(format!("hello {name}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // Round 1: tools/call -> input_required. Capabilities are spelled the way
    // the spec does -- an object per capability, presence being the
    // declaration -- which is what a conformant client (MCP Inspector) sends.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": { "form": {} } } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    assert_eq!(
        r1["result"]["resultType"],
        serde_json::json!("input_required"),
        "round 1 must request input: {r1}"
    );
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();
    let key = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object")
        .keys()
        .next()
        .expect("one input request")
        .clone();

    // Round 2: retry with a new id + inputResponses + echoed state. Both ride
    // on the params, next to `name` and `arguments`, which is where the spec's
    // `InputResponseRequestParams` puts them -- not in `_meta`.
    let retry = serde_json::json!({
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "requestState": state,
            "inputResponses": { key: { "action": "accept", "content": { "name": "octocat" } } },
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": { "form": {} } }
            } }
    });
    let r2: serde_json::Value = routed(client.post(&url), &retry)
        .json(&retry)
        .send()
        .await
        .expect("round 2 send")
        .json()
        .await
        .expect("round 2 json");
    assert_eq!(
        r2.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("hello octocat"),
        "round 2 must complete: {r2}"
    );
    // The two discriminators are the same field: round 1 says `input_required`,
    // the final round says `complete`.
    assert_eq!(
        r2["result"]["resultType"],
        serde_json::json!("complete"),
        "round 2 must be tagged complete: {r2}"
    );

    handle.abort();
}

/// neva wrote `inputResponses` / `requestState` into `_meta` up to 0.5.2. A
/// client on that version must keep working against a newer server, so the old
/// location is still read -- after the spec one, and only if it is empty.
#[tokio::test(flavor = "multi_thread")]
async fn a_retry_stating_its_answers_in_meta_is_still_understood() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        Ok::<String, Error>(format!("hello {name}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();
    let key = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object")
        .keys()
        .next()
        .expect("one input request")
        .clone();

    // The 0.5.2 shape: both fields inside `_meta`.
    let retry = serde_json::json!({
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": true },
                "requestState": state,
                "inputResponses": { key: { "action": "accept", "content": { "name": "octocat" } } }
            } }
    });
    let r2: serde_json::Value = routed(client.post(&url), &retry)
        .json(&retry)
        .send()
        .await
        .expect("round 2 send")
        .json()
        .await
        .expect("round 2 json");

    assert_eq!(
        r2.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("hello octocat"),
        "a 0.5.2-shaped retry must still complete: {r2}"
    );

    handle.abort();
}

use std::sync::atomic::{AtomicUsize, Ordering};

static FETCHES: AtomicUsize = AtomicUsize::new(0);
static CHARGES: AtomicUsize = AtomicUsize::new(0);
static RECEIPTS: AtomicUsize = AtomicUsize::new(0);
static LOST_RESPONSE_COMMITS: AtomicUsize = AtomicUsize::new(0);
static IGNORED_ANSWER_COMMITS: AtomicUsize = AtomicUsize::new(0);
static CONCURRENT_FINAL_COMMITS: AtomicUsize = AtomicUsize::new(0);
static PARTIAL_COMMIT_CHARGES: AtomicUsize = AtomicUsize::new(0);

#[tokio::test(flavor = "multi_thread")]
async fn final_round_replay_is_idempotent_after_a_lost_response() {
    // The final POST commits and produces a result, but its HTTP response is
    // "lost"; the client retries the SAME requestState + inputResponses. The
    // server must serve the cached result without re-running the handler -- so
    // the on_commit side effect fires exactly once across both finals.
    LOST_RESPONSE_COMMITS.store(0, Ordering::SeqCst);

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        ctx.on_commit(async move {
            LOST_RESPONSE_COMMITS.fetch_add(1, Ordering::SeqCst);
            Ok(())
        });
        Ok::<String, Error>(format!("hello {name}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // Round 1: tools/call -> input_required.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();
    let key = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object")
        .keys()
        .next()
        .expect("one input request")
        .clone();

    // The final retry, reused verbatim for both the "lost" send and the replay.
    let retry = serde_json::json!({
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": true },
                "requestState": state,
                "inputResponses": { key: { "action": "accept", "content": { "name": "octocat" } } }
            } }
    });

    // Round 2 (final): completes and runs the commit. Pretend the response is lost.
    let r2: serde_json::Value = routed(client.post(&url), &retry)
        .json(&retry)
        .send()
        .await
        .expect("final send")
        .json()
        .await
        .expect("final json");
    assert_eq!(
        r2.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("hello octocat"),
        "final round must complete: {r2}"
    );
    assert_eq!(LOST_RESPONSE_COMMITS.load(Ordering::SeqCst), 1);

    // Lost-response retry: identical requestState + inputResponses, new id.
    let mut replay = retry.clone();
    replay["id"] = serde_json::json!(3);
    let r3: serde_json::Value = routed(client.post(&url), &replay)
        .json(&replay)
        .send()
        .await
        .expect("replay send")
        .json()
        .await
        .expect("replay json");

    // Same result, the retry's own id, and the commit did NOT fire again.
    assert_eq!(
        r3.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("hello octocat"),
        "replay must return the cached result: {r3}"
    );
    assert_eq!(
        r3["id"],
        serde_json::json!(3),
        "cached response adopts the retry id"
    );
    assert_eq!(
        LOST_RESPONSE_COMMITS.load(Ordering::SeqCst),
        1,
        "on_commit must not fire again on a lost-response retry"
    );

    handle.abort();
}

/// An answer the server ignores must not buy a fresh run of the final round.
///
/// The idempotency key folds in a digest of the round's answers, so that one
/// minted state echoed with two *different* answers cannot serve the first
/// answer's result for the second. But the server drops an answer that is
/// unsolicited or already settled -- so a replay can add a junk key, change
/// nothing the handler sees, and still present a different raw
/// `inputResponses`. Keyed on the raw map that is a different key, the cache
/// misses, and the final handler runs again with its `on_commit` effects: an
/// idempotency guard that anyone can step around by appending a byte.
#[tokio::test(flavor = "multi_thread")]
async fn an_ignored_answer_does_not_buy_a_second_run_of_the_final_round() {
    IGNORED_ANSWER_COMMITS.store(0, Ordering::SeqCst);

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        ctx.on_commit(async move {
            IGNORED_ANSWER_COMMITS.fetch_add(1, Ordering::SeqCst);
            Ok(())
        });
        Ok::<String, Error>(format!("hello {name}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();
    let key = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object")
        .keys()
        .next()
        .expect("one input request")
        .clone();

    let answer = serde_json::json!({ "action": "accept", "content": { "name": "octocat" } });
    let final_round = |id: i32, responses: serde_json::Value| {
        serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": { "name": "greet", "arguments": {},
                "requestState": state,
                "inputResponses": responses,
                "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                    "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
        })
    };

    let first = final_round(2, serde_json::json!({ key.clone(): answer }));
    let r2: serde_json::Value = routed(client.post(&url), &first)
        .json(&first)
        .send()
        .await
        .expect("final send")
        .json()
        .await
        .expect("final json");
    assert_eq!(
        r2.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("hello octocat"),
        "final round must complete: {r2}"
    );
    assert_eq!(IGNORED_ANSWER_COMMITS.load(Ordering::SeqCst), 1);

    // The same state and the same accepted answer, plus a key the server never
    // asked for. The handler sees exactly what it saw the first time.
    let padded = final_round(
        3,
        serde_json::json!({
            key: answer,
            "never-requested": { "action": "accept", "content": { "name": "impostor" } }
        }),
    );
    let r3: serde_json::Value = routed(client.post(&url), &padded)
        .json(&padded)
        .send()
        .await
        .expect("padded send")
        .json()
        .await
        .expect("padded json");

    assert_eq!(
        r3.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("hello octocat"),
        "the padded replay must be served from the cache: {r3}"
    );
    assert_eq!(
        IGNORED_ANSWER_COMMITS.load(Ordering::SeqCst),
        1,
        "an answer the server ignores must not re-run the final round"
    );

    handle.abort();
}

/// A final round that fails partway through its commits must not be repeatable.
///
/// Commits run in registration order and the first `Err` becomes the response
/// error -- but by then the earlier ones have already applied their effects.
/// Caching only successful rounds would leave that state open: a client whose
/// error response went missing re-sends the identical request, misses the
/// cache, and the handler plus every commit before the failing one runs a
/// second time. Charged twice, to be told the same thing.
#[tokio::test(flavor = "multi_thread")]
async fn a_round_that_failed_midway_through_its_commits_is_not_repeatable() {
    PARTIAL_COMMIT_CHARGES.store(0, Ordering::SeqCst);

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("checkout", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Confirm?")
            .with_required("card", "string")
            .into();
        ctx.elicit("card", params).await?;
        // The money moves first and the receipt fails after it -- the ordering
        // that makes a re-run cost something real.
        ctx.on_commit(async move {
            PARTIAL_COMMIT_CHARGES.fetch_add(1, Ordering::SeqCst);
            Ok(())
        });
        ctx.on_commit(async move {
            Err::<(), Error>(Error::new(ErrorCode::InternalError, "receipt service down"))
        });
        Ok::<String, Error>("charged".into())
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "checkout", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();
    let key = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object")
        .keys()
        .next()
        .expect("one input request")
        .clone();

    let answer = serde_json::json!({ "action": "accept", "content": { "card": "4242" } });
    let final_round = |id: i32| {
        serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": { "name": "checkout", "arguments": {},
                "requestState": state,
                "inputResponses": { key.clone(): answer },
                "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                    "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
        })
    };

    let first = final_round(2);
    let r2: serde_json::Value = routed(client.post(&url), &first)
        .json(&first)
        .send()
        .await
        .expect("final send")
        .json()
        .await
        .expect("final json");
    assert!(
        r2["error"]["message"]
            .as_str()
            .is_some_and(|m| m.contains("receipt service down")),
        "the failing commit must be the response error: {r2}"
    );
    assert_eq!(
        PARTIAL_COMMIT_CHARGES.load(Ordering::SeqCst),
        1,
        "the commit before the failure applied once"
    );

    // The client never saw that answer and asks again, byte for byte.
    let again = final_round(3);
    let r3: serde_json::Value = routed(client.post(&url), &again)
        .json(&again)
        .send()
        .await
        .expect("retry send")
        .json()
        .await
        .expect("retry json");
    assert!(
        r3["error"]["message"]
            .as_str()
            .is_some_and(|m| m.contains("receipt service down")),
        "the retry must replay the cached failure: {r3}"
    );
    assert_eq!(
        r3["id"],
        serde_json::json!(3),
        "the cached response adopts the retry id"
    );
    assert_eq!(
        PARTIAL_COMMIT_CHARGES.load(Ordering::SeqCst),
        1,
        "a retry of a failed round must not charge again"
    );

    handle.abort();
}

#[tokio::test(flavor = "multi_thread")]
async fn concurrent_final_round_retries_commit_exactly_once() {
    // Two IDENTICAL final-round retries arrive at the same time (the client
    // timed out and re-sent while the first is still executing). Without a
    // per-state reservation both miss the idempotency cache and re-run the
    // handler + on_commit. The handler sleeps to widen that window; the
    // reservation must still serialise them so the commit fires exactly once.
    CONCURRENT_FINAL_COMMITS.store(0, Ordering::SeqCst);

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        // Widen the get-miss -> put window so both retries would overlap absent
        // the reservation.
        tokio::time::sleep(std::time::Duration::from_millis(200)).await;
        ctx.on_commit(async move {
            CONCURRENT_FINAL_COMMITS.fetch_add(1, Ordering::SeqCst);
            Ok(())
        });
        Ok::<String, Error>(format!("hello {name}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // Round 1: tools/call -> input_required.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();
    let key = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object")
        .keys()
        .next()
        .expect("one input request")
        .clone();

    // Two identical final retries, distinct ids, fired concurrently.
    let retry = |id: i64| {
        serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": { "name": "greet", "arguments": {},
                "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                    "io.modelcontextprotocol/clientCapabilities": { "elicitation": true },
                    "requestState": state,
                    "inputResponses": { key.clone(): { "action": "accept", "content": { "name": "octocat" } } }
                } }
        })
    };
    let send = |body: serde_json::Value| {
        let client = client.clone();
        let url = url.clone();
        async move {
            routed(client.post(&url), &body)
                .json(&body)
                .send()
                .await
                .expect("final send")
                .json::<serde_json::Value>()
                .await
                .expect("final json")
        }
    };

    let (ra, rb) = tokio::join!(send(retry(2)), send(retry(3)));

    // Both retries succeed with the same result; the commit fired only once.
    for r in [&ra, &rb] {
        assert_eq!(
            r.pointer("/result/content/0/text").and_then(|v| v.as_str()),
            Some("hello octocat"),
            "both concurrent finals must return the result: {r}"
        );
    }
    assert_eq!(
        CONCURRENT_FINAL_COMMITS.load(Ordering::SeqCst),
        1,
        "on_commit must fire exactly once across concurrent identical retries"
    );

    handle.abort();
}

#[tokio::test(flavor = "multi_thread")]
async fn distinct_answers_to_the_same_state_do_not_collide_in_the_cache() {
    // Two flows reach the SAME pre-answer requestState (same method/params/
    // principal, no nonce) but supply DIFFERENT inputResponses. The final cache
    // is keyed by the state tag plus the answers digest, so the second flow must
    // see its own answer reflected -- never the first flow's cached result.
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        Ok::<String, Error>(format!("hello {name}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();
    let key = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object")
        .keys()
        .next()
        .expect("one input request")
        .clone();

    // Two finals share the same state but answer with different names.
    let final_with = |id: i64, name: &str| {
        serde_json::json!({
            "jsonrpc": "2.0", "id": id, "method": "tools/call",
            "params": { "name": "greet", "arguments": {},
                "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                    "io.modelcontextprotocol/clientCapabilities": { "elicitation": true },
                    "requestState": state,
                    "inputResponses": { key.clone(): { "action": "accept", "content": { "name": name } } }
                } }
        })
    };

    let post = |body: serde_json::Value| {
        let client = client.clone();
        let url = url.clone();
        async move {
            routed(client.post(&url), &body)
                .json(&body)
                .send()
                .await
                .expect("send")
                .json::<serde_json::Value>()
                .await
                .expect("json")
        }
    };

    let r_a = post(final_with(2, "octocat")).await;
    let r_b = post(final_with(3, "monalisa")).await;

    assert_eq!(
        r_a.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("hello octocat"),
        "first flow gets its own answer: {r_a}"
    );
    assert_eq!(
        r_b.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("hello monalisa"),
        "second flow must NOT receive the first flow's cached result: {r_b}"
    );

    handle.abort();
}

#[tokio::test(flavor = "multi_thread")]
async fn effects_run_once_memo_caches_commit_fires_on_final_round() {
    FETCHES.store(0, Ordering::SeqCst);
    CHARGES.store(0, Ordering::SeqCst);
    RECEIPTS.store(0, Ordering::SeqCst);

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("effectful", |mut ctx: Context| async move {
        let price: i32 = ctx
            .memo("quote", async {
                FETCHES.fetch_add(1, Ordering::SeqCst);
                Ok(42)
            })
            .await?;
        ctx.once("charge", async {
            CHARGES.fetch_add(1, Ordering::SeqCst);
            Ok(())
        })
        .await?;
        ctx.on_commit(async {
            RECEIPTS.fetch_add(1, Ordering::SeqCst);
            Ok(())
        });
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        Ok::<String, Error>(format!("hello {name}, charged at {price}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // Round 1: input_required. Effect + memo ran; commit NOT yet.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "effectful", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    assert_eq!(
        r1["result"]["resultType"],
        serde_json::json!("input_required"),
        "round 1 must request input: {r1}"
    );
    assert_eq!(
        FETCHES.load(Ordering::SeqCst),
        1,
        "memo computed in round 1"
    );
    assert_eq!(CHARGES.load(Ordering::SeqCst), 1, "once ran in round 1");
    assert_eq!(
        RECEIPTS.load(Ordering::SeqCst),
        0,
        "commit must not fire yet"
    );

    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();
    let key = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object")
        .keys()
        .next()
        .expect("one input request")
        .clone();

    // Round 2: retry -> final result. memo HIT (no fetch), once HIT (no charge),
    // commit fires exactly once.
    let retry = serde_json::json!({
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": { "name": "effectful", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": true },
                "requestState": state,
                "inputResponses": { key: { "action": "accept", "content": { "name": "octocat" } } }
            } }
    });
    let r2: serde_json::Value = routed(client.post(&url), &retry)
        .json(&retry)
        .send()
        .await
        .expect("round 2 send")
        .json()
        .await
        .expect("round 2 json");
    assert_eq!(
        r2.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("hello octocat, charged at 42"),
        "round 2 must complete with memoized price: {r2}"
    );
    assert_eq!(
        FETCHES.load(Ordering::SeqCst),
        1,
        "memo not recomputed on round 2"
    );
    assert_eq!(
        CHARGES.load(Ordering::SeqCst),
        1,
        "once not re-run on round 2"
    );
    assert_eq!(
        RECEIPTS.load(Ordering::SeqCst),
        1,
        "commit fired exactly once on final round"
    );

    handle.abort();
}

#[tokio::test(flavor = "multi_thread")]
async fn oversized_request_state_is_rejected() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_max_state_bytes(256) // smaller than the memoized payload
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("bloated", |mut ctx: Context| async move {
        let big: String = ctx.memo("big", async { Ok("x".repeat(2048)) }).await?;
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let _ = ctx.elicit("name", params).await?;
        Ok::<String, Error>(big)
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "bloated", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("send")
        .json()
        .await
        .expect("json");
    let msg = r1
        .pointer("/error/message")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    assert!(
        msg.contains("requestState too large"),
        "oversized state must be rejected: {r1}"
    );

    handle.abort();
}

#[tokio::test(flavor = "multi_thread")]
async fn oversized_inbound_request_state_is_rejected_before_decoding() {
    // An untrusted client supplies a bogus `requestState` far larger than the
    // configured cap. It must be rejected on size *before* base64 decoding and
    // HMAC verification run, so the cap protects inbound retries -- not just the
    // outbound states the server mints.
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_max_state_bytes(256)
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let _ = ctx.elicit("name", params).await?;
        Ok::<String, Error>("ok".into())
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // A 4 KiB blob -- well over the 256-byte cap and never a valid signed state.
    let bogus_state = "A".repeat(4096);
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": true },
                "requestState": bogus_state
            } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("send")
        .json()
        .await
        .expect("json");
    let msg = r1
        .pointer("/error/message")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    assert!(
        msg.contains("exceeds the configured maximum size"),
        "oversized inbound state must be rejected before decoding: {r1}"
    );

    handle.abort();
}

#[tokio::test(flavor = "multi_thread")]
async fn replaying_request_state_against_a_different_request_is_rejected() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let _ = ctx.elicit("name", params).await?;
        Ok::<String, Error>("ok".into())
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // Round 1: bind state to `arguments: {}`.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();

    // Replay that state against a request with DIFFERENT arguments -> the
    // request binding no longer matches.
    let replay = serde_json::json!({
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": { "name": "greet", "arguments": { "x": 1 },
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": true },
                "requestState": state
            } }
    });
    let r2: serde_json::Value = routed(client.post(&url), &replay)
        .json(&replay)
        .send()
        .await
        .expect("replay send")
        .json()
        .await
        .expect("replay json");
    let msg = r2
        .pointer("/error/message")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    assert!(
        msg.contains("does not match this request"),
        "replayed state must be bound to the original request: {r2}"
    );

    handle.abort();
}

/// Two services that share a `requestState` secret -- one fleet-wide shared
/// secret is exactly that -- can decrypt each other's states. Give them a
/// method and parameters they both serve and the request binding matches too,
/// so without an audience the second one picks up a round the first started,
/// answers and all. The audience is what makes it refuse.
#[tokio::test(flavor = "multi_thread")]
async fn a_request_state_minted_by_another_service_is_rejected() {
    /// Both servers are the same MCP service by name, tool and parameters, and
    /// differ only in the identity they bind their states to.
    async fn spawn(addr: &str, audience: &str) -> tokio::task::JoinHandle<()> {
        let mut app = App::new()
            .with_request_state_secret(b"fleet-wide-secret")
            .with_request_state_audience(audience)
            .with_options(|o| o.with_http(|h| h.bind(addr).with_endpoint("/mcp")));

        app.map_tool("greet", |mut ctx: Context| async move {
            let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
                .with_required("name", "string")
                .into();
            let _ = ctx.elicit("name", params).await?;
            Ok::<String, Error>("ok".into())
        });

        tokio::spawn(async move { app.run().await })
    }

    let weather_addr = format!("127.0.0.1:{}", pick_free_port());
    let billing_addr = format!("127.0.0.1:{}", pick_free_port());
    let weather = spawn(&weather_addr, "https://weather.example.com/mcp").await;
    let billing = spawn(&billing_addr, "https://billing.example.com/mcp").await;
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");

    // Round 1 against the first service.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let weather_url = format!("http://{weather_addr}/mcp");
    let r1: serde_json::Value = routed(client.post(&weather_url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();

    // The same round, continued against the second one: same secret, same
    // method, same parameters -- only the service differs.
    let replay = serde_json::json!({
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "requestState": state,
            "inputResponses": { "name": { "action": "accept", "content": { "name": "Ada" } } },
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let billing_url = format!("http://{billing_addr}/mcp");
    let r2: serde_json::Value = routed(client.post(&billing_url), &replay)
        .json(&replay)
        .send()
        .await
        .expect("replay send")
        .json()
        .await
        .expect("replay json");

    let msg = r2
        .pointer("/error/message")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    assert!(
        msg.contains("audience mismatch"),
        "a state minted for another service must be refused: {r2}"
    );

    // And the same retry against the service that minted it goes through, so
    // what the audience refuses is the service, not the retry.
    let accepted: serde_json::Value = routed(client.post(&weather_url), &replay)
        .json(&replay)
        .send()
        .await
        .expect("retry send")
        .json()
        .await
        .expect("retry json");
    assert!(
        accepted.pointer("/result/content").is_some(),
        "the minting service must still accept its own state: {accepted}"
    );

    weather.abort();
    billing.abort();
}

#[tokio::test(flavor = "multi_thread")]
async fn eliciting_without_declared_capability_is_rejected() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let _ = ctx.elicit("name", params).await?;
        Ok::<String, Error>("ok".into())
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // Capabilities are declared, but without elicitation -> the server cannot
    // ask for input. An empty declaration is the point: the server must take
    // it at face value rather than infer anything.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {}, "_meta": {
            "io.modelcontextprotocol/protocolVersion": "2026-07-28",
            "io.modelcontextprotocol/clientCapabilities": {}
        } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("send")
        .json()
        .await
        .expect("json");
    let msg = r1
        .pointer("/error/message")
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    assert!(
        msg.contains("did not declare support"),
        "elicitation without declared capability must be rejected: {r1}"
    );
    // What the client is told to declare comes back in the spec's shape -- the
    // capability is an object, not a boolean -- and names the mode. A client
    // refused for a `url` request it cannot answer learns to declare `url`,
    // which "elicitation" on its own would not have told it.
    assert_eq!(
        r1.pointer("/error/data/requiredCapabilities"),
        Some(&serde_json::json!({ "elicitation": { "form": {} } })),
        "requiredCapabilities must name the missing capability: {r1}"
    );

    handle.abort();
}

// Separate counters from the reqwest `effectful` tool so the two tests can run
// in parallel without racing on shared process-global state.
static C_FETCHES: AtomicUsize = AtomicUsize::new(0);
static C_CHARGES: AtomicUsize = AtomicUsize::new(0);
static C_RECEIPTS: AtomicUsize = AtomicUsize::new(0);

/// Real end-to-end: the neva MCP **client** (not raw reqwest) drives the whole
/// MRTR loop -- `connect()` runs `server/discover`, `call_tool` enters
/// `run_with_mrtr`, and the registered elicitation handler answers the
/// server's request transparently across the round-trip.
#[tokio::test(flavor = "multi_thread")]
async fn client_drives_mrtr_elicitation_end_to_end() {
    C_FETCHES.store(0, Ordering::SeqCst);
    C_CHARGES.store(0, Ordering::SeqCst);
    C_RECEIPTS.store(0, Ordering::SeqCst);

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("client_effectful", |mut ctx: Context| async move {
        let price: i32 = ctx
            .memo("quote", async {
                C_FETCHES.fetch_add(1, Ordering::SeqCst);
                Ok(42)
            })
            .await?;
        ctx.once("charge", async {
            C_CHARGES.fetch_add(1, Ordering::SeqCst);
            Ok(())
        })
        .await?;
        ctx.on_commit(async {
            C_RECEIPTS.fetch_add(1, Ordering::SeqCst);
            Ok(())
        });
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        Ok::<String, Error>(format!("hello {name}, charged at {price}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    // The client declares `clientCapabilities.elicitation` automatically because
    // an elicitation handler is registered; the handler answers every prompt.
    let mut client =
        Client::new().with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));
    client.map_elicitation(|_params: ElicitRequestParams| async move {
        ElicitResult::accept().with_content(serde_json::json!({ "name": "octocat" }))
    });
    client.connect().await.expect("client connects");

    let resp = client
        .call_tool("client_effectful", ())
        .await
        .expect("tool call completes through the MRTR loop");

    let text = resp
        .content
        .first()
        .and_then(|c| c.as_text())
        .map(|t| t.text.as_str());
    assert_eq!(
        text,
        Some("hello octocat, charged at 42"),
        "client should receive the final, memoized result"
    );
    assert!(!resp.is_error, "final result must not be an error");

    // The whole loop ran once front-to-back: effect once, memo once, commit once.
    assert_eq!(C_FETCHES.load(Ordering::SeqCst), 1, "memo computed once");
    assert_eq!(C_CHARGES.load(Ordering::SeqCst), 1, "once ran once");
    assert_eq!(C_RECEIPTS.load(Ordering::SeqCst), 1, "commit fired once");

    client.disconnect().await.ok();
    handle.abort();
}

/// A batch whose requests elicit must be driven through the MRTR loop just like
/// single sends: each eliciting `tools/call` is fulfilled and re-issued (with
/// `inputResponses` + the echoed `requestState`) until it produces a final
/// result, never leaving the protocol-intermediate `input_required` as the
/// batch's answer. Non-eliciting requests and notifications ride the same batch,
/// keep their slots in order, and notifications produce no slot.
#[tokio::test(flavor = "multi_thread")]
async fn client_drives_mrtr_across_a_batch_end_to_end() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        Ok::<String, Error>(format!("hello {name}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let mut client =
        Client::new().with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));
    client.map_elicitation(|_params: ElicitRequestParams| async move {
        ElicitResult::accept().with_content(serde_json::json!({ "name": "octocat" }))
    });
    client.connect().await.expect("client connects");

    // A mixed batch: a non-eliciting list, two eliciting tool calls, and a
    // fire-and-forget notification interleaved between them.
    let responses = client
        .batch()
        .list_tools()
        .call_tool("greet", ())
        .notify("notifications/progress", None)
        .call_tool("greet", ())
        .send()
        .await
        .expect("batch completes through the MRTR loop");

    // Three slots (the notification produces none), in request order.
    assert_eq!(
        responses.len(),
        3,
        "one slot per request, notifications none"
    );

    // Slot 0: the non-eliciting tools/list result.
    let tools = responses[0]
        .clone()
        .into_result::<neva::types::ListToolsResult>()
        .expect("tools/list result");
    assert!(
        tools.tools.iter().any(|t| t.name == "greet"),
        "first slot is the tools/list result"
    );

    // Slots 1 & 2: both eliciting calls were driven to their final results,
    // never returning `input_required`.
    for (slot, resp) in [(1usize, &responses[1]), (2, &responses[2])] {
        let result = resp
            .clone()
            .into_result::<neva::types::CallToolResponse>()
            .unwrap_or_else(|e| panic!("slot {slot} is a final tools/call result: {e}"));
        let text = result
            .content
            .first()
            .and_then(|c| c.as_text())
            .map(|t| t.text.as_str());
        assert_eq!(
            text,
            Some("hello octocat"),
            "slot {slot} must carry the elicited final result"
        );
        assert!(!result.is_error, "slot {slot} must not be an error");
    }

    client.disconnect().await.ok();
    handle.abort();
}

/// One slot failing mid-batch must not roll back the rest of the batch. Here a
/// three-request batch elicits on every slot; after the round-2 retry one tool
/// returns `Err` (surfaced as an `is_error` `CallToolResponse`, not a JSON-RPC
/// error), while the other two complete normally. The batch still resolves to
/// `Ok` with all three slots filled in order -- the failing slot carries the
/// error result, its neighbours carry their final answers. This locks down that
/// a per-slot tool failure is isolated, not fatal to the whole batch.
#[tokio::test(flavor = "multi_thread")]
async fn batch_isolates_a_single_slot_failure_after_elicitation() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        Ok::<String, Error>(format!("hello {name}"))
    });

    // Same elicitation shape, but fails *after* the round-2 input arrives.
    app.map_tool("boom", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let _ = ctx.elicit("name", params).await?;
        Err::<String, Error>(Error::new(
            neva::error::ErrorCode::InternalError,
            "boom failed after elicitation",
        ))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let mut client =
        Client::new().with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));
    client.map_elicitation(|_params: ElicitRequestParams| async move {
        ElicitResult::accept().with_content(serde_json::json!({ "name": "octocat" }))
    });
    client.connect().await.expect("client connects");

    let responses = client
        .batch()
        .call_tool("greet", ())
        .call_tool("boom", ())
        .call_tool("greet", ())
        .send()
        .await
        .expect("batch resolves even though one slot's tool failed");

    assert_eq!(responses.len(), 3, "one slot per request, all preserved");

    // Slots 0 and 2 completed normally through the MRTR loop.
    for slot in [0usize, 2] {
        let result = responses[slot]
            .clone()
            .into_result::<neva::types::CallToolResponse>()
            .unwrap_or_else(|e| panic!("slot {slot} is a final tools/call result: {e}"));
        let text = result
            .content
            .first()
            .and_then(|c| c.as_text())
            .map(|t| t.text.as_str());
        assert_eq!(
            text,
            Some("hello octocat"),
            "slot {slot} completed normally"
        );
        assert!(!result.is_error, "slot {slot} must not be an error");
    }

    // Slot 1 carries the isolated failure as an `is_error` result.
    let failed = responses[1]
        .clone()
        .into_result::<neva::types::CallToolResponse>()
        .expect("a failed tool still yields an is_error CallToolResponse, not a dropped slot");
    assert!(
        failed.is_error,
        "the failing slot must surface its error result"
    );

    client.disconnect().await.ok();
    handle.abort();
}

/// The MRTR round cap is configurable via `with_max_mrtr_rounds`, and counts
/// *re-issues* -- not the initial send. A cap of 0 sends the request once and
/// fails the moment it elicits, so the client gives up with the max-rounds error
/// instead of looping the default 8 times.
#[tokio::test(flavor = "multi_thread")]
async fn configurable_max_rounds_caps_the_mrtr_loop() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let _ = ctx.elicit("name", params).await?;
        Ok::<String, Error>("done".into())
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let mut client = Client::new().with_options(|o| {
        o.with_http(|h| h.bind(&addr).with_endpoint("/mcp"))
            .with_max_mrtr_rounds(0)
    });
    client.map_elicitation(|_params: ElicitRequestParams| async move {
        ElicitResult::accept().with_content(serde_json::json!({ "name": "octocat" }))
    });
    client.connect().await.expect("client connects");

    let err = client
        .call_tool("greet", ())
        .await
        .expect_err("a 0-retry cap must not let the elicitation converge");
    assert!(
        err.to_string().contains("maximum number of rounds"),
        "expected the max-rounds error, got: {err}"
    );

    client.disconnect().await.ok();
    handle.abort();
}

/// The cap counts re-issues, not the initial send: `with_max_mrtr_rounds(1)`
/// must let a normal one-question flow converge (initial send -> `input_required`
/// -> one retry -> final), rather than spending its only iteration on the first
/// send and erroring before it can retry.
#[tokio::test(flavor = "multi_thread")]
async fn one_retry_budget_completes_a_single_question_flow() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let res = ctx.elicit("name", params).await?;
        let name = res
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        Ok::<String, Error>(format!("hello {name}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let mut client = Client::new().with_options(|o| {
        o.with_http(|h| h.bind(&addr).with_endpoint("/mcp"))
            .with_max_mrtr_rounds(1)
    });
    client.map_elicitation(|_params: ElicitRequestParams| async move {
        ElicitResult::accept().with_content(serde_json::json!({ "name": "octocat" }))
    });
    client.connect().await.expect("client connects");

    let res = client
        .call_tool("greet", ())
        .await
        .expect("a 1-retry budget must let a one-question flow converge");
    let text = res
        .content
        .first()
        .and_then(|c| c.as_text())
        .map(|t| t.text.as_str());
    assert_eq!(text, Some("hello octocat"));
    assert!(!res.is_error, "final result must not be an error");

    client.disconnect().await.ok();
    handle.abort();
}

/// #85: sampling returns as an MRTR input-request kind. The wire contract is
/// the same two rounds elicitation uses -- only the envelope's `method` and the
/// result type differ.
#[tokio::test(flavor = "multi_thread")]
async fn tool_samples_then_completes_over_two_rounds() {
    use neva::types::sampling::{CreateMessageRequestParams, SamplingMessage};

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("summarize", |mut ctx: Context| async move {
        let params = CreateMessageRequestParams::new()
            .with_message(SamplingMessage::user().with("Summarize the repo"));
        #[allow(deprecated)]
        let res = ctx.sample("summary", params).await?;
        let text = res
            .content
            .first()
            .and_then(|c| c.as_text())
            .map(|t| t.text.clone())
            .unwrap_or_default();
        Ok::<String, Error>(format!("summary: {text}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "summarize", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "sampling": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    assert_eq!(
        r1["result"]["resultType"],
        serde_json::json!("input_required"),
        "round 1 must request input: {r1}"
    );
    let state = r1["result"]["requestState"]
        .as_str()
        .expect("requestState present")
        .to_string();
    let requests = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object");
    let key = requests.keys().next().expect("one input request").clone();
    assert_eq!(
        requests[&key]["method"],
        serde_json::json!("sampling/createMessage"),
        "the envelope must name the sampling method: {r1}"
    );

    let retry = serde_json::json!({
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": { "name": "summarize", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "sampling": true },
                "requestState": state,
                "inputResponses": { key: {
                    "role": "assistant",
                    "content": { "type": "text", "text": "it is a Rust MCP SDK" },
                    "model": "test-model"
                } }
            } }
    });
    let r2: serde_json::Value = routed(client.post(&url), &retry)
        .json(&retry)
        .send()
        .await
        .expect("round 2 send")
        .json()
        .await
        .expect("round 2 json");
    assert_eq!(
        r2.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("summary: it is a Rust MCP SDK"),
        "round 2 must complete with the sampled text: {r2}"
    );

    handle.abort();
}

/// #85: roots likewise. The envelope carries `roots/list` and the answer is a
/// `ListRootsResult`.
#[tokio::test(flavor = "multi_thread")]
async fn tool_lists_roots_then_completes_over_two_rounds() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("scan", |mut ctx: Context| async move {
        #[allow(deprecated)]
        let roots = ctx.list_roots("dirs").await?;
        let names = roots
            .roots
            .iter()
            .map(|r| r.uri.to_string())
            .collect::<Vec<_>>()
            .join(", ");
        Ok::<String, Error>(format!("scanning {names}"))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "scan", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "roots": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");
    let state = r1["result"]["requestState"]
        .as_str()
        .unwrap_or_else(|| panic!("requestState present: {r1}"))
        .to_string();
    let requests = r1["result"]["inputRequests"]
        .as_object()
        .expect("inputRequests object");
    let key = requests.keys().next().expect("one input request").clone();
    assert_eq!(
        requests[&key]["method"],
        serde_json::json!("roots/list"),
        "the envelope must name the roots method: {r1}"
    );

    let retry = serde_json::json!({
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": { "name": "scan", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "roots": true },
                "requestState": state,
                "inputResponses": { key: {
                    "roots": [{ "uri": "file:///work", "name": "work" }]
                } }
            } }
    });
    let r2: serde_json::Value = routed(client.post(&url), &retry)
        .json(&retry)
        .send()
        .await
        .expect("round 2 send")
        .json()
        .await
        .expect("round 2 json");
    assert_eq!(
        r2.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("scanning file:///work"),
        "round 2 must complete with the listed roots: {r2}"
    );

    handle.abort();
}

/// The real client fulfils both deprecated kinds through the MRTR loop --
/// sampling from its configured handler, roots from its configured list -- with
/// no server->client push channel involved.
#[tokio::test(flavor = "multi_thread")]
async fn client_drives_sampling_and_roots_end_to_end() {
    use neva::types::sampling::{CreateMessageRequestParams, CreateMessageResult, SamplingMessage};

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    // Two different kinds in one call: each is a separate round, and both
    // replay from the same `requestState` log.
    app.map_tool("audit", |mut ctx: Context| async move {
        #[allow(deprecated)]
        let roots = ctx.list_roots("dirs").await?;
        let params = CreateMessageRequestParams::new()
            .with_message(SamplingMessage::user().with("Describe these roots"));
        #[allow(deprecated)]
        let sampled = ctx.sample("describe", params).await?;
        let text = sampled
            .content
            .first()
            .and_then(|c| c.as_text())
            .map(|t| t.text.clone())
            .unwrap_or_default();
        Ok::<String, Error>(format!("{} root(s): {text}", roots.roots.len()))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let mut client =
        Client::new().with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));
    // Roots are configured data, so declaring the capability is implied by
    // having any: no handler is registered for them.
    #[allow(deprecated)]
    client.add_root("file:///work", "work");
    #[allow(deprecated)]
    client.map_sampling(|_params: CreateMessageRequestParams| async move {
        CreateMessageResult::assistant().with_content("looks fine")
    });
    client.connect().await.expect("client connects");

    let resp = client
        .call_tool("audit", ())
        .await
        .expect("tool call completes through the MRTR loop");

    let text = resp
        .content
        .first()
        .and_then(|c| c.as_text())
        .map(|t| t.text.as_str());
    assert_eq!(
        text,
        Some("1 root(s): looks fine"),
        "the client must fulfil both deprecated kinds"
    );
    assert!(!resp.is_error, "final result must not be an error");

    client.disconnect().await.ok();
    handle.abort();
}

/// A client that opted into roots but exposes none must still be askable -- an
/// empty `ListRootsResult` is a valid answer, and gating it out would leave the
/// server unable to complete the call at all.
#[tokio::test(flavor = "multi_thread")]
async fn a_client_with_an_empty_roots_list_still_answers() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("scan", |mut ctx: Context| async move {
        #[allow(deprecated)]
        let roots = ctx.list_roots("dirs").await?;
        Ok::<String, Error>(format!("{} root(s)", roots.roots.len()))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    // Explicit opt-in, no roots added.
    #[allow(deprecated)]
    let mut client = Client::new().with_options(|o| {
        o.with_http(|h| h.bind(&addr).with_endpoint("/mcp"))
            .with_roots(|roots| roots)
    });
    client.connect().await.expect("client connects");

    let resp = client
        .call_tool("scan", ())
        .await
        .expect("the round-trip must complete");
    let text = resp
        .content
        .first()
        .and_then(|c| c.as_text())
        .map(|t| t.text.as_str());
    assert_eq!(text, Some("0 root(s)"));
    assert!(!resp.is_error, "an empty roots list is a valid answer");

    client.disconnect().await.ok();
    handle.abort();
}

/// The server must not ask for a kind the client never declared: a client with
/// no sampling handler declares `sampling: false`, and the request is rejected
/// rather than stalling the loop.
#[tokio::test(flavor = "multi_thread")]
async fn sampling_without_declared_capability_is_rejected() {
    use neva::types::sampling::{CreateMessageRequestParams, SamplingMessage};

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("summarize", |mut ctx: Context| async move {
        let params =
            CreateMessageRequestParams::new().with_message(SamplingMessage::user().with("hi"));
        #[allow(deprecated)]
        let res = ctx.sample("summary", params).await?;
        Ok::<String, Error>(format!("{:?}", res.content))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // Elicitation is declared, sampling is not.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "summarize", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28", "io.modelcontextprotocol/clientCapabilities": { "elicitation": true } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("send")
        .json()
        .await
        .expect("json");

    let message = r1
        .pointer("/result/content/0/text")
        .or_else(|| r1.pointer("/error/message"))
        .and_then(|v| v.as_str())
        .unwrap_or_default();
    assert!(
        message.contains("sampling/createMessage"),
        "the rejection must name the kind the client did not declare: {r1}"
    );

    handle.abort();
}

/// A handler that needs three inputs spends one round on them, not three.
///
/// Each helper records its request and hands back the same "input required"
/// signal, so it is the handler's `?` that decides: unwind at the first miss and
/// the round carries one request; hold the `?` until everything has been asked
/// for and they all travel together.
#[tokio::test(flavor = "multi_thread")]
async fn one_round_carries_every_input_the_handler_asked_for() {
    use neva::types::sampling::{CreateMessageRequestParams, SamplingMessage};

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("intake", |mut ctx: Context| async move {
        let form: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        let sampling = CreateMessageRequestParams::new()
            .with_message(SamplingMessage::user().with("Greet them"))
            .with_max_tokens(50);

        let name = ctx.elicit("who", form).await;
        #[allow(deprecated)]
        let greeting = ctx.sample("greeting", sampling).await;
        #[allow(deprecated)]
        let roots = ctx.list_roots("dirs").await;

        let (name, _greeting, roots) = (name?, greeting?, roots?);
        let name = name
            .content
            .and_then(|c| c.get("name").and_then(|v| v.as_str().map(str::to_owned)))
            .unwrap_or_else(|| "stranger".into());
        Ok::<String, Error>(format!("{name} has {} roots", roots.roots.len()))
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");
    let caps = serde_json::json!({ "elicitation": {}, "sampling": {}, "roots": {} });

    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "intake", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": caps } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");

    let requests = r1["result"]["inputRequests"]
        .as_object()
        .unwrap_or_else(|| panic!("inputRequests object: {r1}"));
    assert_eq!(requests.len(), 3, "all three must ride one round: {r1}");
    let mut methods = requests
        .values()
        .filter_map(|r| r["method"].as_str())
        .collect::<Vec<_>>();
    methods.sort_unstable();
    assert_eq!(
        methods,
        ["elicitation/create", "roots/list", "sampling/createMessage"],
        "every kind must be named in the round: {r1}"
    );

    let state = r1["result"]["requestState"]
        .as_str()
        .unwrap_or_else(|| panic!("requestState present: {r1}"))
        .to_string();

    let retry = serde_json::json!({
        "jsonrpc": "2.0", "id": 2, "method": "tools/call",
        "params": { "name": "intake", "arguments": {},
            "requestState": state,
            "inputResponses": {
                "who": { "action": "accept", "content": { "name": "octocat" } },
                "greeting": { "role": "assistant", "content": { "type": "text", "text": "hi" }, "model": "m" },
                "dirs": { "roots": [{ "uri": "file:///work", "name": "work" }] }
            },
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": caps } }
    });
    let r2: serde_json::Value = routed(client.post(&url), &retry)
        .json(&retry)
        .send()
        .await
        .expect("round 2 send")
        .json()
        .await
        .expect("round 2 json");
    assert_eq!(
        r2.pointer("/result/content/0/text")
            .and_then(|v| v.as_str()),
        Some("octocat has 1 roots"),
        "one retry answering all three must finish the call: {r2}"
    );

    handle.abort();
}

/// An answer of the wrong shape is the client getting the protocol wrong, and
/// is answered as such.
///
/// It must not be re-requested -- asking again for a key the client already
/// answered wrongly is how a chain loops -- and it must not arrive as an in-band
/// tool error either, which on the wire is a *complete* result and reads as the
/// call having run and failed.
#[tokio::test(flavor = "multi_thread")]
async fn an_answer_of_the_wrong_shape_is_a_protocol_error() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("greet", |mut ctx: Context| async move {
        let params: ElicitRequestParams = ElicitRequestParams::form("Your name?")
            .with_required("name", "string")
            .into();
        ctx.elicit("who", params).await?;
        Ok::<String, Error>("done".into())
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // A number where an elicitation result belongs.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "greet", "arguments": {},
            "inputResponses": { "who": 12345 },
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "elicitation": {} } } }
    });
    let r: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("send")
        .json()
        .await
        .expect("json");

    assert_eq!(
        r["error"]["code"], -32602,
        "a malformed answer must be a JSON-RPC error, not a result: {r}"
    );
    assert!(
        r["error"]["message"]
            .as_str()
            .unwrap_or_default()
            .contains("elicitation/create"),
        "the error must name the kind the answer failed to be: {r}"
    );

    handle.abort();
}

/// A handler can read what the caller declared and ask only for that.
///
/// Without it the only feedback is the refusal, which ends the call -- so a tool
/// that could have got its answer another way never gets the chance.
#[tokio::test(flavor = "multi_thread")]
async fn a_handler_asks_only_for_what_the_caller_declared() {
    use neva::types::sampling::{CreateMessageRequestParams, SamplingMessage};

    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new()
        .with_request_state_secret(b"test-secret")
        .with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_tool("ask", |mut ctx: Context| async move {
        if ctx.client_capabilities().elicitation.is_some() {
            let form: ElicitRequestParams = ElicitRequestParams::form("Your name?")
                .with_required("name", "string")
                .into();
            ctx.elicit("who", form).await?;
            return Ok::<String, Error>("asked the user".into());
        }
        let sampling = CreateMessageRequestParams::new()
            .with_message(SamplingMessage::user().with("Guess a name"))
            .with_max_tokens(50);
        #[allow(deprecated)]
        ctx.sample("who", sampling).await?;
        Ok::<String, Error>("asked the model".into())
    });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // Sampling only: the handler must not reach for elicitation.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "tools/call",
        "params": { "name": "ask", "arguments": {},
            "_meta": { "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": { "sampling": {} } } }
    });
    let r1: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("round 1 send")
        .json()
        .await
        .expect("round 1 json");

    assert_eq!(
        r1["result"]["inputRequests"]["who"]["method"],
        serde_json::json!("sampling/createMessage"),
        "the handler must ask the kind the caller declared: {r1}"
    );

    handle.abort();
}

fn pick_free_port() -> u16 {
    let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
    let port = listener.local_addr().unwrap().port();
    drop(listener);
    port
}

/// Attaches the routing headers MCP 2026-07-28 requires on every request, the
/// way a conforming client derives them: from the body it is about to send.
/// `requestState` and `inputResponses` are protocol fields on the methods MRTR
/// runs on -- `tools/call`, `prompts/get`, `resources/read` -- and nowhere
/// else. A custom method registered with `map_handler` owns its own params, so
/// a numeric `requestState` there is a perfectly good argument and judging it
/// by the MRTR shapes would refuse a request this server was written to serve.
#[tokio::test(flavor = "multi_thread")]
async fn a_custom_method_owns_its_own_params() {
    let port = pick_free_port();
    let addr = format!("127.0.0.1:{port}");
    let mut app = App::new().with_options(|o| o.with_http(|h| h.bind(&addr).with_endpoint("/mcp")));

    app.map_handler("custom/echo", || async move { "served" });

    let handle = tokio::spawn(async move { app.run().await });
    tokio::time::sleep(std::time::Duration::from_millis(300)).await;

    let client = reqwest::Client::builder()
        .no_proxy()
        .build()
        .expect("test client");
    let url = format!("http://{addr}/mcp");

    // Both names, both of a shape MRTR would refuse.
    let call = serde_json::json!({
        "jsonrpc": "2.0", "id": 1, "method": "custom/echo",
        "params": {
            "requestState": 42,
            "inputResponses": ["not", "an", "object"],
            "_meta": {
                "io.modelcontextprotocol/protocolVersion": "2026-07-28",
                "io.modelcontextprotocol/clientCapabilities": {}
            }
        }
    });

    let resp: serde_json::Value = routed(client.post(&url), &call)
        .json(&call)
        .send()
        .await
        .expect("send")
        .json()
        .await
        .expect("json");

    assert!(
        resp.get("error").is_none(),
        "a custom method's own params must reach its handler: {resp}"
    );

    handle.abort();
}

fn routed(req: reqwest::RequestBuilder, body: &serde_json::Value) -> reqwest::RequestBuilder {
    let method = body["method"].as_str().unwrap_or_default();
    let req = req
        .header("MCP-Protocol-Version", "2026-07-28")
        .header("Mcp-Method", method);
    let name = match method {
        "tools/call" | "prompts/get" => body.pointer("/params/name"),
        "resources/read" => body.pointer("/params/uri"),
        "tasks/get" | "tasks/update" | "tasks/cancel" => body.pointer("/params/taskId"),
        _ => None,
    };
    match name.and_then(|v| v.as_str()) {
        Some(name) => req.header("Mcp-Name", name),
        None => req,
    }
}