Skip to main content

adk_awp/v2/
capability.rs

1//! Capabilities as `adk_core::Tool`s: one declaration, three bindings, one governed path
2//! (spec 3.5 §7.4, D-4).
3//!
4//! A [`CapabilityTool`] wraps an owner's [`CapabilityHandler`] as an `adk_core::Tool` whose
5//! `effect()` is the declared [`CapabilityEffect`] and whose `origin()` is `awp:{domain}`. It
6//! validates its input against the declared schema before the handler runs. A
7//! [`CapabilityRegistry`] holds a site's capabilities and builds the manifest for a tier.
8
9use 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
21/// Request-metadata key holding the caller's verified requester id.
22pub const META_REQUESTER: &str = "awp.requester";
23/// Request-metadata key holding the caller's tier.
24pub const META_TIER: &str = "awp.tier";
25/// Request-metadata key holding the consent receipt ids the call references.
26pub const META_CONSENT: &str = "awp.consent";
27/// `adk_core::AdkError` metadata key carrying the AWP 2.0 error code of a refused call.
28pub const META_ERROR_CODE: &str = "awp_error_code";
29/// `$id` of the held-call schema, for the output schema of capabilities that may hold.
30pub const HELD_CALL_SCHEMA_ID: &str =
31    "https://agenticwebprotocol.com/schemas/2.0/held-call.schema.json";
32
33/// One call of a capability, as its handler sees it (spec 3.5 §7.4).
34#[derive(Debug, Clone, PartialEq)]
35pub struct CapabilityCall {
36    /// The capability's name.
37    pub capability: String,
38    /// The input object, already validated against the input schema.
39    pub input: Value,
40    /// The caller's tier.
41    pub tier: TrustTier,
42    /// The caller's verified requester id, from `known` up.
43    pub requester: Option<RequesterId>,
44    /// The call's idempotency key; a `NonIdempotent` handler passes it downstream.
45    pub idempotency_key: String,
46    /// Consent receipt ids the call references.
47    pub consent: Vec<Uuid>,
48}
49
50/// Why a capability handler did not produce an output (spec 3.5 §7.4, §7.5).
51#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
52#[non_exhaustive]
53pub enum CapabilityError {
54    /// The call is refused with an AWP error code the requester sees, such as
55    /// `inventory_unavailable` or `quote_expired`.
56    #[error("{message}")]
57    Refused {
58        /// The AWP 2.0 error code.
59        code: ErrorCode,
60        /// A message with no internal detail.
61        message: String,
62    },
63    /// The handler failed; the requester sees `internal_error` and the detail is logged.
64    #[error("capability handler failed: {0}")]
65    Failed(String),
66}
67
68impl CapabilityError {
69    /// A refusal with `code` and `message`.
70    pub fn refused(code: ErrorCode, message: impl Into<String>) -> Self {
71        Self::Refused { code, message: message.into() }
72    }
73}
74
75/// The owner's code behind a capability (spec 3.5 §7.4).
76///
77/// # Example
78///
79/// ```
80/// use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler};
81/// use serde_json::{Value, json};
82///
83/// struct Quote;
84///
85/// #[async_trait::async_trait]
86/// impl CapabilityHandler for Quote {
87///     async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
88///         let panels = call.input["panels"].as_u64().unwrap_or(1);
89///         Ok(json!({ "total": panels * 25_000, "currency": "KES" }))
90///     }
91/// }
92/// ```
93#[async_trait]
94pub trait CapabilityHandler: Send + Sync {
95    /// Executes the call.
96    ///
97    /// # Errors
98    ///
99    /// [`CapabilityError::Refused`] for an outcome the requester should see as an AWP error;
100    /// [`CapabilityError::Failed`] for anything else.
101    async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError>;
102
103    /// The amount of a call in minor units, compared with an `above_amount` approval hint.
104    ///
105    /// The default reads a non-negative integer `amount` member of the input.
106    fn call_amount(&self, input: &Value) -> Option<u64> {
107        input.get("amount").and_then(Value::as_u64)
108    }
109
110    /// The amount of a call in minor units, read where the handler keeps it, such as the
111    /// total of a stored quote or order (spec 3.5 §7.4, §7.9). The edge decides holds with
112    /// this; the default is [`call_amount`](Self::call_amount).
113    async fn amount(&self, input: &Value) -> Option<u64> {
114        self.call_amount(input)
115    }
116}
117
118/// Why a capability cannot be declared (spec 3.5 §7.4).
119#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
120#[non_exhaustive]
121pub enum CapabilityDefinitionError {
122    /// The name is not `^[a-z][a-z0-9_]{0,63}$`.
123    #[error(
124        "capability name `{0}` must match ^[a-z][a-z0-9_]{{0,63}}$: lowercase letters, digits and underscores"
125    )]
126    InvalidName(String),
127    /// The input schema does not compile.
128    #[error("capability `{name}` has an invalid input schema: {reason}")]
129    InvalidSchema {
130        /// The capability's name.
131        name: String,
132        /// Why the schema is invalid.
133        reason: String,
134    },
135    /// Two capabilities share a name.
136    #[error("capability `{0}` is declared twice")]
137    Duplicate(String),
138}
139
140/// Returns `true` when `name` is a valid capability name: `^[a-z][a-z0-9_]{0,63}$`.
141pub 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
148/// A capability exposed as an `adk_core::Tool` (spec 3.5 §7.4, D-4).
149///
150/// # Example
151///
152/// ```
153/// use std::sync::Arc;
154///
155/// use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler, CapabilityTool};
156/// use adk_core::{Tool, ToolEffect};
157/// use awp_types::{CapabilityEffect, CapabilityV2};
158/// use serde_json::{Value, json};
159///
160/// struct Echo;
161///
162/// #[async_trait::async_trait]
163/// impl CapabilityHandler for Echo {
164///     async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> {
165///         Ok(call.input)
166///     }
167/// }
168///
169/// let mut declaration = CapabilityV2::new("place_order", "Place an order", CapabilityEffect::NonIdempotent);
170/// declaration.input_schema = Some(json!({ "type": "object", "required": ["sku"] }));
171/// let tool = CapabilityTool::new("example.com", declaration, Arc::new(Echo)).unwrap();
172/// assert_eq!(tool.origin(), "awp:example.com");
173/// assert_eq!(tool.effect(), ToolEffect::NonIdempotent);
174/// assert!(tool.validate_input(&json!({ "sku": "PANEL-400" })).is_ok());
175/// assert!(tool.validate_input(&json!({})).is_err());
176/// ```
177pub 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    /// Declares `declaration` for the site at `domain`, executed by `handler`.
197    ///
198    /// # Errors
199    ///
200    /// [`CapabilityDefinitionError`] when the name is invalid or the input schema does not
201    /// compile.
202    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        // A call that may be held answers with the held-call document instead of the output.
227        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    /// The tool origin of a capability of the site at `domain`: `awp:{domain}`.
247    pub fn origin_for(domain: &str) -> String {
248        format!("awp:{domain}")
249    }
250
251    /// Returns the declaration.
252    pub fn declaration(&self) -> &CapabilityV2 {
253        &self.declaration
254    }
255
256    /// Validates `input` against the declared input schema; the input must be an object.
257    ///
258    /// # Errors
259    ///
260    /// The validation messages, at most five.
261    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    /// The amount of a call in minor units, for an `above_amount` approval hint: the
276    /// handler's reading of the input, else the declared price.
277    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    /// The amount of a call as the edge decides it (spec 3.5 §7.4): the handler's
284    /// [`amount`](CapabilityHandler::amount), which may read its store, else the declared
285    /// price.
286    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    /// Runs the handler on validated input.
294    ///
295    /// # Errors
296    ///
297    /// [`CapabilityError`] from the handler, or `schema_validation_failed` for invalid input.
298    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
309/// Converts a capability error into the `AdkError` a tool returns, carrying its AWP code.
310pub 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
332/// Converts a tool error into the AWP error body a requester sees: the AWP code a
333/// capability set, else one inferred from the category, with no internal detail.
334pub 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/// A site's capabilities, by name (spec 3.5 §7.4).
417///
418/// # Example
419///
420/// ```
421/// use std::sync::Arc;
422///
423/// use adk_awp::v2::capability::{CapabilityCall, CapabilityError, CapabilityHandler, CapabilityRegistry, CapabilityTool};
424/// use awp_types::{CapabilityEffect, CapabilityV2, TrustTier};
425/// use serde_json::Value;
426///
427/// struct Noop;
428/// #[async_trait::async_trait]
429/// impl CapabilityHandler for Noop {
430///     async fn handle(&self, call: CapabilityCall) -> Result<Value, CapabilityError> { Ok(call.input) }
431/// }
432///
433/// let mut registry = CapabilityRegistry::new("example.com");
434/// registry.declare(CapabilityV2::new("search_site", "Search", CapabilityEffect::ReadOnly), Arc::new(Noop)).unwrap();
435/// registry
436///     .declare(
437///         CapabilityV2::new("book", "Book a visit", CapabilityEffect::NonIdempotent).with_min_trust(TrustTier::Known),
438///         Arc::new(Noop),
439///     )
440///     .unwrap();
441/// assert_eq!(registry.manifest_for(TrustTier::Public).capabilities.len(), 1);
442/// assert_eq!(registry.manifest_for(TrustTier::Known).capabilities.len(), 2);
443/// ```
444#[derive(Debug, Clone)]
445pub struct CapabilityRegistry {
446    domain: String,
447    tools: BTreeMap<String, Arc<CapabilityTool>>,
448}
449
450impl CapabilityRegistry {
451    /// Creates an empty registry for the site at `domain`.
452    pub fn new(domain: impl Into<String>) -> Self {
453        Self { domain: domain.into(), tools: BTreeMap::new() }
454    }
455
456    /// The site's domain.
457    pub fn domain(&self) -> &str {
458        &self.domain
459    }
460
461    /// Declares a capability executed by `handler`.
462    ///
463    /// # Errors
464    ///
465    /// As [`CapabilityTool::new`], and [`CapabilityDefinitionError::Duplicate`] for a name
466    /// already declared.
467    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    /// Returns capability `name`.
481    pub fn get(&self, name: &str) -> Option<&Arc<CapabilityTool>> {
482        self.tools.get(name)
483    }
484
485    /// Returns capability `name` when a caller of `tier` may see it; a capability above the
486    /// tier is reported exactly as one that does not exist (AWP 2.0 §7.3).
487    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    /// Returns the capabilities as `adk_core::Tool`s, for the A2A and MCP bindings.
492    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    /// Returns the tools a caller of `tier` may see.
497    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    /// The unfiltered manifest: every declaration.
506    pub fn manifest(&self) -> CapabilityManifestV2 {
507        CapabilityManifestV2::new(
508            self.tools.values().map(|tool| tool.declaration().clone()).collect(),
509        )
510    }
511
512    /// The manifest a caller of `tier` sees (spec 3.5 §7.4).
513    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    /// Keeps its totals behind an async lock, as a store would.
539    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    /// The MCP binding's hints and output schema follow the declaration (AWP 2.0 §7.4.3, C10).
604    #[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    /// As an `adk_core::Tool`, the capability reads the caller from the edge's request
648    /// metadata and refuses invalid input with its AWP code.
649    #[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}