From d2e23ac876f80229ffbe28e12a246fd327a2ea22 Mon Sep 17 00:00:00 2001 From: IlhamEl777 Date: Sat, 5 Dec 2026 09:57:43 +0000 Subject: [PATCH] Add CrewAI example: pre-pay check of an x402 endpoint Custom CrewAI tool that runs `pay-server check --json` before anything pays: returns fixes/findings/price to the agent, refuses non-https URLs before starting the CLI, and the agent's instructions say do not pay when fixes > 0. Includes a local broken-402 server for the negative demo. Nothing is signed or paid. --- examples/crewai-prepay-check/README.md | 70 ++++++++++++ examples/crewai-prepay-check/broken402.py | 31 ++++++ examples/crewai-prepay-check/main.py | 77 ++++++++++++++ examples/crewai-prepay-check/requirements.txt | 1 + examples/crewai-prepay-check/tool.py | 100 ++++++++++++++++++ 5 files changed, 279 insertions(+) create mode 100644 examples/crewai-prepay-check/README.md create mode 100644 examples/crewai-prepay-check/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/README.md b/examples/crewai-prepay-check/README.md new file mode 100644 index 0000000..b76a871 --- /dev/null +++ b/examples/crewai-prepay-check/README.md @@ -0,0 +1,70 @@ +# Example: pre-pay check of an x402 endpoint in a CrewAI agent + +A CrewAI agent that checks an x402 paid endpoint **before** anything pays for it. The agent has one custom tool that runs the toolkit's checker CLI, reads the price and the number of fixes, and follows one rule: **do not pay when `fixes > 0`**. + +Nothing is paid by this example. There is no wallet, key or RPC here — the check is the whole point: a buying agent should only reach for its wallet after a check like this comes back with `fixes: 0`. + +## Files + +| File | What it does | +| --- | --- | +| `tool.py` | The CrewAI custom tool (`check_x402_endpoint`). Runs `npx -y @agent402-dev/pay-server check --json` and returns the JSON report to the agent. Refuses non-https URLs before the CLI is even started (http is allowed for localhost, for the local demo below — the CLI makes the same exception). | +| `main.py` | Builds one agent with that tool and one task: check the URL given on the command line and answer with the price, the fixes count, and a pay / will-not-pay decision. | +| `broken402.py` | A ~20-line local server that answers a broken 402 (no `PAYMENT-REQUIRED` header), for the negative demo. | + +## Install + +Needs Python 3.10+ and Node 18+ (for `npx`). + +```sh +cd examples/crewai-prepay-check +python -m venv .venv && source .venv/bin/activate +pip install -r requirements.txt +``` + +The agent needs an LLM key for CrewAI — set `OPENAI_API_KEY`, or point CrewAI at another provider. To pick the model explicitly, set `CREWAI_EXAMPLE_MODEL` (for example `CREWAI_EXAMPLE_MODEL=gpt-4o-mini`). No wallet, payment key or RPC is needed. + +## Run it against a live x402 endpoint + +The toolkit developer's hosted check route is itself a live x402 endpoint (0.01 USDC on Solana and Base), so it works as the demo target: + +```sh +python main.py "https://agent402-check402.agent402-ebc.workers.dev/x402/check402?url=https://example.com" +``` + +The agent's answer names the price from the report and `fixes: 0`: + +```json +{ + "url": "https://agent402-check402.agent402-ebc.workers.dev/x402/check402?url=https://example.com", + "fixes": 0, + "findings": [ + { "level": "ok", "code": "price", "message": "accepts[0]: Solana mainnet, 0.01 USDC (amount \"10000\")." }, + { "level": "ok", "code": "price", "message": "accepts[1]: Base, 0.01 USDC (amount \"10000\")." } + ], + "signedOrPaid": false +} +``` + +## Run it against a broken 402 + +```sh +python 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` (`HTTP 402 without a PAYMENT-REQUIRED header`), and the agent says it will not pay. + +## What the tool returns + +The CLI's JSON report, passed through untouched: + +- `fixes` — how many findings are level `fix`. Anything above 0 means a buyer's agent cannot pay as-is, and this agent refuses to pay. +- `findings` — one entry per check (`level`: `fix` / `note` / `ok`, a `code`, and a `message`). The price appears in the `price` findings when the endpoint answers a readable 402. +- `signedOrPaid` — always `false` here: the check sends one request with no payment header, and nothing is signed or paid. + +If the URL is not https (and not localhost), the tool refuses before starting the CLI and returns an `error` report with `fixes: null` instead. + +## Versions used + +Python 3.12.3, CrewAI 1.15.50 (pinned in `requirements.txt`), Node v24.22.1, `@agent402-dev/pay-server` 0.15.0 (fetched by `npx -y` at run time). diff --git a/examples/crewai-prepay-check/broken402.py b/examples/crewai-prepay-check/broken402.py new file mode 100644 index 0000000..1c95244 --- /dev/null +++ b/examples/crewai-prepay-check/broken402.py @@ -0,0 +1,31 @@ +"""A local server that answers a broken 402, for the negative demo. + +It replies HTTP 402 with a plain JSON error body and no PAYMENT-REQUIRED +header, so the checker reports fixes > 0 and the agent refuses to pay. + +Run: python broken402.py (listens on http://127.0.0.1:8402/paid) +Then: python main.py http://127.0.0.1:8402/paid +""" + +import http.server +import json + +PORT = 8402 + + +class Broken402Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + body = json.dumps({"error": "payment required"}).encode() + self.send_response(402) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *args): + pass + + +if __name__ == "__main__": + print(f"Broken 402 server on http://127.0.0.1:{PORT}/paid (Ctrl+C to stop)") + http.server.HTTPServer(("127.0.0.1", PORT), Broken402Handler).serve_forever() diff --git a/examples/crewai-prepay-check/main.py b/examples/crewai-prepay-check/main.py new file mode 100644 index 0000000..f1a2109 --- /dev/null +++ b/examples/crewai-prepay-check/main.py @@ -0,0 +1,77 @@ +"""CrewAI example: check an x402 paid endpoint before anything pays for it. + +Usage: + python main.py https:// + python main.py http://127.0.0.1:8402/paid # after `python broken402.py` + +The agent has one tool (see tool.py): it runs +`npx -y @agent402-dev/pay-server check --json`, which sends one request +with no payment header. The agent reports the price and the number of fixes, +and its instructions are explicit: do not pay when `fixes > 0`. This example +never pays anything itself — there is no wallet, key or RPC here — the check +is the whole point: a buying agent should only reach for its wallet after a +check like this comes back with `fixes: 0`. + +Needs an LLM key for CrewAI (set OPENAI_API_KEY, or point CrewAI at another +provider). The model is read from CREWAI_EXAMPLE_MODEL when set, else CrewAI's +default is used. +""" + +import os +import sys + +from crewai import Agent, Crew, Process, Task + +from tool import Check402Tool + +AGENT_INSTRUCTIONS = ( + "You check x402 paid endpoints before any payment is made. " + "Always run the check tool on the URL first and base your answer only on its JSON report. " + "Report the price from the findings when the report has one. " + "If 'fixes' is greater than 0, say clearly that you will NOT pay this endpoint and list " + "what has to be fixed. If 'fixes' is 0, say the endpoint answers a payable 402 at the " + "reported price. Either way, state that this check signed and paid nothing " + "('signedOrPaid' is false). If the report has an 'error', say the check could not be " + "completed and quote the error." +) + + +def build_crew(url: str) -> Crew: + model = os.environ.get("CREWAI_EXAMPLE_MODEL") + checker = Agent( + role="x402 Pre-Pay Checker", + goal="Check an x402 paid endpoint and say whether a buyer's agent could pay it, and at what price.", + backstory=AGENT_INSTRUCTIONS, + tools=[Check402Tool()], + verbose=True, + **({"llm": model} if model else {}), + ) + task = Task( + description=( + f"Check this x402 paid endpoint before anything pays for it: {url}\n" + "Use the check tool on exactly that URL, then answer with: the price (if the " + "report shows one), the number of fixes, whether you would pay it or refuse to " + "pay it, and confirmation that nothing was signed or paid." + ), + expected_output=( + "A short answer naming the price, the fixes count, a clear pay / will-not-pay " + "decision that follows the fixes count, and the line that nothing was signed or paid." + ), + agent=checker, + ) + return Crew(agents=[checker], tasks=[task], process=Process.sequential, verbose=True) + + +def main() -> int: + if len(sys.argv) != 2: + print(__doc__) + return 2 + url = sys.argv[1] + result = build_crew(url).kickoff() + print("\n=== Agent answer ===") + 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..def16be --- /dev/null +++ b/examples/crewai-prepay-check/requirements.txt @@ -0,0 +1 @@ +crewai==1.15.50 diff --git a/examples/crewai-prepay-check/tool.py b/examples/crewai-prepay-check/tool.py new file mode 100644 index 0000000..3d7edb7 --- /dev/null +++ b/examples/crewai-prepay-check/tool.py @@ -0,0 +1,100 @@ +"""CrewAI custom tool: check an x402 paid endpoint before anything pays for it. + +The tool runs the toolkit's own checker CLI: + + npx -y @agent402-dev/pay-server check --json + +That sends exactly one request to the endpoint, without a payment header. +Nothing is signed or paid and no key is read. The tool returns the CLI's JSON +report to the agent: `fixes` (how much must be fixed before a buyer's agent +could pay), `findings` (one entry per thing checked, with the price in the +`price` findings when the endpoint answers a readable 402), and +`signedOrPaid: false`. + +Non-https URLs are refused before the CLI is even started. The one exception +is localhost / 127.0.0.1 over http, so the local broken-402 demo in this +folder can run — the CLI makes the same exception. +""" + +import json +import shutil +import subprocess +from urllib.parse import urlparse + +from crewai.tools import BaseTool +from pydantic import BaseModel, Field + +LOCAL_HOSTS = {"localhost", "127.0.0.1"} +CHECK_TIMEOUT_SECONDS = 180 + + +class Check402Input(BaseModel): + url: str = Field(..., description="The https URL of the x402 paid endpoint to check.") + + +class Check402Tool(BaseTool): + name: str = "check_x402_endpoint" + description: str = ( + "Check an x402 paid endpoint BEFORE paying it. Sends one request with no " + "payment header, signs and pays nothing, and returns a JSON report with " + "'fixes' (number of problems that would stop a buyer's agent from paying), " + "'findings' (including the price when the 402 is readable) and " + "'signedOrPaid': false. Use this on any paid URL before deciding to pay." + ) + args_schema: type[BaseModel] = Check402Input + + def _run(self, url: str) -> str: + parsed = urlparse(url) + if parsed.scheme != "https" and parsed.hostname not in LOCAL_HOSTS: + # Refuse before starting the CLI, as the issue requires. + return json.dumps( + { + "url": url, + "fixes": None, + "error": "Refused: only https URLs are checked " + "(http is allowed for localhost demos only). Nothing was requested.", + "findings": [], + "signedOrPaid": False, + } + ) + if shutil.which("npx") is None: + return json.dumps( + { + "url": url, + "fixes": None, + "error": "npx not found. Install Node 18+ so the checker CLI can run.", + "findings": [], + "signedOrPaid": False, + } + ) + try: + proc = subprocess.run( + ["npx", "-y", "@agent402-dev/pay-server", "check", url, "--json"], + capture_output=True, + text=True, + timeout=CHECK_TIMEOUT_SECONDS, + ) + except subprocess.TimeoutExpired: + return json.dumps( + { + "url": url, + "fixes": None, + "error": f"Check timed out after {CHECK_TIMEOUT_SECONDS}s.", + "findings": [], + "signedOrPaid": False, + } + ) + out = (proc.stdout or "").strip() + # The CLI prints its JSON report on stdout even when the endpoint has + # fixes; pass it through untouched so the agent reads the real fields. + if out: + return out + return json.dumps( + { + "url": url, + "fixes": None, + "error": (proc.stderr or "").strip() or f"Checker exited with {proc.returncode}.", + "findings": [], + "signedOrPaid": False, + } + )