Skip to main content

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    #[must_use]
48    pub fn new(code: i32, message: impl Into<String>) -> Self {
49        Error {
50            code: code.into(),
51            message: message.into(),
52            data: None,
53        }
54    }
55
56    /// Adds additional data to the error.
57    ///
58    /// This method is chainable and allows attaching context-specific information
59    /// to help with debugging or provide more details about the error.
60    #[must_use]
61    pub fn data(mut self, data: impl IntoOption<serde_json::Value>) -> Self {
62        self.data = data.into_option();
63        self
64    }
65
66    /// Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
67    #[must_use]
68    pub fn parse_error() -> Self {
69        ErrorCode::ParseError.into()
70    }
71
72    /// The JSON sent is not a valid Request object.
73    #[must_use]
74    pub fn invalid_request() -> Self {
75        ErrorCode::InvalidRequest.into()
76    }
77
78    /// The method does not exist / is not available.
79    #[must_use]
80    pub fn method_not_found() -> Self {
81        ErrorCode::MethodNotFound.into()
82    }
83
84    /// Invalid method parameter(s).
85    #[must_use]
86    pub fn invalid_params() -> Self {
87        ErrorCode::InvalidParams.into()
88    }
89
90    /// Internal JSON-RPC error.
91    #[must_use]
92    pub fn internal_error() -> Self {
93        ErrorCode::InternalError.into()
94    }
95
96    /// **UNSTABLE**
97    ///
98    /// This capability is not part of the spec yet, and may be removed or changed at any point.
99    ///
100    /// Request was cancelled.
101    ///
102    /// Execution of the method was aborted either due to a cancellation request from the caller
103    /// or because of resource constraints or shutdown.
104    #[cfg(feature = "unstable_cancel_request")]
105    #[must_use]
106    pub fn request_cancelled() -> Self {
107        ErrorCode::RequestCancelled.into()
108    }
109
110    /// Authentication required.
111    #[must_use]
112    pub fn auth_required() -> Self {
113        ErrorCode::AuthRequired.into()
114    }
115
116    /// A given resource, such as a file, was not found.
117    #[must_use]
118    pub fn resource_not_found(uri: Option<String>) -> Self {
119        let err: Self = ErrorCode::ResourceNotFound.into();
120        if let Some(uri) = uri {
121            err.data(serde_json::json!({ "uri": uri }))
122        } else {
123            err
124        }
125    }
126
127    /// Converts a standard error into an internal JSON-RPC error.
128    ///
129    /// The error's string representation is included as additional data.
130    #[must_use]
131    pub fn into_internal_error(err: impl std::error::Error) -> Self {
132        Error::internal_error().data(err.to_string())
133    }
134}
135
136/// Predefined error codes for common JSON-RPC and ACP-specific errors.
137///
138/// These codes follow the JSON-RPC 2.0 specification for standard errors
139/// and use the reserved range (-32000 to -32099) for protocol-specific errors.
140#[derive(Clone, Copy, Deserialize, Eq, JsonSchema, PartialEq, Serialize, strum::Display)]
141#[cfg_attr(test, derive(strum::EnumIter))]
142#[serde(from = "i32", into = "i32")]
143#[schemars(!from, !into)]
144#[non_exhaustive]
145pub enum ErrorCode {
146    // Standard errors
147    /// Invalid JSON was received by the server.
148    /// An error occurred on the server while parsing the JSON text.
149    #[schemars(transform = error_code_transform)]
150    #[strum(to_string = "Parse error")]
151    ParseError, // -32700
152    /// The JSON sent is not a valid Request object.
153    #[schemars(transform = error_code_transform)]
154    #[strum(to_string = "Invalid request")]
155    InvalidRequest, // -32600
156    /// The method does not exist or is not available.
157    #[schemars(transform = error_code_transform)]
158    #[strum(to_string = "Method not found")]
159    MethodNotFound, // -32601
160    /// Invalid method parameter(s).
161    #[schemars(transform = error_code_transform)]
162    #[strum(to_string = "Invalid params")]
163    InvalidParams, // -32602
164    /// Internal JSON-RPC error.
165    /// Reserved for implementation-defined server errors.
166    #[schemars(transform = error_code_transform)]
167    #[strum(to_string = "Internal error")]
168    InternalError, // -32603
169    #[cfg(feature = "unstable_cancel_request")]
170    /// **UNSTABLE**
171    ///
172    /// This capability is not part of the spec yet, and may be removed or changed at any point.
173    ///
174    /// Execution of the method was aborted either due to a cancellation request from the caller or
175    /// because of resource constraints or shutdown.
176    #[schemars(transform = error_code_transform)]
177    #[strum(to_string = "Request cancelled")]
178    RequestCancelled, // -32800
179
180    // Custom errors
181    /// Authentication is required before this operation can be performed.
182    #[schemars(transform = error_code_transform)]
183    #[strum(to_string = "Authentication required")]
184    AuthRequired, // -32000
185    /// A given resource, such as a file, was not found.
186    #[schemars(transform = error_code_transform)]
187    #[strum(to_string = "Resource not found")]
188    ResourceNotFound, // -32002
189
190    /// Other undefined error code.
191    #[schemars(untagged)]
192    #[strum(to_string = "Unknown error")]
193    Other(i32),
194}
195
196impl From<i32> for ErrorCode {
197    fn from(value: i32) -> Self {
198        match value {
199            -32700 => ErrorCode::ParseError,
200            -32600 => ErrorCode::InvalidRequest,
201            -32601 => ErrorCode::MethodNotFound,
202            -32602 => ErrorCode::InvalidParams,
203            -32603 => ErrorCode::InternalError,
204            #[cfg(feature = "unstable_cancel_request")]
205            -32800 => ErrorCode::RequestCancelled,
206            -32000 => ErrorCode::AuthRequired,
207            -32002 => ErrorCode::ResourceNotFound,
208            _ => ErrorCode::Other(value),
209        }
210    }
211}
212
213impl From<ErrorCode> for i32 {
214    fn from(value: ErrorCode) -> Self {
215        match value {
216            ErrorCode::ParseError => -32700,
217            ErrorCode::InvalidRequest => -32600,
218            ErrorCode::MethodNotFound => -32601,
219            ErrorCode::InvalidParams => -32602,
220            ErrorCode::InternalError => -32603,
221            #[cfg(feature = "unstable_cancel_request")]
222            ErrorCode::RequestCancelled => -32800,
223            ErrorCode::AuthRequired => -32000,
224            ErrorCode::ResourceNotFound => -32002,
225            ErrorCode::Other(value) => value,
226        }
227    }
228}
229
230impl std::fmt::Debug for ErrorCode {
231    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
232        write!(f, "{}: {self}", i32::from(*self))
233    }
234}
235
236fn error_code_transform(schema: &mut Schema) {
237    let name = schema
238        .get("const")
239        .expect("Unexpected schema for ErrorCode")
240        .as_str()
241        .expect("unexpected type for schema");
242    let code = match name {
243        "ParseError" => ErrorCode::ParseError,
244        "InvalidRequest" => ErrorCode::InvalidRequest,
245        "MethodNotFound" => ErrorCode::MethodNotFound,
246        "InvalidParams" => ErrorCode::InvalidParams,
247        "InternalError" => ErrorCode::InternalError,
248        #[cfg(feature = "unstable_cancel_request")]
249        "RequestCancelled" => ErrorCode::RequestCancelled,
250        "AuthRequired" => ErrorCode::AuthRequired,
251        "ResourceNotFound" => ErrorCode::ResourceNotFound,
252        _ => panic!("Unexpected error code name {name}"),
253    };
254    let mut description = schema
255        .get("description")
256        .expect("Missing description")
257        .as_str()
258        .expect("Unexpected type for description")
259        .to_owned();
260    schema.insert("title".into(), code.to_string().into());
261    description.insert_str(0, &format!("**{code}**: "));
262    schema.insert("description".into(), description.into());
263    schema.insert("const".into(), i32::from(code).into());
264    schema.insert("type".into(), "integer".into());
265    schema.insert("format".into(), "int32".into());
266}
267
268impl From<ErrorCode> for Error {
269    fn from(error_code: ErrorCode) -> Self {
270        Error::new(error_code.into(), error_code.to_string())
271    }
272}
273
274impl std::error::Error for Error {}
275
276impl Display for Error {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        if self.message.is_empty() {
279            write!(f, "{}", i32::from(self.code))?;
280        } else {
281            write!(f, "{}", self.message)?;
282        }
283
284        if let Some(data) = &self.data {
285            let pretty = serde_json::to_string_pretty(data).unwrap_or_else(|_| data.to_string());
286            write!(f, ": {pretty}")?;
287        }
288
289        Ok(())
290    }
291}
292
293impl From<anyhow::Error> for Error {
294    fn from(error: anyhow::Error) -> Self {
295        match error.downcast::<Self>() {
296            Ok(error) => error,
297            Err(error) => Error::into_internal_error(&*error),
298        }
299    }
300}
301
302impl From<serde_json::Error> for Error {
303    fn from(error: serde_json::Error) -> Self {
304        Error::invalid_params().data(error.to_string())
305    }
306}
307
308#[cfg(test)]
309mod tests {
310    use strum::IntoEnumIterator;
311
312    use super::*;
313
314    #[test]
315    fn serialize_error_code() {
316        assert_eq!(
317            serde_json::from_value::<ErrorCode>(serde_json::json!(-32700)).unwrap(),
318            ErrorCode::ParseError
319        );
320        assert_eq!(
321            serde_json::to_value(ErrorCode::ParseError).unwrap(),
322            serde_json::json!(-32700)
323        );
324
325        assert_eq!(
326            serde_json::from_value::<ErrorCode>(serde_json::json!(1)).unwrap(),
327            ErrorCode::Other(1)
328        );
329        assert_eq!(
330            serde_json::to_value(ErrorCode::Other(1)).unwrap(),
331            serde_json::json!(1)
332        );
333    }
334
335    #[test]
336    fn serialize_error_code_equality() {
337        // Make sure this doesn't panic
338        let _schema = schemars::schema_for!(ErrorCode);
339        for error in ErrorCode::iter() {
340            assert_eq!(
341                error,
342                serde_json::from_value(serde_json::to_value(error).unwrap()).unwrap()
343            );
344        }
345    }
346}