API 400: request body is not valid JSON (truncated mid-stream) after large tool output
Description
Twice in one session, a request to the API failed with a 400 error indicating the request body was truncated JSON:
API Error: 400 The request body is not valid JSON: unexpected end of data: line 1 column 996035 (char 996034)
and later in the same session:
API Error: 400 The request body is not valid JSON: unexpected end of data: line 1 column 157293 (char 157292)
Both errors were fatal to the turn — the assistant produced no other response, and the only way to recover was to /clear and start a new session, losing all context from the prior turns.
Context / suspected trigger
Both crashes occurred while investigating a local IoT device (an openHASP display reachable over the LAN, e.g. http://192.168.1.203/) to verify its MQTT connectivity to Home Assistant. Immediately before each crash, tool calls had fetched/read data from the device (a mix of a grep search, directory listing, file read, and a few shell commands, e.g. curling the device's web UI / config endpoints).
The working hypothesis is that one of those tool calls returned an unusually large result (raw HTML/JSON/config blob from the device), and when the harness serialized that tool result into the next request body sent to the API, the body got truncated partway through (cut off at ~996KB, then later ~157KB) rather than being sent whole or erroring gracefully before the request went out. The API then correctly rejects it as invalid JSON, but the failure is opaque to the user and unrecoverable within the session.
Impact
- Session becomes unusable after the error — no further assistant responses are produced for that turn or (in this case) subsequent prompts either, forcing a full
/clear. - All conversation context is lost, including in-progress investigation work.
- No user-facing indication of why the request failed (e.g. "a tool result exceeded N bytes and was truncated") — just a raw API 400.
Suggested fix directions
- Validate/guard tool-result payload size client-side before constructing the request body, and either truncate cleanly with a visible marker, or reject with a clear client-side error, rather than sending a truncated JSON body to the API.
- Ensure whatever mechanism serializes tool results into the request stream doesn't cut off mid-write when a size limit or buffer boundary is hit.
Environment
- Claude Code CLI
- macOS (Darwin 24.6.0)