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