Skip to content

Module 03 · Lesson 3.2

Designing Tool Schemas and Validating Arguments

45 minUpdated 18 Nov 2026Part of Tools, APIs and Function Calling · AI Agent Development
On this page
  1. What you will learn
  2. What a tool contract and a tool schema are
  3. JSON Schema keywords every beginner needs
  4. How to write a good tool description
  5. Why you must validate arguments in your own code
  6. A validation checklist for every tool call
  7. Build a small argument validator in Python
  8. Conclusion and your next step
  9. Common errors and fixes
  10. Validation checklist
  11. Hands-on exercise
  12. Knowledge check
  13. Frequently asked questions
  14. References

Think of a paper return form at a shop counter. It has a box for the order number, a tick list of reasons and a short space for a note. A clerk glances at it and says "this number is wrong" before anything goes to the warehouse. The form and the glance are two separate protections.

An AI agent that uses tools needs both. The schema is the form: it tells the model exactly what to fill in. Validation is the clerk: your code checks what came back before the tool does anything real. This lesson shows you how to write the form, how to write the tool description, and how to build the check. Most of it needs no coding. One short Python example at the end runs the check on four sample calls.

What you will learn

  • Write a tool contract: a name, a description and a parameter schema.
  • Use the JSON Schema keywords type, properties, required, enum, pattern, maxLength and additionalProperties.
  • Explain why your own code must validate arguments even when the provider follows a schema.
  • Run a Python validator and return a clear error message that lets the model correct itself.

Before you start

What a tool contract and a tool schema are

In the last lesson the model asked for a tool and your code ran it. Now we look closely at the request itself. What exactly may the model send? You decide that in advance, and you write it down.

Tool contract
Everything you tell the model about one tool: its name, a description of what it does, and the list of arguments it accepts.
Argument
One value the model sends to a tool. For lookup_order, the argument is the order number.
Schema
The exact shape of the arguments, written in a standard format called JSON Schema. It says which arguments exist, their types and which values are allowed.
Validation
Checking the arguments against the schema in your own code, before the tool runs.

In Module 2 you wrote an output contract, which describes what the agent sends back to the customer. A tool contract goes the other way. It is an input contract: it describes what the model may send in.

We will use one tool through the whole lesson. Quillfeather Cycles, our made-up bike shop, has request_return(order_id, reason). It creates a return request that staff must approve. Staff stay in charge, but the tool does more than a read-only lookup, so its input needs more care.

Where the contract and the check sit
  1. Contract

    Name, description, schema

  2. Model

    Asks for a tool call

  3. Validation

    Your code checks the arguments

  4. Tool runs

    Only when the check passes

  5. Observation

    Result or error goes back to the model

The model reads the contract. Your code applies the check. The tool only runs if the check passes.

JSON Schema keywords every beginner needs

JSON Schema is a standard way to describe JSON data. You write rules as small keywords. You only need seven of them for most tools.

KeywordPlain meaningExample in request_return
typeWhat kind of value it is: text, number, true or false, and so on.order_id is a string (text).
propertiesThe list of arguments the tool accepts, each with its own rules.order_id, reason and note.
requiredArguments that must always be present.order_id and reason. The note may be left out.
enumA fixed list of allowed values. Nothing else passes.reason is damaged, wrong_size or changed_mind.
patternA text pattern the value must match, written as a regular expression.^QF-[0-9]{4}$ means QF, a dash, then four digits.
maxLengthThe longest text allowed, in characters.note is at most 200 characters.
additionalPropertiesWhether extra, unlisted arguments are allowed. Set to false to block them.No made-up arguments such as refund_amount.
These seven keywords cover most tool arguments. The full list is in the JSON Schema reference.

A regular expression (regex for short) is a compact way to describe a text pattern. You met ^QF-[0-9]{4}$ in the Module 2 lab. The ^ and $ mean the whole value must match, not just a piece of it.

The full contract for request_return

Here is the whole contract as JSON. Different providers wrap it slightly differently, so check your provider's page. The name, description and schema are the parts you always write.

JSONrequest_return.json
{
  "name": "request_return",
  "description": "Create a return request for one order. Use it only after the customer has said which order and why. Staff approve each request, so this does not refund anything. Returns whether the request is waiting for staff approval. Do not use it to check an order or to ask for a refund.",
  "parameters": {
    "type": "object",
    "properties": {
      "order_id": {
        "type": "string",
        "pattern": "^QF-[0-9]{4}$",
        "description": "Order number, for example QF-1042."
      },
      "reason": {
        "type": "string",
        "enum": ["damaged", "wrong_size", "changed_mind"],
        "description": "Why the customer wants to return the order."
      },
      "note": {
        "type": "string",
        "maxLength": 200,
        "description": "Optional extra detail from the customer."
      }
    },
    "required": ["order_id", "reason"],
    "additionalProperties": false
  }
}

Checked with Python's json.load. It is valid JSON.

What each part does

  • name is the label the model uses to ask for the tool. Keep it short and use the same style for every tool.
  • description tells the model when to use the tool. The next section covers how to write it.
  • "type": "object" says the arguments arrive as one group of named values.
  • Each entry under properties gives one argument its own type and rules. The short description inside each one tells the model what to put there.
  • required lists the two arguments that must be present. note is not listed, so it is optional.
  • additionalProperties: false closes the door on any argument not named above.

How to write a good tool description

The model cannot see your code. It only sees the contract. So the description is its single source of truth about the tool, and a vague one leads to wrong calls.

Compare it to a label on a tool in a shared workshop. "Saw" tells you little. "Fine-tooth saw for cutting thin plastic. Not for wood." tells you when to pick it up and when to leave it.

Say three things

  • When to use it. Name the situation. For example: after the customer has given an order and a reason.
  • What it returns. Say what comes back, so the model knows what to expect and what to tell the customer.
  • What it must not be used for. Name the nearby jobs it does not do. This stops the model from picking it by mistake.
Weak descriptionStronger description
Handles returns.Create a return request for one order. Use it only after the customer has said which order and why. Returns whether the request is waiting for staff approval. Does not refund anything.
Order tool.Look up one order by its number. Returns the status and estimated delivery date. Read-only. Do not use it to change or cancel an order.
The stronger versions state the when, the result and the limits.

Why you must validate arguments in your own code

Many providers can follow a schema you give them, and some can enforce it strictly. That is helpful. It still does not make it safe to skip the check in your code.

  • Models can still produce wrong values. A value may have the right type but the wrong meaning, such as an order that belongs to someone else.
  • Support differs between providers. Not every provider enforces every keyword, and the rules change over time.
  • Other callers exist. A test script, a bug or an attacker may send arguments that never came through the model.
  • Your code is the last gate. After validation, the next step is the real action: a database write, an email, a payment. Nothing stands behind your code.

A good comparison is a security guard at a building door. Even if every visitor was told the rules outside, the guard still checks badges. The guard is cheap, and a mistake at the door is expensive.

A validation checklist for every tool call

Run these checks in order, every time, before the tool runs. Collect all the problems you find, not just the first. Then the model can fix everything in one go.

CheckQuestionExample of a failure
Unknown toolIs there a tool with this name?The model asks for cancel_order, which does not exist.
Missing argumentIs every required argument present?reason is not sent.
Extra argumentIs every argument one the schema lists?refund_amount is sent.
Wrong typeIs each value the right kind?order_id is the number 1042, not text.
Wrong formatDoes the text match its pattern?order_id is "1042", not "QF-1042".
Value not allowedIs the value in the allowed list?reason is "refund_me".
Too longIs the text within its limit?note is 250 characters.
The first check happens before you even look at the arguments.

What to do when a check fails

  1. Do not run the tool. A failed check means the call is not safe to run.
  2. Return an error observation. An observation is the result you hand back to the model after a tool call. Make it a clear message in plain words.
  3. Name the problem and the fix. "reason must be one of: changed_mind, damaged, wrong_size" helps. "Invalid input" does not.
  4. Let the loop continue. The model reads the error and usually tries again with corrected arguments. The step limit, MAX_ROUNDS, stops it from trying forever.
JSON
{"error": "order_id must look like QF-1042"}

An error observation for a call that sent order_id "1042". The format is your choice. Keep it the same across all tools.

Build a small argument validator in Python

Real projects often use a ready-made library for JSON Schema. To see how the checks work, we will write a tiny validator ourselves. It uses only Python's standard library, so it runs offline. It covers the argument checks from the table above. The unknown-tool check is a lookup in your list of tools, which comes before this function.

Pythonvalidate_return.py
import re

ALLOWED = {"order_id", "reason", "note"}
REASONS = {"damaged", "wrong_size", "changed_mind"}


def check_request_return(args):
    problems = []
    for name in ("order_id", "reason"):
        if name not in args:
            problems.append(f"missing argument: {name}")
    for name in args:
        if name not in ALLOWED:
            problems.append(f"unknown argument: {name}")
    order_id = args.get("order_id")
    if order_id is not None:
        if not isinstance(order_id, str):
            problems.append("order_id must be a string")
        elif not re.fullmatch(r"QF-[0-9]{4}", order_id):
            problems.append("order_id must look like QF-1042")
    if "reason" in args and args["reason"] not in REASONS:
        problems.append("reason must be one of: " + ", ".join(sorted(REASONS)))
    note = args.get("note", "")
    if not isinstance(note, str) or len(note) > 200:
        problems.append("note must be text of at most 200 characters")
    return problems


calls = [
    {"order_id": "QF-1044", "reason": "damaged", "note": "Bent wheel."},
    {"order_id": "QF-1042"},
    {"order_id": "1042", "reason": "refund_me", "colour": "red"},
    {"order_id": "QF-1044", "reason": "changed_mind", "note": "x" * 250},
]
for call in calls:
    found = check_request_return(call)
    print("OK" if not found else found)

Runs offline with Python 3.10 or later. Run it with python validate_return.py.

What each part does

  • ALLOWED and REASONS are sets, which are collections of values. They hold the argument names and the allowed reasons.
  • problems = [] starts an empty list. Each failed check adds a message to it.
  • The first loop finds missing required arguments. The second loop finds names that are not in ALLOWED.
  • isinstance(order_id, str) checks the type. re.fullmatch checks the whole value against the pattern, as ^ and $ do in the schema.
  • args["reason"] not in REASONS is the enum check.
  • len(note) > 200 is the maxLength check. A missing note counts as an empty string, so it passes.
  • The function returns the list of problems. An empty list means the call is fine.
  • The last loop runs four sample calls: one valid and three invalid in different ways.
OutputCaptured from a real run
OK
['missing argument: reason']
['unknown argument: colour', 'order_id must look like QF-1042', 'reason must be one of: changed_mind, damaged, wrong_size']
['note must be text of at most 200 characters']

The first call passes. The second is missing reason. The third breaks three rules at once and gets three messages. The fourth has a note that is too long. In a real agent, a non-empty list becomes the error observation, and the tool does not run.

Conclusion and your next step

A tool contract tells the model what a tool does and what it accepts. The schema makes the arguments exact. A clear description helps the model choose well. Your own validation is the last gate: it catches wrong values, sends a helpful error back and keeps the tool from running on bad input.

Your next step: write the contract for one tool you would like your agent to have, including a three-part description. Then run a validator like the one above on a few good and bad calls. After that, continue to Connecting REST APIs and Internal Services, where the validated call reaches a real service.

Want more? When a tool call fails for reasons other than bad arguments, see Tool Errors, Retries, Timeouts and Idempotency. You can also look up any word in the Glossary of AI Engineering and Agent Terms.

Common errors and how to fix them

The model keeps calling the wrong tool.

Why it happens: Two descriptions overlap, or a description is a single vague word.

Fix: Rewrite each description to say when to use the tool and what it must not be used for.

The model sends an extra argument, or an invented one.

Why it happens: The schema does not close the door, so unknown names are allowed through.

Fix: Set additionalProperties to false where your provider accepts it, and always reject unknown names in your own code as well.

The tool runs with bad input anyway.

Why it happens: You trusted the provider's schema and skipped your own check.

Fix: Validate every call before running the tool. If anything fails, return an error and do not run it.

The model retries again and again with the same mistake.

Why it happens: The error message is vague, such as "invalid input".

Fix: Name the argument and the rule it broke, and say what a good value looks like.

Validation checklist

Tick each item once you have confirmed it.

Hands-on exercise

Write and test a contract for add_delivery_note

Quillfeather wants a tool add_delivery_note(order_id, note) that adds a short note for the courier. Write its contract as JSON, then write a small Python validator and test it on four calls.

You will need

  • order_id matches ^QF-[0-9]{4}$.
  • note is required and has at most 120 characters.
  • No other arguments are allowed.
  • Test calls: one valid, one with a missing note, one with an extra argument, one with a note over 120 characters.

Acceptance criteria

Your work is done when every one of these is true.

Hints (3)
  • Copy request_return.json and change the names and limits.
  • Check the pieces in the same order as the checklist table.
  • Remember len(note) > 120 for the length check.
Show a model answer

A strong answer has a contract with order_id (string, pattern ^QF-[0-9]{4}$) and note (string, maxLength 120), both required, with additionalProperties set to false. The description might read: "Add a short note for the courier to one order. Use it only when the customer has given an order and a note. Returns a confirmation. Do not use it to change the address or cancel the order." The validator adds "missing argument: note" for the second call, "unknown argument" for the third and a length message for the fourth. All the problems are collected in one list, and an empty list means OK.

Knowledge check

Choose an answer, then check it. Nothing is recorded — this is for you.

  1. 1.Why validate arguments in your own code when the provider already follows a schema?
    Show the answer and explanation

    Answer: B. Models can still send wrong values, and provider support varies, so your check is the final protection before something real happens. The first option is tempting but wrong: providers do read schemas, they just cannot promise a perfect result every time.

  2. 2.A call to request_return has the reason "refund_me". Which check catches it?
    Show the answer and explanation

    Answer: A. The reason is present and short, but it is not one of damaged, wrong_size or changed_mind, so only the allowed-values check fails. The required check is tempting, but the argument is there. Its value is simply not allowed.

  3. 3.What should your code do when validation fails?
    Show the answer and explanation

    Answer: B. A failed check means the call is unsafe, so the tool must not run. A clear error lets the model fix the call and try again. Stopping the whole agent is tempting, but it throws away a problem the model can usually fix itself in the next round.

Frequently asked questions

What is a tool schema in AI agents?

A tool schema is a precise description of the arguments a tool accepts, usually written in JSON Schema. It lists each argument, its type and its rules, such as allowed values or a maximum length. The model reads it to know how to call the tool, and your code uses it to check the call.

What is JSON Schema used for?

JSON Schema is a standard way to describe what valid JSON data looks like. In agents it describes tool arguments and structured answers. Many tools and AI providers understand it, so one description can serve several purposes.

How do I validate function calling arguments?

Before running the tool, check the tool name, then each argument: present, listed, right type, right format, allowed value and right length. Collect all the problems. If there are any, skip the tool and return an error message to the model. You can write the checks by hand or use a JSON Schema library.

What should I return when a tool call has invalid arguments?

Return a short, clear error as the tool result, such as an error field that names the argument and what a good value looks like. Do not run the tool. The model can read the message and try again with corrected arguments.

Written by
PromptFable Editorial
Last updated 18 Nov 2026
Review
Reviewed by Waseem Nadir, Technical Reviewer
Last reviewed 27 Nov 2026

References

Primary sources for the technical details in this lesson. Vendor platforms change — check the official page if anything here looks different from what you see.

PromptFable is independent and is not affiliated with, endorsed by or sponsored by Anthropic, Google, OpenAI or any other vendor. Claude, Gemini, Google AI Studio and other product names are trademarks of their respective owners.