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.

BeginnerIntermediateExpert · 12 min read · Last updated:

In short

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.

Versions used

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.

Beginner Locate the failure

The path of a tool call

1. Offertool is in the request
2. Choosemodel picks it
3. Parseyour code checks arguments
4. Runtool executes
5. Returnresult goes back
6. Answermodel replies
SymptomFailing stageFirst thing to check
Answers from memory, no callOffer or chooseIs the tool in the request that was actually sent?
Calls an unrelated toolChooseOverlapping names and descriptions
"Cannot parse" errorsParseRaw reply and stop reason
Tool rejects argumentsParse or runSchema against the real function
Model ignores the resultReturnCall identifier and message order
Claims an action that never happenedAnswerIs there a matching result in the trace?
Look at the wire

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

CauseHow to confirmFix
Tools missing from the requestInspect the outgoing payloadRegister them; check filtering by user or step
Tool choice disabledCheck the tool-choice settingAllow automatic choice, or require a call for that step
Model or endpoint lacks supportRun a one-tool minimal requestUse a supported model and request format
Vague descriptionAsk whether a new colleague would know when to use itSay what it does, when to use it and when not
Prompt encourages answering directlySearch instructions for conflictsState that facts of this kind must come from the tool
Too many tools or crowded contextRetry with only the relevant toolsLoad tools by task; trim context
Earlier failures in historyRead the transcriptSummarize 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 endedMeaningWhat your code should do
Tool requestedThe model wants one or more callsValidate, authorize, execute and return every result
Normal completionA final answerCheck that required tool results exist
Output limitThe reply was cut offDo not parse or execute partial arguments; retry with room or a smaller task
Refusal or content filterThe model or service declinedHandle as its own path; do not loop on it
Error or dropped streamNo complete replyRetry 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.

Intermediate Selection and arguments

The agent picks the wrong tool

  • Rename tools so the verb and object are obvious: search_orders and cancel_order, not orders and handle.
  • 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

ErrorTypical causeFix
Trailing commas, single quotes, commentsFree-form text generationNative tool calling or structured output
Text or code fences around JSONAsking for JSON in proseStructured output; do not rely on wording alone
Object cut offOutput limit reached or stream not assembledCheck the stop reason; raise the limit; buffer the stream
Wrong typesLoose schemaTypes, enumerations, formats and required fields
Unexpected fieldsSchema permits extrasDisallow additional properties
Valid shape, wrong valuesSchema cannot know your dataCheck 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.

Repair with care

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.

Syntaxparses
Schematypes
Rulesvalues
Accessallowed
LayerBooking exampleOn failure
SyntaxValid JSON objectAsk for a corrected call
Schemapeople is an integer; date is presentName the field and the expected form
Business rulesDate is not in the past; room capacity sufficesExplain the rule and valid options
PermissionThis user may book this roomRefuse without revealing others' data
ApprovalLarge events need a managerPause 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.

Expert False claims and prevention

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

  1. Capture the failing request, reply, versions and settings.
  2. Reduce to one tool and one message; add pieces back until it fails again.
  3. Repeat several times to measure how often it happens.
  4. Change one thing and measure again.
  5. Add the case to your regression set with a code check.
  6. Monitor the rate of invalid calls and corrections per tool.

A worked diagnosis

Illustrative case: bookings stopped working

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

SignalA rise may indicate
Invalid argument rate per toolSchema drift, a model change or unclear descriptions
Unknown tool namesStale prompts or renamed tools
Corrections per successful callWeak error messages
Truncated repliesGrowing inputs or low output limits
Final answers without required resultsInvented 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

MistakeBetter approach
Adding "ALWAYS use tools!" to the promptFind why the call was not made; enforce required steps in code
Parsing JSON out of prose with patternsUse native tool calls or structured output
Retrying forever on invalid callsLimit attempts and report
Returning stack traces to the modelReturn a short, safe, actionable error
Trusting a schema-valid argumentCheck permissions and business rules
Believing "done" in the replyVerify 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

Next steps