{"record":{"id":"817eb9a49c0cf444","repo":"mastra-ai/mastra","slug":"unable-to-persist-request-context-key-key-th","errorCode":null,"errorMessage":"Unable to persist request context key \"${key}\": the value is not valid schema input and cannot be encoded from the schema output.","messagePattern":"Unable to persist request context key \"(.+?)\": the value is not valid schema input and cannot be encoded from the schema output\\.","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"packages/core/src/tools/tool.ts","lineNumber":108,"sourceCode":"    super(Object.entries({ ...source.all, ...transformedValues }));\n    this.#source = source;\n    this.#acceptsInput = acceptsInput;\n    this.#encode = encode;\n    Object.defineProperty(this, REQUEST_CONTEXT_INPUT_SOURCE, { value: source });\n  }\n\n  #getSourceValue(key: string, value: unknown): unknown {\n    const nextSourceValues = { ...this.#source.all, [key]: value };\n    if (this.#acceptsInput(nextSourceValues)) {\n      return value;\n    }\n\n    const encodedValues = this.#encode?.({ ...this.all, [key]: value });\n    if (encodedValues && Object.prototype.hasOwnProperty.call(encodedValues, key)) {\n      return encodedValues[key];\n    }\n\n    throw new Error(\n      `Unable to persist request context key \"${key}\": the value is not valid schema input and cannot be encoded from the schema output.`,\n    );\n  }\n\n  public override set(key: string, value: any): void {\n    const sourceValue = this.#getSourceValue(key, value);\n    this.#source.setRaw(key, sourceValue);\n    super.set(key, value);\n  }\n\n  public override setRaw(key: string, value: unknown): void {\n    const sourceValue = this.#getSourceValue(key, value);\n    this.#source.setRaw(key, sourceValue);\n    super.setRaw(key, value);\n  }\n\n  public override delete(key: string): boolean {\n    this.#source.deleteRaw(key);","sourceCodeStart":90,"sourceCodeEnd":126,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/packages/core/src/tools/tool.ts#L90-L126","documentation":"The TransformedRequestContext wraps a schema-backed request context: when you `set()` a value, Mastra first checks the raw value is valid schema input, and otherwise tries to re-encode it via the schema's `safeEncode` (Zod transforms). If the value is neither valid input nor encodable back to input form (e.g. one-way transforms like `.transform()` without `.preprocess`, or non-Zod schemas), the mutation cannot be persisted to the underlying context and this error is thrown.","triggerScenarios":"Calling `requestContext.set(key, value)` (or setRaw) inside a tool execute where: the key's value fails the context schema as raw input, AND the schema lacks an encoder (not Zod with safeEncode, or Zod schema uses unidirectional `.transform()` so `safeEncode` fails/returns undefined for that key).","commonSituations":"Tool code mutating request context at runtime when the context schema uses `.transform()` for derived fields; passing values of the wrong type (e.g. a Date where a string is expected); using non-Zod schemas (Valibot/ArkType) that provide no encode path.","solutions":["Set the raw value in a form that directly satisfies the request-context input schema (validate the value against the schema first).","Use Zod schemas with bidirectional transforms (`.preprocess`/decode+encode via z.encode()) so the value can be re-encoded; avoid one-way `.transform()` for keys you will mutate.","If the schema intentionally transforms the key, write to the original request context (the source) with raw input values instead of the transformed wrapper."],"exampleFix":"// before\nrequestContext.set('dueDate', new Date()); // schema expects ISO string via .transform()\n// after\nrequestContext.set('dueDate', new Date().toISOString());","handlingStrategy":"validation","validationCode":"function canPersist(ctxSchema: StandardSchemaV1, key: string, value: unknown): boolean {\n  const res = ctxSchema['~standard'].validate({ [key]: value });\n  return !(res instanceof Promise) && !('issues' in res && res.issues?.length);\n}\n// call canPersist(schema, key, value) before requestContext.set(key, value)","typeGuard":"function isEncodableZodSchema(schema: unknown): schema is { safeEncode: (v: unknown) => { success: boolean; data?: unknown }; '~standard': { vendor: string } } {\n  const s = schema as any;\n  return s?.['~standard']?.vendor === 'zod' && typeof s?.safeEncode === 'function';\n}","tryCatchPattern":"try {\n  requestContext.set(key, value);\n} catch (e) {\n  if (e instanceof Error && e.message.includes('Unable to persist request context key')) {\n    throw new Error(`Value for \"${key}\" must satisfy the requestContext schema input, or the schema must support encoding.`);\n  }\n  throw e;\n}","preventionTips":["Prefer `.preprocess()`/bidirectional Zod transforms over one-way `.transform()` for request-context keys you mutate at runtime.","Write raw input-typed values (matching the schema input, not its output) when calling set().","Remember only Zod schemas expose the encode path; Valibot/ArkType schemas must receive valid raw input directly."],"tags":["request-context","schema","encoding","validation"],"backgroundTag":"schema-validation-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T08:17:16.595Z"}