mastra-ai/mastra · error
Unable to persist request context key "${key}": the value is
Error message
Unable to persist request context key "${key}": the value is not valid schema input and cannot be encoded from the schema output. What it means
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.
Source
Thrown at packages/core/src/tools/tool.ts:108
super(Object.entries({ ...source.all, ...transformedValues }));
this.#source = source;
this.#acceptsInput = acceptsInput;
this.#encode = encode;
Object.defineProperty(this, REQUEST_CONTEXT_INPUT_SOURCE, { value: source });
}
#getSourceValue(key: string, value: unknown): unknown {
const nextSourceValues = { ...this.#source.all, [key]: value };
if (this.#acceptsInput(nextSourceValues)) {
return value;
}
const encodedValues = this.#encode?.({ ...this.all, [key]: value });
if (encodedValues && Object.prototype.hasOwnProperty.call(encodedValues, key)) {
return encodedValues[key];
}
throw new Error(
`Unable to persist request context key "${key}": the value is not valid schema input and cannot be encoded from the schema output.`,
);
}
public override set(key: string, value: any): void {
const sourceValue = this.#getSourceValue(key, value);
this.#source.setRaw(key, sourceValue);
super.set(key, value);
}
public override setRaw(key: string, value: unknown): void {
const sourceValue = this.#getSourceValue(key, value);
this.#source.setRaw(key, sourceValue);
super.setRaw(key, value);
}
public override delete(key: string): boolean {
this.#source.deleteRaw(key);View on GitHub (pinned to 75dd419e61)
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.
Example fix
// before
requestContext.set('dueDate', new Date()); // schema expects ISO string via .transform()
// after
requestContext.set('dueDate', new Date().toISOString()); Defensive patterns
Strategy: validation
Validate before calling
function canPersist(ctxSchema: StandardSchemaV1, key: string, value: unknown): boolean {
const res = ctxSchema['~standard'].validate({ [key]: value });
return !(res instanceof Promise) && !('issues' in res && res.issues?.length);
}
// call canPersist(schema, key, value) before requestContext.set(key, value) Type guard
function isEncodableZodSchema(schema: unknown): schema is { safeEncode: (v: unknown) => { success: boolean; data?: unknown }; '~standard': { vendor: string } } {
const s = schema as any;
return s?.['~standard']?.vendor === 'zod' && typeof s?.safeEncode === 'function';
} Try / catch
try {
requestContext.set(key, value);
} catch (e) {
if (e instanceof Error && e.message.includes('Unable to persist request context key')) {
throw new Error(`Value for "${key}" must satisfy the requestContext schema input, or the schema must support encoding.`);
}
throw e;
} Prevention
- 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.
When it happens
Trigger: 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).
Common situations: 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.
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
- Request context validation failed for workflow '${this.workf
- ${label} contains an unsupported field.
- [FactorySecretEncryption] Invalid encrypted value.
- AGENT_REQUEST_CONTEXT_VALIDATION_FAILED
- Invalid state update: ${messages}
AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30).
Data as JSON: /api/errors/817eb9a49c0cf444.
Report an issue: GitHub.