mastra-ai/mastra · error · Error
Failed to parse working memory input as JSON: ${errorMessage
Error message
Failed to parse working memory input as JSON: ${errorMessage}. Raw input: ${memoryInput.length > 500 ? memoryInput.slice(0, 500) + '...' : memoryInput} What it means
In schema-based (merge-semantics) working memory, the model passed the memory field as a string that is not valid JSON, so it cannot be merged into the stored JSON document. Mastra wraps the underlying JSON.parse error and includes a truncated copy of the raw input (max 500 chars) to help debug what the LLM emitted.
Source
Thrown at packages/memory/src/tools/working-memory.ts:265
// If existing data is not valid JSON, start fresh
existingData = null;
}
}
// Handle case where LLM passes empty object or no memory field
const memoryInput = workingMemoryInput.memory;
if (memoryInput === undefined || memoryInput === null) {
// No data to update - return existing data unchanged
return { success: true, message: 'No memory data provided, existing memory unchanged.' };
}
let newData: unknown;
if (typeof memoryInput === 'string') {
try {
newData = JSON.parse(memoryInput);
} catch (parseError) {
const errorMessage = parseError instanceof Error ? parseError.message : String(parseError);
throw new Error(
`Failed to parse working memory input as JSON: ${errorMessage}. ` +
`Raw input: ${memoryInput.length > 500 ? memoryInput.slice(0, 500) + '...' : memoryInput}`,
);
}
} else {
newData = memoryInput;
}
const mergedData = deepMergeWorkingMemory(existingData, newData as Record<string, unknown>);
workingMemory = JSON.stringify(mergedData);
} else {
// Template-based (Markdown): use existing replace semantics
const memoryInput = workingMemoryInput.memory;
workingMemory = typeof memoryInput === 'string' ? memoryInput : JSON.stringify(memoryInput);
// Validate that we're not replacing good data with an empty template
// This prevents accidental data loss when the LLM returns just the template
const existingRaw = await memory.getWorkingMemory({View on GitHub (pinned to 75dd419e61)
Solutions
- Strengthen the tool prompt/description so the model knows schema-mode memory must be valid JSON (the tool description already asks for merge-friendly JSON; make your schema fields obvious).
- Parse/repair on your side by adding a memory processor or custom tool wrapper that strips code fences and retries the call.
- Check the raw input in the error message for code fences or prose and adjust prompts accordingly.
- Consider using template-based working memory (no schema) if you actually want Markdown replacement semantics instead of JSON merge.
Example fix
// before (model output, fails)
memory: '{ name: "Sam", likes: pizza }'
// after (valid JSON string)
memory: '{"name":"Sam","likes":"pizza"}' Defensive patterns
Strategy: validation
Validate before calling
function isSerializableJson(value: string): boolean {
try { JSON.parse(value); return true; } catch { return false; }
}
// validate the tool input before accepting it
if (typeof modelOutput.memory === 'string' && !isSerializableJson(modelOutput.memory)) {
// retry the model call with a stricter instruction
} Type guard
const isJsonString = (v: string): boolean => {
if (typeof v !== 'string') return false;
try { JSON.parse(v); return true; } catch { return false; }
}; Try / catch
try {
await agent.generate(input, opts);
} catch (e) {
if (e instanceof Error && e.message.startsWith('Failed to parse working memory input as JSON')) {
// inspect e.message for the raw input; retry with corrected prompt
}
} Prevention
- Include 'pass valid JSON' examples in the agent instructions when using schema working memory.
- Strip markdown code fences from model output via a processor before the tool runs.
- Test the exact tool description against your model of choice; weaker models need more explicit JSON instructions.
- Use template (Markdown) working memory if you prefer prose over JSON.
When it happens
Trigger: The LLM calls the update-working-memory tool with memory as a string containing Markdown, prose, trailing commas, single quotes, or comments instead of a JSON document, while working memory is configured with a JSON schema.
Common situations: Model ignores the 'pass data as JSON string' instruction and writes natural language; template/Markdown habits leaking into schema-mode memory; model emits code fences (```json ... ```) inside the string; malformed escaping of quotes in the JSON string.
Understand the failure class
Background: JSON parse error: "Unexpected token" / "not valid JSON" / "failed to parse" — what JSON parsers are really complaining about — this error's family across 45 libraries.
- Parsing and encoding errors: unexpected token, malformed input — why parsers reject input and how to find the real culprit.
Related errors
- ${EXTRACTED_VALUES_TAG} must contain a JSON object.
- Failed to parse A2A stream event: ${error instanceof Error ?
- Linear cursor is invalid.
- The workingMemory.use option has been removed. Working memor
- WORKING_MEMORY_MISSING_STORAGE_ADAPTER
AI-assisted analysis of mastra-ai/mastra@75dd419e61 (2026-08-30).
Data as JSON: /api/errors/54cd97472138f571.
Report an issue: GitHub.