Introducing Token Cost Control for Mastra Agents

Real-time spending caps configurable by thread, user, session, org, and more.

Paul ScanlonPaul Scanlon·

Aug 27, 2026

·

3 min read

You can now enforce spending limits with TokenCostControl — a processor that reads cumulative costs from observability data. Configure a hard maxCost cap that blocks the run when exceeded, or a soft warnAtPercent threshold that fires as usage approaches the limit.

Scopes range from a single agent run to an entire organization's usage. Additional configuration lets you block or warn on violations, and set a lookback window that resets cost tracking after a configurable period.

Before cost control, runaway spending almost always shows up after the fact — a spike in metrics, or a bigger-than-expected bill. WithTokenCostControl you can catch it in real time. The processor reads observability data before each LLM call and stops (or warns) an agent once its cumulative cost crosses a threshold.

Studio surfaces tripwires as expandable errors during development, letting you inspect the violation payload and cost breakdown in development. For production, use the onViolation callback to surface the same details.

Get started

Install @mastra/core and the observability + storage packages needed to persist cost metrics:

GNU BashTerminal
npm install @mastra/core @mastra/observability @mastra/duckdb
note
Requires @mastra/core@1.59.0 or later, added in PR #21372.

Create a TokenCostControl and attach it to the agent as an inputProcessor. Each option tunes a different dimension of the cost check:

  • maxCost: 0.5: Hard cap in USD ($0.50).
  • scope: "resource": Track per resourceId (default). Alternatives: run, thread, user, organization, session.
  • window: "1h": Cost lookback window. Options: 1h, 6h, 24h, 7d, 30d, 365d.
  • strategy: "block": Abort the run when maxCost is exceeded. "warn" logs and fires onViolation without stopping the run.
  • warnAtPercent: Fire onViolation at 80% of maxCost (soft warning).
  • includeBreakdown: true: Attach a per-provider/model cost breakdown to the violation payload.
TypeScriptsrc/mastra/agents/research-agent.ts
import { Agent } from "@mastra/core/agent";
import { Memory } from "@mastra/memory";
import { TokenCostControl } from "@mastra/core/processors";
import type { TokenCostControlViolationDetail } from "@mastra/core/processors";
 
const tokenCostControl = new TokenCostControl({
  maxCost: 0.5,
  scope: "resource",
  window: "1h",
  strategy: "block",
  warnAtPercent: 80,
  includeBreakdown: true
});
 
tokenCostControl.onViolation = ({ detail }) => {
  const d = detail as TokenCostControlViolationDetail;
  console.log(`[${d.threshold}] $${d.usage.toFixed(4)}/$${d.limit}`);
  for (const entry of d.breakdown ?? []) {
    console.log(`  ${entry.provider}/${entry.model}: $${(entry.estimatedCost ?? 0).toFixed(4)}`);
  }
};
 
export const researchAgent = new Agent({
  id: "research-agent",
  name: "Research Agent",
  instructions: /* ... */,
  model: "anthropic/claude-opus-4-8",
  memory: new Memory(),
  inputProcessors: [tokenCostControl]
});

The block strategy aborts the request before the LLM call, fires onViolation, and emits a tripwire chunk. The warn strategy lets the request through and fires onViolation with the current cost, the limit, and a per-provider/model breakdown.

TokenCostControl uses Mastra’s observability layer. Configure storage and observability on your main Mastra instance:

TypeScriptsrc/mastra/index.ts
import { Mastra } from "@mastra/core/mastra";
import { MastraCompositeStore } from "@mastra/core/storage";
import { DuckDBStore } from "@mastra/duckdb";
import { Observability, MastraStorageExporter } from "@mastra/observability";
 
export const mastra = new Mastra({
  // ...
  storage: new MastraCompositeStore({
    // ...
    domains: {
      observability: await new DuckDBStore().getStore("observability")
    }
  }),
  observability: new Observability({
    configs: {
      default: { exporters: [new MastraStorageExporter()] }
    }
  })
});

For more information and full configuration options, see:

Share:
Paul Scanlon
Paul ScanlonTechnical Product Marketing Manager

Paul Scanlon sits between Developer Education and Product Marketing at Mastra. Previously, he was a Technical Product Marketing Manager at Neon and worked in Developer Relations at Gatsby, where he created educational content and developer experiences.

All articles by Paul Scanlon