Defining Tools and JSON Schemas
Independent educational resource, not an official Anthropic course. Facts about the API, prices and limits were checked against Anthropic's documentation on 15 November 2026 and the code was run against a local mock of the API, not the live service. Check the linked official pages before relying on a number, and test with your own key.
When Claude picks the wrong tool, or fills in a parameter strangely, the cause is almost always the definition you wrote. The model sees three things about a tool: its name, its description and its JSON schema. That's the whole interface. This lesson is about writing those three well, and about a small linter that catches the usual mistakes before they cost you a debugging afternoon.
What you'll learn
- The fields of a tool definition and the naming rule.
- How to write a description that works (it matters more than anything else here).
- How to design the schema: enums, required fields, examples.
- What
strict: true guarantees, and what it asks of your schema.
- How to validate inputs yourself, and lint your definitions.
Before you start
The anatomy of a tool
A user-defined tool has three required parts and a few optional ones:
name: must match ^[a-zA-Z0-9_-]{1,128}$. Letters, digits, underscores and hyphens, up to 128 characters. No spaces, no punctuation.
description: plain text saying what the tool does, when to use it and how it behaves.
input_schema: a JSON Schema object describing the parameters.
input_examples (optional): example inputs. Each must be valid against the schema, or you get a 400 error.
strict (optional): true guarantees the model's input matches your schema.
The description does the heavy lifting
Anthropic's docs call detailed descriptions "by far the most important factor in tool performance" and ask for at least three or four sentences per tool, more for complex ones. A good description covers:
- What the tool does.
- When to use it, and when not to.
- What each parameter means and how it changes behaviour.
- What it does not return, especially if the name could mislead.
Compare these two for the same tool:
Poor: "Gets an order."
Good: "Look up a single customer order by its order id, for example A100. Returns the order
status (processing, shipped, delivered or cancelled), the carrier, the tracking number and
the order total. Use it when the customer asks where an order is or what state it is in.
It does not return payment details, the customer's address or other orders. If the id
does not exist it returns an error message."
With the poor version Claude has to guess when to use it, what an "order" includes, and what happens when nothing is found. The good version answers all of that, including the negative: it says what the tool doesn't do, which stops Claude from reaching for it when it shouldn't.
Other design advice from the docs
- Fewer, broader tools. Rather than
create_pr, review_pr and merge_pr, one tool with an action parameter. Fewer tools means less ambiguity about which to pick.
- Namespaced names.
shop_lookup_order, github_list_prs. When tools come from several services the prefix keeps selection unambiguous.
- Return high-signal results. Stable identifiers and only the fields Claude needs to decide the next step. Bloated results waste context and bury the useful part.
- Ask for an explanation, not reasoning. If you add a parameter asking why the model is calling the tool, ask for a short justification. A parameter that asks for step-by-step reasoning can trigger a
reasoning_extraction refusal.
Designing the schema
Keep schemas boring and tight:
- Use enums for closed sets.
"status": {"type": "string", "enum": ["processing", "shipped", "delivered", "cancelled"]} prevents invented values.
- Describe every parameter with an example in the text ("such as A100").
- List
required explicitly. Leave optional things optional; Claude will fill them in only when the conversation supports it.
- Don't accept identities you already know. If the signed-in customer is known to your app, don't add a
customer_id parameter at all. The model would only be guessing, and an attacker could try to change it. Lesson 4.6 expands on this.
- Provide
input_examples for tricky tools (nested objects, format-sensitive values). They cost roughly 20 to 50 tokens each for simple ones and 100 to 200 for complex ones, and they aren't supported on server tools.
Strict mode
Without it, a model can occasionally return "2" where you wanted 2, or leave out a required field. With "strict": true on the tool, Anthropic guarantees the model's input follows your schema (using grammar-constrained sampling) and that the tool name is always valid. There's a price: the schema must stay within the supported subset (the same one as structured outputs), and every object needs "additionalProperties": false. The first request with a new schema takes slightly longer while it compiles, and compiled schemas are cached for up to 24 hours. Also, never put protected health information in schema property names, enums or patterns, because cached schemas don't get the same protections as message content.
Strict mode removes the most common source of bad calls, but it can't make the values right. "A100" can be a perfectly valid string and still be the wrong order.
A tool set, with a linter
These two definitions follow all the advice above. They're followed by a linter that checks the mechanical rules and a function that validates an input against the schema, which you keep even with strict mode on:
import re
from jsonschema import Draft202012Validator, ValidationError
NAME_RE = re.compile(r"^[a-zA-Z0-9_-]{1,128}$") # the pattern the API documents for tool names
LOOKUP_ORDER = {
"name": "shop_lookup_order",
"description": (
"Look up a single customer order by its order id, for example A100. Returns the order status "
"(processing, shipped, delivered or cancelled), the carrier, the tracking number and the order total. "
"Use it when the customer asks where an order is or what state it is in. It does not return payment "
"details, the customer's address or other orders. If the id does not exist it returns an error message."
),
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"order_id": {"type": "string", "description": "The order id as the customer wrote it, such as A100."}
},
"required": ["order_id"],
"additionalProperties": False,
},
"input_examples": [{"order_id": "A100"}],
}
LIST_ORDERS = {
"name": "shop_list_orders",
"description": (
"List the signed-in customer's recent orders, newest first, up to 10. Optionally filter by status. "
"Use it when the customer asks about 'my orders' without giving an id. Returns order id, status and "
"total for each. The customer is identified by the application, so never ask for or pass an email."
),
"strict": True,
"input_schema": {
"type": "object",
"properties": {
"status": {
"type": "string",
"enum": ["processing", "shipped", "delivered", "cancelled"],
"description": "Only return orders in this status. Leave out to return all statuses.",
}
},
"required": [],
"additionalProperties": False,
},
}
POOR = {"name": "get order!", "description": "Gets an order.", "input_schema": {"type": "object", "properties": {"id": {}}}}
def lint_tool(tool: dict) -> list[str]:
"""Catch the definition mistakes the documentation warns about. It checks form, not wisdom:
a definition can pass every rule and still describe a tool badly."""
notes = []
name = tool.get("name", "")
if not NAME_RE.match(name):
notes.append(f"Name {name!r} does not match ^[a-zA-Z0-9_-]{{1,128}}$.")
if "_" not in name and "-" not in name:
notes.append("Consider a namespaced name such as shop_lookup_order; it keeps selection unambiguous as tools grow.")
description = tool.get("description", "")
sentences = [s for s in re.split(r"(?<=[.!?])\s+", description.strip()) if s]
if len(sentences) < 3:
notes.append(f"Description has {len(sentences)} sentence(s); aim for 3 to 4: what it does, when to use it, what it returns, what it does not do.")
schema = tool.get("input_schema", {})
if schema.get("type") != "object":
notes.append("input_schema must be an object schema.")
for prop, spec in schema.get("properties", {}).items():
if not spec.get("description") and "enum" not in spec:
notes.append(f"Parameter '{prop}' has no description.")
if "required" not in schema:
notes.append("No 'required' list. Say which parameters are mandatory.")
if tool.get("strict"):
def walk(node, path="input_schema"):
if isinstance(node, dict):
if node.get("type") == "object" and node.get("additionalProperties") is not False:
notes.append(f"strict tools need additionalProperties: false on every object ({path}).")
for k, v in node.items():
walk(v, f"{path}.{k}")
walk(schema)
try:
validator = Draft202012Validator(schema)
for example in tool.get("input_examples", []):
for err in validator.iter_errors(example):
notes.append(f"input_example {example} is invalid: {err.message}. The API rejects invalid examples with a 400.")
except Exception as e: # noqa: BLE001
notes.append(f"input_schema is not valid JSON Schema: {e}")
return notes
def validate_input(tool: dict, data: dict) -> list[str]:
"""Validate what Claude sent before running anything. Strict mode guarantees the shape on the API side;
this is the check you keep anyway, for non-strict tools and for defence in depth."""
validator = Draft202012Validator(tool["input_schema"])
return [
f"{'.'.join(str(p) for p in e.path) or 'input'}: {e.message}"
for e in sorted(validator.iter_errors(data), key=lambda e: list(e.path))
]
The linter checks only what a program can: the name pattern, a namespace separator, description length, a description on every parameter, a required list, additionalProperties: false on strict tools, and whether each input_example is valid. It can't judge whether your description is good, only whether you wrote one. We tested it with the two definitions above (clean) and a deliberately poor one ("get order!", one short sentence, an undescribed parameter, no required list), and the poor one was flagged for each of those problems. Invalid examples, a missing additionalProperties: false and bad inputs (missing key, wrong type, value outside the enum) were also caught.
In Laravel the equivalent is a definition array in a PHP class, validated at registration time (lesson 4.4 builds the registry).
Real-world use case (illustrative scenario)
This scenario is an invented example to show how the ideas fit together. It is not a case study and its details are not measured results.
A team has an internal tool called search with the description "Searches stuff". Claude calls it for questions it could answer itself, and never calls it for the ones it should. They rewrite it to "Search the company's published help articles by keyword. Returns up to five article titles with their URLs. Use it for questions about shipping, returns and sizing. It does not search orders or customer data." Call quality improves without touching a line of code: the same model, the same function, a better description.
Mistakes to avoid
- One-line descriptions.
- Free-text parameters where an enum would do.
- A
user_id parameter on a tool that should only ever act for the signed-in user.
- Strict tools with
additionalProperties left out.
- Dozens of near-duplicate tools instead of a few well-described ones.
- Examples that don't match the schema (a 400 error).
Security notes
Definitions are part of your attack surface. Every parameter is a place where model-chosen text enters your code. Prefer enums and narrow types, validate values yourself, and keep powerful operations (writes, deletes, payments) out of general-purpose tools. Never describe internal details you wouldn't want leaked, because a model may repeat tool descriptions to a user who asks.
Cost and speed
Definitions are input tokens on every request, including the ones where the tool isn't used. Long descriptions are worth the tokens up to a point, but send each request only the tools it might need. A visitor who isn't signed in shouldn't be shipped the order tools at all. Lesson 4.8 does exactly that.
Key takeaways
- A tool is a name, a description and a schema. The description matters most.
- Say what the tool does, when to use it, what it returns and what it doesn't do.
- Use enums and required fields, namespaced names, and fewer well-described tools.
strict: true guarantees the input matches the schema (with additionalProperties: false); it can't guarantee the values are right.
- Lint your definitions and validate inputs anyway.
Lesson recap: the description is the interface, and strict mode checks shape, not truth.
Quick quiz
- What pattern must a tool name match?
- Name three things a good description should explain.
- What does
strict: true guarantee, and what must your schema contain to use it?
- Why should a tool for "my orders" not have a
customer_id parameter?
- Why validate inputs yourself when strict mode is on?
Answers and explanations
^[a-zA-Z0-9_-]{1,128}$.
- What the tool does, when to use it and when not to, what each parameter means, and what it does not return.
- That the tool's input follows your
input_schema and the name is valid. The schema must use the supported subset and set additionalProperties: false on objects.
- The application already knows who is signed in. A model-supplied id would be a guess at best and a way to attack at worst.
- Strict mode guarantees shape, not meaning. A well-formed value can still be wrong, and non-strict tools need the check anyway.
Official references and further reading
Related tutorials