rust_mcp_schema/generated_schema/2024_11_05/
schema_utils.rs

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