pulseengine_mcp_protocol/
error.rs1use serde::{Deserialize, Serialize};
4use std::fmt;
5
6pub type Result<T> = std::result::Result<T, Error>;
10
11pub type McpResult<T> = std::result::Result<T, Error>;
13
14#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, thiserror::Error)]
16pub struct Error {
17 pub code: ErrorCode,
19 pub message: String,
21 #[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 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 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 pub fn parse_error(message: impl Into<String>) -> Self {
53 Self::new(ErrorCode::ParseError, message)
54 }
55
56 pub fn invalid_request(message: impl Into<String>) -> Self {
58 Self::new(ErrorCode::InvalidRequest, message)
59 }
60
61 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 pub fn invalid_params(message: impl Into<String>) -> Self {
71 Self::new(ErrorCode::InvalidParams, message)
72 }
73
74 pub fn internal_error(message: impl Into<String>) -> Self {
76 Self::new(ErrorCode::InternalError, message)
77 }
78
79 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 pub fn unauthorized(message: impl Into<String>) -> Self {
93 Self::new(ErrorCode::Unauthorized, message)
94 }
95
96 pub fn forbidden(message: impl Into<String>) -> Self {
98 Self::new(ErrorCode::Forbidden, message)
99 }
100
101 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 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 pub fn validation_error(message: impl Into<String>) -> Self {
119 Self::new(ErrorCode::ValidationError, message)
120 }
121
122 pub fn rate_limit_exceeded(message: impl Into<String>) -> Self {
124 Self::new(ErrorCode::RateLimitExceeded, message)
125 }
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
130pub enum ErrorCode {
131 #[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 #[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
177impl 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#[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 }
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 }
253}