Skip to main content

rust_mcp_schema/generated_schema/2025_11_25/
schema_utils.rs

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}
17/// Implements the `Display` trait for the `MessageTypes` enum,
18/// allowing it to be converted into a human-readable string.
19impl Display for MessageTypes {
20    /// Formats the `MessageTypes` enum variant as a string.
21    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
22        write!(
23            f,
24            "{}",
25            // Match the current enum variant and return a corresponding string
26            match self {
27                MessageTypes::Request => "Request",
28                MessageTypes::Response => "Response",
29                MessageTypes::Notification => "Notification",
30                MessageTypes::Error => "Error",
31            }
32        )
33    }
34}
35
36/// A utility function used internally to detect the message type from the payload.
37/// This function is used when deserializing a `ClientMessage` into strongly-typed structs that represent the specific message received.
38#[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
62/// Represents a generic MCP (Model Context Protocol) message.
63/// This trait defines methods to classify and extract information from messages.
64pub 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
78/// A trait for converting a message of type `T` into `Self`.
79/// This is useful for transforming mcp messages into a Type that could be serialized into a JsonrpcMessage.
80///
81/// For example, a ServerMessage can be constructed from a rust_mcp_schema::PingRequest by attaching a RequestId.
82/// Eventually, the ServerMessage can be serialized into a valid JsonrpcMessage for transmission over the transport.
83pub 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
98//*******************************//
99//** RequestId Implementations **//
100//*******************************//
101
102// Implement PartialEq and Eq for RequestId
103impl 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, // Different variants are never equal
109        }
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
121// Implement Hash for RequestId, so we can store it in HashMaps, HashSets, etc.
122impl Hash for RequestId {
123    fn hash<H: Hasher>(&self, state: &mut H) {
124        match self {
125            RequestId::String(s) => {
126                0u8.hash(state); // Prefix with 0 for String variant
127                s.hash(state);
128            }
129            RequestId::Integer(i) => {
130                1u8.hash(state); // Prefix with 1 for Integer variant
131                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//*******************//
146//** ClientMessage **//
147//*******************//
148
149/// "Similar to JsonrpcMessage, but with the variants restricted to client-side messages."
150/// ClientMessage represents a message sent by an MCP Client and received by an MCP Server.
151#[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    /// Converts the current message into a `ClientJsonrpcResponse` if it's of the correct type.
162    ///
163    /// This function checks if the current message is of type `Response`. If so, it returns the
164    /// `ClientJsonrpcResponse` wrapped in a `Result::Ok`. If the message is not a `Response`,
165    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
166    ///
167    /// # Returns
168    /// - `Ok(ClientJsonrpcResponse)` if the message is a valid `Response`.
169    /// - `Err(RpcError)` if the message type is invalid
170    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    /// Converts the current message into a `ClientJsonrpcRequest` if it's of the correct type.
183    ///
184    /// This function checks if the current message is of type `Request`. If so, it returns the
185    /// `ClientJsonrpcRequest` wrapped in a `Result::Ok`. If the message is not a `Request`,
186    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
187    ///
188    /// # Returns
189    /// - `Ok(ClientJsonrpcRequest)` if the message is a valid `Request`.
190    /// - `Err(RpcError)` if the message type is invalid
191    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    /// Converts the current message into a `ClientJsonrpcNotification` if it's of the correct type.
204    ///
205    /// This function checks if the current message is of type `Notification`. If so, it returns the
206    /// `ClientJsonrpcNotification` wrapped in a `Result::Ok`. If the message is not a `Notification`,
207    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
208    ///
209    /// # Returns
210    /// - `Ok(ClientJsonrpcNotification)` if the message is a valid `Notification`.
211    /// - `Err(RpcError)` if the message type is invalid
212    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    /// Converts the current message into a `JsonrpcErrorResponse` if it's of the correct type.
225    ///
226    /// This function checks if the current message is of type `Error`. If so, it returns the
227    /// `JsonrpcErrorResponse` wrapped in a `Result::Ok`. If the message is not a `Error`,
228    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
229    ///
230    /// # Returns
231    /// - `Ok(JsonrpcErrorResponse)` if the message is a valid `Error`.
232    /// - `Err(RpcError)` if the message type is invalid
233    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    /// Returns `true` if message is an `InitializeRequest`.
246    pub fn is_initialize_request(&self) -> bool {
247        matches!(self, Self::Request(ClientJsonrpcRequest::InitializeRequest(_)))
248    }
249
250    /// Returns `true` if the message is an `InitializedNotification`
251    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    // Retrieves the request ID associated with the message, if applicable
279    fn request_id(&self) -> Option<&RequestId> {
280        match self {
281            // If the message is a request, return the associated request ID
282            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            // Notifications do not have request IDs
303            ClientMessage::Notification(_) => None,
304            // If the message is a response, return the associated request ID
305            ClientMessage::Response(client_jsonrpc_response) => Some(&client_jsonrpc_response.id),
306            // If the message is an error, return the associated request ID
307            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
330// Implementing the `McpMessage` trait for `ClientMessage`
331impl McpMessage for ClientMessage {
332    // Returns true if the message is a response type
333    fn is_response(&self) -> bool {
334        matches!(self, ClientMessage::Response(_))
335    }
336
337    // Returns true if the message is a request type
338    fn is_request(&self) -> bool {
339        matches!(self, ClientMessage::Request(_))
340    }
341
342    // Returns true if the message is a notification type (i.e., does not expect a response)
343    fn is_notification(&self) -> bool {
344        matches!(self, ClientMessage::Notification(_))
345    }
346
347    // Returns true if the message represents an error
348    fn is_error(&self) -> bool {
349        matches!(self, ClientMessage::Error(_))
350    }
351
352    /// Determines the type of the message and returns the corresponding `MessageTypes` variant.
353    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//**************************//
364//** ClientJsonrpcRequest **//
365//**************************//
366
367/// "Similar to JsonrpcRequest , but with the variants restricted to client-side requests."
368#[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
532/// Formats the ClientJsonrpcRequest as a JSON string.
533impl 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    /// Parses a JSON-RPC request from a string.
547    ///
548    /// This implementation allows `ClientJsonrpcRequest` to be created
549    /// from a JSON string using the `from_str` method.
550    ///
551    /// # Arguments
552    /// * `s` - A JSON string representing a JSON-RPC request.
553    ///
554    /// # Returns
555    /// * `Ok(ClientJsonrpcRequest)` if parsing is successful.
556    /// * `Err(RpcError)` if the string is not valid JSON.
557    ///
558    /// # Example
559    /// ```
560    /// use std::str::FromStr;
561    /// use rust_mcp_schema::schema_utils::ClientJsonrpcRequest;
562    ///
563    /// let json = r#"{"jsonrpc": "2.0", "method": "initialize", "id": 1}"#;
564    /// let request = ClientJsonrpcRequest::from_str(json);
565    /// assert!(request.is_ok());
566    /// ```
567    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//*************************//
574//** Request From Client **//
575//*************************//
576
577/// To determine standard and custom request from the client side
578/// Custom requests are of type serde_json::Value and can be deserialized into any custom type.
579#[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    /// Returns `true` if the request is an `InitializeRequest`.
627    pub fn is_initialize_request(&self) -> bool {
628        matches!(self, RequestFromClient::InitializeRequest(_))
629    }
630}
631
632// impl From<ClientRequest> for RequestFromClient {
633//     fn from(value: ClientRequest) -> Self {
634//         Self::ClientRequest(value)
635//     }
636// }
637
638// impl From<serde_json::Value> for RequestFromClient {
639//     fn from(value: serde_json::Value) -> Self {
640//         Self::CustomRequest(value)
641//     }
642// }
643
644// impl<'de> serde::Deserialize<'de> for RequestFromClient {
645//     fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
646//     where
647//         D: serde::Deserializer<'de>,
648//     {
649//         let raw_value = Value::deserialize(deserializer)?;
650
651//         let client_result = ClientRequest::deserialize(&raw_value);
652
653//         match client_result {
654//             Ok(client_request) => Ok(Self::ClientRequest(client_request)),
655//             Err(_) => Ok(Self::CustomRequest(raw_value)),
656//         }
657//     }
658// }
659
660//*******************************//
661//** ClientJsonrpcNotification **//
662//*******************************//
663
664/// "Similar to JsonrpcNotification , but with the variants restricted to client-side notifications."
665#[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    /// Returns `true` if the message is an `InitializedNotification`
711    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
751/// Formats the ClientJsonrpcNotification as a JSON string.
752impl 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//*******************************//
772//**  NotificationFromClient   **//
773//*******************************//
774
775/// To determine standard and custom notifications received from the MCP Client
776/// Custom notifications are of type serde_json::Value and can be deserialized into any custom type.
777#[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
788// impl TryFrom<NotificationFromClient> for ClientNotification {
789//     type Error = RpcError;
790//     fn try_from(value: NotificationFromClient) -> result::Result<Self, Self::Error> {
791//         if let NotificationFromClient::ClientNotification(client_notification) = value {
792//             Ok(client_notification)
793//         } else {
794//             Err(RpcError::internal_error().with_message("Not a ClientNotification".to_string()))
795//         }
796//     }
797// }
798
799impl NotificationFromClient {
800    /// Returns `true` if the message is an `InitializedNotification`
801    pub fn is_initialized_notification(&self) -> bool {
802        matches!(self, NotificationFromClient::InitializedNotification(_))
803    }
804
805    //TODO: 'static
806    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//*******************************//
821//**   ClientJsonrpcResponse   **//
822//*******************************//
823
824/// "Similar to JsonrpcResponse , but with the variants restricted to client-side responses."
825#[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
845/// Formats the ClientJsonrpcResponse as a JSON string.
846impl 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//*******************************//
865//**      ResultFromClient     **//
866//*******************************//
867
868#[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}
912//*******************************//
913//**       ClientMessage       **//
914//*******************************//
915
916impl 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//*******************//
936//** ServerMessage **//
937//*******************//
938
939/// "Similar to JsonrpcMessage, but with the variants restricted to client-side messages."
940/// ServerMessage represents a message sent by an MCP Server and received by an MCP Client.
941#[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    /// Converts the current message into a `ServerJsonrpcResponse` if it's of the correct type.
952    ///
953    /// This function checks if the current message is of type `Response`. If so, it returns the
954    /// `ServerJsonrpcResponse` wrapped in a `Result::Ok`. If the message is not a `Response`,
955    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
956    ///
957    /// # Returns
958    /// - `Ok(ServerJsonrpcResponse)` if the message is a valid `Response`.
959    /// - `Err(RpcError)` if the message type is invalid
960    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    /// Converts the current message into a `ServerJsonrpcRequest` if it's of the correct type.
973    ///
974    /// This function checks if the current message is of type `Request`. If so, it returns the
975    /// `ServerJsonrpcRequest` wrapped in a `Result::Ok`. If the message is not a `Request`,
976    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
977    ///
978    /// # Returns
979    /// - `Ok(ServerJsonrpcRequest)` if the message is a valid `Request`.
980    /// - `Err(RpcError)` if the message type is invalid
981    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    /// Converts the current message into a `ServerJsonrpcNotification` if it's of the correct type.
994    ///
995    /// This function checks if the current message is of type `Notification`. If so, it returns the
996    /// `ServerJsonrpcNotification` wrapped in a `Result::Ok`. If the message is not a `Notification`,
997    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
998    ///
999    /// # Returns
1000    /// - `Ok(ServerJsonrpcNotification)` if the message is a valid `Notification`.
1001    /// - `Err(RpcError)` if the message type is invalid
1002    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    /// Converts the current message into a `JsonrpcErrorResponse` if it's of the correct type.
1015    ///
1016    /// This function checks if the current message is of type `Error`. If so, it returns the
1017    /// `JsonrpcErrorResponse` wrapped in a `Result::Ok`. If the message is not a `Error`,
1018    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
1019    ///
1020    /// # Returns
1021    /// - `Ok(JsonrpcErrorResponse)` if the message is a valid `Error`.
1022    /// - `Err(RpcError)` if the message type is invalid
1023    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    // Retrieves the request ID associated with the message, if applicable
1056    fn request_id(&self) -> Option<&RequestId> {
1057        match self {
1058            // If the message is a request, return the associated request ID
1059            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            // Notifications do not have request IDs
1071            ServerMessage::Notification(_) => None,
1072            // If the message is a response, return the associated request ID
1073            ServerMessage::Response(server_jsonrpc_response) => Some(&server_jsonrpc_response.id),
1074            // If the message is an error, return the associated request ID
1075            ServerMessage::Error(jsonrpc_error) => jsonrpc_error.id.as_ref(),
1076        }
1077    }
1078
1079    fn jsonrpc(&self) -> &str {
1080        match self {
1081            // If the message is a request, return the associated request ID
1082            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            // Notifications do not have request IDs
1095            ServerMessage::Notification(notification) => notification.jsonrpc(),
1096            // If the message is a response, return the associated request ID
1097            ServerMessage::Response(server_jsonrpc_response) => server_jsonrpc_response.jsonrpc(),
1098            // If the message is an error, return the associated request ID
1099            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
1113// Implementing the `McpMessage` trait for `ServerMessage`
1114impl McpMessage for ServerMessage {
1115    // Returns true if the message is a response type
1116    fn is_response(&self) -> bool {
1117        matches!(self, ServerMessage::Response(_))
1118    }
1119
1120    // Returns true if the message is a request type
1121    fn is_request(&self) -> bool {
1122        matches!(self, ServerMessage::Request(_))
1123    }
1124
1125    // Returns true if the message is a notification type (i.e., does not expect a response)
1126    fn is_notification(&self) -> bool {
1127        matches!(self, ServerMessage::Notification(_))
1128    }
1129
1130    // Returns true if the message represents an error
1131    fn is_error(&self) -> bool {
1132        matches!(self, ServerMessage::Error(_))
1133    }
1134
1135    /// Determines the type of the message and returns the corresponding `MessageTypes` variant.
1136    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//**************************//
1166//** ServerJsonrpcRequest **//
1167//**************************//
1168
1169/// "Similar to JsonrpcRequest , but with the variants restricted to client-side requests."
1170#[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
1259/// Formats the ServerJsonrpcRequest as a JSON string.
1260impl 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//*************************//
1287//** Request From Server **//
1288//*************************//
1289
1290/// To determine standard and custom request from the server side
1291/// Custom requests are of type serde_json::Value and can be deserialized into any custom type.
1292#[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//*******************************//
1342//** ServerJsonrpcNotification **//
1343//*******************************//
1344
1345/// "Similar to JsonrpcNotification , but with the variants restricted to server-side notifications."
1346#[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
1397//TODO: check do we need from_message() or this
1398impl 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) => &notification.method,
1460        }
1461    }
1462}
1463
1464/// Formats the ServerJsonrpcNotification as a JSON string.
1465impl 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//*******************************//
1484//**  NotificationFromServer   **//
1485//*******************************//
1486
1487/// To determine standard and custom notifications received from the MCP Server
1488/// Custom notifications are of type serde_json::Value and can be deserialized into any custom type.
1489#[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) => ProgressNotification::method_value(),
1509            NotificationFromServer::ResourceListChangedNotification(_params) => {
1510                ResourceListChangedNotification::method_value()
1511            }
1512            NotificationFromServer::ResourceUpdatedNotification(_params) => ResourceUpdatedNotification::method_value(),
1513            NotificationFromServer::PromptListChangedNotification(_params) => PromptListChangedNotification::method_value(),
1514            NotificationFromServer::ToolListChangedNotification(_params) => ToolListChangedNotification::method_value(),
1515            NotificationFromServer::TaskStatusNotification(_params) => TaskStatusNotification::method_value(),
1516            NotificationFromServer::LoggingMessageNotification(_params) => LoggingMessageNotification::method_value(),
1517            NotificationFromServer::ElicitationCompleteNotification(_params) => {
1518                ElicitationCompleteNotification::method_value()
1519            }
1520            NotificationFromServer::CustomNotification(params) => params.method.as_str(),
1521        }
1522    }
1523}
1524
1525//*******************************//
1526//**   ServerJsonrpcResponse   **//
1527//*******************************//
1528
1529/// "Similar to JsonrpcResponse , but with the variants restricted to server-side responses."
1530#[derive(Clone, Debug)]
1531pub struct ServerJsonrpcResponse {
1532    pub id: RequestId,
1533    jsonrpc: ::std::string::String,
1534    pub result: ResultFromServer,
1535}
1536
1537impl ServerJsonrpcResponse {
1538    pub fn new(id: RequestId, result: ResultFromServer) -> Self {
1539        Self {
1540            id,
1541            jsonrpc: JSONRPC_VERSION.to_string(),
1542            result,
1543        }
1544    }
1545    pub fn jsonrpc(&self) -> &::std::string::String {
1546        &self.jsonrpc
1547    }
1548}
1549
1550/// Formats the ServerJsonrpcResponse as a JSON string.
1551impl Display for ServerJsonrpcResponse {
1552    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1553        write!(
1554            f,
1555            "{}",
1556            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1557        )
1558    }
1559}
1560
1561impl FromStr for ServerJsonrpcResponse {
1562    type Err = RpcError;
1563
1564    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1565        serde_json::from_str(s)
1566            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1567    }
1568}
1569//*******************************//
1570//**      ResultFromServer     **//
1571//*******************************//
1572#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
1573#[serde(untagged)]
1574pub enum ResultFromServer {
1575    InitializeResult(InitializeResult),
1576    ListResourcesResult(ListResourcesResult),
1577    ListResourceTemplatesResult(ListResourceTemplatesResult),
1578    ReadResourceResult(ReadResourceResult),
1579    ListPromptsResult(ListPromptsResult),
1580    GetPromptResult(GetPromptResult),
1581    ListToolsResult(ListToolsResult),
1582    CallToolResult(CallToolResult),
1583    GetTaskResult(GetTaskResult),
1584    CancelTaskResult(CancelTaskResult),
1585    ListTasksResult(ListTasksResult),
1586    CompleteResult(CompleteResult),
1587    CreateTaskResult(CreateTaskResult),
1588    Result(Result),
1589    GetTaskPayloadResult(GetTaskPayloadResult),
1590}
1591
1592//***************************//
1593//** impl for JsonrpcErrorResponse **//
1594//***************************//
1595
1596/// Formats the ServerJsonrpcResponse as a JSON string.
1597impl Display for JsonrpcErrorResponse {
1598    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1599        write!(
1600            f,
1601            "{}",
1602            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1603        )
1604    }
1605}
1606
1607impl FromStr for JsonrpcErrorResponse {
1608    type Err = RpcError;
1609
1610    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1611        serde_json::from_str(s)
1612            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1613    }
1614}
1615
1616//**************************//
1617//**  MessageFromServer   **//
1618//**************************//
1619
1620/// An enum representing various types of messages that can be sent from an MCP Server.
1621/// It provides a typed structure for the message payload while skipping internal details like
1622/// `requestId` and protocol version, which are used solely by the transport layer and
1623/// do not need to be exposed to the user.
1624#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1625#[serde(untagged)]
1626pub enum MessageFromServer {
1627    RequestFromServer(RequestFromServer),
1628    ResultFromServer(ResultFromServer),
1629    NotificationFromServer(NotificationFromServer),
1630    Error(RpcError),
1631}
1632
1633impl From<RequestFromServer> for MessageFromServer {
1634    fn from(value: RequestFromServer) -> Self {
1635        Self::RequestFromServer(value)
1636    }
1637}
1638
1639impl From<ResultFromServer> for MessageFromServer {
1640    fn from(value: ResultFromServer) -> Self {
1641        Self::ResultFromServer(value)
1642    }
1643}
1644
1645impl From<NotificationFromServer> for MessageFromServer {
1646    fn from(value: NotificationFromServer) -> Self {
1647        Self::NotificationFromServer(value)
1648    }
1649}
1650
1651impl From<RpcError> for MessageFromServer {
1652    fn from(value: RpcError) -> Self {
1653        Self::Error(value)
1654    }
1655}
1656
1657impl McpMessage for MessageFromServer {
1658    fn is_response(&self) -> bool {
1659        matches!(self, MessageFromServer::ResultFromServer(_))
1660    }
1661
1662    fn is_request(&self) -> bool {
1663        matches!(self, MessageFromServer::RequestFromServer(_))
1664    }
1665
1666    fn is_notification(&self) -> bool {
1667        matches!(self, MessageFromServer::NotificationFromServer(_))
1668    }
1669
1670    fn is_error(&self) -> bool {
1671        matches!(self, MessageFromServer::Error(_))
1672    }
1673
1674    fn message_type(&self) -> MessageTypes {
1675        match self {
1676            MessageFromServer::RequestFromServer(_) => MessageTypes::Request,
1677            MessageFromServer::ResultFromServer(_) => MessageTypes::Response,
1678            MessageFromServer::NotificationFromServer(_) => MessageTypes::Notification,
1679            MessageFromServer::Error(_) => MessageTypes::Error,
1680        }
1681    }
1682}
1683
1684impl FromMessage<MessageFromServer> for ServerMessage {
1685    fn from_message(message: MessageFromServer, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1686        match message {
1687            MessageFromServer::RequestFromServer(request_from_server) => {
1688                let request_id =
1689                    request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1690
1691                let rpc_message = match request_from_server {
1692                    RequestFromServer::PingRequest(params) => {
1693                        ServerJsonrpcRequest::PingRequest(PingRequest::new(request_id, params))
1694                    }
1695                    RequestFromServer::GetTaskRequest(params) => {
1696                        ServerJsonrpcRequest::GetTaskRequest(GetTaskRequest::new(request_id, params))
1697                    }
1698                    RequestFromServer::GetTaskPayloadRequest(params) => {
1699                        ServerJsonrpcRequest::GetTaskPayloadRequest(GetTaskPayloadRequest::new(request_id, params))
1700                    }
1701                    RequestFromServer::CancelTaskRequest(params) => {
1702                        ServerJsonrpcRequest::CancelTaskRequest(CancelTaskRequest::new(request_id, params))
1703                    }
1704                    RequestFromServer::ListTasksRequest(params) => {
1705                        ServerJsonrpcRequest::ListTasksRequest(ListTasksRequest::new(request_id, params))
1706                    }
1707                    RequestFromServer::CreateMessageRequest(params) => {
1708                        ServerJsonrpcRequest::CreateMessageRequest(CreateMessageRequest::new(request_id, params))
1709                    }
1710                    RequestFromServer::ListRootsRequest(params) => {
1711                        ServerJsonrpcRequest::ListRootsRequest(ListRootsRequest::new(request_id, params))
1712                    }
1713                    RequestFromServer::ElicitRequest(params) => {
1714                        ServerJsonrpcRequest::ElicitRequest(ElicitRequest::new(request_id, params))
1715                    }
1716                    RequestFromServer::CustomRequest(params) => {
1717                        ServerJsonrpcRequest::CustomRequest(JsonrpcRequest::new(request_id, params.method, params.params))
1718                    }
1719                };
1720
1721                Ok(ServerMessage::Request(rpc_message))
1722            }
1723            MessageFromServer::ResultFromServer(result_from_server) => {
1724                let request_id =
1725                    request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1726                Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
1727                    request_id,
1728                    result_from_server,
1729                )))
1730            }
1731            MessageFromServer::NotificationFromServer(notification_from_server) => {
1732                if request_id.is_some() {
1733                    return Err(RpcError::internal_error()
1734                        .with_message("request_id expected to be None for Notifications!".to_string()));
1735                }
1736                Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(
1737                    notification_from_server,
1738                )))
1739            }
1740            MessageFromServer::Error(jsonrpc_error_error) => Ok(ServerMessage::Error(JsonrpcErrorResponse::new(
1741                jsonrpc_error_error,
1742                request_id,
1743            ))),
1744        }
1745    }
1746}
1747
1748//**************************//
1749//**  MessageFromClient   **//
1750//**************************//
1751
1752/// An enum representing various types of messages that can be sent from an MCP Client.
1753/// It provides a typed structure for the message payload while skipping internal details like
1754/// `requestId` and protocol version, which are used solely by the transport layer and
1755/// do not need to be exposed to the user.
1756#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1757#[serde(untagged)]
1758pub enum MessageFromClient {
1759    RequestFromClient(RequestFromClient),
1760    ResultFromClient(ResultFromClient),
1761    NotificationFromClient(NotificationFromClient),
1762    Error(RpcError),
1763}
1764
1765impl MessageFromClient {
1766    /// Returns `true` if the message is an `InitializeRequest`.
1767    pub fn is_initialize_request(&self) -> bool {
1768        matches!(self, Self::RequestFromClient(RequestFromClient::InitializeRequest(_)))
1769    }
1770
1771    /// Returns `true` if the message is an `InitializedNotification`
1772    pub fn is_initialized_notification(&self) -> bool {
1773        matches!(
1774            self,
1775            Self::NotificationFromClient(NotificationFromClient::InitializedNotification(_))
1776        )
1777    }
1778}
1779
1780impl From<RequestFromClient> for MessageFromClient {
1781    fn from(value: RequestFromClient) -> Self {
1782        Self::RequestFromClient(value)
1783    }
1784}
1785
1786impl From<ResultFromClient> for MessageFromClient {
1787    fn from(value: ResultFromClient) -> Self {
1788        Self::ResultFromClient(value)
1789    }
1790}
1791
1792impl From<NotificationFromClient> for MessageFromClient {
1793    fn from(value: NotificationFromClient) -> Self {
1794        Self::NotificationFromClient(value)
1795    }
1796}
1797
1798impl From<RpcError> for MessageFromClient {
1799    fn from(value: RpcError) -> Self {
1800        Self::Error(value)
1801    }
1802}
1803
1804impl McpMessage for MessageFromClient {
1805    fn is_response(&self) -> bool {
1806        matches!(self, MessageFromClient::ResultFromClient(_))
1807    }
1808
1809    fn is_request(&self) -> bool {
1810        matches!(self, MessageFromClient::RequestFromClient(_))
1811    }
1812
1813    fn is_notification(&self) -> bool {
1814        matches!(self, MessageFromClient::NotificationFromClient(_))
1815    }
1816
1817    fn is_error(&self) -> bool {
1818        matches!(self, MessageFromClient::Error(_))
1819    }
1820
1821    fn message_type(&self) -> MessageTypes {
1822        match self {
1823            MessageFromClient::RequestFromClient(_) => MessageTypes::Request,
1824            MessageFromClient::ResultFromClient(_) => MessageTypes::Response,
1825            MessageFromClient::NotificationFromClient(_) => MessageTypes::Notification,
1826            MessageFromClient::Error(_) => MessageTypes::Error,
1827        }
1828    }
1829}
1830
1831impl FromMessage<MessageFromClient> for ClientMessage {
1832    fn from_message(message: MessageFromClient, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1833        match message {
1834            MessageFromClient::RequestFromClient(request_from_client) => {
1835                let request_id =
1836                    request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1837                Ok(ClientMessage::Request(ClientJsonrpcRequest::new(
1838                    request_id,
1839                    request_from_client,
1840                )))
1841            }
1842            MessageFromClient::ResultFromClient(result_from_client) => {
1843                let request_id =
1844                    request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1845                Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
1846                    request_id,
1847                    result_from_client,
1848                )))
1849            }
1850            MessageFromClient::NotificationFromClient(notification_from_client) => {
1851                if request_id.is_some() {
1852                    return Err(RpcError::internal_error()
1853                        .with_message("request_id expected to be None for Notifications!".to_string()));
1854                }
1855
1856                Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(
1857                    notification_from_client,
1858                )))
1859            }
1860            MessageFromClient::Error(jsonrpc_error_error) => Ok(ClientMessage::Error(JsonrpcErrorResponse::new(
1861                jsonrpc_error_error,
1862                request_id,
1863            ))),
1864        }
1865    }
1866}
1867
1868//**************************//
1869//**  UnknownTool Error   **//
1870//**************************//
1871
1872/// A custom error type `UnknownTool` that wraps a `String`.
1873/// This can be used as the error type in the result of a `CallToolRequest` when a non-existent or unimplemented tool is called.
1874#[derive(Debug)]
1875pub struct UnknownTool(pub String);
1876
1877// Implement `Display` for `UnknownTool` to format the error message.
1878impl core::fmt::Display for UnknownTool {
1879    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1880        // The formatted string will display "Unknown tool: <tool_name>"
1881        write!(f, "Unknown tool: {}", self.0)
1882    }
1883}
1884
1885// Implement the `Error` trait for `UnknownTool`, making it a valid error type.
1886impl std::error::Error for UnknownTool {}
1887
1888//***************************//
1889//**  CallToolError Error  **//
1890//***************************//
1891/// A specific error type that can hold any kind of error and is used to
1892/// encapsulate various error scenarios when a `CallToolRequest` fails.
1893#[derive(Debug)]
1894pub struct CallToolError(pub Box<dyn std::error::Error>);
1895
1896// Implement methods for `CallToolError` to handle different error types.
1897impl CallToolError {
1898    /// Constructor to create a new `CallToolError` from a generic error.
1899    pub fn new<E: std::error::Error + 'static>(err: E) -> Self {
1900        // Box the error to fit inside the `CallToolError` struct
1901        CallToolError(Box::new(err))
1902    }
1903
1904    /// Specific constructor to create a `CallToolError` for an `UnknownTool` error.
1905    pub fn unknown_tool(tool_name: impl Into<String>) -> Self {
1906        // Create a `CallToolError` from an `UnknownTool` error (wrapped in a `Box`).
1907        CallToolError(Box::new(UnknownTool(tool_name.into())))
1908    }
1909
1910    /// Creates a `CallToolError` indicating that task-augmented tool calls are not supported.
1911    /// This constructor is used when a task-augmented tool call is requested
1912    /// but the capability is not advertised by the peer.
1913    pub fn unsupported_task_augmented_tool_call() -> Self {
1914        Self::from_message("Task-augmented tool calls are not supported.".to_string())
1915    }
1916
1917    /// Creates a `CallToolError` for invalid arguments with optional details.
1918    ///
1919    pub fn invalid_arguments(tool_name: impl AsRef<str>, message: Option<String>) -> Self {
1920        // Trim tool_name to remove whitespace and check for emptiness
1921        let tool_name = tool_name.as_ref().trim();
1922        if tool_name.is_empty() {
1923            return Self::from_message("Invalid arguments: tool name cannot be empty".to_string());
1924        }
1925
1926        // Use a descriptive default message if none provided
1927        let default_message = "no additional details provided".to_string();
1928        let message = message.unwrap_or(default_message);
1929
1930        // Format the full error message
1931        let full_message = format!("Invalid arguments for tool '{tool_name}': {message}");
1932
1933        Self::from_message(full_message)
1934    }
1935
1936    /// Creates a new `CallToolError` from a string message.
1937    ///
1938    /// This is useful for generating ad-hoc or one-off errors without defining a custom error type.
1939    /// Internally, it wraps the string in a lightweight error type that implements the `Error` trait.
1940    ///
1941    /// # Examples
1942    ///
1943    /// ```
1944    /// let err = rust_mcp_schema::schema_utils::CallToolError::from_message("Something went wrong");
1945    /// println!("{:?}", err);
1946    /// ```
1947    ///
1948    /// # Parameters
1949    ///
1950    /// - `message`: Any type that can be converted into a `String` (e.g., `&str` or `String`)
1951    ///
1952    /// # Returns
1953    ///
1954    /// A `CallToolError` wrapping a dynamic error created from the provided message.
1955    pub fn from_message(message: impl Into<String>) -> Self {
1956        struct MsgError(String);
1957        impl std::fmt::Debug for MsgError {
1958            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1959                write!(f, "{}", self.0)
1960            }
1961        }
1962        impl std::fmt::Display for MsgError {
1963            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1964                write!(f, "{}", self.0)
1965            }
1966        }
1967        impl std::error::Error for MsgError {}
1968
1969        CallToolError::new(MsgError(message.into()))
1970    }
1971}
1972
1973/// Converts a `CallToolError` into a `RpcError`.
1974///
1975/// The conversion creates an internal error variant of `RpcError`
1976/// and attaches the string representation of the original `CallToolError` as a message.
1977///
1978impl From<CallToolError> for RpcError {
1979    fn from(value: CallToolError) -> Self {
1980        Self::internal_error().with_message(value.to_string())
1981    }
1982}
1983
1984/// Conversion of `CallToolError` into a `CallToolResult` with an error.
1985impl From<CallToolError> for CallToolResult {
1986    fn from(value: CallToolError) -> Self {
1987        // Convert `CallToolError` to a `CallToolResult`
1988        CallToolResult {
1989            content: vec![TextContent::new(value.to_string(), None, None).into()],
1990            is_error: Some(true),
1991            meta: None,
1992            structured_content: None,
1993        }
1994    }
1995}
1996
1997// Implement `Display` for `CallToolError` to provide a user-friendly error message.
1998impl core::fmt::Display for CallToolError {
1999    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2000        write!(f, "{}", self.0)
2001    }
2002}
2003
2004// Implement `Error` for `CallToolError` to propagate the source of the error.
2005impl std::error::Error for CallToolError {
2006    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
2007        self.0.source()
2008    }
2009}
2010
2011impl CallToolRequest {
2012    /// Retrieves the name of the tool from the request parameters.
2013    ///
2014    /// This method provides access to the tool name stored within the `params` field
2015    /// of the `CallToolRequest` struct, returning it as a string reference.
2016    ///
2017    /// # Returns
2018    /// A reference to the string containing the tool's name.
2019    pub fn tool_name(&self) -> &str {
2020        &self.params.name
2021    }
2022}
2023
2024impl<T: Into<String>> From<T> for TextContent {
2025    fn from(value: T) -> Self {
2026        TextContent::new(value.into(), None, None)
2027    }
2028}
2029
2030impl TextResourceContents {
2031    pub fn new<T: Into<String>>(text: T, uri: T) -> Self {
2032        TextResourceContents {
2033            meta: None,
2034            mime_type: None,
2035            text: text.into(),
2036            uri: uri.into(),
2037        }
2038    }
2039    /// Assigns metadata to the TextResourceContents, enabling the inclusion of extra context or details.
2040    pub fn with_meta(mut self, meta: serde_json::Map<String, Value>) -> Self {
2041        self.meta = Some(meta);
2042        self
2043    }
2044
2045    pub fn with_mime_type<T: Into<String>>(mut self, mime_type: T) -> Self {
2046        self.mime_type = Some(mime_type.into());
2047        self
2048    }
2049
2050    pub fn with_uri<T: Into<String>>(mut self, uri: T) -> Self {
2051        self.uri = uri.into();
2052        self
2053    }
2054}
2055
2056impl BlobResourceContents {
2057    pub fn new<T: Into<String>>(base64_text: T, uri: T) -> Self {
2058        BlobResourceContents {
2059            meta: None,
2060            mime_type: None,
2061            blob: base64_text.into(),
2062            uri: uri.into(),
2063        }
2064    }
2065    /// Assigns metadata to the BlobResourceContents, enabling the inclusion of extra context or details.
2066    pub fn with_meta(mut self, meta: serde_json::Map<String, Value>) -> Self {
2067        self.meta = Some(meta);
2068        self
2069    }
2070    pub fn with_mime_type<T: Into<String>>(mut self, mime_type: T) -> Self {
2071        self.mime_type = Some(mime_type.into());
2072        self
2073    }
2074    pub fn with_uri<T: Into<String>>(mut self, uri: T) -> Self {
2075        self.uri = uri.into();
2076        self
2077    }
2078}
2079
2080#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2081#[serde(untagged)]
2082#[allow(clippy::large_enum_variant)]
2083pub enum ClientMessages {
2084    Single(ClientMessage),
2085    Batch(Vec<ClientMessage>),
2086}
2087
2088impl ClientMessages {
2089    pub fn is_batch(&self) -> bool {
2090        matches!(self, ClientMessages::Batch(_))
2091    }
2092
2093    pub fn includes_request(&self) -> bool {
2094        match self {
2095            ClientMessages::Single(client_message) => client_message.is_request(),
2096            ClientMessages::Batch(client_messages) => client_messages.iter().any(ClientMessage::is_request),
2097        }
2098    }
2099
2100    pub fn as_single(self) -> result::Result<ClientMessage, SdkError> {
2101        match self {
2102            ClientMessages::Single(client_message) => Ok(client_message),
2103            ClientMessages::Batch(_) => Err(SdkError::internal_error()
2104                .with_message("Error: cannot convert ClientMessages::Batch to ClientMessage::Single")),
2105        }
2106    }
2107    pub fn as_batch(self) -> result::Result<Vec<ClientMessage>, SdkError> {
2108        match self {
2109            ClientMessages::Single(_) => Err(SdkError::internal_error()
2110                .with_message("Error: cannot convert ClientMessage::Single to ClientMessages::Batch")),
2111            ClientMessages::Batch(client_messages) => Ok(client_messages),
2112        }
2113    }
2114}
2115
2116impl From<ClientMessage> for ClientMessages {
2117    fn from(value: ClientMessage) -> Self {
2118        Self::Single(value)
2119    }
2120}
2121
2122impl From<Vec<ClientMessage>> for ClientMessages {
2123    fn from(value: Vec<ClientMessage>) -> Self {
2124        Self::Batch(value)
2125    }
2126}
2127
2128impl Display for ClientMessages {
2129    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2130        write!(
2131            f,
2132            "{}",
2133            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
2134        )
2135    }
2136}
2137
2138#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2139#[serde(untagged)]
2140#[allow(clippy::large_enum_variant)]
2141pub enum ServerMessages {
2142    Single(ServerMessage),
2143    Batch(Vec<ServerMessage>),
2144}
2145
2146impl ServerMessages {
2147    pub fn is_batch(&self) -> bool {
2148        matches!(self, ServerMessages::Batch(_))
2149    }
2150
2151    pub fn includes_request(&self) -> bool {
2152        match self {
2153            ServerMessages::Single(server_message) => server_message.is_request(),
2154            ServerMessages::Batch(server_messages) => server_messages.iter().any(ServerMessage::is_request),
2155        }
2156    }
2157
2158    pub fn as_single(self) -> result::Result<ServerMessage, SdkError> {
2159        match self {
2160            ServerMessages::Single(server_message) => Ok(server_message),
2161            ServerMessages::Batch(_) => Err(SdkError::internal_error()
2162                .with_message("Error: cannot convert ServerMessages::Batch to ServerMessage::Single")),
2163        }
2164    }
2165    pub fn as_batch(self) -> result::Result<Vec<ServerMessage>, SdkError> {
2166        match self {
2167            ServerMessages::Single(_) => Err(SdkError::internal_error()
2168                .with_message("Error: cannot convert ServerMessage::Single to ServerMessages::Batch")),
2169            ServerMessages::Batch(server_messages) => Ok(server_messages),
2170        }
2171    }
2172}
2173
2174impl From<ServerMessage> for ServerMessages {
2175    fn from(value: ServerMessage) -> Self {
2176        Self::Single(value)
2177    }
2178}
2179
2180impl From<Vec<ServerMessage>> for ServerMessages {
2181    fn from(value: Vec<ServerMessage>) -> Self {
2182        Self::Batch(value)
2183    }
2184}
2185
2186impl Display for ServerMessages {
2187    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2188        write!(
2189            f,
2190            "{}",
2191            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
2192        )
2193    }
2194}
2195
2196#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2197#[serde(untagged)]
2198#[allow(clippy::large_enum_variant)]
2199pub enum MessagesFromServer {
2200    Single(MessageFromServer),
2201    Batch(Vec<MessageFromServer>),
2202}
2203
2204impl MessagesFromServer {
2205    pub fn is_batch(&self) -> bool {
2206        matches!(self, MessagesFromServer::Batch(_))
2207    }
2208
2209    pub fn includes_request(&self) -> bool {
2210        match self {
2211            MessagesFromServer::Single(server_message) => server_message.is_request(),
2212            MessagesFromServer::Batch(server_messages) => server_messages.iter().any(MessageFromServer::is_request),
2213        }
2214    }
2215
2216    pub fn as_single(self) -> result::Result<MessageFromServer, SdkError> {
2217        match self {
2218            MessagesFromServer::Single(server_message) => Ok(server_message),
2219            MessagesFromServer::Batch(_) => Err(SdkError::internal_error()
2220                .with_message("Error: cannot convert MessagesFromServer::Batch to MessageFromServer::Single")),
2221        }
2222    }
2223    pub fn as_batch(self) -> result::Result<Vec<MessageFromServer>, SdkError> {
2224        match self {
2225            MessagesFromServer::Single(_) => Err(SdkError::internal_error()
2226                .with_message("Error: cannot convert MessageFromServer::Single to MessagesFromServer::Batch")),
2227            MessagesFromServer::Batch(server_messages) => Ok(server_messages),
2228        }
2229    }
2230}
2231
2232impl From<MessageFromServer> for MessagesFromServer {
2233    fn from(value: MessageFromServer) -> Self {
2234        Self::Single(value)
2235    }
2236}
2237
2238impl From<Vec<MessageFromServer>> for MessagesFromServer {
2239    fn from(value: Vec<MessageFromServer>) -> Self {
2240        Self::Batch(value)
2241    }
2242}
2243
2244#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2245#[serde(untagged)]
2246#[allow(clippy::large_enum_variant)]
2247pub enum MessagesFromClient {
2248    Single(MessageFromClient),
2249    Batch(Vec<MessageFromClient>),
2250}
2251
2252impl MessagesFromClient {
2253    pub fn is_batch(&self) -> bool {
2254        matches!(self, MessagesFromClient::Batch(_))
2255    }
2256
2257    pub fn includes_request(&self) -> bool {
2258        match self {
2259            MessagesFromClient::Single(server_message) => server_message.is_request(),
2260            MessagesFromClient::Batch(server_messages) => server_messages.iter().any(MessageFromClient::is_request),
2261        }
2262    }
2263
2264    pub fn as_single(self) -> result::Result<MessageFromClient, SdkError> {
2265        match self {
2266            MessagesFromClient::Single(server_message) => Ok(server_message),
2267            MessagesFromClient::Batch(_) => Err(SdkError::internal_error()
2268                .with_message("Error: cannot convert MessagesFromClient::Batch to MessageFromClient::Single")),
2269        }
2270    }
2271    pub fn as_batch(self) -> result::Result<Vec<MessageFromClient>, SdkError> {
2272        match self {
2273            MessagesFromClient::Single(_) => Err(SdkError::internal_error()
2274                .with_message("Error: cannot convert MessageFromClient::Single to MessagesFromClient::Batch")),
2275            MessagesFromClient::Batch(server_messages) => Ok(server_messages),
2276        }
2277    }
2278}
2279
2280impl From<MessageFromClient> for MessagesFromClient {
2281    fn from(value: MessageFromClient) -> Self {
2282        Self::Single(value)
2283    }
2284}
2285
2286impl From<Vec<MessageFromClient>> for MessagesFromClient {
2287    fn from(value: Vec<MessageFromClient>) -> Self {
2288        Self::Batch(value)
2289    }
2290}
2291
2292#[derive(Debug)]
2293pub struct StringSchemaFormatError {
2294    invalid_value: String,
2295}
2296
2297impl core::fmt::Display for StringSchemaFormatError {
2298    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2299        write!(f, "Invalid string schema format: '{}'", self.invalid_value)
2300    }
2301}
2302
2303impl std::error::Error for StringSchemaFormatError {}
2304
2305impl FromStr for StringSchemaFormat {
2306    type Err = StringSchemaFormatError;
2307
2308    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2309        match s {
2310            "date" => Ok(Self::Date),
2311            "date-time" => Ok(Self::DateTime),
2312            "email" => Ok(Self::Email),
2313            "uri" => Ok(Self::Uri),
2314            _ => Err(StringSchemaFormatError {
2315                invalid_value: s.to_string(),
2316            }),
2317        }
2318    }
2319}
2320
2321// Helper: handle all single-select enum variants
2322fn try_from_enum_schema(map: &serde_json::Map<String, Value>) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2323    // All enum schemas should have type: "string" (or missing, but usually present)
2324    let has_one_of = map.contains_key("oneOf");
2325    let has_enum = map.contains_key("enum");
2326    let has_enum_names = map.contains_key("enumNames");
2327
2328    if has_one_of {
2329        let schema: TitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2330            RpcError::parse_error().with_message(format!("Failed to parse TitledSingleSelectEnumSchema: {e}"))
2331        })?;
2332
2333        Ok(PrimitiveSchemaDefinition::TitledSingleSelectEnumSchema(schema))
2334    } else if has_enum && has_enum_names {
2335        let schema: LegacyTitledEnumSchema = serde_json::from_value(Value::Object(map.clone()))
2336            .map_err(|e| RpcError::parse_error().with_message(format!("Failed to parse LegacyTitledEnumSchema: {e}")))?;
2337        Ok(PrimitiveSchemaDefinition::LegacyTitledEnumSchema(schema))
2338    } else if has_enum {
2339        let schema: UntitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2340            RpcError::parse_error().with_message(format!("Failed to parse UntitledSingleSelectEnumSchema: {e}"))
2341        })?;
2342        Ok(PrimitiveSchemaDefinition::UntitledSingleSelectEnumSchema(schema))
2343    } else {
2344        Err(RpcError::parse_error().with_message("Invalid enum schema: missing 'enum' or 'oneOf'".to_string()))
2345    }
2346}
2347
2348// Helper: handle multi-select (array) enum schemas
2349fn try_from_multi_select_schema(
2350    map: &serde_json::Map<String, Value>,
2351) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2352    let items = map
2353        .get("items")
2354        .ok_or(RpcError::parse_error().with_message("Array schema missing 'items' field".to_string()))?;
2355
2356    let items_obj = items
2357        .as_object()
2358        .ok_or(RpcError::parse_error().with_message("Field 'items' must be an object".to_string()))?;
2359
2360    if items_obj.contains_key("anyOf") {
2361        let schema: TitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2362            RpcError::parse_error().with_message(format!("Failed to parse TitledMultiSelectEnumSchema: {e}"))
2363        })?;
2364        Ok(PrimitiveSchemaDefinition::TitledMultiSelectEnumSchema(schema))
2365    } else if items_obj.contains_key("enum") {
2366        let schema: UntitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2367            RpcError::parse_error().with_message(format!("Failed to parse UntitledMultiSelectEnumSchema: {e}"))
2368        })?;
2369        Ok(PrimitiveSchemaDefinition::UntitledMultiSelectEnumSchema(schema))
2370    } else {
2371        Err(RpcError::parse_error()
2372            .with_message("Array schema 'items' must contain 'enum' or 'oneOf' to be a multi-select enum".to_string()))
2373    }
2374}
2375
2376impl TryFrom<&serde_json::Map<String, Value>> for PrimitiveSchemaDefinition {
2377    type Error = RpcError;
2378
2379    fn try_from(value: &serde_json::Map<String, serde_json::Value>) -> result::Result<Self, Self::Error> {
2380        // 1. First: detect enum schemas (they look like strings but have enum/oneOf)
2381        if value.contains_key("enum") || value.contains_key("oneOf") {
2382            return try_from_enum_schema(value);
2383        }
2384
2385        // 2. Then: detect multi-select array schemas (type: "array" + items with enum/oneOf)
2386        if value.get("type").and_then(|v| v.as_str()) == Some("array") {
2387            return try_from_multi_select_schema(value);
2388        }
2389
2390        let input_type = value
2391            .get("type")
2392            .and_then(|v| v.as_str())
2393            .or_else(|| value.get("oneOf").map(|_| "enum")) // if "oneOf" exists, return "enum"
2394            .ok_or_else(|| {
2395                RpcError::parse_error().with_message("'type' is missing and data type is not supported!".to_string())
2396            })?;
2397
2398        let description = value.get("description").and_then(|v| v.as_str().map(|s| s.to_string()));
2399        let title = value.get("title").and_then(|v| v.as_str().map(|s| s.to_string()));
2400
2401        let schema_definition: PrimitiveSchemaDefinition = match input_type {
2402            "string" => {
2403                let max_length = value.get("maxLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2404                let min_length = value.get("minLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2405                let default = value.get("default").and_then(|v| v.as_str().map(|s| s.to_string()));
2406
2407                let format_str = value.get("format").and_then(|v| v.as_str());
2408                let format = format_str.and_then(|s| StringSchemaFormat::from_str(s).ok());
2409
2410                PrimitiveSchemaDefinition::StringSchema(StringSchema::new(
2411                    default,
2412                    description,
2413                    format,
2414                    max_length,
2415                    min_length,
2416                    title,
2417                ))
2418            }
2419            "number" | "integer" => {
2420                let maximum = value.get("maximum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2421                let minimum = value.get("minimum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2422                let default = value.get("default").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2423
2424                PrimitiveSchemaDefinition::NumberSchema(NumberSchema {
2425                    default,
2426                    description,
2427                    maximum,
2428                    minimum,
2429                    title,
2430                    type_: if input_type == "integer" {
2431                        NumberSchemaType::Integer
2432                    } else {
2433                        NumberSchemaType::Number
2434                    },
2435                })
2436            }
2437            "boolean" => {
2438                let default = value.get("default").and_then(|v| v.as_bool().map(|s| s.to_owned()));
2439                PrimitiveSchemaDefinition::BooleanSchema(BooleanSchema::new(default, description, title))
2440            }
2441            other => {
2442                return Err(RpcError::parse_error().with_message(format!("'{other}' type is not currently supported")));
2443            }
2444        };
2445
2446        Ok(schema_definition)
2447    }
2448}
2449
2450impl RequestFromServer {
2451    pub fn is_task_augmented(&self) -> bool {
2452        match self {
2453            RequestFromServer::CreateMessageRequest(create_message_request_params) => {
2454                create_message_request_params.is_task_augmented()
2455            }
2456            RequestFromServer::ElicitRequest(elicit_request_params) => elicit_request_params.is_task_augmented(),
2457            _ => false,
2458        }
2459    }
2460}
2461
2462impl MessageFromServer {
2463    pub fn is_task_augmented(&self) -> bool {
2464        match self {
2465            MessageFromServer::RequestFromServer(request_from_server) => request_from_server.is_task_augmented(),
2466            _ => false,
2467        }
2468    }
2469}
2470
2471impl CallToolRequest {
2472    pub fn is_task_augmented(&self) -> bool {
2473        self.params.is_task_augmented()
2474    }
2475}
2476
2477impl CallToolRequestParams {
2478    pub fn is_task_augmented(&self) -> bool {
2479        self.task.is_some()
2480    }
2481}
2482
2483impl CreateMessageRequestParams {
2484    pub fn is_task_augmented(&self) -> bool {
2485        self.task.is_some()
2486    }
2487}
2488
2489impl ElicitRequestParams {
2490    pub fn is_task_augmented(&self) -> bool {
2491        match self {
2492            ElicitRequestParams::UrlParams(elicit_request_url_params) => elicit_request_url_params.task.is_some(),
2493            ElicitRequestParams::FormParams(elicit_request_form_params) => elicit_request_form_params.task.is_some(),
2494        }
2495    }
2496
2497    pub fn message(&self) -> &str {
2498        match self {
2499            ElicitRequestParams::UrlParams(elicit_request_url_params) => elicit_request_url_params.message.as_str(),
2500            ElicitRequestParams::FormParams(elicit_request_form_params) => elicit_request_form_params.message.as_str(),
2501        }
2502    }
2503
2504    /// Set task metadata , requesting task-augmented execution for this request
2505    pub fn with_task(mut self, task: TaskMetadata) -> Self {
2506        match &mut self {
2507            ElicitRequestParams::UrlParams(params) => {
2508                params.task = Some(task);
2509            }
2510            ElicitRequestParams::FormParams(params) => {
2511                params.task = Some(task);
2512            }
2513        }
2514        self
2515    }
2516}
2517
2518impl ElicitRequestUrlParams {
2519    /// Set task metadata , requesting task-augmented execution for this request
2520    pub fn with_task(mut self, task: TaskMetadata) -> Self {
2521        self.task = Some(task);
2522        self
2523    }
2524}
2525
2526impl ElicitRequestFormParams {
2527    /// Set task metadata , requesting task-augmented execution for this request
2528    pub fn with_task(mut self, task: TaskMetadata) -> Self {
2529        self.task = Some(task);
2530        self
2531    }
2532}
2533
2534impl ServerCapabilities {
2535    /// Returns `true` if the server supports listing tasks.
2536    ///
2537    /// This is determined by whether the `list` capability is present.
2538    pub fn can_list_tasks(&self) -> bool {
2539        self.tasks.as_ref().is_some_and(|tasks| tasks.can_list_tasks())
2540    }
2541
2542    /// Returns `true` if the server supports canceling tasks.
2543    ///
2544    /// This is determined by whether the `cancel` capability is present.
2545    pub fn can_cancel_tasks(&self) -> bool {
2546        self.tasks.as_ref().is_some_and(|tasks| tasks.can_cancel_tasks())
2547    }
2548
2549    /// Returns `true` if the server supports task-augmented tools/call requests
2550    pub fn can_run_task_augmented_tools(&self) -> bool {
2551        self.tasks.as_ref().is_some_and(|tasks| tasks.can_run_task_augmented_tools())
2552    }
2553
2554    pub fn can_handle_request(&self, client_request: &ClientJsonrpcRequest) -> std::result::Result<(), RpcError> {
2555        let request_method = client_request.method();
2556
2557        // Helper function for creating error messages
2558        fn create_error(capability: &str, method: &str) -> RpcError {
2559            RpcError::internal_error().with_message(create_unsupported_capability_message("Server", capability, method))
2560        }
2561
2562        match client_request {
2563            ClientJsonrpcRequest::SetLevelRequest(_) if self.logging.is_none() => {
2564                return Err(create_error("logging", request_method));
2565            }
2566            ClientJsonrpcRequest::GetPromptRequest(_) | ClientJsonrpcRequest::ListPromptsRequest(_)
2567                if self.prompts.is_none() =>
2568            {
2569                return Err(create_error("prompts", request_method));
2570            }
2571
2572            ClientJsonrpcRequest::ListResourcesRequest(_)
2573            | ClientJsonrpcRequest::ListResourceTemplatesRequest(_)
2574            | ClientJsonrpcRequest::ReadResourceRequest(_)
2575            | ClientJsonrpcRequest::SubscribeRequest(_)
2576            | ClientJsonrpcRequest::UnsubscribeRequest(_)
2577                if self.resources.is_none() =>
2578            {
2579                return Err(create_error("resources", request_method));
2580            }
2581
2582            ClientJsonrpcRequest::CallToolRequest(call_tool_request)
2583                if call_tool_request.is_task_augmented() && !self.can_run_task_augmented_tools() =>
2584            {
2585                return Err(create_error("Task-augmented tool call", request_method));
2586            }
2587
2588            ClientJsonrpcRequest::CallToolRequest(_) | ClientJsonrpcRequest::ListToolsRequest(_) if self.tools.is_none() => {
2589                return Err(create_error("tools", request_method));
2590            }
2591            ClientJsonrpcRequest::CompleteRequest(_) if self.completions.is_none() => {
2592                return Err(create_error("completions", request_method));
2593            }
2594
2595            ClientJsonrpcRequest::GetTaskRequest(_)
2596            | ClientJsonrpcRequest::GetTaskPayloadRequest(_)
2597            | ClientJsonrpcRequest::CancelTaskRequest(_)
2598            | ClientJsonrpcRequest::ListTasksRequest(_)
2599                if self.tasks.is_none() =>
2600            {
2601                return Err(create_error("task", request_method));
2602            }
2603            ClientJsonrpcRequest::ListTasksRequest(_) if !self.can_list_tasks() => {
2604                return Err(create_error("listing tasks", request_method));
2605            }
2606            ClientJsonrpcRequest::CancelTaskRequest(_) if !self.can_cancel_tasks() => {
2607                return Err(create_error("task cancellation", request_method));
2608            }
2609            _ => {}
2610        };
2611        Ok(())
2612    }
2613
2614    /// Asserts that the server supports the requested notification.
2615    ///
2616    /// Verifies that the server advertises support for the notification type,
2617    /// allowing callers to avoid sending notifications that the server does not
2618    /// support. This can be used to prevent issuing requests to peers that lack
2619    /// the required capability.
2620    pub fn can_accept_notification(&self, notification_method: &str) -> std::result::Result<(), RpcError> {
2621        let entity = "Server";
2622
2623        if LoggingMessageNotification::method_value().eq(notification_method) && self.logging.is_none() {
2624            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2625                entity,
2626                "logging",
2627                notification_method,
2628            )));
2629        }
2630
2631        if [
2632            ResourceUpdatedNotification::method_value(),
2633            ResourceListChangedNotification::method_value(),
2634        ]
2635        .contains(&notification_method)
2636            && self.resources.is_none()
2637        {
2638            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2639                entity,
2640                "notifying about resources",
2641                notification_method,
2642            )));
2643        }
2644
2645        if ToolListChangedNotification::method_value().eq(notification_method) && self.tools.is_none() {
2646            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2647                entity,
2648                "notifying of tool list changes",
2649                notification_method,
2650            )));
2651        }
2652
2653        if PromptListChangedNotification::method_value().eq(notification_method) && self.prompts.is_none() {
2654            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2655                entity,
2656                "notifying of prompt list changes",
2657                notification_method,
2658            )));
2659        }
2660
2661        Ok(())
2662    }
2663}
2664
2665impl ServerTasks {
2666    /// Returns `true` if the server supports listing tasks.
2667    ///
2668    /// This is determined by whether the `list` capability is present.
2669    pub fn can_list_tasks(&self) -> bool {
2670        self.list.is_some()
2671    }
2672
2673    /// Returns `true` if the server supports canceling tasks.
2674    ///
2675    /// This is determined by whether the `cancel` capability is present.
2676    pub fn can_cancel_tasks(&self) -> bool {
2677        self.cancel.is_some()
2678    }
2679
2680    /// Returns `true` if the server supports task-augmented tools/call requests
2681    pub fn can_run_task_augmented_tools(&self) -> bool {
2682        if let Some(requests) = self.requests.as_ref() {
2683            if let Some(tools) = requests.tools.as_ref() {
2684                return tools.call.is_some();
2685            }
2686        }
2687        false
2688    }
2689}
2690
2691/// Formats an assertion error message for unsupported capabilities.
2692///
2693/// Constructs a string describing that a specific entity (e.g., server or client) lacks
2694/// support for a required capability, needed for a particular method.
2695///
2696/// # Arguments
2697/// - `entity`: The name of the entity (e.g., "Server" or "Client") that lacks support.
2698/// - `capability`: The name of the unsupported capability or tool.
2699/// - `method_name`: The name of the method requiring the capability.
2700///
2701/// # Returns
2702/// A formatted string detailing the unsupported capability error.
2703///
2704/// # Examples
2705/// ```ignore
2706/// let msg = create_unsupported_capability_message("Server", "tools", rust_mcp_schema::ListResourcesRequest::method_value());
2707/// assert_eq!(msg, "Server does not support resources (required for resources/list)");
2708/// ```
2709fn create_unsupported_capability_message(entity: &str, capability: &str, method_name: &str) -> String {
2710    format!("{entity} does not support {capability} (required for {method_name})")
2711}
2712
2713impl ClientCapabilities {
2714    /// Returns `true` if the server supports listing tasks.
2715    ///
2716    /// This is determined by whether the `list` capability is present.
2717    pub fn can_list_tasks(&self) -> bool {
2718        self.tasks.as_ref().is_some_and(|task| task.can_list_tasks())
2719    }
2720
2721    /// Returns `true` if the server supports canceling tasks.
2722    ///
2723    /// This is determined by whether the `cancel` capability is present.
2724    pub fn can_cancel_tasks(&self) -> bool {
2725        self.tasks.as_ref().is_some_and(|task| task.can_cancel_tasks())
2726    }
2727
2728    /// Returns `true` if the client can request elicitation.
2729    pub fn can_accept_elicitation_task(&self) -> bool {
2730        self.tasks.as_ref().is_some_and(|task| task.can_accept_elicitation_task())
2731    }
2732
2733    /// Returns `true` if the client can request message sampling.
2734    pub fn can_accept_sampling_task(&self) -> bool {
2735        self.tasks.as_ref().is_some_and(|task| task.can_accept_sampling_task())
2736    }
2737
2738    pub fn can_handle_request(&self, server_jsonrpc_request: &ServerJsonrpcRequest) -> std::result::Result<(), RpcError> {
2739        let request_method = server_jsonrpc_request.method();
2740
2741        // Helper function for creating error messages
2742        fn create_error(capability: &str, method: &str) -> RpcError {
2743            RpcError::internal_error().with_message(create_unsupported_capability_message("Client", capability, method))
2744        }
2745
2746        match server_jsonrpc_request {
2747            ServerJsonrpcRequest::CreateMessageRequest(create_message_request) => {
2748                match self.sampling.as_ref() {
2749                    Some(samplig_capabilities) => {
2750                        //  include_context requested but not supported
2751                        if create_message_request.params.include_context.is_some() && samplig_capabilities.context.is_none()
2752                        {
2753                            return Err(create_error("context inclusion", request_method));
2754                        }
2755
2756                        if create_message_request.params.tool_choice.is_some() && samplig_capabilities.tools.is_none() {
2757                            return Err(create_error("tool choice", request_method));
2758                        }
2759                    }
2760                    None => {
2761                        return Err(create_error("sampling capability", request_method));
2762                    }
2763                }
2764
2765                if create_message_request.params.is_task_augmented() && !self.can_accept_sampling_task() {
2766                    return Err(create_error("sampling task", request_method));
2767                }
2768            }
2769            ServerJsonrpcRequest::ListRootsRequest(_) if self.roots.is_none() => {
2770                return Err(create_error("roots capability", request_method));
2771            }
2772            ServerJsonrpcRequest::GetTaskRequest(_) | ServerJsonrpcRequest::GetTaskPayloadRequest(_)
2773                if self.tasks.is_none() =>
2774            {
2775                return Err(create_error("Task", request_method));
2776            }
2777            ServerJsonrpcRequest::CancelTaskRequest(_) => {
2778                if let Some(tasks) = self.tasks.as_ref() {
2779                    if !tasks.can_cancel_tasks() {
2780                        return Err(create_error("task cancellation", request_method));
2781                    }
2782                }
2783            }
2784            ServerJsonrpcRequest::ListTasksRequest(_) => {
2785                if let Some(tasks) = self.tasks.as_ref() {
2786                    if !tasks.can_list_tasks() {
2787                        return Err(create_error("listing tasks", request_method));
2788                    }
2789                }
2790            }
2791
2792            ServerJsonrpcRequest::ElicitRequest(elicit_request) => {
2793                if self.elicitation.is_none() {
2794                    return Err(create_error("input elicitation", request_method));
2795                }
2796
2797                if elicit_request.params.is_task_augmented() && !self.can_accept_elicitation_task() {
2798                    return Err(create_error("elicitation task", request_method));
2799                }
2800            }
2801            _ => {}
2802        }
2803        Ok(())
2804    }
2805
2806    pub fn can_accept_notification(&self, notification_method: &str) -> std::result::Result<(), RpcError> {
2807        let entity = "Client";
2808
2809        if RootsListChangedNotification::method_value().eq(notification_method) && self.roots.is_none() {
2810            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2811                entity,
2812                "roots list changed notifications",
2813                notification_method,
2814            )));
2815        }
2816
2817        Ok(())
2818    }
2819}
2820
2821impl ClientTasks {
2822    /// Returns `true` if the server supports listing tasks.
2823    ///
2824    /// This is determined by whether the `list` capability is present.
2825    pub fn can_list_tasks(&self) -> bool {
2826        self.list.is_some()
2827    }
2828
2829    /// Returns `true` if the server supports canceling tasks.
2830    ///
2831    /// This is determined by whether the `cancel` capability is present.
2832    pub fn can_cancel_tasks(&self) -> bool {
2833        self.cancel.is_some()
2834    }
2835
2836    /// Returns `true` if the client can request elicitation.
2837    pub fn can_accept_elicitation_task(&self) -> bool {
2838        if let Some(requests) = self.requests.as_ref() {
2839            if let Some(elicitation) = requests.elicitation.as_ref() {
2840                return elicitation.create.is_some();
2841            }
2842        }
2843        false
2844    }
2845
2846    /// Returns `true` if the client can request message sampling.
2847    pub fn can_accept_sampling_task(&self) -> bool {
2848        if let Some(requests) = self.requests.as_ref() {
2849            if let Some(sampling) = requests.sampling.as_ref() {
2850                return sampling.create_message.is_some();
2851            }
2852        }
2853        false
2854    }
2855}
2856
2857impl From<JsonrpcRequest> for CustomRequest {
2858    fn from(request: JsonrpcRequest) -> Self {
2859        Self {
2860            method: request.method,
2861            params: request.params,
2862        }
2863    }
2864}
2865
2866impl From<JsonrpcNotification> for CustomNotification {
2867    fn from(notification: JsonrpcNotification) -> Self {
2868        Self {
2869            method: notification.method,
2870            params: notification.params,
2871        }
2872    }
2873}
2874
2875/// Returns `true` if the task is in a terminal state.
2876/// Terminal states are states where the task has finished and will not change anymore.
2877impl TaskStatus {
2878    pub fn is_terminal(&self) -> bool {
2879        match self {
2880            TaskStatus::Cancelled | TaskStatus::Completed | TaskStatus::Failed => true,
2881            TaskStatus::InputRequired | TaskStatus::Working => false,
2882        }
2883    }
2884}
2885
2886/// Returns `true` if the task is in a terminal state.
2887/// Terminal states are states where the task has finished and will not change anymore.
2888impl Task {
2889    pub fn is_terminal(&self) -> bool {
2890        self.status.is_terminal()
2891    }
2892}
2893
2894impl GetTaskResult {
2895    pub fn is_terminal(&self) -> bool {
2896        self.status.is_terminal()
2897    }
2898}
2899
2900impl GetTaskPayloadResult {
2901    /// Retrieves the related task ID from the metadata, if it exists.
2902    ///
2903    /// This function looks for a key corresponding to the `RELATED_TASK_META_KEY` in the
2904    /// `meta` field of the struct. If the key exists and contains a string value, it returns
2905    /// it as an `Option<&str>`. If the key is missing or not a string, it returns `None`.
2906    ///
2907    /// # Returns
2908    /// - `Some(&str)` if a related task ID exists.
2909    /// - `None` if no related task ID is found.
2910    pub fn related_task_id(&self) -> Option<&str> {
2911        self.meta
2912            .as_ref()
2913            .and_then(|v| v.get(RELATED_TASK_META_KEY))
2914            .and_then(|v| v.as_str())
2915    }
2916
2917    /// Sets the related task ID in the metadata.
2918    ///
2919    /// This function inserts a `taskId` key with the provided `task_id` into the `meta` field.
2920    /// If the `meta` field is `None`, it creates a new `serde_json::Map` and assigns it to `meta`.
2921    /// The `task_id` is converted into a string before being inserted.
2922    ///
2923    /// # Type Parameters
2924    /// - `T`: The type of the `task_id`. It must implement `Into<String>` to allow flexible
2925    ///   conversion of various types (e.g., `&str`, `String`).
2926    ///
2927    /// # Arguments
2928    /// - `task_id`: The ID of the related task to set. This can be any type that can be converted
2929    ///   into a `String`.
2930    pub fn set_related_task_id<T>(&mut self, task_id: T)
2931    where
2932        T: Into<String>,
2933    {
2934        let task_json = json!({ "taskId": task_id.into() });
2935
2936        if let Some(meta) = &mut self.meta {
2937            meta.insert(RELATED_TASK_META_KEY.into(), task_json);
2938        } else {
2939            let mut new_meta = serde_json::Map::new();
2940            new_meta.insert(RELATED_TASK_META_KEY.into(), task_json);
2941            self.meta = Some(new_meta);
2942        }
2943    }
2944}
2945
2946pub trait McpMetaEx {
2947    /// Retrieves the related task ID from the metadata, if it exists.
2948    ///
2949    /// This function looks for a key corresponding to the `RELATED_TASK_META_KEY` in the
2950    /// `meta` field of the struct. If the key exists and contains a string value, it returns
2951    /// it as an `Option<&str>`. If the key is missing or not a string, it returns `None`.
2952    ///
2953    /// # Returns
2954    /// - `Some(&str)` if a related task ID exists.
2955    /// - `None` if no related task ID is found.
2956    fn related_task_id(&self) -> Option<&str>;
2957    /// Sets the related task ID in the metadata.
2958    ///
2959    /// This function inserts a `taskId` key with the provided `task_id` into the `meta` field.
2960    /// If the `meta` field is `None`, it creates a new `serde_json::Map` and assigns it to `meta`.
2961    /// The `task_id` is converted into a string before being inserted.
2962    ///
2963    /// # Type Parameters
2964    /// - `T`: The type of the `task_id`. It must implement `Into<String>` to allow flexible
2965    ///   conversion of various types (e.g., `&str`, `String`).
2966    ///
2967    /// # Arguments
2968    /// - `task_id`: The ID of the related task to set. This can be any type that can be converted
2969    ///   into a `String`.
2970    fn set_related_task_id<T>(&mut self, task_id: T)
2971    where
2972        T: Into<String>;
2973
2974    fn with_related_task_id<T>(self, task_id: T) -> Self
2975    where
2976        T: Into<String>;
2977
2978    /// Add a key-value pair.
2979    /// Value can be anything that serde can serialize (primitives, vecs, maps, structs, etc.).
2980    fn add<K, V>(self, key: K, value: V) -> Self
2981    where
2982        K: Into<String>,
2983        V: Into<Value>;
2984
2985    /// Conditionally add a field (useful for optional metadata).
2986    fn add_if<K, V>(self, condition: bool, key: K, value: V) -> Self
2987    where
2988        K: Into<String>,
2989        V: Into<Value>;
2990
2991    /// Add a raw pre-built Value (e.g. from json! macro or complex logic).
2992    fn add_raw<K>(self, key: K, value: Value) -> Self
2993    where
2994        K: Into<String>;
2995}
2996
2997impl McpMetaEx for serde_json::Map<String, Value> {
2998    fn related_task_id(&self) -> Option<&str> {
2999        self.get(RELATED_TASK_META_KEY).and_then(|v| v.as_str())
3000    }
3001
3002    fn set_related_task_id<T>(&mut self, task_id: T)
3003    where
3004        T: Into<String>,
3005    {
3006        let task_json = json!({ "taskId": task_id.into() });
3007        self.entry(RELATED_TASK_META_KEY)
3008            .and_modify(|e| *e = task_json.clone())
3009            .or_insert_with(|| task_json);
3010    }
3011
3012    fn with_related_task_id<T>(mut self, task_id: T) -> Self
3013    where
3014        T: Into<String>,
3015    {
3016        self.set_related_task_id(task_id);
3017        self
3018    }
3019
3020    /// Add a key-value pair.
3021    /// Value can be anything that serde can serialize (primitives, vecs, maps, structs, etc.).
3022    fn add<K, V>(mut self, key: K, value: V) -> Self
3023    where
3024        K: Into<String>,
3025        V: Into<Value>,
3026    {
3027        self.insert(key.into(), value.into());
3028        self
3029    }
3030
3031    /// Conditionally add a field (useful for optional metadata).
3032    fn add_if<K, V>(mut self, condition: bool, key: K, value: V) -> Self
3033    where
3034        K: Into<String>,
3035        V: Into<Value>,
3036    {
3037        if condition {
3038            self.insert(key.into(), value.into());
3039            self
3040        } else {
3041            self
3042        }
3043    }
3044
3045    /// Add a raw pre-built Value (e.g. from json! macro or complex logic).
3046    fn add_raw<K>(mut self, key: K, value: Value) -> Self
3047    where
3048        K: Into<String>,
3049    {
3050        self.insert(key.into(), value);
3051        self
3052    }
3053}
3054
3055impl FromStr for Role {
3056    type Err = RpcError;
3057
3058    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
3059        match s {
3060            "assistant" => Ok(Role::Assistant),
3061            "user" => Ok(Role::User),
3062            _ => {
3063                Err(RpcError::parse_error()
3064                    .with_message(format!("Invalid role '{s}'. Expected one of: 'assistant', 'user'")))
3065            }
3066        }
3067    }
3068}
3069
3070pub type CustomNotification = CustomRequest;
3071
3072/// BEGIN AUTO GENERATED
3073impl ::serde::Serialize for ServerJsonrpcResponse {
3074    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
3075    where
3076        S: ::serde::Serializer,
3077    {
3078        let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
3079        state.serialize_field("id", &self.id)?;
3080        state.serialize_field("jsonrpc", &self.jsonrpc)?;
3081        state.serialize_field("result", &self.result)?;
3082        state.end()
3083    }
3084}
3085impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcResponse {
3086    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
3087    where
3088        D: ::serde::Deserializer<'de>,
3089    {
3090        use serde::de::{self, MapAccess, Visitor};
3091        use std::fmt;
3092        struct ServerJsonrpcResultVisitor;
3093        impl<'de> Visitor<'de> for ServerJsonrpcResultVisitor {
3094            type Value = ServerJsonrpcResponse;
3095            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3096                formatter.write_str("a valid JSON-RPC response object")
3097            }
3098            fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcResponse, M::Error>
3099            where
3100                M: MapAccess<'de>,
3101            {
3102                let mut id: Option<RequestId> = None;
3103                let mut jsonrpc: Option<String> = None;
3104                let mut result: Option<Value> = None;
3105                while let Some(key) = map.next_key::<String>()? {
3106                    match key.as_str() {
3107                        "id" => id = Some(map.next_value()?),
3108                        "jsonrpc" => jsonrpc = Some(map.next_value()?),
3109                        "result" => result = Some(map.next_value()?),
3110                        _ => {
3111                            return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
3112                        }
3113                    }
3114                }
3115                let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
3116                let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
3117                let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
3118                let result = serde_json::from_value::<ResultFromServer>(result).map_err(de::Error::custom)?;
3119                Ok(ServerJsonrpcResponse { id, jsonrpc, result })
3120            }
3121        }
3122        deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ServerJsonrpcResultVisitor)
3123    }
3124}
3125impl ::serde::Serialize for ClientJsonrpcResponse {
3126    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
3127    where
3128        S: ::serde::Serializer,
3129    {
3130        let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
3131        state.serialize_field("id", &self.id)?;
3132        state.serialize_field("jsonrpc", &self.jsonrpc)?;
3133        state.serialize_field("result", &self.result)?;
3134        state.end()
3135    }
3136}
3137impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcResponse {
3138    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
3139    where
3140        D: ::serde::Deserializer<'de>,
3141    {
3142        use serde::de::{self, MapAccess, Visitor};
3143        use std::fmt;
3144        struct ClientJsonrpcResultVisitor;
3145        impl<'de> Visitor<'de> for ClientJsonrpcResultVisitor {
3146            type Value = ClientJsonrpcResponse;
3147            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3148                formatter.write_str("a valid JSON-RPC response object")
3149            }
3150            fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcResponse, M::Error>
3151            where
3152                M: MapAccess<'de>,
3153            {
3154                let mut id: Option<RequestId> = None;
3155                let mut jsonrpc: Option<String> = None;
3156                let mut result: Option<Value> = None;
3157                while let Some(key) = map.next_key::<String>()? {
3158                    match key.as_str() {
3159                        "id" => id = Some(map.next_value()?),
3160                        "jsonrpc" => jsonrpc = Some(map.next_value()?),
3161                        "result" => result = Some(map.next_value()?),
3162                        _ => {
3163                            return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
3164                        }
3165                    }
3166                }
3167                let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
3168                let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
3169                let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
3170                let result = serde_json::from_value::<ResultFromClient>(result).map_err(de::Error::custom)?;
3171                Ok(ClientJsonrpcResponse { id, jsonrpc, result })
3172            }
3173        }
3174        deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ClientJsonrpcResultVisitor)
3175    }
3176}
3177impl From<Result> for ResultFromClient {
3178    fn from(value: Result) -> Self {
3179        Self::Result(value)
3180    }
3181}
3182impl From<GetTaskResult> for ResultFromClient {
3183    fn from(value: GetTaskResult) -> Self {
3184        Self::GetTaskResult(value)
3185    }
3186}
3187impl From<GetTaskPayloadResult> for ResultFromClient {
3188    fn from(value: GetTaskPayloadResult) -> Self {
3189        Self::GetTaskPayloadResult(value)
3190    }
3191}
3192impl From<CancelTaskResult> for ResultFromClient {
3193    fn from(value: CancelTaskResult) -> Self {
3194        Self::CancelTaskResult(value)
3195    }
3196}
3197impl From<ListTasksResult> for ResultFromClient {
3198    fn from(value: ListTasksResult) -> Self {
3199        Self::ListTasksResult(value)
3200    }
3201}
3202impl From<CreateMessageResult> for ResultFromClient {
3203    fn from(value: CreateMessageResult) -> Self {
3204        Self::CreateMessageResult(value)
3205    }
3206}
3207impl From<ListRootsResult> for ResultFromClient {
3208    fn from(value: ListRootsResult) -> Self {
3209        Self::ListRootsResult(value)
3210    }
3211}
3212impl From<ElicitResult> for ResultFromClient {
3213    fn from(value: ElicitResult) -> Self {
3214        Self::ElicitResult(value)
3215    }
3216}
3217impl From<CreateTaskResult> for ResultFromClient {
3218    fn from(value: CreateTaskResult) -> Self {
3219        Self::CreateTaskResult(value)
3220    }
3221}
3222impl From<Result> for MessageFromClient {
3223    fn from(value: Result) -> Self {
3224        MessageFromClient::ResultFromClient(value.into())
3225    }
3226}
3227impl From<GetTaskResult> for MessageFromClient {
3228    fn from(value: GetTaskResult) -> Self {
3229        MessageFromClient::ResultFromClient(value.into())
3230    }
3231}
3232impl From<GetTaskPayloadResult> for MessageFromClient {
3233    fn from(value: GetTaskPayloadResult) -> Self {
3234        MessageFromClient::ResultFromClient(value.into())
3235    }
3236}
3237impl From<CancelTaskResult> for MessageFromClient {
3238    fn from(value: CancelTaskResult) -> Self {
3239        MessageFromClient::ResultFromClient(value.into())
3240    }
3241}
3242impl From<ListTasksResult> for MessageFromClient {
3243    fn from(value: ListTasksResult) -> Self {
3244        MessageFromClient::ResultFromClient(value.into())
3245    }
3246}
3247impl From<CreateMessageResult> for MessageFromClient {
3248    fn from(value: CreateMessageResult) -> Self {
3249        MessageFromClient::ResultFromClient(value.into())
3250    }
3251}
3252impl From<ListRootsResult> for MessageFromClient {
3253    fn from(value: ListRootsResult) -> Self {
3254        MessageFromClient::ResultFromClient(value.into())
3255    }
3256}
3257impl From<ElicitResult> for MessageFromClient {
3258    fn from(value: ElicitResult) -> Self {
3259        MessageFromClient::ResultFromClient(value.into())
3260    }
3261}
3262impl From<CreateTaskResult> for MessageFromClient {
3263    fn from(value: CreateTaskResult) -> Self {
3264        MessageFromClient::ResultFromClient(value.into())
3265    }
3266}
3267impl From<PingRequest> for ServerJsonrpcRequest {
3268    fn from(value: PingRequest) -> Self {
3269        Self::PingRequest(value)
3270    }
3271}
3272impl From<GetTaskRequest> for ServerJsonrpcRequest {
3273    fn from(value: GetTaskRequest) -> Self {
3274        Self::GetTaskRequest(value)
3275    }
3276}
3277impl From<GetTaskPayloadRequest> for ServerJsonrpcRequest {
3278    fn from(value: GetTaskPayloadRequest) -> Self {
3279        Self::GetTaskPayloadRequest(value)
3280    }
3281}
3282impl From<CancelTaskRequest> for ServerJsonrpcRequest {
3283    fn from(value: CancelTaskRequest) -> Self {
3284        Self::CancelTaskRequest(value)
3285    }
3286}
3287impl From<ListTasksRequest> for ServerJsonrpcRequest {
3288    fn from(value: ListTasksRequest) -> Self {
3289        Self::ListTasksRequest(value)
3290    }
3291}
3292impl From<CreateMessageRequest> for ServerJsonrpcRequest {
3293    fn from(value: CreateMessageRequest) -> Self {
3294        Self::CreateMessageRequest(value)
3295    }
3296}
3297impl From<ListRootsRequest> for ServerJsonrpcRequest {
3298    fn from(value: ListRootsRequest) -> Self {
3299        Self::ListRootsRequest(value)
3300    }
3301}
3302impl From<ElicitRequest> for ServerJsonrpcRequest {
3303    fn from(value: ElicitRequest) -> Self {
3304        Self::ElicitRequest(value)
3305    }
3306}
3307impl From<InitializeRequest> for ClientJsonrpcRequest {
3308    fn from(value: InitializeRequest) -> Self {
3309        Self::InitializeRequest(value)
3310    }
3311}
3312impl From<PingRequest> for ClientJsonrpcRequest {
3313    fn from(value: PingRequest) -> Self {
3314        Self::PingRequest(value)
3315    }
3316}
3317impl From<ListResourcesRequest> for ClientJsonrpcRequest {
3318    fn from(value: ListResourcesRequest) -> Self {
3319        Self::ListResourcesRequest(value)
3320    }
3321}
3322impl From<ListResourceTemplatesRequest> for ClientJsonrpcRequest {
3323    fn from(value: ListResourceTemplatesRequest) -> Self {
3324        Self::ListResourceTemplatesRequest(value)
3325    }
3326}
3327impl From<ReadResourceRequest> for ClientJsonrpcRequest {
3328    fn from(value: ReadResourceRequest) -> Self {
3329        Self::ReadResourceRequest(value)
3330    }
3331}
3332impl From<SubscribeRequest> for ClientJsonrpcRequest {
3333    fn from(value: SubscribeRequest) -> Self {
3334        Self::SubscribeRequest(value)
3335    }
3336}
3337impl From<UnsubscribeRequest> for ClientJsonrpcRequest {
3338    fn from(value: UnsubscribeRequest) -> Self {
3339        Self::UnsubscribeRequest(value)
3340    }
3341}
3342impl From<ListPromptsRequest> for ClientJsonrpcRequest {
3343    fn from(value: ListPromptsRequest) -> Self {
3344        Self::ListPromptsRequest(value)
3345    }
3346}
3347impl From<GetPromptRequest> for ClientJsonrpcRequest {
3348    fn from(value: GetPromptRequest) -> Self {
3349        Self::GetPromptRequest(value)
3350    }
3351}
3352impl From<ListToolsRequest> for ClientJsonrpcRequest {
3353    fn from(value: ListToolsRequest) -> Self {
3354        Self::ListToolsRequest(value)
3355    }
3356}
3357impl From<CallToolRequest> for ClientJsonrpcRequest {
3358    fn from(value: CallToolRequest) -> Self {
3359        Self::CallToolRequest(value)
3360    }
3361}
3362impl From<GetTaskRequest> for ClientJsonrpcRequest {
3363    fn from(value: GetTaskRequest) -> Self {
3364        Self::GetTaskRequest(value)
3365    }
3366}
3367impl From<GetTaskPayloadRequest> for ClientJsonrpcRequest {
3368    fn from(value: GetTaskPayloadRequest) -> Self {
3369        Self::GetTaskPayloadRequest(value)
3370    }
3371}
3372impl From<CancelTaskRequest> for ClientJsonrpcRequest {
3373    fn from(value: CancelTaskRequest) -> Self {
3374        Self::CancelTaskRequest(value)
3375    }
3376}
3377impl From<ListTasksRequest> for ClientJsonrpcRequest {
3378    fn from(value: ListTasksRequest) -> Self {
3379        Self::ListTasksRequest(value)
3380    }
3381}
3382impl From<SetLevelRequest> for ClientJsonrpcRequest {
3383    fn from(value: SetLevelRequest) -> Self {
3384        Self::SetLevelRequest(value)
3385    }
3386}
3387impl From<CompleteRequest> for ClientJsonrpcRequest {
3388    fn from(value: CompleteRequest) -> Self {
3389        Self::CompleteRequest(value)
3390    }
3391}
3392/// Enum representing SDK error codes.
3393#[allow(non_camel_case_types)]
3394pub enum SdkErrorCodes {
3395    CONNECTION_CLOSED = -32000,
3396    REQUEST_TIMEOUT = -32001,
3397    RESOURCE_NOT_FOUND = -32002,
3398    BAD_REQUEST = -32015,
3399    SESSION_NOT_FOUND = -32016,
3400    INVALID_REQUEST = -32600,
3401    METHOD_NOT_FOUND = -32601,
3402    INVALID_PARAMS = -32602,
3403    INTERNAL_ERROR = -32603,
3404    PARSE_ERROR = -32700,
3405    URL_ELICITATION_REQUIRED = -32042,
3406}
3407impl core::fmt::Display for SdkErrorCodes {
3408    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3409        match self {
3410            SdkErrorCodes::CONNECTION_CLOSED => write!(f, "Connection closed"),
3411            SdkErrorCodes::REQUEST_TIMEOUT => write!(f, "Request timeout"),
3412            SdkErrorCodes::INVALID_REQUEST => write!(f, "Invalid request"),
3413            SdkErrorCodes::METHOD_NOT_FOUND => write!(f, "Method not found"),
3414            SdkErrorCodes::INVALID_PARAMS => write!(f, "Invalid params"),
3415            SdkErrorCodes::INTERNAL_ERROR => write!(f, "Internal error"),
3416            SdkErrorCodes::PARSE_ERROR => write!(f, "Parse Error"),
3417            SdkErrorCodes::RESOURCE_NOT_FOUND => write!(f, "Resource not found"),
3418            SdkErrorCodes::BAD_REQUEST => write!(f, "Bad request"),
3419            SdkErrorCodes::SESSION_NOT_FOUND => write!(f, "Session not found"),
3420            SdkErrorCodes::URL_ELICITATION_REQUIRED => {
3421                write!(
3422                    f,
3423                    "A required URL was not provided. Please supply the requested URL to continue."
3424                )
3425            }
3426        }
3427    }
3428}
3429impl From<SdkErrorCodes> for i64 {
3430    fn from(code: SdkErrorCodes) -> Self {
3431        code as i64
3432    }
3433}
3434#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
3435pub struct SdkError {
3436    ///The error type that occurred.
3437    pub code: i64,
3438    ///Additional information about the error.
3439    pub data: ::std::option::Option<::serde_json::Value>,
3440    ///A short description of the error.
3441    pub message: ::std::string::String,
3442}
3443impl core::fmt::Display for SdkError {
3444    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3445        write!(f, "MCP error {}: {}", self.code, self.message)
3446    }
3447}
3448impl std::error::Error for SdkError {
3449    fn description(&self) -> &str {
3450        &self.message
3451    }
3452}
3453impl SdkError {
3454    pub fn new(
3455        error_code: SdkErrorCodes,
3456        message: ::std::string::String,
3457        data: ::std::option::Option<::serde_json::Value>,
3458    ) -> Self {
3459        Self {
3460            code: error_code.into(),
3461            data,
3462            message,
3463        }
3464    }
3465    pub fn connection_closed() -> Self {
3466        Self {
3467            code: SdkErrorCodes::CONNECTION_CLOSED.into(),
3468            data: None,
3469            message: SdkErrorCodes::CONNECTION_CLOSED.to_string(),
3470        }
3471    }
3472    pub fn request_timeout(timeout: u128) -> Self {
3473        Self {
3474            code: SdkErrorCodes::REQUEST_TIMEOUT.into(),
3475            data: Some(json!({ "timeout" : timeout })),
3476            message: SdkErrorCodes::REQUEST_TIMEOUT.to_string(),
3477        }
3478    }
3479    pub fn session_not_found() -> Self {
3480        Self {
3481            code: SdkErrorCodes::SESSION_NOT_FOUND.into(),
3482            data: None,
3483            message: SdkErrorCodes::SESSION_NOT_FOUND.to_string(),
3484        }
3485    }
3486    pub fn invalid_request() -> Self {
3487        Self {
3488            code: SdkErrorCodes::INVALID_REQUEST.into(),
3489            data: None,
3490            message: SdkErrorCodes::INVALID_REQUEST.to_string(),
3491        }
3492    }
3493    pub fn method_not_found() -> Self {
3494        Self {
3495            code: SdkErrorCodes::METHOD_NOT_FOUND.into(),
3496            data: None,
3497            message: SdkErrorCodes::METHOD_NOT_FOUND.to_string(),
3498        }
3499    }
3500    pub fn invalid_params() -> Self {
3501        Self {
3502            code: SdkErrorCodes::INVALID_PARAMS.into(),
3503            data: None,
3504            message: SdkErrorCodes::INVALID_PARAMS.to_string(),
3505        }
3506    }
3507    pub fn internal_error() -> Self {
3508        Self {
3509            code: SdkErrorCodes::INTERNAL_ERROR.into(),
3510            data: None,
3511            message: SdkErrorCodes::INTERNAL_ERROR.to_string(),
3512        }
3513    }
3514    pub fn parse_error() -> Self {
3515        Self {
3516            code: SdkErrorCodes::PARSE_ERROR.into(),
3517            data: None,
3518            message: SdkErrorCodes::PARSE_ERROR.to_string(),
3519        }
3520    }
3521    /// Creates a new `RpcError` indicating that a URL elicitation failed
3522    /// and was required for the operation to continue.
3523    ///
3524    /// The resulting error uses the -32042 value as introduced in mcp protocol 2025-11-25
3525    /// The result json matches a UrlElicitError and the `data` value could be deserialized into UrlElicitErrorData
3526    ///
3527    pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
3528        Self {
3529            code: UrlElicitError::code_value(),
3530            data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
3531                json!(
3532                    { "elicitations" : [], "error" :
3533                    "failed to UrlElicitError data" }
3534                )
3535            })),
3536            message: "URL required. Please provide a URL.".to_string(),
3537        }
3538    }
3539    pub fn resource_not_found() -> Self {
3540        Self {
3541            code: SdkErrorCodes::RESOURCE_NOT_FOUND.into(),
3542            data: None,
3543            message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
3544        }
3545    }
3546    pub fn bad_request() -> Self {
3547        Self {
3548            code: SdkErrorCodes::BAD_REQUEST.into(),
3549            data: None,
3550            message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
3551        }
3552    }
3553    pub fn with_message(mut self, message: &str) -> Self {
3554        self.message = message.to_string();
3555        self
3556    }
3557    pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
3558        self.data = data;
3559        self
3560    }
3561}
3562/// Enum representing standard and mcp specific JSON-RPC error codes.
3563#[allow(non_camel_case_types)]
3564pub enum RpcErrorCodes {
3565    PARSE_ERROR = -32700isize,
3566    INVALID_REQUEST = -32600isize,
3567    METHOD_NOT_FOUND = -32601isize,
3568    INVALID_PARAMS = -32602isize,
3569    INTERNAL_ERROR = -32603isize,
3570    URL_ELICITATION_REQUIRED = -32042isize,
3571}
3572impl From<RpcErrorCodes> for i64 {
3573    fn from(code: RpcErrorCodes) -> Self {
3574        code as i64
3575    }
3576}
3577impl RpcError {
3578    /// Constructs a new `RpcError` with the provided arguments.
3579    ///
3580    /// # Arguments
3581    /// * `error_code` - The JSON-RPC error code.
3582    /// * `message` - A descriptive error message.
3583    /// * `data` - Optional additional data.
3584    ///
3585    /// # Example
3586    /// ```
3587    /// use serde_json::json;
3588    /// use rust_mcp_schema::{RpcError, schema_utils::RpcErrorCodes};
3589    ///
3590    /// let error = RpcError::new(RpcErrorCodes::INVALID_PARAMS, "Invalid params!".to_string(), Some(json!({"details": "Missing method field"})));
3591    /// assert_eq!(error.code, -32602);
3592    /// assert_eq!(error.message, "Invalid params!".to_string());
3593    /// ```
3594    pub fn new(
3595        error_code: RpcErrorCodes,
3596        message: ::std::string::String,
3597        data: ::std::option::Option<::serde_json::Value>,
3598    ) -> Self {
3599        Self {
3600            code: error_code.into(),
3601            data,
3602            message,
3603        }
3604    }
3605    /// Creates a new `RpcError` for "Method not found".
3606    ///
3607    /// # Example
3608    /// ```
3609    /// use rust_mcp_schema::RpcError;
3610    ///
3611    /// let error = RpcError::method_not_found();
3612    /// assert_eq!(error.code, -32601);
3613    /// assert_eq!(error.message, "Method not found");
3614    /// ```
3615    pub fn method_not_found() -> Self {
3616        Self {
3617            code: RpcErrorCodes::METHOD_NOT_FOUND.into(),
3618            data: None,
3619            message: "Method not found".to_string(),
3620        }
3621    }
3622    /// Creates a new `RpcError` indicating that a URL elicitation failed
3623    /// and was required for the operation to continue.
3624    ///
3625    /// The resulting error uses the -32042 value as introduced in mcp protocol 2025-11-25
3626    /// The result json matches a UrlElicitError and the `data` value could be deserialized into UrlElicitErrorData
3627    ///
3628    pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
3629        Self {
3630            code: UrlElicitError::code_value(),
3631            data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
3632                json!(
3633                    { "elicitations" : [], "error" :
3634                    "failed to UrlElicitError data" }
3635                )
3636            })),
3637            message: "URL required. Please provide a URL.".to_string(),
3638        }
3639    }
3640    /// Creates a new `RpcError` for "Invalid parameters".
3641    ///
3642    /// # Example
3643    /// ```
3644    /// use rust_mcp_schema::RpcError;
3645    ///
3646    /// let error = RpcError::invalid_params();
3647    /// assert_eq!(error.code, -32602);
3648    /// ```
3649    pub fn invalid_params() -> Self {
3650        Self {
3651            code: RpcErrorCodes::INVALID_PARAMS.into(),
3652            data: None,
3653            message: "Invalid params".to_string(),
3654        }
3655    }
3656    /// Creates a new `RpcError` for "Invalid request".
3657    ///
3658    /// # Example
3659    /// ```
3660    /// use rust_mcp_schema::RpcError;
3661    ///
3662    /// let error = RpcError::invalid_request();
3663    /// assert_eq!(error.code, -32600);
3664    /// ```
3665    pub fn invalid_request() -> Self {
3666        Self {
3667            code: RpcErrorCodes::INVALID_REQUEST.into(),
3668            data: None,
3669            message: "Invalid request".to_string(),
3670        }
3671    }
3672    /// Creates a new `RpcError` for "Internal error".
3673    ///
3674    /// # Example
3675    /// ```
3676    /// use rust_mcp_schema::RpcError;
3677    ///
3678    /// let error = RpcError::internal_error();
3679    /// assert_eq!(error.code, -32603);
3680    /// ```
3681    pub fn internal_error() -> Self {
3682        Self {
3683            code: RpcErrorCodes::INTERNAL_ERROR.into(),
3684            data: None,
3685            message: "Internal error".to_string(),
3686        }
3687    }
3688    /// Creates a new `RpcError` for "Parse error".
3689    ///
3690    /// # Example
3691    /// ```
3692    /// use rust_mcp_schema::RpcError;
3693    ///
3694    /// let error = RpcError::parse_error();
3695    /// assert_eq!(error.code, -32700);
3696    /// ```
3697    pub fn parse_error() -> Self {
3698        Self {
3699            code: RpcErrorCodes::PARSE_ERROR.into(),
3700            data: None,
3701            message: "Parse error".to_string(),
3702        }
3703    }
3704    /// Sets a custom error message.
3705    ///
3706    /// # Example
3707    /// ```
3708    /// use rust_mcp_schema::RpcError;
3709    ///
3710    /// let error = RpcError::invalid_request().with_message("Request format is invalid".to_string());
3711    /// assert_eq!(error.message, "Request format is invalid".to_string());
3712    /// ```
3713    pub fn with_message<T: Into<String>>(mut self, message: T) -> Self {
3714        self.message = message.into();
3715        self
3716    }
3717    /// Attaches optional data to the error.
3718    ///
3719    /// # Example
3720    /// ```
3721    /// use serde_json::json;
3722    /// use rust_mcp_schema::RpcError;
3723    ///
3724    /// let error = RpcError::invalid_request().with_data(Some(json!({"reason": "Missing ID"})));
3725    /// assert!(error.data.is_some());
3726    /// ```
3727    pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
3728        self.data = data;
3729        self
3730    }
3731}
3732impl std::error::Error for RpcError {
3733    fn description(&self) -> &str {
3734        &self.message
3735    }
3736}
3737impl Display for RpcError {
3738    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3739        write!(
3740            f,
3741            "{}",
3742            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
3743        )
3744    }
3745}
3746impl FromStr for RpcError {
3747    type Err = RpcError;
3748    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
3749        serde_json::from_str(s)
3750            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
3751    }
3752}
3753///Constructs a new `JsonrpcErrorResponse` using the provided arguments.
3754impl JsonrpcErrorResponse {
3755    pub fn create(
3756        id: Option<RequestId>,
3757        error_code: RpcErrorCodes,
3758        error_message: ::std::string::String,
3759        error_data: ::std::option::Option<::serde_json::Value>,
3760    ) -> Self {
3761        Self::new(RpcError::new(error_code, error_message, error_data), id)
3762    }
3763}
3764impl From<Result> for ResultFromServer {
3765    fn from(value: Result) -> Self {
3766        Self::Result(value)
3767    }
3768}
3769impl From<InitializeResult> for ResultFromServer {
3770    fn from(value: InitializeResult) -> Self {
3771        Self::InitializeResult(value)
3772    }
3773}
3774impl From<ListResourcesResult> for ResultFromServer {
3775    fn from(value: ListResourcesResult) -> Self {
3776        Self::ListResourcesResult(value)
3777    }
3778}
3779impl From<ListResourceTemplatesResult> for ResultFromServer {
3780    fn from(value: ListResourceTemplatesResult) -> Self {
3781        Self::ListResourceTemplatesResult(value)
3782    }
3783}
3784impl From<ReadResourceResult> for ResultFromServer {
3785    fn from(value: ReadResourceResult) -> Self {
3786        Self::ReadResourceResult(value)
3787    }
3788}
3789impl From<ListPromptsResult> for ResultFromServer {
3790    fn from(value: ListPromptsResult) -> Self {
3791        Self::ListPromptsResult(value)
3792    }
3793}
3794impl From<GetPromptResult> for ResultFromServer {
3795    fn from(value: GetPromptResult) -> Self {
3796        Self::GetPromptResult(value)
3797    }
3798}
3799impl From<ListToolsResult> for ResultFromServer {
3800    fn from(value: ListToolsResult) -> Self {
3801        Self::ListToolsResult(value)
3802    }
3803}
3804impl From<CallToolResult> for ResultFromServer {
3805    fn from(value: CallToolResult) -> Self {
3806        Self::CallToolResult(value)
3807    }
3808}
3809impl From<GetTaskResult> for ResultFromServer {
3810    fn from(value: GetTaskResult) -> Self {
3811        Self::GetTaskResult(value)
3812    }
3813}
3814impl From<GetTaskPayloadResult> for ResultFromServer {
3815    fn from(value: GetTaskPayloadResult) -> Self {
3816        Self::GetTaskPayloadResult(value)
3817    }
3818}
3819impl From<CancelTaskResult> for ResultFromServer {
3820    fn from(value: CancelTaskResult) -> Self {
3821        Self::CancelTaskResult(value)
3822    }
3823}
3824impl From<ListTasksResult> for ResultFromServer {
3825    fn from(value: ListTasksResult) -> Self {
3826        Self::ListTasksResult(value)
3827    }
3828}
3829impl From<CompleteResult> for ResultFromServer {
3830    fn from(value: CompleteResult) -> Self {
3831        Self::CompleteResult(value)
3832    }
3833}
3834impl From<CreateTaskResult> for ResultFromServer {
3835    fn from(value: CreateTaskResult) -> Self {
3836        Self::CreateTaskResult(value)
3837    }
3838}
3839impl From<Result> for MessageFromServer {
3840    fn from(value: Result) -> Self {
3841        MessageFromServer::ResultFromServer(value.into())
3842    }
3843}
3844impl From<InitializeResult> for MessageFromServer {
3845    fn from(value: InitializeResult) -> Self {
3846        MessageFromServer::ResultFromServer(value.into())
3847    }
3848}
3849impl From<ListResourcesResult> for MessageFromServer {
3850    fn from(value: ListResourcesResult) -> Self {
3851        MessageFromServer::ResultFromServer(value.into())
3852    }
3853}
3854impl From<ListResourceTemplatesResult> for MessageFromServer {
3855    fn from(value: ListResourceTemplatesResult) -> Self {
3856        MessageFromServer::ResultFromServer(value.into())
3857    }
3858}
3859impl From<ReadResourceResult> for MessageFromServer {
3860    fn from(value: ReadResourceResult) -> Self {
3861        MessageFromServer::ResultFromServer(value.into())
3862    }
3863}
3864impl From<ListPromptsResult> for MessageFromServer {
3865    fn from(value: ListPromptsResult) -> Self {
3866        MessageFromServer::ResultFromServer(value.into())
3867    }
3868}
3869impl From<GetPromptResult> for MessageFromServer {
3870    fn from(value: GetPromptResult) -> Self {
3871        MessageFromServer::ResultFromServer(value.into())
3872    }
3873}
3874impl From<ListToolsResult> for MessageFromServer {
3875    fn from(value: ListToolsResult) -> Self {
3876        MessageFromServer::ResultFromServer(value.into())
3877    }
3878}
3879impl From<CallToolResult> for MessageFromServer {
3880    fn from(value: CallToolResult) -> Self {
3881        MessageFromServer::ResultFromServer(value.into())
3882    }
3883}
3884impl From<GetTaskResult> for MessageFromServer {
3885    fn from(value: GetTaskResult) -> Self {
3886        MessageFromServer::ResultFromServer(value.into())
3887    }
3888}
3889impl From<GetTaskPayloadResult> for MessageFromServer {
3890    fn from(value: GetTaskPayloadResult) -> Self {
3891        MessageFromServer::ResultFromServer(value.into())
3892    }
3893}
3894impl From<CancelTaskResult> for MessageFromServer {
3895    fn from(value: CancelTaskResult) -> Self {
3896        MessageFromServer::ResultFromServer(value.into())
3897    }
3898}
3899impl From<ListTasksResult> for MessageFromServer {
3900    fn from(value: ListTasksResult) -> Self {
3901        MessageFromServer::ResultFromServer(value.into())
3902    }
3903}
3904impl From<CompleteResult> for MessageFromServer {
3905    fn from(value: CompleteResult) -> Self {
3906        MessageFromServer::ResultFromServer(value.into())
3907    }
3908}
3909impl From<CreateTaskResult> for MessageFromServer {
3910    fn from(value: CreateTaskResult) -> Self {
3911        MessageFromServer::ResultFromServer(value.into())
3912    }
3913}
3914impl TryFrom<ResultFromClient> for GenericResult {
3915    type Error = RpcError;
3916    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3917        match value {
3918            ResultFromClient::GetTaskPayloadResult(result) => Ok(result.into()),
3919            ResultFromClient::Result(result) => Ok(result),
3920            _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
3921        }
3922    }
3923}
3924impl TryFrom<ResultFromClient> for GetTaskResult {
3925    type Error = RpcError;
3926    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3927        if let ResultFromClient::GetTaskResult(result) = value {
3928            Ok(result)
3929        } else {
3930            Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
3931        }
3932    }
3933}
3934impl TryFrom<ResultFromClient> for GetTaskPayloadResult {
3935    type Error = RpcError;
3936    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3937        if let ResultFromClient::GetTaskPayloadResult(result) = value {
3938            Ok(result)
3939        } else {
3940            Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
3941        }
3942    }
3943}
3944impl TryFrom<ResultFromClient> for CancelTaskResult {
3945    type Error = RpcError;
3946    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3947        if let ResultFromClient::CancelTaskResult(result) = value {
3948            Ok(result)
3949        } else {
3950            Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
3951        }
3952    }
3953}
3954impl TryFrom<ResultFromClient> for ListTasksResult {
3955    type Error = RpcError;
3956    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3957        if let ResultFromClient::ListTasksResult(result) = value {
3958            Ok(result)
3959        } else {
3960            Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
3961        }
3962    }
3963}
3964impl TryFrom<ResultFromClient> for CreateMessageResult {
3965    type Error = RpcError;
3966    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3967        if let ResultFromClient::CreateMessageResult(result) = value {
3968            Ok(result)
3969        } else {
3970            Err(RpcError::internal_error().with_message("Not a CreateMessageResult".to_string()))
3971        }
3972    }
3973}
3974impl TryFrom<ResultFromClient> for ListRootsResult {
3975    type Error = RpcError;
3976    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3977        if let ResultFromClient::ListRootsResult(result) = value {
3978            Ok(result)
3979        } else {
3980            Err(RpcError::internal_error().with_message("Not a ListRootsResult".to_string()))
3981        }
3982    }
3983}
3984impl TryFrom<ResultFromClient> for ElicitResult {
3985    type Error = RpcError;
3986    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3987        if let ResultFromClient::ElicitResult(result) = value {
3988            Ok(result)
3989        } else {
3990            Err(RpcError::internal_error().with_message("Not a ElicitResult".to_string()))
3991        }
3992    }
3993}
3994impl TryFrom<ResultFromClient> for CreateTaskResult {
3995    type Error = RpcError;
3996    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3997        if let ResultFromClient::CreateTaskResult(result) = value {
3998            Ok(result)
3999        } else {
4000            Err(RpcError::internal_error().with_message("Not a CreateTaskResult".to_string()))
4001        }
4002    }
4003}
4004impl TryFrom<ResultFromServer> for GenericResult {
4005    type Error = RpcError;
4006    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4007        match value {
4008            ResultFromServer::GetTaskPayloadResult(result) => Ok(result.into()),
4009            ResultFromServer::Result(result) => Ok(result),
4010            _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
4011        }
4012    }
4013}
4014impl TryFrom<ResultFromServer> for InitializeResult {
4015    type Error = RpcError;
4016    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4017        if let ResultFromServer::InitializeResult(result) = value {
4018            Ok(result)
4019        } else {
4020            Err(RpcError::internal_error().with_message("Not a InitializeResult".to_string()))
4021        }
4022    }
4023}
4024impl TryFrom<ResultFromServer> for ListResourcesResult {
4025    type Error = RpcError;
4026    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4027        if let ResultFromServer::ListResourcesResult(result) = value {
4028            Ok(result)
4029        } else {
4030            Err(RpcError::internal_error().with_message("Not a ListResourcesResult".to_string()))
4031        }
4032    }
4033}
4034impl TryFrom<ResultFromServer> for ListResourceTemplatesResult {
4035    type Error = RpcError;
4036    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4037        if let ResultFromServer::ListResourceTemplatesResult(result) = value {
4038            Ok(result)
4039        } else {
4040            Err(RpcError::internal_error().with_message("Not a ListResourceTemplatesResult".to_string()))
4041        }
4042    }
4043}
4044impl TryFrom<ResultFromServer> for ReadResourceResult {
4045    type Error = RpcError;
4046    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4047        if let ResultFromServer::ReadResourceResult(result) = value {
4048            Ok(result)
4049        } else {
4050            Err(RpcError::internal_error().with_message("Not a ReadResourceResult".to_string()))
4051        }
4052    }
4053}
4054impl TryFrom<ResultFromServer> for ListPromptsResult {
4055    type Error = RpcError;
4056    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4057        if let ResultFromServer::ListPromptsResult(result) = value {
4058            Ok(result)
4059        } else {
4060            Err(RpcError::internal_error().with_message("Not a ListPromptsResult".to_string()))
4061        }
4062    }
4063}
4064impl TryFrom<ResultFromServer> for GetPromptResult {
4065    type Error = RpcError;
4066    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4067        if let ResultFromServer::GetPromptResult(result) = value {
4068            Ok(result)
4069        } else {
4070            Err(RpcError::internal_error().with_message("Not a GetPromptResult".to_string()))
4071        }
4072    }
4073}
4074impl TryFrom<ResultFromServer> for ListToolsResult {
4075    type Error = RpcError;
4076    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4077        if let ResultFromServer::ListToolsResult(result) = value {
4078            Ok(result)
4079        } else {
4080            Err(RpcError::internal_error().with_message("Not a ListToolsResult".to_string()))
4081        }
4082    }
4083}
4084impl TryFrom<ResultFromServer> for CallToolResult {
4085    type Error = RpcError;
4086    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4087        if let ResultFromServer::CallToolResult(result) = value {
4088            Ok(result)
4089        } else {
4090            Err(RpcError::internal_error().with_message("Not a CallToolResult".to_string()))
4091        }
4092    }
4093}
4094impl TryFrom<ResultFromServer> for GetTaskResult {
4095    type Error = RpcError;
4096    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4097        if let ResultFromServer::GetTaskResult(result) = value {
4098            Ok(result)
4099        } else {
4100            Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
4101        }
4102    }
4103}
4104impl TryFrom<ResultFromServer> for GetTaskPayloadResult {
4105    type Error = RpcError;
4106    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4107        if let ResultFromServer::GetTaskPayloadResult(result) = value {
4108            Ok(result)
4109        } else {
4110            Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
4111        }
4112    }
4113}
4114impl TryFrom<ResultFromServer> for CancelTaskResult {
4115    type Error = RpcError;
4116    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4117        if let ResultFromServer::CancelTaskResult(result) = value {
4118            Ok(result)
4119        } else {
4120            Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
4121        }
4122    }
4123}
4124impl TryFrom<ResultFromServer> for ListTasksResult {
4125    type Error = RpcError;
4126    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4127        if let ResultFromServer::ListTasksResult(result) = value {
4128            Ok(result)
4129        } else {
4130            Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
4131        }
4132    }
4133}
4134impl TryFrom<ResultFromServer> for CompleteResult {
4135    type Error = RpcError;
4136    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4137        if let ResultFromServer::CompleteResult(result) = value {
4138            Ok(result)
4139        } else {
4140            Err(RpcError::internal_error().with_message("Not a CompleteResult".to_string()))
4141        }
4142    }
4143}
4144impl TryFrom<ResultFromServer> for CreateTaskResult {
4145    type Error = RpcError;
4146    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4147        if let ResultFromServer::CreateTaskResult(result) = value {
4148            Ok(result)
4149        } else {
4150            Err(RpcError::internal_error().with_message("Not a CreateTaskResult".to_string()))
4151        }
4152    }
4153}
4154impl ContentBlock {
4155    ///Create a ContentBlock::TextContent
4156    pub fn text_content(text: ::std::string::String) -> Self {
4157        TextContent::new(text, None, None).into()
4158    }
4159    ///Create a ContentBlock::ImageContent
4160    pub fn image_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
4161        ImageContent::new(data, mime_type, None, None).into()
4162    }
4163    ///Create a ContentBlock::AudioContent
4164    pub fn audio_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
4165        AudioContent::new(data, mime_type, None, None).into()
4166    }
4167    ///Create a ContentBlock::ResourceLink
4168    pub fn resource_link(value: ResourceLink) -> Self {
4169        value.into()
4170    }
4171    ///Create a ContentBlock::EmbeddedResource
4172    pub fn embedded_resource(resource: EmbeddedResourceResource) -> Self {
4173        EmbeddedResource::new(resource, None, None).into()
4174    }
4175    ///Returns the content type as a string based on the variant of `ContentBlock`
4176    pub fn content_type(&self) -> &str {
4177        match self {
4178            ContentBlock::TextContent(text_content) => text_content.type_(),
4179            ContentBlock::ImageContent(image_content) => image_content.type_(),
4180            ContentBlock::AudioContent(audio_content) => audio_content.type_(),
4181            ContentBlock::ResourceLink(resource_link) => resource_link.type_(),
4182            ContentBlock::EmbeddedResource(embedded_resource) => embedded_resource.type_(),
4183        }
4184    }
4185    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4186    pub fn as_text_content(&self) -> std::result::Result<&TextContent, RpcError> {
4187        match &self {
4188            ContentBlock::TextContent(text_content) => Ok(text_content),
4189            _ => Err(RpcError::internal_error().with_message(format!(
4190                "Invalid conversion, \"{}\" is not a {}",
4191                self.content_type(),
4192                "TextContent"
4193            ))),
4194        }
4195    }
4196    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4197    pub fn as_image_content(&self) -> std::result::Result<&ImageContent, RpcError> {
4198        match &self {
4199            ContentBlock::ImageContent(image_content) => Ok(image_content),
4200            _ => Err(RpcError::internal_error().with_message(format!(
4201                "Invalid conversion, \"{}\" is not a {}",
4202                self.content_type(),
4203                "ImageContent"
4204            ))),
4205        }
4206    }
4207    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4208    pub fn as_audio_content(&self) -> std::result::Result<&AudioContent, RpcError> {
4209        match &self {
4210            ContentBlock::AudioContent(audio_content) => Ok(audio_content),
4211            _ => Err(RpcError::internal_error().with_message(format!(
4212                "Invalid conversion, \"{}\" is not a {}",
4213                self.content_type(),
4214                "AudioContent"
4215            ))),
4216        }
4217    }
4218    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4219    pub fn as_resource_link(&self) -> std::result::Result<&ResourceLink, RpcError> {
4220        match &self {
4221            ContentBlock::ResourceLink(resource_link) => Ok(resource_link),
4222            _ => Err(RpcError::internal_error().with_message(format!(
4223                "Invalid conversion, \"{}\" is not a {}",
4224                self.content_type(),
4225                "ResourceLink"
4226            ))),
4227        }
4228    }
4229    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4230    pub fn as_embedded_resource(&self) -> std::result::Result<&EmbeddedResource, RpcError> {
4231        match &self {
4232            ContentBlock::EmbeddedResource(embedded_resource) => Ok(embedded_resource),
4233            _ => Err(RpcError::internal_error().with_message(format!(
4234                "Invalid conversion, \"{}\" is not a {}",
4235                self.content_type(),
4236                "EmbeddedResource"
4237            ))),
4238        }
4239    }
4240}
4241impl CallToolResult {
4242    pub fn text_content(content: Vec<TextContent>) -> Self {
4243        Self {
4244            content: content.into_iter().map(Into::into).collect(),
4245            is_error: None,
4246            meta: None,
4247            structured_content: None,
4248        }
4249    }
4250    pub fn image_content(content: Vec<ImageContent>) -> Self {
4251        Self {
4252            content: content.into_iter().map(Into::into).collect(),
4253            is_error: None,
4254            meta: None,
4255            structured_content: None,
4256        }
4257    }
4258    pub fn audio_content(content: Vec<AudioContent>) -> Self {
4259        Self {
4260            content: content.into_iter().map(Into::into).collect(),
4261            is_error: None,
4262            meta: None,
4263            structured_content: None,
4264        }
4265    }
4266    pub fn resource_link(content: Vec<ResourceLink>) -> Self {
4267        Self {
4268            content: content.into_iter().map(Into::into).collect(),
4269            is_error: None,
4270            meta: None,
4271            structured_content: None,
4272        }
4273    }
4274    pub fn embedded_resource(content: Vec<EmbeddedResource>) -> Self {
4275        Self {
4276            content: content.into_iter().map(Into::into).collect(),
4277            is_error: None,
4278            meta: None,
4279            structured_content: None,
4280        }
4281    }
4282    /// Create a `CallToolResult` with an error, containing an error message in the content
4283    pub fn with_error(error: CallToolError) -> Self {
4284        Self {
4285            content: vec![ContentBlock::TextContent(TextContent::new(error.to_string(), None, None))],
4286            is_error: Some(true),
4287            meta: None,
4288            structured_content: None,
4289        }
4290    }
4291    /// Assigns metadata to the CallToolResult, enabling the inclusion of extra context or details.
4292    pub fn with_meta(mut self, meta: Option<serde_json::Map<String, Value>>) -> Self {
4293        self.meta = meta;
4294        self
4295    }
4296    /// Assigns structured_content to the CallToolResult
4297    pub fn with_structured_content(
4298        mut self,
4299        structured_content: ::serde_json::Map<::std::string::String, ::serde_json::Value>,
4300    ) -> Self {
4301        self.structured_content = Some(structured_content);
4302        self
4303    }
4304    /// Creates a new instance using the provided content blocks.
4305    ///
4306    /// This method initializes the structure with the given `content` and
4307    /// resets all optional fields (`is_error`, `meta`, and `structured_content`)
4308    /// to `None`.
4309    ///
4310    /// # Arguments
4311    ///
4312    /// * `content` - A vector of `ContentBlock` values to populate the instance.
4313    ///
4314    /// # Returns
4315    ///
4316    /// Returns a new instance containing the supplied content.
4317    pub fn from_content(content: Vec<ContentBlock>) -> Self {
4318        Self {
4319            content,
4320            is_error: None,
4321            meta: None,
4322            structured_content: None,
4323        }
4324    }
4325    /// Adds a single content block to the instance.
4326    ///
4327    /// This method appends the provided `content` to the existing `content` vector
4328    /// and returns the updated instance, enabling a builder-style pattern.
4329    pub fn add_content(mut self, content: ContentBlock) -> Self {
4330        self.content.push(content);
4331        self
4332    }
4333}
4334impl ServerRequest {
4335    pub fn request_id(&self) -> &RequestId {
4336        match self {
4337            ServerRequest::PingRequest(request) => &request.id,
4338            ServerRequest::GetTaskRequest(request) => &request.id,
4339            ServerRequest::GetTaskPayloadRequest(request) => &request.id,
4340            ServerRequest::CancelTaskRequest(request) => &request.id,
4341            ServerRequest::ListTasksRequest(request) => &request.id,
4342            ServerRequest::CreateMessageRequest(request) => &request.id,
4343            ServerRequest::ListRootsRequest(request) => &request.id,
4344            ServerRequest::ElicitRequest(request) => &request.id,
4345        }
4346    }
4347}
4348impl ClientRequest {
4349    pub fn request_id(&self) -> &RequestId {
4350        match self {
4351            ClientRequest::InitializeRequest(request) => &request.id,
4352            ClientRequest::PingRequest(request) => &request.id,
4353            ClientRequest::ListResourcesRequest(request) => &request.id,
4354            ClientRequest::ListResourceTemplatesRequest(request) => &request.id,
4355            ClientRequest::ReadResourceRequest(request) => &request.id,
4356            ClientRequest::SubscribeRequest(request) => &request.id,
4357            ClientRequest::UnsubscribeRequest(request) => &request.id,
4358            ClientRequest::ListPromptsRequest(request) => &request.id,
4359            ClientRequest::GetPromptRequest(request) => &request.id,
4360            ClientRequest::ListToolsRequest(request) => &request.id,
4361            ClientRequest::CallToolRequest(request) => &request.id,
4362            ClientRequest::GetTaskRequest(request) => &request.id,
4363            ClientRequest::GetTaskPayloadRequest(request) => &request.id,
4364            ClientRequest::CancelTaskRequest(request) => &request.id,
4365            ClientRequest::ListTasksRequest(request) => &request.id,
4366            ClientRequest::SetLevelRequest(request) => &request.id,
4367            ClientRequest::CompleteRequest(request) => &request.id,
4368        }
4369    }
4370}
4371impl From<&str> for IconTheme {
4372    fn from(s: &str) -> Self {
4373        match s {
4374            "dark" => Self::Dark,
4375            "light" => Self::Light,
4376            _ => Self::Light,
4377        }
4378    }
4379}
4380impl From<&str> for ElicitResultContent {
4381    fn from(value: &str) -> Self {
4382        Self::Primitive(ElicitResultContentPrimitive::String(value.to_string()))
4383    }
4384}
4385impl From<&str> for ElicitResultContentPrimitive {
4386    fn from(value: &str) -> Self {
4387        ElicitResultContentPrimitive::String(value.to_string())
4388    }
4389}
4390impl From<String> for ElicitResultContentPrimitive {
4391    fn from(value: String) -> Self {
4392        ElicitResultContentPrimitive::String(value)
4393    }
4394}
4395impl From<String> for ElicitResultContent {
4396    fn from(value: String) -> Self {
4397        Self::Primitive(ElicitResultContentPrimitive::String(value))
4398    }
4399}
4400impl From<Vec<&str>> for ElicitResultContent {
4401    fn from(value: Vec<&str>) -> Self {
4402        Self::StringArray(value.iter().map(|v| v.to_string()).collect())
4403    }
4404}
4405impl From<i64> for ElicitResultContent {
4406    fn from(value: i64) -> Self {
4407        Self::Primitive(value.into())
4408    }
4409}
4410impl CallToolRequestParams {
4411    pub fn new<T>(tool_name: T) -> Self
4412    where
4413        T: ToString,
4414    {
4415        Self {
4416            name: tool_name.to_string(),
4417            arguments: None,
4418            meta: None,
4419            task: None,
4420        }
4421    }
4422    /// Sets the arguments for the tool call.
4423    pub fn with_arguments(mut self, arguments: serde_json::Map<String, Value>) -> Self {
4424        self.arguments = Some(arguments);
4425        self
4426    }
4427    /// Assigns metadata to the CallToolRequestParams, enabling the inclusion of extra context or details.
4428    pub fn with_meta(mut self, meta: CallToolMeta) -> Self {
4429        self.meta = Some(meta);
4430        self
4431    }
4432    /// Set task metadata , requesting task-augmented execution for this request
4433    pub fn with_task(mut self, task: TaskMetadata) -> Self {
4434        self.task = Some(task);
4435        self
4436    }
4437}
4438/// END AUTO GENERATED
4439#[cfg(test)]
4440mod tests {
4441    use super::*;
4442    use serde_json::json;
4443
4444    #[test]
4445    fn test_detect_message_type() {
4446        // standard request
4447        let message = ClientJsonrpcRequest::new(RequestId::Integer(0), RequestFromClient::PingRequest(None));
4448        let result = detect_message_type(&json!(message));
4449        assert!(matches!(result, MessageTypes::Request));
4450
4451        // custom request
4452
4453        let result = detect_message_type(&json!({
4454        "id":0,
4455        "method":"add_numbers",
4456        "params":{},
4457        "jsonrpc":"2.0"
4458        }));
4459        assert!(matches!(result, MessageTypes::Request));
4460
4461        // standard notification
4462        let message = ClientJsonrpcNotification::new(NotificationFromClient::RootsListChangedNotification(None));
4463        let result = detect_message_type(&json!(message));
4464        assert!(matches!(result, MessageTypes::Notification));
4465
4466        // custom notification
4467        let result = detect_message_type(&json!({
4468            "method":"notifications/email_sent",
4469            "jsonrpc":"2.0"
4470        }));
4471        assert!(matches!(result, MessageTypes::Notification));
4472
4473        // standard response
4474        let message = ClientJsonrpcResponse::new(
4475            RequestId::Integer(0),
4476            ListRootsResult {
4477                meta: None,
4478                roots: vec![],
4479            }
4480            .into(),
4481        );
4482        let result = detect_message_type(&json!(message));
4483        assert!(matches!(result, MessageTypes::Response));
4484
4485        //custom response
4486
4487        let result = detect_message_type(&json!({
4488            "id":1,
4489            "jsonrpc":"2.0",
4490            "result":"{}",
4491        }));
4492        assert!(matches!(result, MessageTypes::Response));
4493
4494        // error message
4495        let message = JsonrpcErrorResponse::create(
4496            Some(RequestId::Integer(0)),
4497            RpcErrorCodes::INVALID_PARAMS,
4498            "Invalid params!".to_string(),
4499            None,
4500        );
4501        let result = detect_message_type(&json!(message));
4502        assert!(matches!(result, MessageTypes::Error));
4503
4504        // default
4505        let result = detect_message_type(&json!({}));
4506        assert!(matches!(result, MessageTypes::Request));
4507    }
4508}