fastmcp-protocol 0.12.0

MCP protocol types and JSON-RPC implementation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
//! JSON-RPC 2.0 message types.

use std::borrow::Cow;
use std::collections::BTreeSet;

use serde::de::Error as _;
use serde::ser::Error as _;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use serde_json::Value;
use serde_json::value::RawValue;

use crate::common_types::JsonInteger;

/// The JSON-RPC version string. Used as a static reference to avoid allocations.
pub const JSONRPC_VERSION: &str = "2.0";

/// Maximum encoded bytes in one JSON-RPC string ID, including quotes.
pub const MAX_JSONRPC_STRING_ID_ENCODED_BYTES: usize = 256;

/// Default maximum nesting depth for raw JSON admission.
pub const MAX_RAW_JSON_NESTING_DEPTH: usize = 64;
/// Default maximum aggregate object members and array elements for raw JSON admission.
pub const MAX_RAW_JSON_CONTAINER_ENTRIES: usize = 100_000;
/// Maximum encoded bytes in one JSON number token before typed decoding.
pub const MAX_RAW_JSON_NUMBER_BYTES: usize = 4 * 1024;
/// Maximum aggregate encoded number bytes in one admitted JSON document.
pub const MAX_RAW_JSON_AGGREGATE_NUMBER_BYTES: usize = 256 * 1024;
/// Maximum absolute decimal exponent accepted by raw JSON admission.
pub const MAX_RAW_JSON_EXPONENT: usize = 10_000;

/// A stable reason why raw JSON was rejected before typed decoding.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RawJsonAdmissionError {
    DocumentTooLarge,
    InvalidUtf8,
    ByteOrderMark,
    InvalidSyntax,
    TopLevelBatch,
    TopLevelNotObject,
    DuplicateObjectMember,
    NestingTooDeep,
    TooManyContainerEntries,
    NumberTooLong,
    TooManyNumberBytes,
    ExponentTooLarge,
    TooManyDecodedStringBytes,
}

impl std::fmt::Display for RawJsonAdmissionError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let message = match self {
            Self::DocumentTooLarge => "JSON document exceeds the configured byte limit",
            Self::InvalidUtf8 => "JSON document is not strict UTF-8",
            Self::ByteOrderMark => "JSON document contains a UTF-8 byte-order mark",
            Self::InvalidSyntax => "invalid JSON syntax during raw admission",
            Self::TopLevelBatch => "JSON-RPC batch arrays are not supported",
            Self::TopLevelNotObject => "JSON-RPC top-level value must be an object",
            Self::DuplicateObjectMember => "duplicate JSON object member",
            Self::NestingTooDeep => "JSON nesting limit exceeded",
            Self::TooManyContainerEntries => "JSON container-entry limit exceeded",
            Self::NumberTooLong => "JSON number-token limit exceeded",
            Self::TooManyNumberBytes => "aggregate JSON number-byte limit exceeded",
            Self::ExponentTooLarge => "JSON exponent limit exceeded",
            Self::TooManyDecodedStringBytes => "decoded JSON string-byte limit exceeded",
        };
        formatter.write_str(message)
    }
}

impl std::error::Error for RawJsonAdmissionError {}

/// Maximum retained bytes in one redacted raw-admission path segment.
pub const MAX_RAW_JSON_PATH_SEGMENT_BYTES: usize = 64;
/// Maximum rendered segments in one redacted raw-admission path.
pub const MAX_RAW_JSON_PATH_SEGMENTS: usize = 16;

/// Structural policy for the single top-level value a raw document may carry.
///
/// The bounded scanning pass itself is role-neutral: duplicate members,
/// depth, container entries, number lexemes, decoded string bytes, strict
/// UTF-8, and byte-order marks are enforced identically for every consumer.
/// Only the admitted top-level shape differs, so a security document is never
/// classified with JSON-RPC batch vocabulary and a JSON-RPC frame still
/// refuses a batch by name.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum RawJsonTopLevel {
    /// One top-level JSON object. A top-level array is reported as
    /// [`RawJsonAdmissionError::TopLevelBatch`] because JSON-RPC ingress
    /// refuses batches deliberately and by name.
    JsonRpcObject,
    /// One top-level JSON object for a security-bearing document such as
    /// OAuth/OIDC/PRM/CIMD/DCR metadata, a token response, a JWKS or JWK, or
    /// a decoded compact-JWS protected header or claims set. A top-level
    /// array is an ordinary shape violation here, not a JSON-RPC batch.
    SecurityDocumentObject,
    /// One top-level JSON value of any kind, still fully bounded.
    AnyValue,
}

/// One structural step in a redacted raw-admission path.
#[derive(Clone, Debug, Eq, PartialEq)]
enum RawJsonPathSegment {
    Member(String),
    Index(usize),
}

/// A raw admission failure together with the redacted structural path at
/// which the bounded scanner detected it.
///
/// The path names only structure: object member names are reduced to
/// `[A-Za-z0-9_.-]` with every other byte replaced by `*` and the segment
/// truncated to [`MAX_RAW_JSON_PATH_SEGMENT_BYTES`], and array steps carry
/// only their index. No admitted value, string content, or number lexeme is
/// ever reproduced, so a rejection diagnostic cannot leak the document that
/// caused it.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RawJsonAdmissionFailure {
    error: RawJsonAdmissionError,
    path: String,
}

impl RawJsonAdmissionFailure {
    /// Returns the stable structural reason the document was refused.
    #[must_use]
    pub const fn error(&self) -> RawJsonAdmissionError {
        self.error
    }

    /// Returns the redacted JSON-Pointer-style path of the refusal.
    ///
    /// The whole-document boundary — byte limit, byte-order mark, strict
    /// UTF-8, and top-level shape — reports the empty root path.
    #[must_use]
    pub fn path(&self) -> &str {
        &self.path
    }

    const fn at_root(error: RawJsonAdmissionError) -> Self {
        Self {
            error,
            path: String::new(),
        }
    }
}

impl std::fmt::Display for RawJsonAdmissionFailure {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.path.is_empty() {
            self.error.fmt(formatter)
        } else {
            write!(formatter, "{} at {}", self.error, self.path)
        }
    }
}

impl std::error::Error for RawJsonAdmissionFailure {}

impl From<RawJsonAdmissionFailure> for RawJsonAdmissionError {
    fn from(failure: RawJsonAdmissionFailure) -> Self {
        failure.error
    }
}

/// Admission failure for a complete strict JSON-RPC document.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum JsonRpcAdmissionError {
    /// The raw JSON boundary rejected the document before typed decoding.
    Raw(RawJsonAdmissionError),
    /// The raw document was valid JSON but not a valid JSON-RPC envelope.
    InvalidEnvelope,
}

impl std::fmt::Display for JsonRpcAdmissionError {
    fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Raw(error) => error.fmt(formatter),
            Self::InvalidEnvelope => formatter.write_str("invalid JSON-RPC envelope"),
        }
    }
}

impl std::error::Error for JsonRpcAdmissionError {}

/// Admit one complete raw JSON-RPC document before any typed decoding.
///
/// The caller chooses the document/body byte bound. The fixed structural
/// limits prevent duplicate-member ambiguity and bound recursive parsing,
/// decoded string bytes, and numeric lexemes before `serde_json` receives the
/// document. Only one top-level object is admitted; JSON-RPC batch arrays are
/// rejected deliberately.
pub fn admit_raw_jsonrpc_document(
    bytes: &[u8],
    document_byte_limit: usize,
) -> Result<(), RawJsonAdmissionError> {
    admit_raw_json_document(bytes, document_byte_limit, RawJsonTopLevel::JsonRpcObject)
        .map_err(RawJsonAdmissionFailure::into)
}

/// One top-level member of an admitted JSON-RPC envelope.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct RawJsonRpcEnvelopeMember {
    /// The member name after JSON string unescaping.
    pub name: String,
    /// The byte span of the member's value token in the admitted document,
    /// excluding the whitespace around it.
    pub value: std::ops::Range<usize>,
}

/// Admits a raw JSON-RPC document exactly as [`admit_raw_jsonrpc_document`]
/// does and returns its top-level members in document order.
///
/// Recording the envelope during the one authoritative pass lets a caller
/// classify the message without scanning the document a second time.
pub fn admit_raw_jsonrpc_envelope(
    bytes: &[u8],
    document_byte_limit: usize,
) -> Result<Vec<RawJsonRpcEnvelopeMember>, RawJsonAdmissionError> {
    scan_raw_json_document(
        bytes,
        document_byte_limit,
        RawJsonTopLevel::JsonRpcObject,
        Some(Vec::new()),
    )
    .map(Option::unwrap_or_default)
    .map_err(RawJsonAdmissionFailure::into)
}

/// Whether the UTF-8 byte-order mark occurs anywhere in `bytes`. This is the
/// predicate of comparing every three-byte window, found by seeking the mark's
/// lead byte; the windowed comparison cost more than the admission scan itself.
fn contains_byte_order_mark(bytes: &[u8]) -> bool {
    const BYTE_ORDER_MARK: [u8; 3] = [0xef, 0xbb, 0xbf];
    let mut rest = bytes;
    while let Some(lead) = rest.iter().position(|byte| *byte == BYTE_ORDER_MARK[0]) {
        if rest[lead..].starts_with(&BYTE_ORDER_MARK) {
            return true;
        }
        rest = &rest[lead + 1..];
    }
    false
}

/// Admit one complete raw JSON document before any typed decoding.
///
/// This is the single bounded streaming pass every FastMCP JSON consumer
/// shares. It is deliberately not a JSON-RPC-only serde hook: the caller
/// selects the document byte bound and the admitted top-level shape, and
/// every other rule — duplicate object members at every nesting level,
/// nesting depth, aggregate container entries, per-number and aggregate
/// numeric lexeme bytes, absolute exponent, decoded string bytes, strict
/// UTF-8, and byte-order-mark rejection — is identical for JSON-RPC
/// envelopes and for security-bearing documents such as OAuth/OIDC/PRM/CIMD/
/// DCR metadata, token responses, JWKS and JWK documents, and decoded
/// compact-JWS protected headers and claim sets.
///
/// Refusals carry a redacted structural path so two consumers of the same
/// document receive the same stable diagnostic without either of them
/// reproducing admitted content.
pub fn admit_raw_json_document(
    bytes: &[u8],
    document_byte_limit: usize,
    top_level: RawJsonTopLevel,
) -> Result<(), RawJsonAdmissionFailure> {
    scan_raw_json_document(bytes, document_byte_limit, top_level, None)?;
    Ok(())
}

/// The admission pass itself. When `top_level_members` is present, the root
/// object's members are appended to it as they are admitted.
fn scan_raw_json_document(
    bytes: &[u8],
    document_byte_limit: usize,
    top_level: RawJsonTopLevel,
    top_level_members: Option<Vec<RawJsonRpcEnvelopeMember>>,
) -> Result<Option<Vec<RawJsonRpcEnvelopeMember>>, RawJsonAdmissionFailure> {
    if bytes.len() > document_byte_limit {
        return Err(RawJsonAdmissionFailure::at_root(
            RawJsonAdmissionError::DocumentTooLarge,
        ));
    }
    if contains_byte_order_mark(bytes) {
        return Err(RawJsonAdmissionFailure::at_root(
            RawJsonAdmissionError::ByteOrderMark,
        ));
    }
    let Ok(input) = std::str::from_utf8(bytes) else {
        return Err(RawJsonAdmissionFailure::at_root(
            RawJsonAdmissionError::InvalidUtf8,
        ));
    };
    let mut scanner = RawJsonScanner::new(input, document_byte_limit);
    scanner.top_level_members = top_level_members;
    scanner.skip_whitespace();
    let scanned = match (scanner.peek(), top_level) {
        (Some(b'{'), _) => scanner.parse_object(0),
        (Some(b'['), RawJsonTopLevel::JsonRpcObject) => {
            return Err(RawJsonAdmissionFailure::at_root(
                RawJsonAdmissionError::TopLevelBatch,
            ));
        }
        (Some(b'['), RawJsonTopLevel::SecurityDocumentObject) => {
            return Err(RawJsonAdmissionFailure::at_root(
                RawJsonAdmissionError::TopLevelNotObject,
            ));
        }
        (Some(_), RawJsonTopLevel::AnyValue) => scanner.parse_value(0),
        _ => {
            return Err(RawJsonAdmissionFailure::at_root(
                RawJsonAdmissionError::TopLevelNotObject,
            ));
        }
    };
    if let Err(error) = scanned {
        return Err(scanner.failure(error));
    }
    scanner.skip_whitespace();
    if scanner.position != scanner.bytes.len() {
        return Err(RawJsonAdmissionFailure::at_root(
            RawJsonAdmissionError::InvalidSyntax,
        ));
    }
    Ok(scanner.top_level_members)
}

/// Decode a complete JSON-RPC message only after raw-document admission.
pub fn decode_strict_jsonrpc_message(
    bytes: &[u8],
    document_byte_limit: usize,
) -> Result<JsonRpcMessage, JsonRpcAdmissionError> {
    admit_raw_jsonrpc_document(bytes, document_byte_limit).map_err(JsonRpcAdmissionError::Raw)?;
    match serde_json::from_slice::<JsonRpcRequest>(bytes) {
        Ok(request) => Ok(JsonRpcMessage::Request(request)),
        Err(_) => serde_json::from_slice::<JsonRpcResponse>(bytes)
            .map(JsonRpcMessage::Response)
            .map_err(|_| JsonRpcAdmissionError::InvalidEnvelope),
    }
}

impl JsonRpcRequest {
    /// Strictly decodes one request while retaining an exact parameter-source
    /// sidecar for method-specific ingress decoding.
    ///
    /// The returned `String`, when present, is the exact JSON source of the
    /// request's `params` member. It is deliberately separate from
    /// [`JsonRpcRequest`] so existing public struct literals and ordinary
    /// typed request APIs retain their established shape. A consumer may only
    /// attach this source to the returned request after comparing its
    /// materialized `params` value; final core dispatch performs that equality
    /// check before it uses the raw source.
    ///
    /// This applies the same bounded raw-document admission as
    /// [`decode_strict_jsonrpc_message`], including duplicate-member
    /// rejection, before producing either the typed request or its sidecar.
    pub fn decode_strict_with_raw_params(
        bytes: &[u8],
        document_byte_limit: usize,
    ) -> Result<(Self, Option<String>), JsonRpcAdmissionError> {
        admit_raw_jsonrpc_document(bytes, document_byte_limit)
            .map_err(JsonRpcAdmissionError::Raw)?;
        let (request, raw_params) = Self::decode_retaining_raw_params(bytes)
            .map_err(|_| JsonRpcAdmissionError::InvalidEnvelope)?;
        request
            .validate()
            .map_err(|_| JsonRpcAdmissionError::InvalidEnvelope)?;
        Ok((request, raw_params))
    }

    /// Performs exactly this type's `Deserialize` decode of one document and
    /// also returns the exact JSON source of its `params` member from that
    /// same decode.
    ///
    /// It applies neither raw-document admission nor [`Self::validate`]. A
    /// caller that has already admitted `bytes`, as the transport codec has,
    /// keeps the parameter source this way instead of decoding the document
    /// again. The attachment rule of [`Self::decode_strict_with_raw_params`]
    /// applies to the returned source.
    ///
    /// # Errors
    ///
    /// Returns the error `serde_json::from_slice::<JsonRpcRequest>` returns
    /// for the same bytes.
    pub fn decode_retaining_raw_params(
        bytes: &[u8],
    ) -> Result<(Self, Option<String>), serde_json::Error> {
        let mut deserializer = serde_json::Deserializer::from_slice(bytes);
        let wire = JsonRpcRequestRawWire::deserialize(&mut deserializer)?;
        deserializer.end()?;
        let (request, raw_params) = wire.into_request::<serde_json::Error>()?;
        Ok((request, raw_params.map(|source| source.get().to_owned())))
    }
}

/// One strictly admitted JSON-RPC response paired with the exact source JSON
/// of its result member.
///
/// `raw_result` is absent for an error response and present even when a success
/// result is the explicit JSON value `null`. It is retained only for local
/// method-specific result decoding; the public [`JsonRpcResponse`] remains
/// unchanged and existing typed transport APIs keep their established shape.
#[derive(Debug, Clone, PartialEq)]
pub struct JsonRpcResponseAdmission {
    response: JsonRpcResponse,
    raw_result: Option<String>,
}

impl JsonRpcResponseAdmission {
    /// Returns the ordinary typed response.
    #[must_use]
    pub const fn response(&self) -> &JsonRpcResponse {
        &self.response
    }

    /// Returns the exact result-member source JSON, including member order and
    /// number lexemes, when the response is successful.
    #[must_use]
    pub fn raw_result(&self) -> Option<&str> {
        self.raw_result.as_deref()
    }

    /// Splits this admission into its typed response and exact result source.
    #[must_use]
    pub fn into_parts(self) -> (JsonRpcResponse, Option<String>) {
        (self.response, self.raw_result)
    }
}

/// Strictly decodes one JSON-RPC response while retaining its exact result
/// member source for the final result algebra.
///
/// This applies the same bounded raw-document admission as
/// [`decode_strict_jsonrpc_message`]. Callers that already decoded a frame may
/// compare the returned typed response with that first decode before attaching
/// `raw_result` to its correlation owner.
pub fn decode_strict_jsonrpc_response(
    bytes: &[u8],
    document_byte_limit: usize,
) -> Result<JsonRpcResponseAdmission, JsonRpcAdmissionError> {
    admit_raw_jsonrpc_document(bytes, document_byte_limit).map_err(JsonRpcAdmissionError::Raw)?;
    let wire =
        JsonRpcResponseRawWire::deserialize(&mut serde_json::Deserializer::from_slice(bytes))
            .map_err(|_| JsonRpcAdmissionError::InvalidEnvelope)?;
    let raw_result = wire.result.map(|result| result.get().to_owned());
    let result = raw_result
        .as_deref()
        .map(serde_json::from_str)
        .transpose()
        .map_err(|_| JsonRpcAdmissionError::InvalidEnvelope)?;
    let response = JsonRpcResponse {
        jsonrpc: wire.jsonrpc,
        result,
        error: wire.error,
        id: wire.id,
    };
    response
        .validate()
        .map_err(|_| JsonRpcAdmissionError::InvalidEnvelope)?;
    Ok(JsonRpcResponseAdmission {
        response,
        raw_result,
    })
}

struct RawJsonScanner<'a> {
    input: &'a str,
    bytes: &'a [u8],
    position: usize,
    container_entries: usize,
    number_bytes: usize,
    decoded_string_bytes: usize,
    decoded_string_byte_limit: usize,
    path: Vec<RawJsonPathSegment>,
    top_level_members: Option<Vec<RawJsonRpcEnvelopeMember>>,
}

impl<'a> RawJsonScanner<'a> {
    fn new(input: &'a str, decoded_string_byte_limit: usize) -> Self {
        Self {
            input,
            bytes: input.as_bytes(),
            position: 0,
            container_entries: 0,
            number_bytes: 0,
            decoded_string_bytes: 0,
            decoded_string_byte_limit,
            path: Vec::new(),
            top_level_members: None,
        }
    }

    /// Renders the structural path held at the moment of refusal.
    ///
    /// The scanner unwinds by returning early, so the stack still describes
    /// the failing position when this runs.
    fn failure(&self, error: RawJsonAdmissionError) -> RawJsonAdmissionFailure {
        RawJsonAdmissionFailure {
            error,
            path: redact_raw_json_path(&self.path),
        }
    }

    fn parse_value(&mut self, depth: usize) -> Result<(), RawJsonAdmissionError> {
        match self.peek() {
            Some(b'{') => self.parse_object(depth),
            Some(b'[') => self.parse_array(depth),
            Some(b'"') => self.parse_string(false).map(|_| ()),
            Some(b't') => self.parse_literal(b"true"),
            Some(b'f') => self.parse_literal(b"false"),
            Some(b'n') => self.parse_literal(b"null"),
            Some(b'-' | b'0'..=b'9') => self.parse_number(),
            _ => Err(RawJsonAdmissionError::InvalidSyntax),
        }
    }

    fn parse_object(&mut self, depth: usize) -> Result<(), RawJsonAdmissionError> {
        let nested_depth = self.enter_container(depth)?;
        self.position += 1;
        self.skip_whitespace();
        if self.consume(b'}') {
            return Ok(());
        }

        let mut names = BTreeSet::new();
        loop {
            self.charge_container_entry()?;
            let name = self
                .parse_string(true)?
                .ok_or(RawJsonAdmissionError::InvalidSyntax)?;
            // The member joins the path before the duplicate check so a
            // refusal names the member it refused, and stays on the path for
            // the whole member value so a nested refusal is located exactly.
            self.path.push(RawJsonPathSegment::Member(name.clone()));
            if !names.insert(name) {
                return Err(RawJsonAdmissionError::DuplicateObjectMember);
            }
            self.skip_whitespace();
            if !self.consume(b':') {
                return Err(RawJsonAdmissionError::InvalidSyntax);
            }
            self.skip_whitespace();
            let value_start = self.position;
            self.parse_value(nested_depth)?;
            let member = self.path.pop();
            if depth == 0
                && let (Some(members), Some(RawJsonPathSegment::Member(name))) =
                    (self.top_level_members.as_mut(), member)
            {
                members.push(RawJsonRpcEnvelopeMember {
                    name,
                    value: value_start..self.position,
                });
            }
            self.skip_whitespace();
            if self.consume(b'}') {
                return Ok(());
            }
            if !self.consume(b',') {
                return Err(RawJsonAdmissionError::InvalidSyntax);
            }
            self.skip_whitespace();
        }
    }

    fn parse_array(&mut self, depth: usize) -> Result<(), RawJsonAdmissionError> {
        let nested_depth = self.enter_container(depth)?;
        self.position += 1;
        self.skip_whitespace();
        if self.consume(b']') {
            return Ok(());
        }
        let mut index = 0_usize;
        loop {
            self.charge_container_entry()?;
            self.path.push(RawJsonPathSegment::Index(index));
            self.parse_value(nested_depth)?;
            self.path.pop();
            index = index.saturating_add(1);
            self.skip_whitespace();
            if self.consume(b']') {
                return Ok(());
            }
            if !self.consume(b',') {
                return Err(RawJsonAdmissionError::InvalidSyntax);
            }
            self.skip_whitespace();
        }
    }

    fn enter_container(&self, depth: usize) -> Result<usize, RawJsonAdmissionError> {
        let nested_depth = depth
            .checked_add(1)
            .ok_or(RawJsonAdmissionError::NestingTooDeep)?;
        if nested_depth > MAX_RAW_JSON_NESTING_DEPTH {
            Err(RawJsonAdmissionError::NestingTooDeep)
        } else {
            Ok(nested_depth)
        }
    }

    fn charge_container_entry(&mut self) -> Result<(), RawJsonAdmissionError> {
        self.container_entries = self
            .container_entries
            .checked_add(1)
            .ok_or(RawJsonAdmissionError::TooManyContainerEntries)?;
        if self.container_entries > MAX_RAW_JSON_CONTAINER_ENTRIES {
            Err(RawJsonAdmissionError::TooManyContainerEntries)
        } else {
            Ok(())
        }
    }

    fn parse_string(&mut self, capture: bool) -> Result<Option<String>, RawJsonAdmissionError> {
        if !self.consume(b'"') {
            return Err(RawJsonAdmissionError::InvalidSyntax);
        }
        let mut decoded = capture.then(String::new);
        loop {
            let byte = self.peek().ok_or(RawJsonAdmissionError::InvalidSyntax)?;
            match byte {
                b'"' => {
                    self.position += 1;
                    return Ok(decoded);
                }
                b'\\' => {
                    self.position += 1;
                    let character = self.parse_escape()?;
                    self.charge_string_bytes(character.len_utf8())?;
                    if let Some(value) = decoded.as_mut() {
                        value.push(character);
                    }
                }
                0x00..=0x1f => return Err(RawJsonAdmissionError::InvalidSyntax),
                0x20..=0x7f => {
                    self.position += 1;
                    self.charge_string_bytes(1)?;
                    if let Some(value) = decoded.as_mut() {
                        value.push(char::from(byte));
                    }
                }
                _ => {
                    let character = self.input[self.position..]
                        .chars()
                        .next()
                        .ok_or(RawJsonAdmissionError::InvalidSyntax)?;
                    self.position += character.len_utf8();
                    self.charge_string_bytes(character.len_utf8())?;
                    if let Some(value) = decoded.as_mut() {
                        value.push(character);
                    }
                }
            }
        }
    }

    fn parse_escape(&mut self) -> Result<char, RawJsonAdmissionError> {
        let escape = self.peek().ok_or(RawJsonAdmissionError::InvalidSyntax)?;
        self.position += 1;
        match escape {
            b'"' => Ok('"'),
            b'\\' => Ok('\\'),
            b'/' => Ok('/'),
            b'b' => Ok('\u{0008}'),
            b'f' => Ok('\u{000c}'),
            b'n' => Ok('\n'),
            b'r' => Ok('\r'),
            b't' => Ok('\t'),
            b'u' => self.parse_unicode_escape(),
            _ => Err(RawJsonAdmissionError::InvalidSyntax),
        }
    }

    fn parse_unicode_escape(&mut self) -> Result<char, RawJsonAdmissionError> {
        let first = self.parse_hex_quad()?;
        let scalar = if (0xd800..=0xdbff).contains(&first) {
            if !self.consume(b'\\') || !self.consume(b'u') {
                return Err(RawJsonAdmissionError::InvalidSyntax);
            }
            let second = self.parse_hex_quad()?;
            if !(0xdc00..=0xdfff).contains(&second) {
                return Err(RawJsonAdmissionError::InvalidSyntax);
            }
            0x1_0000 + ((u32::from(first) - 0xd800) << 10) + u32::from(second) - 0xdc00
        } else if (0xdc00..=0xdfff).contains(&first) {
            return Err(RawJsonAdmissionError::InvalidSyntax);
        } else {
            u32::from(first)
        };
        char::from_u32(scalar).ok_or(RawJsonAdmissionError::InvalidSyntax)
    }

    fn parse_hex_quad(&mut self) -> Result<u16, RawJsonAdmissionError> {
        let end = self
            .position
            .checked_add(4)
            .ok_or(RawJsonAdmissionError::InvalidSyntax)?;
        let digits = self
            .bytes
            .get(self.position..end)
            .ok_or(RawJsonAdmissionError::InvalidSyntax)?;
        let mut value = 0_u16;
        for digit in digits {
            let nibble = match digit {
                b'0'..=b'9' => u16::from(*digit - b'0'),
                b'a'..=b'f' => u16::from(*digit - b'a' + 10),
                b'A'..=b'F' => u16::from(*digit - b'A' + 10),
                _ => return Err(RawJsonAdmissionError::InvalidSyntax),
            };
            value = (value << 4) | nibble;
        }
        self.position = end;
        Ok(value)
    }

    fn parse_literal(&mut self, literal: &[u8]) -> Result<(), RawJsonAdmissionError> {
        let end = self
            .position
            .checked_add(literal.len())
            .ok_or(RawJsonAdmissionError::InvalidSyntax)?;
        if self.bytes.get(self.position..end) == Some(literal) {
            self.position = end;
            Ok(())
        } else {
            Err(RawJsonAdmissionError::InvalidSyntax)
        }
    }

    fn parse_number(&mut self) -> Result<(), RawJsonAdmissionError> {
        let start = self.position;
        self.consume(b'-');
        match self.peek() {
            Some(b'0') => {
                self.position += 1;
                if matches!(self.peek(), Some(b'0'..=b'9')) {
                    return Err(RawJsonAdmissionError::InvalidSyntax);
                }
            }
            Some(b'1'..=b'9') => {
                self.position += 1;
                self.consume_digits();
            }
            _ => return Err(RawJsonAdmissionError::InvalidSyntax),
        }
        if self.consume(b'.') {
            if !matches!(self.peek(), Some(b'0'..=b'9')) {
                return Err(RawJsonAdmissionError::InvalidSyntax);
            }
            self.consume_digits();
        }
        if matches!(self.peek(), Some(b'e' | b'E')) {
            self.position += 1;
            if matches!(self.peek(), Some(b'+' | b'-')) {
                self.position += 1;
            }
            let exponent_start = self.position;
            if !matches!(self.peek(), Some(b'0'..=b'9')) {
                return Err(RawJsonAdmissionError::InvalidSyntax);
            }
            self.consume_digits();
            if exponent_exceeds_raw_limit(&self.bytes[exponent_start..self.position]) {
                return Err(RawJsonAdmissionError::ExponentTooLarge);
            }
        }
        let length = self.position - start;
        if length > MAX_RAW_JSON_NUMBER_BYTES {
            return Err(RawJsonAdmissionError::NumberTooLong);
        }
        self.number_bytes = self
            .number_bytes
            .checked_add(length)
            .ok_or(RawJsonAdmissionError::TooManyNumberBytes)?;
        if self.number_bytes > MAX_RAW_JSON_AGGREGATE_NUMBER_BYTES {
            Err(RawJsonAdmissionError::TooManyNumberBytes)
        } else {
            Ok(())
        }
    }

    fn consume_digits(&mut self) {
        while matches!(self.peek(), Some(b'0'..=b'9')) {
            self.position += 1;
        }
    }
    fn charge_string_bytes(&mut self, bytes: usize) -> Result<(), RawJsonAdmissionError> {
        self.decoded_string_bytes = self
            .decoded_string_bytes
            .checked_add(bytes)
            .ok_or(RawJsonAdmissionError::TooManyDecodedStringBytes)?;
        if self.decoded_string_bytes > self.decoded_string_byte_limit {
            Err(RawJsonAdmissionError::TooManyDecodedStringBytes)
        } else {
            Ok(())
        }
    }
    fn skip_whitespace(&mut self) {
        while matches!(self.peek(), Some(b' ' | b'\t' | b'\r' | b'\n')) {
            self.position += 1;
        }
    }
    fn consume(&mut self, expected: u8) -> bool {
        if self.peek() == Some(expected) {
            self.position += 1;
            true
        } else {
            false
        }
    }
    fn peek(&self) -> Option<u8> {
        self.bytes.get(self.position).copied()
    }
}

/// Renders a scanner path as a redacted JSON-Pointer-style string.
///
/// Only structure survives. An object member keeps `[A-Za-z0-9_.-]` and every
/// other byte becomes `*`, so an attacker-chosen member name can neither
/// smuggle content into a log line nor change the shape of the diagnostic.
/// Segment and path lengths are bounded, and array steps carry only indices.
fn redact_raw_json_path(path: &[RawJsonPathSegment]) -> String {
    let mut rendered = String::new();
    for segment in path.iter().take(MAX_RAW_JSON_PATH_SEGMENTS) {
        rendered.push('/');
        match segment {
            RawJsonPathSegment::Member(name) => {
                // `retained` counts CHARACTERS and is compared against a BYTE
                // budget. That is correct here only because every branch below
                // pushes exactly one ASCII byte: the first is guarded to ASCII
                // alphanumerics plus `_ . -`, and the second is a literal '*'.
                // So character count and byte count are equal for this loop.
                //
                // The equivalence is invisible from the constant's name and
                // depends on the sanitiser immediately below. If either branch
                // ever pushes a multi-byte character -- a Unicode replacement
                // or an ellipsis, say -- this stops bounding bytes and the
                // truncation boundary moves silently. Count bytes explicitly if
                // that happens; do not widen the budget.
                for (retained, character) in name.chars().enumerate() {
                    if retained >= MAX_RAW_JSON_PATH_SEGMENT_BYTES {
                        rendered.push('~');
                        break;
                    }
                    if character.is_ascii_alphanumeric() || matches!(character, '_' | '.' | '-') {
                        rendered.push(character);
                    } else {
                        rendered.push('*');
                    }
                }
            }
            RawJsonPathSegment::Index(index) => {
                rendered.push_str(&index.to_string());
            }
        }
    }
    if path.len() > MAX_RAW_JSON_PATH_SEGMENTS {
        rendered.push_str("/~");
    }
    rendered
}

fn exponent_exceeds_raw_limit(digits: &[u8]) -> bool {
    let first_significant = digits
        .iter()
        .position(|digit| *digit != b'0')
        .unwrap_or(digits.len());
    let significant = &digits[first_significant..];
    significant.len() > 5
        || significant.iter().fold(0_usize, |value, digit| {
            value * 10 + usize::from(*digit - b'0')
        }) > MAX_RAW_JSON_EXPONENT
}

/// Serializes the jsonrpc version field.
fn serialize_jsonrpc_version<S>(value: &str, serializer: S) -> Result<S::Ok, S::Error>
where
    S: Serializer,
{
    if value == JSONRPC_VERSION {
        serializer.serialize_str(JSONRPC_VERSION)
    } else {
        Err(S::Error::custom("jsonrpc must be exactly \"2.0\""))
    }
}

/// Deserializes the required JSON-RPC version, rejecting every value but
/// exactly `"2.0"`.
fn deserialize_jsonrpc_version<'de, D>(deserializer: D) -> Result<Cow<'static, str>, D::Error>
where
    D: Deserializer<'de>,
{
    let s: Cow<'de, str> = Cow::deserialize(deserializer)?;
    if s == JSONRPC_VERSION {
        Ok(Cow::Borrowed(JSONRPC_VERSION))
    } else {
        Err(D::Error::custom("jsonrpc must be exactly \"2.0\""))
    }
}

/// JSON-RPC request ID.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum RequestId {
    /// Integer ID.
    Number(i64),
    /// An arbitrary-precision mathematical-integer ID preserving its admitted
    /// JSON number lexeme for an exact response echo.
    Integer(String),
    /// String ID.
    String(String),
}

/// Canonical map/registry key for a JSON-RPC request ID.
///
/// Numeric spellings are normalized by exact mathematical value; string IDs
/// remain byte-for-byte distinct from numeric IDs.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum CorrelationKey {
    /// A string request ID, retained byte-for-byte.
    String(String),
    /// A canonical decimal mathematical-integer value.
    Integer(String),
}

impl RequestId {
    /// Verifies that this ID can be represented within the JSON-RPC wire
    /// limits enforced by this crate.
    ///
    /// # Errors
    ///
    /// Returns an error for a string ID whose canonical JSON encoding exceeds
    /// [`MAX_JSONRPC_STRING_ID_ENCODED_BYTES`]. Raw decoders must additionally
    /// enforce the byte length of the received token before escape decoding.
    pub fn validate(&self) -> Result<(), &'static str> {
        match self {
            Self::String(value)
                if encoded_json_string_len(value) > MAX_JSONRPC_STRING_ID_ENCODED_BYTES =>
            {
                return Err("JSON-RPC string id exceeds byte limit");
            }
            Self::Integer(lexeme) if !is_mathematical_integer(lexeme) => {
                return Err("JSON-RPC numeric id must be a mathematical integer");
            }
            _ => {}
        }
        Ok(())
    }

    /// Produces the canonical key used by request registries and correlation.
    pub fn correlation_key(&self) -> Result<CorrelationKey, &'static str> {
        self.validate()?;
        match self {
            Self::Number(value) => Ok(CorrelationKey::Integer(value.to_string())),
            Self::Integer(lexeme) => Ok(CorrelationKey::Integer(canonical_integer_lexeme(lexeme))),
            Self::String(value) => Ok(CorrelationKey::String(value.clone())),
        }
    }

    /// Returns whether two wire IDs identify the same JSON-RPC request.
    ///
    /// Numeric spellings compare by exact mathematical-integer value, while a
    /// string remains distinct from every numeric ID.
    #[must_use]
    pub fn correlates_with(&self, other: &Self) -> bool {
        matches!(
            (self.correlation_key(), other.correlation_key()),
            (Ok(left), Ok(right)) if left == right
        )
    }
}

impl Serialize for RequestId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.validate().map_err(S::Error::custom)?;
        match self {
            Self::Number(number) => serializer.serialize_i64(*number),
            Self::Integer(lexeme) => serde_json::from_str::<serde_json::Number>(lexeme)
                .map_err(S::Error::custom)?
                .serialize(serializer),
            Self::String(value) => serializer.serialize_str(value),
        }
    }
}

impl<'de> Deserialize<'de> for RequestId {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        match Value::deserialize(deserializer)? {
            Value::Number(number) => {
                let lexeme = number.to_string();
                if !lexeme.contains(['.', 'e', 'E'])
                    && lexeme != "-0"
                    && let Ok(value) = lexeme.parse::<i64>()
                {
                    Ok(RequestId::Number(value))
                } else if is_mathematical_integer(&lexeme) {
                    Ok(RequestId::Integer(lexeme))
                } else {
                    Err(D::Error::custom(
                        "JSON-RPC numeric id must be a mathematical integer",
                    ))
                }
            }
            Value::String(value) => {
                if encoded_json_string_len(&value) > MAX_JSONRPC_STRING_ID_ENCODED_BYTES {
                    return Err(D::Error::custom("JSON-RPC string id exceeds byte limit"));
                }
                Ok(RequestId::String(value))
            }
            _ => Err(D::Error::custom(
                "JSON-RPC id must be a string or mathematical integer",
            )),
        }
    }
}

fn is_mathematical_integer(lexeme: &str) -> bool {
    if lexeme.len() > MAX_RAW_JSON_NUMBER_BYTES {
        return false;
    }
    let bytes = lexeme.as_bytes();
    let mut index = usize::from(matches!(bytes.first(), Some(b'-')));
    if index == bytes.len() {
        return false;
    }
    let integer_start = index;
    if bytes.get(index) == Some(&b'0') {
        index += 1;
        if matches!(bytes.get(index), Some(b'0'..=b'9')) {
            return false;
        }
    } else if matches!(bytes.get(index), Some(b'1'..=b'9')) {
        index += 1;
        while matches!(bytes.get(index), Some(b'0'..=b'9')) {
            index += 1;
        }
    } else {
        return false;
    }
    let mut fraction_digits = 0_usize;
    let mut trailing_zeroes = 0_usize;
    if bytes.get(index) == Some(&b'.') {
        index += 1;
        let fraction_start = index;
        while matches!(bytes.get(index), Some(b'0'..=b'9')) {
            index += 1;
        }
        fraction_digits = index - fraction_start;
        if fraction_digits == 0 {
            return false;
        }
    }
    let coefficient_end = index;
    let coefficient = &bytes[integer_start..coefficient_end];
    for digit in coefficient.iter().rev() {
        if *digit == b'0' {
            trailing_zeroes += 1;
        } else if *digit != b'.' {
            break;
        }
    }
    let exponent = if matches!(bytes.get(index), Some(b'e' | b'E')) {
        index += 1;
        let negative = if bytes.get(index) == Some(&b'-') {
            index += 1;
            true
        } else {
            if bytes.get(index) == Some(&b'+') {
                index += 1;
            }
            false
        };
        let exponent_start = index;
        while matches!(bytes.get(index), Some(b'0'..=b'9')) {
            index += 1;
        }
        if index == exponent_start || index != bytes.len() {
            return false;
        }
        let magnitude = std::str::from_utf8(&bytes[exponent_start..index])
            .ok()
            .and_then(|value| value.parse::<i64>().ok());
        match magnitude {
            Some(value) if value <= MAX_RAW_JSON_EXPONENT as i64 && negative => -value,
            Some(value) if value <= MAX_RAW_JSON_EXPONENT as i64 => value,
            _ => return false,
        }
    } else {
        if index != bytes.len() {
            return false;
        }
        0
    };
    let scale = i64::try_from(fraction_digits).unwrap_or(i64::MAX) - exponent;
    coefficient.iter().all(|digit| matches!(digit, b'0' | b'.'))
        || scale <= 0
        || usize::try_from(scale).is_ok_and(|required_zeroes| trailing_zeroes >= required_zeroes)
}

fn canonical_integer_lexeme(lexeme: &str) -> String {
    debug_assert!(is_mathematical_integer(lexeme));
    let bytes = lexeme.as_bytes();
    let negative = bytes.first() == Some(&b'-');
    let unsigned = if negative { &lexeme[1..] } else { lexeme };
    let (coefficient, exponent) = match unsigned.find(['e', 'E']) {
        Some(index) => (
            &unsigned[..index],
            unsigned[index + 1..].parse::<i64>().unwrap_or(0),
        ),
        None => (unsigned, 0),
    };
    let (whole, fraction) = coefficient.split_once('.').unwrap_or((coefficient, ""));
    let mut digits = format!("{whole}{fraction}");
    let leading = digits.bytes().take_while(|digit| *digit == b'0').count();
    digits.drain(..leading);
    if digits.is_empty() {
        return "0".to_owned();
    }
    let scale = i64::try_from(fraction.len()).unwrap_or(i64::MAX) - exponent;
    if scale > 0 {
        let removable = usize::try_from(scale).unwrap_or(usize::MAX);
        let retained = digits.len().saturating_sub(removable);
        digits.truncate(retained);
    } else {
        let zeroes = usize::try_from(scale.unsigned_abs()).unwrap_or(usize::MAX);
        digits.extend(std::iter::repeat_n('0', zeroes));
    }
    if negative {
        format!("-{digits}")
    } else {
        digits
    }
}

fn encoded_json_string_len(value: &str) -> usize {
    value.chars().fold(2_usize, |length, character| {
        let encoded = match character {
            '"' | '\\' | '\u{0008}' | '\u{000c}' | '\n' | '\r' | '\t' => 2,
            '\u{0000}'..='\u{001f}' => 6,
            _ => character.len_utf8(),
        };
        length.saturating_add(encoded)
    })
}

fn deserialize_request_id<'de, D>(deserializer: D) -> Result<Option<RequestId>, D::Error>
where
    D: Deserializer<'de>,
{
    RequestId::deserialize(deserializer).map(Some)
}

impl From<i64> for RequestId {
    fn from(id: i64) -> Self {
        RequestId::Number(id)
    }
}

impl From<String> for RequestId {
    fn from(id: String) -> Self {
        RequestId::String(id)
    }
}

impl From<&str> for RequestId {
    fn from(id: &str) -> Self {
        RequestId::String(id.to_owned())
    }
}

impl std::fmt::Display for RequestId {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            RequestId::Number(n) => write!(f, "{n}"),
            RequestId::Integer(lexeme) => f.write_str(lexeme),
            RequestId::String(s) => write!(f, "{s}"),
        }
    }
}

/// JSON-RPC 2.0 request.
#[derive(Debug, Clone, Serialize)]
#[serde(deny_unknown_fields)]
pub struct JsonRpcRequest {
    /// Protocol version (always "2.0").
    #[serde(
        serialize_with = "serialize_jsonrpc_version",
        deserialize_with = "deserialize_jsonrpc_version"
    )]
    pub jsonrpc: Cow<'static, str>,
    /// Method name.
    pub method: String,
    /// Request parameters.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<Value>,
    /// Request ID (absent for notifications).
    ///
    /// An explicit JSON `null` is rejected instead of being conflated with an
    /// absent member. Notifications omit `id` entirely.
    #[serde(
        default,
        deserialize_with = "deserialize_request_id",
        skip_serializing_if = "Option::is_none"
    )]
    pub id: Option<RequestId>,
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct JsonRpcRequestRawWire<'a> {
    #[serde(deserialize_with = "deserialize_jsonrpc_version")]
    jsonrpc: Cow<'static, str>,
    method: String,
    #[serde(borrow, default)]
    params: Option<Cow<'a, RawValue>>,
    #[serde(default, deserialize_with = "deserialize_request_id")]
    id: Option<RequestId>,
}

impl<'de> Deserialize<'de> for JsonRpcRequest {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        JsonRpcRequestRawWire::deserialize(deserializer)?
            .into_request()
            .map(|(request, _)| request)
    }
}

impl<'a> JsonRpcRequestRawWire<'a> {
    /// Types this envelope and hands back the exact `params` source it holds.
    fn into_request<E: serde::de::Error>(
        self,
    ) -> Result<(JsonRpcRequest, Option<Cow<'a, RawValue>>), E> {
        let params = self
            .params
            .as_deref()
            .map(RawValue::get)
            .map(|source| {
                crate::messages::validate_raw_final_completion_params(&self.method, source)
                    .map_err(E::custom)?;
                serde_json::from_str(source).map_err(E::custom)
            })
            .transpose()?;
        Ok((
            JsonRpcRequest {
                jsonrpc: self.jsonrpc,
                method: self.method,
                params,
                id: self.id,
            },
            self.params,
        ))
    }
}

impl JsonRpcRequest {
    /// Creates a new request with the given method and parameters.
    #[must_use]
    pub fn new(method: impl Into<String>, params: Option<Value>, id: impl Into<RequestId>) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            method: method.into(),
            params,
            id: Some(id.into()),
        }
    }

    /// Creates a notification (request without ID).
    #[must_use]
    pub fn notification(method: impl Into<String>, params: Option<Value>) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            method: method.into(),
            params,
            id: None,
        }
    }

    /// Creates the MCP lifecycle `notifications/initialized` notification.
    ///
    /// Uses the spec-correct method name (`notifications/initialized`), avoiding
    /// the bare `initialized` spelling that compliant servers do not route as the
    /// lifecycle ack.
    #[must_use]
    pub fn initialized_notification() -> Self {
        Self::notification(crate::methods::NOTIFICATIONS_INITIALIZED, None)
    }

    /// Returns true if this is a notification (no ID).
    #[must_use]
    pub fn is_notification(&self) -> bool {
        self.id.is_none()
    }

    /// Verifies invariants that can otherwise be bypassed by constructing or
    /// mutating this public protocol type directly.
    ///
    /// # Errors
    ///
    /// Returns an error for a non-standard protocol version or invalid ID.
    pub fn validate(&self) -> Result<(), &'static str> {
        if self.jsonrpc != JSONRPC_VERSION {
            return Err("jsonrpc must be exactly \"2.0\"");
        }
        if let Some(id) = &self.id {
            id.validate()?;
        }
        Ok(())
    }
}

/// JSON-RPC 2.0 error object.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct JsonRpcError {
    /// Error code retained without an implementation-width bound.
    pub code: JsonInteger,
    /// Error message.
    pub message: String,
    /// Additional error data.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<Value>,
}

/// Immutable local endpoint role for raw JSON-RPC ingress disposition.
///
/// The role is chosen by local transport construction. It is deliberately a
/// closed value rather than a peer-provided header/body setting.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum JsonRpcEndpointRole {
    /// This endpoint receives client-to-server JSON-RPC traffic.
    ServerIngress,
    /// This endpoint receives server-to-client JSON-RPC traffic.
    ClientIngress,
}

/// The direction attached by the local transport to a decoded message.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum JsonRpcMessageDirection {
    /// Client-to-server traffic.
    ClientToServer,
    /// Server-to-client traffic.
    ServerToClient,
}

/// Transport ownership for a client-ingress raw protocol failure.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ClientIngressFailureScope {
    /// The malformed body belongs to one request/response exchange.
    OwningExchange,
    /// The malformed body arrived on a multiplexed/shared channel.
    SharedChannel,
}

/// An error response that is deliberately uncorrelated and omits `id`.
///
/// It is distinct from [`JsonRpcResponse`], so safe code cannot accidentally
/// use an absent ID as an ordinary response correlation key.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(deny_unknown_fields)]
pub struct UncorrelatedJsonRpcErrorResponse {
    #[serde(
        serialize_with = "serialize_jsonrpc_version",
        deserialize_with = "deserialize_jsonrpc_version"
    )]
    jsonrpc: Cow<'static, str>,
    error: JsonRpcError,
}

impl UncorrelatedJsonRpcErrorResponse {
    fn parse_or_invalid_request(message: impl Into<String>, code: i32) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            error: JsonRpcError {
                code: code.into(),
                message: message.into(),
                data: None,
            },
        }
    }

    /// Returns the error payload without exposing an ID-bearing response.
    #[must_use]
    pub fn error(&self) -> &JsonRpcError {
        &self.error
    }
}

/// Role-aware disposition of a raw malformed JSON-RPC document.
#[derive(Debug, Clone, PartialEq)]
pub enum RawJsonRpcDisposition {
    /// Server ingress can emit an error correlated to the one readable ID.
    CorrelatedError(JsonRpcResponse),
    /// Server ingress can emit an explicitly uncorrelated parse/invalid error.
    UncorrelatedError(UncorrelatedJsonRpcErrorResponse),
    /// Client ingress emits no JSON-RPC response and fails only its owning exchange.
    ClientOwningFailure,
    /// Client ingress emits no JSON-RPC response and reports a shared-channel failure.
    ClientSharedChannelFailure,
    /// The direction is not an ingress path for this endpoint and emits nothing.
    NoAction,
}

/// Convert a raw admission failure into an endpoint-safe disposition.
///
/// A valid request ID is echoed only at server ingress for client-to-server
/// traffic. Client ingress never obtains a response-emitting branch.
#[must_use]
pub fn dispose_raw_jsonrpc_failure(
    role: JsonRpcEndpointRole,
    direction: JsonRpcMessageDirection,
    readable_id: Option<RequestId>,
    failure_scope: ClientIngressFailureScope,
) -> RawJsonRpcDisposition {
    match (role, direction) {
        (JsonRpcEndpointRole::ServerIngress, JsonRpcMessageDirection::ClientToServer) => {
            if let Some(id) = readable_id {
                RawJsonRpcDisposition::CorrelatedError(JsonRpcResponse::error(
                    Some(id),
                    JsonRpcError {
                        code: (-32600).into(),
                        message: "Invalid Request".to_owned(),
                        data: None,
                    },
                ))
            } else {
                RawJsonRpcDisposition::UncorrelatedError(
                    UncorrelatedJsonRpcErrorResponse::parse_or_invalid_request(
                        "Parse error",
                        -32700,
                    ),
                )
            }
        }
        (JsonRpcEndpointRole::ClientIngress, JsonRpcMessageDirection::ServerToClient) => {
            match failure_scope {
                ClientIngressFailureScope::OwningExchange => {
                    RawJsonRpcDisposition::ClientOwningFailure
                }
                ClientIngressFailureScope::SharedChannel => {
                    RawJsonRpcDisposition::ClientSharedChannelFailure
                }
            }
        }
        _ => RawJsonRpcDisposition::NoAction,
    }
}

impl From<fastmcp_core::McpError> for JsonRpcError {
    fn from(err: fastmcp_core::McpError) -> Self {
        Self {
            code: err.code.into(),
            message: err.message,
            data: err.data,
        }
    }
}

fn deserialize_response_result<'de, D>(deserializer: D) -> Result<Option<Value>, D::Error>
where
    D: Deserializer<'de>,
{
    Value::deserialize(deserializer).map(Some)
}

fn deserialize_response_error<'de, D>(deserializer: D) -> Result<Option<JsonRpcError>, D::Error>
where
    D: Deserializer<'de>,
{
    JsonRpcError::deserialize(deserializer).map(Some)
}

fn deserialize_raw_response_result<'de, D>(
    deserializer: D,
) -> Result<Option<Box<RawValue>>, D::Error>
where
    D: Deserializer<'de>,
{
    Box::<RawValue>::deserialize(deserializer).map(Some)
}

#[derive(Deserialize)]
#[serde(deny_unknown_fields)]
struct JsonRpcResponseRawWire {
    #[serde(deserialize_with = "deserialize_jsonrpc_version")]
    jsonrpc: Cow<'static, str>,
    #[serde(default, deserialize_with = "deserialize_raw_response_result")]
    result: Option<Box<RawValue>>,
    #[serde(default, deserialize_with = "deserialize_response_error")]
    error: Option<JsonRpcError>,
    #[serde(default, deserialize_with = "deserialize_request_id")]
    id: Option<RequestId>,
}

#[derive(Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
struct JsonRpcResponseWire {
    /// Protocol version (always "2.0").
    #[serde(
        serialize_with = "serialize_jsonrpc_version",
        deserialize_with = "deserialize_jsonrpc_version"
    )]
    jsonrpc: Cow<'static, str>,
    #[serde(
        default,
        deserialize_with = "deserialize_response_result",
        skip_serializing_if = "Option::is_none"
    )]
    result: Option<Value>,
    #[serde(
        default,
        deserialize_with = "deserialize_response_error",
        skip_serializing_if = "Option::is_none"
    )]
    error: Option<JsonRpcError>,
    #[serde(
        default,
        deserialize_with = "deserialize_request_id",
        skip_serializing_if = "Option::is_none"
    )]
    id: Option<RequestId>,
}

/// JSON-RPC 2.0 response.
#[derive(Debug, Clone, PartialEq)]
pub struct JsonRpcResponse {
    /// Protocol version (always "2.0").
    pub jsonrpc: Cow<'static, str>,
    /// Result (present on success, including an explicit JSON `null`).
    pub result: Option<Value>,
    /// Error (present on failure).
    pub error: Option<JsonRpcError>,
    /// Request ID this is responding to.
    pub id: Option<RequestId>,
}

impl Serialize for JsonRpcResponse {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.validate().map_err(S::Error::custom)?;

        JsonRpcResponseWire {
            jsonrpc: self.jsonrpc.clone(),
            result: self.result.clone(),
            error: self.error.clone(),
            id: self.id.clone(),
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for JsonRpcResponse {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire = JsonRpcResponseWire::deserialize(deserializer)?;
        let response = Self {
            jsonrpc: wire.jsonrpc,
            result: wire.result,
            error: wire.error,
            id: wire.id,
        };
        response.validate().map_err(D::Error::custom)?;
        Ok(response)
    }
}

impl JsonRpcResponse {
    /// Creates a success response.
    #[must_use]
    pub fn success(id: RequestId, result: Value) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            result: Some(result),
            error: None,
            id: Some(id),
        }
    }

    /// Creates an error response.
    #[must_use]
    pub fn error(id: Option<RequestId>, error: JsonRpcError) -> Self {
        Self {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            result: None,
            error: Some(error),
            id,
        }
    }

    /// Returns true if this is an error response.
    #[must_use]
    pub fn is_error(&self) -> bool {
        self.error.is_some()
    }

    /// Verifies invariants that can otherwise be bypassed by constructing or
    /// mutating this public protocol type directly.
    ///
    /// # Errors
    ///
    /// Returns an error unless the protocol version is exact, exactly one
    /// outcome member is present, every ID is valid, and success is correlated
    /// to a request ID.
    pub fn validate(&self) -> Result<(), &'static str> {
        if self.jsonrpc != JSONRPC_VERSION {
            return Err("jsonrpc must be exactly \"2.0\"");
        }
        if self.result.is_some() == self.error.is_some() {
            return Err("JSON-RPC response must contain exactly one of result or error");
        }
        if self.result.is_some() && self.id.is_none() {
            return Err("JSON-RPC success response must contain an id");
        }
        if let Some(id) = &self.id {
            id.validate()?;
        }
        Ok(())
    }
}

/// A JSON-RPC message (request, response, or notification).
///
/// Decoding requires a `serde_json` deserializer: the input is captured as
/// raw JSON and re-parsed by the selected variant's own decoder.
#[derive(Debug, Clone, Serialize)]
#[serde(untagged)]
pub enum JsonRpcMessage {
    /// A request or notification.
    Request(JsonRpcRequest),
    /// A response.
    Response(JsonRpcResponse),
}

// A derived untagged Deserialize buffers its input in serde's private
// `Content`, and a `RawValue` cannot be read back from that buffer. Since
// `JsonRpcRequest` keeps its params as their exact source (`RawValue`), every
// request or notification carrying params failed to decode through this
// type. Capture the whole input as raw JSON instead, choose the variant by
// whether a `method` member is present, and re-parse the same text through
// that variant's strict decoder so params keep their source bytes.
impl<'de> Deserialize<'de> for JsonRpcMessage {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        #[derive(Deserialize)]
        struct Envelope {
            #[serde(default, deserialize_with = "member_present")]
            method: bool,
        }

        fn member_present<'de, D>(deserializer: D) -> Result<bool, D::Error>
        where
            D: Deserializer<'de>,
        {
            serde::de::IgnoredAny::deserialize(deserializer).map(|_| true)
        }

        let raw = Box::<RawValue>::deserialize(deserializer)?;
        let source = raw.get();
        let envelope: Envelope = serde_json::from_str(source).map_err(D::Error::custom)?;
        if envelope.method {
            serde_json::from_str(source)
                .map(Self::Request)
                .map_err(D::Error::custom)
        } else {
            serde_json::from_str(source)
                .map(Self::Response)
                .map_err(D::Error::custom)
        }
    }
}

impl JsonRpcMessage {
    /// Verifies the contained request or response invariants.
    ///
    /// Typed transports that do not serialize through [`serde_json`] should
    /// call this before accepting a message.
    ///
    /// # Errors
    ///
    /// Returns the first violated request or response invariant.
    pub fn validate(&self) -> Result<(), &'static str> {
        match self {
            Self::Request(request) => request.validate(),
            Self::Response(response) => response.validate(),
        }
    }
}

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

    #[derive(Clone, Debug, Default, PartialEq, Eq)]
    struct AdmittedFrames {
        bytes: Vec<Vec<u8>>,
    }

    fn admit_frame(
        state: &mut AdmittedFrames,
        frame: &[u8],
    ) -> Result<JsonRpcMessage, JsonRpcAdmissionError> {
        let message = decode_strict_jsonrpc_message(frame, 4 * 1024)?;
        state.bytes.push(frame.to_vec());
        Ok(message)
    }

    #[test]
    fn request_and_response_envelopes_decode() {
        let request = br#"{"jsonrpc":"2.0","method":"tools/list","id":42}"#;
        let notification = br#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#;
        let success = br#"{"jsonrpc":"2.0","result":null,"id":"request-42"}"#;
        let error = br#"{"jsonrpc":"2.0","error":{"code":-32601,"message":"missing"},"id":42}"#;

        assert!(matches!(
            decode_strict_jsonrpc_message(request, 4 * 1024),
            Ok(JsonRpcMessage::Request(JsonRpcRequest {
                id: Some(RequestId::Number(42)),
                ..
            }))
        ));
        assert!(matches!(
            decode_strict_jsonrpc_message(notification, 4 * 1024),
            Ok(JsonRpcMessage::Request(JsonRpcRequest { id: None, .. }))
        ));
        assert!(matches!(
            decode_strict_jsonrpc_message(success, 4 * 1024),
            Ok(JsonRpcMessage::Response(JsonRpcResponse {
                result: Some(Value::Null),
                error: None,
                ..
            }))
        ));
        assert!(matches!(
            decode_strict_jsonrpc_message(error, 4 * 1024),
            Ok(JsonRpcMessage::Response(JsonRpcResponse {
                result: None,
                error: Some(_),
                ..
            }))
        ));

        assert!(matches!(
            dispose_raw_jsonrpc_failure(
                JsonRpcEndpointRole::ServerIngress,
                JsonRpcMessageDirection::ClientToServer,
                Some(RequestId::String("known".to_owned())),
                ClientIngressFailureScope::OwningExchange,
            ),
            RawJsonRpcDisposition::CorrelatedError(JsonRpcResponse {
                id: Some(RequestId::String(_)),
                ..
            })
        ));
        assert!(matches!(
            dispose_raw_jsonrpc_failure(
                JsonRpcEndpointRole::ClientIngress,
                JsonRpcMessageDirection::ServerToClient,
                None,
                ClientIngressFailureScope::SharedChannel,
            ),
            RawJsonRpcDisposition::ClientSharedChannelFailure
        ));
    }

    #[test]
    fn strict_response_admission_retains_exact_result_source() {
        let frame = br#"{"jsonrpc":"2.0","result":{"zeta":1.20e+4,"alpha":{"second":2,"first":1},"middle":null},"id":73}"#;
        let admission = decode_strict_jsonrpc_response(frame, 4 * 1024)
            .expect("strict response admission accepts the bounded frame");
        assert_eq!(admission.response().id, Some(RequestId::Number(73)));
        assert_eq!(
            admission.raw_result(),
            Some(r#"{"zeta":1.20e+4,"alpha":{"second":2,"first":1},"middle":null}"#),
            "the exact result substring retains top-level and nested member order plus number lexemes"
        );

        let explicit_null =
            decode_strict_jsonrpc_response(br#"{"jsonrpc":"2.0","result":null,"id":74}"#, 4 * 1024)
                .expect("an explicit null success remains present");
        assert_eq!(explicit_null.raw_result(), Some("null"));

        let error = decode_strict_jsonrpc_response(
            br#"{"jsonrpc":"2.0","error":{"code":-32601,"message":"missing"},"id":75}"#,
            4 * 1024,
        )
        .expect("an error response has no result source");
        assert!(error.raw_result().is_none());
    }

    #[test]
    fn raw_admission_accepts_public_request_surface() {
        let frame = br#"{"jsonrpc":"2.0","method":"tools/list","id":"public-request"}"#;
        let mut state = AdmittedFrames::default();
        let admitted = admit_frame(&mut state, frame)
            .expect("the protocol-owned raw gate admits a strict public request envelope");
        assert!(matches!(admitted, JsonRpcMessage::Request(_)));
        assert_eq!(state.bytes, vec![frame.to_vec()]);
        assert!(matches!(
            dispose_raw_jsonrpc_failure(
                JsonRpcEndpointRole::ClientIngress,
                JsonRpcMessageDirection::ServerToClient,
                None,
                ClientIngressFailureScope::OwningExchange,
            ),
            RawJsonRpcDisposition::ClientOwningFailure
        ));
    }

    #[test]
    fn duplicate_envelope_member_is_rejected_without_state_change() {
        let baseline = br#"{"jsonrpc":"2.0","method":"tools/list","id":42}"#;
        let planted = br#"{"jsonrpc":"2.0","method":"tools/list","id":42,"id":42}"#;
        let mut state = AdmittedFrames::default();
        admit_frame(&mut state, baseline).expect("the unmodified envelope is admitted");
        let state_before = state.clone();

        assert!(
            matches!(
                admit_frame(&mut state, planted),
                Err(JsonRpcAdmissionError::Raw(
                    RawJsonAdmissionError::DuplicateObjectMember
                ))
            ),
            "changing only the second id member must reach production raw admission"
        );
        assert_eq!(
            state, state_before,
            "rejected raw JSON cannot mutate admitted state"
        );
    }

    #[test]
    fn bom_is_rejected_without_state_change() {
        let baseline = br#"{"jsonrpc":"2.0","method":"tools/list","id":"public-request"}"#;
        let mut planted = baseline.to_vec();
        planted.splice(0..0, [0xef, 0xbb, 0xbf]);
        let mut state = AdmittedFrames::default();
        admit_frame(&mut state, baseline).expect("the baseline is admitted");
        let state_before = state.clone();

        assert!(
            matches!(
                admit_frame(&mut state, &planted),
                Err(JsonRpcAdmissionError::Raw(
                    RawJsonAdmissionError::ByteOrderMark
                ))
            ),
            "inserting only a UTF-8 BOM must reach the typed raw-admission refusal"
        );
        assert_eq!(
            state, state_before,
            "rejected raw bytes leave admitted state unchanged"
        );
    }

    #[test]
    fn bom_after_a_lead_byte_near_miss_is_rejected_inside_a_string() {
        // U+FEFB encodes as EF BB BB, sharing the mark's first two bytes, so
        // the seek must continue past it to the U+FEFF (EF BB BF) behind it.
        let planted =
            "{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"id\":\"a\u{fefb}\u{feff}\"}";
        let near_miss =
            "{\"jsonrpc\":\"2.0\",\"method\":\"tools/list\",\"id\":\"a\u{fefb}\u{fefb}\"}";
        let mut state = AdmittedFrames::default();

        assert!(
            matches!(
                admit_frame(&mut state, planted.as_bytes()),
                Err(JsonRpcAdmissionError::Raw(
                    RawJsonAdmissionError::ByteOrderMark
                ))
            ),
            "a mark inside a string value is refused like a leading one"
        );
        admit_frame(&mut state, near_miss.as_bytes())
            .expect("changing only the mark's last byte leaves an admissible code point");
    }

    #[test]
    fn envelope_admission_records_only_the_root_members_with_exact_value_spans() {
        // The second member's name is `id` and its value `ab`, both spelled
        // with a unicode escape.
        let document =
            b" { \"jsonrpc\" : \"2.0\" , \"\\u0069d\" : \"a\\u0062\" , \"params\" : {\"id\":[1,{\"method\":2}]} } ";
        let span_of = |token: &str| {
            let start = document
                .windows(token.len())
                .position(|window| window == token.as_bytes())
                .expect("token is present");
            start..start + token.len()
        };

        let members = admit_raw_jsonrpc_envelope(document, 1024).expect("document is admissible");

        assert_eq!(
            members,
            [
                RawJsonRpcEnvelopeMember {
                    name: "jsonrpc".to_owned(),
                    value: span_of(r#""2.0""#),
                },
                RawJsonRpcEnvelopeMember {
                    name: "id".to_owned(),
                    value: span_of("\"a\\u0062\""),
                },
                RawJsonRpcEnvelopeMember {
                    name: "params".to_owned(),
                    value: span_of(r#"{"id":[1,{"method":2}]}"#),
                },
            ],
            "names are unescaped, spans exclude whitespace, and nested members are not recorded"
        );
        assert_eq!(admit_raw_jsonrpc_document(document, 1024), Ok(()));

        // The same document with the escaped `id` spelled as a second `params`
        // is refused exactly as the unrecorded admission refuses it.
        let duplicate =
            b" { \"jsonrpc\" : \"2.0\" , \"p\\u0061rams\" : \"a\\u0062\" , \"params\" : {\"id\":[1,{\"method\":2}]} } ";
        assert_eq!(
            admit_raw_jsonrpc_envelope(duplicate, 1024),
            Err(RawJsonAdmissionError::DuplicateObjectMember)
        );
        assert_eq!(
            admit_raw_jsonrpc_document(duplicate, 1024),
            Err(RawJsonAdmissionError::DuplicateObjectMember)
        );
    }

    #[test]
    fn request_id_correlation_key_normalizes_numeric_aliases() {
        let numeric = RequestId::Number(1);
        let string = RequestId::String("1".to_owned());
        assert_ne!(
            numeric, string,
            "string and numeric request IDs are disjoint"
        );
        assert_eq!(
            numeric.correlation_key().expect("valid numeric ID"),
            RequestId::Integer("1.0".to_owned())
                .correlation_key()
                .expect("valid mathematical integer ID"),
            "numeric aliases share one exact mathematical correlation key"
        );
        assert_eq!(
            numeric.correlation_key().expect("valid numeric ID"),
            RequestId::Integer("1e0".to_owned())
                .correlation_key()
                .expect("valid mathematical integer ID"),
            "exponent-form integer aliases share one exact mathematical correlation key"
        );
        assert_ne!(
            numeric.correlation_key().expect("valid numeric ID"),
            string.correlation_key().expect("valid string ID"),
            "a string ID never aliases its numeric spelling"
        );
        assert!(numeric.correlates_with(&RequestId::Integer("1.0".to_owned())));
        assert!(numeric.correlates_with(&RequestId::Integer("1e0".to_owned())));
        assert!(!numeric.correlates_with(&string));
        assert_eq!(
            JsonRpcResponse::success(numeric.clone(), Value::Null).id,
            Some(numeric),
            "a correlated success preserves its accepted request ID"
        );
        let large = "922337203685477580812345678901234567890";
        let raw = format!(r#"{{"jsonrpc":"2.0","method":"tools/list","id":{large}}}"#);
        let decoded = decode_strict_jsonrpc_message(raw.as_bytes(), 4 * 1024)
            .expect("an arbitrary-precision mathematical integer is admitted");
        let JsonRpcMessage::Request(request) = decoded else {
            panic!("the admitted envelope remains a request");
        };
        assert_eq!(request.id, Some(RequestId::Integer(large.to_owned())));
        let echoed = JsonRpcResponse::success(
            request
                .id
                .expect("admitted request keeps its original ID lexeme"),
            Value::Null,
        );
        assert!(
            serde_json::to_string(&echoed)
                .expect("the exact admitted ID can be echoed")
                .contains(large),
            "response serialization preserves the accepted arbitrary-precision ID lexeme"
        );
        assert!(matches!(
            dispose_raw_jsonrpc_failure(
                JsonRpcEndpointRole::ServerIngress,
                JsonRpcMessageDirection::ClientToServer,
                Some(RequestId::Number(9)),
                ClientIngressFailureScope::OwningExchange,
            ),
            RawJsonRpcDisposition::CorrelatedError(JsonRpcResponse {
                id: Some(RequestId::Number(9)),
                ..
            })
        ));
    }

    #[test]
    fn request_id_correlation_key_accepts_zero_at_negative_exponent_bound() {
        let zero = RequestId::Number(0);
        for lexeme in ["0e-9999", "-0.00e-10000", "0.0e-4"] {
            let alias = RequestId::Integer(lexeme.to_owned());
            assert!(
                zero.correlates_with(&alias),
                "{lexeme} remains mathematical zero"
            );
            assert_eq!(
                alias.correlation_key().unwrap(),
                CorrelationKey::Integer("0".to_owned())
            );
            let wire = serde_json::to_string(&alias).expect("zero alias is a valid request ID");
            assert_eq!(
                wire, lexeme,
                "canonical correlation does not change exact echo"
            );
            let fractional = RequestId::Integer(lexeme.replacen('0', "1", 1));
            assert!(
                fractional.correlation_key().is_err(),
                "a nonzero fractional sibling is rejected"
            );
            assert_eq!(
                alias.correlation_key().unwrap(),
                zero.correlation_key().unwrap()
            );
        }
        assert!(
            RequestId::Integer("0e-10001".to_owned())
                .correlation_key()
                .is_err()
        );
    }

    #[test]
    fn request_id_fractional_lexeme_is_rejected_before_correlation() {
        let baseline = br#"{"jsonrpc":"2.0","method":"tools/list","id":1}"#;
        let planted = br#"{"jsonrpc":"2.0","method":"tools/list","id":1.5}"#;
        let mut state = AdmittedFrames::default();
        admit_frame(&mut state, baseline).expect("integer request ID is admitted");
        let state_before = state.clone();

        assert!(
            matches!(
                admit_frame(&mut state, planted),
                Err(JsonRpcAdmissionError::InvalidEnvelope)
            ),
            "changing only the ID to a fractional number must be rejected"
        );
        assert_eq!(
            state, state_before,
            "a rejected fractional ID cannot claim a correlation slot"
        );
    }

    #[test]
    fn duplicate_nested_member_is_rejected_without_state_change() {
        let baseline = br#"{"jsonrpc":"2.0","method":"tools/list","params":{"cursor":"a"}}"#;
        let planted =
            br#"{"jsonrpc":"2.0","method":"tools/list","params":{"cursor":"a","cursor":"b"}}"#;
        let mut state = AdmittedFrames::default();
        admit_frame(&mut state, baseline).expect("baseline nested object is admitted");
        let state_before = state.clone();

        assert!(
            matches!(
                admit_frame(&mut state, planted),
                Err(JsonRpcAdmissionError::Raw(
                    RawJsonAdmissionError::DuplicateObjectMember
                ))
            ),
            "a one-member duplicate must fail before typed params decoding"
        );
        assert_eq!(
            state, state_before,
            "duplicate raw members cannot mutate admitted state"
        );
    }

    #[test]
    fn top_level_batches_are_rejected_without_state_change() {
        let baseline = br#"{"jsonrpc":"2.0","method":"tools/list"}"#;
        let array_of_one = br#"[{"jsonrpc":"2.0","method":"tools/list"}]"#;
        let mixed_array = br#"[{"jsonrpc":"2.0","method":"tools/list"},{"jsonrpc":"2.0","method":"notifications/initialized"}]"#;
        let mut state = AdmittedFrames::default();
        admit_frame(&mut state, baseline).expect("one top-level request object is admitted");
        let state_before = state.clone();

        for planted in [array_of_one.as_slice(), mixed_array.as_slice()] {
            assert!(
                matches!(
                    admit_frame(&mut state, planted),
                    Err(JsonRpcAdmissionError::Raw(
                        RawJsonAdmissionError::TopLevelBatch
                    ))
                ),
                "a top-level batch fails before envelope construction"
            );
            assert_eq!(
                state, state_before,
                "rejected batch traffic has no admitted state effect"
            );
        }
    }

    // ========================================================================
    // RequestId Tests
    // ========================================================================

    #[test]
    fn request_id_number_serialization() {
        let id = RequestId::Number(42);
        let value = serde_json::to_value(&id).expect("serialize");
        assert_eq!(value, 42);
    }

    #[test]
    fn request_id_string_serialization() {
        let id = RequestId::String("req-1".to_string());
        let value = serde_json::to_value(&id).expect("serialize");
        assert_eq!(value, "req-1");
    }

    #[test]
    fn request_id_number_deserialization() {
        let id: RequestId = serde_json::from_value(json!(99)).expect("deserialize");
        assert_eq!(id, RequestId::Number(99));
    }

    #[test]
    fn request_id_string_deserialization() {
        let id: RequestId = serde_json::from_value(json!("abc")).expect("deserialize");
        assert_eq!(id, RequestId::String("abc".to_string()));
    }

    #[test]
    fn request_id_string_enforces_encoded_byte_limit() {
        let exact = "a".repeat(MAX_JSONRPC_STRING_ID_ENCODED_BYTES - 2);
        let too_long = "a".repeat(MAX_JSONRPC_STRING_ID_ENCODED_BYTES - 1);
        let exact_json = format!("\"{exact}\"");
        let too_long_json = format!("\"{too_long}\"");

        assert!(serde_json::from_str::<RequestId>(&exact_json).is_ok());
        assert!(serde_json::from_str::<RequestId>(&too_long_json).is_err());
        assert!(serde_json::to_string(&RequestId::String(exact)).is_ok());
        assert!(serde_json::to_string(&RequestId::String(too_long)).is_err());

        let escaped_exact = format!("\"{}\"", "\\u0001".repeat(42));
        let escaped_too_long = format!("\"{}\"", "\\u0001".repeat(43));
        assert_eq!(escaped_exact.len(), 254);
        assert!(serde_json::from_str::<RequestId>(&escaped_exact).is_ok());
        assert!(serde_json::from_str::<RequestId>(&escaped_too_long).is_err());
    }

    #[test]
    fn request_id_validation_catches_direct_construction_bypass() {
        let too_long = RequestId::String("a".repeat(MAX_JSONRPC_STRING_ID_ENCODED_BYTES));

        assert_eq!(
            too_long.validate(),
            Err("JSON-RPC string id exceeds byte limit")
        );
    }

    #[test]
    fn request_rejects_explicit_null_id_but_accepts_absent_id() {
        let error = serde_json::from_str::<JsonRpcRequest>(
            r#"{"jsonrpc":"2.0","method":"notifications/initialized","id":null}"#,
        )
        .expect_err("an explicit null id must not become a notification");
        assert!(
            error
                .to_string()
                .contains("JSON-RPC id must be a string or mathematical integer")
        );

        let notification = serde_json::from_str::<JsonRpcRequest>(
            r#"{"jsonrpc":"2.0","method":"notifications/initialized"}"#,
        )
        .expect("an absent id denotes a notification");
        assert!(notification.is_notification());
    }

    #[test]
    fn request_id_from_i64() {
        let id: RequestId = 7i64.into();
        assert_eq!(id, RequestId::Number(7));
    }

    #[test]
    fn request_id_from_string() {
        let id: RequestId = "test-id".to_string().into();
        assert_eq!(id, RequestId::String("test-id".to_string()));
    }

    #[test]
    fn request_id_from_str() {
        let id: RequestId = "test-id".into();
        assert_eq!(id, RequestId::String("test-id".to_string()));
    }

    #[test]
    fn request_id_display() {
        assert_eq!(format!("{}", RequestId::Number(42)), "42");
        assert_eq!(
            format!("{}", RequestId::String("req-1".to_string())),
            "req-1"
        );
    }

    #[test]
    fn request_id_equality() {
        assert_eq!(RequestId::Number(1), RequestId::Number(1));
        assert_ne!(RequestId::Number(1), RequestId::Number(2));
        assert_eq!(
            RequestId::String("a".to_string()),
            RequestId::String("a".to_string())
        );
        assert_ne!(RequestId::Number(1), RequestId::String("1".to_string()));
    }

    // ========================================================================
    // JsonRpcRequest Tests
    // ========================================================================

    #[test]
    fn jsonrpc_version_deserialize_borrows_static_for_request() {
        let req: JsonRpcRequest =
            serde_json::from_str(r#"{"jsonrpc":"2.0","method":"tools/list","id":1}"#)
                .expect("deserialize");
        assert!(matches!(req.jsonrpc, Cow::Borrowed(JSONRPC_VERSION)));
    }

    #[test]
    fn request_rejects_nonstandard_missing_and_non_string_jsonrpc_versions() {
        for input in [
            r#"{"jsonrpc":"2.1","method":"tools/list","id":1}"#,
            r#"{"jsonrpc":"1.0","method":"tools/list","id":1}"#,
            r#"{"jsonrpc":null,"method":"tools/list","id":1}"#,
            r#"{"method":"tools/list","id":1}"#,
        ] {
            let error = serde_json::from_str::<JsonRpcRequest>(input).unwrap_err();
            assert!(error.is_data(), "unexpected error for {input}: {error}");
        }
    }

    #[test]
    fn request_serialization() {
        let req = JsonRpcRequest::new("tools/list", None, 1i64);
        let json = serde_json::to_string(&req).unwrap();
        assert!(json.contains("\"jsonrpc\":\"2.0\""));
        assert!(json.contains("\"method\":\"tools/list\""));
        assert!(json.contains("\"id\":1"));
    }

    #[test]
    fn request_with_params() {
        let params = json!({"name": "greet", "arguments": {"name": "World"}});
        let req = JsonRpcRequest::new("tools/call", Some(params.clone()), 2i64);
        let value = serde_json::to_value(&req).expect("serialize");
        assert_eq!(value["jsonrpc"], "2.0");
        assert_eq!(value["method"], "tools/call");
        assert_eq!(value["params"]["name"], "greet");
        assert_eq!(value["id"], 2);
    }

    #[test]
    fn strict_request_raw_params_sidecar_preserves_exact_source_and_rejects_duplicates() {
        let raw_params = r#"{"_meta":{"io.modelcontextprotocol/protocolVersion":"2026-07-28","io.modelcontextprotocol/clientCapabilities":{}},"name":"weather","inputResponses":{"second":{"roots":[]},"first":{"roots":[]}},"requestState":"retry-1"}"#;
        let frame =
            format!(r#"{{"jsonrpc":"2.0","method":"tools/call","params":{raw_params},"id":7}}"#);
        let (request, sidecar) =
            JsonRpcRequest::decode_strict_with_raw_params(frame.as_bytes(), frame.len())
                .expect("strict request admission retains the exact parameter source");
        assert_eq!(sidecar.as_deref(), Some(raw_params));
        assert_eq!(
            request.params,
            Some(serde_json::from_str(raw_params).expect("raw params materialize")),
            "the sidecar belongs to the same admitted typed request"
        );

        let duplicate = r#"{"jsonrpc":"2.0","method":"tools/call","params":{"inputResponses":{"roots":{"roots":[]},"roots":{"roots":[]}}},"id":7}"#;
        assert!(matches!(
            JsonRpcRequest::decode_strict_with_raw_params(duplicate.as_bytes(), duplicate.len()),
            Err(JsonRpcAdmissionError::Raw(
                RawJsonAdmissionError::DuplicateObjectMember
            ))
        ));
    }

    #[test]
    fn request_without_params_omits_field() {
        let req = JsonRpcRequest::new("tools/list", None, 1i64);
        let value = serde_json::to_value(&req).expect("serialize");
        assert!(value.get("params").is_none());
    }

    #[test]
    fn notification_has_no_id() {
        let notif = JsonRpcRequest::notification("notifications/progress", None);
        assert!(notif.is_notification());
        assert!(notif.id.is_none());
        let value = serde_json::to_value(&notif).expect("serialize");
        assert!(value.get("id").is_none());
    }

    #[test]
    fn notification_with_params() {
        let params = json!({"uri": "file://changed.txt"});
        let notif = JsonRpcRequest::notification("notifications/resources/updated", Some(params));
        assert!(notif.is_notification());
        let value = serde_json::to_value(&notif).expect("serialize");
        assert_eq!(value["params"]["uri"], "file://changed.txt");
    }

    #[test]
    fn request_is_not_notification() {
        let req = JsonRpcRequest::new("tools/list", None, 1i64);
        assert!(!req.is_notification());
    }

    #[test]
    fn request_with_string_id() {
        let req = JsonRpcRequest::new("tools/list", None, "req-abc");
        let value = serde_json::to_value(&req).expect("serialize");
        assert_eq!(value["id"], "req-abc");
    }

    #[test]
    fn request_round_trip() {
        let original = JsonRpcRequest::new(
            "tools/call",
            Some(json!({"name": "add", "arguments": {"a": 1, "b": 2}})),
            42i64,
        );
        let json_str = serde_json::to_string(&original).expect("serialize");
        let deserialized: JsonRpcRequest = serde_json::from_str(&json_str).expect("deserialize");
        assert_eq!(deserialized.method, "tools/call");
        assert_eq!(deserialized.id, Some(RequestId::Number(42)));
        assert!(deserialized.params.is_some());
    }

    #[test]
    fn request_rejects_unknown_top_level_envelope_members() {
        let error = serde_json::from_str::<JsonRpcRequest>(
            r#"{"jsonrpc":"2.0","method":"tools/list","id":1,"extension":true}"#,
        )
        .expect_err("request envelopes are closed");

        assert!(error.to_string().contains("unknown field"));
    }

    // ========================================================================
    // JsonRpcError Tests
    // ========================================================================

    #[test]
    fn jsonrpc_error_from_mcp_error_preserves_code_message_and_data() {
        let err = fastmcp_core::McpError::with_data(
            fastmcp_core::McpErrorCode::InvalidParams,
            "bad params",
            json!({"field":"name"}),
        );
        let rpc_err: JsonRpcError = err.into();
        assert_eq!(rpc_err.code.as_i32(), Some(-32602));
        assert_eq!(rpc_err.message, "bad params");
        assert_eq!(rpc_err.data, Some(json!({"field":"name"})));
    }

    #[test]
    fn jsonrpc_error_serialization() {
        let error = JsonRpcError {
            code: (-32600).into(),
            message: "Invalid Request".to_string(),
            data: None,
        };
        let value = serde_json::to_value(&error).expect("serialize");
        assert_eq!(value["code"], -32600);
        assert_eq!(value["message"], "Invalid Request");
        assert!(value.get("data").is_none());
    }

    #[test]
    fn jsonrpc_error_with_data() {
        let error = JsonRpcError {
            code: (-32602).into(),
            message: "Invalid params".to_string(),
            data: Some(json!({"field": "name", "reason": "required"})),
        };
        let value = serde_json::to_value(&error).expect("serialize");
        assert_eq!(value["code"], -32602);
        assert_eq!(value["data"]["field"], "name");
    }

    #[test]
    fn jsonrpc_error_preserves_arbitrary_width_integer_code() {
        let source = r#"{"code":-340282366920938463463374607431768211457,"message":"unbounded"}"#;
        let error: JsonRpcError = serde_json::from_str(source).expect("decode arbitrary code");

        assert_eq!(
            error.code.as_str(),
            "-340282366920938463463374607431768211457"
        );
        assert_eq!(
            serde_json::to_string(&error).expect("re-encode arbitrary code"),
            source
        );
    }

    #[test]
    fn jsonrpc_error_rejects_nearby_fractional_code() {
        let source =
            r#"{"code":-340282366920938463463374607431768211457.5,"message":"not integer"}"#;

        assert!(serde_json::from_str::<JsonRpcError>(source).is_err());
    }

    #[test]
    fn jsonrpc_error_standard_codes() {
        // Parse error
        let err = JsonRpcError {
            code: (-32700).into(),
            message: "Parse error".to_string(),
            data: None,
        };
        assert_eq!(serde_json::to_value(&err).unwrap()["code"], -32700);

        // Method not found
        let err = JsonRpcError {
            code: (-32601).into(),
            message: "Method not found".to_string(),
            data: None,
        };
        assert_eq!(serde_json::to_value(&err).unwrap()["code"], -32601);

        // Internal error
        let err = JsonRpcError {
            code: (-32603).into(),
            message: "Internal error".to_string(),
            data: None,
        };
        assert_eq!(serde_json::to_value(&err).unwrap()["code"], -32603);
    }

    // ========================================================================
    // JsonRpcResponse Tests
    // ========================================================================

    #[test]
    fn jsonrpc_version_deserialize_borrows_static_for_response() {
        let resp: JsonRpcResponse =
            serde_json::from_str(r#"{"jsonrpc":"2.0","result":{"tools":[]},"id":1}"#)
                .expect("deserialize");
        assert!(matches!(resp.jsonrpc, Cow::Borrowed(JSONRPC_VERSION)));
    }

    #[test]
    fn response_rejects_nonstandard_missing_and_non_string_jsonrpc_versions() {
        for input in [
            r#"{"jsonrpc":"2.1","result":{"tools":[]},"id":1}"#,
            r#"{"jsonrpc":"1.0","result":{"tools":[]},"id":1}"#,
            r#"{"jsonrpc":null,"result":{"tools":[]},"id":1}"#,
            r#"{"result":{"tools":[]},"id":1}"#,
        ] {
            let error = serde_json::from_str::<JsonRpcResponse>(input).unwrap_err();
            assert!(error.is_data(), "unexpected error for {input}: {error}");
        }
    }

    #[test]
    fn serialization_rejects_mutated_nonstandard_jsonrpc_version() {
        let mut request = JsonRpcRequest::new("tools/list", None, 1_i64);
        request.jsonrpc = Cow::Borrowed("2.1");
        assert!(serde_json::to_string(&request).is_err());

        let mut response = JsonRpcResponse::success(RequestId::Number(1), Value::Null);
        response.jsonrpc = Cow::Borrowed("1.0");
        assert!(serde_json::to_string(&response).is_err());
    }

    #[test]
    fn response_success() {
        let resp = JsonRpcResponse::success(RequestId::Number(1), json!({"result": "ok"}));
        let value = serde_json::to_value(&resp).expect("serialize");
        assert_eq!(value["jsonrpc"], "2.0");
        assert_eq!(value["result"]["result"], "ok");
        assert_eq!(value["id"], 1);
        assert!(value.get("error").is_none());
        assert!(!resp.is_error());
    }

    #[test]
    fn response_error() {
        let error = JsonRpcError {
            code: (-32601).into(),
            message: "Method not found".to_string(),
            data: None,
        };
        let resp = JsonRpcResponse::error(Some(RequestId::Number(1)), error);
        let value = serde_json::to_value(&resp).expect("serialize");
        assert_eq!(value["jsonrpc"], "2.0");
        assert!(value.get("result").is_none());
        assert_eq!(value["error"]["code"], -32601);
        assert_eq!(value["error"]["message"], "Method not found");
        assert_eq!(value["id"], 1);
        assert!(resp.is_error());
    }

    #[test]
    fn uncorrelated_response_error_omits_id() {
        let error = JsonRpcError {
            code: (-32700).into(),
            message: "Parse error".to_string(),
            data: None,
        };
        let resp = JsonRpcResponse::error(None, error);
        let value = serde_json::to_value(&resp).expect("serialize");
        assert!(value.get("id").is_none());
    }

    #[test]
    fn response_rejects_explicit_null_id_but_accepts_absent_id() {
        let explicit_null = serde_json::from_str::<JsonRpcResponse>(
            r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"},"id":null}"#,
        );
        assert!(explicit_null.is_err());

        let absent = serde_json::from_str::<JsonRpcResponse>(
            r#"{"jsonrpc":"2.0","error":{"code":-32700,"message":"Parse error"}}"#,
        )
        .expect("an uncorrelated MCP error omits id");
        assert!(absent.id.is_none());
    }

    #[test]
    fn response_round_trip() {
        let original =
            JsonRpcResponse::success(RequestId::String("abc".to_string()), json!({"tools": []}));
        let json_str = serde_json::to_string(&original).expect("serialize");
        let deserialized: JsonRpcResponse = serde_json::from_str(&json_str).expect("deserialize");
        assert!(!deserialized.is_error());
        assert!(deserialized.result.is_some());
        assert_eq!(deserialized.id, Some(RequestId::String("abc".to_string())));
    }

    #[test]
    fn response_null_result_round_trip_preserves_member_presence() {
        let raw = r#"{"jsonrpc":"2.0","result":null,"id":1}"#;
        let response: JsonRpcResponse = serde_json::from_str(raw).expect("deserialize response");

        assert_eq!(response.result, Some(Value::Null));
        assert!(response.error.is_none());

        let encoded = serde_json::to_value(response).expect("serialize response");
        assert_eq!(encoded.get("result"), Some(&Value::Null));
        assert!(encoded.get("error").is_none());
    }

    #[test]
    fn response_rejects_both_or_neither_outcome_members() {
        for raw in [
            r#"{"jsonrpc":"2.0","result":null,"error":{"code":-32603,"message":"failure"},"id":1}"#,
            r#"{"jsonrpc":"2.0","id":1}"#,
        ] {
            let error = serde_json::from_str::<JsonRpcResponse>(raw)
                .expect_err("invalid response envelope must be rejected");
            assert!(error.to_string().contains("exactly one"));
        }

        let both = JsonRpcResponse {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            result: Some(Value::Null),
            error: Some(JsonRpcError {
                code: (-32_603).into(),
                message: "failure".to_string(),
                data: None,
            }),
            id: Some(RequestId::Number(1)),
        };
        assert!(serde_json::to_value(both).is_err());

        let neither = JsonRpcResponse {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            result: None,
            error: None,
            id: Some(RequestId::Number(1)),
        };
        assert!(serde_json::to_value(neither).is_err());
    }

    #[test]
    fn response_rejects_unknown_top_level_envelope_members() {
        let error = serde_json::from_str::<JsonRpcResponse>(
            r#"{"jsonrpc":"2.0","result":null,"id":1,"extension":true}"#,
        )
        .expect_err("response envelopes are closed");

        assert!(error.to_string().contains("unknown field"));
    }

    #[test]
    fn response_validation_rejects_uncorrelated_success() {
        let response = JsonRpcResponse {
            jsonrpc: Cow::Borrowed(JSONRPC_VERSION),
            result: Some(Value::Null),
            error: None,
            id: None,
        };

        assert_eq!(
            response.validate(),
            Err("JSON-RPC success response must contain an id")
        );
        assert!(serde_json::to_value(response).is_err());
        assert!(
            serde_json::from_str::<JsonRpcResponse>(r#"{"jsonrpc":"2.0","result":null}"#).is_err()
        );
    }

    // ========================================================================
    // JsonRpcMessage Tests
    // ========================================================================

    #[test]
    fn message_request_variant() {
        let req = JsonRpcRequest::new("tools/list", None, 1i64);
        let msg = JsonRpcMessage::Request(req);
        let value = serde_json::to_value(&msg).expect("serialize");
        assert_eq!(value["method"], "tools/list");
    }

    #[test]
    fn message_response_variant() {
        let resp = JsonRpcResponse::success(RequestId::Number(1), json!("ok"));
        let msg = JsonRpcMessage::Response(resp);
        let value = serde_json::to_value(&msg).expect("serialize");
        assert_eq!(value["result"], "ok");
    }

    #[test]
    fn message_deserialize_as_request() {
        let json_str = r#"{"jsonrpc":"2.0","method":"tools/list","id":1}"#;
        let msg: JsonRpcMessage = serde_json::from_str(json_str).expect("deserialize");
        let (method, id) = match msg {
            JsonRpcMessage::Request(req) => (req.method, req.id),
            JsonRpcMessage::Response(_) => (String::new(), None),
        };
        assert_eq!(method, "tools/list");
        assert_eq!(id, Some(RequestId::Number(1)));
    }

    #[test]
    fn message_deserialize_as_response() {
        let json_str = r#"{"jsonrpc":"2.0","result":{"tools":[]},"id":1}"#;
        let msg: JsonRpcMessage = serde_json::from_str(json_str).expect("deserialize");
        let (is_error, id) = match msg {
            JsonRpcMessage::Response(resp) => (resp.is_error(), resp.id),
            JsonRpcMessage::Request(_) => (true, None),
        };
        assert!(!is_error);
        assert_eq!(id, Some(RequestId::Number(1)));
    }

    fn final_completion_request(context: &str) -> String {
        format!(
            r#"{{"jsonrpc":"2.0","method":"completion/complete","params":{{"_meta":{{"io.modelcontextprotocol/protocolVersion":"{}","io.modelcontextprotocol/clientCapabilities":{{}}}},"ref":{{"type":"ref/prompt","name":"deploy"}},"argument":{{"name":"environment","value":"pro"}},{context}}},"id":1}}"#,
            crate::FINAL_PROTOCOL_VERSION
        )
    }

    /// Requests and notifications with params decode through the public
    /// message type to exactly what the request type decodes from the same
    /// text. The completion case goes through the request's raw-source params
    /// validation, which only sees the exact source bytes.
    #[test]
    fn message_serde_decodes_requests_and_notifications_with_params() {
        let completion = final_completion_request(r#""context":{"arguments":{"key":"one"}}"#);
        for text in [
            r#"{"jsonrpc":"2.0","method":"tools/call","params":{"name":"probe","arguments":{}},"id":1}"#,
            r#"{"jsonrpc":"2.0","method":"notifications/progress","params":{"progressToken":"probe","progress":1}}"#,
            completion.as_str(),
        ] {
            let direct = serde_json::from_str::<JsonRpcRequest>(text)
                .unwrap_or_else(|error| panic!("the request type decodes {text}: {error}"));
            let decoded = match serde_json::from_str::<JsonRpcMessage>(text) {
                Ok(JsonRpcMessage::Request(request)) => request,
                other => panic!("{text} must decode as a request, got {other:?}"),
            };
            assert!(decoded.params.is_some(), "{text}");
            assert_eq!(decoded.jsonrpc, direct.jsonrpc);
            assert_eq!(decoded.method, direct.method);
            assert_eq!(decoded.params, direct.params);
            assert_eq!(decoded.id, direct.id);
        }

        for text in [
            r#"{"jsonrpc":"2.0","result":{"tools":[]},"id":1}"#,
            r#"{"jsonrpc":"2.0","error":{"code":-32601,"message":"missing"},"id":1}"#,
        ] {
            assert!(
                matches!(
                    serde_json::from_str::<JsonRpcMessage>(text),
                    Ok(JsonRpcMessage::Response(_))
                ),
                "{text} must still decode as a response"
            );
        }
    }

    /// The same texts differing in one member the request type refuses are
    /// refused through the public message type too. The duplicate `context`
    /// is caught only by the raw params validation, so this also fails if the
    /// message decoder stops handing the request its exact source bytes.
    #[test]
    fn message_serde_refuses_what_the_request_type_refuses() {
        let duplicate_context = final_completion_request(
            r#""context":{"arguments":{"key":"one"}},"context":{"arguments":{"key":"two"}}"#,
        );
        for text in [
            r#"{"jsonrpc":"2.0","method":"tools/call","params":{"name":"probe","arguments":{}},"id":null}"#,
            duplicate_context.as_str(),
        ] {
            assert!(
                serde_json::from_str::<JsonRpcRequest>(text).is_err(),
                "the request type refuses {text}"
            );
            assert!(
                serde_json::from_str::<JsonRpcMessage>(text).is_err(),
                "the message type must refuse {text}"
            );
        }
    }

    #[test]
    fn message_rejects_mixed_request_and_response_envelopes() {
        for raw in [
            r#"{"jsonrpc":"2.0","method":"tools/list","result":null,"id":1}"#,
            r#"{"jsonrpc":"2.0","params":{},"error":{"code":-32603,"message":"failure"},"id":1}"#,
        ] {
            assert!(
                serde_json::from_str::<JsonRpcMessage>(raw).is_err(),
                "mixed envelope was accepted: {raw}"
            );
        }
    }

    #[test]
    fn message_validation_catches_public_field_mutation() {
        let mut request = JsonRpcRequest::new("tools/list", None, 1_i64);
        request.jsonrpc = Cow::Borrowed("2.1");
        let message = JsonRpcMessage::Request(request);

        assert_eq!(message.validate(), Err("jsonrpc must be exactly \"2.0\""));
    }

    // ========================================================================
    // JSONRPC_VERSION constant test
    // ========================================================================

    #[test]
    fn jsonrpc_version_constant() {
        assert_eq!(JSONRPC_VERSION, "2.0");
    }
}