From 40f04cce3ab334034b5e17cd69fde0c1189baafa Mon Sep 17 00:00:00 2001 From: robin09110-collab Date: Sat, 5 Dec 2026 18:55:08 +0900 Subject: [PATCH] Add CrewAI pre-pay check example for x402 endpoints --- examples/crewai-prepay-check/.gitignore | 1 + examples/crewai-prepay-check/README.md | 82 +++++++++++++++ .../crewai-prepay-check/local_broken402.py | 29 ++++++ examples/crewai-prepay-check/main.py | 77 +++++++++++++++ examples/crewai-prepay-check/requirements.txt | 2 + examples/crewai-prepay-check/tool.py | 99 +++++++++++++++++++ 6 files changed, 290 insertions(+) create mode 100644 examples/crewai-prepay-check/.gitignore create mode 100644 examples/crewai-prepay-check/README.md create mode 100644 examples/crewai-prepay-check/local_broken402.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/tool.py diff --git a/examples/crewai-prepay-check/.gitignore b/examples/crewai-prepay-check/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/examples/crewai-prepay-check/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/examples/crewai-prepay-check/README.md b/examples/crewai-prepay-check/README.md new file mode 100644 index 0000000..9ace490 --- /dev/null +++ b/examples/crewai-prepay-check/README.md @@ -0,0 +1,82 @@ +# CrewAI pre-pay check example + +A small, runnable example that lets a CrewAI agent check an x402 paid +endpoint **before** anything pays for it. The agent has one tool — the +pre-pay check — and no wallet and no way to pay. Its instructions say: +do not pay when `fixes > 0`. + +Nothing is paid by this example: the check sends one request without a +payment header, signs nothing, and reads no key. + +## What the tool does + +`tool.py` defines `PrepayCheckTool`, a CrewAI custom tool that runs + +```sh +npx -y @agent402-dev/pay-server check --json +``` + +and returns the CLI's JSON report to the agent: + +- `fixes` — how many things about the endpoint's 402 answer need fixing. +- `findings` — one entry per check (`level`, `code`, `message`), + including the price of each payment option (for example + "Solana mainnet, 0.05 USDC"). +- `signedOrPaid` — always `false` for a check. + +Only https URLs are checked. Plain http is accepted on loopback +(localhost, 127.0.0.1, ::1) so the local test server below can be used — +the same carve-out the CLI itself makes. Any other http URL is refused +by the tool before the CLI is even started. + +## Install + +Needs Python 3.10+ and Node 18+ (for `npx`). + +```sh +python -m venv .venv +. .venv/bin/activate +pip install -r requirements.txt +``` + +CrewAI needs an LLM key in the environment (for example +`OPENAI_API_KEY`). The model defaults to `gpt-4o-mini`; set +`CREWAI_MODEL` to use another model (anything CrewAI/LiteLLM accepts, +for example `ollama/llama3.2:3b` for a local model). + +## Run + +Against a live x402 endpoint (one of the toolkit developer's services, +0.05 USDC per request — the check itself pays nothing): + +```sh +python main.py https://agent402-tx-receipts.agent402-ebc.workers.dev/x402/receipts +``` + +The agent's answer reports the price and `fixes: 0`. + +Against a local server that answers a broken 402: + +```sh +python local_broken402.py # serves http://127.0.0.1:8402/paid +python main.py http://127.0.0.1:8402/paid +``` + +The check reports `fixes: 1` (the `PAYMENT-REQUIRED` header cannot be +decoded) and the agent says it will not pay. + +## Files + +- `tool.py` — the CrewAI custom tool (the check itself). +- `main.py` — one agent, one task: check a URL from the command line + and report price, fixes and verdict. +- `local_broken402.py` — a ~20-line server answering a broken 402, for + the will-not-pay case. +- `requirements.txt` — pinned versions. + +## Versions used to run this example + +- Python 3.12.3, crewai 1.15.50 (see `requirements.txt`) +- Node v24.22.1, `@agent402-dev/pay-server` 0.15.0 (fetched by `npx`) +- Model: see the pull request description for the model the runs were + made with. diff --git a/examples/crewai-prepay-check/local_broken402.py b/examples/crewai-prepay-check/local_broken402.py new file mode 100644 index 0000000..8c3ba2c --- /dev/null +++ b/examples/crewai-prepay-check/local_broken402.py @@ -0,0 +1,29 @@ +"""A tiny local server that answers a deliberately broken 402. + +Run it, then point the example at it: + + python local_broken402.py + python main.py http://127.0.0.1:8402/paid + +The PAYMENT-REQUIRED header is not decodable, so the pre-pay check +reports fixes > 0 and the agent says it will not pay. +""" + +from http.server import BaseHTTPRequestHandler, HTTPServer + + +class Broken402(BaseHTTPRequestHandler): + def do_GET(self): + self.send_response(402) + self.send_header("PAYMENT-REQUIRED", "not-a-valid-payload") + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(b'{"error": "payment required"}') + + def log_message(self, *args): + pass + + +if __name__ == "__main__": + print("Serving a broken 402 on http://127.0.0.1:8402/paid (Ctrl+C to stop)") + HTTPServer(("127.0.0.1", 8402), 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..9949d6b --- /dev/null +++ b/examples/crewai-prepay-check/main.py @@ -0,0 +1,77 @@ +"""Run one CrewAI agent that checks an x402 endpoint before paying it. + +Usage: + python main.py https:// + python main.py http://127.0.0.1:8402/paid # with local_broken402.py + +The agent has only the pre-pay check tool. It has no wallet and no way +to pay: it reports the price and the check findings, and it will not +pay — and says so — whenever the check reports fixes > 0. + +Needs an LLM key for CrewAI in the environment (for example +OPENAI_API_KEY). The model defaults to gpt-4o-mini; set CREWAI_MODEL +to use another one. +""" + +import os +import sys + +from crewai import Agent, Crew, Task + +from tool import PrepayCheckTool + +MODEL = os.environ.get("CREWAI_MODEL", "gpt-4o-mini") + + +def main() -> int: + if len(sys.argv) != 2: + print(__doc__) + return 2 + url = sys.argv[1] + + checker = Agent( + role="x402 payment preflight checker", + goal=( + "Check a paid endpoint with the x402 pre-pay check tool before " + "any payment is considered, and report the price and the " + "verdict. Never pay, and never recommend paying, when the " + "check reports fixes > 0." + ), + backstory=( + "You are a buyer's agent with a strict rule: no endpoint gets " + "paid until the pre-pay check comes back clean. You have no " + "wallet and no payment tool — checking and reporting is all " + "you do. One request without a payment header is all the " + "check sends; nothing is signed or paid." + ), + tools=[PrepayCheckTool()], + llm=MODEL, + verbose=True, + ) + + task = Task( + description=( + f"Run the x402 pre-pay check on {url} and report the result.\n" + "Your report must state:\n" + "1. The price of each payment option the check found " + "(from the findings; say if none was found).\n" + "2. The value of `fixes`.\n" + "3. The verdict: if fixes is 0, the endpoint is payable as " + "listed. If fixes is greater than 0, or the tool refused or " + "errored, state clearly that you will not pay, and list the " + "reasons from the findings." + ), + expected_output=( + "A short report with the price(s), the fixes count, and a " + "clear payable / will-not-pay verdict with reasons." + ), + agent=checker, + ) + + result = Crew(agents=[checker], tasks=[task]).kickoff() + print(result) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/examples/crewai-prepay-check/requirements.txt b/examples/crewai-prepay-check/requirements.txt new file mode 100644 index 0000000..1768a35 --- /dev/null +++ b/examples/crewai-prepay-check/requirements.txt @@ -0,0 +1,2 @@ +crewai==1.15.50 +pydantic==2.12.5 diff --git a/examples/crewai-prepay-check/tool.py b/examples/crewai-prepay-check/tool.py new file mode 100644 index 0000000..f001102 --- /dev/null +++ b/examples/crewai-prepay-check/tool.py @@ -0,0 +1,99 @@ +"""CrewAI tool: check an x402 paid endpoint before anything pays for it. + +The tool runs `npx -y @agent402-dev/pay-server check --json` and +returns the CLI's JSON report to the agent: how many things need fixing +(`fixes`), the per-item `findings` (including the price of each payment +option) and `signedOrPaid` (always false — the check sends one request +without a payment header; nothing is signed or paid, and no key is read). + +Only https URLs are checked. Plain http is accepted on loopback hosts +(localhost, 127.0.0.1, ::1) so a local test server can be checked, the +same carve-out the CLI itself makes; any other http URL is refused +before the CLI is even started. +""" + +import json +import subprocess +import tempfile +from urllib.parse import urlparse + +from crewai.tools import BaseTool +from pydantic import BaseModel, Field + +PAY_SERVER_PACKAGE = "@agent402-dev/pay-server" +LOOPBACK_HOSTS = {"localhost", "127.0.0.1", "::1"} +CHECK_TIMEOUT_SECONDS = 120 + + +class PrepayCheckInput(BaseModel): + url: str = Field(..., description="The full URL of the x402 paid endpoint to check.") + + +def _checkable(url: str) -> bool: + parsed = urlparse(url) + if parsed.scheme == "https" and parsed.hostname: + return True + return parsed.scheme == "http" and (parsed.hostname or "") in LOOPBACK_HOSTS + + +class PrepayCheckTool(BaseTool): + name: str = "x402 pre-pay check" + description: str = ( + "Check an x402 paid endpoint BEFORE paying it. Runs the agent402 " + "pay-server check and returns its JSON report: `fixes` (how many " + "things are broken), `findings` (one entry per check, including " + "the price of each payment option) and `signedOrPaid` (always " + "false). The check sends one request without a payment header: " + "nothing is signed or paid and no key is read. If `fixes` is " + "greater than 0 the endpoint must not be paid." + ) + args_schema: type[BaseModel] = PrepayCheckInput + + def _run(self, url: str) -> str: + if not _checkable(url): + return json.dumps( + { + "url": url, + "refused": True, + "reason": ( + "Only https URLs are checked (http is allowed on " + "loopback for local testing). The check was not " + "started; nothing was requested, signed or paid." + ), + } + ) + try: + proc = subprocess.run( + ["npx", "-y", PAY_SERVER_PACKAGE, "check", url, "--json"], + capture_output=True, + text=True, + timeout=CHECK_TIMEOUT_SECONDS, + # Run npx from a neutral directory: inside an npm + # workspaces repo, npx would resolve the package to the + # local workspace instead of the published one. + cwd=tempfile.gettempdir(), + ) + except FileNotFoundError: + return json.dumps( + { + "url": url, + "error": "npx not found: Node 18+ is required to run the check.", + } + ) + except subprocess.TimeoutExpired: + return json.dumps( + {"url": url, "error": f"Check timed out after {CHECK_TIMEOUT_SECONDS}s."} + ) + # Exit code 1 from the CLI means "fixes found"; the JSON report is + # still on stdout and is the result the agent needs. + try: + report = json.loads(proc.stdout) + except json.JSONDecodeError: + return json.dumps( + { + "url": url, + "error": "The check produced no JSON report.", + "stderr": proc.stderr.strip()[-500:], + } + ) + return json.dumps(report)