Skip to main content

rust_mcp_schema/generated_schema/2026_07_28/
schema_utils.rs

1use crate::generated_schema::*;
2
3use serde::ser::SerializeStruct;
4use serde_json::{json, Value};
5use std::hash::{Hash, Hasher};
6use std::result;
7use std::{fmt::Display, str::FromStr};
8
9fn default_jsonrpc() -> String {
10    "2.0".to_string()
11}
12
13#[derive(Debug, PartialEq)]
14pub enum MessageTypes {
15    Request,
16    Response,
17    Notification,
18    Error,
19}
20/// Implements the `Display` trait for the `MessageTypes` enum,
21/// allowing it to be converted into a human-readable string.
22impl Display for MessageTypes {
23    /// Formats the `MessageTypes` enum variant as a string.
24    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
25        write!(
26            f,
27            "{}",
28            // Match the current enum variant and return a corresponding string
29            match self {
30                MessageTypes::Request => "Request",
31                MessageTypes::Response => "Response",
32                MessageTypes::Notification => "Notification",
33                MessageTypes::Error => "Error",
34            }
35        )
36    }
37}
38
39/// A utility function used internally to detect the message type from the payload.
40/// This function is used when deserializing a `ClientMessage` into strongly-typed structs that represent the specific message received.
41#[allow(dead_code)]
42fn detect_message_type(value: &serde_json::Value) -> MessageTypes {
43    let id_field = value.get("id");
44
45    if id_field.is_some() && value.get("error").is_some() {
46        return MessageTypes::Error;
47    }
48
49    let method_field = value.get("method");
50    let result_field = value.get("result");
51
52    if id_field.is_some() {
53        if result_field.is_some() && method_field.is_none() {
54            return MessageTypes::Response;
55        } else if method_field.is_some() {
56            return MessageTypes::Request;
57        }
58    } else if method_field.is_some() {
59        return MessageTypes::Notification;
60    }
61
62    MessageTypes::Request
63}
64
65/// Represents a generic MCP (Model Context Protocol) message.
66/// This trait defines methods to classify and extract information from messages.
67pub trait RpcMessage: McpMessage {
68    fn request_id(&self) -> Option<&RequestId>;
69    fn jsonrpc(&self) -> &str;
70    fn method(&self) -> Option<&str>;
71}
72
73pub trait McpMessage {
74    fn is_response(&self) -> bool;
75    fn is_request(&self) -> bool;
76    fn is_notification(&self) -> bool;
77    fn is_error(&self) -> bool;
78    fn message_type(&self) -> MessageTypes;
79}
80
81/// A trait for converting a message of type `T` into `Self`.
82/// This is useful for transforming mcp messages into a Type that could be serialized into a JsonrpcMessage.
83///
84/// Eventually, the ServerMessage can be serialized into a valid JsonrpcMessage for transmission over the transport.
85pub trait FromMessage<T>
86where
87    Self: Sized,
88{
89    fn from_message(message: T, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError>;
90}
91
92pub trait ToMessage<T>
93where
94    T: FromMessage<Self>,
95    Self: Sized,
96{
97    fn to_message(self, request_id: Option<RequestId>) -> std::result::Result<T, RpcError>;
98}
99
100//*******************************//
101//** RequestId Implementations **//
102//*******************************//
103
104// Implement PartialEq and Eq for RequestId
105impl PartialEq for RequestId {
106    fn eq(&self, other: &Self) -> bool {
107        match (self, other) {
108            (RequestId::String(a), RequestId::String(b)) => a == b,
109            (RequestId::Integer(a), RequestId::Integer(b)) => a == b,
110            _ => false, // Different variants are never equal
111        }
112    }
113}
114
115impl PartialEq<RequestId> for &RequestId {
116    fn eq(&self, other: &RequestId) -> bool {
117        (*self).eq(other)
118    }
119}
120
121impl Eq for RequestId {}
122
123// Implement Hash for RequestId, so we can store it in HashMaps, HashSets, etc.
124impl Hash for RequestId {
125    fn hash<H: Hasher>(&self, state: &mut H) {
126        match self {
127            RequestId::String(s) => {
128                0u8.hash(state); // Prefix with 0 for String variant
129                s.hash(state);
130            }
131            RequestId::Integer(i) => {
132                1u8.hash(state); // Prefix with 1 for Integer variant
133                i.hash(state);
134            }
135        }
136    }
137}
138
139impl core::fmt::Display for RequestId {
140    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
141        match *self {
142            RequestId::String(ref s) => write!(f, "{}", s),
143            RequestId::Integer(i) => write!(f, "{}", i),
144        }
145    }
146}
147//*******************//
148//** ClientMessage **//
149//*******************//
150
151/// "Similar to JsonrpcMessage, but with the variants restricted to client-side messages."
152/// ClientMessage represents a message sent by an MCP Client and received by an MCP Server.
153#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
154#[serde(untagged)]
155pub enum ClientMessage {
156    Request(ClientJsonrpcRequest),
157    Notification(ClientJsonrpcNotification),
158    Response(ClientJsonrpcResponse),
159    Error(JsonrpcErrorResponse),
160}
161
162impl ClientMessage {
163    /// Converts the current message into a `ClientJsonrpcResponse` if it's of the correct type.
164    ///
165    /// This function checks if the current message is of type `Response`. If so, it returns the
166    /// `ClientJsonrpcResponse` wrapped in a `Result::Ok`. If the message is not a `Response`,
167    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
168    ///
169    /// # Returns
170    /// - `Ok(ClientJsonrpcResponse)` if the message is a valid `Response`.
171    /// - `Err(RpcError)` if the message type is invalid
172    pub fn as_response(self) -> std::result::Result<ClientJsonrpcResponse, RpcError> {
173        if let Self::Response(response) = self {
174            Ok(response)
175        } else {
176            Err(RpcError::internal_error().with_message(format!(
177                "Invalid message type, expected: \"{}\" received\"{}\"",
178                MessageTypes::Response,
179                self.message_type()
180            )))
181        }
182    }
183
184    /// Converts the current message into a `ClientJsonrpcRequest` if it's of the correct type.
185    ///
186    /// This function checks if the current message is of type `Request`. If so, it returns the
187    /// `ClientJsonrpcRequest` wrapped in a `Result::Ok`. If the message is not a `Request`,
188    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
189    ///
190    /// # Returns
191    /// - `Ok(ClientJsonrpcRequest)` if the message is a valid `Request`.
192    /// - `Err(RpcError)` if the message type is invalid
193    pub fn as_request(self) -> std::result::Result<ClientJsonrpcRequest, RpcError> {
194        if let Self::Request(request) = self {
195            Ok(request)
196        } else {
197            Err(RpcError::internal_error().with_message(format!(
198                "Invalid message type, expected: \"{}\" received\"{}\"",
199                MessageTypes::Request,
200                self.message_type()
201            )))
202        }
203    }
204
205    /// Converts the current message into a `ClientJsonrpcNotification` if it's of the correct type.
206    ///
207    /// This function checks if the current message is of type `Notification`. If so, it returns the
208    /// `ClientJsonrpcNotification` wrapped in a `Result::Ok`. If the message is not a `Notification`,
209    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
210    ///
211    /// # Returns
212    /// - `Ok(ClientJsonrpcNotification)` if the message is a valid `Notification`.
213    /// - `Err(RpcError)` if the message type is invalid
214    pub fn as_notification(self) -> std::result::Result<ClientJsonrpcNotification, RpcError> {
215        if let Self::Notification(notification) = self {
216            Ok(notification)
217        } else {
218            Err(RpcError::internal_error().with_message(format!(
219                "Invalid message type, expected: \"{}\" received\"{}\"",
220                MessageTypes::Notification,
221                self.message_type()
222            )))
223        }
224    }
225
226    /// Converts the current message into a `JsonrpcErrorResponse` if it's of the correct type.
227    ///
228    /// This function checks if the current message is of type `Error`. If so, it returns the
229    /// `JsonrpcErrorResponse` wrapped in a `Result::Ok`. If the message is not a `Error`,
230    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
231    ///
232    /// # Returns
233    /// - `Ok(JsonrpcErrorResponse)` if the message is a valid `Error`.
234    /// - `Err(RpcError)` if the message type is invalid
235    pub fn as_error(self) -> std::result::Result<JsonrpcErrorResponse, RpcError> {
236        if let Self::Error(error) = self {
237            Ok(error)
238        } else {
239            Err(RpcError::internal_error().with_message(format!(
240                "Invalid message type, expected: \"{}\" received\"{}\"",
241                MessageTypes::Error,
242                self.message_type()
243            )))
244        }
245    }
246
247    /// Returns `true` if message is an `InitializeRequest`.
248    /// Note: InitializeRequest has been removed from the 2026-07-28 protocol.
249    /// This always returns `false`.
250    pub fn is_initialize_request(&self) -> bool {
251        false
252    }
253
254    /// Returns `true` if the message is an `InitializedNotification`
255    /// Note: InitializedNotification has been removed from the 2026-07-28 protocol.
256    /// This always returns `false`.
257    pub fn is_initialized_notification(&self) -> bool {
258        false
259    }
260}
261
262impl From<ClientJsonrpcNotification> for ClientMessage {
263    fn from(value: ClientJsonrpcNotification) -> Self {
264        Self::Notification(value)
265    }
266}
267
268impl From<ClientJsonrpcRequest> for ClientMessage {
269    fn from(value: ClientJsonrpcRequest) -> Self {
270        Self::Request(value)
271    }
272}
273
274impl From<ClientJsonrpcResponse> for ClientMessage {
275    fn from(value: ClientJsonrpcResponse) -> Self {
276        Self::Response(value)
277    }
278}
279
280impl RpcMessage for ClientMessage {
281    // Retrieves the request ID associated with the message, if applicable
282    fn request_id(&self) -> Option<&RequestId> {
283        match self {
284            // If the message is a request, return the associated request ID
285            ClientMessage::Request(client_jsonrpc_request) => match client_jsonrpc_request {
286                ClientJsonrpcRequest::Custom(request) => Some(&request.id),
287                _ => Some(client_jsonrpc_request.request_id()),
288            },
289            // Notifications do not have request IDs
290            ClientMessage::Notification(_) => None,
291            // If the message is a response, return the associated request ID
292            ClientMessage::Response(client_jsonrpc_response) => Some(&client_jsonrpc_response.id),
293            // If the message is an error, return the associated request ID
294            ClientMessage::Error(jsonrpc_error) => jsonrpc_error.id.as_ref(),
295        }
296    }
297
298    fn jsonrpc(&self) -> &str {
299        match self {
300            ClientMessage::Request(client_jsonrpc_request) => client_jsonrpc_request.jsonrpc(),
301            ClientMessage::Notification(notification) => notification.jsonrpc(),
302            ClientMessage::Response(client_jsonrpc_response) => client_jsonrpc_response.jsonrpc(),
303            ClientMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
304        }
305    }
306
307     fn method(&self) -> Option<&str> {
308        match self {
309            ClientMessage::Request(client_jsonrpc_request) => Some(client_jsonrpc_request.method()),
310            ClientMessage::Notification(client_jsonrpc_notification) => Some(client_jsonrpc_notification.method()),
311            ClientMessage::Response(_) => None,
312            ClientMessage::Error(_) => None,
313        }
314    }
315}
316
317// Implementing the `McpMessage` trait for `ClientMessage`
318impl McpMessage for ClientMessage {
319    // Returns true if the message is a response type
320    fn is_response(&self) -> bool {
321        matches!(self, ClientMessage::Response(_))
322    }
323
324    // Returns true if the message is a request type
325    fn is_request(&self) -> bool {
326        matches!(self, ClientMessage::Request(_))
327    }
328
329    // Returns true if the message is a notification type (i.e., does not expect a response)
330    fn is_notification(&self) -> bool {
331        matches!(self, ClientMessage::Notification(_))
332    }
333
334    // Returns true if the message represents an error
335    fn is_error(&self) -> bool {
336        matches!(self, ClientMessage::Error(_))
337    }
338
339    /// Determines the type of the message and returns the corresponding `MessageTypes` variant.
340    fn message_type(&self) -> MessageTypes {
341        match self {
342            ClientMessage::Request(_) => MessageTypes::Request,
343            ClientMessage::Notification(_) => MessageTypes::Notification,
344            ClientMessage::Response(_) => MessageTypes::Response,
345            ClientMessage::Error(_) => MessageTypes::Error,
346        }
347    }
348}
349
350//**************************//
351//** ClientJsonrpcRequest **//
352//**************************//
353
354/// "Similar to JsonrpcRequest , but with the variants restricted to client-side requests."
355#[derive(Clone, Debug, ::serde::Serialize, ::serde::Deserialize)]
356#[serde(untagged)]
357pub enum ClientJsonrpcRequest {
358    Standard(ClientRequest),
359    Custom(JsonrpcRequest),
360}
361
362impl ClientJsonrpcRequest {
363    pub fn new(id: RequestId, request: RequestFromClient) -> Self {
364        let client_request = match request {
365            RequestFromClient::ListResourcesRequest(params) => ClientRequest::ListResourcesRequest(ListResourcesRequest::new(id, params)),
366            RequestFromClient::ListResourceTemplatesRequest(params) => ClientRequest::ListResourceTemplatesRequest(ListResourceTemplatesRequest::new(id, params)),
367            RequestFromClient::ReadResourceRequest(params) => ClientRequest::ReadResourceRequest(ReadResourceRequest::new(id, params)),
368            RequestFromClient::ListPromptsRequest(params) => ClientRequest::ListPromptsRequest(ListPromptsRequest::new(id, params)),
369            RequestFromClient::GetPromptRequest(params) => ClientRequest::GetPromptRequest(GetPromptRequest::new(id, params)),
370            RequestFromClient::ListToolsRequest(params) => ClientRequest::ListToolsRequest(ListToolsRequest::new(id, params)),
371            RequestFromClient::CallToolRequest(params) => ClientRequest::CallToolRequest(CallToolRequest::new(id, params)),
372            RequestFromClient::CompleteRequest(params) => ClientRequest::CompleteRequest(CompleteRequest::new(id, params)),
373            RequestFromClient::DiscoverRequest(params) => ClientRequest::DiscoverRequest(DiscoverRequest::new(id, params)),
374            RequestFromClient::SubscriptionsListenRequest(params) => ClientRequest::SubscriptionsListenRequest(SubscriptionsListenRequest::new(id, params)),
375            RequestFromClient::CustomRequest(params) => {
376                return Self::Custom(JsonrpcRequest::new(id, params.method, params.params))
377            }
378        };
379        Self::Standard(client_request)
380    }
381
382    pub fn jsonrpc(&self) -> &::std::string::String {
383        match self {
384            ClientJsonrpcRequest::Standard(inner) => match inner {
385                ClientRequest::ListResourcesRequest(r) => r.jsonrpc(),
386                ClientRequest::ListResourceTemplatesRequest(r) => r.jsonrpc(),
387                ClientRequest::ReadResourceRequest(r) => r.jsonrpc(),
388                ClientRequest::ListPromptsRequest(r) => r.jsonrpc(),
389                ClientRequest::GetPromptRequest(r) => r.jsonrpc(),
390                ClientRequest::ListToolsRequest(r) => r.jsonrpc(),
391                ClientRequest::CallToolRequest(r) => r.jsonrpc(),
392                ClientRequest::CompleteRequest(r) => r.jsonrpc(),
393                ClientRequest::DiscoverRequest(r) => r.jsonrpc(),
394                ClientRequest::SubscriptionsListenRequest(r) => r.jsonrpc(),
395            },
396            ClientJsonrpcRequest::Custom(request) => request.jsonrpc(),
397        }
398    }
399
400    pub fn request_id(&self) -> &RequestId {
401        match self {
402            ClientJsonrpcRequest::Standard(inner) => match inner {
403                ClientRequest::ListResourcesRequest(r) => &r.id,
404                ClientRequest::ListResourceTemplatesRequest(r) => &r.id,
405                ClientRequest::ReadResourceRequest(r) => &r.id,
406                ClientRequest::ListPromptsRequest(r) => &r.id,
407                ClientRequest::GetPromptRequest(r) => &r.id,
408                ClientRequest::ListToolsRequest(r) => &r.id,
409                ClientRequest::CallToolRequest(r) => &r.id,
410                ClientRequest::CompleteRequest(r) => &r.id,
411                ClientRequest::DiscoverRequest(r) => &r.id,
412                ClientRequest::SubscriptionsListenRequest(r) => &r.id,
413            },
414            ClientJsonrpcRequest::Custom(request) => &request.id,
415        }
416    }
417
418    pub fn method(&self) -> &str {
419        match self {
420            ClientJsonrpcRequest::Standard(inner) => match inner {
421                ClientRequest::ListResourcesRequest(r) => r.method(),
422                ClientRequest::ListResourceTemplatesRequest(r) => r.method(),
423                ClientRequest::ReadResourceRequest(r) => r.method(),
424                ClientRequest::ListPromptsRequest(r) => r.method(),
425                ClientRequest::GetPromptRequest(r) => r.method(),
426                ClientRequest::ListToolsRequest(r) => r.method(),
427                ClientRequest::CallToolRequest(r) => r.method(),
428                ClientRequest::CompleteRequest(r) => r.method(),
429                ClientRequest::DiscoverRequest(r) => r.method(),
430                ClientRequest::SubscriptionsListenRequest(r) => r.method(),
431            },
432            ClientJsonrpcRequest::Custom(request) => request.method.as_str(),
433        }
434    }
435}
436
437
438impl From<ClientJsonrpcRequest> for RequestFromClient {
439    fn from(request: ClientJsonrpcRequest) -> Self {
440        match request {
441            ClientJsonrpcRequest::Standard(inner) => match inner {
442                ClientRequest::ListResourcesRequest(r) => Self::ListResourcesRequest(r.params),
443                ClientRequest::ListResourceTemplatesRequest(r) => Self::ListResourceTemplatesRequest(r.params),
444                ClientRequest::ReadResourceRequest(r) => Self::ReadResourceRequest(r.params),
445                ClientRequest::ListPromptsRequest(r) => Self::ListPromptsRequest(r.params),
446                ClientRequest::GetPromptRequest(r) => Self::GetPromptRequest(r.params),
447                ClientRequest::ListToolsRequest(r) => Self::ListToolsRequest(r.params),
448                ClientRequest::CallToolRequest(r) => Self::CallToolRequest(r.params),
449                ClientRequest::CompleteRequest(r) => Self::CompleteRequest(r.params),
450                ClientRequest::DiscoverRequest(r) => Self::DiscoverRequest(r.params),
451                ClientRequest::SubscriptionsListenRequest(r) => Self::SubscriptionsListenRequest(r.params),
452            },
453            ClientJsonrpcRequest::Custom(request) => Self::CustomRequest(CustomRequest {
454                method: request.method,
455                params: request.params,
456            }),
457        }
458    }
459}
460
461/// Formats the ClientJsonrpcRequest as a JSON string.
462impl Display for ClientJsonrpcRequest {
463    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
464        write!(
465            f,
466            "{}",
467            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
468        )
469    }
470}
471
472impl FromStr for ClientJsonrpcRequest {
473    type Err = RpcError;
474
475    /// Parses a JSON-RPC request from a string.
476    ///
477    /// This implementation allows `ClientJsonrpcRequest` to be created
478    /// from a JSON string using the `from_str` method.
479    ///
480    /// # Arguments
481    /// * `s` - A JSON string representing a JSON-RPC request.
482    ///
483    /// # Returns
484    /// * `Ok(ClientJsonrpcRequest)` if parsing is successful.
485    /// * `Err(RpcError)` if the string is not valid JSON.
486    ///
487    /// # Example
488    /// ```
489    /// use std::str::FromStr;
490    /// use rust_mcp_schema::schema_utils::ClientJsonrpcRequest;
491    ///
492    /// let json = r#"{"jsonrpc": "2.0", "method": "initialize", "id": 1}"#;
493    /// let request = ClientJsonrpcRequest::from_str(json);
494    /// assert!(request.is_ok());
495    /// ```
496    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
497        serde_json::from_str(s)
498            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
499    }
500}
501
502//*************************//
503//** Request From Client **//
504//*************************//
505
506/// To determine standard and custom request from the client side
507/// Custom requests are of type serde_json::Value and can be deserialized into any custom type.
508#[allow(clippy::large_enum_variant)]
509#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
510#[serde(untagged)]
511pub enum RequestFromClient {
512    ListResourcesRequest(PaginatedRequestParams),
513    ListResourceTemplatesRequest(PaginatedRequestParams),
514    ReadResourceRequest(ReadResourceRequestParams),
515    ListPromptsRequest(PaginatedRequestParams),
516    GetPromptRequest(GetPromptRequestParams),
517    ListToolsRequest(PaginatedRequestParams),
518    CallToolRequest(CallToolRequestParams),
519    CompleteRequest(CompleteRequestParams),
520    DiscoverRequest(RequestParams),
521    SubscriptionsListenRequest(SubscriptionsListenRequestParams),
522    CustomRequest(CustomRequest),
523}
524
525impl RequestFromClient {
526    pub fn method(&self) -> &str {
527        match self {
528            RequestFromClient::ListResourcesRequest(_request) => ListResourcesRequest::method_value(),
529            RequestFromClient::ListResourceTemplatesRequest(_request) => ListResourceTemplatesRequest::method_value(),
530            RequestFromClient::ReadResourceRequest(_request) => ReadResourceRequest::method_value(),
531            RequestFromClient::ListPromptsRequest(_request) => ListPromptsRequest::method_value(),
532            RequestFromClient::GetPromptRequest(_request) => GetPromptRequest::method_value(),
533            RequestFromClient::ListToolsRequest(_request) => ListToolsRequest::method_value(),
534            RequestFromClient::CallToolRequest(_request) => CallToolRequest::method_value(),
535            RequestFromClient::CompleteRequest(_request) => CompleteRequest::method_value(),
536            RequestFromClient::DiscoverRequest(_request) => DiscoverRequest::method_value(),
537            RequestFromClient::SubscriptionsListenRequest(_request) => SubscriptionsListenRequest::method_value(),
538            RequestFromClient::CustomRequest(request) => request.method.as_str(),
539        }
540    }
541    /// Returns `true` if the request is an `InitializeRequest`.
542    /// Note: InitializeRequest has been removed from the 2026-07-28 protocol.
543    /// This always returns `false`.
544    pub fn is_initialize_request(&self) -> bool {
545        false
546    }
547
548    /// Stamps a `RequestMetaObject` (`_meta`) onto the request params.
549    ///
550    /// `params._meta` is required on every request in the 2026-07-28 protocol, so the SDK
551    /// typically builds one connection-level meta (protocol version, client capabilities,
552    /// client info) and stamps it onto each outgoing request via this method.
553    /// `CustomRequest` carries arbitrary params and is left unchanged.
554    pub fn with_meta(mut self, meta: RequestMetaObject) -> Self {
555        match &mut self {
556            RequestFromClient::ListResourcesRequest(params) => params.meta = meta,
557            RequestFromClient::ListResourceTemplatesRequest(params) => params.meta = meta,
558            RequestFromClient::ReadResourceRequest(params) => params.meta = meta,
559            RequestFromClient::ListPromptsRequest(params) => params.meta = meta,
560            RequestFromClient::GetPromptRequest(params) => params.meta = meta,
561            RequestFromClient::ListToolsRequest(params) => params.meta = meta,
562            RequestFromClient::CallToolRequest(params) => params.meta = meta,
563            RequestFromClient::CompleteRequest(params) => params.meta = meta,
564            RequestFromClient::DiscoverRequest(params) => params.meta = meta,
565            RequestFromClient::SubscriptionsListenRequest(params) => params.meta = meta,
566            RequestFromClient::CustomRequest(_) => {}
567        }
568        self
569    }
570
571    /// Returns a reference to the request's `RequestMetaObject` (`_meta`),
572    /// or `None` for `CustomRequest`.
573    pub fn meta(&self) -> Option<&RequestMetaObject> {
574        match self {
575            RequestFromClient::ListResourcesRequest(params) => Some(&params.meta),
576            RequestFromClient::ListResourceTemplatesRequest(params) => Some(&params.meta),
577            RequestFromClient::ReadResourceRequest(params) => Some(&params.meta),
578            RequestFromClient::ListPromptsRequest(params) => Some(&params.meta),
579            RequestFromClient::GetPromptRequest(params) => Some(&params.meta),
580            RequestFromClient::ListToolsRequest(params) => Some(&params.meta),
581            RequestFromClient::CallToolRequest(params) => Some(&params.meta),
582            RequestFromClient::CompleteRequest(params) => Some(&params.meta),
583            RequestFromClient::DiscoverRequest(params) => Some(&params.meta),
584            RequestFromClient::SubscriptionsListenRequest(params) => Some(&params.meta),
585            RequestFromClient::CustomRequest(_) => None,
586        }
587    }
588
589    /// Fills in `inputResponses` and `requestState` to retry the request after the server
590    /// answered with an `input_required` result (the 2026-07-28 mid-request input flow).
591    ///
592    /// Only `CallToolRequest`, `GetPromptRequest`, and `ReadResourceRequest` accept input
593    /// responses per the spec; any other variant returns an `RpcError`.
594    pub fn with_input_responses(
595        self,
596        input_responses: InputResponses,
597        request_state: Option<String>,
598    ) -> std::result::Result<Self, RpcError> {
599        match self {
600            RequestFromClient::CallToolRequest(mut params) => {
601                params.input_responses = Some(input_responses);
602                params.request_state = request_state;
603                Ok(RequestFromClient::CallToolRequest(params))
604            }
605            RequestFromClient::GetPromptRequest(mut params) => {
606                params.input_responses = Some(input_responses);
607                params.request_state = request_state;
608                Ok(RequestFromClient::GetPromptRequest(params))
609            }
610            RequestFromClient::ReadResourceRequest(mut params) => {
611                params.input_responses = Some(input_responses);
612                params.request_state = request_state;
613                Ok(RequestFromClient::ReadResourceRequest(params))
614            }
615            other => Err(RpcError::invalid_params()
616                .with_message(format!("`{}` does not accept inputResponses", other.method()))),
617        }
618    }
619}
620
621// impl From<ClientRequest> for RequestFromClient {
622//     fn from(value: ClientRequest) -> Self {
623//         Self::ClientRequest(value)
624//     }
625// }
626
627// impl From<serde_json::Value> for RequestFromClient {
628//     fn from(value: serde_json::Value) -> Self {
629//         Self::CustomRequest(value)
630//     }
631// }
632
633// impl<'de> serde::Deserialize<'de> for RequestFromClient {
634//     fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
635//     where
636//         D: serde::Deserializer<'de>,
637//     {
638//         let raw_value = Value::deserialize(deserializer)?;
639
640//         let client_result = ClientRequest::deserialize(&raw_value);
641
642//         match client_result {
643//             Ok(client_request) => Ok(Self::ClientRequest(client_request)),
644//             Err(_) => Ok(Self::CustomRequest(raw_value)),
645//         }
646//     }
647// }
648
649//*******************************//
650//** ClientJsonrpcNotification **//
651//*******************************//
652
653/// "Similar to JsonrpcNotification , but with the variants restricted to client-side notifications."
654#[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)]
655#[serde(untagged)]
656pub enum ClientJsonrpcNotification {
657    CancelledNotification(CancelledNotification),
658    CustomNotification(JsonrpcNotification),
659}
660
661impl ClientJsonrpcNotification {
662    pub fn new(notification: NotificationFromClient) -> Self {
663        match notification {
664            NotificationFromClient::CancelledNotification(params) => {
665                Self::CancelledNotification(CancelledNotification::new(params))
666            }
667            NotificationFromClient::CustomNotification(params) => {
668                Self::CustomNotification(JsonrpcNotification::new(params.method, params.params))
669            }
670        }
671    }
672    pub fn jsonrpc(&self) -> &::std::string::String {
673        match self {
674            ClientJsonrpcNotification::CancelledNotification(notification) => notification.jsonrpc(),
675            ClientJsonrpcNotification::CustomNotification(notification) => notification.jsonrpc(),
676        }
677    }
678
679    pub fn method(&self) -> &str {
680        match self {
681            ClientJsonrpcNotification::CancelledNotification(notification) => notification.method(),
682            ClientJsonrpcNotification::CustomNotification(notification) => notification.method.as_str(),
683        }
684    }
685}
686
687impl From<ClientJsonrpcNotification> for NotificationFromClient {
688    fn from(notification: ClientJsonrpcNotification) -> Self {
689        match notification {
690            ClientJsonrpcNotification::CancelledNotification(notification) => {
691                Self::CancelledNotification(notification.params)
692            }
693            ClientJsonrpcNotification::CustomNotification(notification) => Self::CustomNotification(CustomNotification {
694                method: notification.method,
695                params: notification.params,
696            }),
697        }
698    }
699}
700
701/// Formats the ClientJsonrpcNotification as a JSON string.
702impl Display for ClientJsonrpcNotification {
703    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
704        write!(
705            f,
706            "{}",
707            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
708        )
709    }
710}
711
712impl FromStr for ClientJsonrpcNotification {
713    type Err = RpcError;
714
715    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
716        serde_json::from_str(s)
717            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
718    }
719}
720
721//*******************************//
722//**  NotificationFromClient   **//
723//*******************************//
724
725/// To determine standard and custom notifications received from the MCP Client
726/// Custom notifications are of type serde_json::Value and can be deserialized into any custom type.
727#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
728#[serde(untagged)]
729pub enum NotificationFromClient {
730    CancelledNotification(CancelledNotificationParams),
731    CustomNotification(CustomNotification),
732}
733
734// impl TryFrom<NotificationFromClient> for ClientNotification {
735//     type Error = RpcError;
736//     fn try_from(value: NotificationFromClient) -> result::Result<Self, Self::Error> {
737//         if let NotificationFromClient::ClientNotification(client_notification) = value {
738//             Ok(client_notification)
739//         } else {
740//             Err(RpcError::internal_error().with_message("Not a ClientNotification".to_string()))
741//         }
742//     }
743// }
744
745impl NotificationFromClient {
746    pub fn method(&self) -> &str {
747        match self {
748            NotificationFromClient::CancelledNotification(_notification) => CancelledNotification::method_value(),
749            NotificationFromClient::CustomNotification(notification) => notification.method.as_str(),
750        }
751    }
752}
753
754//*******************************//
755//**   ClientJsonrpcResponse   **//
756//*******************************//
757
758/// "Similar to JsonrpcResponse , but with the variants restricted to client-side responses."
759#[derive(Clone, Debug)]
760pub struct ClientJsonrpcResponse {
761    pub id: RequestId,
762    jsonrpc: ::std::string::String,
763    pub result: ResultFromClient,
764}
765
766impl ClientJsonrpcResponse {
767    pub fn new(id: RequestId, result: ResultFromClient) -> Self {
768        Self {
769            id,
770            jsonrpc: JSONRPC_VERSION.to_string(),
771            result,
772        }
773    }
774    pub fn jsonrpc(&self) -> &::std::string::String {
775        &self.jsonrpc
776    }
777}
778
779/// Formats the ClientJsonrpcResponse as a JSON string.
780impl Display for ClientJsonrpcResponse {
781    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
782        write!(
783            f,
784            "{}",
785            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
786        )
787    }
788}
789
790impl FromStr for ClientJsonrpcResponse {
791    type Err = RpcError;
792
793    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
794        serde_json::from_str(s)
795            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
796    }
797}
798//*******************************//
799//**      ResultFromClient     **//
800//*******************************//
801
802#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
803#[serde(untagged)]
804pub enum ResultFromClient {
805    CreateMessageResult(CreateMessageResult),
806    ListRootsResult(ListRootsResult),
807    ElicitResult(ElicitResult),
808    Result(Result),
809}
810
811//*******************************//
812//**       ClientMessage       **//
813//*******************************//
814
815impl FromStr for ClientMessage {
816    type Err = RpcError;
817
818    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
819        serde_json::from_str(s)
820            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
821    }
822}
823
824impl Display for ClientMessage {
825    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
826        write!(
827            f,
828            "{}",
829            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
830        )
831    }
832}
833
834//*******************//
835//** ServerMessage **//
836//*******************//
837
838/// "Similar to JsonrpcMessage, but with the variants restricted to client-side messages."
839/// ServerMessage represents a message sent by an MCP Server and received by an MCP Client.
840#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
841#[serde(untagged)]
842pub enum ServerMessage {
843    Request(ServerJsonrpcRequest),
844    Notification(ServerJsonrpcNotification),
845    Response(ServerJsonrpcResponse),
846    Error(JsonrpcErrorResponse),
847}
848
849impl ServerMessage {
850    /// Converts the current message into a `ServerJsonrpcResponse` if it's of the correct type.
851    ///
852    /// This function checks if the current message is of type `Response`. If so, it returns the
853    /// `ServerJsonrpcResponse` wrapped in a `Result::Ok`. If the message is not a `Response`,
854    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
855    ///
856    /// # Returns
857    /// - `Ok(ServerJsonrpcResponse)` if the message is a valid `Response`.
858    /// - `Err(RpcError)` if the message type is invalid
859    pub fn as_response(self) -> std::result::Result<ServerJsonrpcResponse, RpcError> {
860        if let Self::Response(response) = self {
861            Ok(response)
862        } else {
863            Err(RpcError::internal_error().with_message(format!(
864                "Invalid message type, expected: \"{}\" received\"{}\"",
865                MessageTypes::Response,
866                self.message_type()
867            )))
868        }
869    }
870
871    /// Converts the current message into a `ServerJsonrpcRequest` if it's of the correct type.
872    ///
873    /// This function checks if the current message is of type `Request`. If so, it returns the
874    /// `ServerJsonrpcRequest` wrapped in a `Result::Ok`. If the message is not a `Request`,
875    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
876    ///
877    /// # Returns
878    /// - `Ok(ServerJsonrpcRequest)` if the message is a valid `Request`.
879    /// - `Err(RpcError)` if the message type is invalid
880    pub fn as_request(self) -> std::result::Result<ServerJsonrpcRequest, RpcError> {
881        if let Self::Request(request) = self {
882            Ok(request)
883        } else {
884            Err(RpcError::internal_error().with_message(format!(
885                "Invalid message type, expected: \"{}\" received\"{}\"",
886                MessageTypes::Request,
887                self.message_type()
888            )))
889        }
890    }
891
892    /// Converts the current message into a `ServerJsonrpcNotification` if it's of the correct type.
893    ///
894    /// This function checks if the current message is of type `Notification`. If so, it returns the
895    /// `ServerJsonrpcNotification` wrapped in a `Result::Ok`. If the message is not a `Notification`,
896    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
897    ///
898    /// # Returns
899    /// - `Ok(ServerJsonrpcNotification)` if the message is a valid `Notification`.
900    /// - `Err(RpcError)` if the message type is invalid
901    pub fn as_notification(self) -> std::result::Result<ServerJsonrpcNotification, RpcError> {
902        if let Self::Notification(notification) = self {
903            Ok(notification)
904        } else {
905            Err(RpcError::internal_error().with_message(format!(
906                "Invalid message type, expected: \"{}\" received\"{}\"",
907                MessageTypes::Notification,
908                self.message_type()
909            )))
910        }
911    }
912
913    /// Converts the current message into a `JsonrpcErrorResponse` if it's of the correct type.
914    ///
915    /// This function checks if the current message is of type `Error`. If so, it returns the
916    /// `JsonrpcErrorResponse` wrapped in a `Result::Ok`. If the message is not a `Error`,
917    /// it returns an error with a descriptive message indicating the mismatch in expected message types.
918    ///
919    /// # Returns
920    /// - `Ok(JsonrpcErrorResponse)` if the message is a valid `Error`.
921    /// - `Err(RpcError)` if the message type is invalid
922    pub fn as_error(self) -> std::result::Result<JsonrpcErrorResponse, RpcError> {
923        if let Self::Error(error) = self {
924            Ok(error)
925        } else {
926            Err(RpcError::internal_error().with_message(format!(
927                "Invalid message type, expected: \"{}\" received\"{}\"",
928                MessageTypes::Error,
929                self.message_type()
930            )))
931        }
932    }
933}
934
935impl From<ServerJsonrpcNotification> for ServerMessage {
936    fn from(value: ServerJsonrpcNotification) -> Self {
937        Self::Notification(value)
938    }
939}
940
941impl From<ServerJsonrpcRequest> for ServerMessage {
942    fn from(value: ServerJsonrpcRequest) -> Self {
943        Self::Request(value)
944    }
945}
946
947impl From<ServerJsonrpcResponse> for ServerMessage {
948    fn from(value: ServerJsonrpcResponse) -> Self {
949        Self::Response(value)
950    }
951}
952
953impl RpcMessage for ServerMessage {
954    // Retrieves the request ID associated with the message, if applicable
955    fn request_id(&self) -> Option<&RequestId> {
956        match self {
957            ServerMessage::Request(server_jsonrpc_request) => Some(server_jsonrpc_request.request_id()),
958            // Notifications do not have request IDs
959            ServerMessage::Notification(_) => None,
960            // If the message is a response, return the associated request ID
961            ServerMessage::Response(server_jsonrpc_response) => Some(&server_jsonrpc_response.id),
962            // If the message is an error, return the associated request ID
963            ServerMessage::Error(jsonrpc_error) => jsonrpc_error.id.as_ref(),
964        }
965    }
966
967    fn jsonrpc(&self) -> &str {
968        match self {
969            ServerMessage::Request(server_jsonrpc_request) => server_jsonrpc_request.jsonrpc(),
970
971            // Notifications do not have request IDs
972            ServerMessage::Notification(notification) => notification.jsonrpc(),
973            // If the message is a response, return the associated request ID
974            ServerMessage::Response(server_jsonrpc_response) => server_jsonrpc_response.jsonrpc(),
975            // If the message is an error, return the associated request ID
976            ServerMessage::Error(jsonrpc_error) => jsonrpc_error.jsonrpc(),
977        }
978    }
979
980    fn method(&self) -> Option<&str> {
981        match self {
982            ServerMessage::Request(server_jsonrpc_request) => Some(server_jsonrpc_request.method()),
983            ServerMessage::Notification(server_jsonrpc_notification) => Some(server_jsonrpc_notification.method()),
984            ServerMessage::Response(_) => None,
985            ServerMessage::Error(_) => None,
986        }
987    }
988}
989
990// Implementing the `McpMessage` trait for `ServerMessage`
991impl McpMessage for ServerMessage {
992    // Returns true if the message is a response type
993    fn is_response(&self) -> bool {
994        matches!(self, ServerMessage::Response(_))
995    }
996
997    // Returns true if the message is a request type
998    fn is_request(&self) -> bool {
999        matches!(self, ServerMessage::Request(_))
1000    }
1001
1002    // Returns true if the message is a notification type (i.e., does not expect a response)
1003    fn is_notification(&self) -> bool {
1004        matches!(self, ServerMessage::Notification(_))
1005    }
1006
1007    // Returns true if the message represents an error
1008    fn is_error(&self) -> bool {
1009        matches!(self, ServerMessage::Error(_))
1010    }
1011
1012    /// Determines the type of the message and returns the corresponding `MessageTypes` variant.
1013    fn message_type(&self) -> MessageTypes {
1014        match self {
1015            ServerMessage::Request(_) => MessageTypes::Request,
1016            ServerMessage::Notification(_) => MessageTypes::Notification,
1017            ServerMessage::Response(_) => MessageTypes::Response,
1018            ServerMessage::Error(_) => MessageTypes::Error,
1019        }
1020    }
1021}
1022
1023impl FromStr for ServerMessage {
1024    type Err = RpcError;
1025
1026    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1027        serde_json::from_str(s)
1028            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1029    }
1030}
1031
1032impl Display for ServerMessage {
1033    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1034        write!(
1035            f,
1036            "{}",
1037            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1038        )
1039    }
1040}
1041
1042//**************************//
1043//** ServerJsonrpcRequest **//
1044//**************************//
1045
1046/// "Similar to JsonrpcRequest , but with the variants restricted to client-side requests."
1047#[derive(Clone, Debug, ::serde::Serialize, ::serde::Deserialize)]
1048#[allow(clippy::large_enum_variant)]
1049#[serde(untagged)]
1050pub enum ServerJsonrpcRequest {
1051    CreateMessageRequest {
1052        id: RequestId,
1053        #[serde(default = "default_jsonrpc")]
1054        jsonrpc: String,
1055        #[serde(flatten)]
1056        request: CreateMessageRequest,
1057    },
1058    ListRootsRequest {
1059        id: RequestId,
1060        #[serde(default = "default_jsonrpc")]
1061        jsonrpc: String,
1062        #[serde(flatten)]
1063        request: ListRootsRequest,
1064    },
1065    ElicitRequest {
1066        id: RequestId,
1067        #[serde(default = "default_jsonrpc")]
1068        jsonrpc: String,
1069        #[serde(flatten)]
1070        request: ElicitRequest,
1071    },
1072    CustomRequest(JsonrpcRequest),
1073}
1074
1075impl ServerJsonrpcRequest {
1076    pub fn new(request_id: RequestId, request: RequestFromServer) -> Self {
1077        match request {
1078            RequestFromServer::CreateMessageRequest(params) => {
1079                Self::CreateMessageRequest {
1080                    id: request_id.clone(),
1081                    jsonrpc: "2.0".to_string(),
1082                    request: CreateMessageRequest::new(params),
1083                }
1084            }
1085            RequestFromServer::ListRootsRequest(params) => Self::ListRootsRequest {
1086                id: request_id.clone(),
1087                jsonrpc: "2.0".to_string(),
1088                request: ListRootsRequest::new(params),
1089            },
1090            RequestFromServer::ElicitRequest(params) => Self::ElicitRequest {
1091                id: request_id.clone(),
1092                jsonrpc: "2.0".to_string(),
1093                request: ElicitRequest::new(params),
1094            },
1095            RequestFromServer::CustomRequest(request) => {
1096                Self::CustomRequest(JsonrpcRequest::new(request_id, request.method, request.params))
1097            }
1098        }
1099    }
1100
1101    pub fn request_id(&self) -> &RequestId {
1102        match self {
1103            ServerJsonrpcRequest::CreateMessageRequest { id, .. } => id,
1104            ServerJsonrpcRequest::ListRootsRequest { id, .. } => id,
1105            ServerJsonrpcRequest::ElicitRequest { id, .. } => id,
1106            ServerJsonrpcRequest::CustomRequest(request) => &request.id,
1107        }
1108    }
1109
1110    pub fn jsonrpc(&self) -> &str {
1111        match self {
1112            ServerJsonrpcRequest::CreateMessageRequest { jsonrpc, .. } => jsonrpc,
1113            ServerJsonrpcRequest::ListRootsRequest { jsonrpc, .. } => jsonrpc,
1114            ServerJsonrpcRequest::ElicitRequest { jsonrpc, .. } => jsonrpc,
1115            ServerJsonrpcRequest::CustomRequest(request) => request.jsonrpc(),
1116        }
1117    }
1118
1119    pub fn method(&self) -> &str {
1120        match self {
1121            ServerJsonrpcRequest::CreateMessageRequest { request, .. } => request.method(),
1122            ServerJsonrpcRequest::ListRootsRequest { request, .. } => request.method(),
1123            ServerJsonrpcRequest::ElicitRequest { request, .. } => request.method(),
1124            ServerJsonrpcRequest::CustomRequest(request) => request.method.as_str(),
1125        }
1126    }
1127}
1128
1129/// Formats the ServerJsonrpcRequest as a JSON string.
1130impl Display for ServerJsonrpcRequest {
1131    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1132        write!(
1133            f,
1134            "{}",
1135            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1136        )
1137    }
1138}
1139
1140impl FromStr for ServerJsonrpcRequest {
1141    type Err = RpcError;
1142
1143    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1144        serde_json::from_str(s)
1145            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1146    }
1147}
1148
1149#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
1150pub struct CustomRequest {
1151    pub method: ::std::string::String,
1152    #[serde(default, skip_serializing_if = "::std::option::Option::is_none")]
1153    pub params: ::std::option::Option<::serde_json::Map<::std::string::String, ::serde_json::Value>>,
1154}
1155
1156//*************************//
1157//** Request From Server **//
1158//*************************//
1159
1160/// To determine standard and custom request from the server side
1161/// Custom requests are of type serde_json::Value and can be deserialized into any custom type.
1162#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1163#[serde(untagged)]
1164pub enum RequestFromServer {
1165    CreateMessageRequest(CreateMessageRequestParams),
1166    ListRootsRequest(Option<ListRootsRequestParams>),
1167    ElicitRequest(ElicitRequestParams),
1168    CustomRequest(CustomRequest),
1169}
1170
1171impl From<ServerJsonrpcRequest> for RequestFromServer {
1172    fn from(request: ServerJsonrpcRequest) -> Self {
1173        match request {
1174            ServerJsonrpcRequest::CreateMessageRequest { request, .. } => Self::CreateMessageRequest(request.params),
1175            ServerJsonrpcRequest::ListRootsRequest { request, .. } => Self::ListRootsRequest(request.params),
1176            ServerJsonrpcRequest::ElicitRequest { request, .. } => Self::ElicitRequest(request.params),
1177            ServerJsonrpcRequest::CustomRequest(request) => Self::CustomRequest(CustomRequest {
1178                method: request.method,
1179                params: request.params,
1180            }),
1181        }
1182    }
1183}
1184
1185impl RequestFromServer {
1186    pub fn method(&self) -> &str {
1187        match self {
1188            RequestFromServer::CreateMessageRequest(_request) => CreateMessageRequest::method_value(),
1189            RequestFromServer::ListRootsRequest(_request) => ListRootsRequest::method_value(),
1190            RequestFromServer::ElicitRequest(_request) => ElicitRequest::method_value(),
1191            RequestFromServer::CustomRequest(request) => request.method.as_str(),
1192        }
1193    }
1194}
1195
1196//*******************************//
1197//** ServerJsonrpcNotification **//
1198//*******************************//
1199
1200/// "Similar to JsonrpcNotification , but with the variants restricted to server-side notifications."
1201#[derive(Clone, Debug, ::serde::Deserialize, ::serde::Serialize)]
1202#[serde(untagged)]
1203pub enum ServerJsonrpcNotification {
1204    Standard(ServerNotification),
1205    Custom(JsonrpcNotification),
1206}
1207
1208impl From<ServerJsonrpcNotification> for NotificationFromServer {
1209    fn from(notification: ServerJsonrpcNotification) -> Self {
1210        match notification {
1211            ServerJsonrpcNotification::Standard(inner) => match inner {
1212                ServerNotification::CancelledNotification(n) => Self::CancelledNotification(n.params),
1213                ServerNotification::ProgressNotification(n) => Self::ProgressNotification(n.params),
1214                ServerNotification::ResourceListChangedNotification(n) => Self::ResourceListChangedNotification(n.params),
1215                ServerNotification::ResourceUpdatedNotification(n) => Self::ResourceUpdatedNotification(n.params),
1216                ServerNotification::PromptListChangedNotification(n) => Self::PromptListChangedNotification(n.params),
1217                ServerNotification::ToolListChangedNotification(n) => Self::ToolListChangedNotification(n.params),
1218                ServerNotification::LoggingMessageNotification(n) => Self::LoggingMessageNotification(n.params),
1219                ServerNotification::SubscriptionsAcknowledgedNotification(n) => Self::SubscriptionsAcknowledgedNotification(n.params),
1220            },
1221            ServerJsonrpcNotification::Custom(notification) => Self::CustomNotification(CustomNotification {
1222                method: notification.method,
1223                params: notification.params,
1224            }),
1225        }
1226    }
1227}
1228
1229impl ServerJsonrpcNotification {
1230    pub fn new(notification: NotificationFromServer) -> Self {
1231        match notification {
1232            NotificationFromServer::CancelledNotification(params) => {
1233                Self::Standard(ServerNotification::CancelledNotification(CancelledNotification::new(params)))
1234            }
1235            NotificationFromServer::ProgressNotification(params) => {
1236                Self::Standard(ServerNotification::ProgressNotification(ProgressNotification::new(params)))
1237            }
1238            NotificationFromServer::ResourceListChangedNotification(params) => {
1239                Self::Standard(ServerNotification::ResourceListChangedNotification(ResourceListChangedNotification::new(params)))
1240            }
1241            NotificationFromServer::ResourceUpdatedNotification(params) => {
1242                Self::Standard(ServerNotification::ResourceUpdatedNotification(ResourceUpdatedNotification::new(params)))
1243            }
1244            NotificationFromServer::PromptListChangedNotification(params) => {
1245                Self::Standard(ServerNotification::PromptListChangedNotification(PromptListChangedNotification::new(params)))
1246            }
1247            NotificationFromServer::ToolListChangedNotification(params) => {
1248                Self::Standard(ServerNotification::ToolListChangedNotification(ToolListChangedNotification::new(params)))
1249            }
1250            NotificationFromServer::LoggingMessageNotification(params) => {
1251                Self::Standard(ServerNotification::LoggingMessageNotification(LoggingMessageNotification::new(params)))
1252            }
1253            NotificationFromServer::SubscriptionsAcknowledgedNotification(params) => {
1254                Self::Standard(ServerNotification::SubscriptionsAcknowledgedNotification(SubscriptionsAcknowledgedNotification::new(params)))
1255            }
1256            NotificationFromServer::CustomNotification(params) => {
1257                Self::Custom(JsonrpcNotification::new(params.method, params.params))
1258            }
1259        }
1260    }
1261
1262    pub fn jsonrpc(&self) -> &::std::string::String {
1263        match self {
1264            ServerJsonrpcNotification::Standard(inner) => match inner {
1265                ServerNotification::CancelledNotification(n) => n.jsonrpc(),
1266                ServerNotification::ProgressNotification(n) => n.jsonrpc(),
1267                ServerNotification::ResourceListChangedNotification(n) => n.jsonrpc(),
1268                ServerNotification::ResourceUpdatedNotification(n) => n.jsonrpc(),
1269                ServerNotification::PromptListChangedNotification(n) => n.jsonrpc(),
1270                ServerNotification::ToolListChangedNotification(n) => n.jsonrpc(),
1271                ServerNotification::LoggingMessageNotification(n) => n.jsonrpc(),
1272                ServerNotification::SubscriptionsAcknowledgedNotification(n) => n.jsonrpc(),
1273            },
1274            ServerJsonrpcNotification::Custom(notification) => notification.jsonrpc(),
1275        }
1276    }
1277
1278    pub fn method(&self) -> &str {
1279        match self {
1280            ServerJsonrpcNotification::Standard(inner) => match inner {
1281                ServerNotification::CancelledNotification(n) => n.method(),
1282                ServerNotification::ProgressNotification(n) => n.method(),
1283                ServerNotification::ResourceListChangedNotification(n) => n.method(),
1284                ServerNotification::ResourceUpdatedNotification(n) => n.method(),
1285                ServerNotification::PromptListChangedNotification(n) => n.method(),
1286                ServerNotification::ToolListChangedNotification(n) => n.method(),
1287                ServerNotification::LoggingMessageNotification(n) => n.method(),
1288                ServerNotification::SubscriptionsAcknowledgedNotification(n) => n.method(),
1289            },
1290            ServerJsonrpcNotification::Custom(notification) => notification.method.as_str(),
1291        }
1292    }
1293}
1294
1295/// Formats the ServerJsonrpcNotification as a JSON string.
1296impl Display for ServerJsonrpcNotification {
1297    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1298        write!(
1299            f,
1300            "{}",
1301            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1302        )
1303    }
1304}
1305
1306impl FromStr for ServerJsonrpcNotification {
1307    type Err = RpcError;
1308
1309    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1310        serde_json::from_str(s)
1311            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1312    }
1313}
1314//*******************************//
1315//**  NotificationFromServer   **//
1316//*******************************//
1317
1318/// To determine standard and custom notifications received from the MCP Server
1319/// Custom notifications are of type serde_json::Value and can be deserialized into any custom type.
1320#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1321#[serde(untagged)]
1322pub enum NotificationFromServer {
1323    CancelledNotification(CancelledNotificationParams),
1324    ProgressNotification(ProgressNotificationParams),
1325    ResourceListChangedNotification(Option<NotificationParams>),
1326    ResourceUpdatedNotification(ResourceUpdatedNotificationParams),
1327    PromptListChangedNotification(Option<NotificationParams>),
1328    ToolListChangedNotification(Option<NotificationParams>),
1329    LoggingMessageNotification(LoggingMessageNotificationParams),
1330    SubscriptionsAcknowledgedNotification(SubscriptionsAcknowledgedNotificationParams),
1331    CustomNotification(CustomNotification),
1332}
1333
1334impl NotificationFromServer {
1335    pub fn method(&self) -> &str {
1336        match self {
1337            NotificationFromServer::CancelledNotification(_params) => CancelledNotification::method_value(),
1338            NotificationFromServer::ProgressNotification(_params) => ProgressNotification::method_value(),
1339            NotificationFromServer::ResourceListChangedNotification(_params) => ResourceListChangedNotification::method_value(),
1340            NotificationFromServer::ResourceUpdatedNotification(_params) => ResourceUpdatedNotification::method_value(),
1341            NotificationFromServer::PromptListChangedNotification(_params) => PromptListChangedNotification::method_value(),
1342            NotificationFromServer::ToolListChangedNotification(_params) => ToolListChangedNotification::method_value(),
1343            NotificationFromServer::LoggingMessageNotification(_params) => LoggingMessageNotification::method_value(),
1344            NotificationFromServer::SubscriptionsAcknowledgedNotification(_params) => SubscriptionsAcknowledgedNotification::method_value(),
1345            NotificationFromServer::CustomNotification(params) => params.method.as_str(),
1346        }
1347    }
1348}
1349
1350//*******************************//
1351//**   ServerJsonrpcResponse   **//
1352//*******************************//
1353
1354/// "Similar to JsonrpcResponse , but with the variants restricted to server-side responses."
1355#[derive(Clone, Debug)]
1356pub struct ServerJsonrpcResponse {
1357    pub id: RequestId,
1358    jsonrpc: ::std::string::String,
1359    pub result: ServerResult,
1360}
1361
1362impl ServerJsonrpcResponse {
1363    pub fn new(id: RequestId, result: ServerResult) -> Self {
1364        Self {
1365            id,
1366            jsonrpc: JSONRPC_VERSION.to_string(),
1367            result,
1368        }
1369    }
1370    pub fn jsonrpc(&self) -> &::std::string::String {
1371        &self.jsonrpc
1372    }
1373}
1374
1375/// Formats the ServerJsonrpcResponse as a JSON string.
1376impl Display for ServerJsonrpcResponse {
1377    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1378        write!(
1379            f,
1380            "{}",
1381            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1382        )
1383    }
1384}
1385
1386impl FromStr for ServerJsonrpcResponse {
1387    type Err = RpcError;
1388
1389    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1390        serde_json::from_str(s)
1391            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1392    }
1393}
1394//*******************************//
1395//**      ServerResult     **//
1396//*******************************//
1397// ServerResult is now ServerResult from the schema-generated types.
1398// The schema's ServerResult enum covers all result types.
1399// See mcp_schema.rs for the definition.
1400
1401//***************************//
1402//** impl for JsonrpcErrorResponse **//
1403//***************************//
1404
1405/// Formats the ServerJsonrpcResponse as a JSON string.
1406impl Display for JsonrpcErrorResponse {
1407    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1408        write!(
1409            f,
1410            "{}",
1411            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1412        )
1413    }
1414}
1415
1416impl FromStr for JsonrpcErrorResponse {
1417    type Err = RpcError;
1418
1419    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
1420        serde_json::from_str(s)
1421            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
1422    }
1423}
1424
1425//**************************//
1426//**  MessageFromServer   **//
1427//**************************//
1428
1429/// An enum representing various types of messages that can be sent from an MCP Server.
1430/// It provides a typed structure for the message payload while skipping internal details like
1431/// `requestId` and protocol version, which are used solely by the transport layer and
1432/// do not need to be exposed to the user.
1433#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1434#[serde(untagged)]
1435pub enum MessageFromServer {
1436    RequestFromServer(RequestFromServer),
1437    ServerResult(ServerResult),
1438    NotificationFromServer(NotificationFromServer),
1439    Error(RpcError),
1440}
1441
1442impl From<RequestFromServer> for MessageFromServer {
1443    fn from(value: RequestFromServer) -> Self {
1444        Self::RequestFromServer(value)
1445    }
1446}
1447
1448impl From<ServerResult> for MessageFromServer {
1449    fn from(value: ServerResult) -> Self {
1450        Self::ServerResult(value)
1451    }
1452}
1453
1454impl From<NotificationFromServer> for MessageFromServer {
1455    fn from(value: NotificationFromServer) -> Self {
1456        Self::NotificationFromServer(value)
1457    }
1458}
1459
1460impl From<RpcError> for MessageFromServer {
1461    fn from(value: RpcError) -> Self {
1462        Self::Error(value)
1463    }
1464}
1465
1466impl McpMessage for MessageFromServer {
1467    fn is_response(&self) -> bool {
1468        matches!(self, MessageFromServer::ServerResult(_))
1469    }
1470
1471    fn is_request(&self) -> bool {
1472        matches!(self, MessageFromServer::RequestFromServer(_))
1473    }
1474
1475    fn is_notification(&self) -> bool {
1476        matches!(self, MessageFromServer::NotificationFromServer(_))
1477    }
1478
1479    fn is_error(&self) -> bool {
1480        matches!(self, MessageFromServer::Error(_))
1481    }
1482
1483    fn message_type(&self) -> MessageTypes {
1484        match self {
1485            MessageFromServer::RequestFromServer(_) => MessageTypes::Request,
1486            MessageFromServer::ServerResult(_) => MessageTypes::Response,
1487            MessageFromServer::NotificationFromServer(_) => MessageTypes::Notification,
1488            MessageFromServer::Error(_) => MessageTypes::Error,
1489        }
1490    }
1491}
1492
1493impl FromMessage<MessageFromServer> for ServerMessage {
1494    fn from_message(message: MessageFromServer, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1495        match message {
1496            MessageFromServer::RequestFromServer(request_from_server) => {
1497                let request_id =
1498                    request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1499
1500                let rpc_message = match request_from_server {
1501                    RequestFromServer::CreateMessageRequest(params) => {
1502                        ServerJsonrpcRequest::CreateMessageRequest {
1503                            id: request_id,
1504                            jsonrpc: "2.0".to_string(),
1505                            request: CreateMessageRequest::new(params),
1506                        }
1507                    }
1508                    RequestFromServer::ListRootsRequest(params) => {
1509                        ServerJsonrpcRequest::ListRootsRequest {
1510                            id: request_id,
1511                            jsonrpc: "2.0".to_string(),
1512                            request: ListRootsRequest::new(params),
1513                        }
1514                    }
1515                    RequestFromServer::ElicitRequest(params) => {
1516                        ServerJsonrpcRequest::ElicitRequest {
1517                            id: request_id,
1518                            jsonrpc: "2.0".to_string(),
1519                            request: ElicitRequest::new(params),
1520                        }
1521                    }
1522                    RequestFromServer::CustomRequest(params) => {
1523                        ServerJsonrpcRequest::CustomRequest(JsonrpcRequest::new(request_id, params.method, params.params))
1524                    }
1525                };
1526
1527                Ok(ServerMessage::Request(rpc_message))
1528            }
1529            MessageFromServer::ServerResult(result_from_server) => {
1530                let request_id =
1531                    request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1532                Ok(ServerMessage::Response(ServerJsonrpcResponse::new(
1533                    request_id,
1534                    result_from_server,
1535                )))
1536            }
1537            MessageFromServer::NotificationFromServer(notification_from_server) => {
1538                if request_id.is_some() {
1539                    return Err(RpcError::internal_error()
1540                        .with_message("request_id expected to be None for Notifications!".to_string()));
1541                }
1542                Ok(ServerMessage::Notification(ServerJsonrpcNotification::new(
1543                    notification_from_server,
1544                )))
1545            }
1546            MessageFromServer::Error(jsonrpc_error_error) => Ok(ServerMessage::Error(JsonrpcErrorResponse::new(
1547                jsonrpc_error_error,
1548                request_id,
1549            ))),
1550        }
1551    }
1552}
1553
1554//**************************//
1555//**  MessageFromClient   **//
1556//**************************//
1557
1558/// An enum representing various types of messages that can be sent from an MCP Client.
1559/// It provides a typed structure for the message payload while skipping internal details like
1560/// `requestId` and protocol version, which are used solely by the transport layer and
1561/// do not need to be exposed to the user.
1562#[derive(::serde::Serialize, ::serde::Deserialize, Clone, Debug)]
1563#[serde(untagged)]
1564pub enum MessageFromClient {
1565    RequestFromClient(RequestFromClient),
1566    ResultFromClient(ResultFromClient),
1567    NotificationFromClient(NotificationFromClient),
1568    Error(RpcError),
1569}
1570
1571impl MessageFromClient {
1572    /// Returns `true` if the message is an `InitializeRequest`.
1573    /// Note: InitializeRequest has been removed from the 2026-07-28 protocol.
1574    /// This always returns `false`.
1575    pub fn is_initialize_request(&self) -> bool {
1576        false
1577    }
1578
1579    /// Returns `true` if the message is an `InitializedNotification`
1580    /// Note: InitializedNotification has been removed from the 2026-07-28 protocol.
1581    /// This always returns `false`.
1582    pub fn is_initialized_notification(&self) -> bool {
1583        false
1584    }
1585}
1586
1587impl From<RequestFromClient> for MessageFromClient {
1588    fn from(value: RequestFromClient) -> Self {
1589        Self::RequestFromClient(value)
1590    }
1591}
1592
1593impl From<ResultFromClient> for MessageFromClient {
1594    fn from(value: ResultFromClient) -> Self {
1595        Self::ResultFromClient(value)
1596    }
1597}
1598
1599impl From<NotificationFromClient> for MessageFromClient {
1600    fn from(value: NotificationFromClient) -> Self {
1601        Self::NotificationFromClient(value)
1602    }
1603}
1604
1605impl From<RpcError> for MessageFromClient {
1606    fn from(value: RpcError) -> Self {
1607        Self::Error(value)
1608    }
1609}
1610
1611impl McpMessage for MessageFromClient {
1612    fn is_response(&self) -> bool {
1613        matches!(self, MessageFromClient::ResultFromClient(_))
1614    }
1615
1616    fn is_request(&self) -> bool {
1617        matches!(self, MessageFromClient::RequestFromClient(_))
1618    }
1619
1620    fn is_notification(&self) -> bool {
1621        matches!(self, MessageFromClient::NotificationFromClient(_))
1622    }
1623
1624    fn is_error(&self) -> bool {
1625        matches!(self, MessageFromClient::Error(_))
1626    }
1627
1628    fn message_type(&self) -> MessageTypes {
1629        match self {
1630            MessageFromClient::RequestFromClient(_) => MessageTypes::Request,
1631            MessageFromClient::ResultFromClient(_) => MessageTypes::Response,
1632            MessageFromClient::NotificationFromClient(_) => MessageTypes::Notification,
1633            MessageFromClient::Error(_) => MessageTypes::Error,
1634        }
1635    }
1636}
1637
1638impl FromMessage<MessageFromClient> for ClientMessage {
1639    fn from_message(message: MessageFromClient, request_id: Option<RequestId>) -> std::result::Result<Self, RpcError> {
1640        match message {
1641            MessageFromClient::RequestFromClient(request_from_client) => {
1642                let request_id =
1643                    request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1644                Ok(ClientMessage::Request(ClientJsonrpcRequest::new(
1645                    request_id,
1646                    request_from_client,
1647                )))
1648            }
1649            MessageFromClient::ResultFromClient(result_from_client) => {
1650                let request_id =
1651                    request_id.ok_or_else(|| RpcError::internal_error().with_message("request_id is None!".to_string()))?;
1652                Ok(ClientMessage::Response(ClientJsonrpcResponse::new(
1653                    request_id,
1654                    result_from_client,
1655                )))
1656            }
1657            MessageFromClient::NotificationFromClient(notification_from_client) => {
1658                if request_id.is_some() {
1659                    return Err(RpcError::internal_error()
1660                        .with_message("request_id expected to be None for Notifications!".to_string()));
1661                }
1662
1663                Ok(ClientMessage::Notification(ClientJsonrpcNotification::new(
1664                    notification_from_client,
1665                )))
1666            }
1667            MessageFromClient::Error(jsonrpc_error_error) => Ok(ClientMessage::Error(JsonrpcErrorResponse::new(
1668                jsonrpc_error_error,
1669                request_id,
1670            ))),
1671        }
1672    }
1673}
1674
1675//**************************//
1676//**  UnknownTool Error   **//
1677//**************************//
1678
1679/// A custom error type `UnknownTool` that wraps a `String`.
1680/// This can be used as the error type in the result of a `CallToolRequest` when a non-existent or unimplemented tool is called.
1681#[derive(Debug)]
1682pub struct UnknownTool(pub String);
1683
1684// Implement `Display` for `UnknownTool` to format the error message.
1685impl core::fmt::Display for UnknownTool {
1686    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1687        // The formatted string will display "Unknown tool: <tool_name>"
1688        write!(f, "Unknown tool: {}", self.0)
1689    }
1690}
1691
1692// Implement the `Error` trait for `UnknownTool`, making it a valid error type.
1693impl std::error::Error for UnknownTool {}
1694
1695//***************************//
1696//**  CallToolError Error  **//
1697//***************************//
1698/// A specific error type that can hold any kind of error and is used to
1699/// encapsulate various error scenarios when a `CallToolRequest` fails.
1700#[derive(Debug)]
1701pub struct CallToolError(pub Box<dyn std::error::Error>);
1702
1703// Implement methods for `CallToolError` to handle different error types.
1704impl CallToolError {
1705    /// Constructor to create a new `CallToolError` from a generic error.
1706    pub fn new<E: std::error::Error + 'static>(err: E) -> Self {
1707        // Box the error to fit inside the `CallToolError` struct
1708        CallToolError(Box::new(err))
1709    }
1710
1711    /// Specific constructor to create a `CallToolError` for an `UnknownTool` error.
1712    pub fn unknown_tool(tool_name: impl Into<String>) -> Self {
1713        // Create a `CallToolError` from an `UnknownTool` error (wrapped in a `Box`).
1714        CallToolError(Box::new(UnknownTool(tool_name.into())))
1715    }
1716
1717    /// Creates a `CallToolError` indicating that task-augmented tool calls are not supported.
1718    /// This constructor is used when a task-augmented tool call is requested
1719    /// but the capability is not advertised by the peer.
1720    pub fn unsupported_task_augmented_tool_call() -> Self {
1721        Self::from_message("Task-augmented tool calls are not supported.".to_string())
1722    }
1723
1724    /// Creates a `CallToolError` for invalid arguments with optional details.
1725    ///
1726    pub fn invalid_arguments(tool_name: impl AsRef<str>, message: Option<String>) -> Self {
1727        // Trim tool_name to remove whitespace and check for emptiness
1728        let tool_name = tool_name.as_ref().trim();
1729        if tool_name.is_empty() {
1730            return Self::from_message("Invalid arguments: tool name cannot be empty".to_string());
1731        }
1732
1733        // Use a descriptive default message if none provided
1734        let default_message = "no additional details provided".to_string();
1735        let message = message.unwrap_or(default_message);
1736
1737        // Format the full error message
1738        let full_message = format!("Invalid arguments for tool '{tool_name}': {message}");
1739
1740        Self::from_message(full_message)
1741    }
1742
1743    /// Creates a new `CallToolError` from a string message.
1744    ///
1745    /// This is useful for generating ad-hoc or one-off errors without defining a custom error type.
1746    /// Internally, it wraps the string in a lightweight error type that implements the `Error` trait.
1747    ///
1748    /// # Examples
1749    ///
1750    /// ```
1751    /// let err = rust_mcp_schema::schema_utils::CallToolError::from_message("Something went wrong");
1752    /// println!("{:?}", err);
1753    /// ```
1754    ///
1755    /// # Parameters
1756    ///
1757    /// - `message`: Any type that can be converted into a `String` (e.g., `&str` or `String`)
1758    ///
1759    /// # Returns
1760    ///
1761    /// A `CallToolError` wrapping a dynamic error created from the provided message.
1762    pub fn from_message(message: impl Into<String>) -> Self {
1763        struct MsgError(String);
1764        impl std::fmt::Debug for MsgError {
1765            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1766                write!(f, "{}", self.0)
1767            }
1768        }
1769        impl std::fmt::Display for MsgError {
1770            fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1771                write!(f, "{}", self.0)
1772            }
1773        }
1774        impl std::error::Error for MsgError {}
1775
1776        CallToolError::new(MsgError(message.into()))
1777    }
1778}
1779
1780/// Converts a `CallToolError` into a `RpcError`.
1781///
1782/// The conversion creates an internal error variant of `RpcError`
1783/// and attaches the string representation of the original `CallToolError` as a message.
1784///
1785impl From<CallToolError> for RpcError {
1786    fn from(value: CallToolError) -> Self {
1787        Self::internal_error().with_message(value.to_string())
1788    }
1789}
1790
1791/// Conversion of `CallToolError` into a `CallToolResult` with an error.
1792impl From<CallToolError> for CallToolResult {
1793    fn from(value: CallToolError) -> Self {
1794        // Convert `CallToolError` to a `CallToolResult`
1795        CallToolResult {
1796            content: vec![TextContent::new(value.to_string(), None, None).into()],
1797            result_type: "complete".to_string(),
1798            is_error: Some(true),
1799            meta: None,
1800            structured_content: None,
1801        }
1802    }
1803}
1804
1805// Implement `Display` for `CallToolError` to provide a user-friendly error message.
1806impl core::fmt::Display for CallToolError {
1807    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
1808        write!(f, "{}", self.0)
1809    }
1810}
1811
1812// Implement `Error` for `CallToolError` to propagate the source of the error.
1813impl std::error::Error for CallToolError {
1814    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
1815        self.0.source()
1816    }
1817}
1818
1819impl CallToolRequest {
1820    /// Retrieves the name of the tool from the request parameters.
1821    ///
1822    /// This method provides access to the tool name stored within the `params` field
1823    /// of the `CallToolRequest` struct, returning it as a string reference.
1824    ///
1825    /// # Returns
1826    /// A reference to the string containing the tool's name.
1827    pub fn tool_name(&self) -> &str {
1828        &self.params.name
1829    }
1830}
1831
1832impl<T: Into<String>> From<T> for TextContent {
1833    fn from(value: T) -> Self {
1834        TextContent::new(value.into(), None, None)
1835    }
1836}
1837
1838impl TextResourceContents {
1839    pub fn new<T: Into<String>>(text: T, uri: T) -> Self {
1840        TextResourceContents {
1841            meta: None,
1842            mime_type: None,
1843            text: text.into(),
1844            uri: uri.into(),
1845        }
1846    }
1847    /// Assigns metadata to the TextResourceContents, enabling the inclusion of extra context or details.
1848    pub fn with_meta(mut self, meta: MetaObject) -> Self {
1849        self.meta = Some(meta);
1850        self
1851    }
1852
1853    pub fn with_mime_type<T: Into<String>>(mut self, mime_type: T) -> Self {
1854        self.mime_type = Some(mime_type.into());
1855        self
1856    }
1857
1858    pub fn with_uri<T: Into<String>>(mut self, uri: T) -> Self {
1859        self.uri = uri.into();
1860        self
1861    }
1862}
1863
1864impl BlobResourceContents {
1865    pub fn new<T: Into<String>>(base64_text: T, uri: T) -> Self {
1866        BlobResourceContents {
1867            meta: None,
1868            mime_type: None,
1869            blob: base64_text.into(),
1870            uri: uri.into(),
1871        }
1872    }
1873    /// Assigns metadata to the BlobResourceContents, enabling the inclusion of extra context or details.
1874    pub fn with_meta(mut self, meta: MetaObject) -> Self {
1875        self.meta = Some(meta);
1876        self
1877    }
1878    pub fn with_mime_type<T: Into<String>>(mut self, mime_type: T) -> Self {
1879        self.mime_type = Some(mime_type.into());
1880        self
1881    }
1882    pub fn with_uri<T: Into<String>>(mut self, uri: T) -> Self {
1883        self.uri = uri.into();
1884        self
1885    }
1886}
1887
1888#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1889#[serde(untagged)]
1890#[allow(clippy::large_enum_variant)]
1891pub enum ClientMessages {
1892    Single(ClientMessage),
1893    Batch(Vec<ClientMessage>),
1894}
1895
1896impl ClientMessages {
1897    pub fn is_batch(&self) -> bool {
1898        matches!(self, ClientMessages::Batch(_))
1899    }
1900
1901    pub fn includes_request(&self) -> bool {
1902        match self {
1903            ClientMessages::Single(client_message) => client_message.is_request(),
1904            ClientMessages::Batch(client_messages) => client_messages.iter().any(ClientMessage::is_request),
1905        }
1906    }
1907
1908    pub fn as_single(self) -> result::Result<ClientMessage, SdkError> {
1909        match self {
1910            ClientMessages::Single(client_message) => Ok(client_message),
1911            ClientMessages::Batch(_) => Err(SdkError::internal_error()
1912                .with_message("Error: cannot convert ClientMessages::Batch to ClientMessage::Single")),
1913        }
1914    }
1915    pub fn as_batch(self) -> result::Result<Vec<ClientMessage>, SdkError> {
1916        match self {
1917            ClientMessages::Single(_) => Err(SdkError::internal_error()
1918                .with_message("Error: cannot convert ClientMessage::Single to ClientMessages::Batch")),
1919            ClientMessages::Batch(client_messages) => Ok(client_messages),
1920        }
1921    }
1922}
1923
1924impl From<ClientMessage> for ClientMessages {
1925    fn from(value: ClientMessage) -> Self {
1926        Self::Single(value)
1927    }
1928}
1929
1930impl From<Vec<ClientMessage>> for ClientMessages {
1931    fn from(value: Vec<ClientMessage>) -> Self {
1932        Self::Batch(value)
1933    }
1934}
1935
1936impl Display for ClientMessages {
1937    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1938        write!(
1939            f,
1940            "{}",
1941            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
1942        )
1943    }
1944}
1945
1946#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
1947#[serde(untagged)]
1948#[allow(clippy::large_enum_variant)]
1949pub enum ServerMessages {
1950    Single(ServerMessage),
1951    Batch(Vec<ServerMessage>),
1952}
1953
1954impl ServerMessages {
1955    pub fn is_batch(&self) -> bool {
1956        matches!(self, ServerMessages::Batch(_))
1957    }
1958
1959    pub fn includes_request(&self) -> bool {
1960        match self {
1961            ServerMessages::Single(server_message) => server_message.is_request(),
1962            ServerMessages::Batch(server_messages) => server_messages.iter().any(ServerMessage::is_request),
1963        }
1964    }
1965
1966    pub fn as_single(self) -> result::Result<ServerMessage, SdkError> {
1967        match self {
1968            ServerMessages::Single(server_message) => Ok(server_message),
1969            ServerMessages::Batch(_) => Err(SdkError::internal_error()
1970                .with_message("Error: cannot convert ServerMessages::Batch to ServerMessage::Single")),
1971        }
1972    }
1973    pub fn as_batch(self) -> result::Result<Vec<ServerMessage>, SdkError> {
1974        match self {
1975            ServerMessages::Single(_) => Err(SdkError::internal_error()
1976                .with_message("Error: cannot convert ServerMessage::Single to ServerMessages::Batch")),
1977            ServerMessages::Batch(server_messages) => Ok(server_messages),
1978        }
1979    }
1980}
1981
1982impl From<ServerMessage> for ServerMessages {
1983    fn from(value: ServerMessage) -> Self {
1984        Self::Single(value)
1985    }
1986}
1987
1988impl From<Vec<ServerMessage>> for ServerMessages {
1989    fn from(value: Vec<ServerMessage>) -> Self {
1990        Self::Batch(value)
1991    }
1992}
1993
1994impl Display for ServerMessages {
1995    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1996        write!(
1997            f,
1998            "{}",
1999            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
2000        )
2001    }
2002}
2003
2004#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2005#[serde(untagged)]
2006#[allow(clippy::large_enum_variant)]
2007pub enum MessagesFromServer {
2008    Single(MessageFromServer),
2009    Batch(Vec<MessageFromServer>),
2010}
2011
2012impl MessagesFromServer {
2013    pub fn is_batch(&self) -> bool {
2014        matches!(self, MessagesFromServer::Batch(_))
2015    }
2016
2017    pub fn includes_request(&self) -> bool {
2018        match self {
2019            MessagesFromServer::Single(server_message) => server_message.is_request(),
2020            MessagesFromServer::Batch(server_messages) => server_messages.iter().any(MessageFromServer::is_request),
2021        }
2022    }
2023
2024    pub fn as_single(self) -> result::Result<MessageFromServer, SdkError> {
2025        match self {
2026            MessagesFromServer::Single(server_message) => Ok(server_message),
2027            MessagesFromServer::Batch(_) => Err(SdkError::internal_error()
2028                .with_message("Error: cannot convert MessagesFromServer::Batch to MessageFromServer::Single")),
2029        }
2030    }
2031    pub fn as_batch(self) -> result::Result<Vec<MessageFromServer>, SdkError> {
2032        match self {
2033            MessagesFromServer::Single(_) => Err(SdkError::internal_error()
2034                .with_message("Error: cannot convert MessageFromServer::Single to MessagesFromServer::Batch")),
2035            MessagesFromServer::Batch(server_messages) => Ok(server_messages),
2036        }
2037    }
2038}
2039
2040impl From<MessageFromServer> for MessagesFromServer {
2041    fn from(value: MessageFromServer) -> Self {
2042        Self::Single(value)
2043    }
2044}
2045
2046impl From<Vec<MessageFromServer>> for MessagesFromServer {
2047    fn from(value: Vec<MessageFromServer>) -> Self {
2048        Self::Batch(value)
2049    }
2050}
2051
2052#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
2053#[serde(untagged)]
2054#[allow(clippy::large_enum_variant)]
2055pub enum MessagesFromClient {
2056    Single(MessageFromClient),
2057    Batch(Vec<MessageFromClient>),
2058}
2059
2060impl MessagesFromClient {
2061    pub fn is_batch(&self) -> bool {
2062        matches!(self, MessagesFromClient::Batch(_))
2063    }
2064
2065    pub fn includes_request(&self) -> bool {
2066        match self {
2067            MessagesFromClient::Single(server_message) => server_message.is_request(),
2068            MessagesFromClient::Batch(server_messages) => server_messages.iter().any(MessageFromClient::is_request),
2069        }
2070    }
2071
2072    pub fn as_single(self) -> result::Result<MessageFromClient, SdkError> {
2073        match self {
2074            MessagesFromClient::Single(server_message) => Ok(server_message),
2075            MessagesFromClient::Batch(_) => Err(SdkError::internal_error()
2076                .with_message("Error: cannot convert MessagesFromClient::Batch to MessageFromClient::Single")),
2077        }
2078    }
2079    pub fn as_batch(self) -> result::Result<Vec<MessageFromClient>, SdkError> {
2080        match self {
2081            MessagesFromClient::Single(_) => Err(SdkError::internal_error()
2082                .with_message("Error: cannot convert MessageFromClient::Single to MessagesFromClient::Batch")),
2083            MessagesFromClient::Batch(server_messages) => Ok(server_messages),
2084        }
2085    }
2086}
2087
2088impl From<MessageFromClient> for MessagesFromClient {
2089    fn from(value: MessageFromClient) -> Self {
2090        Self::Single(value)
2091    }
2092}
2093
2094impl From<Vec<MessageFromClient>> for MessagesFromClient {
2095    fn from(value: Vec<MessageFromClient>) -> Self {
2096        Self::Batch(value)
2097    }
2098}
2099
2100#[derive(Debug)]
2101pub struct StringSchemaFormatError {
2102    invalid_value: String,
2103}
2104
2105impl core::fmt::Display for StringSchemaFormatError {
2106    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2107        write!(f, "Invalid string schema format: '{}'", self.invalid_value)
2108    }
2109}
2110
2111impl std::error::Error for StringSchemaFormatError {}
2112
2113impl FromStr for StringSchemaFormat {
2114    type Err = StringSchemaFormatError;
2115
2116    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2117        match s {
2118            "date" => Ok(Self::Date),
2119            "date-time" => Ok(Self::DateTime),
2120            "email" => Ok(Self::Email),
2121            "uri" => Ok(Self::Uri),
2122            _ => Err(StringSchemaFormatError {
2123                invalid_value: s.to_string(),
2124            }),
2125        }
2126    }
2127}
2128
2129// Helper: handle all single-select enum variants
2130fn try_from_enum_schema(map: &serde_json::Map<String, Value>) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2131    // All enum schemas should have type: "string" (or missing, but usually present)
2132    let has_one_of = map.contains_key("oneOf");
2133    let has_enum = map.contains_key("enum");
2134    let has_enum_names = map.contains_key("enumNames");
2135
2136    if has_one_of {
2137        let schema: TitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2138            RpcError::parse_error().with_message(format!("Failed to parse TitledSingleSelectEnumSchema: {e}"))
2139        })?;
2140
2141        Ok(PrimitiveSchemaDefinition::TitledSingleSelectEnumSchema(schema))
2142    } else if has_enum && has_enum_names {
2143        let schema: LegacyTitledEnumSchema = serde_json::from_value(Value::Object(map.clone()))
2144            .map_err(|e| RpcError::parse_error().with_message(format!("Failed to parse LegacyTitledEnumSchema: {e}")))?;
2145        Ok(PrimitiveSchemaDefinition::LegacyTitledEnumSchema(schema))
2146    } else if has_enum {
2147        let schema: UntitledSingleSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2148            RpcError::parse_error().with_message(format!("Failed to parse UntitledSingleSelectEnumSchema: {e}"))
2149        })?;
2150        Ok(PrimitiveSchemaDefinition::UntitledSingleSelectEnumSchema(schema))
2151    } else {
2152        Err(RpcError::parse_error().with_message("Invalid enum schema: missing 'enum' or 'oneOf'".to_string()))
2153    }
2154}
2155
2156// Helper: handle multi-select (array) enum schemas
2157fn try_from_multi_select_schema(
2158    map: &serde_json::Map<String, Value>,
2159) -> result::Result<PrimitiveSchemaDefinition, RpcError> {
2160    let items = map
2161        .get("items")
2162        .ok_or(RpcError::parse_error().with_message("Array schema missing 'items' field".to_string()))?;
2163
2164    let items_obj = items
2165        .as_object()
2166        .ok_or(RpcError::parse_error().with_message("Field 'items' must be an object".to_string()))?;
2167
2168    if items_obj.contains_key("anyOf") {
2169        let schema: TitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2170            RpcError::parse_error().with_message(format!("Failed to parse TitledMultiSelectEnumSchema: {e}"))
2171        })?;
2172        Ok(PrimitiveSchemaDefinition::TitledMultiSelectEnumSchema(schema))
2173    } else if items_obj.contains_key("enum") {
2174        let schema: UntitledMultiSelectEnumSchema = serde_json::from_value(Value::Object(map.clone())).map_err(|e| {
2175            RpcError::parse_error().with_message(format!("Failed to parse UntitledMultiSelectEnumSchema: {e}"))
2176        })?;
2177        Ok(PrimitiveSchemaDefinition::UntitledMultiSelectEnumSchema(schema))
2178    } else {
2179        Err(RpcError::parse_error()
2180            .with_message("Array schema 'items' must contain 'enum' or 'oneOf' to be a multi-select enum".to_string()))
2181    }
2182}
2183
2184impl TryFrom<&serde_json::Map<String, Value>> for PrimitiveSchemaDefinition {
2185    type Error = RpcError;
2186
2187    fn try_from(value: &serde_json::Map<String, serde_json::Value>) -> result::Result<Self, Self::Error> {
2188        // 1. First: detect enum schemas (they look like strings but have enum/oneOf)
2189        if value.contains_key("enum") || value.contains_key("oneOf") {
2190            return try_from_enum_schema(value);
2191        }
2192
2193        // 2. Then: detect multi-select array schemas (type: "array" + items with enum/oneOf)
2194        if value.get("type").and_then(|v| v.as_str()) == Some("array") {
2195            return try_from_multi_select_schema(value);
2196        }
2197
2198        let input_type = value
2199            .get("type")
2200            .and_then(|v| v.as_str())
2201            .or_else(|| value.get("oneOf").map(|_| "enum")) // if "oneOf" exists, return "enum"
2202            .ok_or_else(|| {
2203                RpcError::parse_error().with_message("'type' is missing and data type is not supported!".to_string())
2204            })?;
2205
2206        let description = value.get("description").and_then(|v| v.as_str().map(|s| s.to_string()));
2207        let title = value.get("title").and_then(|v| v.as_str().map(|s| s.to_string()));
2208
2209        let schema_definition: PrimitiveSchemaDefinition = match input_type {
2210            "string" => {
2211                let max_length = value.get("maxLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2212                let min_length = value.get("minLength").and_then(|v| v.as_number().and_then(|n| n.as_i64()));
2213                let default = value.get("default").and_then(|v| v.as_str().map(|s| s.to_string()));
2214
2215                let format_str = value.get("format").and_then(|v| v.as_str());
2216                let format = format_str.and_then(|s| StringSchemaFormat::from_str(s).ok());
2217
2218                PrimitiveSchemaDefinition::StringSchema(StringSchema::new(
2219                    default,
2220                    description,
2221                    format,
2222                    max_length,
2223                    min_length,
2224                    title,
2225                ))
2226            }
2227            "number" | "integer" => {
2228                let maximum = value.get("maximum").and_then(|v| v.as_number().and_then(|n| n.as_f64()));
2229                let minimum = value.get("minimum").and_then(|v| v.as_number().and_then(|n| n.as_f64()));
2230                let default = value.get("default").and_then(|v| v.as_number().and_then(|n| n.as_f64()));
2231
2232                PrimitiveSchemaDefinition::NumberSchema(NumberSchema {
2233                    default,
2234                    description,
2235                    maximum,
2236                    minimum,
2237                    title,
2238                    type_: if input_type == "integer" {
2239                        NumberSchemaType::Integer
2240                    } else {
2241                        NumberSchemaType::Number
2242                    },
2243                })
2244            }
2245            "boolean" => {
2246                let default = value.get("default").and_then(|v| v.as_bool().map(|s| s.to_owned()));
2247                PrimitiveSchemaDefinition::BooleanSchema(BooleanSchema::new(default, description, title))
2248            }
2249            other => {
2250                return Err(RpcError::parse_error().with_message(format!("'{other}' type is not currently supported")));
2251            }
2252        };
2253
2254        Ok(schema_definition)
2255    }
2256}
2257
2258impl ElicitRequestParams {
2259    pub fn message(&self) -> &str {
2260        match self {
2261            ElicitRequestParams::UrlParams(elicit_request_url_params) => elicit_request_url_params.message.as_str(),
2262            ElicitRequestParams::FormParams(elicit_request_form_params) => elicit_request_form_params.message.as_str(),
2263        }
2264    }
2265}
2266
2267impl ServerCapabilities {
2268    pub fn can_handle_request(&self, client_request: &ClientJsonrpcRequest) -> std::result::Result<(), RpcError> {
2269        let request_method = client_request.method();
2270
2271        fn create_error(capability: &str, method: &str) -> RpcError {
2272            RpcError::internal_error().with_message(create_unsupported_capability_message("Server", capability, method))
2273        }
2274
2275        match client_request {
2276            ClientJsonrpcRequest::Standard(inner) => match inner {
2277                ClientRequest::GetPromptRequest(_) | ClientRequest::ListPromptsRequest(_)
2278                    if self.prompts.is_none() =>
2279                {
2280                    return Err(create_error("prompts", request_method));
2281                }
2282                ClientRequest::ListResourcesRequest(_)
2283                | ClientRequest::ListResourceTemplatesRequest(_)
2284                | ClientRequest::ReadResourceRequest(_)
2285                    if self.resources.is_none() =>
2286                {
2287                    return Err(create_error("resources", request_method));
2288                }
2289                ClientRequest::CallToolRequest(_) | ClientRequest::ListToolsRequest(_) if self.tools.is_none() => {
2290                    return Err(create_error("tools", request_method));
2291                }
2292                ClientRequest::CompleteRequest(_) if self.completions.is_none() => {
2293                    return Err(create_error("completions", request_method));
2294                }
2295                ClientRequest::DiscoverRequest(_) => {},
2296                ClientRequest::SubscriptionsListenRequest(_) => {},
2297                _ => {}
2298            },
2299            ClientJsonrpcRequest::Custom(_) => {}
2300        };
2301        Ok(())
2302    }
2303
2304    /// Asserts that the server supports the requested notification.
2305    ///
2306    /// Verifies that the server advertises support for the notification type,
2307    /// allowing callers to avoid sending notifications that the server does not
2308    /// support. This can be used to prevent issuing requests to peers that lack
2309    /// the required capability.
2310    pub fn can_accept_notification(&self, notification_method: &str) -> std::result::Result<(), RpcError> {
2311        let entity = "Server";
2312
2313        if LoggingMessageNotification::method_value().eq(notification_method) && self.logging.is_none() {
2314            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2315                entity,
2316                "logging",
2317                notification_method,
2318            )));
2319        }
2320
2321        if [
2322            ResourceUpdatedNotification::method_value(),
2323            ResourceListChangedNotification::method_value(),
2324        ]
2325        .contains(&notification_method)
2326            && self.resources.is_none()
2327        {
2328            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2329                entity,
2330                "notifying about resources",
2331                notification_method,
2332            )));
2333        }
2334
2335        if ToolListChangedNotification::method_value().eq(notification_method) && self.tools.is_none() {
2336            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2337                entity,
2338                "notifying of tool list changes",
2339                notification_method,
2340            )));
2341        }
2342
2343        if PromptListChangedNotification::method_value().eq(notification_method) && self.prompts.is_none() {
2344            return Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2345                entity,
2346                "notifying of prompt list changes",
2347                notification_method,
2348            )));
2349        }
2350
2351        Ok(())
2352    }
2353}
2354
2355/// Formats an assertion error message for unsupported capabilities.
2356///
2357/// Constructs a string describing that a specific entity (e.g., server or client) lacks
2358/// support for a required capability, needed for a particular method.
2359///
2360/// # Arguments
2361/// - `entity`: The name of the entity (e.g., "Server" or "Client") that lacks support.
2362/// - `capability`: The name of the unsupported capability or tool.
2363/// - `method_name`: The name of the method requiring the capability.
2364///
2365/// # Returns
2366/// A formatted string detailing the unsupported capability error.
2367///
2368/// # Examples
2369/// ```ignore
2370/// let msg = create_unsupported_capability_message("Server", "tools", rust_mcp_schema::ListResourcesRequest::method_value());
2371/// assert_eq!(msg, "Server does not support resources (required for resources/list)");
2372/// ```
2373fn create_unsupported_capability_message(entity: &str, capability: &str, method_name: &str) -> String {
2374    format!("{entity} does not support {capability} (required for {method_name})")
2375}
2376
2377impl ClientCapabilities {
2378    /// Asserts that the client supports the requested server-initiated operation.
2379    ///
2380    /// In the 2026-07-28 protocol, server→client requests arrive as `InputRequest`s
2381    /// (mid-request) or standalone JSON-RPC requests. Each maps to a client capability:
2382    /// - `sampling/createMessage` → `sampling`
2383    /// - `roots/list` → `roots`
2384    /// - `elicitation/create` → `elicitation`
2385    pub fn can_handle_request(&self, server_jsonrpc_request: &ServerJsonrpcRequest) -> std::result::Result<(), RpcError> {
2386        let entity = "Client";
2387        match server_jsonrpc_request {
2388            ServerJsonrpcRequest::CreateMessageRequest { .. } if self.sampling.is_none() => {
2389                Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2390                    entity,
2391                    "sampling",
2392                    CreateMessageRequest::method_value(),
2393                )))
2394            }
2395            ServerJsonrpcRequest::ListRootsRequest { .. } if self.roots.is_none() => {
2396                Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2397                    entity,
2398                    "roots",
2399                    ListRootsRequest::method_value(),
2400                )))
2401            }
2402            ServerJsonrpcRequest::ElicitRequest { .. } if self.elicitation.is_none() => {
2403                Err(RpcError::internal_error().with_message(create_unsupported_capability_message(
2404                    entity,
2405                    "elicitation",
2406                    ElicitRequest::method_value(),
2407                )))
2408            }
2409            _ => Ok(()),
2410        }
2411    }
2412
2413    /// Asserts that the client can emit the given notification.
2414    ///
2415    /// Client→server notifications (`notifications/cancelled`, `notifications/progress`)
2416    /// are not gated by any client capability, so this always succeeds.
2417    pub fn can_accept_notification(&self, _notification_method: &str) -> std::result::Result<(), RpcError> {
2418        Ok(())
2419    }
2420}
2421
2422
2423impl From<JsonrpcRequest> for CustomRequest {
2424    fn from(request: JsonrpcRequest) -> Self {
2425        Self {
2426            method: request.method,
2427            params: request.params,
2428        }
2429    }
2430}
2431
2432impl From<JsonrpcNotification> for CustomNotification {
2433    fn from(notification: JsonrpcNotification) -> Self {
2434        Self {
2435            method: notification.method,
2436            params: notification.params,
2437        }
2438    }
2439}
2440
2441impl FromStr for Role {
2442    type Err = RpcError;
2443
2444    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
2445        match s {
2446            "assistant" => Ok(Role::Assistant),
2447            "user" => Ok(Role::User),
2448            _ => {
2449                Err(RpcError::parse_error()
2450                    .with_message(format!("Invalid role '{s}'. Expected one of: 'assistant', 'user'")))
2451            }
2452        }
2453    }
2454}
2455
2456pub type CustomNotification = CustomRequest;
2457
2458impl ServerResult {
2459    /// Returns `true` if this result is an `InputRequiredResult`, i.e. the server is
2460    /// requesting additional client input (sampling, roots, or elicitation) before it can
2461    /// complete the original request. This is the 2026-07-28 mid-request interaction mechanism.
2462    pub fn is_input_required(&self) -> bool {
2463        matches!(self, ServerResult::InputRequiredResult(_))
2464    }
2465
2466    /// Returns `true` if this result is a final (complete) result rather than an
2467    /// `InputRequiredResult`. For results received from pre-2026 peers (which carry no
2468    /// `resultType`), this is always `true`.
2469    pub fn is_complete(&self) -> bool {
2470        !self.is_input_required()
2471    }
2472
2473    /// Returns the inner `InputRequiredResult` if this is an input-required response,
2474    /// otherwise `None`. Use this to drive the elicitation/retry loop.
2475    pub fn as_input_required(&self) -> Option<&InputRequiredResult> {
2476        match self {
2477            ServerResult::InputRequiredResult(result) => Some(result),
2478            _ => None,
2479        }
2480    }
2481}
2482
2483//*********************************//
2484//**  RequestMetaObject helpers  **//
2485//*********************************//
2486
2487impl RequestMetaObject {
2488    /// Creates the connection-level `_meta` required on every 2026-07-28 request,
2489    /// with the two mandatory fields: protocol version and client capabilities.
2490    pub fn new<T: Into<String>>(protocol_version: T, client_capabilities: ClientCapabilities) -> Self {
2491        Self {
2492            client_capabilities,
2493            client_info: None,
2494            log_level: None,
2495            protocol_version: protocol_version.into(),
2496            progress_token: None,
2497            extra: None,
2498        }
2499    }
2500
2501    pub fn with_client_info(mut self, client_info: Implementation) -> Self {
2502        self.client_info = Some(client_info);
2503        self
2504    }
2505
2506    pub fn with_log_level(mut self, log_level: LoggingLevel) -> Self {
2507        self.log_level = Some(log_level);
2508        self
2509    }
2510
2511    pub fn with_progress_token(mut self, progress_token: ProgressToken) -> Self {
2512        self.progress_token = Some(progress_token);
2513        self
2514    }
2515
2516    // --- SEP-414 OpenTelemetry trace-context accessors ------------------------
2517    //
2518    // `traceparent`, `tracestate` and `baggage` are reserved `_meta` keys
2519    // (W3C Trace Context / Baggage) carried through the `extra` catch-all map.
2520    // Values are opaque strings here — format validation is intentionally left
2521    // to the SDK layer so this crate stays dependency-free and lossless.
2522
2523    /// Returns the W3C `traceparent` value, if present.
2524    pub fn traceparent(&self) -> Option<&str> {
2525        self.extra
2526            .as_ref()
2527            .and_then(|m| m.get("traceparent"))
2528            .and_then(|v| v.as_str())
2529    }
2530
2531    /// Sets the W3C `traceparent` value.
2532    pub fn with_traceparent(mut self, traceparent: impl Into<String>) -> Self {
2533        self.extra_mut().insert(
2534            "traceparent".to_string(),
2535            serde_json::Value::String(traceparent.into()),
2536        );
2537        self
2538    }
2539
2540    /// Returns the W3C `tracestate` value, if present.
2541    pub fn tracestate(&self) -> Option<&str> {
2542        self.extra
2543            .as_ref()
2544            .and_then(|m| m.get("tracestate"))
2545            .and_then(|v| v.as_str())
2546    }
2547
2548    /// Sets the W3C `tracestate` value.
2549    pub fn with_tracestate(mut self, tracestate: impl Into<String>) -> Self {
2550        self.extra_mut().insert(
2551            "tracestate".to_string(),
2552            serde_json::Value::String(tracestate.into()),
2553        );
2554        self
2555    }
2556
2557    /// Returns the W3C `baggage` value, if present.
2558    pub fn baggage(&self) -> Option<&str> {
2559        self.extra
2560            .as_ref()
2561            .and_then(|m| m.get("baggage"))
2562            .and_then(|v| v.as_str())
2563    }
2564
2565    /// Sets the W3C `baggage` value.
2566    pub fn with_baggage(mut self, baggage: impl Into<String>) -> Self {
2567        self.extra_mut().insert(
2568            "baggage".to_string(),
2569            serde_json::Value::String(baggage.into()),
2570        );
2571        self
2572    }
2573
2574    /// Internal helper: get-or-create the `extra` catch-all map.
2575    fn extra_mut(&mut self) -> &mut ::serde_json::Map<String, ::serde_json::Value> {
2576        self.extra.get_or_insert_with(Default::default)
2577    }
2578}
2579
2580//*********************************//
2581//**  InputRequired helpers      **//
2582//*********************************//
2583
2584impl InputRequests {
2585    /// Iterates over the `(key, InputRequest)` pairs the server is asking the client to resolve.
2586    pub fn iter(&self) -> impl Iterator<Item = (&String, &InputRequest)> {
2587        self.0.iter()
2588    }
2589
2590    /// Iterates over the request keys (used to correlate each `InputResponse` in the retry).
2591    pub fn keys(&self) -> impl Iterator<Item = &String> {
2592        self.0.keys()
2593    }
2594
2595    /// Returns the `InputRequest` registered under `key`, if any.
2596    pub fn get(&self, key: &str) -> Option<&InputRequest> {
2597        self.0.get(key)
2598    }
2599
2600    pub fn len(&self) -> usize {
2601        self.0.len()
2602    }
2603
2604    pub fn is_empty(&self) -> bool {
2605        self.0.is_empty()
2606    }
2607}
2608
2609impl InputResponses {
2610    pub fn new() -> Self {
2611        Self(std::collections::BTreeMap::new())
2612    }
2613
2614    /// Adds a resolved response under the key of its originating `InputRequest`
2615    /// (chainable builder for the InputRequired retry flow).
2616    pub fn insert<K: Into<String>, V: Into<InputResponse>>(mut self, key: K, response: V) -> Self {
2617        self.0.insert(key.into(), response.into());
2618        self
2619    }
2620
2621    pub fn len(&self) -> usize {
2622        self.0.len()
2623    }
2624
2625    pub fn is_empty(&self) -> bool {
2626        self.0.is_empty()
2627    }
2628}
2629
2630impl Default for InputResponses {
2631    fn default() -> Self {
2632        Self::new()
2633    }
2634}
2635
2636impl InputRequest {
2637    /// Returns the inner request if this is a `sampling/createMessage` input request.
2638    pub fn as_create_message(&self) -> Option<&CreateMessageRequest> {
2639        match self {
2640            InputRequest::CreateMessageRequest(request) => Some(request),
2641            _ => None,
2642        }
2643    }
2644
2645    /// Returns the inner request if this is a `roots/list` input request.
2646    pub fn as_list_roots(&self) -> Option<&ListRootsRequest> {
2647        match self {
2648            InputRequest::ListRootsRequest(request) => Some(request),
2649            _ => None,
2650        }
2651    }
2652
2653    /// Returns the inner request if this is an `elicitation/create` input request.
2654    pub fn as_elicit(&self) -> Option<&ElicitRequest> {
2655        match self {
2656            InputRequest::ElicitRequest(request) => Some(request),
2657            _ => None,
2658        }
2659    }
2660
2661    /// The JSON-RPC method of the wrapped input request
2662    /// (`sampling/createMessage`, `roots/list`, or `elicitation/create`).
2663    pub fn method(&self) -> &str {
2664        match self {
2665            InputRequest::CreateMessageRequest(request) => request.method(),
2666            InputRequest::ListRootsRequest(request) => request.method(),
2667            InputRequest::ElicitRequest(request) => request.method(),
2668        }
2669    }
2670}
2671
2672/// BEGIN AUTO GENERATED
2673impl From<CreateMessageResult> for ResultFromClient {
2674    fn from(value: CreateMessageResult) -> Self {
2675        Self::CreateMessageResult(value)
2676    }
2677}
2678impl From<ListRootsResult> for ResultFromClient {
2679    fn from(value: ListRootsResult) -> Self {
2680        Self::ListRootsResult(value)
2681    }
2682}
2683impl From<ElicitResult> for ResultFromClient {
2684    fn from(value: ElicitResult) -> Self {
2685        Self::ElicitResult(value)
2686    }
2687}
2688impl From<Result> for ResultFromClient {
2689    fn from(value: Result) -> Self {
2690        Self::Result(value)
2691    }
2692}
2693impl From<CreateMessageResult> for MessageFromClient {
2694    fn from(value: CreateMessageResult) -> Self {
2695        MessageFromClient::ResultFromClient(value.into())
2696    }
2697}
2698impl From<ListRootsResult> for MessageFromClient {
2699    fn from(value: ListRootsResult) -> Self {
2700        MessageFromClient::ResultFromClient(value.into())
2701    }
2702}
2703impl From<ElicitResult> for MessageFromClient {
2704    fn from(value: ElicitResult) -> Self {
2705        MessageFromClient::ResultFromClient(value.into())
2706    }
2707}
2708impl From<Result> for MessageFromClient {
2709    fn from(value: Result) -> Self {
2710        MessageFromClient::ResultFromClient(value.into())
2711    }
2712}
2713impl From<DiscoverRequest> for ClientJsonrpcRequest {
2714    fn from(value: DiscoverRequest) -> Self {
2715        Self::Standard(ClientRequest::DiscoverRequest(value))
2716    }
2717}
2718impl From<ListResourcesRequest> for ClientJsonrpcRequest {
2719    fn from(value: ListResourcesRequest) -> Self {
2720        Self::Standard(ClientRequest::ListResourcesRequest(value))
2721    }
2722}
2723impl From<ListResourceTemplatesRequest> for ClientJsonrpcRequest {
2724    fn from(value: ListResourceTemplatesRequest) -> Self {
2725        Self::Standard(ClientRequest::ListResourceTemplatesRequest(value))
2726    }
2727}
2728impl From<ReadResourceRequest> for ClientJsonrpcRequest {
2729    fn from(value: ReadResourceRequest) -> Self {
2730        Self::Standard(ClientRequest::ReadResourceRequest(value))
2731    }
2732}
2733impl From<SubscriptionsListenRequest> for ClientJsonrpcRequest {
2734    fn from(value: SubscriptionsListenRequest) -> Self {
2735        Self::Standard(ClientRequest::SubscriptionsListenRequest(value))
2736    }
2737}
2738impl From<ListPromptsRequest> for ClientJsonrpcRequest {
2739    fn from(value: ListPromptsRequest) -> Self {
2740        Self::Standard(ClientRequest::ListPromptsRequest(value))
2741    }
2742}
2743impl From<GetPromptRequest> for ClientJsonrpcRequest {
2744    fn from(value: GetPromptRequest) -> Self {
2745        Self::Standard(ClientRequest::GetPromptRequest(value))
2746    }
2747}
2748impl From<ListToolsRequest> for ClientJsonrpcRequest {
2749    fn from(value: ListToolsRequest) -> Self {
2750        Self::Standard(ClientRequest::ListToolsRequest(value))
2751    }
2752}
2753impl From<CallToolRequest> for ClientJsonrpcRequest {
2754    fn from(value: CallToolRequest) -> Self {
2755        Self::Standard(ClientRequest::CallToolRequest(value))
2756    }
2757}
2758impl From<CompleteRequest> for ClientJsonrpcRequest {
2759    fn from(value: CompleteRequest) -> Self {
2760        Self::Standard(ClientRequest::CompleteRequest(value))
2761    }
2762}
2763/// Enum representing SDK error codes.
2764///
2765/// Grouping (reconciled with the 2026-07-28 schema):
2766/// - **SDK-internal** (transport/session; not in the MCP spec): `CONNECTION_CLOSED`,
2767///   `REQUEST_TIMEOUT`, `RESOURCE_NOT_FOUND`, `BAD_REQUEST`, `SESSION_NOT_FOUND`.
2768/// - **MCP-spec** (also schema-derived in `RpcErrorCodes` and as typed error structs
2769///   `MissingRequiredClientCapabilityError` / `UnsupportedProtocolVersionError`):
2770///   `MISSING_REQUIRED_CLIENT_CAPABILITY`, `UNSUPPORTED_PROTOCOL_VERSION`.
2771/// - **JSON-RPC standard** (also schema-derived in `RpcErrorCodes` and as typed error
2772///   structs `ParseError`/`InvalidRequestError`/etc.): `INVALID_REQUEST`,
2773///   `METHOD_NOT_FOUND`, `INVALID_PARAMS`, `INTERNAL_ERROR`, `PARSE_ERROR`.
2774///
2775/// Prefer `RpcErrorCodes` (schema-derived) for protocol errors on the wire; use
2776/// `SdkErrorCodes` for SDK-internal transport/session failures.
2777#[allow(non_camel_case_types)]
2778pub enum SdkErrorCodes {
2779    CONNECTION_CLOSED = -32000,
2780    REQUEST_TIMEOUT = -32001,
2781    RESOURCE_NOT_FOUND = -32002,
2782    BAD_REQUEST = -32015,
2783    SESSION_NOT_FOUND = -32016,
2784    MISSING_REQUIRED_CLIENT_CAPABILITY = -32021,
2785    UNSUPPORTED_PROTOCOL_VERSION = -32022,
2786    INVALID_REQUEST = -32600,
2787    METHOD_NOT_FOUND = -32601,
2788    INVALID_PARAMS = -32602,
2789    INTERNAL_ERROR = -32603,
2790    PARSE_ERROR = -32700,
2791}
2792impl core::fmt::Display for SdkErrorCodes {
2793    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2794        match self {
2795            SdkErrorCodes::CONNECTION_CLOSED => write!(f, "Connection closed"),
2796            SdkErrorCodes::REQUEST_TIMEOUT => write!(f, "Request timeout"),
2797            SdkErrorCodes::INVALID_REQUEST => write!(f, "Invalid request"),
2798            SdkErrorCodes::METHOD_NOT_FOUND => write!(f, "Method not found"),
2799            SdkErrorCodes::INVALID_PARAMS => write!(f, "Invalid params"),
2800            SdkErrorCodes::INTERNAL_ERROR => write!(f, "Internal error"),
2801            SdkErrorCodes::PARSE_ERROR => write!(f, "Parse Error"),
2802            SdkErrorCodes::RESOURCE_NOT_FOUND => write!(f, "Resource not found"),
2803            SdkErrorCodes::BAD_REQUEST => write!(f, "Bad request"),
2804            SdkErrorCodes::SESSION_NOT_FOUND => write!(f, "Session not found"),
2805            SdkErrorCodes::MISSING_REQUIRED_CLIENT_CAPABILITY => {
2806                write!(f, "Missing required client capability")
2807            }
2808            SdkErrorCodes::UNSUPPORTED_PROTOCOL_VERSION => {
2809                write!(f, "Unsupported protocol version")
2810            }
2811        }
2812    }
2813}
2814impl From<SdkErrorCodes> for i64 {
2815    fn from(code: SdkErrorCodes) -> Self {
2816        code as i64
2817    }
2818}
2819#[derive(::serde::Deserialize, ::serde::Serialize, Clone, Debug)]
2820pub struct SdkError {
2821    pub code: i64,
2822    pub data: ::std::option::Option<::serde_json::Value>,
2823    pub message: ::std::string::String,
2824}
2825impl core::fmt::Display for SdkError {
2826    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
2827        write!(f, "MCP error {}: {}", self.code, self.message)
2828    }
2829}
2830impl std::error::Error for SdkError {
2831    fn description(&self) -> &str {
2832        &self.message
2833    }
2834}
2835impl SdkError {
2836    pub fn new(
2837        error_code: SdkErrorCodes,
2838        message: ::std::string::String,
2839        data: ::std::option::Option<::serde_json::Value>,
2840    ) -> Self {
2841        Self {
2842            code: error_code.into(),
2843            data,
2844            message,
2845        }
2846    }
2847    pub fn connection_closed() -> Self {
2848        Self {
2849            code: SdkErrorCodes::CONNECTION_CLOSED.into(),
2850            data: None,
2851            message: SdkErrorCodes::CONNECTION_CLOSED.to_string(),
2852        }
2853    }
2854    pub fn request_timeout(timeout: u128) -> Self {
2855        Self {
2856            code: SdkErrorCodes::REQUEST_TIMEOUT.into(),
2857            data: Some(json!({ "timeout" : timeout })),
2858            message: SdkErrorCodes::REQUEST_TIMEOUT.to_string(),
2859        }
2860    }
2861    pub fn session_not_found() -> Self {
2862        Self {
2863            code: SdkErrorCodes::SESSION_NOT_FOUND.into(),
2864            data: None,
2865            message: SdkErrorCodes::SESSION_NOT_FOUND.to_string(),
2866        }
2867    }
2868    pub fn invalid_request() -> Self {
2869        Self {
2870            code: SdkErrorCodes::INVALID_REQUEST.into(),
2871            data: None,
2872            message: SdkErrorCodes::INVALID_REQUEST.to_string(),
2873        }
2874    }
2875    pub fn method_not_found() -> Self {
2876        Self {
2877            code: SdkErrorCodes::METHOD_NOT_FOUND.into(),
2878            data: None,
2879            message: SdkErrorCodes::METHOD_NOT_FOUND.to_string(),
2880        }
2881    }
2882    pub fn invalid_params() -> Self {
2883        Self {
2884            code: SdkErrorCodes::INVALID_PARAMS.into(),
2885            data: None,
2886            message: SdkErrorCodes::INVALID_PARAMS.to_string(),
2887        }
2888    }
2889    pub fn internal_error() -> Self {
2890        Self {
2891            code: SdkErrorCodes::INTERNAL_ERROR.into(),
2892            data: None,
2893            message: SdkErrorCodes::INTERNAL_ERROR.to_string(),
2894        }
2895    }
2896    pub fn parse_error() -> Self {
2897        Self {
2898            code: SdkErrorCodes::PARSE_ERROR.into(),
2899            data: None,
2900            message: SdkErrorCodes::PARSE_ERROR.to_string(),
2901        }
2902    }
2903    pub fn resource_not_found() -> Self {
2904        Self {
2905            code: SdkErrorCodes::RESOURCE_NOT_FOUND.into(),
2906            data: None,
2907            message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
2908        }
2909    }
2910    pub fn bad_request() -> Self {
2911        Self {
2912            code: SdkErrorCodes::BAD_REQUEST.into(),
2913            data: None,
2914            message: SdkErrorCodes::RESOURCE_NOT_FOUND.to_string(),
2915        }
2916    }
2917    pub fn with_message(mut self, message: &str) -> Self {
2918        self.message = message.to_string();
2919        self
2920    }
2921    pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
2922        self.data = data;
2923        self
2924    }
2925}
2926#[allow(non_camel_case_types)]
2927pub enum RpcErrorCodes {
2928    PARSE_ERROR = -32700isize,
2929    INVALID_REQUEST = -32600isize,
2930    METHOD_NOT_FOUND = -32601isize,
2931    INVALID_PARAMS = -32602isize,
2932    INTERNAL_ERROR = -32603isize,
2933    HEADER_MISMATCH = -32020isize,
2934    MISSING_REQUIRED_CLIENT_CAPABILITY = -32021isize,
2935    UNSUPPORTED_PROTOCOL_VERSION = -32022isize,
2936}
2937impl From<RpcErrorCodes> for i64 {
2938    fn from(code: RpcErrorCodes) -> Self {
2939        code as i64
2940    }
2941}
2942impl RpcError {
2943    pub fn new(
2944        error_code: RpcErrorCodes,
2945        message: ::std::string::String,
2946        data: ::std::option::Option<::serde_json::Value>,
2947    ) -> Self {
2948        Self {
2949            code: error_code.into(),
2950            data,
2951            message,
2952        }
2953    }
2954    pub fn method_not_found() -> Self {
2955        Self {
2956            code: RpcErrorCodes::METHOD_NOT_FOUND.into(),
2957            data: None,
2958            message: "Method not found".to_string(),
2959        }
2960    }
2961    pub fn invalid_params() -> Self {
2962        Self {
2963            code: RpcErrorCodes::INVALID_PARAMS.into(),
2964            data: None,
2965            message: "Invalid params".to_string(),
2966        }
2967    }
2968    pub fn invalid_request() -> Self {
2969        Self {
2970            code: RpcErrorCodes::INVALID_REQUEST.into(),
2971            data: None,
2972            message: "Invalid request".to_string(),
2973        }
2974    }
2975    pub fn internal_error() -> Self {
2976        Self {
2977            code: RpcErrorCodes::INTERNAL_ERROR.into(),
2978            data: None,
2979            message: "Internal error".to_string(),
2980        }
2981    }
2982    pub fn parse_error() -> Self {
2983        Self {
2984            code: RpcErrorCodes::PARSE_ERROR.into(),
2985            data: None,
2986            message: "Parse error".to_string(),
2987        }
2988    }
2989    pub fn with_message<T: Into<String>>(mut self, message: T) -> Self {
2990        self.message = message.into();
2991        self
2992    }
2993    pub fn with_data(mut self, data: ::std::option::Option<::serde_json::Value>) -> Self {
2994        self.data = data;
2995        self
2996    }
2997}
2998impl std::error::Error for RpcError {
2999    fn description(&self) -> &str {
3000        &self.message
3001    }
3002}
3003impl Display for RpcError {
3004    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
3005        write!(
3006            f,
3007            "{}",
3008            serde_json::to_string(self).unwrap_or_else(|err| format!("Serialization error: {err}"))
3009        )
3010    }
3011}
3012impl FromStr for RpcError {
3013    type Err = RpcError;
3014    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
3015        serde_json::from_str(s)
3016            .map_err(|error| RpcError::parse_error().with_data(Some(json!({ "details" : error.to_string() }))))
3017    }
3018}
3019impl JsonrpcErrorResponse {
3020    pub fn create(
3021        id: Option<RequestId>,
3022        error_code: RpcErrorCodes,
3023        error_message: ::std::string::String,
3024        error_data: ::std::option::Option<::serde_json::Value>,
3025    ) -> Self {
3026        Self::new(RpcError::new(error_code, error_message, error_data), id)
3027    }
3028}
3029impl From<MissingRequiredClientCapabilityError> for RpcError {
3030    fn from(value: MissingRequiredClientCapabilityError) -> Self {
3031        RpcError {
3032            code: value.error.code,
3033            data: serde_json::to_value(value.error.data).ok(),
3034            message: value.error.message,
3035        }
3036    }
3037}
3038impl From<UnsupportedProtocolVersionError> for RpcError {
3039    fn from(value: UnsupportedProtocolVersionError) -> Self {
3040        RpcError {
3041            code: value.error.code,
3042            data: serde_json::to_value(value.error.data).ok(),
3043            message: value.error.message,
3044        }
3045    }
3046}
3047impl From<Result> for MessageFromServer {
3048    fn from(value: Result) -> Self {
3049        MessageFromServer::ServerResult(value.into())
3050    }
3051}
3052impl From<InputRequiredResult> for MessageFromServer {
3053    fn from(value: InputRequiredResult) -> Self {
3054        MessageFromServer::ServerResult(value.into())
3055    }
3056}
3057impl From<DiscoverResult> for MessageFromServer {
3058    fn from(value: DiscoverResult) -> Self {
3059        MessageFromServer::ServerResult(value.into())
3060    }
3061}
3062impl From<ListResourcesResult> for MessageFromServer {
3063    fn from(value: ListResourcesResult) -> Self {
3064        MessageFromServer::ServerResult(value.into())
3065    }
3066}
3067impl From<ListResourceTemplatesResult> for MessageFromServer {
3068    fn from(value: ListResourceTemplatesResult) -> Self {
3069        MessageFromServer::ServerResult(value.into())
3070    }
3071}
3072impl From<ReadResourceResult> for MessageFromServer {
3073    fn from(value: ReadResourceResult) -> Self {
3074        MessageFromServer::ServerResult(value.into())
3075    }
3076}
3077impl From<SubscriptionsListenResult> for MessageFromServer {
3078    fn from(value: SubscriptionsListenResult) -> Self {
3079        MessageFromServer::ServerResult(value.into())
3080    }
3081}
3082impl From<ListPromptsResult> for MessageFromServer {
3083    fn from(value: ListPromptsResult) -> Self {
3084        MessageFromServer::ServerResult(value.into())
3085    }
3086}
3087impl From<GetPromptResult> for MessageFromServer {
3088    fn from(value: GetPromptResult) -> Self {
3089        MessageFromServer::ServerResult(value.into())
3090    }
3091}
3092impl From<ListToolsResult> for MessageFromServer {
3093    fn from(value: ListToolsResult) -> Self {
3094        MessageFromServer::ServerResult(value.into())
3095    }
3096}
3097impl From<CallToolResult> for MessageFromServer {
3098    fn from(value: CallToolResult) -> Self {
3099        MessageFromServer::ServerResult(value.into())
3100    }
3101}
3102impl From<CompleteResult> for MessageFromServer {
3103    fn from(value: CompleteResult) -> Self {
3104        MessageFromServer::ServerResult(value.into())
3105    }
3106}
3107impl TryFrom<ResultFromClient> for CreateMessageResult {
3108    type Error = RpcError;
3109    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3110        if let ResultFromClient::CreateMessageResult(result) = value {
3111            Ok(result)
3112        } else {
3113            Err(RpcError::internal_error().with_message("Not a CreateMessageResult".to_string()))
3114        }
3115    }
3116}
3117impl TryFrom<ResultFromClient> for ListRootsResult {
3118    type Error = RpcError;
3119    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3120        if let ResultFromClient::ListRootsResult(result) = value {
3121            Ok(result)
3122        } else {
3123            Err(RpcError::internal_error().with_message("Not a ListRootsResult".to_string()))
3124        }
3125    }
3126}
3127impl TryFrom<ResultFromClient> for ElicitResult {
3128    type Error = RpcError;
3129    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3130        if let ResultFromClient::ElicitResult(result) = value {
3131            Ok(result)
3132        } else {
3133            Err(RpcError::internal_error().with_message("Not a ElicitResult".to_string()))
3134        }
3135    }
3136}
3137impl TryFrom<ResultFromClient> for GenericResult {
3138    type Error = RpcError;
3139    fn try_from(value: ResultFromClient) -> std::result::Result<Self, Self::Error> {
3140        match value {
3141            ResultFromClient::Result(result) => Ok(result),
3142            _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
3143        }
3144    }
3145}
3146impl TryFrom<ServerResult> for GenericResult {
3147    type Error = RpcError;
3148    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3149        match value {
3150            ServerResult::Result(result) => Ok(result),
3151            _ => Err(RpcError::internal_error().with_message("Not a Result".to_string())),
3152        }
3153    }
3154}
3155impl TryFrom<ServerResult> for InputRequiredResult {
3156    type Error = RpcError;
3157    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3158        if let ServerResult::InputRequiredResult(result) = value {
3159            Ok(result)
3160        } else {
3161            Err(RpcError::internal_error().with_message("Not a InputRequiredResult".to_string()))
3162        }
3163    }
3164}
3165impl TryFrom<ServerResult> for DiscoverResult {
3166    type Error = RpcError;
3167    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3168        if let ServerResult::DiscoverResult(result) = value {
3169            Ok(result)
3170        } else {
3171            Err(RpcError::internal_error().with_message("Not a DiscoverResult".to_string()))
3172        }
3173    }
3174}
3175impl TryFrom<ServerResult> for ListResourcesResult {
3176    type Error = RpcError;
3177    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3178        if let ServerResult::ListResourcesResult(result) = value {
3179            Ok(result)
3180        } else {
3181            Err(RpcError::internal_error().with_message("Not a ListResourcesResult".to_string()))
3182        }
3183    }
3184}
3185impl TryFrom<ServerResult> for ListResourceTemplatesResult {
3186    type Error = RpcError;
3187    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3188        if let ServerResult::ListResourceTemplatesResult(result) = value {
3189            Ok(result)
3190        } else {
3191            Err(RpcError::internal_error().with_message("Not a ListResourceTemplatesResult".to_string()))
3192        }
3193    }
3194}
3195impl TryFrom<ServerResult> for ReadResourceResult {
3196    type Error = RpcError;
3197    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3198        if let ServerResult::ReadResourceResult(result) = value {
3199            Ok(result)
3200        } else {
3201            Err(RpcError::internal_error().with_message("Not a ReadResourceResult".to_string()))
3202        }
3203    }
3204}
3205impl TryFrom<ServerResult> for SubscriptionsListenResult {
3206    type Error = RpcError;
3207    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3208        if let ServerResult::SubscriptionsListenResult(result) = value {
3209            Ok(result)
3210        } else {
3211            Err(RpcError::internal_error().with_message("Not a SubscriptionsListenResult".to_string()))
3212        }
3213    }
3214}
3215impl TryFrom<ServerResult> for ListPromptsResult {
3216    type Error = RpcError;
3217    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3218        if let ServerResult::ListPromptsResult(result) = value {
3219            Ok(result)
3220        } else {
3221            Err(RpcError::internal_error().with_message("Not a ListPromptsResult".to_string()))
3222        }
3223    }
3224}
3225impl TryFrom<ServerResult> for GetPromptResult {
3226    type Error = RpcError;
3227    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3228        if let ServerResult::GetPromptResult(result) = value {
3229            Ok(result)
3230        } else {
3231            Err(RpcError::internal_error().with_message("Not a GetPromptResult".to_string()))
3232        }
3233    }
3234}
3235impl TryFrom<ServerResult> for ListToolsResult {
3236    type Error = RpcError;
3237    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3238        if let ServerResult::ListToolsResult(result) = value {
3239            Ok(result)
3240        } else {
3241            Err(RpcError::internal_error().with_message("Not a ListToolsResult".to_string()))
3242        }
3243    }
3244}
3245impl TryFrom<ServerResult> for CallToolResult {
3246    type Error = RpcError;
3247    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3248        if let ServerResult::CallToolResult(result) = value {
3249            Ok(result)
3250        } else {
3251            Err(RpcError::internal_error().with_message("Not a CallToolResult".to_string()))
3252        }
3253    }
3254}
3255impl TryFrom<ServerResult> for CompleteResult {
3256    type Error = RpcError;
3257    fn try_from(value: ServerResult) -> std::result::Result<Self, Self::Error> {
3258        if let ServerResult::CompleteResult(result) = value {
3259            Ok(result)
3260        } else {
3261            Err(RpcError::internal_error().with_message("Not a CompleteResult".to_string()))
3262        }
3263    }
3264}
3265impl ContentBlock {
3266    ///Create a ContentBlock::TextContent
3267    pub fn text_content(text: ::std::string::String) -> Self {
3268        TextContent::new(text, None, None).into()
3269    }
3270    ///Create a ContentBlock::ImageContent
3271    pub fn image_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
3272        ImageContent::new(data, mime_type, None, None).into()
3273    }
3274    ///Create a ContentBlock::AudioContent
3275    pub fn audio_content(data: ::std::string::String, mime_type: ::std::string::String) -> Self {
3276        AudioContent::new(data, mime_type, None, None).into()
3277    }
3278    ///Create a ContentBlock::ResourceLink
3279    pub fn resource_link(value: ResourceLink) -> Self {
3280        value.into()
3281    }
3282    ///Create a ContentBlock::EmbeddedResource
3283    pub fn embedded_resource(resource: EmbeddedResourceResource) -> Self {
3284        EmbeddedResource::new(resource, None, None).into()
3285    }
3286    ///Returns the content type as a string based on the variant of `ContentBlock`
3287    pub fn content_type(&self) -> &str {
3288        match self {
3289            ContentBlock::TextContent(text_content) => text_content.type_(),
3290            ContentBlock::ImageContent(image_content) => image_content.type_(),
3291            ContentBlock::AudioContent(audio_content) => audio_content.type_(),
3292            ContentBlock::ResourceLink(resource_link) => resource_link.type_(),
3293            ContentBlock::EmbeddedResource(embedded_resource) => embedded_resource.type_(),
3294        }
3295    }
3296    pub fn as_text_content(&self) -> std::result::Result<&TextContent, RpcError> {
3297        match &self {
3298            ContentBlock::TextContent(text_content) => Ok(text_content),
3299            _ => Err(RpcError::internal_error().with_message(format!(
3300                "Invalid conversion, \"{}\" is not a {}",
3301                self.content_type(),
3302                "TextContent"
3303            ))),
3304        }
3305    }
3306    pub fn as_image_content(&self) -> std::result::Result<&ImageContent, RpcError> {
3307        match &self {
3308            ContentBlock::ImageContent(image_content) => Ok(image_content),
3309            _ => Err(RpcError::internal_error().with_message(format!(
3310                "Invalid conversion, \"{}\" is not a {}",
3311                self.content_type(),
3312                "ImageContent"
3313            ))),
3314        }
3315    }
3316    pub fn as_audio_content(&self) -> std::result::Result<&AudioContent, RpcError> {
3317        match &self {
3318            ContentBlock::AudioContent(audio_content) => Ok(audio_content),
3319            _ => Err(RpcError::internal_error().with_message(format!(
3320                "Invalid conversion, \"{}\" is not a {}",
3321                self.content_type(),
3322                "AudioContent"
3323            ))),
3324        }
3325    }
3326    pub fn as_resource_link(&self) -> std::result::Result<&ResourceLink, RpcError> {
3327        match &self {
3328            ContentBlock::ResourceLink(resource_link) => Ok(resource_link),
3329            _ => Err(RpcError::internal_error().with_message(format!(
3330                "Invalid conversion, \"{}\" is not a {}",
3331                self.content_type(),
3332                "ResourceLink"
3333            ))),
3334        }
3335    }
3336    pub fn as_embedded_resource(&self) -> std::result::Result<&EmbeddedResource, RpcError> {
3337        match &self {
3338            ContentBlock::EmbeddedResource(embedded_resource) => Ok(embedded_resource),
3339            _ => Err(RpcError::internal_error().with_message(format!(
3340                "Invalid conversion, \"{}\" is not a {}",
3341                self.content_type(),
3342                "EmbeddedResource"
3343            ))),
3344        }
3345    }
3346}
3347impl CallToolResult {
3348    pub fn text_content(content: Vec<TextContent>) -> Self {
3349        Self {
3350            content: content.into_iter().map(Into::into).collect(),
3351            result_type: "complete".to_string(),
3352            is_error: None,
3353            meta: None,
3354            structured_content: None,
3355        }
3356    }
3357    pub fn image_content(content: Vec<ImageContent>) -> Self {
3358        Self {
3359            content: content.into_iter().map(Into::into).collect(),
3360            result_type: "complete".to_string(),
3361            is_error: None,
3362            meta: None,
3363            structured_content: None,
3364        }
3365    }
3366    pub fn audio_content(content: Vec<AudioContent>) -> Self {
3367        Self {
3368            content: content.into_iter().map(Into::into).collect(),
3369            result_type: "complete".to_string(),
3370            is_error: None,
3371            meta: None,
3372            structured_content: None,
3373        }
3374    }
3375    pub fn resource_link(content: Vec<ResourceLink>) -> Self {
3376        Self {
3377            content: content.into_iter().map(Into::into).collect(),
3378            result_type: "complete".to_string(),
3379            is_error: None,
3380            meta: None,
3381            structured_content: None,
3382        }
3383    }
3384    pub fn embedded_resource(content: Vec<EmbeddedResource>) -> Self {
3385        Self {
3386            content: content.into_iter().map(Into::into).collect(),
3387            result_type: "complete".to_string(),
3388            is_error: None,
3389            meta: None,
3390            structured_content: None,
3391        }
3392    }
3393    pub fn with_error(error: CallToolError) -> Self {
3394        Self {
3395            content: vec![ContentBlock::TextContent(TextContent::new(error.to_string(), None, None))],
3396            result_type: "complete".to_string(),
3397            is_error: Some(true),
3398            meta: None,
3399            structured_content: None,
3400        }
3401    }
3402    pub fn with_meta(mut self, meta: Option<ResultMetaObject>) -> Self {
3403        self.meta = meta;
3404        self
3405    }
3406    pub fn with_structured_content(
3407        mut self,
3408        structured_content: ::serde_json::Map<::std::string::String, ::serde_json::Value>,
3409    ) -> Self {
3410        self.structured_content = Some(::serde_json::Value::Object(structured_content));
3411        self
3412    }
3413    pub fn from_content(content: Vec<ContentBlock>) -> Self {
3414        Self {
3415            content,
3416            result_type: "complete".to_string(),
3417            is_error: None,
3418            meta: None,
3419            structured_content: None,
3420        }
3421    }
3422    pub fn add_content(mut self, content: ContentBlock) -> Self {
3423        self.content.push(content);
3424        self
3425    }
3426}
3427impl ::serde::Serialize for ClientJsonrpcResponse {
3428    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
3429    where
3430        S: ::serde::Serializer,
3431    {
3432        let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
3433        state.serialize_field("id", &self.id)?;
3434        state.serialize_field("jsonrpc", &self.jsonrpc)?;
3435        state.serialize_field("result", &self.result)?;
3436        state.end()
3437    }
3438}
3439impl<'de> ::serde::Deserialize<'de> for ClientJsonrpcResponse {
3440    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
3441    where
3442        D: ::serde::Deserializer<'de>,
3443    {
3444        use serde::de::{self, MapAccess, Visitor};
3445        use std::fmt;
3446        struct ClientJsonrpcResponseVisitor;
3447        impl<'de> Visitor<'de> for ClientJsonrpcResponseVisitor {
3448            type Value = ClientJsonrpcResponse;
3449            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3450                formatter.write_str("a valid JSON-RPC response object")
3451            }
3452            fn visit_map<M>(self, mut map: M) -> std::result::Result<ClientJsonrpcResponse, M::Error>
3453            where
3454                M: MapAccess<'de>,
3455            {
3456                let mut id: Option<RequestId> = None;
3457                let mut jsonrpc: Option<String> = None;
3458                let mut result: Option<Value> = None;
3459                while let Some(key) = map.next_key::<String>()? {
3460                    match key.as_str() {
3461                        "id" => id = Some(map.next_value()?),
3462                        "jsonrpc" => jsonrpc = Some(map.next_value()?),
3463                        "result" => result = Some(map.next_value()?),
3464                        _ => {
3465                            return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
3466                        }
3467                    }
3468                }
3469                let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
3470                let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
3471                let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
3472                let result = serde_json::from_value::<ResultFromClient>(result).map_err(de::Error::custom)?;
3473                Ok(ClientJsonrpcResponse { id, jsonrpc, result })
3474            }
3475        }
3476        deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ClientJsonrpcResponseVisitor)
3477    }
3478}
3479impl ::serde::Serialize for ServerJsonrpcResponse {
3480    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
3481    where
3482        S: ::serde::Serializer,
3483    {
3484        let mut state = serializer.serialize_struct("JsonrpcResponse", 3)?;
3485        state.serialize_field("id", &self.id)?;
3486        state.serialize_field("jsonrpc", &self.jsonrpc)?;
3487        state.serialize_field("result", &self.result)?;
3488        state.end()
3489    }
3490}
3491impl<'de> ::serde::Deserialize<'de> for ServerJsonrpcResponse {
3492    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
3493    where
3494        D: ::serde::Deserializer<'de>,
3495    {
3496        use serde::de::{self, MapAccess, Visitor};
3497        use std::fmt;
3498        struct ServerJsonrpcResponseVisitor;
3499        impl<'de> Visitor<'de> for ServerJsonrpcResponseVisitor {
3500            type Value = ServerJsonrpcResponse;
3501            fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
3502                formatter.write_str("a valid JSON-RPC response object")
3503            }
3504            fn visit_map<M>(self, mut map: M) -> std::result::Result<ServerJsonrpcResponse, M::Error>
3505            where
3506                M: MapAccess<'de>,
3507            {
3508                let mut id: Option<RequestId> = None;
3509                let mut jsonrpc: Option<String> = None;
3510                let mut result: Option<Value> = None;
3511                while let Some(key) = map.next_key::<String>()? {
3512                    match key.as_str() {
3513                        "id" => id = Some(map.next_value()?),
3514                        "jsonrpc" => jsonrpc = Some(map.next_value()?),
3515                        "result" => result = Some(map.next_value()?),
3516                        _ => {
3517                            return Err(de::Error::unknown_field(&key, &["id", "jsonrpc", "result"]));
3518                        }
3519                    }
3520                }
3521                let id = id.ok_or_else(|| de::Error::missing_field("id"))?;
3522                let jsonrpc = jsonrpc.ok_or_else(|| de::Error::missing_field("jsonrpc"))?;
3523                let result = result.ok_or_else(|| de::Error::missing_field("result"))?;
3524                let result = serde_json::from_value::<ServerResult>(result).map_err(de::Error::custom)?;
3525                Ok(ServerJsonrpcResponse { id, jsonrpc, result })
3526            }
3527        }
3528        deserializer.deserialize_struct("JsonrpcResponse", &["id", "jsonrpc", "result"], ServerJsonrpcResponseVisitor)
3529    }
3530}
3531impl CallToolRequestParams {
3532    pub fn new<T>(tool_name: T, meta: RequestMetaObject) -> Self
3533    where
3534        T: ToString,
3535    {
3536        Self {
3537            name: tool_name.to_string(),
3538            arguments: None,
3539            input_responses: None,
3540            meta,
3541            request_state: None,
3542        }
3543    }
3544    pub fn with_arguments(mut self, arguments: serde_json::Map<String, Value>) -> Self {
3545        self.arguments = Some(arguments);
3546        self
3547    }
3548}
3549impl CallToolRequestParams {
3550    /// Sets the resolved `inputResponses` for retrying this request after an
3551    /// `input_required` result.
3552    pub fn with_input_responses(mut self, input_responses: InputResponses) -> Self {
3553        self.input_responses = Some(input_responses);
3554        self
3555    }
3556    /// Sets the opaque `requestState` returned by the server, so it can
3557    /// correlate the retry with the original request.
3558    pub fn with_request_state<T: Into<String>>(mut self, request_state: T) -> Self {
3559        self.request_state = Some(request_state.into());
3560        self
3561    }
3562}
3563impl GetPromptRequestParams {
3564    /// Sets the resolved `inputResponses` for retrying this request after an
3565    /// `input_required` result.
3566    pub fn with_input_responses(mut self, input_responses: InputResponses) -> Self {
3567        self.input_responses = Some(input_responses);
3568        self
3569    }
3570    /// Sets the opaque `requestState` returned by the server, so it can
3571    /// correlate the retry with the original request.
3572    pub fn with_request_state<T: Into<String>>(mut self, request_state: T) -> Self {
3573        self.request_state = Some(request_state.into());
3574        self
3575    }
3576}
3577impl InputRequiredResult {
3578    /// Sets the opaque `requestState` returned by the server, so it can
3579    /// correlate the retry with the original request.
3580    pub fn with_request_state<T: Into<String>>(mut self, request_state: T) -> Self {
3581        self.request_state = Some(request_state.into());
3582        self
3583    }
3584    /// Sets the `inputRequests` the server asks the client to resolve before
3585    /// the original request can complete.
3586    pub fn with_input_requests(mut self, input_requests: InputRequests) -> Self {
3587        self.input_requests = Some(input_requests);
3588        self
3589    }
3590}
3591impl InputResponseRequestParams {
3592    /// Sets the resolved `inputResponses` for retrying this request after an
3593    /// `input_required` result.
3594    pub fn with_input_responses(mut self, input_responses: InputResponses) -> Self {
3595        self.input_responses = Some(input_responses);
3596        self
3597    }
3598    /// Sets the opaque `requestState` returned by the server, so it can
3599    /// correlate the retry with the original request.
3600    pub fn with_request_state<T: Into<String>>(mut self, request_state: T) -> Self {
3601        self.request_state = Some(request_state.into());
3602        self
3603    }
3604}
3605impl ReadResourceRequestParams {
3606    /// Sets the resolved `inputResponses` for retrying this request after an
3607    /// `input_required` result.
3608    pub fn with_input_responses(mut self, input_responses: InputResponses) -> Self {
3609        self.input_responses = Some(input_responses);
3610        self
3611    }
3612    /// Sets the opaque `requestState` returned by the server, so it can
3613    /// correlate the retry with the original request.
3614    pub fn with_request_state<T: Into<String>>(mut self, request_state: T) -> Self {
3615        self.request_state = Some(request_state.into());
3616        self
3617    }
3618}
3619/// END AUTO GENERATED
3620#[cfg(test)]
3621mod tests {
3622    use super::*;
3623    use serde_json::json;
3624
3625    #[test]
3626    fn test_detect_message_type() {
3627        // custom request
3628        let result = detect_message_type(&json!({
3629            "id":0,
3630            "method":"add_numbers",
3631            "params":{},
3632            "jsonrpc":"2.0"
3633        }));
3634        assert!(matches!(result, MessageTypes::Request));
3635
3636        // custom notification
3637        let result = detect_message_type(&json!({
3638            "method":"notifications/email_sent",
3639            "jsonrpc":"2.0"
3640        }));
3641        assert!(matches!(result, MessageTypes::Notification));
3642
3643        // standard response
3644        let message = ClientJsonrpcResponse::new(
3645            RequestId::Integer(0),
3646            ResultFromClient::Result(Result {
3647                meta: None,
3648                result_type: "complete".to_string(),
3649                extra: None,
3650            }),
3651        );
3652        let result = detect_message_type(&json!(message));
3653        assert!(matches!(result, MessageTypes::Response));
3654
3655        // custom response
3656        let result = detect_message_type(&json!({
3657            "id":1,
3658            "jsonrpc":"2.0",
3659            "result":"{}",
3660        }));
3661        assert!(matches!(result, MessageTypes::Response));
3662
3663        // error message
3664        let message = JsonrpcErrorResponse::create(
3665            Some(RequestId::Integer(0)),
3666            RpcErrorCodes::INVALID_PARAMS,
3667            "Invalid params!".to_string(),
3668            None,
3669        );
3670        let result = detect_message_type(&json!(message));
3671        assert!(matches!(result, MessageTypes::Error));
3672
3673        // default
3674        let result = detect_message_type(&json!({}));
3675        assert!(matches!(result, MessageTypes::Request));
3676    }
3677}