-
Notifications
You must be signed in to change notification settings - Fork 502
Expand file tree
/
Copy pathmodel.rs
More file actions
1834 lines (1648 loc) · 63.5 KB
/
model.rs
File metadata and controls
1834 lines (1648 loc) · 63.5 KB
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
use std::{borrow::Cow, sync::Arc};
mod annotated;
mod capabilities;
mod content;
mod extension;
mod meta;
mod prompt;
mod resource;
mod serde_impl;
mod tool;
pub use annotated::*;
pub use capabilities::*;
pub use content::*;
pub use extension::*;
pub use meta::*;
pub use prompt::*;
pub use resource::*;
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use serde_json::Value;
pub use tool::*;
/// A JSON object type alias for convenient handling of JSON data.
///
/// You can use [`crate::object!`] or [`crate::model::object`] to create a json object quickly.
/// This is commonly used for storing arbitrary JSON data in MCP messages.
pub type JsonObject<F = Value> = serde_json::Map<String, F>;
/// unwrap the JsonObject under [`serde_json::Value`]
///
/// # Panic
/// This will panic when the value is not a object in debug mode.
pub fn object(value: serde_json::Value) -> JsonObject {
debug_assert!(value.is_object());
match value {
serde_json::Value::Object(map) => map,
_ => JsonObject::default(),
}
}
/// Use this macro just like [`serde_json::json!`]
#[cfg(feature = "macros")]
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
#[macro_export]
macro_rules! object {
({$($tt:tt)*}) => {
$crate::model::object(serde_json::json! {
{$($tt)*}
})
};
}
/// This is commonly used for representing empty objects in MCP messages.
///
/// without returning any specific data.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy, Eq)]
#[cfg_attr(feature = "server", derive(schemars::JsonSchema))]
pub struct EmptyObject {}
pub trait ConstString: Default {
const VALUE: &str;
fn as_str(&self) -> &'static str {
Self::VALUE
}
}
#[macro_export]
macro_rules! const_string {
($name:ident = $value:literal) => {
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct $name;
impl ConstString for $name {
const VALUE: &str = $value;
}
impl serde::Serialize for $name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
$value.serialize(serializer)
}
}
impl<'de> serde::Deserialize<'de> for $name {
fn deserialize<D>(deserializer: D) -> Result<$name, D::Error>
where
D: serde::Deserializer<'de>,
{
let s: String = serde::Deserialize::deserialize(deserializer)?;
if s == $value {
Ok($name)
} else {
Err(serde::de::Error::custom(format!(concat!(
"expect const string value \"",
$value,
"\""
))))
}
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for $name {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed(stringify!($name))
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
use serde_json::{Map, json};
let mut schema_map = Map::new();
schema_map.insert("type".to_string(), json!("string"));
schema_map.insert("format".to_string(), json!("const"));
schema_map.insert("const".to_string(), json!($value));
schemars::Schema::from(schema_map)
}
}
};
}
const_string!(JsonRpcVersion2_0 = "2.0");
// =============================================================================
// CORE PROTOCOL TYPES
// =============================================================================
/// Represents the MCP protocol version used for communication.
///
/// This ensures compatibility between clients and servers by specifying
/// which version of the Model Context Protocol is being used.
#[derive(Debug, Clone, Eq, PartialEq, Hash, PartialOrd)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ProtocolVersion(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_06_18: Self = Self(Cow::Borrowed("2025-06-18"));
pub const V_2025_03_26: Self = Self(Cow::Borrowed("2025-03-26"));
pub const V_2024_11_05: Self = Self(Cow::Borrowed("2024-11-05"));
pub const LATEST: Self = Self::V_2025_03_26;
}
impl Serialize for ProtocolVersion {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.0.serialize(serializer)
}
}
impl<'de> Deserialize<'de> for ProtocolVersion {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let s: String = Deserialize::deserialize(deserializer)?;
#[allow(clippy::single_match)]
match s.as_str() {
"2024-11-05" => return Ok(ProtocolVersion::V_2024_11_05),
"2025-03-26" => return Ok(ProtocolVersion::V_2025_03_26),
"2025-06-18" => return Ok(ProtocolVersion::V_2025_06_18),
_ => {}
}
Ok(ProtocolVersion(Cow::Owned(s)))
}
}
/// A flexible identifier type that can be either a number or a string.
///
/// This is commonly used for request IDs and other identifiers in JSON-RPC
/// where the specification allows both numeric and string values.
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub enum NumberOrString {
/// A numeric identifier
Number(i64),
/// A string identifier
String(Arc<str>),
}
impl NumberOrString {
pub fn into_json_value(self) -> Value {
match self {
NumberOrString::Number(n) => Value::Number(serde_json::Number::from(n)),
NumberOrString::String(s) => Value::String(s.to_string()),
}
}
}
impl std::fmt::Display for NumberOrString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
NumberOrString::Number(n) => n.fmt(f),
NumberOrString::String(s) => s.fmt(f),
}
}
}
impl Serialize for NumberOrString {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
NumberOrString::Number(n) => n.serialize(serializer),
NumberOrString::String(s) => s.serialize(serializer),
}
}
}
impl<'de> Deserialize<'de> for NumberOrString {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let value: Value = Deserialize::deserialize(deserializer)?;
match value {
Value::Number(n) => {
if let Some(i) = n.as_i64() {
Ok(NumberOrString::Number(i))
} else if let Some(u) = n.as_u64() {
// Handle large unsigned numbers that fit in i64
if u <= i64::MAX as u64 {
Ok(NumberOrString::Number(u as i64))
} else {
Err(serde::de::Error::custom("Number too large for i64"))
}
} else {
Err(serde::de::Error::custom("Expected an integer"))
}
}
Value::String(s) => Ok(NumberOrString::String(s.into())),
_ => Err(serde::de::Error::custom("Expect number or string")),
}
}
}
#[cfg(feature = "schemars")]
impl schemars::JsonSchema for NumberOrString {
fn schema_name() -> Cow<'static, str> {
Cow::Borrowed("NumberOrString")
}
fn json_schema(_: &mut schemars::SchemaGenerator) -> schemars::Schema {
use serde_json::{Map, json};
let mut number_schema = Map::new();
number_schema.insert("type".to_string(), json!("number"));
let mut string_schema = Map::new();
string_schema.insert("type".to_string(), json!("string"));
let mut schema_map = Map::new();
schema_map.insert("oneOf".to_string(), json!([number_schema, string_schema]));
schemars::Schema::from(schema_map)
}
}
/// Type alias for request identifiers used in JSON-RPC communication.
pub type RequestId = NumberOrString;
/// A token used to track the progress of long-running operations.
///
/// Progress tokens allow clients and servers to associate progress notifications
/// with specific requests, enabling real-time updates on operation status.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Hash, Eq)]
#[serde(transparent)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ProgressToken(pub NumberOrString);
// =============================================================================
// JSON-RPC MESSAGE STRUCTURES
// =============================================================================
/// Represents a JSON-RPC request with method, parameters, and extensions.
///
/// This is the core structure for all MCP requests, containing:
/// - `method`: The name of the method being called
/// - `params`: The parameters for the method
/// - `extensions`: Additional context data (similar to HTTP headers)
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Request<M = String, P = JsonObject> {
pub method: M,
pub params: P,
/// extensions will carry anything possible in the context, including [`Meta`]
///
/// this is similar with the Extensions in `http` crate
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
impl<M: Default, P> Request<M, P> {
pub fn new(params: P) -> Self {
Self {
method: Default::default(),
params,
extensions: Extensions::default(),
}
}
}
impl<M, P> GetExtensions for Request<M, P> {
fn extensions(&self) -> &Extensions {
&self.extensions
}
fn extensions_mut(&mut self) -> &mut Extensions {
&mut self.extensions
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct RequestOptionalParam<M = String, P = JsonObject> {
pub method: M,
// #[serde(skip_serializing_if = "Option::is_none")]
pub params: Option<P>,
/// extensions will carry anything possible in the context, including [`Meta`]
///
/// this is similar with the Extensions in `http` crate
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
impl<M: Default, P> RequestOptionalParam<M, P> {
pub fn with_param(params: P) -> Self {
Self {
method: Default::default(),
params: Some(params),
extensions: Extensions::default(),
}
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct RequestNoParam<M = String> {
pub method: M,
/// extensions will carry anything possible in the context, including [`Meta`]
///
/// this is similar with the Extensions in `http` crate
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
impl<M> GetExtensions for RequestNoParam<M> {
fn extensions(&self) -> &Extensions {
&self.extensions
}
fn extensions_mut(&mut self) -> &mut Extensions {
&mut self.extensions
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Notification<M = String, P = JsonObject> {
pub method: M,
pub params: P,
/// extensions will carry anything possible in the context, including [`Meta`]
///
/// this is similar with the Extensions in `http` crate
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
impl<M: Default, P> Notification<M, P> {
pub fn new(params: P) -> Self {
Self {
method: Default::default(),
params,
extensions: Extensions::default(),
}
}
}
#[derive(Debug, Clone, Default)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct NotificationNoParam<M = String> {
pub method: M,
/// extensions will carry anything possible in the context, including [`Meta`]
///
/// this is similar with the Extensions in `http` crate
#[cfg_attr(feature = "schemars", schemars(skip))]
pub extensions: Extensions,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct JsonRpcRequest<R = Request> {
pub jsonrpc: JsonRpcVersion2_0,
pub id: RequestId,
#[serde(flatten)]
pub request: R,
}
type DefaultResponse = JsonObject;
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct JsonRpcResponse<R = JsonObject> {
pub jsonrpc: JsonRpcVersion2_0,
pub id: RequestId,
pub result: R,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct JsonRpcError {
pub jsonrpc: JsonRpcVersion2_0,
pub id: RequestId,
pub error: ErrorData,
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct JsonRpcNotification<N = Notification> {
pub jsonrpc: JsonRpcVersion2_0,
#[serde(flatten)]
pub notification: N,
}
/// Standard JSON-RPC error codes used throughout the MCP protocol.
///
/// These codes follow the JSON-RPC 2.0 specification and provide
/// standardized error reporting across all MCP implementations.
#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
#[serde(transparent)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ErrorCode(pub i32);
impl ErrorCode {
pub const RESOURCE_NOT_FOUND: Self = Self(-32002);
pub const INVALID_REQUEST: Self = Self(-32600);
pub const METHOD_NOT_FOUND: Self = Self(-32601);
pub const INVALID_PARAMS: Self = Self(-32602);
pub const INTERNAL_ERROR: Self = Self(-32603);
pub const PARSE_ERROR: Self = Self(-32700);
}
/// Error information for JSON-RPC error responses.
///
/// This structure follows the JSON-RPC 2.0 specification for error reporting,
/// providing a standardized way to communicate errors between clients and servers.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ErrorData {
/// The error type that occurred (using standard JSON-RPC error codes)
pub code: ErrorCode,
/// A short description of the error. The message SHOULD be limited to a concise single sentence.
pub message: Cow<'static, str>,
/// Additional information about the error. The value of this member is defined by the
/// sender (e.g. detailed error information, nested errors etc.).
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<Value>,
}
impl ErrorData {
pub fn new(
code: ErrorCode,
message: impl Into<Cow<'static, str>>,
data: Option<Value>,
) -> Self {
Self {
code,
message: message.into(),
data,
}
}
pub fn resource_not_found(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::RESOURCE_NOT_FOUND, message, data)
}
pub fn parse_error(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::PARSE_ERROR, message, data)
}
pub fn invalid_request(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::INVALID_REQUEST, message, data)
}
pub fn method_not_found<M: ConstString>() -> Self {
Self::new(ErrorCode::METHOD_NOT_FOUND, M::VALUE, None)
}
pub fn invalid_params(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::INVALID_PARAMS, message, data)
}
pub fn internal_error(message: impl Into<Cow<'static, str>>, data: Option<Value>) -> Self {
Self::new(ErrorCode::INTERNAL_ERROR, message, data)
}
}
/// Represents any JSON-RPC message that can be sent or received.
///
/// This enum covers all possible message types in the JSON-RPC protocol:
/// individual requests/responses, notifications, batch operations, and errors.
/// It serves as the top-level message container for MCP communication.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(untagged)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum JsonRpcMessage<Req = Request, Resp = DefaultResponse, Noti = Notification> {
/// A single request expecting a response
Request(JsonRpcRequest<Req>),
/// A response to a previous request
Response(JsonRpcResponse<Resp>),
/// A one-way notification (no response expected)
Notification(JsonRpcNotification<Noti>),
/// An error response
Error(JsonRpcError),
}
impl<Req, Resp, Not> JsonRpcMessage<Req, Resp, Not> {
#[inline]
pub const fn request(request: Req, id: RequestId) -> Self {
JsonRpcMessage::Request(JsonRpcRequest {
jsonrpc: JsonRpcVersion2_0,
id,
request,
})
}
#[inline]
pub const fn response(response: Resp, id: RequestId) -> Self {
JsonRpcMessage::Response(JsonRpcResponse {
jsonrpc: JsonRpcVersion2_0,
id,
result: response,
})
}
#[inline]
pub const fn error(error: ErrorData, id: RequestId) -> Self {
JsonRpcMessage::Error(JsonRpcError {
jsonrpc: JsonRpcVersion2_0,
id,
error,
})
}
#[inline]
pub const fn notification(notification: Not) -> Self {
JsonRpcMessage::Notification(JsonRpcNotification {
jsonrpc: JsonRpcVersion2_0,
notification,
})
}
pub fn into_request(self) -> Option<(Req, RequestId)> {
match self {
JsonRpcMessage::Request(r) => Some((r.request, r.id)),
_ => None,
}
}
pub fn into_response(self) -> Option<(Resp, RequestId)> {
match self {
JsonRpcMessage::Response(r) => Some((r.result, r.id)),
_ => None,
}
}
pub fn into_notification(self) -> Option<Not> {
match self {
JsonRpcMessage::Notification(n) => Some(n.notification),
_ => None,
}
}
pub fn into_error(self) -> Option<(ErrorData, RequestId)> {
match self {
JsonRpcMessage::Error(e) => Some((e.error, e.id)),
_ => None,
}
}
pub fn into_result(self) -> Option<(Result<Resp, ErrorData>, RequestId)> {
match self {
JsonRpcMessage::Response(r) => Some((Ok(r.result), r.id)),
JsonRpcMessage::Error(e) => Some((Err(e.error), e.id)),
_ => None,
}
}
}
// =============================================================================
// INITIALIZATION AND CONNECTION SETUP
// =============================================================================
/// # Empty result
/// A response that indicates success but carries no data.
pub type EmptyResult = EmptyObject;
impl From<()> for EmptyResult {
fn from(_value: ()) -> Self {
EmptyResult {}
}
}
impl From<EmptyResult> for () {
fn from(_value: EmptyResult) {}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct CancelledNotificationParam {
pub request_id: RequestId,
pub reason: Option<String>,
}
const_string!(CancelledNotificationMethod = "notifications/cancelled");
/// # Cancellation
/// This notification can be sent by either side to indicate that it is cancelling a previously-issued request.
///
/// The request SHOULD still be in-flight, but due to communication latency, it is always possible that this notification MAY arrive after the request has already finished.
///
/// This notification indicates that the result will be unused, so any associated processing SHOULD cease.
///
/// A client MUST NOT attempt to cancel its `initialize` request.
pub type CancelledNotification =
Notification<CancelledNotificationMethod, CancelledNotificationParam>;
const_string!(InitializeResultMethod = "initialize");
/// # Initialization
/// This request is sent from the client to the server when it first connects, asking it to begin initialization.
pub type InitializeRequest = Request<InitializeResultMethod, InitializeRequestParam>;
const_string!(InitializedNotificationMethod = "notifications/initialized");
/// This notification is sent from the client to the server after initialization has finished.
pub type InitializedNotification = NotificationNoParam<InitializedNotificationMethod>;
/// Parameters sent by a client when initializing a connection to an MCP server.
///
/// This contains the client's protocol version, capabilities, and implementation
/// information, allowing the server to understand what the client supports.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct InitializeRequestParam {
/// The MCP protocol version this client supports
pub protocol_version: ProtocolVersion,
/// The capabilities this client supports (sampling, roots, etc.)
pub capabilities: ClientCapabilities,
/// Information about the client implementation
pub client_info: Implementation,
}
/// The server's response to an initialization request.
///
/// Contains the server's protocol version, capabilities, and implementation
/// information, along with optional instructions for the client.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct InitializeResult {
/// The MCP protocol version this server supports
pub protocol_version: ProtocolVersion,
/// The capabilities this server provides (tools, resources, prompts, etc.)
pub capabilities: ServerCapabilities,
/// Information about the server implementation
pub server_info: Implementation,
/// Optional human-readable instructions about using this server
#[serde(skip_serializing_if = "Option::is_none")]
pub instructions: Option<String>,
}
pub type ServerInfo = InitializeResult;
pub type ClientInfo = InitializeRequestParam;
impl Default for ServerInfo {
fn default() -> Self {
ServerInfo {
protocol_version: ProtocolVersion::default(),
capabilities: ServerCapabilities::default(),
server_info: Implementation::from_build_env(),
instructions: None,
}
}
}
impl Default for ClientInfo {
fn default() -> Self {
ClientInfo {
protocol_version: ProtocolVersion::default(),
capabilities: ClientCapabilities::default(),
client_info: Implementation::from_build_env(),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct Implementation {
pub name: String,
pub version: String,
}
impl Default for Implementation {
fn default() -> Self {
Self::from_build_env()
}
}
impl Implementation {
pub fn from_build_env() -> Self {
Implementation {
name: env!("CARGO_CRATE_NAME").to_owned(),
version: env!("CARGO_PKG_VERSION").to_owned(),
}
}
}
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct PaginatedRequestParam {
#[serde(skip_serializing_if = "Option::is_none")]
pub cursor: Option<String>,
}
// =============================================================================
// PROGRESS AND PAGINATION
// =============================================================================
const_string!(PingRequestMethod = "ping");
pub type PingRequest = RequestNoParam<PingRequestMethod>;
const_string!(ProgressNotificationMethod = "notifications/progress");
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ProgressNotificationParam {
pub progress_token: ProgressToken,
/// The progress thus far. This should increase every time progress is made, even if the total is unknown.
pub progress: f64,
/// Total number of items to process (or total progress required), if known
#[serde(skip_serializing_if = "Option::is_none")]
pub total: Option<f64>,
/// An optional message describing the current progress.
#[serde(skip_serializing_if = "Option::is_none")]
pub message: Option<String>,
}
pub type ProgressNotification = Notification<ProgressNotificationMethod, ProgressNotificationParam>;
pub type Cursor = String;
macro_rules! paginated_result {
($t:ident {
$i_item: ident: $t_item: ty
}) => {
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct $t {
#[serde(skip_serializing_if = "Option::is_none")]
pub next_cursor: Option<Cursor>,
pub $i_item: $t_item,
}
impl $t {
pub fn with_all_items(
items: $t_item,
) -> Self {
Self {
next_cursor: None,
$i_item: items,
}
}
}
};
}
// =============================================================================
// RESOURCE MANAGEMENT
// =============================================================================
const_string!(ListResourcesRequestMethod = "resources/list");
/// Request to list all available resources from a server
pub type ListResourcesRequest =
RequestOptionalParam<ListResourcesRequestMethod, PaginatedRequestParam>;
paginated_result!(ListResourcesResult {
resources: Vec<Resource>
});
const_string!(ListResourceTemplatesRequestMethod = "resources/templates/list");
/// Request to list all available resource templates from a server
pub type ListResourceTemplatesRequest =
RequestOptionalParam<ListResourceTemplatesRequestMethod, PaginatedRequestParam>;
paginated_result!(ListResourceTemplatesResult {
resource_templates: Vec<ResourceTemplate>
});
const_string!(ReadResourceRequestMethod = "resources/read");
/// Parameters for reading a specific resource
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ReadResourceRequestParam {
/// The URI of the resource to read
pub uri: String,
}
/// Result containing the contents of a read resource
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ReadResourceResult {
/// The actual content of the resource
pub contents: Vec<ResourceContents>,
}
/// Request to read a specific resource
pub type ReadResourceRequest = Request<ReadResourceRequestMethod, ReadResourceRequestParam>;
const_string!(ResourceListChangedNotificationMethod = "notifications/resources/list_changed");
/// Notification sent when the list of available resources changes
pub type ResourceListChangedNotification =
NotificationNoParam<ResourceListChangedNotificationMethod>;
const_string!(SubscribeRequestMethod = "resources/subscribe");
/// Parameters for subscribing to resource updates
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SubscribeRequestParam {
/// The URI of the resource to subscribe to
pub uri: String,
}
/// Request to subscribe to resource updates
pub type SubscribeRequest = Request<SubscribeRequestMethod, SubscribeRequestParam>;
const_string!(UnsubscribeRequestMethod = "resources/unsubscribe");
/// Parameters for unsubscribing from resource updates
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct UnsubscribeRequestParam {
/// The URI of the resource to unsubscribe from
pub uri: String,
}
/// Request to unsubscribe from resource updates
pub type UnsubscribeRequest = Request<UnsubscribeRequestMethod, UnsubscribeRequestParam>;
const_string!(ResourceUpdatedNotificationMethod = "notifications/resources/updated");
/// Parameters for a resource update notification
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct ResourceUpdatedNotificationParam {
/// The URI of the resource that was updated
pub uri: String,
}
/// Notification sent when a subscribed resource is updated
pub type ResourceUpdatedNotification =
Notification<ResourceUpdatedNotificationMethod, ResourceUpdatedNotificationParam>;
// =============================================================================
// PROMPT MANAGEMENT
// =============================================================================
const_string!(ListPromptsRequestMethod = "prompts/list");
/// Request to list all available prompts from a server
pub type ListPromptsRequest = RequestOptionalParam<ListPromptsRequestMethod, PaginatedRequestParam>;
paginated_result!(ListPromptsResult {
prompts: Vec<Prompt>
});
const_string!(GetPromptRequestMethod = "prompts/get");
/// Parameters for retrieving a specific prompt
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct GetPromptRequestParam {
pub name: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub arguments: Option<JsonObject>,
}
/// Request to get a specific prompt
pub type GetPromptRequest = Request<GetPromptRequestMethod, GetPromptRequestParam>;
const_string!(PromptListChangedNotificationMethod = "notifications/prompts/list_changed");
/// Notification sent when the list of available prompts changes
pub type PromptListChangedNotification = NotificationNoParam<PromptListChangedNotificationMethod>;
const_string!(ToolListChangedNotificationMethod = "notifications/tools/list_changed");
/// Notification sent when the list of available tools changes
pub type ToolListChangedNotification = NotificationNoParam<ToolListChangedNotificationMethod>;
// =============================================================================
// LOGGING
// =============================================================================
/// Logging levels supported by the MCP protocol
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Copy)]
#[serde(rename_all = "lowercase")] //match spec
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum LoggingLevel {
Debug,
Info,
Notice,
Warning,
Error,
Critical,
Alert,
Emergency,
}
const_string!(SetLevelRequestMethod = "logging/setLevel");
/// Parameters for setting the logging level
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SetLevelRequestParam {
/// The desired logging level
pub level: LoggingLevel,
}
/// Request to set the logging level
pub type SetLevelRequest = Request<SetLevelRequestMethod, SetLevelRequestParam>;
const_string!(LoggingMessageNotificationMethod = "notifications/message");
/// Parameters for a logging message notification
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct LoggingMessageNotificationParam {
/// The severity level of this log message
pub level: LoggingLevel,
/// Optional logger name that generated this message
#[serde(skip_serializing_if = "Option::is_none")]
pub logger: Option<String>,
/// The actual log data
pub data: Value,
}
/// Notification containing a log message
pub type LoggingMessageNotification =
Notification<LoggingMessageNotificationMethod, LoggingMessageNotificationParam>;
// =============================================================================
// SAMPLING (LLM INTERACTION)
// =============================================================================
const_string!(CreateMessageRequestMethod = "sampling/createMessage");
pub type CreateMessageRequest = Request<CreateMessageRequestMethod, CreateMessageRequestParam>;
/// Represents the role of a participant in a conversation or message exchange.
///
/// Used in sampling and chat contexts to distinguish between different
/// types of message senders in the conversation flow.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum Role {
/// A human user or client making a request
User,
/// An AI assistant or server providing a response
Assistant,
}
/// A message in a sampling conversation, containing a role and content.
///
/// This represents a single message in a conversation flow, used primarily
/// in LLM sampling requests where the conversation history is important
/// for generating appropriate responses.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub struct SamplingMessage {
/// The role of the message sender (User or Assistant)
pub role: Role,
/// The actual content of the message (text, image, etc.)
pub content: Content,
}
/// Specifies how much context should be included in sampling requests.
///
/// This allows clients to control what additional context information
/// should be provided to the LLM when processing sampling requests.
#[derive(Debug, Serialize, Deserialize, Clone, PartialEq)]
#[cfg_attr(feature = "schemars", derive(schemars::JsonSchema))]
pub enum ContextInclusion {
/// Include context from all connected MCP servers
#[serde(rename = "allServers")]
AllServers,
/// Include no additional context
#[serde(rename = "none")]
None,
/// Include context only from the requesting server
#[serde(rename = "thisServer")]
ThisServer,
}
/// Parameters for creating a message through LLM sampling.
///
/// This structure contains all the necessary information for a client to
/// generate an LLM response, including conversation history, model preferences,