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
154    // Custom errors
155    /// Authentication is required before this operation can be performed.
156    #[schemars(transform = error_code_transform)]
157    #[strum(to_string = "Authentication required")]
158    AuthRequired, // -32000
159    /// A given resource, such as a file, was not found.
160    #[schemars(transform = error_code_transform)]
161    #[strum(to_string = "Resource not found")]
162    ResourceNotFound, // -32002
163
164    /// Other undefined error code.
165    #[schemars(untagged)]
166    #[strum(to_string = "Unknown error")]
167    Other(i32),
168}
169
170impl From<i32> for ErrorCode {
171    fn from(value: i32) -> Self {
172        match value {
173            -32700 => ErrorCode::ParseError,
174            -32600 => ErrorCode::InvalidRequest,
175            -32601 => ErrorCode::MethodNotFound,
176            -32602 => ErrorCode::InvalidParams,
177            -32603 => ErrorCode::InternalError,
178            -32000 => ErrorCode::AuthRequired,
179            -32002 => ErrorCode::ResourceNotFound,
180            _ => ErrorCode::Other(value),
181        }
182    }
183}
184
185impl From<ErrorCode> for i32 {
186    fn from(value: ErrorCode) -> Self {
187        match value {
188            ErrorCode::ParseError => -32700,
189            ErrorCode::InvalidRequest => -32600,
190            ErrorCode::MethodNotFound => -32601,
191            ErrorCode::InvalidParams => -32602,
192            ErrorCode::InternalError => -32603,
193            ErrorCode::AuthRequired => -32000,
194            ErrorCode::ResourceNotFound => -32002,
195            ErrorCode::Other(value) => value,
196        }
197    }
198}
199
200impl std::fmt::Debug for ErrorCode {
201    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
202        write!(f, "{}: {self}", i32::from(*self))
203    }
204}
205
206fn error_code_transform(schema: &mut Schema) {
207    let name = schema
208        .get("const")
209        .expect("Unexpected schema for ErrorCode")
210        .as_str()
211        .expect("unexpected type for schema");
212    let code = match name {
213        "ParseError" => ErrorCode::ParseError,
214        "InvalidRequest" => ErrorCode::InvalidRequest,
215        "MethodNotFound" => ErrorCode::MethodNotFound,
216        "InvalidParams" => ErrorCode::InvalidParams,
217        "InternalError" => ErrorCode::InternalError,
218        "AuthRequired" => ErrorCode::AuthRequired,
219        "ResourceNotFound" => ErrorCode::ResourceNotFound,
220        _ => panic!("Unexpected error code name"),
221    };
222    let mut description = schema
223        .get("description")
224        .expect("Missing description")
225        .as_str()
226        .expect("Unexpected type for description")
227        .to_owned();
228    description.insert_str(0, &format!("**{code}**: "));
229    schema.insert("description".into(), description.into());
230    schema.insert("const".into(), i32::from(code).into());
231    schema.insert("type".into(), "integer".into());
232    schema.insert("format".into(), "int32".into());
233}
234
235impl From<ErrorCode> for Error {
236    fn from(error_code: ErrorCode) -> Self {
237        Error::new(error_code.into(), error_code.to_string())
238    }
239}
240
241impl std::error::Error for Error {}
242
243impl Display for Error {
244    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
245        if self.message.is_empty() {
246            write!(f, "{}", i32::from(self.code))?;
247        } else {
248            write!(f, "{}", self.message)?;
249        }
250
251        if let Some(data) = &self.data {
252            let pretty = serde_json::to_string_pretty(data).unwrap_or_else(|_| data.to_string());
253            write!(f, ": {pretty}")?;
254        }
255
256        Ok(())
257    }
258}
259
260impl From<anyhow::Error> for Error {
261    fn from(error: anyhow::Error) -> Self {
262        match error.downcast::<Self>() {
263            Ok(error) => error,
264            Err(error) => Error::into_internal_error(&*error),
265        }
266    }
267}
268
269impl From<serde_json::Error> for Error {
270    fn from(error: serde_json::Error) -> Self {
271        Error::invalid_params().data(error.to_string())
272    }
273}
274
275#[cfg(test)]
276mod tests {
277    use strum::IntoEnumIterator;
278
279    use super::*;
280
281    #[test]
282    fn serialize_error_code() {
283        assert_eq!(
284            serde_json::from_value::<ErrorCode>(serde_json::json!(-32700)).unwrap(),
285            ErrorCode::ParseError
286        );
287        assert_eq!(
288            serde_json::to_value(ErrorCode::ParseError).unwrap(),
289            serde_json::json!(-32700)
290        );
291
292        assert_eq!(
293            serde_json::from_value::<ErrorCode>(serde_json::json!(1)).unwrap(),
294            ErrorCode::Other(1)
295        );
296        assert_eq!(
297            serde_json::to_value(ErrorCode::Other(1)).unwrap(),
298            serde_json::json!(1)
299        );
300    }
301
302    #[test]
303    fn serialize_error_code_equality() {
304        for error in ErrorCode::iter() {
305            assert_eq!(
306                error,
307                serde_json::from_value(serde_json::to_value(error).unwrap()).unwrap()
308            );
309        }
310    }
311}