Setting Up Agent Payments with Mastra and ATXP

Your Mastra agent can call tools, manage memory, and orchestrate multi-step workflows. What it can’t do out of the box is pay for anything — no API credits, no agent-to-agent transactions, no autonomous purchasing. That’s a hard ceiling for any production agentic system.

Setting Up Agent Payments with Mastra and ATXP

Quick answer: To set up Mastra agent payments, create an ATXP agent account via the SDK, attach a spending cap, and register it as a Mastra tool. Your agent can then make autonomous payments — for APIs, services, or other agents — within the limits you define. ATXP handles the payment identity, IOU balance, and revocation controls. Setup takes under 30 minutes for a working integration.

What You Need Before You Start

You need a working Mastra project, an ATXP account, and Node.js 18+. If you haven’t scaffolded a Mastra project yet, their CLI gets you there in two commands:

npx create-mastra@latest my-agent-project
cd my-agent-project

Then install the ATXP SDK alongside your existing dependencies:

npm install @atxp/sdk

You’ll also need your ATXP API key from the dashboard. Keep it in an environment variable — never hardcode credentials that control payment accounts.

ATXP_API_KEY=your_key_here

Creating an Agent Payment Account with ATXP

Each Mastra agent that needs to spend money gets its own isolated ATXP account — a handle, an IOU balance, and a spending cap. This is the blast radius principle: if one agent misbehaves or gets compromised, its damage is capped by design, not by hope.

import { AtxpClient } from "@atxp/sdk";

const atxp = new AtxpClient({ apiKey: process.env.ATXP_API_KEY });

const agentAccount = await atxp.accounts.create({
  handle: "research-agent-01",
  spendingCap: {
    amount: 10_00, // $10.00 in cents
    window: "24h",
  },
  currency: "usd",
});

console.log(agentAccount.handle);   // research-agent-01
console.log(agentAccount.balance);  // 0 — fund it next

Fund the account from your master balance:

await atxp.accounts.fund({
  handle: "research-agent-01",
  amount: 5_00, // $5.00
});

The spendingCap is enforced at the infrastructure level. The agent cannot exceed it regardless of what the LLM decides to do.

Registering the ATXP Payment Tool in Mastra

Mastra agents interact with external systems through tools — ATXP becomes a first-class tool in your agent’s toolkit. Define it once, reuse it across any Mastra workflow.

import { createTool } from "@mastra/core";
import { z } from "zod";
import { AtxpClient } from "@atxp/sdk";

const atxp = new AtxpClient({ apiKey: process.env.ATXP_API_KEY });

export const atxpPaymentTool = createTool({
  id: "atxp-pay",
  description:
    "Send a payment from this agent's ATXP account to a service or another agent.",
  inputSchema: z.object({
    recipient: z.string().describe("ATXP handle or x402 endpoint URL"),
    amount: z.number().describe("Amount in cents (USD)"),
    memo: z.string().optional().describe("Purpose of the payment"),
  }),
  execute: async ({ context }) => {
    const { recipient, amount, memo } = context;

    const result = await atxp.payments.send({
      from: "research-agent-01",
      to: recipient,
      amount,
      memo,
    });

    return {
      transactionId: result.id,
      status: result.status,
      remainingBalance: result.senderBalance,
    };
  },
});

Now attach the tool to your agent:

import { Agent } from "@mastra/core";
import { atxpPaymentTool } from "./tools/atxp-payment";

export const researchAgent = new Agent({
  name: "Research Agent",
  instructions: `You are a research agent. When you need to access a paid API or 
  compensate another agent for work, use the atxp-pay tool. Always include a 
  descriptive memo so expenditures are auditable.`,
  model: {
    provider: "OPEN_AI",
    toolChoice: "auto",
  },
  tools: {
    atxpPay: atxpPaymentTool,
  },
});

Your agents need real payment infrastructure, not workarounds. See how ATXP works →


Handling x402 Payments Inside Mastra Workflows

If your agent calls HTTP services that use the x402 payment protocol, ATXP handles the 402 Payment Required response automatically. You don’t manually intercept 402 responses — the ATXP-aware fetch wrapper does it.

import { atxpFetch } from "@atxp/sdk";

export const paidDataTool = createTool({
  id: "fetch-paid-data",
  description: "Fetch data from a paywalled x402 API endpoint.",
  inputSchema: z.object({
    url: z.string().url(),
  }),
  execute: async ({ context }) => {
    // atxpFetch intercepts 402 responses, pays from the agent's account,
    // then retries the request automatically.
    const response = await atxpFetch(context.url, {
      agentHandle: "research-agent-01",
    });

    return response.json();
  },
});

The agent never sees the payment negotiation. From the workflow’s perspective, it made a request and got data. ATXP debits the account, enforces the cap, and logs the transaction.

Revoking and Auditing Agent Payment Access

You can suspend a Mastra agent’s payment access in one API call — no redeployment, no code change. This is the key operational control for production systems.

// Revoke immediately
await atxp.accounts.revoke({ handle: "research-agent-01" });

// Pull transaction history for audit
const history = await atxp.transactions.list({
  handle: "research-agent-01",
  from: "2026-04-01",
  to: "2026-04-17",
});

history.transactions.forEach((tx) => {
  console.log(`${tx.createdAt} | ${tx.to} | $${tx.amount / 100} | ${tx.memo}`);
});

Every payment the agent makes is logged with a timestamp, recipient, amount, and memo. When something looks wrong — unexpected recipients, unusual spend velocity — you have a full audit trail without digging through LLM logs.

ControlHow It WorksWhen to Use
spendingCapHard limit per time windowAlways — set at account creation
revoke()Instant suspensionRunaway agent, security incident
Transaction logFull payment historyAudits, debugging, cost attribution
Per-agent handlesIsolated identityAny multi-agent system

What a Complete Mastra Payment Workflow Looks Like

At this point your Mastra agent has a payment identity, a capped balance, tool access, and x402 support. A realistic research workflow might look like this:

  1. Agent receives a task: “Compile a market report on EV battery suppliers.”
  2. Agent calls a paywalled data API via atxpFetch — ATXP handles the 402 automatically, $0.08 debited.
  3. Agent delegates a sub-task to a specialist agent via Mastra’s multi-agent API, paying it 200 credits via atxp-pay.
  4. Spending cap prevents any single workflow from burning more than $10 in 24 hours.
  5. You pull the transaction log post-run and see exactly what each dollar bought.

That’s Mastra agent payments working end-to-end — autonomous, auditable, and bounded by controls you set.

Ready to give your Mastra agents real payment infrastructure? Get started with ATXP →