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

A small, runnable [Mastra](https://mastra.ai) example that checks an x402 paid endpoint before anything pays for it. The agent has one tool — the pre-pay check from `@agent402-dev/ai-sdk-tools` — 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 needed.

## Files

| File | What it does |
| --- | --- |
| `src/index.ts` | A Mastra tool (`createTool`) whose `execute` calls `runCheck402({ url })` from `@agent402-dev/ai-sdk-tools` (with `allowLocal: true`, so the local test server below can be checked; public URLs still have to be https), plus one agent whose instructions say: do not pay when `fixes > 0`. |
| `package.json` | Pinned versions (below). |
| `broken402.mjs` | ~20-line local server that answers a broken 402 (its `resource.url` is http), for the local test below. |

## Install

Needs Node 20+ and an OpenAI API key for the agent's LLM (the check itself needs no key of any kind):

```bash
cd examples/mastra-prepay-check
npm install
export OPENAI_API_KEY=... # LLM only
```

## Run

Against a live x402 endpoint:

```bash
npm start -- 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
npm start -- "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
node broken402.mjs & # http://127.0.0.1:8402/paid
npm start -- 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`.

## Result fields

The tool returns the `runCheck402` result:

```json
{
"url": "https://seller.example.com/paid",
"method": "GET",
"fixes": 0,
"findings": [{ "level": "ok", "code": "price", "message": "accepts[0]: Solana mainnet, 0.002 USDC (amount \"2000\")." }],
"usdcAmounts": ["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 before any request.
- `findings`: `fix` first, then `note`, then `ok`; each has `level`, `code`, `message`.
- `usdcAmounts`: USDC base units the 402 asks for, one per USDC payment option (1000000 = 1 USDC).
- `signedOrPaid`: always `false` — one request, no payment header, nothing signed or paid.

## Versions used

Mastra `@mastra/core` 1.87.0 · `@agent402-dev/ai-sdk-tools` 0.1.0 · zod 4.6.7 · runs with tsx 4.23.15 on Node 24 · model `openai/gpt-5-mini` (via `OPENAI_API_KEY`). The author ran the tool against a live endpoint and the local broken-402 server above.

Apache-2.0, same as the repository.
31 changes: 31 additions & 0 deletions examples/mastra-prepay-check/broken402.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 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:
// node broken402.mjs # serves http://127.0.0.1:8402/paid
// npm start -- http://127.0.0.1:8402/paid # the agent says it will not pay
import { createServer } from 'node:http';

const 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' },
},
],
};
const body = JSON.stringify(payload);

createServer((req, res) => {
res.writeHead(402, {
'PAYMENT-REQUIRED': Buffer.from(body).toString('base64'),
'Content-Type': 'application/json',
});
res.end(body);
}).listen(8402, '127.0.0.1', () => console.log('broken 402 at http://127.0.0.1:8402/paid'));
1 change: 1 addition & 0 deletions examples/mastra-prepay-check/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"dependencies":{"@agent402-dev/ai-sdk-tools":"0.1.0","@mastra/core":"1.87.0","zod":"4.6.7"},"description":"Mastra example: check an x402 paid endpoint with @agent402-dev/ai-sdk-tools before anything pays for it. Nothing is signed or paid.","devDependencies":{"@types/node":"24.19.4","tsx":"4.23.15","typescript":"5.9.3"},"engines":{"node":">=20"},"license":"Apache-2.0","name":"mastra-prepay-check","private":true,"scripts":{"start":"tsx src/index.ts"},"type":"module","version":"1.0.0"}
73 changes: 73 additions & 0 deletions examples/mastra-prepay-check/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
import { Agent } from '@mastra/core/agent';
import { createTool } from '@mastra/core/tools';
import { runCheck402, type Check402Result } from '@agent402-dev/ai-sdk-tools';
import { z } from 'zod';
import { fileURLToPath } from 'node:url';

// The pre-pay check as a Mastra tool. runCheck402 sends one request to the
// URL without a payment header and reads the HTTP 402 answer; nothing is
// signed or paid and no key is read. allowLocal is on so the local
// broken-402 test server (broken402.mjs) can be checked too — public URLs
// still have to be https, exactly as runCheck402 enforces them.
const check402Output = z.object({
url: z.string(),
method: z.enum(['GET', 'POST']),
fixes: z.number().nullable(),
findings: z.array(
z.object({
level: z.enum(['fix', 'note', 'ok']),
code: z.string(),
message: z.string(),
}),
),
usdcAmounts: z.array(z.string()),
error: z.string().optional(),
signedOrPaid: z.literal(false),
});

export const check402PrepayTool = createTool({
id: 'check402-prepay',
description:
'Check an x402 paid endpoint before paying it. Sends one request without a payment header and reads the ' +
'HTTP 402 answer: price (usdcAmounts, in USDC base units), network, payTo and findings. Returns fixes — ' +
'the number of findings a buyer will fail on. Nothing is signed or paid. Use it before any payment, ' +
'and do not pay when fixes > 0.',
inputSchema: z.object({
url: z
.string()
.describe('The full https URL of the paid endpoint, exactly as it would be called to pay it.'),
}),
outputSchema: check402Output,
execute: async ({ url }): Promise<Check402Result> => runCheck402({ url }, { allowLocal: true }),
});

export const prepayChecker = new Agent({
id: 'prepay-checker',
name: 'Pre-pay checker',
instructions:
'You check x402 paid endpoints before anything pays for them. For any paid URL the user gives you, ' +
'first call the check402-prepay tool, then answer with the price (usdcAmounts are USDC base units: ' +
'1000000 = 1 USDC) and the number of fixes. 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 and error is set), say you will not pay because the endpoint could not be checked. ' +
'You have no tool that can pay; never claim that you paid.',
model: 'openai/gpt-5-mini',
tools: { check402PrepayTool },
});

async function main(): Promise<void> {
const url = process.argv[2];
if (!url) {
console.error('Usage: npm start -- https://<a live x402 endpoint>');
process.exit(2);
}
const { text } = await prepayChecker.generate(
`Before paying, check ${url} and tell me what it costs and whether you would pay it.`,
{ maxSteps: 5 },
);
console.log(text);
}

if (process.argv[1] === fileURLToPath(import.meta.url)) {
await main();
}