Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions contributing/samples/checkout_guard/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
# Checkout guard plugin for Google ADK

A pre-payment check for shopping agents. Register the tool that moves money,
and the plugin reads the merchant's checkout right before that tool runs. It
blocks the payment, or asks the shopper through ADK tool confirmation, when
the checkout holds something the shopper did not agree to:

* a total over the shopper's limit, a changed total, or parts that do not add
up to the total,
* a subscription or a free trial that turns into a paid plan,
* an item, quantity, tip or gift wrap the shopper did not ask for,
* fees that appear only at checkout,
* a merchant, ship-to postal code or approval that does not match,
* checkout text that gives instructions to the AI, or hides text from the
shopper.

Every check is plain Python: regular expressions and arithmetic, no model
call and no network call, so text a merchant writes in the checkout cannot
talk its way past it. It reads checkouts from the
[Agentic Commerce Protocol](https://github.com/agentic-commerce-protocol/agentic-commerce-protocol)
(spec 2026-04-17) and the
[Universal Commerce Protocol](https://github.com/Universal-Commerce-Protocol/ucp),
including UCP purchase options. The 21 rules are a Python port of
[Fine Print](https://github.com/frostyhand/fine-print) and keep its rule ids.

## Usage

```python
from google.adk.apps import App
from google.adk_community.plugins.checkout_guard import (
CheckoutGuardPlugin, MandateItem, ShopperMandate, from_acp,
)

async def load_checkout(args, tool_context):
# Fetch the checkout from the merchant. Do not trust a copy from the model.
session = await merchant.get_checkout_session(args["checkout_id"])
return from_acp(session, merchant="shop.example")

guard = CheckoutGuardPlugin(
payment_tools={"complete_checkout": load_checkout},
mandate=ShopperMandate(
max_total=12000, # minor units: $120.00, all in
currency="USD",
items=(MandateItem("grinder", max_quantity=1),),
allowed_merchants=("shop.example",),
ship_to_postal_code="94110",
),
)

app = App(name="shop", root_agent=agent, plugins=[guard])
```

To set the mandate per shopper or per session, put
`ShopperMandate(...).to_dict()` in session state under
`checkout_guard:mandate`. A mandate in state takes precedence over the one
passed to the plugin.

## What the agent sees

* **block**: the tool does not run. The call is answered with
`checkout_guard.summary`, the findings, and `suggested_fixes` when there is
a safe change (remove a pre-selected line, switch a line to its one-time
purchase option).
* **confirm**: the plugin calls `tool_context.request_confirmation` with the
summary as the hint and the verdict as the payload. When the shopper
approves, the checkout is loaded and checked again, and the tool runs only
if nothing changed since the shopper saw it. A rejected or stale approval
does not pay.
* **allow**: the tool runs.

A missing mandate or a checkout that cannot be loaded blocks the payment.

## Run the sample

The sample merchant has three checkouts: `cs_clean` (pays), `cs_tip` (asks
the shopper about a $3.00 tip) and `cs_addon` (blocked: a pre-selected
protection plan puts the total over budget).

```bash
export GOOGLE_API_KEY=...
cd contributing/samples/checkout_guard
python main.py cs_tip
python main.py cs_addon
```

Or open it in the dev UI with `adk web contributing/samples/checkout_guard`.

The rules point at the kinds of practices consumer rules target. A finding
does not mean a merchant broke a law, and a clean result does not mean a
checkout is compliant.
88 changes: 88 additions & 0 deletions contributing/samples/checkout_guard/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""Runs the shop agent against each demo checkout from the console.

Usage: python main.py [cs_clean|cs_tip|cs_addon] [--yes|--no]

Needs a Gemini API key (GOOGLE_API_KEY). When the guard asks the shopper,
the answer comes from --yes or --no, or from the keyboard.
"""

from __future__ import annotations

import asyncio
import sys

from google.adk.runners import InMemoryRunner
from google.adk.tools.tool_confirmation import ToolConfirmation
from google.genai import types
from shop_agent.agent import app
from shop_agent.agent import ORDERS


async def main(checkout_id: str, answer: str | None) -> None:
runner = InMemoryRunner(app=app)
session = await runner.session_service.create_session(
app_name=app.name, user_id="shopper"
)
message = types.Content(
role="user",
parts=[
types.Part(text=f"Please buy the grinder in checkout {checkout_id}.")
],
)
while message is not None:
pending = None
async for event in runner.run_async(
user_id="shopper", session_id=session.id, new_message=message
):
for call in event.get_function_calls():
print(f"[tool call] {call.name}({call.args})")
if call.name == "adk_request_confirmation":
pending = call
for response in event.get_function_responses():
print(f"[tool result] {response.name}: {response.response}")
if event.content and event.content.parts:
text = "".join(p.text or "" for p in event.content.parts)
if text.strip():
print(f"[{event.author}] {text.strip()}")
message = None
if pending is not None:
print("\n" + pending.args["toolConfirmation"]["hint"] + "\n")
reply = answer or input("Approve this payment? [y/N] ")
confirmed = reply.strip().lower() in ("y", "yes", "--yes")
print(f"[shopper] {'approved' if confirmed else 'rejected'}")
message = types.Content(
role="user",
parts=[
types.Part(
function_response=types.FunctionResponse(
id=pending.id,
name=pending.name,
response=ToolConfirmation(
confirmed=confirmed
).model_dump(),
)
)
],
)
print(f"\nOrders placed: {ORDERS or 'none'}")


if __name__ == "__main__":
args = sys.argv[1:]
flag = next((a for a in args if a in ("--yes", "--no")), None)
ids = [a for a in args if not a.startswith("--")]
asyncio.run(main(ids[0] if ids else "cs_tip", flag))
15 changes: 15 additions & 0 deletions contributing/samples/checkout_guard/shop_agent/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from . import agent
155 changes: 155 additions & 0 deletions contributing/samples/checkout_guard/shop_agent/agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,155 @@
# Copyright 2026 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""A shopping agent whose payment tool is guarded by CheckoutGuardPlugin.

The merchant is an in-memory stand-in for an Agentic Commerce Protocol
merchant with three checkout sessions:

* ``cs_clean``: one burr grinder, nothing unusual. The payment goes through.
* ``cs_tip``: the merchant added a $3.00 tip. The shopper is asked first.
* ``cs_addon``: a protection plan was pre-selected and the total is over
budget. The payment is blocked.
"""

from __future__ import annotations

import copy
import os
from typing import Any

from google.adk.agents import Agent
from google.adk.apps import App
from google.adk.tools.tool_context import ToolContext

from google.adk_community.plugins.checkout_guard import CheckoutGuardPlugin
from google.adk_community.plugins.checkout_guard import from_acp
from google.adk_community.plugins.checkout_guard import MandateItem
from google.adk_community.plugins.checkout_guard import ShopperMandate

MERCHANT = "shop.example"


def _session(checkout_id: str, extra_lines=(), extra_totals=()) -> dict:
lines = [
{
"id": "li_1",
"item": {"id": "GRINDER-1", "quantity": 1},
"name": "Burr coffee grinder",
"quantity": 1,
"unit_amount": 8900,
"totals": [
{"type": "subtotal", "display_text": "Subtotal", "amount": 8900},
{"type": "total", "display_text": "Total", "amount": 8900},
],
},
*extra_lines,
]
subtotal = sum(li["unit_amount"] * li["quantity"] for li in lines)
totals = [
{"type": "subtotal", "display_text": "Subtotal", "amount": subtotal},
{"type": "fulfillment", "display_text": "Shipping", "amount": 599},
{"type": "tax", "display_text": "Tax", "amount": 790},
*extra_totals,
]
total = sum(t["amount"] for t in totals)
return {
"id": checkout_id,
"status": "ready_for_payment",
"currency": "usd",
"line_items": lines,
"fulfillment_details": {"address": {"postal_code": "94110"}},
"totals": [
*totals,
{"type": "total", "display_text": "Total", "amount": total},
],
}


SESSIONS: dict[str, dict] = {
"cs_clean": _session("cs_clean"),
"cs_tip": _session(
"cs_tip",
extra_totals=[{"type": "tip", "display_text": "Tip", "amount": 300}],
),
"cs_addon": _session(
"cs_addon",
extra_lines=[{
"id": "li_2",
"item": {"id": "PLAN-3Y", "quantity": 1},
"name": "3-year protection plan",
"quantity": 1,
"unit_amount": 2999,
"totals": [
{"type": "total", "display_text": "Total", "amount": 2999}
],
}],
),
}

ORDERS: list[str] = []


def get_checkout(checkout_id: str) -> dict:
"""Returns the merchant's checkout session.

Args:
checkout_id: The checkout session id, for example cs_clean.
"""
return SESSIONS.get(checkout_id) or {"error": f"No checkout {checkout_id}."}


def complete_checkout(checkout_id: str) -> dict:
"""Pays for a checkout session. This charges the shopper.

Args:
checkout_id: The checkout session id.
"""
ORDERS.append(checkout_id)
return {"status": "completed", "order_id": f"ord_{len(ORDERS)}"}


async def load_checkout(args: dict[str, Any], tool_context: ToolContext):
"""Fetches the checkout from the merchant, not from the model's arguments."""
del tool_context
session = SESSIONS.get(args.get("checkout_id", ""))
if session is None:
raise KeyError(args.get("checkout_id"))
return from_acp(copy.deepcopy(session), merchant=MERCHANT)


checkout_guard = CheckoutGuardPlugin(
payment_tools={"complete_checkout": load_checkout},
mandate=ShopperMandate(
max_total=12000,
currency="USD",
items=(MandateItem("grinder", max_quantity=1),),
allowed_merchants=(MERCHANT,),
ship_to_postal_code="94110",
),
)

root_agent = Agent(
name="shop_agent",
model=os.environ.get("ADK_MODEL", "gemini-flash-latest"),
instruction=(
"You buy things for the shopper. Look at the checkout with"
" get_checkout, then pay with complete_checkout. If the payment is"
" blocked, tell the shopper what is wrong in plain words and do not"
" try to pay again."
),
tools=[get_checkout, complete_checkout],
)

app = App(name="shop_agent", root_agent=root_agent, plugins=[checkout_guard])
4 changes: 4 additions & 0 deletions src/google/adk_community/plugins/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@
from google.adk_community.plugins.agent_governance_plugin import (
AgentGovernancePlugin,
)
from google.adk_community.plugins.checkout_guard import CheckoutGuardPlugin
from google.adk_community.plugins.checkout_guard import ShopperMandate
from google.adk_community.plugins.taxonomy import (
DefaultSkillPolicy,
SkillPolicy,
Expand All @@ -27,7 +29,9 @@

__all__ = [
"AgentGovernancePlugin",
"CheckoutGuardPlugin",
"DefaultSkillPolicy",
"ShopperMandate",
"SkillPolicy",
"TaxonomyPipeline",
"TaxonomyPlugin",
Expand Down
Loading