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, Serialize, Deserialize)]
130pub enum ErrorCode {
131    // Standard JSON-RPC 2.0 errors
132    #[serde(rename = "-32700")]
133    ParseError = -32700,
134    #[serde(rename = "-32600")]
135    InvalidRequest = -32600,
136    #[serde(rename = "-32601")]
137    MethodNotFound = -32601,
138    #[serde(rename = "-32602")]
139    InvalidParams = -32602,
140    #[serde(rename = "-32603")]
141    InternalError = -32603,
142
143    // MCP-specific errors
144    #[serde(rename = "-32000")]
145    Unauthorized = -32000,
146    #[serde(rename = "-32001")]
147    Forbidden = -32001,
148    #[serde(rename = "-32002")]
149    ResourceNotFound = -32002,
150    #[serde(rename = "-32003")]
151    ToolNotFound = -32003,
152    #[serde(rename = "-32004")]
153    ValidationError = -32004,
154    #[serde(rename = "-32005")]
155    RateLimitExceeded = -32005,
156}
157
158impl fmt::Display for ErrorCode {
159    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
160        let name = match self {
161            ErrorCode::ParseError => "ParseError",
162            ErrorCode::InvalidRequest => "InvalidRequest",
163            ErrorCode::MethodNotFound => "MethodNotFound",
164            ErrorCode::InvalidParams => "InvalidParams",
165            ErrorCode::InternalError => "InternalError",
166            ErrorCode::Unauthorized => "Unauthorized",
167            ErrorCode::Forbidden => "Forbidden",
168            ErrorCode::ResourceNotFound => "ResourceNotFound",
169            ErrorCode::ToolNotFound => "ToolNotFound",
170            ErrorCode::ValidationError => "ValidationError",
171            ErrorCode::RateLimitExceeded => "RateLimitExceeded",
172        };
173        write!(f, "{name}")
174    }
175}
176
177// Implement conversion from common error types
178impl From<serde_json::Error> for Error {
179    fn from(err: serde_json::Error) -> Self {
180        Error::parse_error(err.to_string())
181    }
182}
183
184impl From<uuid::Error> for Error {
185    fn from(err: uuid::Error) -> Self {
186        Error::validation_error(format!("Invalid UUID: {err}"))
187    }
188}
189
190impl From<validator::ValidationErrors> for Error {
191    fn from(err: validator::ValidationErrors) -> Self {
192        Error::validation_error(err.to_string())
193    }
194}
195
196#[cfg(feature = "logging")]
197impl From<pulseengine_mcp_logging::LoggingError> for Error {
198    fn from(err: pulseengine_mcp_logging::LoggingError) -> Self {
199        match err {
200            pulseengine_mcp_logging::LoggingError::Config(msg) => {
201                Error::invalid_request(format!("Logging config: {msg}"))
202            }
203            pulseengine_mcp_logging::LoggingError::Io(io_err) => {
204                Error::internal_error(format!("Logging I/O: {io_err}"))
205            }
206            pulseengine_mcp_logging::LoggingError::Serialization(serde_err) => {
207                Error::internal_error(format!("Logging serialization: {serde_err}"))
208            }
209            pulseengine_mcp_logging::LoggingError::Tracing(msg) => {
210                Error::internal_error(format!("Tracing: {msg}"))
211            }
212        }
213    }
214}
215
216// Optional ErrorClassification implementation when logging feature is enabled
217#[cfg(feature = "logging")]
218impl pulseengine_mcp_logging::ErrorClassification for Error {
219    fn error_type(&self) -> &str {
220        match self.code {
221            ErrorCode::ParseError => "parse_error",
222            ErrorCode::InvalidRequest => "invalid_request",
223            ErrorCode::MethodNotFound => "method_not_found",
224            ErrorCode::InvalidParams => "invalid_params",
225            ErrorCode::InternalError => "internal_error",
226            ErrorCode::Unauthorized => "unauthorized",
227            ErrorCode::Forbidden => "forbidden",
228            ErrorCode::ResourceNotFound => "resource_not_found",
229            ErrorCode::ToolNotFound => "tool_not_found",
230            ErrorCode::ValidationError => "validation_error",
231            ErrorCode::RateLimitExceeded => "rate_limit_exceeded",
232        }
233    }
234
235    fn is_retryable(&self) -> bool {
236        matches!(
237            self.code,
238            ErrorCode::InternalError | ErrorCode::RateLimitExceeded
239        )
240    }
241
242    fn is_timeout(&self) -> bool {
243        false // Protocol errors don't directly represent timeouts
244    }
245
246    fn is_auth_error(&self) -> bool {
247        matches!(self.code, ErrorCode::Unauthorized | ErrorCode::Forbidden)
248    }
249
250    fn is_connection_error(&self) -> bool {
251        false // Protocol errors don't directly represent connection errors
252    }
253}