From 025a1e7ac112dfc504a421746544b2c9d2e40d70 Mon Sep 17 00:00:00 2001 From: riccardocens-code Date: Sat, 5 Dec 2026 11:52:08 +0100 Subject: [PATCH] examples: CrewAI agent checks an x402 endpoint before paying --- examples/crewai-prepay-check/README.md | 87 +++++++++++++++++++ .../crewai-prepay-check/broken_402_server.py | 21 +++++ examples/crewai-prepay-check/main.py | 54 ++++++++++++ examples/crewai-prepay-check/requirements.txt | 2 + examples/crewai-prepay-check/test_tool.py | 32 +++++++ examples/crewai-prepay-check/tool.py | 72 +++++++++++++++ 6 files changed, 268 insertions(+) create mode 100644 examples/crewai-prepay-check/README.md create mode 100644 examples/crewai-prepay-check/broken_402_server.py create mode 100644 examples/crewai-prepay-check/main.py create mode 100644 examples/crewai-prepay-check/requirements.txt create mode 100644 examples/crewai-prepay-check/test_tool.py create mode 100644 examples/crewai-prepay-check/tool.py diff --git a/examples/crewai-prepay-check/README.md b/examples/crewai-prepay-check/README.md new file mode 100644 index 0000000..cf9382f --- /dev/null +++ b/examples/crewai-prepay-check/README.md @@ -0,0 +1,87 @@ +# CrewAI: check an x402 endpoint before paying it + +A CrewAI agent with one custom tool, `check_x402_endpoint`, that runs + +```sh +npx -y @agent402-dev/pay-server@0.15.0 check --json +``` + +and hands the JSON report to the agent. The agent's instructions say: **do not pay when `fixes > 0`**. + +**Nothing is paid:** the check sends one request without a payment header; nothing is signed or paid, and no key or wallet is read. + +## Install + +Needs Python 3.10–3.13 and Node.js 18+ (for `npx`). + +```sh +cd examples/crewai-prepay-check +python -m venv .venv && . .venv/bin/activate +pip install -r requirements.txt +export GEMINI_API_KEY=... # the LLM key for CrewAI; no wallet, RPC or paid API key is needed +``` + +Any CrewAI model works: set `MODEL` (default `gemini/gemini-3.5-flash-lite`), e.g. `MODEL=openai/gpt-4o-mini` with `OPENAI_API_KEY`. + +## Run + +A live x402 endpoint (the toolkit's paid check402 route, 0.01 USDC; it is only checked, not paid): + +```sh +python main.py "https://agent402-check402.agent402-ebc.workers.dev/x402/check402?url=https://example.com" +``` + +``` +price: Solana mainnet, 0.01 USDC (amount "10000"); Base, 0.01 USDC (amount "10000") +fixes: 0 +fix findings: none +decision: will pay. The endpoint has 0 fixes and can be successfully paid by a paying client. +``` + +A local endpoint that answers a broken 402 (its `PAYMENT-REQUIRED` header is not base64 JSON): + +```sh +python broken_402_server.py & +python main.py http://127.0.0.1:4021/paid +``` + +``` +ERROR:root:Google Gemini API error: 503 - This model is currently experiencing high demand. Spikes in demand are usually temporary. Please try again later. +ERROR:crewai.flow.runtime:Error executing listener call_llm_native_tools: 503 UNAVAILABLE. {'error': {'code': 503, 'message': 'This model is currently experiencing high demand. Spikes in demand are usually temporary. Please try again later.', 'status': 'UNAVAILABLE'}} +price: none found (endpoint returned header_undecodable error) +fixes: 1 +fix findings: [ + { + "code": "header_undecodable", + "level": "fix", + "message": "PAYMENT-REQUIRED is not base64 JSON that @x402/core can decode." + } +] +decision: will not pay because fixes > 0 (specifically, the endpoint has configuration/header decoding issues). +``` + +The agent's wording varies from run to run; the decision follows `fixes`. + +## What the tool returns + +The CLI's JSON report, unchanged: + +| Field | Meaning | +| --- | --- | +| `url` | The URL that was checked. | +| `fixes` | Number of `fix` findings: problems a paying client hits. `0` means it can be paid. | +| `findings` | `{level, code, message}` items, `level` is `fix`, `note` or `ok`. The `price` findings give network, asset and amount for each `accepts` option. | +| `signedOrPaid` | Always `false`. | + +Non-https URLs are refused before the CLI is started (`{"fixes": 1, "refused": "..."}`). As in the CLI, plain http is accepted only on `localhost` and `127.0.0.1`, for a local test server. `python -m unittest test_tool.py` checks this without an LLM key. + +## Files + +- `tool.py`: the CrewAI tool (`Check402Tool`) and `run_check402(url)`. +- `main.py`: the agent, its task and the pay rule. +- `broken_402_server.py`: the local broken 402 (standard library only). +- `test_tool.py`: the URL refusal, without npx or an LLM. + +## Versions used + +Run with crewai 1.15.50 (`crewai[google-genai]`, google-genai 1.65.0), model `gemini/gemini-3.5-flash-lite`, Python 3.12.16, Node.js 24.22.1 / npm 11.21.1, `@agent402-dev/pay-server` 0.15.0. diff --git a/examples/crewai-prepay-check/broken_402_server.py b/examples/crewai-prepay-check/broken_402_server.py new file mode 100644 index 0000000..c617a36 --- /dev/null +++ b/examples/crewai-prepay-check/broken_402_server.py @@ -0,0 +1,21 @@ +"""A local endpoint that answers a broken 402, to see the agent refuse to pay. + +Usage: python broken_402_server.py (then: python main.py http://127.0.0.1:4021/paid) +Its PAYMENT-REQUIRED header is not valid base64 JSON, so no x402 client can pay it. +""" + +from http.server import BaseHTTPRequestHandler, HTTPServer + + +class Broken402(BaseHTTPRequestHandler): + def do_GET(self) -> None: + self.send_response(402) + self.send_header("PAYMENT-REQUIRED", "this-is-not-base64-json") + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(b'{"error": "payment required"}') + + +if __name__ == "__main__": + print("Broken 402 on http://127.0.0.1:4021/paid (Ctrl+C to stop)") + HTTPServer(("127.0.0.1", 4021), Broken402).serve_forever() diff --git a/examples/crewai-prepay-check/main.py b/examples/crewai-prepay-check/main.py new file mode 100644 index 0000000..37fcc83 --- /dev/null +++ b/examples/crewai-prepay-check/main.py @@ -0,0 +1,54 @@ +"""Ask a CrewAI agent whether it would pay an x402 endpoint, after checking it. + +Usage: python main.py https:// +""" + +import logging +import os +import sys + +from crewai import LLM, Agent, Crew, Task + +from tool import Check402Tool + +# CrewAI warns on every call that it estimates Gemini token counts; keep the output short. +logging.getLogger("crewai.llms.base_llm").setLevel(logging.ERROR) + + +def main() -> None: + if len(sys.argv) != 2: + sys.exit("usage: python main.py ") + url = sys.argv[1] + + llm = LLM(model=os.environ.get("MODEL", "gemini/gemini-3.5-flash-lite"), temperature=0) + buyer = Agent( + role="Careful API buyer", + goal="Only pay x402 endpoints that a paying client can actually pay.", + backstory=( + "You buy API calls with x402 payments. Before any payment you run the " + "check_x402_endpoint tool on the URL. Rule: do not pay when fixes > 0. " + "You never pay or sign anything yourself; you only decide and explain." + ), + tools=[Check402Tool()], + llm=llm, + allow_delegation=False, + verbose=False, + ) + task = Task( + description=( + f"Check the x402 endpoint {url} with the check_x402_endpoint tool. " + "Then answer: the price it asks (network, asset and amount, from the 'price' findings), " + "the value of fixes, the 'fix' findings if any, and your decision. " + "Do not pay when fixes > 0." + ), + expected_output=( + "A few lines: 'price: ...', 'fixes: N', the fix findings (if any), and " + "'decision: will pay' or 'decision: will not pay' with the reason." + ), + agent=buyer, + ) + print(Crew(agents=[buyer], tasks=[task]).kickoff().raw) + + +if __name__ == "__main__": + main() diff --git a/examples/crewai-prepay-check/requirements.txt b/examples/crewai-prepay-check/requirements.txt new file mode 100644 index 0000000..2507d7e --- /dev/null +++ b/examples/crewai-prepay-check/requirements.txt @@ -0,0 +1,2 @@ +crewai[google-genai]==1.15.50 +google-genai==1.65.0 diff --git a/examples/crewai-prepay-check/test_tool.py b/examples/crewai-prepay-check/test_tool.py new file mode 100644 index 0000000..6565816 --- /dev/null +++ b/examples/crewai-prepay-check/test_tool.py @@ -0,0 +1,32 @@ +"""The tool refuses non-https URLs without starting the CLI (no LLM key needed). + +Run: python -m unittest test_tool.py +""" + +import unittest +from unittest import mock + +import tool + + +class RefuseBeforeCheck(unittest.TestCase): + def test_refused_urls_never_start_npx(self) -> None: + with mock.patch.object(tool.subprocess, "run") as run: + for url in ["http://example.com/paid", "ftp://example.com/x", "not a url", "https://"]: + report = tool.run_check402(url) + self.assertGreater(report["fixes"], 0, url) + self.assertFalse(report["signedOrPaid"]) + run.assert_not_called() + + def test_https_and_local_http_run_the_cli(self) -> None: + done = mock.Mock(stdout='{"fixes": 0, "findings": [], "signedOrPaid": false}', stderr="") + with mock.patch.object(tool.subprocess, "run", return_value=done) as run: + for url in ["https://api.example.com/paid", "http://127.0.0.1:4021/paid"]: + self.assertEqual(tool.run_check402(url)["fixes"], 0) + commands = [call.args[0] for call in run.call_args_list] + self.assertEqual(commands[0], ["npx", "-y", tool.PAY_SERVER, "check", "https://api.example.com/paid", "--json"]) + self.assertEqual(len(commands), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/examples/crewai-prepay-check/tool.py b/examples/crewai-prepay-check/tool.py new file mode 100644 index 0000000..823b13a --- /dev/null +++ b/examples/crewai-prepay-check/tool.py @@ -0,0 +1,72 @@ +"""CrewAI tool: check an x402 endpoint's 402 answer before anything pays it. + +Runs `npx -y @agent402-dev/pay-server check --json`: one request without a +payment header. Nothing is signed or paid, and no key or wallet is read. +""" + +import json +import subprocess +import tempfile +from urllib.parse import urlparse + +from crewai.tools import BaseTool +from pydantic import BaseModel, Field + +PAY_SERVER = "@agent402-dev/pay-server@0.15.0" +# The CLI also accepts plain http on these hosts, for a seller testing locally. +LOCAL_HOSTS = {"127.0.0.1", "localhost"} + + +class Check402Input(BaseModel): + url: str = Field(..., description="The https URL of the paid x402 endpoint.") + + +def url_problem(url: str) -> str | None: + """Why the check is not started for this URL, or None.""" + try: + parsed = urlparse(url) + except ValueError: + return "Not a valid URL." + if not parsed.hostname: + return "Not a valid URL." + if parsed.scheme == "https": + return None + if parsed.scheme == "http" and parsed.hostname in LOCAL_HOSTS: + return None + return "Refused: only https URLs are checked (plain http only on localhost)." + + +def run_check402(url: str, timeout: float = 90) -> dict: + """The CLI's JSON report: url, fixes, findings, signedOrPaid.""" + problem = url_problem(url) + if problem: + # The CLI is not started at all for a refused URL. + return {"url": url, "fixes": 1, "refused": problem, "findings": [], "signedOrPaid": False} + proc = subprocess.run( + ["npx", "-y", PAY_SERVER, "check", url, "--json"], + capture_output=True, + text=True, + timeout=timeout, + check=False, # the CLI exits non-zero when it finds fixes; the JSON is still on stdout + # Outside this repo: here npx would pick the unbuilt workspace package. + cwd=tempfile.gettempdir(), + ) + try: + return json.loads(proc.stdout) + except json.JSONDecodeError: + error = (proc.stderr or proc.stdout).strip()[-500:] + return {"url": url, "fixes": 1, "error": f"check failed: {error}", "findings": [], "signedOrPaid": False} + + +class Check402Tool(BaseTool): + name: str = "check_x402_endpoint" + description: str = ( + "Check an x402 paid endpoint before paying it. Sends one request without a payment " + "header and returns the JSON report: 'fixes' (number of problems a paying client would hit), " + "'findings' (level fix/note/ok with a message; the 'price' findings give network, asset and amount) " + "and 'signedOrPaid' (always false). Nothing is signed or paid. Do not pay when fixes > 0." + ) + args_schema: type[BaseModel] = Check402Input + + def _run(self, url: str) -> str: + return json.dumps(run_check402(url), indent=2)