pulseengine-mcp-protocol 0.17.1

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

use crate::Error;
use serde::{Deserialize, Serialize};
use std::collections::HashMap;
use std::sync::Arc;

/// MIME type constants for common resource types
pub mod mime_types {
    /// HTML content with MCP JavaScript SDK for interactive UIs (MCP Apps Extension)
    pub const HTML_MCP: &str = "text/html+mcp";

    /// Plain HTML content
    pub const HTML: &str = "text/html";

    /// JSON data
    pub const JSON: &str = "application/json";

    /// Plain text
    pub const TEXT: &str = "text/plain";

    /// Binary blob
    pub const OCTET_STREAM: &str = "application/octet-stream";
}

/// URI scheme constants for resource URIs
pub mod uri_schemes {
    /// UI resources for interactive interfaces (MCP Apps Extension)
    pub const UI: &str = "ui://";

    /// File system resources
    pub const FILE: &str = "file://";

    /// HTTP resources
    pub const HTTP: &str = "http://";

    /// HTTPS resources
    pub const HTTPS: &str = "https://";
}

/// Metadata for MCP protocol messages (MCP 2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Meta {
    /// Progress token for tracking long-running operations
    #[serde(rename = "progressToken", skip_serializing_if = "Option::is_none")]
    pub progress_token: Option<String>,
}

/// A flexible identifier type for JSON-RPC request IDs
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum NumberOrString {
    Number(i64),
    String(Arc<str>),
}

impl NumberOrString {
    pub fn into_json_value(self) -> serde_json::Value {
        match self {
            NumberOrString::Number(n) => serde_json::Value::Number(serde_json::Number::from(n)),
            NumberOrString::String(s) => serde_json::Value::String(s.to_string()),
        }
    }

    pub fn from_json_value(value: serde_json::Value) -> Option<Self> {
        match value {
            serde_json::Value::Number(n) => n.as_i64().map(NumberOrString::Number),
            serde_json::Value::String(s) => Some(NumberOrString::String(Arc::from(s.as_str()))),
            _ => None,
        }
    }
}

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

impl Serialize for NumberOrString {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        match self {
            NumberOrString::Number(n) => serializer.serialize_i64(*n),
            NumberOrString::String(s) => serializer.serialize_str(s),
        }
    }
}

impl<'de> Deserialize<'de> for NumberOrString {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        struct NumberOrStringVisitor;

        impl<'de> serde::de::Visitor<'de> for NumberOrStringVisitor {
            type Value = NumberOrString;

            fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
                formatter.write_str("a number or string")
            }

            fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(NumberOrString::Number(value))
            }

            fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(NumberOrString::Number(value as i64))
            }

            fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(NumberOrString::String(Arc::from(value)))
            }

            fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
            where
                E: serde::de::Error,
            {
                Ok(NumberOrString::String(Arc::from(value.as_str())))
            }
        }

        deserializer.deserialize_any(NumberOrStringVisitor)
    }
}

/// JSON-RPC 2.0 Request
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Request {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// Request method name
    pub method: String,
    /// Request parameters
    #[serde(default = "serde_json::Value::default")]
    pub params: serde_json::Value,
    /// Request ID (None for notifications)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<NumberOrString>,
}

/// JSON-RPC 2.0 Response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Response {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// Response result (if successful)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
    /// Response error (if failed)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub error: Option<Error>,
    /// Request ID (can be null for error responses)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub id: Option<NumberOrString>,
}

/// MCP Protocol version in date format (YYYY-MM-DD)
#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd, Serialize, Deserialize)]
pub struct ProtocolVersion(std::borrow::Cow<'static, str>);

impl Default for ProtocolVersion {
    fn default() -> Self {
        Self::LATEST
    }
}

impl std::fmt::Display for ProtocolVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.0.fmt(f)
    }
}

impl ProtocolVersion {
    pub const V_2025_11_25: Self = Self(std::borrow::Cow::Borrowed("2025-11-25"));
    pub const V_2025_06_18: Self = Self(std::borrow::Cow::Borrowed("2025-06-18"));
    pub const V_2025_03_26: Self = Self(std::borrow::Cow::Borrowed("2025-03-26"));
    pub const V_2024_11_05: Self = Self(std::borrow::Cow::Borrowed("2024-11-05"));
    pub const LATEST: Self = Self::V_2025_11_25;

    pub fn new(version: impl Into<std::borrow::Cow<'static, str>>) -> Self {
        Self(version.into())
    }
}

/// Server implementation information
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Implementation {
    pub name: String,
    pub version: String,
    /// Optional human-readable description of the implementation (MCP 2025-11-25)
    #[serde(skip_serializing_if = "Option::is_none")]
    #[serde(default)]
    pub description: Option<String>,
}

impl Implementation {
    /// Create a new Implementation with name and version
    pub fn new(name: impl Into<String>, version: impl Into<String>) -> Self {
        Self {
            name: name.into(),
            version: version.into(),
            description: None,
        }
    }

    /// Create a new Implementation with name, version, and description
    pub fn with_description(
        name: impl Into<String>,
        version: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        Self {
            name: name.into(),
            version: version.into(),
            description: Some(description.into()),
        }
    }
}

/// Server capabilities configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ServerCapabilities {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<ToolsCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resources: Option<ResourcesCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompts: Option<PromptsCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logging: Option<LoggingCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sampling: Option<SamplingCapability>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub elicitation: Option<ElicitationCapability>,
    /// Tasks capability (MCP 2025-11-25 experimental)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tasks: Option<TasksCapability>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ToolsCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResourcesCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscribe: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct PromptsCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct LoggingCapability {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub level: Option<String>,
}

/// Log level based on RFC 5424 syslog severity levels
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum LogLevel {
    Emergency,
    Alert,
    Critical,
    Error,
    Warning,
    Notice,
    Info,
    Debug,
}

impl LogLevel {
    pub fn as_str(&self) -> &'static str {
        match self {
            LogLevel::Emergency => "emergency",
            LogLevel::Alert => "alert",
            LogLevel::Critical => "critical",
            LogLevel::Error => "error",
            LogLevel::Warning => "warning",
            LogLevel::Notice => "notice",
            LogLevel::Info => "info",
            LogLevel::Debug => "debug",
        }
    }
}

impl std::str::FromStr for LogLevel {
    type Err = String;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s.to_lowercase().as_str() {
            "emergency" => Ok(LogLevel::Emergency),
            "alert" => Ok(LogLevel::Alert),
            "critical" => Ok(LogLevel::Critical),
            "error" => Ok(LogLevel::Error),
            "warning" => Ok(LogLevel::Warning),
            "notice" => Ok(LogLevel::Notice),
            "info" => Ok(LogLevel::Info),
            "debug" => Ok(LogLevel::Debug),
            _ => Err(format!("Invalid log level: {s}")),
        }
    }
}

impl std::fmt::Display for LogLevel {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.as_str())
    }
}

/// Sampling capability configuration (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SamplingCapability {
    /// Whether the client supports tool use during sampling
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<SamplingToolsCapability>,
    /// Whether the client supports context inclusion
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<SamplingContextCapability>,
}

/// Sampling tools capability (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SamplingToolsCapability {}

/// Sampling context capability
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct SamplingContextCapability {}

/// Elicitation capability configuration (MCP 2025-11-25)
///
/// Supports two modes:
/// - `form`: In-band structured data collection with JSON schema validation
/// - `url`: Out-of-band interaction via URL navigation (for sensitive data, OAuth, etc.)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ElicitationCapability {
    /// Form mode elicitation support
    #[serde(skip_serializing_if = "Option::is_none")]
    pub form: Option<FormElicitationCapability>,
    /// URL mode elicitation support (MCP 2025-11-25)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<UrlElicitationCapability>,
}

/// Form mode elicitation capability
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct FormElicitationCapability {}

/// URL mode elicitation capability (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UrlElicitationCapability {}

impl ServerCapabilities {
    pub fn builder() -> ServerCapabilitiesBuilder {
        ServerCapabilitiesBuilder::default()
    }
}

#[derive(Default)]
pub struct ServerCapabilitiesBuilder {
    capabilities: ServerCapabilities,
}

impl ServerCapabilitiesBuilder {
    #[must_use]
    pub fn enable_tools(mut self) -> Self {
        self.capabilities.tools = Some(ToolsCapability {
            list_changed: Some(true),
        });
        self
    }

    #[must_use]
    pub fn enable_resources(mut self) -> Self {
        self.capabilities.resources = Some(ResourcesCapability {
            subscribe: Some(true),
            list_changed: Some(true),
        });
        self
    }

    #[must_use]
    pub fn enable_prompts(mut self) -> Self {
        self.capabilities.prompts = Some(PromptsCapability {
            list_changed: Some(true),
        });
        self
    }

    #[must_use]
    pub fn enable_logging(mut self) -> Self {
        self.capabilities.logging = Some(LoggingCapability {
            level: Some("info".to_string()),
        });
        self
    }

    #[must_use]
    pub fn enable_sampling(mut self) -> Self {
        self.capabilities.sampling = Some(SamplingCapability::default());
        self
    }

    /// Enable sampling with tool support (MCP 2025-11-25)
    #[must_use]
    pub fn enable_sampling_with_tools(mut self) -> Self {
        self.capabilities.sampling = Some(SamplingCapability {
            tools: Some(SamplingToolsCapability {}),
            context: Some(SamplingContextCapability {}),
        });
        self
    }

    /// Enable form-only elicitation (backwards compatible default)
    #[must_use]
    pub fn enable_elicitation(mut self) -> Self {
        self.capabilities.elicitation = Some(ElicitationCapability {
            form: Some(FormElicitationCapability {}),
            url: None,
        });
        self
    }

    /// Enable elicitation with specific modes (MCP 2025-11-25)
    #[must_use]
    pub fn enable_elicitation_modes(mut self, form: bool, url: bool) -> Self {
        self.capabilities.elicitation = Some(ElicitationCapability {
            form: if form {
                Some(FormElicitationCapability {})
            } else {
                None
            },
            url: if url {
                Some(UrlElicitationCapability {})
            } else {
                None
            },
        });
        self
    }

    /// Enable tasks capability (MCP 2025-11-25 experimental)
    #[must_use]
    pub fn enable_tasks(mut self) -> Self {
        self.capabilities.tasks = Some(TasksCapability {
            cancel: Some(TaskCancelCapability {}),
            list: Some(TaskListCapability {}),
            requests: Some(TaskRequestsCapability {
                sampling: Some(TaskSamplingCapability {
                    create_message: Some(TaskMethodCapability {}),
                }),
                elicitation: Some(TaskElicitationCapability {
                    create: Some(TaskMethodCapability {}),
                }),
                tools: Some(TaskToolsCapability {
                    call: Some(TaskMethodCapability {}),
                }),
            }),
        });
        self
    }

    /// Enable basic tasks capability without request augmentation
    #[must_use]
    pub fn enable_tasks_basic(mut self) -> Self {
        self.capabilities.tasks = Some(TasksCapability {
            cancel: Some(TaskCancelCapability {}),
            list: Some(TaskListCapability {}),
            requests: None,
        });
        self
    }

    pub fn build(self) -> ServerCapabilities {
        self.capabilities
    }
}

/// Server information response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ServerInfo {
    pub protocol_version: ProtocolVersion,
    pub capabilities: ServerCapabilities,
    pub server_info: Implementation,
    pub instructions: Option<String>,
}

/// Tool definition
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Tool {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    pub description: String,
    pub input_schema: serde_json::Value,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub output_schema: Option<serde_json::Value>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<ToolAnnotations>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icons: Option<Vec<Icon>>,
    /// Execution configuration for task support (MCP 2025-11-25)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub execution: Option<ToolExecution>,
    /// Tool metadata for extensions like MCP Apps (SEP-1865)
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub _meta: Option<ToolMeta>,
}

/// Tool annotations for behavioral hints
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ToolAnnotations {
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_only_hint: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destructive_hint: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub idempotent_hint: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub open_world_hint: Option<bool>,
}

/// Tool metadata for protocol extensions
///
/// This supports the MCP Apps Extension (SEP-1865) and future extensions
/// that need to attach metadata to tools.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ToolMeta {
    /// Reference to a UI resource (MCP Apps Extension)
    ///
    /// Links this tool to an interactive HTML interface that can be displayed
    /// when the tool is called. The URI should use the `ui://` scheme and
    /// reference a resource returned by `list_resources`.
    ///
    /// Example: `"ui://charts/bar-chart"`
    #[serde(rename = "ui/resourceUri", skip_serializing_if = "Option::is_none")]
    pub ui_resource_uri: Option<String>,
}

impl ToolMeta {
    /// Create tool metadata with a UI resource reference
    pub fn with_ui_resource(uri: impl Into<String>) -> Self {
        Self {
            ui_resource_uri: Some(uri.into()),
        }
    }
}

/// Icon definition for tools and other resources
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Icon {
    pub uri: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
}

/// List tools result
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListToolsResult {
    pub tools: Vec<Tool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// Pagination parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PaginatedRequestParam {
    pub cursor: Option<String>,
}

/// Tool call parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CallToolRequestParam {
    pub name: String,
    pub arguments: Option<serde_json::Value>,
}

/// Content types for tool responses and sampling messages
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum Content {
    #[serde(rename = "text")]
    Text {
        text: String,
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        _meta: Option<Meta>,
    },
    #[serde(rename = "image")]
    Image {
        data: String,
        #[serde(rename = "mimeType")]
        mime_type: String,
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        _meta: Option<Meta>,
    },
    /// Audio content with base64-encoded data
    #[serde(rename = "audio")]
    Audio {
        /// Base64-encoded audio data
        data: String,
        /// MIME type (e.g., "audio/wav", "audio/mp3")
        #[serde(rename = "mimeType")]
        mime_type: String,
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        _meta: Option<Meta>,
    },
    #[serde(rename = "resource")]
    Resource {
        /// The embedded resource contents
        resource: EmbeddedResourceContents,
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        _meta: Option<Meta>,
    },
    /// Tool use request from LLM during sampling (MCP 2025-11-25)
    #[serde(rename = "tool_use")]
    ToolUse {
        /// Unique identifier for this tool use
        id: String,
        /// Name of the tool to invoke
        name: String,
        /// Tool input arguments
        input: serde_json::Value,
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        _meta: Option<Meta>,
    },
    /// Tool result to be passed back to LLM during sampling (MCP 2025-11-25)
    #[serde(rename = "tool_result")]
    ToolResult {
        /// ID of the tool use this is a result for
        #[serde(rename = "toolUseId")]
        tool_use_id: String,
        /// Content of the tool result
        content: Vec<ToolResultContent>,
        /// Whether the tool execution resulted in an error
        #[serde(rename = "isError", skip_serializing_if = "Option::is_none")]
        is_error: Option<bool>,
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        _meta: Option<Meta>,
    },
}

/// Content types that can appear in tool results (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum ToolResultContent {
    #[serde(rename = "text")]
    Text { text: String },
    #[serde(rename = "image")]
    Image {
        data: String,
        #[serde(rename = "mimeType")]
        mime_type: String,
    },
}

impl Content {
    pub fn text(text: impl Into<String>) -> Self {
        Self::Text {
            text: text.into(),
            _meta: None,
        }
    }

    pub fn image(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        Self::Image {
            data: data.into(),
            mime_type: mime_type.into(),
            _meta: None,
        }
    }

    /// Create audio content with base64-encoded data
    pub fn audio(data: impl Into<String>, mime_type: impl Into<String>) -> Self {
        Self::Audio {
            data: data.into(),
            mime_type: mime_type.into(),
            _meta: None,
        }
    }

    /// Create embedded resource content
    pub fn resource(
        uri: impl Into<String>,
        mime_type: Option<String>,
        text: Option<String>,
    ) -> Self {
        Self::Resource {
            resource: EmbeddedResourceContents {
                uri: uri.into(),
                mime_type,
                text,
                blob: None,
                _meta: None,
            },
            _meta: None,
        }
    }

    /// Create embedded resource content from ResourceContents
    pub fn from_resource_contents(contents: ResourceContents) -> Self {
        Self::Resource {
            resource: contents,
            _meta: None,
        }
    }

    /// Create a tool use content (MCP 2025-11-25)
    ///
    /// Used during sampling when the LLM wants to invoke a tool.
    pub fn tool_use(
        id: impl Into<String>,
        name: impl Into<String>,
        input: serde_json::Value,
    ) -> Self {
        Self::ToolUse {
            id: id.into(),
            name: name.into(),
            input,
            _meta: None,
        }
    }

    /// Create a tool result content (MCP 2025-11-25)
    ///
    /// Used during sampling to return tool execution results to the LLM.
    pub fn tool_result(
        tool_use_id: impl Into<String>,
        content: Vec<ToolResultContent>,
        is_error: Option<bool>,
    ) -> Self {
        Self::ToolResult {
            tool_use_id: tool_use_id.into(),
            content,
            is_error,
            _meta: None,
        }
    }

    /// Create a successful tool result with text content (MCP 2025-11-25)
    pub fn tool_result_text(tool_use_id: impl Into<String>, text: impl Into<String>) -> Self {
        Self::tool_result(
            tool_use_id,
            vec![ToolResultContent::Text { text: text.into() }],
            Some(false),
        )
    }

    /// Create an error tool result (MCP 2025-11-25)
    pub fn tool_result_error(
        tool_use_id: impl Into<String>,
        error_message: impl Into<String>,
    ) -> Self {
        Self::tool_result(
            tool_use_id,
            vec![ToolResultContent::Text {
                text: error_message.into(),
            }],
            Some(true),
        )
    }

    /// Create a UI HTML resource content (for MCP Apps Extension / MCP-UI)
    ///
    /// This helper simplifies creating HTML UI resources by automatically formatting
    /// the resource JSON according to the MCP-UI specification.
    ///
    /// # Example
    ///
    /// ```rust
    /// use pulseengine_mcp_protocol::Content;
    ///
    /// let html = r#"<html><body><h1>Hello!</h1></body></html>"#;
    /// let content = Content::ui_html("ui://greetings/interactive", html);
    /// ```
    ///
    /// This is equivalent to but much more concise than:
    /// ```rust,ignore
    /// let resource_json = serde_json::json!({
    ///     "uri": "ui://greetings/interactive",
    ///     "mimeType": "text/html",
    ///     "text": html
    /// });
    /// Content::Resource {
    ///     resource: resource_json.to_string(),
    ///     text: None,
    ///     _meta: None,
    /// }
    /// ```
    /// Create a UI HTML resource content (for MCP Apps Extension / MCP-UI)
    pub fn ui_html(uri: impl Into<String>, html: impl Into<String>) -> Self {
        Self::resource(uri, Some("text/html".to_string()), Some(html.into()))
    }

    /// Create a UI resource content with custom MIME type (for MCP Apps Extension / MCP-UI)
    ///
    /// This helper allows you to create UI resources with any MIME type and content.
    ///
    /// # Example
    ///
    /// ```rust
    /// use pulseengine_mcp_protocol::Content;
    ///
    /// let json_data = r#"{"message": "Hello, World!"}"#;
    /// let content = Content::ui_resource(
    ///     "ui://data/greeting",
    ///     "application/json",
    ///     json_data
    /// );
    /// ```
    pub fn ui_resource(
        uri: impl Into<String>,
        mime_type: impl Into<String>,
        content: impl Into<String>,
    ) -> Self {
        Self::resource(uri, Some(mime_type.into()), Some(content.into()))
    }

    /// Get text content if this is a text content type
    pub fn as_text(&self) -> Option<&Self> {
        match self {
            Self::Text { .. } => Some(self),
            _ => None,
        }
    }
}

/// Text content struct for compatibility
pub struct TextContent {
    pub text: String,
}

impl Content {
    /// Get text content as `TextContent` struct for compatibility
    pub fn as_text_content(&self) -> Option<TextContent> {
        match self {
            Self::Text { text, .. } => Some(TextContent { text: text.clone() }),
            _ => None,
        }
    }
}

/// Tool call result
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CallToolResult {
    pub content: Vec<Content>,
    pub is_error: Option<bool>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub structured_content: Option<serde_json::Value>,
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub _meta: Option<Meta>,
}

impl CallToolResult {
    pub fn success(content: Vec<Content>) -> Self {
        Self {
            content,
            is_error: Some(false),
            structured_content: None,
            _meta: None,
        }
    }

    pub fn error(content: Vec<Content>) -> Self {
        Self {
            content,
            is_error: Some(true),
            structured_content: None,
            _meta: None,
        }
    }

    pub fn text(text: impl Into<String>) -> Self {
        Self::success(vec![Content::text(text)])
    }

    pub fn error_text(text: impl Into<String>) -> Self {
        Self::error(vec![Content::text(text)])
    }

    /// Create an input validation error result (MCP 2025-11-25)
    ///
    /// Per the MCP 2025-11-25 spec, input validation errors should be returned
    /// as tool execution errors (with `is_error: true`) rather than protocol
    /// errors. This enables the LLM to self-correct based on the error feedback.
    ///
    /// # Example
    /// ```rust
    /// use pulseengine_mcp_protocol::CallToolResult;
    ///
    /// // When validating tool arguments fails:
    /// let result = CallToolResult::input_validation_error(
    ///     "location",
    ///     "Expected a valid city name, got empty string"
    /// );
    /// ```
    pub fn input_validation_error(field: impl Into<String>, message: impl Into<String>) -> Self {
        let error_msg = format!(
            "Input validation error for '{}': {}",
            field.into(),
            message.into()
        );
        Self::error(vec![Content::text(error_msg)])
    }

    /// Create a success result with structured content
    pub fn structured(content: Vec<Content>, structured_content: serde_json::Value) -> Self {
        Self {
            content,
            is_error: Some(false),
            structured_content: Some(structured_content),
            _meta: None,
        }
    }

    /// Create an error result with structured content
    pub fn structured_error(content: Vec<Content>, structured_content: serde_json::Value) -> Self {
        Self {
            content,
            is_error: Some(true),
            structured_content: Some(structured_content),
            _meta: None,
        }
    }

    /// Create a result with both text and structured content
    pub fn text_with_structured(
        text: impl Into<String>,
        structured_content: serde_json::Value,
    ) -> Self {
        Self::structured(vec![Content::text(text)], structured_content)
    }

    /// Validate structured content against a schema
    ///
    /// # Errors
    ///
    /// Returns an error if the structured content doesn't match the provided schema
    pub fn validate_structured_content(
        &self,
        output_schema: &serde_json::Value,
    ) -> crate::Result<()> {
        use crate::validation::Validator;

        if let Some(structured_content) = &self.structured_content {
            Validator::validate_structured_content(structured_content, output_schema)?;
        }
        Ok(())
    }
}

/// Resource definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Resource {
    pub uri: String,
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    pub description: Option<String>,
    pub mime_type: Option<String>,
    pub annotations: Option<Annotations>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icons: Option<Vec<Icon>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub raw: Option<RawResource>,
    /// UI-specific metadata (MCP Apps Extension)
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub _meta: Option<ResourceMeta>,
}

/// Resource metadata for extensions
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ResourceMeta {
    /// UI configuration (MCP Apps Extension)
    #[serde(rename = "ui", skip_serializing_if = "Option::is_none")]
    pub ui: Option<UiResourceMeta>,
}

/// UI resource metadata (MCP Apps Extension - SEP-1865)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct UiResourceMeta {
    /// Content Security Policy configuration
    #[serde(skip_serializing_if = "Option::is_none")]
    pub csp: Option<CspConfig>,

    /// Optional dedicated sandbox origin/domain
    #[serde(skip_serializing_if = "Option::is_none")]
    pub domain: Option<String>,

    /// Whether the UI prefers a visual boundary/border
    #[serde(rename = "prefersBorder", skip_serializing_if = "Option::is_none")]
    pub prefers_border: Option<bool>,
}

/// Content Security Policy configuration for UI resources
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct CspConfig {
    /// Allowed origins for network requests (fetch, XHR, WebSocket)
    #[serde(rename = "connectDomains", skip_serializing_if = "Option::is_none")]
    pub connect_domains: Option<Vec<String>>,

    /// Allowed origins for static resources (images, scripts, fonts)
    #[serde(rename = "resourceDomains", skip_serializing_if = "Option::is_none")]
    pub resource_domains: Option<Vec<String>>,
}

/// Resource annotations
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct Annotations {
    pub audience: Option<Vec<String>>,
    pub priority: Option<f32>,
}

impl Resource {
    /// Create a UI resource for interactive interfaces (MCP Apps Extension)
    ///
    /// This creates a resource with the `text/html+mcp` MIME type and `ui://` URI scheme,
    /// suitable for embedding interactive HTML interfaces.
    ///
    /// # Example
    ///
    /// ```
    /// use pulseengine_mcp_protocol::Resource;
    ///
    /// let resource = Resource::ui_resource(
    ///     "ui://charts/bar-chart",
    ///     "Bar Chart Viewer",
    ///     "Interactive bar chart visualization",
    /// );
    /// ```
    pub fn ui_resource(
        uri: impl Into<String>,
        name: impl Into<String>,
        description: impl Into<String>,
    ) -> Self {
        Self {
            uri: uri.into(),
            name: name.into(),
            title: None,
            description: Some(description.into()),
            mime_type: Some(mime_types::HTML_MCP.to_string()),
            annotations: None,
            icons: None,
            raw: None,
            _meta: None,
        }
    }

    /// Create a UI resource with CSP configuration
    pub fn ui_resource_with_csp(
        uri: impl Into<String>,
        name: impl Into<String>,
        description: impl Into<String>,
        csp: CspConfig,
    ) -> Self {
        Self {
            uri: uri.into(),
            name: name.into(),
            title: None,
            description: Some(description.into()),
            mime_type: Some(mime_types::HTML_MCP.to_string()),
            annotations: None,
            icons: None,
            raw: None,
            _meta: Some(ResourceMeta {
                ui: Some(UiResourceMeta {
                    csp: Some(csp),
                    domain: None,
                    prefers_border: None,
                }),
            }),
        }
    }

    /// Check if this resource is a UI resource (has `ui://` scheme)
    pub fn is_ui_resource(&self) -> bool {
        self.uri.starts_with(uri_schemes::UI)
    }

    /// Get the URI scheme of this resource (e.g., "ui://", "file://", etc.)
    pub fn uri_scheme(&self) -> Option<&str> {
        self.uri.split_once("://").map(|(scheme, _)| scheme)
    }
}

impl ResourceContents {
    /// Create resource contents for HTML UI (MCP Apps Extension)
    pub fn html_ui(uri: impl Into<String>, html: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            mime_type: Some(mime_types::HTML_MCP.to_string()),
            text: Some(html.into()),
            blob: None,
            _meta: None,
        }
    }

    /// Create resource contents with JSON data
    pub fn json(uri: impl Into<String>, json: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            mime_type: Some(mime_types::JSON.to_string()),
            text: Some(json.into()),
            blob: None,
            _meta: None,
        }
    }

    /// Create resource contents with plain text
    pub fn text(uri: impl Into<String>, text: impl Into<String>) -> Self {
        Self {
            uri: uri.into(),
            mime_type: Some(mime_types::TEXT.to_string()),
            text: Some(text.into()),
            blob: None,
            _meta: None,
        }
    }
}

/// List resources result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListResourcesResult {
    pub resources: Vec<Resource>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// Read resource parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadResourceRequestParam {
    pub uri: String,
}

/// Resource contents wrapper
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceContents {
    pub uri: String,
    #[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub text: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub blob: Option<String>,
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub _meta: Option<Meta>,
}

/// Read resource result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ReadResourceResult {
    pub contents: Vec<ResourceContents>,
}

/// Embedded resource contents for tool responses (alias for ResourceContents)
pub type EmbeddedResourceContents = ResourceContents;

/// Raw resource (for internal use)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RawResource {
    pub uri: String,
    pub data: Vec<u8>,
    pub mime_type: Option<String>,
    pub name: Option<String>,
    pub description: Option<String>,
    pub size: Option<usize>,
}

impl PromptMessage {
    /// Create a new text message
    pub fn new_text(role: PromptMessageRole, text: impl Into<String>) -> Self {
        Self {
            role,
            content: PromptMessageContent::Text { text: text.into() },
        }
    }

    /// Create a new image message
    pub fn new_image(
        role: PromptMessageRole,
        data: impl Into<String>,
        mime_type: impl Into<String>,
    ) -> Self {
        Self {
            role,
            content: PromptMessageContent::Image {
                data: data.into(),
                mime_type: mime_type.into(),
            },
        }
    }

    /// Create a new resource message with embedded resource content
    pub fn new_resource(
        role: PromptMessageRole,
        uri: impl Into<String>,
        mime_type: Option<String>,
        text: Option<String>,
    ) -> Self {
        Self {
            role,
            content: PromptMessageContent::Resource {
                resource: EmbeddedResourceContents {
                    uri: uri.into(),
                    mime_type,
                    text,
                    blob: None,
                    _meta: None,
                },
            },
        }
    }
}

impl CompleteResult {
    /// Create a simple completion result with a single value
    pub fn simple(value: impl Into<String>) -> Self {
        Self {
            completion: CompletionValues {
                values: vec![value.into()],
                total: None,
                has_more: Some(false),
            },
        }
    }

    /// Create a completion result with multiple values
    pub fn with_values(values: Vec<String>) -> Self {
        let total = values.len() as u64;
        Self {
            completion: CompletionValues {
                values,
                total: Some(total),
                has_more: Some(false),
            },
        }
    }
}

/// Prompt definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Prompt {
    pub name: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<Vec<PromptArgument>>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub icons: Option<Vec<Icon>>,
}

/// Prompt argument definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromptArgument {
    pub name: String,
    pub description: Option<String>,
    pub required: Option<bool>,
}

/// List prompts result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListPromptsResult {
    pub prompts: Vec<Prompt>,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// Get prompt parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetPromptRequestParam {
    pub name: String,
    pub arguments: Option<HashMap<String, String>>,
}

/// Prompt message role
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum PromptMessageRole {
    User,
    Assistant,
    System,
}

/// Prompt message content
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum PromptMessageContent {
    #[serde(rename = "text")]
    Text { text: String },
    #[serde(rename = "image")]
    Image {
        data: String,
        #[serde(rename = "mimeType")]
        mime_type: String,
    },
    /// Embedded resource content in prompts
    #[serde(rename = "resource")]
    Resource {
        /// The embedded resource contents
        resource: EmbeddedResourceContents,
    },
}

/// Prompt message
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PromptMessage {
    pub role: PromptMessageRole,
    pub content: PromptMessageContent,
}

/// Get prompt result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetPromptResult {
    pub description: Option<String>,
    pub messages: Vec<PromptMessage>,
}

/// Initialize request parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InitializeRequestParam {
    #[serde(rename = "protocolVersion")]
    pub protocol_version: String,
    pub capabilities: serde_json::Value,
    #[serde(rename = "clientInfo")]
    pub client_info: Implementation,
}

/// Initialize result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct InitializeResult {
    #[serde(rename = "protocolVersion")]
    pub protocol_version: String,
    pub capabilities: ServerCapabilities,
    #[serde(rename = "serverInfo")]
    pub server_info: Implementation,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub instructions: Option<String>,
}

/// Completion context for context-aware completion (MCP 2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CompletionContext {
    /// Names of arguments that have already been provided
    pub argument_names: Vec<String>,
    /// Values of arguments that have already been provided
    pub values: HashMap<String, serde_json::Value>,
}

impl CompletionContext {
    /// Create a new completion context
    pub fn new(argument_names: Vec<String>, values: HashMap<String, serde_json::Value>) -> Self {
        Self {
            argument_names,
            values,
        }
    }

    /// Get an iterator over argument names
    pub fn argument_names_iter(&self) -> impl Iterator<Item = &String> {
        self.argument_names.iter()
    }
}

/// Reference type for completion requests
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum CompletionRef {
    /// Reference to a prompt for argument completion
    #[serde(rename = "ref/prompt")]
    Prompt { name: String },
    /// Reference to a resource for URI completion
    #[serde(rename = "ref/resource")]
    Resource { uri: String },
}

/// Completion argument being completed
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionArgument {
    pub name: String,
    pub value: String,
}

/// Completion request parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompleteRequestParam {
    #[serde(rename = "ref")]
    pub ref_: CompletionRef,
    pub argument: CompletionArgument,
    /// Optional context for context-aware completion (MCP 2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub context: Option<CompletionContext>,
}

/// Completion values object
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompletionValues {
    /// Array of completion suggestions
    pub values: Vec<String>,
    /// Optional total number of available matches
    #[serde(skip_serializing_if = "Option::is_none")]
    pub total: Option<u64>,
    /// Boolean indicating if additional results exist
    #[serde(rename = "hasMore", skip_serializing_if = "Option::is_none")]
    pub has_more: Option<bool>,
}

/// Complete result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CompleteResult {
    /// The completion object containing values and metadata
    pub completion: CompletionValues,
}

// Keep the old type for backwards compatibility
#[deprecated(note = "Use CompletionValues instead")]
pub type CompletionInfo = CompletionValues;

/// Set logging level parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SetLevelRequestParam {
    pub level: LogLevel,
}

/// Resource template definition
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceTemplate {
    #[serde(rename = "uriTemplate")]
    pub uri_template: String,
    pub name: String,
    pub description: Option<String>,
    #[serde(rename = "mimeType")]
    pub mime_type: Option<String>,
}

/// List resource templates result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ListResourceTemplatesResult {
    #[serde(rename = "resourceTemplates")]
    pub resource_templates: Vec<ResourceTemplate>,
    #[serde(rename = "nextCursor", skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// Subscribe request parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SubscribeRequestParam {
    pub uri: String,
}

/// Unsubscribe request parameters
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UnsubscribeRequestParam {
    pub uri: String,
}

/// Resource updated notification parameters
/// Sent when a subscribed resource changes
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ResourceUpdatedNotification {
    /// URI of the resource that was updated
    pub uri: String,
}

/// Elicitation completion notification (MCP 2025-11-25)
///
/// Sent by the server when a URL mode elicitation interaction completes.
/// Clients can use this to automatically retry requests or update UI.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElicitationCompleteNotification {
    /// The elicitation ID that completed
    #[serde(rename = "elicitationId")]
    pub elicitation_id: String,
}

/// URL elicitation required error data (MCP 2025-11-25)
///
/// Returned as error data when a request requires URL mode elicitation
/// before it can be processed.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UrlElicitationRequiredData {
    /// List of elicitations required before the request can proceed
    pub elicitations: Vec<UrlElicitationInfo>,
}

/// Information about a required URL elicitation (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct UrlElicitationInfo {
    /// Always "url" for URL mode elicitation
    pub mode: ElicitationMode,
    /// Unique identifier for this elicitation
    #[serde(rename = "elicitationId")]
    pub elicitation_id: String,
    /// URL to navigate to
    pub url: String,
    /// Human-readable message explaining what information is needed
    pub message: String,
}

impl UrlElicitationInfo {
    /// Create a new URL elicitation info
    pub fn new(
        elicitation_id: impl Into<String>,
        url: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            mode: ElicitationMode::Url,
            elicitation_id: elicitation_id.into(),
            url: url.into(),
            message: message.into(),
        }
    }
}

/// Elicitation mode (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ElicitationMode {
    /// In-band structured data collection with JSON schema validation
    Form,
    /// Out-of-band interaction via URL navigation
    Url,
}

impl Default for ElicitationMode {
    fn default() -> Self {
        Self::Form
    }
}

/// Elicitation request parameters (MCP 2025-11-25 enhanced)
///
/// Supports two modes:
/// - Form mode: Traditional in-band data collection with schema validation
/// - URL mode: Out-of-band interaction for sensitive data, OAuth flows, etc.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElicitationRequestParam {
    /// Elicitation mode (form or url). Defaults to form for backwards compatibility.
    #[serde(default, skip_serializing_if = "is_form_mode")]
    pub mode: ElicitationMode,
    /// Unique identifier for this elicitation request (MCP 2025-11-25)
    #[serde(rename = "elicitationId", skip_serializing_if = "Option::is_none")]
    pub elicitation_id: Option<String>,
    /// Human-readable message explaining what information is needed
    pub message: String,
    /// JSON Schema for requested data (form mode only)
    #[serde(rename = "requestedSchema", skip_serializing_if = "Option::is_none")]
    pub requested_schema: Option<serde_json::Value>,
    /// URL to navigate to (url mode only, MCP 2025-11-25)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub url: Option<String>,
}

fn is_form_mode(mode: &ElicitationMode) -> bool {
    *mode == ElicitationMode::Form
}

impl ElicitationRequestParam {
    /// Create a form mode elicitation request
    pub fn form(message: impl Into<String>, schema: serde_json::Value) -> Self {
        Self {
            mode: ElicitationMode::Form,
            elicitation_id: None,
            message: message.into(),
            requested_schema: Some(schema),
            url: None,
        }
    }

    /// Create a URL mode elicitation request (MCP 2025-11-25)
    pub fn url(
        elicitation_id: impl Into<String>,
        url: impl Into<String>,
        message: impl Into<String>,
    ) -> Self {
        Self {
            mode: ElicitationMode::Url,
            elicitation_id: Some(elicitation_id.into()),
            message: message.into(),
            requested_schema: None,
            url: Some(url.into()),
        }
    }
}

/// Elicitation response actions
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ElicitationAction {
    Accept,
    Decline,
    Cancel,
}

/// Elicitation response
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElicitationResponse {
    pub action: ElicitationAction,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

/// Elicitation result
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ElicitationResult {
    pub response: ElicitationResponse,
}

impl ElicitationResult {
    /// Create an accept result with data
    pub fn accept(data: serde_json::Value) -> Self {
        Self {
            response: ElicitationResponse {
                action: ElicitationAction::Accept,
                data: Some(data),
            },
        }
    }

    /// Create a decline result
    pub fn decline() -> Self {
        Self {
            response: ElicitationResponse {
                action: ElicitationAction::Decline,
                data: None,
            },
        }
    }

    /// Create a cancel result
    pub fn cancel() -> Self {
        Self {
            response: ElicitationResponse {
                action: ElicitationAction::Cancel,
                data: None,
            },
        }
    }
}

// ==================== MCP 2025-11-25 Sampling Types ====================

/// Sampling message role
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum SamplingRole {
    User,
    Assistant,
}

/// Sampling message for create message requests (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SamplingMessage {
    /// Role of the message sender
    pub role: SamplingRole,
    /// Content of the message
    pub content: SamplingContent,
}

impl SamplingMessage {
    /// Create a user message with text
    pub fn user_text(text: impl Into<String>) -> Self {
        Self {
            role: SamplingRole::User,
            content: SamplingContent::Text { text: text.into() },
        }
    }

    /// Create an assistant message with text
    pub fn assistant_text(text: impl Into<String>) -> Self {
        Self {
            role: SamplingRole::Assistant,
            content: SamplingContent::Text { text: text.into() },
        }
    }
}

/// Content types for sampling messages (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type")]
pub enum SamplingContent {
    #[serde(rename = "text")]
    Text { text: String },
    #[serde(rename = "image")]
    Image { data: String, mime_type: String },
}

/// Model preferences for sampling requests (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ModelPreferences {
    /// Hints for model selection
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hints: Option<Vec<ModelHint>>,
    /// Priority for cost optimization (0.0-1.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cost_priority: Option<f32>,
    /// Priority for speed optimization (0.0-1.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub speed_priority: Option<f32>,
    /// Priority for intelligence/capability (0.0-1.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub intelligence_priority: Option<f32>,
}

/// Model hint for model selection (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ModelHint {
    /// Name pattern to match against model names
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// Context inclusion mode for sampling (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase")]
pub enum ContextInclusion {
    /// Include context from all connected servers
    AllServers,
    /// Include context from only this server
    ThisServer,
    /// Do not include any server context
    None,
}

/// Tool choice configuration for sampling (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ToolChoice {
    /// How the model should use tools
    pub mode: ToolChoiceMode,
}

impl ToolChoice {
    /// Create auto tool choice (model decides when to use tools)
    pub fn auto() -> Self {
        Self {
            mode: ToolChoiceMode::Auto,
        }
    }

    /// Create required tool choice (model must use a tool)
    pub fn required() -> Self {
        Self {
            mode: ToolChoiceMode::Required,
        }
    }

    /// Create none tool choice (model should not use tools)
    pub fn none() -> Self {
        Self {
            mode: ToolChoiceMode::None,
        }
    }
}

impl Default for ToolChoice {
    fn default() -> Self {
        Self::auto()
    }
}

/// Tool choice mode (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum ToolChoiceMode {
    /// Model decides when to use tools
    Auto,
    /// Model must use a tool
    Required,
    /// Model should not use tools
    None,
}

/// Create message request parameters (MCP 2025-11-25)
///
/// Parameters for requesting LLM sampling from the client.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateMessageRequestParam {
    /// Maximum tokens to generate (required)
    pub max_tokens: u32,
    /// Conversation messages (required)
    pub messages: Vec<SamplingMessage>,
    /// System prompt for the model
    #[serde(skip_serializing_if = "Option::is_none")]
    pub system_prompt: Option<String>,
    /// Temperature for generation (0.0-1.0)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub temperature: Option<f32>,
    /// Stop sequences that will end generation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_sequences: Option<Vec<String>>,
    /// Model selection preferences
    #[serde(skip_serializing_if = "Option::is_none")]
    pub model_preferences: Option<ModelPreferences>,
    /// What server context to include
    #[serde(skip_serializing_if = "Option::is_none")]
    pub include_context: Option<ContextInclusion>,
    /// Tools available for the model to use (MCP 2025-11-25)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<Vec<Tool>>,
    /// How the model should use tools (MCP 2025-11-25)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tool_choice: Option<ToolChoice>,
    /// Additional request metadata
    #[serde(skip_serializing_if = "Option::is_none")]
    pub metadata: Option<serde_json::Value>,
}

impl CreateMessageRequestParam {
    /// Create a simple text completion request
    pub fn simple(max_tokens: u32, user_message: impl Into<String>) -> Self {
        Self {
            max_tokens,
            messages: vec![SamplingMessage::user_text(user_message)],
            system_prompt: None,
            temperature: None,
            stop_sequences: None,
            model_preferences: None,
            include_context: None,
            tools: None,
            tool_choice: None,
            metadata: None,
        }
    }

    /// Create a request with tools available (MCP 2025-11-25)
    pub fn with_tools(max_tokens: u32, messages: Vec<SamplingMessage>, tools: Vec<Tool>) -> Self {
        Self {
            max_tokens,
            messages,
            system_prompt: None,
            temperature: None,
            stop_sequences: None,
            model_preferences: None,
            include_context: None,
            tools: Some(tools),
            tool_choice: Some(ToolChoice::auto()),
            metadata: None,
        }
    }
}

/// Create message result (MCP 2025-11-25)
///
/// Response from a sampling request.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateMessageResult {
    /// Model identifier that generated the response
    pub model: String,
    /// Reason generation stopped
    #[serde(skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<String>,
    /// Generated message content
    pub message: SamplingMessage,
}

impl CreateMessageResult {
    /// Check if the model wants to use a tool
    pub fn is_tool_use(&self) -> bool {
        self.stop_reason.as_deref() == Some("tool_use")
    }

    /// Check if generation ended normally
    pub fn is_end_turn(&self) -> bool {
        self.stop_reason.as_deref() == Some("end_turn")
    }

    /// Check if generation hit the token limit
    pub fn is_max_tokens(&self) -> bool {
        self.stop_reason.as_deref() == Some("max_tokens")
    }
}

/// Standard stop reasons for sampling (MCP 2025-11-25)
pub mod stop_reasons {
    /// Natural end of turn
    pub const END_TURN: &str = "end_turn";
    /// Stop sequence encountered
    pub const STOP_SEQUENCE: &str = "stop_sequence";
    /// Max tokens limit reached
    pub const MAX_TOKENS: &str = "max_tokens";
    /// Model wants to use a tool
    pub const TOOL_USE: &str = "tool_use";
}

// ==================== MCP 2025-11-25 Tasks (Experimental) ====================

/// Task status values (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "kebab-case")]
pub enum TaskStatus {
    /// Task is actively processing
    Working,
    /// Task is waiting for user/client input
    InputRequired,
    /// Task completed successfully
    Completed,
    /// Task failed with an error
    Failed,
    /// Task was explicitly cancelled
    Cancelled,
}

impl std::fmt::Display for TaskStatus {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            TaskStatus::Working => "working",
            TaskStatus::InputRequired => "input-required",
            TaskStatus::Completed => "completed",
            TaskStatus::Failed => "failed",
            TaskStatus::Cancelled => "cancelled",
        };
        write!(f, "{s}")
    }
}

/// Represents an asynchronous task (MCP 2025-11-25 experimental)
///
/// Tasks enable long-running operations that can be polled for status,
/// cancelled, and have their results retrieved asynchronously.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Task {
    /// Unique identifier for the task
    pub task_id: String,
    /// Current execution status
    pub status: TaskStatus,
    /// Optional human-readable status description
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_message: Option<String>,
    /// ISO 8601 timestamp of task creation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub created_at: Option<String>,
    /// ISO 8601 timestamp of last status change
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_updated_at: Option<String>,
    /// Time-to-live in seconds before automatic cleanup
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<u64>,
    /// Suggested polling interval in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub poll_interval: Option<u64>,
}

impl Task {
    /// Create a new working task
    pub fn new(task_id: impl Into<String>) -> Self {
        Self {
            task_id: task_id.into(),
            status: TaskStatus::Working,
            status_message: None,
            created_at: None,
            last_updated_at: None,
            ttl: None,
            poll_interval: None,
        }
    }

    /// Create a new task with timestamps
    pub fn with_timestamps(task_id: impl Into<String>, created_at: impl Into<String>) -> Self {
        let ts = created_at.into();
        Self {
            task_id: task_id.into(),
            status: TaskStatus::Working,
            status_message: None,
            created_at: Some(ts.clone()),
            last_updated_at: Some(ts),
            ttl: None,
            poll_interval: None,
        }
    }

    /// Check if the task is in a terminal state
    pub fn is_terminal(&self) -> bool {
        matches!(
            self.status,
            TaskStatus::Completed | TaskStatus::Failed | TaskStatus::Cancelled
        )
    }

    /// Check if the task is still running
    pub fn is_running(&self) -> bool {
        matches!(self.status, TaskStatus::Working | TaskStatus::InputRequired)
    }
}

/// Tasks capability configuration (MCP 2025-11-25 experimental)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TasksCapability {
    /// Whether task cancellation is supported
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cancel: Option<TaskCancelCapability>,
    /// Whether task listing is supported
    #[serde(skip_serializing_if = "Option::is_none")]
    pub list: Option<TaskListCapability>,
    /// Which request types support task augmentation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub requests: Option<TaskRequestsCapability>,
}

/// Task cancel capability marker
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaskCancelCapability {}

/// Task list capability marker
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaskListCapability {}

/// Task requests capability - which methods support task augmentation
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaskRequestsCapability {
    /// Sampling requests can be task-augmented
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sampling: Option<TaskSamplingCapability>,
    /// Elicitation requests can be task-augmented
    #[serde(skip_serializing_if = "Option::is_none")]
    pub elicitation: Option<TaskElicitationCapability>,
    /// Tool calls can be task-augmented
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<TaskToolsCapability>,
}

/// Task sampling capability
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaskSamplingCapability {
    /// createMessage supports task augmentation
    #[serde(rename = "createMessage", skip_serializing_if = "Option::is_none")]
    pub create_message: Option<TaskMethodCapability>,
}

/// Task elicitation capability
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaskElicitationCapability {
    /// create supports task augmentation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub create: Option<TaskMethodCapability>,
}

/// Task tools capability
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaskToolsCapability {
    /// call supports task augmentation
    #[serde(skip_serializing_if = "Option::is_none")]
    pub call: Option<TaskMethodCapability>,
}

/// Marker for a method that supports task augmentation
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct TaskMethodCapability {}

/// Task metadata for request augmentation (MCP 2025-11-25)
///
/// When included in a request's `_meta`, the server returns a `CreateTaskResult`
/// immediately instead of blocking until completion.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct TaskMetadata {
    /// Optional TTL override in seconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub ttl: Option<u64>,
    /// Optional polling interval override in milliseconds
    #[serde(skip_serializing_if = "Option::is_none")]
    pub poll_interval: Option<u64>,
}

/// Result of creating a task-augmented request (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CreateTaskResult {
    /// The created task
    pub task: Task,
}

/// Get task request parameters (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetTaskRequestParam {
    /// ID of the task to retrieve
    pub task_id: String,
}

/// Get task result (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct GetTaskResult {
    /// The task state
    pub task: Task,
}

/// List tasks request parameters (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ListTasksRequestParam {
    /// Pagination cursor
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<String>,
}

/// List tasks result (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ListTasksResult {
    /// List of tasks
    pub tasks: Vec<Task>,
    /// Pagination cursor for next page
    #[serde(skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<String>,
}

/// Get task result/payload request parameters (MCP 2025-11-25)
///
/// Retrieves the actual result of a completed task. This may block
/// until the task completes if it's still running.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GetTaskResultRequestParam {
    /// ID of the task to get results for
    pub task_id: String,
}

/// Cancel task request parameters (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CancelTaskRequestParam {
    /// ID of the task to cancel
    pub task_id: String,
}

/// Cancel task result (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CancelTaskResult {
    /// The cancelled task
    pub task: Task,
}

/// Task status notification (MCP 2025-11-25)
///
/// Sent by the server when a task's status changes.
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TaskStatusNotification {
    /// ID of the task that changed
    pub task_id: String,
    /// New status
    pub status: TaskStatus,
    /// Optional status message
    #[serde(skip_serializing_if = "Option::is_none")]
    pub status_message: Option<String>,
    /// Timestamp of the status change
    #[serde(skip_serializing_if = "Option::is_none")]
    pub last_updated_at: Option<String>,
}

impl TaskStatusNotification {
    /// Create a new task status notification
    pub fn new(task_id: impl Into<String>, status: TaskStatus) -> Self {
        Self {
            task_id: task_id.into(),
            status,
            status_message: None,
            last_updated_at: None,
        }
    }

    /// Create a notification with a status message
    pub fn with_message(
        task_id: impl Into<String>,
        status: TaskStatus,
        message: impl Into<String>,
    ) -> Self {
        Self {
            task_id: task_id.into(),
            status,
            status_message: Some(message.into()),
            last_updated_at: None,
        }
    }
}

/// Tool execution configuration (MCP 2025-11-25)
///
/// Specifies how a tool handles task-based execution.
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "camelCase")]
pub struct ToolExecution {
    /// Whether this tool supports/requires task-based execution
    #[serde(skip_serializing_if = "Option::is_none")]
    pub task_support: Option<TaskSupport>,
}

/// Task support mode for tools (MCP 2025-11-25)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "lowercase")]
pub enum TaskSupport {
    /// Tool does not support task-based execution
    Forbidden,
    /// Tool optionally supports task-based execution
    Optional,
    /// Tool requires task-based execution
    Required,
}

impl Default for TaskSupport {
    fn default() -> Self {
        Self::Optional
    }
}