From b4c292bd704d2b2f69b0a3944a886ce6c5bbcc45 Mon Sep 17 00:00:00 2001 From: riccardocens-code Date: Sat, 5 Dec 2026 11:55:41 +0100 Subject: [PATCH 1/2] examples: Mastra agent checks an x402 endpoint before paying (#3) --- examples/mastra-prepay-check/.gitignore | 3 + examples/mastra-prepay-check/README.md | 79 ++++++++++++++++++++++ examples/mastra-prepay-check/package.json | 21 ++++++ examples/mastra-prepay-check/tsconfig.json | 12 ++++ 4 files changed, 115 insertions(+) create mode 100644 examples/mastra-prepay-check/.gitignore create mode 100644 examples/mastra-prepay-check/README.md create mode 100644 examples/mastra-prepay-check/package.json create mode 100644 examples/mastra-prepay-check/tsconfig.json diff --git a/examples/mastra-prepay-check/.gitignore b/examples/mastra-prepay-check/.gitignore new file mode 100644 index 0000000..65d7854 --- /dev/null +++ b/examples/mastra-prepay-check/.gitignore @@ -0,0 +1,3 @@ +node_modules/ +.env +package-lock.json diff --git a/examples/mastra-prepay-check/README.md b/examples/mastra-prepay-check/README.md new file mode 100644 index 0000000..13dfeb8 --- /dev/null +++ b/examples/mastra-prepay-check/README.md @@ -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 -- `. +- `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. diff --git a/examples/mastra-prepay-check/package.json b/examples/mastra-prepay-check/package.json new file mode 100644 index 0000000..a3ff3c7 --- /dev/null +++ b/examples/mastra-prepay-check/package.json @@ -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" + } +} diff --git a/examples/mastra-prepay-check/tsconfig.json b/examples/mastra-prepay-check/tsconfig.json new file mode 100644 index 0000000..39b836a --- /dev/null +++ b/examples/mastra-prepay-check/tsconfig.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2022", + "module": "NodeNext", + "moduleResolution": "NodeNext", + "allowImportingTsExtensions": true, + "noEmit": true, + "strict": true, + "skipLibCheck": true + }, + "include": ["src"] +} From c950b8eb65b26ef2f7787a2dcda271ef9ce8e0d8 Mon Sep 17 00:00:00 2001 From: riccardocens-code Date: Sat, 5 Dec 2026 11:56:03 +0100 Subject: [PATCH 2/2] examples: add Mastra pre-pay check source files (#3) --- examples/mastra-prepay-check/src/agent.ts | 18 ++++++++++++ .../src/broken402Server.ts | 8 +++++ examples/mastra-prepay-check/src/index.ts | 11 +++++++ examples/mastra-prepay-check/src/tool.test.ts | 29 +++++++++++++++++++ examples/mastra-prepay-check/src/tool.ts | 18 ++++++++++++ 5 files changed, 84 insertions(+) create mode 100644 examples/mastra-prepay-check/src/agent.ts create mode 100644 examples/mastra-prepay-check/src/broken402Server.ts create mode 100644 examples/mastra-prepay-check/src/index.ts create mode 100644 examples/mastra-prepay-check/src/tool.test.ts create mode 100644 examples/mastra-prepay-check/src/tool.ts diff --git a/examples/mastra-prepay-check/src/agent.ts b/examples/mastra-prepay-check/src/agent.ts new file mode 100644 index 0000000..ed6fec6 --- /dev/null +++ b/examples/mastra-prepay-check/src/agent.ts @@ -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 }, +}); diff --git a/examples/mastra-prepay-check/src/broken402Server.ts b/examples/mastra-prepay-check/src/broken402Server.ts new file mode 100644 index 0000000..9687e86 --- /dev/null +++ b/examples/mastra-prepay-check/src/broken402Server.ts @@ -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)')); diff --git a/examples/mastra-prepay-check/src/index.ts b/examples/mastra-prepay-check/src/index.ts new file mode 100644 index 0000000..3ab04ce --- /dev/null +++ b/examples/mastra-prepay-check/src/index.ts @@ -0,0 +1,11 @@ +// Usage: npm start -- https:// +import { buyer } from './agent.ts'; + +const url = process.argv[2]; +if (!url) { + console.error('usage: npm start -- '); + process.exit(1); +} + +const result = await buyer.generate(`Check the x402 endpoint ${url}. Would you pay it?`, { maxSteps: 3 }); +console.log(result.text); diff --git a/examples/mastra-prepay-check/src/tool.test.ts b/examples/mastra-prepay-check/src/tool.test.ts new file mode 100644 index 0000000..a3e0d39 --- /dev/null +++ b/examples/mastra-prepay-check/src/tool.test.ts @@ -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((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(); + } +}); diff --git a/examples/mastra-prepay-check/src/tool.ts b/examples/mastra-prepay-check/src/tool.ts new file mode 100644 index 0000000..3617949 --- /dev/null +++ b/examples/mastra-prepay-check/src/tool.ts @@ -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 }), +});