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