1use crate::{AgentCard, Body, Capability, Envelope, Performative};
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum A2aState {
15 Submitted,
16 Working,
17 InputRequired,
18 Completed,
19 Canceled,
20 Failed,
21 Rejected,
22}
23
24impl A2aState {
25 pub fn as_str(&self) -> &'static str {
26 match self {
27 A2aState::Submitted => "SUBMITTED",
28 A2aState::Working => "WORKING",
29 A2aState::InputRequired => "INPUT_REQUIRED",
30 A2aState::Completed => "COMPLETED",
31 A2aState::Canceled => "CANCELED",
32 A2aState::Failed => "FAILED",
33 A2aState::Rejected => "REJECTED",
34 }
35 }
36}
37
38pub fn acl_to_a2a_state(env: &Envelope) -> Option<A2aState> {
41 Some(match (&env.performative, &env.body) {
42 (Performative::Request, _) => A2aState::Submitted,
43 (Performative::Delegate, _) => A2aState::Submitted,
44 (Performative::Progress, _) => A2aState::Working,
45 (Performative::InputRequired, _) => A2aState::InputRequired,
46 (Performative::Inform, Body::Result { .. }) => A2aState::Completed,
47 (Performative::Inform, _) => A2aState::Working, (Performative::Failure, _) => A2aState::Failed,
49 (Performative::Cancel, _) => A2aState::Canceled,
50 (Performative::Reject, _) => A2aState::Rejected,
51 _ => return None,
52 })
53}
54
55pub fn acl_to_a2a_task(env: &Envelope) -> Option<serde_json::Value> {
57 let state = acl_to_a2a_state(env)?;
58 let mut task = serde_json::json!({
59 "id": env.msg_id,
60 "contextId": env.reply_with.clone().unwrap_or_else(|| env.msg_id.clone()),
61 "status": {"state": state.as_str()},
62 });
63 if let Some(r) = &env.in_reply_to {
64 task["status"]["message"] = serde_json::json!({"role": "agent", "taskId": r});
65 }
66 if let Body::Result { output, artifacts } = &env.body {
68 task["artifacts"] = serde_json::json!(artifacts
69 .iter()
70 .map(|a| serde_json::json!({
71 "artifactId": a.name,
72 "parts": [{"kind": "data", "data": {
73 "mime": a.mime,
74 "size": a.bytes.len(),
76 }}]
77 }))
78 .collect::<Vec<_>>());
79 if let Some(o) = output.as_object() {
80 task["metadata"] = serde_json::json!(o);
81 }
82 }
83 if let Body::Failure { code, reason, .. } = &env.body {
84 task["status"]["message"] = serde_json::json!({
85 "role": "agent", "parts": [{"kind": "text", "text": reason}], "code": code
86 });
87 }
88 Some(task)
89}
90
91pub fn a2a_task_to_acl(task: &serde_json::Value) -> Option<Envelope> {
95 let state = task["status"]["state"].as_str()?;
96 let performative = a2a_state_to_acl(state)?;
97 let id = task["id"].as_str()?.to_string();
98 let context = task["contextId"].as_str().unwrap_or("").to_string();
99 let ctx2 = context.clone();
100 let body = if state == "COMPLETED" {
102 let output = task.get("metadata").cloned().unwrap_or(serde_json::json!({}));
103 let artifacts: Vec<crate::Artifact> = task["artifacts"]
104 .as_array()
105 .map(|arts| {
106 arts.iter()
107 .map(|a| crate::Artifact {
108 name: a["artifactId"].as_str().unwrap_or("").to_string(),
109 mime: a["parts"][0]["data"]["mime"].as_str().unwrap_or("application/json").to_string(),
110 bytes: Vec::new(),
111 })
112 .collect()
113 })
114 .unwrap_or_default();
115 Body::Result { output, artifacts }
116 } else if state == "FAILED" {
117 let reason = task["status"]["message"]["parts"][0]["text"]
118 .as_str()
119 .unwrap_or("failed via A2A")
120 .to_string();
121 let code = task["status"]["message"]["code"].as_u64().unwrap_or(500) as u16;
122 Body::Failure { target_msg_id: context.clone(), code, reason, recoverable: false }
123 } else {
124 Body::Progress {
125 target_msg_id: ctx2,
126 percent: Some(50),
127 note: Some(state.to_string()),
128 }
129 };
130 let mut env = Envelope::new(
131 crate::Aid::new("a2a:bridge"),
132 crate::Aid::new("did:acl:local"),
133 performative,
134 body,
135 );
136 env.msg_id = id;
137 env.reply_with = Some(context);
138 Some(env)
139}
140
141pub fn a2a_state_to_acl(state: &str) -> Option<Performative> {
143 Some(match state {
144 "SUBMITTED" | "WORKING" => Performative::Progress,
145 "INPUT_REQUIRED" => Performative::InputRequired,
146 "COMPLETED" => Performative::Inform,
147 "FAILED" => Performative::Failure,
148 "CANCELED" => Performative::Cancel,
149 "REJECTED" => Performative::Reject,
150 _ => return None,
151 })
152}
153
154pub fn card_to_mcp_tools(card: &AgentCard) -> serde_json::Value {
158 serde_json::json!({
159 "jsonrpc": "2.0",
160 "id": 1,
161 "result": {
162 "tools": card.capabilities.iter().map(|c| {
163 serde_json::json!({
164 "name": c.name,
165 "description": format!("{} v{}", card.name, card.version),
166 "inputSchema": c.input_schema.clone()
167 .unwrap_or(serde_json::json!({"type": "object"})),
168 })
169 }).collect::<Vec<_>>(),
170 }
171 })
172}
173
174pub fn mcp_call_to_acl_body(params: &serde_json::Value) -> Result<Body, String> {
176 let name = params
177 .get("name")
178 .and_then(|v| v.as_str())
179 .ok_or("missing name")?;
180 let args = params.get("arguments").cloned().unwrap_or(serde_json::json!({}));
181 Ok(Body::Task {
182 description: name.to_string(),
183 input: args,
184 deadline_ms: None,
185 priority: None,
186 })
187}
188
189pub fn acl_result_to_mcp(env: &Envelope) -> serde_json::Value {
191 let output = match &env.body {
192 Body::Result { output, .. } => output.clone(),
193 Body::Text { text } => serde_json::json!(text),
194 _ => serde_json::Value::Null,
195 };
196 let (content, is_error) = match (&env.performative, &output) {
197 (Performative::Failure { .. }, _) | (_, _) if env.performative == Performative::Failure => (
198 serde_json::json!([{"type": "text", "text": output.to_string()}]),
199 true,
200 ),
201 _ => (serde_json::json!([{"type": "text", "text": output.to_string()}]), false),
202 };
203 serde_json::json!({
204 "jsonrpc": "2.0",
205 "id": 1,
206 "result": {"content": content, "isError": is_error},
207 })
208}
209
210pub fn card_has_capability(card: &AgentCard, name: &str) -> bool {
212 card.capabilities.iter().any(|Capability { name: n, .. }| n == name)
213}
214
215pub fn validate_arguments(
219 card: &AgentCard,
220 name: &str,
221 arguments: &serde_json::Value,
222) -> Result<(), String> {
223 let Some(cap) = card.capabilities.iter().find(|c| c.name == name) else {
224 return Err(format!("capability '{name}' not on card"));
225 };
226 let Some(schema) = &cap.input_schema else {
227 return Ok(()); };
229 let args = arguments.as_object().ok_or("arguments must be an object")?;
230 if let Some(required) = schema["required"].as_array() {
231 for field in required {
232 let field = field.as_str().unwrap_or_default();
233 if !args.contains_key(field) {
234 return Err(format!("missing required argument '{field}'"));
235 }
236 }
237 }
238 if let Some(props) = schema["properties"].as_object() {
239 for (key, spec) in props {
240 let Some(v) = args.get(key) else { continue };
241 let want = spec["type"].as_str().unwrap_or("");
242 let ok = match want {
243 "string" => v.is_string(),
244 "number" => v.is_number(),
245 "integer" => v.is_i64() || v.is_u64(),
246 "boolean" => v.is_boolean(),
247 "object" => v.is_object(),
248 "array" => v.is_array(),
249 _ => true, };
251 if !ok {
252 return Err(format!("argument '{key}' expected type {want}"));
253 }
254 }
255 }
256 Ok(())
257}
258
259#[cfg(test)]
260mod tests {
261 use super::*;
262 use crate::Aid;
263
264 fn env(perf: Performative, body: Body) -> Envelope {
265 Envelope::new(Aid::local(1, "t"), Aid::new("did:x:y"), perf, body)
266 }
267
268 #[test]
269 fn a2a_state_mapping_full_lifecycle() {
270 let cases = [
271 (Performative::Request, A2aState::Submitted),
272 (Performative::Delegate, A2aState::Submitted),
273 (Performative::Progress, A2aState::Working),
274 (Performative::InputRequired, A2aState::InputRequired),
275 (Performative::Inform, A2aState::Completed),
276 (Performative::Failure, A2aState::Failed),
277 (Performative::Cancel, A2aState::Canceled),
278 (Performative::Reject, A2aState::Rejected),
279 ];
280 for (perf, expected) in cases {
281 let body = match perf {
282 Performative::Inform => Body::Result {
283 output: serde_json::json!("ok"),
284 artifacts: vec![],
285 },
286 Performative::Failure => Body::Failure {
287 target_msg_id: "m1".into(),
288 code: 500,
289 reason: "boom".into(),
290 recoverable: false,
291 },
292 Performative::Progress => Body::Progress {
293 target_msg_id: "m1".into(),
294 percent: Some(10),
295 note: None,
296 },
297 Performative::InputRequired => Body::InputNeeded {
298 target_msg_id: "m1".into(),
299 what: "x".into(),
300 schema: None,
301 },
302 _ => Body::Ref {
303 target_msg_id: "m1".into(),
304 },
305 };
306 let e = env(perf, body);
307 assert_eq!(acl_to_a2a_state(&e), Some(expected), "{perf:?}");
308 }
309 assert_eq!(acl_to_a2a_state(&env(Performative::Propose, Body::Ref { target_msg_id: "m".into() })), None);
311 }
312
313 #[test]
314 fn a2a_task_shape() {
315 let e = env(
316 Performative::Inform,
317 Body::Result {
318 output: serde_json::json!({"reversed": "cba"}),
319 artifacts: vec![],
320 },
321 );
322 let task = acl_to_a2a_task(&e).unwrap();
323 assert_eq!(task["status"]["state"], "COMPLETED");
324 assert_eq!(task["id"], e.msg_id);
325 assert_eq!(task["artifacts"], serde_json::json!([]));
326 }
327
328 #[test]
329 fn a2a_roundtrip_through_bridge() {
330 let e = env(
332 Performative::Request,
333 Body::Task {
334 description: "t".into(),
335 input: serde_json::json!({}),
336 deadline_ms: None,
337 priority: None,
338 },
339 );
340 let task = acl_to_a2a_task(&e).unwrap();
341 let state = task["status"]["state"].as_str().unwrap();
342 assert_eq!(a2a_state_to_acl(state), Some(Performative::Progress));
343 }
344
345 #[test]
346 fn mcp_tools_list_from_card() {
347 let card = AgentCard {
348 name: "demo".into(),
349 version: "1.0".into(),
350 description: "d".into(),
351 endpoint: Aid::local(1, "t"),
352 capabilities: vec![Capability {
353 name: "text.reverse".into(),
354 input_schema: Some(serde_json::json!({
355 "type": "object", "required": ["text"]
356 })),
357 output_schema: None,
358 examples: None,
359 }],
360 auth_scheme: "none".into(),
361 key_id: None,
362 public_key: None,
363 rate_hint: None,
364 valid_until: None,
365 sig: None,
366 };
367 let tools = card_to_mcp_tools(&card);
368 assert_eq!(tools["jsonrpc"], "2.0");
369 assert_eq!(tools["result"]["tools"][0]["name"], "text.reverse");
370 assert_eq!(tools["result"]["tools"][0]["inputSchema"]["required"][0], "text");
371 assert!(card_has_capability(&card, "text.reverse"));
372 assert!(!card_has_capability(&card, "other"));
373 }
374
375 #[test]
376 fn validate_arguments_checks_required_and_types() {
377 let card = AgentCard {
378 name: "demo".into(),
379 version: "1".into(),
380 description: "d".into(),
381 endpoint: Aid::local(1, "t"),
382 capabilities: vec![Capability {
383 name: "text.reverse".into(),
384 input_schema: Some(serde_json::json!({
385 "type": "object",
386 "required": ["text"],
387 "properties": {"text": {"type": "string"}, "count": {"type": "integer"}}
388 })),
389 output_schema: None,
390 examples: None,
391 }],
392 auth_scheme: "none".into(),
393 key_id: None,
394 public_key: None,
395 rate_hint: None,
396 valid_until: None,
397 sig: None,
398 };
399 validate_arguments(&card, "text.reverse", &serde_json::json!({"text": "abc"})).unwrap();
401 assert!(validate_arguments(&card, "text.reverse", &serde_json::json!({})).is_err());
403 assert!(validate_arguments(&card, "text.reverse", &serde_json::json!({"text": 5})).is_err());
405 assert!(validate_arguments(&card, "text.reverse", &serde_json::json!({"text": "a", "count": "many"})).is_err());
407 assert!(validate_arguments(&card, "nope", &serde_json::json!({})).is_err());
409 }
410
411 #[test]
412 fn a2a_full_roundtrip_acl_to_task_and_back() {
413 let e = env(
414 Performative::Inform,
415 Body::Result {
416 output: serde_json::json!({"reversed": "cba"}),
417 artifacts: vec![],
418 },
419 );
420 let task = acl_to_a2a_task(&e).unwrap();
421 let back = a2a_task_to_acl(&task).unwrap();
422 assert_eq!(back.performative, Performative::Inform);
424 assert_eq!(back.msg_id, e.msg_id);
425 match &back.body {
426 Body::Result { output, .. } => assert_eq!(output["reversed"], "cba"),
427 other => panic!("expected Result, got {other:?}"),
428 }
429 }
430
431 #[test]
432 fn mcp_call_to_acl_and_back() {
433 let call = serde_json::json!({
434 "name": "text.reverse",
435 "arguments": {"text": "abc"}
436 });
437 let body = mcp_call_to_acl_body(&call).unwrap();
438 match &body {
439 Body::Task { description, input, .. } => {
440 assert_eq!(description, "text.reverse");
441 assert_eq!(input["text"], "abc");
442 }
443 other => panic!("unexpected body {other:?}"),
444 }
445 let e = env(Performative::Inform, Body::Result {
446 output: serde_json::json!({"reversed": "cba"}),
447 artifacts: vec![],
448 });
449 let result = acl_result_to_mcp(&e);
450 assert_eq!(result["result"]["isError"], false);
451 assert!(result["result"]["content"][0]["text"]
452 .as_str()
453 .unwrap()
454 .contains("cba"));
455 }
456}