agent_client_protocol_schema/
error.rs1use std::{fmt::Display, str};
14
15use schemars::{JsonSchema, Schema};
16use serde::{Deserialize, Serialize};
17
18use crate::IntoOption;
19
20pub type Result<T, E = Error> = std::result::Result<T, E>;
21
22#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct Error {
31 pub code: ErrorCode,
34 pub message: String,
37 #[serde(skip_serializing_if = "Option::is_none")]
40 pub data: Option<serde_json::Value>,
41}
42
43impl Error {
44 pub fn new(code: i32, message: impl Into<String>) -> Self {
48 Error {
49 code: code.into(),
50 message: message.into(),
51 data: None,
52 }
53 }
54
55 #[must_use]
60 pub fn data(mut self, data: impl IntoOption<serde_json::Value>) -> Self {
61 self.data = data.into_option();
62 self
63 }
64
65 #[must_use]
67 pub fn parse_error() -> Self {
68 ErrorCode::ParseError.into()
69 }
70
71 #[must_use]
73 pub fn invalid_request() -> Self {
74 ErrorCode::InvalidRequest.into()
75 }
76
77 #[must_use]
79 pub fn method_not_found() -> Self {
80 ErrorCode::MethodNotFound.into()
81 }
82
83 #[must_use]
85 pub fn invalid_params() -> Self {
86 ErrorCode::InvalidParams.into()
87 }
88
89 #[must_use]
91 pub fn internal_error() -> Self {
92 ErrorCode::InternalError.into()
93 }
94
95 #[must_use]
97 pub fn auth_required() -> Self {
98 ErrorCode::AuthRequired.into()
99 }
100
101 #[must_use]
103 pub fn resource_not_found(uri: Option<String>) -> Self {
104 let err: Self = ErrorCode::ResourceNotFound.into();
105 if let Some(uri) = uri {
106 err.data(serde_json::json!({ "uri": uri }))
107 } else {
108 err
109 }
110 }
111
112 pub fn into_internal_error(err: impl std::error::Error) -> Self {
116 Error::internal_error().data(err.to_string())
117 }
118}
119
120#[derive(Clone, Copy, Deserialize, Eq, JsonSchema, PartialEq, Serialize, strum::Display)]
125#[cfg_attr(test, derive(strum::EnumIter))]
126#[serde(from = "i32", into = "i32")]
127#[schemars(!from, !into)]
128#[non_exhaustive]
129pub enum ErrorCode {
130 #[schemars(transform = error_code_transform)]
134 #[strum(to_string = "Parse error")]
135 ParseError, #[schemars(transform = error_code_transform)]
138 #[strum(to_string = "Invalid request")]
139 InvalidRequest, #[schemars(transform = error_code_transform)]
142 #[strum(to_string = "Method not found")]
143 MethodNotFound, #[schemars(transform = error_code_transform)]
146 #[strum(to_string = "Invalid params")]
147 InvalidParams, #[schemars(transform = error_code_transform)]
151 #[strum(to_string = "Internal error")]
152 InternalError, #[cfg(feature = "unstable_cancel_request")]
154 #[schemars(transform = error_code_transform)]
161 #[strum(to_string = "Request cancelled")]
162 RequestCancelled, #[schemars(transform = error_code_transform)]
167 #[strum(to_string = "Authentication required")]
168 AuthRequired, #[schemars(transform = error_code_transform)]
171 #[strum(to_string = "Resource not found")]
172 ResourceNotFound, #[schemars(untagged)]
176 #[strum(to_string = "Unknown error")]
177 Other(i32),
178}
179
180impl From<i32> for ErrorCode {
181 fn from(value: i32) -> Self {
182 match value {
183 -32700 => ErrorCode::ParseError,
184 -32600 => ErrorCode::InvalidRequest,
185 -32601 => ErrorCode::MethodNotFound,
186 -32602 => ErrorCode::InvalidParams,
187 -32603 => ErrorCode::InternalError,
188 #[cfg(feature = "unstable_cancel_request")]
189 -32800 => ErrorCode::RequestCancelled,
190 -32000 => ErrorCode::AuthRequired,
191 -32002 => ErrorCode::ResourceNotFound,
192 _ => ErrorCode::Other(value),
193 }
194 }
195}
196
197impl From<ErrorCode> for i32 {
198 fn from(value: ErrorCode) -> Self {
199 match value {
200 ErrorCode::ParseError => -32700,
201 ErrorCode::InvalidRequest => -32600,
202 ErrorCode::MethodNotFound => -32601,
203 ErrorCode::InvalidParams => -32602,
204 ErrorCode::InternalError => -32603,
205 #[cfg(feature = "unstable_cancel_request")]
206 ErrorCode::RequestCancelled => -32800,
207 ErrorCode::AuthRequired => -32000,
208 ErrorCode::ResourceNotFound => -32002,
209 ErrorCode::Other(value) => value,
210 }
211 }
212}
213
214impl std::fmt::Debug for ErrorCode {
215 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
216 write!(f, "{}: {self}", i32::from(*self))
217 }
218}
219
220fn error_code_transform(schema: &mut Schema) {
221 let name = schema
222 .get("const")
223 .expect("Unexpected schema for ErrorCode")
224 .as_str()
225 .expect("unexpected type for schema");
226 let code = match name {
227 "ParseError" => ErrorCode::ParseError,
228 "InvalidRequest" => ErrorCode::InvalidRequest,
229 "MethodNotFound" => ErrorCode::MethodNotFound,
230 "InvalidParams" => ErrorCode::InvalidParams,
231 "InternalError" => ErrorCode::InternalError,
232 #[cfg(feature = "unstable_cancel_request")]
233 "RequestCancelled" => ErrorCode::RequestCancelled,
234 "AuthRequired" => ErrorCode::AuthRequired,
235 "ResourceNotFound" => ErrorCode::ResourceNotFound,
236 _ => panic!("Unexpected error code name {name}"),
237 };
238 let mut description = schema
239 .get("description")
240 .expect("Missing description")
241 .as_str()
242 .expect("Unexpected type for description")
243 .to_owned();
244 description.insert_str(0, &format!("**{code}**: "));
245 schema.insert("description".into(), description.into());
246 schema.insert("const".into(), i32::from(code).into());
247 schema.insert("type".into(), "integer".into());
248 schema.insert("format".into(), "int32".into());
249}
250
251impl From<ErrorCode> for Error {
252 fn from(error_code: ErrorCode) -> Self {
253 Error::new(error_code.into(), error_code.to_string())
254 }
255}
256
257impl std::error::Error for Error {}
258
259impl Display for Error {
260 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
261 if self.message.is_empty() {
262 write!(f, "{}", i32::from(self.code))?;
263 } else {
264 write!(f, "{}", self.message)?;
265 }
266
267 if let Some(data) = &self.data {
268 let pretty = serde_json::to_string_pretty(data).unwrap_or_else(|_| data.to_string());
269 write!(f, ": {pretty}")?;
270 }
271
272 Ok(())
273 }
274}
275
276impl From<anyhow::Error> for Error {
277 fn from(error: anyhow::Error) -> Self {
278 match error.downcast::<Self>() {
279 Ok(error) => error,
280 Err(error) => Error::into_internal_error(&*error),
281 }
282 }
283}
284
285impl From<serde_json::Error> for Error {
286 fn from(error: serde_json::Error) -> Self {
287 Error::invalid_params().data(error.to_string())
288 }
289}
290
291#[cfg(test)]
292mod tests {
293 use strum::IntoEnumIterator;
294
295 use super::*;
296
297 #[test]
298 fn serialize_error_code() {
299 assert_eq!(
300 serde_json::from_value::<ErrorCode>(serde_json::json!(-32700)).unwrap(),
301 ErrorCode::ParseError
302 );
303 assert_eq!(
304 serde_json::to_value(ErrorCode::ParseError).unwrap(),
305 serde_json::json!(-32700)
306 );
307
308 assert_eq!(
309 serde_json::from_value::<ErrorCode>(serde_json::json!(1)).unwrap(),
310 ErrorCode::Other(1)
311 );
312 assert_eq!(
313 serde_json::to_value(ErrorCode::Other(1)).unwrap(),
314 serde_json::json!(1)
315 );
316 }
317
318 #[test]
319 fn serialize_error_code_equality() {
320 let _schema = schemars::schema_for!(ErrorCode);
322 for error in ErrorCode::iter() {
323 assert_eq!(
324 error,
325 serde_json::from_value(serde_json::to_value(error).unwrap()).unwrap()
326 );
327 }
328 }
329}