{"record":{"id":"6578aebc3c0de8e9","repo":"mastra-ai/mastra","slug":"agent-request-context-validation-failed","errorCode":"AGENT_REQUEST_CONTEXT_VALIDATION_FAILED","errorMessage":"Request context validation failed for agent '${this.id}':\n${errorMessages}","messagePattern":"Request context validation failed for agent '(.+?)':\n(.+?)","errorType":"error_code","errorClass":"MastraError","httpStatus":null,"severity":"error","filePath":"packages/core/src/agent/agent.ts","lineNumber":1507,"sourceCode":"\n  /**\n   * Validates the request context against the agent's requestContextSchema.\n   * Throws an error if validation fails.\n   */\n  async #validateRequestContext(requestContext?: RequestContext) {\n    if (this.#requestContextSchema) {\n      const contextValues = getRequestContextInputValues(requestContext);\n      const validation = await this.#requestContextSchema['~standard'].validate(contextValues);\n\n      if (validation.issues) {\n        const errors = validation.issues;\n        const errorMessages = errors\n          .map(e => {\n            const pathStr = e.path?.map((p: any) => (typeof p === 'object' ? p.key : p)).join('.');\n            return `- ${pathStr}: ${e.message}`;\n          })\n          .join('\\n');\n        throw new MastraError({\n          id: 'AGENT_REQUEST_CONTEXT_VALIDATION_FAILED',\n          domain: ErrorDomain.AGENT,\n          category: ErrorCategory.USER,\n          text: `Request context validation failed for agent '${this.id}':\\n${errorMessages}`,\n          details: {\n            agentId: this.id,\n            agentName: this.name,\n          },\n        });\n      }\n    }\n  }\n\n  /**\n   * Extract and forward client observability data from incoming messages.\n   *\n   * ## How client-side tool observability flows through the system\n   *","sourceCodeStart":1489,"sourceCodeEnd":1525,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/agent/agent.ts#L1489-L1525","documentation":"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.","triggerScenarios":"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.","commonSituations":"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.","solutions":["Read the per-path messages in the error text and fix the listed requestContext fields at the call site.","Validate the context object with the agent's requestContext schema before invoking the agent.","Ensure required env-backed values are actually present (undefined/empty strings often fail schemas).","If the schema is too strict, update the agent's requestContext schema to match legitimate inputs."],"exampleFix":"// before\nawait agent.generate(prompt, { requestContext: { temperature: \"0.7\", userId: undefined } });\n// after\nawait agent.generate(prompt, { requestContext: { temperature: 0.7, userId: 'u-123' } });","handlingStrategy":"validation","validationCode":"import { z } from 'zod';\nconst ctxSchema = z.object({ userId: z.string().min(1), temperature: z.number().min(0).max(2) });\nexport function validateRequestContext(ctx: unknown) {\n  const r = ctxSchema.safeParse(ctx);\n  if (!r.success) throw new Error(`Invalid request context: ${r.error.issues.map(i => `${i.path.join('.')}: ${i.message}`).join('; ')}`);\n  return r.data;\n}","typeGuard":"function isRequestContext(v: unknown): v is Record<string, unknown> {\n  return typeof v === 'object' && v !== null && !Array.isArray(v);\n}","tryCatchPattern":"try {\n  await agent.generate(prompt, { requestContext: ctx });\n} catch (err) {\n  if ((err as any).id === 'AGENT_REQUEST_CONTEXT_VALIDATION_FAILED') {\n    console.error(`Fix request context for agent ${(err as any).details?.agentId}:\\n${(err as Error).message}`);\n  }\n  throw err;\n}","preventionTips":["Parse request context with the agent's schema (safeParse) at the call site before invoking.","Keep a shared Zod schema exported next to the agent so callers import and validate it.","Guard env-backed fields: fail fast on undefined/empty strings during boot, not at call time.","Log the failing path list from the error message — each '- path: message' line pinpoints a field."],"tags":["agent","request-context","validation","zod"],"backgroundTag":"schema-validation-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}