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
70 changes: 70 additions & 0 deletions examples/crewai-prepay-check/README.md
Original file line number Diff line number Diff line change
@@ -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 <url> --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).
31 changes: 31 additions & 0 deletions examples/crewai-prepay-check/broken402.py
Original file line number Diff line number Diff line change
@@ -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()
77 changes: 77 additions & 0 deletions examples/crewai-prepay-check/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
"""CrewAI example: check 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 # after `python broken402.py`

The agent has one tool (see tool.py): it runs
`npx -y @agent402-dev/pay-server check <url> --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())
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
100 changes: 100 additions & 0 deletions examples/crewai-prepay-check/tool.py
Original file line number Diff line number Diff line change
@@ -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 <url> --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,
}
)