agent_client_protocol_schema/
error.rs

1//! Error handling for the Agent Client Protocol.
2//!
3//! This module provides error types and codes following the JSON-RPC 2.0 specification,
4//! with additional protocol-specific error codes for authentication and other ACP-specific scenarios.
5//!
6//! All methods in the protocol follow standard JSON-RPC 2.0 error handling:
7//! - Successful responses include a `result` field
8//! - Errors include an `error` object with `code` and `message`
9//! - Notifications never receive responses (success or error)
10//!
11//! See: [Error Handling](https://agentclientprotocol.com/protocol/overview#error-handling)
12
13use 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/// JSON-RPC error object.
23///
24/// Represents an error that occurred during method execution, following the
25/// JSON-RPC 2.0 error object specification with optional additional data.
26///
27/// See protocol docs: [JSON-RPC Error Object](https://www.jsonrpc.org/specification#error_object)
28#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema, PartialEq, Eq)]
29#[non_exhaustive]
30pub struct Error {
31    /// A number indicating the error type that occurred.
32    /// This must be an integer as defined in the JSON-RPC specification.
33    pub code: ErrorCode,
34    /// A string providing a short description of the error.
35    /// The message should be limited to a concise single sentence.
36    pub message: String,
37    /// Optional primitive or structured value that contains additional information about the error.
38    /// This may include debugging information or context-specific details.
39    #[serde(skip_serializing_if = "Option::is_none")]
40    pub data: Option<serde_json::Value>,
41}
42
43impl Error {
44    /// Creates a new error with the given code and message.
45    ///
46    /// The code parameter can be an `ErrorCode` constant or a tuple of (code, message).
47    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    /// Adds additional data to the error.
56    ///
57    /// This method is chainable and allows attaching context-specific information
58    /// to help with debugging or provide more details about the error.
59    #[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    /// Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
66    #[must_use]
67    pub fn parse_error() -> Self {
68        ErrorCode::ParseError.into()
69    }
70
71    /// The JSON sent is not a valid Request object.
72    #[must_use]
73    pub fn invalid_request() -> Self {
74        ErrorCode::InvalidRequest.into()
75    }
76
77    /// The method does not exist / is not available.
78    #[must_use]
79    pub fn method_not_found() -> Self {
80        ErrorCode::MethodNotFound.into()
81    }
82
83    /// Invalid method parameter(s).
84    #[must_use]
85    pub fn invalid_params() -> Self {
86        ErrorCode::InvalidParams.into()
87    }
88
89    /// Internal JSON-RPC error.
90    #[must_use]
91    pub fn internal_error() -> Self {
92        ErrorCode::InternalError.into()
93    }
94
95    /// Authentication required.
96    #[must_use]
97    pub fn auth_required() -> Self {
98        ErrorCode::AuthRequired.into()
99    }
100
101    /// A given resource, such as a file, was not found.
102    #[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    /// Converts a standard error into an internal JSON-RPC error.
113    ///
114    /// The error's string representation is included as additional data.
115    pub fn into_internal_error(err: impl std::error::Error) -> Self {
116        Error::internal_error().data(err.to_string())
117    }
118}
119
120/// Predefined error codes for common JSON-RPC and ACP-specific errors.
121///
122/// These codes follow the JSON-RPC 2.0 specification for standard errors
123/// and use the reserved range (-32000 to -32099) for protocol-specific errors.
124#[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    // Standard errors
131    /// Invalid JSON was received by the server.
132    /// An error occurred on the server while parsing the JSON text.
133    #[schemars(transform = error_code_transform)]
134    #[strum(to_string = "Parse error")]
135    ParseError, // -32700
136    /// The JSON sent is not a valid Request object.
137    #[schemars(transform = error_code_transform)]
138    #[strum(to_string = "Invalid request")]
139    InvalidRequest, // -32600
140    /// The method does not exist or is not available.
141    #[schemars(transform = error_code_transform)]
142    #[strum(to_string = "Method not found")]
143    MethodNotFound, // -32601
144    /// Invalid method parameter(s).
145    #[schemars(transform = error_code_transform)]
146    #[strum(to_string = "Invalid params")]
147    InvalidParams, // -32602
148    /// Internal JSON-RPC error.
149    /// Reserved for implementation-defined server errors.
150    #[schemars(transform = error_code_transform)]
151    #[strum(to_string = "Internal error")]
152    InternalError, // -32603
153    #[cfg(feature = "unstable_cancel_request")]
154    /// **UNSTABLE**
155    ///
156    /// This capability is not part of the spec yet, and may be removed or changed at any point.
157    ///
158    /// Execution of the method was aborted either due to a cancellation request from the caller or
159    /// because of resource constraints or shutdown.
160    #[schemars(transform = error_code_transform)]
161    #[strum(to_string = "Request cancelled")]
162    RequestCancelled, // -32800
163
164    // Custom errors
165    /// Authentication is required before this operation can be performed.
166    #[schemars(transform = error_code_transform)]
167    #[strum(to_string = "Authentication required")]
168    AuthRequired, // -32000
169    /// A given resource, such as a file, was not found.
170    #[schemars(transform = error_code_transform)]
171    #[strum(to_string = "Resource not found")]
172    ResourceNotFound, // -32002
173
174    /// Other undefined error code.
175    #[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        // Make sure this doesn't panic
321        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}