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
86 changes: 86 additions & 0 deletions examples/crewai-prepay-check/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
# CrewAI: check an x402 endpoint before the agent pays

A CrewAI agent with one tool, `prepay_check`. It reads an x402 endpoint's 402 the way a buyer's
agent reads it, reports the price and the number of fixes, and does not pay when `fixes > 0`.

The tool runs the free pay-server check:

```
npx -y @agent402-dev/pay-server check <url> --json
```

That is one GET to the URL without a payment header. **Nothing is signed or paid, no wallet or key
is read, and the agent has no payment tool.** No wallet, RPC or paid API key is needed.

The tool runs the check outside any Node project: `npx` would otherwise run a local package with
the same name (this repository has one) instead of the published check.

## What the tool returns

The CLI's JSON, unchanged: `fixes` (how many findings stop a buyer), `findings` (each `ok`, `note`
or `fix`), and the USDC amounts the endpoint asks. Against a live x402 endpoint (`fixes: 0`):

```json
{
"url": "https://…/x402/check402?url=…",
"fixes": 0,
"findings": [
{ "level": "ok", "code": "price", "message": "accepts[0]: Solana mainnet, 0.01 USDC (amount \"10000\")." }
],
"signedOrPaid": false
}
```

(findings abridged.)

The agent is told to answer with the price and `Pay: yes/no`, and never `yes` when `fixes > 0` or
when the check itself failed. It refuses URLs that are not https before starting the check; http is
allowed only on `127.0.0.1`/`localhost`, the same rule the CLI applies.

## Install and run

Needs Python 3.10-3.13 (CrewAI does not support 3.14 yet) and Node.js 18+ for `npx`.

```
python -m venv .venv
.venv/bin/pip install -r requirements.txt # Windows: .venv\Scripts\pip install -r requirements.txt
```

Point it at a live x402 endpoint, for example the toolkit's own paid check route (0.01 USD; the
check still sends no payment):

```
export OPENAI_API_KEY=… # Windows: set OPENAI_API_KEY=…
python main.py "https://agent402-check402.agent402-ebc.workers.dev/x402/check402?url=https%3A%2F%2Fexample.com"
```

To see the agent refuse, start the local server that answers a broken 402 (402 with no
`PAYMENT-REQUIRED` header) in another terminal:

```
python broken_402_server.py
python main.py http://127.0.0.1:8402/paid
```

The check reports one fix (`header_missing`), so the agent answers `Pay: no` and names the fix.

## Model

`MODEL` picks the LiteLLM model, default `gpt-4o-mini` (with `OPENAI_API_KEY` set). Any provider
LiteLLM supports works, with that provider's key in the environment:

```
MODEL=anthropic/claude-3-5-haiku-latest python main.py https://…
```

The example turns CrewAI's trace upload off (`CREWAI_TRACING_ENABLED=false`), so a run sends
nothing but the one check request.

## Ran and verified

- `crewai==1.15.50`, Node.js 24.15.0, npm 11.12.1, Python 3.12.10 on Windows 11.
- `prepay_check` against the live check route above: `fixes: 0`, price `0.01 USDC`; against
`broken_402_server.py`: `fixes: 1`, `header_missing`.
- The CrewAI agent loop (tool call, JSON back to the agent, final answer) was run against a local
OpenAI-compatible stub in place of a hosted model: no hosted model key was available on this
machine. Run it with your own model to see a hosted model's wording; the tool output is the same.
23 changes: 23 additions & 0 deletions examples/crewai-prepay-check/broken_402_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
"""A local endpoint with a broken 402: it answers 402 but sends no PAYMENT-REQUIRED header.

python broken_402_server.py

The check reports one fix (header_missing), so the agent says it will not pay.
"""

from http.server import BaseHTTPRequestHandler, HTTPServer

PORT = 8402


class Broken402(BaseHTTPRequestHandler):
def do_GET(self):
self.send_response(402)
self.send_header("Content-Type", "text/plain")
self.end_headers()
self.wfile.write(b"payment required\n")


if __name__ == "__main__":
print(f"broken 402 at http://127.0.0.1:{PORT}/paid (Ctrl+C stops it)")
HTTPServer(("127.0.0.1", PORT), Broken402).serve_forever()
58 changes: 58 additions & 0 deletions examples/crewai-prepay-check/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
"""Run a CrewAI agent that checks an x402 endpoint before paying it.

python main.py https://your-endpoint.example.com/paid

The agent has one tool, prepay_check, and no way to pay: it reads the 402 the way a buyer's
agent reads it, reports the price and the number of fixes, and refuses to pay when fixes > 0.
One request without a payment header; nothing is signed or paid.
"""

import os
import sys

# The example sends no traces: one request to the endpoint, then the answer.
os.environ.setdefault("CREWAI_TRACING_ENABLED", "false")

from crewai import Agent, Crew, LLM, Task # noqa: E402

from tool import PrePayCheckTool


def main() -> None:
if len(sys.argv) != 2:
sys.exit("usage: python main.py <https URL of a paid x402 endpoint>")
url = sys.argv[1]
model = os.environ.get("MODEL", "gpt-4o-mini")

agent = Agent(
role="Buyer agent for x402 APIs",
goal=(
"Decide from an endpoint's 402 whether it is safe to pay. "
"Never pay when the check reports fixes, and never pay when the check itself failed."
),
backstory=(
"You pay for APIs on behalf of a user. Before anything pays, you run prepay_check: "
"one request without a payment header, nothing signed, nothing paid, no key read. "
"Its JSON has `fixes` (things that stop a buyer), `findings`, and the USDC amounts. "
"You have no payment tool; the check is all you can do."
),
tools=[PrePayCheckTool()],
llm=LLM(model=model),
verbose=False,
)
task = Task(
description=(
f"Check {url} with prepay_check. Then answer with exactly two lines:\n"
"Price: <the USDC amount the endpoint asks, or 'unknown'>\n"
"Pay: <yes or no>\n"
"Add one sentence on the fixes. Say Pay: no when fixes > 0 or when the check returned an error."
),
expected_output="Two lines, Price: and Pay:, then one sentence on the fixes.",
agent=agent,
)
crew = Crew(agents=[agent], tasks=[task])
print(crew.kickoff().raw)


if __name__ == "__main__":
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
102 changes: 102 additions & 0 deletions examples/crewai-prepay-check/tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,102 @@
"""A CrewAI tool that reads an x402 endpoint's 402 before anything pays for it.

It runs the free pay-server check (one request, no payment header, nothing signed or paid,
no key read) and hands the JSON to the agent: `fixes`, `findings`, and the amounts.
"""

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

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

CHECK_TIMEOUT_SECONDS = 120
LOCAL_HOSTS = ("127.0.0.1", "localhost")


class PrePayCheckInput(BaseModel):
url: str = Field(description="The https URL of the paid x402 endpoint to check.")


def check_url(url: str) -> str:
"""Return the pay-server check JSON for `url`, or an error JSON without running anything."""
url = url.strip()
parts = urlsplit(url)
scheme = parts.scheme.lower()
# Same rule as the CLI: https, and http only on this machine for the local demo below.
if scheme != "https" and not (scheme == "http" and parts.hostname in LOCAL_HOSTS):
return json.dumps(
{
"url": url,
"fixes": None,
"error": "Refused: give an https URL (http is only allowed on localhost). Nothing was run, signed or paid.",
"findings": [],
"signedOrPaid": False,
}
)
npx = shutil.which("npx")
if npx is None:
return json.dumps(
{
"url": url,
"fixes": None,
"error": "npx was not found; Node.js 18+ is needed for the check. Nothing was run, signed or paid.",
"findings": [],
"signedOrPaid": False,
}
)
try:
done = subprocess.run(
[npx, "-y", "@agent402-dev/pay-server", "check", url, "--json"],
capture_output=True,
text=True,
timeout=CHECK_TIMEOUT_SECONDS,
# Outside any Node project: npm would otherwise run a local package of the same
# name (this repository has one) instead of the published check.
cwd=tempfile.gettempdir(),
)
except subprocess.TimeoutExpired:
return json.dumps(
{
"url": url,
"fixes": None,
"error": f"The check did not finish within {CHECK_TIMEOUT_SECONDS} seconds. Nothing was signed or paid.",
"findings": [],
"signedOrPaid": False,
}
)
try:
return json.dumps(json.loads(done.stdout))
except json.JSONDecodeError:
detail = (done.stderr or done.stdout).strip().splitlines()
return json.dumps(
{
"url": url,
"fixes": None,
"error": f"The check printed no JSON (exit code {done.returncode}): {detail[-1] if detail else 'no output'}",
"findings": [],
"signedOrPaid": False,
}
)


class PrePayCheckTool(BaseTool):
name: str = "prepay_check"
description: str = (
"Check an x402 paid endpoint BEFORE paying it. Sends one request without a payment header "
"(nothing signed or paid, no key read) and returns JSON with `fixes` (how many things stop "
"a buyer), `findings`, and the USDC amounts the endpoint asks. Never pay when fixes > 0."
)
args_schema: type[BaseModel] = PrePayCheckInput

def _run(self, url: str) -> str:
return check_url(url)


if __name__ == "__main__":
import sys

print(check_url(sys.argv[1]))