mcp-protocol-sdk 0.5.1

Production-ready Rust SDK for the Model Context Protocol (MCP) with multiple transport support
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
//! Complete MCP Protocol Types for 2025-06-18 Specification
//!
//! This module contains all the core types defined by the Model Context Protocol
//! specification version 2025-06-18, with simplified JSON-RPC (no batching) and
//! enhanced metadata handling.

use serde::{Deserialize, Serialize};
use std::collections::HashMap;

// ============================================================================
// Core Protocol Constants
// ============================================================================

/// MCP Protocol version (2025-06-18)
pub const LATEST_PROTOCOL_VERSION: &str = "2025-06-18";
pub const JSONRPC_VERSION: &str = "2.0";

// Legacy constant for compatibility
pub const PROTOCOL_VERSION: &str = LATEST_PROTOCOL_VERSION;

// ============================================================================
// Type Aliases
// ============================================================================

/// Progress token for associating notifications with requests
pub type ProgressToken = serde_json::Value; // string | number

/// Cursor for pagination
pub type Cursor = String;

/// Request ID for JSON-RPC correlation
pub type RequestId = serde_json::Value; // string | number | null

/// JSON-RPC ID type for better type safety
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum JsonRpcId {
    String(String),
    Number(i64),
    Null,
}

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

impl From<String> for JsonRpcId {
    fn from(value: String) -> Self {
        JsonRpcId::String(value)
    }
}

impl From<&str> for JsonRpcId {
    fn from(value: &str) -> Self {
        JsonRpcId::String(value.to_string())
    }
}

// ============================================================================
// BaseMetadata Interface (2025-06-18)
// ============================================================================

/// Base interface for metadata with name (identifier) and title (display name) properties.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct BaseMetadata {
    /// Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).
    pub name: String,
    /// Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
    /// even by those unfamiliar with domain-specific terminology.
    ///
    /// If not provided, the name should be used for display (except for Tool,
    /// where `annotations.title` should be given precedence over using `name`, if present).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

// ============================================================================
// Core Implementation Info
// ============================================================================

/// Information about an MCP implementation (2025-06-18 with title support)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Implementation {
    /// Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).
    pub name: String,
    /// Version of the implementation
    pub version: String,
    /// Intended for UI and end-user contexts — optimized to be human-readable and easily understood,
    /// even by those unfamiliar with domain-specific terminology.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

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

    /// Create implementation with title
    pub fn with_title<S: Into<String>>(name: S, version: S, title: S) -> Self {
        Self {
            name: name.into(),
            version: version.into(),
            title: Some(title.into()),
        }
    }
}

// Type aliases for compatibility
pub type ServerInfo = Implementation;
pub type ClientInfo = Implementation;

// ============================================================================
// Capabilities (2025-06-18)
// ============================================================================

/// Server capabilities for 2025-06-18
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct ServerCapabilities {
    /// Prompt-related capabilities
    #[serde(skip_serializing_if = "Option::is_none")]
    pub prompts: Option<PromptsCapability>,
    /// Resource-related capabilities
    #[serde(skip_serializing_if = "Option::is_none")]
    pub resources: Option<ResourcesCapability>,
    /// Tool-related capabilities
    #[serde(skip_serializing_if = "Option::is_none")]
    pub tools: Option<ToolsCapability>,
    /// Sampling-related capabilities (client to server)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sampling: Option<SamplingCapability>,
    /// Logging capabilities (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub logging: Option<LoggingCapability>,
    /// Autocompletion capabilities (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub completions: Option<CompletionsCapability>,
    /// Experimental capabilities (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub experimental: Option<HashMap<String, serde_json::Value>>,
}

/// Client capabilities for 2025-06-18
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct ClientCapabilities {
    /// Sampling-related capabilities
    #[serde(skip_serializing_if = "Option::is_none")]
    pub sampling: Option<SamplingCapability>,
    /// Roots listing capabilities (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub roots: Option<RootsCapability>,
    /// Elicitation support (2025-06-18 NEW)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub elicitation: Option<ElicitationCapability>,
    /// Experimental capabilities (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub experimental: Option<HashMap<String, serde_json::Value>>,
}

/// Prompt-related server capabilities
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct PromptsCapability {
    /// Whether the server supports prompt list change notifications
    #[serde(rename = "listChanged", skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

/// Resource-related server capabilities
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct ResourcesCapability {
    /// Whether the server supports resource subscriptions
    #[serde(skip_serializing_if = "Option::is_none")]
    pub subscribe: Option<bool>,
    /// Whether the server supports resource list change notifications
    #[serde(rename = "listChanged", skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

/// Tool-related server capabilities
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct ToolsCapability {
    /// Whether the server supports tool list change notifications
    #[serde(rename = "listChanged", skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

/// Sampling-related capabilities
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct SamplingCapability {
    /// Additional properties
    #[serde(flatten)]
    pub additional_properties: HashMap<String, serde_json::Value>,
}

/// Logging capabilities (2025-03-26)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct LoggingCapability {
    /// Additional properties
    #[serde(flatten)]
    pub additional_properties: HashMap<String, serde_json::Value>,
}

/// Autocompletion capabilities (2025-03-26)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct CompletionsCapability {
    /// Additional properties
    #[serde(flatten)]
    pub additional_properties: HashMap<String, serde_json::Value>,
}

/// Roots capability for clients (2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct RootsCapability {
    /// Whether the client supports notifications for changes to the roots list
    #[serde(rename = "listChanged", skip_serializing_if = "Option::is_none")]
    pub list_changed: Option<bool>,
}

/// Elicitation capabilities (2025-06-18 NEW)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct ElicitationCapability {
    /// Additional properties for elicitation capability
    #[serde(flatten)]
    pub additional_properties: HashMap<String, serde_json::Value>,
}

// ============================================================================
// Annotations (2025-06-18 Enhanced)
// ============================================================================

/// Optional annotations for the client. The client can use annotations to inform how objects are used or displayed.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct Annotations {
    /// Describes who the intended customer of this object or data is.
    ///
    /// It can include multiple entries to indicate content useful for multiple audiences (e.g., `["user", "assistant"]`).
    #[serde(skip_serializing_if = "Option::is_none")]
    pub audience: Option<Vec<Role>>,
    /// Describes how important this data is for operating the server.
    ///
    /// A value of 1 means "most important," and indicates that the data is
    /// effectively required, while 0 means "least important," and indicates that
    /// the data is entirely optional.
    #[serde(skip_serializing_if = "Option::is_none")]
    pub priority: Option<f64>,
    /// The moment the resource was last modified, as an ISO 8601 formatted string.
    ///
    /// Should be an ISO 8601 formatted string (e.g., "2025-01-12T15:00:58Z").
    ///
    /// Examples: last activity timestamp in an open file, timestamp when the resource
    /// was attached, etc.
    #[serde(rename = "lastModified", skip_serializing_if = "Option::is_none")]
    pub last_modified: Option<String>,
    /// Legacy danger level field for test compatibility
    #[serde(skip_serializing_if = "Option::is_none")]
    pub danger: Option<DangerLevel>,
    /// Legacy destructive field for test compatibility
    #[serde(skip_serializing_if = "Option::is_none")]
    pub destructive: Option<bool>,
    /// Legacy read_only field for test compatibility
    #[serde(skip_serializing_if = "Option::is_none")]
    pub read_only: Option<bool>,
}

// ============================================================================
// Content Types (2025-06-18 with ResourceLink)
// ============================================================================

/// Text content
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TextContent {
    /// Content type identifier
    #[serde(rename = "type")]
    pub content_type: String, // "text"
    /// The text content
    pub text: String,
    /// Content annotations (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
    /// Metadata field for future extensions
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// Image content
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ImageContent {
    /// Content type identifier
    #[serde(rename = "type")]
    pub content_type: String, // "image"
    /// Base64-encoded image data
    pub data: String,
    /// MIME type of the image
    #[serde(rename = "mimeType")]
    pub mime_type: String,
    /// Content annotations (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
    /// Metadata field for future extensions
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// Audio content (2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct AudioContent {
    /// Content type identifier
    #[serde(rename = "type")]
    pub content_type: String, // "audio"
    /// Base64-encoded audio data
    pub data: String,
    /// MIME type of the audio
    #[serde(rename = "mimeType")]
    pub mime_type: String,
    /// Content annotations (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
    /// Metadata field for future extensions
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// ResourceLink content (2025-06-18 NEW)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ResourceLink {
    /// Content type identifier
    #[serde(rename = "type")]
    pub content_type: String, // "resource_link"
    /// URI of the resource
    pub uri: String,
    /// Human-readable name of the resource
    pub name: String,
    /// Description of the resource
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// MIME type of the resource
    #[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    /// Size of the resource in bytes
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<u64>,
    /// Title for UI display
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Content annotations (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
    /// Metadata field for future extensions
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// Embedded resource content (2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct EmbeddedResource {
    /// Content type identifier
    #[serde(rename = "type")]
    pub content_type: String, // "resource"
    /// Resource contents
    pub resource: ResourceContents,
    /// Content annotations (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
    /// Metadata field for future extensions
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// ContentBlock union type (2025-06-18 complete with ResourceLink)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum ContentBlock {
    /// Text content
    #[serde(rename = "text")]
    Text {
        /// The text content
        text: String,
        /// Content annotations (2025-06-18)
        #[serde(skip_serializing_if = "Option::is_none")]
        annotations: Option<Annotations>,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
    /// Image content
    #[serde(rename = "image")]
    Image {
        /// Base64-encoded image data
        data: String,
        /// MIME type of the image
        #[serde(rename = "mimeType")]
        mime_type: String,
        /// Content annotations (2025-06-18)
        #[serde(skip_serializing_if = "Option::is_none")]
        annotations: Option<Annotations>,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
    /// Audio content (2025-06-18)
    #[serde(rename = "audio")]
    Audio {
        /// Base64-encoded audio data
        data: String,
        /// MIME type of the audio
        #[serde(rename = "mimeType")]
        mime_type: String,
        /// Content annotations (2025-06-18)
        #[serde(skip_serializing_if = "Option::is_none")]
        annotations: Option<Annotations>,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
    /// ResourceLink content (2025-06-18 NEW)
    #[serde(rename = "resource_link")]
    ResourceLink {
        /// URI of the resource
        uri: String,
        /// Human-readable name of the resource
        name: String,
        /// Description of the resource
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        /// MIME type of the resource
        #[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
        mime_type: Option<String>,
        /// Size of the resource in bytes
        #[serde(skip_serializing_if = "Option::is_none")]
        size: Option<u64>,
        /// Title for UI display
        #[serde(skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        /// Content annotations (2025-06-18)
        #[serde(skip_serializing_if = "Option::is_none")]
        annotations: Option<Annotations>,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
    /// Embedded resource content (2025-06-18)
    #[serde(rename = "resource")]
    Resource {
        /// Resource contents
        resource: ResourceContents,
        /// Content annotations (2025-06-18)
        #[serde(skip_serializing_if = "Option::is_none")]
        annotations: Option<Annotations>,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
}

// Legacy alias for backwards compatibility
pub type Content = ContentBlock;

// ============================================================================
// Tool Types (2025-06-18 with Title and Structured Content)
// ============================================================================

/// Tool-specific annotations (2025-06-18 Schema Compliance)
///
/// NOTE: all properties in ToolAnnotations are **hints**.
/// They are not guaranteed to provide a faithful description of
/// tool behavior (including descriptive properties like `title`).
///
/// Clients should never make tool use decisions based on ToolAnnotations
/// received from untrusted servers.
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct ToolAnnotations {
    /// A human-readable title for the tool
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,

    /// If true, the tool does not modify its environment
    /// Default: false
    #[serde(rename = "readOnlyHint", skip_serializing_if = "Option::is_none")]
    pub read_only_hint: Option<bool>,

    /// If true, the tool may perform destructive updates to its environment
    /// If false, the tool performs only additive updates
    /// (This property is meaningful only when `readOnlyHint == false`)
    /// Default: true
    #[serde(rename = "destructiveHint", skip_serializing_if = "Option::is_none")]
    pub destructive_hint: Option<bool>,

    /// If true, calling the tool repeatedly with the same arguments
    /// will have no additional effect on its environment
    /// (This property is meaningful only when `readOnlyHint == false`)
    /// Default: false
    #[serde(rename = "idempotentHint", skip_serializing_if = "Option::is_none")]
    pub idempotent_hint: Option<bool>,

    /// If true, this tool may interact with an "open world" of external entities
    /// If false, the tool's domain of interaction is closed
    /// For example, the world of a web search tool is open, whereas that
    /// of a memory tool is not
    /// Default: true
    #[serde(rename = "openWorldHint", skip_serializing_if = "Option::is_none")]
    pub open_world_hint: Option<bool>,
}

impl ToolAnnotations {
    /// Create new empty tool annotations
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the human-readable title for the tool
    pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Mark tool as read-only (does not modify environment)
    pub fn read_only(mut self) -> Self {
        self.read_only_hint = Some(true);
        self
    }

    /// Mark tool as destructive (may perform destructive updates)
    pub fn destructive(mut self) -> Self {
        self.destructive_hint = Some(true);
        self
    }

    /// Mark tool as idempotent (same input produces same result)
    pub fn idempotent(mut self) -> Self {
        self.idempotent_hint = Some(true);
        self
    }

    /// Mark tool as interacting with open world of external entities
    pub fn open_world(mut self) -> Self {
        self.open_world_hint = Some(true);
        self
    }

    /// Mark tool as interacting with closed world (limited domain)
    pub fn closed_world(mut self) -> Self {
        self.open_world_hint = Some(false);
        self
    }
}

// ============================================================================
// Tool Annotations Integration with Enhanced Metadata
// ============================================================================

impl From<&crate::core::tool_metadata::ToolBehaviorHints> for ToolAnnotations {
    fn from(hints: &crate::core::tool_metadata::ToolBehaviorHints) -> Self {
        Self {
            title: None, // Title should be set separately at tool level
            read_only_hint: hints.read_only,
            destructive_hint: hints.destructive,
            idempotent_hint: hints.idempotent,
            // Map open_world_hint: if requires_auth or resource_intensive, likely open world
            open_world_hint: if hints.requires_auth.unwrap_or(false)
                || hints.resource_intensive.unwrap_or(false)
            {
                Some(true)
            } else {
                None
            },
        }
    }
}

impl From<&crate::core::tool_metadata::EnhancedToolMetadata> for ToolAnnotations {
    fn from(metadata: &crate::core::tool_metadata::EnhancedToolMetadata) -> Self {
        ToolAnnotations::from(&metadata.behavior_hints)
    }
}

impl ToolAnnotations {
    /// Create ToolAnnotations from enhanced metadata with explicit title override
    pub fn from_enhanced_metadata(
        metadata: &crate::core::tool_metadata::EnhancedToolMetadata,
        title_override: Option<String>,
    ) -> Self {
        let mut annotations = Self::from(metadata);
        if let Some(title) = title_override {
            annotations.title = Some(title);
        }
        annotations
    }

    /// Create minimal ToolAnnotations from behavior hints
    pub fn from_behavior_hints(hints: &crate::core::tool_metadata::ToolBehaviorHints) -> Self {
        Self::from(hints)
    }
}

/// Tool definition with annotations and title (2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Tool {
    /// Intended for programmatic or logical use
    pub name: String,
    /// Description of what the tool does
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// JSON Schema describing the tool's input parameters
    #[serde(rename = "inputSchema")]
    pub input_schema: ToolInputSchema,
    /// Tool behavior annotations (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<ToolAnnotations>,
    /// Intended for UI and end-user contexts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Metadata field for future extensions
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// Tool input schema
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ToolInputSchema {
    /// Schema type (always "object")
    #[serde(rename = "type")]
    pub schema_type: String,
    /// Schema properties
    #[serde(skip_serializing_if = "Option::is_none")]
    pub properties: Option<HashMap<String, serde_json::Value>>,
    /// Required properties
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
    /// Additional schema properties
    #[serde(flatten)]
    pub additional_properties: HashMap<String, serde_json::Value>,
}

/// Result of a tool execution (2025-06-18 with structured content)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CallToolResult {
    /// Content returned by the tool
    pub content: Vec<ContentBlock>,
    /// Whether this result represents an error
    #[serde(rename = "isError", skip_serializing_if = "Option::is_none")]
    pub is_error: Option<bool>,
    /// An optional JSON object that represents the structured result of the tool call
    #[serde(rename = "structuredContent", skip_serializing_if = "Option::is_none")]
    pub structured_content: Option<serde_json::Value>,
    /// Result metadata (2025-06-18)
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

// Re-export types with legacy names for compatibility
pub type ToolInfo = Tool;
pub type ToolResult = CallToolResult;

// ============================================================================
// Resource Types (2025-06-18)
// ============================================================================

/// Resource definition
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Resource {
    /// URI of the resource
    pub uri: String,
    /// Intended for programmatic or logical use, but used as a display name in past specs or fallback (if title isn't present).
    pub name: String,
    /// Description of the resource
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// MIME type of the resource
    #[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    /// Resource annotations (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
    /// Resource size in bytes (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub size: Option<u64>,
    /// Intended for UI and end-user contexts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Metadata field for future extensions
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// Resource template for URI patterns
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ResourceTemplate {
    /// URI template with variables
    #[serde(rename = "uriTemplate")]
    pub uri_template: String,
    /// Intended for programmatic or logical use
    pub name: String,
    /// Description of the resource template
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// MIME type of resources from this template
    #[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
    pub mime_type: Option<String>,
    /// Resource annotations (2025-06-18)
    #[serde(skip_serializing_if = "Option::is_none")]
    pub annotations: Option<Annotations>,
    /// Intended for UI and end-user contexts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Metadata field for future extensions
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// Content of a resource (2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum ResourceContents {
    /// Text resource content
    Text {
        /// URI of the resource
        uri: String,
        /// MIME type
        #[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
        mime_type: Option<String>,
        /// Text content
        text: String,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
    /// Binary resource content
    Blob {
        /// URI of the resource
        uri: String,
        /// MIME type
        #[serde(rename = "mimeType", skip_serializing_if = "Option::is_none")]
        mime_type: Option<String>,
        /// Base64-encoded binary data
        blob: String,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
}

impl ResourceContents {
    /// Get the URI of the resource
    pub fn uri(&self) -> &str {
        match self {
            ResourceContents::Text { uri, .. } => uri,
            ResourceContents::Blob { uri, .. } => uri,
        }
    }
}

// Legacy type aliases for compatibility
pub type ResourceInfo = Resource;

// ============================================================================
// Prompt Types (2025-06-18)
// ============================================================================

/// Prompt definition
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Prompt {
    /// Intended for programmatic or logical use
    pub name: String,
    /// Description of what the prompt does
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Arguments that the prompt accepts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub arguments: Option<Vec<PromptArgument>>,
    /// Intended for UI and end-user contexts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
    /// Metadata field for future extensions
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// Argument for a prompt
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PromptArgument {
    /// Intended for programmatic or logical use
    pub name: String,
    /// Description of the argument
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Whether this argument is required
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<bool>,
    /// Intended for UI and end-user contexts
    #[serde(skip_serializing_if = "Option::is_none")]
    pub title: Option<String>,
}

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

/// Message in a prompt result (2025-06-18 with ContentBlock support)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PromptMessage {
    /// Role of the message
    pub role: Role,
    /// Content of the message (supports all content types including resource_link)
    pub content: ContentBlock,
}

/// Result of prompt execution (2025-06-18 with metadata)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct GetPromptResult {
    /// Description of the prompt result
    #[serde(skip_serializing_if = "Option::is_none")]
    pub description: Option<String>,
    /// Messages generated by the prompt
    pub messages: Vec<PromptMessage>,
    /// Result metadata (2025-06-18)
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

// Legacy type aliases for compatibility
pub type PromptInfo = Prompt;
pub type PromptResult = GetPromptResult;

// ============================================================================
// Sampling Types (2025-06-18)
// ============================================================================

/// A message in a sampling conversation (2025-06-18 with ContentBlock)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct SamplingMessage {
    /// Role of the message
    pub role: Role,
    /// Content of the message (text, image, or audio only - no resource_link in sampling)
    pub content: SamplingContent,
}

/// Content types allowed in sampling (subset of ContentBlock)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum SamplingContent {
    /// Text content
    #[serde(rename = "text")]
    Text {
        /// The text content
        text: String,
        /// Content annotations (2025-06-18)
        #[serde(skip_serializing_if = "Option::is_none")]
        annotations: Option<Annotations>,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
    /// Image content
    #[serde(rename = "image")]
    Image {
        /// Base64-encoded image data
        data: String,
        /// MIME type of the image
        #[serde(rename = "mimeType")]
        mime_type: String,
        /// Content annotations (2025-06-18)
        #[serde(skip_serializing_if = "Option::is_none")]
        annotations: Option<Annotations>,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
    /// Audio content (2025-06-18)
    #[serde(rename = "audio")]
    Audio {
        /// Base64-encoded audio data
        data: String,
        /// MIME type of the audio
        #[serde(rename = "mimeType")]
        mime_type: String,
        /// Content annotations (2025-06-18)
        #[serde(skip_serializing_if = "Option::is_none")]
        annotations: Option<Annotations>,
        /// Metadata field for future extensions
        #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
        meta: Option<HashMap<String, serde_json::Value>>,
    },
}

/// Model hint for model selection (2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ModelHint {
    /// A hint for a model name.
    ///
    /// The client SHOULD treat this as a substring of a model name; for example:
    /// - `claude-3-5-sonnet` should match `claude-3-5-sonnet-20241022`
    /// - `sonnet` should match `claude-3-5-sonnet-20241022`, `claude-3-sonnet-20240229`, etc.
    /// - `claude` should match any Claude model
    #[serde(skip_serializing_if = "Option::is_none")]
    pub name: Option<String>,
}

/// Model preferences for sampling (2025-06-18 enhanced)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
pub struct ModelPreferences {
    /// How much to prioritize cost when selecting a model
    #[serde(rename = "costPriority", skip_serializing_if = "Option::is_none")]
    pub cost_priority: Option<f64>,
    /// How much to prioritize sampling speed (latency) when selecting a model
    #[serde(rename = "speedPriority", skip_serializing_if = "Option::is_none")]
    pub speed_priority: Option<f64>,
    /// How much to prioritize intelligence and capabilities when selecting a model
    #[serde(
        rename = "intelligencePriority",
        skip_serializing_if = "Option::is_none"
    )]
    pub intelligence_priority: Option<f64>,
    /// Optional hints to use for model selection
    #[serde(skip_serializing_if = "Option::is_none")]
    pub hints: Option<Vec<ModelHint>>,
}

/// Result of sampling/createMessage (2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct CreateMessageResult {
    /// Role of the generated message
    pub role: Role,
    /// Content of the generated message
    pub content: SamplingContent,
    /// Model used for generation
    pub model: String,
    /// Stop reason
    #[serde(rename = "stopReason", skip_serializing_if = "Option::is_none")]
    pub stop_reason: Option<StopReason>,
    /// Result metadata (2025-06-18)
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
}

/// Reasons why sampling stopped
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub enum StopReason {
    EndTurn,
    StopSequence,
    MaxTokens,
    #[serde(untagged)]
    Other(String),
}

// ============================================================================
// Elicitation Types (2025-06-18 NEW)
// ============================================================================

/// Primitive schema definition for elicitation
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(tag = "type")]
pub enum PrimitiveSchemaDefinition {
    #[serde(rename = "string")]
    String {
        #[serde(skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        #[serde(rename = "minLength", skip_serializing_if = "Option::is_none")]
        min_length: Option<u32>,
        #[serde(rename = "maxLength", skip_serializing_if = "Option::is_none")]
        max_length: Option<u32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        format: Option<String>,
        #[serde(rename = "enum", skip_serializing_if = "Option::is_none")]
        enum_values: Option<Vec<String>>,
        #[serde(rename = "enumNames", skip_serializing_if = "Option::is_none")]
        enum_names: Option<Vec<String>>,
    },
    #[serde(rename = "number")]
    Number {
        #[serde(skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        minimum: Option<i32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        maximum: Option<i32>,
    },
    #[serde(rename = "integer")]
    Integer {
        #[serde(skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        minimum: Option<i32>,
        #[serde(skip_serializing_if = "Option::is_none")]
        maximum: Option<i32>,
    },
    #[serde(rename = "boolean")]
    Boolean {
        #[serde(skip_serializing_if = "Option::is_none")]
        title: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        description: Option<String>,
        #[serde(skip_serializing_if = "Option::is_none")]
        default: Option<bool>,
    },
}

/// Restricted schema for elicitation (only top-level properties allowed)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ElicitationSchema {
    /// Schema type (always "object")
    #[serde(rename = "type")]
    pub schema_type: String,
    /// Top-level properties
    pub properties: HashMap<String, PrimitiveSchemaDefinition>,
    /// Required properties
    #[serde(skip_serializing_if = "Option::is_none")]
    pub required: Option<Vec<String>>,
}

/// Elicitation user action
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum ElicitationAction {
    /// User submitted the form/confirmed the action
    Accept,
    /// User explicitly declined the action
    Decline,
    /// User dismissed without making an explicit choice
    Cancel,
}

// ============================================================================
// Logging Types (2025-06-18)
// ============================================================================

/// Logging level enumeration (2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum LoggingLevel {
    Debug,
    Info,
    Notice,
    Warning,
    Error,
    Critical,
    Alert,
    Emergency,
}

// ============================================================================
// JSON-RPC Types (2025-03-26 with Batching)
// ============================================================================

/// JSON-RPC request message
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct JsonRpcRequest {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// Request ID for correlation
    pub id: RequestId,
    /// Method name being called
    pub method: String,
    /// Method parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
}

/// JSON-RPC response message
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct JsonRpcResponse {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// Request ID for correlation
    pub id: RequestId,
    /// Result of the method call
    #[serde(skip_serializing_if = "Option::is_none")]
    pub result: Option<serde_json::Value>,
}

/// JSON-RPC error message
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct JsonRpcError {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// Request ID for correlation
    pub id: RequestId,
    /// Error information
    pub error: ErrorObject,
}

/// Error object
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ErrorObject {
    /// Error code
    pub code: i32,
    /// Error message
    pub message: String,
    /// Additional error data
    #[serde(skip_serializing_if = "Option::is_none")]
    pub data: Option<serde_json::Value>,
}

/// JSON-RPC notification message
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct JsonRpcNotification {
    /// JSON-RPC version (always "2.0")
    pub jsonrpc: String,
    /// Method name being called
    pub method: String,
    /// Method parameters
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<serde_json::Value>,
}

/// Complete JSON-RPC message types (2025-06-18)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum JsonRpcMessage {
    Request(JsonRpcRequest),
    Response(JsonRpcResponse),
    Error(JsonRpcError),
    Notification(JsonRpcNotification),
}

// ============================================================================
// Request/Response Metadata (2025-03-26 NEW)
// ============================================================================

/// Base request with metadata support
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Request {
    /// Method name
    pub method: String,
    /// Parameters with metadata support
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<RequestParams>,
}

/// Request parameters with metadata
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RequestParams {
    /// Request metadata (2025-03-26 NEW)
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<RequestMeta>,
    /// Additional parameters
    #[serde(flatten)]
    pub params: HashMap<String, serde_json::Value>,
}

/// Request metadata
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct RequestMeta {
    /// Progress token for out-of-band progress notifications
    #[serde(rename = "progressToken", skip_serializing_if = "Option::is_none")]
    pub progress_token: Option<ProgressToken>,
}

/// Base notification with metadata support
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct Notification {
    /// Method name
    pub method: String,
    /// Parameters with metadata support
    #[serde(skip_serializing_if = "Option::is_none")]
    pub params: Option<NotificationParams>,
}

/// Notification parameters with metadata
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct NotificationParams {
    /// Notification metadata (2025-03-26 NEW)
    #[serde(rename = "_meta", skip_serializing_if = "Option::is_none")]
    pub meta: Option<HashMap<String, serde_json::Value>>,
    /// Additional parameters
    #[serde(flatten)]
    pub params: HashMap<String, serde_json::Value>,
}

// ============================================================================
// Pagination Support
// ============================================================================

/// Base for paginated requests
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaginatedRequest {
    /// Cursor for pagination
    #[serde(skip_serializing_if = "Option::is_none")]
    pub cursor: Option<Cursor>,
}

/// Base for paginated results
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct PaginatedResult {
    /// Cursor for next page
    #[serde(rename = "nextCursor", skip_serializing_if = "Option::is_none")]
    pub next_cursor: Option<Cursor>,
}

// ============================================================================
// Helper Constructors
// ============================================================================

impl ContentBlock {
    /// Create text content
    pub fn text<S: Into<String>>(text: S) -> Self {
        Self::Text {
            text: text.into(),
            annotations: None,
            meta: None,
        }
    }

    /// Create image content
    pub fn image<S: Into<String>>(data: S, mime_type: S) -> Self {
        Self::Image {
            data: data.into(),
            mime_type: mime_type.into(),
            annotations: None,
            meta: None,
        }
    }

    /// Create audio content (2025-06-18)
    pub fn audio<S: Into<String>>(data: S, mime_type: S) -> Self {
        Self::Audio {
            data: data.into(),
            mime_type: mime_type.into(),
            annotations: None,
            meta: None,
        }
    }

    /// Create resource link content (2025-06-18 NEW)
    pub fn resource_link<S: Into<String>>(uri: S, name: S) -> Self {
        Self::ResourceLink {
            uri: uri.into(),
            name: name.into(),
            description: None,
            mime_type: None,
            size: None,
            title: None,
            annotations: None,
            meta: None,
        }
    }

    /// Create embedded resource content (2025-06-18)
    pub fn embedded_resource(resource: ResourceContents) -> Self {
        Self::Resource {
            resource,
            annotations: None,
            meta: None,
        }
    }

    /// Create resource content (legacy compatibility)
    pub fn resource<S: Into<String>>(uri: S) -> Self {
        let uri_str = uri.into();
        Self::resource_link(uri_str.clone(), uri_str)
    }
}

impl SamplingContent {
    /// Create text content for sampling
    pub fn text<S: Into<String>>(text: S) -> Self {
        Self::Text {
            text: text.into(),
            annotations: None,
            meta: None,
        }
    }

    /// Create image content for sampling
    pub fn image<S: Into<String>>(data: S, mime_type: S) -> Self {
        Self::Image {
            data: data.into(),
            mime_type: mime_type.into(),
            annotations: None,
            meta: None,
        }
    }

    /// Create audio content for sampling
    pub fn audio<S: Into<String>>(data: S, mime_type: S) -> Self {
        Self::Audio {
            data: data.into(),
            mime_type: mime_type.into(),
            annotations: None,
            meta: None,
        }
    }
}

impl Annotations {
    /// Create new annotations
    pub fn new() -> Self {
        Self {
            audience: None,
            priority: None,
            last_modified: None,
            danger: None,
            destructive: None,
            read_only: None,
        }
    }

    /// Set priority (0.0 = least important, 1.0 = most important)
    pub fn with_priority(mut self, priority: f64) -> Self {
        self.priority = Some(priority.clamp(0.0, 1.0));
        self
    }

    /// Set audience
    pub fn for_audience(mut self, audience: Vec<Role>) -> Self {
        self.audience = Some(audience);
        self
    }

    /// Set last modified timestamp (ISO 8601 format)
    pub fn with_last_modified<S: Into<String>>(mut self, timestamp: S) -> Self {
        self.last_modified = Some(timestamp.into());
        self
    }

    /// Set audience (legacy compatibility)
    pub fn for_audience_legacy(self, _audience: Vec<AnnotationAudience>) -> Self {
        // Legacy compatibility - ignore audience in new API
        self
    }

    /// Set danger level (legacy compatibility)
    pub fn with_danger_level(self, _level: DangerLevel) -> Self {
        // Legacy compatibility - ignore danger level in new API
        self
    }

    /// Legacy danger field (always returns None for compatibility)
    pub fn danger(&self) -> Option<DangerLevel> {
        None
    }

    /// Legacy audience field (always returns None for compatibility)
    pub fn audience(&self) -> Option<Vec<AnnotationAudience>> {
        None
    }

    /// Set as read-only (legacy compatibility)
    pub fn read_only(mut self) -> Self {
        self.read_only = Some(true);
        self
    }

    /// Set as destructive (legacy compatibility)
    pub fn destructive(mut self, level: DangerLevel) -> Self {
        self.destructive = Some(true);
        self.danger = Some(level);
        self
    }
}

impl Tool {
    /// Create a new tool
    pub fn new<S: Into<String>>(name: S, description: S) -> Self {
        Self {
            name: name.into(),
            description: Some(description.into()),
            input_schema: ToolInputSchema {
                schema_type: "object".to_string(),
                properties: None,
                required: None,
                additional_properties: HashMap::new(),
            },
            annotations: None,
            title: None,
            meta: None,
        }
    }

    /// Add title to the tool
    pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Add annotations to the tool
    pub fn with_annotations(mut self, annotations: ToolAnnotations) -> Self {
        self.annotations = Some(annotations);
        self
    }
}

impl Resource {
    /// Create a new resource
    pub fn new<S: Into<String>>(uri: S, name: S) -> Self {
        Self {
            uri: uri.into(),
            name: name.into(),
            description: None,
            mime_type: None,
            annotations: None,
            size: None,
            title: None,
            meta: None,
        }
    }

    /// Create a resource from legacy format (name was optional)
    pub fn from_legacy<S: Into<String>>(uri: S, name: Option<S>) -> Self {
        Self {
            uri: uri.into(),
            name: name
                .map(|n| n.into())
                .unwrap_or_else(|| "Unnamed Resource".to_string()),
            description: None,
            mime_type: None,
            annotations: None,
            size: None,
            title: None,
            meta: None,
        }
    }

    /// Add title to the resource
    pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Add description to the resource
    pub fn with_description<S: Into<String>>(mut self, description: S) -> Self {
        self.description = Some(description.into());
        self
    }
}

impl ResourceTemplate {
    /// Create a new resource template
    pub fn new<S: Into<String>>(uri_template: S, name: S) -> Self {
        Self {
            uri_template: uri_template.into(),
            name: name.into(),
            description: None,
            mime_type: None,
            annotations: None,
            title: None,
            meta: None,
        }
    }

    /// Create a resource template from legacy format (name was optional)
    pub fn from_legacy<S: Into<String>>(uri_template: S, name: Option<S>) -> Self {
        Self {
            uri_template: uri_template.into(),
            name: name
                .map(|n| n.into())
                .unwrap_or_else(|| "Unnamed Template".to_string()),
            description: None,
            mime_type: None,
            annotations: None,
            title: None,
            meta: None,
        }
    }

    /// Add title to the resource template
    pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
        self.title = Some(title.into());
        self
    }
}

impl Prompt {
    /// Create a new prompt
    pub fn new<S: Into<String>>(name: S) -> Self {
        Self {
            name: name.into(),
            description: None,
            arguments: None,
            title: None,
            meta: None,
        }
    }

    /// Add title to the prompt
    pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Add description to the prompt
    pub fn with_description<S: Into<String>>(mut self, description: S) -> Self {
        self.description = Some(description.into());
        self
    }
}

impl PromptArgument {
    /// Create a new prompt argument
    pub fn new<S: Into<String>>(name: S) -> Self {
        Self {
            name: name.into(),
            description: None,
            required: None,
            title: None,
        }
    }

    /// Add title to the prompt argument
    pub fn with_title<S: Into<String>>(mut self, title: S) -> Self {
        self.title = Some(title.into());
        self
    }

    /// Mark as required
    pub fn required(mut self, required: bool) -> Self {
        self.required = Some(required);
        self
    }
}

impl JsonRpcRequest {
    /// Create a new JSON-RPC request
    pub fn new<T: Serialize>(
        id: RequestId,
        method: String,
        params: Option<T>,
    ) -> std::result::Result<Self, serde_json::Error> {
        let params = match params {
            Some(p) => Some(serde_json::to_value(p)?),
            None => None,
        };

        Ok(Self {
            jsonrpc: JSONRPC_VERSION.to_string(),
            id,
            method,
            params,
        })
    }
}

impl JsonRpcResponse {
    /// Create a successful JSON-RPC response
    pub fn success<T: Serialize>(
        id: RequestId,
        result: T,
    ) -> std::result::Result<Self, serde_json::Error> {
        Ok(Self {
            jsonrpc: JSONRPC_VERSION.to_string(),
            id,
            result: Some(serde_json::to_value(result)?),
        })
    }
}

impl JsonRpcError {
    /// Create an error JSON-RPC response
    pub fn error(
        id: RequestId,
        code: i32,
        message: String,
        data: Option<serde_json::Value>,
    ) -> Self {
        Self {
            jsonrpc: JSONRPC_VERSION.to_string(),
            id,
            error: ErrorObject {
                code,
                message,
                data,
            },
        }
    }
}

impl JsonRpcNotification {
    /// Create a new JSON-RPC notification
    pub fn new<T: Serialize>(
        method: String,
        params: Option<T>,
    ) -> std::result::Result<Self, serde_json::Error> {
        let params = match params {
            Some(p) => Some(serde_json::to_value(p)?),
            None => None,
        };

        Ok(Self {
            jsonrpc: JSONRPC_VERSION.to_string(),
            method,
            params,
        })
    }
}

impl SamplingMessage {
    /// Create a user text message
    pub fn user_text<S: Into<String>>(text: S) -> Self {
        Self {
            role: Role::User,
            content: SamplingContent::text(text),
        }
    }

    /// Create an assistant text message
    pub fn assistant_text<S: Into<String>>(text: S) -> Self {
        Self {
            role: Role::Assistant,
            content: SamplingContent::text(text),
        }
    }

    /// Create a user image message
    pub fn user_image<S: Into<String>>(data: S, mime_type: S) -> Self {
        Self {
            role: Role::User,
            content: SamplingContent::image(data, mime_type),
        }
    }

    /// Create a user audio message
    pub fn user_audio<S: Into<String>>(data: S, mime_type: S) -> Self {
        Self {
            role: Role::User,
            content: SamplingContent::audio(data, mime_type),
        }
    }
}

// ============================================================================
// Error Codes
// ============================================================================

/// Standard JSON-RPC error codes
pub mod error_codes {
    /// Invalid JSON was received
    pub const PARSE_ERROR: i32 = -32700;
    /// The JSON sent is not a valid Request object
    pub const INVALID_REQUEST: i32 = -32600;
    /// The method does not exist / is not available
    pub const METHOD_NOT_FOUND: i32 = -32601;
    /// Invalid method parameter(s)
    pub const INVALID_PARAMS: i32 = -32602;
    /// Internal JSON-RPC error
    pub const INTERNAL_ERROR: i32 = -32603;

    /// MCP-specific error codes
    pub const TOOL_NOT_FOUND: i32 = -32000;
    pub const RESOURCE_NOT_FOUND: i32 = -32001;
    pub const PROMPT_NOT_FOUND: i32 = -32002;
}

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

    #[test]
    fn test_protocol_version() {
        assert_eq!(LATEST_PROTOCOL_VERSION, "2025-06-18");
        assert_eq!(JSONRPC_VERSION, "2.0");
    }

    #[test]
    fn test_content_block_types() {
        // Test text content
        let text = ContentBlock::text("Hello, world!");
        let json = serde_json::to_value(&text).unwrap();
        assert_eq!(json["type"], "text");
        assert_eq!(json["text"], "Hello, world!");

        // Test audio content (2025-06-18)
        let audio = ContentBlock::audio("base64data", "audio/wav");
        let json = serde_json::to_value(&audio).unwrap();
        assert_eq!(json["type"], "audio");
        assert_eq!(json["data"], "base64data");
        assert_eq!(json["mimeType"], "audio/wav");

        // Test resource link content (new in 2025-06-18)
        let resource_link = ContentBlock::resource_link("file:///test.txt", "test file");
        let json = serde_json::to_value(&resource_link).unwrap();
        assert_eq!(json["type"], "resource_link");
        assert_eq!(json["uri"], "file:///test.txt");
        assert_eq!(json["name"], "test file");
    }

    #[test]
    fn test_annotations() {
        let annotations = Annotations::new()
            .with_priority(0.8)
            .for_audience(vec![Role::User, Role::Assistant])
            .with_last_modified("2025-01-12T15:00:58Z");

        assert_eq!(annotations.priority, Some(0.8));
        assert_eq!(
            annotations.audience,
            Some(vec![Role::User, Role::Assistant])
        );
        assert_eq!(
            annotations.last_modified,
            Some("2025-01-12T15:00:58Z".to_string())
        );
    }

    #[test]
    fn test_tool_with_title() {
        let tool = Tool::new("file_reader", "Read files safely")
            .with_title("File Reader Tool")
            .with_annotations(ToolAnnotations::new().with_title("File Reader"));

        assert_eq!(tool.name, "file_reader");
        assert_eq!(tool.title, Some("File Reader Tool".to_string()));
        assert!(tool.annotations.is_some());
        assert_eq!(
            tool.annotations.unwrap().title,
            Some("File Reader".to_string())
        );
    }

    #[test]
    fn test_server_capabilities_2025_06_18() {
        let caps = ServerCapabilities {
            tools: Some(ToolsCapability {
                list_changed: Some(true),
            }),
            completions: Some(CompletionsCapability::default()),
            logging: Some(LoggingCapability::default()),
            experimental: Some(HashMap::new()),
            ..Default::default()
        };

        let json = serde_json::to_value(&caps).unwrap();
        assert!(json["tools"]["listChanged"].as_bool().unwrap());
        assert!(json["completions"].is_object());
        assert!(json["logging"].is_object());
        assert!(json["experimental"].is_object());
    }

    #[test]
    fn test_client_capabilities_with_elicitation() {
        let caps = ClientCapabilities {
            elicitation: Some(ElicitationCapability::default()),
            roots: Some(RootsCapability {
                list_changed: Some(true),
            }),
            ..Default::default()
        };

        let json = serde_json::to_value(&caps).unwrap();
        assert!(json["elicitation"].is_object());
        assert!(json["roots"]["listChanged"].as_bool().unwrap());
    }

    #[test]
    fn test_implementation_with_title() {
        let impl_info = Implementation::with_title("my-server", "1.0.0", "My Awesome Server");

        assert_eq!(impl_info.name, "my-server");
        assert_eq!(impl_info.version, "1.0.0");
        assert_eq!(impl_info.title, Some("My Awesome Server".to_string()));
    }

    #[test]
    fn test_model_preferences_enhanced() {
        let prefs = ModelPreferences {
            cost_priority: Some(0.3),
            speed_priority: Some(0.7),
            intelligence_priority: Some(0.9),
            hints: Some(vec![ModelHint {
                name: Some("claude".to_string()),
            }]),
        };

        let json = serde_json::to_value(&prefs).unwrap();
        assert_eq!(json["costPriority"], 0.3);
        assert_eq!(json["speedPriority"], 0.7);
        assert_eq!(json["intelligencePriority"], 0.9);
        assert!(json["hints"].is_array());
    }

    #[test]
    fn test_call_tool_result_with_structured_content() {
        let result = CallToolResult {
            content: vec![ContentBlock::text("Operation completed")],
            is_error: Some(false),
            structured_content: Some(json!({"status": "success", "count": 42})),
            meta: None,
        };

        let json = serde_json::to_value(&result).unwrap();
        assert!(json["content"].is_array());
        assert_eq!(json["isError"], false);
        assert_eq!(json["structuredContent"]["status"], "success");
        assert_eq!(json["structuredContent"]["count"], 42);
    }

    #[test]
    fn test_sampling_content_types() {
        // Test that SamplingContent doesn't include resource_link
        let text = SamplingContent::text("Hello");
        let image = SamplingContent::image("data", "image/png");
        let audio = SamplingContent::audio("data", "audio/wav");

        let text_json = serde_json::to_value(&text).unwrap();
        let image_json = serde_json::to_value(&image).unwrap();
        let audio_json = serde_json::to_value(&audio).unwrap();

        assert_eq!(text_json["type"], "text");
        assert_eq!(image_json["type"], "image");
        assert_eq!(audio_json["type"], "audio");
    }
}

// ============================================================================
// Legacy/Compatibility Types for Tests
// ============================================================================

/// Batch request type alias for compatibility
pub type JsonRpcBatchRequest = Vec<JsonRpcRequest>;

/// Batch response type alias for compatibility  
pub type JsonRpcBatchResponse = Vec<JsonRpcResponse>;

/// Request or notification union for compatibility
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum JsonRpcRequestOrNotification {
    Request(JsonRpcRequest),
    Notification(JsonRpcNotification),
}

/// Response or error union for compatibility
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(untagged)]
pub enum JsonRpcResponseOrError {
    Response(JsonRpcResponse),
    Error(JsonRpcError),
}

/// Annotation audience for content targeting (legacy)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum AnnotationAudience {
    User,
    Developer,
    System,
}

/// Danger level for tool safety annotations (legacy)
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum DangerLevel {
    Safe,
    Low,
    Medium,
    High,
}