Fix Tool Calling and Invalid JSON Errors
Most tool problems become easy once you know which of a handful of failure points you are looking at.
Find the stage that failed: was the tool offered, chosen, called with valid arguments, executed and reported back? Read the raw request and reply, validate every call in code, return helpful errors the model can act on, use strict schemas where supported and never accept a claim of success without a matching tool result.
What you will learn: how to diagnose agents that do not call tools, choose wrongly, produce invalid JSON or report results that never happened, and how to prevent each.
Prerequisites: Agent Tools, Function Calling and Tool Registries and Designing Tool Schemas and Contracts.
The example runs in November 2026 with Python 3.13 and only the standard library. The model replies are hand-written samples. API field names and options differ between providers and change, so check current documentation.
The path of a tool call
| Symptom | Failing stage | First thing to check |
|---|---|---|
| Answers from memory, no call | Offer or choose | Is the tool in the request that was actually sent? |
| Calls an unrelated tool | Choose | Overlapping names and descriptions |
| "Cannot parse" errors | Parse | Raw reply and stop reason |
| Tool rejects arguments | Parse or run | Schema against the real function |
| Model ignores the result | Return | Call identifier and message order |
| Claims an action that never happened | Answer | Is there a matching result in the trace? |
Log the exact request and raw response for a failing run, with secrets and personal data removed. Frameworks assemble messages for you, and the surprise is often visible in what they sent.
A diagnostic script
The script classifies sample replies the way a runtime should before it executes anything.
"""Classify tool-calling failures from raw model replies (invented replies)."""
import json
TOOLS = {"book_room": {"room": str, "date": str, "people": int}}
def diagnose(reply):
text = reply["text"].strip()
if reply["stop"] == "max_tokens":
return "truncated: raise the output limit or ask for less"
if not text.startswith(("{", "```")):
if "booked" in text.lower():
return "claimed success without calling a tool"
return "no tool call: check descriptions and tool choice settings"
if text.startswith("```"):
return "JSON wrapped in a code fence: use native tool calling"
try:
call = json.loads(text)
except json.JSONDecodeError as err:
return f"invalid JSON at position {err.pos}: {err.msg}"
schema = TOOLS.get(call.get("name"))
if schema is None:
return f"unknown tool {call.get('name')!r}"
args = call.get("arguments", {})
problems = [f"missing {k}" for k in schema if k not in args]
problems += [f"unexpected {k}" for k in args if k not in schema]
problems += [f"{k} must be {t.__name__}" for k, t in schema.items()
if k in args and type(args[k]) is not t]
return "; ".join(problems) or "ok"
def call(arguments, name="book_room", stop="tool_use"):
return {"stop": stop, "text": json.dumps({"name": name, "arguments": arguments})}
REPLIES = [
call({"room": "Oak", "date": "2027-01-12", "people": 4}),
call({"room": "Oak", "date": "2027-01-12", "people": "four"}),
call({"room": "Oak", "when": "tomorrow", "people": 4}),
call({"room": "Oak"}, name="reserve_room"),
{"stop": "tool_use", "text": '{"name": "book_room", "arguments": {"room": "Oak",}}'},
{"stop": "end_turn", "text": '```json\n{"name": "book_room"}\n```'},
{"stop": "max_tokens", "text": '{"name": "book_room", "argum'},
{"stop": "end_turn", "text": "Done, I have booked the Oak room for you."},
]
if __name__ == "__main__":
for number, reply in enumerate(REPLIES, 1):
print(f"{number}. {diagnose(reply)}")
Output:
1. ok
2. people must be int
3. missing date; unexpected when
4. unknown tool 'reserve_room'
5. invalid JSON at position 49: Illegal trailing comma before end of object
6. JSON wrapped in a code fence: use native tool calling
7. truncated: raise the output limit or ask for less
8. claimed success without calling a tool
Each category calls for a different fix. Type and missing-field errors point to the schema and error messages. An unknown tool means the model guessed a name. A truncated reply is a limit problem, not a formatting one. The last case is the most dangerous, because the text sounds finished although nothing ran.
The agent does not call tools
| Cause | How to confirm | Fix |
|---|---|---|
| Tools missing from the request | Inspect the outgoing payload | Register them; check filtering by user or step |
| Tool choice disabled | Check the tool-choice setting | Allow automatic choice, or require a call for that step |
| Model or endpoint lacks support | Run a one-tool minimal request | Use a supported model and request format |
| Vague description | Ask whether a new colleague would know when to use it | Say what it does, when to use it and when not |
| Prompt encourages answering directly | Search instructions for conflicts | State that facts of this kind must come from the tool |
| Too many tools or crowded context | Retry with only the relevant tools | Load tools by task; trim context |
| Earlier failures in history | Read the transcript | Summarize or reset the failed attempts |
Where a call is mandatory, such as reading a balance before quoting it, enforce that in code: run the lookup yourself, or refuse to send a final answer that lacks the required result.
Read the stop reason first
Model APIs report why generation ended, under names that differ by provider. Branch on that value before trying to parse anything.
| Why it ended | Meaning | What your code should do |
|---|---|---|
| Tool requested | The model wants one or more calls | Validate, authorize, execute and return every result |
| Normal completion | A final answer | Check that required tool results exist |
| Output limit | The reply was cut off | Do not parse or execute partial arguments; retry with room or a smaller task |
| Refusal or content filter | The model or service declined | Handle as its own path; do not loop on it |
| Error or dropped stream | No complete reply | Retry safely, after checking whether anything ran |
With streaming, arguments arrive in fragments. Assemble them until the stream says the block is complete, then parse once. A parser that runs on each fragment will report errors that are not really there.
The agent picks the wrong tool
- Rename tools so the verb and object are obvious:
search_ordersandcancel_order, notordersandhandle. - Separate overlapping tools, or merge them into one with a clear parameter.
- State boundaries in each description, including which tool to use instead.
- Offer fewer tools per step, chosen by the workflow.
- Add examples of confusing requests to your tests, then change one description at a time.
- Protect risky tools with policy checks, so a wrong choice cannot cause harm.
Count selections in a confusion table: for each expected tool, which tool was chosen? Two tools that trade places show exactly which descriptions to edit (Task, Tool and Planning Metrics).
Invalid JSON and schema errors
| Error | Typical cause | Fix |
|---|---|---|
| Trailing commas, single quotes, comments | Free-form text generation | Native tool calling or structured output |
| Text or code fences around JSON | Asking for JSON in prose | Structured output; do not rely on wording alone |
| Object cut off | Output limit reached or stream not assembled | Check the stop reason; raise the limit; buffer the stream |
| Wrong types | Loose schema | Types, enumerations, formats and required fields |
| Unexpected fields | Schema permits extras | Disallow additional properties |
| Valid shape, wrong values | Schema cannot know your data | Check against records and rules |
Providers offer features that constrain output to a schema. Claude's strict tool use uses grammar-constrained sampling so that tool inputs match the schema, with limits on which JSON Schema features are supported. OpenAI describes Structured Outputs for a similar purpose and notes that a refusal is reported separately, so handle that path too. These features address shape. A date in the right format can still be the wrong date, and a truncated or refused reply still needs handling.
Stripping a code fence is harmless. Guessing a missing value is not. Never "fix" arguments for an action that changes something; reject them and let the model or a person supply the right value.
Write errors the model can act on
"Bad request" invites the same call again. A useful error says what was wrong, what is allowed and whether retrying makes sense, without exposing internals.
{
"ok": false,
"error": "invalid_argument",
"message": "people must be an integer from 1 to 20; received the text 'four'",
"retryable": true
}
In the Model Context Protocol, a tool can return a normal result marked isError: true, which lets the model see the problem and correct itself, as distinct from a protocol-level JSON-RPC error. Input validation problems belong in the former. Limit corrections to a small number, then stop or hand over.
Layers of validation
Check each call in order, cheapest first, and report the first failure clearly.
| Layer | Booking example | On failure |
|---|---|---|
| Syntax | Valid JSON object | Ask for a corrected call |
| Schema | people is an integer; date is present | Name the field and the expected form |
| Business rules | Date is not in the past; room capacity suffices | Explain the rule and valid options |
| Permission | This user may book this room | Refuse without revealing others' data |
| Approval | Large events need a manager | Pause and request approval |
Only the first two layers are about the model's formatting. The others protect your system even when the call is perfectly formed, including when someone has manipulated the model into making it.
Invented tool results
An agent may state a price it never looked up, report an email as sent after a failure or describe a file it did not read. Common causes are an error result phrased like success, a missing result that the model fills in, examples in the prompt that show completed actions and history compression that drops failures.
- Return an explicit status for every call, including empty results.
- Require final answers to reference result identifiers, and verify them.
- Generate confirmations from system records: "Reservation R-1042 created" should be written by code from the tool's response.
- Check the claim against the environment in tests.
- Preserve failures when summarizing history.
- Allow the agent to say it could not do something.
Message order and identifiers
Most APIs require each tool call to be followed by a result carrying the same identifier, in the expected position. Errors appear when code drops a call while trimming history, answers only one of several parallel calls or edits earlier turns. Trim history in whole call-and-result pairs, answer every call, including those you refuse, and keep the provider's returned blocks as required by its documentation.
Parallel and repeated calls
If a model requests several actions at once, check whether they depend on each other. Run independent reads together; serialize writes and give each an idempotency key so that a retry cannot repeat it (Reliable Tool Execution and Error Recovery).
Reproduce, fix and prevent
- Capture the failing request, reply, versions and settings.
- Reduce to one tool and one message; add pieces back until it fails again.
- Repeat several times to measure how often it happens.
- Change one thing and measure again.
- Add the case to your regression set with a code check.
- Monitor the rate of invalid calls and corrections per tool.
A worked diagnosis
Report: the assistant says rooms are booked, but none appear.
Trace: the final replies contain no tool request at all.
Sent request: the booking tool is absent for users in one group.
Cause: a permission filter, changed in a release, removed the tool, while the prompt still described booking.
Fix: correct the filter; have the agent say when it lacks a capability; generate confirmations only from tool responses.
Prevention: a test per user group that checks the tool list and verifies a booking record.
The visible symptom looked like a model inventing results. The root cause was configuration, and the lasting protection is that a missing tool can no longer turn into a convincing confirmation.
Signals worth watching
| Signal | A rise may indicate |
|---|---|
| Invalid argument rate per tool | Schema drift, a model change or unclear descriptions |
| Unknown tool names | Stale prompts or renamed tools |
| Corrections per successful call | Weak error messages |
| Truncated replies | Growing inputs or low output limits |
| Final answers without required results | Invented outcomes |
When an API changes, update the schema, description, validation and tests together, and version the tool if older tasks may still be running (Tool Testing and Observability).
Common mistakes
| Mistake | Better approach |
|---|---|
| Adding "ALWAYS use tools!" to the prompt | Find why the call was not made; enforce required steps in code |
| Parsing JSON out of prose with patterns | Use native tool calls or structured output |
| Retrying forever on invalid calls | Limit attempts and report |
| Returning stack traces to the model | Return a short, safe, actionable error |
| Trusting a schema-valid argument | Check permissions and business rules |
| Believing "done" in the reply | Verify the tool result and the system record |
Tool troubleshooting checklist
- The sent request contains the intended tools and settings.
- Names and descriptions say when each tool applies.
- Arguments are validated against schema and business rules.
- Stop reasons, refusals and truncation are handled.
- Errors tell the model what to change and whether to retry.
- Every call receives a result with the matching identifier.
- Claims of action are verified against results.
- The failure is now a regression case with a monitored rate.
Frequently asked questions
Should I force a tool call?
Force it only for steps where a call is always correct, because forcing in other situations produces pointless or invented arguments.
Does lowering temperature fix invalid JSON?
It may reduce variation where the setting is available, but schema-constrained features and validation are far more dependable.
Why did tool calls break after a model upgrade?
Choice behavior, formats or parameters can differ, so rerun tool tests and read the migration notes for the new model.
Can the framework handle all of this?
Frameworks help with parsing and retries, but business validation, permissions and verification remain your responsibility.
References and further reading
- Claude tool use documentation: request and result format.
- Claude strict tool use: schema-constrained tool inputs.
- OpenAI Structured Outputs announcement: constrained output and refusals.
- MCP SEP-1303: input validation errors as tool execution errors.
- Understanding JSON Schema: types and constraints.
Next steps
Fix Loops, Memory, Handoff, RAG and SQL Errors
Fix repeating, forgetting and wrong data.
Message Roles, Structured Output and Function Calling
Get data your code can rely on.
Debugging Agents, RAG and Handoffs
Use traces and replay to find causes.