pulseengine_mcp_protocol/
error.rs

1//! Error types for the MCP protocol
2
3use serde::{Deserialize, Serialize};
4use std::fmt;
5
6/// Result type alias for MCP protocol operations
7///
8/// Note: Use `McpResult` instead of `Result` to avoid conflicts with std::result::Result
9pub type Result<T> = std::result::Result<T, Error>;
10
11/// Preferred result type alias that doesn't conflict with std::result::Result
12pub type McpResult<T> = std::result::Result<T, Error>;
13
14/// Core MCP error type
15#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, thiserror::Error)]
16pub struct Error {
17    /// Error code following MCP specification
18    pub code: ErrorCode,
19    /// Human-readable error message
20    pub message: String,
21    /// Optional additional error data
22    #[serde(skip_serializing_if = "Option::is_none")]
23    pub data: Option<serde_json::Value>,
24}
25
26impl fmt::Display for Error {
27    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28        write!(f, "{}: {}", self.code, self.message)
29    }
30}
31
32impl Error {
33    /// Create a new error with the given code and message
34    pub fn new(code: ErrorCode, message: impl Into<String>) -> Self {
35        Self {
36            code,
37            message: message.into(),
38            data: None,
39        }
40    }
41
42    /// Create an error with additional data
43    pub fn with_data(code: ErrorCode, message: impl Into<String>, data: serde_json::Value) -> Self {
44        Self {
45            code,
46            message: message.into(),
47            data: Some(data),
48        }
49    }
50
51    /// Create a parse error
52    pub fn parse_error(message: impl Into<String>) -> Self {
53        Self::new(ErrorCode::ParseError, message)
54    }
55
56    /// Create an invalid request error
57    pub fn invalid_request(message: impl Into<String>) -> Self {
58        Self::new(ErrorCode::InvalidRequest, message)
59    }
60
61    /// Create a method not found error
62    pub fn method_not_found(method: impl Into<String>) -> Self {
63        Self::new(
64            ErrorCode::MethodNotFound,
65            format!("Method not found: {}", method.into()),
66        )
67    }
68
69    /// Create an invalid params error
70    pub fn invalid_params(message: impl Into<String>) -> Self {
71        Self::new(ErrorCode::InvalidParams, message)
72    }
73
74    /// Create an internal error
75    pub fn internal_error(message: impl Into<String>) -> Self {
76        Self::new(ErrorCode::InternalError, message)
77    }
78
79    /// Create a protocol version mismatch error
80    pub fn protocol_version_mismatch(client_version: &str, server_version: &str) -> Self {
81        Self::with_data(
82            ErrorCode::InvalidRequest,
83            format!("Protocol version mismatch: client={client_version}, server={server_version}"),
84            serde_json::json!({
85                "client_version": client_version,
86                "server_version": server_version
87            }),
88        )
89    }
90
91    /// Create an authorization error
92    pub fn unauthorized(message: impl Into<String>) -> Self {
93        Self::new(ErrorCode::Unauthorized, message)
94    }
95
96    /// Create a forbidden error
97    pub fn forbidden(message: impl Into<String>) -> Self {
98        Self::new(ErrorCode::Forbidden, message)
99    }
100
101    /// Create a resource not found error
102    pub fn resource_not_found(resource: impl Into<String>) -> Self {
103        Self::new(
104            ErrorCode::ResourceNotFound,
105            format!("Resource not found: {}", resource.into()),
106        )
107    }
108
109    /// Create a tool not found error
110    pub fn tool_not_found(tool: impl Into<String>) -> Self {
111        Self::new(
112            ErrorCode::ToolNotFound,
113            format!("Tool not found: {}", tool.into()),
114        )
115    }
116
117    /// Create a validation error
118    pub fn validation_error(message: impl Into<String>) -> Self {
119        Self::new(ErrorCode::ValidationError, message)
120    }
121
122    /// Create a rate limit exceeded error
123    pub fn rate_limit_exceeded(message: impl Into<String>) -> Self {
124        Self::new(ErrorCode::RateLimitExceeded, message)
125    }
126}
127
128/// MCP error codes following JSON-RPC 2.0 specification
129#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
130#[repr(i32)]
131pub enum ErrorCode {
132    // Standard JSON-RPC 2.0 errors
133    ParseError = -32700,
134    InvalidRequest = -32600,
135    MethodNotFound = -32601,
136    InvalidParams = -32602,
137    InternalError = -32603,
138
139    // MCP-specific errors
140    Unauthorized = -32000,
141    Forbidden = -32001,
142    ResourceNotFound = -32002,
143    ToolNotFound = -32003,
144    ValidationError = -32004,
145    RateLimitExceeded = -32005,
146}
147
148impl Serialize for ErrorCode {
149    fn serialize<S>(&self, serializer: S) -> std::result::Result<S::Ok, S::Error>
150    where
151        S: serde::Serializer,
152    {
153        serializer.serialize_i32(*self as i32)
154    }
155}
156
157impl<'de> Deserialize<'de> for ErrorCode {
158    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
159    where
160        D: serde::Deserializer<'de>,
161    {
162        let code = i32::deserialize(deserializer)?;
163        match code {
164            -32700 => Ok(ErrorCode::ParseError),
165            -32600 => Ok(ErrorCode::InvalidRequest),
166            -32601 => Ok(ErrorCode::MethodNotFound),
167            -32602 => Ok(ErrorCode::InvalidParams),
168            -32603 => Ok(ErrorCode::InternalError),
169            -32000 => Ok(ErrorCode::Unauthorized),
170            -32001 => Ok(ErrorCode::Forbidden),
171            -32002 => Ok(ErrorCode::ResourceNotFound),
172            -32003 => Ok(ErrorCode::ToolNotFound),
173            -32004 => Ok(ErrorCode::ValidationError),
174            -32005 => Ok(ErrorCode::RateLimitExceeded),
175            _ => Err(serde::de::Error::custom(format!(
176                "Unknown error code: {code}"
177            ))),
178        }
179    }
180}
181
182impl fmt::Display for ErrorCode {
183    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
184        let name = match self {
185            ErrorCode::ParseError => "ParseError",
186            ErrorCode::InvalidRequest => "InvalidRequest",
187            ErrorCode::MethodNotFound => "MethodNotFound",
188            ErrorCode::InvalidParams => "InvalidParams",
189            ErrorCode::InternalError => "InternalError",
190            ErrorCode::Unauthorized => "Unauthorized",
191            ErrorCode::Forbidden => "Forbidden",
192            ErrorCode::ResourceNotFound => "ResourceNotFound",
193            ErrorCode::ToolNotFound => "ToolNotFound",
194            ErrorCode::ValidationError => "ValidationError",
195            ErrorCode::RateLimitExceeded => "RateLimitExceeded",
196        };
197        write!(f, "{name}")
198    }
199}
200
201// Implement conversion from common error types
202impl From<serde_json::Error> for Error {
203    fn from(err: serde_json::Error) -> Self {
204        Error::parse_error(err.to_string())
205    }
206}
207
208impl From<uuid::Error> for Error {
209    fn from(err: uuid::Error) -> Self {
210        Error::validation_error(format!("Invalid UUID: {err}"))
211    }
212}
213
214impl From<validator::ValidationErrors> for Error {
215    fn from(err: validator::ValidationErrors) -> Self {
216        Error::validation_error(err.to_string())
217    }
218}
219
220#[cfg(feature = "logging")]
221impl From<pulseengine_mcp_logging::LoggingError> for Error {
222    fn from(err: pulseengine_mcp_logging::LoggingError) -> Self {
223        match err {
224            pulseengine_mcp_logging::LoggingError::Config(msg) => {
225                Error::invalid_request(format!("Logging config: {msg}"))
226            }
227            pulseengine_mcp_logging::LoggingError::Io(io_err) => {
228                Error::internal_error(format!("Logging I/O: {io_err}"))
229            }
230            pulseengine_mcp_logging::LoggingError::Serialization(serde_err) => {
231                Error::internal_error(format!("Logging serialization: {serde_err}"))
232            }
233            pulseengine_mcp_logging::LoggingError::Tracing(msg) => {
234                Error::internal_error(format!("Tracing: {msg}"))
235            }
236        }
237    }
238}
239
240// Optional ErrorClassification implementation when logging feature is enabled
241#[cfg(feature = "logging")]
242impl pulseengine_mcp_logging::ErrorClassification for Error {
243    fn error_type(&self) -> &str {
244        match self.code {
245            ErrorCode::ParseError => "parse_error",
246            ErrorCode::InvalidRequest => "invalid_request",
247            ErrorCode::MethodNotFound => "method_not_found",
248            ErrorCode::InvalidParams => "invalid_params",
249            ErrorCode::InternalError => "internal_error",
250            ErrorCode::Unauthorized => "unauthorized",
251            ErrorCode::Forbidden => "forbidden",
252            ErrorCode::ResourceNotFound => "resource_not_found",
253            ErrorCode::ToolNotFound => "tool_not_found",
254            ErrorCode::ValidationError => "validation_error",
255            ErrorCode::RateLimitExceeded => "rate_limit_exceeded",
256        }
257    }
258
259    fn is_retryable(&self) -> bool {
260        matches!(
261            self.code,
262            ErrorCode::InternalError | ErrorCode::RateLimitExceeded
263        )
264    }
265
266    fn is_timeout(&self) -> bool {
267        false // Protocol errors don't directly represent timeouts
268    }
269
270    fn is_auth_error(&self) -> bool {
271        matches!(self.code, ErrorCode::Unauthorized | ErrorCode::Forbidden)
272    }
273
274    fn is_connection_error(&self) -> bool {
275        false // Protocol errors don't directly represent connection errors
276    }
277}