Mastra

Make a Mastra tool ask a person before it acts, with the TypeScript client, in an agent, a workflow step or a Mastra MCP server.

A Mastra agent acts through tools, and a tool acts in its execute function. Ask a person at the top of execute, and the refund, email or deploy cannot happen without their yes, whether the tool runs in an agent, a workflow step or an MCP server built with Mastra. The example below was run against Mastra 1.85 with an approval and with a denial.

1. Install the client

npm install https://variantgate.com/sdk/variantgate-agent-latest.tgz

Make an agent key under Agents and put it in VARIANTGATE_KEY. One client per agent is enough:

import { ApprovalClient } from "@variantgate/agent";

export const approvals = new ApprovalClient({
  agent: "support-agent",
  apiUrl: "https://api.variantgate.com",
  key: process.env.VARIANTGATE_KEY ?? "",
});

2. Ask inside the tool

import { createTool } from "@mastra/core/tools";
import { NotApprovedError } from "@variantgate/agent/errors";
import { z } from "zod";
import { approvals } from "./approvals";
import { shop } from "./shop"; // your own refund code

const EUROS = /^\d+(\.\d{1,2})?$/;

export const refundOrder = createTool({
  id: "refund-order",
  description: "Refund an order to the customer's original payment method.",
  inputSchema: z.object({
    orderId: z.string(),
    amountEur: z.string().regex(EUROS).describe("Euros, such as 25.00"),
  }),
  outputSchema: z.object({ refunded: z.boolean(), message: z.string() }),
  execute: async ({ orderId, amountEur }) => {
    const done = `Refunded €${amountEur} for order ${orderId}.`;
    let refunded = false;
    try {
      // The sentence returned here is kept on the record as the outcome.
      const message = await approvals.guard(
        {
          action: "payment.refund",
          summary: `Refund €${amountEur} for order ${orderId}`,
          amount: amountEur,
          currency: "EUR",
          details: { order: orderId },
        },
        async () => {
          await shop.refund(orderId, amountEur);
          refunded = true;
          return done;
        },
        // Withdraw the request if nobody answers in two minutes.
        { timeoutMs: 120_000 }
      );
      return { refunded, message };
    } catch (error) {
      if (refunded) {
        // Only recording the outcome failed. Never let the model retry.
        return { refunded, message: done };
      }
      if (error instanceof NotApprovedError) {
        return { refunded, message: `Not refunded. ${error.message}` };
      }
      throw error;
    }
  },
});
  • guard asks, waits for the answer and runs the function only on a yes, then records whether it worked. Pending, denied, expired, withdrawn and a paused workspace all throw NotApprovedError.
  • On a no the tool returns refunded: false and the reason, rather than throwing. The model reads it and can tell the customer instead of trying again.
  • If the refund went through but recording the outcome failed, guard still throws. The refunded flag makes the tool report the refund anyway, so the model never asks for a second one.
  • timeoutMs withdraws the request when nobody answers in time, so nobody can approve it after the agent has stopped waiting.
  • If a person lowers the amount or rewords the request, guard throws ChangedApprovalError, a kind of NotApprovedError, and does nothing. To act on the changed version, pass { acceptChanges: true } and refund only the approved_amount of the decision your function receives, never the amount the model asked for.
  • A rule such as “always allow payment.refund up to €20” lets small refunds through at once, while larger ones wait for a person.

3. Give the tool to the agent

import { anthropic } from "@ai-sdk/anthropic";
import { Agent } from "@mastra/core/agent";
import { refundOrder } from "./tools";

export const supportAgent = new Agent({
  id: "support-agent",
  name: "Support agent",
  instructions:
    "You handle refunds. Use the refund tool, then tell the customer what happened.",
  model: anthropic("claude-sonnet-5-5"),
  tools: { refundOrder },
});

Then, in a script, a route or a job:

import { supportAgent } from "./agent";

const result = await supportAgent.generate(
  "Order 1182 arrived broken. Please refund it."
);
console.log(result.text);

Any model works; the approval lives in your tool, not in the model. The same tool can become a workflow step with createStep, or be served by a Mastra MCP server, unchanged.

When Mastra’s own requireApproval is enough

Mastra can suspend a run before a tool marked requireApproval and wait until your app approves or declines the call. That fits when the person in your app is the one who should decide, and your app shows them the question. VariantGate fits when the agent runs with nobody watching, someone else must decide, the answer should reach them by email, Slack, Teams, Discord or a phone notification, a rule should settle routine cases, or you need a sealed record of who approved what. The two can be used together.

Waiting longer

A person may take hours. Ask without waiting, store the request id, and let a signed webhook start the next step, such as resuming a suspended workflow; then read the answer with check before acting, since a webhook is a notice, never a permission. Act only on allowed: true; when changed is true, do only the approved_summary for at most the approved_amount. Afterwards, report how it went with reportOutcome, which guard otherwise does for you. See the TypeScript client for every method, or try the whole loop in the playground first.