1use crate::generated_schema::*;
2use serde::ser::SerializeStruct;
3use serde_json::{json, Value};
4use std::hash::{Hash, Hasher};
5use std::result;
6use std::{fmt::Display, str::FromStr};
7
8pub const RELATED_TASK_META_KEY: &str = "io.modelcontextprotocol/related-task";
9
10#[derive(Debug, PartialEq)]
11pub enum MessageTypes {
12 Request,
13 Response,
14 Notification,
15 Error,
16}
17impl Display for MessageTypes {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22 write!(
23 f,
24 "{}",
25 match self {
27 MessageTypes::Request => "Request",
28 MessageTypes::Response => "Response",
29 MessageTypes::Notification => "Notification",
30 MessageTypes::Error => "Error",
31 }
32 )
33 }
34}
35
36#[allow(dead_code)]
39fn detect_message_type(value: &serde_json::Value) -> MessageTypes {
40 let id_field = value.get("id");
41
42 if id_field.is_some() && value.get("error").is_some() {
43 return MessageTypes::Error;
44 }
45
46 let method_field = value.get("method");
47 let result_field = value.get("result");
48
49 if id_field.is_some() {
50 if result_field.is_some() && method_field.is_none() {
51 return MessageTypes::Response;
52 } else if method_field.is_some() {
53 return MessageTypes::Request;
54 }
55 } else if method_field.is_some() {
56 return MessageTypes::Notification;
57 }
58
59 MessageTypes::Request
60}
61
62pub trait RpcMessage: McpMessage {
65 fn request_id(&self) -> Option<&RequestId>;
66 fn jsonrpc(&self) -> &str;
67 fn method(&self) -> Option<&str>;
68}
69
70pub trait McpMessage {
71 fn is_response(&self) -> bool;
72 fn is_request(&self) -> bool;
73 fn is_notification(&self) -> bool;
74 fn is_error(&self) -> bool;
75 fn message_type(&self) -> MessageTypes;
76}
77
78pub trait FromMessage<T>
84where
85 Self: Sized,
86{
87 fn from_message(message: T, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError>;
88}
89
90pub trait ToMessage<T>
91where
92 T: FromMessage<Self>,
93 Self: Sized,
94{
95 fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<T, RpcError>;
96}
97
98impl PartialEq for RequestId {
104 fn eq(&self, other: &Self) -> bool {
105 match (self, other) {
106 (RequestId::String(a), RequestId::String(b)) => a == b,
107 (RequestId::Integer(a), RequestId::Integer(b)) => a == b,
108 _ => false, }
110 }
111}
112
113impl PartialEq<RequestId> for &RequestId {
114 fn eq(&self, other: &RequestId) -> bool {
115 (*self).eq(other)
116 }
117}
118
119impl Eq for RequestId {}
120
121impl Hash for RequestId {
123 fn hash<H: Hasher>(&self, state: &mut H) {
124 match self {
125 RequestId::String(s) => {
126 0u8.hash(state); s.hash(state);
128 }
129 RequestId::Integer(i) => {
130 1u8.hash(state); i.hash(state);
132 }
133 }
134 }
135}
136
137impl core::fmt::Display for RequestId {
138 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
139 match *self {
140 RequestId::String(ref s) => write!(f, "{}", s),
141 RequestId::Integer(i) => write!(f, "{}", i),
142 }
143 }
144}
145#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
152#[serde(untagged)]
153pub enum ClientMessage {
154 Request(ClientJsonrpcRequest),
155 Notification(ClientJsonrpcNotification),
156 Response(ClientJsonrpcResponse),
157 Error(JsonrpcErrorResponse),
158}
159
160impl ClientMessage {
161 pub fn as_response(self) -> std::result::Result<ClientJsonrpcResponse, RpcError> {
171 if let Self::Response(response) = self {
172 Ok(response)
173 } else {
174 Err(RpcError::internal_error().with_message(format!(
175 "Invalid message type, expected: \"{}\" received\"{}\"",
176 MessageTypes::Response,
177 self.message_type()
178 )))
179 }
180 }
181
182 pub fn as_request(self) -> std::result::Result<ClientJsonrpcRequest, RpcError> {
192 if let Self::Request(request) = self {
193 Ok(request)
194 } else {
195 Err(RpcError::internal_error().with_message(format!(
196 "Invalid message type, expected: \"{}\" received\"{}\"",
197 MessageTypes::Request,
198 self.message_type()
199 )))
200 }
201 }
202
203 pub fn as_notification(self) -> std::result::Result<ClientJsonrpcNotification, RpcError> {
213 if let Self::Notification(notification) = self {
214 Ok(notification)
215 } else {
216 Err(RpcError::internal_error().with_message(format!(
217 "Invalid message type, expected: \"{}\" received\"{}\"",
218 MessageTypes::Notification,
219 self.message_type()
220 )))
221 }
222 }
223
224 pub fn as_error(self) -> std::result::Result<JsonrpcErrorResponse, RpcError> {
234 if let Self::Error(error) = self {
235 Ok(error)
236 } else {
237 Err(RpcError::internal_error().with_message(format!(
238 "Invalid message type, expected: \"{}\" received\"{}\"",
239 MessageTypes::Error,
240 self.message_type()
241 )))
242 }
243 }
244
245 pub fn is_initialize_request(&self) -> bool {
247 matches!(self, Self::Request(ClientJsonrpcRequest::InitializeRequest(_)))
248 }
249
250 pub fn is_initialized_notification(&self) -> bool {
252 matches!(
253 self,
254 Self::Notification(ClientJsonrpcNotification::InitializedNotification(_))
255 )
256 }
257}
258
259impl From<ClientJsonrpcNotification> for ClientMessage {
260 fn from(value: ClientJsonrpcNotification) -> Self {
261 Self::Notification(value)
262 }
263}
264
265impl From<ClientJsonrpcRequest> for ClientMessage {
266 fn from(value: ClientJsonrpcRequest) -> Self {
267 Self::Request(value)
268 }
269}
270
271impl From<ClientJsonrpcResponse> for ClientMessage {
272 fn from(value: ClientJsonrpcResponse) -> Self {
273 Self::Response(value)
274 }
275}
276
277impl RpcMessage for ClientMessage {
278 fn request_id(&self) -> Option<&RequestId> {
280 match self {
281 ClientMessage::Request(client_jsonrpc_request) => match client_jsonrpc_request {
283 ClientJsonrpcRequest::InitializeRequest(request) => Some(&request.id),
284 ClientJsonrpcRequest::PingRequest(request) => Some(&request.id),
285 ClientJsonrpcRequest::ListResourcesRequest(request) => Some(&request.id),
286 ClientJsonrpcRequest::ListResourceTemplatesRequest(request) => Some(&request.id),
287 ClientJsonrpcRequest::ReadResourceRequest(request) => Some(&request.id),
288 ClientJsonrpcRequest::SubscribeRequest(request) => Some(&request.id),
289 ClientJsonrpcRequest::UnsubscribeRequest(request) => Some(&request.id),
290 ClientJsonrpcRequest::ListPromptsRequest(request) => Some(&request.id),
291 ClientJsonrpcRequest::GetPromptRequest(request) => Some(&request.id),
292 ClientJsonrpcRequest::ListToolsRequest(request) => Some(&request.id),
293 ClientJsonrpcRequest::CallToolRequest(request) => Some(&request.id),
294 ClientJsonrpcRequest::GetTaskRequest(request) => Some(&request.id),
295 ClientJsonrpcRequest::GetTaskPayloadRequest(request) => Some(&request.id),
296 ClientJsonrpcRequest::CancelTaskRequest(request) => Some(&request.id),
297 ClientJsonrpcRequest::ListTasksRequest(request) => Some(&request.id),
298 ClientJsonrpcRequest::SetLevelRequest(request) => Some(&request.id),
299 ClientJsonrpcRequest::CompleteRequest(request) => Some(&request.id),
300 ClientJsonrpcRequest::CustomRequest(request) => Some(&request.id),
301 },
302 ClientMessage::Notification(_) => None,
304 ClientMessage::Response(client_jsonrpc_response) => Some(&client_jsonrpc_response.id),
306 ClientMessage::Error(jsonrpc_error) => jsonrpc_error.id.as_ref(),
308 }
309 }
310
311 fn jsonrpc(&self) -> &str {
312 match self {
313 ClientMessage::Request(client_jsonrpc_request) => client_jsonrpc_request.jsonrpc(),
314 ClientMessage::Notification(notification) => notification.jsonrpc(),
315 ClientMessage::Response(client_jsonrpc_response) => client_jsonrpc_response.jsonrpc(),
316 ClientMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
317 }
318 }
319
320 fn method(&self) -> Option<&str> {
321 match self {
322 ClientMessage::Request(client_jsonrpc_request) => Some(client_jsonrpc_request.method()),
323 ClientMessage::Notification(client_jsonrpc_notification) => Some(client_jsonrpc_notification.method()),
324 ClientMessage::Response(_) => None,
325 ClientMessage::Error(_) => None,
326 }
327 }
328}
329
330impl McpMessage for ClientMessage {
332 fn is_response(&self) -> bool {
334 matches!(self, ClientMessage::Response(_))
335 }
336
337 fn is_request(&self) -> bool {
339 matches!(self, ClientMessage::Request(_))
340 }
341
342 fn is_notification(&self) -> bool {
344 matches!(self, ClientMessage::Notification(_))
345 }
346
347 fn is_error(&self) -> bool {
349 matches!(self, ClientMessage::Error(_))
350 }
351
352 fn message_type(&self) -> MessageTypes {
354 match self {
355 ClientMessage::Request(_) => MessageTypes::Request,
356 ClientMessage::Notification(_) => MessageTypes::Notification,
357 ClientMessage::Response(_) => MessageTypes::Response,
358 ClientMessage::Error(_) => MessageTypes::Error,
359 }
360 }
361}
362
363#[derive(Clone, Debug, ::serde::Serialize, ::serde::Deserialize)]
369#[serde(untagged)]
370pub enum ClientJsonrpcRequest {
371 InitializeRequest(InitializeRequest),
372 PingRequest(PingRequest),
373 ListResourcesRequest(ListResourcesRequest),
374 ListResourceTemplatesRequest(ListResourceTemplatesRequest),
375 ReadResourceRequest(ReadResourceRequest),
376 SubscribeRequest(SubscribeRequest),
377 UnsubscribeRequest(UnsubscribeRequest),
378 ListPromptsRequest(ListPromptsRequest),
379 GetPromptRequest(GetPromptRequest),
380 ListToolsRequest(ListToolsRequest),
381 CallToolRequest(CallToolRequest),
382 GetTaskRequest(GetTaskRequest),
383 GetTaskPayloadRequest(GetTaskPayloadRequest),
384 CancelTaskRequest(CancelTaskRequest),
385 ListTasksRequest(ListTasksRequest),
386 SetLevelRequest(SetLevelRequest),
387 CompleteRequest(CompleteRequest),
388 CustomRequest(JsonrpcRequest),
389}
390
391impl ClientJsonrpcRequest {
392 pub fn new(id: RequestId, request: RequestFromClient) -> Self {
393 match request {
394 RequestFromClient::InitializeRequest(params) => Self::InitializeRequest(InitializeRequest::new(id, params)),
395 RequestFromClient::PingRequest(params) => Self::PingRequest(PingRequest::new(id, params)),
396 RequestFromClient::ListResourcesRequest(params) => {
397 Self::ListResourcesRequest(ListResourcesRequest::new(id, params))
398 }
399 RequestFromClient::ListResourceTemplatesRequest(params) => {
400 Self::ListResourceTemplatesRequest(ListResourceTemplatesRequest::new(id, params))
401 }
402 RequestFromClient::ReadResourceRequest(params) => {
403 Self::ReadResourceRequest(ReadResourceRequest::new(id, params))
404 }
405 RequestFromClient::SubscribeRequest(params) => Self::SubscribeRequest(SubscribeRequest::new(id, params)),
406 RequestFromClient::UnsubscribeRequest(params) => Self::UnsubscribeRequest(UnsubscribeRequest::new(id, params)),
407 RequestFromClient::ListPromptsRequest(params) => Self::ListPromptsRequest(ListPromptsRequest::new(id, params)),
408 RequestFromClient::GetPromptRequest(params) => Self::GetPromptRequest(GetPromptRequest::new(id, params)),
409 RequestFromClient::ListToolsRequest(params) => Self::ListToolsRequest(ListToolsRequest::new(id, params)),
410 RequestFromClient::CallToolRequest(params) => Self::CallToolRequest(CallToolRequest::new(id, params)),
411 RequestFromClient::GetTaskRequest(params) => Self::GetTaskRequest(GetTaskRequest::new(id, params)),
412 RequestFromClient::GetTaskPayloadRequest(params) => {
413 Self::GetTaskPayloadRequest(GetTaskPayloadRequest::new(id, params))
414 }
415 RequestFromClient::CancelTaskRequest(params) => Self::CancelTaskRequest(CancelTaskRequest::new(id, params)),
416 RequestFromClient::ListTasksRequest(params) => Self::ListTasksRequest(ListTasksRequest::new(id, params)),
417 RequestFromClient::SetLevelRequest(params) => Self::SetLevelRequest(SetLevelRequest::new(id, params)),
418 RequestFromClient::CompleteRequest(params) => Self::CompleteRequest(CompleteRequest::new(id, params)),
419 RequestFromClient::CustomRequest(params) => {
420 Self::CustomRequest(JsonrpcRequest::new(id, params.method, params.params))
421 }
422 }
423 }
424 pub fn jsonrpc(&self) -> &::std::string::String {
425 match self {
426 ClientJsonrpcRequest::InitializeRequest(request) => request.jsonrpc(),
427 ClientJsonrpcRequest::PingRequest(request) => request.jsonrpc(),
428 ClientJsonrpcRequest::ListResourcesRequest(request) => request.jsonrpc(),
429 ClientJsonrpcRequest::ListResourceTemplatesRequest(request) => request.jsonrpc(),
430 ClientJsonrpcRequest::ReadResourceRequest(request) => request.jsonrpc(),
431 ClientJsonrpcRequest::SubscribeRequest(request) => request.jsonrpc(),
432 ClientJsonrpcRequest::UnsubscribeRequest(request) => request.jsonrpc(),
433 ClientJsonrpcRequest::ListPromptsRequest(request) => request.jsonrpc(),
434 ClientJsonrpcRequest::GetPromptRequest(request) => request.jsonrpc(),
435 ClientJsonrpcRequest::ListToolsRequest(request) => request.jsonrpc(),
436 ClientJsonrpcRequest::CallToolRequest(request) => request.jsonrpc(),
437 ClientJsonrpcRequest::GetTaskRequest(request) => request.jsonrpc(),
438 ClientJsonrpcRequest::GetTaskPayloadRequest(request) => request.jsonrpc(),
439 ClientJsonrpcRequest::CancelTaskRequest(request) => request.jsonrpc(),
440 ClientJsonrpcRequest::ListTasksRequest(request) => request.jsonrpc(),
441 ClientJsonrpcRequest::SetLevelRequest(request) => request.jsonrpc(),
442 ClientJsonrpcRequest::CompleteRequest(request) => request.jsonrpc(),
443 ClientJsonrpcRequest::CustomRequest(request) => request.jsonrpc(),
444 }
445 }
446
447 pub fn request_id(&self) -> &RequestId {
448 match self {
449 ClientJsonrpcRequest::InitializeRequest(request) => &request.id,
450 ClientJsonrpcRequest::PingRequest(request) => &request.id,
451 ClientJsonrpcRequest::ListResourcesRequest(request) => &request.id,
452 ClientJsonrpcRequest::ListResourceTemplatesRequest(request) => &request.id,
453 ClientJsonrpcRequest::ReadResourceRequest(request) => &request.id,
454 ClientJsonrpcRequest::SubscribeRequest(request) => &request.id,
455 ClientJsonrpcRequest::UnsubscribeRequest(request) => &request.id,
456 ClientJsonrpcRequest::ListPromptsRequest(request) => &request.id,
457 ClientJsonrpcRequest::GetPromptRequest(request) => &request.id,
458 ClientJsonrpcRequest::ListToolsRequest(request) => &request.id,
459 ClientJsonrpcRequest::CallToolRequest(request) => &request.id,
460 ClientJsonrpcRequest::GetTaskRequest(request) => &request.id,
461 ClientJsonrpcRequest::GetTaskPayloadRequest(request) => &request.id,
462 ClientJsonrpcRequest::CancelTaskRequest(request) => &request.id,
463 ClientJsonrpcRequest::ListTasksRequest(request) => &request.id,
464 ClientJsonrpcRequest::SetLevelRequest(request) => &request.id,
465 ClientJsonrpcRequest::CompleteRequest(request) => &request.id,
466 ClientJsonrpcRequest::CustomRequest(request) => &request.id,
467 }
468 }
469
470 pub fn is_task_augmented(&self) -> bool {
471 if let ClientJsonrpcRequest::CallToolRequest(call_tool_request) = self {
472 call_tool_request.is_task_augmented()
473 } else {
474 false
475 }
476 }
477
478 pub fn method(&self) -> &str {
479 match self {
480 ClientJsonrpcRequest::InitializeRequest(request) => request.method(),
481 ClientJsonrpcRequest::PingRequest(request) => request.method(),
482 ClientJsonrpcRequest::ListResourcesRequest(request) => request.method(),
483 ClientJsonrpcRequest::ListResourceTemplatesRequest(request) => request.method(),
484 ClientJsonrpcRequest::ReadResourceRequest(request) => request.method(),
485 ClientJsonrpcRequest::SubscribeRequest(request) => request.method(),
486 ClientJsonrpcRequest::UnsubscribeRequest(request) => request.method(),
487 ClientJsonrpcRequest::ListPromptsRequest(request) => request.method(),
488 ClientJsonrpcRequest::GetPromptRequest(request) => request.method(),
489 ClientJsonrpcRequest::ListToolsRequest(request) => request.method(),
490 ClientJsonrpcRequest::CallToolRequest(request) => request.method(),
491 ClientJsonrpcRequest::GetTaskRequest(request) => request.method(),
492 ClientJsonrpcRequest::GetTaskPayloadRequest(request) => request.method(),
493 ClientJsonrpcRequest::CancelTaskRequest(request) => request.method(),
494 ClientJsonrpcRequest::ListTasksRequest(request) => request.method(),
495 ClientJsonrpcRequest::SetLevelRequest(request) => request.method(),
496 ClientJsonrpcRequest::CompleteRequest(request) => request.method(),
497 ClientJsonrpcRequest::CustomRequest(request) => request.method.as_str(),
498 }
499 }
500}
501
502impl From<ClientJsonrpcRequest> for RequestFromClient {
503 fn from(request: ClientJsonrpcRequest) -> Self {
504 match request {
505 ClientJsonrpcRequest::InitializeRequest(request) => Self::InitializeRequest(request.params),
506 ClientJsonrpcRequest::PingRequest(request) => Self::PingRequest(request.params),
507 ClientJsonrpcRequest::ListResourcesRequest(request) => Self::ListResourcesRequest(request.params),
508 ClientJsonrpcRequest::ListResourceTemplatesRequest(request) => {
509 Self::ListResourceTemplatesRequest(request.params)
510 }
511 ClientJsonrpcRequest::ReadResourceRequest(request) => Self::ReadResourceRequest(request.params),
512 ClientJsonrpcRequest::SubscribeRequest(request) => Self::SubscribeRequest(request.params),
513 ClientJsonrpcRequest::UnsubscribeRequest(request) => Self::UnsubscribeRequest(request.params),
514 ClientJsonrpcRequest::ListPromptsRequest(request) => Self::ListPromptsRequest(request.params),
515 ClientJsonrpcRequest::GetPromptRequest(request) => Self::GetPromptRequest(request.params),
516 ClientJsonrpcRequest::ListToolsRequest(request) => Self::ListToolsRequest(request.params),
517 ClientJsonrpcRequest::CallToolRequest(request) => Self::CallToolRequest(request.params),
518 ClientJsonrpcRequest::GetTaskRequest(request) => Self::GetTaskRequest(request.params),
519 ClientJsonrpcRequest::GetTaskPayloadRequest(request) => Self::GetTaskPayloadRequest(request.params),
520 ClientJsonrpcRequest::CancelTaskRequest(request) => Self::CancelTaskRequest(request.params),
521 ClientJsonrpcRequest::ListTasksRequest(request) => Self::ListTasksRequest(request.params),
522 ClientJsonrpcRequest::SetLevelRequest(request) => Self::SetLevelRequest(request.params),
523 ClientJsonrpcRequest::CompleteRequest(request) => Self::CompleteRequest(request.params),
524 ClientJsonrpcRequest::CustomRequest(request) => Self::CustomRequest(CustomRequest {
525 method: request.method,
526 params: request.params,
527 }),
528 }
529 }
530}
531
532impl Display for ClientJsonrpcRequest {
534 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
535 write!(
536 f,
537 "{}",
538 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
539 )
540 }
541}
542
543impl FromStr for ClientJsonrpcRequest {
544 type Err = RpcError;
545
546 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
568 serde_json::from_str(s)
569 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
570 }
571}
572
573#[allow(clippy::large_enum_variant)]
580#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
581#[serde(untagged)]
582pub enum RequestFromClient {
583 InitializeRequest(InitializeRequestParams),
584 PingRequest(Option<RequestParams>),
585 ListResourcesRequest(Option<PaginatedRequestParams>),
586 ListResourceTemplatesRequest(Option<PaginatedRequestParams>),
587 ReadResourceRequest(ReadResourceRequestParams),
588 SubscribeRequest(SubscribeRequestParams),
589 UnsubscribeRequest(UnsubscribeRequestParams),
590 ListPromptsRequest(Option<PaginatedRequestParams>),
591 GetPromptRequest(GetPromptRequestParams),
592 ListToolsRequest(Option<PaginatedRequestParams>),
593 CallToolRequest(CallToolRequestParams),
594 GetTaskRequest(GetTaskParams),
595 GetTaskPayloadRequest(GetTaskPayloadParams),
596 CancelTaskRequest(CancelTaskParams),
597 ListTasksRequest(Option<PaginatedRequestParams>),
598 SetLevelRequest(SetLevelRequestParams),
599 CompleteRequest(CompleteRequestParams),
600 CustomRequest(CustomRequest),
601}
602
603impl RequestFromClient {
604 pub fn method(&self) -> &str {
605 match self {
606 RequestFromClient::InitializeRequest(_request) => InitializeRequest::method_value(),
607 RequestFromClient::PingRequest(_request) => PingRequest::method_value(),
608 RequestFromClient::ListResourcesRequest(_request) => ListResourcesRequest::method_value(),
609 RequestFromClient::ListResourceTemplatesRequest(_request) => ListResourceTemplatesRequest::method_value(),
610 RequestFromClient::ReadResourceRequest(_request) => ReadResourceRequest::method_value(),
611 RequestFromClient::SubscribeRequest(_request) => SubscribeRequest::method_value(),
612 RequestFromClient::UnsubscribeRequest(_request) => UnsubscribeRequest::method_value(),
613 RequestFromClient::ListPromptsRequest(_request) => ListPromptsRequest::method_value(),
614 RequestFromClient::GetPromptRequest(_request) => GetPromptRequest::method_value(),
615 RequestFromClient::ListToolsRequest(_request) => ListToolsRequest::method_value(),
616 RequestFromClient::CallToolRequest(_request) => CallToolRequest::method_value(),
617 RequestFromClient::GetTaskRequest(_request) => GetTaskRequest::method_value(),
618 RequestFromClient::GetTaskPayloadRequest(_request) => GetTaskPayloadRequest::method_value(),
619 RequestFromClient::CancelTaskRequest(_request) => CancelTaskRequest::method_value(),
620 RequestFromClient::ListTasksRequest(_request) => ListTasksRequest::method_value(),
621 RequestFromClient::SetLevelRequest(_request) => SetLevelRequest::method_value(),
622 RequestFromClient::CompleteRequest(_request) => CompleteRequest::method_value(),
623 RequestFromClient::CustomRequest(request) => request.method.as_str(),
624 }
625 }
626 pub fn is_initialize_request(&self) -> bool {
628 matches!(self, RequestFromClient::InitializeRequest(_))
629 }
630}
631
632#[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)]
666#[serde(untagged)]
667pub enum ClientJsonrpcNotification {
668 CancelledNotification(CancelledNotification),
669 InitializedNotification(InitializedNotification),
670 ProgressNotification(ProgressNotification),
671 TaskStatusNotification(TaskStatusNotification),
672 RootsListChangedNotification(RootsListChangedNotification),
673 CustomNotification(JsonrpcNotification),
674}
675
676impl ClientJsonrpcNotification {
677 pub fn new(notification: NotificationFromClient) -> Self {
678 match notification {
679 NotificationFromClient::CancelledNotification(params) => {
680 Self::CancelledNotification(CancelledNotification::new(params))
681 }
682 NotificationFromClient::InitializedNotification(params) => {
683 Self::InitializedNotification(InitializedNotification::new(params))
684 }
685 NotificationFromClient::ProgressNotification(params) => {
686 Self::ProgressNotification(ProgressNotification::new(params))
687 }
688 NotificationFromClient::TaskStatusNotification(params) => {
689 Self::TaskStatusNotification(TaskStatusNotification::new(params))
690 }
691 NotificationFromClient::RootsListChangedNotification(params) => {
692 Self::RootsListChangedNotification(RootsListChangedNotification::new(params))
693 }
694 NotificationFromClient::CustomNotification(params) => {
695 Self::CustomNotification(JsonrpcNotification::new(params.method, params.params))
696 }
697 }
698 }
699 pub fn jsonrpc(&self) -> &::std::string::String {
700 match self {
701 ClientJsonrpcNotification::CancelledNotification(notification) => notification.jsonrpc(),
702 ClientJsonrpcNotification::InitializedNotification(notification) => notification.jsonrpc(),
703 ClientJsonrpcNotification::ProgressNotification(notification) => notification.jsonrpc(),
704 ClientJsonrpcNotification::TaskStatusNotification(notification) => notification.jsonrpc(),
705 ClientJsonrpcNotification::RootsListChangedNotification(notification) => notification.jsonrpc(),
706 ClientJsonrpcNotification::CustomNotification(notification) => notification.jsonrpc(),
707 }
708 }
709
710 pub fn is_initialized_notification(&self) -> bool {
712 matches!(self, Self::InitializedNotification(_))
713 }
714
715 pub fn method(&self) -> &str {
716 match self {
717 ClientJsonrpcNotification::CancelledNotification(notification) => notification.method(),
718 ClientJsonrpcNotification::InitializedNotification(notification) => notification.method(),
719 ClientJsonrpcNotification::ProgressNotification(notification) => notification.method(),
720 ClientJsonrpcNotification::TaskStatusNotification(notification) => notification.method(),
721 ClientJsonrpcNotification::RootsListChangedNotification(notification) => notification.method(),
722 ClientJsonrpcNotification::CustomNotification(notification) => notification.method.as_str(),
723 }
724 }
725}
726
727impl From<ClientJsonrpcNotification> for NotificationFromClient {
728 fn from(notification: ClientJsonrpcNotification) -> Self {
729 match notification {
730 ClientJsonrpcNotification::CancelledNotification(notification) => {
731 Self::CancelledNotification(notification.params)
732 }
733 ClientJsonrpcNotification::InitializedNotification(notification) => {
734 Self::InitializedNotification(notification.params)
735 }
736 ClientJsonrpcNotification::ProgressNotification(notification) => Self::ProgressNotification(notification.params),
737 ClientJsonrpcNotification::TaskStatusNotification(notification) => {
738 Self::TaskStatusNotification(notification.params)
739 }
740 ClientJsonrpcNotification::RootsListChangedNotification(notification) => {
741 Self::RootsListChangedNotification(notification.params)
742 }
743 ClientJsonrpcNotification::CustomNotification(notification) => Self::CustomNotification(CustomNotification {
744 method: notification.method,
745 params: notification.params,
746 }),
747 }
748 }
749}
750
751impl Display for ClientJsonrpcNotification {
753 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
754 write!(
755 f,
756 "{}",
757 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
758 )
759 }
760}
761
762impl FromStr for ClientJsonrpcNotification {
763 type Err = RpcError;
764
765 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
766 serde_json::from_str(s)
767 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
768 }
769}
770
771#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
778#[serde(untagged)]
779pub enum NotificationFromClient {
780 CancelledNotification(CancelledNotificationParams),
781 InitializedNotification(Option<NotificationParams>),
782 ProgressNotification(ProgressNotificationParams),
783 TaskStatusNotification(TaskStatusNotificationParams),
784 RootsListChangedNotification(Option<NotificationParams>),
785 CustomNotification(CustomNotification),
786}
787
788impl NotificationFromClient {
800 pub fn is_initialized_notification(&self) -> bool {
802 matches!(self, NotificationFromClient::InitializedNotification(_))
803 }
804
805 pub fn method(&self) -> &str {
807 match self {
808 NotificationFromClient::CancelledNotification(_notification) => CancelledNotification::method_value(),
809 NotificationFromClient::InitializedNotification(_notification) => InitializedNotification::method_value(),
810 NotificationFromClient::ProgressNotification(_notification) => ProgressNotification::method_value(),
811 NotificationFromClient::TaskStatusNotification(_notification) => TaskStatusNotification::method_value(),
812 NotificationFromClient::RootsListChangedNotification(_notification) => {
813 RootsListChangedNotification::method_value()
814 }
815 NotificationFromClient::CustomNotification(notification) => notification.method.as_str(),
816 }
817 }
818}
819
820#[derive(Clone, Debug)]
826pub struct ClientJsonrpcResponse {
827 pub id: RequestId,
828 jsonrpc: ::std::string::String,
829 pub result: ResultFromClient,
830}
831
832impl ClientJsonrpcResponse {
833 pub fn new(id: RequestId, result: ResultFromClient) -> Self {
834 Self {
835 id,
836 jsonrpc: JSONRPC_VERSION.to_string(),
837 result,
838 }
839 }
840 pub fn jsonrpc(&self) -> &::std::string::String {
841 &self.jsonrpc
842 }
843}
844
845impl Display for ClientJsonrpcResponse {
847 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
848 write!(
849 f,
850 "{}",
851 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
852 )
853 }
854}
855
856impl FromStr for ClientJsonrpcResponse {
857 type Err = RpcError;
858
859 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
860 serde_json::from_str(s)
861 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
862 }
863}
864#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
869#[serde(untagged)]
870pub enum ResultFromClient {
871 GetTaskResult(GetTaskResult),
872 CancelTaskResult(CancelTaskResult),
873 ListTasksResult(ListTasksResult),
874 CreateMessageResult(CreateMessageResult),
875 ListRootsResult(ListRootsResult),
876 ElicitResult(ElicitResult),
877 CreateTaskResult(CreateTaskResult),
878 Result(Result),
879 GetTaskPayloadResult(GetTaskPayloadResult),
880}
881
882#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
883#[serde(untagged)]
884pub enum ClientTaskResult {
885 ElicitResult(ElicitResult),
886 CreateMessageResult(CreateMessageResult),
887}
888
889pub type ServerTaskResult = CallToolResult;
890
891impl TryFrom<ResultFromClient> for ClientTaskResult {
892 type Error = RpcError;
893 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
894 match value {
895 ResultFromClient::CreateMessageResult(create_message_result) => {
896 Ok(Self::CreateMessageResult(create_message_result))
897 }
898 ResultFromClient::ElicitResult(elicit_result) => Ok(Self::ElicitResult(elicit_result)),
899 _ => Err(RpcError::internal_error().with_message("Not a ClientTaskResult variant".to_string())),
900 }
901 }
902}
903
904impl From<ClientTaskResult> for ResultFromClient {
905 fn from(value: ClientTaskResult) -> Self {
906 match value {
907 ClientTaskResult::ElicitResult(elicit_result) => Self::ElicitResult(elicit_result),
908 ClientTaskResult::CreateMessageResult(create_message_result) => Self::CreateMessageResult(create_message_result),
909 }
910 }
911}
912impl FromStr for ClientMessage {
917 type Err = RpcError;
918
919 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
920 serde_json::from_str(s)
921 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
922 }
923}
924
925impl Display for ClientMessage {
926 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
927 write!(
928 f,
929 "{}",
930 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
931 )
932 }
933}
934
935#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
942#[serde(untagged)]
943pub enum ServerMessage {
944 Request(ServerJsonrpcRequest),
945 Notification(ServerJsonrpcNotification),
946 Response(ServerJsonrpcResponse),
947 Error(JsonrpcErrorResponse),
948}
949
950impl ServerMessage {
951 pub fn as_response(self) -> std::result::Result<ServerJsonrpcResponse, RpcError> {
961 if let Self::Response(response) = self {
962 Ok(response)
963 } else {
964 Err(RpcError::internal_error().with_message(format!(
965 "Invalid message type, expected: \"{}\" received\"{}\"",
966 MessageTypes::Response,
967 self.message_type()
968 )))
969 }
970 }
971
972 pub fn as_request(self) -> std::result::Result<ServerJsonrpcRequest, RpcError> {
982 if let Self::Request(request) = self {
983 Ok(request)
984 } else {
985 Err(RpcError::internal_error().with_message(format!(
986 "Invalid message type, expected: \"{}\" received\"{}\"",
987 MessageTypes::Request,
988 self.message_type()
989 )))
990 }
991 }
992
993 pub fn as_notification(self) -> std::result::Result<ServerJsonrpcNotification, RpcError> {
1003 if let Self::Notification(notification) = self {
1004 Ok(notification)
1005 } else {
1006 Err(RpcError::internal_error().with_message(format!(
1007 "Invalid message type, expected: \"{}\" received\"{}\"",
1008 MessageTypes::Notification,
1009 self.message_type()
1010 )))
1011 }
1012 }
1013
1014 pub fn as_error(self) -> std::result::Result<JsonrpcErrorResponse, RpcError> {
1024 if let Self::Error(error) = self {
1025 Ok(error)
1026 } else {
1027 Err(RpcError::internal_error().with_message(format!(
1028 "Invalid message type, expected: \"{}\" received\"{}\"",
1029 MessageTypes::Error,
1030 self.message_type()
1031 )))
1032 }
1033 }
1034}
1035
1036impl From<ServerJsonrpcNotification> for ServerMessage {
1037 fn from(value: ServerJsonrpcNotification) -> Self {
1038 Self::Notification(value)
1039 }
1040}
1041
1042impl From<ServerJsonrpcRequest> for ServerMessage {
1043 fn from(value: ServerJsonrpcRequest) -> Self {
1044 Self::Request(value)
1045 }
1046}
1047
1048impl From<ServerJsonrpcResponse> for ServerMessage {
1049 fn from(value: ServerJsonrpcResponse) -> Self {
1050 Self::Response(value)
1051 }
1052}
1053
1054impl RpcMessage for ServerMessage {
1055 fn request_id(&self) -> Option<&RequestId> {
1057 match self {
1058 ServerMessage::Request(server_jsonrpc_request) => match server_jsonrpc_request {
1060 ServerJsonrpcRequest::PingRequest(request) => Some(&request.id),
1061 ServerJsonrpcRequest::GetTaskRequest(request) => Some(&request.id),
1062 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => Some(&request.id),
1063 ServerJsonrpcRequest::CancelTaskRequest(request) => Some(&request.id),
1064 ServerJsonrpcRequest::ListTasksRequest(request) => Some(&request.id),
1065 ServerJsonrpcRequest::CreateMessageRequest(request) => Some(&request.id),
1066 ServerJsonrpcRequest::ListRootsRequest(request) => Some(&request.id),
1067 ServerJsonrpcRequest::ElicitRequest(request) => Some(&request.id),
1068 ServerJsonrpcRequest::CustomRequest(request) => Some(&request.id),
1069 },
1070 ServerMessage::Notification(_) => None,
1072 ServerMessage::Response(server_jsonrpc_response) => Some(&server_jsonrpc_response.id),
1074 ServerMessage::Error(jsonrpc_error) => jsonrpc_error.id.as_ref(),
1076 }
1077 }
1078
1079 fn jsonrpc(&self) -> &str {
1080 match self {
1081 ServerMessage::Request(server_jsonrpc_request) => match server_jsonrpc_request {
1083 ServerJsonrpcRequest::PingRequest(request) => request.jsonrpc(),
1084 ServerJsonrpcRequest::GetTaskRequest(request) => request.jsonrpc(),
1085 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => request.jsonrpc(),
1086 ServerJsonrpcRequest::CancelTaskRequest(request) => request.jsonrpc(),
1087 ServerJsonrpcRequest::ListTasksRequest(request) => request.jsonrpc(),
1088 ServerJsonrpcRequest::CreateMessageRequest(request) => request.jsonrpc(),
1089 ServerJsonrpcRequest::ListRootsRequest(request) => request.jsonrpc(),
1090 ServerJsonrpcRequest::ElicitRequest(request) => request.jsonrpc(),
1091 ServerJsonrpcRequest::CustomRequest(request) => request.jsonrpc(),
1092 },
1093
1094 ServerMessage::Notification(notification) => notification.jsonrpc(),
1096 ServerMessage::Response(server_jsonrpc_response) => server_jsonrpc_response.jsonrpc(),
1098 ServerMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
1100 }
1101 }
1102
1103 fn method(&self) -> Option<&str> {
1104 match self {
1105 ServerMessage::Request(server_jsonrpc_request) => Some(server_jsonrpc_request.method()),
1106 ServerMessage::Notification(server_jsonrpc_notification) => Some(server_jsonrpc_notification.method()),
1107 ServerMessage::Response(_) => None,
1108 ServerMessage::Error(_) => None,
1109 }
1110 }
1111}
1112
1113impl McpMessage for ServerMessage {
1115 fn is_response(&self) -> bool {
1117 matches!(self, ServerMessage::Response(_))
1118 }
1119
1120 fn is_request(&self) -> bool {
1122 matches!(self, ServerMessage::Request(_))
1123 }
1124
1125 fn is_notification(&self) -> bool {
1127 matches!(self, ServerMessage::Notification(_))
1128 }
1129
1130 fn is_error(&self) -> bool {
1132 matches!(self, ServerMessage::Error(_))
1133 }
1134
1135 fn message_type(&self) -> MessageTypes {
1137 match self {
1138 ServerMessage::Request(_) => MessageTypes::Request,
1139 ServerMessage::Notification(_) => MessageTypes::Notification,
1140 ServerMessage::Response(_) => MessageTypes::Response,
1141 ServerMessage::Error(_) => MessageTypes::Error,
1142 }
1143 }
1144}
1145
1146impl FromStr for ServerMessage {
1147 type Err = RpcError;
1148
1149 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1150 serde_json::from_str(s)
1151 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1152 }
1153}
1154
1155impl Display for ServerMessage {
1156 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1157 write!(
1158 f,
1159 "{}",
1160 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1161 )
1162 }
1163}
1164
1165#[derive(Clone, Debug, ::serde::Serialize, ::serde::Deserialize)]
1171#[allow(clippy::large_enum_variant)]
1172#[serde(untagged)]
1173pub enum ServerJsonrpcRequest {
1174 PingRequest(PingRequest),
1175 GetTaskRequest(GetTaskRequest),
1176 GetTaskPayloadRequest(GetTaskPayloadRequest),
1177 CancelTaskRequest(CancelTaskRequest),
1178 ListTasksRequest(ListTasksRequest),
1179 CreateMessageRequest(CreateMessageRequest),
1180 ListRootsRequest(ListRootsRequest),
1181 ElicitRequest(ElicitRequest),
1182 CustomRequest(JsonrpcRequest),
1183}
1184
1185impl ServerJsonrpcRequest {
1186 pub fn new(request_id: RequestId, request: RequestFromServer) -> Self {
1187 match request {
1188 RequestFromServer::PingRequest(params) => Self::PingRequest(PingRequest::new(request_id, params)),
1189 RequestFromServer::GetTaskRequest(params) => Self::GetTaskRequest(GetTaskRequest::new(request_id, params)),
1190 RequestFromServer::GetTaskPayloadRequest(params) => {
1191 Self::GetTaskPayloadRequest(GetTaskPayloadRequest::new(request_id, params))
1192 }
1193 RequestFromServer::CancelTaskRequest(params) => {
1194 Self::CancelTaskRequest(CancelTaskRequest::new(request_id, params))
1195 }
1196 RequestFromServer::ListTasksRequest(params) => Self::ListTasksRequest(ListTasksRequest::new(request_id, params)),
1197 RequestFromServer::CreateMessageRequest(params) => {
1198 Self::CreateMessageRequest(CreateMessageRequest::new(request_id, params))
1199 }
1200 RequestFromServer::ListRootsRequest(params) => Self::ListRootsRequest(ListRootsRequest::new(request_id, params)),
1201 RequestFromServer::ElicitRequest(params) => Self::ElicitRequest(ElicitRequest::new(request_id, params)),
1202 RequestFromServer::CustomRequest(request) => {
1203 Self::CustomRequest(JsonrpcRequest::new(request_id, request.method, request.params))
1204 }
1205 }
1206 }
1207
1208 pub fn request_id(&self) -> &RequestId {
1209 match self {
1210 ServerJsonrpcRequest::PingRequest(request) => &request.id,
1211 ServerJsonrpcRequest::GetTaskRequest(request) => &request.id,
1212 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => &request.id,
1213 ServerJsonrpcRequest::CancelTaskRequest(request) => &request.id,
1214 ServerJsonrpcRequest::ListTasksRequest(request) => &request.id,
1215 ServerJsonrpcRequest::CreateMessageRequest(request) => &request.id,
1216 ServerJsonrpcRequest::ListRootsRequest(request) => &request.id,
1217 ServerJsonrpcRequest::ElicitRequest(request) => &request.id,
1218 ServerJsonrpcRequest::CustomRequest(request) => &request.id,
1219 }
1220 }
1221
1222 pub fn jsonrpc(&self) -> &::std::string::String {
1223 match self {
1224 ServerJsonrpcRequest::PingRequest(request) => request.jsonrpc(),
1225 ServerJsonrpcRequest::GetTaskRequest(request) => request.jsonrpc(),
1226 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => request.jsonrpc(),
1227 ServerJsonrpcRequest::CancelTaskRequest(request) => request.jsonrpc(),
1228 ServerJsonrpcRequest::ListTasksRequest(request) => request.jsonrpc(),
1229 ServerJsonrpcRequest::CreateMessageRequest(request) => request.jsonrpc(),
1230 ServerJsonrpcRequest::ListRootsRequest(request) => request.jsonrpc(),
1231 ServerJsonrpcRequest::ElicitRequest(request) => request.jsonrpc(),
1232 ServerJsonrpcRequest::CustomRequest(request) => request.jsonrpc(),
1233 }
1234 }
1235
1236 pub fn is_task_augmented(&self) -> bool {
1237 match self {
1238 ServerJsonrpcRequest::ElicitRequest(request) => request.params.is_task_augmented(),
1239 ServerJsonrpcRequest::CreateMessageRequest(request) => request.params.is_task_augmented(),
1240 _ => false,
1241 }
1242 }
1243
1244 pub fn method(&self) -> &str {
1245 match self {
1246 ServerJsonrpcRequest::PingRequest(request) => request.method(),
1247 ServerJsonrpcRequest::GetTaskRequest(request) => request.method(),
1248 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => request.method(),
1249 ServerJsonrpcRequest::CancelTaskRequest(request) => request.method(),
1250 ServerJsonrpcRequest::ListTasksRequest(request) => request.method(),
1251 ServerJsonrpcRequest::CreateMessageRequest(request) => request.method(),
1252 ServerJsonrpcRequest::ListRootsRequest(request) => request.method(),
1253 ServerJsonrpcRequest::ElicitRequest(request) => request.method(),
1254 ServerJsonrpcRequest::CustomRequest(request) => request.method.as_str(),
1255 }
1256 }
1257}
1258
1259impl Display for ServerJsonrpcRequest {
1261 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1262 write!(
1263 f,
1264 "{}",
1265 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1266 )
1267 }
1268}
1269
1270impl FromStr for ServerJsonrpcRequest {
1271 type Err = RpcError;
1272
1273 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1274 serde_json::from_str(s)
1275 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1276 }
1277}
1278
1279#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
1280pub struct CustomRequest {
1281 pub method: ::std::string::String,
1282 #[serde(default, skip_serializing_if = "::std::option::Option::is_none")]
1283 pub params: ::std::option::Option<::serde_json::Map<::std::string::String, ::serde_json::Value>>,
1284}
1285
1286#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1293#[serde(untagged)]
1294pub enum RequestFromServer {
1295 PingRequest(Option<RequestParams>),
1296 GetTaskRequest(GetTaskParams),
1297 GetTaskPayloadRequest(GetTaskPayloadParams),
1298 CancelTaskRequest(CancelTaskParams),
1299 ListTasksRequest(Option<PaginatedRequestParams>),
1300 CreateMessageRequest(CreateMessageRequestParams),
1301 ListRootsRequest(Option<RequestParams>),
1302 ElicitRequest(ElicitRequestParams),
1303 CustomRequest(CustomRequest),
1304}
1305
1306impl From<ServerJsonrpcRequest> for RequestFromServer {
1307 fn from(request: ServerJsonrpcRequest) -> Self {
1308 match request {
1309 ServerJsonrpcRequest::PingRequest(request) => Self::PingRequest(request.params),
1310 ServerJsonrpcRequest::GetTaskRequest(request) => Self::GetTaskRequest(request.params),
1311 ServerJsonrpcRequest::GetTaskPayloadRequest(request) => Self::GetTaskPayloadRequest(request.params),
1312 ServerJsonrpcRequest::CancelTaskRequest(request) => Self::CancelTaskRequest(request.params),
1313 ServerJsonrpcRequest::ListTasksRequest(request) => Self::ListTasksRequest(request.params),
1314 ServerJsonrpcRequest::CreateMessageRequest(request) => Self::CreateMessageRequest(request.params),
1315 ServerJsonrpcRequest::ListRootsRequest(request) => Self::ListRootsRequest(request.params),
1316 ServerJsonrpcRequest::ElicitRequest(request) => Self::ElicitRequest(request.params),
1317 ServerJsonrpcRequest::CustomRequest(request) => Self::CustomRequest(CustomRequest {
1318 method: request.method,
1319 params: request.params,
1320 }),
1321 }
1322 }
1323}
1324
1325impl RequestFromServer {
1326 pub fn method(&self) -> &str {
1327 match self {
1328 RequestFromServer::PingRequest(_request) => PingRequest::method_value(),
1329 RequestFromServer::GetTaskRequest(_request) => GetTaskRequest::method_value(),
1330 RequestFromServer::GetTaskPayloadRequest(_request) => GetTaskPayloadRequest::method_value(),
1331 RequestFromServer::CancelTaskRequest(_request) => CancelTaskRequest::method_value(),
1332 RequestFromServer::ListTasksRequest(_request) => ListTasksRequest::method_value(),
1333 RequestFromServer::CreateMessageRequest(_request) => CreateMessageRequest::method_value(),
1334 RequestFromServer::ListRootsRequest(_request) => ListRootsRequest::method_value(),
1335 RequestFromServer::ElicitRequest(_request) => ElicitRequest::method_value(),
1336 RequestFromServer::CustomRequest(request) => request.method.as_str(),
1337 }
1338 }
1339}
1340
1341#[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)]
1347#[serde(untagged)]
1348pub enum ServerJsonrpcNotification {
1349 CancelledNotification(CancelledNotification),
1350 ProgressNotification(ProgressNotification),
1351 ResourceListChangedNotification(ResourceListChangedNotification),
1352 ResourceUpdatedNotification(ResourceUpdatedNotification),
1353 PromptListChangedNotification(PromptListChangedNotification),
1354 ToolListChangedNotification(ToolListChangedNotification),
1355 TaskStatusNotification(TaskStatusNotification),
1356 LoggingMessageNotification(LoggingMessageNotification),
1357 ElicitationCompleteNotification(ElicitationCompleteNotification),
1358 CustomNotification(JsonrpcNotification),
1359}
1360
1361impl From<ServerJsonrpcNotification> for NotificationFromServer {
1362 fn from(notification: ServerJsonrpcNotification) -> Self {
1363 match notification {
1364 ServerJsonrpcNotification::CancelledNotification(notification) => {
1365 Self::CancelledNotification(notification.params)
1366 }
1367 ServerJsonrpcNotification::ProgressNotification(notification) => Self::ProgressNotification(notification.params),
1368 ServerJsonrpcNotification::ResourceListChangedNotification(notification) => {
1369 Self::ResourceListChangedNotification(notification.params)
1370 }
1371 ServerJsonrpcNotification::ResourceUpdatedNotification(notification) => {
1372 Self::ResourceUpdatedNotification(notification.params)
1373 }
1374 ServerJsonrpcNotification::PromptListChangedNotification(notification) => {
1375 Self::PromptListChangedNotification(notification.params)
1376 }
1377 ServerJsonrpcNotification::ToolListChangedNotification(notification) => {
1378 Self::ToolListChangedNotification(notification.params)
1379 }
1380 ServerJsonrpcNotification::TaskStatusNotification(notification) => {
1381 Self::TaskStatusNotification(notification.params)
1382 }
1383 ServerJsonrpcNotification::LoggingMessageNotification(notification) => {
1384 Self::LoggingMessageNotification(notification.params)
1385 }
1386 ServerJsonrpcNotification::ElicitationCompleteNotification(notification) => {
1387 Self::ElicitationCompleteNotification(notification.params)
1388 }
1389 ServerJsonrpcNotification::CustomNotification(notification) => Self::CustomNotification(CustomNotification {
1390 method: notification.method,
1391 params: notification.params,
1392 }),
1393 }
1394 }
1395}
1396
1397impl ServerJsonrpcNotification {
1399 pub fn new(notification: NotificationFromServer) -> Self {
1400 match notification {
1401 NotificationFromServer::CancelledNotification(params) => {
1402 Self::CancelledNotification(CancelledNotification::new(params))
1403 }
1404 NotificationFromServer::ProgressNotification(params) => {
1405 Self::ProgressNotification(ProgressNotification::new(params))
1406 }
1407 NotificationFromServer::ResourceListChangedNotification(params) => {
1408 Self::ResourceListChangedNotification(ResourceListChangedNotification::new(params))
1409 }
1410 NotificationFromServer::ResourceUpdatedNotification(params) => {
1411 Self::ResourceUpdatedNotification(ResourceUpdatedNotification::new(params))
1412 }
1413 NotificationFromServer::PromptListChangedNotification(params) => {
1414 Self::PromptListChangedNotification(PromptListChangedNotification::new(params))
1415 }
1416 NotificationFromServer::ToolListChangedNotification(params) => {
1417 Self::ToolListChangedNotification(ToolListChangedNotification::new(params))
1418 }
1419 NotificationFromServer::TaskStatusNotification(params) => {
1420 Self::TaskStatusNotification(TaskStatusNotification::new(params))
1421 }
1422 NotificationFromServer::LoggingMessageNotification(params) => {
1423 Self::LoggingMessageNotification(LoggingMessageNotification::new(params))
1424 }
1425 NotificationFromServer::ElicitationCompleteNotification(params) => {
1426 Self::ElicitationCompleteNotification(ElicitationCompleteNotification::new(params))
1427 }
1428 NotificationFromServer::CustomNotification(params) => {
1429 Self::CustomNotification(JsonrpcNotification::new(params.method, params.params))
1430 }
1431 }
1432 }
1433 pub fn jsonrpc(&self) -> &::std::string::String {
1434 match self {
1435 ServerJsonrpcNotification::CancelledNotification(notification) => notification.jsonrpc(),
1436 ServerJsonrpcNotification::ProgressNotification(notification) => notification.jsonrpc(),
1437 ServerJsonrpcNotification::ResourceListChangedNotification(notification) => notification.jsonrpc(),
1438 ServerJsonrpcNotification::ResourceUpdatedNotification(notification) => notification.jsonrpc(),
1439 ServerJsonrpcNotification::PromptListChangedNotification(notification) => notification.jsonrpc(),
1440 ServerJsonrpcNotification::ToolListChangedNotification(notification) => notification.jsonrpc(),
1441 ServerJsonrpcNotification::TaskStatusNotification(notification) => notification.jsonrpc(),
1442 ServerJsonrpcNotification::LoggingMessageNotification(notification) => notification.jsonrpc(),
1443 ServerJsonrpcNotification::ElicitationCompleteNotification(notification) => notification.jsonrpc(),
1444 ServerJsonrpcNotification::CustomNotification(notification) => notification.jsonrpc(),
1445 }
1446 }
1447
1448 fn method(&self) -> &str {
1449 match self {
1450 ServerJsonrpcNotification::CancelledNotification(notification) => notification.method(),
1451 ServerJsonrpcNotification::ProgressNotification(notification) => notification.method(),
1452 ServerJsonrpcNotification::ResourceListChangedNotification(notification) => notification.method(),
1453 ServerJsonrpcNotification::ResourceUpdatedNotification(notification) => notification.method(),
1454 ServerJsonrpcNotification::PromptListChangedNotification(notification) => notification.method(),
1455 ServerJsonrpcNotification::ToolListChangedNotification(notification) => notification.method(),
1456 ServerJsonrpcNotification::TaskStatusNotification(notification) => notification.method(),
1457 ServerJsonrpcNotification::LoggingMessageNotification(notification) => notification.method(),
1458 ServerJsonrpcNotification::ElicitationCompleteNotification(notification) => notification.method(),
1459 ServerJsonrpcNotification::CustomNotification(notification) => ¬ification.method,
1460 }
1461 }
1462}
1463
1464impl Display for ServerJsonrpcNotification {
1466 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1467 write!(
1468 f,
1469 "{}",
1470 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1471 )
1472 }
1473}
1474
1475impl FromStr for ServerJsonrpcNotification {
1476 type Err = RpcError;
1477
1478 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1479 serde_json::from_str(s)
1480 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1481 }
1482}
1483#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1490#[serde(untagged)]
1491pub enum NotificationFromServer {
1492 CancelledNotification(CancelledNotificationParams),
1493 ProgressNotification(ProgressNotificationParams),
1494 ResourceListChangedNotification(Option<NotificationParams>),
1495 ResourceUpdatedNotification(ResourceUpdatedNotificationParams),
1496 PromptListChangedNotification(Option<NotificationParams>),
1497 ToolListChangedNotification(Option<NotificationParams>),
1498 TaskStatusNotification(TaskStatusNotificationParams),
1499 LoggingMessageNotification(LoggingMessageNotificationParams),
1500 ElicitationCompleteNotification(ElicitCompleteParams),
1501 CustomNotification(CustomNotification),
1502}
1503
1504impl NotificationFromServer {
1505 pub fn method(&self) -> &str {
1506 match self {
1507 NotificationFromServer::CancelledNotification(_params) => CancelledNotification::method_value(),
1508 NotificationFromServer::ProgressNotification(_params) => CancelledNotification::method_value(),
1509 NotificationFromServer::ResourceListChangedNotification(_params) => CancelledNotification::method_value(),
1510 NotificationFromServer::ResourceUpdatedNotification(_params) => CancelledNotification::method_value(),
1511 NotificationFromServer::PromptListChangedNotification(_params) => CancelledNotification::method_value(),
1512 NotificationFromServer::ToolListChangedNotification(_params) => CancelledNotification::method_value(),
1513 NotificationFromServer::TaskStatusNotification(_params) => CancelledNotification::method_value(),
1514 NotificationFromServer::LoggingMessageNotification(_params) => CancelledNotification::method_value(),
1515 NotificationFromServer::ElicitationCompleteNotification(_params) => CancelledNotification::method_value(),
1516 NotificationFromServer::CustomNotification(params) => params.method.as_str(),
1517 }
1518 }
1519}
1520
1521#[derive(Clone, Debug)]
1527pub struct ServerJsonrpcResponse {
1528 pub id: RequestId,
1529 jsonrpc: ::std::string::String,
1530 pub result: ResultFromServer,
1531}
1532
1533impl ServerJsonrpcResponse {
1534 pub fn new(id: RequestId, result: ResultFromServer) -> Self {
1535 Self {
1536 id,
1537 jsonrpc: JSONRPC_VERSION.to_string(),
1538 result,
1539 }
1540 }
1541 pub fn jsonrpc(&self) -> &::std::string::String {
1542 &self.jsonrpc
1543 }
1544}
1545
1546impl Display for ServerJsonrpcResponse {
1548 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1549 write!(
1550 f,
1551 "{}",
1552 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1553 )
1554 }
1555}
1556
1557impl FromStr for ServerJsonrpcResponse {
1558 type Err = RpcError;
1559
1560 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1561 serde_json::from_str(s)
1562 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1563 }
1564}
1565#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
1569#[serde(untagged)]
1570pub enum ResultFromServer {
1571 InitializeResult(InitializeResult),
1572 ListResourcesResult(ListResourcesResult),
1573 ListResourceTemplatesResult(ListResourceTemplatesResult),
1574 ReadResourceResult(ReadResourceResult),
1575 ListPromptsResult(ListPromptsResult),
1576 GetPromptResult(GetPromptResult),
1577 ListToolsResult(ListToolsResult),
1578 CallToolResult(CallToolResult),
1579 GetTaskResult(GetTaskResult),
1580 CancelTaskResult(CancelTaskResult),
1581 ListTasksResult(ListTasksResult),
1582 CompleteResult(CompleteResult),
1583 CreateTaskResult(CreateTaskResult),
1584 Result(Result),
1585 GetTaskPayloadResult(GetTaskPayloadResult),
1586}
1587
1588impl Display for JsonrpcErrorResponse {
1594 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1595 write!(
1596 f,
1597 "{}",
1598 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1599 )
1600 }
1601}
1602
1603impl FromStr for JsonrpcErrorResponse {
1604 type Err = RpcError;
1605
1606 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1607 serde_json::from_str(s)
1608 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1609 }
1610}
1611
1612#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1621#[serde(untagged)]
1622pub enum MessageFromServer {
1623 RequestFromServer(RequestFromServer),
1624 ResultFromServer(ResultFromServer),
1625 NotificationFromServer(NotificationFromServer),
1626 Error(RpcError),
1627}
1628
1629impl From<RequestFromServer> for MessageFromServer {
1630 fn from(value: RequestFromServer) -> Self {
1631 Self::RequestFromServer(value)
1632 }
1633}
1634
1635impl From<ResultFromServer> for MessageFromServer {
1636 fn from(value: ResultFromServer) -> Self {
1637 Self::ResultFromServer(value)
1638 }
1639}
1640
1641impl From<NotificationFromServer> for MessageFromServer {
1642 fn from(value: NotificationFromServer) -> Self {
1643 Self::NotificationFromServer(value)
1644 }
1645}
1646
1647impl From<RpcError> for MessageFromServer {
1648 fn from(value: RpcError) -> Self {
1649 Self::Error(value)
1650 }
1651}
1652
1653impl McpMessage for MessageFromServer {
1654 fn is_response(&self) -> bool {
1655 matches!(self, MessageFromServer::ResultFromServer(_))
1656 }
1657
1658 fn is_request(&self) -> bool {
1659 matches!(self, MessageFromServer::RequestFromServer(_))
1660 }
1661
1662 fn is_notification(&self) -> bool {
1663 matches!(self, MessageFromServer::NotificationFromServer(_))
1664 }
1665
1666 fn is_error(&self) -> bool {
1667 matches!(self, MessageFromServer::Error(_))
1668 }
1669
1670 fn message_type(&self) -> MessageTypes {
1671 match self {
1672 MessageFromServer::RequestFromServer(_) => MessageTypes::Request,
1673 MessageFromServer::ResultFromServer(_) => MessageTypes::Response,
1674 MessageFromServer::NotificationFromServer(_) => MessageTypes::Notification,
1675 MessageFromServer::Error(_) => MessageTypes::Error,
1676 }
1677 }
1678}
1679
1680impl FromMessage<MessageFromServer> for ServerMessage {
1681 fn from_message(message: MessageFromServer, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1682 match message {
1683 MessageFromServer::RequestFromServer(request_from_server) => {
1684 let request_id =
1685 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1686
1687 let rpc_message = match request_from_server {
1688 RequestFromServer::PingRequest(params) => {
1689 ServerJsonrpcRequest::PingRequest(PingRequest::new(request_id, params))
1690 }
1691 RequestFromServer::GetTaskRequest(params) => {
1692 ServerJsonrpcRequest::GetTaskRequest(GetTaskRequest::new(request_id, params))
1693 }
1694 RequestFromServer::GetTaskPayloadRequest(params) => {
1695 ServerJsonrpcRequest::GetTaskPayloadRequest(GetTaskPayloadRequest::new(request_id, params))
1696 }
1697 RequestFromServer::CancelTaskRequest(params) => {
1698 ServerJsonrpcRequest::CancelTaskRequest(CancelTaskRequest::new(request_id, params))
1699 }
1700 RequestFromServer::ListTasksRequest(params) => {
1701 ServerJsonrpcRequest::ListTasksRequest(ListTasksRequest::new(request_id, params))
1702 }
1703 RequestFromServer::CreateMessageRequest(params) => {
1704 ServerJsonrpcRequest::CreateMessageRequest(CreateMessageRequest::new(request_id, params))
1705 }
1706 RequestFromServer::ListRootsRequest(params) => {
1707 ServerJsonrpcRequest::ListRootsRequest(ListRootsRequest::new(request_id, params))
1708 }
1709 RequestFromServer::ElicitRequest(params) => {
1710 ServerJsonrpcRequest::ElicitRequest(ElicitRequest::new(request_id, params))
1711 }
1712 RequestFromServer::CustomRequest(params) => {
1713 ServerJsonrpcRequest::CustomRequest(JsonrpcRequest::new(request_id, params.method, params.params))
1714 }
1715 };
1716
1717 Ok(ServerMessage::Request(rpc_message))
1718 }
1719 MessageFromServer::ResultFromServer(result_from_server) => {
1720 let request_id =
1721 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1722 Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
1723 request_id,
1724 result_from_server,
1725 )))
1726 }
1727 MessageFromServer::NotificationFromServer(notification_from_server) => {
1728 if request_id.is_some() {
1729 return Err(RpcError::internal_error()
1730 .with_message("request_id expected to be None for Notifications!".to_string()));
1731 }
1732 Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(
1733 notification_from_server,
1734 )))
1735 }
1736 MessageFromServer::Error(jsonrpc_error_error) => Ok(ServerMessage::Error(JsonrpcErrorResponse::new(
1737 jsonrpc_error_error,
1738 request_id,
1739 ))),
1740 }
1741 }
1742}
1743
1744#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1753#[serde(untagged)]
1754pub enum MessageFromClient {
1755 RequestFromClient(RequestFromClient),
1756 ResultFromClient(ResultFromClient),
1757 NotificationFromClient(NotificationFromClient),
1758 Error(RpcError),
1759}
1760
1761impl MessageFromClient {
1762 pub fn is_initialize_request(&self) -> bool {
1764 matches!(self, Self::RequestFromClient(RequestFromClient::InitializeRequest(_)))
1765 }
1766
1767 pub fn is_initialized_notification(&self) -> bool {
1769 matches!(
1770 self,
1771 Self::NotificationFromClient(NotificationFromClient::InitializedNotification(_))
1772 )
1773 }
1774}
1775
1776impl From<RequestFromClient> for MessageFromClient {
1777 fn from(value: RequestFromClient) -> Self {
1778 Self::RequestFromClient(value)
1779 }
1780}
1781
1782impl From<ResultFromClient> for MessageFromClient {
1783 fn from(value: ResultFromClient) -> Self {
1784 Self::ResultFromClient(value)
1785 }
1786}
1787
1788impl From<NotificationFromClient> for MessageFromClient {
1789 fn from(value: NotificationFromClient) -> Self {
1790 Self::NotificationFromClient(value)
1791 }
1792}
1793
1794impl From<RpcError> for MessageFromClient {
1795 fn from(value: RpcError) -> Self {
1796 Self::Error(value)
1797 }
1798}
1799
1800impl McpMessage for MessageFromClient {
1801 fn is_response(&self) -> bool {
1802 matches!(self, MessageFromClient::ResultFromClient(_))
1803 }
1804
1805 fn is_request(&self) -> bool {
1806 matches!(self, MessageFromClient::RequestFromClient(_))
1807 }
1808
1809 fn is_notification(&self) -> bool {
1810 matches!(self, MessageFromClient::NotificationFromClient(_))
1811 }
1812
1813 fn is_error(&self) -> bool {
1814 matches!(self, MessageFromClient::Error(_))
1815 }
1816
1817 fn message_type(&self) -> MessageTypes {
1818 match self {
1819 MessageFromClient::RequestFromClient(_) => MessageTypes::Request,
1820 MessageFromClient::ResultFromClient(_) => MessageTypes::Response,
1821 MessageFromClient::NotificationFromClient(_) => MessageTypes::Notification,
1822 MessageFromClient::Error(_) => MessageTypes::Error,
1823 }
1824 }
1825}
1826
1827impl FromMessage<MessageFromClient> for ClientMessage {
1828 fn from_message(message: MessageFromClient, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1829 match message {
1830 MessageFromClient::RequestFromClient(request_from_client) => {
1831 let request_id =
1832 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1833 Ok(ClientMessage::Request(ClientJsonrpcRequest::new(
1834 request_id,
1835 request_from_client,
1836 )))
1837 }
1838 MessageFromClient::ResultFromClient(result_from_client) => {
1839 let request_id =
1840 request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1841 Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
1842 request_id,
1843 result_from_client,
1844 )))
1845 }
1846 MessageFromClient::NotificationFromClient(notification_from_client) => {
1847 if request_id.is_some() {
1848 return Err(RpcError::internal_error()
1849 .with_message("request_id expected to be None for Notifications!".to_string()));
1850 }
1851
1852 Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(
1853 notification_from_client,
1854 )))
1855 }
1856 MessageFromClient::Error(jsonrpc_error_error) => Ok(ClientMessage::Error(JsonrpcErrorResponse::new(
1857 jsonrpc_error_error,
1858 request_id,
1859 ))),
1860 }
1861 }
1862}
1863
1864#[derive(Debug)]
1871pub struct UnknownTool(pub String);
1872
1873impl core::fmt::Display for UnknownTool {
1875 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1876 write!(f, "Unknown tool: {}", self.0)
1878 }
1879}
1880
1881impl std::error::Error for UnknownTool {}
1883
1884#[derive(Debug)]
1890pub struct CallToolError(pub Box<dyn std::error::Error>);
1891
1892impl CallToolError {
1894 pub fn new<E: std::error::Error + 'static>(err: E) -> Self {
1896 CallToolError(Box::new(err))
1898 }
1899
1900 pub fn unknown_tool(tool_name: impl Into<String>) -> Self {
1902 CallToolError(Box::new(UnknownTool(tool_name.into())))
1904 }
1905
1906 pub fn unsupported_task_augmented_tool_call() -> Self {
1910 Self::from_message("Task-augmented tool calls are not supported.".to_string())
1911 }
1912
1913 pub fn invalid_arguments(tool_name: impl AsRef<str>, message: Option<String>) -> Self {
1916 let tool_name = tool_name.as_ref().trim();
1918 if tool_name.is_empty() {
1919 return Self::from_message("Invalid arguments: tool name cannot be empty".to_string());
1920 }
1921
1922 let default_message = "no additional details provided".to_string();
1924 let message = message.unwrap_or(default_message);
1925
1926 let full_message = format!("Invalid arguments for tool '{tool_name}': {message}");
1928
1929 Self::from_message(full_message)
1930 }
1931
1932 pub fn from_message(message: impl Into<String>) -> Self {
1952 struct MsgError(String);
1953 impl std::fmt::Debug for MsgError {
1954 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1955 write!(f, "{}", self.0)
1956 }
1957 }
1958 impl std::fmt::Display for MsgError {
1959 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1960 write!(f, "{}", self.0)
1961 }
1962 }
1963 impl std::error::Error for MsgError {}
1964
1965 CallToolError::new(MsgError(message.into()))
1966 }
1967}
1968
1969impl From<CallToolError> for RpcError {
1975 fn from(value: CallToolError) -> Self {
1976 Self::internal_error().with_message(value.to_string())
1977 }
1978}
1979
1980impl From<CallToolError> for CallToolResult {
1982 fn from(value: CallToolError) -> Self {
1983 CallToolResult {
1985 content: vec![TextContent::new(value.to_string(), None, None).into()],
1986 is_error: Some(true),
1987 meta: None,
1988 structured_content: None,
1989 }
1990 }
1991}
1992
1993impl core::fmt::Display for CallToolError {
1995 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1996 write!(f, "{}", self.0)
1997 }
1998}
1999
2000impl std::error::Error for CallToolError {
2002 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2003 self.0.source()
2004 }
2005}
2006
2007impl CallToolRequest {
2008 pub fn tool_name(&self) -> &str {
2016 &self.params.name
2017 }
2018}
2019
2020impl<T: Into<String>> From<T> for TextContent {
2021 fn from(value: T) -> Self {
2022 TextContent::new(value.into(), None, None)
2023 }
2024}
2025
2026impl TextResourceContents {
2027 pub fn new<T: Into<String>>(text: T, uri: T) -> Self {
2028 TextResourceContents {
2029 meta: None,
2030 mime_type: None,
2031 text: text.into(),
2032 uri: uri.into(),
2033 }
2034 }
2035 pub fn with_meta(mut self, meta: serde_json::Map<String, Value>) -> Self {
2037 self.meta = Some(meta);
2038 self
2039 }
2040
2041 pub fn with_mime_type<T: Into<String>>(mut self, mime_type: T) -> Self {
2042 self.mime_type = Some(mime_type.into());
2043 self
2044 }
2045
2046 pub fn with_uri<T: Into<String>>(mut self, uri: T) -> Self {
2047 self.uri = uri.into();
2048 self
2049 }
2050}
2051
2052impl BlobResourceContents {
2053 pub fn new<T: Into<String>>(base64_text: T, uri: T) -> Self {
2054 BlobResourceContents {
2055 meta: None,
2056 mime_type: None,
2057 blob: base64_text.into(),
2058 uri: uri.into(),
2059 }
2060 }
2061 pub fn with_meta(mut self, meta: serde_json::Map<String, Value>) -> Self {
2063 self.meta = Some(meta);
2064 self
2065 }
2066 pub fn with_mime_type<T: Into<String>>(mut self, mime_type: T) -> Self {
2067 self.mime_type = Some(mime_type.into());
2068 self
2069 }
2070 pub fn with_uri<T: Into<String>>(mut self, uri: T) -> Self {
2071 self.uri = uri.into();
2072 self
2073 }
2074}
2075
2076#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2077#[serde(untagged)]
2078#[allow(clippy::large_enum_variant)]
2079pub enum ClientMessages {
2080 Single(ClientMessage),
2081 Batch(Vec<ClientMessage>),
2082}
2083
2084impl ClientMessages {
2085 pub fn is_batch(&self) -> bool {
2086 matches!(self, ClientMessages::Batch(_))
2087 }
2088
2089 pub fn includes_request(&self) -> bool {
2090 match self {
2091 ClientMessages::Single(client_message) => client_message.is_request(),
2092 ClientMessages::Batch(client_messages) => client_messages.iter().any(ClientMessage::is_request),
2093 }
2094 }
2095
2096 pub fn as_single(self) -> result::Result<ClientMessage, SdkError> {
2097 match self {
2098 ClientMessages::Single(client_message) => Ok(client_message),
2099 ClientMessages::Batch(_) => Err(SdkError::internal_error()
2100 .with_message("Error: cannot convert ClientMessages::Batch to ClientMessage::Single")),
2101 }
2102 }
2103 pub fn as_batch(self) -> result::Result<Vec<ClientMessage>, SdkError> {
2104 match self {
2105 ClientMessages::Single(_) => Err(SdkError::internal_error()
2106 .with_message("Error: cannot convert ClientMessage::Single to ClientMessages::Batch")),
2107 ClientMessages::Batch(client_messages) => Ok(client_messages),
2108 }
2109 }
2110}
2111
2112impl From<ClientMessage> for ClientMessages {
2113 fn from(value: ClientMessage) -> Self {
2114 Self::Single(value)
2115 }
2116}
2117
2118impl From<Vec<ClientMessage>> for ClientMessages {
2119 fn from(value: Vec<ClientMessage>) -> Self {
2120 Self::Batch(value)
2121 }
2122}
2123
2124impl Display for ClientMessages {
2125 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2126 write!(
2127 f,
2128 "{}",
2129 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
2130 )
2131 }
2132}
2133
2134#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2135#[serde(untagged)]
2136#[allow(clippy::large_enum_variant)]
2137pub enum ServerMessages {
2138 Single(ServerMessage),
2139 Batch(Vec<ServerMessage>),
2140}
2141
2142impl ServerMessages {
2143 pub fn is_batch(&self) -> bool {
2144 matches!(self, ServerMessages::Batch(_))
2145 }
2146
2147 pub fn includes_request(&self) -> bool {
2148 match self {
2149 ServerMessages::Single(server_message) => server_message.is_request(),
2150 ServerMessages::Batch(server_messages) => server_messages.iter().any(ServerMessage::is_request),
2151 }
2152 }
2153
2154 pub fn as_single(self) -> result::Result<ServerMessage, SdkError> {
2155 match self {
2156 ServerMessages::Single(server_message) => Ok(server_message),
2157 ServerMessages::Batch(_) => Err(SdkError::internal_error()
2158 .with_message("Error: cannot convert ServerMessages::Batch to ServerMessage::Single")),
2159 }
2160 }
2161 pub fn as_batch(self) -> result::Result<Vec<ServerMessage>, SdkError> {
2162 match self {
2163 ServerMessages::Single(_) => Err(SdkError::internal_error()
2164 .with_message("Error: cannot convert ServerMessage::Single to ServerMessages::Batch")),
2165 ServerMessages::Batch(server_messages) => Ok(server_messages),
2166 }
2167 }
2168}
2169
2170impl From<ServerMessage> for ServerMessages {
2171 fn from(value: ServerMessage) -> Self {
2172 Self::Single(value)
2173 }
2174}
2175
2176impl From<Vec<ServerMessage>> for ServerMessages {
2177 fn from(value: Vec<ServerMessage>) -> Self {
2178 Self::Batch(value)
2179 }
2180}
2181
2182impl Display for ServerMessages {
2183 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2184 write!(
2185 f,
2186 "{}",
2187 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
2188 )
2189 }
2190}
2191
2192#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2193#[serde(untagged)]
2194#[allow(clippy::large_enum_variant)]
2195pub enum MessagesFromServer {
2196 Single(MessageFromServer),
2197 Batch(Vec<MessageFromServer>),
2198}
2199
2200impl MessagesFromServer {
2201 pub fn is_batch(&self) -> bool {
2202 matches!(self, MessagesFromServer::Batch(_))
2203 }
2204
2205 pub fn includes_request(&self) -> bool {
2206 match self {
2207 MessagesFromServer::Single(server_message) => server_message.is_request(),
2208 MessagesFromServer::Batch(server_messages) => server_messages.iter().any(MessageFromServer::is_request),
2209 }
2210 }
2211
2212 pub fn as_single(self) -> result::Result<MessageFromServer, SdkError> {
2213 match self {
2214 MessagesFromServer::Single(server_message) => Ok(server_message),
2215 MessagesFromServer::Batch(_) => Err(SdkError::internal_error()
2216 .with_message("Error: cannot convert MessagesFromServer::Batch to MessageFromServer::Single")),
2217 }
2218 }
2219 pub fn as_batch(self) -> result::Result<Vec<MessageFromServer>, SdkError> {
2220 match self {
2221 MessagesFromServer::Single(_) => Err(SdkError::internal_error()
2222 .with_message("Error: cannot convert MessageFromServer::Single to MessagesFromServer::Batch")),
2223 MessagesFromServer::Batch(server_messages) => Ok(server_messages),
2224 }
2225 }
2226}
2227
2228impl From<MessageFromServer> for MessagesFromServer {
2229 fn from(value: MessageFromServer) -> Self {
2230 Self::Single(value)
2231 }
2232}
2233
2234impl From<Vec<MessageFromServer>> for MessagesFromServer {
2235 fn from(value: Vec<MessageFromServer>) -> Self {
2236 Self::Batch(value)
2237 }
2238}
2239
2240#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2241#[serde(untagged)]
2242#[allow(clippy::large_enum_variant)]
2243pub enum MessagesFromClient {
2244 Single(MessageFromClient),
2245 Batch(Vec<MessageFromClient>),
2246}
2247
2248impl MessagesFromClient {
2249 pub fn is_batch(&self) -> bool {
2250 matches!(self, MessagesFromClient::Batch(_))
2251 }
2252
2253 pub fn includes_request(&self) -> bool {
2254 match self {
2255 MessagesFromClient::Single(server_message) => server_message.is_request(),
2256 MessagesFromClient::Batch(server_messages) => server_messages.iter().any(MessageFromClient::is_request),
2257 }
2258 }
2259
2260 pub fn as_single(self) -> result::Result<MessageFromClient, SdkError> {
2261 match self {
2262 MessagesFromClient::Single(server_message) => Ok(server_message),
2263 MessagesFromClient::Batch(_) => Err(SdkError::internal_error()
2264 .with_message("Error: cannot convert MessagesFromClient::Batch to MessageFromClient::Single")),
2265 }
2266 }
2267 pub fn as_batch(self) -> result::Result<Vec<MessageFromClient>, SdkError> {
2268 match self {
2269 MessagesFromClient::Single(_) => Err(SdkError::internal_error()
2270 .with_message("Error: cannot convert MessageFromClient::Single to MessagesFromClient::Batch")),
2271 MessagesFromClient::Batch(server_messages) => Ok(server_messages),
2272 }
2273 }
2274}
2275
2276impl From<MessageFromClient> for MessagesFromClient {
2277 fn from(value: MessageFromClient) -> Self {
2278 Self::Single(value)
2279 }
2280}
2281
2282impl From<Vec<MessageFromClient>> for MessagesFromClient {
2283 fn from(value: Vec<MessageFromClient>) -> Self {
2284 Self::Batch(value)
2285 }
2286}
2287
2288#[derive(Debug)]
2289pub struct StringSchemaFormatError {
2290 invalid_value: String,
2291}
2292
2293impl core::fmt::Display for StringSchemaFormatError {
2294 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2295 write!(f, "Invalid string schema format: '{}'", self.invalid_value)
2296 }
2297}
2298
2299impl std::error::Error for StringSchemaFormatError {}
2300
2301impl FromStr for StringSchemaFormat {
2302 type Err = StringSchemaFormatError;
2303
2304 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2305 match s {
2306 "date" => Ok(Self::Date),
2307 "date-time" => Ok(Self::DateTime),
2308 "email" => Ok(Self::Email),
2309 "uri" => Ok(Self::Uri),
2310 _ => Err(StringSchemaFormatError {
2311 invalid_value: s.to_string(),
2312 }),
2313 }
2314 }
2315}
2316
2317fn try_from_enum_schema(map: &serde_json::Map<String, Value>) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2319 let has_one_of = map.contains_key("oneOf");
2321 let has_enum = map.contains_key("enum");
2322 let has_enum_names = map.contains_key("enumNames");
2323
2324 if has_one_of {
2325 let schema: TitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2326 RpcError::parse_error().with_message(format!("Failed to parse TitledSingleSelectEnumSchema: {e}"))
2327 })?;
2328
2329 Ok(PrimitiveSchemaDefinition::TitledSingleSelectEnumSchema(schema))
2330 } else if has_enum && has_enum_names {
2331 let schema: LegacyTitledEnumSchema = serde_json::from_value(Value::Object(map.clone()))
2332 .map_err(|e| RpcError::parse_error().with_message(format!("Failed to parse LegacyTitledEnumSchema: {e}")))?;
2333 Ok(PrimitiveSchemaDefinition::LegacyTitledEnumSchema(schema))
2334 } else if has_enum {
2335 let schema: UntitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2336 RpcError::parse_error().with_message(format!("Failed to parse UntitledSingleSelectEnumSchema: {e}"))
2337 })?;
2338 Ok(PrimitiveSchemaDefinition::UntitledSingleSelectEnumSchema(schema))
2339 } else {
2340 Err(RpcError::parse_error().with_message("Invalid enum schema: missing 'enum' or 'oneOf'".to_string()))
2341 }
2342}
2343
2344fn try_from_multi_select_schema(
2346 map: &serde_json::Map<String, Value>,
2347) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2348 let items = map
2349 .get("items")
2350 .ok_or(RpcError::parse_error().with_message("Array schema missing 'items' field".to_string()))?;
2351
2352 let items_obj = items
2353 .as_object()
2354 .ok_or(RpcError::parse_error().with_message("Field 'items' must be an object".to_string()))?;
2355
2356 if items_obj.contains_key("anyOf") {
2357 let schema: TitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2358 RpcError::parse_error().with_message(format!("Failed to parse TitledMultiSelectEnumSchema: {e}"))
2359 })?;
2360 Ok(PrimitiveSchemaDefinition::TitledMultiSelectEnumSchema(schema))
2361 } else if items_obj.contains_key("enum") {
2362 let schema: UntitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2363 RpcError::parse_error().with_message(format!("Failed to parse UntitledMultiSelectEnumSchema: {e}"))
2364 })?;
2365 Ok(PrimitiveSchemaDefinition::UntitledMultiSelectEnumSchema(schema))
2366 } else {
2367 Err(RpcError::parse_error()
2368 .with_message("Array schema 'items' must contain 'enum' or 'oneOf' to be a multi-select enum".to_string()))
2369 }
2370}
2371
2372impl TryFrom<&serde_json::Map<String, Value>> for PrimitiveSchemaDefinition {
2373 type Error = RpcError;
2374
2375 fn try_from(value: &serde_json::Map<String, serde_json::Value>) -> result::Result<Self, Self::Error> {
2376 if value.contains_key("enum") || value.contains_key("oneOf") {
2378 return try_from_enum_schema(value);
2379 }
2380
2381 if value.get("type").and_then(|v| v.as_str()) == Some("array") {
2383 return try_from_multi_select_schema(value);
2384 }
2385
2386 let input_type = value
2387 .get("type")
2388 .and_then(|v| v.as_str())
2389 .or_else(|| value.get("oneOf").map(|_| "enum")) .ok_or_else(|| {
2391 RpcError::parse_error().with_message("'type' is missing and data type is not supported!".to_string())
2392 })?;
2393
2394 let description = value.get("description").and_then(|v| v.as_str().map(|s| s.to_string()));
2395 let title = value.get("title").and_then(|v| v.as_str().map(|s| s.to_string()));
2396
2397 let schema_definition: PrimitiveSchemaDefinition = match input_type {
2398 "string" => {
2399 let max_length = value.get("maxLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2400 let min_length = value.get("minLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2401 let default = value.get("default").and_then(|v| v.as_str().map(|s| s.to_string()));
2402
2403 let format_str = value.get("format").and_then(|v| v.as_str());
2404 let format = format_str.and_then(|s| StringSchemaFormat::from_str(s).ok());
2405
2406 PrimitiveSchemaDefinition::StringSchema(StringSchema::new(
2407 default,
2408 description,
2409 format,
2410 max_length,
2411 min_length,
2412 title,
2413 ))
2414 }
2415 "number" | "integer" => {
2416 let maximum = value.get("maximum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2417 let minimum = value.get("minimum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2418 let default = value.get("default").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2419
2420 PrimitiveSchemaDefinition::NumberSchema(NumberSchema {
2421 default,
2422 description,
2423 maximum,
2424 minimum,
2425 title,
2426 type_: if input_type == "integer" {
2427 NumberSchemaType::Integer
2428 } else {
2429 NumberSchemaType::Number
2430 },
2431 })
2432 }
2433 "boolean" => {
2434 let default = value.get("default").and_then(|v| v.as_bool().map(|s| s.to_owned()));
2435 PrimitiveSchemaDefinition::BooleanSchema(BooleanSchema::new(default, description, title))
2436 }
2437 other => {
2438 return Err(RpcError::parse_error().with_message(format!("'{other}' type is not currently supported")));
2439 }
2440 };
2441
2442 Ok(schema_definition)
2443 }
2444}
2445
2446impl RequestFromServer {
2447 pub fn is_task_augmented(&self) -> bool {
2448 match self {
2449 RequestFromServer::CreateMessageRequest(create_message_request_params) => {
2450 create_message_request_params.is_task_augmented()
2451 }
2452 RequestFromServer::ElicitRequest(elicit_request_params) => elicit_request_params.is_task_augmented(),
2453 _ => false,
2454 }
2455 }
2456}
2457
2458impl MessageFromServer {
2459 pub fn is_task_augmented(&self) -> bool {
2460 match self {
2461 MessageFromServer::RequestFromServer(request_from_server) => request_from_server.is_task_augmented(),
2462 _ => false,
2463 }
2464 }
2465}
2466
2467impl CallToolRequest {
2468 pub fn is_task_augmented(&self) -> bool {
2469 self.params.is_task_augmented()
2470 }
2471}
2472
2473impl CallToolRequestParams {
2474 pub fn is_task_augmented(&self) -> bool {
2475 self.task.is_some()
2476 }
2477}
2478
2479impl CreateMessageRequestParams {
2480 pub fn is_task_augmented(&self) -> bool {
2481 self.task.is_some()
2482 }
2483}
2484
2485impl ElicitRequestParams {
2486 pub fn is_task_augmented(&self) -> bool {
2487 match self {
2488 ElicitRequestParams::UrlParams(elicit_request_url_params) => elicit_request_url_params.task.is_some(),
2489 ElicitRequestParams::FormParams(elicit_request_form_params) => elicit_request_form_params.task.is_some(),
2490 }
2491 }
2492
2493 pub fn message(&self) -> &str {
2494 match self {
2495 ElicitRequestParams::UrlParams(elicit_request_url_params) => elicit_request_url_params.message.as_str(),
2496 ElicitRequestParams::FormParams(elicit_request_form_params) => elicit_request_form_params.message.as_str(),
2497 }
2498 }
2499
2500 pub fn with_task(mut self, task: TaskMetadata) -> Self {
2502 match &mut self {
2503 ElicitRequestParams::UrlParams(params) => {
2504 params.task = Some(task);
2505 }
2506 ElicitRequestParams::FormParams(params) => {
2507 params.task = Some(task);
2508 }
2509 }
2510 self
2511 }
2512}
2513
2514impl ElicitRequestUrlParams {
2515 pub fn with_task(mut self, task: TaskMetadata) -> Self {
2517 self.task = Some(task);
2518 self
2519 }
2520}
2521
2522impl ElicitRequestFormParams {
2523 pub fn with_task(mut self, task: TaskMetadata) -> Self {
2525 self.task = Some(task);
2526 self
2527 }
2528}
2529
2530impl ServerCapabilities {
2531 pub fn can_list_tasks(&self) -> bool {
2535 self.tasks.as_ref().is_some_and(|tasks| tasks.can_list_tasks())
2536 }
2537
2538 pub fn can_cancel_tasks(&self) -> bool {
2542 self.tasks.as_ref().is_some_and(|tasks| tasks.can_cancel_tasks())
2543 }
2544
2545 pub fn can_run_task_augmented_tools(&self) -> bool {
2547 self.tasks.as_ref().is_some_and(|tasks| tasks.can_run_task_augmented_tools())
2548 }
2549
2550 pub fn can_handle_request(&self, client_request: &ClientJsonrpcRequest) -> std::result::Result<(), RpcError> {
2551 let request_method = client_request.method();
2552
2553 fn create_error(capability: &str, method: &str) -> RpcError {
2555 RpcError::internal_error().with_message(create_unsupported_capability_message("Server", capability, method))
2556 }
2557
2558 match client_request {
2559 ClientJsonrpcRequest::SetLevelRequest(_) if self.logging.is_none() => {
2560 return Err(create_error("logging", request_method));
2561 }
2562 ClientJsonrpcRequest::GetPromptRequest(_) | ClientJsonrpcRequest::ListPromptsRequest(_)
2563 if self.prompts.is_none() =>
2564 {
2565 return Err(create_error("prompts", request_method));
2566 }
2567
2568 ClientJsonrpcRequest::ListResourcesRequest(_)
2569 | ClientJsonrpcRequest::ListResourceTemplatesRequest(_)
2570 | ClientJsonrpcRequest::ReadResourceRequest(_)
2571 | ClientJsonrpcRequest::SubscribeRequest(_)
2572 | ClientJsonrpcRequest::UnsubscribeRequest(_)
2573 if self.resources.is_none() =>
2574 {
2575 return Err(create_error("resources", request_method));
2576 }
2577
2578 ClientJsonrpcRequest::CallToolRequest(call_tool_request)
2579 if call_tool_request.is_task_augmented() && !self.can_run_task_augmented_tools() =>
2580 {
2581 return Err(create_error("Task-augmented tool call", request_method));
2582 }
2583
2584 ClientJsonrpcRequest::CallToolRequest(_) | ClientJsonrpcRequest::ListToolsRequest(_) if self.tools.is_none() => {
2585 return Err(create_error("tools", request_method));
2586 }
2587 ClientJsonrpcRequest::CompleteRequest(_) if self.completions.is_none() => {
2588 return Err(create_error("completions", request_method));
2589 }
2590
2591 ClientJsonrpcRequest::GetTaskRequest(_)
2592 | ClientJsonrpcRequest::GetTaskPayloadRequest(_)
2593 | ClientJsonrpcRequest::CancelTaskRequest(_)
2594 | ClientJsonrpcRequest::ListTasksRequest(_)
2595 if self.tasks.is_none() =>
2596 {
2597 return Err(create_error("task", request_method));
2598 }
2599 ClientJsonrpcRequest::ListTasksRequest(_) if !self.can_list_tasks() => {
2600 return Err(create_error("listing tasks", request_method));
2601 }
2602 ClientJsonrpcRequest::CancelTaskRequest(_) if !self.can_cancel_tasks() => {
2603 return Err(create_error("task cancellation", request_method));
2604 }
2605 _ => {}
2606 };
2607 Ok(())
2608 }
2609
2610 pub fn can_accept_notification(&self, notification_method: &str) -> std::result::Result<(), RpcError> {
2617 let entity = "Server";
2618
2619 if LoggingMessageNotification::method_value().eq(notification_method) && self.logging.is_none() {
2620 return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2621 entity,
2622 "logging",
2623 notification_method,
2624 )));
2625 }
2626
2627 if [
2628 ResourceUpdatedNotification::method_value(),
2629 ResourceListChangedNotification::method_value(),
2630 ]
2631 .contains(¬ification_method)
2632 && self.resources.is_none()
2633 {
2634 return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2635 entity,
2636 "notifying about resources",
2637 notification_method,
2638 )));
2639 }
2640
2641 if ToolListChangedNotification::method_value().eq(notification_method) && self.tools.is_none() {
2642 return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2643 entity,
2644 "notifying of tool list changes",
2645 notification_method,
2646 )));
2647 }
2648
2649 if PromptListChangedNotification::method_value().eq(notification_method) && self.prompts.is_none() {
2650 return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2651 entity,
2652 "notifying of prompt list changes",
2653 notification_method,
2654 )));
2655 }
2656
2657 Ok(())
2658 }
2659}
2660
2661impl ServerTasks {
2662 pub fn can_list_tasks(&self) -> bool {
2666 self.list.is_some()
2667 }
2668
2669 pub fn can_cancel_tasks(&self) -> bool {
2673 self.cancel.is_some()
2674 }
2675
2676 pub fn can_run_task_augmented_tools(&self) -> bool {
2678 if let Some(requests) = self.requests.as_ref() {
2679 if let Some(tools) = requests.tools.as_ref() {
2680 return tools.call.is_some();
2681 }
2682 }
2683 false
2684 }
2685}
2686
2687fn create_unsupported_capability_message(entity: &str, capability: &str, method_name: &str) -> String {
2706 format!("{entity} does not support {capability} (required for {method_name})")
2707}
2708
2709impl ClientCapabilities {
2710 pub fn can_list_tasks(&self) -> bool {
2714 self.tasks.as_ref().is_some_and(|task| task.can_list_tasks())
2715 }
2716
2717 pub fn can_cancel_tasks(&self) -> bool {
2721 self.tasks.as_ref().is_some_and(|task| task.can_cancel_tasks())
2722 }
2723
2724 pub fn can_accept_elicitation_task(&self) -> bool {
2726 self.tasks.as_ref().is_some_and(|task| task.can_accept_elicitation_task())
2727 }
2728
2729 pub fn can_accept_sampling_task(&self) -> bool {
2731 self.tasks.as_ref().is_some_and(|task| task.can_accept_sampling_task())
2732 }
2733
2734 pub fn can_handle_request(&self, server_jsonrpc_request: &ServerJsonrpcRequest) -> std::result::Result<(), RpcError> {
2735 let request_method = server_jsonrpc_request.method();
2736
2737 fn create_error(capability: &str, method: &str) -> RpcError {
2739 RpcError::internal_error().with_message(create_unsupported_capability_message("Client", capability, method))
2740 }
2741
2742 match server_jsonrpc_request {
2743 ServerJsonrpcRequest::CreateMessageRequest(create_message_request) => {
2744 match self.sampling.as_ref() {
2745 Some(samplig_capabilities) => {
2746 if create_message_request.params.include_context.is_some() && samplig_capabilities.context.is_none()
2748 {
2749 return Err(create_error("context inclusion", request_method));
2750 }
2751
2752 if create_message_request.params.tool_choice.is_some() && samplig_capabilities.tools.is_none() {
2753 return Err(create_error("tool choice", request_method));
2754 }
2755 }
2756 None => {
2757 return Err(create_error("sampling capability", request_method));
2758 }
2759 }
2760
2761 if create_message_request.params.is_task_augmented() && !self.can_accept_sampling_task() {
2762 return Err(create_error("sampling task", request_method));
2763 }
2764 }
2765 ServerJsonrpcRequest::ListRootsRequest(_) => {
2766 if self.roots.is_none() {
2767 return Err(create_error("roots capability", request_method));
2768 }
2769 }
2770 ServerJsonrpcRequest::GetTaskRequest(_) | ServerJsonrpcRequest::GetTaskPayloadRequest(_) => {
2771 if self.tasks.is_none() {
2772 return Err(create_error("Task", request_method));
2773 }
2774 }
2775 ServerJsonrpcRequest::CancelTaskRequest(_) => {
2776 if let Some(tasks) = self.tasks.as_ref() {
2777 if !tasks.can_cancel_tasks() {
2778 return Err(create_error("task cancellation", request_method));
2779 }
2780 }
2781 }
2782 ServerJsonrpcRequest::ListTasksRequest(_) => {
2783 if let Some(tasks) = self.tasks.as_ref() {
2784 if !tasks.can_list_tasks() {
2785 return Err(create_error("listing tasks", request_method));
2786 }
2787 }
2788 }
2789
2790 ServerJsonrpcRequest::ElicitRequest(elicit_request) => {
2791 if self.elicitation.is_none() {
2792 return Err(create_error("input elicitation", request_method));
2793 }
2794
2795 if elicit_request.params.is_task_augmented() && !self.can_accept_elicitation_task() {
2796 return Err(create_error("elicitation task", request_method));
2797 }
2798 }
2799 _ => {}
2800 }
2801 Ok(())
2802 }
2803
2804 pub fn can_accept_notification(&self, notification_method: &str) -> std::result::Result<(), RpcError> {
2805 let entity = "Client";
2806
2807 if RootsListChangedNotification::method_value().eq(notification_method) && self.roots.is_none() {
2808 return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2809 entity,
2810 "roots list changed notifications",
2811 notification_method,
2812 )));
2813 }
2814
2815 Ok(())
2816 }
2817}
2818
2819impl ClientTasks {
2820 pub fn can_list_tasks(&self) -> bool {
2824 self.list.is_some()
2825 }
2826
2827 pub fn can_cancel_tasks(&self) -> bool {
2831 self.cancel.is_some()
2832 }
2833
2834 pub fn can_accept_elicitation_task(&self) -> bool {
2836 if let Some(requests) = self.requests.as_ref() {
2837 if let Some(elicitation) = requests.elicitation.as_ref() {
2838 return elicitation.create.is_some();
2839 }
2840 }
2841 false
2842 }
2843
2844 pub fn can_accept_sampling_task(&self) -> bool {
2846 if let Some(requests) = self.requests.as_ref() {
2847 if let Some(sampling) = requests.sampling.as_ref() {
2848 return sampling.create_message.is_some();
2849 }
2850 }
2851 false
2852 }
2853}
2854
2855impl From<JsonrpcRequest> for CustomRequest {
2856 fn from(request: JsonrpcRequest) -> Self {
2857 Self {
2858 method: request.method,
2859 params: request.params,
2860 }
2861 }
2862}
2863
2864impl From<JsonrpcNotification> for CustomNotification {
2865 fn from(notification: JsonrpcNotification) -> Self {
2866 Self {
2867 method: notification.method,
2868 params: notification.params,
2869 }
2870 }
2871}
2872
2873impl TaskStatus {
2876 pub fn is_terminal(&self) -> bool {
2877 match self {
2878 TaskStatus::Cancelled | TaskStatus::Completed | TaskStatus::Failed => true,
2879 TaskStatus::InputRequired | TaskStatus::Working => false,
2880 }
2881 }
2882}
2883
2884impl Task {
2887 pub fn is_terminal(&self) -> bool {
2888 self.status.is_terminal()
2889 }
2890}
2891
2892impl GetTaskResult {
2893 pub fn is_terminal(&self) -> bool {
2894 self.status.is_terminal()
2895 }
2896}
2897
2898impl GetTaskPayloadResult {
2899 pub fn related_task_id(&self) -> Option<&str> {
2909 self.meta
2910 .as_ref()
2911 .and_then(|v| v.get(RELATED_TASK_META_KEY))
2912 .and_then(|v| v.as_str())
2913 }
2914
2915 pub fn set_related_task_id<T>(&mut self, task_id: T)
2929 where
2930 T: Into<String>,
2931 {
2932 let task_json = json!({ "taskId": task_id.into() });
2933
2934 if let Some(meta) = &mut self.meta {
2935 meta.insert(RELATED_TASK_META_KEY.into(), task_json);
2936 } else {
2937 let mut new_meta = serde_json::Map::new();
2938 new_meta.insert(RELATED_TASK_META_KEY.into(), task_json);
2939 self.meta = Some(new_meta);
2940 }
2941 }
2942}
2943
2944pub trait McpMetaEx {
2945 fn related_task_id(&self) -> Option<&str>;
2955 fn set_related_task_id<T>(&mut self, task_id: T)
2969 where
2970 T: Into<String>;
2971
2972 fn with_related_task_id<T>(self, task_id: T) -> Self
2973 where
2974 T: Into<String>;
2975
2976 fn add<K, V>(self, key: K, value: V) -> Self
2979 where
2980 K: Into<String>,
2981 V: Into<Value>;
2982
2983 fn add_if<K, V>(self, condition: bool, key: K, value: V) -> Self
2985 where
2986 K: Into<String>,
2987 V: Into<Value>;
2988
2989 fn add_raw<K>(self, key: K, value: Value) -> Self
2991 where
2992 K: Into<String>;
2993}
2994
2995impl McpMetaEx for serde_json::Map<String, Value> {
2996 fn related_task_id(&self) -> Option<&str> {
2997 self.get(RELATED_TASK_META_KEY).and_then(|v| v.as_str())
2998 }
2999
3000 fn set_related_task_id<T>(&mut self, task_id: T)
3001 where
3002 T: Into<String>,
3003 {
3004 let task_json = json!({ "taskId": task_id.into() });
3005 self.entry(RELATED_TASK_META_KEY)
3006 .and_modify(|e| *e = task_json.clone())
3007 .or_insert_with(|| task_json);
3008 }
3009
3010 fn with_related_task_id<T>(mut self, task_id: T) -> Self
3011 where
3012 T: Into<String>,
3013 {
3014 self.set_related_task_id(task_id);
3015 self
3016 }
3017
3018 fn add<K, V>(mut self, key: K, value: V) -> Self
3021 where
3022 K: Into<String>,
3023 V: Into<Value>,
3024 {
3025 self.insert(key.into(), value.into());
3026 self
3027 }
3028
3029 fn add_if<K, V>(mut self, condition: bool, key: K, value: V) -> Self
3031 where
3032 K: Into<String>,
3033 V: Into<Value>,
3034 {
3035 if condition {
3036 self.insert(key.into(), value.into());
3037 self
3038 } else {
3039 self
3040 }
3041 }
3042
3043 fn add_raw<K>(mut self, key: K, value: Value) -> Self
3045 where
3046 K: Into<String>,
3047 {
3048 self.insert(key.into(), value);
3049 self
3050 }
3051}
3052
3053impl FromStr for Role {
3054 type Err = RpcError;
3055
3056 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
3057 match s {
3058 "assistant" => Ok(Role::Assistant),
3059 "user" => Ok(Role::User),
3060 _ => {
3061 Err(RpcError::parse_error()
3062 .with_message(format!("Invalid role '{s}'. Expected one of: 'assistant', 'user'")))
3063 }
3064 }
3065 }
3066}
3067
3068pub type CustomNotification = CustomRequest;
3069
3070impl ::serde::Serialize for ServerJsonrpcResponse {
3072 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
3073 where
3074 S: ::serde::Serializer,
3075 {
3076 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
3077 state.serialize_field("id", &self.id)?;
3078 state.serialize_field("jsonrpc", &self.jsonrpc)?;
3079 state.serialize_field("result", &self.result)?;
3080 state.end()
3081 }
3082}
3083impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcResponse {
3084 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
3085 where
3086 D: ::serde::Deserializer<'de>,
3087 {
3088 use serde::de::{self, MapAccess, Visitor};
3089 use std::fmt;
3090 struct ServerJsonrpcResultVisitor;
3091 impl<'de> Visitor<'de> for ServerJsonrpcResultVisitor {
3092 type Value = ServerJsonrpcResponse;
3093 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3094 formatter.write_str("a valid JSON-RPC response object")
3095 }
3096 fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcResponse, M::Error>
3097 where
3098 M: MapAccess<'de>,
3099 {
3100 let mut id: Option<RequestId> = None;
3101 let mut jsonrpc: Option<String> = None;
3102 let mut result: Option<Value> = None;
3103 while let Some(key) = map.next_key::<String>()? {
3104 match key.as_str() {
3105 "id" => id = Some(map.next_value()?),
3106 "jsonrpc" => jsonrpc = Some(map.next_value()?),
3107 "result" => result = Some(map.next_value()?),
3108 _ => {
3109 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
3110 }
3111 }
3112 }
3113 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
3114 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
3115 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
3116 let result = serde_json::from_value::<ResultFromServer>(result).map_err(de::Error::custom)?;
3117 Ok(ServerJsonrpcResponse { id, jsonrpc, result })
3118 }
3119 }
3120 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ServerJsonrpcResultVisitor)
3121 }
3122}
3123impl ::serde::Serialize for ClientJsonrpcResponse {
3124 fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
3125 where
3126 S: ::serde::Serializer,
3127 {
3128 let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
3129 state.serialize_field("id", &self.id)?;
3130 state.serialize_field("jsonrpc", &self.jsonrpc)?;
3131 state.serialize_field("result", &self.result)?;
3132 state.end()
3133 }
3134}
3135impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcResponse {
3136 fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
3137 where
3138 D: ::serde::Deserializer<'de>,
3139 {
3140 use serde::de::{self, MapAccess, Visitor};
3141 use std::fmt;
3142 struct ClientJsonrpcResultVisitor;
3143 impl<'de> Visitor<'de> for ClientJsonrpcResultVisitor {
3144 type Value = ClientJsonrpcResponse;
3145 fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3146 formatter.write_str("a valid JSON-RPC response object")
3147 }
3148 fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcResponse, M::Error>
3149 where
3150 M: MapAccess<'de>,
3151 {
3152 let mut id: Option<RequestId> = None;
3153 let mut jsonrpc: Option<String> = None;
3154 let mut result: Option<Value> = None;
3155 while let Some(key) = map.next_key::<String>()? {
3156 match key.as_str() {
3157 "id" => id = Some(map.next_value()?),
3158 "jsonrpc" => jsonrpc = Some(map.next_value()?),
3159 "result" => result = Some(map.next_value()?),
3160 _ => {
3161 return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
3162 }
3163 }
3164 }
3165 let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
3166 let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
3167 let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
3168 let result = serde_json::from_value::<ResultFromClient>(result).map_err(de::Error::custom)?;
3169 Ok(ClientJsonrpcResponse { id, jsonrpc, result })
3170 }
3171 }
3172 deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ClientJsonrpcResultVisitor)
3173 }
3174}
3175impl From<Result> for ResultFromClient {
3176 fn from(value: Result) -> Self {
3177 Self::Result(value)
3178 }
3179}
3180impl From<GetTaskResult> for ResultFromClient {
3181 fn from(value: GetTaskResult) -> Self {
3182 Self::GetTaskResult(value)
3183 }
3184}
3185impl From<GetTaskPayloadResult> for ResultFromClient {
3186 fn from(value: GetTaskPayloadResult) -> Self {
3187 Self::GetTaskPayloadResult(value)
3188 }
3189}
3190impl From<CancelTaskResult> for ResultFromClient {
3191 fn from(value: CancelTaskResult) -> Self {
3192 Self::CancelTaskResult(value)
3193 }
3194}
3195impl From<ListTasksResult> for ResultFromClient {
3196 fn from(value: ListTasksResult) -> Self {
3197 Self::ListTasksResult(value)
3198 }
3199}
3200impl From<CreateMessageResult> for ResultFromClient {
3201 fn from(value: CreateMessageResult) -> Self {
3202 Self::CreateMessageResult(value)
3203 }
3204}
3205impl From<ListRootsResult> for ResultFromClient {
3206 fn from(value: ListRootsResult) -> Self {
3207 Self::ListRootsResult(value)
3208 }
3209}
3210impl From<ElicitResult> for ResultFromClient {
3211 fn from(value: ElicitResult) -> Self {
3212 Self::ElicitResult(value)
3213 }
3214}
3215impl From<CreateTaskResult> for ResultFromClient {
3216 fn from(value: CreateTaskResult) -> Self {
3217 Self::CreateTaskResult(value)
3218 }
3219}
3220impl From<Result> for MessageFromClient {
3221 fn from(value: Result) -> Self {
3222 MessageFromClient::ResultFromClient(value.into())
3223 }
3224}
3225impl From<GetTaskResult> for MessageFromClient {
3226 fn from(value: GetTaskResult) -> Self {
3227 MessageFromClient::ResultFromClient(value.into())
3228 }
3229}
3230impl From<GetTaskPayloadResult> for MessageFromClient {
3231 fn from(value: GetTaskPayloadResult) -> Self {
3232 MessageFromClient::ResultFromClient(value.into())
3233 }
3234}
3235impl From<CancelTaskResult> for MessageFromClient {
3236 fn from(value: CancelTaskResult) -> Self {
3237 MessageFromClient::ResultFromClient(value.into())
3238 }
3239}
3240impl From<ListTasksResult> for MessageFromClient {
3241 fn from(value: ListTasksResult) -> Self {
3242 MessageFromClient::ResultFromClient(value.into())
3243 }
3244}
3245impl From<CreateMessageResult> for MessageFromClient {
3246 fn from(value: CreateMessageResult) -> Self {
3247 MessageFromClient::ResultFromClient(value.into())
3248 }
3249}
3250impl From<ListRootsResult> for MessageFromClient {
3251 fn from(value: ListRootsResult) -> Self {
3252 MessageFromClient::ResultFromClient(value.into())
3253 }
3254}
3255impl From<ElicitResult> for MessageFromClient {
3256 fn from(value: ElicitResult) -> Self {
3257 MessageFromClient::ResultFromClient(value.into())
3258 }
3259}
3260impl From<CreateTaskResult> for MessageFromClient {
3261 fn from(value: CreateTaskResult) -> Self {
3262 MessageFromClient::ResultFromClient(value.into())
3263 }
3264}
3265impl From<PingRequest> for ServerJsonrpcRequest {
3266 fn from(value: PingRequest) -> Self {
3267 Self::PingRequest(value)
3268 }
3269}
3270impl From<GetTaskRequest> for ServerJsonrpcRequest {
3271 fn from(value: GetTaskRequest) -> Self {
3272 Self::GetTaskRequest(value)
3273 }
3274}
3275impl From<GetTaskPayloadRequest> for ServerJsonrpcRequest {
3276 fn from(value: GetTaskPayloadRequest) -> Self {
3277 Self::GetTaskPayloadRequest(value)
3278 }
3279}
3280impl From<CancelTaskRequest> for ServerJsonrpcRequest {
3281 fn from(value: CancelTaskRequest) -> Self {
3282 Self::CancelTaskRequest(value)
3283 }
3284}
3285impl From<ListTasksRequest> for ServerJsonrpcRequest {
3286 fn from(value: ListTasksRequest) -> Self {
3287 Self::ListTasksRequest(value)
3288 }
3289}
3290impl From<CreateMessageRequest> for ServerJsonrpcRequest {
3291 fn from(value: CreateMessageRequest) -> Self {
3292 Self::CreateMessageRequest(value)
3293 }
3294}
3295impl From<ListRootsRequest> for ServerJsonrpcRequest {
3296 fn from(value: ListRootsRequest) -> Self {
3297 Self::ListRootsRequest(value)
3298 }
3299}
3300impl From<ElicitRequest> for ServerJsonrpcRequest {
3301 fn from(value: ElicitRequest) -> Self {
3302 Self::ElicitRequest(value)
3303 }
3304}
3305impl From<InitializeRequest> for ClientJsonrpcRequest {
3306 fn from(value: InitializeRequest) -> Self {
3307 Self::InitializeRequest(value)
3308 }
3309}
3310impl From<PingRequest> for ClientJsonrpcRequest {
3311 fn from(value: PingRequest) -> Self {
3312 Self::PingRequest(value)
3313 }
3314}
3315impl From<ListResourcesRequest> for ClientJsonrpcRequest {
3316 fn from(value: ListResourcesRequest) -> Self {
3317 Self::ListResourcesRequest(value)
3318 }
3319}
3320impl From<ListResourceTemplatesRequest> for ClientJsonrpcRequest {
3321 fn from(value: ListResourceTemplatesRequest) -> Self {
3322 Self::ListResourceTemplatesRequest(value)
3323 }
3324}
3325impl From<ReadResourceRequest> for ClientJsonrpcRequest {
3326 fn from(value: ReadResourceRequest) -> Self {
3327 Self::ReadResourceRequest(value)
3328 }
3329}
3330impl From<SubscribeRequest> for ClientJsonrpcRequest {
3331 fn from(value: SubscribeRequest) -> Self {
3332 Self::SubscribeRequest(value)
3333 }
3334}
3335impl From<UnsubscribeRequest> for ClientJsonrpcRequest {
3336 fn from(value: UnsubscribeRequest) -> Self {
3337 Self::UnsubscribeRequest(value)
3338 }
3339}
3340impl From<ListPromptsRequest> for ClientJsonrpcRequest {
3341 fn from(value: ListPromptsRequest) -> Self {
3342 Self::ListPromptsRequest(value)
3343 }
3344}
3345impl From<GetPromptRequest> for ClientJsonrpcRequest {
3346 fn from(value: GetPromptRequest) -> Self {
3347 Self::GetPromptRequest(value)
3348 }
3349}
3350impl From<ListToolsRequest> for ClientJsonrpcRequest {
3351 fn from(value: ListToolsRequest) -> Self {
3352 Self::ListToolsRequest(value)
3353 }
3354}
3355impl From<CallToolRequest> for ClientJsonrpcRequest {
3356 fn from(value: CallToolRequest) -> Self {
3357 Self::CallToolRequest(value)
3358 }
3359}
3360impl From<GetTaskRequest> for ClientJsonrpcRequest {
3361 fn from(value: GetTaskRequest) -> Self {
3362 Self::GetTaskRequest(value)
3363 }
3364}
3365impl From<GetTaskPayloadRequest> for ClientJsonrpcRequest {
3366 fn from(value: GetTaskPayloadRequest) -> Self {
3367 Self::GetTaskPayloadRequest(value)
3368 }
3369}
3370impl From<CancelTaskRequest> for ClientJsonrpcRequest {
3371 fn from(value: CancelTaskRequest) -> Self {
3372 Self::CancelTaskRequest(value)
3373 }
3374}
3375impl From<ListTasksRequest> for ClientJsonrpcRequest {
3376 fn from(value: ListTasksRequest) -> Self {
3377 Self::ListTasksRequest(value)
3378 }
3379}
3380impl From<SetLevelRequest> for ClientJsonrpcRequest {
3381 fn from(value: SetLevelRequest) -> Self {
3382 Self::SetLevelRequest(value)
3383 }
3384}
3385impl From<CompleteRequest> for ClientJsonrpcRequest {
3386 fn from(value: CompleteRequest) -> Self {
3387 Self::CompleteRequest(value)
3388 }
3389}
3390#[allow(non_camel_case_types)]
3392pub enum SdkErrorCodes {
3393 CONNECTION_CLOSED = -32000,
3394 REQUEST_TIMEOUT = -32001,
3395 RESOURCE_NOT_FOUND = -32002,
3396 BAD_REQUEST = -32015,
3397 SESSION_NOT_FOUND = -32016,
3398 INVALID_REQUEST = -32600,
3399 METHOD_NOT_FOUND = -32601,
3400 INVALID_PARAMS = -32602,
3401 INTERNAL_ERROR = -32603,
3402 PARSE_ERROR = -32700,
3403 URL_ELICITATION_REQUIRED = -32042,
3404}
3405impl core::fmt::Display for SdkErrorCodes {
3406 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3407 match self {
3408 SdkErrorCodes::CONNECTION_CLOSED => write!(f, "Connection closed"),
3409 SdkErrorCodes::REQUEST_TIMEOUT => write!(f, "Request timeout"),
3410 SdkErrorCodes::INVALID_REQUEST => write!(f, "Invalid request"),
3411 SdkErrorCodes::METHOD_NOT_FOUND => write!(f, "Method not found"),
3412 SdkErrorCodes::INVALID_PARAMS => write!(f, "Invalid params"),
3413 SdkErrorCodes::INTERNAL_ERROR => write!(f, "Internal error"),
3414 SdkErrorCodes::PARSE_ERROR => write!(f, "Parse Error"),
3415 SdkErrorCodes::RESOURCE_NOT_FOUND => write!(f, "Resource not found"),
3416 SdkErrorCodes::BAD_REQUEST => write!(f, "Bad request"),
3417 SdkErrorCodes::SESSION_NOT_FOUND => write!(f, "Session not found"),
3418 SdkErrorCodes::URL_ELICITATION_REQUIRED => {
3419 write!(
3420 f,
3421 "A required URL was not provided. Please supply the requested URL to continue."
3422 )
3423 }
3424 }
3425 }
3426}
3427impl From<SdkErrorCodes> for i64 {
3428 fn from(code: SdkErrorCodes) -> Self {
3429 code as i64
3430 }
3431}
3432#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
3433pub struct SdkError {
3434 pub code: i64,
3436 pub data: ::std::option::Option<::serde_json::Value>,
3438 pub message: ::std::string::String,
3440}
3441impl core::fmt::Display for SdkError {
3442 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3443 write!(f, "MCP error {}: {}", self.code, self.message)
3444 }
3445}
3446impl std::error::Error for SdkError {
3447 fn description(&self) -> &str {
3448 &self.message
3449 }
3450}
3451impl SdkError {
3452 pub fn new(
3453 error_code: SdkErrorCodes,
3454 message: ::std::string::String,
3455 data: ::std::option::Option<::serde_json::Value>,
3456 ) -> Self {
3457 Self {
3458 code: error_code.into(),
3459 data,
3460 message,
3461 }
3462 }
3463 pub fn connection_closed() -> Self {
3464 Self {
3465 code: SdkErrorCodes::CONNECTION_CLOSED.into(),
3466 data: None,
3467 message: SdkErrorCodes::CONNECTION_CLOSED.to_string(),
3468 }
3469 }
3470 pub fn request_timeout(timeout: u128) -> Self {
3471 Self {
3472 code: SdkErrorCodes::REQUEST_TIMEOUT.into(),
3473 data: Some(json!({ "timeout" : timeout })),
3474 message: SdkErrorCodes::REQUEST_TIMEOUT.to_string(),
3475 }
3476 }
3477 pub fn session_not_found() -> Self {
3478 Self {
3479 code: SdkErrorCodes::SESSION_NOT_FOUND.into(),
3480 data: None,
3481 message: SdkErrorCodes::SESSION_NOT_FOUND.to_string(),
3482 }
3483 }
3484 pub fn invalid_request() -> Self {
3485 Self {
3486 code: SdkErrorCodes::INVALID_REQUEST.into(),
3487 data: None,
3488 message: SdkErrorCodes::INVALID_REQUEST.to_string(),
3489 }
3490 }
3491 pub fn method_not_found() -> Self {
3492 Self {
3493 code: SdkErrorCodes::METHOD_NOT_FOUND.into(),
3494 data: None,
3495 message: SdkErrorCodes::METHOD_NOT_FOUND.to_string(),
3496 }
3497 }
3498 pub fn invalid_params() -> Self {
3499 Self {
3500 code: SdkErrorCodes::INVALID_PARAMS.into(),
3501 data: None,
3502 message: SdkErrorCodes::INVALID_PARAMS.to_string(),
3503 }
3504 }
3505 pub fn internal_error() -> Self {
3506 Self {
3507 code: SdkErrorCodes::INTERNAL_ERROR.into(),
3508 data: None,
3509 message: SdkErrorCodes::INTERNAL_ERROR.to_string(),
3510 }
3511 }
3512 pub fn parse_error() -> Self {
3513 Self {
3514 code: SdkErrorCodes::PARSE_ERROR.into(),
3515 data: None,
3516 message: SdkErrorCodes::PARSE_ERROR.to_string(),
3517 }
3518 }
3519 pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
3526 Self {
3527 code: UrlElicitError::code_value(),
3528 data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
3529 json!(
3530 { "elicitations" : [], "error" :
3531 "failed to UrlElicitError data" }
3532 )
3533 })),
3534 message: "URL required. Please provide a URL.".to_string(),
3535 }
3536 }
3537 pub fn resource_not_found() -> Self {
3538 Self {
3539 code: SdkErrorCodes::RESOURCE_NOT_FOUND.into(),
3540 data: None,
3541 message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
3542 }
3543 }
3544 pub fn bad_request() -> Self {
3545 Self {
3546 code: SdkErrorCodes::BAD_REQUEST.into(),
3547 data: None,
3548 message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
3549 }
3550 }
3551 pub fn with_message(mut self, message: &str) -> Self {
3552 self.message = message.to_string();
3553 self
3554 }
3555 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
3556 self.data = data;
3557 self
3558 }
3559}
3560#[allow(non_camel_case_types)]
3562pub enum RpcErrorCodes {
3563 PARSE_ERROR = -32700isize,
3564 INVALID_REQUEST = -32600isize,
3565 METHOD_NOT_FOUND = -32601isize,
3566 INVALID_PARAMS = -32602isize,
3567 INTERNAL_ERROR = -32603isize,
3568 URL_ELICITATION_REQUIRED = -32042isize,
3569}
3570impl From<RpcErrorCodes> for i64 {
3571 fn from(code: RpcErrorCodes) -> Self {
3572 code as i64
3573 }
3574}
3575impl RpcError {
3576 pub fn new(
3593 error_code: RpcErrorCodes,
3594 message: ::std::string::String,
3595 data: ::std::option::Option<::serde_json::Value>,
3596 ) -> Self {
3597 Self {
3598 code: error_code.into(),
3599 data,
3600 message,
3601 }
3602 }
3603 pub fn method_not_found() -> Self {
3614 Self {
3615 code: RpcErrorCodes::METHOD_NOT_FOUND.into(),
3616 data: None,
3617 message: "Method not found".to_string(),
3618 }
3619 }
3620 pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
3627 Self {
3628 code: UrlElicitError::code_value(),
3629 data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
3630 json!(
3631 { "elicitations" : [], "error" :
3632 "failed to UrlElicitError data" }
3633 )
3634 })),
3635 message: "URL required. Please provide a URL.".to_string(),
3636 }
3637 }
3638 pub fn invalid_params() -> Self {
3648 Self {
3649 code: RpcErrorCodes::INVALID_PARAMS.into(),
3650 data: None,
3651 message: "Invalid params".to_string(),
3652 }
3653 }
3654 pub fn invalid_request() -> Self {
3664 Self {
3665 code: RpcErrorCodes::INVALID_REQUEST.into(),
3666 data: None,
3667 message: "Invalid request".to_string(),
3668 }
3669 }
3670 pub fn internal_error() -> Self {
3680 Self {
3681 code: RpcErrorCodes::INTERNAL_ERROR.into(),
3682 data: None,
3683 message: "Internal error".to_string(),
3684 }
3685 }
3686 pub fn parse_error() -> Self {
3696 Self {
3697 code: RpcErrorCodes::PARSE_ERROR.into(),
3698 data: None,
3699 message: "Parse error".to_string(),
3700 }
3701 }
3702 pub fn with_message<T: Into<String>>(mut self, message: T) -> Self {
3712 self.message = message.into();
3713 self
3714 }
3715 pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
3726 self.data = data;
3727 self
3728 }
3729}
3730impl std::error::Error for RpcError {
3731 fn description(&self) -> &str {
3732 &self.message
3733 }
3734}
3735impl Display for RpcError {
3736 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3737 write!(
3738 f,
3739 "{}",
3740 serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
3741 )
3742 }
3743}
3744impl FromStr for RpcError {
3745 type Err = RpcError;
3746 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
3747 serde_json::from_str(s)
3748 .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
3749 }
3750}
3751impl JsonrpcErrorResponse {
3753 pub fn create(
3754 id: Option<RequestId>,
3755 error_code: RpcErrorCodes,
3756 error_message: ::std::string::String,
3757 error_data: ::std::option::Option<::serde_json::Value>,
3758 ) -> Self {
3759 Self::new(RpcError::new(error_code, error_message, error_data), id)
3760 }
3761}
3762impl From<Result> for ResultFromServer {
3763 fn from(value: Result) -> Self {
3764 Self::Result(value)
3765 }
3766}
3767impl From<InitializeResult> for ResultFromServer {
3768 fn from(value: InitializeResult) -> Self {
3769 Self::InitializeResult(value)
3770 }
3771}
3772impl From<ListResourcesResult> for ResultFromServer {
3773 fn from(value: ListResourcesResult) -> Self {
3774 Self::ListResourcesResult(value)
3775 }
3776}
3777impl From<ListResourceTemplatesResult> for ResultFromServer {
3778 fn from(value: ListResourceTemplatesResult) -> Self {
3779 Self::ListResourceTemplatesResult(value)
3780 }
3781}
3782impl From<ReadResourceResult> for ResultFromServer {
3783 fn from(value: ReadResourceResult) -> Self {
3784 Self::ReadResourceResult(value)
3785 }
3786}
3787impl From<ListPromptsResult> for ResultFromServer {
3788 fn from(value: ListPromptsResult) -> Self {
3789 Self::ListPromptsResult(value)
3790 }
3791}
3792impl From<GetPromptResult> for ResultFromServer {
3793 fn from(value: GetPromptResult) -> Self {
3794 Self::GetPromptResult(value)
3795 }
3796}
3797impl From<ListToolsResult> for ResultFromServer {
3798 fn from(value: ListToolsResult) -> Self {
3799 Self::ListToolsResult(value)
3800 }
3801}
3802impl From<CallToolResult> for ResultFromServer {
3803 fn from(value: CallToolResult) -> Self {
3804 Self::CallToolResult(value)
3805 }
3806}
3807impl From<GetTaskResult> for ResultFromServer {
3808 fn from(value: GetTaskResult) -> Self {
3809 Self::GetTaskResult(value)
3810 }
3811}
3812impl From<GetTaskPayloadResult> for ResultFromServer {
3813 fn from(value: GetTaskPayloadResult) -> Self {
3814 Self::GetTaskPayloadResult(value)
3815 }
3816}
3817impl From<CancelTaskResult> for ResultFromServer {
3818 fn from(value: CancelTaskResult) -> Self {
3819 Self::CancelTaskResult(value)
3820 }
3821}
3822impl From<ListTasksResult> for ResultFromServer {
3823 fn from(value: ListTasksResult) -> Self {
3824 Self::ListTasksResult(value)
3825 }
3826}
3827impl From<CompleteResult> for ResultFromServer {
3828 fn from(value: CompleteResult) -> Self {
3829 Self::CompleteResult(value)
3830 }
3831}
3832impl From<CreateTaskResult> for ResultFromServer {
3833 fn from(value: CreateTaskResult) -> Self {
3834 Self::CreateTaskResult(value)
3835 }
3836}
3837impl From<Result> for MessageFromServer {
3838 fn from(value: Result) -> Self {
3839 MessageFromServer::ResultFromServer(value.into())
3840 }
3841}
3842impl From<InitializeResult> for MessageFromServer {
3843 fn from(value: InitializeResult) -> Self {
3844 MessageFromServer::ResultFromServer(value.into())
3845 }
3846}
3847impl From<ListResourcesResult> for MessageFromServer {
3848 fn from(value: ListResourcesResult) -> Self {
3849 MessageFromServer::ResultFromServer(value.into())
3850 }
3851}
3852impl From<ListResourceTemplatesResult> for MessageFromServer {
3853 fn from(value: ListResourceTemplatesResult) -> Self {
3854 MessageFromServer::ResultFromServer(value.into())
3855 }
3856}
3857impl From<ReadResourceResult> for MessageFromServer {
3858 fn from(value: ReadResourceResult) -> Self {
3859 MessageFromServer::ResultFromServer(value.into())
3860 }
3861}
3862impl From<ListPromptsResult> for MessageFromServer {
3863 fn from(value: ListPromptsResult) -> Self {
3864 MessageFromServer::ResultFromServer(value.into())
3865 }
3866}
3867impl From<GetPromptResult> for MessageFromServer {
3868 fn from(value: GetPromptResult) -> Self {
3869 MessageFromServer::ResultFromServer(value.into())
3870 }
3871}
3872impl From<ListToolsResult> for MessageFromServer {
3873 fn from(value: ListToolsResult) -> Self {
3874 MessageFromServer::ResultFromServer(value.into())
3875 }
3876}
3877impl From<CallToolResult> for MessageFromServer {
3878 fn from(value: CallToolResult) -> Self {
3879 MessageFromServer::ResultFromServer(value.into())
3880 }
3881}
3882impl From<GetTaskResult> for MessageFromServer {
3883 fn from(value: GetTaskResult) -> Self {
3884 MessageFromServer::ResultFromServer(value.into())
3885 }
3886}
3887impl From<GetTaskPayloadResult> for MessageFromServer {
3888 fn from(value: GetTaskPayloadResult) -> Self {
3889 MessageFromServer::ResultFromServer(value.into())
3890 }
3891}
3892impl From<CancelTaskResult> for MessageFromServer {
3893 fn from(value: CancelTaskResult) -> Self {
3894 MessageFromServer::ResultFromServer(value.into())
3895 }
3896}
3897impl From<ListTasksResult> for MessageFromServer {
3898 fn from(value: ListTasksResult) -> Self {
3899 MessageFromServer::ResultFromServer(value.into())
3900 }
3901}
3902impl From<CompleteResult> for MessageFromServer {
3903 fn from(value: CompleteResult) -> Self {
3904 MessageFromServer::ResultFromServer(value.into())
3905 }
3906}
3907impl From<CreateTaskResult> for MessageFromServer {
3908 fn from(value: CreateTaskResult) -> Self {
3909 MessageFromServer::ResultFromServer(value.into())
3910 }
3911}
3912impl TryFrom<ResultFromClient> for GenericResult {
3913 type Error = RpcError;
3914 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3915 match value {
3916 ResultFromClient::GetTaskPayloadResult(result) => Ok(result.into()),
3917 ResultFromClient::Result(result) => Ok(result),
3918 _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
3919 }
3920 }
3921}
3922impl TryFrom<ResultFromClient> for GetTaskResult {
3923 type Error = RpcError;
3924 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3925 if let ResultFromClient::GetTaskResult(result) = value {
3926 Ok(result)
3927 } else {
3928 Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
3929 }
3930 }
3931}
3932impl TryFrom<ResultFromClient> for GetTaskPayloadResult {
3933 type Error = RpcError;
3934 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3935 if let ResultFromClient::GetTaskPayloadResult(result) = value {
3936 Ok(result)
3937 } else {
3938 Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
3939 }
3940 }
3941}
3942impl TryFrom<ResultFromClient> for CancelTaskResult {
3943 type Error = RpcError;
3944 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3945 if let ResultFromClient::CancelTaskResult(result) = value {
3946 Ok(result)
3947 } else {
3948 Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
3949 }
3950 }
3951}
3952impl TryFrom<ResultFromClient> for ListTasksResult {
3953 type Error = RpcError;
3954 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3955 if let ResultFromClient::ListTasksResult(result) = value {
3956 Ok(result)
3957 } else {
3958 Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
3959 }
3960 }
3961}
3962impl TryFrom<ResultFromClient> for CreateMessageResult {
3963 type Error = RpcError;
3964 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3965 if let ResultFromClient::CreateMessageResult(result) = value {
3966 Ok(result)
3967 } else {
3968 Err(RpcError::internal_error().with_message("Not a CreateMessageResult".to_string()))
3969 }
3970 }
3971}
3972impl TryFrom<ResultFromClient> for ListRootsResult {
3973 type Error = RpcError;
3974 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3975 if let ResultFromClient::ListRootsResult(result) = value {
3976 Ok(result)
3977 } else {
3978 Err(RpcError::internal_error().with_message("Not a ListRootsResult".to_string()))
3979 }
3980 }
3981}
3982impl TryFrom<ResultFromClient> for ElicitResult {
3983 type Error = RpcError;
3984 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3985 if let ResultFromClient::ElicitResult(result) = value {
3986 Ok(result)
3987 } else {
3988 Err(RpcError::internal_error().with_message("Not a ElicitResult".to_string()))
3989 }
3990 }
3991}
3992impl TryFrom<ResultFromClient> for CreateTaskResult {
3993 type Error = RpcError;
3994 fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3995 if let ResultFromClient::CreateTaskResult(result) = value {
3996 Ok(result)
3997 } else {
3998 Err(RpcError::internal_error().with_message("Not a CreateTaskResult".to_string()))
3999 }
4000 }
4001}
4002impl TryFrom<ResultFromServer> for GenericResult {
4003 type Error = RpcError;
4004 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4005 match value {
4006 ResultFromServer::GetTaskPayloadResult(result) => Ok(result.into()),
4007 ResultFromServer::Result(result) => Ok(result),
4008 _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
4009 }
4010 }
4011}
4012impl TryFrom<ResultFromServer> for InitializeResult {
4013 type Error = RpcError;
4014 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4015 if let ResultFromServer::InitializeResult(result) = value {
4016 Ok(result)
4017 } else {
4018 Err(RpcError::internal_error().with_message("Not a InitializeResult".to_string()))
4019 }
4020 }
4021}
4022impl TryFrom<ResultFromServer> for ListResourcesResult {
4023 type Error = RpcError;
4024 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4025 if let ResultFromServer::ListResourcesResult(result) = value {
4026 Ok(result)
4027 } else {
4028 Err(RpcError::internal_error().with_message("Not a ListResourcesResult".to_string()))
4029 }
4030 }
4031}
4032impl TryFrom<ResultFromServer> for ListResourceTemplatesResult {
4033 type Error = RpcError;
4034 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4035 if let ResultFromServer::ListResourceTemplatesResult(result) = value {
4036 Ok(result)
4037 } else {
4038 Err(RpcError::internal_error().with_message("Not a ListResourceTemplatesResult".to_string()))
4039 }
4040 }
4041}
4042impl TryFrom<ResultFromServer> for ReadResourceResult {
4043 type Error = RpcError;
4044 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4045 if let ResultFromServer::ReadResourceResult(result) = value {
4046 Ok(result)
4047 } else {
4048 Err(RpcError::internal_error().with_message("Not a ReadResourceResult".to_string()))
4049 }
4050 }
4051}
4052impl TryFrom<ResultFromServer> for ListPromptsResult {
4053 type Error = RpcError;
4054 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4055 if let ResultFromServer::ListPromptsResult(result) = value {
4056 Ok(result)
4057 } else {
4058 Err(RpcError::internal_error().with_message("Not a ListPromptsResult".to_string()))
4059 }
4060 }
4061}
4062impl TryFrom<ResultFromServer> for GetPromptResult {
4063 type Error = RpcError;
4064 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4065 if let ResultFromServer::GetPromptResult(result) = value {
4066 Ok(result)
4067 } else {
4068 Err(RpcError::internal_error().with_message("Not a GetPromptResult".to_string()))
4069 }
4070 }
4071}
4072impl TryFrom<ResultFromServer> for ListToolsResult {
4073 type Error = RpcError;
4074 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4075 if let ResultFromServer::ListToolsResult(result) = value {
4076 Ok(result)
4077 } else {
4078 Err(RpcError::internal_error().with_message("Not a ListToolsResult".to_string()))
4079 }
4080 }
4081}
4082impl TryFrom<ResultFromServer> for CallToolResult {
4083 type Error = RpcError;
4084 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4085 if let ResultFromServer::CallToolResult(result) = value {
4086 Ok(result)
4087 } else {
4088 Err(RpcError::internal_error().with_message("Not a CallToolResult".to_string()))
4089 }
4090 }
4091}
4092impl TryFrom<ResultFromServer> for GetTaskResult {
4093 type Error = RpcError;
4094 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4095 if let ResultFromServer::GetTaskResult(result) = value {
4096 Ok(result)
4097 } else {
4098 Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
4099 }
4100 }
4101}
4102impl TryFrom<ResultFromServer> for GetTaskPayloadResult {
4103 type Error = RpcError;
4104 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4105 if let ResultFromServer::GetTaskPayloadResult(result) = value {
4106 Ok(result)
4107 } else {
4108 Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
4109 }
4110 }
4111}
4112impl TryFrom<ResultFromServer> for CancelTaskResult {
4113 type Error = RpcError;
4114 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4115 if let ResultFromServer::CancelTaskResult(result) = value {
4116 Ok(result)
4117 } else {
4118 Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
4119 }
4120 }
4121}
4122impl TryFrom<ResultFromServer> for ListTasksResult {
4123 type Error = RpcError;
4124 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4125 if let ResultFromServer::ListTasksResult(result) = value {
4126 Ok(result)
4127 } else {
4128 Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
4129 }
4130 }
4131}
4132impl TryFrom<ResultFromServer> for CompleteResult {
4133 type Error = RpcError;
4134 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4135 if let ResultFromServer::CompleteResult(result) = value {
4136 Ok(result)
4137 } else {
4138 Err(RpcError::internal_error().with_message("Not a CompleteResult".to_string()))
4139 }
4140 }
4141}
4142impl TryFrom<ResultFromServer> for CreateTaskResult {
4143 type Error = RpcError;
4144 fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4145 if let ResultFromServer::CreateTaskResult(result) = value {
4146 Ok(result)
4147 } else {
4148 Err(RpcError::internal_error().with_message("Not a CreateTaskResult".to_string()))
4149 }
4150 }
4151}
4152impl ContentBlock {
4153 pub fn text_content(text: ::std::string::String) -> Self {
4155 TextContent::new(text, None, None).into()
4156 }
4157 pub fn image_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
4159 ImageContent::new(data, mime_type, None, None).into()
4160 }
4161 pub fn audio_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
4163 AudioContent::new(data, mime_type, None, None).into()
4164 }
4165 pub fn resource_link(value: ResourceLink) -> Self {
4167 value.into()
4168 }
4169 pub fn embedded_resource(resource: EmbeddedResourceResource) -> Self {
4171 EmbeddedResource::new(resource, None, None).into()
4172 }
4173 pub fn content_type(&self) -> &str {
4175 match self {
4176 ContentBlock::TextContent(text_content) => text_content.type_(),
4177 ContentBlock::ImageContent(image_content) => image_content.type_(),
4178 ContentBlock::AudioContent(audio_content) => audio_content.type_(),
4179 ContentBlock::ResourceLink(resource_link) => resource_link.type_(),
4180 ContentBlock::EmbeddedResource(embedded_resource) => embedded_resource.type_(),
4181 }
4182 }
4183 pub fn as_text_content(&self) -> std::result::Result<&TextContent, RpcError> {
4185 match &self {
4186 ContentBlock::TextContent(text_content) => Ok(text_content),
4187 _ => Err(RpcError::internal_error().with_message(format!(
4188 "Invalid conversion, \"{}\" is not a {}",
4189 self.content_type(),
4190 "TextContent"
4191 ))),
4192 }
4193 }
4194 pub fn as_image_content(&self) -> std::result::Result<&ImageContent, RpcError> {
4196 match &self {
4197 ContentBlock::ImageContent(image_content) => Ok(image_content),
4198 _ => Err(RpcError::internal_error().with_message(format!(
4199 "Invalid conversion, \"{}\" is not a {}",
4200 self.content_type(),
4201 "ImageContent"
4202 ))),
4203 }
4204 }
4205 pub fn as_audio_content(&self) -> std::result::Result<&AudioContent, RpcError> {
4207 match &self {
4208 ContentBlock::AudioContent(audio_content) => Ok(audio_content),
4209 _ => Err(RpcError::internal_error().with_message(format!(
4210 "Invalid conversion, \"{}\" is not a {}",
4211 self.content_type(),
4212 "AudioContent"
4213 ))),
4214 }
4215 }
4216 pub fn as_resource_link(&self) -> std::result::Result<&ResourceLink, RpcError> {
4218 match &self {
4219 ContentBlock::ResourceLink(resource_link) => Ok(resource_link),
4220 _ => Err(RpcError::internal_error().with_message(format!(
4221 "Invalid conversion, \"{}\" is not a {}",
4222 self.content_type(),
4223 "ResourceLink"
4224 ))),
4225 }
4226 }
4227 pub fn as_embedded_resource(&self) -> std::result::Result<&EmbeddedResource, RpcError> {
4229 match &self {
4230 ContentBlock::EmbeddedResource(embedded_resource) => Ok(embedded_resource),
4231 _ => Err(RpcError::internal_error().with_message(format!(
4232 "Invalid conversion, \"{}\" is not a {}",
4233 self.content_type(),
4234 "EmbeddedResource"
4235 ))),
4236 }
4237 }
4238}
4239impl CallToolResult {
4240 pub fn text_content(content: Vec<TextContent>) -> Self {
4241 Self {
4242 content: content.into_iter().map(Into::into).collect(),
4243 is_error: None,
4244 meta: None,
4245 structured_content: None,
4246 }
4247 }
4248 pub fn image_content(content: Vec<ImageContent>) -> Self {
4249 Self {
4250 content: content.into_iter().map(Into::into).collect(),
4251 is_error: None,
4252 meta: None,
4253 structured_content: None,
4254 }
4255 }
4256 pub fn audio_content(content: Vec<AudioContent>) -> Self {
4257 Self {
4258 content: content.into_iter().map(Into::into).collect(),
4259 is_error: None,
4260 meta: None,
4261 structured_content: None,
4262 }
4263 }
4264 pub fn resource_link(content: Vec<ResourceLink>) -> Self {
4265 Self {
4266 content: content.into_iter().map(Into::into).collect(),
4267 is_error: None,
4268 meta: None,
4269 structured_content: None,
4270 }
4271 }
4272 pub fn embedded_resource(content: Vec<EmbeddedResource>) -> Self {
4273 Self {
4274 content: content.into_iter().map(Into::into).collect(),
4275 is_error: None,
4276 meta: None,
4277 structured_content: None,
4278 }
4279 }
4280 pub fn with_error(error: CallToolError) -> Self {
4282 Self {
4283 content: vec![ContentBlock::TextContent(TextContent::new(error.to_string(), None, None))],
4284 is_error: Some(true),
4285 meta: None,
4286 structured_content: None,
4287 }
4288 }
4289 pub fn with_meta(mut self, meta: Option<serde_json::Map<String, Value>>) -> Self {
4291 self.meta = meta;
4292 self
4293 }
4294 pub fn with_structured_content(
4296 mut self,
4297 structured_content: ::serde_json::Map<::std::string::String, ::serde_json::Value>,
4298 ) -> Self {
4299 self.structured_content = Some(structured_content);
4300 self
4301 }
4302 pub fn from_content(content: Vec<ContentBlock>) -> Self {
4316 Self {
4317 content,
4318 is_error: None,
4319 meta: None,
4320 structured_content: None,
4321 }
4322 }
4323 pub fn add_content(mut self, content: ContentBlock) -> Self {
4328 self.content.push(content);
4329 self
4330 }
4331}
4332impl ServerRequest {
4333 pub fn request_id(&self) -> &RequestId {
4334 match self {
4335 ServerRequest::PingRequest(request) => &request.id,
4336 ServerRequest::GetTaskRequest(request) => &request.id,
4337 ServerRequest::GetTaskPayloadRequest(request) => &request.id,
4338 ServerRequest::CancelTaskRequest(request) => &request.id,
4339 ServerRequest::ListTasksRequest(request) => &request.id,
4340 ServerRequest::CreateMessageRequest(request) => &request.id,
4341 ServerRequest::ListRootsRequest(request) => &request.id,
4342 ServerRequest::ElicitRequest(request) => &request.id,
4343 }
4344 }
4345}
4346impl ClientRequest {
4347 pub fn request_id(&self) -> &RequestId {
4348 match self {
4349 ClientRequest::InitializeRequest(request) => &request.id,
4350 ClientRequest::PingRequest(request) => &request.id,
4351 ClientRequest::ListResourcesRequest(request) => &request.id,
4352 ClientRequest::ListResourceTemplatesRequest(request) => &request.id,
4353 ClientRequest::ReadResourceRequest(request) => &request.id,
4354 ClientRequest::SubscribeRequest(request) => &request.id,
4355 ClientRequest::UnsubscribeRequest(request) => &request.id,
4356 ClientRequest::ListPromptsRequest(request) => &request.id,
4357 ClientRequest::GetPromptRequest(request) => &request.id,
4358 ClientRequest::ListToolsRequest(request) => &request.id,
4359 ClientRequest::CallToolRequest(request) => &request.id,
4360 ClientRequest::GetTaskRequest(request) => &request.id,
4361 ClientRequest::GetTaskPayloadRequest(request) => &request.id,
4362 ClientRequest::CancelTaskRequest(request) => &request.id,
4363 ClientRequest::ListTasksRequest(request) => &request.id,
4364 ClientRequest::SetLevelRequest(request) => &request.id,
4365 ClientRequest::CompleteRequest(request) => &request.id,
4366 }
4367 }
4368}
4369impl From<&str> for IconTheme {
4370 fn from(s: &str) -> Self {
4371 match s {
4372 "dark" => Self::Dark,
4373 "light" => Self::Light,
4374 _ => Self::Light,
4375 }
4376 }
4377}
4378impl From<&str> for ElicitResultContent {
4379 fn from(value: &str) -> Self {
4380 Self::Primitive(ElicitResultContentPrimitive::String(value.to_string()))
4381 }
4382}
4383impl From<&str> for ElicitResultContentPrimitive {
4384 fn from(value: &str) -> Self {
4385 ElicitResultContentPrimitive::String(value.to_string())
4386 }
4387}
4388impl From<String> for ElicitResultContentPrimitive {
4389 fn from(value: String) -> Self {
4390 ElicitResultContentPrimitive::String(value)
4391 }
4392}
4393impl From<String> for ElicitResultContent {
4394 fn from(value: String) -> Self {
4395 Self::Primitive(ElicitResultContentPrimitive::String(value))
4396 }
4397}
4398impl From<Vec<&str>> for ElicitResultContent {
4399 fn from(value: Vec<&str>) -> Self {
4400 Self::StringArray(value.iter().map(|v| v.to_string()).collect())
4401 }
4402}
4403impl From<i64> for ElicitResultContent {
4404 fn from(value: i64) -> Self {
4405 Self::Primitive(value.into())
4406 }
4407}
4408impl CallToolRequestParams {
4409 pub fn new<T>(tool_name: T) -> Self
4410 where
4411 T: ToString,
4412 {
4413 Self {
4414 name: tool_name.to_string(),
4415 arguments: None,
4416 meta: None,
4417 task: None,
4418 }
4419 }
4420 pub fn with_arguments(mut self, arguments: serde_json::Map<String, Value>) -> Self {
4422 self.arguments = Some(arguments);
4423 self
4424 }
4425 pub fn with_meta(mut self, meta: CallToolMeta) -> Self {
4427 self.meta = Some(meta);
4428 self
4429 }
4430 pub fn with_task(mut self, task: TaskMetadata) -> Self {
4432 self.task = Some(task);
4433 self
4434 }
4435}
4436#[cfg(test)]
4438mod tests {
4439 use super::*;
4440 use serde_json::json;
4441
4442 #[test]
4443 fn test_detect_message_type() {
4444 let message = ClientJsonrpcRequest::new(RequestId::Integer(0), RequestFromClient::PingRequest(None));
4446 let result = detect_message_type(&json!(message));
4447 assert!(matches!(result, MessageTypes::Request));
4448
4449 let result = detect_message_type(&json!({
4452 "id":0,
4453 "method":"add_numbers",
4454 "params":{},
4455 "jsonrpc":"2.0"
4456 }));
4457 assert!(matches!(result, MessageTypes::Request));
4458
4459 let message = ClientJsonrpcNotification::new(NotificationFromClient::RootsListChangedNotification(None));
4461 let result = detect_message_type(&json!(message));
4462 assert!(matches!(result, MessageTypes::Notification));
4463
4464 let result = detect_message_type(&json!({
4466 "method":"notifications/email_sent",
4467 "jsonrpc":"2.0"
4468 }));
4469 assert!(matches!(result, MessageTypes::Notification));
4470
4471 let message = ClientJsonrpcResponse::new(
4473 RequestId::Integer(0),
4474 ListRootsResult {
4475 meta: None,
4476 roots: vec![],
4477 }
4478 .into(),
4479 );
4480 let result = detect_message_type(&json!(message));
4481 assert!(matches!(result, MessageTypes::Response));
4482
4483 let result = detect_message_type(&json!({
4486 "id":1,
4487 "jsonrpc":"2.0",
4488 "result":"{}",
4489 }));
4490 assert!(matches!(result, MessageTypes::Response));
4491
4492 let message = JsonrpcErrorResponse::create(
4494 Some(RequestId::Integer(0)),
4495 RpcErrorCodes::INVALID_PARAMS,
4496 "Invalid params!".to_string(),
4497 None,
4498 );
4499 let result = detect_message_type(&json!(message));
4500 assert!(matches!(result, MessageTypes::Error));
4501
4502 let result = detect_message_type(&json!({}));
4504 assert!(matches!(result, MessageTypes::Request));
4505 }
4506}