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(ClientJsonrpcRequest::InitializeRequest(_)))
238 }
239
240 pub fn is_initialized_notification(&self) -> bool {
242 matches!(
243 self,
244 Self::Notification(ClientJsonrpcNotification::InitializedNotification(_))
245 )
246 }
247}
248
249impl From<ClientJsonrpcNotification> for ClientMessage {
250 fn from(value: ClientJsonrpcNotification) -> Self {
251 Self::Notification(value)
252 }
253}
254
255impl From<ClientJsonrpcRequest> for ClientMessage {
256 fn from(value: ClientJsonrpcRequest) -> Self {
257 Self::Request(value)
258 }
259}
260
261impl From<ClientJsonrpcResponse> for ClientMessage {
262 fn from(value: ClientJsonrpcResponse) -> Self {
263 Self::Response(value)
264 }
265}
266
267impl RpcMessage for ClientMessage {
268 fn request_id(&self) -> Option<&RequestId> {
270 match self {
271 ClientMessage::Request(client_jsonrpc_request) => match client_jsonrpc_request {
273 ClientJsonrpcRequest::InitializeRequest(request) => Some(&request.id),
274 ClientJsonrpcRequest::PingRequest(request) => Some(&request.id),
275 ClientJsonrpcRequest::ListResourcesRequest(request) => Some(&request.id),
276 ClientJsonrpcRequest::ListResourceTemplatesRequest(request) => Some(&request.id),
277 ClientJsonrpcRequest::ReadResourceRequest(request) => Some(&request.id),
278 ClientJsonrpcRequest::SubscribeRequest(request) => Some(&request.id),
279 ClientJsonrpcRequest::UnsubscribeRequest(request) => Some(&request.id),
280 ClientJsonrpcRequest::ListPromptsRequest(request) => Some(&request.id),
281 ClientJsonrpcRequest::GetPromptRequest(request) => Some(&request.id),
282 ClientJsonrpcRequest::ListToolsRequest(request) => Some(&request.id),
283 ClientJsonrpcRequest::CallToolRequest(request) => Some(&request.id),
284 ClientJsonrpcRequest::GetTaskRequest(request) => Some(&request.id),
285 ClientJsonrpcRequest::GetTaskPayloadRequest(request) => Some(&request.id),
286 ClientJsonrpcRequest::CancelTaskRequest(request) => Some(&request.id),
287 ClientJsonrpcRequest::ListTasksRequest(request) => Some(&request.id),
288 ClientJsonrpcRequest::SetLevelRequest(request) => Some(&request.id),
289 ClientJsonrpcRequest::CompleteRequest(request) => Some(&request.id),
290 ClientJsonrpcRequest::CustomRequest(request) => Some(&request.id),
291 },
292 ClientMessage::Notification(_) => None,
294 ClientMessage::Response(client_jsonrpc_response) => Some(&client_jsonrpc_response.id),
296 ClientMessage::Error(jsonrpc_error) => jsonrpc_error.id.as_ref(),
298 }
299 }
300
301 fn jsonrpc(&self) -> &str {
302 match self {
303 ClientMessage::Request(client_jsonrpc_request) => client_jsonrpc_request.jsonrpc(),
304 ClientMessage::Notification(notification) => notification.jsonrpc(),
305 ClientMessage::Response(client_jsonrpc_response) => client_jsonrpc_response.jsonrpc(),
306 ClientMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
307 }
308 }
309}
310
311impl McpMessage for ClientMessage {
313 fn is_response(&self) -> bool {
315 matches!(self, ClientMessage::Response(_))
316 }
317
318 fn is_request(&self) -> bool {
320 matches!(self, ClientMessage::Request(_))
321 }
322
323 fn is_notification(&self) -> bool {
325 matches!(self, ClientMessage::Notification(_))
326 }
327
328 fn is_error(&self) -> bool {
330 matches!(self, ClientMessage::Error(_))
331 }
332
333 fn message_type(&self) -> MessageTypes {
335 match self {
336 ClientMessage::Request(_) => MessageTypes::Request,
337 ClientMessage::Notification(_) => MessageTypes::Notification,
338 ClientMessage::Response(_) => MessageTypes::Response,
339 ClientMessage::Error(_) => MessageTypes::Error,
340 }
341 }
342}
343
344#[derive(Clone, Debug, ::serde::Serialize, ::serde::Deserialize)]
350#[serde(untagged)]
351pub enum ClientJsonrpcRequest {
352 InitializeRequest(InitializeRequest),
353 PingRequest(PingRequest),
354 ListResourcesRequest(ListResourcesRequest),
355 ListResourceTemplatesRequest(ListResourceTemplatesRequest),
356 ReadResourceRequest(ReadResourceRequest),
357 SubscribeRequest(SubscribeRequest),
358 UnsubscribeRequest(UnsubscribeRequest),
359 ListPromptsRequest(ListPromptsRequest),
360 GetPromptRequest(GetPromptRequest),
361 ListToolsRequest(ListToolsRequest),
362 CallToolRequest(CallToolRequest),
363 GetTaskRequest(GetTaskRequest),
364 GetTaskPayloadRequest(GetTaskPayloadRequest),
365 CancelTaskRequest(CancelTaskRequest),
366 ListTasksRequest(ListTasksRequest),
367 SetLevelRequest(SetLevelRequest),
368 CompleteRequest(CompleteRequest),
369 CustomRequest(JsonrpcRequest),
370}
371
372impl ClientJsonrpcRequest {
373 pub fn new(id: RequestId, request: RequestFromClient) -> Self {
374 match request {
375 RequestFromClient::InitializeRequest(params) => Self::InitializeRequest(InitializeRequest::new(id, params)),
376 RequestFromClient::PingRequest(params) => Self::PingRequest(PingRequest::new(id, params)),
377 RequestFromClient::ListResourcesRequest(params) => {
378 Self::ListResourcesRequest(ListResourcesRequest::new(id, params))
379 }
380 RequestFromClient::ListResourceTemplatesRequest(params) => {
381 Self::ListResourceTemplatesRequest(ListResourceTemplatesRequest::new(id, params))
382 }
383 RequestFromClient::ReadResourceRequest(params) => {
384 Self::ReadResourceRequest(ReadResourceRequest::new(id, params))
385 }
386 RequestFromClient::SubscribeRequest(params) => Self::SubscribeRequest(SubscribeRequest::new(id, params)),
387 RequestFromClient::UnsubscribeRequest(params) => Self::UnsubscribeRequest(UnsubscribeRequest::new(id, params)),
388 RequestFromClient::ListPromptsRequest(params) => Self::ListPromptsRequest(ListPromptsRequest::new(id, params)),
389 RequestFromClient::GetPromptRequest(params) => Self::GetPromptRequest(GetPromptRequest::new(id, params)),
390 RequestFromClient::ListToolsRequest(params) => Self::ListToolsRequest(ListToolsRequest::new(id, params)),
391 RequestFromClient::CallToolRequest(params) => Self::CallToolRequest(CallToolRequest::new(id, params)),
392 RequestFromClient::GetTaskRequest(params) => Self::GetTaskRequest(GetTaskRequest::new(id, params)),
393 RequestFromClient::GetTaskPayloadRequest(params) => {
394 Self::GetTaskPayloadRequest(GetTaskPayloadRequest::new(id, params))
395 }
396 RequestFromClient::CancelTaskRequest(params) => Self::CancelTaskRequest(CancelTaskRequest::new(id, params)),
397 RequestFromClient::ListTasksRequest(params) => Self::ListTasksRequest(ListTasksRequest::new(id, params)),
398 RequestFromClient::SetLevelRequest(params) => Self::SetLevelRequest(SetLevelRequest::new(id, params)),
399 RequestFromClient::CompleteRequest(params) => Self::CompleteRequest(CompleteRequest::new(id, params)),
400 RequestFromClient::CustomRequest(params) => {
401 Self::CustomRequest(JsonrpcRequest::new(id, params.method, params.params))
402 }
403 }
404 }
405 pub fn jsonrpc(&self) -> &::std::string::String {
406 match self {
407 ClientJsonrpcRequest::InitializeRequest(request) => request.jsonrpc(),
408 ClientJsonrpcRequest::PingRequest(request) => request.jsonrpc(),
409 ClientJsonrpcRequest::ListResourcesRequest(request) => request.jsonrpc(),
410 ClientJsonrpcRequest::ListResourceTemplatesRequest(request) => request.jsonrpc(),
411 ClientJsonrpcRequest::ReadResourceRequest(request) => request.jsonrpc(),
412 ClientJsonrpcRequest::SubscribeRequest(request) => request.jsonrpc(),
413 ClientJsonrpcRequest::UnsubscribeRequest(request) => request.jsonrpc(),
414 ClientJsonrpcRequest::ListPromptsRequest(request) => request.jsonrpc(),
415 ClientJsonrpcRequest::GetPromptRequest(request) => request.jsonrpc(),
416 ClientJsonrpcRequest::ListToolsRequest(request) => request.jsonrpc(),
417 ClientJsonrpcRequest::CallToolRequest(request) => request.jsonrpc(),
418 ClientJsonrpcRequest::GetTaskRequest(request) => request.jsonrpc(),
419 ClientJsonrpcRequest::GetTaskPayloadRequest(request) => request.jsonrpc(),
420 ClientJsonrpcRequest::CancelTaskRequest(request) => request.jsonrpc(),
421 ClientJsonrpcRequest::ListTasksRequest(request) => request.jsonrpc(),
422 ClientJsonrpcRequest::SetLevelRequest(request) => request.jsonrpc(),
423 ClientJsonrpcRequest::CompleteRequest(request) => request.jsonrpc(),
424 ClientJsonrpcRequest::CustomRequest(request) => request.jsonrpc(),
425 }
426 }
427
428 pub fn request_id(&self) -> &RequestId {
429 match self {
430 ClientJsonrpcRequest::InitializeRequest(request) => &request.id,
431 ClientJsonrpcRequest::PingRequest(request) => &request.id,
432 ClientJsonrpcRequest::ListResourcesRequest(request) => &request.id,
433 ClientJsonrpcRequest::ListResourceTemplatesRequest(request) => &request.id,
434 ClientJsonrpcRequest::ReadResourceRequest(request) => &request.id,
435 ClientJsonrpcRequest::SubscribeRequest(request) => &request.id,
436 ClientJsonrpcRequest::UnsubscribeRequest(request) => &request.id,
437 ClientJsonrpcRequest::ListPromptsRequest(request) => &request.id,
438 ClientJsonrpcRequest::GetPromptRequest(request) => &request.id,
439 ClientJsonrpcRequest::ListToolsRequest(request) => &request.id,
440 ClientJsonrpcRequest::CallToolRequest(request) => &request.id,
441 ClientJsonrpcRequest::GetTaskRequest(request) => &request.id,
442 ClientJsonrpcRequest::GetTaskPayloadRequest(request) => &request.id,
443 ClientJsonrpcRequest::CancelTaskRequest(request) => &request.id,
444 ClientJsonrpcRequest::ListTasksRequest(request) => &request.id,
445 ClientJsonrpcRequest::SetLevelRequest(request) => &request.id,
446 ClientJsonrpcRequest::CompleteRequest(request) => &request.id,
447 ClientJsonrpcRequest::CustomRequest(request) => &request.id,
448 }
449 }
450}
451
452impl From<ClientJsonrpcRequest> for RequestFromClient {
453 fn from(request: ClientJsonrpcRequest) -> Self {
454 match request {
455 ClientJsonrpcRequest::InitializeRequest(request) => Self::InitializeRequest(request.params),
456 ClientJsonrpcRequest::PingRequest(request) => Self::PingRequest(request.params),
457 ClientJsonrpcRequest::ListResourcesRequest(request) => Self::ListResourcesRequest(request.params),
458 ClientJsonrpcRequest::ListResourceTemplatesRequest(request) => {
459 Self::ListResourceTemplatesRequest(request.params)
460 }
461 ClientJsonrpcRequest::ReadResourceRequest(request) => Self::ReadResourceRequest(request.params),
462 ClientJsonrpcRequest::SubscribeRequest(request) => Self::SubscribeRequest(request.params),
463 ClientJsonrpcRequest::UnsubscribeRequest(request) => Self::UnsubscribeRequest(request.params),
464 ClientJsonrpcRequest::ListPromptsRequest(request) => Self::ListPromptsRequest(request.params),
465 ClientJsonrpcRequest::GetPromptRequest(request) => Self::GetPromptRequest(request.params),
466 ClientJsonrpcRequest::ListToolsRequest(request) => Self::ListToolsRequest(request.params),
467 ClientJsonrpcRequest::CallToolRequest(request) => Self::CallToolRequest(request.params),
468 ClientJsonrpcRequest::GetTaskRequest(request) => Self::GetTaskRequest(request.params),
469 ClientJsonrpcRequest::GetTaskPayloadRequest(request) => Self::GetTaskPayloadRequest(request.params),
470 ClientJsonrpcRequest::CancelTaskRequest(request) => Self::CancelTaskRequest(request.params),
471 ClientJsonrpcRequest::ListTasksRequest(request) => Self::ListTasksRequest(request.params),
472 ClientJsonrpcRequest::SetLevelRequest(request) => Self::SetLevelRequest(request.params),
473 ClientJsonrpcRequest::CompleteRequest(request) => Self::CompleteRequest(request.params),
474 ClientJsonrpcRequest::CustomRequest(request) => Self::CustomRequest(CustomRequest {
475 method: request.method,
476 params: request.params,
477 }),
478 }
479 }
480}
481
482impl Display for ClientJsonrpcRequest {
484 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
485 write!(
486 f,
487 "{}",
488 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
489 )
490 }
491}
492
493impl FromStr for ClientJsonrpcRequest {
494 type Err = RpcError;
495
496 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
518 serde_json::from_str(s)
519 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
520 }
521}
522
523#[allow(clippy::large_enum_variant)]
530#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
531#[serde(untagged)]
532pub enum RequestFromClient {
533 InitializeRequest(InitializeRequestParams),
534 PingRequest(Option<RequestParams>),
535 ListResourcesRequest(Option<PaginatedRequestParams>),
536 ListResourceTemplatesRequest(Option<PaginatedRequestParams>),
537 ReadResourceRequest(ReadResourceRequestParams),
538 SubscribeRequest(SubscribeRequestParams),
539 UnsubscribeRequest(UnsubscribeRequestParams),
540 ListPromptsRequest(Option<PaginatedRequestParams>),
541 GetPromptRequest(GetPromptRequestParams),
542 ListToolsRequest(Option<PaginatedRequestParams>),
543 CallToolRequest(CallToolRequestParams),
544 GetTaskRequest(GetTaskParams),
545 GetTaskPayloadRequest(GetTaskPayloadParams),
546 CancelTaskRequest(CancelTaskParams),
547 ListTasksRequest(Option<PaginatedRequestParams>),
548 SetLevelRequest(SetLevelRequestParams),
549 CompleteRequest(CompleteRequestParams),
550 CustomRequest(CustomRequest),
551}
552
553impl RequestFromClient {
554 pub fn method(&self) -> &str {
555 match self {
556 RequestFromClient::InitializeRequest(_request) => InitializeRequest::method_value(),
557 RequestFromClient::PingRequest(_request) => PingRequest::method_value(),
558 RequestFromClient::ListResourcesRequest(_request) => ListResourcesRequest::method_value(),
559 RequestFromClient::ListResourceTemplatesRequest(_request) => ListResourceTemplatesRequest::method_value(),
560 RequestFromClient::ReadResourceRequest(_request) => ReadResourceRequest::method_value(),
561 RequestFromClient::SubscribeRequest(_request) => SubscribeRequest::method_value(),
562 RequestFromClient::UnsubscribeRequest(_request) => UnsubscribeRequest::method_value(),
563 RequestFromClient::ListPromptsRequest(_request) => ListPromptsRequest::method_value(),
564 RequestFromClient::GetPromptRequest(_request) => GetPromptRequest::method_value(),
565 RequestFromClient::ListToolsRequest(_request) => ListToolsRequest::method_value(),
566 RequestFromClient::CallToolRequest(_request) => CallToolRequest::method_value(),
567 RequestFromClient::GetTaskRequest(_request) => GetTaskRequest::method_value(),
568 RequestFromClient::GetTaskPayloadRequest(_request) => GetTaskPayloadRequest::method_value(),
569 RequestFromClient::CancelTaskRequest(_request) => CancelTaskRequest::method_value(),
570 RequestFromClient::ListTasksRequest(_request) => ListTasksRequest::method_value(),
571 RequestFromClient::SetLevelRequest(_request) => SetLevelRequest::method_value(),
572 RequestFromClient::CompleteRequest(_request) => CompleteRequest::method_value(),
573 RequestFromClient::CustomRequest(request) => request.method.as_str(),
574 }
575 }
576 pub fn is_initialize_request(&self) -> bool {
578 matches!(self, RequestFromClient::InitializeRequest(_))
579 }
580}
581
582#[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)]
616#[serde(untagged)]
617pub enum ClientJsonrpcNotification {
618 CancelledNotification(CancelledNotification),
619 InitializedNotification(InitializedNotification),
620 ProgressNotification(ProgressNotification),
621 TaskStatusNotification(TaskStatusNotification),
622 RootsListChangedNotification(RootsListChangedNotification),
623 CustomNotification(JsonrpcNotification),
624}
625
626impl ClientJsonrpcNotification {
627 pub fn new(notification: NotificationFromClient) -> Self {
628 match notification {
629 NotificationFromClient::CancelledNotification(params) => {
630 Self::CancelledNotification(CancelledNotification::new(params))
631 }
632 NotificationFromClient::InitializedNotification(params) => {
633 Self::InitializedNotification(InitializedNotification::new(params))
634 }
635 NotificationFromClient::ProgressNotification(params) => {
636 Self::ProgressNotification(ProgressNotification::new(params))
637 }
638 NotificationFromClient::TaskStatusNotification(params) => {
639 Self::TaskStatusNotification(TaskStatusNotification::new(params))
640 }
641 NotificationFromClient::RootsListChangedNotification(params) => {
642 Self::RootsListChangedNotification(RootsListChangedNotification::new(params))
643 }
644 NotificationFromClient::CustomNotification(params) => {
645 Self::CustomNotification(JsonrpcNotification::new(params.method, params.params))
646 }
647 }
648 }
649 pub fn jsonrpc(&self) -> &::std::string::String {
650 match self {
651 ClientJsonrpcNotification::CancelledNotification(notification) => notification.jsonrpc(),
652 ClientJsonrpcNotification::InitializedNotification(notification) => notification.jsonrpc(),
653 ClientJsonrpcNotification::ProgressNotification(notification) => notification.jsonrpc(),
654 ClientJsonrpcNotification::TaskStatusNotification(notification) => notification.jsonrpc(),
655 ClientJsonrpcNotification::RootsListChangedNotification(notification) => notification.jsonrpc(),
656 ClientJsonrpcNotification::CustomNotification(notification) => notification.jsonrpc(),
657 }
658 }
659}
660
661impl From<ClientJsonrpcNotification> for NotificationFromClient {
662 fn from(notification: ClientJsonrpcNotification) -> Self {
663 match notification {
664 ClientJsonrpcNotification::CancelledNotification(notification) => {
665 Self::CancelledNotification(notification.params)
666 }
667 ClientJsonrpcNotification::InitializedNotification(notification) => {
668 Self::InitializedNotification(notification.params)
669 }
670 ClientJsonrpcNotification::ProgressNotification(notification) => Self::ProgressNotification(notification.params),
671 ClientJsonrpcNotification::TaskStatusNotification(notification) => {
672 Self::TaskStatusNotification(notification.params)
673 }
674 ClientJsonrpcNotification::RootsListChangedNotification(notification) => {
675 Self::RootsListChangedNotification(notification.params)
676 }
677 ClientJsonrpcNotification::CustomNotification(notification) => Self::CustomNotification(CustomNotification {
678 method: notification.method,
679 params: notification.params,
680 }),
681 }
682 }
683}
684
685impl Display for ClientJsonrpcNotification {
687 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
688 write!(
689 f,
690 "{}",
691 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
692 )
693 }
694}
695
696impl FromStr for ClientJsonrpcNotification {
697 type Err = RpcError;
698
699 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
700 serde_json::from_str(s)
701 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
702 }
703}
704
705#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
712#[serde(untagged)]
713pub enum NotificationFromClient {
714 CancelledNotification(CancelledNotificationParams),
715 InitializedNotification(Option<NotificationParams>),
716 ProgressNotification(ProgressNotificationParams),
717 TaskStatusNotification(TaskStatusNotificationParams),
718 RootsListChangedNotification(Option<NotificationParams>),
719 CustomNotification(CustomNotification),
720}
721
722impl NotificationFromClient {
734 pub fn is_initialized_notification(&self) -> bool {
736 matches!(self, NotificationFromClient::InitializedNotification(_))
737 }
738
739 pub fn method(&self) -> &str {
741 match self {
742 NotificationFromClient::CancelledNotification(_notification) => CancelledNotification::method_value(),
743 NotificationFromClient::InitializedNotification(_notification) => InitializedNotification::method_value(),
744 NotificationFromClient::ProgressNotification(_notification) => ProgressNotification::method_value(),
745 NotificationFromClient::TaskStatusNotification(_notification) => TaskStatusNotification::method_value(),
746 NotificationFromClient::RootsListChangedNotification(_notification) => {
747 RootsListChangedNotification::method_value()
748 }
749 NotificationFromClient::CustomNotification(notification) => notification.method.as_str(),
750 }
751 }
752}
753
754#[derive(Clone, Debug)]
760pub struct ClientJsonrpcResponse {
761 pub id: RequestId,
762 jsonrpc: ::std::string::String,
763 pub result: ResultFromClient,
764}
765
766impl ClientJsonrpcResponse {
767 pub fn new(id: RequestId, result: ResultFromClient) -> Self {
768 Self {
769 id,
770 jsonrpc: JSONRPC_VERSION.to_string(),
771 result,
772 }
773 }
774 pub fn jsonrpc(&self) -> &::std::string::String {
775 &self.jsonrpc
776 }
777}
778
779impl Display for ClientJsonrpcResponse {
781 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
782 write!(
783 f,
784 "{}",
785 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
786 )
787 }
788}
789
790impl FromStr for ClientJsonrpcResponse {
791 type Err = RpcError;
792
793 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
794 serde_json::from_str(s)
795 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
796 }
797}
798pub type ResultFromClient = ClientResult;
803
804impl FromStr for ClientMessage {
809 type Err = RpcError;
810
811 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
812 serde_json::from_str(s)
813 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
814 }
815}
816
817impl Display for ClientMessage {
818 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
819 write!(
820 f,
821 "{}",
822 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
823 )
824 }
825}
826
827#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
834#[serde(untagged)]
835pub enum ServerMessage {
836 Request(ServerJsonrpcRequest),
837 Notification(ServerJsonrpcNotification),
838 Response(ServerJsonrpcResponse),
839 Error(JsonrpcErrorResponse),
840}
841
842impl ServerMessage {
843 pub fn as_response(self) -> std::result::Result<ServerJsonrpcResponse, RpcError> {
853 if let Self::Response(response) = self {
854 Ok(response)
855 } else {
856 Err(RpcError::internal_error().with_message(format!(
857 "Invalid message type, expected: \"{}\" received\"{}\"",
858 MessageTypes::Response,
859 self.message_type()
860 )))
861 }
862 }
863
864 pub fn as_request(self) -> std::result::Result<ServerJsonrpcRequest, RpcError> {
874 if let Self::Request(request) = self {
875 Ok(request)
876 } else {
877 Err(RpcError::internal_error().with_message(format!(
878 "Invalid message type, expected: \"{}\" received\"{}\"",
879 MessageTypes::Request,
880 self.message_type()
881 )))
882 }
883 }
884
885 pub fn as_notification(self) -> std::result::Result<ServerJsonrpcNotification, RpcError> {
895 if let Self::Notification(notification) = self {
896 Ok(notification)
897 } else {
898 Err(RpcError::internal_error().with_message(format!(
899 "Invalid message type, expected: \"{}\" received\"{}\"",
900 MessageTypes::Notification,
901 self.message_type()
902 )))
903 }
904 }
905
906 pub fn as_error(self) -> std::result::Result<JsonrpcErrorResponse, RpcError> {
916 if let Self::Error(error) = self {
917 Ok(error)
918 } else {
919 Err(RpcError::internal_error().with_message(format!(
920 "Invalid message type, expected: \"{}\" received\"{}\"",
921 MessageTypes::Error,
922 self.message_type()
923 )))
924 }
925 }
926}
927
928impl From<ServerJsonrpcNotification> for ServerMessage {
929 fn from(value: ServerJsonrpcNotification) -> Self {
930 Self::Notification(value)
931 }
932}
933
934impl From<ServerJsonrpcRequest> for ServerMessage {
935 fn from(value: ServerJsonrpcRequest) -> Self {
936 Self::Request(value)
937 }
938}
939
940impl From<ServerJsonrpcResponse> for ServerMessage {
941 fn from(value: ServerJsonrpcResponse) -> Self {
942 Self::Response(value)
943 }
944}
945
946impl RpcMessage for ServerMessage {
947 fn request_id(&self) -> Option<&RequestId> {
949 match self {
950 ServerMessage::Request(server_jsonrpc_request) => match server_jsonrpc_request {
952 ServerJsonrpcRequest::PingRequest(request) => Some(&request.id),
953 ServerJsonrpcRequest::GetTaskRequest(request) => Some(&request.id),
954 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => Some(&request.id),
955 ServerJsonrpcRequest::CancelTaskRequest(request) => Some(&request.id),
956 ServerJsonrpcRequest::ListTasksRequest(request) => Some(&request.id),
957 ServerJsonrpcRequest::CreateMessageRequest(request) => Some(&request.id),
958 ServerJsonrpcRequest::ListRootsRequest(request) => Some(&request.id),
959 ServerJsonrpcRequest::ElicitRequest(request) => Some(&request.id),
960 ServerJsonrpcRequest::CustomRequest(request) => Some(&request.id),
961 },
962 ServerMessage::Notification(_) => None,
964 ServerMessage::Response(server_jsonrpc_response) => Some(&server_jsonrpc_response.id),
966 ServerMessage::Error(jsonrpc_error) => jsonrpc_error.id.as_ref(),
968 }
969 }
970
971 fn jsonrpc(&self) -> &str {
972 match self {
973 ServerMessage::Request(server_jsonrpc_request) => match server_jsonrpc_request {
975 ServerJsonrpcRequest::PingRequest(request) => request.jsonrpc(),
976 ServerJsonrpcRequest::GetTaskRequest(request) => request.jsonrpc(),
977 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => request.jsonrpc(),
978 ServerJsonrpcRequest::CancelTaskRequest(request) => request.jsonrpc(),
979 ServerJsonrpcRequest::ListTasksRequest(request) => request.jsonrpc(),
980 ServerJsonrpcRequest::CreateMessageRequest(request) => request.jsonrpc(),
981 ServerJsonrpcRequest::ListRootsRequest(request) => request.jsonrpc(),
982 ServerJsonrpcRequest::ElicitRequest(request) => request.jsonrpc(),
983 ServerJsonrpcRequest::CustomRequest(request) => request.jsonrpc(),
984 },
985
986 ServerMessage::Notification(notification) => notification.jsonrpc(),
988 ServerMessage::Response(server_jsonrpc_response) => server_jsonrpc_response.jsonrpc(),
990 ServerMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
992 }
993 }
994}
995
996impl McpMessage for ServerMessage {
998 fn is_response(&self) -> bool {
1000 matches!(self, ServerMessage::Response(_))
1001 }
1002
1003 fn is_request(&self) -> bool {
1005 matches!(self, ServerMessage::Request(_))
1006 }
1007
1008 fn is_notification(&self) -> bool {
1010 matches!(self, ServerMessage::Notification(_))
1011 }
1012
1013 fn is_error(&self) -> bool {
1015 matches!(self, ServerMessage::Error(_))
1016 }
1017
1018 fn message_type(&self) -> MessageTypes {
1020 match self {
1021 ServerMessage::Request(_) => MessageTypes::Request,
1022 ServerMessage::Notification(_) => MessageTypes::Notification,
1023 ServerMessage::Response(_) => MessageTypes::Response,
1024 ServerMessage::Error(_) => MessageTypes::Error,
1025 }
1026 }
1027}
1028
1029impl FromStr for ServerMessage {
1030 type Err = RpcError;
1031
1032 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1033 serde_json::from_str(s)
1034 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1035 }
1036}
1037
1038impl Display for ServerMessage {
1039 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1040 write!(
1041 f,
1042 "{}",
1043 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1044 )
1045 }
1046}
1047
1048#[derive(Clone, Debug, ::serde::Serialize, ::serde::Deserialize)]
1054#[allow(clippy::large_enum_variant)]
1055#[serde(untagged)]
1056pub enum ServerJsonrpcRequest {
1057 PingRequest(PingRequest),
1058 GetTaskRequest(GetTaskRequest),
1059 GetTaskPayloadRequest(GetTaskPayloadRequest),
1060 CancelTaskRequest(CancelTaskRequest),
1061 ListTasksRequest(ListTasksRequest),
1062 CreateMessageRequest(CreateMessageRequest),
1063 ListRootsRequest(ListRootsRequest),
1064 ElicitRequest(ElicitRequest),
1065 CustomRequest(JsonrpcRequest),
1066}
1067
1068impl ServerJsonrpcRequest {
1069 pub fn request_id(&self) -> &RequestId {
1080 match self {
1081 ServerJsonrpcRequest::PingRequest(request) => &request.id,
1082 ServerJsonrpcRequest::GetTaskRequest(request) => &request.id,
1083 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => &request.id,
1084 ServerJsonrpcRequest::CancelTaskRequest(request) => &request.id,
1085 ServerJsonrpcRequest::ListTasksRequest(request) => &request.id,
1086 ServerJsonrpcRequest::CreateMessageRequest(request) => &request.id,
1087 ServerJsonrpcRequest::ListRootsRequest(request) => &request.id,
1088 ServerJsonrpcRequest::ElicitRequest(request) => &request.id,
1089 ServerJsonrpcRequest::CustomRequest(request) => &request.id,
1090 }
1091 }
1092
1093 pub fn jsonrpc(&self) -> &::std::string::String {
1094 match self {
1095 ServerJsonrpcRequest::PingRequest(request) => request.jsonrpc(),
1096 ServerJsonrpcRequest::GetTaskRequest(request) => request.jsonrpc(),
1097 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => request.jsonrpc(),
1098 ServerJsonrpcRequest::CancelTaskRequest(request) => request.jsonrpc(),
1099 ServerJsonrpcRequest::ListTasksRequest(request) => request.jsonrpc(),
1100 ServerJsonrpcRequest::CreateMessageRequest(request) => request.jsonrpc(),
1101 ServerJsonrpcRequest::ListRootsRequest(request) => request.jsonrpc(),
1102 ServerJsonrpcRequest::ElicitRequest(request) => request.jsonrpc(),
1103 ServerJsonrpcRequest::CustomRequest(request) => request.jsonrpc(),
1104 }
1105 }
1106}
1107
1108impl Display for ServerJsonrpcRequest {
1110 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1111 write!(
1112 f,
1113 "{}",
1114 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1115 )
1116 }
1117}
1118
1119impl FromStr for ServerJsonrpcRequest {
1120 type Err = RpcError;
1121
1122 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1123 serde_json::from_str(s)
1124 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1125 }
1126}
1127
1128#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
1129pub struct CustomRequest {
1130 pub method: ::std::string::String,
1131 #[serde(default, skip_serializing_if = "::std::option::Option::is_none")]
1132 pub params: ::std::option::Option<::serde_json::Map<::std::string::String, ::serde_json::Value>>,
1133}
1134
1135#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1142#[serde(untagged)]
1143pub enum RequestFromServer {
1144 PingRequest(Option<RequestParams>),
1145 GetTaskRequest(GetTaskParams),
1146 GetTaskPayloadRequest(GetTaskPayloadParams),
1147 CancelTaskRequest(CancelTaskParams),
1148 ListTasksRequest(Option<PaginatedRequestParams>),
1149 CreateMessageRequest(CreateMessageRequestParams),
1150 ListRootsRequest(Option<RequestParams>),
1151 ElicitRequest(ElicitRequestParams),
1152 CustomRequest(CustomRequest),
1153}
1154
1155impl From<ServerJsonrpcRequest> for RequestFromServer {
1156 fn from(request: ServerJsonrpcRequest) -> Self {
1157 match request {
1158 ServerJsonrpcRequest::PingRequest(request) => Self::PingRequest(request.params),
1159 ServerJsonrpcRequest::GetTaskRequest(request) => Self::GetTaskRequest(request.params),
1160 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => Self::GetTaskPayloadRequest(request.params),
1161 ServerJsonrpcRequest::CancelTaskRequest(request) => Self::CancelTaskRequest(request.params),
1162 ServerJsonrpcRequest::ListTasksRequest(request) => Self::ListTasksRequest(request.params),
1163 ServerJsonrpcRequest::CreateMessageRequest(request) => Self::CreateMessageRequest(request.params),
1164 ServerJsonrpcRequest::ListRootsRequest(request) => Self::ListRootsRequest(request.params),
1165 ServerJsonrpcRequest::ElicitRequest(request) => Self::ElicitRequest(request.params),
1166 ServerJsonrpcRequest::CustomRequest(request) => Self::CustomRequest(CustomRequest {
1167 method: request.method,
1168 params: request.params,
1169 }),
1170 }
1171 }
1172}
1173
1174impl RequestFromServer {
1175 pub fn method(&self) -> &str {
1176 match self {
1177 RequestFromServer::PingRequest(_request) => PingRequest::method_value(),
1178 RequestFromServer::GetTaskRequest(_request) => GetTaskRequest::method_value(),
1179 RequestFromServer::GetTaskPayloadRequest(_request) => GetTaskPayloadRequest::method_value(),
1180 RequestFromServer::CancelTaskRequest(_request) => CancelTaskRequest::method_value(),
1181 RequestFromServer::ListTasksRequest(_request) => ListTasksRequest::method_value(),
1182 RequestFromServer::CreateMessageRequest(_request) => CreateMessageRequest::method_value(),
1183 RequestFromServer::ListRootsRequest(_request) => ListRootsRequest::method_value(),
1184 RequestFromServer::ElicitRequest(_request) => ElicitRequest::method_value(),
1185 RequestFromServer::CustomRequest(request) => request.method.as_str(),
1186 }
1187 }
1188}
1189
1190#[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)]
1196#[serde(untagged)]
1197pub enum ServerJsonrpcNotification {
1198 CancelledNotification(CancelledNotification),
1199 ProgressNotification(ProgressNotification),
1200 ResourceListChangedNotification(ResourceListChangedNotification),
1201 ResourceUpdatedNotification(ResourceUpdatedNotification),
1202 PromptListChangedNotification(PromptListChangedNotification),
1203 ToolListChangedNotification(ToolListChangedNotification),
1204 TaskStatusNotification(TaskStatusNotification),
1205 LoggingMessageNotification(LoggingMessageNotification),
1206 ElicitationCompleteNotification(ElicitationCompleteNotification),
1207 CustomNotification(JsonrpcNotification),
1208}
1209
1210impl From<ServerJsonrpcNotification> for NotificationFromServer {
1211 fn from(notification: ServerJsonrpcNotification) -> Self {
1212 match notification {
1213 ServerJsonrpcNotification::CancelledNotification(notification) => {
1214 Self::CancelledNotification(notification.params)
1215 }
1216 ServerJsonrpcNotification::ProgressNotification(notification) => Self::ProgressNotification(notification.params),
1217 ServerJsonrpcNotification::ResourceListChangedNotification(notification) => {
1218 Self::ResourceListChangedNotification(notification.params)
1219 }
1220 ServerJsonrpcNotification::ResourceUpdatedNotification(notification) => {
1221 Self::ResourceUpdatedNotification(notification.params)
1222 }
1223 ServerJsonrpcNotification::PromptListChangedNotification(notification) => {
1224 Self::PromptListChangedNotification(notification.params)
1225 }
1226 ServerJsonrpcNotification::ToolListChangedNotification(notification) => {
1227 Self::ToolListChangedNotification(notification.params)
1228 }
1229 ServerJsonrpcNotification::TaskStatusNotification(notification) => {
1230 Self::TaskStatusNotification(notification.params)
1231 }
1232 ServerJsonrpcNotification::LoggingMessageNotification(notification) => {
1233 Self::LoggingMessageNotification(notification.params)
1234 }
1235 ServerJsonrpcNotification::ElicitationCompleteNotification(notification) => {
1236 Self::ElicitationCompleteNotification(notification.params)
1237 }
1238 ServerJsonrpcNotification::CustomNotification(notification) => Self::CustomNotification(CustomNotification {
1239 method: notification.method,
1240 params: notification.params,
1241 }),
1242 }
1243 }
1244}
1245
1246impl ServerJsonrpcNotification {
1248 pub fn new(notification: NotificationFromServer) -> Self {
1249 match notification {
1250 NotificationFromServer::CancelledNotification(params) => {
1251 Self::CancelledNotification(CancelledNotification::new(params))
1252 }
1253 NotificationFromServer::ProgressNotification(params) => {
1254 Self::ProgressNotification(ProgressNotification::new(params))
1255 }
1256 NotificationFromServer::ResourceListChangedNotification(params) => {
1257 Self::ResourceListChangedNotification(ResourceListChangedNotification::new(params))
1258 }
1259 NotificationFromServer::ResourceUpdatedNotification(params) => {
1260 Self::ResourceUpdatedNotification(ResourceUpdatedNotification::new(params))
1261 }
1262 NotificationFromServer::PromptListChangedNotification(params) => {
1263 Self::PromptListChangedNotification(PromptListChangedNotification::new(params))
1264 }
1265 NotificationFromServer::ToolListChangedNotification(params) => {
1266 Self::ToolListChangedNotification(ToolListChangedNotification::new(params))
1267 }
1268 NotificationFromServer::TaskStatusNotification(params) => {
1269 Self::TaskStatusNotification(TaskStatusNotification::new(params))
1270 }
1271 NotificationFromServer::LoggingMessageNotification(params) => {
1272 Self::LoggingMessageNotification(LoggingMessageNotification::new(params))
1273 }
1274 NotificationFromServer::ElicitationCompleteNotification(params) => {
1275 Self::ElicitationCompleteNotification(ElicitationCompleteNotification::new(params))
1276 }
1277 NotificationFromServer::CustomNotification(params) => {
1278 Self::CustomNotification(JsonrpcNotification::new(params.method, params.params))
1279 }
1280 }
1281 }
1282 pub fn jsonrpc(&self) -> &::std::string::String {
1283 match self {
1284 ServerJsonrpcNotification::CancelledNotification(notification) => notification.jsonrpc(),
1285 ServerJsonrpcNotification::ProgressNotification(notification) => notification.jsonrpc(),
1286 ServerJsonrpcNotification::ResourceListChangedNotification(notification) => notification.jsonrpc(),
1287 ServerJsonrpcNotification::ResourceUpdatedNotification(notification) => notification.jsonrpc(),
1288 ServerJsonrpcNotification::PromptListChangedNotification(notification) => notification.jsonrpc(),
1289 ServerJsonrpcNotification::ToolListChangedNotification(notification) => notification.jsonrpc(),
1290 ServerJsonrpcNotification::TaskStatusNotification(notification) => notification.jsonrpc(),
1291 ServerJsonrpcNotification::LoggingMessageNotification(notification) => notification.jsonrpc(),
1292 ServerJsonrpcNotification::ElicitationCompleteNotification(notification) => notification.jsonrpc(),
1293 ServerJsonrpcNotification::CustomNotification(notification) => notification.jsonrpc(),
1294 }
1295 }
1296}
1297
1298impl Display for ServerJsonrpcNotification {
1300 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1301 write!(
1302 f,
1303 "{}",
1304 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1305 )
1306 }
1307}
1308
1309impl FromStr for ServerJsonrpcNotification {
1310 type Err = RpcError;
1311
1312 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1313 serde_json::from_str(s)
1314 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1315 }
1316}
1317#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1324#[serde(untagged)]
1325pub enum NotificationFromServer {
1326 CancelledNotification(CancelledNotificationParams),
1327 ProgressNotification(ProgressNotificationParams),
1328 ResourceListChangedNotification(Option<NotificationParams>),
1329 ResourceUpdatedNotification(ResourceUpdatedNotificationParams),
1330 PromptListChangedNotification(Option<NotificationParams>),
1331 ToolListChangedNotification(Option<NotificationParams>),
1332 TaskStatusNotification(TaskStatusNotificationParams),
1333 LoggingMessageNotification(LoggingMessageNotificationParams),
1334 ElicitationCompleteNotification(ElicitCompleteParams),
1335 CustomNotification(CustomNotification),
1336}
1337
1338impl NotificationFromServer {
1339 pub fn method(&self) -> &str {
1340 match self {
1341 NotificationFromServer::CancelledNotification(_params) => CancelledNotification::method_value(),
1342 NotificationFromServer::ProgressNotification(_params) => CancelledNotification::method_value(),
1343 NotificationFromServer::ResourceListChangedNotification(_params) => CancelledNotification::method_value(),
1344 NotificationFromServer::ResourceUpdatedNotification(_params) => CancelledNotification::method_value(),
1345 NotificationFromServer::PromptListChangedNotification(_params) => CancelledNotification::method_value(),
1346 NotificationFromServer::ToolListChangedNotification(_params) => CancelledNotification::method_value(),
1347 NotificationFromServer::TaskStatusNotification(_params) => CancelledNotification::method_value(),
1348 NotificationFromServer::LoggingMessageNotification(_params) => CancelledNotification::method_value(),
1349 NotificationFromServer::ElicitationCompleteNotification(_params) => CancelledNotification::method_value(),
1350 NotificationFromServer::CustomNotification(params) => params.method.as_str(),
1351 }
1352 }
1353}
1354
1355#[derive(Clone, Debug)]
1361pub struct ServerJsonrpcResponse {
1362 pub id: RequestId,
1363 jsonrpc: ::std::string::String,
1364 pub result: ResultFromServer,
1365}
1366
1367impl ServerJsonrpcResponse {
1368 pub fn new(id: RequestId, result: ResultFromServer) -> Self {
1369 Self {
1370 id,
1371 jsonrpc: JSONRPC_VERSION.to_string(),
1372 result,
1373 }
1374 }
1375 pub fn jsonrpc(&self) -> &::std::string::String {
1376 &self.jsonrpc
1377 }
1378}
1379
1380impl Display for ServerJsonrpcResponse {
1382 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1383 write!(
1384 f,
1385 "{}",
1386 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1387 )
1388 }
1389}
1390
1391impl FromStr for ServerJsonrpcResponse {
1392 type Err = RpcError;
1393
1394 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1395 serde_json::from_str(s)
1396 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1397 }
1398}
1399pub type ResultFromServer = ServerResult;
1403
1404impl Display for JsonrpcErrorResponse {
1410 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1411 write!(
1412 f,
1413 "{}",
1414 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1415 )
1416 }
1417}
1418
1419impl FromStr for JsonrpcErrorResponse {
1420 type Err = RpcError;
1421
1422 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1423 serde_json::from_str(s)
1424 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1425 }
1426}
1427
1428#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1437#[serde(untagged)]
1438pub enum MessageFromServer {
1439 RequestFromServer(RequestFromServer),
1440 ResultFromServer(ResultFromServer),
1441 NotificationFromServer(NotificationFromServer),
1442 Error(RpcError),
1443}
1444
1445impl From<RequestFromServer> for MessageFromServer {
1446 fn from(value: RequestFromServer) -> Self {
1447 Self::RequestFromServer(value)
1448 }
1449}
1450
1451impl From<ResultFromServer> for MessageFromServer {
1452 fn from(value: ResultFromServer) -> Self {
1453 Self::ResultFromServer(value)
1454 }
1455}
1456
1457impl From<NotificationFromServer> for MessageFromServer {
1458 fn from(value: NotificationFromServer) -> Self {
1459 Self::NotificationFromServer(value)
1460 }
1461}
1462
1463impl From<RpcError> for MessageFromServer {
1464 fn from(value: RpcError) -> Self {
1465 Self::Error(value)
1466 }
1467}
1468
1469impl McpMessage for MessageFromServer {
1470 fn is_response(&self) -> bool {
1471 matches!(self, MessageFromServer::ResultFromServer(_))
1472 }
1473
1474 fn is_request(&self) -> bool {
1475 matches!(self, MessageFromServer::RequestFromServer(_))
1476 }
1477
1478 fn is_notification(&self) -> bool {
1479 matches!(self, MessageFromServer::NotificationFromServer(_))
1480 }
1481
1482 fn is_error(&self) -> bool {
1483 matches!(self, MessageFromServer::Error(_))
1484 }
1485
1486 fn message_type(&self) -> MessageTypes {
1487 match self {
1488 MessageFromServer::RequestFromServer(_) => MessageTypes::Request,
1489 MessageFromServer::ResultFromServer(_) => MessageTypes::Response,
1490 MessageFromServer::NotificationFromServer(_) => MessageTypes::Notification,
1491 MessageFromServer::Error(_) => MessageTypes::Error,
1492 }
1493 }
1494}
1495
1496impl FromMessage<MessageFromServer> for ServerMessage {
1497 fn from_message(message: MessageFromServer, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1498 match message {
1499 MessageFromServer::RequestFromServer(request_from_server) => {
1500 let request_id =
1501 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1502
1503 let rpc_message = match request_from_server {
1504 RequestFromServer::PingRequest(params) => {
1505 ServerJsonrpcRequest::PingRequest(PingRequest::new(request_id, params))
1506 }
1507 RequestFromServer::GetTaskRequest(params) => {
1508 ServerJsonrpcRequest::GetTaskRequest(GetTaskRequest::new(request_id, params))
1509 }
1510 RequestFromServer::GetTaskPayloadRequest(params) => {
1511 ServerJsonrpcRequest::GetTaskPayloadRequest(GetTaskPayloadRequest::new(request_id, params))
1512 }
1513 RequestFromServer::CancelTaskRequest(params) => {
1514 ServerJsonrpcRequest::CancelTaskRequest(CancelTaskRequest::new(request_id, params))
1515 }
1516 RequestFromServer::ListTasksRequest(params) => {
1517 ServerJsonrpcRequest::ListTasksRequest(ListTasksRequest::new(request_id, params))
1518 }
1519 RequestFromServer::CreateMessageRequest(params) => {
1520 ServerJsonrpcRequest::CreateMessageRequest(CreateMessageRequest::new(request_id, params))
1521 }
1522 RequestFromServer::ListRootsRequest(params) => {
1523 ServerJsonrpcRequest::ListRootsRequest(ListRootsRequest::new(request_id, params))
1524 }
1525 RequestFromServer::ElicitRequest(params) => {
1526 ServerJsonrpcRequest::ElicitRequest(ElicitRequest::new(request_id, params))
1527 }
1528 RequestFromServer::CustomRequest(params) => {
1529 ServerJsonrpcRequest::CustomRequest(JsonrpcRequest::new(request_id, params.method, params.params))
1530 }
1531 };
1532
1533 Ok(ServerMessage::Request(rpc_message))
1534 }
1535 MessageFromServer::ResultFromServer(result_from_server) => {
1536 let request_id =
1537 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1538 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
1539 request_id,
1540 result_from_server,
1541 )))
1542 }
1543 MessageFromServer::NotificationFromServer(notification_from_server) => {
1544 if request_id.is_some() {
1545 return Err(RpcError::internal_error()
1546 .with_message("request_id expected to be None for Notifications!".to_string()));
1547 }
1548 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(
1549 notification_from_server,
1550 )))
1551 }
1552 MessageFromServer::Error(jsonrpc_error_error) => Ok(ServerMessage::Error(JsonrpcErrorResponse::new(
1553 jsonrpc_error_error,
1554 request_id,
1555 ))),
1556 }
1557 }
1558}
1559
1560#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1569#[serde(untagged)]
1570pub enum MessageFromClient {
1571 RequestFromClient(RequestFromClient),
1572 ResultFromClient(ResultFromClient),
1573 NotificationFromClient(NotificationFromClient),
1574 Error(RpcError),
1575}
1576
1577impl MessageFromClient {
1578 pub fn is_initialize_request(&self) -> bool {
1580 matches!(self, Self::RequestFromClient(RequestFromClient::InitializeRequest(_)))
1581 }
1582
1583 pub fn is_initialized_notification(&self) -> bool {
1585 matches!(
1586 self,
1587 Self::NotificationFromClient(NotificationFromClient::InitializedNotification(_))
1588 )
1589 }
1590}
1591
1592impl From<RequestFromClient> for MessageFromClient {
1593 fn from(value: RequestFromClient) -> Self {
1594 Self::RequestFromClient(value)
1595 }
1596}
1597
1598impl From<ResultFromClient> for MessageFromClient {
1599 fn from(value: ResultFromClient) -> Self {
1600 Self::ResultFromClient(value)
1601 }
1602}
1603
1604impl From<NotificationFromClient> for MessageFromClient {
1605 fn from(value: NotificationFromClient) -> Self {
1606 Self::NotificationFromClient(value)
1607 }
1608}
1609
1610impl From<RpcError> for MessageFromClient {
1611 fn from(value: RpcError) -> Self {
1612 Self::Error(value)
1613 }
1614}
1615
1616impl McpMessage for MessageFromClient {
1617 fn is_response(&self) -> bool {
1618 matches!(self, MessageFromClient::ResultFromClient(_))
1619 }
1620
1621 fn is_request(&self) -> bool {
1622 matches!(self, MessageFromClient::RequestFromClient(_))
1623 }
1624
1625 fn is_notification(&self) -> bool {
1626 matches!(self, MessageFromClient::NotificationFromClient(_))
1627 }
1628
1629 fn is_error(&self) -> bool {
1630 matches!(self, MessageFromClient::Error(_))
1631 }
1632
1633 fn message_type(&self) -> MessageTypes {
1634 match self {
1635 MessageFromClient::RequestFromClient(_) => MessageTypes::Request,
1636 MessageFromClient::ResultFromClient(_) => MessageTypes::Response,
1637 MessageFromClient::NotificationFromClient(_) => MessageTypes::Notification,
1638 MessageFromClient::Error(_) => MessageTypes::Error,
1639 }
1640 }
1641}
1642
1643impl FromMessage<MessageFromClient> for ClientMessage {
1644 fn from_message(message: MessageFromClient, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1645 match message {
1646 MessageFromClient::RequestFromClient(request_from_client) => {
1647 let request_id =
1648 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1649 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(
1650 request_id,
1651 request_from_client,
1652 )))
1653 }
1654 MessageFromClient::ResultFromClient(result_from_client) => {
1655 let request_id =
1656 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1657 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
1658 request_id,
1659 result_from_client,
1660 )))
1661 }
1662 MessageFromClient::NotificationFromClient(notification_from_client) => {
1663 if request_id.is_some() {
1664 return Err(RpcError::internal_error()
1665 .with_message("request_id expected to be None for Notifications!".to_string()));
1666 }
1667
1668 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(
1669 notification_from_client,
1670 )))
1671 }
1672 MessageFromClient::Error(jsonrpc_error_error) => Ok(ClientMessage::Error(JsonrpcErrorResponse::new(
1673 jsonrpc_error_error,
1674 request_id,
1675 ))),
1676 }
1677 }
1678}
1679
1680#[derive(Debug)]
1687pub struct UnknownTool(pub String);
1688
1689impl core::fmt::Display for UnknownTool {
1691 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1692 write!(f, "Unknown tool: {}", self.0)
1694 }
1695}
1696
1697impl std::error::Error for UnknownTool {}
1699
1700#[derive(Debug)]
1706pub struct CallToolError(pub Box<dyn std::error::Error>);
1707
1708impl CallToolError {
1710 pub fn new<E: std::error::Error + 'static>(err: E) -> Self {
1712 CallToolError(Box::new(err))
1714 }
1715
1716 pub fn unknown_tool(tool_name: impl Into<String>) -> Self {
1718 CallToolError(Box::new(UnknownTool(tool_name.into())))
1720 }
1721
1722 pub fn invalid_arguments(tool_name: impl AsRef<str>, message: Option<String>) -> Self {
1725 let tool_name = tool_name.as_ref().trim();
1727 if tool_name.is_empty() {
1728 return Self::from_message("Invalid arguments: tool name cannot be empty".to_string());
1729 }
1730
1731 let default_message = "no additional details provided".to_string();
1733 let message = message.unwrap_or(default_message);
1734
1735 let full_message = format!("Invalid arguments for tool '{tool_name}': {message}");
1737
1738 Self::from_message(full_message)
1739 }
1740
1741 pub fn from_message(message: impl Into<String>) -> Self {
1761 struct MsgError(String);
1762 impl std::fmt::Debug for MsgError {
1763 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1764 write!(f, "{}", self.0)
1765 }
1766 }
1767 impl std::fmt::Display for MsgError {
1768 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1769 write!(f, "{}", self.0)
1770 }
1771 }
1772 impl std::error::Error for MsgError {}
1773
1774 CallToolError::new(MsgError(message.into()))
1775 }
1776}
1777
1778impl From<CallToolError> for RpcError {
1784 fn from(value: CallToolError) -> Self {
1785 Self::internal_error().with_message(value.to_string())
1786 }
1787}
1788
1789impl From<CallToolError> for CallToolResult {
1791 fn from(value: CallToolError) -> Self {
1792 CallToolResult {
1794 content: vec![TextContent::new(value.to_string(), None, None).into()],
1795 is_error: Some(true),
1796 meta: None,
1797 structured_content: None,
1798 }
1799 }
1800}
1801
1802impl core::fmt::Display for CallToolError {
1804 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1805 write!(f, "{}", self.0)
1806 }
1807}
1808
1809impl std::error::Error for CallToolError {
1811 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1812 self.0.source()
1813 }
1814}
1815
1816impl CallToolRequest {
1817 pub fn tool_name(&self) -> &str {
1825 &self.params.name
1826 }
1827}
1828
1829impl<T: Into<String>> From<T> for TextContent {
1830 fn from(value: T) -> Self {
1831 TextContent::new(value.into(), None, None)
1832 }
1833}
1834
1835#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1836#[serde(untagged)]
1837#[allow(clippy::large_enum_variant)]
1838pub enum ClientMessages {
1839 Single(ClientMessage),
1840 Batch(Vec<ClientMessage>),
1841}
1842
1843impl ClientMessages {
1844 pub fn is_batch(&self) -> bool {
1845 matches!(self, ClientMessages::Batch(_))
1846 }
1847
1848 pub fn includes_request(&self) -> bool {
1849 match self {
1850 ClientMessages::Single(client_message) => client_message.is_request(),
1851 ClientMessages::Batch(client_messages) => client_messages.iter().any(ClientMessage::is_request),
1852 }
1853 }
1854
1855 pub fn as_single(self) -> result::Result<ClientMessage, SdkError> {
1856 match self {
1857 ClientMessages::Single(client_message) => Ok(client_message),
1858 ClientMessages::Batch(_) => Err(SdkError::internal_error()
1859 .with_message("Error: cannot convert ClientMessages::Batch to ClientMessage::Single")),
1860 }
1861 }
1862 pub fn as_batch(self) -> result::Result<Vec<ClientMessage>, SdkError> {
1863 match self {
1864 ClientMessages::Single(_) => Err(SdkError::internal_error()
1865 .with_message("Error: cannot convert ClientMessage::Single to ClientMessages::Batch")),
1866 ClientMessages::Batch(client_messages) => Ok(client_messages),
1867 }
1868 }
1869}
1870
1871impl From<ClientMessage> for ClientMessages {
1872 fn from(value: ClientMessage) -> Self {
1873 Self::Single(value)
1874 }
1875}
1876
1877impl From<Vec<ClientMessage>> for ClientMessages {
1878 fn from(value: Vec<ClientMessage>) -> Self {
1879 Self::Batch(value)
1880 }
1881}
1882
1883impl Display for ClientMessages {
1884 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1885 write!(
1886 f,
1887 "{}",
1888 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1889 )
1890 }
1891}
1892
1893#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1894#[serde(untagged)]
1895#[allow(clippy::large_enum_variant)]
1896pub enum ServerMessages {
1897 Single(ServerMessage),
1898 Batch(Vec<ServerMessage>),
1899}
1900
1901impl ServerMessages {
1902 pub fn is_batch(&self) -> bool {
1903 matches!(self, ServerMessages::Batch(_))
1904 }
1905
1906 pub fn includes_request(&self) -> bool {
1907 match self {
1908 ServerMessages::Single(server_message) => server_message.is_request(),
1909 ServerMessages::Batch(server_messages) => server_messages.iter().any(ServerMessage::is_request),
1910 }
1911 }
1912
1913 pub fn as_single(self) -> result::Result<ServerMessage, SdkError> {
1914 match self {
1915 ServerMessages::Single(server_message) => Ok(server_message),
1916 ServerMessages::Batch(_) => Err(SdkError::internal_error()
1917 .with_message("Error: cannot convert ServerMessages::Batch to ServerMessage::Single")),
1918 }
1919 }
1920 pub fn as_batch(self) -> result::Result<Vec<ServerMessage>, SdkError> {
1921 match self {
1922 ServerMessages::Single(_) => Err(SdkError::internal_error()
1923 .with_message("Error: cannot convert ServerMessage::Single to ServerMessages::Batch")),
1924 ServerMessages::Batch(server_messages) => Ok(server_messages),
1925 }
1926 }
1927}
1928
1929impl From<ServerMessage> for ServerMessages {
1930 fn from(value: ServerMessage) -> Self {
1931 Self::Single(value)
1932 }
1933}
1934
1935impl From<Vec<ServerMessage>> for ServerMessages {
1936 fn from(value: Vec<ServerMessage>) -> Self {
1937 Self::Batch(value)
1938 }
1939}
1940
1941impl Display for ServerMessages {
1942 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1943 write!(
1944 f,
1945 "{}",
1946 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1947 )
1948 }
1949}
1950
1951#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1952#[serde(untagged)]
1953#[allow(clippy::large_enum_variant)]
1954pub enum MessagesFromServer {
1955 Single(MessageFromServer),
1956 Batch(Vec<MessageFromServer>),
1957}
1958
1959impl MessagesFromServer {
1960 pub fn is_batch(&self) -> bool {
1961 matches!(self, MessagesFromServer::Batch(_))
1962 }
1963
1964 pub fn includes_request(&self) -> bool {
1965 match self {
1966 MessagesFromServer::Single(server_message) => server_message.is_request(),
1967 MessagesFromServer::Batch(server_messages) => server_messages.iter().any(MessageFromServer::is_request),
1968 }
1969 }
1970
1971 pub fn as_single(self) -> result::Result<MessageFromServer, SdkError> {
1972 match self {
1973 MessagesFromServer::Single(server_message) => Ok(server_message),
1974 MessagesFromServer::Batch(_) => Err(SdkError::internal_error()
1975 .with_message("Error: cannot convert MessagesFromServer::Batch to MessageFromServer::Single")),
1976 }
1977 }
1978 pub fn as_batch(self) -> result::Result<Vec<MessageFromServer>, SdkError> {
1979 match self {
1980 MessagesFromServer::Single(_) => Err(SdkError::internal_error()
1981 .with_message("Error: cannot convert MessageFromServer::Single to MessagesFromServer::Batch")),
1982 MessagesFromServer::Batch(server_messages) => Ok(server_messages),
1983 }
1984 }
1985}
1986
1987impl From<MessageFromServer> for MessagesFromServer {
1988 fn from(value: MessageFromServer) -> Self {
1989 Self::Single(value)
1990 }
1991}
1992
1993impl From<Vec<MessageFromServer>> for MessagesFromServer {
1994 fn from(value: Vec<MessageFromServer>) -> Self {
1995 Self::Batch(value)
1996 }
1997}
1998
1999#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2000#[serde(untagged)]
2001#[allow(clippy::large_enum_variant)]
2002pub enum MessagesFromClient {
2003 Single(MessageFromClient),
2004 Batch(Vec<MessageFromClient>),
2005}
2006
2007impl MessagesFromClient {
2008 pub fn is_batch(&self) -> bool {
2009 matches!(self, MessagesFromClient::Batch(_))
2010 }
2011
2012 pub fn includes_request(&self) -> bool {
2013 match self {
2014 MessagesFromClient::Single(server_message) => server_message.is_request(),
2015 MessagesFromClient::Batch(server_messages) => server_messages.iter().any(MessageFromClient::is_request),
2016 }
2017 }
2018
2019 pub fn as_single(self) -> result::Result<MessageFromClient, SdkError> {
2020 match self {
2021 MessagesFromClient::Single(server_message) => Ok(server_message),
2022 MessagesFromClient::Batch(_) => Err(SdkError::internal_error()
2023 .with_message("Error: cannot convert MessagesFromClient::Batch to MessageFromClient::Single")),
2024 }
2025 }
2026 pub fn as_batch(self) -> result::Result<Vec<MessageFromClient>, SdkError> {
2027 match self {
2028 MessagesFromClient::Single(_) => Err(SdkError::internal_error()
2029 .with_message("Error: cannot convert MessageFromClient::Single to MessagesFromClient::Batch")),
2030 MessagesFromClient::Batch(server_messages) => Ok(server_messages),
2031 }
2032 }
2033}
2034
2035impl From<MessageFromClient> for MessagesFromClient {
2036 fn from(value: MessageFromClient) -> Self {
2037 Self::Single(value)
2038 }
2039}
2040
2041impl From<Vec<MessageFromClient>> for MessagesFromClient {
2042 fn from(value: Vec<MessageFromClient>) -> Self {
2043 Self::Batch(value)
2044 }
2045}
2046
2047#[derive(Debug)]
2048pub struct StringSchemaFormatError {
2049 invalid_value: String,
2050}
2051
2052impl core::fmt::Display for StringSchemaFormatError {
2053 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2054 write!(f, "Invalid string schema format: '{}'", self.invalid_value)
2055 }
2056}
2057
2058impl std::error::Error for StringSchemaFormatError {}
2059
2060impl FromStr for StringSchemaFormat {
2061 type Err = StringSchemaFormatError;
2062
2063 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2064 match s {
2065 "date" => Ok(Self::Date),
2066 "date-time" => Ok(Self::DateTime),
2067 "email" => Ok(Self::Email),
2068 "uri" => Ok(Self::Uri),
2069 _ => Err(StringSchemaFormatError {
2070 invalid_value: s.to_string(),
2071 }),
2072 }
2073 }
2074}
2075
2076fn try_from_enum_schema(map: &serde_json::Map<String, Value>) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2078 let has_one_of = map.contains_key("oneOf");
2080 let has_enum = map.contains_key("enum");
2081 let has_enum_names = map.contains_key("enumNames");
2082
2083 if has_one_of {
2084 let schema: TitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2085 RpcError::parse_error().with_message(format!("Failed to parse TitledSingleSelectEnumSchema: {e}"))
2086 })?;
2087
2088 Ok(PrimitiveSchemaDefinition::TitledSingleSelectEnumSchema(schema))
2089 } else if has_enum && has_enum_names {
2090 let schema: LegacyTitledEnumSchema = serde_json::from_value(Value::Object(map.clone()))
2091 .map_err(|e| RpcError::parse_error().with_message(format!("Failed to parse LegacyTitledEnumSchema: {e}")))?;
2092 Ok(PrimitiveSchemaDefinition::LegacyTitledEnumSchema(schema))
2093 } else if has_enum {
2094 let schema: UntitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2095 RpcError::parse_error().with_message(format!("Failed to parse UntitledSingleSelectEnumSchema: {e}"))
2096 })?;
2097 Ok(PrimitiveSchemaDefinition::UntitledSingleSelectEnumSchema(schema))
2098 } else {
2099 Err(RpcError::parse_error().with_message("Invalid enum schema: missing 'enum' or 'oneOf'".to_string()))
2100 }
2101}
2102
2103fn try_from_multi_select_schema(
2105 map: &serde_json::Map<String, Value>,
2106) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2107 let items = map
2108 .get("items")
2109 .ok_or(RpcError::parse_error().with_message("Array schema missing 'items' field".to_string()))?;
2110
2111 let items_obj = items
2112 .as_object()
2113 .ok_or(RpcError::parse_error().with_message("Field 'items' must be an object".to_string()))?;
2114
2115 if items_obj.contains_key("anyOf") {
2116 let schema: TitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2117 RpcError::parse_error().with_message(format!("Failed to parse TitledMultiSelectEnumSchema: {e}"))
2118 })?;
2119 Ok(PrimitiveSchemaDefinition::TitledMultiSelectEnumSchema(schema))
2120 } else if items_obj.contains_key("enum") {
2121 let schema: UntitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2122 RpcError::parse_error().with_message(format!("Failed to parse UntitledMultiSelectEnumSchema: {e}"))
2123 })?;
2124 Ok(PrimitiveSchemaDefinition::UntitledMultiSelectEnumSchema(schema))
2125 } else {
2126 Err(RpcError::parse_error()
2127 .with_message("Array schema 'items' must contain 'enum' or 'oneOf' to be a multi-select enum".to_string()))
2128 }
2129}
2130
2131impl TryFrom<&serde_json::Map<String, Value>> for PrimitiveSchemaDefinition {
2132 type Error = RpcError;
2133
2134 fn try_from(value: &serde_json::Map<String, serde_json::Value>) -> result::Result<Self, Self::Error> {
2135 if value.contains_key("enum") || value.contains_key("oneOf") {
2137 return try_from_enum_schema(value);
2138 }
2139
2140 if value.get("type").and_then(|v| v.as_str()) == Some("array") {
2142 return try_from_multi_select_schema(value);
2143 }
2144
2145 let input_type = value
2146 .get("type")
2147 .and_then(|v| v.as_str())
2148 .or_else(|| value.get("oneOf").map(|_| "enum")) .ok_or_else(|| {
2150 RpcError::parse_error().with_message("'type' is missing and data type is not supported!".to_string())
2151 })?;
2152
2153 let description = value.get("description").and_then(|v| v.as_str().map(|s| s.to_string()));
2154 let title = value.get("title").and_then(|v| v.as_str().map(|s| s.to_string()));
2155
2156 let schema_definition: PrimitiveSchemaDefinition = match input_type {
2157 "string" => {
2158 let max_length = value.get("maxLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2159 let min_length = value.get("minLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2160 let default = value.get("default").and_then(|v| v.as_str().map(|s| s.to_string()));
2161
2162 let format_str = value.get("format").and_then(|v| v.as_str());
2163 let format = format_str.and_then(|s| StringSchemaFormat::from_str(s).ok());
2164
2165 PrimitiveSchemaDefinition::StringSchema(StringSchema::new(
2166 default,
2167 description,
2168 format,
2169 max_length,
2170 min_length,
2171 title,
2172 ))
2173 }
2174 "number" | "integer" => {
2175 let maximum = value.get("maximum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2176 let minimum = value.get("minimum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2177 let default = value.get("default").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2178
2179 PrimitiveSchemaDefinition::NumberSchema(NumberSchema {
2180 default,
2181 description,
2182 maximum,
2183 minimum,
2184 title,
2185 type_: if input_type == "integer" {
2186 NumberSchemaType::Integer
2187 } else {
2188 NumberSchemaType::Number
2189 },
2190 })
2191 }
2192 "boolean" => {
2193 let default = value.get("default").and_then(|v| v.as_bool().map(|s| s.to_owned()));
2194 PrimitiveSchemaDefinition::BooleanSchema(BooleanSchema::new(default, description, title))
2195 }
2196 other => {
2197 return Err(RpcError::parse_error().with_message(format!("'{other}' type is not currently supported")));
2198 }
2199 };
2200
2201 Ok(schema_definition)
2202 }
2203}
2204
2205pub type CustomNotification = CustomRequest;
2206
2207impl ::serde::Serialize for ServerJsonrpcResponse {
2209 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2210 where
2211 S: ::serde::Serializer,
2212 {
2213 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
2214 state.serialize_field("id", &self.id)?;
2215 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2216 state.serialize_field("result", &self.result)?;
2217 state.end()
2218 }
2219}
2220impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcResponse {
2221 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2222 where
2223 D: ::serde::Deserializer<'de>,
2224 {
2225 use serde::de::{self, MapAccess, Visitor};
2226 use std::fmt;
2227 struct ServerJsonrpcResultVisitor;
2228 impl<'de> Visitor<'de> for ServerJsonrpcResultVisitor {
2229 type Value = ServerJsonrpcResponse;
2230 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2231 formatter.write_str("a valid JSON-RPC response object")
2232 }
2233 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcResponse, M::Error>
2234 where
2235 M: MapAccess<'de>,
2236 {
2237 let mut id: Option<RequestId> = None;
2238 let mut jsonrpc: Option<String> = None;
2239 let mut result: Option<Value> = None;
2240 while let Some(key) = map.next_key::<String>()? {
2241 match key.as_str() {
2242 "id" => id = Some(map.next_value()?),
2243 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2244 "result" => result = Some(map.next_value()?),
2245 _ => {
2246 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
2247 }
2248 }
2249 }
2250 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
2251 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2252 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
2253 let result = serde_json::from_value::<ResultFromServer>(result).map_err(de::Error::custom)?;
2254 Ok(ServerJsonrpcResponse { id, jsonrpc, result })
2255 }
2256 }
2257 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ServerJsonrpcResultVisitor)
2258 }
2259}
2260impl ::serde::Serialize for ClientJsonrpcResponse {
2261 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2262 where
2263 S: ::serde::Serializer,
2264 {
2265 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
2266 state.serialize_field("id", &self.id)?;
2267 state.serialize_field("jsonrpc", &self.jsonrpc)?;
2268 state.serialize_field("result", &self.result)?;
2269 state.end()
2270 }
2271}
2272impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcResponse {
2273 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2274 where
2275 D: ::serde::Deserializer<'de>,
2276 {
2277 use serde::de::{self, MapAccess, Visitor};
2278 use std::fmt;
2279 struct ClientJsonrpcResultVisitor;
2280 impl<'de> Visitor<'de> for ClientJsonrpcResultVisitor {
2281 type Value = ClientJsonrpcResponse;
2282 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2283 formatter.write_str("a valid JSON-RPC response object")
2284 }
2285 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcResponse, M::Error>
2286 where
2287 M: MapAccess<'de>,
2288 {
2289 let mut id: Option<RequestId> = None;
2290 let mut jsonrpc: Option<String> = None;
2291 let mut result: Option<Value> = None;
2292 while let Some(key) = map.next_key::<String>()? {
2293 match key.as_str() {
2294 "id" => id = Some(map.next_value()?),
2295 "jsonrpc" => jsonrpc = Some(map.next_value()?),
2296 "result" => result = Some(map.next_value()?),
2297 _ => {
2298 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
2299 }
2300 }
2301 }
2302 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
2303 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2304 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
2305 let result = serde_json::from_value::<ResultFromClient>(result).map_err(de::Error::custom)?;
2306 Ok(ClientJsonrpcResponse { id, jsonrpc, result })
2307 }
2308 }
2309 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ClientJsonrpcResultVisitor)
2310 }
2311}
2312#[allow(non_camel_case_types)]
2314pub enum SdkErrorCodes {
2315 CONNECTION_CLOSED = -32000,
2316 REQUEST_TIMEOUT = -32001,
2317 RESOURCE_NOT_FOUND = -32002,
2318 BAD_REQUEST = -32015,
2319 SESSION_NOT_FOUND = -32016,
2320 INVALID_REQUEST = -32600,
2321 METHOD_NOT_FOUND = -32601,
2322 INVALID_PARAMS = -32602,
2323 INTERNAL_ERROR = -32603,
2324 PARSE_ERROR = -32700,
2325 URL_ELICITATION_REQUIRED = -32042,
2326}
2327impl core::fmt::Display for SdkErrorCodes {
2328 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2329 match self {
2330 SdkErrorCodes::CONNECTION_CLOSED => write!(f, "Connection closed"),
2331 SdkErrorCodes::REQUEST_TIMEOUT => write!(f, "Request timeout"),
2332 SdkErrorCodes::INVALID_REQUEST => write!(f, "Invalid request"),
2333 SdkErrorCodes::METHOD_NOT_FOUND => write!(f, "Method not found"),
2334 SdkErrorCodes::INVALID_PARAMS => write!(f, "Invalid params"),
2335 SdkErrorCodes::INTERNAL_ERROR => write!(f, "Internal error"),
2336 SdkErrorCodes::PARSE_ERROR => write!(f, "Parse Error"),
2337 SdkErrorCodes::RESOURCE_NOT_FOUND => write!(f, "Resource not found"),
2338 SdkErrorCodes::BAD_REQUEST => write!(f, "Bad request"),
2339 SdkErrorCodes::SESSION_NOT_FOUND => write!(f, "Session not found"),
2340 SdkErrorCodes::URL_ELICITATION_REQUIRED => {
2341 write!(
2342 f,
2343 "A required URL was not provided. Please supply the requested URL to continue."
2344 )
2345 }
2346 }
2347 }
2348}
2349impl From<SdkErrorCodes> for i64 {
2350 fn from(code: SdkErrorCodes) -> Self {
2351 code as i64
2352 }
2353}
2354#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
2355pub struct SdkError {
2356 pub code: i64,
2358 pub data: ::std::option::Option<::serde_json::Value>,
2360 pub message: ::std::string::String,
2362}
2363impl core::fmt::Display for SdkError {
2364 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2365 write!(f, "MCP error {}: {}", self.code, self.message)
2366 }
2367}
2368impl std::error::Error for SdkError {
2369 fn description(&self) -> &str {
2370 &self.message
2371 }
2372}
2373impl SdkError {
2374 pub fn new(
2375 error_code: SdkErrorCodes,
2376 message: ::std::string::String,
2377 data: ::std::option::Option<::serde_json::Value>,
2378 ) -> Self {
2379 Self {
2380 code: error_code.into(),
2381 data,
2382 message,
2383 }
2384 }
2385 pub fn connection_closed() -> Self {
2386 Self {
2387 code: SdkErrorCodes::CONNECTION_CLOSED.into(),
2388 data: None,
2389 message: SdkErrorCodes::CONNECTION_CLOSED.to_string(),
2390 }
2391 }
2392 pub fn request_timeout(timeout: u128) -> Self {
2393 Self {
2394 code: SdkErrorCodes::REQUEST_TIMEOUT.into(),
2395 data: Some(json!({ "timeout" : timeout })),
2396 message: SdkErrorCodes::REQUEST_TIMEOUT.to_string(),
2397 }
2398 }
2399 pub fn session_not_found() -> Self {
2400 Self {
2401 code: SdkErrorCodes::SESSION_NOT_FOUND.into(),
2402 data: None,
2403 message: SdkErrorCodes::SESSION_NOT_FOUND.to_string(),
2404 }
2405 }
2406 pub fn invalid_request() -> Self {
2407 Self {
2408 code: SdkErrorCodes::INVALID_REQUEST.into(),
2409 data: None,
2410 message: SdkErrorCodes::INVALID_REQUEST.to_string(),
2411 }
2412 }
2413 pub fn method_not_found() -> Self {
2414 Self {
2415 code: SdkErrorCodes::METHOD_NOT_FOUND.into(),
2416 data: None,
2417 message: SdkErrorCodes::METHOD_NOT_FOUND.to_string(),
2418 }
2419 }
2420 pub fn invalid_params() -> Self {
2421 Self {
2422 code: SdkErrorCodes::INVALID_PARAMS.into(),
2423 data: None,
2424 message: SdkErrorCodes::INVALID_PARAMS.to_string(),
2425 }
2426 }
2427 pub fn internal_error() -> Self {
2428 Self {
2429 code: SdkErrorCodes::INTERNAL_ERROR.into(),
2430 data: None,
2431 message: SdkErrorCodes::INTERNAL_ERROR.to_string(),
2432 }
2433 }
2434 pub fn parse_error() -> Self {
2435 Self {
2436 code: SdkErrorCodes::PARSE_ERROR.into(),
2437 data: None,
2438 message: SdkErrorCodes::PARSE_ERROR.to_string(),
2439 }
2440 }
2441 pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
2448 Self {
2449 code: UrlElicitError::code_value(),
2450 data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
2451 json!(
2452 { "elicitations" : [], "error" :
2453 "failed to UrlElicitError data" }
2454 )
2455 })),
2456 message: "URL required. Please provide a URL.".to_string(),
2457 }
2458 }
2459 pub fn resource_not_found() -> Self {
2460 Self {
2461 code: SdkErrorCodes::RESOURCE_NOT_FOUND.into(),
2462 data: None,
2463 message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
2464 }
2465 }
2466 pub fn bad_request() -> Self {
2467 Self {
2468 code: SdkErrorCodes::BAD_REQUEST.into(),
2469 data: None,
2470 message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
2471 }
2472 }
2473 pub fn with_message(mut self, message: &str) -> Self {
2474 self.message = message.to_string();
2475 self
2476 }
2477 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
2478 self.data = data;
2479 self
2480 }
2481}
2482#[allow(non_camel_case_types)]
2484pub enum RpcErrorCodes {
2485 PARSE_ERROR = -32700isize,
2486 INVALID_REQUEST = -32600isize,
2487 METHOD_NOT_FOUND = -32601isize,
2488 INVALID_PARAMS = -32602isize,
2489 INTERNAL_ERROR = -32603isize,
2490 URL_ELICITATION_REQUIRED = -32042isize,
2491}
2492impl From<RpcErrorCodes> for i64 {
2493 fn from(code: RpcErrorCodes) -> Self {
2494 code as i64
2495 }
2496}
2497impl RpcError {
2498 pub fn new(
2515 error_code: RpcErrorCodes,
2516 message: ::std::string::String,
2517 data: ::std::option::Option<::serde_json::Value>,
2518 ) -> Self {
2519 Self {
2520 code: error_code.into(),
2521 data,
2522 message,
2523 }
2524 }
2525 pub fn method_not_found() -> Self {
2536 Self {
2537 code: RpcErrorCodes::METHOD_NOT_FOUND.into(),
2538 data: None,
2539 message: "Method not found".to_string(),
2540 }
2541 }
2542 pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
2549 Self {
2550 code: UrlElicitError::code_value(),
2551 data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
2552 json!(
2553 { "elicitations" : [], "error" :
2554 "failed to UrlElicitError data" }
2555 )
2556 })),
2557 message: "URL required. Please provide a URL.".to_string(),
2558 }
2559 }
2560 pub fn invalid_params() -> Self {
2570 Self {
2571 code: RpcErrorCodes::INVALID_PARAMS.into(),
2572 data: None,
2573 message: "Invalid params".to_string(),
2574 }
2575 }
2576 pub fn invalid_request() -> Self {
2586 Self {
2587 code: RpcErrorCodes::INVALID_REQUEST.into(),
2588 data: None,
2589 message: "Invalid request".to_string(),
2590 }
2591 }
2592 pub fn internal_error() -> Self {
2602 Self {
2603 code: RpcErrorCodes::INTERNAL_ERROR.into(),
2604 data: None,
2605 message: "Internal error".to_string(),
2606 }
2607 }
2608 pub fn parse_error() -> Self {
2618 Self {
2619 code: RpcErrorCodes::PARSE_ERROR.into(),
2620 data: None,
2621 message: "Parse error".to_string(),
2622 }
2623 }
2624 pub fn with_message(mut self, message: String) -> Self {
2634 self.message = message;
2635 self
2636 }
2637 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
2648 self.data = data;
2649 self
2650 }
2651}
2652impl std::error::Error for RpcError {
2653 fn description(&self) -> &str {
2654 &self.message
2655 }
2656}
2657impl Display for RpcError {
2658 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2659 write!(
2660 f,
2661 "{}",
2662 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
2663 )
2664 }
2665}
2666impl FromStr for RpcError {
2667 type Err = RpcError;
2668 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2669 serde_json::from_str(s)
2670 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
2671 }
2672}
2673impl JsonrpcErrorResponse {
2675 pub fn create(
2676 id: Option<RequestId>,
2677 error_code: RpcErrorCodes,
2678 error_message: ::std::string::String,
2679 error_data: ::std::option::Option<::serde_json::Value>,
2680 ) -> Self {
2681 Self::new(RpcError::new(error_code, error_message, error_data), id)
2682 }
2683}
2684impl TryFrom<ResultFromClient> for GenericResult {
2685 type Error = RpcError;
2686 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
2687 match value {
2688 ClientResult::GetTaskPayloadResult(result) => Ok(result.into()),
2689 ClientResult::Result(result) => Ok(result),
2690 _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
2691 }
2692 }
2693}
2694impl TryFrom<ResultFromClient> for GetTaskResult {
2695 type Error = RpcError;
2696 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
2697 if let ClientResult::GetTaskResult(result) = value {
2698 Ok(result)
2699 } else {
2700 Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
2701 }
2702 }
2703}
2704impl TryFrom<ResultFromClient> for GetTaskPayloadResult {
2705 type Error = RpcError;
2706 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
2707 if let ClientResult::GetTaskPayloadResult(result) = value {
2708 Ok(result)
2709 } else {
2710 Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
2711 }
2712 }
2713}
2714impl TryFrom<ResultFromClient> for CancelTaskResult {
2715 type Error = RpcError;
2716 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
2717 if let ClientResult::CancelTaskResult(result) = value {
2718 Ok(result)
2719 } else {
2720 Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
2721 }
2722 }
2723}
2724impl TryFrom<ResultFromClient> for ListTasksResult {
2725 type Error = RpcError;
2726 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
2727 if let ClientResult::ListTasksResult(result) = value {
2728 Ok(result)
2729 } else {
2730 Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
2731 }
2732 }
2733}
2734impl TryFrom<ResultFromClient> for CreateMessageResult {
2735 type Error = RpcError;
2736 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
2737 if let ClientResult::CreateMessageResult(result) = value {
2738 Ok(result)
2739 } else {
2740 Err(RpcError::internal_error().with_message("Not a CreateMessageResult".to_string()))
2741 }
2742 }
2743}
2744impl TryFrom<ResultFromClient> for ListRootsResult {
2745 type Error = RpcError;
2746 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
2747 if let ClientResult::ListRootsResult(result) = value {
2748 Ok(result)
2749 } else {
2750 Err(RpcError::internal_error().with_message("Not a ListRootsResult".to_string()))
2751 }
2752 }
2753}
2754impl TryFrom<ResultFromClient> for ElicitResult {
2755 type Error = RpcError;
2756 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
2757 if let ClientResult::ElicitResult(result) = value {
2758 Ok(result)
2759 } else {
2760 Err(RpcError::internal_error().with_message("Not a ElicitResult".to_string()))
2761 }
2762 }
2763}
2764impl TryFrom<ResultFromServer> for GenericResult {
2765 type Error = RpcError;
2766 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2767 match value {
2768 ServerResult::GetTaskPayloadResult(result) => Ok(result.into()),
2769 ServerResult::Result(result) => Ok(result),
2770 _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
2771 }
2772 }
2773}
2774impl TryFrom<ResultFromServer> for InitializeResult {
2775 type Error = RpcError;
2776 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2777 if let ServerResult::InitializeResult(result) = value {
2778 Ok(result)
2779 } else {
2780 Err(RpcError::internal_error().with_message("Not a InitializeResult".to_string()))
2781 }
2782 }
2783}
2784impl TryFrom<ResultFromServer> for ListResourcesResult {
2785 type Error = RpcError;
2786 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2787 if let ServerResult::ListResourcesResult(result) = value {
2788 Ok(result)
2789 } else {
2790 Err(RpcError::internal_error().with_message("Not a ListResourcesResult".to_string()))
2791 }
2792 }
2793}
2794impl TryFrom<ResultFromServer> for ListResourceTemplatesResult {
2795 type Error = RpcError;
2796 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2797 if let ServerResult::ListResourceTemplatesResult(result) = value {
2798 Ok(result)
2799 } else {
2800 Err(RpcError::internal_error().with_message("Not a ListResourceTemplatesResult".to_string()))
2801 }
2802 }
2803}
2804impl TryFrom<ResultFromServer> for ReadResourceResult {
2805 type Error = RpcError;
2806 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2807 if let ServerResult::ReadResourceResult(result) = value {
2808 Ok(result)
2809 } else {
2810 Err(RpcError::internal_error().with_message("Not a ReadResourceResult".to_string()))
2811 }
2812 }
2813}
2814impl TryFrom<ResultFromServer> for ListPromptsResult {
2815 type Error = RpcError;
2816 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2817 if let ServerResult::ListPromptsResult(result) = value {
2818 Ok(result)
2819 } else {
2820 Err(RpcError::internal_error().with_message("Not a ListPromptsResult".to_string()))
2821 }
2822 }
2823}
2824impl TryFrom<ResultFromServer> for GetPromptResult {
2825 type Error = RpcError;
2826 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2827 if let ServerResult::GetPromptResult(result) = value {
2828 Ok(result)
2829 } else {
2830 Err(RpcError::internal_error().with_message("Not a GetPromptResult".to_string()))
2831 }
2832 }
2833}
2834impl TryFrom<ResultFromServer> for ListToolsResult {
2835 type Error = RpcError;
2836 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2837 if let ServerResult::ListToolsResult(result) = value {
2838 Ok(result)
2839 } else {
2840 Err(RpcError::internal_error().with_message("Not a ListToolsResult".to_string()))
2841 }
2842 }
2843}
2844impl TryFrom<ResultFromServer> for CallToolResult {
2845 type Error = RpcError;
2846 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2847 if let ServerResult::CallToolResult(result) = value {
2848 Ok(result)
2849 } else {
2850 Err(RpcError::internal_error().with_message("Not a CallToolResult".to_string()))
2851 }
2852 }
2853}
2854impl TryFrom<ResultFromServer> for GetTaskResult {
2855 type Error = RpcError;
2856 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2857 if let ServerResult::GetTaskResult(result) = value {
2858 Ok(result)
2859 } else {
2860 Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
2861 }
2862 }
2863}
2864impl TryFrom<ResultFromServer> for GetTaskPayloadResult {
2865 type Error = RpcError;
2866 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2867 if let ServerResult::GetTaskPayloadResult(result) = value {
2868 Ok(result)
2869 } else {
2870 Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
2871 }
2872 }
2873}
2874impl TryFrom<ResultFromServer> for CancelTaskResult {
2875 type Error = RpcError;
2876 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2877 if let ServerResult::CancelTaskResult(result) = value {
2878 Ok(result)
2879 } else {
2880 Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
2881 }
2882 }
2883}
2884impl TryFrom<ResultFromServer> for ListTasksResult {
2885 type Error = RpcError;
2886 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2887 if let ServerResult::ListTasksResult(result) = value {
2888 Ok(result)
2889 } else {
2890 Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
2891 }
2892 }
2893}
2894impl TryFrom<ResultFromServer> for CompleteResult {
2895 type Error = RpcError;
2896 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
2897 if let ServerResult::CompleteResult(result) = value {
2898 Ok(result)
2899 } else {
2900 Err(RpcError::internal_error().with_message("Not a CompleteResult".to_string()))
2901 }
2902 }
2903}
2904impl ContentBlock {
2905 pub fn text_content(text: ::std::string::String) -> Self {
2907 TextContent::new(text, None, None).into()
2908 }
2909 pub fn image_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
2911 ImageContent::new(data, mime_type, None, None).into()
2912 }
2913 pub fn audio_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
2915 AudioContent::new(data, mime_type, None, None).into()
2916 }
2917 pub fn resource_link(value: ResourceLink) -> Self {
2919 value.into()
2920 }
2921 pub fn embedded_resource(resource: EmbeddedResourceResource) -> Self {
2923 EmbeddedResource::new(resource, None, None).into()
2924 }
2925 pub fn content_type(&self) -> &str {
2927 match self {
2928 ContentBlock::TextContent(text_content) => text_content.type_(),
2929 ContentBlock::ImageContent(image_content) => image_content.type_(),
2930 ContentBlock::AudioContent(audio_content) => audio_content.type_(),
2931 ContentBlock::ResourceLink(resource_link) => resource_link.type_(),
2932 ContentBlock::EmbeddedResource(embedded_resource) => embedded_resource.type_(),
2933 }
2934 }
2935 pub fn as_text_content(&self) -> std::result::Result<&TextContent, RpcError> {
2937 match &self {
2938 ContentBlock::TextContent(text_content) => Ok(text_content),
2939 _ => Err(RpcError::internal_error().with_message(format!(
2940 "Invalid conversion, \"{}\" is not a {}",
2941 self.content_type(),
2942 "TextContent"
2943 ))),
2944 }
2945 }
2946 pub fn as_image_content(&self) -> std::result::Result<&ImageContent, RpcError> {
2948 match &self {
2949 ContentBlock::ImageContent(image_content) => Ok(image_content),
2950 _ => Err(RpcError::internal_error().with_message(format!(
2951 "Invalid conversion, \"{}\" is not a {}",
2952 self.content_type(),
2953 "ImageContent"
2954 ))),
2955 }
2956 }
2957 pub fn as_audio_content(&self) -> std::result::Result<&AudioContent, RpcError> {
2959 match &self {
2960 ContentBlock::AudioContent(audio_content) => Ok(audio_content),
2961 _ => Err(RpcError::internal_error().with_message(format!(
2962 "Invalid conversion, \"{}\" is not a {}",
2963 self.content_type(),
2964 "AudioContent"
2965 ))),
2966 }
2967 }
2968 pub fn as_resource_link(&self) -> std::result::Result<&ResourceLink, RpcError> {
2970 match &self {
2971 ContentBlock::ResourceLink(resource_link) => Ok(resource_link),
2972 _ => Err(RpcError::internal_error().with_message(format!(
2973 "Invalid conversion, \"{}\" is not a {}",
2974 self.content_type(),
2975 "ResourceLink"
2976 ))),
2977 }
2978 }
2979 pub fn as_embedded_resource(&self) -> std::result::Result<&EmbeddedResource, RpcError> {
2981 match &self {
2982 ContentBlock::EmbeddedResource(embedded_resource) => Ok(embedded_resource),
2983 _ => Err(RpcError::internal_error().with_message(format!(
2984 "Invalid conversion, \"{}\" is not a {}",
2985 self.content_type(),
2986 "EmbeddedResource"
2987 ))),
2988 }
2989 }
2990}
2991impl CallToolResult {
2992 pub fn text_content(content: Vec<TextContent>) -> Self {
2993 Self {
2994 content: content.into_iter().map(Into::into).collect(),
2995 is_error: None,
2996 meta: None,
2997 structured_content: None,
2998 }
2999 }
3000 pub fn image_content(content: Vec<ImageContent>) -> Self {
3001 Self {
3002 content: content.into_iter().map(Into::into).collect(),
3003 is_error: None,
3004 meta: None,
3005 structured_content: None,
3006 }
3007 }
3008 pub fn audio_content(content: Vec<AudioContent>) -> Self {
3009 Self {
3010 content: content.into_iter().map(Into::into).collect(),
3011 is_error: None,
3012 meta: None,
3013 structured_content: None,
3014 }
3015 }
3016 pub fn resource_link(content: Vec<ResourceLink>) -> Self {
3017 Self {
3018 content: content.into_iter().map(Into::into).collect(),
3019 is_error: None,
3020 meta: None,
3021 structured_content: None,
3022 }
3023 }
3024 pub fn embedded_resource(content: Vec<EmbeddedResource>) -> Self {
3025 Self {
3026 content: content.into_iter().map(Into::into).collect(),
3027 is_error: None,
3028 meta: None,
3029 structured_content: None,
3030 }
3031 }
3032 pub fn with_error(error: CallToolError) -> Self {
3034 Self {
3035 content: vec![ContentBlock::TextContent(TextContent::new(error.to_string(), None, None))],
3036 is_error: Some(true),
3037 meta: None,
3038 structured_content: None,
3039 }
3040 }
3041 pub fn with_meta(mut self, meta: Option<serde_json::Map<String, Value>>) -> Self {
3043 self.meta = meta;
3044 self
3045 }
3046 pub fn with_structured_content(
3048 mut self,
3049 structured_content: ::serde_json::Map<::std::string::String, ::serde_json::Value>,
3050 ) -> Self {
3051 self.structured_content = Some(structured_content);
3052 self
3053 }
3054}
3055impl ServerRequest {
3056 pub fn request_id(&self) -> &RequestId {
3057 match self {
3058 ServerRequest::PingRequest(request) => &request.id,
3059 ServerRequest::GetTaskRequest(request) => &request.id,
3060 ServerRequest::GetTaskPayloadRequest(request) => &request.id,
3061 ServerRequest::CancelTaskRequest(request) => &request.id,
3062 ServerRequest::ListTasksRequest(request) => &request.id,
3063 ServerRequest::CreateMessageRequest(request) => &request.id,
3064 ServerRequest::ListRootsRequest(request) => &request.id,
3065 ServerRequest::ElicitRequest(request) => &request.id,
3066 }
3067 }
3068}
3069impl ClientRequest {
3070 pub fn request_id(&self) -> &RequestId {
3071 match self {
3072 ClientRequest::InitializeRequest(request) => &request.id,
3073 ClientRequest::PingRequest(request) => &request.id,
3074 ClientRequest::ListResourcesRequest(request) => &request.id,
3075 ClientRequest::ListResourceTemplatesRequest(request) => &request.id,
3076 ClientRequest::ReadResourceRequest(request) => &request.id,
3077 ClientRequest::SubscribeRequest(request) => &request.id,
3078 ClientRequest::UnsubscribeRequest(request) => &request.id,
3079 ClientRequest::ListPromptsRequest(request) => &request.id,
3080 ClientRequest::GetPromptRequest(request) => &request.id,
3081 ClientRequest::ListToolsRequest(request) => &request.id,
3082 ClientRequest::CallToolRequest(request) => &request.id,
3083 ClientRequest::GetTaskRequest(request) => &request.id,
3084 ClientRequest::GetTaskPayloadRequest(request) => &request.id,
3085 ClientRequest::CancelTaskRequest(request) => &request.id,
3086 ClientRequest::ListTasksRequest(request) => &request.id,
3087 ClientRequest::SetLevelRequest(request) => &request.id,
3088 ClientRequest::CompleteRequest(request) => &request.id,
3089 }
3090 }
3091}
3092#[cfg(test)]
3094mod tests {
3095 use super::*;
3096 use serde_json::json;
3097
3098 #[test]
3099 fn test_detect_message_type() {
3100 let message = ClientJsonrpcRequest::new(RequestId::Integer(0), RequestFromClient::PingRequest(None));
3102 let result = detect_message_type(&json!(message));
3103 assert!(matches!(result, MessageTypes::Request));
3104
3105 let result = detect_message_type(&json!({
3108 "id":0,
3109 "method":"add_numbers",
3110 "params":{},
3111 "jsonrpc":"2.0"
3112 }));
3113 assert!(matches!(result, MessageTypes::Request));
3114
3115 let message = ClientJsonrpcNotification::new(NotificationFromClient::RootsListChangedNotification(None));
3117 let result = detect_message_type(&json!(message));
3118 assert!(matches!(result, MessageTypes::Notification));
3119
3120 let result = detect_message_type(&json!({
3122 "method":"notifications/email_sent",
3123 "jsonrpc":"2.0"
3124 }));
3125 assert!(matches!(result, MessageTypes::Notification));
3126
3127 let message = ClientJsonrpcResponse::new(
3129 RequestId::Integer(0),
3130 ListRootsResult {
3131 meta: None,
3132 roots: vec![],
3133 }
3134 .into(),
3135 );
3136 let result = detect_message_type(&json!(message));
3137 assert!(matches!(result, MessageTypes::Response));
3138
3139 let result = detect_message_type(&json!({
3142 "id":1,
3143 "jsonrpc":"2.0",
3144 "result":"{}",
3145 }));
3146 assert!(matches!(result, MessageTypes::Response));
3147
3148 let message = JsonrpcErrorResponse::create(
3150 Some(RequestId::Integer(0)),
3151 RpcErrorCodes::INVALID_PARAMS,
3152 "Invalid params!".to_string(),
3153 None,
3154 );
3155 let result = detect_message_type(&json!(message));
3156 assert!(matches!(result, MessageTypes::Error));
3157
3158 let result = detect_message_type(&json!({}));
3160 assert!(matches!(result, MessageTypes::Request));
3161 }
3162}