mastra-ai/mastra · error · MastraError

AGENT_REQUEST_CONTEXT_VALIDATION_FAILED

AGENT_REQUEST_CONTEXT_VALIDATION_FAILED

Error message

Request context validation failed for agent '${this.id}':
${errorMessages}

What it means

Agents validate the request context (runtimeContext / requestContext input) against a declared schema. When validation fails, Mastra aggregates all Zod/path errors into a bullet list and throws AGENT_REQUEST_CONTEXT_VALIDATION_FAILED including the agent id and each failing path. It is a USER-category error: the input you supplied at call time does not match the agent's requestContext schema.

Source

Thrown at packages/core/src/agent/agent.ts:1507

  /**
   * Validates the request context against the agent's requestContextSchema.
   * Throws an error if validation fails.
   */
  async #validateRequestContext(requestContext?: RequestContext) {
    if (this.#requestContextSchema) {
      const contextValues = getRequestContextInputValues(requestContext);
      const validation = await this.#requestContextSchema['~standard'].validate(contextValues);

      if (validation.issues) {
        const errors = validation.issues;
        const errorMessages = errors
          .map(e => {
            const pathStr = e.path?.map((p: any) => (typeof p === 'object' ? p.key : p)).join('.');
            return `- ${pathStr}: ${e.message}`;
          })
          .join('\n');
        throw new MastraError({
          id: 'AGENT_REQUEST_CONTEXT_VALIDATION_FAILED',
          domain: ErrorDomain.AGENT,
          category: ErrorCategory.USER,
          text: `Request context validation failed for agent '${this.id}':\n${errorMessages}`,
          details: {
            agentId: this.id,
            agentName: this.name,
          },
        });
      }
    }
  }

  /**
   * Extract and forward client observability data from incoming messages.
   *
   * ## How client-side tool observability flows through the system
   *

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Read the per-path messages in the error text and fix the listed requestContext fields at the call site.
  2. Validate the context object with the agent's requestContext schema before invoking the agent.
  3. Ensure required env-backed values are actually present (undefined/empty strings often fail schemas).
  4. If the schema is too strict, update the agent's requestContext schema to match legitimate inputs.

Example fix

// before
await agent.generate(prompt, { requestContext: { temperature: "0.7", userId: undefined } });
// after
await agent.generate(prompt, { requestContext: { temperature: 0.7, userId: 'u-123' } });
Defensive patterns

Strategy: validation

Validate before calling

import { z } from 'zod';
const ctxSchema = z.object({ userId: z.string().min(1), temperature: z.number().min(0).max(2) });
export function validateRequestContext(ctx: unknown) {
  const r = ctxSchema.safeParse(ctx);
  if (!r.success) throw new Error(`Invalid request context: ${r.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ')}`);
  return r.data;
}

Type guard

function isRequestContext(v: unknown): v is Record<string, unknown> {
  return typeof v === 'object' && v !== null && !Array.isArray(v);
}

Try / catch

try {
  await agent.generate(prompt, { requestContext: ctx });
} catch (err) {
  if ((err as any).id === 'AGENT_REQUEST_CONTEXT_VALIDATION_FAILED') {
    console.error(`Fix request context for agent ${(err as any).details?.agentId}:\n${(err as Error).message}`);
  }
  throw err;
}

Prevention

When it happens

Trigger: Calling generate/stream/loop (or starting a workflow-backed agent) on an Agent with a requestContext schema while passing runtime context values that fail that schema — wrong types, missing required fields, or unknown values.

Common situations: Passing string values where the schema expects numbers, forgetting a required context field added by a teammate, sending nested objects whose keys don't match the schema path, or env-derived values that are undefined at runtime.

Understand the failure class

Background: Schema validation failed / invalid input schema: payload rejected because its shape doesn't match the expected schema — this error's family across 28 libraries.

Related errors


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