agent_client_protocol/
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, ops::Deref as _};
14
15use schemars::JsonSchema;
16use serde::{Deserialize, Serialize};
17
18/// JSON-RPC error object.
19///
20/// Represents an error that occurred during method execution, following the
21/// JSON-RPC 2.0 error object specification with optional additional data.
22///
23/// See protocol docs: [JSON-RPC Error Object](https://www.jsonrpc.org/specification#error_object)
24#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
25pub struct Error {
26    /// A number indicating the error type that occurred.
27    /// This must be an integer as defined in the JSON-RPC specification.
28    pub code: i32,
29    /// A string providing a short description of the error.
30    /// The message should be limited to a concise single sentence.
31    pub message: String,
32    /// Optional primitive or structured value that contains additional information about the error.
33    /// This may include debugging information or context-specific details.
34    #[serde(skip_serializing_if = "Option::is_none")]
35    pub data: Option<serde_json::Value>,
36}
37
38impl Error {
39    /// Creates a new error with the given code and message.
40    ///
41    /// The code parameter can be an `ErrorCode` constant or a tuple of (code, message).
42    pub fn new(code: impl Into<(i32, String)>) -> Self {
43        let (code, message) = code.into();
44        Error {
45            code,
46            message,
47            data: None,
48        }
49    }
50
51    /// Adds additional data to the error.
52    ///
53    /// This method is chainable and allows attaching context-specific information
54    /// to help with debugging or provide more details about the error.
55    pub fn with_data(mut self, data: impl Into<serde_json::Value>) -> Self {
56        self.data = Some(data.into());
57        self
58    }
59
60    /// Invalid JSON was received by the server. An error occurred on the server while parsing the JSON text.
61    pub fn parse_error() -> Self {
62        Error::new(ErrorCode::PARSE_ERROR)
63    }
64
65    /// The JSON sent is not a valid Request object.
66    pub fn invalid_request() -> Self {
67        Error::new(ErrorCode::INVALID_REQUEST)
68    }
69
70    /// The method does not exist / is not available.
71    pub fn method_not_found() -> Self {
72        Error::new(ErrorCode::METHOD_NOT_FOUND)
73    }
74
75    /// Invalid method parameter(s).
76    pub fn invalid_params() -> Self {
77        Error::new(ErrorCode::INVALID_PARAMS)
78    }
79
80    /// Internal JSON-RPC error.
81    pub fn internal_error() -> Self {
82        Error::new(ErrorCode::INTERNAL_ERROR)
83    }
84
85    /// Authentication required.
86    pub fn auth_required() -> Self {
87        Error::new(ErrorCode::AUTH_REQUIRED)
88    }
89
90    /// Converts a standard error into an internal JSON-RPC error.
91    ///
92    /// The error's string representation is included as additional data.
93    pub fn into_internal_error(err: impl std::error::Error) -> Self {
94        Error::internal_error().with_data(err.to_string())
95    }
96}
97
98/// Predefined error codes for common JSON-RPC and ACP-specific errors.
99///
100/// These codes follow the JSON-RPC 2.0 specification for standard errors
101/// and use the reserved range (-32000 to -32099) for protocol-specific errors.
102#[derive(Debug, Clone, Serialize, Deserialize, JsonSchema)]
103pub struct ErrorCode {
104    /// The numeric error code.
105    pub code: i32,
106    /// The standard error message for this code.
107    pub message: &'static str,
108}
109
110impl ErrorCode {
111    /// Invalid JSON was received by the server.
112    /// An error occurred on the server while parsing the JSON text.
113    pub const PARSE_ERROR: ErrorCode = ErrorCode {
114        code: -32700,
115        message: "Parse error",
116    };
117
118    /// The JSON sent is not a valid Request object.
119    pub const INVALID_REQUEST: ErrorCode = ErrorCode {
120        code: -32600,
121        message: "Invalid Request",
122    };
123
124    /// The method does not exist or is not available.
125    pub const METHOD_NOT_FOUND: ErrorCode = ErrorCode {
126        code: -32601,
127        message: "Method not found",
128    };
129
130    /// Invalid method parameter(s).
131    pub const INVALID_PARAMS: ErrorCode = ErrorCode {
132        code: -32602,
133        message: "Invalid params",
134    };
135
136    /// Internal JSON-RPC error.
137    /// Reserved for implementation-defined server errors.
138    pub const INTERNAL_ERROR: ErrorCode = ErrorCode {
139        code: -32603,
140        message: "Internal error",
141    };
142
143    /// Authentication is required before this operation can be performed.
144    /// This is an ACP-specific error code in the reserved range.
145    pub const AUTH_REQUIRED: ErrorCode = ErrorCode {
146        code: -32000,
147        message: "Authentication required",
148    };
149}
150
151impl From<ErrorCode> for (i32, String) {
152    fn from(error_code: ErrorCode) -> Self {
153        (error_code.code, error_code.message.to_string())
154    }
155}
156
157impl From<ErrorCode> for Error {
158    fn from(error_code: ErrorCode) -> Self {
159        Error::new(error_code)
160    }
161}
162
163impl std::error::Error for Error {}
164
165impl Display for Error {
166    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
167        if self.message.is_empty() {
168            write!(f, "{}", self.code)?;
169        } else {
170            write!(f, "{}", self.message)?;
171        }
172
173        if let Some(data) = &self.data {
174            let pretty = serde_json::to_string_pretty(data).unwrap_or_else(|_| data.to_string());
175            write!(f, ": {pretty}")?;
176        }
177
178        Ok(())
179    }
180}
181
182impl From<anyhow::Error> for Error {
183    fn from(error: anyhow::Error) -> Self {
184        Error::into_internal_error(error.deref())
185    }
186}
187
188impl From<serde_json::Error> for Error {
189    fn from(error: serde_json::Error) -> Self {
190        Error::invalid_params().with_data(error.to_string())
191    }
192}