mastra-ai/mastra · error

Request context validation failed for workflow '${this.workf

Error message

Request context validation failed for workflow '${this.workflowId}': \n${errors.map(e => { const pathStr = e.path?.map(p => (typeof p === 'object' ? p.key : p)).join('.'); return `- ${pathStr}: ${e.message}`; }).join('\n')}

What it means

This is the sync validation-failure branch of `_validateRequestContext`: when request-context values fail the (sync) `requestContextSchema`, Mastra throws an Error enumerating each issue's dotted path and message, prefixed with the workflow id.

Source

Thrown at packages/core/src/workflows/workflow.ts:3500

    if (!this.validateInputs || !this.stateSchema) {
      return initialState;
    }

    return this.#validateSchema(this.stateSchema, initialState, 'initial data');
  }

  protected async _validateRequestContext(requestContext?: RequestContext) {
    if (this.validateInputs && this.requestContextSchema) {
      const contextValues = getRequestContextInputValues(requestContext);
      const validation = this.requestContextSchema['~standard'].validate(contextValues);

      if (validation instanceof Promise) {
        throw new Error('Your schema is async, which is not supported. Please use a sync schema.');
      }

      if (!('value' in validation)) {
        const errors = validation.issues;
        throw new Error(
          `Request context validation failed for workflow '${this.workflowId}': \n` +
            errors
              .map(e => {
                const pathStr = e.path?.map(p => (typeof p === 'object' ? p.key : p)).join('.');
                return `- ${pathStr}: ${e.message}`;
              })
              .join('\n'),
        );
      }
    }
  }

  protected async _validateResumeData<TResume>(resumeData: TResume, suspendedStep?: StepWithComponent) {
    if (!this.validateInputs || !suspendedStep?.resumeSchema) {
      return resumeData;
    }

    return this.#validateSchema(suspendedStep.resumeSchema, resumeData, 'resume data');

View on GitHub (pinned to 75dd419e61)

Solutions

  1. Read the `- path: message` lines and correct the requestContext values to match requestContextSchema.
  2. Parse request context with the schema (`requestContextSchema.parse(values)`) at the entry point before createRun.
  3. Give optional fields defaults in the schema (`z.string().default(...)`) where appropriate.
  4. Ensure all call sites (API routes, cron jobs) supply the newly required context keys.

Example fix

// before
await workflow.createRun({ requestContext: { tenantId: undefined } });
// after
const rc = workflow.requestContextSchema.parse({ tenantId: req.headers['x-tenant-id'] });
await workflow.createRun({ requestContext: rc });
Defensive patterns

Strategy: validation

Validate before calling

const rc = workflow.requestContextSchema.safeParse(requestContext);
if (!rc.success) {
  throw new Error(rc.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('\n'));
}
await workflow.createRun({ requestContext: rc.data });

Type guard

function isValidRequestContext<S extends z.ZodTypeAny>(schema: S, data: unknown): data is z.infer<S> {
  return schema.safeParse(data).success;
}

Try / catch

try {
  await workflow.createRun({ requestContext });
} catch (e) {
  if (e instanceof Error && e.message.startsWith('Request context validation failed')) {
    console.error('fix requestContext per:', e.message);
  } else throw e;
}

Prevention

When it happens

Trigger: Calling `workflow.createRun()` / `start()` / `execute()` with a `requestContext` whose values violate `requestContextSchema` while `validateInputs: true` — wrong types, missing required keys, failed sync refinements.

Common situations: Request context built dynamically from env/HTTP headers with missing or mistyped values; schema updated to require new fields while call sites weren't; tenant/role values passing null where strings are required.

Related errors


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