1use crate::generated_schema::*;
2use serde::ser::SerializeStruct;
3use serde_json::{json, Value};
4use std::hash::{Hash, Hasher};
5use std::result;
6use std::{fmt::Display, str::FromStr};
7
8#[derive(Debug, PartialEq)]
9pub enum MessageTypes {
10 Request,
11 Response,
12 Notification,
13 Error,
14}
15impl Display for MessageTypes {
18 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20 write!(
21 f,
22 "{}",
23 match self {
25 MessageTypes::Request => "Request",
26 MessageTypes::Response => "Response",
27 MessageTypes::Notification => "Notification",
28 MessageTypes::Error => "Error",
29 }
30 )
31 }
32}
33
34#[allow(dead_code)]
37fn detect_message_type(value: &serde_json::Value) -> MessageTypes {
38 let id_field = value.get("id");
39
40 if id_field.is_some() && value.get("error").is_some() {
41 return MessageTypes::Error;
42 }
43
44 let method_field = value.get("method");
45 let result_field = value.get("result");
46
47 if id_field.is_some() {
48 if result_field.is_some() && method_field.is_none() {
49 return MessageTypes::Response;
50 } else if method_field.is_some() {
51 return MessageTypes::Request;
52 }
53 } else if method_field.is_some() {
54 return MessageTypes::Notification;
55 }
56
57 MessageTypes::Request
58}
59
60pub trait RPCMessage: MCPMessage {
63 fn request_id(&self) -> Option<&RequestId>;
64 fn jsonrpc(&self) -> &str;
65}
66
67pub trait MCPMessage {
68 fn is_response(&self) -> bool;
69 fn is_request(&self) -> bool;
70 fn is_notification(&self) -> bool;
71 fn is_error(&self) -> bool;
72 fn message_type(&self) -> MessageTypes;
73}
74
75pub trait FromMessage<T>
81where
82 Self: Sized,
83{
84 fn from_message(message: T, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError>;
85}
86
87pub trait ToMessage<T>
88where
89 T: FromMessage<Self>,
90 Self: Sized,
91{
92 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<T, JsonrpcErrorError>;
93}
94
95impl PartialEq for RequestId {
101 fn eq(&self, other: &Self) -> bool {
102 match (self, other) {
103 (RequestId::String(a), RequestId::String(b)) => a == b,
104 (RequestId::Integer(a), RequestId::Integer(b)) => a == b,
105 _ => false, }
107 }
108}
109
110impl Eq for RequestId {}
111
112impl Hash for RequestId {
114 fn hash<H: Hasher>(&self, state: &mut H) {
115 match self {
116 RequestId::String(s) => {
117 0u8.hash(state); s.hash(state);
119 }
120 RequestId::Integer(i) => {
121 1u8.hash(state); i.hash(state);
123 }
124 }
125 }
126}
127
128#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
135#[serde(untagged)]
136pub enum ClientMessage {
137 Request(ClientJsonrpcRequest),
138 Notification(ClientJsonrpcNotification),
139 Response(ClientJsonrpcResponse),
140 Error(JsonrpcError),
141}
142
143impl ClientMessage {
144 pub fn as_response(self) -> std::result::Result<ClientJsonrpcResponse, JsonrpcErrorError> {
154 if let Self::Response(response) = self {
155 Ok(response)
156 } else {
157 Err(JsonrpcErrorError::internal_error().with_message(format!(
158 "Invalid message type, expected: \"{}\" received\"{}\"",
159 MessageTypes::Response,
160 self.message_type()
161 )))
162 }
163 }
164
165 pub fn as_request(self) -> std::result::Result<ClientJsonrpcRequest, JsonrpcErrorError> {
175 if let Self::Request(request) = self {
176 Ok(request)
177 } else {
178 Err(JsonrpcErrorError::internal_error().with_message(format!(
179 "Invalid message type, expected: \"{}\" received\"{}\"",
180 MessageTypes::Request,
181 self.message_type()
182 )))
183 }
184 }
185
186 pub fn as_notification(self) -> std::result::Result<ClientJsonrpcNotification, JsonrpcErrorError> {
196 if let Self::Notification(notification) = self {
197 Ok(notification)
198 } else {
199 Err(JsonrpcErrorError::internal_error().with_message(format!(
200 "Invalid message type, expected: \"{}\" received\"{}\"",
201 MessageTypes::Notification,
202 self.message_type()
203 )))
204 }
205 }
206
207 pub fn as_error(self) -> std::result::Result<JsonrpcError, JsonrpcErrorError> {
217 if let Self::Error(error) = self {
218 Ok(error)
219 } else {
220 Err(JsonrpcErrorError::internal_error().with_message(format!(
221 "Invalid message type, expected: \"{}\" received\"{}\"",
222 MessageTypes::Error,
223 self.message_type()
224 )))
225 }
226 }
227}
228
229impl RPCMessage for ClientMessage {
230 fn request_id(&self) -> Option<&RequestId> {
232 match self {
233 ClientMessage::Request(client_jsonrpc_request) => Some(&client_jsonrpc_request.id),
235 ClientMessage::Notification(_) => None,
237 ClientMessage::Response(client_jsonrpc_response) => Some(&client_jsonrpc_response.id),
239 ClientMessage::Error(jsonrpc_error) => Some(&jsonrpc_error.id),
241 }
242 }
243
244 fn jsonrpc(&self) -> &str {
245 match self {
246 ClientMessage::Request(client_jsonrpc_request) => client_jsonrpc_request.jsonrpc(),
247 ClientMessage::Notification(notification) => notification.jsonrpc(),
248 ClientMessage::Response(client_jsonrpc_response) => client_jsonrpc_response.jsonrpc(),
249 ClientMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
250 }
251 }
252}
253
254impl MCPMessage for ClientMessage {
256 fn is_response(&self) -> bool {
258 matches!(self, ClientMessage::Response(_))
259 }
260
261 fn is_request(&self) -> bool {
263 matches!(self, ClientMessage::Request(_))
264 }
265
266 fn is_notification(&self) -> bool {
268 matches!(self, ClientMessage::Notification(_))
269 }
270
271 fn is_error(&self) -> bool {
273 matches!(self, ClientMessage::Error(_))
274 }
275
276 fn message_type(&self) -> MessageTypes {
278 match self {
279 ClientMessage::Request(_) => MessageTypes::Request,
280 ClientMessage::Notification(_) => MessageTypes::Notification,
281 ClientMessage::Response(_) => MessageTypes::Response,
282 ClientMessage::Error(_) => MessageTypes::Error,
283 }
284 }
285}
286
287#[derive(Clone, Debug)]
293pub struct ClientJsonrpcRequest {
294 pub id: RequestId,
295 jsonrpc: ::std::string::String,
296 pub method: String,
297 pub request: RequestFromClient,
298}
299
300impl ClientJsonrpcRequest {
301 pub fn new(id: RequestId, request: RequestFromClient) -> Self {
302 let method = request.method().to_string();
303 Self {
304 id,
305 jsonrpc: JSONRPC_VERSION.to_string(),
306 method,
307 request,
308 }
309 }
310 pub fn jsonrpc(&self) -> &::std::string::String {
311 &self.jsonrpc
312 }
313}
314
315impl Display for ClientJsonrpcRequest {
317 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318 write!(
319 f,
320 "{}",
321 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
322 )
323 }
324}
325
326impl FromStr for ClientJsonrpcRequest {
327 type Err = JsonrpcErrorError;
328
329 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
351 serde_json::from_str(s)
352 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
353 }
354}
355
356#[derive(::serde::Serialize, Clone, Debug)]
363#[serde(untagged)]
364pub enum RequestFromClient {
365 ClientRequest(ClientRequest),
366 CustomRequest(serde_json::Value),
367}
368
369impl TryFrom<RequestFromClient> for ClientRequest {
370 type Error = JsonrpcErrorError;
371 fn try_from(value: RequestFromClient) -> result::Result<Self, Self::Error> {
372 if let RequestFromClient::ClientRequest(client_request) = value {
373 Ok(client_request)
374 } else {
375 Err(JsonrpcErrorError::internal_error().with_message("Not a ClientRequest".to_string()))
376 }
377 }
378}
379
380impl RequestFromClient {
381 #[deprecated(since = "0.1.4", note = "Use `method()` instead.")]
382 pub fn get_method(&self) -> &str {
383 match self {
384 RequestFromClient::ClientRequest(request) => request.method(),
385 RequestFromClient::CustomRequest(request) => request["method"].as_str().unwrap(),
386 }
387 }
388
389 pub fn method(&self) -> &str {
390 match self {
391 RequestFromClient::ClientRequest(request) => request.method(),
392 RequestFromClient::CustomRequest(request) => request["method"].as_str().unwrap(),
393 }
394 }
395}
396
397impl From<ClientRequest> for RequestFromClient {
398 fn from(value: ClientRequest) -> Self {
399 Self::ClientRequest(value)
400 }
401}
402
403impl From<serde_json::Value> for RequestFromClient {
404 fn from(value: serde_json::Value) -> Self {
405 Self::CustomRequest(value)
406 }
407}
408
409impl<'de> serde::Deserialize<'de> for RequestFromClient {
410 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
411 where
412 D: serde::Deserializer<'de>,
413 {
414 let raw_value = Value::deserialize(deserializer)?;
415
416 let client_result = ClientRequest::deserialize(&raw_value);
417
418 match client_result {
419 Ok(client_request) => Ok(Self::ClientRequest(client_request)),
420 Err(_) => Ok(Self::CustomRequest(raw_value)),
421 }
422 }
423}
424
425#[derive(Clone, Debug)]
431pub struct ClientJsonrpcNotification {
432 jsonrpc: ::std::string::String,
433 pub method: ::std::string::String,
434 pub notification: NotificationFromClient,
435}
436
437impl ClientJsonrpcNotification {
438 pub fn new(notification: NotificationFromClient) -> Self {
439 let method = notification.method().to_string();
440 Self {
441 jsonrpc: JSONRPC_VERSION.to_string(),
442 method,
443 notification,
444 }
445 }
446 pub fn jsonrpc(&self) -> &::std::string::String {
447 &self.jsonrpc
448 }
449}
450
451impl Display for ClientJsonrpcNotification {
453 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
454 write!(
455 f,
456 "{}",
457 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
458 )
459 }
460}
461
462impl FromStr for ClientJsonrpcNotification {
463 type Err = JsonrpcErrorError;
464
465 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
466 serde_json::from_str(s)
467 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
468 }
469}
470
471#[derive(::serde::Serialize, Clone, Debug)]
478#[serde(untagged)]
479pub enum NotificationFromClient {
480 ClientNotification(ClientNotification),
481 CustomNotification(serde_json::Value),
482}
483
484impl TryFrom<NotificationFromClient> for ClientNotification {
485 type Error = JsonrpcErrorError;
486 fn try_from(value: NotificationFromClient) -> result::Result<Self, Self::Error> {
487 if let NotificationFromClient::ClientNotification(client_notification) = value {
488 Ok(client_notification)
489 } else {
490 Err(JsonrpcErrorError::internal_error().with_message("Not a ClientNotification".to_string()))
491 }
492 }
493}
494
495impl NotificationFromClient {
496 pub fn is_initialized_notification(&self) -> bool {
498 matches!(
499 self,
500 NotificationFromClient::ClientNotification(ClientNotification::InitializedNotification(_))
501 )
502 }
503
504 #[deprecated(since = "0.1.4", note = "Use `method()` instead.")]
505 pub fn get_method(&self) -> &str {
506 match self {
507 NotificationFromClient::ClientNotification(notification) => notification.method(),
508 NotificationFromClient::CustomNotification(notification) => notification["method"].as_str().unwrap(),
509 }
510 }
511
512 fn method(&self) -> &str {
513 match self {
514 NotificationFromClient::ClientNotification(notification) => notification.method(),
515 NotificationFromClient::CustomNotification(notification) => notification["method"].as_str().unwrap(),
516 }
517 }
518}
519
520impl<'de> serde::Deserialize<'de> for NotificationFromClient {
521 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
522 where
523 D: serde::Deserializer<'de>,
524 {
525 let raw_value = Value::deserialize(deserializer)?;
526
527 let result = ClientNotification::deserialize(&raw_value);
528
529 match result {
530 Ok(client_notification) => Ok(Self::ClientNotification(client_notification)),
531 Err(_) => Ok(Self::CustomNotification(raw_value)),
532 }
533 }
534}
535
536#[derive(Clone, Debug)]
542pub struct ClientJsonrpcResponse {
543 pub id: RequestId,
544 jsonrpc: ::std::string::String,
545 pub result: ResultFromClient,
546}
547
548impl ClientJsonrpcResponse {
549 pub fn new(id: RequestId, result: ResultFromClient) -> Self {
550 Self {
551 id,
552 jsonrpc: JSONRPC_VERSION.to_string(),
553 result,
554 }
555 }
556 pub fn jsonrpc(&self) -> &::std::string::String {
557 &self.jsonrpc
558 }
559}
560
561impl Display for ClientJsonrpcResponse {
563 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
564 write!(
565 f,
566 "{}",
567 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
568 )
569 }
570}
571
572impl FromStr for ClientJsonrpcResponse {
573 type Err = JsonrpcErrorError;
574
575 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
576 serde_json::from_str(s)
577 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
578 }
579}
580#[derive(::serde::Serialize, Clone, Debug)]
587#[serde(untagged)]
588pub enum ResultFromClient {
589 ClientResult(ClientResult),
590 CustomResult(serde_json::Value),
591}
592
593impl TryFrom<ResultFromClient> for ClientResult {
594 type Error = JsonrpcErrorError;
595 fn try_from(value: ResultFromClient) -> result::Result<Self, Self::Error> {
596 if let ResultFromClient::ClientResult(client_result) = value {
597 Ok(client_result)
598 } else {
599 Err(JsonrpcErrorError::internal_error().with_message("Not a ClientResult".to_string()))
600 }
601 }
602}
603
604impl From<ClientResult> for ResultFromClient {
605 fn from(value: ClientResult) -> Self {
606 Self::ClientResult(value)
607 }
608}
609
610impl From<serde_json::Value> for ResultFromClient {
611 fn from(value: serde_json::Value) -> Self {
612 Self::CustomResult(value)
613 }
614}
615
616impl<'de> serde::Deserialize<'de> for ResultFromClient {
617 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
618 where
619 D: serde::Deserializer<'de>,
620 {
621 let raw_value = Value::deserialize(deserializer)?;
622
623 let result = ClientResult::deserialize(&raw_value);
624
625 match result {
626 Ok(client_result) => Ok(Self::ClientResult(client_result)),
627 Err(_) => Ok(Self::CustomResult(raw_value)),
628 }
629 }
630}
631
632impl FromStr for ClientMessage {
637 type Err = JsonrpcErrorError;
638
639 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
640 serde_json::from_str(s)
641 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
642 }
643}
644
645impl Display for ClientMessage {
646 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
647 write!(
648 f,
649 "{}",
650 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
651 )
652 }
653}
654
655#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
662#[serde(untagged)]
663pub enum ServerMessage {
664 Request(ServerJsonrpcRequest),
665 Notification(ServerJsonrpcNotification),
666 Response(ServerJsonrpcResponse),
667 Error(JsonrpcError),
668}
669
670impl ServerMessage {
671 pub fn as_response(self) -> std::result::Result<ServerJsonrpcResponse, JsonrpcErrorError> {
681 if let Self::Response(response) = self {
682 Ok(response)
683 } else {
684 Err(JsonrpcErrorError::internal_error().with_message(format!(
685 "Invalid message type, expected: \"{}\" received\"{}\"",
686 MessageTypes::Response,
687 self.message_type()
688 )))
689 }
690 }
691
692 pub fn as_request(self) -> std::result::Result<ServerJsonrpcRequest, JsonrpcErrorError> {
702 if let Self::Request(request) = self {
703 Ok(request)
704 } else {
705 Err(JsonrpcErrorError::internal_error().with_message(format!(
706 "Invalid message type, expected: \"{}\" received\"{}\"",
707 MessageTypes::Request,
708 self.message_type()
709 )))
710 }
711 }
712
713 pub fn as_notification(self) -> std::result::Result<ServerJsonrpcNotification, JsonrpcErrorError> {
723 if let Self::Notification(notification) = self {
724 Ok(notification)
725 } else {
726 Err(JsonrpcErrorError::internal_error().with_message(format!(
727 "Invalid message type, expected: \"{}\" received\"{}\"",
728 MessageTypes::Notification,
729 self.message_type()
730 )))
731 }
732 }
733
734 pub fn as_error(self) -> std::result::Result<JsonrpcError, JsonrpcErrorError> {
744 if let Self::Error(error) = self {
745 Ok(error)
746 } else {
747 Err(JsonrpcErrorError::internal_error().with_message(format!(
748 "Invalid message type, expected: \"{}\" received\"{}\"",
749 MessageTypes::Error,
750 self.message_type()
751 )))
752 }
753 }
754}
755
756impl RPCMessage for ServerMessage {
757 fn request_id(&self) -> Option<&RequestId> {
759 match self {
760 ServerMessage::Request(server_jsonrpc_request) => Some(&server_jsonrpc_request.id),
762 ServerMessage::Notification(_) => None,
764 ServerMessage::Response(server_jsonrpc_response) => Some(&server_jsonrpc_response.id),
766 ServerMessage::Error(jsonrpc_error) => Some(&jsonrpc_error.id),
768 }
769 }
770
771 fn jsonrpc(&self) -> &str {
772 match self {
773 ServerMessage::Request(server_jsonrpc_request) => server_jsonrpc_request.jsonrpc(),
775 ServerMessage::Notification(notification) => notification.jsonrpc(),
777 ServerMessage::Response(server_jsonrpc_response) => server_jsonrpc_response.jsonrpc(),
779 ServerMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
781 }
782 }
783}
784
785impl MCPMessage for ServerMessage {
787 fn is_response(&self) -> bool {
789 matches!(self, ServerMessage::Response(_))
790 }
791
792 fn is_request(&self) -> bool {
794 matches!(self, ServerMessage::Request(_))
795 }
796
797 fn is_notification(&self) -> bool {
799 matches!(self, ServerMessage::Notification(_))
800 }
801
802 fn is_error(&self) -> bool {
804 matches!(self, ServerMessage::Error(_))
805 }
806
807 fn message_type(&self) -> MessageTypes {
809 match self {
810 ServerMessage::Request(_) => MessageTypes::Request,
811 ServerMessage::Notification(_) => MessageTypes::Notification,
812 ServerMessage::Response(_) => MessageTypes::Response,
813 ServerMessage::Error(_) => MessageTypes::Error,
814 }
815 }
816}
817
818impl FromStr for ServerMessage {
819 type Err = JsonrpcErrorError;
820
821 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
822 serde_json::from_str(s)
823 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
824 }
825}
826
827impl Display for ServerMessage {
828 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
829 write!(
830 f,
831 "{}",
832 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
833 )
834 }
835}
836
837#[derive(Clone, Debug)]
843pub struct ServerJsonrpcRequest {
844 pub id: RequestId,
845 jsonrpc: ::std::string::String,
846 pub method: String,
847 pub request: RequestFromServer,
848}
849
850impl ServerJsonrpcRequest {
851 pub fn new(id: RequestId, request: RequestFromServer) -> Self {
852 let method = request.method().to_string();
853 Self {
854 id,
855 jsonrpc: JSONRPC_VERSION.to_string(),
856 method,
857 request,
858 }
859 }
860 pub fn jsonrpc(&self) -> &::std::string::String {
861 &self.jsonrpc
862 }
863}
864
865impl Display for ServerJsonrpcRequest {
867 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
868 write!(
869 f,
870 "{}",
871 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
872 )
873 }
874}
875
876impl FromStr for ServerJsonrpcRequest {
877 type Err = JsonrpcErrorError;
878
879 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
880 serde_json::from_str(s)
881 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
882 }
883}
884#[derive(::serde::Serialize, Clone, Debug)]
891#[serde(untagged)]
892pub enum RequestFromServer {
893 ServerRequest(ServerRequest),
894 CustomRequest(serde_json::Value),
895}
896
897impl TryFrom<RequestFromServer> for ServerRequest {
898 type Error = JsonrpcErrorError;
899 fn try_from(value: RequestFromServer) -> result::Result<Self, Self::Error> {
900 if let RequestFromServer::ServerRequest(server_request) = value {
901 Ok(server_request)
902 } else {
903 Err(JsonrpcErrorError::internal_error().with_message("Not a ServerRequest".to_string()))
904 }
905 }
906}
907
908impl RequestFromServer {
909 #[deprecated(since = "0.1.4", note = "Use `method()` instead.")]
910 pub fn get_method(&self) -> &str {
911 match self {
912 RequestFromServer::ServerRequest(request) => request.method(),
913 RequestFromServer::CustomRequest(request) => request["method"].as_str().unwrap(),
914 }
915 }
916
917 pub fn method(&self) -> &str {
918 match self {
919 RequestFromServer::ServerRequest(request) => request.method(),
920 RequestFromServer::CustomRequest(request) => request["method"].as_str().unwrap(),
921 }
922 }
923}
924
925impl From<ServerRequest> for RequestFromServer {
926 fn from(value: ServerRequest) -> Self {
927 Self::ServerRequest(value)
928 }
929}
930
931impl From<serde_json::Value> for RequestFromServer {
932 fn from(value: serde_json::Value) -> Self {
933 Self::CustomRequest(value)
934 }
935}
936
937impl<'de> serde::Deserialize<'de> for RequestFromServer {
938 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
939 where
940 D: serde::Deserializer<'de>,
941 {
942 let raw_value = Value::deserialize(deserializer)?;
943
944 let server_result = ServerRequest::deserialize(&raw_value);
945
946 match server_result {
947 Ok(server_request) => Ok(Self::ServerRequest(server_request)),
948 Err(_) => Ok(Self::CustomRequest(raw_value)),
949 }
950 }
951}
952
953#[derive(Clone, Debug)]
959pub struct ServerJsonrpcNotification {
960 jsonrpc: ::std::string::String,
961 pub method: ::std::string::String,
962 pub notification: NotificationFromServer,
963}
964
965impl ServerJsonrpcNotification {
966 pub fn new(notification: NotificationFromServer) -> Self {
967 let method = notification.method().to_string();
968 Self {
969 jsonrpc: JSONRPC_VERSION.to_string(),
970 method,
971 notification,
972 }
973 }
974 pub fn jsonrpc(&self) -> &::std::string::String {
975 &self.jsonrpc
976 }
977}
978
979impl Display for ServerJsonrpcNotification {
981 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
982 write!(
983 f,
984 "{}",
985 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
986 )
987 }
988}
989
990impl FromStr for ServerJsonrpcNotification {
991 type Err = JsonrpcErrorError;
992
993 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
994 serde_json::from_str(s)
995 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
996 }
997}
998#[derive(::serde::Serialize, Clone, Debug)]
1005#[serde(untagged)]
1006pub enum NotificationFromServer {
1007 ServerNotification(ServerNotification),
1008 CustomNotification(serde_json::Value),
1009}
1010
1011impl TryFrom<NotificationFromServer> for ServerNotification {
1012 type Error = JsonrpcErrorError;
1013 fn try_from(value: NotificationFromServer) -> result::Result<Self, Self::Error> {
1014 if let NotificationFromServer::ServerNotification(server_notification) = value {
1015 Ok(server_notification)
1016 } else {
1017 Err(JsonrpcErrorError::internal_error().with_message("Not a ServerNotification".to_string()))
1018 }
1019 }
1020}
1021
1022impl NotificationFromServer {
1023 #[deprecated(since = "0.1.4", note = "Use `method()` instead.")]
1024 pub fn get_method(&self) -> &str {
1025 match self {
1026 NotificationFromServer::ServerNotification(notification) => notification.method(),
1027 NotificationFromServer::CustomNotification(notification) => notification["method"].as_str().unwrap(),
1028 }
1029 }
1030
1031 pub fn method(&self) -> &str {
1032 match self {
1033 NotificationFromServer::ServerNotification(notification) => notification.method(),
1034 NotificationFromServer::CustomNotification(notification) => notification["method"].as_str().unwrap(),
1035 }
1036 }
1037}
1038
1039impl<'de> serde::Deserialize<'de> for NotificationFromServer {
1040 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
1041 where
1042 D: serde::Deserializer<'de>,
1043 {
1044 let raw_value = Value::deserialize(deserializer)?;
1045
1046 let result = ServerNotification::deserialize(&raw_value);
1047
1048 match result {
1049 Ok(client_notification) => Ok(Self::ServerNotification(client_notification)),
1050 Err(_) => Ok(Self::CustomNotification(raw_value)),
1051 }
1052 }
1053}
1054
1055#[derive(Clone, Debug)]
1061pub struct ServerJsonrpcResponse {
1062 pub id: RequestId,
1063 jsonrpc: ::std::string::String,
1064 pub result: ResultFromServer,
1065}
1066
1067impl ServerJsonrpcResponse {
1068 pub fn new(id: RequestId, result: ResultFromServer) -> Self {
1069 Self {
1070 id,
1071 jsonrpc: JSONRPC_VERSION.to_string(),
1072 result,
1073 }
1074 }
1075 pub fn jsonrpc(&self) -> &::std::string::String {
1076 &self.jsonrpc
1077 }
1078}
1079
1080impl Display for ServerJsonrpcResponse {
1082 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1083 write!(
1084 f,
1085 "{}",
1086 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
1087 )
1088 }
1089}
1090
1091impl FromStr for ServerJsonrpcResponse {
1092 type Err = JsonrpcErrorError;
1093
1094 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1095 serde_json::from_str(s)
1096 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1097 }
1098}
1099#[derive(::serde::Serialize, Clone, Debug)]
1106#[serde(untagged)]
1107pub enum ResultFromServer {
1108 ServerResult(ServerResult),
1109 CustomResult(serde_json::Value),
1110}
1111
1112impl TryFrom<ResultFromServer> for ServerResult {
1113 type Error = JsonrpcErrorError;
1114 fn try_from(value: ResultFromServer) -> result::Result<Self, Self::Error> {
1115 if let ResultFromServer::ServerResult(server_result) = value {
1116 Ok(server_result)
1117 } else {
1118 Err(JsonrpcErrorError::internal_error().with_message("Not a ServerResult".to_string()))
1119 }
1120 }
1121}
1122
1123impl From<ServerResult> for ResultFromServer {
1124 fn from(value: ServerResult) -> Self {
1125 Self::ServerResult(value)
1126 }
1127}
1128
1129impl From<serde_json::Value> for ResultFromServer {
1130 fn from(value: serde_json::Value) -> Self {
1131 Self::CustomResult(value)
1132 }
1133}
1134
1135impl<'de> serde::Deserialize<'de> for ResultFromServer {
1136 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
1137 where
1138 D: serde::Deserializer<'de>,
1139 {
1140 let raw_value = Value::deserialize(deserializer)?;
1141
1142 let result = ServerResult::deserialize(&raw_value);
1143
1144 match result {
1145 Ok(server_result) => {
1146 if matches!(server_result, ServerResult::Result(_)) {
1147 Ok(Self::CustomResult(raw_value))
1148 } else {
1149 Ok(Self::ServerResult(server_result))
1150 }
1151 }
1152 Err(_) => Ok(Self::CustomResult(raw_value)),
1153 }
1154 }
1155}
1156
1157impl Display for JsonrpcError {
1163 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1164 write!(
1165 f,
1166 "{}",
1167 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
1168 )
1169 }
1170}
1171
1172impl FromStr for JsonrpcError {
1173 type Err = JsonrpcErrorError;
1174
1175 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1176 serde_json::from_str(s)
1177 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1178 }
1179}
1180
1181#[derive(::serde::Serialize, Clone, Debug)]
1190#[serde(untagged)]
1191pub enum MessageFromServer {
1192 RequestFromServer(RequestFromServer),
1193 ResultFromServer(ResultFromServer),
1194 NotificationFromServer(NotificationFromServer),
1195 Error(JsonrpcErrorError),
1196}
1197
1198impl From<RequestFromServer> for MessageFromServer {
1199 fn from(value: RequestFromServer) -> Self {
1200 Self::RequestFromServer(value)
1201 }
1202}
1203
1204impl From<ResultFromServer> for MessageFromServer {
1205 fn from(value: ResultFromServer) -> Self {
1206 Self::ResultFromServer(value)
1207 }
1208}
1209
1210impl From<NotificationFromServer> for MessageFromServer {
1211 fn from(value: NotificationFromServer) -> Self {
1212 Self::NotificationFromServer(value)
1213 }
1214}
1215
1216impl From<JsonrpcErrorError> for MessageFromServer {
1217 fn from(value: JsonrpcErrorError) -> Self {
1218 Self::Error(value)
1219 }
1220}
1221
1222impl MCPMessage for MessageFromServer {
1223 fn is_response(&self) -> bool {
1224 matches!(self, MessageFromServer::ResultFromServer(_))
1225 }
1226
1227 fn is_request(&self) -> bool {
1228 matches!(self, MessageFromServer::RequestFromServer(_))
1229 }
1230
1231 fn is_notification(&self) -> bool {
1232 matches!(self, MessageFromServer::NotificationFromServer(_))
1233 }
1234
1235 fn is_error(&self) -> bool {
1236 matches!(self, MessageFromServer::Error(_))
1237 }
1238
1239 fn message_type(&self) -> MessageTypes {
1240 match self {
1241 MessageFromServer::RequestFromServer(_) => MessageTypes::Request,
1242 MessageFromServer::ResultFromServer(_) => MessageTypes::Response,
1243 MessageFromServer::NotificationFromServer(_) => MessageTypes::Notification,
1244 MessageFromServer::Error(_) => MessageTypes::Error,
1245 }
1246 }
1247}
1248
1249impl FromMessage<MessageFromServer> for ServerMessage {
1250 fn from_message(
1251 message: MessageFromServer,
1252 request_id: Option<RequestId>,
1253 ) -> std::result::Result<Self, JsonrpcErrorError> {
1254 match message {
1255 MessageFromServer::RequestFromServer(request_from_server) => {
1256 let request_id = request_id
1257 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1258 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(
1259 request_id,
1260 request_from_server,
1261 )))
1262 }
1263 MessageFromServer::ResultFromServer(result_from_server) => {
1264 let request_id = request_id
1265 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1266 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
1267 request_id,
1268 result_from_server,
1269 )))
1270 }
1271 MessageFromServer::NotificationFromServer(notification_from_server) => {
1272 if request_id.is_some() {
1273 return Err(JsonrpcErrorError::internal_error()
1274 .with_message("request_id expected to be None for Notifications!".to_string()));
1275 }
1276 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(
1277 notification_from_server,
1278 )))
1279 }
1280 MessageFromServer::Error(jsonrpc_error_error) => {
1281 let request_id = request_id
1282 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1283 Ok(ServerMessage::Error(JsonrpcError::new(jsonrpc_error_error, request_id)))
1284 }
1285 }
1286 }
1287}
1288
1289#[derive(::serde::Serialize, Clone, Debug)]
1298#[serde(untagged)]
1299pub enum MessageFromClient {
1300 RequestFromClient(RequestFromClient),
1301 ResultFromClient(ResultFromClient),
1302 NotificationFromClient(NotificationFromClient),
1303 Error(JsonrpcErrorError),
1304}
1305
1306impl From<RequestFromClient> for MessageFromClient {
1307 fn from(value: RequestFromClient) -> Self {
1308 Self::RequestFromClient(value)
1309 }
1310}
1311
1312impl From<ResultFromClient> for MessageFromClient {
1313 fn from(value: ResultFromClient) -> Self {
1314 Self::ResultFromClient(value)
1315 }
1316}
1317
1318impl From<NotificationFromClient> for MessageFromClient {
1319 fn from(value: NotificationFromClient) -> Self {
1320 Self::NotificationFromClient(value)
1321 }
1322}
1323
1324impl From<JsonrpcErrorError> for MessageFromClient {
1325 fn from(value: JsonrpcErrorError) -> Self {
1326 Self::Error(value)
1327 }
1328}
1329
1330impl MCPMessage for MessageFromClient {
1331 fn is_response(&self) -> bool {
1332 matches!(self, MessageFromClient::ResultFromClient(_))
1333 }
1334
1335 fn is_request(&self) -> bool {
1336 matches!(self, MessageFromClient::RequestFromClient(_))
1337 }
1338
1339 fn is_notification(&self) -> bool {
1340 matches!(self, MessageFromClient::NotificationFromClient(_))
1341 }
1342
1343 fn is_error(&self) -> bool {
1344 matches!(self, MessageFromClient::Error(_))
1345 }
1346
1347 fn message_type(&self) -> MessageTypes {
1348 match self {
1349 MessageFromClient::RequestFromClient(_) => MessageTypes::Request,
1350 MessageFromClient::ResultFromClient(_) => MessageTypes::Response,
1351 MessageFromClient::NotificationFromClient(_) => MessageTypes::Notification,
1352 MessageFromClient::Error(_) => MessageTypes::Error,
1353 }
1354 }
1355}
1356
1357impl FromMessage<MessageFromClient> for ClientMessage {
1358 fn from_message(
1359 message: MessageFromClient,
1360 request_id: Option<RequestId>,
1361 ) -> std::result::Result<Self, JsonrpcErrorError> {
1362 match message {
1363 MessageFromClient::RequestFromClient(request_from_client) => {
1364 let request_id = request_id
1365 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1366 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(
1367 request_id,
1368 request_from_client,
1369 )))
1370 }
1371 MessageFromClient::ResultFromClient(result_from_client) => {
1372 let request_id = request_id
1373 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1374 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
1375 request_id,
1376 result_from_client,
1377 )))
1378 }
1379 MessageFromClient::NotificationFromClient(notification_from_client) => {
1380 if request_id.is_some() {
1381 return Err(JsonrpcErrorError::internal_error()
1382 .with_message("request_id expected to be None for Notifications!".to_string()));
1383 }
1384
1385 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(
1386 notification_from_client,
1387 )))
1388 }
1389 MessageFromClient::Error(jsonrpc_error_error) => {
1390 let request_id = request_id
1391 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1392 Ok(ClientMessage::Error(JsonrpcError::new(jsonrpc_error_error, request_id)))
1393 }
1394 }
1395 }
1396}
1397
1398#[derive(Debug)]
1405pub struct UnknownTool(pub String);
1406
1407impl core::fmt::Display for UnknownTool {
1409 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1410 write!(f, "Unknown tool: {}", self.0)
1412 }
1413}
1414
1415impl std::error::Error for UnknownTool {}
1417
1418#[derive(Debug)]
1424pub struct CallToolError(pub Box<dyn std::error::Error>);
1425
1426impl CallToolError {
1428 pub fn new<E: std::error::Error + 'static>(err: E) -> Self {
1430 CallToolError(Box::new(err))
1432 }
1433
1434 pub fn unknown_tool(tool_name: String) -> Self {
1436 CallToolError(Box::new(UnknownTool(tool_name)))
1438 }
1439}
1440
1441impl core::fmt::Display for CallToolError {
1443 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1444 write!(f, "{}", self.0)
1445 }
1446}
1447
1448impl std::error::Error for CallToolError {
1450 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1451 self.0.source()
1452 }
1453}
1454
1455impl From<CallToolError> for CallToolResult {
1457 fn from(value: CallToolError) -> Self {
1458 CallToolResult::with_error(value)
1460 }
1461}
1462
1463impl CallToolResult {
1467 pub fn with_error(error: CallToolError) -> Self {
1469 Self {
1470 content: vec![CallToolResultContentItem::TextContent(TextContent::new(
1471 None,
1472 error.to_string(), ))],
1474 is_error: Some(true), meta: None,
1476 }
1477 }
1478
1479 pub fn text_content(text_content: String, text_annotations: Option<TextContentAnnotations>) -> Self {
1481 Self {
1482 content: vec![TextContent::new(text_annotations, text_content).into()],
1483 is_error: None,
1484 meta: None,
1485 }
1486 }
1487
1488 pub fn image_content(data: String, mime_type: String, annotations: Option<ImageContentAnnotations>) -> Self {
1490 Self {
1491 content: vec![ImageContent::new(annotations, data, mime_type).into()],
1492 is_error: None,
1493 meta: None,
1494 }
1495 }
1496
1497 pub fn embedded_resource(resource: EmbeddedResourceResource, annotations: Option<EmbeddedResourceAnnotations>) -> Self {
1499 Self {
1500 content: vec![EmbeddedResource::new(annotations, resource).into()],
1501 is_error: None,
1502 meta: None,
1503 }
1504 }
1505
1506 pub fn with_meta(mut self, meta: Option<serde_json::Map<String, Value>>) -> Self {
1508 self.meta = meta;
1509 self
1510 }
1511}
1512
1513impl CallToolResultContentItem {
1517 pub fn text_content(test_content: String, annotations: Option<TextContentAnnotations>) -> Self {
1519 TextContent::new(annotations, test_content).into()
1520 }
1521
1522 pub fn image_content(data: String, mime_type: String, annotations: Option<ImageContentAnnotations>) -> Self {
1524 ImageContent::new(annotations, data, mime_type).into()
1525 }
1526
1527 pub fn embedded_resource(resource: EmbeddedResourceResource, annotations: Option<EmbeddedResourceAnnotations>) -> Self {
1529 EmbeddedResource::new(annotations, resource).into()
1530 }
1531}
1532
1533impl ::serde::Serialize for ClientJsonrpcRequest {
1535 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1536 where
1537 S: ::serde::Serializer,
1538 {
1539 let mut state = serializer.serialize_struct("JsonrpcRequest", 4)?;
1540 state.serialize_field("id", &self.id)?;
1541 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1542 state.serialize_field("method", &self.method)?;
1543 use ClientRequest::*;
1544 match &self.request {
1545 RequestFromClient::ClientRequest(message) => match message {
1546 InitializeRequest(msg) => state.serialize_field("params", &msg.params)?,
1547 PingRequest(msg) => {
1548 if let Some(params) = &msg.params {
1549 state.serialize_field("params", params)?
1550 }
1551 }
1552 ListResourcesRequest(msg) => state.serialize_field("params", &msg.params)?,
1553 ListResourceTemplatesRequest(msg) => {
1554 if let Some(params) = &msg.params {
1555 state.serialize_field("params", params)?
1556 }
1557 }
1558 ReadResourceRequest(msg) => state.serialize_field("params", &msg.params)?,
1559 SubscribeRequest(msg) => state.serialize_field("params", &msg.params)?,
1560 UnsubscribeRequest(msg) => state.serialize_field("params", &msg.params)?,
1561 ListPromptsRequest(msg) => {
1562 if let Some(params) = &msg.params {
1563 state.serialize_field("params", params)?
1564 }
1565 }
1566 GetPromptRequest(msg) => state.serialize_field("params", &msg.params)?,
1567 ListToolsRequest(msg) => {
1568 if let Some(params) = &msg.params {
1569 state.serialize_field("params", params)?
1570 }
1571 }
1572 CallToolRequest(msg) => state.serialize_field("params", &msg.params)?,
1573 SetLevelRequest(msg) => state.serialize_field("params", &msg.params)?,
1574 CompleteRequest(msg) => state.serialize_field("params", &msg.params)?,
1575 },
1576 RequestFromClient::CustomRequest(value) => state.serialize_field("params", value)?,
1577 }
1578 state.end()
1579 }
1580}
1581impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcRequest {
1582 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1583 where
1584 D: ::serde::Deserializer<'de>,
1585 {
1586 use serde::de::{self, MapAccess, Visitor};
1587 use std::fmt;
1588 struct ClientJsonrpcRequestVisitor;
1589 impl<'de> Visitor<'de> for ClientJsonrpcRequestVisitor {
1590 type Value = ClientJsonrpcRequest;
1591 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1592 formatter.write_str("a valid JSON-RPC request object")
1593 }
1594 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcRequest, M::Error>
1595 where
1596 M: MapAccess<'de>,
1597 {
1598 let mut id: Option<RequestId> = None;
1599 let mut jsonrpc: Option<String> = None;
1600 let mut method: Option<String> = None;
1601 let mut params: Option<Value> = None;
1602 while let Some(key) = map.next_key::<String>()? {
1603 match key.as_str() {
1604 "id" => id = Some(map.next_value()?),
1605 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1606 "method" => method = Some(map.next_value()?),
1607 "params" => params = Some(map.next_value()?),
1608 _ => {
1609 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1610 }
1611 }
1612 }
1613 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1614 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1615 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1616 let params = params.unwrap_or_default();
1617 let req_object = json!({ "method" : method, "params" : params });
1618 let request = serde_json::from_value::<RequestFromClient>(req_object).map_err(de::Error::custom)?;
1619 Ok(ClientJsonrpcRequest {
1620 id,
1621 jsonrpc,
1622 method,
1623 request,
1624 })
1625 }
1626 }
1627 deserializer.deserialize_struct(
1628 "JsonrpcRequest",
1629 &["id", "jsonrpc", "method", "params"],
1630 ClientJsonrpcRequestVisitor,
1631 )
1632 }
1633}
1634impl ::serde::Serialize for ServerJsonrpcRequest {
1635 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1636 where
1637 S: ::serde::Serializer,
1638 {
1639 let mut state = serializer.serialize_struct("JsonrpcRequest", 4)?;
1640 state.serialize_field("id", &self.id)?;
1641 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1642 state.serialize_field("method", &self.method)?;
1643 use ServerRequest::*;
1644 match &self.request {
1645 RequestFromServer::ServerRequest(message) => match message {
1646 PingRequest(msg) => {
1647 if let Some(params) = &msg.params {
1648 state.serialize_field("params", params)?
1649 }
1650 }
1651 CreateMessageRequest(msg) => state.serialize_field("params", &msg.params)?,
1652 ListRootsRequest(msg) => {
1653 if let Some(params) = &msg.params {
1654 state.serialize_field("params", params)?
1655 }
1656 }
1657 },
1658 RequestFromServer::CustomRequest(value) => state.serialize_field("params", value)?,
1659 }
1660 state.end()
1661 }
1662}
1663impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcRequest {
1664 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1665 where
1666 D: ::serde::Deserializer<'de>,
1667 {
1668 use serde::de::{self, MapAccess, Visitor};
1669 use std::fmt;
1670 struct ServerJsonrpcRequestVisitor;
1671 impl<'de> Visitor<'de> for ServerJsonrpcRequestVisitor {
1672 type Value = ServerJsonrpcRequest;
1673 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1674 formatter.write_str("a valid JSON-RPC request object")
1675 }
1676 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcRequest, M::Error>
1677 where
1678 M: MapAccess<'de>,
1679 {
1680 let mut id: Option<RequestId> = None;
1681 let mut jsonrpc: Option<String> = None;
1682 let mut method: Option<String> = None;
1683 let mut params: Option<Value> = None;
1684 while let Some(key) = map.next_key::<String>()? {
1685 match key.as_str() {
1686 "id" => id = Some(map.next_value()?),
1687 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1688 "method" => method = Some(map.next_value()?),
1689 "params" => params = Some(map.next_value()?),
1690 _ => {
1691 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1692 }
1693 }
1694 }
1695 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1696 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1697 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1698 let params = params.unwrap_or_default();
1699 let req_object = json!({ "method" : method, "params" : params });
1700 let request = serde_json::from_value::<RequestFromServer>(req_object).map_err(de::Error::custom)?;
1701 Ok(ServerJsonrpcRequest {
1702 id,
1703 jsonrpc,
1704 method,
1705 request,
1706 })
1707 }
1708 }
1709 deserializer.deserialize_struct(
1710 "JsonrpcRequest",
1711 &["id", "jsonrpc", "method", "params"],
1712 ServerJsonrpcRequestVisitor,
1713 )
1714 }
1715}
1716impl ::serde::Serialize for ClientJsonrpcNotification {
1717 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1718 where
1719 S: ::serde::Serializer,
1720 {
1721 let mut state = serializer.serialize_struct("JsonrpcNotification", 3)?;
1722 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1723 state.serialize_field("method", &self.method)?;
1724 use ClientNotification::*;
1725 match &self.notification {
1726 NotificationFromClient::ClientNotification(message) => match message {
1727 CancelledNotification(msg) => state.serialize_field("params", &msg.params)?,
1728 InitializedNotification(msg) => {
1729 if let Some(params) = &msg.params {
1730 state.serialize_field("params", params)?
1731 }
1732 }
1733 ProgressNotification(msg) => state.serialize_field("params", &msg.params)?,
1734 RootsListChangedNotification(msg) => {
1735 if let Some(params) = &msg.params {
1736 state.serialize_field("params", params)?
1737 }
1738 }
1739 },
1740 NotificationFromClient::CustomNotification(value) => state.serialize_field("params", value)?,
1741 }
1742 state.end()
1743 }
1744}
1745impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcNotification {
1746 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1747 where
1748 D: ::serde::Deserializer<'de>,
1749 {
1750 use serde::de::{self, MapAccess, Visitor};
1751 use std::fmt;
1752 struct ClientJsonrpcNotificationVisitor;
1753 impl<'de> Visitor<'de> for ClientJsonrpcNotificationVisitor {
1754 type Value = ClientJsonrpcNotification;
1755 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1756 formatter.write_str("a valid JSON-RPC notification object")
1757 }
1758 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcNotification, M::Error>
1759 where
1760 M: MapAccess<'de>,
1761 {
1762 let mut jsonrpc: Option<String> = None;
1763 let mut method: Option<String> = None;
1764 let mut params: Option<Value> = None;
1765 while let Some(key) = map.next_key::<String>()? {
1766 match key.as_str() {
1767 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1768 "method" => method = Some(map.next_value()?),
1769 "params" => params = Some(map.next_value()?),
1770 _ => {
1771 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1772 }
1773 }
1774 }
1775 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1776 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1777 let params = params.unwrap_or_default();
1778 let req_object = json!({ "method" : method, "params" : params });
1779 let notification =
1780 serde_json::from_value::<NotificationFromClient>(req_object).map_err(de::Error::custom)?;
1781 Ok(ClientJsonrpcNotification {
1782 jsonrpc,
1783 method,
1784 notification,
1785 })
1786 }
1787 }
1788 deserializer.deserialize_struct(
1789 "JsonrpcRequest",
1790 &["jsonrpc", "method", "params"],
1791 ClientJsonrpcNotificationVisitor,
1792 )
1793 }
1794}
1795impl ::serde::Serialize for ServerJsonrpcNotification {
1796 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1797 where
1798 S: ::serde::Serializer,
1799 {
1800 let mut state = serializer.serialize_struct("JsonrpcNotification", 3)?;
1801 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1802 state.serialize_field("method", &self.method)?;
1803 use ServerNotification::*;
1804 match &self.notification {
1805 NotificationFromServer::ServerNotification(message) => match message {
1806 CancelledNotification(msg) => state.serialize_field("params", &msg.params)?,
1807 ProgressNotification(msg) => state.serialize_field("params", &msg.params)?,
1808 ResourceListChangedNotification(msg) => {
1809 if let Some(params) = &msg.params {
1810 state.serialize_field("params", params)?
1811 }
1812 }
1813 ResourceUpdatedNotification(msg) => state.serialize_field("params", &msg.params)?,
1814 PromptListChangedNotification(msg) => {
1815 if let Some(params) = &msg.params {
1816 state.serialize_field("params", params)?
1817 }
1818 }
1819 ToolListChangedNotification(msg) => {
1820 if let Some(params) = &msg.params {
1821 state.serialize_field("params", params)?
1822 }
1823 }
1824 LoggingMessageNotification(msg) => state.serialize_field("params", &msg.params)?,
1825 },
1826 NotificationFromServer::CustomNotification(value) => state.serialize_field("params", value)?,
1827 }
1828 state.end()
1829 }
1830}
1831impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcNotification {
1832 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1833 where
1834 D: ::serde::Deserializer<'de>,
1835 {
1836 use serde::de::{self, MapAccess, Visitor};
1837 use std::fmt;
1838 struct ServerJsonrpcNotificationVisitor;
1839 impl<'de> Visitor<'de> for ServerJsonrpcNotificationVisitor {
1840 type Value = ServerJsonrpcNotification;
1841 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1842 formatter.write_str("a valid JSON-RPC notification object")
1843 }
1844 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcNotification, M::Error>
1845 where
1846 M: MapAccess<'de>,
1847 {
1848 let mut jsonrpc: Option<String> = None;
1849 let mut method: Option<String> = None;
1850 let mut params: Option<Value> = None;
1851 while let Some(key) = map.next_key::<String>()? {
1852 match key.as_str() {
1853 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1854 "method" => method = Some(map.next_value()?),
1855 "params" => params = Some(map.next_value()?),
1856 _ => {
1857 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1858 }
1859 }
1860 }
1861 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1862 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1863 let params = params.unwrap_or_default();
1864 let req_object = json!({ "method" : method, "params" : params });
1865 let notification =
1866 serde_json::from_value::<NotificationFromServer>(req_object).map_err(de::Error::custom)?;
1867 Ok(ServerJsonrpcNotification {
1868 jsonrpc,
1869 method,
1870 notification,
1871 })
1872 }
1873 }
1874 deserializer.deserialize_struct(
1875 "JsonrpcRequest",
1876 &["jsonrpc", "method", "params"],
1877 ServerJsonrpcNotificationVisitor,
1878 )
1879 }
1880}
1881impl ::serde::Serialize for ServerJsonrpcResponse {
1882 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1883 where
1884 S: ::serde::Serializer,
1885 {
1886 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
1887 state.serialize_field("id", &self.id)?;
1888 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1889 state.serialize_field("result", &self.result)?;
1890 state.end()
1891 }
1892}
1893impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcResponse {
1894 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1895 where
1896 D: ::serde::Deserializer<'de>,
1897 {
1898 use serde::de::{self, MapAccess, Visitor};
1899 use std::fmt;
1900 struct ServerJsonrpcResultVisitor;
1901 impl<'de> Visitor<'de> for ServerJsonrpcResultVisitor {
1902 type Value = ServerJsonrpcResponse;
1903 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1904 formatter.write_str("a valid JSON-RPC response object")
1905 }
1906 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcResponse, M::Error>
1907 where
1908 M: MapAccess<'de>,
1909 {
1910 let mut id: Option<RequestId> = None;
1911 let mut jsonrpc: Option<String> = None;
1912 let mut result: Option<Value> = None;
1913 while let Some(key) = map.next_key::<String>()? {
1914 match key.as_str() {
1915 "id" => id = Some(map.next_value()?),
1916 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1917 "result" => result = Some(map.next_value()?),
1918 _ => {
1919 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
1920 }
1921 }
1922 }
1923 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1924 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1925 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
1926 let result = serde_json::from_value::<ResultFromServer>(result).map_err(de::Error::custom)?;
1927 Ok(ServerJsonrpcResponse { id, jsonrpc, result })
1928 }
1929 }
1930 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ServerJsonrpcResultVisitor)
1931 }
1932}
1933impl ::serde::Serialize for ClientJsonrpcResponse {
1934 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1935 where
1936 S: ::serde::Serializer,
1937 {
1938 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
1939 state.serialize_field("id", &self.id)?;
1940 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1941 state.serialize_field("result", &self.result)?;
1942 state.end()
1943 }
1944}
1945impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcResponse {
1946 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1947 where
1948 D: ::serde::Deserializer<'de>,
1949 {
1950 use serde::de::{self, MapAccess, Visitor};
1951 use std::fmt;
1952 struct ClientJsonrpcResultVisitor;
1953 impl<'de> Visitor<'de> for ClientJsonrpcResultVisitor {
1954 type Value = ClientJsonrpcResponse;
1955 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1956 formatter.write_str("a valid JSON-RPC response object")
1957 }
1958 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcResponse, M::Error>
1959 where
1960 M: MapAccess<'de>,
1961 {
1962 let mut id: Option<RequestId> = None;
1963 let mut jsonrpc: Option<String> = None;
1964 let mut result: Option<Value> = None;
1965 while let Some(key) = map.next_key::<String>()? {
1966 match key.as_str() {
1967 "id" => id = Some(map.next_value()?),
1968 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1969 "result" => result = Some(map.next_value()?),
1970 _ => {
1971 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
1972 }
1973 }
1974 }
1975 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1976 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1977 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
1978 let result = serde_json::from_value::<ResultFromClient>(result).map_err(de::Error::custom)?;
1979 Ok(ClientJsonrpcResponse { id, jsonrpc, result })
1980 }
1981 }
1982 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ClientJsonrpcResultVisitor)
1983 }
1984}
1985impl From<InitializeRequest> for RequestFromClient {
1986 fn from(value: InitializeRequest) -> Self {
1987 Self::ClientRequest(value.into())
1988 }
1989}
1990impl From<PingRequest> for RequestFromClient {
1991 fn from(value: PingRequest) -> Self {
1992 Self::ClientRequest(value.into())
1993 }
1994}
1995impl From<ListResourcesRequest> for RequestFromClient {
1996 fn from(value: ListResourcesRequest) -> Self {
1997 Self::ClientRequest(value.into())
1998 }
1999}
2000impl From<ListResourceTemplatesRequest> for RequestFromClient {
2001 fn from(value: ListResourceTemplatesRequest) -> Self {
2002 Self::ClientRequest(value.into())
2003 }
2004}
2005impl From<ReadResourceRequest> for RequestFromClient {
2006 fn from(value: ReadResourceRequest) -> Self {
2007 Self::ClientRequest(value.into())
2008 }
2009}
2010impl From<SubscribeRequest> for RequestFromClient {
2011 fn from(value: SubscribeRequest) -> Self {
2012 Self::ClientRequest(value.into())
2013 }
2014}
2015impl From<UnsubscribeRequest> for RequestFromClient {
2016 fn from(value: UnsubscribeRequest) -> Self {
2017 Self::ClientRequest(value.into())
2018 }
2019}
2020impl From<ListPromptsRequest> for RequestFromClient {
2021 fn from(value: ListPromptsRequest) -> Self {
2022 Self::ClientRequest(value.into())
2023 }
2024}
2025impl From<GetPromptRequest> for RequestFromClient {
2026 fn from(value: GetPromptRequest) -> Self {
2027 Self::ClientRequest(value.into())
2028 }
2029}
2030impl From<ListToolsRequest> for RequestFromClient {
2031 fn from(value: ListToolsRequest) -> Self {
2032 Self::ClientRequest(value.into())
2033 }
2034}
2035impl From<CallToolRequest> for RequestFromClient {
2036 fn from(value: CallToolRequest) -> Self {
2037 Self::ClientRequest(value.into())
2038 }
2039}
2040impl From<SetLevelRequest> for RequestFromClient {
2041 fn from(value: SetLevelRequest) -> Self {
2042 Self::ClientRequest(value.into())
2043 }
2044}
2045impl From<CompleteRequest> for RequestFromClient {
2046 fn from(value: CompleteRequest) -> Self {
2047 Self::ClientRequest(value.into())
2048 }
2049}
2050impl From<InitializeRequest> for MessageFromClient {
2051 fn from(value: InitializeRequest) -> Self {
2052 MessageFromClient::RequestFromClient(value.into())
2053 }
2054}
2055impl From<PingRequest> for MessageFromClient {
2056 fn from(value: PingRequest) -> Self {
2057 MessageFromClient::RequestFromClient(value.into())
2058 }
2059}
2060impl From<ListResourcesRequest> for MessageFromClient {
2061 fn from(value: ListResourcesRequest) -> Self {
2062 MessageFromClient::RequestFromClient(value.into())
2063 }
2064}
2065impl From<ListResourceTemplatesRequest> for MessageFromClient {
2066 fn from(value: ListResourceTemplatesRequest) -> Self {
2067 MessageFromClient::RequestFromClient(value.into())
2068 }
2069}
2070impl From<ReadResourceRequest> for MessageFromClient {
2071 fn from(value: ReadResourceRequest) -> Self {
2072 MessageFromClient::RequestFromClient(value.into())
2073 }
2074}
2075impl From<SubscribeRequest> for MessageFromClient {
2076 fn from(value: SubscribeRequest) -> Self {
2077 MessageFromClient::RequestFromClient(value.into())
2078 }
2079}
2080impl From<UnsubscribeRequest> for MessageFromClient {
2081 fn from(value: UnsubscribeRequest) -> Self {
2082 MessageFromClient::RequestFromClient(value.into())
2083 }
2084}
2085impl From<ListPromptsRequest> for MessageFromClient {
2086 fn from(value: ListPromptsRequest) -> Self {
2087 MessageFromClient::RequestFromClient(value.into())
2088 }
2089}
2090impl From<GetPromptRequest> for MessageFromClient {
2091 fn from(value: GetPromptRequest) -> Self {
2092 MessageFromClient::RequestFromClient(value.into())
2093 }
2094}
2095impl From<ListToolsRequest> for MessageFromClient {
2096 fn from(value: ListToolsRequest) -> Self {
2097 MessageFromClient::RequestFromClient(value.into())
2098 }
2099}
2100impl From<CallToolRequest> for MessageFromClient {
2101 fn from(value: CallToolRequest) -> Self {
2102 MessageFromClient::RequestFromClient(value.into())
2103 }
2104}
2105impl From<SetLevelRequest> for MessageFromClient {
2106 fn from(value: SetLevelRequest) -> Self {
2107 MessageFromClient::RequestFromClient(value.into())
2108 }
2109}
2110impl From<CompleteRequest> for MessageFromClient {
2111 fn from(value: CompleteRequest) -> Self {
2112 MessageFromClient::RequestFromClient(value.into())
2113 }
2114}
2115impl From<CancelledNotification> for NotificationFromClient {
2116 fn from(value: CancelledNotification) -> Self {
2117 Self::ClientNotification(value.into())
2118 }
2119}
2120impl From<InitializedNotification> for NotificationFromClient {
2121 fn from(value: InitializedNotification) -> Self {
2122 Self::ClientNotification(value.into())
2123 }
2124}
2125impl From<ProgressNotification> for NotificationFromClient {
2126 fn from(value: ProgressNotification) -> Self {
2127 Self::ClientNotification(value.into())
2128 }
2129}
2130impl From<RootsListChangedNotification> for NotificationFromClient {
2131 fn from(value: RootsListChangedNotification) -> Self {
2132 Self::ClientNotification(value.into())
2133 }
2134}
2135impl From<CancelledNotification> for ClientJsonrpcNotification {
2136 fn from(value: CancelledNotification) -> Self {
2137 Self::new(value.into())
2138 }
2139}
2140impl From<InitializedNotification> for ClientJsonrpcNotification {
2141 fn from(value: InitializedNotification) -> Self {
2142 Self::new(value.into())
2143 }
2144}
2145impl From<ProgressNotification> for ClientJsonrpcNotification {
2146 fn from(value: ProgressNotification) -> Self {
2147 Self::new(value.into())
2148 }
2149}
2150impl From<RootsListChangedNotification> for ClientJsonrpcNotification {
2151 fn from(value: RootsListChangedNotification) -> Self {
2152 Self::new(value.into())
2153 }
2154}
2155impl From<CancelledNotification> for MessageFromClient {
2156 fn from(value: CancelledNotification) -> Self {
2157 MessageFromClient::NotificationFromClient(value.into())
2158 }
2159}
2160impl From<InitializedNotification> for MessageFromClient {
2161 fn from(value: InitializedNotification) -> Self {
2162 MessageFromClient::NotificationFromClient(value.into())
2163 }
2164}
2165impl From<ProgressNotification> for MessageFromClient {
2166 fn from(value: ProgressNotification) -> Self {
2167 MessageFromClient::NotificationFromClient(value.into())
2168 }
2169}
2170impl From<RootsListChangedNotification> for MessageFromClient {
2171 fn from(value: RootsListChangedNotification) -> Self {
2172 MessageFromClient::NotificationFromClient(value.into())
2173 }
2174}
2175impl From<Result> for ResultFromClient {
2176 fn from(value: Result) -> Self {
2177 Self::ClientResult(value.into())
2178 }
2179}
2180impl From<CreateMessageResult> for ResultFromClient {
2181 fn from(value: CreateMessageResult) -> Self {
2182 Self::ClientResult(value.into())
2183 }
2184}
2185impl From<ListRootsResult> for ResultFromClient {
2186 fn from(value: ListRootsResult) -> Self {
2187 Self::ClientResult(value.into())
2188 }
2189}
2190impl From<Result> for MessageFromClient {
2191 fn from(value: Result) -> Self {
2192 MessageFromClient::ResultFromClient(value.into())
2193 }
2194}
2195impl From<CreateMessageResult> for MessageFromClient {
2196 fn from(value: CreateMessageResult) -> Self {
2197 MessageFromClient::ResultFromClient(value.into())
2198 }
2199}
2200impl From<ListRootsResult> for MessageFromClient {
2201 fn from(value: ListRootsResult) -> Self {
2202 MessageFromClient::ResultFromClient(value.into())
2203 }
2204}
2205#[allow(non_camel_case_types)]
2207pub enum SdkErrorCodes {
2208 CONNECTION_CLOSED = -32000,
2209 REQUEST_TIMEOUT = -32001,
2210}
2211impl core::fmt::Display for SdkErrorCodes {
2212 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2213 match self {
2214 SdkErrorCodes::CONNECTION_CLOSED => write!(f, "Connection closed"),
2215 SdkErrorCodes::REQUEST_TIMEOUT => write!(f, "Request timeout"),
2216 }
2217 }
2218}
2219impl From<SdkErrorCodes> for i64 {
2220 fn from(code: SdkErrorCodes) -> Self {
2221 code as i64
2222 }
2223}
2224#[derive(Debug)]
2225pub struct SdkError {
2226 pub code: i64,
2228 pub data: ::std::option::Option<::serde_json::Value>,
2230 pub message: ::std::string::String,
2232}
2233impl core::fmt::Display for SdkError {
2234 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2235 write!(f, "MCP error {}: {}", self.code, self.message)
2236 }
2237}
2238impl std::error::Error for SdkError {
2239 fn description(&self) -> &str {
2240 &self.message
2241 }
2242}
2243impl SdkError {
2244 pub fn new(
2245 error_code: SdkErrorCodes,
2246 message: ::std::string::String,
2247 data: ::std::option::Option<::serde_json::Value>,
2248 ) -> Self {
2249 Self {
2250 code: error_code.into(),
2251 data,
2252 message,
2253 }
2254 }
2255 pub fn connection_closed() -> Self {
2256 Self {
2257 code: SdkErrorCodes::CONNECTION_CLOSED.into(),
2258 data: None,
2259 message: SdkErrorCodes::CONNECTION_CLOSED.to_string(),
2260 }
2261 }
2262 pub fn request_timeout(timeout: u128) -> Self {
2263 Self {
2264 code: SdkErrorCodes::REQUEST_TIMEOUT.into(),
2265 data: Some(json!({ "timeout" : timeout })),
2266 message: SdkErrorCodes::REQUEST_TIMEOUT.to_string(),
2267 }
2268 }
2269}
2270#[allow(non_camel_case_types)]
2272pub enum RpcErrorCodes {
2273 PARSE_ERROR = -32700isize,
2274 INVALID_REQUEST = -32600isize,
2275 METHOD_NOT_FOUND = -32601isize,
2276 INVALID_PARAMS = -32602isize,
2277 INTERNAL_ERROR = -32603isize,
2278}
2279impl From<RpcErrorCodes> for i64 {
2280 fn from(code: RpcErrorCodes) -> Self {
2281 code as i64
2282 }
2283}
2284impl JsonrpcErrorError {
2285 pub fn new(
2302 error_code: RpcErrorCodes,
2303 message: ::std::string::String,
2304 data: ::std::option::Option<::serde_json::Value>,
2305 ) -> Self {
2306 Self {
2307 code: error_code.into(),
2308 data,
2309 message,
2310 }
2311 }
2312 pub fn method_not_found() -> Self {
2323 Self {
2324 code: RpcErrorCodes::METHOD_NOT_FOUND.into(),
2325 data: None,
2326 message: "Method not found".to_string(),
2327 }
2328 }
2329 pub fn invalid_params() -> Self {
2339 Self {
2340 code: RpcErrorCodes::INVALID_PARAMS.into(),
2341 data: None,
2342 message: "Invalid params".to_string(),
2343 }
2344 }
2345 pub fn invalid_request() -> Self {
2355 Self {
2356 code: RpcErrorCodes::INVALID_REQUEST.into(),
2357 data: None,
2358 message: "Invalid request".to_string(),
2359 }
2360 }
2361 pub fn internal_error() -> Self {
2371 Self {
2372 code: RpcErrorCodes::INTERNAL_ERROR.into(),
2373 data: None,
2374 message: "Internal error".to_string(),
2375 }
2376 }
2377 pub fn parse_error() -> Self {
2387 Self {
2388 code: RpcErrorCodes::PARSE_ERROR.into(),
2389 data: None,
2390 message: "Parse error".to_string(),
2391 }
2392 }
2393 pub fn with_message(mut self, message: String) -> Self {
2403 self.message = message;
2404 self
2405 }
2406 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
2417 self.data = data;
2418 self
2419 }
2420}
2421impl std::error::Error for JsonrpcErrorError {
2422 fn description(&self) -> &str {
2423 &self.message
2424 }
2425}
2426impl Display for JsonrpcErrorError {
2427 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2428 write!(
2429 f,
2430 "{}",
2431 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
2432 )
2433 }
2434}
2435impl FromStr for JsonrpcErrorError {
2436 type Err = JsonrpcErrorError;
2437 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2438 serde_json::from_str(s)
2439 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
2440 }
2441}
2442impl JsonrpcError {
2444 pub fn create(
2445 id: RequestId,
2446 error_code: RpcErrorCodes,
2447 error_message: ::std::string::String,
2448 error_data: ::std::option::Option<::serde_json::Value>,
2449 ) -> Self {
2450 Self::new(JsonrpcErrorError::new(error_code, error_message, error_data), id)
2451 }
2452}
2453impl From<CancelledNotification> for NotificationFromServer {
2454 fn from(value: CancelledNotification) -> Self {
2455 Self::ServerNotification(value.into())
2456 }
2457}
2458impl From<ProgressNotification> for NotificationFromServer {
2459 fn from(value: ProgressNotification) -> Self {
2460 Self::ServerNotification(value.into())
2461 }
2462}
2463impl From<ResourceListChangedNotification> for NotificationFromServer {
2464 fn from(value: ResourceListChangedNotification) -> Self {
2465 Self::ServerNotification(value.into())
2466 }
2467}
2468impl From<ResourceUpdatedNotification> for NotificationFromServer {
2469 fn from(value: ResourceUpdatedNotification) -> Self {
2470 Self::ServerNotification(value.into())
2471 }
2472}
2473impl From<PromptListChangedNotification> for NotificationFromServer {
2474 fn from(value: PromptListChangedNotification) -> Self {
2475 Self::ServerNotification(value.into())
2476 }
2477}
2478impl From<ToolListChangedNotification> for NotificationFromServer {
2479 fn from(value: ToolListChangedNotification) -> Self {
2480 Self::ServerNotification(value.into())
2481 }
2482}
2483impl From<LoggingMessageNotification> for NotificationFromServer {
2484 fn from(value: LoggingMessageNotification) -> Self {
2485 Self::ServerNotification(value.into())
2486 }
2487}
2488impl From<CancelledNotification> for ServerJsonrpcNotification {
2489 fn from(value: CancelledNotification) -> Self {
2490 Self::new(value.into())
2491 }
2492}
2493impl From<ProgressNotification> for ServerJsonrpcNotification {
2494 fn from(value: ProgressNotification) -> Self {
2495 Self::new(value.into())
2496 }
2497}
2498impl From<ResourceListChangedNotification> for ServerJsonrpcNotification {
2499 fn from(value: ResourceListChangedNotification) -> Self {
2500 Self::new(value.into())
2501 }
2502}
2503impl From<ResourceUpdatedNotification> for ServerJsonrpcNotification {
2504 fn from(value: ResourceUpdatedNotification) -> Self {
2505 Self::new(value.into())
2506 }
2507}
2508impl From<PromptListChangedNotification> for ServerJsonrpcNotification {
2509 fn from(value: PromptListChangedNotification) -> Self {
2510 Self::new(value.into())
2511 }
2512}
2513impl From<ToolListChangedNotification> for ServerJsonrpcNotification {
2514 fn from(value: ToolListChangedNotification) -> Self {
2515 Self::new(value.into())
2516 }
2517}
2518impl From<LoggingMessageNotification> for ServerJsonrpcNotification {
2519 fn from(value: LoggingMessageNotification) -> Self {
2520 Self::new(value.into())
2521 }
2522}
2523impl From<CancelledNotification> for MessageFromServer {
2524 fn from(value: CancelledNotification) -> Self {
2525 MessageFromServer::NotificationFromServer(value.into())
2526 }
2527}
2528impl From<ProgressNotification> for MessageFromServer {
2529 fn from(value: ProgressNotification) -> Self {
2530 MessageFromServer::NotificationFromServer(value.into())
2531 }
2532}
2533impl From<ResourceListChangedNotification> for MessageFromServer {
2534 fn from(value: ResourceListChangedNotification) -> Self {
2535 MessageFromServer::NotificationFromServer(value.into())
2536 }
2537}
2538impl From<ResourceUpdatedNotification> for MessageFromServer {
2539 fn from(value: ResourceUpdatedNotification) -> Self {
2540 MessageFromServer::NotificationFromServer(value.into())
2541 }
2542}
2543impl From<PromptListChangedNotification> for MessageFromServer {
2544 fn from(value: PromptListChangedNotification) -> Self {
2545 MessageFromServer::NotificationFromServer(value.into())
2546 }
2547}
2548impl From<ToolListChangedNotification> for MessageFromServer {
2549 fn from(value: ToolListChangedNotification) -> Self {
2550 MessageFromServer::NotificationFromServer(value.into())
2551 }
2552}
2553impl From<LoggingMessageNotification> for MessageFromServer {
2554 fn from(value: LoggingMessageNotification) -> Self {
2555 MessageFromServer::NotificationFromServer(value.into())
2556 }
2557}
2558impl From<PingRequest> for RequestFromServer {
2559 fn from(value: PingRequest) -> Self {
2560 Self::ServerRequest(value.into())
2561 }
2562}
2563impl From<CreateMessageRequest> for RequestFromServer {
2564 fn from(value: CreateMessageRequest) -> Self {
2565 Self::ServerRequest(value.into())
2566 }
2567}
2568impl From<ListRootsRequest> for RequestFromServer {
2569 fn from(value: ListRootsRequest) -> Self {
2570 Self::ServerRequest(value.into())
2571 }
2572}
2573impl From<PingRequest> for MessageFromServer {
2574 fn from(value: PingRequest) -> Self {
2575 MessageFromServer::RequestFromServer(value.into())
2576 }
2577}
2578impl From<CreateMessageRequest> for MessageFromServer {
2579 fn from(value: CreateMessageRequest) -> Self {
2580 MessageFromServer::RequestFromServer(value.into())
2581 }
2582}
2583impl From<ListRootsRequest> for MessageFromServer {
2584 fn from(value: ListRootsRequest) -> Self {
2585 MessageFromServer::RequestFromServer(value.into())
2586 }
2587}
2588impl From<Result> for ResultFromServer {
2589 fn from(value: Result) -> Self {
2590 Self::ServerResult(value.into())
2591 }
2592}
2593impl From<InitializeResult> for ResultFromServer {
2594 fn from(value: InitializeResult) -> Self {
2595 Self::ServerResult(value.into())
2596 }
2597}
2598impl From<ListResourcesResult> for ResultFromServer {
2599 fn from(value: ListResourcesResult) -> Self {
2600 Self::ServerResult(value.into())
2601 }
2602}
2603impl From<ListResourceTemplatesResult> for ResultFromServer {
2604 fn from(value: ListResourceTemplatesResult) -> Self {
2605 Self::ServerResult(value.into())
2606 }
2607}
2608impl From<ReadResourceResult> for ResultFromServer {
2609 fn from(value: ReadResourceResult) -> Self {
2610 Self::ServerResult(value.into())
2611 }
2612}
2613impl From<ListPromptsResult> for ResultFromServer {
2614 fn from(value: ListPromptsResult) -> Self {
2615 Self::ServerResult(value.into())
2616 }
2617}
2618impl From<GetPromptResult> for ResultFromServer {
2619 fn from(value: GetPromptResult) -> Self {
2620 Self::ServerResult(value.into())
2621 }
2622}
2623impl From<ListToolsResult> for ResultFromServer {
2624 fn from(value: ListToolsResult) -> Self {
2625 Self::ServerResult(value.into())
2626 }
2627}
2628impl From<CallToolResult> for ResultFromServer {
2629 fn from(value: CallToolResult) -> Self {
2630 Self::ServerResult(value.into())
2631 }
2632}
2633impl From<CompleteResult> for ResultFromServer {
2634 fn from(value: CompleteResult) -> Self {
2635 Self::ServerResult(value.into())
2636 }
2637}
2638impl From<Result> for MessageFromServer {
2639 fn from(value: Result) -> Self {
2640 MessageFromServer::ResultFromServer(value.into())
2641 }
2642}
2643impl From<InitializeResult> for MessageFromServer {
2644 fn from(value: InitializeResult) -> Self {
2645 MessageFromServer::ResultFromServer(value.into())
2646 }
2647}
2648impl From<ListResourcesResult> for MessageFromServer {
2649 fn from(value: ListResourcesResult) -> Self {
2650 MessageFromServer::ResultFromServer(value.into())
2651 }
2652}
2653impl From<ListResourceTemplatesResult> for MessageFromServer {
2654 fn from(value: ListResourceTemplatesResult) -> Self {
2655 MessageFromServer::ResultFromServer(value.into())
2656 }
2657}
2658impl From<ReadResourceResult> for MessageFromServer {
2659 fn from(value: ReadResourceResult) -> Self {
2660 MessageFromServer::ResultFromServer(value.into())
2661 }
2662}
2663impl From<ListPromptsResult> for MessageFromServer {
2664 fn from(value: ListPromptsResult) -> Self {
2665 MessageFromServer::ResultFromServer(value.into())
2666 }
2667}
2668impl From<GetPromptResult> for MessageFromServer {
2669 fn from(value: GetPromptResult) -> Self {
2670 MessageFromServer::ResultFromServer(value.into())
2671 }
2672}
2673impl From<ListToolsResult> for MessageFromServer {
2674 fn from(value: ListToolsResult) -> Self {
2675 MessageFromServer::ResultFromServer(value.into())
2676 }
2677}
2678impl From<CallToolResult> for MessageFromServer {
2679 fn from(value: CallToolResult) -> Self {
2680 MessageFromServer::ResultFromServer(value.into())
2681 }
2682}
2683impl From<CompleteResult> for MessageFromServer {
2684 fn from(value: CompleteResult) -> Self {
2685 MessageFromServer::ResultFromServer(value.into())
2686 }
2687}
2688impl FromMessage<InitializeRequest> for ClientMessage {
2689 fn from_message(
2690 message: InitializeRequest,
2691 request_id: Option<RequestId>,
2692 ) -> std::result::Result<Self, JsonrpcErrorError> {
2693 let request_id =
2694 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2695 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2696 }
2697}
2698impl ToMessage<ClientMessage> for InitializeRequest {
2699 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2700 ClientMessage::from_message(self, request_id)
2701 }
2702}
2703impl FromMessage<PingRequest> for ClientMessage {
2704 fn from_message(message: PingRequest, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
2705 let request_id =
2706 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2707 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2708 }
2709}
2710impl ToMessage<ClientMessage> for PingRequest {
2711 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2712 ClientMessage::from_message(self, request_id)
2713 }
2714}
2715impl FromMessage<ListResourcesRequest> for ClientMessage {
2716 fn from_message(
2717 message: ListResourcesRequest,
2718 request_id: Option<RequestId>,
2719 ) -> std::result::Result<Self, JsonrpcErrorError> {
2720 let request_id =
2721 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2722 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2723 }
2724}
2725impl ToMessage<ClientMessage> for ListResourcesRequest {
2726 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2727 ClientMessage::from_message(self, request_id)
2728 }
2729}
2730impl FromMessage<ListResourceTemplatesRequest> for ClientMessage {
2731 fn from_message(
2732 message: ListResourceTemplatesRequest,
2733 request_id: Option<RequestId>,
2734 ) -> std::result::Result<Self, JsonrpcErrorError> {
2735 let request_id =
2736 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2737 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2738 }
2739}
2740impl ToMessage<ClientMessage> for ListResourceTemplatesRequest {
2741 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2742 ClientMessage::from_message(self, request_id)
2743 }
2744}
2745impl FromMessage<ReadResourceRequest> for ClientMessage {
2746 fn from_message(
2747 message: ReadResourceRequest,
2748 request_id: Option<RequestId>,
2749 ) -> std::result::Result<Self, JsonrpcErrorError> {
2750 let request_id =
2751 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2752 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2753 }
2754}
2755impl ToMessage<ClientMessage> for ReadResourceRequest {
2756 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2757 ClientMessage::from_message(self, request_id)
2758 }
2759}
2760impl FromMessage<SubscribeRequest> for ClientMessage {
2761 fn from_message(
2762 message: SubscribeRequest,
2763 request_id: Option<RequestId>,
2764 ) -> std::result::Result<Self, JsonrpcErrorError> {
2765 let request_id =
2766 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2767 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2768 }
2769}
2770impl ToMessage<ClientMessage> for SubscribeRequest {
2771 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2772 ClientMessage::from_message(self, request_id)
2773 }
2774}
2775impl FromMessage<UnsubscribeRequest> for ClientMessage {
2776 fn from_message(
2777 message: UnsubscribeRequest,
2778 request_id: Option<RequestId>,
2779 ) -> std::result::Result<Self, JsonrpcErrorError> {
2780 let request_id =
2781 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2782 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2783 }
2784}
2785impl ToMessage<ClientMessage> for UnsubscribeRequest {
2786 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2787 ClientMessage::from_message(self, request_id)
2788 }
2789}
2790impl FromMessage<ListPromptsRequest> for ClientMessage {
2791 fn from_message(
2792 message: ListPromptsRequest,
2793 request_id: Option<RequestId>,
2794 ) -> std::result::Result<Self, JsonrpcErrorError> {
2795 let request_id =
2796 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2797 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2798 }
2799}
2800impl ToMessage<ClientMessage> for ListPromptsRequest {
2801 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2802 ClientMessage::from_message(self, request_id)
2803 }
2804}
2805impl FromMessage<GetPromptRequest> for ClientMessage {
2806 fn from_message(
2807 message: GetPromptRequest,
2808 request_id: Option<RequestId>,
2809 ) -> std::result::Result<Self, JsonrpcErrorError> {
2810 let request_id =
2811 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2812 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2813 }
2814}
2815impl ToMessage<ClientMessage> for GetPromptRequest {
2816 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2817 ClientMessage::from_message(self, request_id)
2818 }
2819}
2820impl FromMessage<ListToolsRequest> for ClientMessage {
2821 fn from_message(
2822 message: ListToolsRequest,
2823 request_id: Option<RequestId>,
2824 ) -> std::result::Result<Self, JsonrpcErrorError> {
2825 let request_id =
2826 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2827 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2828 }
2829}
2830impl ToMessage<ClientMessage> for ListToolsRequest {
2831 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2832 ClientMessage::from_message(self, request_id)
2833 }
2834}
2835impl FromMessage<CallToolRequest> for ClientMessage {
2836 fn from_message(
2837 message: CallToolRequest,
2838 request_id: Option<RequestId>,
2839 ) -> std::result::Result<Self, JsonrpcErrorError> {
2840 let request_id =
2841 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2842 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2843 }
2844}
2845impl ToMessage<ClientMessage> for CallToolRequest {
2846 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2847 ClientMessage::from_message(self, request_id)
2848 }
2849}
2850impl FromMessage<SetLevelRequest> for ClientMessage {
2851 fn from_message(
2852 message: SetLevelRequest,
2853 request_id: Option<RequestId>,
2854 ) -> std::result::Result<Self, JsonrpcErrorError> {
2855 let request_id =
2856 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2857 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2858 }
2859}
2860impl ToMessage<ClientMessage> for SetLevelRequest {
2861 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2862 ClientMessage::from_message(self, request_id)
2863 }
2864}
2865impl FromMessage<CompleteRequest> for ClientMessage {
2866 fn from_message(
2867 message: CompleteRequest,
2868 request_id: Option<RequestId>,
2869 ) -> std::result::Result<Self, JsonrpcErrorError> {
2870 let request_id =
2871 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2872 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2873 }
2874}
2875impl ToMessage<ClientMessage> for CompleteRequest {
2876 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2877 ClientMessage::from_message(self, request_id)
2878 }
2879}
2880impl FromMessage<Result> for ClientMessage {
2881 fn from_message(message: Result, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
2882 let request_id =
2883 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2884 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
2885 request_id,
2886 message.into(),
2887 )))
2888 }
2889}
2890impl ToMessage<ClientMessage> for Result {
2891 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2892 ClientMessage::from_message(self, request_id)
2893 }
2894}
2895impl FromMessage<CreateMessageResult> for ClientMessage {
2896 fn from_message(
2897 message: CreateMessageResult,
2898 request_id: Option<RequestId>,
2899 ) -> std::result::Result<Self, JsonrpcErrorError> {
2900 let request_id =
2901 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2902 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
2903 request_id,
2904 message.into(),
2905 )))
2906 }
2907}
2908impl ToMessage<ClientMessage> for CreateMessageResult {
2909 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2910 ClientMessage::from_message(self, request_id)
2911 }
2912}
2913impl FromMessage<ListRootsResult> for ClientMessage {
2914 fn from_message(
2915 message: ListRootsResult,
2916 request_id: Option<RequestId>,
2917 ) -> std::result::Result<Self, JsonrpcErrorError> {
2918 let request_id =
2919 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2920 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
2921 request_id,
2922 message.into(),
2923 )))
2924 }
2925}
2926impl ToMessage<ClientMessage> for ListRootsResult {
2927 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2928 ClientMessage::from_message(self, request_id)
2929 }
2930}
2931impl FromMessage<CancelledNotification> for ClientMessage {
2932 fn from_message(
2933 message: CancelledNotification,
2934 request_id: Option<RequestId>,
2935 ) -> std::result::Result<Self, JsonrpcErrorError> {
2936 if request_id.is_some() {
2937 return Err(JsonrpcErrorError::internal_error()
2938 .with_message("request_id expected to be None for Notifications!".to_string()));
2939 }
2940 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
2941 }
2942}
2943impl ToMessage<ClientMessage> for CancelledNotification {
2944 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2945 ClientMessage::from_message(self, request_id)
2946 }
2947}
2948impl FromMessage<InitializedNotification> for ClientMessage {
2949 fn from_message(
2950 message: InitializedNotification,
2951 request_id: Option<RequestId>,
2952 ) -> std::result::Result<Self, JsonrpcErrorError> {
2953 if request_id.is_some() {
2954 return Err(JsonrpcErrorError::internal_error()
2955 .with_message("request_id expected to be None for Notifications!".to_string()));
2956 }
2957 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
2958 }
2959}
2960impl ToMessage<ClientMessage> for InitializedNotification {
2961 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2962 ClientMessage::from_message(self, request_id)
2963 }
2964}
2965impl FromMessage<ProgressNotification> for ClientMessage {
2966 fn from_message(
2967 message: ProgressNotification,
2968 request_id: Option<RequestId>,
2969 ) -> std::result::Result<Self, JsonrpcErrorError> {
2970 if request_id.is_some() {
2971 return Err(JsonrpcErrorError::internal_error()
2972 .with_message("request_id expected to be None for Notifications!".to_string()));
2973 }
2974 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
2975 }
2976}
2977impl ToMessage<ClientMessage> for ProgressNotification {
2978 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2979 ClientMessage::from_message(self, request_id)
2980 }
2981}
2982impl FromMessage<RootsListChangedNotification> for ClientMessage {
2983 fn from_message(
2984 message: RootsListChangedNotification,
2985 request_id: Option<RequestId>,
2986 ) -> std::result::Result<Self, JsonrpcErrorError> {
2987 if request_id.is_some() {
2988 return Err(JsonrpcErrorError::internal_error()
2989 .with_message("request_id expected to be None for Notifications!".to_string()));
2990 }
2991 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
2992 }
2993}
2994impl ToMessage<ClientMessage> for RootsListChangedNotification {
2995 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2996 ClientMessage::from_message(self, request_id)
2997 }
2998}
2999impl FromMessage<PingRequest> for ServerMessage {
3000 fn from_message(message: PingRequest, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
3001 let request_id =
3002 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3003 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3004 }
3005}
3006impl ToMessage<ServerMessage> for PingRequest {
3007 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3008 ServerMessage::from_message(self, request_id)
3009 }
3010}
3011impl FromMessage<CreateMessageRequest> for ServerMessage {
3012 fn from_message(
3013 message: CreateMessageRequest,
3014 request_id: Option<RequestId>,
3015 ) -> std::result::Result<Self, JsonrpcErrorError> {
3016 let request_id =
3017 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3018 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3019 }
3020}
3021impl ToMessage<ServerMessage> for CreateMessageRequest {
3022 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3023 ServerMessage::from_message(self, request_id)
3024 }
3025}
3026impl FromMessage<ListRootsRequest> for ServerMessage {
3027 fn from_message(
3028 message: ListRootsRequest,
3029 request_id: Option<RequestId>,
3030 ) -> std::result::Result<Self, JsonrpcErrorError> {
3031 let request_id =
3032 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3033 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3034 }
3035}
3036impl ToMessage<ServerMessage> for ListRootsRequest {
3037 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3038 ServerMessage::from_message(self, request_id)
3039 }
3040}
3041impl FromMessage<Result> for ServerMessage {
3042 fn from_message(message: Result, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
3043 let request_id =
3044 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3045 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3046 request_id,
3047 message.into(),
3048 )))
3049 }
3050}
3051impl ToMessage<ServerMessage> for Result {
3052 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3053 ServerMessage::from_message(self, request_id)
3054 }
3055}
3056impl FromMessage<InitializeResult> for ServerMessage {
3057 fn from_message(
3058 message: InitializeResult,
3059 request_id: Option<RequestId>,
3060 ) -> std::result::Result<Self, JsonrpcErrorError> {
3061 let request_id =
3062 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3063 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3064 request_id,
3065 message.into(),
3066 )))
3067 }
3068}
3069impl ToMessage<ServerMessage> for InitializeResult {
3070 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3071 ServerMessage::from_message(self, request_id)
3072 }
3073}
3074impl FromMessage<ListResourcesResult> for ServerMessage {
3075 fn from_message(
3076 message: ListResourcesResult,
3077 request_id: Option<RequestId>,
3078 ) -> std::result::Result<Self, JsonrpcErrorError> {
3079 let request_id =
3080 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3081 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3082 request_id,
3083 message.into(),
3084 )))
3085 }
3086}
3087impl ToMessage<ServerMessage> for ListResourcesResult {
3088 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3089 ServerMessage::from_message(self, request_id)
3090 }
3091}
3092impl FromMessage<ListResourceTemplatesResult> for ServerMessage {
3093 fn from_message(
3094 message: ListResourceTemplatesResult,
3095 request_id: Option<RequestId>,
3096 ) -> std::result::Result<Self, JsonrpcErrorError> {
3097 let request_id =
3098 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3099 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3100 request_id,
3101 message.into(),
3102 )))
3103 }
3104}
3105impl ToMessage<ServerMessage> for ListResourceTemplatesResult {
3106 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3107 ServerMessage::from_message(self, request_id)
3108 }
3109}
3110impl FromMessage<ReadResourceResult> for ServerMessage {
3111 fn from_message(
3112 message: ReadResourceResult,
3113 request_id: Option<RequestId>,
3114 ) -> std::result::Result<Self, JsonrpcErrorError> {
3115 let request_id =
3116 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3117 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3118 request_id,
3119 message.into(),
3120 )))
3121 }
3122}
3123impl ToMessage<ServerMessage> for ReadResourceResult {
3124 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3125 ServerMessage::from_message(self, request_id)
3126 }
3127}
3128impl FromMessage<ListPromptsResult> for ServerMessage {
3129 fn from_message(
3130 message: ListPromptsResult,
3131 request_id: Option<RequestId>,
3132 ) -> std::result::Result<Self, JsonrpcErrorError> {
3133 let request_id =
3134 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3135 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3136 request_id,
3137 message.into(),
3138 )))
3139 }
3140}
3141impl ToMessage<ServerMessage> for ListPromptsResult {
3142 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3143 ServerMessage::from_message(self, request_id)
3144 }
3145}
3146impl FromMessage<GetPromptResult> for ServerMessage {
3147 fn from_message(
3148 message: GetPromptResult,
3149 request_id: Option<RequestId>,
3150 ) -> std::result::Result<Self, JsonrpcErrorError> {
3151 let request_id =
3152 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3153 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3154 request_id,
3155 message.into(),
3156 )))
3157 }
3158}
3159impl ToMessage<ServerMessage> for GetPromptResult {
3160 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3161 ServerMessage::from_message(self, request_id)
3162 }
3163}
3164impl FromMessage<ListToolsResult> for ServerMessage {
3165 fn from_message(
3166 message: ListToolsResult,
3167 request_id: Option<RequestId>,
3168 ) -> std::result::Result<Self, JsonrpcErrorError> {
3169 let request_id =
3170 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3171 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3172 request_id,
3173 message.into(),
3174 )))
3175 }
3176}
3177impl ToMessage<ServerMessage> for ListToolsResult {
3178 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3179 ServerMessage::from_message(self, request_id)
3180 }
3181}
3182impl FromMessage<CallToolResult> for ServerMessage {
3183 fn from_message(message: CallToolResult, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
3184 let request_id =
3185 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3186 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3187 request_id,
3188 message.into(),
3189 )))
3190 }
3191}
3192impl ToMessage<ServerMessage> for CallToolResult {
3193 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3194 ServerMessage::from_message(self, request_id)
3195 }
3196}
3197impl FromMessage<CompleteResult> for ServerMessage {
3198 fn from_message(message: CompleteResult, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
3199 let request_id =
3200 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3201 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3202 request_id,
3203 message.into(),
3204 )))
3205 }
3206}
3207impl ToMessage<ServerMessage> for CompleteResult {
3208 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3209 ServerMessage::from_message(self, request_id)
3210 }
3211}
3212impl FromMessage<CancelledNotification> for ServerMessage {
3213 fn from_message(
3214 message: CancelledNotification,
3215 request_id: Option<RequestId>,
3216 ) -> std::result::Result<Self, JsonrpcErrorError> {
3217 if request_id.is_some() {
3218 return Err(JsonrpcErrorError::internal_error()
3219 .with_message("request_id expected to be None for Notifications!".to_string()));
3220 }
3221 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3222 }
3223}
3224impl ToMessage<ServerMessage> for CancelledNotification {
3225 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3226 ServerMessage::from_message(self, request_id)
3227 }
3228}
3229impl FromMessage<ProgressNotification> for ServerMessage {
3230 fn from_message(
3231 message: ProgressNotification,
3232 request_id: Option<RequestId>,
3233 ) -> std::result::Result<Self, JsonrpcErrorError> {
3234 if request_id.is_some() {
3235 return Err(JsonrpcErrorError::internal_error()
3236 .with_message("request_id expected to be None for Notifications!".to_string()));
3237 }
3238 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3239 }
3240}
3241impl ToMessage<ServerMessage> for ProgressNotification {
3242 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3243 ServerMessage::from_message(self, request_id)
3244 }
3245}
3246impl FromMessage<ResourceListChangedNotification> for ServerMessage {
3247 fn from_message(
3248 message: ResourceListChangedNotification,
3249 request_id: Option<RequestId>,
3250 ) -> std::result::Result<Self, JsonrpcErrorError> {
3251 if request_id.is_some() {
3252 return Err(JsonrpcErrorError::internal_error()
3253 .with_message("request_id expected to be None for Notifications!".to_string()));
3254 }
3255 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3256 }
3257}
3258impl ToMessage<ServerMessage> for ResourceListChangedNotification {
3259 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3260 ServerMessage::from_message(self, request_id)
3261 }
3262}
3263impl FromMessage<ResourceUpdatedNotification> for ServerMessage {
3264 fn from_message(
3265 message: ResourceUpdatedNotification,
3266 request_id: Option<RequestId>,
3267 ) -> std::result::Result<Self, JsonrpcErrorError> {
3268 if request_id.is_some() {
3269 return Err(JsonrpcErrorError::internal_error()
3270 .with_message("request_id expected to be None for Notifications!".to_string()));
3271 }
3272 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3273 }
3274}
3275impl ToMessage<ServerMessage> for ResourceUpdatedNotification {
3276 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3277 ServerMessage::from_message(self, request_id)
3278 }
3279}
3280impl FromMessage<PromptListChangedNotification> for ServerMessage {
3281 fn from_message(
3282 message: PromptListChangedNotification,
3283 request_id: Option<RequestId>,
3284 ) -> std::result::Result<Self, JsonrpcErrorError> {
3285 if request_id.is_some() {
3286 return Err(JsonrpcErrorError::internal_error()
3287 .with_message("request_id expected to be None for Notifications!".to_string()));
3288 }
3289 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3290 }
3291}
3292impl ToMessage<ServerMessage> for PromptListChangedNotification {
3293 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3294 ServerMessage::from_message(self, request_id)
3295 }
3296}
3297impl FromMessage<ToolListChangedNotification> for ServerMessage {
3298 fn from_message(
3299 message: ToolListChangedNotification,
3300 request_id: Option<RequestId>,
3301 ) -> std::result::Result<Self, JsonrpcErrorError> {
3302 if request_id.is_some() {
3303 return Err(JsonrpcErrorError::internal_error()
3304 .with_message("request_id expected to be None for Notifications!".to_string()));
3305 }
3306 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3307 }
3308}
3309impl ToMessage<ServerMessage> for ToolListChangedNotification {
3310 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3311 ServerMessage::from_message(self, request_id)
3312 }
3313}
3314impl FromMessage<LoggingMessageNotification> for ServerMessage {
3315 fn from_message(
3316 message: LoggingMessageNotification,
3317 request_id: Option<RequestId>,
3318 ) -> std::result::Result<Self, JsonrpcErrorError> {
3319 if request_id.is_some() {
3320 return Err(JsonrpcErrorError::internal_error()
3321 .with_message("request_id expected to be None for Notifications!".to_string()));
3322 }
3323 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3324 }
3325}
3326impl ToMessage<ServerMessage> for LoggingMessageNotification {
3327 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3328 ServerMessage::from_message(self, request_id)
3329 }
3330}
3331impl TryFrom<RequestFromClient> for InitializeRequest {
3332 type Error = JsonrpcErrorError;
3333 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3334 let matched_type: ClientRequest = value.try_into()?;
3335 if let ClientRequest::InitializeRequest(result) = matched_type {
3336 Ok(result)
3337 } else {
3338 Err(JsonrpcErrorError::internal_error().with_message("Not a InitializeRequest".to_string()))
3339 }
3340 }
3341}
3342impl TryFrom<RequestFromClient> for PingRequest {
3343 type Error = JsonrpcErrorError;
3344 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3345 let matched_type: ClientRequest = value.try_into()?;
3346 if let ClientRequest::PingRequest(result) = matched_type {
3347 Ok(result)
3348 } else {
3349 Err(JsonrpcErrorError::internal_error().with_message("Not a PingRequest".to_string()))
3350 }
3351 }
3352}
3353impl TryFrom<RequestFromClient> for ListResourcesRequest {
3354 type Error = JsonrpcErrorError;
3355 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3356 let matched_type: ClientRequest = value.try_into()?;
3357 if let ClientRequest::ListResourcesRequest(result) = matched_type {
3358 Ok(result)
3359 } else {
3360 Err(JsonrpcErrorError::internal_error().with_message("Not a ListResourcesRequest".to_string()))
3361 }
3362 }
3363}
3364impl TryFrom<RequestFromClient> for ListResourceTemplatesRequest {
3365 type Error = JsonrpcErrorError;
3366 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3367 let matched_type: ClientRequest = value.try_into()?;
3368 if let ClientRequest::ListResourceTemplatesRequest(result) = matched_type {
3369 Ok(result)
3370 } else {
3371 Err(JsonrpcErrorError::internal_error().with_message("Not a ListResourceTemplatesRequest".to_string()))
3372 }
3373 }
3374}
3375impl TryFrom<RequestFromClient> for ReadResourceRequest {
3376 type Error = JsonrpcErrorError;
3377 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3378 let matched_type: ClientRequest = value.try_into()?;
3379 if let ClientRequest::ReadResourceRequest(result) = matched_type {
3380 Ok(result)
3381 } else {
3382 Err(JsonrpcErrorError::internal_error().with_message("Not a ReadResourceRequest".to_string()))
3383 }
3384 }
3385}
3386impl TryFrom<RequestFromClient> for SubscribeRequest {
3387 type Error = JsonrpcErrorError;
3388 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3389 let matched_type: ClientRequest = value.try_into()?;
3390 if let ClientRequest::SubscribeRequest(result) = matched_type {
3391 Ok(result)
3392 } else {
3393 Err(JsonrpcErrorError::internal_error().with_message("Not a SubscribeRequest".to_string()))
3394 }
3395 }
3396}
3397impl TryFrom<RequestFromClient> for UnsubscribeRequest {
3398 type Error = JsonrpcErrorError;
3399 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3400 let matched_type: ClientRequest = value.try_into()?;
3401 if let ClientRequest::UnsubscribeRequest(result) = matched_type {
3402 Ok(result)
3403 } else {
3404 Err(JsonrpcErrorError::internal_error().with_message("Not a UnsubscribeRequest".to_string()))
3405 }
3406 }
3407}
3408impl TryFrom<RequestFromClient> for ListPromptsRequest {
3409 type Error = JsonrpcErrorError;
3410 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3411 let matched_type: ClientRequest = value.try_into()?;
3412 if let ClientRequest::ListPromptsRequest(result) = matched_type {
3413 Ok(result)
3414 } else {
3415 Err(JsonrpcErrorError::internal_error().with_message("Not a ListPromptsRequest".to_string()))
3416 }
3417 }
3418}
3419impl TryFrom<RequestFromClient> for GetPromptRequest {
3420 type Error = JsonrpcErrorError;
3421 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3422 let matched_type: ClientRequest = value.try_into()?;
3423 if let ClientRequest::GetPromptRequest(result) = matched_type {
3424 Ok(result)
3425 } else {
3426 Err(JsonrpcErrorError::internal_error().with_message("Not a GetPromptRequest".to_string()))
3427 }
3428 }
3429}
3430impl TryFrom<RequestFromClient> for ListToolsRequest {
3431 type Error = JsonrpcErrorError;
3432 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3433 let matched_type: ClientRequest = value.try_into()?;
3434 if let ClientRequest::ListToolsRequest(result) = matched_type {
3435 Ok(result)
3436 } else {
3437 Err(JsonrpcErrorError::internal_error().with_message("Not a ListToolsRequest".to_string()))
3438 }
3439 }
3440}
3441impl TryFrom<RequestFromClient> for CallToolRequest {
3442 type Error = JsonrpcErrorError;
3443 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3444 let matched_type: ClientRequest = value.try_into()?;
3445 if let ClientRequest::CallToolRequest(result) = matched_type {
3446 Ok(result)
3447 } else {
3448 Err(JsonrpcErrorError::internal_error().with_message("Not a CallToolRequest".to_string()))
3449 }
3450 }
3451}
3452impl TryFrom<RequestFromClient> for SetLevelRequest {
3453 type Error = JsonrpcErrorError;
3454 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3455 let matched_type: ClientRequest = value.try_into()?;
3456 if let ClientRequest::SetLevelRequest(result) = matched_type {
3457 Ok(result)
3458 } else {
3459 Err(JsonrpcErrorError::internal_error().with_message("Not a SetLevelRequest".to_string()))
3460 }
3461 }
3462}
3463impl TryFrom<RequestFromClient> for CompleteRequest {
3464 type Error = JsonrpcErrorError;
3465 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3466 let matched_type: ClientRequest = value.try_into()?;
3467 if let ClientRequest::CompleteRequest(result) = matched_type {
3468 Ok(result)
3469 } else {
3470 Err(JsonrpcErrorError::internal_error().with_message("Not a CompleteRequest".to_string()))
3471 }
3472 }
3473}
3474impl TryFrom<ResultFromClient> for Result {
3475 type Error = JsonrpcErrorError;
3476 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3477 let matched_type: ClientResult = value.try_into()?;
3478 if let ClientResult::Result(result) = matched_type {
3479 Ok(result)
3480 } else {
3481 Err(JsonrpcErrorError::internal_error().with_message("Not a Result".to_string()))
3482 }
3483 }
3484}
3485impl TryFrom<ResultFromClient> for CreateMessageResult {
3486 type Error = JsonrpcErrorError;
3487 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3488 let matched_type: ClientResult = value.try_into()?;
3489 if let ClientResult::CreateMessageResult(result) = matched_type {
3490 Ok(result)
3491 } else {
3492 Err(JsonrpcErrorError::internal_error().with_message("Not a CreateMessageResult".to_string()))
3493 }
3494 }
3495}
3496impl TryFrom<ResultFromClient> for ListRootsResult {
3497 type Error = JsonrpcErrorError;
3498 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3499 let matched_type: ClientResult = value.try_into()?;
3500 if let ClientResult::ListRootsResult(result) = matched_type {
3501 Ok(result)
3502 } else {
3503 Err(JsonrpcErrorError::internal_error().with_message("Not a ListRootsResult".to_string()))
3504 }
3505 }
3506}
3507impl TryFrom<NotificationFromClient> for CancelledNotification {
3508 type Error = JsonrpcErrorError;
3509 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
3510 let matched_type: ClientNotification = value.try_into()?;
3511 if let ClientNotification::CancelledNotification(result) = matched_type {
3512 Ok(result)
3513 } else {
3514 Err(JsonrpcErrorError::internal_error().with_message("Not a CancelledNotification".to_string()))
3515 }
3516 }
3517}
3518impl TryFrom<NotificationFromClient> for InitializedNotification {
3519 type Error = JsonrpcErrorError;
3520 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
3521 let matched_type: ClientNotification = value.try_into()?;
3522 if let ClientNotification::InitializedNotification(result) = matched_type {
3523 Ok(result)
3524 } else {
3525 Err(JsonrpcErrorError::internal_error().with_message("Not a InitializedNotification".to_string()))
3526 }
3527 }
3528}
3529impl TryFrom<NotificationFromClient> for ProgressNotification {
3530 type Error = JsonrpcErrorError;
3531 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
3532 let matched_type: ClientNotification = value.try_into()?;
3533 if let ClientNotification::ProgressNotification(result) = matched_type {
3534 Ok(result)
3535 } else {
3536 Err(JsonrpcErrorError::internal_error().with_message("Not a ProgressNotification".to_string()))
3537 }
3538 }
3539}
3540impl TryFrom<NotificationFromClient> for RootsListChangedNotification {
3541 type Error = JsonrpcErrorError;
3542 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
3543 let matched_type: ClientNotification = value.try_into()?;
3544 if let ClientNotification::RootsListChangedNotification(result) = matched_type {
3545 Ok(result)
3546 } else {
3547 Err(JsonrpcErrorError::internal_error().with_message("Not a RootsListChangedNotification".to_string()))
3548 }
3549 }
3550}
3551impl TryFrom<RequestFromServer> for PingRequest {
3552 type Error = JsonrpcErrorError;
3553 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
3554 let matched_type: ServerRequest = value.try_into()?;
3555 if let ServerRequest::PingRequest(result) = matched_type {
3556 Ok(result)
3557 } else {
3558 Err(JsonrpcErrorError::internal_error().with_message("Not a PingRequest".to_string()))
3559 }
3560 }
3561}
3562impl TryFrom<RequestFromServer> for CreateMessageRequest {
3563 type Error = JsonrpcErrorError;
3564 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
3565 let matched_type: ServerRequest = value.try_into()?;
3566 if let ServerRequest::CreateMessageRequest(result) = matched_type {
3567 Ok(result)
3568 } else {
3569 Err(JsonrpcErrorError::internal_error().with_message("Not a CreateMessageRequest".to_string()))
3570 }
3571 }
3572}
3573impl TryFrom<RequestFromServer> for ListRootsRequest {
3574 type Error = JsonrpcErrorError;
3575 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
3576 let matched_type: ServerRequest = value.try_into()?;
3577 if let ServerRequest::ListRootsRequest(result) = matched_type {
3578 Ok(result)
3579 } else {
3580 Err(JsonrpcErrorError::internal_error().with_message("Not a ListRootsRequest".to_string()))
3581 }
3582 }
3583}
3584impl TryFrom<ResultFromServer> for Result {
3585 type Error = JsonrpcErrorError;
3586 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3587 let matched_type: ServerResult = value.try_into()?;
3588 if let ServerResult::Result(result) = matched_type {
3589 Ok(result)
3590 } else {
3591 Err(JsonrpcErrorError::internal_error().with_message("Not a Result".to_string()))
3592 }
3593 }
3594}
3595impl TryFrom<ResultFromServer> for InitializeResult {
3596 type Error = JsonrpcErrorError;
3597 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3598 let matched_type: ServerResult = value.try_into()?;
3599 if let ServerResult::InitializeResult(result) = matched_type {
3600 Ok(result)
3601 } else {
3602 Err(JsonrpcErrorError::internal_error().with_message("Not a InitializeResult".to_string()))
3603 }
3604 }
3605}
3606impl TryFrom<ResultFromServer> for ListResourcesResult {
3607 type Error = JsonrpcErrorError;
3608 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3609 let matched_type: ServerResult = value.try_into()?;
3610 if let ServerResult::ListResourcesResult(result) = matched_type {
3611 Ok(result)
3612 } else {
3613 Err(JsonrpcErrorError::internal_error().with_message("Not a ListResourcesResult".to_string()))
3614 }
3615 }
3616}
3617impl TryFrom<ResultFromServer> for ListResourceTemplatesResult {
3618 type Error = JsonrpcErrorError;
3619 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3620 let matched_type: ServerResult = value.try_into()?;
3621 if let ServerResult::ListResourceTemplatesResult(result) = matched_type {
3622 Ok(result)
3623 } else {
3624 Err(JsonrpcErrorError::internal_error().with_message("Not a ListResourceTemplatesResult".to_string()))
3625 }
3626 }
3627}
3628impl TryFrom<ResultFromServer> for ReadResourceResult {
3629 type Error = JsonrpcErrorError;
3630 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3631 let matched_type: ServerResult = value.try_into()?;
3632 if let ServerResult::ReadResourceResult(result) = matched_type {
3633 Ok(result)
3634 } else {
3635 Err(JsonrpcErrorError::internal_error().with_message("Not a ReadResourceResult".to_string()))
3636 }
3637 }
3638}
3639impl TryFrom<ResultFromServer> for ListPromptsResult {
3640 type Error = JsonrpcErrorError;
3641 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3642 let matched_type: ServerResult = value.try_into()?;
3643 if let ServerResult::ListPromptsResult(result) = matched_type {
3644 Ok(result)
3645 } else {
3646 Err(JsonrpcErrorError::internal_error().with_message("Not a ListPromptsResult".to_string()))
3647 }
3648 }
3649}
3650impl TryFrom<ResultFromServer> for GetPromptResult {
3651 type Error = JsonrpcErrorError;
3652 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3653 let matched_type: ServerResult = value.try_into()?;
3654 if let ServerResult::GetPromptResult(result) = matched_type {
3655 Ok(result)
3656 } else {
3657 Err(JsonrpcErrorError::internal_error().with_message("Not a GetPromptResult".to_string()))
3658 }
3659 }
3660}
3661impl TryFrom<ResultFromServer> for ListToolsResult {
3662 type Error = JsonrpcErrorError;
3663 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3664 let matched_type: ServerResult = value.try_into()?;
3665 if let ServerResult::ListToolsResult(result) = matched_type {
3666 Ok(result)
3667 } else {
3668 Err(JsonrpcErrorError::internal_error().with_message("Not a ListToolsResult".to_string()))
3669 }
3670 }
3671}
3672impl TryFrom<ResultFromServer> for CallToolResult {
3673 type Error = JsonrpcErrorError;
3674 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3675 let matched_type: ServerResult = value.try_into()?;
3676 if let ServerResult::CallToolResult(result) = matched_type {
3677 Ok(result)
3678 } else {
3679 Err(JsonrpcErrorError::internal_error().with_message("Not a CallToolResult".to_string()))
3680 }
3681 }
3682}
3683impl TryFrom<ResultFromServer> for CompleteResult {
3684 type Error = JsonrpcErrorError;
3685 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3686 let matched_type: ServerResult = value.try_into()?;
3687 if let ServerResult::CompleteResult(result) = matched_type {
3688 Ok(result)
3689 } else {
3690 Err(JsonrpcErrorError::internal_error().with_message("Not a CompleteResult".to_string()))
3691 }
3692 }
3693}
3694impl TryFrom<NotificationFromServer> for CancelledNotification {
3695 type Error = JsonrpcErrorError;
3696 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
3697 let matched_type: ServerNotification = value.try_into()?;
3698 if let ServerNotification::CancelledNotification(result) = matched_type {
3699 Ok(result)
3700 } else {
3701 Err(JsonrpcErrorError::internal_error().with_message("Not a CancelledNotification".to_string()))
3702 }
3703 }
3704}
3705impl TryFrom<NotificationFromServer> for ProgressNotification {
3706 type Error = JsonrpcErrorError;
3707 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
3708 let matched_type: ServerNotification = value.try_into()?;
3709 if let ServerNotification::ProgressNotification(result) = matched_type {
3710 Ok(result)
3711 } else {
3712 Err(JsonrpcErrorError::internal_error().with_message("Not a ProgressNotification".to_string()))
3713 }
3714 }
3715}
3716impl TryFrom<NotificationFromServer> for ResourceListChangedNotification {
3717 type Error = JsonrpcErrorError;
3718 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
3719 let matched_type: ServerNotification = value.try_into()?;
3720 if let ServerNotification::ResourceListChangedNotification(result) = matched_type {
3721 Ok(result)
3722 } else {
3723 Err(JsonrpcErrorError::internal_error().with_message("Not a ResourceListChangedNotification".to_string()))
3724 }
3725 }
3726}
3727impl TryFrom<NotificationFromServer> for ResourceUpdatedNotification {
3728 type Error = JsonrpcErrorError;
3729 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
3730 let matched_type: ServerNotification = value.try_into()?;
3731 if let ServerNotification::ResourceUpdatedNotification(result) = matched_type {
3732 Ok(result)
3733 } else {
3734 Err(JsonrpcErrorError::internal_error().with_message("Not a ResourceUpdatedNotification".to_string()))
3735 }
3736 }
3737}
3738impl TryFrom<NotificationFromServer> for PromptListChangedNotification {
3739 type Error = JsonrpcErrorError;
3740 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
3741 let matched_type: ServerNotification = value.try_into()?;
3742 if let ServerNotification::PromptListChangedNotification(result) = matched_type {
3743 Ok(result)
3744 } else {
3745 Err(JsonrpcErrorError::internal_error().with_message("Not a PromptListChangedNotification".to_string()))
3746 }
3747 }
3748}
3749impl TryFrom<NotificationFromServer> for ToolListChangedNotification {
3750 type Error = JsonrpcErrorError;
3751 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
3752 let matched_type: ServerNotification = value.try_into()?;
3753 if let ServerNotification::ToolListChangedNotification(result) = matched_type {
3754 Ok(result)
3755 } else {
3756 Err(JsonrpcErrorError::internal_error().with_message("Not a ToolListChangedNotification".to_string()))
3757 }
3758 }
3759}
3760impl TryFrom<NotificationFromServer> for LoggingMessageNotification {
3761 type Error = JsonrpcErrorError;
3762 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
3763 let matched_type: ServerNotification = value.try_into()?;
3764 if let ServerNotification::LoggingMessageNotification(result) = matched_type {
3765 Ok(result)
3766 } else {
3767 Err(JsonrpcErrorError::internal_error().with_message("Not a LoggingMessageNotification".to_string()))
3768 }
3769 }
3770}
3771#[cfg(test)]
3773mod tests {
3774 use super::*;
3775 use serde_json::json;
3776
3777 #[test]
3778 fn test_detect_message_type() {
3779 let message = ClientJsonrpcRequest::new(RequestId::Integer(0), PingRequest::new(None).into());
3781 let result = detect_message_type(&json!(message));
3782 assert!(matches!(result, MessageTypes::Request));
3783
3784 let result = detect_message_type(&json!({
3787 "id":0,
3788 "method":"add_numbers",
3789 "params":{},
3790 "jsonrpc":"2.0"
3791 }));
3792 assert!(matches!(result, MessageTypes::Request));
3793
3794 let message = ClientJsonrpcNotification::new(RootsListChangedNotification::new(None).into());
3796 let result = detect_message_type(&json!(message));
3797 assert!(matches!(result, MessageTypes::Notification));
3798
3799 let result = detect_message_type(&json!({
3801 "method":"notifications/email_sent",
3802 "jsonrpc":"2.0"
3803 }));
3804 assert!(matches!(result, MessageTypes::Notification));
3805
3806 let message = ClientJsonrpcResponse::new(
3808 RequestId::Integer(0),
3809 ListRootsResult {
3810 meta: None,
3811 roots: vec![],
3812 }
3813 .into(),
3814 );
3815 let result = detect_message_type(&json!(message));
3816 assert!(matches!(result, MessageTypes::Response));
3817
3818 let result = detect_message_type(&json!({
3821 "id":1,
3822 "jsonrpc":"2.0",
3823 "result":"{}",
3824 }));
3825 assert!(matches!(result, MessageTypes::Response));
3826
3827 let message = JsonrpcError::create(
3829 RequestId::Integer(0),
3830 RpcErrorCodes::INVALID_PARAMS,
3831 "Invalid params!".to_string(),
3832 None,
3833 );
3834 let result = detect_message_type(&json!(message));
3835 assert!(matches!(result, MessageTypes::Error));
3836
3837 let result = detect_message_type(&json!({}));
3839 assert!(matches!(result, MessageTypes::Request));
3840 }
3841}