1use std::collections::BTreeMap;
10use std::sync::Arc;
11
12use adk_core::{AdkError, ErrorCategory, ErrorComponent, Tool, ToolContext, ToolEffect};
13use async_trait::async_trait;
14use awp_types::{
15 ApprovalHint, CapabilityEffect, CapabilityManifestV2, CapabilityV2, ErrorBody, ErrorCode,
16 RequesterId, TrustTier,
17};
18use serde_json::{Value, json};
19use uuid::Uuid;
20
21pub const META_REQUESTER: &str = "awp.requester";
23pub const META_TIER: &str = "awp.tier";
25pub const META_CONSENT: &str = "awp.consent";
27pub const META_ERROR_CODE: &str = "awp_error_code";
29pub const HELD_CALL_SCHEMA_ID: &str =
31 "https://agenticwebprotocol.com/schemas/2.0/held-call.schema.json";
32
33#[derive(Debug, Clone, PartialEq)]
35pub struct CapabilityCall {
36 pub capability: String,
38 pub input: Value,
40 pub tier: TrustTier,
42 pub requester: Option<RequesterId>,
44 pub idempotency_key: String,
46 pub consent: Vec<Uuid>,
48}
49
50#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
52#[non_exhaustive]
53pub enum CapabilityError {
54 #[error("{message}")]
57 Refused {
58 code: ErrorCode,
60 message: String,
62 },
63 #[error("capability handler failed: {0}")]
65 Failed(String),
66}
67
68impl CapabilityError {
69 pub fn refused(code: ErrorCode, message: impl Into<String>) -> Self {
71 Self::Refused { code, message: message.into() }
72 }
73}
74
75#[async_trait]
94pub trait CapabilityHandler: Send + Sync {
95 async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError>;
102
103 fn call_amount(&self, input: &Value) -> Option<u64> {
107 input.get("amount").and_then(Value::as_u64)
108 }
109
110 async fn amount(&self, input: &Value) -> Option<u64> {
114 self.call_amount(input)
115 }
116}
117
118#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
120#[non_exhaustive]
121pub enum CapabilityDefinitionError {
122 #[error(
124 "capability name `{0}` must match ^[a-z][a-z0-9_]{{0,63}}$: lowercase letters, digits and underscores"
125 )]
126 InvalidName(String),
127 #[error("capability `{name}` has an invalid input schema: {reason}")]
129 InvalidSchema {
130 name: String,
132 reason: String,
134 },
135 #[error("capability `{0}` is declared twice")]
137 Duplicate(String),
138}
139
140pub fn is_valid_capability_name(name: &str) -> bool {
142 let mut bytes = name.bytes();
143 bytes.next().is_some_and(|first| first.is_ascii_lowercase())
144 && name.len() <= 64
145 && bytes.all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_')
146}
147
148pub struct CapabilityTool {
178 declaration: CapabilityV2,
179 origin: String,
180 handler: Arc<dyn CapabilityHandler>,
181 validator: Option<jsonschema::Validator>,
182 annotations: Value,
183 response_schema: Option<Value>,
184}
185
186impl std::fmt::Debug for CapabilityTool {
187 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
188 f.debug_struct("CapabilityTool")
189 .field("name", &self.declaration.name)
190 .field("origin", &self.origin)
191 .finish_non_exhaustive()
192 }
193}
194
195impl CapabilityTool {
196 pub fn new(
203 domain: &str,
204 declaration: CapabilityV2,
205 handler: Arc<dyn CapabilityHandler>,
206 ) -> Result<Self, CapabilityDefinitionError> {
207 if !is_valid_capability_name(&declaration.name) {
208 return Err(CapabilityDefinitionError::InvalidName(declaration.name));
209 }
210 let validator = declaration
211 .input_schema
212 .as_ref()
213 .map(|schema| {
214 jsonschema::validator_for(schema).map_err(|error| {
215 CapabilityDefinitionError::InvalidSchema {
216 name: declaration.name.clone(),
217 reason: error.to_string(),
218 }
219 })
220 })
221 .transpose()?;
222 let annotations = json!({
223 "readOnlyHint": declaration.effect == CapabilityEffect::ReadOnly,
224 "idempotentHint": declaration.effect != CapabilityEffect::NonIdempotent,
225 });
226 let response_schema = match (&declaration.approval, &declaration.output_schema) {
228 (ApprovalHint::Never, output) => output.clone(),
229 (_, output) => Some(json!({
230 "oneOf": [
231 output.clone().unwrap_or_else(|| json!({ "type": "object" })),
232 { "$ref": HELD_CALL_SCHEMA_ID },
233 ]
234 })),
235 };
236 Ok(Self {
237 origin: Self::origin_for(domain),
238 declaration,
239 handler,
240 validator,
241 annotations,
242 response_schema,
243 })
244 }
245
246 pub fn origin_for(domain: &str) -> String {
248 format!("awp:{domain}")
249 }
250
251 pub fn declaration(&self) -> &CapabilityV2 {
253 &self.declaration
254 }
255
256 pub fn validate_input(&self, input: &Value) -> Result<(), Vec<String>> {
262 if !input.is_object() {
263 return Err(vec!["the input must be a JSON object".to_owned()]);
264 }
265 match &self.validator {
266 None => Ok(()),
267 Some(validator) => {
268 let errors: Vec<String> =
269 validator.iter_errors(input).take(5).map(|error| error.to_string()).collect();
270 if errors.is_empty() { Ok(()) } else { Err(errors) }
271 }
272 }
273 }
274
275 pub fn call_amount(&self, input: &Value) -> Option<u64> {
278 self.handler
279 .call_amount(input)
280 .or_else(|| self.declaration.price.as_ref().map(|price| price.amount))
281 }
282
283 pub async fn amount(&self, input: &Value) -> Option<u64> {
287 match self.handler.amount(input).await {
288 Some(amount) => Some(amount),
289 None => self.declaration.price.as_ref().map(|price| price.amount),
290 }
291 }
292
293 pub async fn invoke(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
299 if let Err(errors) = self.validate_input(&call.input) {
300 return Err(CapabilityError::refused(
301 ErrorCode::SchemaValidationFailed,
302 format!("the input does not match the input schema: {}", errors.join("; ")),
303 ));
304 }
305 self.handler.handle(call).await
306 }
307}
308
309pub fn capability_error_to_adk(error: &CapabilityError) -> AdkError {
311 let (code, message) = match error {
312 CapabilityError::Refused { code, message } => (code.clone(), message.clone()),
313 CapabilityError::Failed(detail) => {
314 tracing::warn!(error = %detail, "awp capability handler failed");
315 (ErrorCode::InternalError, "the capability failed".to_owned())
316 }
317 };
318 let category = match code.http_status() {
319 400 | 409 | 410 | 451 => ErrorCategory::InvalidInput,
320 401 => ErrorCategory::Unauthorized,
321 402 | 403 => ErrorCategory::Forbidden,
322 404 => ErrorCategory::NotFound,
323 429 => ErrorCategory::RateLimited,
324 502 | 503 => ErrorCategory::Unavailable,
325 _ => ErrorCategory::Internal,
326 };
327 let mut adk = AdkError::new(ErrorComponent::Tool, category, "awp.capability.refused", message);
328 adk.details.metadata.insert(META_ERROR_CODE.to_owned(), Value::String(code.to_string()));
329 adk
330}
331
332pub fn adk_error_to_body(error: &AdkError) -> ErrorBody {
335 if let Some(Value::String(code)) = error.details.metadata.get(META_ERROR_CODE) {
336 return ErrorBody::new(ErrorCode::from(code.as_str()), error.message.clone());
337 }
338 let code = match error.category {
339 ErrorCategory::InvalidInput => ErrorCode::InvalidRequest,
340 ErrorCategory::Unauthorized => ErrorCode::Unauthorized,
341 ErrorCategory::Forbidden => ErrorCode::Forbidden,
342 ErrorCategory::NotFound => ErrorCode::ResourceNotFound,
343 ErrorCategory::RateLimited => ErrorCode::RateLimitExceeded,
344 ErrorCategory::Timeout | ErrorCategory::Unavailable => ErrorCode::ServiceDegraded,
345 _ => ErrorCode::InternalError,
346 };
347 tracing::warn!(error.code = error.code, error = %error.message, "awp capability tool failed");
348 ErrorBody::new(code.clone(), format!("the capability failed ({code})"))
349}
350
351#[async_trait]
352impl Tool for CapabilityTool {
353 fn name(&self) -> &str {
354 &self.declaration.name
355 }
356
357 fn description(&self) -> &str {
358 &self.declaration.description
359 }
360
361 fn parameters_schema(&self) -> Option<Value> {
362 Some(self.declaration.input_schema.clone().unwrap_or_else(|| json!({ "type": "object" })))
363 }
364
365 fn response_schema(&self) -> Option<Value> {
366 self.response_schema.clone()
367 }
368
369 fn annotations(&self) -> Option<&Value> {
370 Some(&self.annotations)
371 }
372
373 fn origin(&self) -> &str {
374 &self.origin
375 }
376
377 fn effect(&self) -> ToolEffect {
378 match self.declaration.effect {
379 CapabilityEffect::ReadOnly => ToolEffect::ReadOnly,
380 CapabilityEffect::Idempotent => ToolEffect::Idempotent,
381 _ => ToolEffect::NonIdempotent,
382 }
383 }
384
385 fn is_read_only(&self) -> bool {
386 self.declaration.effect == CapabilityEffect::ReadOnly
387 }
388
389 fn is_concurrency_safe(&self) -> bool {
390 self.declaration.effect == CapabilityEffect::ReadOnly
391 }
392
393 async fn execute(&self, ctx: Arc<dyn ToolContext>, args: Value) -> adk_core::Result<Value> {
394 let metadata = ctx.request_metadata();
395 let requester = metadata.get(META_REQUESTER).and_then(Value::as_str).map(RequesterId::new);
396 let tier = metadata
397 .get(META_TIER)
398 .and_then(|tier| serde_json::from_value(tier.clone()).ok())
399 .unwrap_or(TrustTier::Public);
400 let consent = metadata
401 .get(META_CONSENT)
402 .and_then(|ids| serde_json::from_value(ids.clone()).ok())
403 .unwrap_or_default();
404 let call = CapabilityCall {
405 capability: self.declaration.name.clone(),
406 input: args,
407 tier,
408 requester,
409 idempotency_key: ctx.idempotency_key(),
410 consent,
411 };
412 self.invoke(call).await.map_err(|error| capability_error_to_adk(&error))
413 }
414}
415
416#[derive(Debug, Clone)]
445pub struct CapabilityRegistry {
446 domain: String,
447 tools: BTreeMap<String, Arc<CapabilityTool>>,
448}
449
450impl CapabilityRegistry {
451 pub fn new(domain: impl Into<String>) -> Self {
453 Self { domain: domain.into(), tools: BTreeMap::new() }
454 }
455
456 pub fn domain(&self) -> &str {
458 &self.domain
459 }
460
461 pub fn declare(
468 &mut self,
469 declaration: CapabilityV2,
470 handler: Arc<dyn CapabilityHandler>,
471 ) -> Result<Arc<CapabilityTool>, CapabilityDefinitionError> {
472 if self.tools.contains_key(&declaration.name) {
473 return Err(CapabilityDefinitionError::Duplicate(declaration.name));
474 }
475 let tool = Arc::new(CapabilityTool::new(&self.domain, declaration, handler)?);
476 self.tools.insert(tool.declaration().name.clone(), Arc::clone(&tool));
477 Ok(tool)
478 }
479
480 pub fn get(&self, name: &str) -> Option<&Arc<CapabilityTool>> {
482 self.tools.get(name)
483 }
484
485 pub fn visible(&self, name: &str, tier: TrustTier) -> Option<&Arc<CapabilityTool>> {
488 self.get(name).filter(|tool| tool.declaration().visible_to(tier))
489 }
490
491 pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
493 self.tools.values().map(|tool| Arc::clone(tool) as Arc<dyn Tool>).collect()
494 }
495
496 pub fn tools_for(&self, tier: TrustTier) -> Vec<Arc<dyn Tool>> {
498 self.tools
499 .values()
500 .filter(|tool| tool.declaration().visible_to(tier))
501 .map(|tool| Arc::clone(tool) as Arc<dyn Tool>)
502 .collect()
503 }
504
505 pub fn manifest(&self) -> CapabilityManifestV2 {
507 CapabilityManifestV2::new(
508 self.tools.values().map(|tool| tool.declaration().clone()).collect(),
509 )
510 }
511
512 pub fn manifest_for(&self, tier: TrustTier) -> CapabilityManifestV2 {
514 self.manifest().visible_to(tier)
515 }
516}
517
518#[cfg(test)]
519mod tests {
520 use super::*;
521 use crate::v2::executor::{Binding, EdgeToolContext, Invocation};
522
523 struct Echo;
524
525 #[async_trait]
526 impl CapabilityHandler for Echo {
527 async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
528 Ok(json!({
529 "input": call.input,
530 "tier": call.tier,
531 "requester": call.requester.map(|r| r.to_string()),
532 "consent": call.consent,
533 "key": call.idempotency_key,
534 }))
535 }
536 }
537
538 struct Stored(tokio::sync::Mutex<std::collections::BTreeMap<String, u64>>);
540
541 #[async_trait]
542 impl CapabilityHandler for Stored {
543 async fn handle(&self, _call: CapabilityCall) -> Result<Value, CapabilityError> {
544 Ok(json!({}))
545 }
546
547 async fn amount(&self, input: &Value) -> Option<u64> {
548 let order = input["orderId"].as_str()?;
549 self.0.lock().await.get(order).copied()
550 }
551 }
552
553 #[tokio::test]
554 async fn the_edge_reads_amounts_where_the_handler_keeps_them() {
555 let totals = [("order-1".to_string(), 250_000)].into_iter().collect();
556 let mut declaration =
557 CapabilityV2::new("pay_order", "Pay", CapabilityEffect::NonIdempotent);
558 declaration.price =
559 Some(awp_types::Price { amount: 500, currency: "KES".into(), rails: Vec::new() });
560 let tool = CapabilityTool::new(
561 "example.com",
562 declaration,
563 Arc::new(Stored(tokio::sync::Mutex::new(totals))),
564 )
565 .unwrap();
566 assert_eq!(tool.amount(&json!({ "orderId": "order-1" })).await, Some(250_000));
567 assert_eq!(
568 tool.amount(&json!({ "orderId": "order-9" })).await,
569 Some(500),
570 "an amount the handler cannot read is the declared price"
571 );
572 assert_eq!(tool.call_amount(&json!({ "orderId": "order-1" })), Some(500));
573 let echo = CapabilityTool::new(
574 "example.com",
575 CapabilityV2::new("donate", "Donate", CapabilityEffect::NonIdempotent),
576 Arc::new(Echo),
577 )
578 .unwrap();
579 assert_eq!(
580 echo.amount(&json!({ "amount": 70 })).await,
581 Some(70),
582 "the default reads `amount`"
583 );
584 }
585
586 #[test]
587 fn names_follow_the_protocol_pattern() {
588 for good in ["a", "search_site", "book2", &"x".repeat(64)] {
589 assert!(is_valid_capability_name(good), "{good}");
590 }
591 for bad in ["", "Search", "2book", "place-order", "with space", &"x".repeat(65)] {
592 assert!(!is_valid_capability_name(bad), "{bad}");
593 }
594 let error = CapabilityTool::new(
595 "example.com",
596 CapabilityV2::new("Bad-Name", "x", CapabilityEffect::ReadOnly),
597 Arc::new(Echo),
598 )
599 .unwrap_err();
600 assert_eq!(error, CapabilityDefinitionError::InvalidName("Bad-Name".to_owned()));
601 }
602
603 #[test]
605 fn tool_metadata_mirrors_the_declaration() {
606 let read = CapabilityTool::new(
607 "example.com",
608 CapabilityV2::new("search_site", "Search", CapabilityEffect::ReadOnly),
609 Arc::new(Echo),
610 )
611 .unwrap();
612 assert_eq!(
613 read.annotations(),
614 Some(&json!({ "readOnlyHint": true, "idempotentHint": true }))
615 );
616 assert_eq!(read.effect(), ToolEffect::ReadOnly);
617 assert!(read.is_read_only() && read.is_concurrency_safe());
618 assert_eq!(read.parameters_schema(), Some(json!({ "type": "object" })));
619 assert_eq!(read.response_schema(), None);
620
621 let mut order = CapabilityV2::new("place_order", "Order", CapabilityEffect::NonIdempotent)
622 .with_approval(ApprovalHint::Always);
623 order.output_schema = Some(json!({ "type": "object", "required": ["orderId"] }));
624 let order = CapabilityTool::new("example.com", order, Arc::new(Echo)).unwrap();
625 assert_eq!(
626 order.annotations(),
627 Some(&json!({ "readOnlyHint": false, "idempotentHint": false }))
628 );
629 assert_eq!(
630 order.response_schema(),
631 Some(json!({ "oneOf": [
632 { "type": "object", "required": ["orderId"] },
633 { "$ref": HELD_CALL_SCHEMA_ID }
634 ] }))
635 );
636 assert_eq!(order.origin(), "awp:example.com");
637 let bad_schema = CapabilityV2 {
638 input_schema: Some(json!({ "type": 7 })),
639 ..CapabilityV2::new("x", "x", CapabilityEffect::ReadOnly)
640 };
641 assert!(matches!(
642 CapabilityTool::new("example.com", bad_schema, Arc::new(Echo)),
643 Err(CapabilityDefinitionError::InvalidSchema { .. })
644 ));
645 }
646
647 #[tokio::test]
650 async fn the_tool_path_carries_the_caller_and_the_awp_code() {
651 let mut declaration = CapabilityV2::new("book", "Book", CapabilityEffect::Idempotent);
652 declaration.input_schema = Some(json!({ "type": "object", "required": ["date"] }));
653 let tool =
654 Arc::new(CapabilityTool::new("example.com", declaration, Arc::new(Echo)).unwrap());
655 let consent = Uuid::now_v7();
656 let invocation = Invocation {
657 tier: TrustTier::Known,
658 requester: Some(RequesterId::web_bot_auth("https://buyer.example", "k")),
659 idempotency_key: Some("key-1".to_owned()),
660 consent: vec![consent],
661 ..Invocation::new("book", json!({ "date": "2026-11-02" }), Binding::Mcp)
662 };
663 let context = Arc::new(EdgeToolContext::new(&tool, &invocation, "call-1"));
664 let output =
665 Arc::clone(&tool).execute(context.clone(), invocation.input.clone()).await.unwrap();
666 assert_eq!(
667 output,
668 json!({
669 "input": { "date": "2026-11-02" },
670 "tier": "known",
671 "requester": "wba:https://buyer.example#k",
672 "consent": [consent],
673 "key": "key-1",
674 })
675 );
676 let error = tool.execute(context, json!({})).await.unwrap_err();
677 assert_eq!(error.code, "awp.capability.refused");
678 let body = adk_error_to_body(&error);
679 assert_eq!(body.code, ErrorCode::SchemaValidationFailed);
680 assert!(!body.retryable);
681 }
682
683 #[test]
684 fn handler_failures_hide_their_detail() {
685 let error = capability_error_to_adk(&CapabilityError::Failed("db password wrong".into()));
686 let body = adk_error_to_body(&error);
687 assert_eq!(body.code, ErrorCode::InternalError);
688 assert!(!body.message.contains("password"));
689 }
690}