The 5-Strategy JSON Parser That Took Tool Calls from 70% to 95%
Every tutorial about building AI agents has the same assumption baked in: the model returns valid JSON, you parse it, you call the tool. In practice, especially with streaming responses across 11 different providers, this assumption breaks constantly.
I discovered this the hard way while building Gogaa CLI. Tool calls would randomly fail. Not because the model made a bad decision, but because the JSON was malformed. Truncated strings from streaming cutoffs. Double-escaped characters from models that over-sanitize their output. Extra whitespace around the JSON block. Partial objects that cut off mid-key because the response hit a token limit.
The problem nobody talks about
A single JSON.parse throws on any of these, and the tool call is lost. The agent retries, burns tokens, and often produces a worse result the second time because its context now includes a confusing error message. On real agentic sessions across multiple providers, I measured a ~70% success rate for tool call parsing with naive JSON.parse.
Thirty percent of tool calls silently failing is not a minor inconvenience. It is the difference between an agent that reliably completes multi-step tasks and one that randomly falls apart.
Five strategies, progressive fallback
The parser tries five strategies in order, each progressively looser: strict JSON.parse on the raw input. Trim whitespace and strip markdown code fences, then parse. Unescape double-escaped characters (\\n to \n, \\" to \"), then parse. Attempt partial object reconstruction by finding the last complete key-value pair and closing the object. Finally, extract any JSON-like substring from the response and parse that.
When a strategy partially recovers the input, it injects an error recovery hint into the tool result. The model sees something like 'Parsed with recovery: original input had trailing truncation. Please verify the file_path argument.' This gives the model enough information to retry correctly if the recovered parse was wrong, without the confusing generic error that causes hallucinated retries.
The result
Tool call success went from ~70% to ~95% on real agentic sessions. The remaining 5% are genuinely malformed outputs where the model produced something that isn't JSON at all, and those get a clear error message that leads to a clean retry.
This is not glamorous work. Nobody writes conference talks about JSON parsing. But it is the kind of infrastructure that separates a demo from a tool people actually use for hours at a time. If you are building an AI agent and your tool calls occasionally fail for no apparent reason, your parser is probably the problem.