1use std::collections::HashMap;
5
6use chrono::Utc;
7use serde_json::Value;
8
9use crate::errordetails::{self, TypedDetail};
10use crate::timestamp::format_timestamp;
11
12pub mod error_code {
14 pub const TASK_NOT_FOUND: i32 = -32001;
16 pub const TASK_NOT_CANCELABLE: i32 = -32002;
17 pub const PUSH_NOTIFICATION_NOT_SUPPORTED: i32 = -32003;
18 pub const UNSUPPORTED_OPERATION: i32 = -32004;
19 pub const CONTENT_TYPE_NOT_SUPPORTED: i32 = -32005;
20 pub const INVALID_AGENT_RESPONSE: i32 = -32006;
21 pub const EXTENDED_CARD_NOT_CONFIGURED: i32 = -32007;
22 pub const EXTENSION_SUPPORT_REQUIRED: i32 = -32008;
23 pub const VERSION_NOT_SUPPORTED: i32 = -32009;
24
25 pub const PARSE_ERROR: i32 = -32700;
27 pub const INVALID_REQUEST: i32 = -32600;
28 pub const METHOD_NOT_FOUND: i32 = -32601;
29 pub const INVALID_PARAMS: i32 = -32602;
30 pub const INTERNAL_ERROR: i32 = -32603;
31}
32
33pub fn error_reason(code: i32) -> &'static str {
35 match code {
36 error_code::TASK_NOT_FOUND => "TASK_NOT_FOUND",
37 error_code::TASK_NOT_CANCELABLE => "TASK_NOT_CANCELABLE",
38 error_code::PUSH_NOTIFICATION_NOT_SUPPORTED => "PUSH_NOTIFICATION_NOT_SUPPORTED",
39 error_code::UNSUPPORTED_OPERATION => "UNSUPPORTED_OPERATION",
40 error_code::CONTENT_TYPE_NOT_SUPPORTED => "CONTENT_TYPE_NOT_SUPPORTED",
41 error_code::INVALID_AGENT_RESPONSE => "INVALID_AGENT_RESPONSE",
42 error_code::EXTENDED_CARD_NOT_CONFIGURED => "EXTENDED_AGENT_CARD_NOT_CONFIGURED",
43 error_code::EXTENSION_SUPPORT_REQUIRED => "EXTENSION_SUPPORT_REQUIRED",
44 error_code::VERSION_NOT_SUPPORTED => "VERSION_NOT_SUPPORTED",
45 error_code::PARSE_ERROR => "PARSE_ERROR",
46 error_code::INVALID_REQUEST => "INVALID_REQUEST",
47 error_code::METHOD_NOT_FOUND => "METHOD_NOT_FOUND",
48 error_code::INVALID_PARAMS => "INVALID_PARAMS",
49 _ => "INTERNAL_ERROR",
50 }
51}
52
53pub fn reason_to_error_code(reason: &str) -> Option<i32> {
55 match reason {
56 "TASK_NOT_FOUND" => Some(error_code::TASK_NOT_FOUND),
57 "TASK_NOT_CANCELABLE" => Some(error_code::TASK_NOT_CANCELABLE),
58 "PUSH_NOTIFICATION_NOT_SUPPORTED" => Some(error_code::PUSH_NOTIFICATION_NOT_SUPPORTED),
59 "UNSUPPORTED_OPERATION" => Some(error_code::UNSUPPORTED_OPERATION),
60 "UNSUPPORTED_CONTENT_TYPE" | "CONTENT_TYPE_NOT_SUPPORTED" => {
61 Some(error_code::CONTENT_TYPE_NOT_SUPPORTED)
62 }
63 "INVALID_AGENT_RESPONSE" => Some(error_code::INVALID_AGENT_RESPONSE),
64 "EXTENDED_AGENT_CARD_NOT_CONFIGURED" | "EXTENDED_CARD_NOT_CONFIGURED" => {
65 Some(error_code::EXTENDED_CARD_NOT_CONFIGURED)
66 }
67 "EXTENSION_SUPPORT_REQUIRED" => Some(error_code::EXTENSION_SUPPORT_REQUIRED),
68 "VERSION_NOT_SUPPORTED" => Some(error_code::VERSION_NOT_SUPPORTED),
69 "PARSE_ERROR" => Some(error_code::PARSE_ERROR),
70 "INVALID_REQUEST" => Some(error_code::INVALID_REQUEST),
71 "METHOD_NOT_FOUND" => Some(error_code::METHOD_NOT_FOUND),
72 "INVALID_PARAMS" => Some(error_code::INVALID_PARAMS),
73 "INTERNAL_ERROR" => Some(error_code::INTERNAL_ERROR),
74 _ => None,
75 }
76}
77
78pub fn protocol_error_code(details: &[TypedDetail]) -> Option<i32> {
80 details
81 .iter()
82 .filter(|detail| {
83 detail.type_url == errordetails::ERROR_INFO_TYPE
84 && detail.value.get("domain").and_then(Value::as_str)
85 == Some(errordetails::PROTOCOL_DOMAIN)
86 })
87 .filter_map(|detail| reason_to_error_code(detail.value.get("reason")?.as_str()?))
88 .next_back()
89}
90
91pub fn a2a_error_from_details(code: i32, message: String, details: Vec<TypedDetail>) -> A2AError {
97 let mut message = message;
98 let mut has_bad_request = false;
99
100 for detail in details
101 .iter()
102 .filter(|detail| detail.type_url == errordetails::BAD_REQUEST_TYPE)
103 {
104 has_bad_request = true;
105 if let Some(Value::Array(violations)) = detail.value.get("fieldViolations") {
106 let violation_strs: Vec<String> = violations
107 .iter()
108 .filter_map(|v| {
109 let field = v.get("field")?.as_str()?;
110 let desc = v.get("description")?.as_str()?;
111 if field.is_empty() {
112 Some(desc.to_string())
113 } else {
114 Some(format!("{field}: {desc}"))
115 }
116 })
117 .collect();
118 if !violation_strs.is_empty() {
119 message = format!("{}: {}", message, violation_strs.join("; "));
120 }
121 }
122 }
123
124 let code = protocol_error_code(&details).unwrap_or(
125 if has_bad_request && code == error_code::INTERNAL_ERROR {
126 error_code::INVALID_PARAMS
127 } else {
128 code
129 },
130 );
131
132 A2AError {
133 code,
134 message,
135 details: (!details.is_empty()).then_some(details),
136 }
137}
138
139#[derive(Debug, Clone, thiserror::Error)]
141#[error("{message}")]
142pub struct A2AError {
143 pub code: i32,
144 pub message: String,
145 pub details: Option<Vec<TypedDetail>>,
146}
147
148impl A2AError {
149 pub fn new(code: i32, message: impl Into<String>) -> Self {
150 A2AError {
151 code,
152 message: message.into(),
153 details: None,
154 }
155 }
156
157 pub fn with_details(mut self, details: Vec<TypedDetail>) -> Self {
158 self.details = Some(details);
159 self
160 }
161
162 pub fn task_not_found(task_id: &str) -> Self {
165 A2AError::new(
166 error_code::TASK_NOT_FOUND,
167 format!("task not found: {task_id}"),
168 )
169 }
170
171 pub fn task_not_cancelable(task_id: &str) -> Self {
172 A2AError::new(
173 error_code::TASK_NOT_CANCELABLE,
174 format!("task cannot be canceled: {task_id}"),
175 )
176 }
177
178 pub fn push_notification_not_supported() -> Self {
179 A2AError::new(
180 error_code::PUSH_NOTIFICATION_NOT_SUPPORTED,
181 "push notification not supported",
182 )
183 }
184
185 pub fn unsupported_operation(msg: impl Into<String>) -> Self {
186 A2AError::new(error_code::UNSUPPORTED_OPERATION, msg)
187 }
188
189 pub fn extended_card_not_configured() -> Self {
194 A2AError::new(
195 error_code::EXTENDED_CARD_NOT_CONFIGURED,
196 "extended agent card not configured",
197 )
198 }
199
200 pub fn content_type_not_supported() -> Self {
201 A2AError::new(
202 error_code::CONTENT_TYPE_NOT_SUPPORTED,
203 "incompatible content types",
204 )
205 }
206
207 pub fn invalid_agent_response() -> Self {
208 A2AError::new(error_code::INVALID_AGENT_RESPONSE, "invalid agent response")
209 }
210
211 pub fn extension_support_required(uri: &str) -> Self {
214 A2AError::new(
215 error_code::EXTENSION_SUPPORT_REQUIRED,
216 format!("extension support required: {uri}"),
217 )
218 }
219
220 pub fn version_not_supported(version: &str) -> Self {
221 A2AError::new(
222 error_code::VERSION_NOT_SUPPORTED,
223 format!("version not supported: {version}"),
224 )
225 }
226
227 pub fn internal(msg: impl Into<String>) -> Self {
228 A2AError::new(error_code::INTERNAL_ERROR, msg)
229 }
230
231 pub fn invalid_params(msg: impl Into<String>) -> Self {
232 A2AError::new(error_code::INVALID_PARAMS, msg)
233 }
234
235 pub fn parse_error(msg: impl Into<String>) -> Self {
236 A2AError::new(error_code::PARSE_ERROR, msg)
237 }
238
239 pub fn invalid_request(msg: impl Into<String>) -> Self {
240 A2AError::new(error_code::INVALID_REQUEST, msg)
241 }
242
243 pub fn method_not_found(method: &str) -> Self {
244 A2AError::new(
245 error_code::METHOD_NOT_FOUND,
246 format!("method not found: {method}"),
247 )
248 }
249
250 pub fn http_status_code(&self) -> u16 {
252 match self.code {
253 error_code::TASK_NOT_FOUND => 404,
254 error_code::TASK_NOT_CANCELABLE => 400,
255 error_code::PUSH_NOTIFICATION_NOT_SUPPORTED => 400,
256 error_code::UNSUPPORTED_OPERATION => 400,
257 error_code::CONTENT_TYPE_NOT_SUPPORTED => 400,
258 error_code::VERSION_NOT_SUPPORTED => 400,
259 error_code::EXTENDED_CARD_NOT_CONFIGURED => 400,
264 error_code::EXTENSION_SUPPORT_REQUIRED => 400,
265 error_code::PARSE_ERROR => 400,
266 error_code::INVALID_REQUEST => 400,
267 error_code::METHOD_NOT_FOUND => 501,
268 error_code::INVALID_PARAMS => 400,
269 error_code::INTERNAL_ERROR => 500,
270 _ => 500,
271 }
272 }
273
274 pub fn to_jsonrpc_error(&self) -> crate::JsonRpcError {
280 let reason = error_reason(self.code);
281 let metadata = HashMap::from([("timestamp".to_string(), format_timestamp(&Utc::now()))]);
282
283 let mut data: Vec<Value> = self
284 .details
285 .as_ref()
286 .map(|d| {
287 d.iter()
288 .filter(|detail| detail.type_url != errordetails::ERROR_INFO_TYPE)
289 .map(|detail| serde_json::to_value(detail).unwrap_or_default())
290 .collect()
291 })
292 .unwrap_or_default();
293
294 let mut error_info =
295 TypedDetail::error_info(reason, errordetails::PROTOCOL_DOMAIN, Some(metadata));
296
297 if let Some(details) = &self.details {
298 for existing in details
299 .iter()
300 .filter(|d| d.type_url == errordetails::ERROR_INFO_TYPE)
301 {
302 if let Some(Value::Object(meta)) = existing.value.get("metadata") {
303 if let Some(Value::Object(info_meta)) = error_info.value.get_mut("metadata") {
304 for (k, v) in meta {
305 info_meta.entry(k.clone()).or_insert_with(|| v.clone());
306 }
307 }
308 }
309 }
310 }
311
312 data.push(serde_json::to_value(&error_info).unwrap_or_default());
313
314 crate::JsonRpcError {
315 code: self.code,
316 message: self.message.clone(),
317 data: Some(Value::Array(data)),
318 }
319 }
320}
321
322impl From<A2AError> for crate::JsonRpcError {
323 fn from(e: A2AError) -> Self {
324 e.to_jsonrpc_error()
325 }
326}
327
328#[cfg(test)]
329mod tests {
330 use super::*;
331
332 #[test]
333 fn test_error_constructors() {
334 let e = A2AError::task_not_found("t1");
335 assert_eq!(e.code, error_code::TASK_NOT_FOUND);
336 assert!(e.message.contains("t1"));
337
338 let e = A2AError::task_not_cancelable("t2");
339 assert_eq!(e.code, error_code::TASK_NOT_CANCELABLE);
340
341 let e = A2AError::push_notification_not_supported();
342 assert_eq!(e.code, error_code::PUSH_NOTIFICATION_NOT_SUPPORTED);
343
344 let e = A2AError::unsupported_operation("nope");
345 assert_eq!(e.code, error_code::UNSUPPORTED_OPERATION);
346
347 let e = A2AError::content_type_not_supported();
348 assert_eq!(e.code, error_code::CONTENT_TYPE_NOT_SUPPORTED);
349
350 let e = A2AError::invalid_agent_response();
351 assert_eq!(e.code, error_code::INVALID_AGENT_RESPONSE);
352
353 let e = A2AError::version_not_supported("2.0");
354 assert_eq!(e.code, error_code::VERSION_NOT_SUPPORTED);
355
356 let e = A2AError::internal("boom");
357 assert_eq!(e.code, error_code::INTERNAL_ERROR);
358
359 let e = A2AError::invalid_params("bad param");
360 assert_eq!(e.code, error_code::INVALID_PARAMS);
361
362 let e = A2AError::parse_error("bad json");
363 assert_eq!(e.code, error_code::PARSE_ERROR);
364
365 let e = A2AError::invalid_request("bad req");
366 assert_eq!(e.code, error_code::INVALID_REQUEST);
367
368 let e = A2AError::method_not_found("foo");
369 assert_eq!(e.code, error_code::METHOD_NOT_FOUND);
370 }
371
372 #[test]
373 fn test_http_status_codes() {
374 assert_eq!(A2AError::task_not_found("x").http_status_code(), 404);
375 assert_eq!(A2AError::task_not_cancelable("x").http_status_code(), 400);
376 assert_eq!(A2AError::internal("x").http_status_code(), 500);
377 assert_eq!(A2AError::invalid_params("x").http_status_code(), 400);
378 assert_eq!(
379 A2AError::content_type_not_supported().http_status_code(),
380 400
381 );
382 assert_eq!(A2AError::new(9999, "unknown").http_status_code(), 500);
383 }
384
385 #[test]
386 fn test_http_status_codes_for_remaining_a2a_mappings() {
387 assert_eq!(
388 A2AError::push_notification_not_supported().http_status_code(),
389 400
390 );
391 assert_eq!(
392 A2AError::unsupported_operation("nope").http_status_code(),
393 400
394 );
395 assert_eq!(
396 A2AError::version_not_supported("9.9").http_status_code(),
397 400
398 );
399 assert_eq!(A2AError::parse_error("bad").http_status_code(), 400);
400 assert_eq!(A2AError::invalid_request("bad").http_status_code(), 400);
401 assert_eq!(
402 A2AError::method_not_found("missing").http_status_code(),
403 501
404 );
405 }
406
407 #[test]
412 fn test_precondition_codes_are_client_errors_not_server_faults() {
413 assert_eq!(
414 A2AError::extended_card_not_configured().http_status_code(),
415 400
416 );
417 assert_eq!(
418 A2AError::new(error_code::EXTENSION_SUPPORT_REQUIRED, "needs ext").http_status_code(),
419 400
420 );
421 }
422
423 #[test]
424 fn test_extended_card_not_configured_carries_its_own_code() {
425 let error = A2AError::extended_card_not_configured();
426 assert_eq!(error.code, error_code::EXTENDED_CARD_NOT_CONFIGURED);
427 assert_ne!(error.code, error_code::UNSUPPORTED_OPERATION);
428 assert_eq!(
429 error_reason(error.code),
430 "EXTENDED_AGENT_CARD_NOT_CONFIGURED"
431 );
432 }
433
434 #[test]
435 fn test_to_jsonrpc_error() {
436 let e = A2AError::task_not_found("t1");
437 let rpc = e.to_jsonrpc_error();
438 assert_eq!(rpc.code, error_code::TASK_NOT_FOUND);
439 assert!(rpc.message.contains("t1"));
440 let data = rpc.data.expect("data should always be present");
441 let arr = data.as_array().expect("data should be an array");
442 assert_eq!(arr.len(), 1);
443 assert_eq!(arr[0]["@type"], errordetails::ERROR_INFO_TYPE);
444 assert_eq!(arr[0]["reason"], "TASK_NOT_FOUND");
445 assert_eq!(arr[0]["domain"], errordetails::PROTOCOL_DOMAIN);
446 assert!(arr[0]["metadata"]["timestamp"].is_string());
447 }
448
449 #[test]
452 fn test_error_info_timestamp_uses_the_z_designator() {
453 let rpc = A2AError::task_not_found("t1").to_jsonrpc_error();
454 let data = rpc.data.unwrap();
455 let timestamp = data[0]["metadata"]["timestamp"].as_str().unwrap();
456 assert!(timestamp.ends_with('Z'), "{timestamp}");
457 assert!(timestamp.parse::<chrono::DateTime<Utc>>().is_ok());
458 }
459
460 #[test]
461 fn test_with_details() {
462 use std::collections::HashMap;
463 let struct_detail = TypedDetail::from_struct(HashMap::from([(
464 "key".to_string(),
465 Value::String("val".to_string()),
466 )]));
467 let e = A2AError::internal("err").with_details(vec![struct_detail]);
468
469 let rpc = e.to_jsonrpc_error();
470 let data = rpc.data.expect("data should always be present");
471 let arr = data.as_array().unwrap();
472 assert_eq!(arr.len(), 2);
473 assert_eq!(arr[0]["key"], "val");
474 assert_eq!(arr[1]["@type"], errordetails::ERROR_INFO_TYPE);
475 assert_eq!(arr[1]["reason"], "INTERNAL_ERROR");
476 }
477
478 #[test]
479 fn test_to_jsonrpc_error_merges_existing_error_info_metadata() {
480 let existing_info = TypedDetail::error_info(
481 "TASK_NOT_FOUND",
482 errordetails::PROTOCOL_DOMAIN,
483 Some(HashMap::from([("taskId".to_string(), "t1".to_string())])),
484 );
485 let e = A2AError::task_not_found("t1").with_details(vec![existing_info]);
486 let rpc = e.to_jsonrpc_error();
487 let data = rpc.data.unwrap();
488 let arr = data.as_array().unwrap();
489 assert_eq!(arr.len(), 1);
491 assert_eq!(arr[0]["@type"], errordetails::ERROR_INFO_TYPE);
492 assert_eq!(arr[0]["metadata"]["taskId"], "t1");
493 assert!(arr[0]["metadata"]["timestamp"].is_string());
494 }
495
496 #[test]
497 fn test_reason_to_error_code() {
498 assert_eq!(
499 reason_to_error_code("TASK_NOT_FOUND"),
500 Some(error_code::TASK_NOT_FOUND)
501 );
502 assert_eq!(
503 reason_to_error_code("TASK_NOT_CANCELABLE"),
504 Some(error_code::TASK_NOT_CANCELABLE)
505 );
506 assert_eq!(
507 reason_to_error_code("PUSH_NOTIFICATION_NOT_SUPPORTED"),
508 Some(error_code::PUSH_NOTIFICATION_NOT_SUPPORTED)
509 );
510 assert_eq!(
511 reason_to_error_code("UNSUPPORTED_OPERATION"),
512 Some(error_code::UNSUPPORTED_OPERATION)
513 );
514 assert_eq!(
515 reason_to_error_code("CONTENT_TYPE_NOT_SUPPORTED"),
516 Some(error_code::CONTENT_TYPE_NOT_SUPPORTED)
517 );
518 assert_eq!(
519 reason_to_error_code("UNSUPPORTED_CONTENT_TYPE"),
520 Some(error_code::CONTENT_TYPE_NOT_SUPPORTED)
521 );
522 assert_eq!(
523 reason_to_error_code("INVALID_AGENT_RESPONSE"),
524 Some(error_code::INVALID_AGENT_RESPONSE)
525 );
526 assert_eq!(
527 reason_to_error_code("EXTENDED_AGENT_CARD_NOT_CONFIGURED"),
528 Some(error_code::EXTENDED_CARD_NOT_CONFIGURED)
529 );
530 assert_eq!(
531 reason_to_error_code("EXTENDED_CARD_NOT_CONFIGURED"),
532 Some(error_code::EXTENDED_CARD_NOT_CONFIGURED)
533 );
534 assert_eq!(
535 reason_to_error_code("EXTENSION_SUPPORT_REQUIRED"),
536 Some(error_code::EXTENSION_SUPPORT_REQUIRED)
537 );
538 assert_eq!(
539 reason_to_error_code("VERSION_NOT_SUPPORTED"),
540 Some(error_code::VERSION_NOT_SUPPORTED)
541 );
542 assert_eq!(
543 reason_to_error_code("PARSE_ERROR"),
544 Some(error_code::PARSE_ERROR)
545 );
546 assert_eq!(
547 reason_to_error_code("INVALID_REQUEST"),
548 Some(error_code::INVALID_REQUEST)
549 );
550 assert_eq!(
551 reason_to_error_code("METHOD_NOT_FOUND"),
552 Some(error_code::METHOD_NOT_FOUND)
553 );
554 assert_eq!(
555 reason_to_error_code("INVALID_PARAMS"),
556 Some(error_code::INVALID_PARAMS)
557 );
558 assert_eq!(
559 reason_to_error_code("INTERNAL_ERROR"),
560 Some(error_code::INTERNAL_ERROR)
561 );
562 assert_eq!(reason_to_error_code("UNKNOWN_REASON"), None);
563 }
564
565 #[test]
566 fn test_error_display() {
567 let e = A2AError::internal("test message");
568 assert_eq!(format!("{e}"), "test message");
569 }
570
571 #[test]
572 fn test_jsonrpc_error_from() {
573 let e = A2AError::internal("test");
574 let rpc: crate::JsonRpcError = e.into();
575 assert_eq!(rpc.code, error_code::INTERNAL_ERROR);
576 }
577
578 #[test]
579 fn test_a2a_error_from_details_folds_violations_and_promotes_a_bare_internal_error() {
580 let details = vec![
581 TypedDetail::bad_request(vec![
582 errordetails::FieldViolation {
583 field: "message.parts".to_string(),
584 description: "at least one part is required".to_string(),
585 },
586 errordetails::FieldViolation {
587 field: String::new(),
588 description: "body is not JSON".to_string(),
589 },
590 ]),
591 TypedDetail::from_struct(HashMap::new()),
592 ];
593
594 let err =
595 a2a_error_from_details(error_code::INTERNAL_ERROR, "invalid".to_string(), details);
596
597 assert_eq!(err.code, error_code::INVALID_PARAMS);
598 assert_eq!(
599 err.message,
600 "invalid: message.parts: at least one part is required; body is not JSON"
601 );
602 assert_eq!(err.details.map(|d| d.len()), Some(2));
603 }
604
605 #[test]
606 fn test_a2a_error_from_details_takes_the_reason_whatever_the_detail_order() {
607 let bad_request = TypedDetail::new(errordetails::BAD_REQUEST_TYPE, HashMap::new());
608 let error_info =
609 TypedDetail::error_info("INTERNAL_ERROR", errordetails::PROTOCOL_DOMAIN, None);
610
611 for details in [
612 vec![bad_request.clone(), error_info.clone()],
613 vec![error_info, bad_request],
614 ] {
615 let err =
616 a2a_error_from_details(error_code::INTERNAL_ERROR, "boom".to_string(), details);
617 assert_eq!(err.code, error_code::INTERNAL_ERROR);
618 assert_eq!(err.message, "boom");
619 }
620
621 let err = a2a_error_from_details(error_code::PARSE_ERROR, "boom".to_string(), Vec::new());
622 assert_eq!(err.code, error_code::PARSE_ERROR);
623 assert!(err.details.is_none());
624 }
625}