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
71 changes: 71 additions & 0 deletions examples/mastra-prepay-check/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
# Mastra pre-pay check for x402 endpoints

Small runnable [Mastra](https://mastra.ai) example that checks an x402 paid endpoint before paying it, using `runCheck402` from [`@agent402-dev/ai-sdk-tools`](../../packages/ai-sdk-tools).

Nothing is signed or paid and no wallet, private key, or RPC is needed — only one HTTP request without a payment header is sent.

## Install

```sh
cd examples/mastra-prepay-check
npm install
```

Set an LLM API key for your chosen provider (no wallet or RPC key is needed):

```sh
export OPENAI_API_KEY=sk-...
# Optional: override the default model (provider/model format)
# export MODEL=openai/gpt-5-mini
# Or use Anthropic / Google:
# export ANTHROPIC_API_KEY=...
# export GOOGLE_GENERATIVE_AI_API_KEY=...
```

## Run

Against a live x402 endpoint:

```sh
npm start -- "https://agent402-tx-receipts.agent402-ebc.workers.dev/x402/receipts?signatures=5VERv8NMvzbJMEkV8xnrLkEaWRtSz9CosKDYjCJjBRnbJLgp8uirBgmQpjKhoR4tjF3ZpRzrFmBV6UjKdiSZkQUW"
```

The agent calls `check402`, prints the price (`0.05 USDC`, base units `50000`) and `fixes: 0`, and notes whether it would proceed.

### Test against a local broken 402

Start a local server that returns HTTP `402` with a broken `PAYMENT-REQUIRED` header (for example, missing or malformed payment requirements):

```sh
node -e "require('http').createServer((req, res) => { res.writeHead(402, { 'content-type': 'application/json' }); res.end('{}'); }).listen(4021)"
```

Then run the agent against it:

```sh
npm start -- http://127.0.0.1:4021/paid
```

Because `fixes > 0`, the agent reports the `fix` findings and states that it will not pay.

## Result fields

The `check402` tool calls `runCheck402({ url })` and returns:

| Field | Description |
|---|---|
| `url` | The endpoint URL that was checked. |
| `method` | HTTP method sent (`GET` or `POST`). |
| `fixes` | Number of `fix` findings a buyer will fail on (`0` = no blocking issues; `null` if the request failed or was refused). |
| `findings` | Array of `{ level, code, message }` sorted `fix` first, then `note`, then `ok`. |
| `usdcAmounts` | Array of USDC amounts requested in base units (`1,000,000` = `1 USDC`), one per USDC payment option. |
| `error` | Present when the request failed or was refused before sending. |
| `signedOrPaid` | Always `false` — nothing is signed or paid. |

## Versions

- `@mastra/core`: `1.87.0`
- `@agent402-dev/ai-sdk-tools`: `0.1.0`
- `zod`: `4.3.6`
- `tsx`: `4.23.15`
- Model tested: `google/gemini-2.5-flash` (overridable via `MODEL`; defaults to `openai/gpt-5-mini`, or `anthropic/claude-haiku-4-5` / `google/gemini-2.5-flash` when only the matching provider key is set)
20 changes: 20 additions & 0 deletions examples/mastra-prepay-check/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"name": "mastra-prepay-check",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"start": "tsx src/index.ts",
"typecheck": "tsc --noEmit --target ES2022 --module ESNext --moduleResolution bundler --strict --skipLibCheck --types node src/index.ts"
},
"dependencies": {
"@agent402-dev/ai-sdk-tools": "0.1.0",
"@mastra/core": "1.87.0",
"zod": "4.3.6"
},
"devDependencies": {
"@types/node": "22.20.5",
"tsx": "4.23.15",
"typescript": "5.9.3"
}
}
75 changes: 75 additions & 0 deletions examples/mastra-prepay-check/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
import { Agent } from '@mastra/core/agent';
import { createTool } from '@mastra/core/tools';
import { runCheck402 } from '@agent402-dev/ai-sdk-tools';
import { z } from 'zod';

const targetUrl = process.argv[2];
if (!targetUrl) {
console.error('Usage: npm start -- <x402-endpoint-url>');
process.exit(1);
}

let parsedTarget: URL;
try {
parsedTarget = new URL(targetUrl);
} catch {
console.error(`Invalid URL: ${targetUrl}`);
process.exit(1);
}

const targetHost = parsedTarget.hostname.toLowerCase();
const isLocalTarget = targetHost === 'localhost' || targetHost === '127.0.0.1';
const allowLocal = isLocalTarget || process.env.ALLOW_LOCAL === '1';

export const check402Tool = createTool({
id: 'check402',
description:
'Check an x402 paid endpoint before paying it. Sends one request without a payment header ' +
'and returns the HTTP 402 findings ("fix", "note", "ok"), fixes count, and USDC amounts. ' +
'Nothing is signed or paid and no key is read.',
inputSchema: z.object({
url: z.string().describe('Full URL of the x402 paid endpoint to check.'),
method: z.enum(['GET', 'POST']).optional().describe('HTTP method (default GET).'),
body: z.string().optional().describe('Optional JSON request body for POST endpoints.'),
}),
execute: async ({ url, method, body }) =>
runCheck402({ url, method, body }, { allowLocal, allowHosts: [targetHost] }),
});

type ProviderModel = `${string}/${string}`;

function resolveModel(): ProviderModel {
if (process.env.MODEL) {
if (!process.env.MODEL.includes('/')) {
console.error('MODEL must use Mastra provider/model format, e.g. openai/gpt-5-mini');
process.exit(1);
}
return process.env.MODEL as ProviderModel;
}
if (process.env.ANTHROPIC_API_KEY && !process.env.OPENAI_API_KEY) {
return 'anthropic/claude-haiku-4-5';
}
if ((process.env.GOOGLE_GENERATIVE_AI_API_KEY || process.env.GOOGLE_API_KEY) && !process.env.OPENAI_API_KEY) {
return 'google/gemini-2.5-flash';
}
return 'openai/gpt-5-mini';
}

export const prepayCheckAgent = new Agent({
id: 'x402-prepay-check-agent',
name: 'x402 Pre-Pay Check Agent',
instructions: [
'Before paying any x402 endpoint, call the check402 tool on the URL.',
'Report the price (usdcAmounts are in USDC base units, where 1,000,000 = 1 USDC, and findings also list parsed prices), the exact fixes count (for example `fixes: 0`), and key findings.',
'Do not pay when fixes > 0 or when fixes is null (request failed or was refused). When fixes > 0 or fixes is null, state clearly that you will not pay and explain the fix findings or error.',
'Nothing is signed or paid by this check.',
].join('\n'),
model: resolveModel(),
tools: { check402: check402Tool },
});

const response = await prepayCheckAgent.generate(
`Before paying, check ${targetUrl} with check402. Tell me the price, fixes count, and whether you would pay.`,
);

console.log(response.text);