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
73 changes: 73 additions & 0 deletions examples/crewai-prepay-check/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
# Example: pre-pay check of an x402 endpoint in a CrewAI agent

A small, runnable [CrewAI](https://docs.crewai.com) example that lets an agent check an x402 paid endpoint **before** anything pays for it. The agent has one tool — the pre-pay check — and no way to pay: it reports the price and the number of fixes, and states whether it would pay.

Nothing is paid: the check sends one request without a payment header, nothing is signed, and no wallet, key or RPC is read or needed.

## Files

| File | What it does |
| --- | --- |
| `tool.py` | CrewAI tool (`Check402Tool`) that runs `npx -y @agent402-dev/pay-server check <url> --json` and returns the JSON to the agent. Non-https URLs are refused before the CLI is started (http is allowed only for `localhost` / `127.0.0.1`, the same exception the check itself makes, so the local test below works). It runs `npx` from a scratch directory so an enclosing npm workspace — this repository is one — cannot shadow the published package. |
| `main.py` | One agent + one task: check the URL given on the command line, then answer with the price, the fixes count, and pay / will-not-pay. The agent's instructions say: do not pay when `fixes > 0`. |
| `broken402.py` | ~20-line local server that answers a broken 402 (its `resource.url` is http), for the local test below. |
| `requirements.txt` | Pinned Python dependency: `crewai==1.15.50`. |

## Install

Needs Python 3.10–3.13, Node 18+ (for `npx`), and an OpenAI API key for the agent's LLM (the check itself needs no key of any kind):

```bash
cd examples/crewai-prepay-check
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt
export OPENAI_API_KEY=... # LLM only
```

## Run

Against a live x402 endpoint:

```bash
python main.py https://<a live x402 endpoint>
```

One live endpoint you can try is the toolkit's own hosted check402 route (0.01 USD per request, USDC on Solana or Base):

```bash
python main.py "https://agent402-check402.agent402-ebc.workers.dev/x402/check402?url=https://example.com"
```

The agent prints its answer with the price and `fixes: 0` when the endpoint's 402 is clean.

Against a local server that answers a broken 402:

```bash
python broken402.py & # http://127.0.0.1:8402/paid
python main.py http://127.0.0.1:8402/paid # the agent says it will not pay
```

The broken 402's payment option is fine but its `resource.url` is http, which is one `fix` finding — and the agent's rule is: do not pay when `fixes > 0`.

## What the tool returns

The CLI's JSON, unchanged:

```json
{
"url": "https://seller.example.com/paid",
"fixes": 0,
"findings": [{ "level": "ok", "code": "price", "message": "accepts[0]: Solana mainnet, 0.002 USDC (amount \"2000\")." }],
"signedOrPaid": false
}
```

- `fixes`: number of findings a buyer will fail on (`null`, with an `error` field, when the request itself failed or the URL was refused).
- `findings`: `fix` first, then `note`, then `ok`; each has `level`, `code`, `message`. The price is the message of the finding with code `price` (USDC amounts are also spelled out there, in USDC and in base units).
- `signedOrPaid`: always `false` — one request, no payment header, nothing signed or paid.

## Versions used

CrewAI 1.15.50 · the check CLI is `@agent402-dev/pay-server` fetched by `npx` (0.15.0 at the time of writing) · model `gpt-5-mini` (OpenAI, via `OPENAI_API_KEY`) · developed on Python 3.12 / Node 24. The author ran the tool against a live endpoint and the local broken-402 server above.

Apache-2.0, same as the repository.
46 changes: 46 additions & 0 deletions examples/crewai-prepay-check/broken402.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
"""A tiny local server that answers a BROKEN x402 402, for testing.

The payment option itself is fine, but resource.url is http, not https —
exactly one "fix" finding (resource_url_http). Run:

python broken402.py # serves http://127.0.0.1:8402/paid
python main.py http://127.0.0.1:8402/paid # the agent says it will not pay
"""

import base64
import json
from http.server import BaseHTTPRequestHandler, HTTPServer

PAYLOAD = {
"x402Version": 2,
"resource": {"url": "http://seller.example.com/paid", "description": "Paid report", "mimeType": "application/json"},
"accepts": [
{
"scheme": "exact",
"network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
"asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
"amount": "2000",
"payTo": "11111111111111111111111111111111",
"maxTimeoutSeconds": 60,
"extra": {"feePayer": "2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4"},
}
],
}
BODY = json.dumps(PAYLOAD).encode()


class Handler(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(402)
self.send_header("PAYMENT-REQUIRED", base64.b64encode(BODY).decode())
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__":
HTTPServer(("127.0.0.1", 8402), Handler).serve_forever()
66 changes: 66 additions & 0 deletions examples/crewai-prepay-check/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
"""CrewAI agent that checks an x402 paid endpoint before anything pays for it.

Usage:
python main.py https://<a live x402 endpoint>
python main.py http://127.0.0.1:8402/paid # with broken402.py running

The agent has exactly one tool (the pre-pay check in tool.py) and no way to
pay: it reports the price and the number of fixes, and states whether it
would pay. It will not pay when fixes > 0.

Needs an OpenAI API key in OPENAI_API_KEY — for the LLM only. The check
itself needs no wallet, key, RPC or paid API key. Model used: gpt-5-mini
(CrewAI 1.15.50, @agent402-dev/pay-server 0.15.0 via npx, Python 3.12).
"""

import sys

from crewai import LLM, Agent, Crew, Process, Task

from tool import Check402Tool

MODEL = "gpt-5-mini"


def main() -> int:
if len(sys.argv) != 2:
print(__doc__)
return 2
url = sys.argv[1]

checker = Agent(
role="Pre-pay checker",
goal=(
"Check an x402 paid endpoint before any payment and report whether paying it would work. "
"Rule: do not pay when fixes > 0."
),
backstory=(
"You are the last stop before an agent wallet spends money. You never pay anything yourself; "
"you run the pre-pay check, read its findings, and give a clear pay / will-not-pay answer. "
"When the check reports fixes > 0 you always say you will not pay. When the check itself fails "
"(fixes is null) you also say you will not pay, because the endpoint could not be checked."
),
tools=[Check402Tool()],
llm=LLM(model=MODEL),
verbose=True,
)
task = Task(
description=(
f"Use the check_x402_endpoint tool to check this paid endpoint before paying it: {url}\n"
"Then answer with: the price it asks (quote the amount from the findings), the number of "
"fixes, and whether you would pay it. Rule: do not pay when fixes > 0 — if fixes is greater "
"than 0, say clearly that you will not pay and name the blocking findings. If the check "
"itself failed (fixes is null), say you will not pay because the endpoint could not be checked."
),
expected_output=(
"The price, the fixes count, and a clear pay / will-not-pay statement with the reason."
),
agent=checker,
)
result = Crew(agents=[checker], tasks=[task], process=Process.sequential).kickoff()
print(result)
return 0


if __name__ == "__main__":
raise SystemExit(main())
1 change: 1 addition & 0 deletions examples/crewai-prepay-check/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
crewai==1.15.50
89 changes: 89 additions & 0 deletions examples/crewai-prepay-check/tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
"""CrewAI tool: check an x402 paid endpoint before anything pays for it.

Runs `npx -y @agent402-dev/pay-server check <url> --json` and returns the
CLI's JSON to the agent: `fixes` (how many findings a buyer will fail on),
`findings` (level/code/message — the price is the message of the finding
with code "price") and `signedOrPaid` (always false). The check sends one
request without a payment header; nothing is signed or paid, no key is read.

Non-https URLs are refused before the CLI is even started. The one
exception is http://localhost and http://127.0.0.1 — the same exception the
check itself makes — so a local test server can be checked.
"""

import json
import subprocess
import tempfile
from urllib.parse import urlsplit

from crewai.tools import BaseTool
from pydantic import BaseModel, Field

CHECK_TIMEOUT_SECONDS = 180 # the first `npx` run downloads the pay-server package


class Check402Input(BaseModel):
url: str = Field(
...,
description="The full https URL of the paid endpoint, exactly as it would be called to pay it.",
)


def _refused(url: str, message: str) -> str:
# Same shape as the check CLI's own error JSON.
return json.dumps(
{"url": url, "fixes": None, "error": message, "findings": [], "signedOrPaid": False},
indent=2,
)


def _url_problem(url: str) -> str | None:
parts = urlsplit(url)
host = (parts.hostname or "").lower()
if parts.scheme == "https" and host:
return None
if parts.scheme == "http" and host in ("localhost", "127.0.0.1"):
return None # local test servers only; the check makes the same exception
return (
"Refused before running the check: only https URLs are checked "
"(http is allowed only for localhost / 127.0.0.1 test servers)."
)


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 reads "
"the HTTP 402 answer: price, network, payTo and what a buyer would fail on. Returns JSON with `fixes` "
"(number of findings a buyer will fail on), `findings` and `signedOrPaid` (always false). Nothing is "
"signed or paid. Use it before any payment, and do not pay when fixes > 0."
)
args_schema: type[BaseModel] = Check402Input

def _run(self, url: str) -> str:
problem = _url_problem(url)
if problem:
return _refused(url, problem)
try:
proc = subprocess.run(
["npx", "-y", "@agent402-dev/pay-server", "check", url, "--json"],
capture_output=True,
text=True,
timeout=CHECK_TIMEOUT_SECONDS,
# Run npx from a scratch directory: inside an npm workspace
# (like this repository itself) npx would resolve the
# workspace's own @agent402-dev/pay-server instead of the
# published package, and its bin does not run from source.
cwd=tempfile.gettempdir(),
)
except FileNotFoundError:
return _refused(url, "npx not found. Node 18+ is needed to run the check.")
except subprocess.TimeoutExpired:
return _refused(url, f"The check did not finish within {CHECK_TIMEOUT_SECONDS} seconds.")
out = proc.stdout.strip()
if not out:
detail = proc.stderr.strip()[:200]
return _refused(url, f"The check printed nothing (exit {proc.returncode}). {detail}")
# Exit 1 from the CLI only means fixes > 0 (or the request failed, which
# the CLI then reports as JSON too) — the JSON is the result either way.
return out