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

A CrewAI agent that checks an [x402](https://www.x402.org/) payment endpoint
**before** paying for it. The agent runs the
`@agent402-dev/pay-server` checker once and reports the price and how many
fixes the endpoint needs. Its standing rule is: **do not pay when
`fixes > 0`**.

**Nothing is paid by this example.** The check makes one unpaid request to
the endpoint; no payment header is sent, nothing is signed, and no wallet,
key, RPC endpoint, or paid API key is needed to run the check itself. The
only key you need is an LLM key for CrewAI itself.

## Install

Requires Python 3.10+ and Node 18+ (for `npx`).

```bash
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```

Set an LLM key for CrewAI (pick one):

```bash
export OPENAI_API_KEY="..." # OpenAI (default model)
# or
export GEMINI_API_KEY="..." # Google Gemini (model gemini/gemini-2.5-flash)
```

## Run

Check a live x402 endpoint (default is the Xynaptic crypto-price API):

```bash
python main.py https://api.xynaptic.io/v1/crypto-price
```

The agent prints the price the endpoint asks for, the `fixes` count, and a
clear pay / do-not-pay recommendation. For the default endpoint you should
see a price of 0.02 USDC and `fixes: 0`.

## Try the "will not pay" path

A tiny local server answers a deliberately broken 402 (no usable payment
details), so you can see the agent refuse to pay without spending anything:

```bash
python broken_server.py &
python main.py http://127.0.0.1:8765/broken
```

The agent reports `fixes: 1` and says it will not pay.

## What the tool returns

`tool.py` defines `X402PrePayCheckTool`, a CrewAI custom tool. It runs:

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

and returns the checker's JSON to the agent, including:

- `fixes` — how many things the endpoint must fix (0 = clean)
- `findings` — one entry per check (`ok`, `note`, or `fix`), including the
accepted prices (network, token, amount)
- `signedOrPaid` — always `false` here; the check never signs or pays

## Safety rules

- **Non-https URLs are refused before any check runs** — the tool never
starts the checker for them. The one exception is plain `http` to a
loopback address (`127.0.0.1` / `::1` / `localhost`), allowed only so the
bundled local demo server can be checked; loopback traffic never leaves
your machine.
- **One request, no payment.** The check sends a single unpaid request.
No payment header is attached, nothing is signed, and no wallet or key
is read.

## Files

- `main.py` — the CrewAI agent and its "do not pay when `fixes > 0`"
instructions. Without an LLM key it runs the check tool directly and
prints the JSON, so the check itself is still verifiable.
- `tool.py` — the `X402PrePayCheckTool` custom tool.
- `broken_server.py` — ~20-line local server answering a broken 402.
- `requirements.txt` — pinned dependencies.
35 changes: 35 additions & 0 deletions examples/crewai-prepay-check/broken_server.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""A tiny local server that answers a broken 402.

Run it, then point the example at it:

python broken_server.py &
python main.py http://127.0.0.1:8765/broken

The 402 it returns is deliberately malformed (no usable `accepts` entry),
so the pre-pay check reports fixes > 0 and the agent says it will not pay.
Nothing here spends money: the server never asks for a real payment.
"""

from http.server import BaseHTTPRequestHandler, HTTPServer

PORT = 8765


class Broken402Handler(BaseHTTPRequestHandler):
def do_GET(self):
body = b'{"error": "payment required, but this 402 is broken"}'
self.send_response(402)
# Deliberately wrong: a plain-text body and no PAYMENT-REQUIRED
# header / accepts list, so the checker must flag fixes.
self.send_header("Content-Type", "text/plain")
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)

def log_message(self, *args): # keep the demo output clean
pass


if __name__ == "__main__":
print(f"Broken 402 server listening on http://127.0.0.1:{PORT}/broken")
HTTPServer(("127.0.0.1", PORT), Broken402Handler).serve_forever()
110 changes: 110 additions & 0 deletions examples/crewai-prepay-check/main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
"""Pre-pay check of an x402 endpoint in a CrewAI agent.

Usage:
python main.py https://api.xynaptic.io/v1/crypto-price

The agent runs the x402 pre-pay check tool once and reports the price and
the number of fixes needed. It does NOT pay anything: the check makes one
unpaid request and no payment header is ever sent.

The agent's standing instruction is: do not pay when `fixes > 0`.

LLM: the agent uses whatever model CrewAI is configured for. Set one of the
usual provider keys before running, e.g. ``OPENAI_API_KEY`` (OpenAI) or
``GEMINI_API_KEY`` (Google Gemini, model ``gemini/gemini-2.5-flash``).
If no LLM key is set, the script falls back to running the check tool
directly and printing its JSON, so the check itself can still be verified
without an LLM.
"""

import json
import os
import sys

from tool import X402PrePayCheckTool

LIVE_ENDPOINT = "https://api.xynaptic.io/v1/crypto-price"


def _select_llm():
"""Pick the LLM for the agent, or None for CrewAI's default.

A Gemini key on its own (no OpenAI key) selects
``gemini/gemini-2.5-flash``; otherwise CrewAI's default (OpenAI)
applies. Returning None leaves the Agent's default untouched.
"""
if os.environ.get("GEMINI_API_KEY") and not os.environ.get("OPENAI_API_KEY"):
from crewai import LLM

return LLM(model="gemini/gemini-2.5-flash")
return None


def build_checker_agent():
"""Build the x402 pre-pay check agent."""
from crewai import Agent

kwargs = {}
llm = _select_llm()
if llm is not None:
kwargs["llm"] = llm
return Agent(
role="x402 payment checker",
goal=(
"Check an x402 endpoint before any payment is made and report "
"whether it is safe to pay for it."
),
backstory=(
"You verify x402 payment endpoints. You never pay for anything "
"yourself; you only run the pre-pay check and report what it "
"found. Your rule is absolute: do not pay when fixes > 0."
),
tools=[X402PrePayCheckTool()],
verbose=True,
**kwargs,
)


def run_with_agent(url: str) -> str:
"""Run the check through a CrewAI agent and return its answer."""
from crewai import Crew, Task

checker = build_checker_agent()
task = Task(
description=(
f"Run the x402 pre-pay check on {url}. Report the price the "
"endpoint asks for, the value of `fixes`, and whether it is "
"safe to pay. If `fixes` is greater than 0, say clearly that "
"you will NOT pay."
),
expected_output=(
"The endpoint price, the fixes count, and a clear pay / do-not-pay "
"recommendation."
),
agent=checker,
)
crew = Crew(agents=[checker], tasks=[task])
return str(crew.kickoff())


def run_tool_only(url: str) -> str:
"""Run the check tool directly (no LLM) and print its JSON."""
return X402PrePayCheckTool().run(url)


def main() -> int:
url = sys.argv[1] if len(sys.argv) > 1 else LIVE_ENDPOINT
if os.environ.get("OPENAI_API_KEY") or os.environ.get("GEMINI_API_KEY"):
print(run_with_agent(url))
else:
print(
"No LLM key found (OPENAI_API_KEY or GEMINI_API_KEY unset); "
"running the check tool directly.",
file=sys.stderr,
)
print(run_tool_only(url))
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[google-genai]==1.15.50
79 changes: 79 additions & 0 deletions examples/crewai-prepay-check/tool.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
"""CrewAI custom tool: pre-pay check of an x402 endpoint.

Runs ``npx -y @agent402-dev/pay-server check <url> --json`` and returns the
checker's JSON to the agent. One request to the endpoint, no payment header,
nothing signed, nothing paid, no key read.

Safety rules enforced here, before the checker ever runs:
- Only https URLs are accepted, with one narrow exception: plain http to a
loopback address (127.0.0.1 / ::1 / localhost) is allowed so the bundled
local demo server can be checked. Loopback traffic never leaves the
machine, so no payment data crosses an insecure network. Every other
non-https URL is refused outright.
"""

import json
import shutil
import subprocess
from urllib.parse import urlparse

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


class PrePayCheckInput(BaseModel):
"""Input schema for the pre-pay check tool."""

url: str = Field(..., description="The https URL of the x402 endpoint to check.")


class X402PrePayCheckTool(BaseTool):
name: str = "x402_pre_pay_check"
description: str = (
"Check an x402 payment endpoint BEFORE paying for it. "
"Input is the endpoint URL (https only). "
"Returns the pay-server check JSON with fields `fixes`, `findings`, "
"and the accepted prices. The check makes ONE unpaid request and "
"pays nothing. Do NOT pay when `fixes` is greater than 0."
)
args_schema: type[BaseModel] = PrePayCheckInput

def _run(self, url: str) -> str:
parsed = urlparse(url)
host = (parsed.hostname or "").lower()
is_loopback = host in ("127.0.0.1", "::1", "localhost")
if parsed.scheme == "http" and is_loopback:
pass # local demo server only; loopback never leaves the machine
elif parsed.scheme != "https" or not parsed.netloc:
return json.dumps(
{
"error": "refused: only https URLs are accepted",
"url": url,
"fixes": None,
"findings": [],
}
)
npx = shutil.which("npx")
if npx is None:
return json.dumps(
{"error": "npx not found; Node 18+ is required", "url": url}
)
proc = subprocess.run(
[npx, "-y", "@agent402-dev/pay-server", "check", url, "--json"],
capture_output=True,
text=True,
timeout=120,
)
try:
result = json.loads(proc.stdout)
except json.JSONDecodeError:
return json.dumps(
{
"error": "checker output was not JSON",
"url": url,
"stdout": proc.stdout[:500],
"stderr": proc.stderr[:500],
}
)
result.setdefault("url", url)
return json.dumps(result)