Module 03 · Lesson 3.2
Designing Tool Schemas and Validating Arguments
On this page
- What you will learn
- What a tool contract and a tool schema are
- JSON Schema keywords every beginner needs
- How to write a good tool description
- Why you must validate arguments in your own code
- A validation checklist for every tool call
- Build a small argument validator in Python
- Conclusion and your next step
- Common errors and fixes
- Validation checklist
- Hands-on exercise
- Knowledge check
- Frequently asked questions
- 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
- How Tool Calling Works. You should know that the model asks for a tool call and your code runs it.
- System Instructions, Role, Constraints and Output Contracts, where JSON and JSON Schema were first introduced.
- Most of this lesson needs no coding. Optional: Python 3.10 or later, if you want to run the example.
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.
- Contract
Name, description, schema
- Model
Asks for a tool call
- Validation
Your code checks the arguments
- Tool runs
Only when the check passes
- 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.
| Keyword | Plain meaning | Example in request_return |
|---|---|---|
| type | What kind of value it is: text, number, true or false, and so on. | order_id is a string (text). |
| properties | The list of arguments the tool accepts, each with its own rules. | order_id, reason and note. |
| required | Arguments that must always be present. | order_id and reason. The note may be left out. |
| enum | A fixed list of allowed values. Nothing else passes. | reason is damaged, wrong_size or changed_mind. |
| pattern | A text pattern the value must match, written as a regular expression. | ^QF-[0-9]{4}$ means QF, a dash, then four digits. |
| maxLength | The longest text allowed, in characters. | note is at most 200 characters. |
| additionalProperties | Whether extra, unlisted arguments are allowed. Set to false to block them. | No made-up arguments such as refund_amount. |
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.
{
"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
nameis the label the model uses to ask for the tool. Keep it short and use the same style for every tool.descriptiontells 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
propertiesgives one argument its own type and rules. The shortdescriptioninside each one tells the model what to put there. requiredlists the two arguments that must be present.noteis not listed, so it is optional.additionalProperties: falsecloses 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 description | Stronger 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. |
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.
| Check | Question | Example of a failure |
|---|---|---|
| Unknown tool | Is there a tool with this name? | The model asks for cancel_order, which does not exist. |
| Missing argument | Is every required argument present? | reason is not sent. |
| Extra argument | Is every argument one the schema lists? | refund_amount is sent. |
| Wrong type | Is each value the right kind? | order_id is the number 1042, not text. |
| Wrong format | Does the text match its pattern? | order_id is "1042", not "QF-1042". |
| Value not allowed | Is the value in the allowed list? | reason is "refund_me". |
| Too long | Is the text within its limit? | note is 250 characters. |
What to do when a check fails
- Do not run the tool. A failed check means the call is not safe to run.
- 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.
- Name the problem and the fix. "reason must be one of: changed_mind, damaged, wrong_size" helps. "Invalid input" does not.
- 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.
{"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.
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
ALLOWEDandREASONSare 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.fullmatchchecks the whole value against the pattern, as^and$do in the schema.args["reason"] not in REASONSis theenumcheck.len(note) > 200is themaxLengthcheck. 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.
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_idmatches^QF-[0-9]{4}$.noteis 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.jsonand change the names and limits. - Check the pieces in the same order as the checklist table.
- Remember
len(note) > 120for 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.
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.
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.
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.
- Getting started with JSON Schema(opens in a new tab)
JSON Schema · Official documentation · A step-by-step introduction to writing a schema and its basic keywords.
- What is a schema?(opens in a new tab)
JSON Schema · Official documentation · Background on what a schema is and why it is useful.
- Object(opens in a new tab)
JSON Schema · Official documentation · Reference for properties, required and additionalProperties.
- Define tools(opens in a new tab)
Anthropic · Official documentation · How Anthropic describes tool definitions for Claude.
- Writing effective tools for agents(opens in a new tab)
Anthropic · Official documentation · Engineering advice on designing and describing tools.
- Input Validation Cheat Sheet(opens in a new tab)
OWASP Foundation · Official documentation · General guidance on checking input before using it.
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.