mastra-ai/mastra · error · HTTPException

Argument "${key}" is required

Error message

Argument "${key}" is required

What it means

validateBody collects every required body key that is missing and throws a 400 with the first missing argument's message. The generate/stream route handlers use it to fail fast when the caller omitted required fields (e.g. messages) before agent execution begins.

Source

Thrown at packages/server/src/server/handlers/utils.ts:18

import type { MastraFGAPermissionInput } from '@mastra/core/auth/ee';
import type { RequestContext } from '@mastra/core/di';
import { MastraMemory } from '@mastra/core/memory';
import { MASTRA_RESOURCE_ID_KEY, MASTRA_THREAD_ID_KEY } from '../constants';
import { MastraFGAPermissions } from '../fga-permissions';
import { HTTPException } from '../http-exception';

// Validation helper
export function validateBody(body: Record<string, unknown>) {
  const errorResponse = Object.entries(body).reduce<Record<string, string>>((acc, [key, value]) => {
    if (!value) {
      acc[key] = `Argument "${key}" is required`;
    }
    return acc;
  }, {});

  if (Object.keys(errorResponse).length > 0) {
    throw new HTTPException(400, { message: Object.values(errorResponse)[0] });
  }
}

/**
 * sanitizes the body by removing disallowed keys.
 * @param body body to sanitize
 * @param disallowedKeys keys to remove from the body
 */
export function sanitizeBody(body: Record<string, unknown>, disallowedKeys: string[]) {
  for (const key of disallowedKeys) {
    if (key in body) {
      delete body[key];
    }
  }
}

export function parsePerPage(
  value: string | undefined,

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Include all required keys in the JSON body — for generate routes typically `messages: [{ role, content }]`.
  2. Set Content-Type: application/json and send a valid JSON payload.
  3. Compare against the current route contract in packages/server handlers or the client SDK types for required fields.
  4. Log the outgoing body client-side to catch misspelled/absent keys.

Example fix

// before
await fetch('/api/agents/assistant/generate', { method: 'POST', body: JSON.stringify({ prompt: 'hi' }) });
// after
await fetch('/api/agents/assistant/generate', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ messages: [{ role: 'user', content: 'hi' }] }),
});
Defensive patterns

Strategy: validation

Validate before calling

function validateGenerateBody(body: unknown): asserts body is { messages: Array<{ role: string; content: string }> } {
  const b = body as any;
  if (!b || typeof b !== 'object') throw new Error('Request body must be a JSON object');
  if (!Array.isArray(b.messages) || b.messages.length === 0) {
    throw new Error('messages array is required in the request body');
  }
}

Type guard

function hasRequiredArgs(body: unknown, required: string[]): body is Record<string, unknown> {
  return !!body && typeof body === 'object' &&
    required.every(k => (body as Record<string, unknown>)[k] !== undefined && (body as Record<string, unknown>)[k] !== null);
}

Try / catch

try {
  const res = await fetch('/api/agents/assistant/generate', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
  if (res.status === 400) {
    const msg = await res.text();
    throw new Error(`Bad request: ${msg}`);
  }
  return await res.json();
} catch (e) { throw e; }

Prevention

When it happens

Trigger: POSTing to generate/stream routes (GENERATE_AGENT_ROUTE, GENERATE_LEGACY_ROUTE, STREAM_GENERATE_ROUTE/LEGACY, STREAM_UNTIL_IDLE, STREAM_NETWORK) with a body missing required keys such as `messages`, or sending no/empty body, or wrong Content-Type so the body parses to nothing.

Common situations: Forgetting the JSON body entirely, sending form data where JSON is expected, misspelling a key (e.g. `message` instead of `messages`), or a client SDK version sending the old body shape after a server upgrade.

Related errors


AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30). Data as JSON: /api/errors/639fed68ec45b426. Report an issue: GitHub.