Skip to main content

strands/mcp/
error.rs

1//! [`McpError`], the failures of an MCP client: protocol errors, MCP SDK errors and the plain
2//! errors `McpClient` throws.
3
4use rmcp::ServiceError;
5use rmcp::model::ErrorData;
6
7use crate::types::JsonValue;
8
9/// The JSON-RPC code a server uses when a request needs URL elicitation first
10/// (`ProtocolErrorCode.UrlElicitationRequired`).
11pub const URL_ELICITATION_REQUIRED: i32 = -32042;
12
13/// Why an MCP SDK operation failed.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15#[non_exhaustive]
16pub enum McpSdkErrorCode {
17    /// The connection closed, or the client disconnected while the operation waited
18    /// (`ConnectionClosed`).
19    ConnectionClosed,
20    /// The operation is not possible before connecting (`NotConnected`).
21    NotConnected,
22    /// The request did not complete in time (`RequestTimeout`).
23    RequestTimeout,
24    /// The server paged past the list cap (`ListPaginationExceeded`).
25    ListPaginationExceeded,
26    /// The transport failed to start, send or receive (`SendFailed`).
27    SendFailed,
28    /// The server sent a response of the wrong shape (`InvalidResult`).
29    InvalidResult,
30}
31
32/// A failure of an MCP client operation.
33///
34/// [`McpError::name`] gives the error's class name.
35#[derive(Debug, Clone, PartialEq, thiserror::Error)]
36#[non_exhaustive]
37pub enum McpError {
38    /// The server answered with a JSON-RPC error (`ProtocolError`).
39    #[error("{message}")]
40    #[non_exhaustive]
41    Protocol {
42        /// The JSON-RPC error code.
43        code: i32,
44        /// The server's message.
45        message: String,
46        /// The server's error data.
47        data: Option<JsonValue>,
48    },
49    /// The MCP SDK failed (`SdkError`).
50    #[error("{message}")]
51    #[non_exhaustive]
52    Sdk {
53        /// What failed.
54        code: McpSdkErrorCode,
55        /// What happened.
56        message: String,
57    },
58    /// Any other failure.
59    #[error("{0}")]
60    Other(String),
61}
62
63impl McpError {
64    /// A protocol error with the given code, message and data.
65    pub fn protocol(code: i32, message: impl Into<String>, data: Option<JsonValue>) -> Self {
66        Self::Protocol {
67            code,
68            message: message.into(),
69            data,
70        }
71    }
72
73    /// An MCP SDK error.
74    pub fn sdk(code: McpSdkErrorCode, message: impl Into<String>) -> Self {
75        Self::Sdk {
76            code,
77            message: message.into(),
78        }
79    }
80
81    /// A plain error.
82    pub fn other(message: impl Into<String>) -> Self {
83        Self::Other(message.into())
84    }
85
86    /// The error's class name: `"ProtocolError"`, `"SdkError"` or `"Error"`.
87    #[must_use]
88    pub fn name(&self) -> &'static str {
89        match self {
90            Self::Protocol { .. } => "ProtocolError",
91            Self::Sdk { .. } => "SdkError",
92            Self::Other(_) => "Error",
93        }
94    }
95
96    /// The `<name>: <message>` form.
97    #[must_use]
98    pub fn to_js_string(&self) -> String {
99        format!("{}: {self}", self.name())
100    }
101
102    pub(crate) fn disconnected() -> Self {
103        Self::sdk(McpSdkErrorCode::ConnectionClosed, "MCP client disconnected")
104    }
105
106    pub(crate) fn transport(error: impl std::fmt::Display) -> Self {
107        Self::sdk(McpSdkErrorCode::SendFailed, error.to_string())
108    }
109}
110
111impl From<ErrorData> for McpError {
112    fn from(error: ErrorData) -> Self {
113        Self::protocol(error.code.0, error.message.into_owned(), error.data)
114    }
115}
116
117impl From<ServiceError> for McpError {
118    fn from(error: ServiceError) -> Self {
119        match error {
120            ServiceError::McpError(data) => data.into(),
121            ServiceError::TransportClosed => Self::sdk(McpSdkErrorCode::ConnectionClosed, "Connection closed"),
122            ServiceError::Timeout { timeout } => Self::sdk(
123                McpSdkErrorCode::RequestTimeout,
124                format!("Request timed out after {}ms", timeout.as_millis()),
125            ),
126            ServiceError::UnexpectedResponse => Self::sdk(McpSdkErrorCode::InvalidResult, "Unexpected response type"),
127            other => Self::transport(other),
128        }
129    }
130}
131
132impl From<McpError> for crate::Error {
133    fn from(error: McpError) -> Self {
134        Self::Mcp(error)
135    }
136}
137
138/// Unit tests for the translation of `rmcp` service errors into MCP error codes and texts.
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn maps_a_closed_transport_to_connection_closed() {
145        assert_eq!(
146            McpError::from(ServiceError::TransportClosed),
147            McpError::sdk(McpSdkErrorCode::ConnectionClosed, "Connection closed")
148        );
149    }
150
151    #[test]
152    fn reports_a_disconnect_during_an_operation_as_connection_closed() {
153        let McpError::Sdk { code, message } = McpError::disconnected() else {
154            panic!("expected an SDK error");
155        };
156        assert_eq!(
157            (code, message.as_str()),
158            (McpSdkErrorCode::ConnectionClosed, "MCP client disconnected")
159        );
160    }
161
162    #[test]
163    fn reports_a_transport_failure_as_send_failed() {
164        let McpError::Sdk { code, .. } = McpError::transport("broken pipe") else {
165            panic!("expected an SDK error");
166        };
167        assert_eq!(code, McpSdkErrorCode::SendFailed);
168    }
169}