{"record":{"id":"3559b45cfb40511d","repo":"mastra-ai/mastra","slug":"failed-to-parse-a2a-stream-event-error-instance","errorCode":null,"errorMessage":"Failed to parse A2A stream event: ${error instanceof Error ? error.message : 'unknown parse error'}","messagePattern":"Failed to parse A2A stream event: (.+?)","errorType":"exception","errorClass":null,"httpStatus":null,"severity":"error","filePath":"client-sdks/client-js/src/utils/process-a2a-stream.ts","lineNumber":43,"sourceCode":"\n  if (!trimmedBlock) {\n    return {};\n  }\n\n  const lines = trimmedBlock.split(/\\r?\\n/);\n  const dataLines = lines.filter(line => line.startsWith('data:')).map(line => line.slice(5).trimStart());\n\n  const payload = dataLines.length > 0 ? dataLines.join('\\n') : trimmedBlock;\n\n  if (!payload || payload === '[DONE]') {\n    return { done: true };\n  }\n\n  let parsed: unknown;\n  try {\n    parsed = JSON.parse(payload);\n  } catch (error) {\n    throw new Error(\n      `Failed to parse A2A stream event: ${error instanceof Error ? error.message : 'unknown parse error'}`,\n    );\n  }\n\n  if (parsed && typeof parsed === 'object' && 'error' in parsed && parsed.error) {\n    throw new MastraClientError(200, 'OK', `A2A stream error - ${JSON.stringify(parsed.error)}`, parsed.error);\n  }\n\n  if (parsed && typeof parsed === 'object' && 'result' in parsed) {\n    return { event: parsed.result as T };\n  }\n\n  return { event: parsed as T };\n}\n\nexport async function* processA2AStream<T = A2AStreamEventData>(\n  stream: globalThis.ReadableStream<Uint8Array>,\n): AsyncGenerator<T, void, undefined> {","sourceCodeStart":25,"sourceCodeEnd":61,"githubUrl":"https://github.com/mastra-ai/mastra/blob/75dd419e613fe9c39f846ffc500716141b74fda6/client-sdks/client-js/src/utils/process-a2a-stream.ts#L25-L61","documentation":"parseEventBlock in the A2A (Agent-to-Agent) stream processor expects each event payload line to be valid JSON. When JSON.parse fails, the client wraps the underlying parse error in this Error so developers know which streamed event could not be decoded.","triggerScenarios":"Consuming an A2A stream via the client where a data/event block contains malformed JSON — e.g. truncated lines from a broken connection, non-JSON output (HTML error page, plain text) served with a 200, or a custom server emitting improperly serialized events.","commonSituations":"A2A server behind a proxy that intercepts the stream and returns an HTML error page, partial writes when the connection drops mid-event, writing multiple JSON objects without proper newlines so blocks concatenate, or custom A2A agent implementations serializing with the wrong content/encoding.","solutions":["Log the raw payload line that failed to parse to see whether it is truncated, HTML, or concatenated JSON.","Ensure the A2A server emits newline-delimited, individually valid JSON objects with proper framing.","Check proxies/load balancers for response buffering or modification of the streaming response (disable buffering, fix error pages injected mid-stream).","Verify network stability / retry the stream on disconnect to avoid truncated final events.","Upgrade both @mastra/client-js and the A2A server package to compatible versions."],"exampleFix":"// before (server)\nres.write(JSON.stringify(event) + JSON.stringify(next)); // concatenated\n// after (server)\nres.write(JSON.stringify(event) + '\\n');\nres.write(JSON.stringify(next) + '\\n');","handlingStrategy":"try-catch","validationCode":"// validate each SSE data line before trusting it\nfunction isPlausibleJsonLine(line: string): boolean {\n  const t = line.trim();\n  return t.startsWith('{') && t.endsWith('}') || t.startsWith('[') && t.endsWith(']');\n}","typeGuard":"function isParsedA2AEvent(v: unknown): v is Record<string, unknown> {\n  try { JSON.parse(typeof v === 'string' ? v : JSON.stringify(v)); return typeof v === 'object' && v !== null; }\n  catch { return false; }\n}","tryCatchPattern":"try {\n  for await (const event of a2aStream) handle(event);\n} catch (e) {\n  if (e.message.startsWith('Failed to parse A2A stream event')) {\n    console.error('Malformed event from A2A server:', e.message);\n    // reconnect and resume stream, or log raw payload for server-side debugging\n  } else throw e;\n}","preventionTips":["Ensure the A2A server writes newline-delimited valid JSON events.","Disable proxy buffering/modification for streaming endpoints.","Retry streams on network interruption to avoid truncated events.","Pin compatible versions of client and A2A server packages."],"tags":["streaming","json","parsing","a2a","client"],"backgroundTag":"json-parse-failed","analyzedSha":"75dd419e613fe9c39f846ffc500716141b74fda6","analyzedAt":"2026-08-30T00:15:31.844Z","schemaVersion":2},"datasetVersion":"2026-08-30T03:17:51.788Z"}