Skip to main content

adk_payments/tools/
toolset.rs

1use std::sync::Arc;
2
3use adk_auth::{ContextScopeResolver, ScopeGuard};
4use adk_core::{SpendLedger, Tool};
5
6use crate::guardrail::PaymentPolicySet;
7#[cfg(doc)]
8use crate::guardrail::SpendLimitGuardrail;
9use crate::kernel::GovernedCheckoutService;
10use crate::kernel::governed::with_spend_limit;
11use crate::kernel::service::{InterventionService, MerchantCheckoutService, TransactionStore};
12
13use super::checkout::{governed_complete_checkout_tool, governed_create_checkout_tool};
14use super::{
15    cancel_checkout_tool, continue_intervention_tool, status_lookup_tool, update_checkout_tool,
16};
17
18/// Builder for the canonical payment toolset.
19///
20/// Produces a set of scope-protected, redaction-safe tools backed by the
21/// commerce kernel service traits. Every tool is wrapped in an `adk-auth`
22/// [`ScopeGuard`], so a call fails unless the caller holds the scopes the tool
23/// declares through `Tool::required_scopes()`. The default guard reads them from
24/// `ToolContext::user_scopes()` ([`ContextScopeResolver`]), which is empty unless a
25/// request context grants scopes.
26///
27/// Checkout creation and completion run through a [`GovernedCheckoutService`]: the
28/// configured [`PaymentPolicySet`] is evaluated on every call, an escalation goes through
29/// the run's tool confirmation flow, and a [`SpendLimitGuardrail`] reserves each
30/// completion against the spend ledger. When the policy set has no spend guardrail, the
31/// toolset adds [`SpendLimitGuardrail::when_configured`], which reserves against
32/// [`with_spend_ledger`](Self::with_spend_ledger) or `RunConfig::spend_ledger`.
33///
34/// # Example
35///
36/// ```rust,ignore
37/// use adk_auth::{ScopeGuard, StaticScopeResolver};
38/// use adk_payments::tools::PaymentToolsetBuilder;
39///
40/// let toolset = PaymentToolsetBuilder::new(checkout_service, transaction_store)
41///     .with_scope_guard(ScopeGuard::new(StaticScopeResolver::new(vec![
42///         "payments:checkout:create".to_string(),
43///     ])))
44///     .build();
45/// ```
46pub struct PaymentToolsetBuilder {
47    checkout_service: Arc<dyn MerchantCheckoutService>,
48    transaction_store: Arc<dyn TransactionStore>,
49    intervention_service: Option<Arc<dyn InterventionService>>,
50    scope_guard: Option<ScopeGuard>,
51    policies: PaymentPolicySet,
52    spend_ledger: Option<Arc<dyn SpendLedger>>,
53    #[cfg(feature = "ap2")]
54    ap2_adapter: Option<Arc<crate::protocol::ap2::Ap2Adapter>>,
55}
56
57impl PaymentToolsetBuilder {
58    /// Creates a new builder with the required checkout and transaction services.
59    #[must_use]
60    pub fn new(
61        checkout_service: Arc<dyn MerchantCheckoutService>,
62        transaction_store: Arc<dyn TransactionStore>,
63    ) -> Self {
64        Self {
65            checkout_service,
66            transaction_store,
67            intervention_service: None,
68            scope_guard: None,
69            policies: PaymentPolicySet::new(),
70            spend_ledger: None,
71            #[cfg(feature = "ap2")]
72            ap2_adapter: None,
73        }
74    }
75
76    /// Enables the intervention continuation tool.
77    #[must_use]
78    pub fn with_intervention_service(
79        mut self,
80        intervention_service: Arc<dyn InterventionService>,
81    ) -> Self {
82        self.intervention_service = Some(intervention_service);
83        self
84    }
85
86    /// Replaces the guard that enforces each tool's declared scopes.
87    ///
88    /// Defaults to `ScopeGuard::new(ContextScopeResolver)`. Supply a guard with a
89    /// different resolver, or one with an audit sink, to change where scopes come
90    /// from or to record each decision.
91    #[must_use]
92    pub fn with_scope_guard(mut self, scope_guard: ScopeGuard) -> Self {
93        self.scope_guard = Some(scope_guard);
94        self
95    }
96
97    /// Evaluates `policies` on every checkout creation and completion.
98    ///
99    /// # Example
100    ///
101    /// ```rust,ignore
102    /// use adk_payments::guardrail::{
103    ///     AmountThresholdGuardrail, MerchantAllowlistGuardrail, PaymentPolicySet,
104    /// };
105    /// use adk_payments::tools::PaymentToolsetBuilder;
106    ///
107    /// let toolset = PaymentToolsetBuilder::new(checkout_service, transaction_store)
108    ///     .with_payment_policies(
109    ///         PaymentPolicySet::new()
110    ///             .with(AmountThresholdGuardrail::new(Some(5_000), Some(10_000)).with_currency("USD", 2))
111    ///             .with(MerchantAllowlistGuardrail::new(["merchant-1"])),
112    ///     )
113    ///     .build();
114    /// ```
115    #[must_use]
116    pub fn with_payment_policies(mut self, policies: PaymentPolicySet) -> Self {
117        self.policies = policies;
118        self
119    }
120
121    /// Reserves completed checkouts against `ledger` instead of `RunConfig::spend_ledger`.
122    #[must_use]
123    pub fn with_spend_ledger(mut self, ledger: Arc<dyn SpendLedger>) -> Self {
124        self.spend_ledger = Some(ledger);
125        self
126    }
127
128    /// Adds the `payments_ap2_payment_submit` tool, which submits AP2 payment mandates
129    /// through `adapter` under the same scope guard as the checkout tools.
130    ///
131    /// The adapter enforces its own payment policies and spend ledger
132    /// ([`Ap2Adapter::with_payment_policies`](crate::protocol::ap2::Ap2Adapter::with_payment_policies));
133    /// see [`ap2_payment_tool`](super::ap2_payment_tool).
134    #[cfg(feature = "ap2")]
135    #[cfg_attr(docsrs, doc(cfg(feature = "ap2")))]
136    #[must_use]
137    pub fn with_ap2_adapter(mut self, adapter: Arc<crate::protocol::ap2::Ap2Adapter>) -> Self {
138        self.ap2_adapter = Some(adapter);
139        self
140    }
141
142    /// Builds the payment toolset containing all configured tools.
143    #[must_use]
144    pub fn build(self) -> PaymentToolset {
145        let mut governed = GovernedCheckoutService::new(
146            self.checkout_service.clone(),
147            with_spend_limit(self.policies),
148        );
149        if let Some(ledger) = self.spend_ledger {
150            governed = governed.with_spend_ledger(ledger);
151        }
152        let governed = Arc::new(governed);
153        let mut tools: Vec<Arc<dyn Tool>> = vec![
154            Arc::new(governed_create_checkout_tool(governed.clone())),
155            Arc::new(update_checkout_tool(self.checkout_service.clone())),
156            Arc::new(governed_complete_checkout_tool(governed)),
157            Arc::new(cancel_checkout_tool(self.checkout_service.clone())),
158            Arc::new(status_lookup_tool(self.transaction_store.clone())),
159        ];
160        if let Some(intervention_service) = self.intervention_service {
161            tools.push(Arc::new(continue_intervention_tool(intervention_service)));
162        }
163        #[cfg(feature = "ap2")]
164        if let Some(adapter) = self.ap2_adapter {
165            tools.push(Arc::new(super::ap2_payment_tool(adapter)));
166        }
167        let scope_guard = self.scope_guard.unwrap_or_else(|| ScopeGuard::new(ContextScopeResolver));
168        PaymentToolset { tools: scope_guard.protect_all(tools) }
169    }
170}
171
172/// A set of agent-facing payment tools backed by the canonical commerce kernel.
173///
174/// Every tool is scope-protected; see [`PaymentToolsetBuilder`].
175pub struct PaymentToolset {
176    tools: Vec<Arc<dyn Tool>>,
177}
178
179impl PaymentToolset {
180    /// Returns all configured payment tools.
181    #[must_use]
182    pub fn tools(&self) -> Vec<Arc<dyn Tool>> {
183        self.tools.clone()
184    }
185}