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
3 changes: 3 additions & 0 deletions examples/mastra-prepay-check/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules/
.env
package-lock.json
79 changes: 79 additions & 0 deletions examples/mastra-prepay-check/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Mastra: check an x402 endpoint before paying it

A Mastra agent with one tool, `check_x402_endpoint` (`createTool`), that calls `runCheck402({ url })` from
[`@agent402-dev/ai-sdk-tools`](../../packages/ai-sdk-tools) and returns its result. The agent's instructions say:
**do not pay when `fixes > 0`** (nor when `fixes` is `null`, i.e. the check was refused or failed).

**Nothing is paid:** the check sends one request without a payment header; nothing is signed or paid, and no key or wallet is read.

## Install

Needs Node.js 22.13+ (Mastra's requirement).

```sh
cd examples/mastra-prepay-check
npm install
export GOOGLE_GENERATIVE_AI_API_KEY=... # the LLM key; no wallet, RPC or paid API key is needed
```

The model is `google/gemini-3.5-flash-lite` by default. Set `MODEL` to use another Mastra model id,
e.g. `MODEL=openai/gpt-4o-mini` with `OPENAI_API_KEY`.

## Run

A live x402 endpoint (the toolkit's paid check402 route, 0.01 USDC; it is only checked, not paid):

```sh
npm start -- "https://agent402-check402.agent402-ebc.workers.dev/x402/check402?url=https://example.com"
```

```
price: Solana mainnet or Base, 0.01 USDC (10000 base units).
fixes: 0
decision: will pay because there are no fixes required (`fixes: 0`) and all checks passed successfully.
```

A local endpoint that answers a broken 402 (its `PAYMENT-REQUIRED` header is not base64 JSON):

```sh
npm run broken-402 &
npm start -- http://127.0.0.1:4021/paid
```

```
price: none (no USDC amounts returned)
fixes: 1 (header_undecodable: PAYMENT-REQUIRED is not base64 JSON that @x402/core can decode)
decision: will not pay because fixes > 0 (the endpoint has decoding issues with its payment requirement header).
```

The agent's wording varies from run to run; the decision follows `fixes`.

## Result fields

`runCheck402` returns:

| Field | Meaning |
| --- | --- |
| `url`, `method` | What was checked (`GET`). |
| `fixes` | Number of `fix` findings: problems a paying client hits. `0` means it can be paid. `null` when the URL was refused or the request failed (see `error`). |
| `findings` | `{level, code, message}` items, `fix` first, then `note`, then `ok`. The `price` findings give network, asset and amount of each `accepts` option. |
| `usdcAmounts` | The USDC amounts the 402 asks for, in base units (6 decimals). |
| `error` | Why the check did not run, if it did not. |
| `signedOrPaid` | Always `false`. |

URLs that are not public https are refused before any request. The example passes `allowLocal: true`, which also lets the
check reach `http://127.0.0.1` and `http://localhost` for the local server above; drop it to check public https URLs only.
`npm test` checks the refusal and a local broken 402 without an LLM key.

## Files

- `src/tool.ts`: the `createTool` tool.
- `src/agent.ts`: the agent and the pay rule.
- `src/index.ts`: `npm start -- <url>`.
- `src/broken402Server.ts`: the local broken 402.
- `src/tool.test.ts`: tests that need no LLM key.

## Versions used

`@mastra/core` 1.87.0, model `google/gemini-3.5-flash-lite` (through Mastra's model router), `@agent402-dev/ai-sdk-tools` 0.1.0
(with `@agent402-dev/pay-server` 0.15.0), zod 4.6.7, tsx 4.23.15, Node.js 24.22.1, npm 11.21.1.
21 changes: 21 additions & 0 deletions examples/mastra-prepay-check/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "mastra-prepay-check",
"private": true,
"type": "module",
"description": "A Mastra agent that checks an x402 endpoint before it would pay it. Nothing is paid.",
"engines": { "node": ">=22.13.0" },
"scripts": {
"start": "tsx src/index.ts",
"broken-402": "tsx src/broken402Server.ts",
"test": "tsx --test src/tool.test.ts"
},
"dependencies": {
"@agent402-dev/ai-sdk-tools": "0.1.0",
"@mastra/core": "1.87.0",
"zod": "4.6.7"
},
"devDependencies": {
"@types/node": "^22.0.0",
"tsx": "4.23.15"
}
}
18 changes: 18 additions & 0 deletions examples/mastra-prepay-check/src/agent.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Agent } from '@mastra/core/agent';
import { check402 } from './tool.ts';

export const MODEL = process.env.MODEL ?? 'google/gemini-3.5-flash-lite';

export const buyer = new Agent({
id: 'careful-buyer',
name: 'Careful API buyer',
instructions: [
'You decide whether to buy calls to x402 paid endpoints. You never pay or sign anything yourself.',
'Before any payment, run the check_x402_endpoint tool on the URL.',
'Rule: do not pay when fixes > 0. Do not pay either when fixes is null (the check was refused or failed).',
'Answer in a few lines: "price: ..." (network, asset and amount from the price findings, USDC amounts have 6 decimals),',
'"fixes: N", the fix findings if any, and "decision: will pay" or "decision: will not pay" with the reason.',
].join('\n'),
model: MODEL,
tools: { check402 },
});
8 changes: 8 additions & 0 deletions examples/mastra-prepay-check/src/broken402Server.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// A local endpoint that answers a broken 402: its PAYMENT-REQUIRED header is not base64 JSON, so no x402 client can pay it.
// Usage: npm run broken-402 (then: npm start -- http://127.0.0.1:4021/paid)
import { createServer } from 'node:http';

createServer((_req, res) => {
res.writeHead(402, { 'PAYMENT-REQUIRED': 'this-is-not-base64-json', 'Content-Type': 'application/json' });
res.end('{"error":"payment required"}');
}).listen(4021, '127.0.0.1', () => console.log('Broken 402 on http://127.0.0.1:4021/paid (Ctrl+C to stop)'));
11 changes: 11 additions & 0 deletions examples/mastra-prepay-check/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// Usage: npm start -- https://<x402 endpoint>
import { buyer } from './agent.ts';

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

const result = await buyer.generate(`Check the x402 endpoint ${url}. Would you pay it?`, { maxSteps: 3 });
console.log(result.text);
29 changes: 29 additions & 0 deletions examples/mastra-prepay-check/src/tool.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// The tool refuses non-https URLs without a request, and reads a 402 from a local server. No LLM key needed.
// Run: npm test
import assert from 'node:assert/strict';
import { createServer } from 'node:http';
import { test } from 'node:test';
import { runCheck402 } from '@agent402-dev/ai-sdk-tools';

test('a plain http public URL is refused before any request', async () => {
const r = await runCheck402({ url: 'http://example.com/paid' }, { allowLocal: true });
assert.equal(r.fixes, null);
assert.match(r.error ?? '', /https/);
assert.equal(r.signedOrPaid, false);
});

test('a broken 402 on localhost gives fixes > 0, and nothing is paid', async () => {
const server = createServer((_req, res) => {
res.writeHead(402, { 'PAYMENT-REQUIRED': 'not-base64-json' });
res.end('{}');
});
await new Promise<void>((ok) => server.listen(0, '127.0.0.1', ok));
try {
const { port } = server.address() as { port: number };
const r = await runCheck402({ url: `http://127.0.0.1:${port}/paid` }, { allowLocal: true });
assert.ok((r.fixes ?? 0) > 0);
assert.equal(r.signedOrPaid, false);
} finally {
server.close();
}
});
18 changes: 18 additions & 0 deletions examples/mastra-prepay-check/src/tool.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { createTool } from '@mastra/core/tools';
import { runCheck402 } from '@agent402-dev/ai-sdk-tools';
import { z } from 'zod';

// One request to the endpoint, without a payment header. Nothing is signed or paid and no key is read.
// runCheck402 never throws: a refused URL (not https) or a failed request comes back as `error`, with fixes: null.
// allowLocal lets the check reach http://127.0.0.1 and http://localhost, for the local broken-402 server below;
// every other URL must still be a public https URL.
export const check402 = createTool({
id: 'check_x402_endpoint',
description:
'Check an x402 paid endpoint before paying it. Sends one request without a payment header and returns ' +
'{ fixes, findings, usdcAmounts, error, signedOrPaid }: fixes is the number of problems a paying client would hit ' +
'(null with an error when the URL was refused or the request failed), findings are { level: fix | note | ok, code, message }, ' +
'usdcAmounts are the USDC amounts the endpoint asks, in base units (6 decimals). Nothing is signed or paid. Do not pay when fixes > 0.',
inputSchema: z.object({ url: z.string().describe('The https URL of the paid x402 endpoint') }),
execute: async ({ url }) => runCheck402({ url }, { allowLocal: true }),
});
12 changes: 12 additions & 0 deletions examples/mastra-prepay-check/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"allowImportingTsExtensions": true,
"noEmit": true,
"strict": true,
"skipLibCheck": true
},
"include": ["src"]
}