Skip to main content

adk_server/a2a/v1/
error.rs

1//! A2A v1.0.0 error types per spec §5.4.
2//!
3//! Defines [`A2aError`] with JSON-RPC error codes, HTTP status codes,
4//! `google.rpc.ErrorInfo` production, and AIP-193 HTTP error responses.
5
6use serde_json::{Map, Value, json};
7
8/// A2A v1.0.0 protocol errors.
9///
10/// Each variant maps to a specific JSON-RPC error code and HTTP status code
11/// as defined in the A2A Protocol v1.0.0 specification §5.4.
12#[derive(Debug, thiserror::Error)]
13pub enum A2aError {
14    /// Task not found in the task store.
15    /// JSON-RPC: -32001, HTTP: 404
16    #[error("Task not found: {task_id}")]
17    TaskNotFound { task_id: String },
18
19    /// Task cannot be canceled because it is in a terminal state.
20    /// JSON-RPC: -32002, HTTP: 409
21    #[error("Task not cancelable: {task_id} is in state {current_state}")]
22    TaskNotCancelable { task_id: String, current_state: String },
23
24    /// Agent does not support push notifications.
25    /// JSON-RPC: -32003, HTTP: 400
26    #[error("Push notifications not supported")]
27    PushNotificationNotSupported,
28
29    /// A valid method was called but the agent does not support it.
30    /// JSON-RPC: -32004, HTTP: 400
31    #[error("Unsupported operation: {method}")]
32    UnsupportedOperation { method: String },
33
34    /// A media type in the request is not supported.
35    /// JSON-RPC: -32005, HTTP: 415
36    #[error("Content type not supported: {media_type}")]
37    ContentTypeNotSupported { media_type: String },
38
39    /// The agent returned a non-conformant response.
40    /// JSON-RPC: -32006, HTTP: 502
41    #[error("Invalid agent response: {message}")]
42    InvalidAgentResponse { message: String },
43
44    /// Extended agent card is declared but not configured.
45    /// JSON-RPC: -32007, HTTP: 400
46    #[error("Extended agent card not configured")]
47    ExtendedAgentCardNotConfigured,
48
49    /// A required extension is not declared by the client.
50    /// JSON-RPC: -32008, HTTP: 400
51    #[error("Extension support required: {uri}")]
52    ExtensionSupportRequired { uri: String },
53
54    /// Requested protocol version is not supported.
55    /// JSON-RPC: -32009, HTTP: 400
56    #[error("Version not supported: {requested}")]
57    VersionNotSupported { requested: String, supported: Vec<String> },
58
59    /// Request parameters failed validation.
60    /// JSON-RPC: -32602, HTTP: 400
61    #[error("Invalid parameters: {message}")]
62    InvalidParams { message: String },
63
64    /// Unexpected server-side failure.
65    /// JSON-RPC: -32603, HTTP: 500
66    #[error("Internal error: {message}")]
67    Internal { message: String },
68
69    /// Requested JSON-RPC method is not recognized.
70    /// JSON-RPC: -32601, HTTP: 404
71    #[error("Method not found: {method}")]
72    MethodNotFound { method: String },
73
74    /// Attempted an invalid task state transition.
75    /// JSON-RPC: -32603, HTTP: 409
76    #[error("Invalid state transition from {from} to {to}")]
77    InvalidStateTransition { from: String, to: String },
78
79    /// Push notification webhook delivery failed after retries.
80    /// JSON-RPC: -32603, HTTP: 500
81    #[error("Push notification delivery failed: {message}")]
82    PushDeliveryFailed { message: String },
83
84    /// Another writer saved the task since it was read (its version moved on).
85    /// JSON-RPC: -32603, HTTP: 500
86    #[error("Task {task_id} was changed concurrently")]
87    ConcurrentModification { task_id: String },
88}
89
90impl A2aError {
91    /// Map to JSON-RPC error code per A2A v1.0.0 spec §5.4.
92    pub fn json_rpc_code(&self) -> i32 {
93        match self {
94            Self::TaskNotFound { .. } => -32001,
95            Self::TaskNotCancelable { .. } => -32002,
96            Self::PushNotificationNotSupported => -32003,
97            Self::UnsupportedOperation { .. } => -32004,
98            Self::ContentTypeNotSupported { .. } => -32005,
99            Self::InvalidAgentResponse { .. } => -32006,
100            Self::ExtendedAgentCardNotConfigured => -32007,
101            Self::ExtensionSupportRequired { .. } => -32008,
102            Self::VersionNotSupported { .. } => -32009,
103            Self::InvalidParams { .. } => -32602,
104            Self::Internal { .. }
105            | Self::InvalidStateTransition { .. }
106            | Self::PushDeliveryFailed { .. }
107            | Self::ConcurrentModification { .. } => -32603,
108            Self::MethodNotFound { .. } => -32601,
109        }
110    }
111
112    /// Map to HTTP status code per A2A v1.0.0 spec §5.4.
113    pub fn http_status(&self) -> u16 {
114        match self {
115            Self::TaskNotFound { .. } | Self::MethodNotFound { .. } => 404,
116            Self::TaskNotCancelable { .. } | Self::InvalidStateTransition { .. } => 409,
117            Self::ContentTypeNotSupported { .. } => 415,
118            Self::InvalidAgentResponse { .. } => 502,
119            Self::Internal { .. }
120            | Self::PushDeliveryFailed { .. }
121            | Self::ConcurrentModification { .. } => 500,
122            Self::PushNotificationNotSupported
123            | Self::UnsupportedOperation { .. }
124            | Self::ExtendedAgentCardNotConfigured
125            | Self::ExtensionSupportRequired { .. }
126            | Self::VersionNotSupported { .. }
127            | Self::InvalidParams { .. } => 400,
128        }
129    }
130
131    /// Produce `google.rpc.ErrorInfo` data per spec §9.5.
132    ///
133    /// Returns a JSON array containing a single `google.rpc.ErrorInfo` object
134    /// with `@type`, `reason` (UPPER_SNAKE_CASE, no "Error" suffix), `domain`,
135    /// and variant-specific `metadata`.
136    pub fn to_error_info(&self) -> Value {
137        json!([{
138            "@type": "type.googleapis.com/google.rpc.ErrorInfo",
139            "reason": self.reason_code(),
140            "domain": "a2a-protocol.org",
141            "metadata": self.error_metadata()
142        }])
143    }
144
145    /// Produce a JSON-RPC error object: `{ "code": ..., "message": ..., "data": <error_info> }`.
146    pub fn to_jsonrpc_error(&self) -> Value {
147        json!({
148            "code": self.json_rpc_code(),
149            "message": self.to_string(),
150            "data": self.to_error_info()
151        })
152    }
153
154    /// Produce an AIP-193 HTTP error response.
155    ///
156    /// ```json
157    /// {
158    ///   "error": {
159    ///     "code": 404,
160    ///     "status": "NOT_FOUND",
161    ///     "message": "Task not found: task_abc123",
162    ///     "details": [<error_info>]
163    ///   }
164    /// }
165    /// ```
166    pub fn to_http_error_response(&self) -> Value {
167        json!({
168            "error": {
169                "code": self.http_status(),
170                "status": self.http_status_string(),
171                "message": self.to_string(),
172                "details": self.to_error_info()
173            }
174        })
175    }
176
177    /// UPPER_SNAKE_CASE reason code without "Error" suffix.
178    fn reason_code(&self) -> &'static str {
179        match self {
180            Self::TaskNotFound { .. } => "TASK_NOT_FOUND",
181            Self::TaskNotCancelable { .. } => "TASK_NOT_CANCELABLE",
182            Self::PushNotificationNotSupported => "PUSH_NOTIFICATION_NOT_SUPPORTED",
183            Self::UnsupportedOperation { .. } => "UNSUPPORTED_OPERATION",
184            Self::ContentTypeNotSupported { .. } => "CONTENT_TYPE_NOT_SUPPORTED",
185            Self::InvalidAgentResponse { .. } => "INVALID_AGENT_RESPONSE",
186            Self::ExtendedAgentCardNotConfigured => "EXTENDED_AGENT_CARD_NOT_CONFIGURED",
187            Self::ExtensionSupportRequired { .. } => "EXTENSION_SUPPORT_REQUIRED",
188            Self::VersionNotSupported { .. } => "VERSION_NOT_SUPPORTED",
189            Self::InvalidParams { .. } => "INVALID_PARAMS",
190            Self::Internal { .. } => "INTERNAL_ERROR",
191            Self::MethodNotFound { .. } => "METHOD_NOT_FOUND",
192            Self::InvalidStateTransition { .. } => "INVALID_STATE_TRANSITION",
193            Self::PushDeliveryFailed { .. } => "PUSH_DELIVERY_FAILED",
194            Self::ConcurrentModification { .. } => "CONCURRENT_MODIFICATION",
195        }
196    }
197
198    /// Variant-specific metadata for the `google.rpc.ErrorInfo` object.
199    fn error_metadata(&self) -> Map<String, Value> {
200        let mut map = Map::new();
201        match self {
202            Self::TaskNotFound { task_id } => {
203                map.insert("task_id".to_string(), Value::String(task_id.clone()));
204                map.insert("taskId".to_string(), Value::String(task_id.clone()));
205            }
206            Self::TaskNotCancelable { task_id, current_state } => {
207                map.insert("task_id".to_string(), Value::String(task_id.clone()));
208                map.insert("taskId".to_string(), Value::String(task_id.clone()));
209                map.insert("current_state".to_string(), Value::String(current_state.clone()));
210            }
211            Self::UnsupportedOperation { method } => {
212                map.insert("method".to_string(), Value::String(method.clone()));
213            }
214            Self::ContentTypeNotSupported { media_type } => {
215                map.insert("media_type".to_string(), Value::String(media_type.clone()));
216            }
217            Self::InvalidAgentResponse { message } => {
218                map.insert("message".to_string(), Value::String(message.clone()));
219            }
220            Self::ExtensionSupportRequired { uri } => {
221                map.insert("uri".to_string(), Value::String(uri.clone()));
222            }
223            Self::VersionNotSupported { requested, supported } => {
224                map.insert("requested".to_string(), Value::String(requested.clone()));
225                map.insert("supported".to_string(), Value::String(supported.join(", ")));
226            }
227            Self::InvalidParams { message } => {
228                map.insert("message".to_string(), Value::String(message.clone()));
229            }
230            Self::Internal { message } => {
231                map.insert("message".to_string(), Value::String(message.clone()));
232            }
233            Self::MethodNotFound { method } => {
234                map.insert("method".to_string(), Value::String(method.clone()));
235            }
236            Self::InvalidStateTransition { from, to } => {
237                map.insert("from".to_string(), Value::String(from.clone()));
238                map.insert("to".to_string(), Value::String(to.clone()));
239            }
240            Self::ConcurrentModification { task_id } => {
241                map.insert("task_id".to_string(), Value::String(task_id.clone()));
242                map.insert("taskId".to_string(), Value::String(task_id.clone()));
243            }
244            Self::PushDeliveryFailed { message } => {
245                map.insert("message".to_string(), Value::String(message.clone()));
246            }
247            Self::PushNotificationNotSupported | Self::ExtendedAgentCardNotConfigured => {
248                // No variant-specific metadata
249            }
250        }
251        // When the error happened, as a2a-go stamps every ErrorInfo.
252        map.insert(
253            "timestamp".to_string(),
254            Value::String(chrono::Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Secs, true)),
255        );
256        map
257    }
258
259    /// Map HTTP status code to a canonical status string for AIP-193 responses.
260    /// The AIP-193 `status`: the `google.rpc.Code` name of the error, as a2a-go names it.
261    fn http_status_string(&self) -> &'static str {
262        match self {
263            Self::TaskNotFound { .. } | Self::MethodNotFound { .. } => "NOT_FOUND",
264            Self::InvalidParams { .. } | Self::ContentTypeNotSupported { .. } => "INVALID_ARGUMENT",
265            Self::TaskNotCancelable { .. }
266            | Self::InvalidStateTransition { .. }
267            | Self::PushNotificationNotSupported
268            | Self::UnsupportedOperation { .. }
269            | Self::ExtendedAgentCardNotConfigured
270            | Self::ExtensionSupportRequired { .. }
271            | Self::VersionNotSupported { .. } => "FAILED_PRECONDITION",
272            Self::Internal { .. }
273            | Self::PushDeliveryFailed { .. }
274            | Self::ConcurrentModification { .. }
275            | Self::InvalidAgentResponse { .. } => "INTERNAL",
276        }
277    }
278}
279
280#[cfg(test)]
281mod tests {
282    use super::*;
283
284    #[test]
285    fn test_task_not_found_json_rpc_code() {
286        let err = A2aError::TaskNotFound { task_id: "task_123".to_string() };
287        assert_eq!(err.json_rpc_code(), -32001);
288        assert_eq!(err.http_status(), 404);
289    }
290
291    #[test]
292    fn test_task_not_found_error_info() {
293        let err = A2aError::TaskNotFound { task_id: "task_abc".to_string() };
294        let info = err.to_error_info();
295        let arr = info.as_array().expect("should be array");
296        assert_eq!(arr.len(), 1);
297        let obj = &arr[0];
298        assert_eq!(obj["@type"], "type.googleapis.com/google.rpc.ErrorInfo");
299        assert_eq!(obj["reason"], "TASK_NOT_FOUND");
300        assert_eq!(obj["domain"], "a2a-protocol.org");
301        assert_eq!(obj["metadata"]["task_id"], "task_abc");
302    }
303
304    #[test]
305    fn test_version_not_supported_metadata() {
306        let err = A2aError::VersionNotSupported {
307            requested: "2.0".to_string(),
308            supported: vec!["0.3".to_string(), "1.0".to_string()],
309        };
310        assert_eq!(err.json_rpc_code(), -32009);
311        assert_eq!(err.http_status(), 400);
312        let info = err.to_error_info();
313        let meta = &info[0]["metadata"];
314        assert_eq!(meta["requested"], "2.0");
315        assert_eq!(meta["supported"], "0.3, 1.0");
316    }
317
318    #[test]
319    fn test_jsonrpc_error_structure() {
320        let err = A2aError::MethodNotFound { method: "UnknownMethod".to_string() };
321        let rpc_err = err.to_jsonrpc_error();
322        assert_eq!(rpc_err["code"], -32601);
323        assert!(rpc_err["message"].as_str().unwrap().contains("UnknownMethod"));
324        assert!(rpc_err["data"].is_array());
325    }
326
327    #[test]
328    fn test_http_error_response_structure() {
329        let err = A2aError::TaskNotFound { task_id: "task_abc123".to_string() };
330        let resp = err.to_http_error_response();
331        let error_obj = &resp["error"];
332        assert_eq!(error_obj["code"], 404);
333        assert_eq!(error_obj["status"], "NOT_FOUND");
334        assert!(error_obj["message"].as_str().unwrap().contains("task_abc123"));
335        assert!(error_obj["details"].is_array());
336        assert_eq!(error_obj["details"][0]["reason"], "TASK_NOT_FOUND");
337    }
338
339    #[test]
340    fn test_invalid_state_transition() {
341        let err = A2aError::InvalidStateTransition {
342            from: "COMPLETED".to_string(),
343            to: "WORKING".to_string(),
344        };
345        assert_eq!(err.json_rpc_code(), -32603);
346        assert_eq!(err.http_status(), 409);
347        let info = err.to_error_info();
348        assert_eq!(info[0]["metadata"]["from"], "COMPLETED");
349        assert_eq!(info[0]["metadata"]["to"], "WORKING");
350    }
351
352    #[test]
353    fn test_push_notification_not_supported() {
354        let err = A2aError::PushNotificationNotSupported;
355        assert_eq!(err.json_rpc_code(), -32003);
356        assert_eq!(err.http_status(), 400);
357        let info = err.to_error_info();
358        assert_eq!(info[0]["reason"], "PUSH_NOTIFICATION_NOT_SUPPORTED");
359        let metadata = info[0]["metadata"].as_object().unwrap();
360        assert_eq!(metadata.keys().collect::<Vec<_>>(), ["timestamp"], "only when it happened");
361    }
362
363    #[test]
364    fn test_content_type_not_supported() {
365        let err = A2aError::ContentTypeNotSupported { media_type: "text/xml".to_string() };
366        assert_eq!(err.json_rpc_code(), -32005);
367        assert_eq!(err.http_status(), 415);
368        assert_eq!(err.to_error_info()[0]["metadata"]["media_type"], "text/xml");
369    }
370
371    #[test]
372    fn test_invalid_agent_response() {
373        let err = A2aError::InvalidAgentResponse { message: "missing required field".to_string() };
374        assert_eq!(err.json_rpc_code(), -32006);
375        assert_eq!(err.http_status(), 502);
376    }
377
378    #[test]
379    fn test_extended_agent_card_not_configured() {
380        let err = A2aError::ExtendedAgentCardNotConfigured;
381        assert_eq!(err.json_rpc_code(), -32007);
382        assert_eq!(err.http_status(), 400);
383        assert_eq!(err.to_error_info()[0]["reason"], "EXTENDED_AGENT_CARD_NOT_CONFIGURED");
384    }
385
386    #[test]
387    fn test_all_variants_have_valid_codes() {
388        let variants: Vec<A2aError> = vec![
389            A2aError::TaskNotFound { task_id: "t".into() },
390            A2aError::TaskNotCancelable { task_id: "t".into(), current_state: "s".into() },
391            A2aError::PushNotificationNotSupported,
392            A2aError::UnsupportedOperation { method: "m".into() },
393            A2aError::ContentTypeNotSupported { media_type: "x".into() },
394            A2aError::InvalidAgentResponse { message: "m".into() },
395            A2aError::ExtendedAgentCardNotConfigured,
396            A2aError::ExtensionSupportRequired { uri: "u".into() },
397            A2aError::VersionNotSupported { requested: "v".into(), supported: vec![] },
398            A2aError::InvalidParams { message: "m".into() },
399            A2aError::Internal { message: "m".into() },
400            A2aError::MethodNotFound { method: "m".into() },
401            A2aError::InvalidStateTransition { from: "a".into(), to: "b".into() },
402            A2aError::PushDeliveryFailed { message: "m".into() },
403            A2aError::ConcurrentModification { task_id: "t".into() },
404        ];
405
406        for err in &variants {
407            // JSON-RPC codes are negative
408            assert!(err.json_rpc_code() < 0, "code should be negative for {err}");
409            // HTTP status codes are in valid range
410            let status = err.http_status();
411            assert!((400..=599).contains(&status), "status {status} out of range for {err}");
412            // error_info is a non-empty array
413            let info = err.to_error_info();
414            assert!(info.is_array());
415            assert_eq!(info.as_array().unwrap().len(), 1);
416            // reason is non-empty UPPER_SNAKE_CASE
417            let reason = info[0]["reason"].as_str().unwrap();
418            assert!(!reason.is_empty());
419            assert!(
420                reason.chars().all(|c| c.is_ascii_uppercase() || c == '_'),
421                "reason {reason} is not UPPER_SNAKE_CASE"
422            );
423            // domain is correct
424            assert_eq!(info[0]["domain"], "a2a-protocol.org");
425            // jsonrpc error has required fields
426            let rpc = err.to_jsonrpc_error();
427            assert!(rpc["code"].is_i64());
428            assert!(rpc["message"].is_string());
429            assert!(rpc["data"].is_array());
430            // http error response has required fields
431            let http = err.to_http_error_response();
432            assert!(http["error"]["code"].is_u64());
433            assert!(http["error"]["status"].is_string());
434            assert!(http["error"]["message"].is_string());
435            assert!(http["error"]["details"].is_array());
436        }
437    }
438}