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 #[deprecated(since = "0.1.8", note = "Use `ClientResult::Result` with extra attributes instead.")]
591 CustomResult(serde_json::Value),
592}
593
594impl TryFrom<ResultFromClient> for ClientResult {
595 type Error = JsonrpcErrorError;
596 fn try_from(value: ResultFromClient) -> result::Result<Self, Self::Error> {
597 if let ResultFromClient::ClientResult(client_result) = value {
598 Ok(client_result)
599 } else {
600 Err(JsonrpcErrorError::internal_error().with_message("Not a ClientResult".to_string()))
601 }
602 }
603}
604
605impl From<ClientResult> for ResultFromClient {
606 fn from(value: ClientResult) -> Self {
607 Self::ClientResult(value)
608 }
609}
610
611impl From<serde_json::Value> for ResultFromClient {
612 fn from(value: serde_json::Value) -> Self {
613 Self::CustomResult(value)
614 }
615}
616
617impl<'de> serde::Deserialize<'de> for ResultFromClient {
618 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
619 where
620 D: serde::Deserializer<'de>,
621 {
622 let raw_value = Value::deserialize(deserializer)?;
623
624 let result = ClientResult::deserialize(&raw_value);
625
626 match result {
627 Ok(client_result) => Ok(Self::ClientResult(client_result)),
628 Err(_) => Ok(Self::CustomResult(raw_value)),
629 }
630 }
631}
632
633impl FromStr for ClientMessage {
638 type Err = JsonrpcErrorError;
639
640 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
641 serde_json::from_str(s)
642 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
643 }
644}
645
646impl Display for ClientMessage {
647 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
648 write!(
649 f,
650 "{}",
651 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
652 )
653 }
654}
655
656#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
663#[serde(untagged)]
664pub enum ServerMessage {
665 Request(ServerJsonrpcRequest),
666 Notification(ServerJsonrpcNotification),
667 Response(ServerJsonrpcResponse),
668 Error(JsonrpcError),
669}
670
671impl ServerMessage {
672 pub fn as_response(self) -> std::result::Result<ServerJsonrpcResponse, JsonrpcErrorError> {
682 if let Self::Response(response) = self {
683 Ok(response)
684 } else {
685 Err(JsonrpcErrorError::internal_error().with_message(format!(
686 "Invalid message type, expected: \"{}\" received\"{}\"",
687 MessageTypes::Response,
688 self.message_type()
689 )))
690 }
691 }
692
693 pub fn as_request(self) -> std::result::Result<ServerJsonrpcRequest, JsonrpcErrorError> {
703 if let Self::Request(request) = self {
704 Ok(request)
705 } else {
706 Err(JsonrpcErrorError::internal_error().with_message(format!(
707 "Invalid message type, expected: \"{}\" received\"{}\"",
708 MessageTypes::Request,
709 self.message_type()
710 )))
711 }
712 }
713
714 pub fn as_notification(self) -> std::result::Result<ServerJsonrpcNotification, JsonrpcErrorError> {
724 if let Self::Notification(notification) = self {
725 Ok(notification)
726 } else {
727 Err(JsonrpcErrorError::internal_error().with_message(format!(
728 "Invalid message type, expected: \"{}\" received\"{}\"",
729 MessageTypes::Notification,
730 self.message_type()
731 )))
732 }
733 }
734
735 pub fn as_error(self) -> std::result::Result<JsonrpcError, JsonrpcErrorError> {
745 if let Self::Error(error) = self {
746 Ok(error)
747 } else {
748 Err(JsonrpcErrorError::internal_error().with_message(format!(
749 "Invalid message type, expected: \"{}\" received\"{}\"",
750 MessageTypes::Error,
751 self.message_type()
752 )))
753 }
754 }
755}
756
757impl RPCMessage for ServerMessage {
758 fn request_id(&self) -> Option<&RequestId> {
760 match self {
761 ServerMessage::Request(server_jsonrpc_request) => Some(&server_jsonrpc_request.id),
763 ServerMessage::Notification(_) => None,
765 ServerMessage::Response(server_jsonrpc_response) => Some(&server_jsonrpc_response.id),
767 ServerMessage::Error(jsonrpc_error) => Some(&jsonrpc_error.id),
769 }
770 }
771
772 fn jsonrpc(&self) -> &str {
773 match self {
774 ServerMessage::Request(server_jsonrpc_request) => server_jsonrpc_request.jsonrpc(),
776 ServerMessage::Notification(notification) => notification.jsonrpc(),
778 ServerMessage::Response(server_jsonrpc_response) => server_jsonrpc_response.jsonrpc(),
780 ServerMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
782 }
783 }
784}
785
786impl MCPMessage for ServerMessage {
788 fn is_response(&self) -> bool {
790 matches!(self, ServerMessage::Response(_))
791 }
792
793 fn is_request(&self) -> bool {
795 matches!(self, ServerMessage::Request(_))
796 }
797
798 fn is_notification(&self) -> bool {
800 matches!(self, ServerMessage::Notification(_))
801 }
802
803 fn is_error(&self) -> bool {
805 matches!(self, ServerMessage::Error(_))
806 }
807
808 fn message_type(&self) -> MessageTypes {
810 match self {
811 ServerMessage::Request(_) => MessageTypes::Request,
812 ServerMessage::Notification(_) => MessageTypes::Notification,
813 ServerMessage::Response(_) => MessageTypes::Response,
814 ServerMessage::Error(_) => MessageTypes::Error,
815 }
816 }
817}
818
819impl FromStr for ServerMessage {
820 type Err = JsonrpcErrorError;
821
822 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
823 serde_json::from_str(s)
824 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
825 }
826}
827
828impl Display for ServerMessage {
829 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
830 write!(
831 f,
832 "{}",
833 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
834 )
835 }
836}
837
838#[derive(Clone, Debug)]
844pub struct ServerJsonrpcRequest {
845 pub id: RequestId,
846 jsonrpc: ::std::string::String,
847 pub method: String,
848 pub request: RequestFromServer,
849}
850
851impl ServerJsonrpcRequest {
852 pub fn new(id: RequestId, request: RequestFromServer) -> Self {
853 let method = request.method().to_string();
854 Self {
855 id,
856 jsonrpc: JSONRPC_VERSION.to_string(),
857 method,
858 request,
859 }
860 }
861 pub fn jsonrpc(&self) -> &::std::string::String {
862 &self.jsonrpc
863 }
864}
865
866impl Display for ServerJsonrpcRequest {
868 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
869 write!(
870 f,
871 "{}",
872 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
873 )
874 }
875}
876
877impl FromStr for ServerJsonrpcRequest {
878 type Err = JsonrpcErrorError;
879
880 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
881 serde_json::from_str(s)
882 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
883 }
884}
885#[derive(::serde::Serialize, Clone, Debug)]
892#[serde(untagged)]
893pub enum RequestFromServer {
894 ServerRequest(ServerRequest),
895 CustomRequest(serde_json::Value),
896}
897
898impl TryFrom<RequestFromServer> for ServerRequest {
899 type Error = JsonrpcErrorError;
900 fn try_from(value: RequestFromServer) -> result::Result<Self, Self::Error> {
901 if let RequestFromServer::ServerRequest(server_request) = value {
902 Ok(server_request)
903 } else {
904 Err(JsonrpcErrorError::internal_error().with_message("Not a ServerRequest".to_string()))
905 }
906 }
907}
908
909impl RequestFromServer {
910 #[deprecated(since = "0.1.4", note = "Use `method()` instead.")]
911 pub fn get_method(&self) -> &str {
912 match self {
913 RequestFromServer::ServerRequest(request) => request.method(),
914 RequestFromServer::CustomRequest(request) => request["method"].as_str().unwrap(),
915 }
916 }
917
918 pub fn method(&self) -> &str {
919 match self {
920 RequestFromServer::ServerRequest(request) => request.method(),
921 RequestFromServer::CustomRequest(request) => request["method"].as_str().unwrap(),
922 }
923 }
924}
925
926impl From<ServerRequest> for RequestFromServer {
927 fn from(value: ServerRequest) -> Self {
928 Self::ServerRequest(value)
929 }
930}
931
932impl From<serde_json::Value> for RequestFromServer {
933 fn from(value: serde_json::Value) -> Self {
934 Self::CustomRequest(value)
935 }
936}
937
938impl<'de> serde::Deserialize<'de> for RequestFromServer {
939 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
940 where
941 D: serde::Deserializer<'de>,
942 {
943 let raw_value = Value::deserialize(deserializer)?;
944
945 let server_result = ServerRequest::deserialize(&raw_value);
946
947 match server_result {
948 Ok(server_request) => Ok(Self::ServerRequest(server_request)),
949 Err(_) => Ok(Self::CustomRequest(raw_value)),
950 }
951 }
952}
953
954#[derive(Clone, Debug)]
960pub struct ServerJsonrpcNotification {
961 jsonrpc: ::std::string::String,
962 pub method: ::std::string::String,
963 pub notification: NotificationFromServer,
964}
965
966impl ServerJsonrpcNotification {
967 pub fn new(notification: NotificationFromServer) -> Self {
968 let method = notification.method().to_string();
969 Self {
970 jsonrpc: JSONRPC_VERSION.to_string(),
971 method,
972 notification,
973 }
974 }
975 pub fn jsonrpc(&self) -> &::std::string::String {
976 &self.jsonrpc
977 }
978}
979
980impl Display for ServerJsonrpcNotification {
982 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
983 write!(
984 f,
985 "{}",
986 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
987 )
988 }
989}
990
991impl FromStr for ServerJsonrpcNotification {
992 type Err = JsonrpcErrorError;
993
994 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
995 serde_json::from_str(s)
996 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
997 }
998}
999#[derive(::serde::Serialize, Clone, Debug)]
1006#[serde(untagged)]
1007pub enum NotificationFromServer {
1008 ServerNotification(ServerNotification),
1009 CustomNotification(serde_json::Value),
1010}
1011
1012impl TryFrom<NotificationFromServer> for ServerNotification {
1013 type Error = JsonrpcErrorError;
1014 fn try_from(value: NotificationFromServer) -> result::Result<Self, Self::Error> {
1015 if let NotificationFromServer::ServerNotification(server_notification) = value {
1016 Ok(server_notification)
1017 } else {
1018 Err(JsonrpcErrorError::internal_error().with_message("Not a ServerNotification".to_string()))
1019 }
1020 }
1021}
1022
1023impl NotificationFromServer {
1024 #[deprecated(since = "0.1.4", note = "Use `method()` instead.")]
1025 pub fn get_method(&self) -> &str {
1026 match self {
1027 NotificationFromServer::ServerNotification(notification) => notification.method(),
1028 NotificationFromServer::CustomNotification(notification) => notification["method"].as_str().unwrap(),
1029 }
1030 }
1031
1032 pub fn method(&self) -> &str {
1033 match self {
1034 NotificationFromServer::ServerNotification(notification) => notification.method(),
1035 NotificationFromServer::CustomNotification(notification) => notification["method"].as_str().unwrap(),
1036 }
1037 }
1038}
1039
1040impl<'de> serde::Deserialize<'de> for NotificationFromServer {
1041 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
1042 where
1043 D: serde::Deserializer<'de>,
1044 {
1045 let raw_value = Value::deserialize(deserializer)?;
1046
1047 let result = ServerNotification::deserialize(&raw_value);
1048
1049 match result {
1050 Ok(client_notification) => Ok(Self::ServerNotification(client_notification)),
1051 Err(_) => Ok(Self::CustomNotification(raw_value)),
1052 }
1053 }
1054}
1055
1056#[derive(Clone, Debug)]
1062pub struct ServerJsonrpcResponse {
1063 pub id: RequestId,
1064 jsonrpc: ::std::string::String,
1065 pub result: ResultFromServer,
1066}
1067
1068impl ServerJsonrpcResponse {
1069 pub fn new(id: RequestId, result: ResultFromServer) -> Self {
1070 Self {
1071 id,
1072 jsonrpc: JSONRPC_VERSION.to_string(),
1073 result,
1074 }
1075 }
1076 pub fn jsonrpc(&self) -> &::std::string::String {
1077 &self.jsonrpc
1078 }
1079}
1080
1081impl Display for ServerJsonrpcResponse {
1083 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1084 write!(
1085 f,
1086 "{}",
1087 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
1088 )
1089 }
1090}
1091
1092impl FromStr for ServerJsonrpcResponse {
1093 type Err = JsonrpcErrorError;
1094
1095 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1096 serde_json::from_str(s)
1097 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1098 }
1099}
1100#[derive(::serde::Serialize, Clone, Debug)]
1107#[serde(untagged)]
1108pub enum ResultFromServer {
1109 ServerResult(ServerResult),
1110 #[deprecated(since = "0.1.8", note = "Use `ServerResult::Result` with extra attributes instead.")]
1111 CustomResult(serde_json::Value),
1112}
1113
1114impl TryFrom<ResultFromServer> for ServerResult {
1115 type Error = JsonrpcErrorError;
1116 fn try_from(value: ResultFromServer) -> result::Result<Self, Self::Error> {
1117 if let ResultFromServer::ServerResult(server_result) = value {
1118 Ok(server_result)
1119 } else {
1120 Err(JsonrpcErrorError::internal_error().with_message("Not a ServerResult".to_string()))
1121 }
1122 }
1123}
1124
1125impl From<ServerResult> for ResultFromServer {
1126 fn from(value: ServerResult) -> Self {
1127 Self::ServerResult(value)
1128 }
1129}
1130
1131impl From<serde_json::Value> for ResultFromServer {
1132 fn from(value: serde_json::Value) -> Self {
1133 Self::CustomResult(value)
1134 }
1135}
1136
1137impl<'de> serde::Deserialize<'de> for ResultFromServer {
1138 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
1139 where
1140 D: serde::Deserializer<'de>,
1141 {
1142 let raw_value = Value::deserialize(deserializer)?;
1143
1144 let result = ServerResult::deserialize(&raw_value);
1145
1146 match result {
1147 Ok(server_result) => Ok(Self::ServerResult(server_result)),
1148 Err(_) => Ok(Self::CustomResult(raw_value)),
1149 }
1150 }
1151}
1152
1153impl Display for JsonrpcError {
1159 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1160 write!(
1161 f,
1162 "{}",
1163 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
1164 )
1165 }
1166}
1167
1168impl FromStr for JsonrpcError {
1169 type Err = JsonrpcErrorError;
1170
1171 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1172 serde_json::from_str(s)
1173 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1174 }
1175}
1176
1177#[derive(::serde::Serialize, Clone, Debug)]
1186#[serde(untagged)]
1187pub enum MessageFromServer {
1188 RequestFromServer(RequestFromServer),
1189 ResultFromServer(ResultFromServer),
1190 NotificationFromServer(NotificationFromServer),
1191 Error(JsonrpcErrorError),
1192}
1193
1194impl From<RequestFromServer> for MessageFromServer {
1195 fn from(value: RequestFromServer) -> Self {
1196 Self::RequestFromServer(value)
1197 }
1198}
1199
1200impl From<ResultFromServer> for MessageFromServer {
1201 fn from(value: ResultFromServer) -> Self {
1202 Self::ResultFromServer(value)
1203 }
1204}
1205
1206impl From<NotificationFromServer> for MessageFromServer {
1207 fn from(value: NotificationFromServer) -> Self {
1208 Self::NotificationFromServer(value)
1209 }
1210}
1211
1212impl From<JsonrpcErrorError> for MessageFromServer {
1213 fn from(value: JsonrpcErrorError) -> Self {
1214 Self::Error(value)
1215 }
1216}
1217
1218impl MCPMessage for MessageFromServer {
1219 fn is_response(&self) -> bool {
1220 matches!(self, MessageFromServer::ResultFromServer(_))
1221 }
1222
1223 fn is_request(&self) -> bool {
1224 matches!(self, MessageFromServer::RequestFromServer(_))
1225 }
1226
1227 fn is_notification(&self) -> bool {
1228 matches!(self, MessageFromServer::NotificationFromServer(_))
1229 }
1230
1231 fn is_error(&self) -> bool {
1232 matches!(self, MessageFromServer::Error(_))
1233 }
1234
1235 fn message_type(&self) -> MessageTypes {
1236 match self {
1237 MessageFromServer::RequestFromServer(_) => MessageTypes::Request,
1238 MessageFromServer::ResultFromServer(_) => MessageTypes::Response,
1239 MessageFromServer::NotificationFromServer(_) => MessageTypes::Notification,
1240 MessageFromServer::Error(_) => MessageTypes::Error,
1241 }
1242 }
1243}
1244
1245impl FromMessage<MessageFromServer> for ServerMessage {
1246 fn from_message(
1247 message: MessageFromServer,
1248 request_id: Option<RequestId>,
1249 ) -> std::result::Result<Self, JsonrpcErrorError> {
1250 match message {
1251 MessageFromServer::RequestFromServer(request_from_server) => {
1252 let request_id = request_id
1253 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1254 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(
1255 request_id,
1256 request_from_server,
1257 )))
1258 }
1259 MessageFromServer::ResultFromServer(result_from_server) => {
1260 let request_id = request_id
1261 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1262 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
1263 request_id,
1264 result_from_server,
1265 )))
1266 }
1267 MessageFromServer::NotificationFromServer(notification_from_server) => {
1268 if request_id.is_some() {
1269 return Err(JsonrpcErrorError::internal_error()
1270 .with_message("request_id expected to be None for Notifications!".to_string()));
1271 }
1272 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(
1273 notification_from_server,
1274 )))
1275 }
1276 MessageFromServer::Error(jsonrpc_error_error) => {
1277 let request_id = request_id
1278 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1279 Ok(ServerMessage::Error(JsonrpcError::new(jsonrpc_error_error, request_id)))
1280 }
1281 }
1282 }
1283}
1284
1285#[derive(::serde::Serialize, Clone, Debug)]
1294#[serde(untagged)]
1295pub enum MessageFromClient {
1296 RequestFromClient(RequestFromClient),
1297 ResultFromClient(ResultFromClient),
1298 NotificationFromClient(NotificationFromClient),
1299 Error(JsonrpcErrorError),
1300}
1301
1302impl From<RequestFromClient> for MessageFromClient {
1303 fn from(value: RequestFromClient) -> Self {
1304 Self::RequestFromClient(value)
1305 }
1306}
1307
1308impl From<ResultFromClient> for MessageFromClient {
1309 fn from(value: ResultFromClient) -> Self {
1310 Self::ResultFromClient(value)
1311 }
1312}
1313
1314impl From<NotificationFromClient> for MessageFromClient {
1315 fn from(value: NotificationFromClient) -> Self {
1316 Self::NotificationFromClient(value)
1317 }
1318}
1319
1320impl From<JsonrpcErrorError> for MessageFromClient {
1321 fn from(value: JsonrpcErrorError) -> Self {
1322 Self::Error(value)
1323 }
1324}
1325
1326impl MCPMessage for MessageFromClient {
1327 fn is_response(&self) -> bool {
1328 matches!(self, MessageFromClient::ResultFromClient(_))
1329 }
1330
1331 fn is_request(&self) -> bool {
1332 matches!(self, MessageFromClient::RequestFromClient(_))
1333 }
1334
1335 fn is_notification(&self) -> bool {
1336 matches!(self, MessageFromClient::NotificationFromClient(_))
1337 }
1338
1339 fn is_error(&self) -> bool {
1340 matches!(self, MessageFromClient::Error(_))
1341 }
1342
1343 fn message_type(&self) -> MessageTypes {
1344 match self {
1345 MessageFromClient::RequestFromClient(_) => MessageTypes::Request,
1346 MessageFromClient::ResultFromClient(_) => MessageTypes::Response,
1347 MessageFromClient::NotificationFromClient(_) => MessageTypes::Notification,
1348 MessageFromClient::Error(_) => MessageTypes::Error,
1349 }
1350 }
1351}
1352
1353impl FromMessage<MessageFromClient> for ClientMessage {
1354 fn from_message(
1355 message: MessageFromClient,
1356 request_id: Option<RequestId>,
1357 ) -> std::result::Result<Self, JsonrpcErrorError> {
1358 match message {
1359 MessageFromClient::RequestFromClient(request_from_client) => {
1360 let request_id = request_id
1361 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1362 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(
1363 request_id,
1364 request_from_client,
1365 )))
1366 }
1367 MessageFromClient::ResultFromClient(result_from_client) => {
1368 let request_id = request_id
1369 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1370 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
1371 request_id,
1372 result_from_client,
1373 )))
1374 }
1375 MessageFromClient::NotificationFromClient(notification_from_client) => {
1376 if request_id.is_some() {
1377 return Err(JsonrpcErrorError::internal_error()
1378 .with_message("request_id expected to be None for Notifications!".to_string()));
1379 }
1380
1381 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(
1382 notification_from_client,
1383 )))
1384 }
1385 MessageFromClient::Error(jsonrpc_error_error) => {
1386 let request_id = request_id
1387 .ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
1388 Ok(ClientMessage::Error(JsonrpcError::new(jsonrpc_error_error, request_id)))
1389 }
1390 }
1391 }
1392}
1393
1394#[derive(Debug)]
1401pub struct UnknownTool(pub String);
1402
1403impl core::fmt::Display for UnknownTool {
1405 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1406 write!(f, "Unknown tool: {}", self.0)
1408 }
1409}
1410
1411impl std::error::Error for UnknownTool {}
1413
1414#[derive(Debug)]
1420pub struct CallToolError(pub Box<dyn std::error::Error>);
1421
1422impl CallToolError {
1424 pub fn new<E: std::error::Error + 'static>(err: E) -> Self {
1426 CallToolError(Box::new(err))
1428 }
1429
1430 pub fn unknown_tool(tool_name: String) -> Self {
1432 CallToolError(Box::new(UnknownTool(tool_name)))
1434 }
1435}
1436
1437impl core::fmt::Display for CallToolError {
1439 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1440 write!(f, "{}", self.0)
1441 }
1442}
1443
1444impl std::error::Error for CallToolError {
1446 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1447 self.0.source()
1448 }
1449}
1450
1451impl From<CallToolError> for CallToolResult {
1453 fn from(value: CallToolError) -> Self {
1454 CallToolResult::with_error(value)
1456 }
1457}
1458
1459impl CallToolResult {
1463 pub fn with_error(error: CallToolError) -> Self {
1465 Self {
1466 content: vec![CallToolResultContentItem::TextContent(TextContent::new(
1467 None,
1468 error.to_string(), ))],
1470 is_error: Some(true), meta: None,
1472 }
1473 }
1474
1475 pub fn text_content(text_content: String, text_annotations: Option<TextContentAnnotations>) -> Self {
1477 Self {
1478 content: vec![TextContent::new(text_annotations, text_content).into()],
1479 is_error: None,
1480 meta: None,
1481 }
1482 }
1483
1484 pub fn image_content(data: String, mime_type: String, annotations: Option<ImageContentAnnotations>) -> Self {
1486 Self {
1487 content: vec![ImageContent::new(annotations, data, mime_type).into()],
1488 is_error: None,
1489 meta: None,
1490 }
1491 }
1492
1493 pub fn embedded_resource(resource: EmbeddedResourceResource, annotations: Option<EmbeddedResourceAnnotations>) -> Self {
1495 Self {
1496 content: vec![EmbeddedResource::new(annotations, resource).into()],
1497 is_error: None,
1498 meta: None,
1499 }
1500 }
1501
1502 pub fn with_meta(mut self, meta: Option<serde_json::Map<String, Value>>) -> Self {
1504 self.meta = meta;
1505 self
1506 }
1507}
1508
1509impl CallToolRequest {
1510 pub fn tool_name(&self) -> &str {
1518 &self.params.name
1519 }
1520}
1521
1522impl ::serde::Serialize for ClientJsonrpcRequest {
1524 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1525 where
1526 S: ::serde::Serializer,
1527 {
1528 let mut state = serializer.serialize_struct("JsonrpcRequest", 4)?;
1529 state.serialize_field("id", &self.id)?;
1530 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1531 state.serialize_field("method", &self.method)?;
1532 use ClientRequest::*;
1533 match &self.request {
1534 RequestFromClient::ClientRequest(message) => match message {
1535 InitializeRequest(msg) => state.serialize_field("params", &msg.params)?,
1536 PingRequest(msg) => {
1537 if let Some(params) = &msg.params {
1538 state.serialize_field("params", params)?
1539 }
1540 }
1541 ListResourcesRequest(msg) => state.serialize_field("params", &msg.params)?,
1542 ListResourceTemplatesRequest(msg) => {
1543 if let Some(params) = &msg.params {
1544 state.serialize_field("params", params)?
1545 }
1546 }
1547 ReadResourceRequest(msg) => state.serialize_field("params", &msg.params)?,
1548 SubscribeRequest(msg) => state.serialize_field("params", &msg.params)?,
1549 UnsubscribeRequest(msg) => state.serialize_field("params", &msg.params)?,
1550 ListPromptsRequest(msg) => {
1551 if let Some(params) = &msg.params {
1552 state.serialize_field("params", params)?
1553 }
1554 }
1555 GetPromptRequest(msg) => state.serialize_field("params", &msg.params)?,
1556 ListToolsRequest(msg) => {
1557 if let Some(params) = &msg.params {
1558 state.serialize_field("params", params)?
1559 }
1560 }
1561 CallToolRequest(msg) => state.serialize_field("params", &msg.params)?,
1562 SetLevelRequest(msg) => state.serialize_field("params", &msg.params)?,
1563 CompleteRequest(msg) => state.serialize_field("params", &msg.params)?,
1564 },
1565 RequestFromClient::CustomRequest(value) => state.serialize_field("params", value)?,
1566 }
1567 state.end()
1568 }
1569}
1570impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcRequest {
1571 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1572 where
1573 D: ::serde::Deserializer<'de>,
1574 {
1575 use serde::de::{self, MapAccess, Visitor};
1576 use std::fmt;
1577 struct ClientJsonrpcRequestVisitor;
1578 impl<'de> Visitor<'de> for ClientJsonrpcRequestVisitor {
1579 type Value = ClientJsonrpcRequest;
1580 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1581 formatter.write_str("a valid JSON-RPC request object")
1582 }
1583 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcRequest, M::Error>
1584 where
1585 M: MapAccess<'de>,
1586 {
1587 let mut id: Option<RequestId> = None;
1588 let mut jsonrpc: Option<String> = None;
1589 let mut method: Option<String> = None;
1590 let mut params: Option<Value> = None;
1591 while let Some(key) = map.next_key::<String>()? {
1592 match key.as_str() {
1593 "id" => id = Some(map.next_value()?),
1594 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1595 "method" => method = Some(map.next_value()?),
1596 "params" => params = Some(map.next_value()?),
1597 _ => {
1598 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1599 }
1600 }
1601 }
1602 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1603 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1604 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1605 let params = params.unwrap_or_default();
1606 let req_object = json!({ "method" : method, "params" : params });
1607 let request = serde_json::from_value::<RequestFromClient>(req_object).map_err(de::Error::custom)?;
1608 Ok(ClientJsonrpcRequest {
1609 id,
1610 jsonrpc,
1611 method,
1612 request,
1613 })
1614 }
1615 }
1616 deserializer.deserialize_struct(
1617 "JsonrpcRequest",
1618 &["id", "jsonrpc", "method", "params"],
1619 ClientJsonrpcRequestVisitor,
1620 )
1621 }
1622}
1623impl ::serde::Serialize for ServerJsonrpcRequest {
1624 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1625 where
1626 S: ::serde::Serializer,
1627 {
1628 let mut state = serializer.serialize_struct("JsonrpcRequest", 4)?;
1629 state.serialize_field("id", &self.id)?;
1630 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1631 state.serialize_field("method", &self.method)?;
1632 use ServerRequest::*;
1633 match &self.request {
1634 RequestFromServer::ServerRequest(message) => match message {
1635 PingRequest(msg) => {
1636 if let Some(params) = &msg.params {
1637 state.serialize_field("params", params)?
1638 }
1639 }
1640 CreateMessageRequest(msg) => state.serialize_field("params", &msg.params)?,
1641 ListRootsRequest(msg) => {
1642 if let Some(params) = &msg.params {
1643 state.serialize_field("params", params)?
1644 }
1645 }
1646 },
1647 RequestFromServer::CustomRequest(value) => state.serialize_field("params", value)?,
1648 }
1649 state.end()
1650 }
1651}
1652impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcRequest {
1653 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1654 where
1655 D: ::serde::Deserializer<'de>,
1656 {
1657 use serde::de::{self, MapAccess, Visitor};
1658 use std::fmt;
1659 struct ServerJsonrpcRequestVisitor;
1660 impl<'de> Visitor<'de> for ServerJsonrpcRequestVisitor {
1661 type Value = ServerJsonrpcRequest;
1662 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1663 formatter.write_str("a valid JSON-RPC request object")
1664 }
1665 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcRequest, M::Error>
1666 where
1667 M: MapAccess<'de>,
1668 {
1669 let mut id: Option<RequestId> = None;
1670 let mut jsonrpc: Option<String> = None;
1671 let mut method: Option<String> = None;
1672 let mut params: Option<Value> = None;
1673 while let Some(key) = map.next_key::<String>()? {
1674 match key.as_str() {
1675 "id" => id = Some(map.next_value()?),
1676 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1677 "method" => method = Some(map.next_value()?),
1678 "params" => params = Some(map.next_value()?),
1679 _ => {
1680 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1681 }
1682 }
1683 }
1684 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1685 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1686 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1687 let params = params.unwrap_or_default();
1688 let req_object = json!({ "method" : method, "params" : params });
1689 let request = serde_json::from_value::<RequestFromServer>(req_object).map_err(de::Error::custom)?;
1690 Ok(ServerJsonrpcRequest {
1691 id,
1692 jsonrpc,
1693 method,
1694 request,
1695 })
1696 }
1697 }
1698 deserializer.deserialize_struct(
1699 "JsonrpcRequest",
1700 &["id", "jsonrpc", "method", "params"],
1701 ServerJsonrpcRequestVisitor,
1702 )
1703 }
1704}
1705impl ::serde::Serialize for ClientJsonrpcNotification {
1706 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1707 where
1708 S: ::serde::Serializer,
1709 {
1710 let mut state = serializer.serialize_struct("JsonrpcNotification", 3)?;
1711 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1712 state.serialize_field("method", &self.method)?;
1713 use ClientNotification::*;
1714 match &self.notification {
1715 NotificationFromClient::ClientNotification(message) => match message {
1716 CancelledNotification(msg) => state.serialize_field("params", &msg.params)?,
1717 InitializedNotification(msg) => {
1718 if let Some(params) = &msg.params {
1719 state.serialize_field("params", params)?
1720 }
1721 }
1722 ProgressNotification(msg) => state.serialize_field("params", &msg.params)?,
1723 RootsListChangedNotification(msg) => {
1724 if let Some(params) = &msg.params {
1725 state.serialize_field("params", params)?
1726 }
1727 }
1728 },
1729 NotificationFromClient::CustomNotification(value) => state.serialize_field("params", value)?,
1730 }
1731 state.end()
1732 }
1733}
1734impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcNotification {
1735 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1736 where
1737 D: ::serde::Deserializer<'de>,
1738 {
1739 use serde::de::{self, MapAccess, Visitor};
1740 use std::fmt;
1741 struct ClientJsonrpcNotificationVisitor;
1742 impl<'de> Visitor<'de> for ClientJsonrpcNotificationVisitor {
1743 type Value = ClientJsonrpcNotification;
1744 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1745 formatter.write_str("a valid JSON-RPC notification object")
1746 }
1747 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcNotification, M::Error>
1748 where
1749 M: MapAccess<'de>,
1750 {
1751 let mut jsonrpc: Option<String> = None;
1752 let mut method: Option<String> = None;
1753 let mut params: Option<Value> = None;
1754 while let Some(key) = map.next_key::<String>()? {
1755 match key.as_str() {
1756 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1757 "method" => method = Some(map.next_value()?),
1758 "params" => params = Some(map.next_value()?),
1759 _ => {
1760 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1761 }
1762 }
1763 }
1764 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1765 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1766 let params = params.unwrap_or_default();
1767 let req_object = json!({ "method" : method, "params" : params });
1768 let notification =
1769 serde_json::from_value::<NotificationFromClient>(req_object).map_err(de::Error::custom)?;
1770 Ok(ClientJsonrpcNotification {
1771 jsonrpc,
1772 method,
1773 notification,
1774 })
1775 }
1776 }
1777 deserializer.deserialize_struct(
1778 "JsonrpcRequest",
1779 &["jsonrpc", "method", "params"],
1780 ClientJsonrpcNotificationVisitor,
1781 )
1782 }
1783}
1784impl ::serde::Serialize for ServerJsonrpcNotification {
1785 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1786 where
1787 S: ::serde::Serializer,
1788 {
1789 let mut state = serializer.serialize_struct("JsonrpcNotification", 3)?;
1790 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1791 state.serialize_field("method", &self.method)?;
1792 use ServerNotification::*;
1793 match &self.notification {
1794 NotificationFromServer::ServerNotification(message) => match message {
1795 CancelledNotification(msg) => state.serialize_field("params", &msg.params)?,
1796 ProgressNotification(msg) => state.serialize_field("params", &msg.params)?,
1797 ResourceListChangedNotification(msg) => {
1798 if let Some(params) = &msg.params {
1799 state.serialize_field("params", params)?
1800 }
1801 }
1802 ResourceUpdatedNotification(msg) => state.serialize_field("params", &msg.params)?,
1803 PromptListChangedNotification(msg) => {
1804 if let Some(params) = &msg.params {
1805 state.serialize_field("params", params)?
1806 }
1807 }
1808 ToolListChangedNotification(msg) => {
1809 if let Some(params) = &msg.params {
1810 state.serialize_field("params", params)?
1811 }
1812 }
1813 LoggingMessageNotification(msg) => state.serialize_field("params", &msg.params)?,
1814 },
1815 NotificationFromServer::CustomNotification(value) => state.serialize_field("params", value)?,
1816 }
1817 state.end()
1818 }
1819}
1820impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcNotification {
1821 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1822 where
1823 D: ::serde::Deserializer<'de>,
1824 {
1825 use serde::de::{self, MapAccess, Visitor};
1826 use std::fmt;
1827 struct ServerJsonrpcNotificationVisitor;
1828 impl<'de> Visitor<'de> for ServerJsonrpcNotificationVisitor {
1829 type Value = ServerJsonrpcNotification;
1830 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1831 formatter.write_str("a valid JSON-RPC notification object")
1832 }
1833 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcNotification, M::Error>
1834 where
1835 M: MapAccess<'de>,
1836 {
1837 let mut jsonrpc: Option<String> = None;
1838 let mut method: Option<String> = None;
1839 let mut params: Option<Value> = None;
1840 while let Some(key) = map.next_key::<String>()? {
1841 match key.as_str() {
1842 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1843 "method" => method = Some(map.next_value()?),
1844 "params" => params = Some(map.next_value()?),
1845 _ => {
1846 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1847 }
1848 }
1849 }
1850 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1851 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1852 let params = params.unwrap_or_default();
1853 let req_object = json!({ "method" : method, "params" : params });
1854 let notification =
1855 serde_json::from_value::<NotificationFromServer>(req_object).map_err(de::Error::custom)?;
1856 Ok(ServerJsonrpcNotification {
1857 jsonrpc,
1858 method,
1859 notification,
1860 })
1861 }
1862 }
1863 deserializer.deserialize_struct(
1864 "JsonrpcRequest",
1865 &["jsonrpc", "method", "params"],
1866 ServerJsonrpcNotificationVisitor,
1867 )
1868 }
1869}
1870impl ::serde::Serialize for ServerJsonrpcResponse {
1871 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1872 where
1873 S: ::serde::Serializer,
1874 {
1875 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
1876 state.serialize_field("id", &self.id)?;
1877 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1878 state.serialize_field("result", &self.result)?;
1879 state.end()
1880 }
1881}
1882impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcResponse {
1883 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1884 where
1885 D: ::serde::Deserializer<'de>,
1886 {
1887 use serde::de::{self, MapAccess, Visitor};
1888 use std::fmt;
1889 struct ServerJsonrpcResultVisitor;
1890 impl<'de> Visitor<'de> for ServerJsonrpcResultVisitor {
1891 type Value = ServerJsonrpcResponse;
1892 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1893 formatter.write_str("a valid JSON-RPC response object")
1894 }
1895 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcResponse, M::Error>
1896 where
1897 M: MapAccess<'de>,
1898 {
1899 let mut id: Option<RequestId> = None;
1900 let mut jsonrpc: Option<String> = None;
1901 let mut result: Option<Value> = None;
1902 while let Some(key) = map.next_key::<String>()? {
1903 match key.as_str() {
1904 "id" => id = Some(map.next_value()?),
1905 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1906 "result" => result = Some(map.next_value()?),
1907 _ => {
1908 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
1909 }
1910 }
1911 }
1912 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1913 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1914 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
1915 let result = serde_json::from_value::<ResultFromServer>(result).map_err(de::Error::custom)?;
1916 Ok(ServerJsonrpcResponse { id, jsonrpc, result })
1917 }
1918 }
1919 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ServerJsonrpcResultVisitor)
1920 }
1921}
1922impl ::serde::Serialize for ClientJsonrpcResponse {
1923 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1924 where
1925 S: ::serde::Serializer,
1926 {
1927 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
1928 state.serialize_field("id", &self.id)?;
1929 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1930 state.serialize_field("result", &self.result)?;
1931 state.end()
1932 }
1933}
1934impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcResponse {
1935 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1936 where
1937 D: ::serde::Deserializer<'de>,
1938 {
1939 use serde::de::{self, MapAccess, Visitor};
1940 use std::fmt;
1941 struct ClientJsonrpcResultVisitor;
1942 impl<'de> Visitor<'de> for ClientJsonrpcResultVisitor {
1943 type Value = ClientJsonrpcResponse;
1944 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1945 formatter.write_str("a valid JSON-RPC response object")
1946 }
1947 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcResponse, M::Error>
1948 where
1949 M: MapAccess<'de>,
1950 {
1951 let mut id: Option<RequestId> = None;
1952 let mut jsonrpc: Option<String> = None;
1953 let mut result: Option<Value> = None;
1954 while let Some(key) = map.next_key::<String>()? {
1955 match key.as_str() {
1956 "id" => id = Some(map.next_value()?),
1957 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1958 "result" => result = Some(map.next_value()?),
1959 _ => {
1960 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
1961 }
1962 }
1963 }
1964 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1965 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1966 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
1967 let result = serde_json::from_value::<ResultFromClient>(result).map_err(de::Error::custom)?;
1968 Ok(ClientJsonrpcResponse { id, jsonrpc, result })
1969 }
1970 }
1971 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ClientJsonrpcResultVisitor)
1972 }
1973}
1974impl From<InitializeRequest> for RequestFromClient {
1975 fn from(value: InitializeRequest) -> Self {
1976 Self::ClientRequest(value.into())
1977 }
1978}
1979impl From<PingRequest> for RequestFromClient {
1980 fn from(value: PingRequest) -> Self {
1981 Self::ClientRequest(value.into())
1982 }
1983}
1984impl From<ListResourcesRequest> for RequestFromClient {
1985 fn from(value: ListResourcesRequest) -> Self {
1986 Self::ClientRequest(value.into())
1987 }
1988}
1989impl From<ListResourceTemplatesRequest> for RequestFromClient {
1990 fn from(value: ListResourceTemplatesRequest) -> Self {
1991 Self::ClientRequest(value.into())
1992 }
1993}
1994impl From<ReadResourceRequest> for RequestFromClient {
1995 fn from(value: ReadResourceRequest) -> Self {
1996 Self::ClientRequest(value.into())
1997 }
1998}
1999impl From<SubscribeRequest> for RequestFromClient {
2000 fn from(value: SubscribeRequest) -> Self {
2001 Self::ClientRequest(value.into())
2002 }
2003}
2004impl From<UnsubscribeRequest> for RequestFromClient {
2005 fn from(value: UnsubscribeRequest) -> Self {
2006 Self::ClientRequest(value.into())
2007 }
2008}
2009impl From<ListPromptsRequest> for RequestFromClient {
2010 fn from(value: ListPromptsRequest) -> Self {
2011 Self::ClientRequest(value.into())
2012 }
2013}
2014impl From<GetPromptRequest> for RequestFromClient {
2015 fn from(value: GetPromptRequest) -> Self {
2016 Self::ClientRequest(value.into())
2017 }
2018}
2019impl From<ListToolsRequest> for RequestFromClient {
2020 fn from(value: ListToolsRequest) -> Self {
2021 Self::ClientRequest(value.into())
2022 }
2023}
2024impl From<CallToolRequest> for RequestFromClient {
2025 fn from(value: CallToolRequest) -> Self {
2026 Self::ClientRequest(value.into())
2027 }
2028}
2029impl From<SetLevelRequest> for RequestFromClient {
2030 fn from(value: SetLevelRequest) -> Self {
2031 Self::ClientRequest(value.into())
2032 }
2033}
2034impl From<CompleteRequest> for RequestFromClient {
2035 fn from(value: CompleteRequest) -> Self {
2036 Self::ClientRequest(value.into())
2037 }
2038}
2039impl From<InitializeRequest> for MessageFromClient {
2040 fn from(value: InitializeRequest) -> Self {
2041 MessageFromClient::RequestFromClient(value.into())
2042 }
2043}
2044impl From<PingRequest> for MessageFromClient {
2045 fn from(value: PingRequest) -> Self {
2046 MessageFromClient::RequestFromClient(value.into())
2047 }
2048}
2049impl From<ListResourcesRequest> for MessageFromClient {
2050 fn from(value: ListResourcesRequest) -> Self {
2051 MessageFromClient::RequestFromClient(value.into())
2052 }
2053}
2054impl From<ListResourceTemplatesRequest> for MessageFromClient {
2055 fn from(value: ListResourceTemplatesRequest) -> Self {
2056 MessageFromClient::RequestFromClient(value.into())
2057 }
2058}
2059impl From<ReadResourceRequest> for MessageFromClient {
2060 fn from(value: ReadResourceRequest) -> Self {
2061 MessageFromClient::RequestFromClient(value.into())
2062 }
2063}
2064impl From<SubscribeRequest> for MessageFromClient {
2065 fn from(value: SubscribeRequest) -> Self {
2066 MessageFromClient::RequestFromClient(value.into())
2067 }
2068}
2069impl From<UnsubscribeRequest> for MessageFromClient {
2070 fn from(value: UnsubscribeRequest) -> Self {
2071 MessageFromClient::RequestFromClient(value.into())
2072 }
2073}
2074impl From<ListPromptsRequest> for MessageFromClient {
2075 fn from(value: ListPromptsRequest) -> Self {
2076 MessageFromClient::RequestFromClient(value.into())
2077 }
2078}
2079impl From<GetPromptRequest> for MessageFromClient {
2080 fn from(value: GetPromptRequest) -> Self {
2081 MessageFromClient::RequestFromClient(value.into())
2082 }
2083}
2084impl From<ListToolsRequest> for MessageFromClient {
2085 fn from(value: ListToolsRequest) -> Self {
2086 MessageFromClient::RequestFromClient(value.into())
2087 }
2088}
2089impl From<CallToolRequest> for MessageFromClient {
2090 fn from(value: CallToolRequest) -> Self {
2091 MessageFromClient::RequestFromClient(value.into())
2092 }
2093}
2094impl From<SetLevelRequest> for MessageFromClient {
2095 fn from(value: SetLevelRequest) -> Self {
2096 MessageFromClient::RequestFromClient(value.into())
2097 }
2098}
2099impl From<CompleteRequest> for MessageFromClient {
2100 fn from(value: CompleteRequest) -> Self {
2101 MessageFromClient::RequestFromClient(value.into())
2102 }
2103}
2104impl From<CancelledNotification> for NotificationFromClient {
2105 fn from(value: CancelledNotification) -> Self {
2106 Self::ClientNotification(value.into())
2107 }
2108}
2109impl From<InitializedNotification> for NotificationFromClient {
2110 fn from(value: InitializedNotification) -> Self {
2111 Self::ClientNotification(value.into())
2112 }
2113}
2114impl From<ProgressNotification> for NotificationFromClient {
2115 fn from(value: ProgressNotification) -> Self {
2116 Self::ClientNotification(value.into())
2117 }
2118}
2119impl From<RootsListChangedNotification> for NotificationFromClient {
2120 fn from(value: RootsListChangedNotification) -> Self {
2121 Self::ClientNotification(value.into())
2122 }
2123}
2124impl From<CancelledNotification> for ClientJsonrpcNotification {
2125 fn from(value: CancelledNotification) -> Self {
2126 Self::new(value.into())
2127 }
2128}
2129impl From<InitializedNotification> for ClientJsonrpcNotification {
2130 fn from(value: InitializedNotification) -> Self {
2131 Self::new(value.into())
2132 }
2133}
2134impl From<ProgressNotification> for ClientJsonrpcNotification {
2135 fn from(value: ProgressNotification) -> Self {
2136 Self::new(value.into())
2137 }
2138}
2139impl From<RootsListChangedNotification> for ClientJsonrpcNotification {
2140 fn from(value: RootsListChangedNotification) -> Self {
2141 Self::new(value.into())
2142 }
2143}
2144impl From<CancelledNotification> for MessageFromClient {
2145 fn from(value: CancelledNotification) -> Self {
2146 MessageFromClient::NotificationFromClient(value.into())
2147 }
2148}
2149impl From<InitializedNotification> for MessageFromClient {
2150 fn from(value: InitializedNotification) -> Self {
2151 MessageFromClient::NotificationFromClient(value.into())
2152 }
2153}
2154impl From<ProgressNotification> for MessageFromClient {
2155 fn from(value: ProgressNotification) -> Self {
2156 MessageFromClient::NotificationFromClient(value.into())
2157 }
2158}
2159impl From<RootsListChangedNotification> for MessageFromClient {
2160 fn from(value: RootsListChangedNotification) -> Self {
2161 MessageFromClient::NotificationFromClient(value.into())
2162 }
2163}
2164impl From<Result> for ResultFromClient {
2165 fn from(value: Result) -> Self {
2166 Self::ClientResult(value.into())
2167 }
2168}
2169impl From<CreateMessageResult> for ResultFromClient {
2170 fn from(value: CreateMessageResult) -> Self {
2171 Self::ClientResult(value.into())
2172 }
2173}
2174impl From<ListRootsResult> for ResultFromClient {
2175 fn from(value: ListRootsResult) -> Self {
2176 Self::ClientResult(value.into())
2177 }
2178}
2179impl From<Result> for MessageFromClient {
2180 fn from(value: Result) -> Self {
2181 MessageFromClient::ResultFromClient(value.into())
2182 }
2183}
2184impl From<CreateMessageResult> for MessageFromClient {
2185 fn from(value: CreateMessageResult) -> Self {
2186 MessageFromClient::ResultFromClient(value.into())
2187 }
2188}
2189impl From<ListRootsResult> for MessageFromClient {
2190 fn from(value: ListRootsResult) -> Self {
2191 MessageFromClient::ResultFromClient(value.into())
2192 }
2193}
2194#[allow(non_camel_case_types)]
2196pub enum SdkErrorCodes {
2197 CONNECTION_CLOSED = -32000,
2198 REQUEST_TIMEOUT = -32001,
2199}
2200impl core::fmt::Display for SdkErrorCodes {
2201 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2202 match self {
2203 SdkErrorCodes::CONNECTION_CLOSED => write!(f, "Connection closed"),
2204 SdkErrorCodes::REQUEST_TIMEOUT => write!(f, "Request timeout"),
2205 }
2206 }
2207}
2208impl From<SdkErrorCodes> for i64 {
2209 fn from(code: SdkErrorCodes) -> Self {
2210 code as i64
2211 }
2212}
2213#[derive(Debug)]
2214pub struct SdkError {
2215 pub code: i64,
2217 pub data: ::std::option::Option<::serde_json::Value>,
2219 pub message: ::std::string::String,
2221}
2222impl core::fmt::Display for SdkError {
2223 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2224 write!(f, "MCP error {}: {}", self.code, self.message)
2225 }
2226}
2227impl std::error::Error for SdkError {
2228 fn description(&self) -> &str {
2229 &self.message
2230 }
2231}
2232impl SdkError {
2233 pub fn new(
2234 error_code: SdkErrorCodes,
2235 message: ::std::string::String,
2236 data: ::std::option::Option<::serde_json::Value>,
2237 ) -> Self {
2238 Self {
2239 code: error_code.into(),
2240 data,
2241 message,
2242 }
2243 }
2244 pub fn connection_closed() -> Self {
2245 Self {
2246 code: SdkErrorCodes::CONNECTION_CLOSED.into(),
2247 data: None,
2248 message: SdkErrorCodes::CONNECTION_CLOSED.to_string(),
2249 }
2250 }
2251 pub fn request_timeout(timeout: u128) -> Self {
2252 Self {
2253 code: SdkErrorCodes::REQUEST_TIMEOUT.into(),
2254 data: Some(json!({ "timeout" : timeout })),
2255 message: SdkErrorCodes::REQUEST_TIMEOUT.to_string(),
2256 }
2257 }
2258}
2259#[allow(non_camel_case_types)]
2261pub enum RpcErrorCodes {
2262 PARSE_ERROR = -32700isize,
2263 INVALID_REQUEST = -32600isize,
2264 METHOD_NOT_FOUND = -32601isize,
2265 INVALID_PARAMS = -32602isize,
2266 INTERNAL_ERROR = -32603isize,
2267}
2268impl From<RpcErrorCodes> for i64 {
2269 fn from(code: RpcErrorCodes) -> Self {
2270 code as i64
2271 }
2272}
2273impl JsonrpcErrorError {
2274 pub fn new(
2291 error_code: RpcErrorCodes,
2292 message: ::std::string::String,
2293 data: ::std::option::Option<::serde_json::Value>,
2294 ) -> Self {
2295 Self {
2296 code: error_code.into(),
2297 data,
2298 message,
2299 }
2300 }
2301 pub fn method_not_found() -> Self {
2312 Self {
2313 code: RpcErrorCodes::METHOD_NOT_FOUND.into(),
2314 data: None,
2315 message: "Method not found".to_string(),
2316 }
2317 }
2318 pub fn invalid_params() -> Self {
2328 Self {
2329 code: RpcErrorCodes::INVALID_PARAMS.into(),
2330 data: None,
2331 message: "Invalid params".to_string(),
2332 }
2333 }
2334 pub fn invalid_request() -> Self {
2344 Self {
2345 code: RpcErrorCodes::INVALID_REQUEST.into(),
2346 data: None,
2347 message: "Invalid request".to_string(),
2348 }
2349 }
2350 pub fn internal_error() -> Self {
2360 Self {
2361 code: RpcErrorCodes::INTERNAL_ERROR.into(),
2362 data: None,
2363 message: "Internal error".to_string(),
2364 }
2365 }
2366 pub fn parse_error() -> Self {
2376 Self {
2377 code: RpcErrorCodes::PARSE_ERROR.into(),
2378 data: None,
2379 message: "Parse error".to_string(),
2380 }
2381 }
2382 pub fn with_message(mut self, message: String) -> Self {
2392 self.message = message;
2393 self
2394 }
2395 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
2406 self.data = data;
2407 self
2408 }
2409}
2410impl std::error::Error for JsonrpcErrorError {
2411 fn description(&self) -> &str {
2412 &self.message
2413 }
2414}
2415impl Display for JsonrpcErrorError {
2416 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2417 write!(
2418 f,
2419 "{}",
2420 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {}", err))
2421 )
2422 }
2423}
2424impl FromStr for JsonrpcErrorError {
2425 type Err = JsonrpcErrorError;
2426 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2427 serde_json::from_str(s)
2428 .map_err(|error| JsonrpcErrorError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
2429 }
2430}
2431impl JsonrpcError {
2433 pub fn create(
2434 id: RequestId,
2435 error_code: RpcErrorCodes,
2436 error_message: ::std::string::String,
2437 error_data: ::std::option::Option<::serde_json::Value>,
2438 ) -> Self {
2439 Self::new(JsonrpcErrorError::new(error_code, error_message, error_data), id)
2440 }
2441}
2442impl From<CancelledNotification> for NotificationFromServer {
2443 fn from(value: CancelledNotification) -> Self {
2444 Self::ServerNotification(value.into())
2445 }
2446}
2447impl From<ProgressNotification> for NotificationFromServer {
2448 fn from(value: ProgressNotification) -> Self {
2449 Self::ServerNotification(value.into())
2450 }
2451}
2452impl From<ResourceListChangedNotification> for NotificationFromServer {
2453 fn from(value: ResourceListChangedNotification) -> Self {
2454 Self::ServerNotification(value.into())
2455 }
2456}
2457impl From<ResourceUpdatedNotification> for NotificationFromServer {
2458 fn from(value: ResourceUpdatedNotification) -> Self {
2459 Self::ServerNotification(value.into())
2460 }
2461}
2462impl From<PromptListChangedNotification> for NotificationFromServer {
2463 fn from(value: PromptListChangedNotification) -> Self {
2464 Self::ServerNotification(value.into())
2465 }
2466}
2467impl From<ToolListChangedNotification> for NotificationFromServer {
2468 fn from(value: ToolListChangedNotification) -> Self {
2469 Self::ServerNotification(value.into())
2470 }
2471}
2472impl From<LoggingMessageNotification> for NotificationFromServer {
2473 fn from(value: LoggingMessageNotification) -> Self {
2474 Self::ServerNotification(value.into())
2475 }
2476}
2477impl From<CancelledNotification> for ServerJsonrpcNotification {
2478 fn from(value: CancelledNotification) -> Self {
2479 Self::new(value.into())
2480 }
2481}
2482impl From<ProgressNotification> for ServerJsonrpcNotification {
2483 fn from(value: ProgressNotification) -> Self {
2484 Self::new(value.into())
2485 }
2486}
2487impl From<ResourceListChangedNotification> for ServerJsonrpcNotification {
2488 fn from(value: ResourceListChangedNotification) -> Self {
2489 Self::new(value.into())
2490 }
2491}
2492impl From<ResourceUpdatedNotification> for ServerJsonrpcNotification {
2493 fn from(value: ResourceUpdatedNotification) -> Self {
2494 Self::new(value.into())
2495 }
2496}
2497impl From<PromptListChangedNotification> for ServerJsonrpcNotification {
2498 fn from(value: PromptListChangedNotification) -> Self {
2499 Self::new(value.into())
2500 }
2501}
2502impl From<ToolListChangedNotification> for ServerJsonrpcNotification {
2503 fn from(value: ToolListChangedNotification) -> Self {
2504 Self::new(value.into())
2505 }
2506}
2507impl From<LoggingMessageNotification> for ServerJsonrpcNotification {
2508 fn from(value: LoggingMessageNotification) -> Self {
2509 Self::new(value.into())
2510 }
2511}
2512impl From<CancelledNotification> for MessageFromServer {
2513 fn from(value: CancelledNotification) -> Self {
2514 MessageFromServer::NotificationFromServer(value.into())
2515 }
2516}
2517impl From<ProgressNotification> for MessageFromServer {
2518 fn from(value: ProgressNotification) -> Self {
2519 MessageFromServer::NotificationFromServer(value.into())
2520 }
2521}
2522impl From<ResourceListChangedNotification> for MessageFromServer {
2523 fn from(value: ResourceListChangedNotification) -> Self {
2524 MessageFromServer::NotificationFromServer(value.into())
2525 }
2526}
2527impl From<ResourceUpdatedNotification> for MessageFromServer {
2528 fn from(value: ResourceUpdatedNotification) -> Self {
2529 MessageFromServer::NotificationFromServer(value.into())
2530 }
2531}
2532impl From<PromptListChangedNotification> for MessageFromServer {
2533 fn from(value: PromptListChangedNotification) -> Self {
2534 MessageFromServer::NotificationFromServer(value.into())
2535 }
2536}
2537impl From<ToolListChangedNotification> for MessageFromServer {
2538 fn from(value: ToolListChangedNotification) -> Self {
2539 MessageFromServer::NotificationFromServer(value.into())
2540 }
2541}
2542impl From<LoggingMessageNotification> for MessageFromServer {
2543 fn from(value: LoggingMessageNotification) -> Self {
2544 MessageFromServer::NotificationFromServer(value.into())
2545 }
2546}
2547impl From<PingRequest> for RequestFromServer {
2548 fn from(value: PingRequest) -> Self {
2549 Self::ServerRequest(value.into())
2550 }
2551}
2552impl From<CreateMessageRequest> for RequestFromServer {
2553 fn from(value: CreateMessageRequest) -> Self {
2554 Self::ServerRequest(value.into())
2555 }
2556}
2557impl From<ListRootsRequest> for RequestFromServer {
2558 fn from(value: ListRootsRequest) -> Self {
2559 Self::ServerRequest(value.into())
2560 }
2561}
2562impl From<PingRequest> for MessageFromServer {
2563 fn from(value: PingRequest) -> Self {
2564 MessageFromServer::RequestFromServer(value.into())
2565 }
2566}
2567impl From<CreateMessageRequest> for MessageFromServer {
2568 fn from(value: CreateMessageRequest) -> Self {
2569 MessageFromServer::RequestFromServer(value.into())
2570 }
2571}
2572impl From<ListRootsRequest> for MessageFromServer {
2573 fn from(value: ListRootsRequest) -> Self {
2574 MessageFromServer::RequestFromServer(value.into())
2575 }
2576}
2577impl From<Result> for ResultFromServer {
2578 fn from(value: Result) -> Self {
2579 Self::ServerResult(value.into())
2580 }
2581}
2582impl From<InitializeResult> for ResultFromServer {
2583 fn from(value: InitializeResult) -> Self {
2584 Self::ServerResult(value.into())
2585 }
2586}
2587impl From<ListResourcesResult> for ResultFromServer {
2588 fn from(value: ListResourcesResult) -> Self {
2589 Self::ServerResult(value.into())
2590 }
2591}
2592impl From<ListResourceTemplatesResult> for ResultFromServer {
2593 fn from(value: ListResourceTemplatesResult) -> Self {
2594 Self::ServerResult(value.into())
2595 }
2596}
2597impl From<ReadResourceResult> for ResultFromServer {
2598 fn from(value: ReadResourceResult) -> Self {
2599 Self::ServerResult(value.into())
2600 }
2601}
2602impl From<ListPromptsResult> for ResultFromServer {
2603 fn from(value: ListPromptsResult) -> Self {
2604 Self::ServerResult(value.into())
2605 }
2606}
2607impl From<GetPromptResult> for ResultFromServer {
2608 fn from(value: GetPromptResult) -> Self {
2609 Self::ServerResult(value.into())
2610 }
2611}
2612impl From<ListToolsResult> for ResultFromServer {
2613 fn from(value: ListToolsResult) -> Self {
2614 Self::ServerResult(value.into())
2615 }
2616}
2617impl From<CallToolResult> for ResultFromServer {
2618 fn from(value: CallToolResult) -> Self {
2619 Self::ServerResult(value.into())
2620 }
2621}
2622impl From<CompleteResult> for ResultFromServer {
2623 fn from(value: CompleteResult) -> Self {
2624 Self::ServerResult(value.into())
2625 }
2626}
2627impl From<Result> for MessageFromServer {
2628 fn from(value: Result) -> Self {
2629 MessageFromServer::ResultFromServer(value.into())
2630 }
2631}
2632impl From<InitializeResult> for MessageFromServer {
2633 fn from(value: InitializeResult) -> Self {
2634 MessageFromServer::ResultFromServer(value.into())
2635 }
2636}
2637impl From<ListResourcesResult> for MessageFromServer {
2638 fn from(value: ListResourcesResult) -> Self {
2639 MessageFromServer::ResultFromServer(value.into())
2640 }
2641}
2642impl From<ListResourceTemplatesResult> for MessageFromServer {
2643 fn from(value: ListResourceTemplatesResult) -> Self {
2644 MessageFromServer::ResultFromServer(value.into())
2645 }
2646}
2647impl From<ReadResourceResult> for MessageFromServer {
2648 fn from(value: ReadResourceResult) -> Self {
2649 MessageFromServer::ResultFromServer(value.into())
2650 }
2651}
2652impl From<ListPromptsResult> for MessageFromServer {
2653 fn from(value: ListPromptsResult) -> Self {
2654 MessageFromServer::ResultFromServer(value.into())
2655 }
2656}
2657impl From<GetPromptResult> for MessageFromServer {
2658 fn from(value: GetPromptResult) -> Self {
2659 MessageFromServer::ResultFromServer(value.into())
2660 }
2661}
2662impl From<ListToolsResult> for MessageFromServer {
2663 fn from(value: ListToolsResult) -> Self {
2664 MessageFromServer::ResultFromServer(value.into())
2665 }
2666}
2667impl From<CallToolResult> for MessageFromServer {
2668 fn from(value: CallToolResult) -> Self {
2669 MessageFromServer::ResultFromServer(value.into())
2670 }
2671}
2672impl From<CompleteResult> for MessageFromServer {
2673 fn from(value: CompleteResult) -> Self {
2674 MessageFromServer::ResultFromServer(value.into())
2675 }
2676}
2677impl FromMessage<InitializeRequest> for ClientMessage {
2678 fn from_message(
2679 message: InitializeRequest,
2680 request_id: Option<RequestId>,
2681 ) -> std::result::Result<Self, JsonrpcErrorError> {
2682 let request_id =
2683 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2684 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2685 }
2686}
2687impl ToMessage<ClientMessage> for InitializeRequest {
2688 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2689 ClientMessage::from_message(self, request_id)
2690 }
2691}
2692impl FromMessage<PingRequest> for ClientMessage {
2693 fn from_message(message: PingRequest, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
2694 let request_id =
2695 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2696 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2697 }
2698}
2699impl ToMessage<ClientMessage> for PingRequest {
2700 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2701 ClientMessage::from_message(self, request_id)
2702 }
2703}
2704impl FromMessage<ListResourcesRequest> for ClientMessage {
2705 fn from_message(
2706 message: ListResourcesRequest,
2707 request_id: Option<RequestId>,
2708 ) -> std::result::Result<Self, JsonrpcErrorError> {
2709 let request_id =
2710 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2711 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2712 }
2713}
2714impl ToMessage<ClientMessage> for ListResourcesRequest {
2715 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2716 ClientMessage::from_message(self, request_id)
2717 }
2718}
2719impl FromMessage<ListResourceTemplatesRequest> for ClientMessage {
2720 fn from_message(
2721 message: ListResourceTemplatesRequest,
2722 request_id: Option<RequestId>,
2723 ) -> std::result::Result<Self, JsonrpcErrorError> {
2724 let request_id =
2725 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2726 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2727 }
2728}
2729impl ToMessage<ClientMessage> for ListResourceTemplatesRequest {
2730 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2731 ClientMessage::from_message(self, request_id)
2732 }
2733}
2734impl FromMessage<ReadResourceRequest> for ClientMessage {
2735 fn from_message(
2736 message: ReadResourceRequest,
2737 request_id: Option<RequestId>,
2738 ) -> std::result::Result<Self, JsonrpcErrorError> {
2739 let request_id =
2740 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2741 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2742 }
2743}
2744impl ToMessage<ClientMessage> for ReadResourceRequest {
2745 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2746 ClientMessage::from_message(self, request_id)
2747 }
2748}
2749impl FromMessage<SubscribeRequest> for ClientMessage {
2750 fn from_message(
2751 message: SubscribeRequest,
2752 request_id: Option<RequestId>,
2753 ) -> std::result::Result<Self, JsonrpcErrorError> {
2754 let request_id =
2755 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2756 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2757 }
2758}
2759impl ToMessage<ClientMessage> for SubscribeRequest {
2760 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2761 ClientMessage::from_message(self, request_id)
2762 }
2763}
2764impl FromMessage<UnsubscribeRequest> for ClientMessage {
2765 fn from_message(
2766 message: UnsubscribeRequest,
2767 request_id: Option<RequestId>,
2768 ) -> std::result::Result<Self, JsonrpcErrorError> {
2769 let request_id =
2770 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2771 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2772 }
2773}
2774impl ToMessage<ClientMessage> for UnsubscribeRequest {
2775 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2776 ClientMessage::from_message(self, request_id)
2777 }
2778}
2779impl FromMessage<ListPromptsRequest> for ClientMessage {
2780 fn from_message(
2781 message: ListPromptsRequest,
2782 request_id: Option<RequestId>,
2783 ) -> std::result::Result<Self, JsonrpcErrorError> {
2784 let request_id =
2785 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2786 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2787 }
2788}
2789impl ToMessage<ClientMessage> for ListPromptsRequest {
2790 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2791 ClientMessage::from_message(self, request_id)
2792 }
2793}
2794impl FromMessage<GetPromptRequest> for ClientMessage {
2795 fn from_message(
2796 message: GetPromptRequest,
2797 request_id: Option<RequestId>,
2798 ) -> std::result::Result<Self, JsonrpcErrorError> {
2799 let request_id =
2800 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2801 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2802 }
2803}
2804impl ToMessage<ClientMessage> for GetPromptRequest {
2805 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2806 ClientMessage::from_message(self, request_id)
2807 }
2808}
2809impl FromMessage<ListToolsRequest> for ClientMessage {
2810 fn from_message(
2811 message: ListToolsRequest,
2812 request_id: Option<RequestId>,
2813 ) -> std::result::Result<Self, JsonrpcErrorError> {
2814 let request_id =
2815 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2816 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2817 }
2818}
2819impl ToMessage<ClientMessage> for ListToolsRequest {
2820 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2821 ClientMessage::from_message(self, request_id)
2822 }
2823}
2824impl FromMessage<CallToolRequest> for ClientMessage {
2825 fn from_message(
2826 message: CallToolRequest,
2827 request_id: Option<RequestId>,
2828 ) -> std::result::Result<Self, JsonrpcErrorError> {
2829 let request_id =
2830 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2831 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2832 }
2833}
2834impl ToMessage<ClientMessage> for CallToolRequest {
2835 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2836 ClientMessage::from_message(self, request_id)
2837 }
2838}
2839impl FromMessage<SetLevelRequest> for ClientMessage {
2840 fn from_message(
2841 message: SetLevelRequest,
2842 request_id: Option<RequestId>,
2843 ) -> std::result::Result<Self, JsonrpcErrorError> {
2844 let request_id =
2845 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2846 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2847 }
2848}
2849impl ToMessage<ClientMessage> for SetLevelRequest {
2850 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2851 ClientMessage::from_message(self, request_id)
2852 }
2853}
2854impl FromMessage<CompleteRequest> for ClientMessage {
2855 fn from_message(
2856 message: CompleteRequest,
2857 request_id: Option<RequestId>,
2858 ) -> std::result::Result<Self, JsonrpcErrorError> {
2859 let request_id =
2860 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2861 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
2862 }
2863}
2864impl ToMessage<ClientMessage> for CompleteRequest {
2865 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2866 ClientMessage::from_message(self, request_id)
2867 }
2868}
2869impl FromMessage<Result> for ClientMessage {
2870 fn from_message(message: Result, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
2871 let request_id =
2872 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2873 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
2874 request_id,
2875 message.into(),
2876 )))
2877 }
2878}
2879impl ToMessage<ClientMessage> for Result {
2880 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2881 ClientMessage::from_message(self, request_id)
2882 }
2883}
2884impl FromMessage<CreateMessageResult> for ClientMessage {
2885 fn from_message(
2886 message: CreateMessageResult,
2887 request_id: Option<RequestId>,
2888 ) -> std::result::Result<Self, JsonrpcErrorError> {
2889 let request_id =
2890 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2891 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
2892 request_id,
2893 message.into(),
2894 )))
2895 }
2896}
2897impl ToMessage<ClientMessage> for CreateMessageResult {
2898 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2899 ClientMessage::from_message(self, request_id)
2900 }
2901}
2902impl FromMessage<ListRootsResult> for ClientMessage {
2903 fn from_message(
2904 message: ListRootsResult,
2905 request_id: Option<RequestId>,
2906 ) -> std::result::Result<Self, JsonrpcErrorError> {
2907 let request_id =
2908 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2909 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
2910 request_id,
2911 message.into(),
2912 )))
2913 }
2914}
2915impl ToMessage<ClientMessage> for ListRootsResult {
2916 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2917 ClientMessage::from_message(self, request_id)
2918 }
2919}
2920impl FromMessage<CancelledNotification> for ClientMessage {
2921 fn from_message(
2922 message: CancelledNotification,
2923 request_id: Option<RequestId>,
2924 ) -> std::result::Result<Self, JsonrpcErrorError> {
2925 if request_id.is_some() {
2926 return Err(JsonrpcErrorError::internal_error()
2927 .with_message("request_id expected to be None for Notifications!".to_string()));
2928 }
2929 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
2930 }
2931}
2932impl ToMessage<ClientMessage> for CancelledNotification {
2933 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2934 ClientMessage::from_message(self, request_id)
2935 }
2936}
2937impl FromMessage<InitializedNotification> for ClientMessage {
2938 fn from_message(
2939 message: InitializedNotification,
2940 request_id: Option<RequestId>,
2941 ) -> std::result::Result<Self, JsonrpcErrorError> {
2942 if request_id.is_some() {
2943 return Err(JsonrpcErrorError::internal_error()
2944 .with_message("request_id expected to be None for Notifications!".to_string()));
2945 }
2946 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
2947 }
2948}
2949impl ToMessage<ClientMessage> for InitializedNotification {
2950 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2951 ClientMessage::from_message(self, request_id)
2952 }
2953}
2954impl FromMessage<ProgressNotification> for ClientMessage {
2955 fn from_message(
2956 message: ProgressNotification,
2957 request_id: Option<RequestId>,
2958 ) -> std::result::Result<Self, JsonrpcErrorError> {
2959 if request_id.is_some() {
2960 return Err(JsonrpcErrorError::internal_error()
2961 .with_message("request_id expected to be None for Notifications!".to_string()));
2962 }
2963 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
2964 }
2965}
2966impl ToMessage<ClientMessage> for ProgressNotification {
2967 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2968 ClientMessage::from_message(self, request_id)
2969 }
2970}
2971impl FromMessage<RootsListChangedNotification> for ClientMessage {
2972 fn from_message(
2973 message: RootsListChangedNotification,
2974 request_id: Option<RequestId>,
2975 ) -> std::result::Result<Self, JsonrpcErrorError> {
2976 if request_id.is_some() {
2977 return Err(JsonrpcErrorError::internal_error()
2978 .with_message("request_id expected to be None for Notifications!".to_string()));
2979 }
2980 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
2981 }
2982}
2983impl ToMessage<ClientMessage> for RootsListChangedNotification {
2984 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, JsonrpcErrorError> {
2985 ClientMessage::from_message(self, request_id)
2986 }
2987}
2988impl FromMessage<PingRequest> for ServerMessage {
2989 fn from_message(message: PingRequest, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
2990 let request_id =
2991 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
2992 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
2993 }
2994}
2995impl ToMessage<ServerMessage> for PingRequest {
2996 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
2997 ServerMessage::from_message(self, request_id)
2998 }
2999}
3000impl FromMessage<CreateMessageRequest> for ServerMessage {
3001 fn from_message(
3002 message: CreateMessageRequest,
3003 request_id: Option<RequestId>,
3004 ) -> std::result::Result<Self, JsonrpcErrorError> {
3005 let request_id =
3006 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3007 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3008 }
3009}
3010impl ToMessage<ServerMessage> for CreateMessageRequest {
3011 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3012 ServerMessage::from_message(self, request_id)
3013 }
3014}
3015impl FromMessage<ListRootsRequest> for ServerMessage {
3016 fn from_message(
3017 message: ListRootsRequest,
3018 request_id: Option<RequestId>,
3019 ) -> std::result::Result<Self, JsonrpcErrorError> {
3020 let request_id =
3021 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3022 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3023 }
3024}
3025impl ToMessage<ServerMessage> for ListRootsRequest {
3026 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3027 ServerMessage::from_message(self, request_id)
3028 }
3029}
3030impl FromMessage<Result> for ServerMessage {
3031 fn from_message(message: Result, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
3032 let request_id =
3033 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3034 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3035 request_id,
3036 message.into(),
3037 )))
3038 }
3039}
3040impl ToMessage<ServerMessage> for Result {
3041 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3042 ServerMessage::from_message(self, request_id)
3043 }
3044}
3045impl FromMessage<InitializeResult> for ServerMessage {
3046 fn from_message(
3047 message: InitializeResult,
3048 request_id: Option<RequestId>,
3049 ) -> std::result::Result<Self, JsonrpcErrorError> {
3050 let request_id =
3051 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3052 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3053 request_id,
3054 message.into(),
3055 )))
3056 }
3057}
3058impl ToMessage<ServerMessage> for InitializeResult {
3059 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3060 ServerMessage::from_message(self, request_id)
3061 }
3062}
3063impl FromMessage<ListResourcesResult> for ServerMessage {
3064 fn from_message(
3065 message: ListResourcesResult,
3066 request_id: Option<RequestId>,
3067 ) -> std::result::Result<Self, JsonrpcErrorError> {
3068 let request_id =
3069 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3070 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3071 request_id,
3072 message.into(),
3073 )))
3074 }
3075}
3076impl ToMessage<ServerMessage> for ListResourcesResult {
3077 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3078 ServerMessage::from_message(self, request_id)
3079 }
3080}
3081impl FromMessage<ListResourceTemplatesResult> for ServerMessage {
3082 fn from_message(
3083 message: ListResourceTemplatesResult,
3084 request_id: Option<RequestId>,
3085 ) -> std::result::Result<Self, JsonrpcErrorError> {
3086 let request_id =
3087 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3088 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3089 request_id,
3090 message.into(),
3091 )))
3092 }
3093}
3094impl ToMessage<ServerMessage> for ListResourceTemplatesResult {
3095 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3096 ServerMessage::from_message(self, request_id)
3097 }
3098}
3099impl FromMessage<ReadResourceResult> for ServerMessage {
3100 fn from_message(
3101 message: ReadResourceResult,
3102 request_id: Option<RequestId>,
3103 ) -> std::result::Result<Self, JsonrpcErrorError> {
3104 let request_id =
3105 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3106 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3107 request_id,
3108 message.into(),
3109 )))
3110 }
3111}
3112impl ToMessage<ServerMessage> for ReadResourceResult {
3113 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3114 ServerMessage::from_message(self, request_id)
3115 }
3116}
3117impl FromMessage<ListPromptsResult> for ServerMessage {
3118 fn from_message(
3119 message: ListPromptsResult,
3120 request_id: Option<RequestId>,
3121 ) -> std::result::Result<Self, JsonrpcErrorError> {
3122 let request_id =
3123 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3124 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3125 request_id,
3126 message.into(),
3127 )))
3128 }
3129}
3130impl ToMessage<ServerMessage> for ListPromptsResult {
3131 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3132 ServerMessage::from_message(self, request_id)
3133 }
3134}
3135impl FromMessage<GetPromptResult> for ServerMessage {
3136 fn from_message(
3137 message: GetPromptResult,
3138 request_id: Option<RequestId>,
3139 ) -> std::result::Result<Self, JsonrpcErrorError> {
3140 let request_id =
3141 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3142 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3143 request_id,
3144 message.into(),
3145 )))
3146 }
3147}
3148impl ToMessage<ServerMessage> for GetPromptResult {
3149 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3150 ServerMessage::from_message(self, request_id)
3151 }
3152}
3153impl FromMessage<ListToolsResult> for ServerMessage {
3154 fn from_message(
3155 message: ListToolsResult,
3156 request_id: Option<RequestId>,
3157 ) -> std::result::Result<Self, JsonrpcErrorError> {
3158 let request_id =
3159 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3160 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3161 request_id,
3162 message.into(),
3163 )))
3164 }
3165}
3166impl ToMessage<ServerMessage> for ListToolsResult {
3167 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3168 ServerMessage::from_message(self, request_id)
3169 }
3170}
3171impl FromMessage<CallToolResult> for ServerMessage {
3172 fn from_message(message: CallToolResult, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
3173 let request_id =
3174 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3175 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3176 request_id,
3177 message.into(),
3178 )))
3179 }
3180}
3181impl ToMessage<ServerMessage> for CallToolResult {
3182 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3183 ServerMessage::from_message(self, request_id)
3184 }
3185}
3186impl FromMessage<CompleteResult> for ServerMessage {
3187 fn from_message(message: CompleteResult, request_id: Option<RequestId>) -> std::result::Result<Self, JsonrpcErrorError> {
3188 let request_id =
3189 request_id.ok_or_else(|| JsonrpcErrorError::internal_error().with_message("request_id is None!".to_string()))?;
3190 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3191 request_id,
3192 message.into(),
3193 )))
3194 }
3195}
3196impl ToMessage<ServerMessage> for CompleteResult {
3197 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3198 ServerMessage::from_message(self, request_id)
3199 }
3200}
3201impl FromMessage<CancelledNotification> for ServerMessage {
3202 fn from_message(
3203 message: CancelledNotification,
3204 request_id: Option<RequestId>,
3205 ) -> std::result::Result<Self, JsonrpcErrorError> {
3206 if request_id.is_some() {
3207 return Err(JsonrpcErrorError::internal_error()
3208 .with_message("request_id expected to be None for Notifications!".to_string()));
3209 }
3210 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3211 }
3212}
3213impl ToMessage<ServerMessage> for CancelledNotification {
3214 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3215 ServerMessage::from_message(self, request_id)
3216 }
3217}
3218impl FromMessage<ProgressNotification> for ServerMessage {
3219 fn from_message(
3220 message: ProgressNotification,
3221 request_id: Option<RequestId>,
3222 ) -> std::result::Result<Self, JsonrpcErrorError> {
3223 if request_id.is_some() {
3224 return Err(JsonrpcErrorError::internal_error()
3225 .with_message("request_id expected to be None for Notifications!".to_string()));
3226 }
3227 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3228 }
3229}
3230impl ToMessage<ServerMessage> for ProgressNotification {
3231 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3232 ServerMessage::from_message(self, request_id)
3233 }
3234}
3235impl FromMessage<ResourceListChangedNotification> for ServerMessage {
3236 fn from_message(
3237 message: ResourceListChangedNotification,
3238 request_id: Option<RequestId>,
3239 ) -> std::result::Result<Self, JsonrpcErrorError> {
3240 if request_id.is_some() {
3241 return Err(JsonrpcErrorError::internal_error()
3242 .with_message("request_id expected to be None for Notifications!".to_string()));
3243 }
3244 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3245 }
3246}
3247impl ToMessage<ServerMessage> for ResourceListChangedNotification {
3248 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3249 ServerMessage::from_message(self, request_id)
3250 }
3251}
3252impl FromMessage<ResourceUpdatedNotification> for ServerMessage {
3253 fn from_message(
3254 message: ResourceUpdatedNotification,
3255 request_id: Option<RequestId>,
3256 ) -> std::result::Result<Self, JsonrpcErrorError> {
3257 if request_id.is_some() {
3258 return Err(JsonrpcErrorError::internal_error()
3259 .with_message("request_id expected to be None for Notifications!".to_string()));
3260 }
3261 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3262 }
3263}
3264impl ToMessage<ServerMessage> for ResourceUpdatedNotification {
3265 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3266 ServerMessage::from_message(self, request_id)
3267 }
3268}
3269impl FromMessage<PromptListChangedNotification> for ServerMessage {
3270 fn from_message(
3271 message: PromptListChangedNotification,
3272 request_id: Option<RequestId>,
3273 ) -> std::result::Result<Self, JsonrpcErrorError> {
3274 if request_id.is_some() {
3275 return Err(JsonrpcErrorError::internal_error()
3276 .with_message("request_id expected to be None for Notifications!".to_string()));
3277 }
3278 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3279 }
3280}
3281impl ToMessage<ServerMessage> for PromptListChangedNotification {
3282 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3283 ServerMessage::from_message(self, request_id)
3284 }
3285}
3286impl FromMessage<ToolListChangedNotification> for ServerMessage {
3287 fn from_message(
3288 message: ToolListChangedNotification,
3289 request_id: Option<RequestId>,
3290 ) -> std::result::Result<Self, JsonrpcErrorError> {
3291 if request_id.is_some() {
3292 return Err(JsonrpcErrorError::internal_error()
3293 .with_message("request_id expected to be None for Notifications!".to_string()));
3294 }
3295 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3296 }
3297}
3298impl ToMessage<ServerMessage> for ToolListChangedNotification {
3299 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3300 ServerMessage::from_message(self, request_id)
3301 }
3302}
3303impl FromMessage<LoggingMessageNotification> for ServerMessage {
3304 fn from_message(
3305 message: LoggingMessageNotification,
3306 request_id: Option<RequestId>,
3307 ) -> std::result::Result<Self, JsonrpcErrorError> {
3308 if request_id.is_some() {
3309 return Err(JsonrpcErrorError::internal_error()
3310 .with_message("request_id expected to be None for Notifications!".to_string()));
3311 }
3312 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3313 }
3314}
3315impl ToMessage<ServerMessage> for LoggingMessageNotification {
3316 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, JsonrpcErrorError> {
3317 ServerMessage::from_message(self, request_id)
3318 }
3319}
3320impl TryFrom<RequestFromClient> for InitializeRequest {
3321 type Error = JsonrpcErrorError;
3322 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3323 let matched_type: ClientRequest = value.try_into()?;
3324 if let ClientRequest::InitializeRequest(result) = matched_type {
3325 Ok(result)
3326 } else {
3327 Err(JsonrpcErrorError::internal_error().with_message("Not a InitializeRequest".to_string()))
3328 }
3329 }
3330}
3331impl TryFrom<RequestFromClient> for PingRequest {
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::PingRequest(result) = matched_type {
3336 Ok(result)
3337 } else {
3338 Err(JsonrpcErrorError::internal_error().with_message("Not a PingRequest".to_string()))
3339 }
3340 }
3341}
3342impl TryFrom<RequestFromClient> for ListResourcesRequest {
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::ListResourcesRequest(result) = matched_type {
3347 Ok(result)
3348 } else {
3349 Err(JsonrpcErrorError::internal_error().with_message("Not a ListResourcesRequest".to_string()))
3350 }
3351 }
3352}
3353impl TryFrom<RequestFromClient> for ListResourceTemplatesRequest {
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::ListResourceTemplatesRequest(result) = matched_type {
3358 Ok(result)
3359 } else {
3360 Err(JsonrpcErrorError::internal_error().with_message("Not a ListResourceTemplatesRequest".to_string()))
3361 }
3362 }
3363}
3364impl TryFrom<RequestFromClient> for ReadResourceRequest {
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::ReadResourceRequest(result) = matched_type {
3369 Ok(result)
3370 } else {
3371 Err(JsonrpcErrorError::internal_error().with_message("Not a ReadResourceRequest".to_string()))
3372 }
3373 }
3374}
3375impl TryFrom<RequestFromClient> for SubscribeRequest {
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::SubscribeRequest(result) = matched_type {
3380 Ok(result)
3381 } else {
3382 Err(JsonrpcErrorError::internal_error().with_message("Not a SubscribeRequest".to_string()))
3383 }
3384 }
3385}
3386impl TryFrom<RequestFromClient> for UnsubscribeRequest {
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::UnsubscribeRequest(result) = matched_type {
3391 Ok(result)
3392 } else {
3393 Err(JsonrpcErrorError::internal_error().with_message("Not a UnsubscribeRequest".to_string()))
3394 }
3395 }
3396}
3397impl TryFrom<RequestFromClient> for ListPromptsRequest {
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::ListPromptsRequest(result) = matched_type {
3402 Ok(result)
3403 } else {
3404 Err(JsonrpcErrorError::internal_error().with_message("Not a ListPromptsRequest".to_string()))
3405 }
3406 }
3407}
3408impl TryFrom<RequestFromClient> for GetPromptRequest {
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::GetPromptRequest(result) = matched_type {
3413 Ok(result)
3414 } else {
3415 Err(JsonrpcErrorError::internal_error().with_message("Not a GetPromptRequest".to_string()))
3416 }
3417 }
3418}
3419impl TryFrom<RequestFromClient> for ListToolsRequest {
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::ListToolsRequest(result) = matched_type {
3424 Ok(result)
3425 } else {
3426 Err(JsonrpcErrorError::internal_error().with_message("Not a ListToolsRequest".to_string()))
3427 }
3428 }
3429}
3430impl TryFrom<RequestFromClient> for CallToolRequest {
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::CallToolRequest(result) = matched_type {
3435 Ok(result)
3436 } else {
3437 Err(JsonrpcErrorError::internal_error().with_message("Not a CallToolRequest".to_string()))
3438 }
3439 }
3440}
3441impl TryFrom<RequestFromClient> for SetLevelRequest {
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::SetLevelRequest(result) = matched_type {
3446 Ok(result)
3447 } else {
3448 Err(JsonrpcErrorError::internal_error().with_message("Not a SetLevelRequest".to_string()))
3449 }
3450 }
3451}
3452impl TryFrom<RequestFromClient> for CompleteRequest {
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::CompleteRequest(result) = matched_type {
3457 Ok(result)
3458 } else {
3459 Err(JsonrpcErrorError::internal_error().with_message("Not a CompleteRequest".to_string()))
3460 }
3461 }
3462}
3463impl TryFrom<ResultFromClient> for Result {
3464 type Error = JsonrpcErrorError;
3465 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3466 let matched_type: ClientResult = value.try_into()?;
3467 if let ClientResult::Result(result) = matched_type {
3468 Ok(result)
3469 } else {
3470 Err(JsonrpcErrorError::internal_error().with_message("Not a Result".to_string()))
3471 }
3472 }
3473}
3474impl TryFrom<ResultFromClient> for CreateMessageResult {
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::CreateMessageResult(result) = matched_type {
3479 Ok(result)
3480 } else {
3481 Err(JsonrpcErrorError::internal_error().with_message("Not a CreateMessageResult".to_string()))
3482 }
3483 }
3484}
3485impl TryFrom<ResultFromClient> for ListRootsResult {
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::ListRootsResult(result) = matched_type {
3490 Ok(result)
3491 } else {
3492 Err(JsonrpcErrorError::internal_error().with_message("Not a ListRootsResult".to_string()))
3493 }
3494 }
3495}
3496impl TryFrom<NotificationFromClient> for CancelledNotification {
3497 type Error = JsonrpcErrorError;
3498 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
3499 let matched_type: ClientNotification = value.try_into()?;
3500 if let ClientNotification::CancelledNotification(result) = matched_type {
3501 Ok(result)
3502 } else {
3503 Err(JsonrpcErrorError::internal_error().with_message("Not a CancelledNotification".to_string()))
3504 }
3505 }
3506}
3507impl TryFrom<NotificationFromClient> for InitializedNotification {
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::InitializedNotification(result) = matched_type {
3512 Ok(result)
3513 } else {
3514 Err(JsonrpcErrorError::internal_error().with_message("Not a InitializedNotification".to_string()))
3515 }
3516 }
3517}
3518impl TryFrom<NotificationFromClient> for ProgressNotification {
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::ProgressNotification(result) = matched_type {
3523 Ok(result)
3524 } else {
3525 Err(JsonrpcErrorError::internal_error().with_message("Not a ProgressNotification".to_string()))
3526 }
3527 }
3528}
3529impl TryFrom<NotificationFromClient> for RootsListChangedNotification {
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::RootsListChangedNotification(result) = matched_type {
3534 Ok(result)
3535 } else {
3536 Err(JsonrpcErrorError::internal_error().with_message("Not a RootsListChangedNotification".to_string()))
3537 }
3538 }
3539}
3540impl TryFrom<RequestFromServer> for PingRequest {
3541 type Error = JsonrpcErrorError;
3542 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
3543 let matched_type: ServerRequest = value.try_into()?;
3544 if let ServerRequest::PingRequest(result) = matched_type {
3545 Ok(result)
3546 } else {
3547 Err(JsonrpcErrorError::internal_error().with_message("Not a PingRequest".to_string()))
3548 }
3549 }
3550}
3551impl TryFrom<RequestFromServer> for CreateMessageRequest {
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::CreateMessageRequest(result) = matched_type {
3556 Ok(result)
3557 } else {
3558 Err(JsonrpcErrorError::internal_error().with_message("Not a CreateMessageRequest".to_string()))
3559 }
3560 }
3561}
3562impl TryFrom<RequestFromServer> for ListRootsRequest {
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::ListRootsRequest(result) = matched_type {
3567 Ok(result)
3568 } else {
3569 Err(JsonrpcErrorError::internal_error().with_message("Not a ListRootsRequest".to_string()))
3570 }
3571 }
3572}
3573impl TryFrom<ResultFromServer> for Result {
3574 type Error = JsonrpcErrorError;
3575 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3576 let matched_type: ServerResult = value.try_into()?;
3577 if let ServerResult::Result(result) = matched_type {
3578 Ok(result)
3579 } else {
3580 Err(JsonrpcErrorError::internal_error().with_message("Not a Result".to_string()))
3581 }
3582 }
3583}
3584impl TryFrom<ResultFromServer> for InitializeResult {
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::InitializeResult(result) = matched_type {
3589 Ok(result)
3590 } else {
3591 Err(JsonrpcErrorError::internal_error().with_message("Not a InitializeResult".to_string()))
3592 }
3593 }
3594}
3595impl TryFrom<ResultFromServer> for ListResourcesResult {
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::ListResourcesResult(result) = matched_type {
3600 Ok(result)
3601 } else {
3602 Err(JsonrpcErrorError::internal_error().with_message("Not a ListResourcesResult".to_string()))
3603 }
3604 }
3605}
3606impl TryFrom<ResultFromServer> for ListResourceTemplatesResult {
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::ListResourceTemplatesResult(result) = matched_type {
3611 Ok(result)
3612 } else {
3613 Err(JsonrpcErrorError::internal_error().with_message("Not a ListResourceTemplatesResult".to_string()))
3614 }
3615 }
3616}
3617impl TryFrom<ResultFromServer> for ReadResourceResult {
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::ReadResourceResult(result) = matched_type {
3622 Ok(result)
3623 } else {
3624 Err(JsonrpcErrorError::internal_error().with_message("Not a ReadResourceResult".to_string()))
3625 }
3626 }
3627}
3628impl TryFrom<ResultFromServer> for ListPromptsResult {
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::ListPromptsResult(result) = matched_type {
3633 Ok(result)
3634 } else {
3635 Err(JsonrpcErrorError::internal_error().with_message("Not a ListPromptsResult".to_string()))
3636 }
3637 }
3638}
3639impl TryFrom<ResultFromServer> for GetPromptResult {
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::GetPromptResult(result) = matched_type {
3644 Ok(result)
3645 } else {
3646 Err(JsonrpcErrorError::internal_error().with_message("Not a GetPromptResult".to_string()))
3647 }
3648 }
3649}
3650impl TryFrom<ResultFromServer> for ListToolsResult {
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::ListToolsResult(result) = matched_type {
3655 Ok(result)
3656 } else {
3657 Err(JsonrpcErrorError::internal_error().with_message("Not a ListToolsResult".to_string()))
3658 }
3659 }
3660}
3661impl TryFrom<ResultFromServer> for CallToolResult {
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::CallToolResult(result) = matched_type {
3666 Ok(result)
3667 } else {
3668 Err(JsonrpcErrorError::internal_error().with_message("Not a CallToolResult".to_string()))
3669 }
3670 }
3671}
3672impl TryFrom<ResultFromServer> for CompleteResult {
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::CompleteResult(result) = matched_type {
3677 Ok(result)
3678 } else {
3679 Err(JsonrpcErrorError::internal_error().with_message("Not a CompleteResult".to_string()))
3680 }
3681 }
3682}
3683impl TryFrom<NotificationFromServer> for CancelledNotification {
3684 type Error = JsonrpcErrorError;
3685 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
3686 let matched_type: ServerNotification = value.try_into()?;
3687 if let ServerNotification::CancelledNotification(result) = matched_type {
3688 Ok(result)
3689 } else {
3690 Err(JsonrpcErrorError::internal_error().with_message("Not a CancelledNotification".to_string()))
3691 }
3692 }
3693}
3694impl TryFrom<NotificationFromServer> for ProgressNotification {
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::ProgressNotification(result) = matched_type {
3699 Ok(result)
3700 } else {
3701 Err(JsonrpcErrorError::internal_error().with_message("Not a ProgressNotification".to_string()))
3702 }
3703 }
3704}
3705impl TryFrom<NotificationFromServer> for ResourceListChangedNotification {
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::ResourceListChangedNotification(result) = matched_type {
3710 Ok(result)
3711 } else {
3712 Err(JsonrpcErrorError::internal_error().with_message("Not a ResourceListChangedNotification".to_string()))
3713 }
3714 }
3715}
3716impl TryFrom<NotificationFromServer> for ResourceUpdatedNotification {
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::ResourceUpdatedNotification(result) = matched_type {
3721 Ok(result)
3722 } else {
3723 Err(JsonrpcErrorError::internal_error().with_message("Not a ResourceUpdatedNotification".to_string()))
3724 }
3725 }
3726}
3727impl TryFrom<NotificationFromServer> for PromptListChangedNotification {
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::PromptListChangedNotification(result) = matched_type {
3732 Ok(result)
3733 } else {
3734 Err(JsonrpcErrorError::internal_error().with_message("Not a PromptListChangedNotification".to_string()))
3735 }
3736 }
3737}
3738impl TryFrom<NotificationFromServer> for ToolListChangedNotification {
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::ToolListChangedNotification(result) = matched_type {
3743 Ok(result)
3744 } else {
3745 Err(JsonrpcErrorError::internal_error().with_message("Not a ToolListChangedNotification".to_string()))
3746 }
3747 }
3748}
3749impl TryFrom<NotificationFromServer> for LoggingMessageNotification {
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::LoggingMessageNotification(result) = matched_type {
3754 Ok(result)
3755 } else {
3756 Err(JsonrpcErrorError::internal_error().with_message("Not a LoggingMessageNotification".to_string()))
3757 }
3758 }
3759}
3760impl CallToolResultContentItem {
3761 pub fn text_content(text_content: String, annotations: Option<TextContentAnnotations>) -> Self {
3763 TextContent::new(annotations, text_content).into()
3764 }
3765 pub fn image_content(data: String, mime_type: String, annotations: Option<ImageContentAnnotations>) -> Self {
3767 ImageContent::new(annotations, data, mime_type).into()
3768 }
3769 pub fn embedded_resource(resource: EmbeddedResourceResource, annotations: Option<EmbeddedResourceAnnotations>) -> Self {
3771 EmbeddedResource::new(annotations, resource).into()
3772 }
3773 pub fn content_type(&self) -> &str {
3775 match self {
3776 CallToolResultContentItem::TextContent(text_content) => text_content.type_(),
3777 CallToolResultContentItem::ImageContent(image_content) => image_content.type_(),
3778 CallToolResultContentItem::EmbeddedResource(embedded_resource) => embedded_resource.type_(),
3779 }
3780 }
3781 pub fn as_text_content(&self) -> std::result::Result<&TextContent, JsonrpcErrorError> {
3783 match &self {
3784 CallToolResultContentItem::TextContent(text_content) => Ok(text_content),
3785 _ => Err(JsonrpcErrorError::internal_error().with_message(format!(
3786 "Invalid conversion, \"{}\" is not a {}",
3787 self.content_type(),
3788 "TextContent"
3789 ))),
3790 }
3791 }
3792 pub fn as_image_content(&self) -> std::result::Result<&ImageContent, JsonrpcErrorError> {
3794 match &self {
3795 CallToolResultContentItem::ImageContent(image_content) => Ok(image_content),
3796 _ => Err(JsonrpcErrorError::internal_error().with_message(format!(
3797 "Invalid conversion, \"{}\" is not a {}",
3798 self.content_type(),
3799 "ImageContent"
3800 ))),
3801 }
3802 }
3803 pub fn as_embedded_resource(&self) -> std::result::Result<&EmbeddedResource, JsonrpcErrorError> {
3805 match &self {
3806 CallToolResultContentItem::EmbeddedResource(embedded_resource) => Ok(embedded_resource),
3807 _ => Err(JsonrpcErrorError::internal_error().with_message(format!(
3808 "Invalid conversion, \"{}\" is not a {}",
3809 self.content_type(),
3810 "EmbeddedResource"
3811 ))),
3812 }
3813 }
3814}
3815#[cfg(test)]
3817mod tests {
3818 use super::*;
3819 use serde_json::json;
3820
3821 #[test]
3822 fn test_detect_message_type() {
3823 let message = ClientJsonrpcRequest::new(RequestId::Integer(0), PingRequest::new(None).into());
3825 let result = detect_message_type(&json!(message));
3826 assert!(matches!(result, MessageTypes::Request));
3827
3828 let result = detect_message_type(&json!({
3831 "id":0,
3832 "method":"add_numbers",
3833 "params":{},
3834 "jsonrpc":"2.0"
3835 }));
3836 assert!(matches!(result, MessageTypes::Request));
3837
3838 let message = ClientJsonrpcNotification::new(RootsListChangedNotification::new(None).into());
3840 let result = detect_message_type(&json!(message));
3841 assert!(matches!(result, MessageTypes::Notification));
3842
3843 let result = detect_message_type(&json!({
3845 "method":"notifications/email_sent",
3846 "jsonrpc":"2.0"
3847 }));
3848 assert!(matches!(result, MessageTypes::Notification));
3849
3850 let message = ClientJsonrpcResponse::new(
3852 RequestId::Integer(0),
3853 ListRootsResult {
3854 meta: None,
3855 roots: vec![],
3856 }
3857 .into(),
3858 );
3859 let result = detect_message_type(&json!(message));
3860 assert!(matches!(result, MessageTypes::Response));
3861
3862 let result = detect_message_type(&json!({
3865 "id":1,
3866 "jsonrpc":"2.0",
3867 "result":"{}",
3868 }));
3869 assert!(matches!(result, MessageTypes::Response));
3870
3871 let message = JsonrpcError::create(
3873 RequestId::Integer(0),
3874 RpcErrorCodes::INVALID_PARAMS,
3875 "Invalid params!".to_string(),
3876 None,
3877 );
3878 let result = detect_message_type(&json!(message));
3879 assert!(matches!(result, MessageTypes::Error));
3880
3881 let result = detect_message_type(&json!({}));
3883 assert!(matches!(result, MessageTypes::Request));
3884 }
3885}