1use crate::generated_schema::*;
2
3use serde::ser::SerializeStruct;
4use serde_json::{json, Value};
5use std::hash::{Hash, Hasher};
6use std::result;
7use std::{fmt::Display, str::FromStr};
8
9#[derive(Debug, PartialEq)]
10pub enum MessageTypes {
11 Request,
12 Response,
13 Notification,
14 Error,
15}
16impl Display for MessageTypes {
19 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 write!(
22 f,
23 "{}",
24 match self {
26 MessageTypes::Request => "Request",
27 MessageTypes::Response => "Response",
28 MessageTypes::Notification => "Notification",
29 MessageTypes::Error => "Error",
30 }
31 )
32 }
33}
34
35#[allow(dead_code)]
38fn detect_message_type(value: &serde_json::Value) -> MessageTypes {
39 let id_field = value.get("id");
40
41 if id_field.is_some() && value.get("error").is_some() {
42 return MessageTypes::Error;
43 }
44
45 let method_field = value.get("method");
46 let result_field = value.get("result");
47
48 if id_field.is_some() {
49 if result_field.is_some() && method_field.is_none() {
50 return MessageTypes::Response;
51 } else if method_field.is_some() {
52 return MessageTypes::Request;
53 }
54 } else if method_field.is_some() {
55 return MessageTypes::Notification;
56 }
57
58 MessageTypes::Request
59}
60
61pub trait RpcMessage: McpMessage {
64 fn request_id(&self) -> Option<&RequestId>;
65 fn jsonrpc(&self) -> &str;
66}
67
68pub trait McpMessage {
69 fn is_response(&self) -> bool;
70 fn is_request(&self) -> bool;
71 fn is_notification(&self) -> bool;
72 fn is_error(&self) -> bool;
73 fn message_type(&self) -> MessageTypes;
74}
75
76pub trait FromMessage<T>
82where
83 Self: Sized,
84{
85 fn from_message(message: T, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError>;
86}
87
88pub trait ToMessage<T>
89where
90 T: FromMessage<Self>,
91 Self: Sized,
92{
93 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<T, RpcError>;
94}
95
96impl PartialEq for RequestId {
102 fn eq(&self, other: &Self) -> bool {
103 match (self, other) {
104 (RequestId::String(a), RequestId::String(b)) => a == b,
105 (RequestId::Integer(a), RequestId::Integer(b)) => a == b,
106 _ => false, }
108 }
109}
110
111impl PartialEq<RequestId> for &RequestId {
112 fn eq(&self, other: &RequestId) -> bool {
113 (*self).eq(other)
114 }
115}
116
117impl Eq for RequestId {}
118
119impl Hash for RequestId {
121 fn hash<H: Hasher>(&self, state: &mut H) {
122 match self {
123 RequestId::String(s) => {
124 0u8.hash(state); s.hash(state);
126 }
127 RequestId::Integer(i) => {
128 1u8.hash(state); i.hash(state);
130 }
131 }
132 }
133}
134
135#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
142#[serde(untagged)]
143pub enum ClientMessage {
144 Request(ClientJsonrpcRequest),
145 Notification(ClientJsonrpcNotification),
146 Response(ClientJsonrpcResponse),
147 Error(JsonrpcErrorResponse),
148}
149
150impl ClientMessage {
151 pub fn as_response(self) -> std::result::Result<ClientJsonrpcResponse, RpcError> {
161 if let Self::Response(response) = self {
162 Ok(response)
163 } else {
164 Err(RpcError::internal_error().with_message(format!(
165 "Invalid message type, expected: \"{}\" received\"{}\"",
166 MessageTypes::Response,
167 self.message_type()
168 )))
169 }
170 }
171
172 pub fn as_request(self) -> std::result::Result<ClientJsonrpcRequest, RpcError> {
182 if let Self::Request(request) = self {
183 Ok(request)
184 } else {
185 Err(RpcError::internal_error().with_message(format!(
186 "Invalid message type, expected: \"{}\" received\"{}\"",
187 MessageTypes::Request,
188 self.message_type()
189 )))
190 }
191 }
192
193 pub fn as_notification(self) -> std::result::Result<ClientJsonrpcNotification, RpcError> {
203 if let Self::Notification(notification) = self {
204 Ok(notification)
205 } else {
206 Err(RpcError::internal_error().with_message(format!(
207 "Invalid message type, expected: \"{}\" received\"{}\"",
208 MessageTypes::Notification,
209 self.message_type()
210 )))
211 }
212 }
213
214 pub fn as_error(self) -> std::result::Result<JsonrpcErrorResponse, RpcError> {
224 if let Self::Error(error) = self {
225 Ok(error)
226 } else {
227 Err(RpcError::internal_error().with_message(format!(
228 "Invalid message type, expected: \"{}\" received\"{}\"",
229 MessageTypes::Error,
230 self.message_type()
231 )))
232 }
233 }
234
235 pub fn is_initialize_request(&self) -> bool {
237 matches!(self, Self::Request(request) if request.request.is_initialize_request())
238 }
239
240 pub fn is_initialized_notification(&self) -> bool {
242 matches!(self, Self::Notification(notofication) if notofication.notification.is_initialized_notification())
243 }
244}
245
246impl From<ClientJsonrpcNotification> for ClientMessage {
247 fn from(value: ClientJsonrpcNotification) -> Self {
248 Self::Notification(value)
249 }
250}
251
252impl From<ClientJsonrpcRequest> for ClientMessage {
253 fn from(value: ClientJsonrpcRequest) -> Self {
254 Self::Request(value)
255 }
256}
257
258impl From<ClientJsonrpcResponse> for ClientMessage {
259 fn from(value: ClientJsonrpcResponse) -> Self {
260 Self::Response(value)
261 }
262}
263
264impl RpcMessage for ClientMessage {
265 fn request_id(&self) -> Option<&RequestId> {
267 match self {
268 ClientMessage::Request(client_jsonrpc_request) => Some(&client_jsonrpc_request.id),
270 ClientMessage::Notification(_) => None,
272 ClientMessage::Response(client_jsonrpc_response) => Some(&client_jsonrpc_response.id),
274 ClientMessage::Error(jsonrpc_error) => jsonrpc_error.id.as_ref(),
276 }
277 }
278
279 fn jsonrpc(&self) -> &str {
280 match self {
281 ClientMessage::Request(client_jsonrpc_request) => client_jsonrpc_request.jsonrpc(),
282 ClientMessage::Notification(notification) => notification.jsonrpc(),
283 ClientMessage::Response(client_jsonrpc_response) => client_jsonrpc_response.jsonrpc(),
284 ClientMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
285 }
286 }
287}
288
289impl McpMessage for ClientMessage {
291 fn is_response(&self) -> bool {
293 matches!(self, ClientMessage::Response(_))
294 }
295
296 fn is_request(&self) -> bool {
298 matches!(self, ClientMessage::Request(_))
299 }
300
301 fn is_notification(&self) -> bool {
303 matches!(self, ClientMessage::Notification(_))
304 }
305
306 fn is_error(&self) -> bool {
308 matches!(self, ClientMessage::Error(_))
309 }
310
311 fn message_type(&self) -> MessageTypes {
313 match self {
314 ClientMessage::Request(_) => MessageTypes::Request,
315 ClientMessage::Notification(_) => MessageTypes::Notification,
316 ClientMessage::Response(_) => MessageTypes::Response,
317 ClientMessage::Error(_) => MessageTypes::Error,
318 }
319 }
320}
321
322#[derive(Clone, Debug)]
328pub struct ClientJsonrpcRequest {
329 pub id: RequestId,
330 jsonrpc: ::std::string::String,
331 pub method: String,
332 pub request: RequestFromClient,
333}
334
335impl ClientJsonrpcRequest {
336 pub fn new(id: RequestId, request: RequestFromClient) -> Self {
337 let method = request.method().to_string();
338 Self {
339 id,
340 jsonrpc: JSONRPC_VERSION.to_string(),
341 method,
342 request,
343 }
344 }
345 pub fn jsonrpc(&self) -> &::std::string::String {
346 &self.jsonrpc
347 }
348}
349
350impl Display for ClientJsonrpcRequest {
352 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
353 write!(
354 f,
355 "{}",
356 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
357 )
358 }
359}
360
361impl FromStr for ClientJsonrpcRequest {
362 type Err = RpcError;
363
364 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
386 serde_json::from_str(s)
387 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
388 }
389}
390
391#[allow(clippy::large_enum_variant)]
398#[derive(::serde::Serialize, Clone, Debug)]
399#[serde(untagged)]
400pub enum RequestFromClient {
401 ClientRequest(ClientRequest),
402 CustomRequest(serde_json::Value),
403}
404
405impl TryFrom<RequestFromClient> for ClientRequest {
406 type Error = RpcError;
407 fn try_from(value: RequestFromClient) -> result::Result<Self, Self::Error> {
408 if let RequestFromClient::ClientRequest(client_request) = value {
409 Ok(client_request)
410 } else {
411 Err(RpcError::internal_error().with_message("Not a ClientRequest".to_string()))
412 }
413 }
414}
415
416impl RequestFromClient {
417 pub fn method(&self) -> &str {
418 match self {
419 RequestFromClient::ClientRequest(request) => request.method(),
420 RequestFromClient::CustomRequest(request) => request["method"].as_str().unwrap(),
421 }
422 }
423 pub fn is_initialize_request(&self) -> bool {
425 matches!(self, RequestFromClient::ClientRequest(ClientRequest::InitializeRequest(_)))
426 }
427}
428
429impl From<ClientRequest> for RequestFromClient {
430 fn from(value: ClientRequest) -> Self {
431 Self::ClientRequest(value)
432 }
433}
434
435impl From<serde_json::Value> for RequestFromClient {
436 fn from(value: serde_json::Value) -> Self {
437 Self::CustomRequest(value)
438 }
439}
440
441impl<'de> serde::Deserialize<'de> for RequestFromClient {
442 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
443 where
444 D: serde::Deserializer<'de>,
445 {
446 let raw_value = Value::deserialize(deserializer)?;
447
448 let client_result = ClientRequest::deserialize(&raw_value);
449
450 match client_result {
451 Ok(client_request) => Ok(Self::ClientRequest(client_request)),
452 Err(_) => Ok(Self::CustomRequest(raw_value)),
453 }
454 }
455}
456
457#[derive(Clone, Debug)]
463pub struct ClientJsonrpcNotification {
464 jsonrpc: ::std::string::String,
465 pub method: ::std::string::String,
466 pub notification: NotificationFromClient,
467}
468
469impl ClientJsonrpcNotification {
470 pub fn new(notification: NotificationFromClient) -> Self {
471 let method = notification.method().to_string();
472 Self {
473 jsonrpc: JSONRPC_VERSION.to_string(),
474 method,
475 notification,
476 }
477 }
478 pub fn jsonrpc(&self) -> &::std::string::String {
479 &self.jsonrpc
480 }
481}
482
483impl Display for ClientJsonrpcNotification {
485 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
486 write!(
487 f,
488 "{}",
489 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
490 )
491 }
492}
493
494impl FromStr for ClientJsonrpcNotification {
495 type Err = RpcError;
496
497 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
498 serde_json::from_str(s)
499 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
500 }
501}
502
503#[derive(::serde::Serialize, Clone, Debug)]
510#[serde(untagged)]
511pub enum NotificationFromClient {
512 ClientNotification(ClientNotification),
513 CustomNotification(serde_json::Value),
514}
515
516impl TryFrom<NotificationFromClient> for ClientNotification {
517 type Error = RpcError;
518 fn try_from(value: NotificationFromClient) -> result::Result<Self, Self::Error> {
519 if let NotificationFromClient::ClientNotification(client_notification) = value {
520 Ok(client_notification)
521 } else {
522 Err(RpcError::internal_error().with_message("Not a ClientNotification".to_string()))
523 }
524 }
525}
526
527impl NotificationFromClient {
528 pub fn is_initialized_notification(&self) -> bool {
530 matches!(
531 self,
532 NotificationFromClient::ClientNotification(ClientNotification::InitializedNotification(_))
533 )
534 }
535
536 fn method(&self) -> &str {
537 match self {
538 NotificationFromClient::ClientNotification(notification) => notification.method(),
539 NotificationFromClient::CustomNotification(notification) => notification["method"].as_str().unwrap(),
540 }
541 }
542}
543
544impl<'de> serde::Deserialize<'de> for NotificationFromClient {
545 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
546 where
547 D: serde::Deserializer<'de>,
548 {
549 let raw_value = Value::deserialize(deserializer)?;
550
551 let result = ClientNotification::deserialize(&raw_value);
552
553 match result {
554 Ok(client_notification) => Ok(Self::ClientNotification(client_notification)),
555 Err(_) => Ok(Self::CustomNotification(raw_value)),
556 }
557 }
558}
559
560#[derive(Clone, Debug)]
566pub struct ClientJsonrpcResponse {
567 pub id: RequestId,
568 jsonrpc: ::std::string::String,
569 pub result: ResultFromClient,
570}
571
572impl ClientJsonrpcResponse {
573 pub fn new(id: RequestId, result: ResultFromClient) -> Self {
574 Self {
575 id,
576 jsonrpc: JSONRPC_VERSION.to_string(),
577 result,
578 }
579 }
580 pub fn jsonrpc(&self) -> &::std::string::String {
581 &self.jsonrpc
582 }
583}
584
585impl Display for ClientJsonrpcResponse {
587 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
588 write!(
589 f,
590 "{}",
591 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
592 )
593 }
594}
595
596impl FromStr for ClientJsonrpcResponse {
597 type Err = RpcError;
598
599 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
600 serde_json::from_str(s)
601 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
602 }
603}
604#[allow(clippy::large_enum_variant)]
611#[derive(::serde::Serialize, Clone, Debug)]
612#[serde(untagged)]
613pub enum ResultFromClient {
614 ClientResult(ClientResult),
615 CustomResult(serde_json::Value),
617}
618
619impl TryFrom<ResultFromClient> for ClientResult {
620 type Error = RpcError;
621 fn try_from(value: ResultFromClient) -> result::Result<Self, Self::Error> {
622 if let ResultFromClient::ClientResult(client_result) = value {
623 Ok(client_result)
624 } else {
625 Err(RpcError::internal_error().with_message("Not a ClientResult".to_string()))
626 }
627 }
628}
629
630impl From<ClientResult> for ResultFromClient {
631 fn from(value: ClientResult) -> Self {
632 Self::ClientResult(value)
633 }
634}
635
636impl From<serde_json::Value> for ResultFromClient {
637 fn from(value: serde_json::Value) -> Self {
638 Self::CustomResult(value)
639 }
640}
641
642impl<'de> serde::Deserialize<'de> for ResultFromClient {
643 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
644 where
645 D: serde::Deserializer<'de>,
646 {
647 let raw_value = Value::deserialize(deserializer)?;
648
649 let result = ClientResult::deserialize(&raw_value);
650
651 match result {
652 Ok(client_result) => Ok(Self::ClientResult(client_result)),
653 Err(_) => Ok(Self::CustomResult(raw_value)),
654 }
655 }
656}
657
658impl FromStr for ClientMessage {
663 type Err = RpcError;
664
665 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
666 serde_json::from_str(s)
667 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
668 }
669}
670
671impl Display for ClientMessage {
672 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
673 write!(
674 f,
675 "{}",
676 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
677 )
678 }
679}
680
681#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
688#[serde(untagged)]
689pub enum ServerMessage {
690 Request(ServerJsonrpcRequest),
691 Notification(ServerJsonrpcNotification),
692 Response(ServerJsonrpcResponse),
693 Error(JsonrpcErrorResponse),
694}
695
696impl ServerMessage {
697 pub fn as_response(self) -> std::result::Result<ServerJsonrpcResponse, RpcError> {
707 if let Self::Response(response) = self {
708 Ok(response)
709 } else {
710 Err(RpcError::internal_error().with_message(format!(
711 "Invalid message type, expected: \"{}\" received\"{}\"",
712 MessageTypes::Response,
713 self.message_type()
714 )))
715 }
716 }
717
718 pub fn as_request(self) -> std::result::Result<ServerJsonrpcRequest, RpcError> {
728 if let Self::Request(request) = self {
729 Ok(request)
730 } else {
731 Err(RpcError::internal_error().with_message(format!(
732 "Invalid message type, expected: \"{}\" received\"{}\"",
733 MessageTypes::Request,
734 self.message_type()
735 )))
736 }
737 }
738
739 pub fn as_notification(self) -> std::result::Result<ServerJsonrpcNotification, RpcError> {
749 if let Self::Notification(notification) = self {
750 Ok(notification)
751 } else {
752 Err(RpcError::internal_error().with_message(format!(
753 "Invalid message type, expected: \"{}\" received\"{}\"",
754 MessageTypes::Notification,
755 self.message_type()
756 )))
757 }
758 }
759
760 pub fn as_error(self) -> std::result::Result<JsonrpcErrorResponse, RpcError> {
770 if let Self::Error(error) = self {
771 Ok(error)
772 } else {
773 Err(RpcError::internal_error().with_message(format!(
774 "Invalid message type, expected: \"{}\" received\"{}\"",
775 MessageTypes::Error,
776 self.message_type()
777 )))
778 }
779 }
780}
781
782impl From<ServerJsonrpcNotification> for ServerMessage {
783 fn from(value: ServerJsonrpcNotification) -> Self {
784 Self::Notification(value)
785 }
786}
787
788impl From<ServerJsonrpcRequest> for ServerMessage {
789 fn from(value: ServerJsonrpcRequest) -> Self {
790 Self::Request(value)
791 }
792}
793
794impl From<ServerJsonrpcResponse> for ServerMessage {
795 fn from(value: ServerJsonrpcResponse) -> Self {
796 Self::Response(value)
797 }
798}
799
800impl RpcMessage for ServerMessage {
801 fn request_id(&self) -> Option<&RequestId> {
803 match self {
804 ServerMessage::Request(server_jsonrpc_request) => Some(&server_jsonrpc_request.id),
806 ServerMessage::Notification(_) => None,
808 ServerMessage::Response(server_jsonrpc_response) => Some(&server_jsonrpc_response.id),
810 ServerMessage::Error(jsonrpc_error) => jsonrpc_error.id.as_ref(),
812 }
813 }
814
815 fn jsonrpc(&self) -> &str {
816 match self {
817 ServerMessage::Request(server_jsonrpc_request) => server_jsonrpc_request.jsonrpc(),
819 ServerMessage::Notification(notification) => notification.jsonrpc(),
821 ServerMessage::Response(server_jsonrpc_response) => server_jsonrpc_response.jsonrpc(),
823 ServerMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
825 }
826 }
827}
828
829impl McpMessage for ServerMessage {
831 fn is_response(&self) -> bool {
833 matches!(self, ServerMessage::Response(_))
834 }
835
836 fn is_request(&self) -> bool {
838 matches!(self, ServerMessage::Request(_))
839 }
840
841 fn is_notification(&self) -> bool {
843 matches!(self, ServerMessage::Notification(_))
844 }
845
846 fn is_error(&self) -> bool {
848 matches!(self, ServerMessage::Error(_))
849 }
850
851 fn message_type(&self) -> MessageTypes {
853 match self {
854 ServerMessage::Request(_) => MessageTypes::Request,
855 ServerMessage::Notification(_) => MessageTypes::Notification,
856 ServerMessage::Response(_) => MessageTypes::Response,
857 ServerMessage::Error(_) => MessageTypes::Error,
858 }
859 }
860}
861
862impl FromStr for ServerMessage {
863 type Err = RpcError;
864
865 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
866 serde_json::from_str(s)
867 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
868 }
869}
870
871impl Display for ServerMessage {
872 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
873 write!(
874 f,
875 "{}",
876 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
877 )
878 }
879}
880
881#[derive(Clone, Debug)]
887#[allow(clippy::large_enum_variant)]
888pub struct ServerJsonrpcRequest {
889 pub id: RequestId,
890 jsonrpc: ::std::string::String,
891 pub method: String,
892 pub request: RequestFromServer,
893}
894
895impl ServerJsonrpcRequest {
896 pub fn new(id: RequestId, request: RequestFromServer) -> Self {
897 let method = request.method().to_string();
898 Self {
899 id,
900 jsonrpc: JSONRPC_VERSION.to_string(),
901 method,
902 request,
903 }
904 }
905 pub fn jsonrpc(&self) -> &::std::string::String {
906 &self.jsonrpc
907 }
908}
909
910impl Display for ServerJsonrpcRequest {
912 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
913 write!(
914 f,
915 "{}",
916 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
917 )
918 }
919}
920
921impl FromStr for ServerJsonrpcRequest {
922 type Err = RpcError;
923
924 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
925 serde_json::from_str(s)
926 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
927 }
928}
929#[derive(::serde::Serialize, Clone, Debug)]
936#[serde(untagged)]
937pub enum RequestFromServer {
938 ServerRequest(ServerRequest),
939 CustomRequest(serde_json::Value),
940}
941
942impl TryFrom<RequestFromServer> for ServerRequest {
943 type Error = RpcError;
944 fn try_from(value: RequestFromServer) -> result::Result<Self, Self::Error> {
945 if let RequestFromServer::ServerRequest(server_request) = value {
946 Ok(server_request)
947 } else {
948 Err(RpcError::internal_error().with_message("Not a ServerRequest".to_string()))
949 }
950 }
951}
952
953impl RequestFromServer {
954 pub fn method(&self) -> &str {
955 match self {
956 RequestFromServer::ServerRequest(request) => request.method(),
957 RequestFromServer::CustomRequest(request) => request["method"].as_str().unwrap(),
958 }
959 }
960}
961
962impl From<ServerRequest> for RequestFromServer {
963 fn from(value: ServerRequest) -> Self {
964 Self::ServerRequest(value)
965 }
966}
967
968impl From<serde_json::Value> for RequestFromServer {
969 fn from(value: serde_json::Value) -> Self {
970 Self::CustomRequest(value)
971 }
972}
973
974impl<'de> serde::Deserialize<'de> for RequestFromServer {
975 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
976 where
977 D: serde::Deserializer<'de>,
978 {
979 let raw_value = Value::deserialize(deserializer)?;
980
981 let server_result = ServerRequest::deserialize(&raw_value);
982
983 match server_result {
984 Ok(server_request) => Ok(Self::ServerRequest(server_request)),
985 Err(_) => Ok(Self::CustomRequest(raw_value)),
986 }
987 }
988}
989
990#[derive(Clone, Debug)]
996pub struct ServerJsonrpcNotification {
997 jsonrpc: ::std::string::String,
998 pub method: ::std::string::String,
999 pub notification: NotificationFromServer,
1000}
1001
1002impl ServerJsonrpcNotification {
1003 pub fn new(notification: NotificationFromServer) -> Self {
1004 let method = notification.method().to_string();
1005 Self {
1006 jsonrpc: JSONRPC_VERSION.to_string(),
1007 method,
1008 notification,
1009 }
1010 }
1011 pub fn jsonrpc(&self) -> &::std::string::String {
1012 &self.jsonrpc
1013 }
1014}
1015
1016impl Display for ServerJsonrpcNotification {
1018 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1019 write!(
1020 f,
1021 "{}",
1022 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1023 )
1024 }
1025}
1026
1027impl FromStr for ServerJsonrpcNotification {
1028 type Err = RpcError;
1029
1030 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1031 serde_json::from_str(s)
1032 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1033 }
1034}
1035#[derive(::serde::Serialize, Clone, Debug)]
1042#[serde(untagged)]
1043pub enum NotificationFromServer {
1044 ServerNotification(ServerNotification),
1045 CustomNotification(serde_json::Value),
1046}
1047
1048impl TryFrom<NotificationFromServer> for ServerNotification {
1049 type Error = RpcError;
1050 fn try_from(value: NotificationFromServer) -> result::Result<Self, Self::Error> {
1051 if let NotificationFromServer::ServerNotification(server_notification) = value {
1052 Ok(server_notification)
1053 } else {
1054 Err(RpcError::internal_error().with_message("Not a ServerNotification".to_string()))
1055 }
1056 }
1057}
1058
1059impl NotificationFromServer {
1060 pub fn method(&self) -> &str {
1061 match self {
1062 NotificationFromServer::ServerNotification(notification) => notification.method(),
1063 NotificationFromServer::CustomNotification(notification) => notification["method"].as_str().unwrap(),
1064 }
1065 }
1066}
1067
1068impl<'de> serde::Deserialize<'de> for NotificationFromServer {
1069 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
1070 where
1071 D: serde::Deserializer<'de>,
1072 {
1073 let raw_value = Value::deserialize(deserializer)?;
1074
1075 let result = ServerNotification::deserialize(&raw_value);
1076
1077 match result {
1078 Ok(client_notification) => Ok(Self::ServerNotification(client_notification)),
1079 Err(_) => Ok(Self::CustomNotification(raw_value)),
1080 }
1081 }
1082}
1083
1084#[derive(Clone, Debug)]
1090pub struct ServerJsonrpcResponse {
1091 pub id: RequestId,
1092 jsonrpc: ::std::string::String,
1093 pub result: ResultFromServer,
1094}
1095
1096impl ServerJsonrpcResponse {
1097 pub fn new(id: RequestId, result: ResultFromServer) -> Self {
1098 Self {
1099 id,
1100 jsonrpc: JSONRPC_VERSION.to_string(),
1101 result,
1102 }
1103 }
1104 pub fn jsonrpc(&self) -> &::std::string::String {
1105 &self.jsonrpc
1106 }
1107}
1108
1109impl Display for ServerJsonrpcResponse {
1111 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1112 write!(
1113 f,
1114 "{}",
1115 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1116 )
1117 }
1118}
1119
1120impl FromStr for ServerJsonrpcResponse {
1121 type Err = RpcError;
1122
1123 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1124 serde_json::from_str(s)
1125 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1126 }
1127}
1128#[allow(clippy::large_enum_variant)]
1135#[derive(::serde::Serialize, Clone, Debug)]
1136#[serde(untagged)]
1137pub enum ResultFromServer {
1138 ServerResult(ServerResult),
1139 CustomResult(serde_json::Value),
1141}
1142
1143impl TryFrom<ResultFromServer> for ServerResult {
1144 type Error = RpcError;
1145 fn try_from(value: ResultFromServer) -> result::Result<Self, Self::Error> {
1146 if let ResultFromServer::ServerResult(server_result) = value {
1147 Ok(server_result)
1148 } else {
1149 Err(RpcError::internal_error().with_message("Not a ServerResult".to_string()))
1150 }
1151 }
1152}
1153
1154impl From<ServerResult> for ResultFromServer {
1155 fn from(value: ServerResult) -> Self {
1156 Self::ServerResult(value)
1157 }
1158}
1159
1160impl From<serde_json::Value> for ResultFromServer {
1161 fn from(value: serde_json::Value) -> Self {
1162 Self::CustomResult(value)
1163 }
1164}
1165
1166impl<'de> serde::Deserialize<'de> for ResultFromServer {
1167 fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
1168 where
1169 D: serde::Deserializer<'de>,
1170 {
1171 let raw_value = Value::deserialize(deserializer)?;
1172
1173 let result = ServerResult::deserialize(&raw_value);
1174
1175 match result {
1176 Ok(server_result) => Ok(Self::ServerResult(server_result)),
1177 Err(_) => Ok(Self::CustomResult(raw_value)),
1178 }
1179 }
1180}
1181
1182impl Display for JsonrpcErrorResponse {
1188 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1189 write!(
1190 f,
1191 "{}",
1192 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1193 )
1194 }
1195}
1196
1197impl FromStr for JsonrpcErrorResponse {
1198 type Err = RpcError;
1199
1200 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1201 serde_json::from_str(s)
1202 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1203 }
1204}
1205
1206#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1215#[serde(untagged)]
1216pub enum MessageFromServer {
1217 RequestFromServer(RequestFromServer),
1218 ResultFromServer(ResultFromServer),
1219 NotificationFromServer(NotificationFromServer),
1220 Error(RpcError),
1221}
1222
1223impl From<RequestFromServer> for MessageFromServer {
1224 fn from(value: RequestFromServer) -> Self {
1225 Self::RequestFromServer(value)
1226 }
1227}
1228
1229impl From<ResultFromServer> for MessageFromServer {
1230 fn from(value: ResultFromServer) -> Self {
1231 Self::ResultFromServer(value)
1232 }
1233}
1234
1235impl From<NotificationFromServer> for MessageFromServer {
1236 fn from(value: NotificationFromServer) -> Self {
1237 Self::NotificationFromServer(value)
1238 }
1239}
1240
1241impl From<RpcError> for MessageFromServer {
1242 fn from(value: RpcError) -> Self {
1243 Self::Error(value)
1244 }
1245}
1246
1247impl McpMessage for MessageFromServer {
1248 fn is_response(&self) -> bool {
1249 matches!(self, MessageFromServer::ResultFromServer(_))
1250 }
1251
1252 fn is_request(&self) -> bool {
1253 matches!(self, MessageFromServer::RequestFromServer(_))
1254 }
1255
1256 fn is_notification(&self) -> bool {
1257 matches!(self, MessageFromServer::NotificationFromServer(_))
1258 }
1259
1260 fn is_error(&self) -> bool {
1261 matches!(self, MessageFromServer::Error(_))
1262 }
1263
1264 fn message_type(&self) -> MessageTypes {
1265 match self {
1266 MessageFromServer::RequestFromServer(_) => MessageTypes::Request,
1267 MessageFromServer::ResultFromServer(_) => MessageTypes::Response,
1268 MessageFromServer::NotificationFromServer(_) => MessageTypes::Notification,
1269 MessageFromServer::Error(_) => MessageTypes::Error,
1270 }
1271 }
1272}
1273
1274impl FromMessage<MessageFromServer> for ServerMessage {
1275 fn from_message(message: MessageFromServer, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1276 match message {
1277 MessageFromServer::RequestFromServer(request_from_server) => {
1278 let request_id =
1279 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1280 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(
1281 request_id,
1282 request_from_server,
1283 )))
1284 }
1285 MessageFromServer::ResultFromServer(result_from_server) => {
1286 let request_id =
1287 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1288 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
1289 request_id,
1290 result_from_server,
1291 )))
1292 }
1293 MessageFromServer::NotificationFromServer(notification_from_server) => {
1294 if request_id.is_some() {
1295 return Err(RpcError::internal_error()
1296 .with_message("request_id expected to be None for Notifications!".to_string()));
1297 }
1298 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(
1299 notification_from_server,
1300 )))
1301 }
1302 MessageFromServer::Error(jsonrpc_error_error) => {
1303 Ok(ServerMessage::Error(JsonrpcErrorResponse::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 Ok(ClientMessage::Error(JsonrpcErrorResponse::new(jsonrpc_error_error, request_id)))
1420 }
1421 }
1422 }
1423}
1424
1425#[derive(Debug)]
1432pub struct UnknownTool(pub String);
1433
1434impl core::fmt::Display for UnknownTool {
1436 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1437 write!(f, "Unknown tool: {}", self.0)
1439 }
1440}
1441
1442impl std::error::Error for UnknownTool {}
1444
1445#[derive(Debug)]
1451pub struct CallToolError(pub Box<dyn std::error::Error>);
1452
1453impl CallToolError {
1455 pub fn new<E: std::error::Error + 'static>(err: E) -> Self {
1457 CallToolError(Box::new(err))
1459 }
1460
1461 pub fn unknown_tool(tool_name: impl Into<String>) -> Self {
1463 CallToolError(Box::new(UnknownTool(tool_name.into())))
1465 }
1466
1467 pub fn invalid_arguments(tool_name: impl AsRef<str>, message: Option<String>) -> Self {
1470 let tool_name = tool_name.as_ref().trim();
1472 if tool_name.is_empty() {
1473 return Self::from_message("Invalid arguments: tool name cannot be empty".to_string());
1474 }
1475
1476 let default_message = "no additional details provided".to_string();
1478 let message = message.unwrap_or(default_message);
1479
1480 let full_message = format!("Invalid arguments for tool '{tool_name}': {message}");
1482
1483 Self::from_message(full_message)
1484 }
1485
1486 pub fn from_message(message: impl Into<String>) -> Self {
1506 struct MsgError(String);
1507 impl std::fmt::Debug for MsgError {
1508 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1509 write!(f, "{}", self.0)
1510 }
1511 }
1512 impl std::fmt::Display for MsgError {
1513 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1514 write!(f, "{}", self.0)
1515 }
1516 }
1517 impl std::error::Error for MsgError {}
1518
1519 CallToolError::new(MsgError(message.into()))
1520 }
1521}
1522
1523impl From<CallToolError> for RpcError {
1529 fn from(value: CallToolError) -> Self {
1530 Self::internal_error().with_message(value.to_string())
1531 }
1532}
1533
1534impl From<CallToolError> for CallToolResult {
1536 fn from(value: CallToolError) -> Self {
1537 CallToolResult {
1539 content: vec![TextContent::new(value.to_string(), None, None).into()],
1540 is_error: Some(true),
1541 meta: None,
1542 structured_content: None,
1543 }
1544 }
1545}
1546
1547impl core::fmt::Display for CallToolError {
1549 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1550 write!(f, "{}", self.0)
1551 }
1552}
1553
1554impl std::error::Error for CallToolError {
1556 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1557 self.0.source()
1558 }
1559}
1560
1561impl CallToolRequest {
1562 pub fn tool_name(&self) -> &str {
1570 &self.params.name
1571 }
1572}
1573
1574impl<T: Into<String>> From<T> for TextContent {
1575 fn from(value: T) -> Self {
1576 TextContent::new(value.into(), None, None)
1577 }
1578}
1579
1580#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1581#[serde(untagged)]
1582#[allow(clippy::large_enum_variant)]
1583pub enum ClientMessages {
1584 Single(ClientMessage),
1585 Batch(Vec<ClientMessage>),
1586}
1587
1588impl ClientMessages {
1589 pub fn is_batch(&self) -> bool {
1590 matches!(self, ClientMessages::Batch(_))
1591 }
1592
1593 pub fn includes_request(&self) -> bool {
1594 match self {
1595 ClientMessages::Single(client_message) => client_message.is_request(),
1596 ClientMessages::Batch(client_messages) => client_messages.iter().any(ClientMessage::is_request),
1597 }
1598 }
1599
1600 pub fn as_single(self) -> result::Result<ClientMessage, SdkError> {
1601 match self {
1602 ClientMessages::Single(client_message) => Ok(client_message),
1603 ClientMessages::Batch(_) => Err(SdkError::internal_error()
1604 .with_message("Error: cannot convert ClientMessages::Batch to ClientMessage::Single")),
1605 }
1606 }
1607 pub fn as_batch(self) -> result::Result<Vec<ClientMessage>, SdkError> {
1608 match self {
1609 ClientMessages::Single(_) => Err(SdkError::internal_error()
1610 .with_message("Error: cannot convert ClientMessage::Single to ClientMessages::Batch")),
1611 ClientMessages::Batch(client_messages) => Ok(client_messages),
1612 }
1613 }
1614}
1615
1616impl From<ClientMessage> for ClientMessages {
1617 fn from(value: ClientMessage) -> Self {
1618 Self::Single(value)
1619 }
1620}
1621
1622impl From<Vec<ClientMessage>> for ClientMessages {
1623 fn from(value: Vec<ClientMessage>) -> Self {
1624 Self::Batch(value)
1625 }
1626}
1627
1628impl Display for ClientMessages {
1629 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1630 write!(
1631 f,
1632 "{}",
1633 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1634 )
1635 }
1636}
1637
1638#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1639#[serde(untagged)]
1640#[allow(clippy::large_enum_variant)]
1641pub enum ServerMessages {
1642 Single(ServerMessage),
1643 Batch(Vec<ServerMessage>),
1644}
1645
1646impl ServerMessages {
1647 pub fn is_batch(&self) -> bool {
1648 matches!(self, ServerMessages::Batch(_))
1649 }
1650
1651 pub fn includes_request(&self) -> bool {
1652 match self {
1653 ServerMessages::Single(server_message) => server_message.is_request(),
1654 ServerMessages::Batch(server_messages) => server_messages.iter().any(ServerMessage::is_request),
1655 }
1656 }
1657
1658 pub fn as_single(self) -> result::Result<ServerMessage, SdkError> {
1659 match self {
1660 ServerMessages::Single(server_message) => Ok(server_message),
1661 ServerMessages::Batch(_) => Err(SdkError::internal_error()
1662 .with_message("Error: cannot convert ServerMessages::Batch to ServerMessage::Single")),
1663 }
1664 }
1665 pub fn as_batch(self) -> result::Result<Vec<ServerMessage>, SdkError> {
1666 match self {
1667 ServerMessages::Single(_) => Err(SdkError::internal_error()
1668 .with_message("Error: cannot convert ServerMessage::Single to ServerMessages::Batch")),
1669 ServerMessages::Batch(server_messages) => Ok(server_messages),
1670 }
1671 }
1672}
1673
1674impl From<ServerMessage> for ServerMessages {
1675 fn from(value: ServerMessage) -> Self {
1676 Self::Single(value)
1677 }
1678}
1679
1680impl From<Vec<ServerMessage>> for ServerMessages {
1681 fn from(value: Vec<ServerMessage>) -> Self {
1682 Self::Batch(value)
1683 }
1684}
1685
1686impl Display for ServerMessages {
1687 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1688 write!(
1689 f,
1690 "{}",
1691 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1692 )
1693 }
1694}
1695
1696#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1697#[serde(untagged)]
1698#[allow(clippy::large_enum_variant)]
1699pub enum MessagesFromServer {
1700 Single(MessageFromServer),
1701 Batch(Vec<MessageFromServer>),
1702}
1703
1704impl MessagesFromServer {
1705 pub fn is_batch(&self) -> bool {
1706 matches!(self, MessagesFromServer::Batch(_))
1707 }
1708
1709 pub fn includes_request(&self) -> bool {
1710 match self {
1711 MessagesFromServer::Single(server_message) => server_message.is_request(),
1712 MessagesFromServer::Batch(server_messages) => server_messages.iter().any(MessageFromServer::is_request),
1713 }
1714 }
1715
1716 pub fn as_single(self) -> result::Result<MessageFromServer, SdkError> {
1717 match self {
1718 MessagesFromServer::Single(server_message) => Ok(server_message),
1719 MessagesFromServer::Batch(_) => Err(SdkError::internal_error()
1720 .with_message("Error: cannot convert MessagesFromServer::Batch to MessageFromServer::Single")),
1721 }
1722 }
1723 pub fn as_batch(self) -> result::Result<Vec<MessageFromServer>, SdkError> {
1724 match self {
1725 MessagesFromServer::Single(_) => Err(SdkError::internal_error()
1726 .with_message("Error: cannot convert MessageFromServer::Single to MessagesFromServer::Batch")),
1727 MessagesFromServer::Batch(server_messages) => Ok(server_messages),
1728 }
1729 }
1730}
1731
1732impl From<MessageFromServer> for MessagesFromServer {
1733 fn from(value: MessageFromServer) -> Self {
1734 Self::Single(value)
1735 }
1736}
1737
1738impl From<Vec<MessageFromServer>> for MessagesFromServer {
1739 fn from(value: Vec<MessageFromServer>) -> Self {
1740 Self::Batch(value)
1741 }
1742}
1743
1744#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1745#[serde(untagged)]
1746#[allow(clippy::large_enum_variant)]
1747pub enum MessagesFromClient {
1748 Single(MessageFromClient),
1749 Batch(Vec<MessageFromClient>),
1750}
1751
1752impl MessagesFromClient {
1753 pub fn is_batch(&self) -> bool {
1754 matches!(self, MessagesFromClient::Batch(_))
1755 }
1756
1757 pub fn includes_request(&self) -> bool {
1758 match self {
1759 MessagesFromClient::Single(server_message) => server_message.is_request(),
1760 MessagesFromClient::Batch(server_messages) => server_messages.iter().any(MessageFromClient::is_request),
1761 }
1762 }
1763
1764 pub fn as_single(self) -> result::Result<MessageFromClient, SdkError> {
1765 match self {
1766 MessagesFromClient::Single(server_message) => Ok(server_message),
1767 MessagesFromClient::Batch(_) => Err(SdkError::internal_error()
1768 .with_message("Error: cannot convert MessagesFromClient::Batch to MessageFromClient::Single")),
1769 }
1770 }
1771 pub fn as_batch(self) -> result::Result<Vec<MessageFromClient>, SdkError> {
1772 match self {
1773 MessagesFromClient::Single(_) => Err(SdkError::internal_error()
1774 .with_message("Error: cannot convert MessageFromClient::Single to MessagesFromClient::Batch")),
1775 MessagesFromClient::Batch(server_messages) => Ok(server_messages),
1776 }
1777 }
1778}
1779
1780impl From<MessageFromClient> for MessagesFromClient {
1781 fn from(value: MessageFromClient) -> Self {
1782 Self::Single(value)
1783 }
1784}
1785
1786impl From<Vec<MessageFromClient>> for MessagesFromClient {
1787 fn from(value: Vec<MessageFromClient>) -> Self {
1788 Self::Batch(value)
1789 }
1790}
1791
1792#[derive(Debug)]
1793pub struct StringSchemaFormatError {
1794 invalid_value: String,
1795}
1796
1797impl core::fmt::Display for StringSchemaFormatError {
1798 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1799 write!(f, "Invalid string schema format: '{}'", self.invalid_value)
1800 }
1801}
1802
1803impl std::error::Error for StringSchemaFormatError {}
1804
1805impl FromStr for StringSchemaFormat {
1806 type Err = StringSchemaFormatError;
1807
1808 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1809 match s {
1810 "date" => Ok(Self::Date),
1811 "date-time" => Ok(Self::DateTime),
1812 "email" => Ok(Self::Email),
1813 "uri" => Ok(Self::Uri),
1814 _ => Err(StringSchemaFormatError {
1815 invalid_value: s.to_string(),
1816 }),
1817 }
1818 }
1819}
1820
1821
1822fn try_from_enum_schema(map: &serde_json::Map<String, Value>) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
1824 let has_one_of = map.contains_key("oneOf");
1826 let has_enum = map.contains_key("enum");
1827 let has_enum_names = map.contains_key("enumNames");
1828
1829 if has_one_of {
1830 let schema: TitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
1831 RpcError::parse_error().with_message(format!("Failed to parse TitledSingleSelectEnumSchema: {e}"))
1832 })?;
1833
1834 Ok(PrimitiveSchemaDefinition::TitledSingleSelectEnumSchema(schema))
1835 } else if has_enum && has_enum_names {
1836 let schema: LegacyTitledEnumSchema = serde_json::from_value(Value::Object(map.clone()))
1837 .map_err(|e| RpcError::parse_error().with_message(format!("Failed to parse LegacyTitledEnumSchema: {e}")))?;
1838 Ok(PrimitiveSchemaDefinition::LegacyTitledEnumSchema(schema))
1839 } else if has_enum {
1840 let schema: UntitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
1841 RpcError::parse_error().with_message(format!("Failed to parse UntitledSingleSelectEnumSchema: {e}"))
1842 })?;
1843 Ok(PrimitiveSchemaDefinition::UntitledSingleSelectEnumSchema(schema))
1844 } else {
1845 Err(RpcError::parse_error().with_message("Invalid enum schema: missing 'enum' or 'oneOf'".to_string()))
1846 }
1847}
1848
1849fn try_from_multi_select_schema(
1851 map: &serde_json::Map<String, Value>,
1852) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
1853 let items = map
1854 .get("items")
1855 .ok_or(RpcError::parse_error().with_message("Array schema missing 'items' field".to_string()))?;
1856
1857 let items_obj = items
1858 .as_object()
1859 .ok_or(RpcError::parse_error().with_message("Field 'items' must be an object".to_string()))?;
1860
1861 if items_obj.contains_key("anyOf") {
1862 let schema: TitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
1863 RpcError::parse_error().with_message(format!("Failed to parse TitledMultiSelectEnumSchema: {e}"))
1864 })?;
1865 Ok(PrimitiveSchemaDefinition::TitledMultiSelectEnumSchema(schema))
1866 } else if items_obj.contains_key("enum") {
1867 let schema: UntitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
1868 RpcError::parse_error().with_message(format!("Failed to parse UntitledMultiSelectEnumSchema: {e}"))
1869 })?;
1870 Ok(PrimitiveSchemaDefinition::UntitledMultiSelectEnumSchema(schema))
1871 } else {
1872 Err(RpcError::parse_error()
1873 .with_message("Array schema 'items' must contain 'enum' or 'oneOf' to be a multi-select enum".to_string()))
1874 }
1875}
1876
1877impl TryFrom<&serde_json::Map<String, Value>> for PrimitiveSchemaDefinition {
1878 type Error = RpcError;
1879
1880 fn try_from(value: &serde_json::Map<String, serde_json::Value>) -> result::Result<Self, Self::Error> {
1881 if value.contains_key("enum") || value.contains_key("oneOf") {
1883 return try_from_enum_schema(value);
1884 }
1885
1886 if value.get("type").and_then(|v| v.as_str()) == Some("array") {
1888 return try_from_multi_select_schema(value);
1889 }
1890
1891 let input_type = value
1892 .get("type")
1893 .and_then(|v| v.as_str())
1894 .or_else(|| value.get("oneOf").map(|_| "enum")) .ok_or_else(|| {
1896 RpcError::parse_error().with_message("'type' is missing and data type is not supported!".to_string())
1897 })?;
1898
1899 let description = value.get("description").and_then(|v| v.as_str().map(|s| s.to_string()));
1900 let title = value.get("title").and_then(|v| v.as_str().map(|s| s.to_string()));
1901
1902 let schema_definition: PrimitiveSchemaDefinition = match input_type {
1903 "string" => {
1904 let max_length = value.get("maxLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
1905 let min_length = value.get("minLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
1906 let default = value.get("default").and_then(|v| v.as_str().map(|s| s.to_string()));
1907
1908 let format_str = value.get("format").and_then(|v| v.as_str());
1909 let format = format_str.and_then(|s| StringSchemaFormat::from_str(s).ok());
1910
1911 PrimitiveSchemaDefinition::StringSchema(StringSchema::new(
1912 default,
1913 description,
1914 format,
1915 max_length,
1916 min_length,
1917 title,
1918 ))
1919 }
1920 "number" | "integer" => {
1921 let maximum = value.get("maximum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
1922 let minimum = value.get("minimum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
1923 let default = value.get("default").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
1924
1925 PrimitiveSchemaDefinition::NumberSchema(NumberSchema {
1926 default,
1927 description,
1928 maximum,
1929 minimum,
1930 title,
1931 type_: if input_type == "integer" {
1932 NumberSchemaType::Integer
1933 } else {
1934 NumberSchemaType::Number
1935 },
1936 })
1937 }
1938 "boolean" => {
1939 let default = value.get("default").and_then(|v| v.as_bool().map(|s| s.to_owned()));
1940 PrimitiveSchemaDefinition::BooleanSchema(BooleanSchema::new(default, description, title))
1941 }
1942 other => {
1943 return Err(RpcError::parse_error().with_message(format!("'{other}' type is not currently supported")));
1944 }
1945 };
1946
1947 Ok(schema_definition)
1948 }
1949}
1950
1951#[deprecated(since = "0.4.0", note = "This trait was renamed to RpcMessage. Use RpcMessage instead.")]
1952pub type RPCMessage = ();
1953#[deprecated(since = "0.4.0", note = "This trait was renamed to McpMessage. Use McpMessage instead.")]
1954pub type MCPMessage = ();
1955
1956impl ::serde::Serialize for ClientJsonrpcRequest {
1958 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
1959 where
1960 S: ::serde::Serializer,
1961 {
1962 let mut state = serializer.serialize_struct("JsonrpcRequest", 4)?;
1963 state.serialize_field("id", &self.id)?;
1964 state.serialize_field("jsonrpc", &self.jsonrpc)?;
1965 state.serialize_field("method", &self.method)?;
1966 use ClientRequest::*;
1967 match &self.request {
1968 RequestFromClient::ClientRequest(message) => match message {
1969 InitializeRequest(msg) => state.serialize_field("params", &msg.params)?,
1970 PingRequest(msg) => {
1971 if let Some(params) = &msg.params {
1972 state.serialize_field("params", params)?
1973 }
1974 }
1975 ListResourcesRequest(msg) => state.serialize_field("params", &msg.params)?,
1976 ListResourceTemplatesRequest(msg) => {
1977 if let Some(params) = &msg.params {
1978 state.serialize_field("params", params)?
1979 }
1980 }
1981 ReadResourceRequest(msg) => state.serialize_field("params", &msg.params)?,
1982 SubscribeRequest(msg) => state.serialize_field("params", &msg.params)?,
1983 UnsubscribeRequest(msg) => state.serialize_field("params", &msg.params)?,
1984 ListPromptsRequest(msg) => {
1985 if let Some(params) = &msg.params {
1986 state.serialize_field("params", params)?
1987 }
1988 }
1989 GetPromptRequest(msg) => state.serialize_field("params", &msg.params)?,
1990 ListToolsRequest(msg) => {
1991 if let Some(params) = &msg.params {
1992 state.serialize_field("params", params)?
1993 }
1994 }
1995 CallToolRequest(msg) => state.serialize_field("params", &msg.params)?,
1996 GetTaskRequest(msg) => state.serialize_field("params", &msg.params)?,
1997 GetTaskPayloadRequest(msg) => state.serialize_field("params", &msg.params)?,
1998 CancelTaskRequest(msg) => state.serialize_field("params", &msg.params)?,
1999 ListTasksRequest(msg) => state.serialize_field("params", &msg.params)?,
2000 SetLevelRequest(msg) => state.serialize_field("params", &msg.params)?,
2001 CompleteRequest(msg) => state.serialize_field("params", &msg.params)?,
2002 },
2003 RequestFromClient::CustomRequest(value) => state.serialize_field("params", value)?,
2004 }
2005 state.end()
2006 }
2007}
2008impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcRequest {
2009 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2010 where
2011 D: ::serde::Deserializer<'de>,
2012 {
2013 use serde::de::{self, MapAccess, Visitor};
2014 use std::fmt;
2015 struct ClientJsonrpcRequestVisitor;
2016 impl<'de> Visitor<'de> for ClientJsonrpcRequestVisitor {
2017 type Value = ClientJsonrpcRequest;
2018 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2019 formatter.write_str("a valid JSON-RPC request object")
2020 }
2021 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcRequest, M::Error>
2022 where
2023 M: MapAccess<'de>,
2024 {
2025 let mut id: Option<RequestId> = None;
2026 let mut jsonrpc: Option<String> = None;
2027 let mut method: Option<String> = None;
2028 let mut params: Option<Value> = None;
2029 while let Some(key) = map.next_key::<String>()? {
2030 match key.as_str() {
2031 "id" => id = Some(map.next_value()?),
2032 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2033 "method" => method = Some(map.next_value()?),
2034 "params" => params = Some(map.next_value()?),
2035 _ => {
2036 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
2037 }
2038 }
2039 }
2040 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
2041 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2042 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
2043 let params = params.unwrap_or_default();
2044 let req_object = json!({ "method" : method, "params" : params });
2045 let request = serde_json::from_value::<RequestFromClient>(req_object).map_err(de::Error::custom)?;
2046 Ok(ClientJsonrpcRequest {
2047 id,
2048 jsonrpc,
2049 method,
2050 request,
2051 })
2052 }
2053 }
2054 deserializer.deserialize_struct(
2055 "JsonrpcRequest",
2056 &["id", "jsonrpc", "method", "params"],
2057 ClientJsonrpcRequestVisitor,
2058 )
2059 }
2060}
2061impl ::serde::Serialize for ServerJsonrpcRequest {
2062 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2063 where
2064 S: ::serde::Serializer,
2065 {
2066 let mut state = serializer.serialize_struct("JsonrpcRequest", 4)?;
2067 state.serialize_field("id", &self.id)?;
2068 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2069 state.serialize_field("method", &self.method)?;
2070 use ServerRequest::*;
2071 match &self.request {
2072 RequestFromServer::ServerRequest(message) => match message {
2073 PingRequest(msg) => {
2074 if let Some(params) = &msg.params {
2075 state.serialize_field("params", params)?
2076 }
2077 }
2078 GetTaskRequest(msg) => state.serialize_field("params", &msg.params)?,
2079 GetTaskPayloadRequest(msg) => state.serialize_field("params", &msg.params)?,
2080 CancelTaskRequest(msg) => state.serialize_field("params", &msg.params)?,
2081 ListTasksRequest(msg) => state.serialize_field("params", &msg.params)?,
2082 CreateMessageRequest(msg) => state.serialize_field("params", &msg.params)?,
2083 ListRootsRequest(msg) => {
2084 if let Some(params) = &msg.params {
2085 state.serialize_field("params", params)?
2086 }
2087 }
2088 ElicitRequest(msg) => state.serialize_field("params", &msg.params)?,
2089 },
2090 RequestFromServer::CustomRequest(value) => state.serialize_field("params", value)?,
2091 }
2092 state.end()
2093 }
2094}
2095impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcRequest {
2096 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2097 where
2098 D: ::serde::Deserializer<'de>,
2099 {
2100 use serde::de::{self, MapAccess, Visitor};
2101 use std::fmt;
2102 struct ServerJsonrpcRequestVisitor;
2103 impl<'de> Visitor<'de> for ServerJsonrpcRequestVisitor {
2104 type Value = ServerJsonrpcRequest;
2105 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2106 formatter.write_str("a valid JSON-RPC request object")
2107 }
2108 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcRequest, M::Error>
2109 where
2110 M: MapAccess<'de>,
2111 {
2112 let mut id: Option<RequestId> = None;
2113 let mut jsonrpc: Option<String> = None;
2114 let mut method: Option<String> = None;
2115 let mut params: Option<Value> = None;
2116 while let Some(key) = map.next_key::<String>()? {
2117 match key.as_str() {
2118 "id" => id = Some(map.next_value()?),
2119 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2120 "method" => method = Some(map.next_value()?),
2121 "params" => params = Some(map.next_value()?),
2122 _ => {
2123 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
2124 }
2125 }
2126 }
2127 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
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 request = serde_json::from_value::<RequestFromServer>(req_object).map_err(de::Error::custom)?;
2133 Ok(ServerJsonrpcRequest {
2134 id,
2135 jsonrpc,
2136 method,
2137 request,
2138 })
2139 }
2140 }
2141 deserializer.deserialize_struct(
2142 "JsonrpcRequest",
2143 &["id", "jsonrpc", "method", "params"],
2144 ServerJsonrpcRequestVisitor,
2145 )
2146 }
2147}
2148impl ::serde::Serialize for ClientJsonrpcNotification {
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("JsonrpcNotification", 3)?;
2154 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2155 state.serialize_field("method", &self.method)?;
2156 use ClientNotification::*;
2157 match &self.notification {
2158 NotificationFromClient::ClientNotification(message) => match message {
2159 CancelledNotification(msg) => state.serialize_field("params", &msg.params)?,
2160 InitializedNotification(msg) => {
2161 if let Some(params) = &msg.params {
2162 state.serialize_field("params", params)?
2163 }
2164 }
2165 ProgressNotification(msg) => state.serialize_field("params", &msg.params)?,
2166 TaskStatusNotification(msg) => state.serialize_field("params", &msg.params)?,
2167 RootsListChangedNotification(msg) => {
2168 if let Some(params) = &msg.params {
2169 state.serialize_field("params", params)?
2170 }
2171 }
2172 },
2173 NotificationFromClient::CustomNotification(value) => state.serialize_field("params", value)?,
2174 }
2175 state.end()
2176 }
2177}
2178impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcNotification {
2179 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2180 where
2181 D: ::serde::Deserializer<'de>,
2182 {
2183 use serde::de::{self, MapAccess, Visitor};
2184 use std::fmt;
2185 struct ClientJsonrpcNotificationVisitor;
2186 impl<'de> Visitor<'de> for ClientJsonrpcNotificationVisitor {
2187 type Value = ClientJsonrpcNotification;
2188 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2189 formatter.write_str("a valid JSON-RPC notification object")
2190 }
2191 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcNotification, M::Error>
2192 where
2193 M: MapAccess<'de>,
2194 {
2195 let mut jsonrpc: Option<String> = None;
2196 let mut method: Option<String> = None;
2197 let mut params: Option<Value> = None;
2198 while let Some(key) = map.next_key::<String>()? {
2199 match key.as_str() {
2200 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2201 "method" => method = Some(map.next_value()?),
2202 "params" => params = Some(map.next_value()?),
2203 _ => {
2204 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
2205 }
2206 }
2207 }
2208 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2209 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
2210 let params = params.unwrap_or_default();
2211 let req_object = json!({ "method" : method, "params" : params });
2212 let notification =
2213 serde_json::from_value::<NotificationFromClient>(req_object).map_err(de::Error::custom)?;
2214 Ok(ClientJsonrpcNotification {
2215 jsonrpc,
2216 method,
2217 notification,
2218 })
2219 }
2220 }
2221 deserializer.deserialize_struct(
2222 "JsonrpcRequest",
2223 &["jsonrpc", "method", "params"],
2224 ClientJsonrpcNotificationVisitor,
2225 )
2226 }
2227}
2228impl ::serde::Serialize for ServerJsonrpcNotification {
2229 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2230 where
2231 S: ::serde::Serializer,
2232 {
2233 let mut state = serializer.serialize_struct("JsonrpcNotification", 3)?;
2234 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2235 state.serialize_field("method", &self.method)?;
2236 use ServerNotification::*;
2237 match &self.notification {
2238 NotificationFromServer::ServerNotification(message) => match message {
2239 CancelledNotification(msg) => state.serialize_field("params", &msg.params)?,
2240 ProgressNotification(msg) => state.serialize_field("params", &msg.params)?,
2241 ResourceListChangedNotification(msg) => {
2242 if let Some(params) = &msg.params {
2243 state.serialize_field("params", params)?
2244 }
2245 }
2246 ResourceUpdatedNotification(msg) => state.serialize_field("params", &msg.params)?,
2247 PromptListChangedNotification(msg) => {
2248 if let Some(params) = &msg.params {
2249 state.serialize_field("params", params)?
2250 }
2251 }
2252 ToolListChangedNotification(msg) => {
2253 if let Some(params) = &msg.params {
2254 state.serialize_field("params", params)?
2255 }
2256 }
2257 TaskStatusNotification(msg) => state.serialize_field("params", &msg.params)?,
2258 LoggingMessageNotification(msg) => state.serialize_field("params", &msg.params)?,
2259 ElicitationCompleteNotification(msg) => state.serialize_field("params", &msg.params)?,
2260 },
2261 NotificationFromServer::CustomNotification(value) => state.serialize_field("params", value)?,
2262 }
2263 state.end()
2264 }
2265}
2266impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcNotification {
2267 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2268 where
2269 D: ::serde::Deserializer<'de>,
2270 {
2271 use serde::de::{self, MapAccess, Visitor};
2272 use std::fmt;
2273 struct ServerJsonrpcNotificationVisitor;
2274 impl<'de> Visitor<'de> for ServerJsonrpcNotificationVisitor {
2275 type Value = ServerJsonrpcNotification;
2276 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2277 formatter.write_str("a valid JSON-RPC notification object")
2278 }
2279 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcNotification, M::Error>
2280 where
2281 M: MapAccess<'de>,
2282 {
2283 let mut jsonrpc: Option<String> = None;
2284 let mut method: Option<String> = None;
2285 let mut params: Option<Value> = None;
2286 while let Some(key) = map.next_key::<String>()? {
2287 match key.as_str() {
2288 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2289 "method" => method = Some(map.next_value()?),
2290 "params" => params = Some(map.next_value()?),
2291 _ => {
2292 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "method", "params"]));
2293 }
2294 }
2295 }
2296 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2297 let method = method.ok_or_else(|| de::Error::missing_field("method"))?;
2298 let params = params.unwrap_or_default();
2299 let req_object = json!({ "method" : method, "params" : params });
2300 let notification =
2301 serde_json::from_value::<NotificationFromServer>(req_object).map_err(de::Error::custom)?;
2302 Ok(ServerJsonrpcNotification {
2303 jsonrpc,
2304 method,
2305 notification,
2306 })
2307 }
2308 }
2309 deserializer.deserialize_struct(
2310 "JsonrpcRequest",
2311 &["jsonrpc", "method", "params"],
2312 ServerJsonrpcNotificationVisitor,
2313 )
2314 }
2315}
2316impl ::serde::Serialize for ServerJsonrpcResponse {
2317 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2318 where
2319 S: ::serde::Serializer,
2320 {
2321 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
2322 state.serialize_field("id", &self.id)?;
2323 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2324 state.serialize_field("result", &self.result)?;
2325 state.end()
2326 }
2327}
2328impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcResponse {
2329 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2330 where
2331 D: ::serde::Deserializer<'de>,
2332 {
2333 use serde::de::{self, MapAccess, Visitor};
2334 use std::fmt;
2335 struct ServerJsonrpcResultVisitor;
2336 impl<'de> Visitor<'de> for ServerJsonrpcResultVisitor {
2337 type Value = ServerJsonrpcResponse;
2338 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2339 formatter.write_str("a valid JSON-RPC response object")
2340 }
2341 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcResponse, M::Error>
2342 where
2343 M: MapAccess<'de>,
2344 {
2345 let mut id: Option<RequestId> = None;
2346 let mut jsonrpc: Option<String> = None;
2347 let mut result: Option<Value> = None;
2348 while let Some(key) = map.next_key::<String>()? {
2349 match key.as_str() {
2350 "id" => id = Some(map.next_value()?),
2351 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2352 "result" => result = Some(map.next_value()?),
2353 _ => {
2354 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
2355 }
2356 }
2357 }
2358 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
2359 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2360 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
2361 let result = serde_json::from_value::<ResultFromServer>(result).map_err(de::Error::custom)?;
2362 Ok(ServerJsonrpcResponse { id, jsonrpc, result })
2363 }
2364 }
2365 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ServerJsonrpcResultVisitor)
2366 }
2367}
2368impl ::serde::Serialize for ClientJsonrpcResponse {
2369 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2370 where
2371 S: ::serde::Serializer,
2372 {
2373 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
2374 state.serialize_field("id", &self.id)?;
2375 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2376 state.serialize_field("result", &self.result)?;
2377 state.end()
2378 }
2379}
2380impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcResponse {
2381 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2382 where
2383 D: ::serde::Deserializer<'de>,
2384 {
2385 use serde::de::{self, MapAccess, Visitor};
2386 use std::fmt;
2387 struct ClientJsonrpcResultVisitor;
2388 impl<'de> Visitor<'de> for ClientJsonrpcResultVisitor {
2389 type Value = ClientJsonrpcResponse;
2390 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2391 formatter.write_str("a valid JSON-RPC response object")
2392 }
2393 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcResponse, M::Error>
2394 where
2395 M: MapAccess<'de>,
2396 {
2397 let mut id: Option<RequestId> = None;
2398 let mut jsonrpc: Option<String> = None;
2399 let mut result: Option<Value> = None;
2400 while let Some(key) = map.next_key::<String>()? {
2401 match key.as_str() {
2402 "id" => id = Some(map.next_value()?),
2403 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2404 "result" => result = Some(map.next_value()?),
2405 _ => {
2406 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
2407 }
2408 }
2409 }
2410 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
2411 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2412 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
2413 let result = serde_json::from_value::<ResultFromClient>(result).map_err(de::Error::custom)?;
2414 Ok(ClientJsonrpcResponse { id, jsonrpc, result })
2415 }
2416 }
2417 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ClientJsonrpcResultVisitor)
2418 }
2419}
2420impl From<InitializeRequest> for RequestFromClient {
2421 fn from(value: InitializeRequest) -> Self {
2422 Self::ClientRequest(value.into())
2423 }
2424}
2425impl From<PingRequest> for RequestFromClient {
2426 fn from(value: PingRequest) -> Self {
2427 Self::ClientRequest(value.into())
2428 }
2429}
2430impl From<ListResourcesRequest> for RequestFromClient {
2431 fn from(value: ListResourcesRequest) -> Self {
2432 Self::ClientRequest(value.into())
2433 }
2434}
2435impl From<ListResourceTemplatesRequest> for RequestFromClient {
2436 fn from(value: ListResourceTemplatesRequest) -> Self {
2437 Self::ClientRequest(value.into())
2438 }
2439}
2440impl From<ReadResourceRequest> for RequestFromClient {
2441 fn from(value: ReadResourceRequest) -> Self {
2442 Self::ClientRequest(value.into())
2443 }
2444}
2445impl From<SubscribeRequest> for RequestFromClient {
2446 fn from(value: SubscribeRequest) -> Self {
2447 Self::ClientRequest(value.into())
2448 }
2449}
2450impl From<UnsubscribeRequest> for RequestFromClient {
2451 fn from(value: UnsubscribeRequest) -> Self {
2452 Self::ClientRequest(value.into())
2453 }
2454}
2455impl From<ListPromptsRequest> for RequestFromClient {
2456 fn from(value: ListPromptsRequest) -> Self {
2457 Self::ClientRequest(value.into())
2458 }
2459}
2460impl From<GetPromptRequest> for RequestFromClient {
2461 fn from(value: GetPromptRequest) -> Self {
2462 Self::ClientRequest(value.into())
2463 }
2464}
2465impl From<ListToolsRequest> for RequestFromClient {
2466 fn from(value: ListToolsRequest) -> Self {
2467 Self::ClientRequest(value.into())
2468 }
2469}
2470impl From<CallToolRequest> for RequestFromClient {
2471 fn from(value: CallToolRequest) -> Self {
2472 Self::ClientRequest(value.into())
2473 }
2474}
2475impl From<GetTaskRequest> for RequestFromClient {
2476 fn from(value: GetTaskRequest) -> Self {
2477 Self::ClientRequest(value.into())
2478 }
2479}
2480impl From<GetTaskPayloadRequest> for RequestFromClient {
2481 fn from(value: GetTaskPayloadRequest) -> Self {
2482 Self::ClientRequest(value.into())
2483 }
2484}
2485impl From<CancelTaskRequest> for RequestFromClient {
2486 fn from(value: CancelTaskRequest) -> Self {
2487 Self::ClientRequest(value.into())
2488 }
2489}
2490impl From<ListTasksRequest> for RequestFromClient {
2491 fn from(value: ListTasksRequest) -> Self {
2492 Self::ClientRequest(value.into())
2493 }
2494}
2495impl From<SetLevelRequest> for RequestFromClient {
2496 fn from(value: SetLevelRequest) -> Self {
2497 Self::ClientRequest(value.into())
2498 }
2499}
2500impl From<CompleteRequest> for RequestFromClient {
2501 fn from(value: CompleteRequest) -> Self {
2502 Self::ClientRequest(value.into())
2503 }
2504}
2505impl From<InitializeRequest> for MessageFromClient {
2506 fn from(value: InitializeRequest) -> Self {
2507 MessageFromClient::RequestFromClient(value.into())
2508 }
2509}
2510impl From<PingRequest> for MessageFromClient {
2511 fn from(value: PingRequest) -> Self {
2512 MessageFromClient::RequestFromClient(value.into())
2513 }
2514}
2515impl From<ListResourcesRequest> for MessageFromClient {
2516 fn from(value: ListResourcesRequest) -> Self {
2517 MessageFromClient::RequestFromClient(value.into())
2518 }
2519}
2520impl From<ListResourceTemplatesRequest> for MessageFromClient {
2521 fn from(value: ListResourceTemplatesRequest) -> Self {
2522 MessageFromClient::RequestFromClient(value.into())
2523 }
2524}
2525impl From<ReadResourceRequest> for MessageFromClient {
2526 fn from(value: ReadResourceRequest) -> Self {
2527 MessageFromClient::RequestFromClient(value.into())
2528 }
2529}
2530impl From<SubscribeRequest> for MessageFromClient {
2531 fn from(value: SubscribeRequest) -> Self {
2532 MessageFromClient::RequestFromClient(value.into())
2533 }
2534}
2535impl From<UnsubscribeRequest> for MessageFromClient {
2536 fn from(value: UnsubscribeRequest) -> Self {
2537 MessageFromClient::RequestFromClient(value.into())
2538 }
2539}
2540impl From<ListPromptsRequest> for MessageFromClient {
2541 fn from(value: ListPromptsRequest) -> Self {
2542 MessageFromClient::RequestFromClient(value.into())
2543 }
2544}
2545impl From<GetPromptRequest> for MessageFromClient {
2546 fn from(value: GetPromptRequest) -> Self {
2547 MessageFromClient::RequestFromClient(value.into())
2548 }
2549}
2550impl From<ListToolsRequest> for MessageFromClient {
2551 fn from(value: ListToolsRequest) -> Self {
2552 MessageFromClient::RequestFromClient(value.into())
2553 }
2554}
2555impl From<CallToolRequest> for MessageFromClient {
2556 fn from(value: CallToolRequest) -> Self {
2557 MessageFromClient::RequestFromClient(value.into())
2558 }
2559}
2560impl From<GetTaskRequest> for MessageFromClient {
2561 fn from(value: GetTaskRequest) -> Self {
2562 MessageFromClient::RequestFromClient(value.into())
2563 }
2564}
2565impl From<GetTaskPayloadRequest> for MessageFromClient {
2566 fn from(value: GetTaskPayloadRequest) -> Self {
2567 MessageFromClient::RequestFromClient(value.into())
2568 }
2569}
2570impl From<CancelTaskRequest> for MessageFromClient {
2571 fn from(value: CancelTaskRequest) -> Self {
2572 MessageFromClient::RequestFromClient(value.into())
2573 }
2574}
2575impl From<ListTasksRequest> for MessageFromClient {
2576 fn from(value: ListTasksRequest) -> Self {
2577 MessageFromClient::RequestFromClient(value.into())
2578 }
2579}
2580impl From<SetLevelRequest> for MessageFromClient {
2581 fn from(value: SetLevelRequest) -> Self {
2582 MessageFromClient::RequestFromClient(value.into())
2583 }
2584}
2585impl From<CompleteRequest> for MessageFromClient {
2586 fn from(value: CompleteRequest) -> Self {
2587 MessageFromClient::RequestFromClient(value.into())
2588 }
2589}
2590impl From<CancelledNotification> for NotificationFromClient {
2591 fn from(value: CancelledNotification) -> Self {
2592 Self::ClientNotification(value.into())
2593 }
2594}
2595impl From<InitializedNotification> for NotificationFromClient {
2596 fn from(value: InitializedNotification) -> Self {
2597 Self::ClientNotification(value.into())
2598 }
2599}
2600impl From<ProgressNotification> for NotificationFromClient {
2601 fn from(value: ProgressNotification) -> Self {
2602 Self::ClientNotification(value.into())
2603 }
2604}
2605impl From<TaskStatusNotification> for NotificationFromClient {
2606 fn from(value: TaskStatusNotification) -> Self {
2607 Self::ClientNotification(value.into())
2608 }
2609}
2610impl From<RootsListChangedNotification> for NotificationFromClient {
2611 fn from(value: RootsListChangedNotification) -> Self {
2612 Self::ClientNotification(value.into())
2613 }
2614}
2615impl From<CancelledNotification> for ClientJsonrpcNotification {
2616 fn from(value: CancelledNotification) -> Self {
2617 Self::new(value.into())
2618 }
2619}
2620impl From<InitializedNotification> for ClientJsonrpcNotification {
2621 fn from(value: InitializedNotification) -> Self {
2622 Self::new(value.into())
2623 }
2624}
2625impl From<ProgressNotification> for ClientJsonrpcNotification {
2626 fn from(value: ProgressNotification) -> Self {
2627 Self::new(value.into())
2628 }
2629}
2630impl From<TaskStatusNotification> for ClientJsonrpcNotification {
2631 fn from(value: TaskStatusNotification) -> Self {
2632 Self::new(value.into())
2633 }
2634}
2635impl From<RootsListChangedNotification> for ClientJsonrpcNotification {
2636 fn from(value: RootsListChangedNotification) -> Self {
2637 Self::new(value.into())
2638 }
2639}
2640impl From<CancelledNotification> for MessageFromClient {
2641 fn from(value: CancelledNotification) -> Self {
2642 MessageFromClient::NotificationFromClient(value.into())
2643 }
2644}
2645impl From<InitializedNotification> for MessageFromClient {
2646 fn from(value: InitializedNotification) -> Self {
2647 MessageFromClient::NotificationFromClient(value.into())
2648 }
2649}
2650impl From<ProgressNotification> for MessageFromClient {
2651 fn from(value: ProgressNotification) -> Self {
2652 MessageFromClient::NotificationFromClient(value.into())
2653 }
2654}
2655impl From<TaskStatusNotification> for MessageFromClient {
2656 fn from(value: TaskStatusNotification) -> Self {
2657 MessageFromClient::NotificationFromClient(value.into())
2658 }
2659}
2660impl From<RootsListChangedNotification> for MessageFromClient {
2661 fn from(value: RootsListChangedNotification) -> Self {
2662 MessageFromClient::NotificationFromClient(value.into())
2663 }
2664}
2665impl From<Result> for ResultFromClient {
2666 fn from(value: Result) -> Self {
2667 Self::ClientResult(value.into())
2668 }
2669}
2670impl From<GetTaskResult> for ResultFromClient {
2671 fn from(value: GetTaskResult) -> Self {
2672 Self::ClientResult(value.into())
2673 }
2674}
2675impl From<GetTaskPayloadResult> for ResultFromClient {
2676 fn from(value: GetTaskPayloadResult) -> Self {
2677 Self::ClientResult(value.into())
2678 }
2679}
2680impl From<CancelTaskResult> for ResultFromClient {
2681 fn from(value: CancelTaskResult) -> Self {
2682 Self::ClientResult(value.into())
2683 }
2684}
2685impl From<ListTasksResult> for ResultFromClient {
2686 fn from(value: ListTasksResult) -> Self {
2687 Self::ClientResult(value.into())
2688 }
2689}
2690impl From<CreateMessageResult> for ResultFromClient {
2691 fn from(value: CreateMessageResult) -> Self {
2692 Self::ClientResult(value.into())
2693 }
2694}
2695impl From<ListRootsResult> for ResultFromClient {
2696 fn from(value: ListRootsResult) -> Self {
2697 Self::ClientResult(value.into())
2698 }
2699}
2700impl From<ElicitResult> for ResultFromClient {
2701 fn from(value: ElicitResult) -> Self {
2702 Self::ClientResult(value.into())
2703 }
2704}
2705impl From<Result> for MessageFromClient {
2706 fn from(value: Result) -> Self {
2707 MessageFromClient::ResultFromClient(value.into())
2708 }
2709}
2710impl From<GetTaskResult> for MessageFromClient {
2711 fn from(value: GetTaskResult) -> Self {
2712 MessageFromClient::ResultFromClient(value.into())
2713 }
2714}
2715impl From<GetTaskPayloadResult> for MessageFromClient {
2716 fn from(value: GetTaskPayloadResult) -> Self {
2717 MessageFromClient::ResultFromClient(value.into())
2718 }
2719}
2720impl From<CancelTaskResult> for MessageFromClient {
2721 fn from(value: CancelTaskResult) -> Self {
2722 MessageFromClient::ResultFromClient(value.into())
2723 }
2724}
2725impl From<ListTasksResult> for MessageFromClient {
2726 fn from(value: ListTasksResult) -> Self {
2727 MessageFromClient::ResultFromClient(value.into())
2728 }
2729}
2730impl From<CreateMessageResult> for MessageFromClient {
2731 fn from(value: CreateMessageResult) -> Self {
2732 MessageFromClient::ResultFromClient(value.into())
2733 }
2734}
2735impl From<ListRootsResult> for MessageFromClient {
2736 fn from(value: ListRootsResult) -> Self {
2737 MessageFromClient::ResultFromClient(value.into())
2738 }
2739}
2740impl From<ElicitResult> for MessageFromClient {
2741 fn from(value: ElicitResult) -> Self {
2742 MessageFromClient::ResultFromClient(value.into())
2743 }
2744}
2745#[allow(non_camel_case_types)]
2747pub enum SdkErrorCodes {
2748 CONNECTION_CLOSED = -32000,
2749 REQUEST_TIMEOUT = -32001,
2750 RESOURCE_NOT_FOUND = -32002,
2751 BAD_REQUEST = -32015,
2752 SESSION_NOT_FOUND = -32016,
2753 INVALID_REQUEST = -32600,
2754 METHOD_NOT_FOUND = -32601,
2755 INVALID_PARAMS = -32602,
2756 INTERNAL_ERROR = -32603,
2757 PARSE_ERROR = -32700,
2758 URL_ELICITATION_REQUIRED = -32042,
2759}
2760impl core::fmt::Display for SdkErrorCodes {
2761 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2762 match self {
2763 SdkErrorCodes::CONNECTION_CLOSED => write!(f, "Connection closed"),
2764 SdkErrorCodes::REQUEST_TIMEOUT => write!(f, "Request timeout"),
2765 SdkErrorCodes::INVALID_REQUEST => write!(f, "Invalid request"),
2766 SdkErrorCodes::METHOD_NOT_FOUND => write!(f, "Method not found"),
2767 SdkErrorCodes::INVALID_PARAMS => write!(f, "Invalid params"),
2768 SdkErrorCodes::INTERNAL_ERROR => write!(f, "Internal error"),
2769 SdkErrorCodes::PARSE_ERROR => write!(f, "Parse Error"),
2770 SdkErrorCodes::RESOURCE_NOT_FOUND => write!(f, "Resource not found"),
2771 SdkErrorCodes::BAD_REQUEST => write!(f, "Bad request"),
2772 SdkErrorCodes::SESSION_NOT_FOUND => write!(f, "Session not found"),
2773 SdkErrorCodes::URL_ELICITATION_REQUIRED => {
2774 write!(
2775 f,
2776 "A required URL was not provided. Please supply the requested URL to continue."
2777 )
2778 }
2779 }
2780 }
2781}
2782impl From<SdkErrorCodes> for i64 {
2783 fn from(code: SdkErrorCodes) -> Self {
2784 code as i64
2785 }
2786}
2787#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
2788pub struct SdkError {
2789 pub code: i64,
2791 pub data: ::std::option::Option<::serde_json::Value>,
2793 pub message: ::std::string::String,
2795}
2796impl core::fmt::Display for SdkError {
2797 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2798 write!(f, "MCP error {}: {}", self.code, self.message)
2799 }
2800}
2801impl std::error::Error for SdkError {
2802 fn description(&self) -> &str {
2803 &self.message
2804 }
2805}
2806impl SdkError {
2807 pub fn new(
2808 error_code: SdkErrorCodes,
2809 message: ::std::string::String,
2810 data: ::std::option::Option<::serde_json::Value>,
2811 ) -> Self {
2812 Self {
2813 code: error_code.into(),
2814 data,
2815 message,
2816 }
2817 }
2818 pub fn connection_closed() -> Self {
2819 Self {
2820 code: SdkErrorCodes::CONNECTION_CLOSED.into(),
2821 data: None,
2822 message: SdkErrorCodes::CONNECTION_CLOSED.to_string(),
2823 }
2824 }
2825 pub fn request_timeout(timeout: u128) -> Self {
2826 Self {
2827 code: SdkErrorCodes::REQUEST_TIMEOUT.into(),
2828 data: Some(json!({ "timeout" : timeout })),
2829 message: SdkErrorCodes::REQUEST_TIMEOUT.to_string(),
2830 }
2831 }
2832 pub fn session_not_found() -> Self {
2833 Self {
2834 code: SdkErrorCodes::SESSION_NOT_FOUND.into(),
2835 data: None,
2836 message: SdkErrorCodes::SESSION_NOT_FOUND.to_string(),
2837 }
2838 }
2839 pub fn invalid_request() -> Self {
2840 Self {
2841 code: SdkErrorCodes::INVALID_REQUEST.into(),
2842 data: None,
2843 message: SdkErrorCodes::INVALID_REQUEST.to_string(),
2844 }
2845 }
2846 pub fn method_not_found() -> Self {
2847 Self {
2848 code: SdkErrorCodes::METHOD_NOT_FOUND.into(),
2849 data: None,
2850 message: SdkErrorCodes::METHOD_NOT_FOUND.to_string(),
2851 }
2852 }
2853 pub fn invalid_params() -> Self {
2854 Self {
2855 code: SdkErrorCodes::INVALID_PARAMS.into(),
2856 data: None,
2857 message: SdkErrorCodes::INVALID_PARAMS.to_string(),
2858 }
2859 }
2860 pub fn internal_error() -> Self {
2861 Self {
2862 code: SdkErrorCodes::INTERNAL_ERROR.into(),
2863 data: None,
2864 message: SdkErrorCodes::INTERNAL_ERROR.to_string(),
2865 }
2866 }
2867 pub fn parse_error() -> Self {
2868 Self {
2869 code: SdkErrorCodes::PARSE_ERROR.into(),
2870 data: None,
2871 message: SdkErrorCodes::PARSE_ERROR.to_string(),
2872 }
2873 }
2874 pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
2881 Self {
2882 code: UrlElicitError::code_value(),
2883 data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
2884 json!(
2885 { "elicitations" : [], "error" :
2886 "failed to UrlElicitError data" }
2887 )
2888 })),
2889 message: "URL required. Please provide a URL.".to_string(),
2890 }
2891 }
2892 pub fn resource_not_found() -> Self {
2893 Self {
2894 code: SdkErrorCodes::RESOURCE_NOT_FOUND.into(),
2895 data: None,
2896 message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
2897 }
2898 }
2899 pub fn bad_request() -> Self {
2900 Self {
2901 code: SdkErrorCodes::BAD_REQUEST.into(),
2902 data: None,
2903 message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
2904 }
2905 }
2906 pub fn with_message(mut self, message: &str) -> Self {
2907 self.message = message.to_string();
2908 self
2909 }
2910 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
2911 self.data = data;
2912 self
2913 }
2914}
2915#[allow(non_camel_case_types)]
2917pub enum RpcErrorCodes {
2918 PARSE_ERROR = -32700isize,
2919 INVALID_REQUEST = -32600isize,
2920 METHOD_NOT_FOUND = -32601isize,
2921 INVALID_PARAMS = -32602isize,
2922 INTERNAL_ERROR = -32603isize,
2923 URL_ELICITATION_REQUIRED = -32042isize,
2924}
2925impl From<RpcErrorCodes> for i64 {
2926 fn from(code: RpcErrorCodes) -> Self {
2927 code as i64
2928 }
2929}
2930impl RpcError {
2931 pub fn new(
2948 error_code: RpcErrorCodes,
2949 message: ::std::string::String,
2950 data: ::std::option::Option<::serde_json::Value>,
2951 ) -> Self {
2952 Self {
2953 code: error_code.into(),
2954 data,
2955 message,
2956 }
2957 }
2958 pub fn method_not_found() -> Self {
2969 Self {
2970 code: RpcErrorCodes::METHOD_NOT_FOUND.into(),
2971 data: None,
2972 message: "Method not found".to_string(),
2973 }
2974 }
2975 pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
2982 Self {
2983 code: UrlElicitError::code_value(),
2984 data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
2985 json!(
2986 { "elicitations" : [], "error" :
2987 "failed to UrlElicitError data" }
2988 )
2989 })),
2990 message: "URL required. Please provide a URL.".to_string(),
2991 }
2992 }
2993 pub fn invalid_params() -> Self {
3003 Self {
3004 code: RpcErrorCodes::INVALID_PARAMS.into(),
3005 data: None,
3006 message: "Invalid params".to_string(),
3007 }
3008 }
3009 pub fn invalid_request() -> Self {
3019 Self {
3020 code: RpcErrorCodes::INVALID_REQUEST.into(),
3021 data: None,
3022 message: "Invalid request".to_string(),
3023 }
3024 }
3025 pub fn internal_error() -> Self {
3035 Self {
3036 code: RpcErrorCodes::INTERNAL_ERROR.into(),
3037 data: None,
3038 message: "Internal error".to_string(),
3039 }
3040 }
3041 pub fn parse_error() -> Self {
3051 Self {
3052 code: RpcErrorCodes::PARSE_ERROR.into(),
3053 data: None,
3054 message: "Parse error".to_string(),
3055 }
3056 }
3057 pub fn with_message(mut self, message: String) -> Self {
3067 self.message = message;
3068 self
3069 }
3070 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
3081 self.data = data;
3082 self
3083 }
3084}
3085impl std::error::Error for RpcError {
3086 fn description(&self) -> &str {
3087 &self.message
3088 }
3089}
3090impl Display for RpcError {
3091 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3092 write!(
3093 f,
3094 "{}",
3095 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
3096 )
3097 }
3098}
3099impl FromStr for RpcError {
3100 type Err = RpcError;
3101 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
3102 serde_json::from_str(s)
3103 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
3104 }
3105}
3106impl JsonrpcErrorResponse {
3108 pub fn create(
3109 id: Option<RequestId>,
3110 error_code: RpcErrorCodes,
3111 error_message: ::std::string::String,
3112 error_data: ::std::option::Option<::serde_json::Value>,
3113 ) -> Self {
3114 Self::new(RpcError::new(error_code, error_message, error_data), id)
3115 }
3116}
3117impl From<CancelledNotification> for NotificationFromServer {
3118 fn from(value: CancelledNotification) -> Self {
3119 Self::ServerNotification(value.into())
3120 }
3121}
3122impl From<ProgressNotification> for NotificationFromServer {
3123 fn from(value: ProgressNotification) -> Self {
3124 Self::ServerNotification(value.into())
3125 }
3126}
3127impl From<ResourceListChangedNotification> for NotificationFromServer {
3128 fn from(value: ResourceListChangedNotification) -> Self {
3129 Self::ServerNotification(value.into())
3130 }
3131}
3132impl From<ResourceUpdatedNotification> for NotificationFromServer {
3133 fn from(value: ResourceUpdatedNotification) -> Self {
3134 Self::ServerNotification(value.into())
3135 }
3136}
3137impl From<PromptListChangedNotification> for NotificationFromServer {
3138 fn from(value: PromptListChangedNotification) -> Self {
3139 Self::ServerNotification(value.into())
3140 }
3141}
3142impl From<ToolListChangedNotification> for NotificationFromServer {
3143 fn from(value: ToolListChangedNotification) -> Self {
3144 Self::ServerNotification(value.into())
3145 }
3146}
3147impl From<TaskStatusNotification> for NotificationFromServer {
3148 fn from(value: TaskStatusNotification) -> Self {
3149 Self::ServerNotification(value.into())
3150 }
3151}
3152impl From<LoggingMessageNotification> for NotificationFromServer {
3153 fn from(value: LoggingMessageNotification) -> Self {
3154 Self::ServerNotification(value.into())
3155 }
3156}
3157impl From<ElicitationCompleteNotification> for NotificationFromServer {
3158 fn from(value: ElicitationCompleteNotification) -> Self {
3159 Self::ServerNotification(value.into())
3160 }
3161}
3162impl From<CancelledNotification> for ServerJsonrpcNotification {
3163 fn from(value: CancelledNotification) -> Self {
3164 Self::new(value.into())
3165 }
3166}
3167impl From<ProgressNotification> for ServerJsonrpcNotification {
3168 fn from(value: ProgressNotification) -> Self {
3169 Self::new(value.into())
3170 }
3171}
3172impl From<ResourceListChangedNotification> for ServerJsonrpcNotification {
3173 fn from(value: ResourceListChangedNotification) -> Self {
3174 Self::new(value.into())
3175 }
3176}
3177impl From<ResourceUpdatedNotification> for ServerJsonrpcNotification {
3178 fn from(value: ResourceUpdatedNotification) -> Self {
3179 Self::new(value.into())
3180 }
3181}
3182impl From<PromptListChangedNotification> for ServerJsonrpcNotification {
3183 fn from(value: PromptListChangedNotification) -> Self {
3184 Self::new(value.into())
3185 }
3186}
3187impl From<ToolListChangedNotification> for ServerJsonrpcNotification {
3188 fn from(value: ToolListChangedNotification) -> Self {
3189 Self::new(value.into())
3190 }
3191}
3192impl From<TaskStatusNotification> for ServerJsonrpcNotification {
3193 fn from(value: TaskStatusNotification) -> Self {
3194 Self::new(value.into())
3195 }
3196}
3197impl From<LoggingMessageNotification> for ServerJsonrpcNotification {
3198 fn from(value: LoggingMessageNotification) -> Self {
3199 Self::new(value.into())
3200 }
3201}
3202impl From<ElicitationCompleteNotification> for ServerJsonrpcNotification {
3203 fn from(value: ElicitationCompleteNotification) -> Self {
3204 Self::new(value.into())
3205 }
3206}
3207impl From<CancelledNotification> for MessageFromServer {
3208 fn from(value: CancelledNotification) -> Self {
3209 MessageFromServer::NotificationFromServer(value.into())
3210 }
3211}
3212impl From<ProgressNotification> for MessageFromServer {
3213 fn from(value: ProgressNotification) -> Self {
3214 MessageFromServer::NotificationFromServer(value.into())
3215 }
3216}
3217impl From<ResourceListChangedNotification> for MessageFromServer {
3218 fn from(value: ResourceListChangedNotification) -> Self {
3219 MessageFromServer::NotificationFromServer(value.into())
3220 }
3221}
3222impl From<ResourceUpdatedNotification> for MessageFromServer {
3223 fn from(value: ResourceUpdatedNotification) -> Self {
3224 MessageFromServer::NotificationFromServer(value.into())
3225 }
3226}
3227impl From<PromptListChangedNotification> for MessageFromServer {
3228 fn from(value: PromptListChangedNotification) -> Self {
3229 MessageFromServer::NotificationFromServer(value.into())
3230 }
3231}
3232impl From<ToolListChangedNotification> for MessageFromServer {
3233 fn from(value: ToolListChangedNotification) -> Self {
3234 MessageFromServer::NotificationFromServer(value.into())
3235 }
3236}
3237impl From<TaskStatusNotification> for MessageFromServer {
3238 fn from(value: TaskStatusNotification) -> Self {
3239 MessageFromServer::NotificationFromServer(value.into())
3240 }
3241}
3242impl From<LoggingMessageNotification> for MessageFromServer {
3243 fn from(value: LoggingMessageNotification) -> Self {
3244 MessageFromServer::NotificationFromServer(value.into())
3245 }
3246}
3247impl From<ElicitationCompleteNotification> for MessageFromServer {
3248 fn from(value: ElicitationCompleteNotification) -> Self {
3249 MessageFromServer::NotificationFromServer(value.into())
3250 }
3251}
3252impl From<PingRequest> for RequestFromServer {
3253 fn from(value: PingRequest) -> Self {
3254 Self::ServerRequest(value.into())
3255 }
3256}
3257impl From<GetTaskRequest> for RequestFromServer {
3258 fn from(value: GetTaskRequest) -> Self {
3259 Self::ServerRequest(value.into())
3260 }
3261}
3262impl From<GetTaskPayloadRequest> for RequestFromServer {
3263 fn from(value: GetTaskPayloadRequest) -> Self {
3264 Self::ServerRequest(value.into())
3265 }
3266}
3267impl From<CancelTaskRequest> for RequestFromServer {
3268 fn from(value: CancelTaskRequest) -> Self {
3269 Self::ServerRequest(value.into())
3270 }
3271}
3272impl From<ListTasksRequest> for RequestFromServer {
3273 fn from(value: ListTasksRequest) -> Self {
3274 Self::ServerRequest(value.into())
3275 }
3276}
3277impl From<CreateMessageRequest> for RequestFromServer {
3278 fn from(value: CreateMessageRequest) -> Self {
3279 Self::ServerRequest(value.into())
3280 }
3281}
3282impl From<ListRootsRequest> for RequestFromServer {
3283 fn from(value: ListRootsRequest) -> Self {
3284 Self::ServerRequest(value.into())
3285 }
3286}
3287impl From<ElicitRequest> for RequestFromServer {
3288 fn from(value: ElicitRequest) -> Self {
3289 Self::ServerRequest(value.into())
3290 }
3291}
3292impl From<PingRequest> for MessageFromServer {
3293 fn from(value: PingRequest) -> Self {
3294 MessageFromServer::RequestFromServer(value.into())
3295 }
3296}
3297impl From<GetTaskRequest> for MessageFromServer {
3298 fn from(value: GetTaskRequest) -> Self {
3299 MessageFromServer::RequestFromServer(value.into())
3300 }
3301}
3302impl From<GetTaskPayloadRequest> for MessageFromServer {
3303 fn from(value: GetTaskPayloadRequest) -> Self {
3304 MessageFromServer::RequestFromServer(value.into())
3305 }
3306}
3307impl From<CancelTaskRequest> for MessageFromServer {
3308 fn from(value: CancelTaskRequest) -> Self {
3309 MessageFromServer::RequestFromServer(value.into())
3310 }
3311}
3312impl From<ListTasksRequest> for MessageFromServer {
3313 fn from(value: ListTasksRequest) -> Self {
3314 MessageFromServer::RequestFromServer(value.into())
3315 }
3316}
3317impl From<CreateMessageRequest> for MessageFromServer {
3318 fn from(value: CreateMessageRequest) -> Self {
3319 MessageFromServer::RequestFromServer(value.into())
3320 }
3321}
3322impl From<ListRootsRequest> for MessageFromServer {
3323 fn from(value: ListRootsRequest) -> Self {
3324 MessageFromServer::RequestFromServer(value.into())
3325 }
3326}
3327impl From<ElicitRequest> for MessageFromServer {
3328 fn from(value: ElicitRequest) -> Self {
3329 MessageFromServer::RequestFromServer(value.into())
3330 }
3331}
3332impl From<Result> for ResultFromServer {
3333 fn from(value: Result) -> Self {
3334 Self::ServerResult(value.into())
3335 }
3336}
3337impl From<InitializeResult> for ResultFromServer {
3338 fn from(value: InitializeResult) -> Self {
3339 Self::ServerResult(value.into())
3340 }
3341}
3342impl From<ListResourcesResult> for ResultFromServer {
3343 fn from(value: ListResourcesResult) -> Self {
3344 Self::ServerResult(value.into())
3345 }
3346}
3347impl From<ListResourceTemplatesResult> for ResultFromServer {
3348 fn from(value: ListResourceTemplatesResult) -> Self {
3349 Self::ServerResult(value.into())
3350 }
3351}
3352impl From<ReadResourceResult> for ResultFromServer {
3353 fn from(value: ReadResourceResult) -> Self {
3354 Self::ServerResult(value.into())
3355 }
3356}
3357impl From<ListPromptsResult> for ResultFromServer {
3358 fn from(value: ListPromptsResult) -> Self {
3359 Self::ServerResult(value.into())
3360 }
3361}
3362impl From<GetPromptResult> for ResultFromServer {
3363 fn from(value: GetPromptResult) -> Self {
3364 Self::ServerResult(value.into())
3365 }
3366}
3367impl From<ListToolsResult> for ResultFromServer {
3368 fn from(value: ListToolsResult) -> Self {
3369 Self::ServerResult(value.into())
3370 }
3371}
3372impl From<CallToolResult> for ResultFromServer {
3373 fn from(value: CallToolResult) -> Self {
3374 Self::ServerResult(value.into())
3375 }
3376}
3377impl From<GetTaskResult> for ResultFromServer {
3378 fn from(value: GetTaskResult) -> Self {
3379 Self::ServerResult(value.into())
3380 }
3381}
3382impl From<GetTaskPayloadResult> for ResultFromServer {
3383 fn from(value: GetTaskPayloadResult) -> Self {
3384 Self::ServerResult(value.into())
3385 }
3386}
3387impl From<CancelTaskResult> for ResultFromServer {
3388 fn from(value: CancelTaskResult) -> Self {
3389 Self::ServerResult(value.into())
3390 }
3391}
3392impl From<ListTasksResult> for ResultFromServer {
3393 fn from(value: ListTasksResult) -> Self {
3394 Self::ServerResult(value.into())
3395 }
3396}
3397impl From<CompleteResult> for ResultFromServer {
3398 fn from(value: CompleteResult) -> Self {
3399 Self::ServerResult(value.into())
3400 }
3401}
3402impl From<Result> for MessageFromServer {
3403 fn from(value: Result) -> Self {
3404 MessageFromServer::ResultFromServer(value.into())
3405 }
3406}
3407impl From<InitializeResult> for MessageFromServer {
3408 fn from(value: InitializeResult) -> Self {
3409 MessageFromServer::ResultFromServer(value.into())
3410 }
3411}
3412impl From<ListResourcesResult> for MessageFromServer {
3413 fn from(value: ListResourcesResult) -> Self {
3414 MessageFromServer::ResultFromServer(value.into())
3415 }
3416}
3417impl From<ListResourceTemplatesResult> for MessageFromServer {
3418 fn from(value: ListResourceTemplatesResult) -> Self {
3419 MessageFromServer::ResultFromServer(value.into())
3420 }
3421}
3422impl From<ReadResourceResult> for MessageFromServer {
3423 fn from(value: ReadResourceResult) -> Self {
3424 MessageFromServer::ResultFromServer(value.into())
3425 }
3426}
3427impl From<ListPromptsResult> for MessageFromServer {
3428 fn from(value: ListPromptsResult) -> Self {
3429 MessageFromServer::ResultFromServer(value.into())
3430 }
3431}
3432impl From<GetPromptResult> for MessageFromServer {
3433 fn from(value: GetPromptResult) -> Self {
3434 MessageFromServer::ResultFromServer(value.into())
3435 }
3436}
3437impl From<ListToolsResult> for MessageFromServer {
3438 fn from(value: ListToolsResult) -> Self {
3439 MessageFromServer::ResultFromServer(value.into())
3440 }
3441}
3442impl From<CallToolResult> for MessageFromServer {
3443 fn from(value: CallToolResult) -> Self {
3444 MessageFromServer::ResultFromServer(value.into())
3445 }
3446}
3447impl From<GetTaskResult> for MessageFromServer {
3448 fn from(value: GetTaskResult) -> Self {
3449 MessageFromServer::ResultFromServer(value.into())
3450 }
3451}
3452impl From<GetTaskPayloadResult> for MessageFromServer {
3453 fn from(value: GetTaskPayloadResult) -> Self {
3454 MessageFromServer::ResultFromServer(value.into())
3455 }
3456}
3457impl From<CancelTaskResult> for MessageFromServer {
3458 fn from(value: CancelTaskResult) -> Self {
3459 MessageFromServer::ResultFromServer(value.into())
3460 }
3461}
3462impl From<ListTasksResult> for MessageFromServer {
3463 fn from(value: ListTasksResult) -> Self {
3464 MessageFromServer::ResultFromServer(value.into())
3465 }
3466}
3467impl From<CompleteResult> for MessageFromServer {
3468 fn from(value: CompleteResult) -> Self {
3469 MessageFromServer::ResultFromServer(value.into())
3470 }
3471}
3472impl FromMessage<InitializeRequest> for ClientMessage {
3473 fn from_message(message: InitializeRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3474 let request_id =
3475 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3476 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3477 }
3478}
3479impl ToMessage<ClientMessage> for InitializeRequest {
3480 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3481 ClientMessage::from_message(self, request_id)
3482 }
3483}
3484impl FromMessage<PingRequest> for ClientMessage {
3485 fn from_message(message: PingRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3486 let request_id =
3487 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3488 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3489 }
3490}
3491impl ToMessage<ClientMessage> for PingRequest {
3492 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3493 ClientMessage::from_message(self, request_id)
3494 }
3495}
3496impl FromMessage<ListResourcesRequest> for ClientMessage {
3497 fn from_message(message: ListResourcesRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3498 let request_id =
3499 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3500 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3501 }
3502}
3503impl ToMessage<ClientMessage> for ListResourcesRequest {
3504 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3505 ClientMessage::from_message(self, request_id)
3506 }
3507}
3508impl FromMessage<ListResourceTemplatesRequest> for ClientMessage {
3509 fn from_message(
3510 message: ListResourceTemplatesRequest,
3511 request_id: Option<RequestId>,
3512 ) -> std::result::Result<Self, RpcError> {
3513 let request_id =
3514 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3515 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3516 }
3517}
3518impl ToMessage<ClientMessage> for ListResourceTemplatesRequest {
3519 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3520 ClientMessage::from_message(self, request_id)
3521 }
3522}
3523impl FromMessage<ReadResourceRequest> for ClientMessage {
3524 fn from_message(message: ReadResourceRequest, 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(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3528 }
3529}
3530impl ToMessage<ClientMessage> for ReadResourceRequest {
3531 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3532 ClientMessage::from_message(self, request_id)
3533 }
3534}
3535impl FromMessage<SubscribeRequest> for ClientMessage {
3536 fn from_message(message: SubscribeRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3537 let request_id =
3538 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3539 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3540 }
3541}
3542impl ToMessage<ClientMessage> for SubscribeRequest {
3543 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3544 ClientMessage::from_message(self, request_id)
3545 }
3546}
3547impl FromMessage<UnsubscribeRequest> for ClientMessage {
3548 fn from_message(message: UnsubscribeRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3549 let request_id =
3550 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3551 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3552 }
3553}
3554impl ToMessage<ClientMessage> for UnsubscribeRequest {
3555 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3556 ClientMessage::from_message(self, request_id)
3557 }
3558}
3559impl FromMessage<ListPromptsRequest> for ClientMessage {
3560 fn from_message(message: ListPromptsRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3561 let request_id =
3562 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3563 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3564 }
3565}
3566impl ToMessage<ClientMessage> for ListPromptsRequest {
3567 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3568 ClientMessage::from_message(self, request_id)
3569 }
3570}
3571impl FromMessage<GetPromptRequest> for ClientMessage {
3572 fn from_message(message: GetPromptRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3573 let request_id =
3574 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3575 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3576 }
3577}
3578impl ToMessage<ClientMessage> for GetPromptRequest {
3579 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3580 ClientMessage::from_message(self, request_id)
3581 }
3582}
3583impl FromMessage<ListToolsRequest> for ClientMessage {
3584 fn from_message(message: ListToolsRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3585 let request_id =
3586 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3587 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3588 }
3589}
3590impl ToMessage<ClientMessage> for ListToolsRequest {
3591 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3592 ClientMessage::from_message(self, request_id)
3593 }
3594}
3595impl FromMessage<CallToolRequest> for ClientMessage {
3596 fn from_message(message: CallToolRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3597 let request_id =
3598 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3599 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3600 }
3601}
3602impl ToMessage<ClientMessage> for CallToolRequest {
3603 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3604 ClientMessage::from_message(self, request_id)
3605 }
3606}
3607impl FromMessage<GetTaskRequest> for ClientMessage {
3608 fn from_message(message: GetTaskRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3609 let request_id =
3610 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3611 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3612 }
3613}
3614impl ToMessage<ClientMessage> for GetTaskRequest {
3615 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3616 ClientMessage::from_message(self, request_id)
3617 }
3618}
3619impl FromMessage<GetTaskPayloadRequest> for ClientMessage {
3620 fn from_message(message: GetTaskPayloadRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3621 let request_id =
3622 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3623 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3624 }
3625}
3626impl ToMessage<ClientMessage> for GetTaskPayloadRequest {
3627 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3628 ClientMessage::from_message(self, request_id)
3629 }
3630}
3631impl FromMessage<CancelTaskRequest> for ClientMessage {
3632 fn from_message(message: CancelTaskRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3633 let request_id =
3634 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3635 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3636 }
3637}
3638impl ToMessage<ClientMessage> for CancelTaskRequest {
3639 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3640 ClientMessage::from_message(self, request_id)
3641 }
3642}
3643impl FromMessage<ListTasksRequest> for ClientMessage {
3644 fn from_message(message: ListTasksRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3645 let request_id =
3646 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3647 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3648 }
3649}
3650impl ToMessage<ClientMessage> for ListTasksRequest {
3651 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3652 ClientMessage::from_message(self, request_id)
3653 }
3654}
3655impl FromMessage<SetLevelRequest> for ClientMessage {
3656 fn from_message(message: SetLevelRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3657 let request_id =
3658 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3659 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3660 }
3661}
3662impl ToMessage<ClientMessage> for SetLevelRequest {
3663 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3664 ClientMessage::from_message(self, request_id)
3665 }
3666}
3667impl FromMessage<CompleteRequest> for ClientMessage {
3668 fn from_message(message: CompleteRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3669 let request_id =
3670 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3671 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(request_id, message.into())))
3672 }
3673}
3674impl ToMessage<ClientMessage> for CompleteRequest {
3675 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3676 ClientMessage::from_message(self, request_id)
3677 }
3678}
3679impl FromMessage<Result> for ClientMessage {
3680 fn from_message(message: Result, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3681 let request_id =
3682 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3683 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3684 request_id,
3685 message.into(),
3686 )))
3687 }
3688}
3689impl ToMessage<ClientMessage> for Result {
3690 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3691 ClientMessage::from_message(self, request_id)
3692 }
3693}
3694impl FromMessage<GetTaskResult> for ClientMessage {
3695 fn from_message(message: GetTaskResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3696 let request_id =
3697 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3698 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3699 request_id,
3700 message.into(),
3701 )))
3702 }
3703}
3704impl ToMessage<ClientMessage> for GetTaskResult {
3705 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3706 ClientMessage::from_message(self, request_id)
3707 }
3708}
3709impl FromMessage<GetTaskPayloadResult> for ClientMessage {
3710 fn from_message(message: GetTaskPayloadResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3711 let request_id =
3712 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3713 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3714 request_id,
3715 message.into(),
3716 )))
3717 }
3718}
3719impl ToMessage<ClientMessage> for GetTaskPayloadResult {
3720 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3721 ClientMessage::from_message(self, request_id)
3722 }
3723}
3724impl FromMessage<CancelTaskResult> for ClientMessage {
3725 fn from_message(message: CancelTaskResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3726 let request_id =
3727 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3728 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3729 request_id,
3730 message.into(),
3731 )))
3732 }
3733}
3734impl ToMessage<ClientMessage> for CancelTaskResult {
3735 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3736 ClientMessage::from_message(self, request_id)
3737 }
3738}
3739impl FromMessage<ListTasksResult> for ClientMessage {
3740 fn from_message(message: ListTasksResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3741 let request_id =
3742 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3743 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3744 request_id,
3745 message.into(),
3746 )))
3747 }
3748}
3749impl ToMessage<ClientMessage> for ListTasksResult {
3750 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3751 ClientMessage::from_message(self, request_id)
3752 }
3753}
3754impl FromMessage<CreateMessageResult> for ClientMessage {
3755 fn from_message(message: CreateMessageResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3756 let request_id =
3757 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3758 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3759 request_id,
3760 message.into(),
3761 )))
3762 }
3763}
3764impl ToMessage<ClientMessage> for CreateMessageResult {
3765 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3766 ClientMessage::from_message(self, request_id)
3767 }
3768}
3769impl FromMessage<ListRootsResult> for ClientMessage {
3770 fn from_message(message: ListRootsResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3771 let request_id =
3772 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3773 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3774 request_id,
3775 message.into(),
3776 )))
3777 }
3778}
3779impl ToMessage<ClientMessage> for ListRootsResult {
3780 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3781 ClientMessage::from_message(self, request_id)
3782 }
3783}
3784impl FromMessage<ElicitResult> for ClientMessage {
3785 fn from_message(message: ElicitResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3786 let request_id =
3787 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3788 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
3789 request_id,
3790 message.into(),
3791 )))
3792 }
3793}
3794impl ToMessage<ClientMessage> for ElicitResult {
3795 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3796 ClientMessage::from_message(self, request_id)
3797 }
3798}
3799impl FromMessage<CancelledNotification> for ClientMessage {
3800 fn from_message(message: CancelledNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3801 if request_id.is_some() {
3802 return Err(
3803 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3804 );
3805 }
3806 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
3807 }
3808}
3809impl ToMessage<ClientMessage> for CancelledNotification {
3810 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3811 ClientMessage::from_message(self, request_id)
3812 }
3813}
3814impl FromMessage<InitializedNotification> for ClientMessage {
3815 fn from_message(message: InitializedNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3816 if request_id.is_some() {
3817 return Err(
3818 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3819 );
3820 }
3821 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
3822 }
3823}
3824impl ToMessage<ClientMessage> for InitializedNotification {
3825 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3826 ClientMessage::from_message(self, request_id)
3827 }
3828}
3829impl FromMessage<ProgressNotification> for ClientMessage {
3830 fn from_message(message: ProgressNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3831 if request_id.is_some() {
3832 return Err(
3833 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3834 );
3835 }
3836 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
3837 }
3838}
3839impl ToMessage<ClientMessage> for ProgressNotification {
3840 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3841 ClientMessage::from_message(self, request_id)
3842 }
3843}
3844impl FromMessage<TaskStatusNotification> for ClientMessage {
3845 fn from_message(message: TaskStatusNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3846 if request_id.is_some() {
3847 return Err(
3848 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3849 );
3850 }
3851 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
3852 }
3853}
3854impl ToMessage<ClientMessage> for TaskStatusNotification {
3855 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3856 ClientMessage::from_message(self, request_id)
3857 }
3858}
3859impl FromMessage<RootsListChangedNotification> for ClientMessage {
3860 fn from_message(
3861 message: RootsListChangedNotification,
3862 request_id: Option<RequestId>,
3863 ) -> std::result::Result<Self, RpcError> {
3864 if request_id.is_some() {
3865 return Err(
3866 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
3867 );
3868 }
3869 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(message.into())))
3870 }
3871}
3872impl ToMessage<ClientMessage> for RootsListChangedNotification {
3873 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ClientMessage, RpcError> {
3874 ClientMessage::from_message(self, request_id)
3875 }
3876}
3877impl FromMessage<PingRequest> for ServerMessage {
3878 fn from_message(message: PingRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3879 let request_id =
3880 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3881 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3882 }
3883}
3884impl ToMessage<ServerMessage> for PingRequest {
3885 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3886 ServerMessage::from_message(self, request_id)
3887 }
3888}
3889impl FromMessage<GetTaskRequest> for ServerMessage {
3890 fn from_message(message: GetTaskRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3891 let request_id =
3892 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3893 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3894 }
3895}
3896impl ToMessage<ServerMessage> for GetTaskRequest {
3897 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3898 ServerMessage::from_message(self, request_id)
3899 }
3900}
3901impl FromMessage<GetTaskPayloadRequest> for ServerMessage {
3902 fn from_message(message: GetTaskPayloadRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3903 let request_id =
3904 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3905 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3906 }
3907}
3908impl ToMessage<ServerMessage> for GetTaskPayloadRequest {
3909 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3910 ServerMessage::from_message(self, request_id)
3911 }
3912}
3913impl FromMessage<CancelTaskRequest> for ServerMessage {
3914 fn from_message(message: CancelTaskRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3915 let request_id =
3916 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3917 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3918 }
3919}
3920impl ToMessage<ServerMessage> for CancelTaskRequest {
3921 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3922 ServerMessage::from_message(self, request_id)
3923 }
3924}
3925impl FromMessage<ListTasksRequest> for ServerMessage {
3926 fn from_message(message: ListTasksRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3927 let request_id =
3928 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3929 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3930 }
3931}
3932impl ToMessage<ServerMessage> for ListTasksRequest {
3933 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3934 ServerMessage::from_message(self, request_id)
3935 }
3936}
3937impl FromMessage<CreateMessageRequest> for ServerMessage {
3938 fn from_message(message: CreateMessageRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3939 let request_id =
3940 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3941 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3942 }
3943}
3944impl ToMessage<ServerMessage> for CreateMessageRequest {
3945 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3946 ServerMessage::from_message(self, request_id)
3947 }
3948}
3949impl FromMessage<ListRootsRequest> for ServerMessage {
3950 fn from_message(message: ListRootsRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3951 let request_id =
3952 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3953 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3954 }
3955}
3956impl ToMessage<ServerMessage> for ListRootsRequest {
3957 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3958 ServerMessage::from_message(self, request_id)
3959 }
3960}
3961impl FromMessage<ElicitRequest> for ServerMessage {
3962 fn from_message(message: ElicitRequest, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3963 let request_id =
3964 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3965 Ok(ServerMessage::Request(ServerJsonrpcRequest::new(request_id, message.into())))
3966 }
3967}
3968impl ToMessage<ServerMessage> for ElicitRequest {
3969 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3970 ServerMessage::from_message(self, request_id)
3971 }
3972}
3973impl FromMessage<Result> for ServerMessage {
3974 fn from_message(message: Result, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3975 let request_id =
3976 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3977 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3978 request_id,
3979 message.into(),
3980 )))
3981 }
3982}
3983impl ToMessage<ServerMessage> for Result {
3984 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
3985 ServerMessage::from_message(self, request_id)
3986 }
3987}
3988impl FromMessage<InitializeResult> for ServerMessage {
3989 fn from_message(message: InitializeResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
3990 let request_id =
3991 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
3992 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
3993 request_id,
3994 message.into(),
3995 )))
3996 }
3997}
3998impl ToMessage<ServerMessage> for InitializeResult {
3999 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4000 ServerMessage::from_message(self, request_id)
4001 }
4002}
4003impl FromMessage<ListResourcesResult> for ServerMessage {
4004 fn from_message(message: ListResourcesResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4005 let request_id =
4006 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4007 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4008 request_id,
4009 message.into(),
4010 )))
4011 }
4012}
4013impl ToMessage<ServerMessage> for ListResourcesResult {
4014 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4015 ServerMessage::from_message(self, request_id)
4016 }
4017}
4018impl FromMessage<ListResourceTemplatesResult> for ServerMessage {
4019 fn from_message(
4020 message: ListResourceTemplatesResult,
4021 request_id: Option<RequestId>,
4022 ) -> std::result::Result<Self, RpcError> {
4023 let request_id =
4024 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4025 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4026 request_id,
4027 message.into(),
4028 )))
4029 }
4030}
4031impl ToMessage<ServerMessage> for ListResourceTemplatesResult {
4032 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4033 ServerMessage::from_message(self, request_id)
4034 }
4035}
4036impl FromMessage<ReadResourceResult> for ServerMessage {
4037 fn from_message(message: ReadResourceResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4038 let request_id =
4039 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4040 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4041 request_id,
4042 message.into(),
4043 )))
4044 }
4045}
4046impl ToMessage<ServerMessage> for ReadResourceResult {
4047 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4048 ServerMessage::from_message(self, request_id)
4049 }
4050}
4051impl FromMessage<ListPromptsResult> for ServerMessage {
4052 fn from_message(message: ListPromptsResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4053 let request_id =
4054 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4055 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4056 request_id,
4057 message.into(),
4058 )))
4059 }
4060}
4061impl ToMessage<ServerMessage> for ListPromptsResult {
4062 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4063 ServerMessage::from_message(self, request_id)
4064 }
4065}
4066impl FromMessage<GetPromptResult> for ServerMessage {
4067 fn from_message(message: GetPromptResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4068 let request_id =
4069 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4070 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4071 request_id,
4072 message.into(),
4073 )))
4074 }
4075}
4076impl ToMessage<ServerMessage> for GetPromptResult {
4077 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4078 ServerMessage::from_message(self, request_id)
4079 }
4080}
4081impl FromMessage<ListToolsResult> for ServerMessage {
4082 fn from_message(message: ListToolsResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4083 let request_id =
4084 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4085 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4086 request_id,
4087 message.into(),
4088 )))
4089 }
4090}
4091impl ToMessage<ServerMessage> for ListToolsResult {
4092 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4093 ServerMessage::from_message(self, request_id)
4094 }
4095}
4096impl FromMessage<CallToolResult> for ServerMessage {
4097 fn from_message(message: CallToolResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4098 let request_id =
4099 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4100 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4101 request_id,
4102 message.into(),
4103 )))
4104 }
4105}
4106impl ToMessage<ServerMessage> for CallToolResult {
4107 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4108 ServerMessage::from_message(self, request_id)
4109 }
4110}
4111impl FromMessage<GetTaskResult> for ServerMessage {
4112 fn from_message(message: GetTaskResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4113 let request_id =
4114 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4115 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4116 request_id,
4117 message.into(),
4118 )))
4119 }
4120}
4121impl ToMessage<ServerMessage> for GetTaskResult {
4122 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4123 ServerMessage::from_message(self, request_id)
4124 }
4125}
4126impl FromMessage<GetTaskPayloadResult> for ServerMessage {
4127 fn from_message(message: GetTaskPayloadResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4128 let request_id =
4129 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4130 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4131 request_id,
4132 message.into(),
4133 )))
4134 }
4135}
4136impl ToMessage<ServerMessage> for GetTaskPayloadResult {
4137 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4138 ServerMessage::from_message(self, request_id)
4139 }
4140}
4141impl FromMessage<CancelTaskResult> for ServerMessage {
4142 fn from_message(message: CancelTaskResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4143 let request_id =
4144 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4145 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4146 request_id,
4147 message.into(),
4148 )))
4149 }
4150}
4151impl ToMessage<ServerMessage> for CancelTaskResult {
4152 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4153 ServerMessage::from_message(self, request_id)
4154 }
4155}
4156impl FromMessage<ListTasksResult> for ServerMessage {
4157 fn from_message(message: ListTasksResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4158 let request_id =
4159 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4160 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4161 request_id,
4162 message.into(),
4163 )))
4164 }
4165}
4166impl ToMessage<ServerMessage> for ListTasksResult {
4167 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4168 ServerMessage::from_message(self, request_id)
4169 }
4170}
4171impl FromMessage<CompleteResult> for ServerMessage {
4172 fn from_message(message: CompleteResult, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4173 let request_id =
4174 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
4175 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
4176 request_id,
4177 message.into(),
4178 )))
4179 }
4180}
4181impl ToMessage<ServerMessage> for CompleteResult {
4182 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4183 ServerMessage::from_message(self, request_id)
4184 }
4185}
4186impl FromMessage<CancelledNotification> for ServerMessage {
4187 fn from_message(message: CancelledNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4188 if request_id.is_some() {
4189 return Err(
4190 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
4191 );
4192 }
4193 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
4194 }
4195}
4196impl ToMessage<ServerMessage> for CancelledNotification {
4197 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4198 ServerMessage::from_message(self, request_id)
4199 }
4200}
4201impl FromMessage<ProgressNotification> for ServerMessage {
4202 fn from_message(message: ProgressNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4203 if request_id.is_some() {
4204 return Err(
4205 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
4206 );
4207 }
4208 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
4209 }
4210}
4211impl ToMessage<ServerMessage> for ProgressNotification {
4212 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4213 ServerMessage::from_message(self, request_id)
4214 }
4215}
4216impl FromMessage<ResourceListChangedNotification> for ServerMessage {
4217 fn from_message(
4218 message: ResourceListChangedNotification,
4219 request_id: Option<RequestId>,
4220 ) -> std::result::Result<Self, RpcError> {
4221 if request_id.is_some() {
4222 return Err(
4223 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
4224 );
4225 }
4226 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
4227 }
4228}
4229impl ToMessage<ServerMessage> for ResourceListChangedNotification {
4230 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4231 ServerMessage::from_message(self, request_id)
4232 }
4233}
4234impl FromMessage<ResourceUpdatedNotification> for ServerMessage {
4235 fn from_message(
4236 message: ResourceUpdatedNotification,
4237 request_id: Option<RequestId>,
4238 ) -> std::result::Result<Self, RpcError> {
4239 if request_id.is_some() {
4240 return Err(
4241 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
4242 );
4243 }
4244 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
4245 }
4246}
4247impl ToMessage<ServerMessage> for ResourceUpdatedNotification {
4248 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4249 ServerMessage::from_message(self, request_id)
4250 }
4251}
4252impl FromMessage<PromptListChangedNotification> for ServerMessage {
4253 fn from_message(
4254 message: PromptListChangedNotification,
4255 request_id: Option<RequestId>,
4256 ) -> std::result::Result<Self, RpcError> {
4257 if request_id.is_some() {
4258 return Err(
4259 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
4260 );
4261 }
4262 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
4263 }
4264}
4265impl ToMessage<ServerMessage> for PromptListChangedNotification {
4266 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4267 ServerMessage::from_message(self, request_id)
4268 }
4269}
4270impl FromMessage<ToolListChangedNotification> for ServerMessage {
4271 fn from_message(
4272 message: ToolListChangedNotification,
4273 request_id: Option<RequestId>,
4274 ) -> std::result::Result<Self, RpcError> {
4275 if request_id.is_some() {
4276 return Err(
4277 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
4278 );
4279 }
4280 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
4281 }
4282}
4283impl ToMessage<ServerMessage> for ToolListChangedNotification {
4284 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4285 ServerMessage::from_message(self, request_id)
4286 }
4287}
4288impl FromMessage<TaskStatusNotification> for ServerMessage {
4289 fn from_message(message: TaskStatusNotification, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
4290 if request_id.is_some() {
4291 return Err(
4292 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
4293 );
4294 }
4295 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
4296 }
4297}
4298impl ToMessage<ServerMessage> for TaskStatusNotification {
4299 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4300 ServerMessage::from_message(self, request_id)
4301 }
4302}
4303impl FromMessage<LoggingMessageNotification> for ServerMessage {
4304 fn from_message(
4305 message: LoggingMessageNotification,
4306 request_id: Option<RequestId>,
4307 ) -> std::result::Result<Self, RpcError> {
4308 if request_id.is_some() {
4309 return Err(
4310 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
4311 );
4312 }
4313 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
4314 }
4315}
4316impl ToMessage<ServerMessage> for LoggingMessageNotification {
4317 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4318 ServerMessage::from_message(self, request_id)
4319 }
4320}
4321impl FromMessage<ElicitationCompleteNotification> for ServerMessage {
4322 fn from_message(
4323 message: ElicitationCompleteNotification,
4324 request_id: Option<RequestId>,
4325 ) -> std::result::Result<Self, RpcError> {
4326 if request_id.is_some() {
4327 return Err(
4328 RpcError::internal_error().with_message("request_id expected to be None for Notifications!".to_string())
4329 );
4330 }
4331 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(message.into())))
4332 }
4333}
4334impl ToMessage<ServerMessage> for ElicitationCompleteNotification {
4335 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<ServerMessage, RpcError> {
4336 ServerMessage::from_message(self, request_id)
4337 }
4338}
4339impl TryFrom<RequestFromClient> for InitializeRequest {
4340 type Error = RpcError;
4341 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4342 let matched_type: ClientRequest = value.try_into()?;
4343 if let ClientRequest::InitializeRequest(result) = matched_type {
4344 Ok(result)
4345 } else {
4346 Err(RpcError::internal_error().with_message("Not a InitializeRequest".to_string()))
4347 }
4348 }
4349}
4350impl TryFrom<RequestFromClient> for PingRequest {
4351 type Error = RpcError;
4352 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4353 let matched_type: ClientRequest = value.try_into()?;
4354 if let ClientRequest::PingRequest(result) = matched_type {
4355 Ok(result)
4356 } else {
4357 Err(RpcError::internal_error().with_message("Not a PingRequest".to_string()))
4358 }
4359 }
4360}
4361impl TryFrom<RequestFromClient> for ListResourcesRequest {
4362 type Error = RpcError;
4363 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4364 let matched_type: ClientRequest = value.try_into()?;
4365 if let ClientRequest::ListResourcesRequest(result) = matched_type {
4366 Ok(result)
4367 } else {
4368 Err(RpcError::internal_error().with_message("Not a ListResourcesRequest".to_string()))
4369 }
4370 }
4371}
4372impl TryFrom<RequestFromClient> for ListResourceTemplatesRequest {
4373 type Error = RpcError;
4374 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4375 let matched_type: ClientRequest = value.try_into()?;
4376 if let ClientRequest::ListResourceTemplatesRequest(result) = matched_type {
4377 Ok(result)
4378 } else {
4379 Err(RpcError::internal_error().with_message("Not a ListResourceTemplatesRequest".to_string()))
4380 }
4381 }
4382}
4383impl TryFrom<RequestFromClient> for ReadResourceRequest {
4384 type Error = RpcError;
4385 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4386 let matched_type: ClientRequest = value.try_into()?;
4387 if let ClientRequest::ReadResourceRequest(result) = matched_type {
4388 Ok(result)
4389 } else {
4390 Err(RpcError::internal_error().with_message("Not a ReadResourceRequest".to_string()))
4391 }
4392 }
4393}
4394impl TryFrom<RequestFromClient> for SubscribeRequest {
4395 type Error = RpcError;
4396 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4397 let matched_type: ClientRequest = value.try_into()?;
4398 if let ClientRequest::SubscribeRequest(result) = matched_type {
4399 Ok(result)
4400 } else {
4401 Err(RpcError::internal_error().with_message("Not a SubscribeRequest".to_string()))
4402 }
4403 }
4404}
4405impl TryFrom<RequestFromClient> for UnsubscribeRequest {
4406 type Error = RpcError;
4407 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4408 let matched_type: ClientRequest = value.try_into()?;
4409 if let ClientRequest::UnsubscribeRequest(result) = matched_type {
4410 Ok(result)
4411 } else {
4412 Err(RpcError::internal_error().with_message("Not a UnsubscribeRequest".to_string()))
4413 }
4414 }
4415}
4416impl TryFrom<RequestFromClient> for ListPromptsRequest {
4417 type Error = RpcError;
4418 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4419 let matched_type: ClientRequest = value.try_into()?;
4420 if let ClientRequest::ListPromptsRequest(result) = matched_type {
4421 Ok(result)
4422 } else {
4423 Err(RpcError::internal_error().with_message("Not a ListPromptsRequest".to_string()))
4424 }
4425 }
4426}
4427impl TryFrom<RequestFromClient> for GetPromptRequest {
4428 type Error = RpcError;
4429 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4430 let matched_type: ClientRequest = value.try_into()?;
4431 if let ClientRequest::GetPromptRequest(result) = matched_type {
4432 Ok(result)
4433 } else {
4434 Err(RpcError::internal_error().with_message("Not a GetPromptRequest".to_string()))
4435 }
4436 }
4437}
4438impl TryFrom<RequestFromClient> for ListToolsRequest {
4439 type Error = RpcError;
4440 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4441 let matched_type: ClientRequest = value.try_into()?;
4442 if let ClientRequest::ListToolsRequest(result) = matched_type {
4443 Ok(result)
4444 } else {
4445 Err(RpcError::internal_error().with_message("Not a ListToolsRequest".to_string()))
4446 }
4447 }
4448}
4449impl TryFrom<RequestFromClient> for CallToolRequest {
4450 type Error = RpcError;
4451 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4452 let matched_type: ClientRequest = value.try_into()?;
4453 if let ClientRequest::CallToolRequest(result) = matched_type {
4454 Ok(result)
4455 } else {
4456 Err(RpcError::internal_error().with_message("Not a CallToolRequest".to_string()))
4457 }
4458 }
4459}
4460impl TryFrom<RequestFromClient> for GetTaskRequest {
4461 type Error = RpcError;
4462 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4463 let matched_type: ClientRequest = value.try_into()?;
4464 if let ClientRequest::GetTaskRequest(result) = matched_type {
4465 Ok(result)
4466 } else {
4467 Err(RpcError::internal_error().with_message("Not a GetTaskRequest".to_string()))
4468 }
4469 }
4470}
4471impl TryFrom<RequestFromClient> for GetTaskPayloadRequest {
4472 type Error = RpcError;
4473 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4474 let matched_type: ClientRequest = value.try_into()?;
4475 if let ClientRequest::GetTaskPayloadRequest(result) = matched_type {
4476 Ok(result)
4477 } else {
4478 Err(RpcError::internal_error().with_message("Not a GetTaskPayloadRequest".to_string()))
4479 }
4480 }
4481}
4482impl TryFrom<RequestFromClient> for CancelTaskRequest {
4483 type Error = RpcError;
4484 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4485 let matched_type: ClientRequest = value.try_into()?;
4486 if let ClientRequest::CancelTaskRequest(result) = matched_type {
4487 Ok(result)
4488 } else {
4489 Err(RpcError::internal_error().with_message("Not a CancelTaskRequest".to_string()))
4490 }
4491 }
4492}
4493impl TryFrom<RequestFromClient> for ListTasksRequest {
4494 type Error = RpcError;
4495 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4496 let matched_type: ClientRequest = value.try_into()?;
4497 if let ClientRequest::ListTasksRequest(result) = matched_type {
4498 Ok(result)
4499 } else {
4500 Err(RpcError::internal_error().with_message("Not a ListTasksRequest".to_string()))
4501 }
4502 }
4503}
4504impl TryFrom<RequestFromClient> for SetLevelRequest {
4505 type Error = RpcError;
4506 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4507 let matched_type: ClientRequest = value.try_into()?;
4508 if let ClientRequest::SetLevelRequest(result) = matched_type {
4509 Ok(result)
4510 } else {
4511 Err(RpcError::internal_error().with_message("Not a SetLevelRequest".to_string()))
4512 }
4513 }
4514}
4515impl TryFrom<RequestFromClient> for CompleteRequest {
4516 type Error = RpcError;
4517 fn try_from(value: RequestFromClient) -> std::result::Result<Self, Self::Error> {
4518 let matched_type: ClientRequest = value.try_into()?;
4519 if let ClientRequest::CompleteRequest(result) = matched_type {
4520 Ok(result)
4521 } else {
4522 Err(RpcError::internal_error().with_message("Not a CompleteRequest".to_string()))
4523 }
4524 }
4525}
4526impl TryFrom<ResultFromClient> for Result {
4527 type Error = RpcError;
4528 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
4529 let matched_type: ClientResult = value.try_into()?;
4530 if let ClientResult::Result(result) = matched_type {
4531 Ok(result)
4532 } else {
4533 Err(RpcError::internal_error().with_message("Not a Result".to_string()))
4534 }
4535 }
4536}
4537impl TryFrom<ResultFromClient> for GetTaskResult {
4538 type Error = RpcError;
4539 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
4540 let matched_type: ClientResult = value.try_into()?;
4541 if let ClientResult::GetTaskResult(result) = matched_type {
4542 Ok(result)
4543 } else {
4544 Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
4545 }
4546 }
4547}
4548impl TryFrom<ResultFromClient> for GetTaskPayloadResult {
4549 type Error = RpcError;
4550 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
4551 let matched_type: ClientResult = value.try_into()?;
4552 if let ClientResult::GetTaskPayloadResult(result) = matched_type {
4553 Ok(result)
4554 } else {
4555 Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
4556 }
4557 }
4558}
4559impl TryFrom<ResultFromClient> for CancelTaskResult {
4560 type Error = RpcError;
4561 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
4562 let matched_type: ClientResult = value.try_into()?;
4563 if let ClientResult::CancelTaskResult(result) = matched_type {
4564 Ok(result)
4565 } else {
4566 Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
4567 }
4568 }
4569}
4570impl TryFrom<ResultFromClient> for ListTasksResult {
4571 type Error = RpcError;
4572 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
4573 let matched_type: ClientResult = value.try_into()?;
4574 if let ClientResult::ListTasksResult(result) = matched_type {
4575 Ok(result)
4576 } else {
4577 Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
4578 }
4579 }
4580}
4581impl TryFrom<ResultFromClient> for CreateMessageResult {
4582 type Error = RpcError;
4583 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
4584 let matched_type: ClientResult = value.try_into()?;
4585 if let ClientResult::CreateMessageResult(result) = matched_type {
4586 Ok(result)
4587 } else {
4588 Err(RpcError::internal_error().with_message("Not a CreateMessageResult".to_string()))
4589 }
4590 }
4591}
4592impl TryFrom<ResultFromClient> for ListRootsResult {
4593 type Error = RpcError;
4594 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
4595 let matched_type: ClientResult = value.try_into()?;
4596 if let ClientResult::ListRootsResult(result) = matched_type {
4597 Ok(result)
4598 } else {
4599 Err(RpcError::internal_error().with_message("Not a ListRootsResult".to_string()))
4600 }
4601 }
4602}
4603impl TryFrom<ResultFromClient> for ElicitResult {
4604 type Error = RpcError;
4605 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
4606 let matched_type: ClientResult = value.try_into()?;
4607 if let ClientResult::ElicitResult(result) = matched_type {
4608 Ok(result)
4609 } else {
4610 Err(RpcError::internal_error().with_message("Not a ElicitResult".to_string()))
4611 }
4612 }
4613}
4614impl TryFrom<NotificationFromClient> for CancelledNotification {
4615 type Error = RpcError;
4616 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
4617 let matched_type: ClientNotification = value.try_into()?;
4618 if let ClientNotification::CancelledNotification(result) = matched_type {
4619 Ok(result)
4620 } else {
4621 Err(RpcError::internal_error().with_message("Not a CancelledNotification".to_string()))
4622 }
4623 }
4624}
4625impl TryFrom<NotificationFromClient> for InitializedNotification {
4626 type Error = RpcError;
4627 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
4628 let matched_type: ClientNotification = value.try_into()?;
4629 if let ClientNotification::InitializedNotification(result) = matched_type {
4630 Ok(result)
4631 } else {
4632 Err(RpcError::internal_error().with_message("Not a InitializedNotification".to_string()))
4633 }
4634 }
4635}
4636impl TryFrom<NotificationFromClient> for ProgressNotification {
4637 type Error = RpcError;
4638 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
4639 let matched_type: ClientNotification = value.try_into()?;
4640 if let ClientNotification::ProgressNotification(result) = matched_type {
4641 Ok(result)
4642 } else {
4643 Err(RpcError::internal_error().with_message("Not a ProgressNotification".to_string()))
4644 }
4645 }
4646}
4647impl TryFrom<NotificationFromClient> for TaskStatusNotification {
4648 type Error = RpcError;
4649 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
4650 let matched_type: ClientNotification = value.try_into()?;
4651 if let ClientNotification::TaskStatusNotification(result) = matched_type {
4652 Ok(result)
4653 } else {
4654 Err(RpcError::internal_error().with_message("Not a TaskStatusNotification".to_string()))
4655 }
4656 }
4657}
4658impl TryFrom<NotificationFromClient> for RootsListChangedNotification {
4659 type Error = RpcError;
4660 fn try_from(value: NotificationFromClient) -> std::result::Result<Self, Self::Error> {
4661 let matched_type: ClientNotification = value.try_into()?;
4662 if let ClientNotification::RootsListChangedNotification(result) = matched_type {
4663 Ok(result)
4664 } else {
4665 Err(RpcError::internal_error().with_message("Not a RootsListChangedNotification".to_string()))
4666 }
4667 }
4668}
4669impl TryFrom<RequestFromServer> for PingRequest {
4670 type Error = RpcError;
4671 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
4672 let matched_type: ServerRequest = value.try_into()?;
4673 if let ServerRequest::PingRequest(result) = matched_type {
4674 Ok(result)
4675 } else {
4676 Err(RpcError::internal_error().with_message("Not a PingRequest".to_string()))
4677 }
4678 }
4679}
4680impl TryFrom<RequestFromServer> for GetTaskRequest {
4681 type Error = RpcError;
4682 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
4683 let matched_type: ServerRequest = value.try_into()?;
4684 if let ServerRequest::GetTaskRequest(result) = matched_type {
4685 Ok(result)
4686 } else {
4687 Err(RpcError::internal_error().with_message("Not a GetTaskRequest".to_string()))
4688 }
4689 }
4690}
4691impl TryFrom<RequestFromServer> for GetTaskPayloadRequest {
4692 type Error = RpcError;
4693 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
4694 let matched_type: ServerRequest = value.try_into()?;
4695 if let ServerRequest::GetTaskPayloadRequest(result) = matched_type {
4696 Ok(result)
4697 } else {
4698 Err(RpcError::internal_error().with_message("Not a GetTaskPayloadRequest".to_string()))
4699 }
4700 }
4701}
4702impl TryFrom<RequestFromServer> for CancelTaskRequest {
4703 type Error = RpcError;
4704 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
4705 let matched_type: ServerRequest = value.try_into()?;
4706 if let ServerRequest::CancelTaskRequest(result) = matched_type {
4707 Ok(result)
4708 } else {
4709 Err(RpcError::internal_error().with_message("Not a CancelTaskRequest".to_string()))
4710 }
4711 }
4712}
4713impl TryFrom<RequestFromServer> for ListTasksRequest {
4714 type Error = RpcError;
4715 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
4716 let matched_type: ServerRequest = value.try_into()?;
4717 if let ServerRequest::ListTasksRequest(result) = matched_type {
4718 Ok(result)
4719 } else {
4720 Err(RpcError::internal_error().with_message("Not a ListTasksRequest".to_string()))
4721 }
4722 }
4723}
4724impl TryFrom<RequestFromServer> for CreateMessageRequest {
4725 type Error = RpcError;
4726 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
4727 let matched_type: ServerRequest = value.try_into()?;
4728 if let ServerRequest::CreateMessageRequest(result) = matched_type {
4729 Ok(result)
4730 } else {
4731 Err(RpcError::internal_error().with_message("Not a CreateMessageRequest".to_string()))
4732 }
4733 }
4734}
4735impl TryFrom<RequestFromServer> for ListRootsRequest {
4736 type Error = RpcError;
4737 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
4738 let matched_type: ServerRequest = value.try_into()?;
4739 if let ServerRequest::ListRootsRequest(result) = matched_type {
4740 Ok(result)
4741 } else {
4742 Err(RpcError::internal_error().with_message("Not a ListRootsRequest".to_string()))
4743 }
4744 }
4745}
4746impl TryFrom<RequestFromServer> for ElicitRequest {
4747 type Error = RpcError;
4748 fn try_from(value: RequestFromServer) -> std::result::Result<Self, Self::Error> {
4749 let matched_type: ServerRequest = value.try_into()?;
4750 if let ServerRequest::ElicitRequest(result) = matched_type {
4751 Ok(result)
4752 } else {
4753 Err(RpcError::internal_error().with_message("Not a ElicitRequest".to_string()))
4754 }
4755 }
4756}
4757impl TryFrom<ResultFromServer> for Result {
4758 type Error = RpcError;
4759 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4760 let matched_type: ServerResult = value.try_into()?;
4761 if let ServerResult::Result(result) = matched_type {
4762 Ok(result)
4763 } else {
4764 Err(RpcError::internal_error().with_message("Not a Result".to_string()))
4765 }
4766 }
4767}
4768impl TryFrom<ResultFromServer> for InitializeResult {
4769 type Error = RpcError;
4770 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4771 let matched_type: ServerResult = value.try_into()?;
4772 if let ServerResult::InitializeResult(result) = matched_type {
4773 Ok(result)
4774 } else {
4775 Err(RpcError::internal_error().with_message("Not a InitializeResult".to_string()))
4776 }
4777 }
4778}
4779impl TryFrom<ResultFromServer> for ListResourcesResult {
4780 type Error = RpcError;
4781 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4782 let matched_type: ServerResult = value.try_into()?;
4783 if let ServerResult::ListResourcesResult(result) = matched_type {
4784 Ok(result)
4785 } else {
4786 Err(RpcError::internal_error().with_message("Not a ListResourcesResult".to_string()))
4787 }
4788 }
4789}
4790impl TryFrom<ResultFromServer> for ListResourceTemplatesResult {
4791 type Error = RpcError;
4792 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4793 let matched_type: ServerResult = value.try_into()?;
4794 if let ServerResult::ListResourceTemplatesResult(result) = matched_type {
4795 Ok(result)
4796 } else {
4797 Err(RpcError::internal_error().with_message("Not a ListResourceTemplatesResult".to_string()))
4798 }
4799 }
4800}
4801impl TryFrom<ResultFromServer> for ReadResourceResult {
4802 type Error = RpcError;
4803 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4804 let matched_type: ServerResult = value.try_into()?;
4805 if let ServerResult::ReadResourceResult(result) = matched_type {
4806 Ok(result)
4807 } else {
4808 Err(RpcError::internal_error().with_message("Not a ReadResourceResult".to_string()))
4809 }
4810 }
4811}
4812impl TryFrom<ResultFromServer> for ListPromptsResult {
4813 type Error = RpcError;
4814 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4815 let matched_type: ServerResult = value.try_into()?;
4816 if let ServerResult::ListPromptsResult(result) = matched_type {
4817 Ok(result)
4818 } else {
4819 Err(RpcError::internal_error().with_message("Not a ListPromptsResult".to_string()))
4820 }
4821 }
4822}
4823impl TryFrom<ResultFromServer> for GetPromptResult {
4824 type Error = RpcError;
4825 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4826 let matched_type: ServerResult = value.try_into()?;
4827 if let ServerResult::GetPromptResult(result) = matched_type {
4828 Ok(result)
4829 } else {
4830 Err(RpcError::internal_error().with_message("Not a GetPromptResult".to_string()))
4831 }
4832 }
4833}
4834impl TryFrom<ResultFromServer> for ListToolsResult {
4835 type Error = RpcError;
4836 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4837 let matched_type: ServerResult = value.try_into()?;
4838 if let ServerResult::ListToolsResult(result) = matched_type {
4839 Ok(result)
4840 } else {
4841 Err(RpcError::internal_error().with_message("Not a ListToolsResult".to_string()))
4842 }
4843 }
4844}
4845impl TryFrom<ResultFromServer> for CallToolResult {
4846 type Error = RpcError;
4847 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4848 let matched_type: ServerResult = value.try_into()?;
4849 if let ServerResult::CallToolResult(result) = matched_type {
4850 Ok(result)
4851 } else {
4852 Err(RpcError::internal_error().with_message("Not a CallToolResult".to_string()))
4853 }
4854 }
4855}
4856impl TryFrom<ResultFromServer> for GetTaskResult {
4857 type Error = RpcError;
4858 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4859 let matched_type: ServerResult = value.try_into()?;
4860 if let ServerResult::GetTaskResult(result) = matched_type {
4861 Ok(result)
4862 } else {
4863 Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
4864 }
4865 }
4866}
4867impl TryFrom<ResultFromServer> for GetTaskPayloadResult {
4868 type Error = RpcError;
4869 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4870 let matched_type: ServerResult = value.try_into()?;
4871 if let ServerResult::GetTaskPayloadResult(result) = matched_type {
4872 Ok(result)
4873 } else {
4874 Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
4875 }
4876 }
4877}
4878impl TryFrom<ResultFromServer> for CancelTaskResult {
4879 type Error = RpcError;
4880 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4881 let matched_type: ServerResult = value.try_into()?;
4882 if let ServerResult::CancelTaskResult(result) = matched_type {
4883 Ok(result)
4884 } else {
4885 Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
4886 }
4887 }
4888}
4889impl TryFrom<ResultFromServer> for ListTasksResult {
4890 type Error = RpcError;
4891 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4892 let matched_type: ServerResult = value.try_into()?;
4893 if let ServerResult::ListTasksResult(result) = matched_type {
4894 Ok(result)
4895 } else {
4896 Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
4897 }
4898 }
4899}
4900impl TryFrom<ResultFromServer> for CompleteResult {
4901 type Error = RpcError;
4902 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4903 let matched_type: ServerResult = value.try_into()?;
4904 if let ServerResult::CompleteResult(result) = matched_type {
4905 Ok(result)
4906 } else {
4907 Err(RpcError::internal_error().with_message("Not a CompleteResult".to_string()))
4908 }
4909 }
4910}
4911impl TryFrom<NotificationFromServer> for CancelledNotification {
4912 type Error = RpcError;
4913 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4914 let matched_type: ServerNotification = value.try_into()?;
4915 if let ServerNotification::CancelledNotification(result) = matched_type {
4916 Ok(result)
4917 } else {
4918 Err(RpcError::internal_error().with_message("Not a CancelledNotification".to_string()))
4919 }
4920 }
4921}
4922impl TryFrom<NotificationFromServer> for ProgressNotification {
4923 type Error = RpcError;
4924 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4925 let matched_type: ServerNotification = value.try_into()?;
4926 if let ServerNotification::ProgressNotification(result) = matched_type {
4927 Ok(result)
4928 } else {
4929 Err(RpcError::internal_error().with_message("Not a ProgressNotification".to_string()))
4930 }
4931 }
4932}
4933impl TryFrom<NotificationFromServer> for ResourceListChangedNotification {
4934 type Error = RpcError;
4935 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4936 let matched_type: ServerNotification = value.try_into()?;
4937 if let ServerNotification::ResourceListChangedNotification(result) = matched_type {
4938 Ok(result)
4939 } else {
4940 Err(RpcError::internal_error().with_message("Not a ResourceListChangedNotification".to_string()))
4941 }
4942 }
4943}
4944impl TryFrom<NotificationFromServer> for ResourceUpdatedNotification {
4945 type Error = RpcError;
4946 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4947 let matched_type: ServerNotification = value.try_into()?;
4948 if let ServerNotification::ResourceUpdatedNotification(result) = matched_type {
4949 Ok(result)
4950 } else {
4951 Err(RpcError::internal_error().with_message("Not a ResourceUpdatedNotification".to_string()))
4952 }
4953 }
4954}
4955impl TryFrom<NotificationFromServer> for PromptListChangedNotification {
4956 type Error = RpcError;
4957 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4958 let matched_type: ServerNotification = value.try_into()?;
4959 if let ServerNotification::PromptListChangedNotification(result) = matched_type {
4960 Ok(result)
4961 } else {
4962 Err(RpcError::internal_error().with_message("Not a PromptListChangedNotification".to_string()))
4963 }
4964 }
4965}
4966impl TryFrom<NotificationFromServer> for ToolListChangedNotification {
4967 type Error = RpcError;
4968 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4969 let matched_type: ServerNotification = value.try_into()?;
4970 if let ServerNotification::ToolListChangedNotification(result) = matched_type {
4971 Ok(result)
4972 } else {
4973 Err(RpcError::internal_error().with_message("Not a ToolListChangedNotification".to_string()))
4974 }
4975 }
4976}
4977impl TryFrom<NotificationFromServer> for TaskStatusNotification {
4978 type Error = RpcError;
4979 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4980 let matched_type: ServerNotification = value.try_into()?;
4981 if let ServerNotification::TaskStatusNotification(result) = matched_type {
4982 Ok(result)
4983 } else {
4984 Err(RpcError::internal_error().with_message("Not a TaskStatusNotification".to_string()))
4985 }
4986 }
4987}
4988impl TryFrom<NotificationFromServer> for LoggingMessageNotification {
4989 type Error = RpcError;
4990 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
4991 let matched_type: ServerNotification = value.try_into()?;
4992 if let ServerNotification::LoggingMessageNotification(result) = matched_type {
4993 Ok(result)
4994 } else {
4995 Err(RpcError::internal_error().with_message("Not a LoggingMessageNotification".to_string()))
4996 }
4997 }
4998}
4999impl TryFrom<NotificationFromServer> for ElicitationCompleteNotification {
5000 type Error = RpcError;
5001 fn try_from(value: NotificationFromServer) -> std::result::Result<Self, Self::Error> {
5002 let matched_type: ServerNotification = value.try_into()?;
5003 if let ServerNotification::ElicitationCompleteNotification(result) = matched_type {
5004 Ok(result)
5005 } else {
5006 Err(RpcError::internal_error().with_message("Not a ElicitationCompleteNotification".to_string()))
5007 }
5008 }
5009}
5010impl ContentBlock {
5011 pub fn text_content(text: ::std::string::String) -> Self {
5013 TextContent::new(text, None, None).into()
5014 }
5015 pub fn image_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
5017 ImageContent::new(data, mime_type, None, None).into()
5018 }
5019 pub fn audio_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
5021 AudioContent::new(data, mime_type, None, None).into()
5022 }
5023 pub fn resource_link(value: ResourceLink) -> Self {
5025 value.into()
5026 }
5027 pub fn embedded_resource(resource: EmbeddedResourceResource) -> Self {
5029 EmbeddedResource::new(resource, None, None).into()
5030 }
5031 pub fn content_type(&self) -> &str {
5033 match self {
5034 ContentBlock::TextContent(text_content) => text_content.type_(),
5035 ContentBlock::ImageContent(image_content) => image_content.type_(),
5036 ContentBlock::AudioContent(audio_content) => audio_content.type_(),
5037 ContentBlock::ResourceLink(resource_link) => resource_link.type_(),
5038 ContentBlock::EmbeddedResource(embedded_resource) => embedded_resource.type_(),
5039 }
5040 }
5041 pub fn as_text_content(&self) -> std::result::Result<&TextContent, RpcError> {
5043 match &self {
5044 ContentBlock::TextContent(text_content) => Ok(text_content),
5045 _ => Err(RpcError::internal_error().with_message(format!(
5046 "Invalid conversion, \"{}\" is not a {}",
5047 self.content_type(),
5048 "TextContent"
5049 ))),
5050 }
5051 }
5052 pub fn as_image_content(&self) -> std::result::Result<&ImageContent, RpcError> {
5054 match &self {
5055 ContentBlock::ImageContent(image_content) => Ok(image_content),
5056 _ => Err(RpcError::internal_error().with_message(format!(
5057 "Invalid conversion, \"{}\" is not a {}",
5058 self.content_type(),
5059 "ImageContent"
5060 ))),
5061 }
5062 }
5063 pub fn as_audio_content(&self) -> std::result::Result<&AudioContent, RpcError> {
5065 match &self {
5066 ContentBlock::AudioContent(audio_content) => Ok(audio_content),
5067 _ => Err(RpcError::internal_error().with_message(format!(
5068 "Invalid conversion, \"{}\" is not a {}",
5069 self.content_type(),
5070 "AudioContent"
5071 ))),
5072 }
5073 }
5074 pub fn as_resource_link(&self) -> std::result::Result<&ResourceLink, RpcError> {
5076 match &self {
5077 ContentBlock::ResourceLink(resource_link) => Ok(resource_link),
5078 _ => Err(RpcError::internal_error().with_message(format!(
5079 "Invalid conversion, \"{}\" is not a {}",
5080 self.content_type(),
5081 "ResourceLink"
5082 ))),
5083 }
5084 }
5085 pub fn as_embedded_resource(&self) -> std::result::Result<&EmbeddedResource, RpcError> {
5087 match &self {
5088 ContentBlock::EmbeddedResource(embedded_resource) => Ok(embedded_resource),
5089 _ => Err(RpcError::internal_error().with_message(format!(
5090 "Invalid conversion, \"{}\" is not a {}",
5091 self.content_type(),
5092 "EmbeddedResource"
5093 ))),
5094 }
5095 }
5096}
5097impl CallToolResult {
5098 pub fn text_content(content: Vec<TextContent>) -> Self {
5099 Self {
5100 content: content.into_iter().map(Into::into).collect(),
5101 is_error: None,
5102 meta: None,
5103 structured_content: None,
5104 }
5105 }
5106 pub fn image_content(content: Vec<ImageContent>) -> Self {
5107 Self {
5108 content: content.into_iter().map(Into::into).collect(),
5109 is_error: None,
5110 meta: None,
5111 structured_content: None,
5112 }
5113 }
5114 pub fn audio_content(content: Vec<AudioContent>) -> Self {
5115 Self {
5116 content: content.into_iter().map(Into::into).collect(),
5117 is_error: None,
5118 meta: None,
5119 structured_content: None,
5120 }
5121 }
5122 pub fn resource_link(content: Vec<ResourceLink>) -> Self {
5123 Self {
5124 content: content.into_iter().map(Into::into).collect(),
5125 is_error: None,
5126 meta: None,
5127 structured_content: None,
5128 }
5129 }
5130 pub fn embedded_resource(content: Vec<EmbeddedResource>) -> Self {
5131 Self {
5132 content: content.into_iter().map(Into::into).collect(),
5133 is_error: None,
5134 meta: None,
5135 structured_content: None,
5136 }
5137 }
5138 pub fn with_error(error: CallToolError) -> Self {
5140 Self {
5141 content: vec![ContentBlock::TextContent(TextContent::new(error.to_string(), None, None))],
5142 is_error: Some(true),
5143 meta: None,
5144 structured_content: None,
5145 }
5146 }
5147 pub fn with_meta(mut self, meta: Option<serde_json::Map<String, Value>>) -> Self {
5149 self.meta = meta;
5150 self
5151 }
5152 pub fn with_structured_content(
5154 mut self,
5155 structured_content: ::serde_json::Map<::std::string::String, ::serde_json::Value>,
5156 ) -> Self {
5157 self.structured_content = Some(structured_content);
5158 self
5159 }
5160}
5161#[cfg(test)]
5163mod tests {
5164 }