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
1973#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1974#[serde(untagged)]
1975#[allow(clippy::large_enum_variant)]
1976pub enum ClientMessages {
1977    Single(ClientMessage),
1978    Batch(Vec<ClientMessage>),
1979}
1980
1981impl ClientMessages {
1982    pub fn is_batch(&self) -> bool {
1983        matches!(self, ClientMessages::Batch(_))
1984    }
1985
1986    pub fn includes_request(&self) -> bool {
1987        match self {
1988            ClientMessages::Single(client_message) => client_message.is_request(),
1989            ClientMessages::Batch(client_messages) => client_messages.iter().any(ClientMessage::is_request),
1990        }
1991    }
1992
1993    pub fn as_single(self) -> result::Result<ClientMessage, SdkError> {
1994        match self {
1995            ClientMessages::Single(client_message) => Ok(client_message),
1996            ClientMessages::Batch(_) => Err(SdkError::internal_error()
1997                .with_message("Error: cannot convert ClientMessages::Batch to ClientMessage::Single")),
1998        }
1999    }
2000    pub fn as_batch(self) -> result::Result<Vec<ClientMessage>, SdkError> {
2001        match self {
2002            ClientMessages::Single(_) => Err(SdkError::internal_error()
2003                .with_message("Error: cannot convert ClientMessage::Single to ClientMessages::Batch")),
2004            ClientMessages::Batch(client_messages) => Ok(client_messages),
2005        }
2006    }
2007}
2008
2009impl From<ClientMessage> for ClientMessages {
2010    fn from(value: ClientMessage) -> Self {
2011        Self::Single(value)
2012    }
2013}
2014
2015impl From<Vec<ClientMessage>> for ClientMessages {
2016    fn from(value: Vec<ClientMessage>) -> Self {
2017        Self::Batch(value)
2018    }
2019}
2020
2021impl Display for ClientMessages {
2022    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2023        write!(
2024            f,
2025            "{}",
2026            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
2027        )
2028    }
2029}
2030
2031#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2032#[serde(untagged)]
2033#[allow(clippy::large_enum_variant)]
2034pub enum ServerMessages {
2035    Single(ServerMessage),
2036    Batch(Vec<ServerMessage>),
2037}
2038
2039impl ServerMessages {
2040    pub fn is_batch(&self) -> bool {
2041        matches!(self, ServerMessages::Batch(_))
2042    }
2043
2044    pub fn includes_request(&self) -> bool {
2045        match self {
2046            ServerMessages::Single(server_message) => server_message.is_request(),
2047            ServerMessages::Batch(server_messages) => server_messages.iter().any(ServerMessage::is_request),
2048        }
2049    }
2050
2051    pub fn as_single(self) -> result::Result<ServerMessage, SdkError> {
2052        match self {
2053            ServerMessages::Single(server_message) => Ok(server_message),
2054            ServerMessages::Batch(_) => Err(SdkError::internal_error()
2055                .with_message("Error: cannot convert ServerMessages::Batch to ServerMessage::Single")),
2056        }
2057    }
2058    pub fn as_batch(self) -> result::Result<Vec<ServerMessage>, SdkError> {
2059        match self {
2060            ServerMessages::Single(_) => Err(SdkError::internal_error()
2061                .with_message("Error: cannot convert ServerMessage::Single to ServerMessages::Batch")),
2062            ServerMessages::Batch(server_messages) => Ok(server_messages),
2063        }
2064    }
2065}
2066
2067impl From<ServerMessage> for ServerMessages {
2068    fn from(value: ServerMessage) -> Self {
2069        Self::Single(value)
2070    }
2071}
2072
2073impl From<Vec<ServerMessage>> for ServerMessages {
2074    fn from(value: Vec<ServerMessage>) -> Self {
2075        Self::Batch(value)
2076    }
2077}
2078
2079impl Display for ServerMessages {
2080    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2081        write!(
2082            f,
2083            "{}",
2084            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
2085        )
2086    }
2087}
2088
2089#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2090#[serde(untagged)]
2091#[allow(clippy::large_enum_variant)]
2092pub enum MessagesFromServer {
2093    Single(MessageFromServer),
2094    Batch(Vec<MessageFromServer>),
2095}
2096
2097impl MessagesFromServer {
2098    pub fn is_batch(&self) -> bool {
2099        matches!(self, MessagesFromServer::Batch(_))
2100    }
2101
2102    pub fn includes_request(&self) -> bool {
2103        match self {
2104            MessagesFromServer::Single(server_message) => server_message.is_request(),
2105            MessagesFromServer::Batch(server_messages) => server_messages.iter().any(MessageFromServer::is_request),
2106        }
2107    }
2108
2109    pub fn as_single(self) -> result::Result<MessageFromServer, SdkError> {
2110        match self {
2111            MessagesFromServer::Single(server_message) => Ok(server_message),
2112            MessagesFromServer::Batch(_) => Err(SdkError::internal_error()
2113                .with_message("Error: cannot convert MessagesFromServer::Batch to MessageFromServer::Single")),
2114        }
2115    }
2116    pub fn as_batch(self) -> result::Result<Vec<MessageFromServer>, SdkError> {
2117        match self {
2118            MessagesFromServer::Single(_) => Err(SdkError::internal_error()
2119                .with_message("Error: cannot convert MessageFromServer::Single to MessagesFromServer::Batch")),
2120            MessagesFromServer::Batch(server_messages) => Ok(server_messages),
2121        }
2122    }
2123}
2124
2125impl From<MessageFromServer> for MessagesFromServer {
2126    fn from(value: MessageFromServer) -> Self {
2127        Self::Single(value)
2128    }
2129}
2130
2131impl From<Vec<MessageFromServer>> for MessagesFromServer {
2132    fn from(value: Vec<MessageFromServer>) -> Self {
2133        Self::Batch(value)
2134    }
2135}
2136
2137#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2138#[serde(untagged)]
2139#[allow(clippy::large_enum_variant)]
2140pub enum MessagesFromClient {
2141    Single(MessageFromClient),
2142    Batch(Vec<MessageFromClient>),
2143}
2144
2145impl MessagesFromClient {
2146    pub fn is_batch(&self) -> bool {
2147        matches!(self, MessagesFromClient::Batch(_))
2148    }
2149
2150    pub fn includes_request(&self) -> bool {
2151        match self {
2152            MessagesFromClient::Single(server_message) => server_message.is_request(),
2153            MessagesFromClient::Batch(server_messages) => server_messages.iter().any(MessageFromClient::is_request),
2154        }
2155    }
2156
2157    pub fn as_single(self) -> result::Result<MessageFromClient, SdkError> {
2158        match self {
2159            MessagesFromClient::Single(server_message) => Ok(server_message),
2160            MessagesFromClient::Batch(_) => Err(SdkError::internal_error()
2161                .with_message("Error: cannot convert MessagesFromClient::Batch to MessageFromClient::Single")),
2162        }
2163    }
2164    pub fn as_batch(self) -> result::Result<Vec<MessageFromClient>, SdkError> {
2165        match self {
2166            MessagesFromClient::Single(_) => Err(SdkError::internal_error()
2167                .with_message("Error: cannot convert MessageFromClient::Single to MessagesFromClient::Batch")),
2168            MessagesFromClient::Batch(server_messages) => Ok(server_messages),
2169        }
2170    }
2171}
2172
2173impl From<MessageFromClient> for MessagesFromClient {
2174    fn from(value: MessageFromClient) -> Self {
2175        Self::Single(value)
2176    }
2177}
2178
2179impl From<Vec<MessageFromClient>> for MessagesFromClient {
2180    fn from(value: Vec<MessageFromClient>) -> Self {
2181        Self::Batch(value)
2182    }
2183}
2184
2185#[derive(Debug)]
2186pub struct StringSchemaFormatError {
2187    invalid_value: String,
2188}
2189
2190impl core::fmt::Display for StringSchemaFormatError {
2191    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2192        write!(f, "Invalid string schema format: '{}'", self.invalid_value)
2193    }
2194}
2195
2196impl std::error::Error for StringSchemaFormatError {}
2197
2198impl FromStr for StringSchemaFormat {
2199    type Err = StringSchemaFormatError;
2200
2201    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2202        match s {
2203            "date" => Ok(Self::Date),
2204            "date-time" => Ok(Self::DateTime),
2205            "email" => Ok(Self::Email),
2206            "uri" => Ok(Self::Uri),
2207            _ => Err(StringSchemaFormatError {
2208                invalid_value: s.to_string(),
2209            }),
2210        }
2211    }
2212}
2213
2214// Helper: handle all single-select enum variants
2215fn try_from_enum_schema(map: &serde_json::Map<String, Value>) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2216    // All enum schemas should have type: "string" (or missing, but usually present)
2217    let has_one_of = map.contains_key("oneOf");
2218    let has_enum = map.contains_key("enum");
2219    let has_enum_names = map.contains_key("enumNames");
2220
2221    if has_one_of {
2222        let schema: TitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2223            RpcError::parse_error().with_message(format!("Failed to parse TitledSingleSelectEnumSchema: {e}"))
2224        })?;
2225
2226        Ok(PrimitiveSchemaDefinition::TitledSingleSelectEnumSchema(schema))
2227    } else if has_enum && has_enum_names {
2228        let schema: LegacyTitledEnumSchema = serde_json::from_value(Value::Object(map.clone()))
2229            .map_err(|e| RpcError::parse_error().with_message(format!("Failed to parse LegacyTitledEnumSchema: {e}")))?;
2230        Ok(PrimitiveSchemaDefinition::LegacyTitledEnumSchema(schema))
2231    } else if has_enum {
2232        let schema: UntitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2233            RpcError::parse_error().with_message(format!("Failed to parse UntitledSingleSelectEnumSchema: {e}"))
2234        })?;
2235        Ok(PrimitiveSchemaDefinition::UntitledSingleSelectEnumSchema(schema))
2236    } else {
2237        Err(RpcError::parse_error().with_message("Invalid enum schema: missing 'enum' or 'oneOf'".to_string()))
2238    }
2239}
2240
2241// Helper: handle multi-select (array) enum schemas
2242fn try_from_multi_select_schema(
2243    map: &serde_json::Map<String, Value>,
2244) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2245    let items = map
2246        .get("items")
2247        .ok_or(RpcError::parse_error().with_message("Array schema missing 'items' field".to_string()))?;
2248
2249    let items_obj = items
2250        .as_object()
2251        .ok_or(RpcError::parse_error().with_message("Field 'items' must be an object".to_string()))?;
2252
2253    if items_obj.contains_key("anyOf") {
2254        let schema: TitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2255            RpcError::parse_error().with_message(format!("Failed to parse TitledMultiSelectEnumSchema: {e}"))
2256        })?;
2257        Ok(PrimitiveSchemaDefinition::TitledMultiSelectEnumSchema(schema))
2258    } else if items_obj.contains_key("enum") {
2259        let schema: UntitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2260            RpcError::parse_error().with_message(format!("Failed to parse UntitledMultiSelectEnumSchema: {e}"))
2261        })?;
2262        Ok(PrimitiveSchemaDefinition::UntitledMultiSelectEnumSchema(schema))
2263    } else {
2264        Err(RpcError::parse_error()
2265            .with_message("Array schema 'items' must contain 'enum' or 'oneOf' to be a multi-select enum".to_string()))
2266    }
2267}
2268
2269impl TryFrom<&serde_json::Map<String, Value>> for PrimitiveSchemaDefinition {
2270    type Error = RpcError;
2271
2272    fn try_from(value: &serde_json::Map<String, serde_json::Value>) -> result::Result<Self, Self::Error> {
2273        // 1. First: detect enum schemas (they look like strings but have enum/oneOf)
2274        if value.contains_key("enum") || value.contains_key("oneOf") {
2275            return try_from_enum_schema(value);
2276        }
2277
2278        // 2. Then: detect multi-select array schemas (type: "array" + items with enum/oneOf)
2279        if value.get("type").and_then(|v| v.as_str()) == Some("array") {
2280            return try_from_multi_select_schema(value);
2281        }
2282
2283        let input_type = value
2284            .get("type")
2285            .and_then(|v| v.as_str())
2286            .or_else(|| value.get("oneOf").map(|_| "enum")) // if "oneOf" exists, return "enum"
2287            .ok_or_else(|| {
2288                RpcError::parse_error().with_message("'type' is missing and data type is not supported!".to_string())
2289            })?;
2290
2291        let description = value.get("description").and_then(|v| v.as_str().map(|s| s.to_string()));
2292        let title = value.get("title").and_then(|v| v.as_str().map(|s| s.to_string()));
2293
2294        let schema_definition: PrimitiveSchemaDefinition = match input_type {
2295            "string" => {
2296                let max_length = value.get("maxLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2297                let min_length = value.get("minLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2298                let default = value.get("default").and_then(|v| v.as_str().map(|s| s.to_string()));
2299
2300                let format_str = value.get("format").and_then(|v| v.as_str());
2301                let format = format_str.and_then(|s| StringSchemaFormat::from_str(s).ok());
2302
2303                PrimitiveSchemaDefinition::StringSchema(StringSchema::new(
2304                    default,
2305                    description,
2306                    format,
2307                    max_length,
2308                    min_length,
2309                    title,
2310                ))
2311            }
2312            "number" | "integer" => {
2313                let maximum = value.get("maximum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2314                let minimum = value.get("minimum").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2315                let default = value.get("default").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2316
2317                PrimitiveSchemaDefinition::NumberSchema(NumberSchema {
2318                    default,
2319                    description,
2320                    maximum,
2321                    minimum,
2322                    title,
2323                    type_: if input_type == "integer" {
2324                        NumberSchemaType::Integer
2325                    } else {
2326                        NumberSchemaType::Number
2327                    },
2328                })
2329            }
2330            "boolean" => {
2331                let default = value.get("default").and_then(|v| v.as_bool().map(|s| s.to_owned()));
2332                PrimitiveSchemaDefinition::BooleanSchema(BooleanSchema::new(default, description, title))
2333            }
2334            other => {
2335                return Err(RpcError::parse_error().with_message(format!("'{other}' type is not currently supported")));
2336            }
2337        };
2338
2339        Ok(schema_definition)
2340    }
2341}
2342
2343impl RequestFromServer {
2344    pub fn is_task_augmented(&self) -> bool {
2345        match self {
2346            RequestFromServer::CreateMessageRequest(create_message_request_params) => {
2347                create_message_request_params.is_task_augmented()
2348            }
2349            RequestFromServer::ElicitRequest(elicit_request_params) => elicit_request_params.is_task_augmented(),
2350            _ => false,
2351        }
2352    }
2353}
2354
2355impl MessageFromServer {
2356    pub fn is_task_augmented(&self) -> bool {
2357        match self {
2358            MessageFromServer::RequestFromServer(request_from_server) => request_from_server.is_task_augmented(),
2359            _ => false,
2360        }
2361    }
2362}
2363
2364impl CallToolRequest {
2365    pub fn is_task_augmented(&self) -> bool {
2366        self.params.is_task_augmented()
2367    }
2368}
2369
2370impl CallToolRequestParams {
2371    pub fn is_task_augmented(&self) -> bool {
2372        self.task.is_some()
2373    }
2374}
2375
2376impl CreateMessageRequestParams {
2377    pub fn is_task_augmented(&self) -> bool {
2378        self.task.is_some()
2379    }
2380}
2381
2382impl ElicitRequestParams {
2383    pub fn is_task_augmented(&self) -> bool {
2384        match self {
2385            ElicitRequestParams::UrlParams(elicit_request_url_params) => elicit_request_url_params.task.is_some(),
2386            ElicitRequestParams::FormParams(elicit_request_form_params) => elicit_request_form_params.task.is_some(),
2387        }
2388    }
2389
2390    pub fn message(&self) -> &str {
2391        match self {
2392            ElicitRequestParams::UrlParams(elicit_request_url_params) => elicit_request_url_params.message.as_str(),
2393            ElicitRequestParams::FormParams(elicit_request_form_params) => elicit_request_form_params.message.as_str(),
2394        }
2395    }
2396
2397    /// Set task metadata , requesting task-augmented execution for this request
2398    pub fn with_task(mut self, task: TaskMetadata) -> Self {
2399        match &mut self {
2400            ElicitRequestParams::UrlParams(params) => {
2401                params.task = Some(task);
2402            }
2403            ElicitRequestParams::FormParams(params) => {
2404                params.task = Some(task);
2405            }
2406        }
2407        self
2408    }
2409}
2410
2411impl ElicitRequestUrlParams {
2412    /// Set task metadata , requesting task-augmented execution for this request
2413    pub fn with_task(mut self, task: TaskMetadata) -> Self {
2414        self.task = Some(task);
2415        self
2416    }
2417}
2418
2419impl ElicitRequestFormParams {
2420    /// Set task metadata , requesting task-augmented execution for this request
2421    pub fn with_task(mut self, task: TaskMetadata) -> Self {
2422        self.task = Some(task);
2423        self
2424    }
2425}
2426
2427impl ServerCapabilities {
2428    /// Returns `true` if the server supports listing tasks.
2429    ///
2430    /// This is determined by whether the `list` capability is present.
2431    pub fn can_list_tasks(&self) -> bool {
2432        self.tasks.as_ref().is_some_and(|tasks| tasks.can_list_tasks())
2433    }
2434
2435    /// Returns `true` if the server supports canceling tasks.
2436    ///
2437    /// This is determined by whether the `cancel` capability is present.
2438    pub fn can_cancel_tasks(&self) -> bool {
2439        self.tasks.as_ref().is_some_and(|tasks| tasks.can_cancel_tasks())
2440    }
2441
2442    /// Returns `true` if the server supports task-augmented tools/call requests
2443    pub fn can_run_task_augmented_tools(&self) -> bool {
2444        self.tasks.as_ref().is_some_and(|tasks| tasks.can_run_task_augmented_tools())
2445    }
2446
2447    pub fn can_handle_request(&self, client_request: &ClientJsonrpcRequest) -> std::result::Result<(), RpcError> {
2448        let request_method = client_request.method();
2449
2450        // Helper function for creating error messages
2451        fn create_error(capability: &str, method: &str) -> RpcError {
2452            RpcError::internal_error().with_message(create_unsupported_capability_message("Server", capability, method))
2453        }
2454
2455        match client_request {
2456            ClientJsonrpcRequest::SetLevelRequest(_) if self.logging.is_none() => {
2457                return Err(create_error("logging", request_method));
2458            }
2459            ClientJsonrpcRequest::GetPromptRequest(_) | ClientJsonrpcRequest::ListPromptsRequest(_)
2460                if self.prompts.is_none() =>
2461            {
2462                return Err(create_error("prompts", request_method));
2463            }
2464
2465            ClientJsonrpcRequest::ListResourcesRequest(_)
2466            | ClientJsonrpcRequest::ListResourceTemplatesRequest(_)
2467            | ClientJsonrpcRequest::ReadResourceRequest(_)
2468            | ClientJsonrpcRequest::SubscribeRequest(_)
2469            | ClientJsonrpcRequest::UnsubscribeRequest(_)
2470                if self.resources.is_none() =>
2471            {
2472                return Err(create_error("resources", request_method));
2473            }
2474
2475            ClientJsonrpcRequest::CallToolRequest(call_tool_request)
2476                if call_tool_request.is_task_augmented() && !self.can_run_task_augmented_tools() =>
2477            {
2478                return Err(create_error("Task-augmented tool call", request_method));
2479            }
2480
2481            ClientJsonrpcRequest::CallToolRequest(_) | ClientJsonrpcRequest::ListToolsRequest(_) if self.tools.is_none() => {
2482                return Err(create_error("tools", request_method));
2483            }
2484            ClientJsonrpcRequest::CompleteRequest(_) if self.completions.is_none() => {
2485                return Err(create_error("completions", request_method));
2486            }
2487
2488            ClientJsonrpcRequest::GetTaskRequest(_)
2489            | ClientJsonrpcRequest::GetTaskPayloadRequest(_)
2490            | ClientJsonrpcRequest::CancelTaskRequest(_)
2491            | ClientJsonrpcRequest::ListTasksRequest(_)
2492                if self.tasks.is_none() =>
2493            {
2494                return Err(create_error("task", request_method));
2495            }
2496            ClientJsonrpcRequest::ListTasksRequest(_) if !self.can_list_tasks() => {
2497                return Err(create_error("listing tasks", request_method));
2498            }
2499            ClientJsonrpcRequest::CancelTaskRequest(_) if !self.can_cancel_tasks() => {
2500                return Err(create_error("task cancellation", request_method));
2501            }
2502            _ => {}
2503        };
2504        Ok(())
2505    }
2506
2507    /// Asserts that the server supports the requested notification.
2508    ///
2509    /// Verifies that the server advertises support for the notification type,
2510    /// allowing callers to avoid sending notifications that the server does not
2511    /// support. This can be used to prevent issuing requests to peers that lack
2512    /// the required capability.
2513    pub fn can_accept_notification(&self, notification_method: &str) -> std::result::Result<(), RpcError> {
2514        let entity = "Server";
2515
2516        if LoggingMessageNotification::method_value().eq(notification_method) && self.logging.is_none() {
2517            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2518                entity,
2519                "logging",
2520                notification_method,
2521            )));
2522        }
2523
2524        if [
2525            ResourceUpdatedNotification::method_value(),
2526            ResourceListChangedNotification::method_value(),
2527        ]
2528        .contains(&notification_method)
2529            && self.resources.is_none()
2530        {
2531            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2532                entity,
2533                "notifying about resources",
2534                notification_method,
2535            )));
2536        }
2537
2538        if ToolListChangedNotification::method_value().eq(notification_method) && self.tools.is_none() {
2539            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2540                entity,
2541                "notifying of tool list changes",
2542                notification_method,
2543            )));
2544        }
2545
2546        if PromptListChangedNotification::method_value().eq(notification_method) && self.prompts.is_none() {
2547            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2548                entity,
2549                "notifying of prompt list changes",
2550                notification_method,
2551            )));
2552        }
2553
2554        Ok(())
2555    }
2556}
2557
2558impl ServerTasks {
2559    /// Returns `true` if the server supports listing tasks.
2560    ///
2561    /// This is determined by whether the `list` capability is present.
2562    pub fn can_list_tasks(&self) -> bool {
2563        self.list.is_some()
2564    }
2565
2566    /// Returns `true` if the server supports canceling tasks.
2567    ///
2568    /// This is determined by whether the `cancel` capability is present.
2569    pub fn can_cancel_tasks(&self) -> bool {
2570        self.cancel.is_some()
2571    }
2572
2573    /// Returns `true` if the server supports task-augmented tools/call requests
2574    pub fn can_run_task_augmented_tools(&self) -> bool {
2575        if let Some(requests) = self.requests.as_ref() {
2576            if let Some(tools) = requests.tools.as_ref() {
2577                return tools.call.is_some();
2578            }
2579        }
2580        false
2581    }
2582}
2583
2584/// Formats an assertion error message for unsupported capabilities.
2585///
2586/// Constructs a string describing that a specific entity (e.g., server or client) lacks
2587/// support for a required capability, needed for a particular method.
2588///
2589/// # Arguments
2590/// - `entity`: The name of the entity (e.g., "Server" or "Client") that lacks support.
2591/// - `capability`: The name of the unsupported capability or tool.
2592/// - `method_name`: The name of the method requiring the capability.
2593///
2594/// # Returns
2595/// A formatted string detailing the unsupported capability error.
2596///
2597/// # Examples
2598/// ```ignore
2599/// let msg = create_unsupported_capability_message("Server", "tools", rust_mcp_schema::ListResourcesRequest::method_value());
2600/// assert_eq!(msg, "Server does not support resources (required for resources/list)");
2601/// ```
2602fn create_unsupported_capability_message(entity: &str, capability: &str, method_name: &str) -> String {
2603    format!("{entity} does not support {capability} (required for {method_name})")
2604}
2605
2606impl ClientCapabilities {
2607    /// Returns `true` if the server supports listing tasks.
2608    ///
2609    /// This is determined by whether the `list` capability is present.
2610    pub fn can_list_tasks(&self) -> bool {
2611        self.tasks.as_ref().is_some_and(|task| task.can_list_tasks())
2612    }
2613
2614    /// Returns `true` if the server supports canceling tasks.
2615    ///
2616    /// This is determined by whether the `cancel` capability is present.
2617    pub fn can_cancel_tasks(&self) -> bool {
2618        self.tasks.as_ref().is_some_and(|task| task.can_cancel_tasks())
2619    }
2620
2621    /// Returns `true` if the client can request elicitation.
2622    pub fn can_accept_elicitation_task(&self) -> bool {
2623        self.tasks.as_ref().is_some_and(|task| task.can_accept_elicitation_task())
2624    }
2625
2626    /// Returns `true` if the client can request message sampling.
2627    pub fn can_accept_sampling_task(&self) -> bool {
2628        self.tasks.as_ref().is_some_and(|task| task.can_accept_sampling_task())
2629    }
2630
2631    pub fn can_handle_request(&self, server_jsonrpc_request: &ServerJsonrpcRequest) -> std::result::Result<(), RpcError> {
2632        let request_method = server_jsonrpc_request.method();
2633
2634        // Helper function for creating error messages
2635        fn create_error(capability: &str, method: &str) -> RpcError {
2636            RpcError::internal_error().with_message(create_unsupported_capability_message("Client", capability, method))
2637        }
2638
2639        match server_jsonrpc_request {
2640            ServerJsonrpcRequest::CreateMessageRequest(create_message_request) => {
2641                match self.sampling.as_ref() {
2642                    Some(samplig_capabilities) => {
2643                        //  include_context requested but not supported
2644                        if create_message_request.params.include_context.is_some() && samplig_capabilities.context.is_none()
2645                        {
2646                            return Err(create_error("context inclusion", request_method));
2647                        }
2648
2649                        if create_message_request.params.tool_choice.is_some() && samplig_capabilities.tools.is_none() {
2650                            return Err(create_error("tool choice", request_method));
2651                        }
2652                    }
2653                    None => {
2654                        return Err(create_error("sampling capability", request_method));
2655                    }
2656                }
2657
2658                if create_message_request.params.is_task_augmented() && !self.can_accept_sampling_task() {
2659                    return Err(create_error("sampling task", request_method));
2660                }
2661            }
2662            ServerJsonrpcRequest::ListRootsRequest(_) => {
2663                if self.roots.is_none() {
2664                    return Err(create_error("roots capability", request_method));
2665                }
2666            }
2667            ServerJsonrpcRequest::GetTaskRequest(_) | ServerJsonrpcRequest::GetTaskPayloadRequest(_) => {
2668                if self.tasks.is_none() {
2669                    return Err(create_error("Task", request_method));
2670                }
2671            }
2672            ServerJsonrpcRequest::CancelTaskRequest(_) => {
2673                if let Some(tasks) = self.tasks.as_ref() {
2674                    if !tasks.can_cancel_tasks() {
2675                        return Err(create_error("task cancellation", request_method));
2676                    }
2677                }
2678            }
2679            ServerJsonrpcRequest::ListTasksRequest(_) => {
2680                if let Some(tasks) = self.tasks.as_ref() {
2681                    if !tasks.can_list_tasks() {
2682                        return Err(create_error("listing tasks", request_method));
2683                    }
2684                }
2685            }
2686
2687            ServerJsonrpcRequest::ElicitRequest(elicit_request) => {
2688                if self.elicitation.is_none() {
2689                    return Err(create_error("input elicitation", request_method));
2690                }
2691
2692                if elicit_request.params.is_task_augmented() && !self.can_accept_elicitation_task() {
2693                    return Err(create_error("elicitation task", request_method));
2694                }
2695            }
2696            _ => {}
2697        }
2698        Ok(())
2699    }
2700
2701    pub fn can_accept_notification(&self, notification_method: &str) -> std::result::Result<(), RpcError> {
2702        let entity = "Client";
2703
2704        if RootsListChangedNotification::method_value().eq(notification_method) && self.roots.is_none() {
2705            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2706                entity,
2707                "roots list changed notifications",
2708                notification_method,
2709            )));
2710        }
2711
2712        Ok(())
2713    }
2714}
2715
2716impl ClientTasks {
2717    /// Returns `true` if the server supports listing tasks.
2718    ///
2719    /// This is determined by whether the `list` capability is present.
2720    pub fn can_list_tasks(&self) -> bool {
2721        self.list.is_some()
2722    }
2723
2724    /// Returns `true` if the server supports canceling tasks.
2725    ///
2726    /// This is determined by whether the `cancel` capability is present.
2727    pub fn can_cancel_tasks(&self) -> bool {
2728        self.cancel.is_some()
2729    }
2730
2731    /// Returns `true` if the client can request elicitation.
2732    pub fn can_accept_elicitation_task(&self) -> bool {
2733        if let Some(requests) = self.requests.as_ref() {
2734            if let Some(elicitation) = requests.elicitation.as_ref() {
2735                return elicitation.create.is_some();
2736            }
2737        }
2738        false
2739    }
2740
2741    /// Returns `true` if the client can request message sampling.
2742    pub fn can_accept_sampling_task(&self) -> bool {
2743        if let Some(requests) = self.requests.as_ref() {
2744            if let Some(sampling) = requests.sampling.as_ref() {
2745                return sampling.create_message.is_some();
2746            }
2747        }
2748        false
2749    }
2750}
2751
2752impl From<JsonrpcRequest> for CustomRequest {
2753    fn from(request: JsonrpcRequest) -> Self {
2754        Self {
2755            method: request.method,
2756            params: request.params,
2757        }
2758    }
2759}
2760
2761impl From<JsonrpcNotification> for CustomNotification {
2762    fn from(notification: JsonrpcNotification) -> Self {
2763        Self {
2764            method: notification.method,
2765            params: notification.params,
2766        }
2767    }
2768}
2769
2770/// Returns `true` if the task is in a terminal state.
2771/// Terminal states are states where the task has finished and will not change anymore.
2772impl TaskStatus {
2773    pub fn is_terminal(&self) -> bool {
2774        match self {
2775            TaskStatus::Cancelled | TaskStatus::Completed | TaskStatus::Failed => true,
2776            TaskStatus::InputRequired | TaskStatus::Working => false,
2777        }
2778    }
2779}
2780
2781/// Returns `true` if the task is in a terminal state.
2782/// Terminal states are states where the task has finished and will not change anymore.
2783impl Task {
2784    pub fn is_terminal(&self) -> bool {
2785        self.status.is_terminal()
2786    }
2787}
2788
2789impl GetTaskResult {
2790    pub fn is_terminal(&self) -> bool {
2791        self.status.is_terminal()
2792    }
2793}
2794
2795impl GetTaskPayloadResult {
2796    /// Retrieves the related task ID from the metadata, if it exists.
2797    ///
2798    /// This function looks for a key corresponding to the `RELATED_TASK_META_KEY` in the
2799    /// `meta` field of the struct. If the key exists and contains a string value, it returns
2800    /// it as an `Option<&str>`. If the key is missing or not a string, it returns `None`.
2801    ///
2802    /// # Returns
2803    /// - `Some(&str)` if a related task ID exists.
2804    /// - `None` if no related task ID is found.
2805    pub fn related_task_id(&self) -> Option<&str> {
2806        self.meta
2807            .as_ref()
2808            .and_then(|v| v.get(RELATED_TASK_META_KEY))
2809            .and_then(|v| v.as_str())
2810    }
2811
2812    /// Sets the related task ID in the metadata.
2813    ///
2814    /// This function inserts a `taskId` key with the provided `task_id` into the `meta` field.
2815    /// If the `meta` field is `None`, it creates a new `serde_json::Map` and assigns it to `meta`.
2816    /// The `task_id` is converted into a string before being inserted.
2817    ///
2818    /// # Type Parameters
2819    /// - `T`: The type of the `task_id`. It must implement `Into<String>` to allow flexible
2820    ///   conversion of various types (e.g., `&str`, `String`).
2821    ///
2822    /// # Arguments
2823    /// - `task_id`: The ID of the related task to set. This can be any type that can be converted
2824    ///   into a `String`.
2825    pub fn set_related_task_id<T>(&mut self, task_id: T)
2826    where
2827        T: Into<String>,
2828    {
2829        let task_json = json!({ "taskId": task_id.into() });
2830
2831        if let Some(meta) = &mut self.meta {
2832            meta.insert(RELATED_TASK_META_KEY.into(), task_json);
2833        } else {
2834            let mut new_meta = serde_json::Map::new();
2835            new_meta.insert(RELATED_TASK_META_KEY.into(), task_json);
2836            self.meta = Some(new_meta);
2837        }
2838    }
2839}
2840
2841pub trait McpMetaEx {
2842    /// Retrieves the related task ID from the metadata, if it exists.
2843    ///
2844    /// This function looks for a key corresponding to the `RELATED_TASK_META_KEY` in the
2845    /// `meta` field of the struct. If the key exists and contains a string value, it returns
2846    /// it as an `Option<&str>`. If the key is missing or not a string, it returns `None`.
2847    ///
2848    /// # Returns
2849    /// - `Some(&str)` if a related task ID exists.
2850    /// - `None` if no related task ID is found.
2851    fn related_task_id(&self) -> Option<&str>;
2852    /// Sets the related task ID in the metadata.
2853    ///
2854    /// This function inserts a `taskId` key with the provided `task_id` into the `meta` field.
2855    /// If the `meta` field is `None`, it creates a new `serde_json::Map` and assigns it to `meta`.
2856    /// The `task_id` is converted into a string before being inserted.
2857    ///
2858    /// # Type Parameters
2859    /// - `T`: The type of the `task_id`. It must implement `Into<String>` to allow flexible
2860    ///   conversion of various types (e.g., `&str`, `String`).
2861    ///
2862    /// # Arguments
2863    /// - `task_id`: The ID of the related task to set. This can be any type that can be converted
2864    ///   into a `String`.
2865    fn set_related_task_id<T>(&mut self, task_id: T)
2866    where
2867        T: Into<String>;
2868
2869    fn with_related_task_id<T>(self, task_id: T) -> Self
2870    where
2871        T: Into<String>;
2872
2873    /// Add a key-value pair.
2874    /// Value can be anything that serde can serialize (primitives, vecs, maps, structs, etc.).
2875    fn add<K, V>(self, key: K, value: V) -> Self
2876    where
2877        K: Into<String>,
2878        V: Into<Value>;
2879
2880    /// Conditionally add a field (useful for optional metadata).
2881    fn add_if<K, V>(self, condition: bool, key: K, value: V) -> Self
2882    where
2883        K: Into<String>,
2884        V: Into<Value>;
2885
2886    /// Add a raw pre-built Value (e.g. from json! macro or complex logic).
2887    fn add_raw<K>(self, key: K, value: Value) -> Self
2888    where
2889        K: Into<String>;
2890}
2891
2892impl McpMetaEx for serde_json::Map<String, Value> {
2893    fn related_task_id(&self) -> Option<&str> {
2894        self.get(RELATED_TASK_META_KEY).and_then(|v| v.as_str())
2895    }
2896
2897    fn set_related_task_id<T>(&mut self, task_id: T)
2898    where
2899        T: Into<String>,
2900    {
2901        let task_json = json!({ "taskId": task_id.into() });
2902        self.entry(RELATED_TASK_META_KEY)
2903            .and_modify(|e| *e = task_json.clone())
2904            .or_insert_with(|| task_json);
2905    }
2906
2907    fn with_related_task_id<T>(mut self, task_id: T) -> Self
2908    where
2909        T: Into<String>,
2910    {
2911        self.set_related_task_id(task_id);
2912        self
2913    }
2914
2915    /// Add a key-value pair.
2916    /// Value can be anything that serde can serialize (primitives, vecs, maps, structs, etc.).
2917    fn add<K, V>(mut self, key: K, value: V) -> Self
2918    where
2919        K: Into<String>,
2920        V: Into<Value>,
2921    {
2922        self.insert(key.into(), value.into());
2923        self
2924    }
2925
2926    /// Conditionally add a field (useful for optional metadata).
2927    fn add_if<K, V>(mut self, condition: bool, key: K, value: V) -> Self
2928    where
2929        K: Into<String>,
2930        V: Into<Value>,
2931    {
2932        if condition {
2933            self.insert(key.into(), value.into());
2934            self
2935        } else {
2936            self
2937        }
2938    }
2939
2940    /// Add a raw pre-built Value (e.g. from json! macro or complex logic).
2941    fn add_raw<K>(mut self, key: K, value: Value) -> Self
2942    where
2943        K: Into<String>,
2944    {
2945        self.insert(key.into(), value);
2946        self
2947    }
2948}
2949
2950pub type CustomNotification = CustomRequest;
2951
2952/// BEGIN AUTO GENERATED
2953impl ::serde::Serialize for ServerJsonrpcResponse {
2954    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
2955    where
2956        S: ::serde::Serializer,
2957    {
2958        let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
2959        state.serialize_field("id", &self.id)?;
2960        state.serialize_field("jsonrpc", &self.jsonrpc)?;
2961        state.serialize_field("result", &self.result)?;
2962        state.end()
2963    }
2964}
2965impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcResponse {
2966    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
2967    where
2968        D: ::serde::Deserializer<'de>,
2969    {
2970        use serde::de::{self, MapAccess, Visitor};
2971        use std::fmt;
2972        struct ServerJsonrpcResultVisitor;
2973        impl<'de> Visitor<'de> for ServerJsonrpcResultVisitor {
2974            type Value = ServerJsonrpcResponse;
2975            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
2976                formatter.write_str("a valid JSON-RPC response object")
2977            }
2978            fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcResponse, M::Error>
2979            where
2980                M: MapAccess<'de>,
2981            {
2982                let mut id: Option<RequestId> = None;
2983                let mut jsonrpc: Option<String> = None;
2984                let mut result: Option<Value> = None;
2985                while let Some(key) = map.next_key::<String>()? {
2986                    match key.as_str() {
2987                        "id" => id = Some(map.next_value()?),
2988                        "jsonrpc" => jsonrpc = Some(map.next_value()?),
2989                        "result" => result = Some(map.next_value()?),
2990                        _ => {
2991                            return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
2992                        }
2993                    }
2994                }
2995                let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
2996                let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
2997                let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
2998                let result = serde_json::from_value::<ResultFromServer>(result).map_err(de::Error::custom)?;
2999                Ok(ServerJsonrpcResponse { id, jsonrpc, result })
3000            }
3001        }
3002        deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ServerJsonrpcResultVisitor)
3003    }
3004}
3005impl ::serde::Serialize for ClientJsonrpcResponse {
3006    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
3007    where
3008        S: ::serde::Serializer,
3009    {
3010        let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
3011        state.serialize_field("id", &self.id)?;
3012        state.serialize_field("jsonrpc", &self.jsonrpc)?;
3013        state.serialize_field("result", &self.result)?;
3014        state.end()
3015    }
3016}
3017impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcResponse {
3018    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
3019    where
3020        D: ::serde::Deserializer<'de>,
3021    {
3022        use serde::de::{self, MapAccess, Visitor};
3023        use std::fmt;
3024        struct ClientJsonrpcResultVisitor;
3025        impl<'de> Visitor<'de> for ClientJsonrpcResultVisitor {
3026            type Value = ClientJsonrpcResponse;
3027            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3028                formatter.write_str("a valid JSON-RPC response object")
3029            }
3030            fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcResponse, M::Error>
3031            where
3032                M: MapAccess<'de>,
3033            {
3034                let mut id: Option<RequestId> = None;
3035                let mut jsonrpc: Option<String> = None;
3036                let mut result: Option<Value> = None;
3037                while let Some(key) = map.next_key::<String>()? {
3038                    match key.as_str() {
3039                        "id" => id = Some(map.next_value()?),
3040                        "jsonrpc" => jsonrpc = Some(map.next_value()?),
3041                        "result" => result = Some(map.next_value()?),
3042                        _ => {
3043                            return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
3044                        }
3045                    }
3046                }
3047                let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
3048                let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
3049                let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
3050                let result = serde_json::from_value::<ResultFromClient>(result).map_err(de::Error::custom)?;
3051                Ok(ClientJsonrpcResponse { id, jsonrpc, result })
3052            }
3053        }
3054        deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ClientJsonrpcResultVisitor)
3055    }
3056}
3057impl From<Result> for ResultFromClient {
3058    fn from(value: Result) -> Self {
3059        Self::Result(value)
3060    }
3061}
3062impl From<GetTaskResult> for ResultFromClient {
3063    fn from(value: GetTaskResult) -> Self {
3064        Self::GetTaskResult(value)
3065    }
3066}
3067impl From<GetTaskPayloadResult> for ResultFromClient {
3068    fn from(value: GetTaskPayloadResult) -> Self {
3069        Self::GetTaskPayloadResult(value)
3070    }
3071}
3072impl From<CancelTaskResult> for ResultFromClient {
3073    fn from(value: CancelTaskResult) -> Self {
3074        Self::CancelTaskResult(value)
3075    }
3076}
3077impl From<ListTasksResult> for ResultFromClient {
3078    fn from(value: ListTasksResult) -> Self {
3079        Self::ListTasksResult(value)
3080    }
3081}
3082impl From<CreateMessageResult> for ResultFromClient {
3083    fn from(value: CreateMessageResult) -> Self {
3084        Self::CreateMessageResult(value)
3085    }
3086}
3087impl From<ListRootsResult> for ResultFromClient {
3088    fn from(value: ListRootsResult) -> Self {
3089        Self::ListRootsResult(value)
3090    }
3091}
3092impl From<ElicitResult> for ResultFromClient {
3093    fn from(value: ElicitResult) -> Self {
3094        Self::ElicitResult(value)
3095    }
3096}
3097impl From<CreateTaskResult> for ResultFromClient {
3098    fn from(value: CreateTaskResult) -> Self {
3099        Self::CreateTaskResult(value)
3100    }
3101}
3102impl From<Result> for MessageFromClient {
3103    fn from(value: Result) -> Self {
3104        MessageFromClient::ResultFromClient(value.into())
3105    }
3106}
3107impl From<GetTaskResult> for MessageFromClient {
3108    fn from(value: GetTaskResult) -> Self {
3109        MessageFromClient::ResultFromClient(value.into())
3110    }
3111}
3112impl From<GetTaskPayloadResult> for MessageFromClient {
3113    fn from(value: GetTaskPayloadResult) -> Self {
3114        MessageFromClient::ResultFromClient(value.into())
3115    }
3116}
3117impl From<CancelTaskResult> for MessageFromClient {
3118    fn from(value: CancelTaskResult) -> Self {
3119        MessageFromClient::ResultFromClient(value.into())
3120    }
3121}
3122impl From<ListTasksResult> for MessageFromClient {
3123    fn from(value: ListTasksResult) -> Self {
3124        MessageFromClient::ResultFromClient(value.into())
3125    }
3126}
3127impl From<CreateMessageResult> for MessageFromClient {
3128    fn from(value: CreateMessageResult) -> Self {
3129        MessageFromClient::ResultFromClient(value.into())
3130    }
3131}
3132impl From<ListRootsResult> for MessageFromClient {
3133    fn from(value: ListRootsResult) -> Self {
3134        MessageFromClient::ResultFromClient(value.into())
3135    }
3136}
3137impl From<ElicitResult> for MessageFromClient {
3138    fn from(value: ElicitResult) -> Self {
3139        MessageFromClient::ResultFromClient(value.into())
3140    }
3141}
3142impl From<CreateTaskResult> for MessageFromClient {
3143    fn from(value: CreateTaskResult) -> Self {
3144        MessageFromClient::ResultFromClient(value.into())
3145    }
3146}
3147impl From<PingRequest> for ServerJsonrpcRequest {
3148    fn from(value: PingRequest) -> Self {
3149        Self::PingRequest(value)
3150    }
3151}
3152impl From<GetTaskRequest> for ServerJsonrpcRequest {
3153    fn from(value: GetTaskRequest) -> Self {
3154        Self::GetTaskRequest(value)
3155    }
3156}
3157impl From<GetTaskPayloadRequest> for ServerJsonrpcRequest {
3158    fn from(value: GetTaskPayloadRequest) -> Self {
3159        Self::GetTaskPayloadRequest(value)
3160    }
3161}
3162impl From<CancelTaskRequest> for ServerJsonrpcRequest {
3163    fn from(value: CancelTaskRequest) -> Self {
3164        Self::CancelTaskRequest(value)
3165    }
3166}
3167impl From<ListTasksRequest> for ServerJsonrpcRequest {
3168    fn from(value: ListTasksRequest) -> Self {
3169        Self::ListTasksRequest(value)
3170    }
3171}
3172impl From<CreateMessageRequest> for ServerJsonrpcRequest {
3173    fn from(value: CreateMessageRequest) -> Self {
3174        Self::CreateMessageRequest(value)
3175    }
3176}
3177impl From<ListRootsRequest> for ServerJsonrpcRequest {
3178    fn from(value: ListRootsRequest) -> Self {
3179        Self::ListRootsRequest(value)
3180    }
3181}
3182impl From<ElicitRequest> for ServerJsonrpcRequest {
3183    fn from(value: ElicitRequest) -> Self {
3184        Self::ElicitRequest(value)
3185    }
3186}
3187impl From<InitializeRequest> for ClientJsonrpcRequest {
3188    fn from(value: InitializeRequest) -> Self {
3189        Self::InitializeRequest(value)
3190    }
3191}
3192impl From<PingRequest> for ClientJsonrpcRequest {
3193    fn from(value: PingRequest) -> Self {
3194        Self::PingRequest(value)
3195    }
3196}
3197impl From<ListResourcesRequest> for ClientJsonrpcRequest {
3198    fn from(value: ListResourcesRequest) -> Self {
3199        Self::ListResourcesRequest(value)
3200    }
3201}
3202impl From<ListResourceTemplatesRequest> for ClientJsonrpcRequest {
3203    fn from(value: ListResourceTemplatesRequest) -> Self {
3204        Self::ListResourceTemplatesRequest(value)
3205    }
3206}
3207impl From<ReadResourceRequest> for ClientJsonrpcRequest {
3208    fn from(value: ReadResourceRequest) -> Self {
3209        Self::ReadResourceRequest(value)
3210    }
3211}
3212impl From<SubscribeRequest> for ClientJsonrpcRequest {
3213    fn from(value: SubscribeRequest) -> Self {
3214        Self::SubscribeRequest(value)
3215    }
3216}
3217impl From<UnsubscribeRequest> for ClientJsonrpcRequest {
3218    fn from(value: UnsubscribeRequest) -> Self {
3219        Self::UnsubscribeRequest(value)
3220    }
3221}
3222impl From<ListPromptsRequest> for ClientJsonrpcRequest {
3223    fn from(value: ListPromptsRequest) -> Self {
3224        Self::ListPromptsRequest(value)
3225    }
3226}
3227impl From<GetPromptRequest> for ClientJsonrpcRequest {
3228    fn from(value: GetPromptRequest) -> Self {
3229        Self::GetPromptRequest(value)
3230    }
3231}
3232impl From<ListToolsRequest> for ClientJsonrpcRequest {
3233    fn from(value: ListToolsRequest) -> Self {
3234        Self::ListToolsRequest(value)
3235    }
3236}
3237impl From<CallToolRequest> for ClientJsonrpcRequest {
3238    fn from(value: CallToolRequest) -> Self {
3239        Self::CallToolRequest(value)
3240    }
3241}
3242impl From<GetTaskRequest> for ClientJsonrpcRequest {
3243    fn from(value: GetTaskRequest) -> Self {
3244        Self::GetTaskRequest(value)
3245    }
3246}
3247impl From<GetTaskPayloadRequest> for ClientJsonrpcRequest {
3248    fn from(value: GetTaskPayloadRequest) -> Self {
3249        Self::GetTaskPayloadRequest(value)
3250    }
3251}
3252impl From<CancelTaskRequest> for ClientJsonrpcRequest {
3253    fn from(value: CancelTaskRequest) -> Self {
3254        Self::CancelTaskRequest(value)
3255    }
3256}
3257impl From<ListTasksRequest> for ClientJsonrpcRequest {
3258    fn from(value: ListTasksRequest) -> Self {
3259        Self::ListTasksRequest(value)
3260    }
3261}
3262impl From<SetLevelRequest> for ClientJsonrpcRequest {
3263    fn from(value: SetLevelRequest) -> Self {
3264        Self::SetLevelRequest(value)
3265    }
3266}
3267impl From<CompleteRequest> for ClientJsonrpcRequest {
3268    fn from(value: CompleteRequest) -> Self {
3269        Self::CompleteRequest(value)
3270    }
3271}
3272/// Enum representing SDK error codes.
3273#[allow(non_camel_case_types)]
3274pub enum SdkErrorCodes {
3275    CONNECTION_CLOSED = -32000,
3276    REQUEST_TIMEOUT = -32001,
3277    RESOURCE_NOT_FOUND = -32002,
3278    BAD_REQUEST = -32015,
3279    SESSION_NOT_FOUND = -32016,
3280    INVALID_REQUEST = -32600,
3281    METHOD_NOT_FOUND = -32601,
3282    INVALID_PARAMS = -32602,
3283    INTERNAL_ERROR = -32603,
3284    PARSE_ERROR = -32700,
3285    URL_ELICITATION_REQUIRED = -32042,
3286}
3287impl core::fmt::Display for SdkErrorCodes {
3288    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3289        match self {
3290            SdkErrorCodes::CONNECTION_CLOSED => write!(f, "Connection closed"),
3291            SdkErrorCodes::REQUEST_TIMEOUT => write!(f, "Request timeout"),
3292            SdkErrorCodes::INVALID_REQUEST => write!(f, "Invalid request"),
3293            SdkErrorCodes::METHOD_NOT_FOUND => write!(f, "Method not found"),
3294            SdkErrorCodes::INVALID_PARAMS => write!(f, "Invalid params"),
3295            SdkErrorCodes::INTERNAL_ERROR => write!(f, "Internal error"),
3296            SdkErrorCodes::PARSE_ERROR => write!(f, "Parse Error"),
3297            SdkErrorCodes::RESOURCE_NOT_FOUND => write!(f, "Resource not found"),
3298            SdkErrorCodes::BAD_REQUEST => write!(f, "Bad request"),
3299            SdkErrorCodes::SESSION_NOT_FOUND => write!(f, "Session not found"),
3300            SdkErrorCodes::URL_ELICITATION_REQUIRED => {
3301                write!(
3302                    f,
3303                    "A required URL was not provided. Please supply the requested URL to continue."
3304                )
3305            }
3306        }
3307    }
3308}
3309impl From<SdkErrorCodes> for i64 {
3310    fn from(code: SdkErrorCodes) -> Self {
3311        code as i64
3312    }
3313}
3314#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
3315pub struct SdkError {
3316    ///The error type that occurred.
3317    pub code: i64,
3318    ///Additional information about the error.
3319    pub data: ::std::option::Option<::serde_json::Value>,
3320    ///A short description of the error.
3321    pub message: ::std::string::String,
3322}
3323impl core::fmt::Display for SdkError {
3324    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
3325        write!(f, "MCP error {}: {}", self.code, self.message)
3326    }
3327}
3328impl std::error::Error for SdkError {
3329    fn description(&self) -> &str {
3330        &self.message
3331    }
3332}
3333impl SdkError {
3334    pub fn new(
3335        error_code: SdkErrorCodes,
3336        message: ::std::string::String,
3337        data: ::std::option::Option<::serde_json::Value>,
3338    ) -> Self {
3339        Self {
3340            code: error_code.into(),
3341            data,
3342            message,
3343        }
3344    }
3345    pub fn connection_closed() -> Self {
3346        Self {
3347            code: SdkErrorCodes::CONNECTION_CLOSED.into(),
3348            data: None,
3349            message: SdkErrorCodes::CONNECTION_CLOSED.to_string(),
3350        }
3351    }
3352    pub fn request_timeout(timeout: u128) -> Self {
3353        Self {
3354            code: SdkErrorCodes::REQUEST_TIMEOUT.into(),
3355            data: Some(json!({ "timeout" : timeout })),
3356            message: SdkErrorCodes::REQUEST_TIMEOUT.to_string(),
3357        }
3358    }
3359    pub fn session_not_found() -> Self {
3360        Self {
3361            code: SdkErrorCodes::SESSION_NOT_FOUND.into(),
3362            data: None,
3363            message: SdkErrorCodes::SESSION_NOT_FOUND.to_string(),
3364        }
3365    }
3366    pub fn invalid_request() -> Self {
3367        Self {
3368            code: SdkErrorCodes::INVALID_REQUEST.into(),
3369            data: None,
3370            message: SdkErrorCodes::INVALID_REQUEST.to_string(),
3371        }
3372    }
3373    pub fn method_not_found() -> Self {
3374        Self {
3375            code: SdkErrorCodes::METHOD_NOT_FOUND.into(),
3376            data: None,
3377            message: SdkErrorCodes::METHOD_NOT_FOUND.to_string(),
3378        }
3379    }
3380    pub fn invalid_params() -> Self {
3381        Self {
3382            code: SdkErrorCodes::INVALID_PARAMS.into(),
3383            data: None,
3384            message: SdkErrorCodes::INVALID_PARAMS.to_string(),
3385        }
3386    }
3387    pub fn internal_error() -> Self {
3388        Self {
3389            code: SdkErrorCodes::INTERNAL_ERROR.into(),
3390            data: None,
3391            message: SdkErrorCodes::INTERNAL_ERROR.to_string(),
3392        }
3393    }
3394    pub fn parse_error() -> Self {
3395        Self {
3396            code: SdkErrorCodes::PARSE_ERROR.into(),
3397            data: None,
3398            message: SdkErrorCodes::PARSE_ERROR.to_string(),
3399        }
3400    }
3401    /// Creates a new `RpcError` indicating that a URL elicitation failed
3402    /// and was required for the operation to continue.
3403    ///
3404    /// The resulting error uses the -32042 value as introduced in mcp protocol 2025-11-25
3405    /// The result json matches a UrlElicitError and the `data` value could be deserialized into UrlElicitErrorData
3406    ///
3407    pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
3408        Self {
3409            code: UrlElicitError::code_value(),
3410            data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
3411                json!(
3412                    { "elicitations" : [], "error" :
3413                    "failed to UrlElicitError data" }
3414                )
3415            })),
3416            message: "URL required. Please provide a URL.".to_string(),
3417        }
3418    }
3419    pub fn resource_not_found() -> Self {
3420        Self {
3421            code: SdkErrorCodes::RESOURCE_NOT_FOUND.into(),
3422            data: None,
3423            message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
3424        }
3425    }
3426    pub fn bad_request() -> Self {
3427        Self {
3428            code: SdkErrorCodes::BAD_REQUEST.into(),
3429            data: None,
3430            message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
3431        }
3432    }
3433    pub fn with_message(mut self, message: &str) -> Self {
3434        self.message = message.to_string();
3435        self
3436    }
3437    pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
3438        self.data = data;
3439        self
3440    }
3441}
3442/// Enum representing standard and mcp specific JSON-RPC error codes.
3443#[allow(non_camel_case_types)]
3444pub enum RpcErrorCodes {
3445    PARSE_ERROR = -32700isize,
3446    INVALID_REQUEST = -32600isize,
3447    METHOD_NOT_FOUND = -32601isize,
3448    INVALID_PARAMS = -32602isize,
3449    INTERNAL_ERROR = -32603isize,
3450    URL_ELICITATION_REQUIRED = -32042isize,
3451}
3452impl From<RpcErrorCodes> for i64 {
3453    fn from(code: RpcErrorCodes) -> Self {
3454        code as i64
3455    }
3456}
3457impl RpcError {
3458    /// Constructs a new `RpcError` with the provided arguments.
3459    ///
3460    /// # Arguments
3461    /// * `error_code` - The JSON-RPC error code.
3462    /// * `message` - A descriptive error message.
3463    /// * `data` - Optional additional data.
3464    ///
3465    /// # Example
3466    /// ```
3467    /// use serde_json::json;
3468    /// use rust_mcp_schema::{RpcError, schema_utils::RpcErrorCodes};
3469    ///
3470    /// let error = RpcError::new(RpcErrorCodes::INVALID_PARAMS, "Invalid params!".to_string(), Some(json!({"details": "Missing method field"})));
3471    /// assert_eq!(error.code, -32602);
3472    /// assert_eq!(error.message, "Invalid params!".to_string());
3473    /// ```
3474    pub fn new(
3475        error_code: RpcErrorCodes,
3476        message: ::std::string::String,
3477        data: ::std::option::Option<::serde_json::Value>,
3478    ) -> Self {
3479        Self {
3480            code: error_code.into(),
3481            data,
3482            message,
3483        }
3484    }
3485    /// Creates a new `RpcError` for "Method not found".
3486    ///
3487    /// # Example
3488    /// ```
3489    /// use rust_mcp_schema::RpcError;
3490    ///
3491    /// let error = RpcError::method_not_found();
3492    /// assert_eq!(error.code, -32601);
3493    /// assert_eq!(error.message, "Method not found");
3494    /// ```
3495    pub fn method_not_found() -> Self {
3496        Self {
3497            code: RpcErrorCodes::METHOD_NOT_FOUND.into(),
3498            data: None,
3499            message: "Method not found".to_string(),
3500        }
3501    }
3502    /// Creates a new `RpcError` indicating that a URL elicitation failed
3503    /// and was required for the operation to continue.
3504    ///
3505    /// The resulting error uses the -32042 value as introduced in mcp protocol 2025-11-25
3506    /// The result json matches a UrlElicitError and the `data` value could be deserialized into UrlElicitErrorData
3507    ///
3508    pub fn url_elicit_required(elicit_url_params: Vec<ElicitRequestUrlParams>) -> Self {
3509        Self {
3510            code: UrlElicitError::code_value(),
3511            data: Some(serde_json::to_value(elicit_url_params).unwrap_or_else(|_| {
3512                json!(
3513                    { "elicitations" : [], "error" :
3514                    "failed to UrlElicitError data" }
3515                )
3516            })),
3517            message: "URL required. Please provide a URL.".to_string(),
3518        }
3519    }
3520    /// Creates a new `RpcError` for "Invalid parameters".
3521    ///
3522    /// # Example
3523    /// ```
3524    /// use rust_mcp_schema::RpcError;
3525    ///
3526    /// let error = RpcError::invalid_params();
3527    /// assert_eq!(error.code, -32602);
3528    /// ```
3529    pub fn invalid_params() -> Self {
3530        Self {
3531            code: RpcErrorCodes::INVALID_PARAMS.into(),
3532            data: None,
3533            message: "Invalid params".to_string(),
3534        }
3535    }
3536    /// Creates a new `RpcError` for "Invalid request".
3537    ///
3538    /// # Example
3539    /// ```
3540    /// use rust_mcp_schema::RpcError;
3541    ///
3542    /// let error = RpcError::invalid_request();
3543    /// assert_eq!(error.code, -32600);
3544    /// ```
3545    pub fn invalid_request() -> Self {
3546        Self {
3547            code: RpcErrorCodes::INVALID_REQUEST.into(),
3548            data: None,
3549            message: "Invalid request".to_string(),
3550        }
3551    }
3552    /// Creates a new `RpcError` for "Internal error".
3553    ///
3554    /// # Example
3555    /// ```
3556    /// use rust_mcp_schema::RpcError;
3557    ///
3558    /// let error = RpcError::internal_error();
3559    /// assert_eq!(error.code, -32603);
3560    /// ```
3561    pub fn internal_error() -> Self {
3562        Self {
3563            code: RpcErrorCodes::INTERNAL_ERROR.into(),
3564            data: None,
3565            message: "Internal error".to_string(),
3566        }
3567    }
3568    /// Creates a new `RpcError` for "Parse error".
3569    ///
3570    /// # Example
3571    /// ```
3572    /// use rust_mcp_schema::RpcError;
3573    ///
3574    /// let error = RpcError::parse_error();
3575    /// assert_eq!(error.code, -32700);
3576    /// ```
3577    pub fn parse_error() -> Self {
3578        Self {
3579            code: RpcErrorCodes::PARSE_ERROR.into(),
3580            data: None,
3581            message: "Parse error".to_string(),
3582        }
3583    }
3584    /// Sets a custom error message.
3585    ///
3586    /// # Example
3587    /// ```
3588    /// use rust_mcp_schema::RpcError;
3589    ///
3590    /// let error = RpcError::invalid_request().with_message("Request format is invalid".to_string());
3591    /// assert_eq!(error.message, "Request format is invalid".to_string());
3592    /// ```
3593    pub fn with_message<T: Into<String>>(mut self, message: T) -> Self {
3594        self.message = message.into();
3595        self
3596    }
3597    /// Attaches optional data to the error.
3598    ///
3599    /// # Example
3600    /// ```
3601    /// use serde_json::json;
3602    /// use rust_mcp_schema::RpcError;
3603    ///
3604    /// let error = RpcError::invalid_request().with_data(Some(json!({"reason": "Missing ID"})));
3605    /// assert!(error.data.is_some());
3606    /// ```
3607    pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
3608        self.data = data;
3609        self
3610    }
3611}
3612impl std::error::Error for RpcError {
3613    fn description(&self) -> &str {
3614        &self.message
3615    }
3616}
3617impl Display for RpcError {
3618    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3619        write!(
3620            f,
3621            "{}",
3622            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
3623        )
3624    }
3625}
3626impl FromStr for RpcError {
3627    type Err = RpcError;
3628    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
3629        serde_json::from_str(s)
3630            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
3631    }
3632}
3633///Constructs a new `JsonrpcErrorResponse` using the provided arguments.
3634impl JsonrpcErrorResponse {
3635    pub fn create(
3636        id: Option<RequestId>,
3637        error_code: RpcErrorCodes,
3638        error_message: ::std::string::String,
3639        error_data: ::std::option::Option<::serde_json::Value>,
3640    ) -> Self {
3641        Self::new(RpcError::new(error_code, error_message, error_data), id)
3642    }
3643}
3644impl From<Result> for ResultFromServer {
3645    fn from(value: Result) -> Self {
3646        Self::Result(value)
3647    }
3648}
3649impl From<InitializeResult> for ResultFromServer {
3650    fn from(value: InitializeResult) -> Self {
3651        Self::InitializeResult(value)
3652    }
3653}
3654impl From<ListResourcesResult> for ResultFromServer {
3655    fn from(value: ListResourcesResult) -> Self {
3656        Self::ListResourcesResult(value)
3657    }
3658}
3659impl From<ListResourceTemplatesResult> for ResultFromServer {
3660    fn from(value: ListResourceTemplatesResult) -> Self {
3661        Self::ListResourceTemplatesResult(value)
3662    }
3663}
3664impl From<ReadResourceResult> for ResultFromServer {
3665    fn from(value: ReadResourceResult) -> Self {
3666        Self::ReadResourceResult(value)
3667    }
3668}
3669impl From<ListPromptsResult> for ResultFromServer {
3670    fn from(value: ListPromptsResult) -> Self {
3671        Self::ListPromptsResult(value)
3672    }
3673}
3674impl From<GetPromptResult> for ResultFromServer {
3675    fn from(value: GetPromptResult) -> Self {
3676        Self::GetPromptResult(value)
3677    }
3678}
3679impl From<ListToolsResult> for ResultFromServer {
3680    fn from(value: ListToolsResult) -> Self {
3681        Self::ListToolsResult(value)
3682    }
3683}
3684impl From<CallToolResult> for ResultFromServer {
3685    fn from(value: CallToolResult) -> Self {
3686        Self::CallToolResult(value)
3687    }
3688}
3689impl From<GetTaskResult> for ResultFromServer {
3690    fn from(value: GetTaskResult) -> Self {
3691        Self::GetTaskResult(value)
3692    }
3693}
3694impl From<GetTaskPayloadResult> for ResultFromServer {
3695    fn from(value: GetTaskPayloadResult) -> Self {
3696        Self::GetTaskPayloadResult(value)
3697    }
3698}
3699impl From<CancelTaskResult> for ResultFromServer {
3700    fn from(value: CancelTaskResult) -> Self {
3701        Self::CancelTaskResult(value)
3702    }
3703}
3704impl From<ListTasksResult> for ResultFromServer {
3705    fn from(value: ListTasksResult) -> Self {
3706        Self::ListTasksResult(value)
3707    }
3708}
3709impl From<CompleteResult> for ResultFromServer {
3710    fn from(value: CompleteResult) -> Self {
3711        Self::CompleteResult(value)
3712    }
3713}
3714impl From<CreateTaskResult> for ResultFromServer {
3715    fn from(value: CreateTaskResult) -> Self {
3716        Self::CreateTaskResult(value)
3717    }
3718}
3719impl From<Result> for MessageFromServer {
3720    fn from(value: Result) -> Self {
3721        MessageFromServer::ResultFromServer(value.into())
3722    }
3723}
3724impl From<InitializeResult> for MessageFromServer {
3725    fn from(value: InitializeResult) -> Self {
3726        MessageFromServer::ResultFromServer(value.into())
3727    }
3728}
3729impl From<ListResourcesResult> for MessageFromServer {
3730    fn from(value: ListResourcesResult) -> Self {
3731        MessageFromServer::ResultFromServer(value.into())
3732    }
3733}
3734impl From<ListResourceTemplatesResult> for MessageFromServer {
3735    fn from(value: ListResourceTemplatesResult) -> Self {
3736        MessageFromServer::ResultFromServer(value.into())
3737    }
3738}
3739impl From<ReadResourceResult> for MessageFromServer {
3740    fn from(value: ReadResourceResult) -> Self {
3741        MessageFromServer::ResultFromServer(value.into())
3742    }
3743}
3744impl From<ListPromptsResult> for MessageFromServer {
3745    fn from(value: ListPromptsResult) -> Self {
3746        MessageFromServer::ResultFromServer(value.into())
3747    }
3748}
3749impl From<GetPromptResult> for MessageFromServer {
3750    fn from(value: GetPromptResult) -> Self {
3751        MessageFromServer::ResultFromServer(value.into())
3752    }
3753}
3754impl From<ListToolsResult> for MessageFromServer {
3755    fn from(value: ListToolsResult) -> Self {
3756        MessageFromServer::ResultFromServer(value.into())
3757    }
3758}
3759impl From<CallToolResult> for MessageFromServer {
3760    fn from(value: CallToolResult) -> Self {
3761        MessageFromServer::ResultFromServer(value.into())
3762    }
3763}
3764impl From<GetTaskResult> for MessageFromServer {
3765    fn from(value: GetTaskResult) -> Self {
3766        MessageFromServer::ResultFromServer(value.into())
3767    }
3768}
3769impl From<GetTaskPayloadResult> for MessageFromServer {
3770    fn from(value: GetTaskPayloadResult) -> Self {
3771        MessageFromServer::ResultFromServer(value.into())
3772    }
3773}
3774impl From<CancelTaskResult> for MessageFromServer {
3775    fn from(value: CancelTaskResult) -> Self {
3776        MessageFromServer::ResultFromServer(value.into())
3777    }
3778}
3779impl From<ListTasksResult> for MessageFromServer {
3780    fn from(value: ListTasksResult) -> Self {
3781        MessageFromServer::ResultFromServer(value.into())
3782    }
3783}
3784impl From<CompleteResult> for MessageFromServer {
3785    fn from(value: CompleteResult) -> Self {
3786        MessageFromServer::ResultFromServer(value.into())
3787    }
3788}
3789impl From<CreateTaskResult> for MessageFromServer {
3790    fn from(value: CreateTaskResult) -> Self {
3791        MessageFromServer::ResultFromServer(value.into())
3792    }
3793}
3794impl TryFrom<ResultFromClient> for GenericResult {
3795    type Error = RpcError;
3796    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3797        match value {
3798            ResultFromClient::GetTaskPayloadResult(result) => Ok(result.into()),
3799            ResultFromClient::Result(result) => Ok(result),
3800            _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
3801        }
3802    }
3803}
3804impl TryFrom<ResultFromClient> for GetTaskResult {
3805    type Error = RpcError;
3806    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3807        if let ResultFromClient::GetTaskResult(result) = value {
3808            Ok(result)
3809        } else {
3810            Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
3811        }
3812    }
3813}
3814impl TryFrom<ResultFromClient> for GetTaskPayloadResult {
3815    type Error = RpcError;
3816    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3817        if let ResultFromClient::GetTaskPayloadResult(result) = value {
3818            Ok(result)
3819        } else {
3820            Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
3821        }
3822    }
3823}
3824impl TryFrom<ResultFromClient> for CancelTaskResult {
3825    type Error = RpcError;
3826    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3827        if let ResultFromClient::CancelTaskResult(result) = value {
3828            Ok(result)
3829        } else {
3830            Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
3831        }
3832    }
3833}
3834impl TryFrom<ResultFromClient> for ListTasksResult {
3835    type Error = RpcError;
3836    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3837        if let ResultFromClient::ListTasksResult(result) = value {
3838            Ok(result)
3839        } else {
3840            Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
3841        }
3842    }
3843}
3844impl TryFrom<ResultFromClient> for CreateMessageResult {
3845    type Error = RpcError;
3846    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3847        if let ResultFromClient::CreateMessageResult(result) = value {
3848            Ok(result)
3849        } else {
3850            Err(RpcError::internal_error().with_message("Not a CreateMessageResult".to_string()))
3851        }
3852    }
3853}
3854impl TryFrom<ResultFromClient> for ListRootsResult {
3855    type Error = RpcError;
3856    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3857        if let ResultFromClient::ListRootsResult(result) = value {
3858            Ok(result)
3859        } else {
3860            Err(RpcError::internal_error().with_message("Not a ListRootsResult".to_string()))
3861        }
3862    }
3863}
3864impl TryFrom<ResultFromClient> for ElicitResult {
3865    type Error = RpcError;
3866    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3867        if let ResultFromClient::ElicitResult(result) = value {
3868            Ok(result)
3869        } else {
3870            Err(RpcError::internal_error().with_message("Not a ElicitResult".to_string()))
3871        }
3872    }
3873}
3874impl TryFrom<ResultFromClient> for CreateTaskResult {
3875    type Error = RpcError;
3876    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3877        if let ResultFromClient::CreateTaskResult(result) = value {
3878            Ok(result)
3879        } else {
3880            Err(RpcError::internal_error().with_message("Not a CreateTaskResult".to_string()))
3881        }
3882    }
3883}
3884impl TryFrom<ResultFromServer> for GenericResult {
3885    type Error = RpcError;
3886    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3887        match value {
3888            ResultFromServer::GetTaskPayloadResult(result) => Ok(result.into()),
3889            ResultFromServer::Result(result) => Ok(result),
3890            _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
3891        }
3892    }
3893}
3894impl TryFrom<ResultFromServer> for InitializeResult {
3895    type Error = RpcError;
3896    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3897        if let ResultFromServer::InitializeResult(result) = value {
3898            Ok(result)
3899        } else {
3900            Err(RpcError::internal_error().with_message("Not a InitializeResult".to_string()))
3901        }
3902    }
3903}
3904impl TryFrom<ResultFromServer> for ListResourcesResult {
3905    type Error = RpcError;
3906    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3907        if let ResultFromServer::ListResourcesResult(result) = value {
3908            Ok(result)
3909        } else {
3910            Err(RpcError::internal_error().with_message("Not a ListResourcesResult".to_string()))
3911        }
3912    }
3913}
3914impl TryFrom<ResultFromServer> for ListResourceTemplatesResult {
3915    type Error = RpcError;
3916    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3917        if let ResultFromServer::ListResourceTemplatesResult(result) = value {
3918            Ok(result)
3919        } else {
3920            Err(RpcError::internal_error().with_message("Not a ListResourceTemplatesResult".to_string()))
3921        }
3922    }
3923}
3924impl TryFrom<ResultFromServer> for ReadResourceResult {
3925    type Error = RpcError;
3926    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3927        if let ResultFromServer::ReadResourceResult(result) = value {
3928            Ok(result)
3929        } else {
3930            Err(RpcError::internal_error().with_message("Not a ReadResourceResult".to_string()))
3931        }
3932    }
3933}
3934impl TryFrom<ResultFromServer> for ListPromptsResult {
3935    type Error = RpcError;
3936    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3937        if let ResultFromServer::ListPromptsResult(result) = value {
3938            Ok(result)
3939        } else {
3940            Err(RpcError::internal_error().with_message("Not a ListPromptsResult".to_string()))
3941        }
3942    }
3943}
3944impl TryFrom<ResultFromServer> for GetPromptResult {
3945    type Error = RpcError;
3946    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3947        if let ResultFromServer::GetPromptResult(result) = value {
3948            Ok(result)
3949        } else {
3950            Err(RpcError::internal_error().with_message("Not a GetPromptResult".to_string()))
3951        }
3952    }
3953}
3954impl TryFrom<ResultFromServer> for ListToolsResult {
3955    type Error = RpcError;
3956    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3957        if let ResultFromServer::ListToolsResult(result) = value {
3958            Ok(result)
3959        } else {
3960            Err(RpcError::internal_error().with_message("Not a ListToolsResult".to_string()))
3961        }
3962    }
3963}
3964impl TryFrom<ResultFromServer> for CallToolResult {
3965    type Error = RpcError;
3966    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3967        if let ResultFromServer::CallToolResult(result) = value {
3968            Ok(result)
3969        } else {
3970            Err(RpcError::internal_error().with_message("Not a CallToolResult".to_string()))
3971        }
3972    }
3973}
3974impl TryFrom<ResultFromServer> for GetTaskResult {
3975    type Error = RpcError;
3976    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3977        if let ResultFromServer::GetTaskResult(result) = value {
3978            Ok(result)
3979        } else {
3980            Err(RpcError::internal_error().with_message("Not a GetTaskResult".to_string()))
3981        }
3982    }
3983}
3984impl TryFrom<ResultFromServer> for GetTaskPayloadResult {
3985    type Error = RpcError;
3986    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3987        if let ResultFromServer::GetTaskPayloadResult(result) = value {
3988            Ok(result)
3989        } else {
3990            Err(RpcError::internal_error().with_message("Not a GetTaskPayloadResult".to_string()))
3991        }
3992    }
3993}
3994impl TryFrom<ResultFromServer> for CancelTaskResult {
3995    type Error = RpcError;
3996    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
3997        if let ResultFromServer::CancelTaskResult(result) = value {
3998            Ok(result)
3999        } else {
4000            Err(RpcError::internal_error().with_message("Not a CancelTaskResult".to_string()))
4001        }
4002    }
4003}
4004impl TryFrom<ResultFromServer> for ListTasksResult {
4005    type Error = RpcError;
4006    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4007        if let ResultFromServer::ListTasksResult(result) = value {
4008            Ok(result)
4009        } else {
4010            Err(RpcError::internal_error().with_message("Not a ListTasksResult".to_string()))
4011        }
4012    }
4013}
4014impl TryFrom<ResultFromServer> for CompleteResult {
4015    type Error = RpcError;
4016    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4017        if let ResultFromServer::CompleteResult(result) = value {
4018            Ok(result)
4019        } else {
4020            Err(RpcError::internal_error().with_message("Not a CompleteResult".to_string()))
4021        }
4022    }
4023}
4024impl TryFrom<ResultFromServer> for CreateTaskResult {
4025    type Error = RpcError;
4026    fn try_from(value: ResultFromServer) -> std::result::Result<Self, Self::Error> {
4027        if let ResultFromServer::CreateTaskResult(result) = value {
4028            Ok(result)
4029        } else {
4030            Err(RpcError::internal_error().with_message("Not a CreateTaskResult".to_string()))
4031        }
4032    }
4033}
4034impl ContentBlock {
4035    ///Create a ContentBlock::TextContent
4036    pub fn text_content(text: ::std::string::String) -> Self {
4037        TextContent::new(text, None, None).into()
4038    }
4039    ///Create a ContentBlock::ImageContent
4040    pub fn image_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
4041        ImageContent::new(data, mime_type, None, None).into()
4042    }
4043    ///Create a ContentBlock::AudioContent
4044    pub fn audio_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
4045        AudioContent::new(data, mime_type, None, None).into()
4046    }
4047    ///Create a ContentBlock::ResourceLink
4048    pub fn resource_link(value: ResourceLink) -> Self {
4049        value.into()
4050    }
4051    ///Create a ContentBlock::EmbeddedResource
4052    pub fn embedded_resource(resource: EmbeddedResourceResource) -> Self {
4053        EmbeddedResource::new(resource, None, None).into()
4054    }
4055    ///Returns the content type as a string based on the variant of `ContentBlock`
4056    pub fn content_type(&self) -> &str {
4057        match self {
4058            ContentBlock::TextContent(text_content) => text_content.type_(),
4059            ContentBlock::ImageContent(image_content) => image_content.type_(),
4060            ContentBlock::AudioContent(audio_content) => audio_content.type_(),
4061            ContentBlock::ResourceLink(resource_link) => resource_link.type_(),
4062            ContentBlock::EmbeddedResource(embedded_resource) => embedded_resource.type_(),
4063        }
4064    }
4065    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4066    pub fn as_text_content(&self) -> std::result::Result<&TextContent, RpcError> {
4067        match &self {
4068            ContentBlock::TextContent(text_content) => Ok(text_content),
4069            _ => Err(RpcError::internal_error().with_message(format!(
4070                "Invalid conversion, \"{}\" is not a {}",
4071                self.content_type(),
4072                "TextContent"
4073            ))),
4074        }
4075    }
4076    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4077    pub fn as_image_content(&self) -> std::result::Result<&ImageContent, RpcError> {
4078        match &self {
4079            ContentBlock::ImageContent(image_content) => Ok(image_content),
4080            _ => Err(RpcError::internal_error().with_message(format!(
4081                "Invalid conversion, \"{}\" is not a {}",
4082                self.content_type(),
4083                "ImageContent"
4084            ))),
4085        }
4086    }
4087    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4088    pub fn as_audio_content(&self) -> std::result::Result<&AudioContent, RpcError> {
4089        match &self {
4090            ContentBlock::AudioContent(audio_content) => Ok(audio_content),
4091            _ => Err(RpcError::internal_error().with_message(format!(
4092                "Invalid conversion, \"{}\" is not a {}",
4093                self.content_type(),
4094                "AudioContent"
4095            ))),
4096        }
4097    }
4098    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4099    pub fn as_resource_link(&self) -> std::result::Result<&ResourceLink, RpcError> {
4100        match &self {
4101            ContentBlock::ResourceLink(resource_link) => Ok(resource_link),
4102            _ => Err(RpcError::internal_error().with_message(format!(
4103                "Invalid conversion, \"{}\" is not a {}",
4104                self.content_type(),
4105                "ResourceLink"
4106            ))),
4107        }
4108    }
4109    /// Converts the content to a reference to `TextContent`, returning an error if the conversion is invalid.
4110    pub fn as_embedded_resource(&self) -> std::result::Result<&EmbeddedResource, RpcError> {
4111        match &self {
4112            ContentBlock::EmbeddedResource(embedded_resource) => Ok(embedded_resource),
4113            _ => Err(RpcError::internal_error().with_message(format!(
4114                "Invalid conversion, \"{}\" is not a {}",
4115                self.content_type(),
4116                "EmbeddedResource"
4117            ))),
4118        }
4119    }
4120}
4121impl CallToolResult {
4122    pub fn text_content(content: Vec<TextContent>) -> Self {
4123        Self {
4124            content: content.into_iter().map(Into::into).collect(),
4125            is_error: None,
4126            meta: None,
4127            structured_content: None,
4128        }
4129    }
4130    pub fn image_content(content: Vec<ImageContent>) -> Self {
4131        Self {
4132            content: content.into_iter().map(Into::into).collect(),
4133            is_error: None,
4134            meta: None,
4135            structured_content: None,
4136        }
4137    }
4138    pub fn audio_content(content: Vec<AudioContent>) -> Self {
4139        Self {
4140            content: content.into_iter().map(Into::into).collect(),
4141            is_error: None,
4142            meta: None,
4143            structured_content: None,
4144        }
4145    }
4146    pub fn resource_link(content: Vec<ResourceLink>) -> Self {
4147        Self {
4148            content: content.into_iter().map(Into::into).collect(),
4149            is_error: None,
4150            meta: None,
4151            structured_content: None,
4152        }
4153    }
4154    pub fn embedded_resource(content: Vec<EmbeddedResource>) -> Self {
4155        Self {
4156            content: content.into_iter().map(Into::into).collect(),
4157            is_error: None,
4158            meta: None,
4159            structured_content: None,
4160        }
4161    }
4162    /// Create a `CallToolResult` with an error, containing an error message in the content
4163    pub fn with_error(error: CallToolError) -> Self {
4164        Self {
4165            content: vec![ContentBlock::TextContent(TextContent::new(error.to_string(), None, None))],
4166            is_error: Some(true),
4167            meta: None,
4168            structured_content: None,
4169        }
4170    }
4171    /// Assigns metadata to the CallToolResult, enabling the inclusion of extra context or details.
4172    pub fn with_meta(mut self, meta: Option<serde_json::Map<String, Value>>) -> Self {
4173        self.meta = meta;
4174        self
4175    }
4176    /// Assigns structured_content to the CallToolResult
4177    pub fn with_structured_content(
4178        mut self,
4179        structured_content: ::serde_json::Map<::std::string::String, ::serde_json::Value>,
4180    ) -> Self {
4181        self.structured_content = Some(structured_content);
4182        self
4183    }
4184}
4185impl ServerRequest {
4186    pub fn request_id(&self) -> &RequestId {
4187        match self {
4188            ServerRequest::PingRequest(request) => &request.id,
4189            ServerRequest::GetTaskRequest(request) => &request.id,
4190            ServerRequest::GetTaskPayloadRequest(request) => &request.id,
4191            ServerRequest::CancelTaskRequest(request) => &request.id,
4192            ServerRequest::ListTasksRequest(request) => &request.id,
4193            ServerRequest::CreateMessageRequest(request) => &request.id,
4194            ServerRequest::ListRootsRequest(request) => &request.id,
4195            ServerRequest::ElicitRequest(request) => &request.id,
4196        }
4197    }
4198}
4199impl ClientRequest {
4200    pub fn request_id(&self) -> &RequestId {
4201        match self {
4202            ClientRequest::InitializeRequest(request) => &request.id,
4203            ClientRequest::PingRequest(request) => &request.id,
4204            ClientRequest::ListResourcesRequest(request) => &request.id,
4205            ClientRequest::ListResourceTemplatesRequest(request) => &request.id,
4206            ClientRequest::ReadResourceRequest(request) => &request.id,
4207            ClientRequest::SubscribeRequest(request) => &request.id,
4208            ClientRequest::UnsubscribeRequest(request) => &request.id,
4209            ClientRequest::ListPromptsRequest(request) => &request.id,
4210            ClientRequest::GetPromptRequest(request) => &request.id,
4211            ClientRequest::ListToolsRequest(request) => &request.id,
4212            ClientRequest::CallToolRequest(request) => &request.id,
4213            ClientRequest::GetTaskRequest(request) => &request.id,
4214            ClientRequest::GetTaskPayloadRequest(request) => &request.id,
4215            ClientRequest::CancelTaskRequest(request) => &request.id,
4216            ClientRequest::ListTasksRequest(request) => &request.id,
4217            ClientRequest::SetLevelRequest(request) => &request.id,
4218            ClientRequest::CompleteRequest(request) => &request.id,
4219        }
4220    }
4221}
4222impl From<&str> for IconTheme {
4223    fn from(s: &str) -> Self {
4224        match s {
4225            "dark" => Self::Dark,
4226            "light" => Self::Light,
4227            _ => Self::Light,
4228        }
4229    }
4230}
4231impl From<&str> for ElicitResultContent {
4232    fn from(value: &str) -> Self {
4233        Self::Primitive(ElicitResultContentPrimitive::String(value.to_string()))
4234    }
4235}
4236impl From<&str> for ElicitResultContentPrimitive {
4237    fn from(value: &str) -> Self {
4238        ElicitResultContentPrimitive::String(value.to_string())
4239    }
4240}
4241impl From<String> for ElicitResultContentPrimitive {
4242    fn from(value: String) -> Self {
4243        ElicitResultContentPrimitive::String(value)
4244    }
4245}
4246impl From<String> for ElicitResultContent {
4247    fn from(value: String) -> Self {
4248        Self::Primitive(ElicitResultContentPrimitive::String(value))
4249    }
4250}
4251impl From<Vec<&str>> for ElicitResultContent {
4252    fn from(value: Vec<&str>) -> Self {
4253        Self::StringArray(value.iter().map(|v| v.to_string()).collect())
4254    }
4255}
4256impl From<i64> for ElicitResultContent {
4257    fn from(value: i64) -> Self {
4258        Self::Primitive(value.into())
4259    }
4260}
4261impl CallToolRequestParams {
4262    pub fn new<T>(tool_name: T) -> Self
4263    where
4264        T: ToString,
4265    {
4266        Self {
4267            name: tool_name.to_string(),
4268            arguments: None,
4269            meta: None,
4270            task: None,
4271        }
4272    }
4273    /// Sets the arguments for the tool call.
4274    pub fn with_arguments(mut self, arguments: serde_json::Map<String, Value>) -> Self {
4275        self.arguments = Some(arguments);
4276        self
4277    }
4278    /// Assigns metadata to the CallToolRequestParams, enabling the inclusion of extra context or details.
4279    pub fn with_meta(mut self, meta: CallToolMeta) -> Self {
4280        self.meta = Some(meta);
4281        self
4282    }
4283    /// Set task metadata , requesting task-augmented execution for this request
4284    pub fn with_task(mut self, task: TaskMetadata) -> Self {
4285        self.task = Some(task);
4286        self
4287    }
4288}
4289/// END AUTO GENERATED
4290#[cfg(test)]
4291mod tests {
4292    use super::*;
4293    use serde_json::json;
4294
4295    #[test]
4296    fn test_detect_message_type() {
4297        // standard request
4298        let message = ClientJsonrpcRequest::new(RequestId::Integer(0), RequestFromClient::PingRequest(None));
4299        let result = detect_message_type(&json!(message));
4300        assert!(matches!(result, MessageTypes::Request));
4301
4302        // custom request
4303
4304        let result = detect_message_type(&json!({
4305        "id":0,
4306        "method":"add_numbers",
4307        "params":{},
4308        "jsonrpc":"2.0"
4309        }));
4310        assert!(matches!(result, MessageTypes::Request));
4311
4312        // standard notification
4313        let message = ClientJsonrpcNotification::new(NotificationFromClient::RootsListChangedNotification(None));
4314        let result = detect_message_type(&json!(message));
4315        assert!(matches!(result, MessageTypes::Notification));
4316
4317        // custom notification
4318        let result = detect_message_type(&json!({
4319            "method":"notifications/email_sent",
4320            "jsonrpc":"2.0"
4321        }));
4322        assert!(matches!(result, MessageTypes::Notification));
4323
4324        // standard response
4325        let message = ClientJsonrpcResponse::new(
4326            RequestId::Integer(0),
4327            ListRootsResult {
4328                meta: None,
4329                roots: vec![],
4330            }
4331            .into(),
4332        );
4333        let result = detect_message_type(&json!(message));
4334        assert!(matches!(result, MessageTypes::Response));
4335
4336        //custom response
4337
4338        let result = detect_message_type(&json!({
4339            "id":1,
4340            "jsonrpc":"2.0",
4341            "result":"{}",
4342        }));
4343        assert!(matches!(result, MessageTypes::Response));
4344
4345        // error message
4346        let message = JsonrpcErrorResponse::create(
4347            Some(RequestId::Integer(0)),
4348            RpcErrorCodes::INVALID_PARAMS,
4349            "Invalid params!".to_string(),
4350            None,
4351        );
4352        let result = detect_message_type(&json!(message));
4353        assert!(matches!(result, MessageTypes::Error));
4354
4355        // default
4356        let result = detect_message_type(&json!({}));
4357        assert!(matches!(result, MessageTypes::Request));
4358    }
4359}