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, RpcError>;
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, RpcError>;
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 PartialEq<RequestId> for &RequestId {
111 fn eq(&self, other: &RequestId) -> bool {
112 (*self).eq(other)
113 }
114}
115
116impl Eq for RequestId {}
117
118impl Hash for RequestId {
120 fn hash<H: Hasher>(&self, state: &mut H) {
121 match self {
122 RequestId::String(s) => {
123 0u8.hash(state); s.hash(state);
125 }
126 RequestId::Integer(i) => {
127 1u8.hash(state); i.hash(state);
129 }
130 }
131 }
132}
133
134#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
141#[serde(untagged)]
142pub enum ClientMessage {
143 Request(ClientJsonrpcRequest),
144 Notification(ClientJsonrpcNotification),
145 Response(ClientJsonrpcResponse),
146 Error(JsonrpcError),
147}
148
149impl ClientMessage {
150 pub fn as_response(self) -> std::result::Result<ClientJsonrpcResponse, RpcError> {
160 if let Self::Response(response) = self {
161 Ok(response)
162 } else {
163 Err(RpcError::internal_error().with_message(format!(
164 "Invalid message type, expected: \"{}\" received\"{}\"",
165 MessageTypes::Response,
166 self.message_type()
167 )))
168 }
169 }
170
171 pub fn as_request(self) -> std::result::Result<ClientJsonrpcRequest, RpcError> {
181 if let Self::Request(request) = self {
182 Ok(request)
183 } else {
184 Err(RpcError::internal_error().with_message(format!(
185 "Invalid message type, expected: \"{}\" received\"{}\"",
186 MessageTypes::Request,
187 self.message_type()
188 )))
189 }
190 }
191
192 pub fn as_notification(self) -> std::result::Result<ClientJsonrpcNotification, RpcError> {
202 if let Self::Notification(notification) = self {
203 Ok(notification)
204 } else {
205 Err(RpcError::internal_error().with_message(format!(
206 "Invalid message type, expected: \"{}\" received\"{}\"",
207 MessageTypes::Notification,
208 self.message_type()
209 )))
210 }
211 }
212
213 pub fn as_error(self) -> std::result::Result<JsonrpcError, RpcError> {
223 if let Self::Error(error) = self {
224 Ok(error)
225 } else {
226 Err(RpcError::internal_error().with_message(format!(
227 "Invalid message type, expected: \"{}\" received\"{}\"",
228 MessageTypes::Error,
229 self.message_type()
230 )))
231 }
232 }
233
234 pub fn is_initialize_request(&self) -> bool {
236 matches!(self, Self::Request(request) if request.request.is_initialize_request())
237 }
238
239 pub fn is_initialized_notification(&self) -> bool {
241 matches!(self, Self::Notification(notofication) if notofication.notification.is_initialized_notification())
242 }
243}
244
245impl From<ClientJsonrpcNotification> for ClientMessage {
246 fn from(value: ClientJsonrpcNotification) -> Self {
247 Self::Notification(value)
248 }
249}
250
251impl From<ClientJsonrpcRequest> for ClientMessage {
252 fn from(value: ClientJsonrpcRequest) -> Self {
253 Self::Request(value)
254 }
255}
256
257impl From<ClientJsonrpcResponse> for ClientMessage {
258 fn from(value: ClientJsonrpcResponse) -> Self {
259 Self::Response(value)
260 }
261}
262
263impl RpcMessage for ClientMessage {
264 fn request_id(&self) -> Option<&RequestId> {
266 match self {
267 ClientMessage::Request(client_jsonrpc_request) => Some(&client_jsonrpc_request.id),
269 ClientMessage::Notification(_) => None,
271 ClientMessage::Response(client_jsonrpc_response) => Some(&client_jsonrpc_response.id),
273 ClientMessage::Error(jsonrpc_error) => Some(&jsonrpc_error.id),
275 }
276 }
277
278 fn jsonrpc(&self) -> &str {
279 match self {
280 ClientMessage::Request(client_jsonrpc_request) => client_jsonrpc_request.jsonrpc(),
281 ClientMessage::Notification(notification) => notification.jsonrpc(),
282 ClientMessage::Response(client_jsonrpc_response) => client_jsonrpc_response.jsonrpc(),
283 ClientMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
284 }
285 }
286}
287
288impl McpMessage for ClientMessage {
290 fn is_response(&self) -> bool {
292 matches!(self, ClientMessage::Response(_))
293 }
294
295 fn is_request(&self) -> bool {
297 matches!(self, ClientMessage::Request(_))
298 }
299
300 fn is_notification(&self) -> bool {
302 matches!(self, ClientMessage::Notification(_))
303 }
304
305 fn is_error(&self) -> bool {
307 matches!(self, ClientMessage::Error(_))
308 }
309
310 fn message_type(&self) -> MessageTypes {
312 match self {
313 ClientMessage::Request(_) => MessageTypes::Request,
314 ClientMessage::Notification(_) => MessageTypes::Notification,
315 ClientMessage::Response(_) => MessageTypes::Response,
316 ClientMessage::Error(_) => MessageTypes::Error,
317 }
318 }
319}
320
321#[derive(Clone, Debug)]
327pub struct ClientJsonrpcRequest {
328 pub id: RequestId,
329 jsonrpc: ::std::string::String,
330 pub method: String,
331 pub request: RequestFromClient,
332}
333
334impl ClientJsonrpcRequest {
335 pub fn new(id: RequestId, request: RequestFromClient) -> Self {
336 let method = request.method().to_string();
337 Self {
338 id,
339 jsonrpc: JSONRPC_VERSION.to_string(),
340 method,
341 request,
342 }
343 }
344 pub fn jsonrpc(&self) -> &::std::string::String {
345 &self.jsonrpc
346 }
347}
348
349impl Display for ClientJsonrpcRequest {
351 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
352 write!(
353 f,
354 "{}",
355 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
356 )
357 }
358}
359
360impl FromStr for ClientJsonrpcRequest {
361 type Err = RpcError;
362
363 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
385 serde_json::from_str(s)
386 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
387 }
388}
389
390#[allow(clippy::large_enum_variant)]
397#[derive(::serde::Serialize, Clone, Debug)]
398#[serde(untagged)]
399pub enum RequestFromClient {
400 ClientRequest(ClientRequest),
401 CustomRequest(serde_json::Value),
402}
403
404impl TryFrom<RequestFromClient> for ClientRequest {
405 type Error = RpcError;
406 fn try_from(value: RequestFromClient) -> result::Result<Self, Self::Error> {
407 if let RequestFromClient::ClientRequest(client_request) = value {
408 Ok(client_request)
409 } else {
410 Err(RpcError::internal_error().with_message("Not a ClientRequest".to_string()))
411 }
412 }
413}
414
415impl RequestFromClient {
416 pub fn method(&self) -> &str {
417 match self {
418 RequestFromClient::ClientRequest(request) => request.method(),
419 RequestFromClient::CustomRequest(request) => request["method"].as_str().unwrap(),
420 }
421 }
422 pub fn is_initialize_request(&self) -> bool {
424 matches!(self, RequestFromClient::ClientRequest(ClientRequest::InitializeRequest(_)))
425 }
426}
427
428impl From<ClientRequest> for RequestFromClient {
429 fn from(value: ClientRequest) -> Self {
430 Self::ClientRequest(value)
431 }
432}
433
434impl From<serde_json::Value> for RequestFromClient {
435 fn from(value: serde_json::Value) -> Self {
436 Self::CustomRequest(value)
437 }
438}
439
440impl<'de> serde::Deserialize<'de> for RequestFromClient {
441 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
442 where
443 D: serde::Deserializer<'de>,
444 {
445 let raw_value = Value::deserialize(deserializer)?;
446
447 let client_result = ClientRequest::deserialize(&raw_value);
448
449 match client_result {
450 Ok(client_request) => Ok(Self::ClientRequest(client_request)),
451 Err(_) => Ok(Self::CustomRequest(raw_value)),
452 }
453 }
454}
455
456#[derive(Clone, Debug)]
462pub struct ClientJsonrpcNotification {
463 jsonrpc: ::std::string::String,
464 pub method: ::std::string::String,
465 pub notification: NotificationFromClient,
466}
467
468impl ClientJsonrpcNotification {
469 pub fn new(notification: NotificationFromClient) -> Self {
470 let method = notification.method().to_string();
471 Self {
472 jsonrpc: JSONRPC_VERSION.to_string(),
473 method,
474 notification,
475 }
476 }
477 pub fn jsonrpc(&self) -> &::std::string::String {
478 &self.jsonrpc
479 }
480}
481
482impl Display for ClientJsonrpcNotification {
484 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
485 write!(
486 f,
487 "{}",
488 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
489 )
490 }
491}
492
493impl FromStr for ClientJsonrpcNotification {
494 type Err = RpcError;
495
496 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
497 serde_json::from_str(s)
498 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
499 }
500}
501
502#[derive(::serde::Serialize, Clone, Debug)]
509#[serde(untagged)]
510pub enum NotificationFromClient {
511 ClientNotification(ClientNotification),
512 CustomNotification(serde_json::Value),
513}
514
515impl TryFrom<NotificationFromClient> for ClientNotification {
516 type Error = RpcError;
517 fn try_from(value: NotificationFromClient) -> result::Result<Self, Self::Error> {
518 if let NotificationFromClient::ClientNotification(client_notification) = value {
519 Ok(client_notification)
520 } else {
521 Err(RpcError::internal_error().with_message("Not a ClientNotification".to_string()))
522 }
523 }
524}
525
526impl NotificationFromClient {
527 pub fn is_initialized_notification(&self) -> bool {
529 matches!(
530 self,
531 NotificationFromClient::ClientNotification(ClientNotification::InitializedNotification(_))
532 )
533 }
534
535 fn method(&self) -> &str {
536 match self {
537 NotificationFromClient::ClientNotification(notification) => notification.method(),
538 NotificationFromClient::CustomNotification(notification) => notification["method"].as_str().unwrap(),
539 }
540 }
541}
542
543impl<'de> serde::Deserialize<'de> for NotificationFromClient {
544 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
545 where
546 D: serde::Deserializer<'de>,
547 {
548 let raw_value = Value::deserialize(deserializer)?;
549
550 let result = ClientNotification::deserialize(&raw_value);
551
552 match result {
553 Ok(client_notification) => Ok(Self::ClientNotification(client_notification)),
554 Err(_) => Ok(Self::CustomNotification(raw_value)),
555 }
556 }
557}
558
559#[derive(Clone, Debug)]
565pub struct ClientJsonrpcResponse {
566 pub id: RequestId,
567 jsonrpc: ::std::string::String,
568 pub result: ResultFromClient,
569}
570
571impl ClientJsonrpcResponse {
572 pub fn new(id: RequestId, result: ResultFromClient) -> Self {
573 Self {
574 id,
575 jsonrpc: JSONRPC_VERSION.to_string(),
576 result,
577 }
578 }
579 pub fn jsonrpc(&self) -> &::std::string::String {
580 &self.jsonrpc
581 }
582}
583
584impl Display for ClientJsonrpcResponse {
586 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
587 write!(
588 f,
589 "{}",
590 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
591 )
592 }
593}
594
595impl FromStr for ClientJsonrpcResponse {
596 type Err = RpcError;
597
598 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
599 serde_json::from_str(s)
600 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
601 }
602}
603#[allow(clippy::large_enum_variant)]
610#[derive(::serde::Serialize, Clone, Debug)]
611#[serde(untagged)]
612pub enum ResultFromClient {
613 ClientResult(ClientResult),
614 CustomResult(serde_json::Value),
616}
617
618impl TryFrom<ResultFromClient> for ClientResult {
619 type Error = RpcError;
620 fn try_from(value: ResultFromClient) -> result::Result<Self, Self::Error> {
621 if let ResultFromClient::ClientResult(client_result) = value {
622 Ok(client_result)
623 } else {
624 Err(RpcError::internal_error().with_message("Not a ClientResult".to_string()))
625 }
626 }
627}
628
629impl From<ClientResult> for ResultFromClient {
630 fn from(value: ClientResult) -> Self {
631 Self::ClientResult(value)
632 }
633}
634
635impl From<serde_json::Value> for ResultFromClient {
636 fn from(value: serde_json::Value) -> Self {
637 Self::CustomResult(value)
638 }
639}
640
641impl<'de> serde::Deserialize<'de> for ResultFromClient {
642 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
643 where
644 D: serde::Deserializer<'de>,
645 {
646 let raw_value = Value::deserialize(deserializer)?;
647
648 let result = ClientResult::deserialize(&raw_value);
649
650 match result {
651 Ok(client_result) => Ok(Self::ClientResult(client_result)),
652 Err(_) => Ok(Self::CustomResult(raw_value)),
653 }
654 }
655}
656
657impl FromStr for ClientMessage {
662 type Err = RpcError;
663
664 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
665 serde_json::from_str(s)
666 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
667 }
668}
669
670impl Display for ClientMessage {
671 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
672 write!(
673 f,
674 "{}",
675 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
676 )
677 }
678}
679
680#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
687#[serde(untagged)]
688pub enum ServerMessage {
689 Request(ServerJsonrpcRequest),
690 Notification(ServerJsonrpcNotification),
691 Response(ServerJsonrpcResponse),
692 Error(JsonrpcError),
693}
694
695impl ServerMessage {
696 pub fn as_response(self) -> std::result::Result<ServerJsonrpcResponse, RpcError> {
706 if let Self::Response(response) = self {
707 Ok(response)
708 } else {
709 Err(RpcError::internal_error().with_message(format!(
710 "Invalid message type, expected: \"{}\" received\"{}\"",
711 MessageTypes::Response,
712 self.message_type()
713 )))
714 }
715 }
716
717 pub fn as_request(self) -> std::result::Result<ServerJsonrpcRequest, RpcError> {
727 if let Self::Request(request) = self {
728 Ok(request)
729 } else {
730 Err(RpcError::internal_error().with_message(format!(
731 "Invalid message type, expected: \"{}\" received\"{}\"",
732 MessageTypes::Request,
733 self.message_type()
734 )))
735 }
736 }
737
738 pub fn as_notification(self) -> std::result::Result<ServerJsonrpcNotification, RpcError> {
748 if let Self::Notification(notification) = self {
749 Ok(notification)
750 } else {
751 Err(RpcError::internal_error().with_message(format!(
752 "Invalid message type, expected: \"{}\" received\"{}\"",
753 MessageTypes::Notification,
754 self.message_type()
755 )))
756 }
757 }
758
759 pub fn as_error(self) -> std::result::Result<JsonrpcError, RpcError> {
769 if let Self::Error(error) = self {
770 Ok(error)
771 } else {
772 Err(RpcError::internal_error().with_message(format!(
773 "Invalid message type, expected: \"{}\" received\"{}\"",
774 MessageTypes::Error,
775 self.message_type()
776 )))
777 }
778 }
779}
780
781impl From<ServerJsonrpcNotification> for ServerMessage {
782 fn from(value: ServerJsonrpcNotification) -> Self {
783 Self::Notification(value)
784 }
785}
786
787impl From<ServerJsonrpcRequest> for ServerMessage {
788 fn from(value: ServerJsonrpcRequest) -> Self {
789 Self::Request(value)
790 }
791}
792
793impl From<ServerJsonrpcResponse> for ServerMessage {
794 fn from(value: ServerJsonrpcResponse) -> Self {
795 Self::Response(value)
796 }
797}
798
799impl RpcMessage for ServerMessage {
800 fn request_id(&self) -> Option<&RequestId> {
802 match self {
803 ServerMessage::Request(server_jsonrpc_request) => Some(&server_jsonrpc_request.id),
805 ServerMessage::Notification(_) => None,
807 ServerMessage::Response(server_jsonrpc_response) => Some(&server_jsonrpc_response.id),
809 ServerMessage::Error(jsonrpc_error) => Some(&jsonrpc_error.id),
811 }
812 }
813
814 fn jsonrpc(&self) -> &str {
815 match self {
816 ServerMessage::Request(server_jsonrpc_request) => server_jsonrpc_request.jsonrpc(),
818 ServerMessage::Notification(notification) => notification.jsonrpc(),
820 ServerMessage::Response(server_jsonrpc_response) => server_jsonrpc_response.jsonrpc(),
822 ServerMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
824 }
825 }
826}
827
828impl McpMessage for ServerMessage {
830 fn is_response(&self) -> bool {
832 matches!(self, ServerMessage::Response(_))
833 }
834
835 fn is_request(&self) -> bool {
837 matches!(self, ServerMessage::Request(_))
838 }
839
840 fn is_notification(&self) -> bool {
842 matches!(self, ServerMessage::Notification(_))
843 }
844
845 fn is_error(&self) -> bool {
847 matches!(self, ServerMessage::Error(_))
848 }
849
850 fn message_type(&self) -> MessageTypes {
852 match self {
853 ServerMessage::Request(_) => MessageTypes::Request,
854 ServerMessage::Notification(_) => MessageTypes::Notification,
855 ServerMessage::Response(_) => MessageTypes::Response,
856 ServerMessage::Error(_) => MessageTypes::Error,
857 }
858 }
859}
860
861impl FromStr for ServerMessage {
862 type Err = RpcError;
863
864 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
865 serde_json::from_str(s)
866 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
867 }
868}
869
870impl Display for ServerMessage {
871 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
872 write!(
873 f,
874 "{}",
875 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
876 )
877 }
878}
879
880#[derive(Clone, Debug)]
886pub struct ServerJsonrpcRequest {
887 pub id: RequestId,
888 jsonrpc: ::std::string::String,
889 pub method: String,
890 pub request: RequestFromServer,
891}
892
893impl ServerJsonrpcRequest {
894 pub fn new(id: RequestId, request: RequestFromServer) -> Self {
895 let method = request.method().to_string();
896 Self {
897 id,
898 jsonrpc: JSONRPC_VERSION.to_string(),
899 method,
900 request,
901 }
902 }
903 pub fn jsonrpc(&self) -> &::std::string::String {
904 &self.jsonrpc
905 }
906}
907
908impl Display for ServerJsonrpcRequest {
910 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
911 write!(
912 f,
913 "{}",
914 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
915 )
916 }
917}
918
919impl FromStr for ServerJsonrpcRequest {
920 type Err = RpcError;
921
922 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
923 serde_json::from_str(s)
924 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
925 }
926}
927#[derive(::serde::Serialize, Clone, Debug)]
934#[serde(untagged)]
935pub enum RequestFromServer {
936 ServerRequest(ServerRequest),
937 CustomRequest(serde_json::Value),
938}
939
940impl TryFrom<RequestFromServer> for ServerRequest {
941 type Error = RpcError;
942 fn try_from(value: RequestFromServer) -> result::Result<Self, Self::Error> {
943 if let RequestFromServer::ServerRequest(server_request) = value {
944 Ok(server_request)
945 } else {
946 Err(RpcError::internal_error().with_message("Not a ServerRequest".to_string()))
947 }
948 }
949}
950
951impl RequestFromServer {
952 pub fn method(&self) -> &str {
953 match self {
954 RequestFromServer::ServerRequest(request) => request.method(),
955 RequestFromServer::CustomRequest(request) => request["method"].as_str().unwrap(),
956 }
957 }
958}
959
960impl From<ServerRequest> for RequestFromServer {
961 fn from(value: ServerRequest) -> Self {
962 Self::ServerRequest(value)
963 }
964}
965
966impl From<serde_json::Value> for RequestFromServer {
967 fn from(value: serde_json::Value) -> Self {
968 Self::CustomRequest(value)
969 }
970}
971
972impl<'de> serde::Deserialize<'de> for RequestFromServer {
973 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
974 where
975 D: serde::Deserializer<'de>,
976 {
977 let raw_value = Value::deserialize(deserializer)?;
978
979 let server_result = ServerRequest::deserialize(&raw_value);
980
981 match server_result {
982 Ok(server_request) => Ok(Self::ServerRequest(server_request)),
983 Err(_) => Ok(Self::CustomRequest(raw_value)),
984 }
985 }
986}
987
988#[derive(Clone, Debug)]
994pub struct ServerJsonrpcNotification {
995 jsonrpc: ::std::string::String,
996 pub method: ::std::string::String,
997 pub notification: NotificationFromServer,
998}
999
1000impl ServerJsonrpcNotification {
1001 pub fn new(notification: NotificationFromServer) -> Self {
1002 let method = notification.method().to_string();
1003 Self {
1004 jsonrpc: JSONRPC_VERSION.to_string(),
1005 method,
1006 notification,
1007 }
1008 }
1009 pub fn jsonrpc(&self) -> &::std::string::String {
1010 &self.jsonrpc
1011 }
1012}
1013
1014impl Display for ServerJsonrpcNotification {
1016 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1017 write!(
1018 f,
1019 "{}",
1020 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1021 )
1022 }
1023}
1024
1025impl FromStr for ServerJsonrpcNotification {
1026 type Err = RpcError;
1027
1028 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1029 serde_json::from_str(s)
1030 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1031 }
1032}
1033#[derive(::serde::Serialize, Clone, Debug)]
1040#[serde(untagged)]
1041pub enum NotificationFromServer {
1042 ServerNotification(ServerNotification),
1043 CustomNotification(serde_json::Value),
1044}
1045
1046impl TryFrom<NotificationFromServer> for ServerNotification {
1047 type Error = RpcError;
1048 fn try_from(value: NotificationFromServer) -> result::Result<Self, Self::Error> {
1049 if let NotificationFromServer::ServerNotification(server_notification) = value {
1050 Ok(server_notification)
1051 } else {
1052 Err(RpcError::internal_error().with_message("Not a ServerNotification".to_string()))
1053 }
1054 }
1055}
1056
1057impl NotificationFromServer {
1058 pub fn method(&self) -> &str {
1059 match self {
1060 NotificationFromServer::ServerNotification(notification) => notification.method(),
1061 NotificationFromServer::CustomNotification(notification) => notification["method"].as_str().unwrap(),
1062 }
1063 }
1064}
1065
1066impl<'de> serde::Deserialize<'de> for NotificationFromServer {
1067 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
1068 where
1069 D: serde::Deserializer<'de>,
1070 {
1071 let raw_value = Value::deserialize(deserializer)?;
1072
1073 let result = ServerNotification::deserialize(&raw_value);
1074
1075 match result {
1076 Ok(client_notification) => Ok(Self::ServerNotification(client_notification)),
1077 Err(_) => Ok(Self::CustomNotification(raw_value)),
1078 }
1079 }
1080}
1081
1082#[derive(Clone, Debug)]
1088pub struct ServerJsonrpcResponse {
1089 pub id: RequestId,
1090 jsonrpc: ::std::string::String,
1091 pub result: ResultFromServer,
1092}
1093
1094impl ServerJsonrpcResponse {
1095 pub fn new(id: RequestId, result: ResultFromServer) -> Self {
1096 Self {
1097 id,
1098 jsonrpc: JSONRPC_VERSION.to_string(),
1099 result,
1100 }
1101 }
1102 pub fn jsonrpc(&self) -> &::std::string::String {
1103 &self.jsonrpc
1104 }
1105}
1106
1107impl Display for ServerJsonrpcResponse {
1109 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1110 write!(
1111 f,
1112 "{}",
1113 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1114 )
1115 }
1116}
1117
1118impl FromStr for ServerJsonrpcResponse {
1119 type Err = RpcError;
1120
1121 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1122 serde_json::from_str(s)
1123 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1124 }
1125}
1126#[allow(clippy::large_enum_variant)]
1133#[derive(::serde::Serialize, Clone, Debug)]
1134#[serde(untagged)]
1135pub enum ResultFromServer {
1136 ServerResult(ServerResult),
1137 CustomResult(serde_json::Value),
1139}
1140
1141impl TryFrom<ResultFromServer> for ServerResult {
1142 type Error = RpcError;
1143 fn try_from(value: ResultFromServer) -> result::Result<Self, Self::Error> {
1144 if let ResultFromServer::ServerResult(server_result) = value {
1145 Ok(server_result)
1146 } else {
1147 Err(RpcError::internal_error().with_message("Not a ServerResult".to_string()))
1148 }
1149 }
1150}
1151
1152impl From<ServerResult> for ResultFromServer {
1153 fn from(value: ServerResult) -> Self {
1154 Self::ServerResult(value)
1155 }
1156}
1157
1158impl From<serde_json::Value> for ResultFromServer {
1159 fn from(value: serde_json::Value) -> Self {
1160 Self::CustomResult(value)
1161 }
1162}
1163
1164impl<'de> serde::Deserialize<'de> for ResultFromServer {
1165 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
1166 where
1167 D: serde::Deserializer<'de>,
1168 {
1169 let raw_value = Value::deserialize(deserializer)?;
1170
1171 let result = ServerResult::deserialize(&raw_value);
1172
1173 match result {
1174 Ok(server_result) => Ok(Self::ServerResult(server_result)),
1175 Err(_) => Ok(Self::CustomResult(raw_value)),
1176 }
1177 }
1178}
1179
1180impl Display for JsonrpcError {
1186 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1187 write!(
1188 f,
1189 "{}",
1190 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1191 )
1192 }
1193}
1194
1195impl FromStr for JsonrpcError {
1196 type Err = RpcError;
1197
1198 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1199 serde_json::from_str(s)
1200 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1201 }
1202}
1203
1204#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1213#[serde(untagged)]
1214pub enum MessageFromServer {
1215 RequestFromServer(RequestFromServer),
1216 ResultFromServer(ResultFromServer),
1217 NotificationFromServer(NotificationFromServer),
1218 Error(RpcError),
1219}
1220
1221impl From<RequestFromServer> for MessageFromServer {
1222 fn from(value: RequestFromServer) -> Self {
1223 Self::RequestFromServer(value)
1224 }
1225}
1226
1227impl From<ResultFromServer> for MessageFromServer {
1228 fn from(value: ResultFromServer) -> Self {
1229 Self::ResultFromServer(value)
1230 }
1231}
1232
1233impl From<NotificationFromServer> for MessageFromServer {
1234 fn from(value: NotificationFromServer) -> Self {
1235 Self::NotificationFromServer(value)
1236 }
1237}
1238
1239impl From<RpcError> for MessageFromServer {
1240 fn from(value: RpcError) -> Self {
1241 Self::Error(value)
1242 }
1243}
1244
1245impl McpMessage for MessageFromServer {
1246 fn is_response(&self) -> bool {
1247 matches!(self, MessageFromServer::ResultFromServer(_))
1248 }
1249
1250 fn is_request(&self) -> bool {
1251 matches!(self, MessageFromServer::RequestFromServer(_))
1252 }
1253
1254 fn is_notification(&self) -> bool {
1255 matches!(self, MessageFromServer::NotificationFromServer(_))
1256 }
1257
1258 fn is_error(&self) -> bool {
1259 matches!(self, MessageFromServer::Error(_))
1260 }
1261
1262 fn message_type(&self) -> MessageTypes {
1263 match self {
1264 MessageFromServer::RequestFromServer(_) => MessageTypes::Request,
1265 MessageFromServer::ResultFromServer(_) => MessageTypes::Response,
1266 MessageFromServer::NotificationFromServer(_) => MessageTypes::Notification,
1267 MessageFromServer::Error(_) => MessageTypes::Error,
1268 }
1269 }
1270}
1271
1272impl FromMessage<MessageFromServer> for ServerMessage {
1273 fn from_message(message: MessageFromServer, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1274 match message {
1275 MessageFromServer::RequestFromServer(request_from_server) => {
1276 let request_id =
1277 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1278 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(
1279 request_id,
1280 request_from_server,
1281 )))
1282 }
1283 MessageFromServer::ResultFromServer(result_from_server) => {
1284 let request_id =
1285 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1286 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
1287 request_id,
1288 result_from_server,
1289 )))
1290 }
1291 MessageFromServer::NotificationFromServer(notification_from_server) => {
1292 if request_id.is_some() {
1293 return Err(RpcError::internal_error()
1294 .with_message("request_id expected to be None for Notifications!".to_string()));
1295 }
1296 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(
1297 notification_from_server,
1298 )))
1299 }
1300 MessageFromServer::Error(jsonrpc_error_error) => {
1301 let request_id =
1302 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1303 Ok(ServerMessage::Error(JsonrpcError::new(jsonrpc_error_error, request_id)))
1304 }
1305 }
1306 }
1307}
1308
1309#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1318#[serde(untagged)]
1319pub enum MessageFromClient {
1320 RequestFromClient(RequestFromClient),
1321 ResultFromClient(ResultFromClient),
1322 NotificationFromClient(NotificationFromClient),
1323 Error(RpcError),
1324}
1325
1326impl MessageFromClient {
1327 pub fn is_initialize_request(&self) -> bool {
1329 matches!(self, Self::RequestFromClient(request) if request.is_initialize_request())
1330 }
1331
1332 pub fn is_initialized_notification(&self) -> bool {
1334 matches!(self, Self::NotificationFromClient(notofication) if notofication.is_initialized_notification())
1335 }
1336}
1337
1338impl From<RequestFromClient> for MessageFromClient {
1339 fn from(value: RequestFromClient) -> Self {
1340 Self::RequestFromClient(value)
1341 }
1342}
1343
1344impl From<ResultFromClient> for MessageFromClient {
1345 fn from(value: ResultFromClient) -> Self {
1346 Self::ResultFromClient(value)
1347 }
1348}
1349
1350impl From<NotificationFromClient> for MessageFromClient {
1351 fn from(value: NotificationFromClient) -> Self {
1352 Self::NotificationFromClient(value)
1353 }
1354}
1355
1356impl From<RpcError> for MessageFromClient {
1357 fn from(value: RpcError) -> Self {
1358 Self::Error(value)
1359 }
1360}
1361
1362impl McpMessage for MessageFromClient {
1363 fn is_response(&self) -> bool {
1364 matches!(self, MessageFromClient::ResultFromClient(_))
1365 }
1366
1367 fn is_request(&self) -> bool {
1368 matches!(self, MessageFromClient::RequestFromClient(_))
1369 }
1370
1371 fn is_notification(&self) -> bool {
1372 matches!(self, MessageFromClient::NotificationFromClient(_))
1373 }
1374
1375 fn is_error(&self) -> bool {
1376 matches!(self, MessageFromClient::Error(_))
1377 }
1378
1379 fn message_type(&self) -> MessageTypes {
1380 match self {
1381 MessageFromClient::RequestFromClient(_) => MessageTypes::Request,
1382 MessageFromClient::ResultFromClient(_) => MessageTypes::Response,
1383 MessageFromClient::NotificationFromClient(_) => MessageTypes::Notification,
1384 MessageFromClient::Error(_) => MessageTypes::Error,
1385 }
1386 }
1387}
1388
1389impl FromMessage<MessageFromClient> for ClientMessage {
1390 fn from_message(message: MessageFromClient, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1391 match message {
1392 MessageFromClient::RequestFromClient(request_from_client) => {
1393 let request_id =
1394 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1395 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(
1396 request_id,
1397 request_from_client,
1398 )))
1399 }
1400 MessageFromClient::ResultFromClient(result_from_client) => {
1401 let request_id =
1402 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1403 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
1404 request_id,
1405 result_from_client,
1406 )))
1407 }
1408 MessageFromClient::NotificationFromClient(notification_from_client) => {
1409 if request_id.is_some() {
1410 return Err(RpcError::internal_error()
1411 .with_message("request_id expected to be None for Notifications!".to_string()));
1412 }
1413
1414 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(
1415 notification_from_client,
1416 )))
1417 }
1418 MessageFromClient::Error(jsonrpc_error_error) => {
1419 let request_id =
1420 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1421 Ok(ClientMessage::Error(JsonrpcError::new(jsonrpc_error_error, request_id)))
1422 }
1423 }
1424 }
1425}
1426
1427#[derive(Debug)]
1434pub struct UnknownTool(pub String);
1435
1436impl core::fmt::Display for UnknownTool {
1438 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1439 write!(f, "Unknown tool: {}", self.0)
1441 }
1442}
1443
1444impl std::error::Error for UnknownTool {}
1446
1447#[derive(Debug)]
1453pub struct CallToolError(pub Box<dyn std::error::Error>);
1454
1455impl CallToolError {
1457 pub fn new<E: std::error::Error + 'static>(err: E) -> Self {
1459 CallToolError(Box::new(err))
1461 }
1462
1463 pub fn unknown_tool(tool_name: impl Into<String>) -> Self {
1465 CallToolError(Box::new(UnknownTool(tool_name.into())))
1467 }
1468
1469 pub fn invalid_arguments(tool_name: impl AsRef<str>, message: Option<String>) -> Self {
1472 let tool_name = tool_name.as_ref().trim();
1474 if tool_name.is_empty() {
1475 return Self::from_message("Invalid arguments: tool name cannot be empty".to_string());
1476 }
1477
1478 let default_message = "no additional details provided".to_string();
1480 let message = message.unwrap_or(default_message);
1481
1482 let full_message = format!("Invalid arguments for tool '{tool_name}': {message}");
1484
1485 Self::from_message(full_message)
1486 }
1487
1488 pub fn from_message(message: impl Into<String>) -> Self {
1508 struct MsgError(String);
1509 impl std::fmt::Debug for MsgError {
1510 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1511 write!(f, "{}", self.0)
1512 }
1513 }
1514 impl std::fmt::Display for MsgError {
1515 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1516 write!(f, "{}", self.0)
1517 }
1518 }
1519 impl std::error::Error for MsgError {}
1520
1521 CallToolError::new(MsgError(message.into()))
1522 }
1523}
1524
1525impl From<CallToolError> for RpcError {
1531 fn from(value: CallToolError) -> Self {
1532 Self::internal_error().with_message(value.to_string())
1533 }
1534}
1535
1536impl From<CallToolError> for CallToolResult {
1538 fn from(value: CallToolError) -> Self {
1539 CallToolResult {
1541 content: vec![TextContent::new(value.to_string(), None, None).into()],
1542 is_error: Some(true),
1543 meta: None,
1544 structured_content: None,
1545 }
1546 }
1547}
1548
1549impl core::fmt::Display for CallToolError {
1551 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1552 write!(f, "{}", self.0)
1553 }
1554}
1555
1556impl std::error::Error for CallToolError {
1558 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1559 self.0.source()
1560 }
1561}
1562
1563impl CallToolRequest {
1564 pub fn tool_name(&self) -> &str {
1572 &self.params.name
1573 }
1574}
1575
1576impl<T: Into<String>> From<T> for TextContent {
1577 fn from(value: T) -> Self {
1578 TextContent::new(value.into(), None, None)
1579 }
1580}
1581
1582#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1583#[serde(untagged)]
1584#[allow(clippy::large_enum_variant)]
1585pub enum ClientMessages {
1586 Single(ClientMessage),
1587 Batch(Vec<ClientMessage>),
1588}
1589
1590impl ClientMessages {
1591 pub fn is_batch(&self) -> bool {
1592 matches!(self, ClientMessages::Batch(_))
1593 }
1594
1595 pub fn includes_request(&self) -> bool {
1596 match self {
1597 ClientMessages::Single(client_message) => client_message.is_request(),
1598 ClientMessages::Batch(client_messages) => client_messages.iter().any(ClientMessage::is_request),
1599 }
1600 }
1601
1602 pub fn as_single(self) -> result::Result<ClientMessage, SdkError> {
1603 match self {
1604 ClientMessages::Single(client_message) => Ok(client_message),
1605 ClientMessages::Batch(_) => Err(SdkError::internal_error()
1606 .with_message("Error: cannot convert ClientMessages::Batch to ClientMessage::Single")),
1607 }
1608 }
1609 pub fn as_batch(self) -> result::Result<Vec<ClientMessage>, SdkError> {
1610 match self {
1611 ClientMessages::Single(_) => Err(SdkError::internal_error()
1612 .with_message("Error: cannot convert ClientMessage::Single to ClientMessages::Batch")),
1613 ClientMessages::Batch(client_messages) => Ok(client_messages),
1614 }
1615 }
1616}
1617
1618impl From<ClientMessage> for ClientMessages {
1619 fn from(value: ClientMessage) -> Self {
1620 Self::Single(value)
1621 }
1622}
1623
1624impl From<Vec<ClientMessage>> for ClientMessages {
1625 fn from(value: Vec<ClientMessage>) -> Self {
1626 Self::Batch(value)
1627 }
1628}
1629
1630impl Display for ClientMessages {
1631 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1632 write!(
1633 f,
1634 "{}",
1635 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1636 )
1637 }
1638}
1639
1640#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1641#[serde(untagged)]
1642#[allow(clippy::large_enum_variant)]
1643pub enum ServerMessages {
1644 Single(ServerMessage),
1645 Batch(Vec<ServerMessage>),
1646}
1647
1648impl ServerMessages {
1649 pub fn is_batch(&self) -> bool {
1650 matches!(self, ServerMessages::Batch(_))
1651 }
1652
1653 pub fn includes_request(&self) -> bool {
1654 match self {
1655 ServerMessages::Single(server_message) => server_message.is_request(),
1656 ServerMessages::Batch(server_messages) => server_messages.iter().any(ServerMessage::is_request),
1657 }
1658 }
1659
1660 pub fn as_single(self) -> result::Result<ServerMessage, SdkError> {
1661 match self {
1662 ServerMessages::Single(server_message) => Ok(server_message),
1663 ServerMessages::Batch(_) => Err(SdkError::internal_error()
1664 .with_message("Error: cannot convert ServerMessages::Batch to ServerMessage::Single")),
1665 }
1666 }
1667 pub fn as_batch(self) -> result::Result<Vec<ServerMessage>, SdkError> {
1668 match self {
1669 ServerMessages::Single(_) => Err(SdkError::internal_error()
1670 .with_message("Error: cannot convert ServerMessage::Single to ServerMessages::Batch")),
1671 ServerMessages::Batch(server_messages) => Ok(server_messages),
1672 }
1673 }
1674}
1675
1676impl From<ServerMessage> for ServerMessages {
1677 fn from(value: ServerMessage) -> Self {
1678 Self::Single(value)
1679 }
1680}
1681
1682impl From<Vec<ServerMessage>> for ServerMessages {
1683 fn from(value: Vec<ServerMessage>) -> Self {
1684 Self::Batch(value)
1685 }
1686}
1687
1688impl Display for ServerMessages {
1689 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1690 write!(
1691 f,
1692 "{}",
1693 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1694 )
1695 }
1696}
1697
1698#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1699#[serde(untagged)]
1700#[allow(clippy::large_enum_variant)]
1701pub enum MessagesFromServer {
1702 Single(MessageFromServer),
1703 Batch(Vec<MessageFromServer>),
1704}
1705
1706impl MessagesFromServer {
1707 pub fn is_batch(&self) -> bool {
1708 matches!(self, MessagesFromServer::Batch(_))
1709 }
1710
1711 pub fn includes_request(&self) -> bool {
1712 match self {
1713 MessagesFromServer::Single(server_message) => server_message.is_request(),
1714 MessagesFromServer::Batch(server_messages) => server_messages.iter().any(MessageFromServer::is_request),
1715 }
1716 }
1717
1718 pub fn as_single(self) -> result::Result<MessageFromServer, SdkError> {
1719 match self {
1720 MessagesFromServer::Single(server_message) => Ok(server_message),
1721 MessagesFromServer::Batch(_) => Err(SdkError::internal_error()
1722 .with_message("Error: cannot convert MessagesFromServer::Batch to MessageFromServer::Single")),
1723 }
1724 }
1725 pub fn as_batch(self) -> result::Result<Vec<MessageFromServer>, SdkError> {
1726 match self {
1727 MessagesFromServer::Single(_) => Err(SdkError::internal_error()
1728 .with_message("Error: cannot convert MessageFromServer::Single to MessagesFromServer::Batch")),
1729 MessagesFromServer::Batch(server_messages) => Ok(server_messages),
1730 }
1731 }
1732}
1733
1734impl From<MessageFromServer> for MessagesFromServer {
1735 fn from(value: MessageFromServer) -> Self {
1736 Self::Single(value)
1737 }
1738}
1739
1740impl From<Vec<MessageFromServer>> for MessagesFromServer {
1741 fn from(value: Vec<MessageFromServer>) -> Self {
1742 Self::Batch(value)
1743 }
1744}
1745
1746#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1747#[serde(untagged)]
1748#[allow(clippy::large_enum_variant)]
1749pub enum MessagesFromClient {
1750 Single(MessageFromClient),
1751 Batch(Vec<MessageFromClient>),
1752}
1753
1754impl MessagesFromClient {
1755 pub fn is_batch(&self) -> bool {
1756 matches!(self, MessagesFromClient::Batch(_))
1757 }
1758
1759 pub fn includes_request(&self) -> bool {
1760 match self {
1761 MessagesFromClient::Single(server_message) => server_message.is_request(),
1762 MessagesFromClient::Batch(server_messages) => server_messages.iter().any(MessageFromClient::is_request),
1763 }
1764 }
1765
1766 pub fn as_single(self) -> result::Result<MessageFromClient, SdkError> {
1767 match self {
1768 MessagesFromClient::Single(server_message) => Ok(server_message),
1769 MessagesFromClient::Batch(_) => Err(SdkError::internal_error()
1770 .with_message("Error: cannot convert MessagesFromClient::Batch to MessageFromClient::Single")),
1771 }
1772 }
1773 pub fn as_batch(self) -> result::Result<Vec<MessageFromClient>, SdkError> {
1774 match self {
1775 MessagesFromClient::Single(_) => Err(SdkError::internal_error()
1776 .with_message("Error: cannot convert MessageFromClient::Single to MessagesFromClient::Batch")),
1777 MessagesFromClient::Batch(server_messages) => Ok(server_messages),
1778 }
1779 }
1780}
1781
1782impl From<MessageFromClient> for MessagesFromClient {
1783 fn from(value: MessageFromClient) -> Self {
1784 Self::Single(value)
1785 }
1786}
1787
1788impl From<Vec<MessageFromClient>> for MessagesFromClient {
1789 fn from(value: Vec<MessageFromClient>) -> Self {
1790 Self::Batch(value)
1791 }
1792}
1793
1794#[deprecated(since = "0.4.0", note = "This trait was renamed to RpcMessage. Use RpcMessage instead.")]
1795pub type RPCMessage = ();
1796#[deprecated(since = "0.4.0", note = "This trait was renamed to McpMessage. Use McpMessage instead.")]
1797pub type MCPMessage = ();
1798
1799impl ::serde::Serialize for ClientJsonrpcRequest {
1801 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1802 where
1803 S: ::serde::Serializer,
1804 {
1805 let mut state = serializer.serialize_struct("JsonrpcRequest", 4)?;
1806 state.serialize_field("id", &self.id)?;
1807 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1808 state.serialize_field("method", &self.method)?;
1809 use ClientRequest::*;
1810 match &self.request {
1811 RequestFromClient::ClientRequest(message) => match message {
1812 InitializeRequest(msg) => state.serialize_field("params", &msg.params)?,
1813 PingRequest(msg) => {
1814 if let Some(params) = &msg.params {
1815 state.serialize_field("params", params)?
1816 }
1817 }
1818 ListResourcesRequest(msg) => state.serialize_field("params", &msg.params)?,
1819 ListResourceTemplatesRequest(msg) => {
1820 if let Some(params) = &msg.params {
1821 state.serialize_field("params", params)?
1822 }
1823 }
1824 ReadResourceRequest(msg) => state.serialize_field("params", &msg.params)?,
1825 SubscribeRequest(msg) => state.serialize_field("params", &msg.params)?,
1826 UnsubscribeRequest(msg) => state.serialize_field("params", &msg.params)?,
1827 ListPromptsRequest(msg) => {
1828 if let Some(params) = &msg.params {
1829 state.serialize_field("params", params)?
1830 }
1831 }
1832 GetPromptRequest(msg) => state.serialize_field("params", &msg.params)?,
1833 ListToolsRequest(msg) => {
1834 if let Some(params) = &msg.params {
1835 state.serialize_field("params", params)?
1836 }
1837 }
1838 CallToolRequest(msg) => state.serialize_field("params", &msg.params)?,
1839 SetLevelRequest(msg) => state.serialize_field("params", &msg.params)?,
1840 CompleteRequest(msg) => state.serialize_field("params", &msg.params)?,
1841 },
1842 RequestFromClient::CustomRequest(value) => state.serialize_field("params", value)?,
1843 }
1844 state.end()
1845 }
1846}
1847impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcRequest {
1848 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1849 where
1850 D: ::serde::Deserializer<'de>,
1851 {
1852 use serde::de::{self, MapAccess, Visitor};
1853 use std::fmt;
1854 struct ClientJsonrpcRequestVisitor;
1855 impl<'de> Visitor<'de> for ClientJsonrpcRequestVisitor {
1856 type Value = ClientJsonrpcRequest;
1857 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1858 formatter.write_str("a valid JSON-RPC request object")
1859 }
1860 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcRequest, M::Error>
1861 where
1862 M: MapAccess<'de>,
1863 {
1864 let mut id: Option<RequestId> = None;
1865 let mut jsonrpc: Option<String> = None;
1866 let mut method: Option<String> = None;
1867 let mut params: Option<Value> = None;
1868 while let Some(key) = map.next_key::<String>()? {
1869 match key.as_str() {
1870 "id" => id = Some(map.next_value()?),
1871 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1872 "method" => method = Some(map.next_value()?),
1873 "params" => params = Some(map.next_value()?),
1874 _ => {
1875 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1876 }
1877 }
1878 }
1879 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1880 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1881 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1882 let params = params.unwrap_or_default();
1883 let req_object = json!({ "method" : method, "params" : params });
1884 let request = serde_json::from_value::<RequestFromClient>(req_object).map_err(de::Error::custom)?;
1885 Ok(ClientJsonrpcRequest {
1886 id,
1887 jsonrpc,
1888 method,
1889 request,
1890 })
1891 }
1892 }
1893 deserializer.deserialize_struct(
1894 "JsonrpcRequest",
1895 &["id", "jsonrpc", "method", "params"],
1896 ClientJsonrpcRequestVisitor,
1897 )
1898 }
1899}
1900impl ::serde::Serialize for ServerJsonrpcRequest {
1901 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1902 where
1903 S: ::serde::Serializer,
1904 {
1905 let mut state = serializer.serialize_struct("JsonrpcRequest", 4)?;
1906 state.serialize_field("id", &self.id)?;
1907 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1908 state.serialize_field("method", &self.method)?;
1909 use ServerRequest::*;
1910 match &self.request {
1911 RequestFromServer::ServerRequest(message) => match message {
1912 PingRequest(msg) => {
1913 if let Some(params) = &msg.params {
1914 state.serialize_field("params", params)?
1915 }
1916 }
1917 CreateMessageRequest(msg) => state.serialize_field("params", &msg.params)?,
1918 ListRootsRequest(msg) => {
1919 if let Some(params) = &msg.params {
1920 state.serialize_field("params", params)?
1921 }
1922 }
1923 ElicitRequest(msg) => state.serialize_field("params", &msg.params)?,
1924 },
1925 RequestFromServer::CustomRequest(value) => state.serialize_field("params", value)?,
1926 }
1927 state.end()
1928 }
1929}
1930impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcRequest {
1931 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
1932 where
1933 D: ::serde::Deserializer<'de>,
1934 {
1935 use serde::de::{self, MapAccess, Visitor};
1936 use std::fmt;
1937 struct ServerJsonrpcRequestVisitor;
1938 impl<'de> Visitor<'de> for ServerJsonrpcRequestVisitor {
1939 type Value = ServerJsonrpcRequest;
1940 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
1941 formatter.write_str("a valid JSON-RPC request object")
1942 }
1943 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcRequest, M::Error>
1944 where
1945 M: MapAccess<'de>,
1946 {
1947 let mut id: Option<RequestId> = None;
1948 let mut jsonrpc: Option<String> = None;
1949 let mut method: Option<String> = None;
1950 let mut params: Option<Value> = None;
1951 while let Some(key) = map.next_key::<String>()? {
1952 match key.as_str() {
1953 "id" => id = Some(map.next_value()?),
1954 "jsonrpc" => jsonrpc = Some(map.next_value()?),
1955 "method" => method = Some(map.next_value()?),
1956 "params" => params = Some(map.next_value()?),
1957 _ => {
1958 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
1959 }
1960 }
1961 }
1962 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
1963 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
1964 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
1965 let params = params.unwrap_or_default();
1966 let req_object = json!({ "method" : method, "params" : params });
1967 let request = serde_json::from_value::<RequestFromServer>(req_object).map_err(de::Error::custom)?;
1968 Ok(ServerJsonrpcRequest {
1969 id,
1970 jsonrpc,
1971 method,
1972 request,
1973 })
1974 }
1975 }
1976 deserializer.deserialize_struct(
1977 "JsonrpcRequest",
1978 &["id", "jsonrpc", "method", "params"],
1979 ServerJsonrpcRequestVisitor,
1980 )
1981 }
1982}
1983impl ::serde::Serialize for ClientJsonrpcNotification {
1984 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1985 where
1986 S: ::serde::Serializer,
1987 {
1988 let mut state = serializer.serialize_struct("JsonrpcNotification", 3)?;
1989 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1990 state.serialize_field("method", &self.method)?;
1991 use ClientNotification::*;
1992 match &self.notification {
1993 NotificationFromClient::ClientNotification(message) => match message {
1994 CancelledNotification(msg) => state.serialize_field("params", &msg.params)?,
1995 InitializedNotification(msg) => {
1996 if let Some(params) = &msg.params {
1997 state.serialize_field("params", params)?
1998 }
1999 }
2000 ProgressNotification(msg) => state.serialize_field("params", &msg.params)?,
2001 RootsListChangedNotification(msg) => {
2002 if let Some(params) = &msg.params {
2003 state.serialize_field("params", params)?
2004 }
2005 }
2006 },
2007 NotificationFromClient::CustomNotification(value) => state.serialize_field("params", value)?,
2008 }
2009 state.end()
2010 }
2011}
2012impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcNotification {
2013 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2014 where
2015 D: ::serde::Deserializer<'de>,
2016 {
2017 use serde::de::{self, MapAccess, Visitor};
2018 use std::fmt;
2019 struct ClientJsonrpcNotificationVisitor;
2020 impl<'de> Visitor<'de> for ClientJsonrpcNotificationVisitor {
2021 type Value = ClientJsonrpcNotification;
2022 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2023 formatter.write_str("a valid JSON-RPC notification object")
2024 }
2025 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcNotification, M::Error>
2026 where
2027 M: MapAccess<'de>,
2028 {
2029 let mut jsonrpc: Option<String> = None;
2030 let mut method: Option<String> = None;
2031 let mut params: Option<Value> = None;
2032 while let Some(key) = map.next_key::<String>()? {
2033 match key.as_str() {
2034 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2035 "method" => method = Some(map.next_value()?),
2036 "params" => params = Some(map.next_value()?),
2037 _ => {
2038 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
2039 }
2040 }
2041 }
2042 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2043 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
2044 let params = params.unwrap_or_default();
2045 let req_object = json!({ "method" : method, "params" : params });
2046 let notification =
2047 serde_json::from_value::<NotificationFromClient>(req_object).map_err(de::Error::custom)?;
2048 Ok(ClientJsonrpcNotification {
2049 jsonrpc,
2050 method,
2051 notification,
2052 })
2053 }
2054 }
2055 deserializer.deserialize_struct(
2056 "JsonrpcRequest",
2057 &["jsonrpc", "method", "params"],
2058 ClientJsonrpcNotificationVisitor,
2059 )
2060 }
2061}
2062impl ::serde::Serialize for ServerJsonrpcNotification {
2063 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2064 where
2065 S: ::serde::Serializer,
2066 {
2067 let mut state = serializer.serialize_struct("JsonrpcNotification", 3)?;
2068 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2069 state.serialize_field("method", &self.method)?;
2070 use ServerNotification::*;
2071 match &self.notification {
2072 NotificationFromServer::ServerNotification(message) => match message {
2073 CancelledNotification(msg) => state.serialize_field("params", &msg.params)?,
2074 ProgressNotification(msg) => state.serialize_field("params", &msg.params)?,
2075 ResourceListChangedNotification(msg) => {
2076 if let Some(params) = &msg.params {
2077 state.serialize_field("params", params)?
2078 }
2079 }
2080 ResourceUpdatedNotification(msg) => state.serialize_field("params", &msg.params)?,
2081 PromptListChangedNotification(msg) => {
2082 if let Some(params) = &msg.params {
2083 state.serialize_field("params", params)?
2084 }
2085 }
2086 ToolListChangedNotification(msg) => {
2087 if let Some(params) = &msg.params {
2088 state.serialize_field("params", params)?
2089 }
2090 }
2091 LoggingMessageNotification(msg) => state.serialize_field("params", &msg.params)?,
2092 },
2093 NotificationFromServer::CustomNotification(value) => state.serialize_field("params", value)?,
2094 }
2095 state.end()
2096 }
2097}
2098impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcNotification {
2099 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2100 where
2101 D: ::serde::Deserializer<'de>,
2102 {
2103 use serde::de::{self, MapAccess, Visitor};
2104 use std::fmt;
2105 struct ServerJsonrpcNotificationVisitor;
2106 impl<'de> Visitor<'de> for ServerJsonrpcNotificationVisitor {
2107 type Value = ServerJsonrpcNotification;
2108 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2109 formatter.write_str("a valid JSON-RPC notification object")
2110 }
2111 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcNotification, M::Error>
2112 where
2113 M: MapAccess<'de>,
2114 {
2115 let mut jsonrpc: Option<String> = None;
2116 let mut method: Option<String> = None;
2117 let mut params: Option<Value> = None;
2118 while let Some(key) = map.next_key::<String>()? {
2119 match key.as_str() {
2120 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2121 "method" => method = Some(map.next_value()?),
2122 "params" => params = Some(map.next_value()?),
2123 _ => {
2124 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
2125 }
2126 }
2127 }
2128 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2129 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
2130 let params = params.unwrap_or_default();
2131 let req_object = json!({ "method" : method, "params" : params });
2132 let notification =
2133 serde_json::from_value::<NotificationFromServer>(req_object).map_err(de::Error::custom)?;
2134 Ok(ServerJsonrpcNotification {
2135 jsonrpc,
2136 method,
2137 notification,
2138 })
2139 }
2140 }
2141 deserializer.deserialize_struct(
2142 "JsonrpcRequest",
2143 &["jsonrpc", "method", "params"],
2144 ServerJsonrpcNotificationVisitor,
2145 )
2146 }
2147}
2148impl ::serde::Serialize for ServerJsonrpcResponse {
2149 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2150 where
2151 S: ::serde::Serializer,
2152 {
2153 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
2154 state.serialize_field("id", &self.id)?;
2155 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2156 state.serialize_field("result", &self.result)?;
2157 state.end()
2158 }
2159}
2160impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcResponse {
2161 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2162 where
2163 D: ::serde::Deserializer<'de>,
2164 {
2165 use serde::de::{self, MapAccess, Visitor};
2166 use std::fmt;
2167 struct ServerJsonrpcResultVisitor;
2168 impl<'de> Visitor<'de> for ServerJsonrpcResultVisitor {
2169 type Value = ServerJsonrpcResponse;
2170 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2171 formatter.write_str("a valid JSON-RPC response object")
2172 }
2173 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcResponse, M::Error>
2174 where
2175 M: MapAccess<'de>,
2176 {
2177 let mut id: Option<RequestId> = None;
2178 let mut jsonrpc: Option<String> = None;
2179 let mut result: Option<Value> = None;
2180 while let Some(key) = map.next_key::<String>()? {
2181 match key.as_str() {
2182 "id" => id = Some(map.next_value()?),
2183 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2184 "result" => result = Some(map.next_value()?),
2185 _ => {
2186 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
2187 }
2188 }
2189 }
2190 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
2191 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2192 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
2193 let result = serde_json::from_value::<ResultFromServer>(result).map_err(de::Error::custom)?;
2194 Ok(ServerJsonrpcResponse { id, jsonrpc, result })
2195 }
2196 }
2197 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ServerJsonrpcResultVisitor)
2198 }
2199}
2200impl ::serde::Serialize for ClientJsonrpcResponse {
2201 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2202 where
2203 S: ::serde::Serializer,
2204 {
2205 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
2206 state.serialize_field("id", &self.id)?;
2207 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2208 state.serialize_field("result", &self.result)?;
2209 state.end()
2210 }
2211}
2212impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcResponse {
2213 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2214 where
2215 D: ::serde::Deserializer<'de>,
2216 {
2217 use serde::de::{self, MapAccess, Visitor};
2218 use std::fmt;
2219 struct ClientJsonrpcResultVisitor;
2220 impl<'de> Visitor<'de> for ClientJsonrpcResultVisitor {
2221 type Value = ClientJsonrpcResponse;
2222 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2223 formatter.write_str("a valid JSON-RPC response object")
2224 }
2225 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcResponse, M::Error>
2226 where
2227 M: MapAccess<'de>,
2228 {
2229 let mut id: Option<RequestId> = None;
2230 let mut jsonrpc: Option<String> = None;
2231 let mut result: Option<Value> = None;
2232 while let Some(key) = map.next_key::<String>()? {
2233 match key.as_str() {
2234 "id" => id = Some(map.next_value()?),
2235 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2236 "result" => result = Some(map.next_value()?),
2237 _ => {
2238 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
2239 }
2240 }
2241 }
2242 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
2243 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2244 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
2245 let result = serde_json::from_value::<ResultFromClient>(result).map_err(de::Error::custom)?;
2246 Ok(ClientJsonrpcResponse { id, jsonrpc, result })
2247 }
2248 }
2249 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ClientJsonrpcResultVisitor)
2250 }
2251}
2252impl From<InitializeRequest> for RequestFromClient {
2253 fn from(value: InitializeRequest) -> Self {
2254 Self::ClientRequest(value.into())
2255 }
2256}
2257impl From<PingRequest> for RequestFromClient {
2258 fn from(value: PingRequest) -> Self {
2259 Self::ClientRequest(value.into())
2260 }
2261}
2262impl From<ListResourcesRequest> for RequestFromClient {
2263 fn from(value: ListResourcesRequest) -> Self {
2264 Self::ClientRequest(value.into())
2265 }
2266}
2267impl From<ListResourceTemplatesRequest> for RequestFromClient {
2268 fn from(value: ListResourceTemplatesRequest) -> Self {
2269 Self::ClientRequest(value.into())
2270 }
2271}
2272impl From<ReadResourceRequest> for RequestFromClient {
2273 fn from(value: ReadResourceRequest) -> Self {
2274 Self::ClientRequest(value.into())
2275 }
2276}
2277impl From<SubscribeRequest> for RequestFromClient {
2278 fn from(value: SubscribeRequest) -> Self {
2279 Self::ClientRequest(value.into())
2280 }
2281}
2282impl From<UnsubscribeRequest> for RequestFromClient {
2283 fn from(value: UnsubscribeRequest) -> Self {
2284 Self::ClientRequest(value.into())
2285 }
2286}
2287impl From<ListPromptsRequest> for RequestFromClient {
2288 fn from(value: ListPromptsRequest) -> Self {
2289 Self::ClientRequest(value.into())
2290 }
2291}
2292impl From<GetPromptRequest> for RequestFromClient {
2293 fn from(value: GetPromptRequest) -> Self {
2294 Self::ClientRequest(value.into())
2295 }
2296}
2297impl From<ListToolsRequest> for RequestFromClient {
2298 fn from(value: ListToolsRequest) -> Self {
2299 Self::ClientRequest(value.into())
2300 }
2301}
2302impl From<CallToolRequest> for RequestFromClient {
2303 fn from(value: CallToolRequest) -> Self {
2304 Self::ClientRequest(value.into())
2305 }
2306}
2307impl From<SetLevelRequest> for RequestFromClient {
2308 fn from(value: SetLevelRequest) -> Self {
2309 Self::ClientRequest(value.into())
2310 }
2311}
2312impl From<CompleteRequest> for RequestFromClient {
2313 fn from(value: CompleteRequest) -> Self {
2314 Self::ClientRequest(value.into())
2315 }
2316}
2317impl From<InitializeRequest> for MessageFromClient {
2318 fn from(value: InitializeRequest) -> Self {
2319 MessageFromClient::RequestFromClient(value.into())
2320 }
2321}
2322impl From<PingRequest> for MessageFromClient {
2323 fn from(value: PingRequest) -> Self {
2324 MessageFromClient::RequestFromClient(value.into())
2325 }
2326}
2327impl From<ListResourcesRequest> for MessageFromClient {
2328 fn from(value: ListResourcesRequest) -> Self {
2329 MessageFromClient::RequestFromClient(value.into())
2330 }
2331}
2332impl From<ListResourceTemplatesRequest> for MessageFromClient {
2333 fn from(value: ListResourceTemplatesRequest) -> Self {
2334 MessageFromClient::RequestFromClient(value.into())
2335 }
2336}
2337impl From<ReadResourceRequest> for MessageFromClient {
2338 fn from(value: ReadResourceRequest) -> Self {
2339 MessageFromClient::RequestFromClient(value.into())
2340 }
2341}
2342impl From<SubscribeRequest> for MessageFromClient {
2343 fn from(value: SubscribeRequest) -> Self {
2344 MessageFromClient::RequestFromClient(value.into())
2345 }
2346}
2347impl From<UnsubscribeRequest> for MessageFromClient {
2348 fn from(value: UnsubscribeRequest) -> Self {
2349 MessageFromClient::RequestFromClient(value.into())
2350 }
2351}
2352impl From<ListPromptsRequest> for MessageFromClient {
2353 fn from(value: ListPromptsRequest) -> Self {
2354 MessageFromClient::RequestFromClient(value.into())
2355 }
2356}
2357impl From<GetPromptRequest> for MessageFromClient {
2358 fn from(value: GetPromptRequest) -> Self {
2359 MessageFromClient::RequestFromClient(value.into())
2360 }
2361}
2362impl From<ListToolsRequest> for MessageFromClient {
2363 fn from(value: ListToolsRequest) -> Self {
2364 MessageFromClient::RequestFromClient(value.into())
2365 }
2366}
2367impl From<CallToolRequest> for MessageFromClient {
2368 fn from(value: CallToolRequest) -> Self {
2369 MessageFromClient::RequestFromClient(value.into())
2370 }
2371}
2372impl From<SetLevelRequest> for MessageFromClient {
2373 fn from(value: SetLevelRequest) -> Self {
2374 MessageFromClient::RequestFromClient(value.into())
2375 }
2376}
2377impl From<CompleteRequest> for MessageFromClient {
2378 fn from(value: CompleteRequest) -> Self {
2379 MessageFromClient::RequestFromClient(value.into())
2380 }
2381}
2382impl From<CancelledNotification> for NotificationFromClient {
2383 fn from(value: CancelledNotification) -> Self {
2384 Self::ClientNotification(value.into())
2385 }
2386}
2387impl From<InitializedNotification> for NotificationFromClient {
2388 fn from(value: InitializedNotification) -> Self {
2389 Self::ClientNotification(value.into())
2390 }
2391}
2392impl From<ProgressNotification> for NotificationFromClient {
2393 fn from(value: ProgressNotification) -> Self {
2394 Self::ClientNotification(value.into())
2395 }
2396}
2397impl From<RootsListChangedNotification> for NotificationFromClient {
2398 fn from(value: RootsListChangedNotification) -> Self {
2399 Self::ClientNotification(value.into())
2400 }
2401}
2402impl From<CancelledNotification> for ClientJsonrpcNotification {
2403 fn from(value: CancelledNotification) -> Self {
2404 Self::new(value.into())
2405 }
2406}
2407impl From<InitializedNotification> for ClientJsonrpcNotification {
2408 fn from(value: InitializedNotification) -> Self {
2409 Self::new(value.into())
2410 }
2411}
2412impl From<ProgressNotification> for ClientJsonrpcNotification {
2413 fn from(value: ProgressNotification) -> Self {
2414 Self::new(value.into())
2415 }
2416}
2417impl From<RootsListChangedNotification> for ClientJsonrpcNotification {
2418 fn from(value: RootsListChangedNotification) -> Self {
2419 Self::new(value.into())
2420 }
2421}
2422impl From<CancelledNotification> for MessageFromClient {
2423 fn from(value: CancelledNotification) -> Self {
2424 MessageFromClient::NotificationFromClient(value.into())
2425 }
2426}
2427impl From<InitializedNotification> for MessageFromClient {
2428 fn from(value: InitializedNotification) -> Self {
2429 MessageFromClient::NotificationFromClient(value.into())
2430 }
2431}
2432impl From<ProgressNotification> for MessageFromClient {
2433 fn from(value: ProgressNotification) -> Self {
2434 MessageFromClient::NotificationFromClient(value.into())
2435 }
2436}
2437impl From<RootsListChangedNotification> for MessageFromClient {
2438 fn from(value: RootsListChangedNotification) -> Self {
2439 MessageFromClient::NotificationFromClient(value.into())
2440 }
2441}
2442impl From<Result> for ResultFromClient {
2443 fn from(value: Result) -> Self {
2444 Self::ClientResult(value.into())
2445 }
2446}
2447impl From<CreateMessageResult> for ResultFromClient {
2448 fn from(value: CreateMessageResult) -> Self {
2449 Self::ClientResult(value.into())
2450 }
2451}
2452impl From<ListRootsResult> for ResultFromClient {
2453 fn from(value: ListRootsResult) -> Self {
2454 Self::ClientResult(value.into())
2455 }
2456}
2457impl From<ElicitResult> for ResultFromClient {
2458 fn from(value: ElicitResult) -> Self {
2459 Self::ClientResult(value.into())
2460 }
2461}
2462impl From<Result> for MessageFromClient {
2463 fn from(value: Result) -> Self {
2464 MessageFromClient::ResultFromClient(value.into())
2465 }
2466}
2467impl From<CreateMessageResult> for MessageFromClient {
2468 fn from(value: CreateMessageResult) -> Self {
2469 MessageFromClient::ResultFromClient(value.into())
2470 }
2471}
2472impl From<ListRootsResult> for MessageFromClient {
2473 fn from(value: ListRootsResult) -> Self {
2474 MessageFromClient::ResultFromClient(value.into())
2475 }
2476}
2477impl From<ElicitResult> for MessageFromClient {
2478 fn from(value: ElicitResult) -> Self {
2479 MessageFromClient::ResultFromClient(value.into())
2480 }
2481}
2482#[allow(non_camel_case_types)]
2484pub enum SdkErrorCodes {
2485 CONNECTION_CLOSED = -32000,
2486 REQUEST_TIMEOUT = -32001,
2487 RESOURCE_NOT_FOUND = -32002,
2488 BAD_REQUEST = -32015,
2489 SESSION_NOT_FOUND = -32016,
2490 INVALID_REQUEST = -32600,
2491 METHOD_NOT_FOUND = -32601,
2492 INVALID_PARAMS = -32602,
2493 INTERNAL_ERROR = -32603,
2494 PARSE_ERROR = -32700,
2495}
2496impl core::fmt::Display for SdkErrorCodes {
2497 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2498 match self {
2499 SdkErrorCodes::CONNECTION_CLOSED => write!(f, "Connection closed"),
2500 SdkErrorCodes::REQUEST_TIMEOUT => write!(f, "Request timeout"),
2501 SdkErrorCodes::INVALID_REQUEST => write!(f, "Invalid request"),
2502 SdkErrorCodes::METHOD_NOT_FOUND => write!(f, "Method not found"),
2503 SdkErrorCodes::INVALID_PARAMS => write!(f, "Invalid params"),
2504 SdkErrorCodes::INTERNAL_ERROR => write!(f, "Internal error"),
2505 SdkErrorCodes::PARSE_ERROR => write!(f, "Parse Error"),
2506 SdkErrorCodes::RESOURCE_NOT_FOUND => write!(f, "Resource not found"),
2507 SdkErrorCodes::BAD_REQUEST => write!(f, "Bad request"),
2508 SdkErrorCodes::SESSION_NOT_FOUND => write!(f, "Session not found"),
2509 }
2510 }
2511}
2512impl From<SdkErrorCodes> for i64 {
2513 fn from(code: SdkErrorCodes) -> Self {
2514 code as i64
2515 }
2516}
2517#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
2518pub struct SdkError {
2519 pub code: i64,
2521 pub data: ::std::option::Option<::serde_json::Value>,
2523 pub message: ::std::string::String,
2525}
2526impl core::fmt::Display for SdkError {
2527 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2528 write!(f, "MCP error {}: {}", self.code, self.message)
2529 }
2530}
2531impl std::error::Error for SdkError {
2532 fn description(&self) -> &str {
2533 &self.message
2534 }
2535}
2536impl SdkError {
2537 pub fn new(
2538 error_code: SdkErrorCodes,
2539 message: ::std::string::String,
2540 data: ::std::option::Option<::serde_json::Value>,
2541 ) -> Self {
2542 Self {
2543 code: error_code.into(),
2544 data,
2545 message,
2546 }
2547 }
2548 pub fn connection_closed() -> Self {
2549 Self {
2550 code: SdkErrorCodes::CONNECTION_CLOSED.into(),
2551 data: None,
2552 message: SdkErrorCodes::CONNECTION_CLOSED.to_string(),
2553 }
2554 }
2555 pub fn request_timeout(timeout: u128) -> Self {
2556 Self {
2557 code: SdkErrorCodes::REQUEST_TIMEOUT.into(),
2558 data: Some(json!({ "timeout" : timeout })),
2559 message: SdkErrorCodes::REQUEST_TIMEOUT.to_string(),
2560 }
2561 }
2562 pub fn session_not_found() -> Self {
2563 Self {
2564 code: SdkErrorCodes::SESSION_NOT_FOUND.into(),
2565 data: None,
2566 message: SdkErrorCodes::SESSION_NOT_FOUND.to_string(),
2567 }
2568 }
2569 pub fn invalid_request() -> Self {
2570 Self {
2571 code: SdkErrorCodes::INVALID_REQUEST.into(),
2572 data: None,
2573 message: SdkErrorCodes::INVALID_REQUEST.to_string(),
2574 }
2575 }
2576 pub fn method_not_found() -> Self {
2577 Self {
2578 code: SdkErrorCodes::METHOD_NOT_FOUND.into(),
2579 data: None,
2580 message: SdkErrorCodes::METHOD_NOT_FOUND.to_string(),
2581 }
2582 }
2583 pub fn invalid_params() -> Self {
2584 Self {
2585 code: SdkErrorCodes::INVALID_PARAMS.into(),
2586 data: None,
2587 message: SdkErrorCodes::INVALID_PARAMS.to_string(),
2588 }
2589 }
2590 pub fn internal_error() -> Self {
2591 Self {
2592 code: SdkErrorCodes::INTERNAL_ERROR.into(),
2593 data: None,
2594 message: SdkErrorCodes::INTERNAL_ERROR.to_string(),
2595 }
2596 }
2597 pub fn parse_error() -> Self {
2598 Self {
2599 code: SdkErrorCodes::PARSE_ERROR.into(),
2600 data: None,
2601 message: SdkErrorCodes::PARSE_ERROR.to_string(),
2602 }
2603 }
2604 pub fn resource_not_found() -> Self {
2605 Self {
2606 code: SdkErrorCodes::RESOURCE_NOT_FOUND.into(),
2607 data: None,
2608 message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
2609 }
2610 }
2611 pub fn bad_request() -> Self {
2612 Self {
2613 code: SdkErrorCodes::BAD_REQUEST.into(),
2614 data: None,
2615 message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
2616 }
2617 }
2618 pub fn with_message(mut self, message: &str) -> Self {
2619 self.message = message.to_string();
2620 self
2621 }
2622 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
2623 self.data = data;
2624 self
2625 }
2626}
2627#[allow(non_camel_case_types)]
2629pub enum RpcErrorCodes {
2630 PARSE_ERROR = -32700isize,
2631 INVALID_REQUEST = -32600isize,
2632 METHOD_NOT_FOUND = -32601isize,
2633 INVALID_PARAMS = -32602isize,
2634 INTERNAL_ERROR = -32603isize,
2635}
2636impl From<RpcErrorCodes> for i64 {
2637 fn from(code: RpcErrorCodes) -> Self {
2638 code as i64
2639 }
2640}
2641impl RpcError {
2642 pub fn new(
2659 error_code: RpcErrorCodes,
2660 message: ::std::string::String,
2661 data: ::std::option::Option<::serde_json::Value>,
2662 ) -> Self {
2663 Self {
2664 code: error_code.into(),
2665 data,
2666 message,
2667 }
2668 }
2669 pub fn method_not_found() -> Self {
2680 Self {
2681 code: RpcErrorCodes::METHOD_NOT_FOUND.into(),
2682 data: None,
2683 message: "Method not found".to_string(),
2684 }
2685 }
2686 pub fn invalid_params() -> Self {
2696 Self {
2697 code: RpcErrorCodes::INVALID_PARAMS.into(),
2698 data: None,
2699 message: "Invalid params".to_string(),
2700 }
2701 }
2702 pub fn invalid_request() -> Self {
2712 Self {
2713 code: RpcErrorCodes::INVALID_REQUEST.into(),
2714 data: None,
2715 message: "Invalid request".to_string(),
2716 }
2717 }
2718 pub fn internal_error() -> Self {
2728 Self {
2729 code: RpcErrorCodes::INTERNAL_ERROR.into(),
2730 data: None,
2731 message: "Internal error".to_string(),
2732 }
2733 }
2734 pub fn parse_error() -> Self {
2744 Self {
2745 code: RpcErrorCodes::PARSE_ERROR.into(),
2746 data: None,
2747 message: "Parse error".to_string(),
2748 }
2749 }
2750 pub fn with_message(mut self, message: String) -> Self {
2760 self.message = message;
2761 self
2762 }
2763 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
2774 self.data = data;
2775 self
2776 }
2777}
2778impl std::error::Error for RpcError {
2779 fn description(&self) -> &str {
2780 &self.message
2781 }
2782}
2783impl Display for RpcError {
2784 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2785 write!(
2786 f,
2787 "{}",
2788 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
2789 )
2790 }
2791}
2792impl FromStr for RpcError {
2793 type Err = RpcError;
2794 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2795 serde_json::from_str(s)
2796 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
2797 }
2798}
2799impl JsonrpcError {
2801 pub fn create(
2802 id: RequestId,
2803 error_code: RpcErrorCodes,
2804 error_message: ::std::string::String,
2805 error_data: ::std::option::Option<::serde_json::Value>,
2806 ) -> Self {
2807 Self::new(RpcError::new(error_code, error_message, error_data), id)
2808 }
2809}
2810impl From<CancelledNotification> for NotificationFromServer {
2811 fn from(value: CancelledNotification) -> Self {
2812 Self::ServerNotification(value.into())
2813 }
2814}
2815impl From<ProgressNotification> for NotificationFromServer {
2816 fn from(value: ProgressNotification) -> Self {
2817 Self::ServerNotification(value.into())
2818 }
2819}
2820impl From<ResourceListChangedNotification> for NotificationFromServer {
2821 fn from(value: ResourceListChangedNotification) -> Self {
2822 Self::ServerNotification(value.into())
2823 }
2824}
2825impl From<ResourceUpdatedNotification> for NotificationFromServer {
2826 fn from(value: ResourceUpdatedNotification) -> Self {
2827 Self::ServerNotification(value.into())
2828 }
2829}
2830impl From<PromptListChangedNotification> for NotificationFromServer {
2831 fn from(value: PromptListChangedNotification) -> Self {
2832 Self::ServerNotification(value.into())
2833 }
2834}
2835impl From<ToolListChangedNotification> for NotificationFromServer {
2836 fn from(value: ToolListChangedNotification) -> Self {
2837 Self::ServerNotification(value.into())
2838 }
2839}
2840impl From<LoggingMessageNotification> for NotificationFromServer {
2841 fn from(value: LoggingMessageNotification) -> Self {
2842 Self::ServerNotification(value.into())
2843 }
2844}
2845impl From<CancelledNotification> for ServerJsonrpcNotification {
2846 fn from(value: CancelledNotification) -> Self {
2847 Self::new(value.into())
2848 }
2849}
2850impl From<ProgressNotification> for ServerJsonrpcNotification {
2851 fn from(value: ProgressNotification) -> Self {
2852 Self::new(value.into())
2853 }
2854}
2855impl From<ResourceListChangedNotification> for ServerJsonrpcNotification {
2856 fn from(value: ResourceListChangedNotification) -> Self {
2857 Self::new(value.into())
2858 }
2859}
2860impl From<ResourceUpdatedNotification> for ServerJsonrpcNotification {
2861 fn from(value: ResourceUpdatedNotification) -> Self {
2862 Self::new(value.into())
2863 }
2864}
2865impl From<PromptListChangedNotification> for ServerJsonrpcNotification {
2866 fn from(value: PromptListChangedNotification) -> Self {
2867 Self::new(value.into())
2868 }
2869}
2870impl From<ToolListChangedNotification> for ServerJsonrpcNotification {
2871 fn from(value: ToolListChangedNotification) -> Self {
2872 Self::new(value.into())
2873 }
2874}
2875impl From<LoggingMessageNotification> for ServerJsonrpcNotification {
2876 fn from(value: LoggingMessageNotification) -> Self {
2877 Self::new(value.into())
2878 }
2879}
2880impl From<CancelledNotification> for MessageFromServer {
2881 fn from(value: CancelledNotification) -> Self {
2882 MessageFromServer::NotificationFromServer(value.into())
2883 }
2884}
2885impl From<ProgressNotification> for MessageFromServer {
2886 fn from(value: ProgressNotification) -> Self {
2887 MessageFromServer::NotificationFromServer(value.into())
2888 }
2889}
2890impl From<ResourceListChangedNotification> for MessageFromServer {
2891 fn from(value: ResourceListChangedNotification) -> Self {
2892 MessageFromServer::NotificationFromServer(value.into())
2893 }
2894}
2895impl From<ResourceUpdatedNotification> for MessageFromServer {
2896 fn from(value: ResourceUpdatedNotification) -> Self {
2897 MessageFromServer::NotificationFromServer(value.into())
2898 }
2899}
2900impl From<PromptListChangedNotification> for MessageFromServer {
2901 fn from(value: PromptListChangedNotification) -> Self {
2902 MessageFromServer::NotificationFromServer(value.into())
2903 }
2904}
2905impl From<ToolListChangedNotification> for MessageFromServer {
2906 fn from(value: ToolListChangedNotification) -> Self {
2907 MessageFromServer::NotificationFromServer(value.into())
2908 }
2909}
2910impl From<LoggingMessageNotification> for MessageFromServer {
2911 fn from(value: LoggingMessageNotification) -> Self {
2912 MessageFromServer::NotificationFromServer(value.into())
2913 }
2914}
2915impl From<PingRequest> for RequestFromServer {
2916 fn from(value: PingRequest) -> Self {
2917 Self::ServerRequest(value.into())
2918 }
2919}
2920impl From<CreateMessageRequest> for RequestFromServer {
2921 fn from(value: CreateMessageRequest) -> Self {
2922 Self::ServerRequest(value.into())
2923 }
2924}
2925impl From<ListRootsRequest> for RequestFromServer {
2926 fn from(value: ListRootsRequest) -> Self {
2927 Self::ServerRequest(value.into())
2928 }
2929}
2930impl From<ElicitRequest> for RequestFromServer {
2931 fn from(value: ElicitRequest) -> Self {
2932 Self::ServerRequest(value.into())
2933 }
2934}
2935impl From<PingRequest> for MessageFromServer {
2936 fn from(value: PingRequest) -> Self {
2937 MessageFromServer::RequestFromServer(value.into())
2938 }
2939}
2940impl From<CreateMessageRequest> for MessageFromServer {
2941 fn from(value: CreateMessageRequest) -> Self {
2942 MessageFromServer::RequestFromServer(value.into())
2943 }
2944}
2945impl From<ListRootsRequest> for MessageFromServer {
2946 fn from(value: ListRootsRequest) -> Self {
2947 MessageFromServer::RequestFromServer(value.into())
2948 }
2949}
2950impl From<ElicitRequest> for MessageFromServer {
2951 fn from(value: ElicitRequest) -> Self {
2952 MessageFromServer::RequestFromServer(value.into())
2953 }
2954}
2955impl From<Result> for ResultFromServer {
2956 fn from(value: Result) -> Self {
2957 Self::ServerResult(value.into())
2958 }
2959}
2960impl From<InitializeResult> for ResultFromServer {
2961 fn from(value: InitializeResult) -> Self {
2962 Self::ServerResult(value.into())
2963 }
2964}
2965impl From<ListResourcesResult> for ResultFromServer {
2966 fn from(value: ListResourcesResult) -> Self {
2967 Self::ServerResult(value.into())
2968 }
2969}
2970impl From<ListResourceTemplatesResult> for ResultFromServer {
2971 fn from(value: ListResourceTemplatesResult) -> Self {
2972 Self::ServerResult(value.into())
2973 }
2974}
2975impl From<ReadResourceResult> for ResultFromServer {
2976 fn from(value: ReadResourceResult) -> Self {
2977 Self::ServerResult(value.into())
2978 }
2979}
2980impl From<ListPromptsResult> for ResultFromServer {
2981 fn from(value: ListPromptsResult) -> Self {
2982 Self::ServerResult(value.into())
2983 }
2984}
2985impl From<GetPromptResult> for ResultFromServer {
2986 fn from(value: GetPromptResult) -> Self {
2987 Self::ServerResult(value.into())
2988 }
2989}
2990impl From<ListToolsResult> for ResultFromServer {
2991 fn from(value: ListToolsResult) -> Self {
2992 Self::ServerResult(value.into())
2993 }
2994}
2995impl From<CallToolResult> for ResultFromServer {
2996 fn from(value: CallToolResult) -> Self {
2997 Self::ServerResult(value.into())
2998 }
2999}
3000impl From<CompleteResult> for ResultFromServer {
3001 fn from(value: CompleteResult) -> Self {
3002 Self::ServerResult(value.into())
3003 }
3004}
3005impl From<Result> for MessageFromServer {
3006 fn from(value: Result) -> Self {
3007 MessageFromServer::ResultFromServer(value.into())
3008 }
3009}
3010impl From<InitializeResult> for MessageFromServer {
3011 fn from(value: InitializeResult) -> Self {
3012 MessageFromServer::ResultFromServer(value.into())
3013 }
3014}
3015impl From<ListResourcesResult> for MessageFromServer {
3016 fn from(value: ListResourcesResult) -> Self {
3017 MessageFromServer::ResultFromServer(value.into())
3018 }
3019}
3020impl From<ListResourceTemplatesResult> for MessageFromServer {
3021 fn from(value: ListResourceTemplatesResult) -> Self {
3022 MessageFromServer::ResultFromServer(value.into())
3023 }
3024}
3025impl From<ReadResourceResult> for MessageFromServer {
3026 fn from(value: ReadResourceResult) -> Self {
3027 MessageFromServer::ResultFromServer(value.into())
3028 }
3029}
3030impl From<ListPromptsResult> for MessageFromServer {
3031 fn from(value: ListPromptsResult) -> Self {
3032 MessageFromServer::ResultFromServer(value.into())
3033 }
3034}
3035impl From<GetPromptResult> for MessageFromServer {
3036 fn from(value: GetPromptResult) -> Self {
3037 MessageFromServer::ResultFromServer(value.into())
3038 }
3039}
3040impl From<ListToolsResult> for MessageFromServer {
3041 fn from(value: ListToolsResult) -> Self {
3042 MessageFromServer::ResultFromServer(value.into())
3043 }
3044}
3045impl From<CallToolResult> for MessageFromServer {
3046 fn from(value: CallToolResult) -> Self {
3047 MessageFromServer::ResultFromServer(value.into())
3048 }
3049}
3050impl From<CompleteResult> for MessageFromServer {
3051 fn from(value: CompleteResult) -> Self {
3052 MessageFromServer::ResultFromServer(value.into())
3053 }
3054}
3055impl FromMessage<InitializeRequest> for ClientMessage {
3056 fn from_message(message: InitializeRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3057 let request_id =
3058 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3059 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3060 }
3061}
3062impl ToMessage<ClientMessage> for InitializeRequest {
3063 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3064 ClientMessage::from_message(self, request_id)
3065 }
3066}
3067impl FromMessage<PingRequest> for ClientMessage {
3068 fn from_message(message: PingRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3069 let request_id =
3070 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3071 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3072 }
3073}
3074impl ToMessage<ClientMessage> for PingRequest {
3075 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3076 ClientMessage::from_message(self, request_id)
3077 }
3078}
3079impl FromMessage<ListResourcesRequest> for ClientMessage {
3080 fn from_message(message: ListResourcesRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3081 let request_id =
3082 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3083 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3084 }
3085}
3086impl ToMessage<ClientMessage> for ListResourcesRequest {
3087 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3088 ClientMessage::from_message(self, request_id)
3089 }
3090}
3091impl FromMessage<ListResourceTemplatesRequest> for ClientMessage {
3092 fn from_message(
3093 message: ListResourceTemplatesRequest,
3094 request_id: Option<RequestId>,
3095 ) -> std::result::Result<Self, RpcError> {
3096 let request_id =
3097 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3098 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3099 }
3100}
3101impl ToMessage<ClientMessage> for ListResourceTemplatesRequest {
3102 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3103 ClientMessage::from_message(self, request_id)
3104 }
3105}
3106impl FromMessage<ReadResourceRequest> for ClientMessage {
3107 fn from_message(message: ReadResourceRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3108 let request_id =
3109 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3110 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3111 }
3112}
3113impl ToMessage<ClientMessage> for ReadResourceRequest {
3114 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3115 ClientMessage::from_message(self, request_id)
3116 }
3117}
3118impl FromMessage<SubscribeRequest> for ClientMessage {
3119 fn from_message(message: SubscribeRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3120 let request_id =
3121 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3122 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3123 }
3124}
3125impl ToMessage<ClientMessage> for SubscribeRequest {
3126 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3127 ClientMessage::from_message(self, request_id)
3128 }
3129}
3130impl FromMessage<UnsubscribeRequest> for ClientMessage {
3131 fn from_message(message: UnsubscribeRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3132 let request_id =
3133 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3134 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3135 }
3136}
3137impl ToMessage<ClientMessage> for UnsubscribeRequest {
3138 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3139 ClientMessage::from_message(self, request_id)
3140 }
3141}
3142impl FromMessage<ListPromptsRequest> for ClientMessage {
3143 fn from_message(message: ListPromptsRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3144 let request_id =
3145 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3146 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3147 }
3148}
3149impl ToMessage<ClientMessage> for ListPromptsRequest {
3150 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3151 ClientMessage::from_message(self, request_id)
3152 }
3153}
3154impl FromMessage<GetPromptRequest> for ClientMessage {
3155 fn from_message(message: GetPromptRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3156 let request_id =
3157 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3158 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3159 }
3160}
3161impl ToMessage<ClientMessage> for GetPromptRequest {
3162 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3163 ClientMessage::from_message(self, request_id)
3164 }
3165}
3166impl FromMessage<ListToolsRequest> for ClientMessage {
3167 fn from_message(message: ListToolsRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3168 let request_id =
3169 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3170 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3171 }
3172}
3173impl ToMessage<ClientMessage> for ListToolsRequest {
3174 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3175 ClientMessage::from_message(self, request_id)
3176 }
3177}
3178impl FromMessage<CallToolRequest> for ClientMessage {
3179 fn from_message(message: CallToolRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3180 let request_id =
3181 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3182 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3183 }
3184}
3185impl ToMessage<ClientMessage> for CallToolRequest {
3186 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3187 ClientMessage::from_message(self, request_id)
3188 }
3189}
3190impl FromMessage<SetLevelRequest> for ClientMessage {
3191 fn from_message(message: SetLevelRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3192 let request_id =
3193 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3194 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3195 }
3196}
3197impl ToMessage<ClientMessage> for SetLevelRequest {
3198 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3199 ClientMessage::from_message(self, request_id)
3200 }
3201}
3202impl FromMessage<CompleteRequest> for ClientMessage {
3203 fn from_message(message: CompleteRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3204 let request_id =
3205 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3206 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3207 }
3208}
3209impl ToMessage<ClientMessage> for CompleteRequest {
3210 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3211 ClientMessage::from_message(self, request_id)
3212 }
3213}
3214impl FromMessage<Result> for ClientMessage {
3215 fn from_message(message: Result, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3216 let request_id =
3217 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3218 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3219 request_id,
3220 message.into(),
3221 )))
3222 }
3223}
3224impl ToMessage<ClientMessage> for Result {
3225 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3226 ClientMessage::from_message(self, request_id)
3227 }
3228}
3229impl FromMessage<CreateMessageResult> for ClientMessage {
3230 fn from_message(message: CreateMessageResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3231 let request_id =
3232 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3233 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3234 request_id,
3235 message.into(),
3236 )))
3237 }
3238}
3239impl ToMessage<ClientMessage> for CreateMessageResult {
3240 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3241 ClientMessage::from_message(self, request_id)
3242 }
3243}
3244impl FromMessage<ListRootsResult> for ClientMessage {
3245 fn from_message(message: ListRootsResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3246 let request_id =
3247 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3248 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3249 request_id,
3250 message.into(),
3251 )))
3252 }
3253}
3254impl ToMessage<ClientMessage> for ListRootsResult {
3255 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3256 ClientMessage::from_message(self, request_id)
3257 }
3258}
3259impl FromMessage<ElicitResult> for ClientMessage {
3260 fn from_message(message: ElicitResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3261 let request_id =
3262 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3263 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3264 request_id,
3265 message.into(),
3266 )))
3267 }
3268}
3269impl ToMessage<ClientMessage> for ElicitResult {
3270 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3271 ClientMessage::from_message(self, request_id)
3272 }
3273}
3274impl FromMessage<CancelledNotification> for ClientMessage {
3275 fn from_message(message: CancelledNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3276 if request_id.is_some() {
3277 return Err(
3278 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3279 );
3280 }
3281 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
3282 }
3283}
3284impl ToMessage<ClientMessage> for CancelledNotification {
3285 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3286 ClientMessage::from_message(self, request_id)
3287 }
3288}
3289impl FromMessage<InitializedNotification> for ClientMessage {
3290 fn from_message(message: InitializedNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3291 if request_id.is_some() {
3292 return Err(
3293 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3294 );
3295 }
3296 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
3297 }
3298}
3299impl ToMessage<ClientMessage> for InitializedNotification {
3300 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3301 ClientMessage::from_message(self, request_id)
3302 }
3303}
3304impl FromMessage<ProgressNotification> for ClientMessage {
3305 fn from_message(message: ProgressNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3306 if request_id.is_some() {
3307 return Err(
3308 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3309 );
3310 }
3311 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
3312 }
3313}
3314impl ToMessage<ClientMessage> for ProgressNotification {
3315 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3316 ClientMessage::from_message(self, request_id)
3317 }
3318}
3319impl FromMessage<RootsListChangedNotification> for ClientMessage {
3320 fn from_message(
3321 message: RootsListChangedNotification,
3322 request_id: Option<RequestId>,
3323 ) -> std::result::Result<Self, RpcError> {
3324 if request_id.is_some() {
3325 return Err(
3326 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3327 );
3328 }
3329 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
3330 }
3331}
3332impl ToMessage<ClientMessage> for RootsListChangedNotification {
3333 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3334 ClientMessage::from_message(self, request_id)
3335 }
3336}
3337impl FromMessage<PingRequest> for ServerMessage {
3338 fn from_message(message: PingRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3339 let request_id =
3340 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3341 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3342 }
3343}
3344impl ToMessage<ServerMessage> for PingRequest {
3345 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3346 ServerMessage::from_message(self, request_id)
3347 }
3348}
3349impl FromMessage<CreateMessageRequest> for ServerMessage {
3350 fn from_message(message: CreateMessageRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3351 let request_id =
3352 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3353 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3354 }
3355}
3356impl ToMessage<ServerMessage> for CreateMessageRequest {
3357 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3358 ServerMessage::from_message(self, request_id)
3359 }
3360}
3361impl FromMessage<ListRootsRequest> for ServerMessage {
3362 fn from_message(message: ListRootsRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3363 let request_id =
3364 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3365 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3366 }
3367}
3368impl ToMessage<ServerMessage> for ListRootsRequest {
3369 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3370 ServerMessage::from_message(self, request_id)
3371 }
3372}
3373impl FromMessage<ElicitRequest> for ServerMessage {
3374 fn from_message(message: ElicitRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3375 let request_id =
3376 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3377 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3378 }
3379}
3380impl ToMessage<ServerMessage> for ElicitRequest {
3381 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3382 ServerMessage::from_message(self, request_id)
3383 }
3384}
3385impl FromMessage<Result> for ServerMessage {
3386 fn from_message(message: Result, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3387 let request_id =
3388 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3389 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3390 request_id,
3391 message.into(),
3392 )))
3393 }
3394}
3395impl ToMessage<ServerMessage> for Result {
3396 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3397 ServerMessage::from_message(self, request_id)
3398 }
3399}
3400impl FromMessage<InitializeResult> for ServerMessage {
3401 fn from_message(message: InitializeResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3402 let request_id =
3403 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3404 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3405 request_id,
3406 message.into(),
3407 )))
3408 }
3409}
3410impl ToMessage<ServerMessage> for InitializeResult {
3411 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3412 ServerMessage::from_message(self, request_id)
3413 }
3414}
3415impl FromMessage<ListResourcesResult> for ServerMessage {
3416 fn from_message(message: ListResourcesResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3417 let request_id =
3418 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3419 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3420 request_id,
3421 message.into(),
3422 )))
3423 }
3424}
3425impl ToMessage<ServerMessage> for ListResourcesResult {
3426 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3427 ServerMessage::from_message(self, request_id)
3428 }
3429}
3430impl FromMessage<ListResourceTemplatesResult> for ServerMessage {
3431 fn from_message(
3432 message: ListResourceTemplatesResult,
3433 request_id: Option<RequestId>,
3434 ) -> std::result::Result<Self, RpcError> {
3435 let request_id =
3436 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3437 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3438 request_id,
3439 message.into(),
3440 )))
3441 }
3442}
3443impl ToMessage<ServerMessage> for ListResourceTemplatesResult {
3444 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3445 ServerMessage::from_message(self, request_id)
3446 }
3447}
3448impl FromMessage<ReadResourceResult> for ServerMessage {
3449 fn from_message(message: ReadResourceResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3450 let request_id =
3451 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3452 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3453 request_id,
3454 message.into(),
3455 )))
3456 }
3457}
3458impl ToMessage<ServerMessage> for ReadResourceResult {
3459 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3460 ServerMessage::from_message(self, request_id)
3461 }
3462}
3463impl FromMessage<ListPromptsResult> for ServerMessage {
3464 fn from_message(message: ListPromptsResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3465 let request_id =
3466 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3467 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3468 request_id,
3469 message.into(),
3470 )))
3471 }
3472}
3473impl ToMessage<ServerMessage> for ListPromptsResult {
3474 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3475 ServerMessage::from_message(self, request_id)
3476 }
3477}
3478impl FromMessage<GetPromptResult> for ServerMessage {
3479 fn from_message(message: GetPromptResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3480 let request_id =
3481 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3482 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3483 request_id,
3484 message.into(),
3485 )))
3486 }
3487}
3488impl ToMessage<ServerMessage> for GetPromptResult {
3489 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3490 ServerMessage::from_message(self, request_id)
3491 }
3492}
3493impl FromMessage<ListToolsResult> for ServerMessage {
3494 fn from_message(message: ListToolsResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3495 let request_id =
3496 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3497 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3498 request_id,
3499 message.into(),
3500 )))
3501 }
3502}
3503impl ToMessage<ServerMessage> for ListToolsResult {
3504 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3505 ServerMessage::from_message(self, request_id)
3506 }
3507}
3508impl FromMessage<CallToolResult> for ServerMessage {
3509 fn from_message(message: CallToolResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3510 let request_id =
3511 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3512 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3513 request_id,
3514 message.into(),
3515 )))
3516 }
3517}
3518impl ToMessage<ServerMessage> for CallToolResult {
3519 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3520 ServerMessage::from_message(self, request_id)
3521 }
3522}
3523impl FromMessage<CompleteResult> for ServerMessage {
3524 fn from_message(message: CompleteResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3525 let request_id =
3526 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3527 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3528 request_id,
3529 message.into(),
3530 )))
3531 }
3532}
3533impl ToMessage<ServerMessage> for CompleteResult {
3534 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3535 ServerMessage::from_message(self, request_id)
3536 }
3537}
3538impl FromMessage<CancelledNotification> for ServerMessage {
3539 fn from_message(message: CancelledNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3540 if request_id.is_some() {
3541 return Err(
3542 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3543 );
3544 }
3545 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3546 }
3547}
3548impl ToMessage<ServerMessage> for CancelledNotification {
3549 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3550 ServerMessage::from_message(self, request_id)
3551 }
3552}
3553impl FromMessage<ProgressNotification> for ServerMessage {
3554 fn from_message(message: ProgressNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3555 if request_id.is_some() {
3556 return Err(
3557 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3558 );
3559 }
3560 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3561 }
3562}
3563impl ToMessage<ServerMessage> for ProgressNotification {
3564 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3565 ServerMessage::from_message(self, request_id)
3566 }
3567}
3568impl FromMessage<ResourceListChangedNotification> for ServerMessage {
3569 fn from_message(
3570 message: ResourceListChangedNotification,
3571 request_id: Option<RequestId>,
3572 ) -> std::result::Result<Self, RpcError> {
3573 if request_id.is_some() {
3574 return Err(
3575 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3576 );
3577 }
3578 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3579 }
3580}
3581impl ToMessage<ServerMessage> for ResourceListChangedNotification {
3582 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3583 ServerMessage::from_message(self, request_id)
3584 }
3585}
3586impl FromMessage<ResourceUpdatedNotification> for ServerMessage {
3587 fn from_message(
3588 message: ResourceUpdatedNotification,
3589 request_id: Option<RequestId>,
3590 ) -> std::result::Result<Self, RpcError> {
3591 if request_id.is_some() {
3592 return Err(
3593 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3594 );
3595 }
3596 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3597 }
3598}
3599impl ToMessage<ServerMessage> for ResourceUpdatedNotification {
3600 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3601 ServerMessage::from_message(self, request_id)
3602 }
3603}
3604impl FromMessage<PromptListChangedNotification> for ServerMessage {
3605 fn from_message(
3606 message: PromptListChangedNotification,
3607 request_id: Option<RequestId>,
3608 ) -> std::result::Result<Self, RpcError> {
3609 if request_id.is_some() {
3610 return Err(
3611 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3612 );
3613 }
3614 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3615 }
3616}
3617impl ToMessage<ServerMessage> for PromptListChangedNotification {
3618 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3619 ServerMessage::from_message(self, request_id)
3620 }
3621}
3622impl FromMessage<ToolListChangedNotification> for ServerMessage {
3623 fn from_message(
3624 message: ToolListChangedNotification,
3625 request_id: Option<RequestId>,
3626 ) -> std::result::Result<Self, RpcError> {
3627 if request_id.is_some() {
3628 return Err(
3629 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3630 );
3631 }
3632 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3633 }
3634}
3635impl ToMessage<ServerMessage> for ToolListChangedNotification {
3636 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3637 ServerMessage::from_message(self, request_id)
3638 }
3639}
3640impl FromMessage<LoggingMessageNotification> for ServerMessage {
3641 fn from_message(
3642 message: LoggingMessageNotification,
3643 request_id: Option<RequestId>,
3644 ) -> std::result::Result<Self, RpcError> {
3645 if request_id.is_some() {
3646 return Err(
3647 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3648 );
3649 }
3650 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
3651 }
3652}
3653impl ToMessage<ServerMessage> for LoggingMessageNotification {
3654 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3655 ServerMessage::from_message(self, request_id)
3656 }
3657}
3658impl TryFrom<RequestFromClient> for InitializeRequest {
3659 type Error = RpcError;
3660 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3661 let matched_type: ClientRequest = value.try_into()?;
3662 if let ClientRequest::InitializeRequest(result) = matched_type {
3663 Ok(result)
3664 } else {
3665 Err(RpcError::internal_error().with_message("Not a InitializeRequest".to_string()))
3666 }
3667 }
3668}
3669impl TryFrom<RequestFromClient> for PingRequest {
3670 type Error = RpcError;
3671 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3672 let matched_type: ClientRequest = value.try_into()?;
3673 if let ClientRequest::PingRequest(result) = matched_type {
3674 Ok(result)
3675 } else {
3676 Err(RpcError::internal_error().with_message("Not a PingRequest".to_string()))
3677 }
3678 }
3679}
3680impl TryFrom<RequestFromClient> for ListResourcesRequest {
3681 type Error = RpcError;
3682 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3683 let matched_type: ClientRequest = value.try_into()?;
3684 if let ClientRequest::ListResourcesRequest(result) = matched_type {
3685 Ok(result)
3686 } else {
3687 Err(RpcError::internal_error().with_message("Not a ListResourcesRequest".to_string()))
3688 }
3689 }
3690}
3691impl TryFrom<RequestFromClient> for ListResourceTemplatesRequest {
3692 type Error = RpcError;
3693 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3694 let matched_type: ClientRequest = value.try_into()?;
3695 if let ClientRequest::ListResourceTemplatesRequest(result) = matched_type {
3696 Ok(result)
3697 } else {
3698 Err(RpcError::internal_error().with_message("Not a ListResourceTemplatesRequest".to_string()))
3699 }
3700 }
3701}
3702impl TryFrom<RequestFromClient> for ReadResourceRequest {
3703 type Error = RpcError;
3704 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3705 let matched_type: ClientRequest = value.try_into()?;
3706 if let ClientRequest::ReadResourceRequest(result) = matched_type {
3707 Ok(result)
3708 } else {
3709 Err(RpcError::internal_error().with_message("Not a ReadResourceRequest".to_string()))
3710 }
3711 }
3712}
3713impl TryFrom<RequestFromClient> for SubscribeRequest {
3714 type Error = RpcError;
3715 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3716 let matched_type: ClientRequest = value.try_into()?;
3717 if let ClientRequest::SubscribeRequest(result) = matched_type {
3718 Ok(result)
3719 } else {
3720 Err(RpcError::internal_error().with_message("Not a SubscribeRequest".to_string()))
3721 }
3722 }
3723}
3724impl TryFrom<RequestFromClient> for UnsubscribeRequest {
3725 type Error = RpcError;
3726 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3727 let matched_type: ClientRequest = value.try_into()?;
3728 if let ClientRequest::UnsubscribeRequest(result) = matched_type {
3729 Ok(result)
3730 } else {
3731 Err(RpcError::internal_error().with_message("Not a UnsubscribeRequest".to_string()))
3732 }
3733 }
3734}
3735impl TryFrom<RequestFromClient> for ListPromptsRequest {
3736 type Error = RpcError;
3737 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3738 let matched_type: ClientRequest = value.try_into()?;
3739 if let ClientRequest::ListPromptsRequest(result) = matched_type {
3740 Ok(result)
3741 } else {
3742 Err(RpcError::internal_error().with_message("Not a ListPromptsRequest".to_string()))
3743 }
3744 }
3745}
3746impl TryFrom<RequestFromClient> for GetPromptRequest {
3747 type Error = RpcError;
3748 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3749 let matched_type: ClientRequest = value.try_into()?;
3750 if let ClientRequest::GetPromptRequest(result) = matched_type {
3751 Ok(result)
3752 } else {
3753 Err(RpcError::internal_error().with_message("Not a GetPromptRequest".to_string()))
3754 }
3755 }
3756}
3757impl TryFrom<RequestFromClient> for ListToolsRequest {
3758 type Error = RpcError;
3759 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3760 let matched_type: ClientRequest = value.try_into()?;
3761 if let ClientRequest::ListToolsRequest(result) = matched_type {
3762 Ok(result)
3763 } else {
3764 Err(RpcError::internal_error().with_message("Not a ListToolsRequest".to_string()))
3765 }
3766 }
3767}
3768impl TryFrom<RequestFromClient> for CallToolRequest {
3769 type Error = RpcError;
3770 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3771 let matched_type: ClientRequest = value.try_into()?;
3772 if let ClientRequest::CallToolRequest(result) = matched_type {
3773 Ok(result)
3774 } else {
3775 Err(RpcError::internal_error().with_message("Not a CallToolRequest".to_string()))
3776 }
3777 }
3778}
3779impl TryFrom<RequestFromClient> for SetLevelRequest {
3780 type Error = RpcError;
3781 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3782 let matched_type: ClientRequest = value.try_into()?;
3783 if let ClientRequest::SetLevelRequest(result) = matched_type {
3784 Ok(result)
3785 } else {
3786 Err(RpcError::internal_error().with_message("Not a SetLevelRequest".to_string()))
3787 }
3788 }
3789}
3790impl TryFrom<RequestFromClient> for CompleteRequest {
3791 type Error = RpcError;
3792 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
3793 let matched_type: ClientRequest = value.try_into()?;
3794 if let ClientRequest::CompleteRequest(result) = matched_type {
3795 Ok(result)
3796 } else {
3797 Err(RpcError::internal_error().with_message("Not a CompleteRequest".to_string()))
3798 }
3799 }
3800}
3801impl TryFrom<ResultFromClient> for Result {
3802 type Error = RpcError;
3803 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3804 let matched_type: ClientResult = value.try_into()?;
3805 if let ClientResult::Result(result) = matched_type {
3806 Ok(result)
3807 } else {
3808 Err(RpcError::internal_error().with_message("Not a Result".to_string()))
3809 }
3810 }
3811}
3812impl TryFrom<ResultFromClient> for CreateMessageResult {
3813 type Error = RpcError;
3814 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3815 let matched_type: ClientResult = value.try_into()?;
3816 if let ClientResult::CreateMessageResult(result) = matched_type {
3817 Ok(result)
3818 } else {
3819 Err(RpcError::internal_error().with_message("Not a CreateMessageResult".to_string()))
3820 }
3821 }
3822}
3823impl TryFrom<ResultFromClient> for ListRootsResult {
3824 type Error = RpcError;
3825 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3826 let matched_type: ClientResult = value.try_into()?;
3827 if let ClientResult::ListRootsResult(result) = matched_type {
3828 Ok(result)
3829 } else {
3830 Err(RpcError::internal_error().with_message("Not a ListRootsResult".to_string()))
3831 }
3832 }
3833}
3834impl TryFrom<ResultFromClient> for ElicitResult {
3835 type Error = RpcError;
3836 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3837 let matched_type: ClientResult = value.try_into()?;
3838 if let ClientResult::ElicitResult(result) = matched_type {
3839 Ok(result)
3840 } else {
3841 Err(RpcError::internal_error().with_message("Not a ElicitResult".to_string()))
3842 }
3843 }
3844}
3845impl TryFrom<NotificationFromClient> for CancelledNotification {
3846 type Error = RpcError;
3847 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
3848 let matched_type: ClientNotification = value.try_into()?;
3849 if let ClientNotification::CancelledNotification(result) = matched_type {
3850 Ok(result)
3851 } else {
3852 Err(RpcError::internal_error().with_message("Not a CancelledNotification".to_string()))
3853 }
3854 }
3855}
3856impl TryFrom<NotificationFromClient> for InitializedNotification {
3857 type Error = RpcError;
3858 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
3859 let matched_type: ClientNotification = value.try_into()?;
3860 if let ClientNotification::InitializedNotification(result) = matched_type {
3861 Ok(result)
3862 } else {
3863 Err(RpcError::internal_error().with_message("Not a InitializedNotification".to_string()))
3864 }
3865 }
3866}
3867impl TryFrom<NotificationFromClient> for ProgressNotification {
3868 type Error = RpcError;
3869 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
3870 let matched_type: ClientNotification = value.try_into()?;
3871 if let ClientNotification::ProgressNotification(result) = matched_type {
3872 Ok(result)
3873 } else {
3874 Err(RpcError::internal_error().with_message("Not a ProgressNotification".to_string()))
3875 }
3876 }
3877}
3878impl TryFrom<NotificationFromClient> for RootsListChangedNotification {
3879 type Error = RpcError;
3880 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
3881 let matched_type: ClientNotification = value.try_into()?;
3882 if let ClientNotification::RootsListChangedNotification(result) = matched_type {
3883 Ok(result)
3884 } else {
3885 Err(RpcError::internal_error().with_message("Not a RootsListChangedNotification".to_string()))
3886 }
3887 }
3888}
3889impl TryFrom<RequestFromServer> for PingRequest {
3890 type Error = RpcError;
3891 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
3892 let matched_type: ServerRequest = value.try_into()?;
3893 if let ServerRequest::PingRequest(result) = matched_type {
3894 Ok(result)
3895 } else {
3896 Err(RpcError::internal_error().with_message("Not a PingRequest".to_string()))
3897 }
3898 }
3899}
3900impl TryFrom<RequestFromServer> for CreateMessageRequest {
3901 type Error = RpcError;
3902 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
3903 let matched_type: ServerRequest = value.try_into()?;
3904 if let ServerRequest::CreateMessageRequest(result) = matched_type {
3905 Ok(result)
3906 } else {
3907 Err(RpcError::internal_error().with_message("Not a CreateMessageRequest".to_string()))
3908 }
3909 }
3910}
3911impl TryFrom<RequestFromServer> for ListRootsRequest {
3912 type Error = RpcError;
3913 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
3914 let matched_type: ServerRequest = value.try_into()?;
3915 if let ServerRequest::ListRootsRequest(result) = matched_type {
3916 Ok(result)
3917 } else {
3918 Err(RpcError::internal_error().with_message("Not a ListRootsRequest".to_string()))
3919 }
3920 }
3921}
3922impl TryFrom<RequestFromServer> for ElicitRequest {
3923 type Error = RpcError;
3924 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
3925 let matched_type: ServerRequest = value.try_into()?;
3926 if let ServerRequest::ElicitRequest(result) = matched_type {
3927 Ok(result)
3928 } else {
3929 Err(RpcError::internal_error().with_message("Not a ElicitRequest".to_string()))
3930 }
3931 }
3932}
3933impl TryFrom<ResultFromServer> for Result {
3934 type Error = RpcError;
3935 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3936 let matched_type: ServerResult = value.try_into()?;
3937 if let ServerResult::Result(result) = matched_type {
3938 Ok(result)
3939 } else {
3940 Err(RpcError::internal_error().with_message("Not a Result".to_string()))
3941 }
3942 }
3943}
3944impl TryFrom<ResultFromServer> for InitializeResult {
3945 type Error = RpcError;
3946 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3947 let matched_type: ServerResult = value.try_into()?;
3948 if let ServerResult::InitializeResult(result) = matched_type {
3949 Ok(result)
3950 } else {
3951 Err(RpcError::internal_error().with_message("Not a InitializeResult".to_string()))
3952 }
3953 }
3954}
3955impl TryFrom<ResultFromServer> for ListResourcesResult {
3956 type Error = RpcError;
3957 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3958 let matched_type: ServerResult = value.try_into()?;
3959 if let ServerResult::ListResourcesResult(result) = matched_type {
3960 Ok(result)
3961 } else {
3962 Err(RpcError::internal_error().with_message("Not a ListResourcesResult".to_string()))
3963 }
3964 }
3965}
3966impl TryFrom<ResultFromServer> for ListResourceTemplatesResult {
3967 type Error = RpcError;
3968 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3969 let matched_type: ServerResult = value.try_into()?;
3970 if let ServerResult::ListResourceTemplatesResult(result) = matched_type {
3971 Ok(result)
3972 } else {
3973 Err(RpcError::internal_error().with_message("Not a ListResourceTemplatesResult".to_string()))
3974 }
3975 }
3976}
3977impl TryFrom<ResultFromServer> for ReadResourceResult {
3978 type Error = RpcError;
3979 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3980 let matched_type: ServerResult = value.try_into()?;
3981 if let ServerResult::ReadResourceResult(result) = matched_type {
3982 Ok(result)
3983 } else {
3984 Err(RpcError::internal_error().with_message("Not a ReadResourceResult".to_string()))
3985 }
3986 }
3987}
3988impl TryFrom<ResultFromServer> for ListPromptsResult {
3989 type Error = RpcError;
3990 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3991 let matched_type: ServerResult = value.try_into()?;
3992 if let ServerResult::ListPromptsResult(result) = matched_type {
3993 Ok(result)
3994 } else {
3995 Err(RpcError::internal_error().with_message("Not a ListPromptsResult".to_string()))
3996 }
3997 }
3998}
3999impl TryFrom<ResultFromServer> for GetPromptResult {
4000 type Error = RpcError;
4001 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4002 let matched_type: ServerResult = value.try_into()?;
4003 if let ServerResult::GetPromptResult(result) = matched_type {
4004 Ok(result)
4005 } else {
4006 Err(RpcError::internal_error().with_message("Not a GetPromptResult".to_string()))
4007 }
4008 }
4009}
4010impl TryFrom<ResultFromServer> for ListToolsResult {
4011 type Error = RpcError;
4012 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4013 let matched_type: ServerResult = value.try_into()?;
4014 if let ServerResult::ListToolsResult(result) = matched_type {
4015 Ok(result)
4016 } else {
4017 Err(RpcError::internal_error().with_message("Not a ListToolsResult".to_string()))
4018 }
4019 }
4020}
4021impl TryFrom<ResultFromServer> for CallToolResult {
4022 type Error = RpcError;
4023 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4024 let matched_type: ServerResult = value.try_into()?;
4025 if let ServerResult::CallToolResult(result) = matched_type {
4026 Ok(result)
4027 } else {
4028 Err(RpcError::internal_error().with_message("Not a CallToolResult".to_string()))
4029 }
4030 }
4031}
4032impl TryFrom<ResultFromServer> for CompleteResult {
4033 type Error = RpcError;
4034 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4035 let matched_type: ServerResult = value.try_into()?;
4036 if let ServerResult::CompleteResult(result) = matched_type {
4037 Ok(result)
4038 } else {
4039 Err(RpcError::internal_error().with_message("Not a CompleteResult".to_string()))
4040 }
4041 }
4042}
4043impl TryFrom<NotificationFromServer> for CancelledNotification {
4044 type Error = RpcError;
4045 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4046 let matched_type: ServerNotification = value.try_into()?;
4047 if let ServerNotification::CancelledNotification(result) = matched_type {
4048 Ok(result)
4049 } else {
4050 Err(RpcError::internal_error().with_message("Not a CancelledNotification".to_string()))
4051 }
4052 }
4053}
4054impl TryFrom<NotificationFromServer> for ProgressNotification {
4055 type Error = RpcError;
4056 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4057 let matched_type: ServerNotification = value.try_into()?;
4058 if let ServerNotification::ProgressNotification(result) = matched_type {
4059 Ok(result)
4060 } else {
4061 Err(RpcError::internal_error().with_message("Not a ProgressNotification".to_string()))
4062 }
4063 }
4064}
4065impl TryFrom<NotificationFromServer> for ResourceListChangedNotification {
4066 type Error = RpcError;
4067 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4068 let matched_type: ServerNotification = value.try_into()?;
4069 if let ServerNotification::ResourceListChangedNotification(result) = matched_type {
4070 Ok(result)
4071 } else {
4072 Err(RpcError::internal_error().with_message("Not a ResourceListChangedNotification".to_string()))
4073 }
4074 }
4075}
4076impl TryFrom<NotificationFromServer> for ResourceUpdatedNotification {
4077 type Error = RpcError;
4078 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4079 let matched_type: ServerNotification = value.try_into()?;
4080 if let ServerNotification::ResourceUpdatedNotification(result) = matched_type {
4081 Ok(result)
4082 } else {
4083 Err(RpcError::internal_error().with_message("Not a ResourceUpdatedNotification".to_string()))
4084 }
4085 }
4086}
4087impl TryFrom<NotificationFromServer> for PromptListChangedNotification {
4088 type Error = RpcError;
4089 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4090 let matched_type: ServerNotification = value.try_into()?;
4091 if let ServerNotification::PromptListChangedNotification(result) = matched_type {
4092 Ok(result)
4093 } else {
4094 Err(RpcError::internal_error().with_message("Not a PromptListChangedNotification".to_string()))
4095 }
4096 }
4097}
4098impl TryFrom<NotificationFromServer> for ToolListChangedNotification {
4099 type Error = RpcError;
4100 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4101 let matched_type: ServerNotification = value.try_into()?;
4102 if let ServerNotification::ToolListChangedNotification(result) = matched_type {
4103 Ok(result)
4104 } else {
4105 Err(RpcError::internal_error().with_message("Not a ToolListChangedNotification".to_string()))
4106 }
4107 }
4108}
4109impl TryFrom<NotificationFromServer> for LoggingMessageNotification {
4110 type Error = RpcError;
4111 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4112 let matched_type: ServerNotification = value.try_into()?;
4113 if let ServerNotification::LoggingMessageNotification(result) = matched_type {
4114 Ok(result)
4115 } else {
4116 Err(RpcError::internal_error().with_message("Not a LoggingMessageNotification".to_string()))
4117 }
4118 }
4119}
4120impl ContentBlock {
4121 pub fn text_content(text: ::std::string::String) -> Self {
4123 TextContent::new(text, None, None).into()
4124 }
4125 pub fn image_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
4127 ImageContent::new(data, mime_type, None, None).into()
4128 }
4129 pub fn audio_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
4131 AudioContent::new(data, mime_type, None, None).into()
4132 }
4133 pub fn resource_link(value: ResourceLink) -> Self {
4135 value.into()
4136 }
4137 pub fn embedded_resource(resource: EmbeddedResourceResource) -> Self {
4139 EmbeddedResource::new(resource, None, None).into()
4140 }
4141 pub fn content_type(&self) -> &str {
4143 match self {
4144 ContentBlock::TextContent(text_content) => text_content.type_(),
4145 ContentBlock::ImageContent(image_content) => image_content.type_(),
4146 ContentBlock::AudioContent(audio_content) => audio_content.type_(),
4147 ContentBlock::ResourceLink(resource_link) => resource_link.type_(),
4148 ContentBlock::EmbeddedResource(embedded_resource) => embedded_resource.type_(),
4149 }
4150 }
4151 pub fn as_text_content(&self) -> std::result::Result<&TextContent, RpcError> {
4153 match &self {
4154 ContentBlock::TextContent(text_content) => Ok(text_content),
4155 _ => Err(RpcError::internal_error().with_message(format!(
4156 "Invalid conversion, \"{}\" is not a {}",
4157 self.content_type(),
4158 "TextContent"
4159 ))),
4160 }
4161 }
4162 pub fn as_image_content(&self) -> std::result::Result<&ImageContent, RpcError> {
4164 match &self {
4165 ContentBlock::ImageContent(image_content) => Ok(image_content),
4166 _ => Err(RpcError::internal_error().with_message(format!(
4167 "Invalid conversion, \"{}\" is not a {}",
4168 self.content_type(),
4169 "ImageContent"
4170 ))),
4171 }
4172 }
4173 pub fn as_audio_content(&self) -> std::result::Result<&AudioContent, RpcError> {
4175 match &self {
4176 ContentBlock::AudioContent(audio_content) => Ok(audio_content),
4177 _ => Err(RpcError::internal_error().with_message(format!(
4178 "Invalid conversion, \"{}\" is not a {}",
4179 self.content_type(),
4180 "AudioContent"
4181 ))),
4182 }
4183 }
4184 pub fn as_resource_link(&self) -> std::result::Result<&ResourceLink, RpcError> {
4186 match &self {
4187 ContentBlock::ResourceLink(resource_link) => Ok(resource_link),
4188 _ => Err(RpcError::internal_error().with_message(format!(
4189 "Invalid conversion, \"{}\" is not a {}",
4190 self.content_type(),
4191 "ResourceLink"
4192 ))),
4193 }
4194 }
4195 pub fn as_embedded_resource(&self) -> std::result::Result<&EmbeddedResource, RpcError> {
4197 match &self {
4198 ContentBlock::EmbeddedResource(embedded_resource) => Ok(embedded_resource),
4199 _ => Err(RpcError::internal_error().with_message(format!(
4200 "Invalid conversion, \"{}\" is not a {}",
4201 self.content_type(),
4202 "EmbeddedResource"
4203 ))),
4204 }
4205 }
4206}
4207impl CallToolResult {
4208 pub fn text_content(content: Vec<TextContent>) -> Self {
4209 Self {
4210 content: content.into_iter().map(Into::into).collect(),
4211 is_error: None,
4212 meta: None,
4213 structured_content: None,
4214 }
4215 }
4216 pub fn image_content(content: Vec<ImageContent>) -> Self {
4217 Self {
4218 content: content.into_iter().map(Into::into).collect(),
4219 is_error: None,
4220 meta: None,
4221 structured_content: None,
4222 }
4223 }
4224 pub fn audio_content(content: Vec<AudioContent>) -> Self {
4225 Self {
4226 content: content.into_iter().map(Into::into).collect(),
4227 is_error: None,
4228 meta: None,
4229 structured_content: None,
4230 }
4231 }
4232 pub fn resource_link(content: Vec<ResourceLink>) -> Self {
4233 Self {
4234 content: content.into_iter().map(Into::into).collect(),
4235 is_error: None,
4236 meta: None,
4237 structured_content: None,
4238 }
4239 }
4240 pub fn embedded_resource(content: Vec<EmbeddedResource>) -> Self {
4241 Self {
4242 content: content.into_iter().map(Into::into).collect(),
4243 is_error: None,
4244 meta: None,
4245 structured_content: None,
4246 }
4247 }
4248 pub fn with_error(error: CallToolError) -> Self {
4250 Self {
4251 content: vec![ContentBlock::TextContent(TextContent::new(error.to_string(), None, None))],
4252 is_error: Some(true),
4253 meta: None,
4254 structured_content: None,
4255 }
4256 }
4257 pub fn with_meta(mut self, meta: Option<serde_json::Map<String, Value>>) -> Self {
4259 self.meta = meta;
4260 self
4261 }
4262 pub fn with_structured_content(
4264 mut self,
4265 structured_content: ::serde_json::Map<::std::string::String, ::serde_json::Value>,
4266 ) -> Self {
4267 self.structured_content = Some(structured_content);
4268 self
4269 }
4270}
4271#[cfg(test)]
4273mod tests {
4274 use super::*;
4275 use serde_json::json;
4276
4277 #[test]
4278 fn test_detect_message_type() {
4279 let message = ClientJsonrpcRequest::new(RequestId::Integer(0), PingRequest::new(None).into());
4281 let result = detect_message_type(&json!(message));
4282 assert!(matches!(result, MessageTypes::Request));
4283
4284 let result = detect_message_type(&json!({
4287 "id":0,
4288 "method":"add_numbers",
4289 "params":{},
4290 "jsonrpc":"2.0"
4291 }));
4292 assert!(matches!(result, MessageTypes::Request));
4293
4294 let message = ClientJsonrpcNotification::new(RootsListChangedNotification::new(None).into());
4296 let result = detect_message_type(&json!(message));
4297 assert!(matches!(result, MessageTypes::Notification));
4298
4299 let result = detect_message_type(&json!({
4301 "method":"notifications/email_sent",
4302 "jsonrpc":"2.0"
4303 }));
4304 assert!(matches!(result, MessageTypes::Notification));
4305
4306 let message = ClientJsonrpcResponse::new(
4308 RequestId::Integer(0),
4309 ListRootsResult {
4310 meta: None,
4311 roots: vec![],
4312 }
4313 .into(),
4314 );
4315 let result = detect_message_type(&json!(message));
4316 assert!(matches!(result, MessageTypes::Response));
4317
4318 let result = detect_message_type(&json!({
4321 "id":1,
4322 "jsonrpc":"2.0",
4323 "result":"{}",
4324 }));
4325 assert!(matches!(result, MessageTypes::Response));
4326
4327 let message = JsonrpcError::create(
4329 RequestId::Integer(0),
4330 RpcErrorCodes::INVALID_PARAMS,
4331 "Invalid params!".to_string(),
4332 None,
4333 );
4334 let result = detect_message_type(&json!(message));
4335 assert!(matches!(result, MessageTypes::Error));
4336
4337 let result = detect_message_type(&json!({}));
4339 assert!(matches!(result, MessageTypes::Request));
4340 }
4341}