Designing Tool Schemas and Contracts
A tool schema is the instruction the model reads and the rule your code enforces. Make wrong calls hard to express.
A tool contract states what a tool does, which arguments it accepts, what it returns, how it fails and what it changes. Use clear task-shaped names, constrain arguments with types, enumerations and ranges, return small predictable results, and validate every call in code. A valid shape does not make a call correct or permitted, so keep business checks and authorization separate.
What you will learn: writing names and descriptions, constraining arguments with JSON Schema, designing results and errors, what strict modes guarantee, versioning and an end-to-end checklist.
Prerequisites: Agent Tools, Function Calling and Tool Registries and basic JSON.
The parts of a tool contract
The model sees only what you send it. It does not read your source code, your wiki or the comments beside the function. Anything it must know to choose and use the tool belongs in the definition or in the instructions.
Names that reduce confusion
| Weak | Better | Why |
|---|---|---|
data | search_orders | A verb and an object state the action |
get and fetch side by side | get_order, search_orders | One returns a known item, the other finds candidates |
update_record | change_delivery_address | Narrow actions are easier to authorize |
process | preview_refund, issue_refund | Separates looking from doing |
When tools come from several servers, names can collide. Add a prefix for the system, such as billing.search_invoices, where your platform allows it. The Model Context Protocol specification recommends names of 1 to 128 characters using letters, digits, underscore, hyphen and dot.
Write the description as guidance
A useful description answers five questions in a few sentences.
- What does it do? "Searches orders belonging to the signed-in customer."
- When should it be used? "Use when the customer does not know the order number."
- When should it not be used? "If the number is known, use get_order."
- What comes back? "Up to five matches, newest first, with a flag if more exist."
- What does it change? "Read only."
Describe each argument too, including format, unit and an example. "date" invites guessing; "delivery date as YYYY-MM-DD in the customer's local time" does not. Keep instructions about general behavior in the system prompt, where they apply to every tool. See Prompt Templates and Tool-Use Prompting.
JSON Schema for arguments
Most tool interfaces describe arguments with JSON Schema. A handful of keywords does most of the work.
| Keyword | Constrains | Example use |
|---|---|---|
type | String, integer, number, boolean, object, array | Quantity is an integer |
required | Fields that must be present | Order number |
enum | A fixed list of values | Refund reason |
pattern | Text shape; not anchored unless you add anchors | ^A[0-9]{4}$ |
minimum, maximum | Numeric range | Page size 1 to 50 |
maxLength, maxItems | Size | Ticket title, recipient list |
additionalProperties: false | No unknown fields | Catch invented arguments |
The following program sends the same three situations to a loose schema and a tight one. Its small checker handles only the keywords shown; use a maintained validator in real systems.
"""Compare a loose and a tight schema on the same model-produced calls."""
import re
LOOSE = {"properties": {"order": {"type": "string"},
"amount": {"type": "string"},
"reason": {"type": "string"}},
"required": ["order"]}
TIGHT = {"properties": {
# JSON Schema patterns are unanchored, so write ^ and $
"order_id": {"type": "string", "pattern": "^A[0-9]{4}$"},
"amount_cents": {"type": "integer", "minimum": 1,
"maximum": 50000},
"reason": {"type": "string",
"enum": ["damaged", "late", "wrong_item"]}},
"required": ["order_id", "amount_cents", "reason"],
"additionalProperties": False}
TYPES = {"string": str, "integer": int}
def check(schema, args):
"""Handles only the keywords used above, not all of JSON Schema."""
props, errors = schema["properties"], []
errors += [f"missing {k}" for k in schema["required"] if k not in args]
for key, value in args.items():
rule = props.get(key)
if rule is None:
if schema.get("additionalProperties") is False:
errors.append(f"unknown {key}")
continue
if type(value) is not TYPES[rule["type"]]:
errors.append(f"{key} must be {rule['type']}")
elif "enum" in rule and value not in rule["enum"]:
errors.append(f"{key} must be one of {rule['enum']}")
elif "pattern" in rule and not re.fullmatch(rule["pattern"], value):
errors.append(f"{key} has the wrong format")
elif "minimum" in rule and not (
rule["minimum"] <= value <= rule["maximum"]):
errors.append(f"{key} out of range")
return errors
calls = [
({"order": "the blue one", "amount": "all of it"},
{"order_id": "the blue one", "amount_cents": "all of it",
"reason": "late"}),
({"order": "A1001", "amount": "-20", "reason": "because"},
{"order_id": "A1001", "amount_cents": -2000, "reason": "because"}),
({"order": "A1001", "amount": "20.00", "reason": "late"},
{"order_id": "A1001", "amount_cents": 2000, "reason": "late"}),
]
for number, (loose_args, tight_args) in enumerate(calls, 1):
print(f"call {number} loose: {check(LOOSE, loose_args) or 'accepted'}")
print(f"call {number} tight: {check(TIGHT, tight_args) or 'accepted'}")
Output:
call 1 loose: accepted
call 1 tight: ['order_id has the wrong format', 'amount_cents must be integer']
call 2 loose: accepted
call 2 tight: ['amount_cents out of range', "reason must be one of ['damaged', 'late', 'wrong_item']"]
call 3 loose: accepted
call 3 tight: accepted
The loose schema accepted "all of it" as an amount and a negative refund. The tight one rejected both with messages a model can act on. The third call passed both, but only the tight version delivers an unambiguous whole number of cents rather than a string that some later code must interpret.
Argument design patterns
| Advice | Instead of | Prefer |
|---|---|---|
| Name units | amount | amount_cents with a currency |
| Use identifiers | Customer name | Identifier returned by a search tool |
| Prefer choices | Free-text status | Enumeration |
| Keep it flat | Deeply nested options | A few top-level fields |
| Avoid hidden modes | One tool with an operation field | Separate tools when permissions differ |
| Do not ask for what you know | User identifier supplied by the model | Identity injected by trusted code |
The last row is a security rule. If the model supplies the user or tenant identifier, a mistake or a malicious document can select someone else's data. Take identity from the authenticated session and leave it out of the schema entirely.
Design the result
Results enter the model's context, so shape them for reading.
- Return meaningful fields, not an entire database row.
- Include stable identifiers needed for the next call.
- State completeness: total count, whether results were cut off and how to get more.
- Label time and source so that old data is recognizable.
- Keep types consistent, including an empty list when nothing matches.
- Declare an output schema where your protocol supports it, and validate against it.
MCP lets a tool publish an optional outputSchema. In the 2026-07-28 revision both input and output schemas default to JSON Schema 2020-12 when no dialect is named, servers must return structured results that match a declared output schema, and clients should check them.
Errors are part of the contract
Give each failure a stable code, a short explanation and a hint about what to do. "invalid_date: use YYYY-MM-DD, today or later" lets a model correct itself. MCP distinguishes protocol errors, such as an unknown tool, from tool execution errors returned in the result with isError set, which carry feedback the model can use. Never return stack traces, connection strings or other users' data in an error. Reliable Tool Execution and Error Recovery covers recovery.
What strict modes guarantee
Some model providers can constrain generation so that tool arguments match your schema. Anthropic documents this for Claude: setting strict: true on a tool uses grammar-constrained sampling to make the arguments fit the input schema, within a supported subset of JSON Schema. Other providers offer similar features with their own limits, so read the current documentation.
| A schema match helps with | It does not establish |
|---|---|
| Correct types and field names | That the order number exists |
| Allowed enumeration values | That the chosen reason is true |
| Required fields present | That this user may do this |
| Parsable input | That calling this tool now is sensible |
Keep server-side validation even with strict modes. Other callers may reach the tool, some constraints may be unsupported by the generator, and a response cut short or refused may not follow the schema.
Strict modes also affect design. A schema using unsupported keywords may be rejected or only partly enforced, so keep a test that registers every tool with each provider you use. If one service must work with several providers, define the contract once in the richest form your server validates, then derive a simpler version for each model interface and check that nothing important was dropped on the way.
Behavior hints
MCP tool annotations describe behavior: readOnlyHint, destructiveHint, idempotentHint and openWorldHint. The defaults are cautious; for example a tool is not assumed to be read only, and destructive is assumed unless stated otherwise. These are hints, and the specification requires clients to treat annotations as untrusted unless they come from a trusted server. Use them to improve confirmation screens, and enforce real limits elsewhere.
State across calls
Some work spans calls, such as a shopping basket or a browser session. Return an explicit handle from a "create" tool and require it in later calls. Make handles hard to guess, give them an expiry, check on every call that the caller owns the handle and return a clear error when it has expired. MCP's current guidance follows this approach because the protocol has no session of its own.
Changing a contract safely
Callers include prompts, evaluation sets, workflows and other teams. A compatibility check in your build catches obvious breaks.
"""Flag input-schema changes that can break existing callers."""
def breaking(old, new):
problems = []
before, after = old["properties"], new["properties"]
for name in before:
if name not in after:
problems.append(f"removed field '{name}'")
continue
a, b = before[name], after[name]
if a["type"] != b["type"]:
problems.append(f"'{name}' type {a['type']} -> {b['type']}")
lost = set(a.get("enum", [])) - set(b.get("enum", []))
if "enum" in b and lost:
problems.append(f"'{name}' no longer accepts {sorted(lost)}")
if b.get("unit") != a.get("unit"):
problems.append(f"'{name}' unit changed")
added = set(new["required"]) - set(old["required"])
problems += [f"'{n}' is newly required" for n in sorted(added)]
return problems
v1 = {"properties": {
"city": {"type": "string"},
"limit": {"type": "integer", "unit": "items"},
"sort": {"type": "string", "enum": ["price", "rating", "name"]}},
"required": ["city"]}
v2 = {"properties": {**v1["properties"],
"language": {"type": "string"}},
"required": ["city"]}
v3 = {"properties": {
"city": {"type": "string"},
"limit": {"type": "integer", "unit": "pages"},
"sort": {"type": "string", "enum": ["price", "rating"]},
"language": {"type": "string"}},
"required": ["city", "language"]}
for label, old, new in (("v1 -> v2", v1, v2), ("v2 -> v3", v2, v3)):
found = breaking(old, new)
print(label, "compatible" if not found else "BREAKING")
for item in found:
print(" -", item)
Output:
v1 -> v2 compatible
v2 -> v3 BREAKING
- 'limit' unit changed
- 'sort' no longer accepts ['name']
- 'language' is newly required
Adding an optional field passed. Changing the meaning of limit from items to pages, removing a sort value and requiring a new field were all flagged. The unit change is the most dangerous: the type is unchanged, so every old call still validates while doing something different. This checker looks at only a few rules and cannot detect a reworded description that changes which tool a model picks. Run behavior tests as well.
- Add the new version beside the old one.
- Run evaluations on both with the same cases.
- Move callers gradually and watch error rates.
- Announce a retirement date and remove the old version when unused.
A design process that works
| Step | Output |
|---|---|
| Collect real requests | Examples of what users ask for |
| Group them into actions | A short list of task-shaped tools |
| Draft contracts | Schemas, results, errors and effects |
| Try them with a model | Selection and argument error rates |
| Read the failures | Wording and schema fixes |
| Review security | Identity, permissions, limits |
A first draft offers create_event(details) with free text. The agent books wrong days and wrong time zones. The redesign takes a start time with an offset, a duration in minutes, attendee identifiers returned by a lookup tool, and returns the booked time written out in full for confirmation. A separate read tool lists free slots.
Test the contract itself
Keep a small set of cases per tool: typical requests, boundary values, missing information where the agent should ask, requests that no tool should handle, and look-alike requests that belong to a neighboring tool. Score both the choice and the arguments. Rerun it whenever a name, description, schema or model changes. See Tool Testing and Observability.
Walk through one contract
Consider a tool that changes a delivery address. A complete contract can be written on half a page, and writing it exposes questions that code alone would hide.
| Part | Decision | Question it forced |
|---|---|---|
| Name | change_delivery_address | Is billing address a separate action? Yes |
| Use when | The customer asks to redirect an order not yet dispatched | What happens after dispatch? |
| Inputs | Order identifier; address identifier from the customer's saved addresses | May the agent type a new address? Not through this tool |
| Not an input | Customer identity | Taken from the session |
| Success | Order identifier, new address as text, expected delivery date | Can the date change? Report it |
| Failures | already_dispatched, address_not_found, not_allowed, temporary | What should each one lead to? |
| Effects | Changes one order; repeating with the same inputs has no further effect | Is the carrier notified twice? |
| Control | Confirmation by the customer before the call | Who records the confirmation? |
Notice how restricting the address to a saved identifier removes a whole class of problems: mistyped addresses, addresses copied from untrusted text and arguments about formats. If customers need to add addresses, give that its own tool or screen with its own checks. Narrow contracts often feel less flexible during design and prove easier to operate.
Where should each rule live?
- In the schema: shape, types, allowed values and sizes that never depend on stored data.
- In the tool code: existence, ownership, state of the record and business limits.
- In the policy layer: who may call, under which conditions, and whether approval is needed.
- In the description: what helps the model choose well, never the only copy of a rule that must hold.
Common mistakes
- Exposing raw API endpoints with cryptic parameters.
- Free-text fields where a short list would do.
- Unstated units, time zones or currencies.
- Asking the model for user identity or permissions.
- Believing a valid shape means a safe call.
- Returning huge or inconsistent results.
- Changing meaning without changing the version.
Checklist
- Name states one action clearly.
- Description says when to use and not use it.
- Arguments are typed, bounded and documented with units.
- Unknown fields are rejected.
- Identity comes from trusted code.
- Results state completeness and keep a stable shape.
- Errors tell the caller what to do next.
- Changes pass compatibility and behavior tests.
Frequently asked questions
How long should a tool description be?
Long enough to remove ambiguity and no longer. A few sentences usually suffice. Every definition uses context on each call, so measure both accuracy and tokens.
Should I include examples in the definition?
Short examples of formats help. If a model copies example values into real calls, replace them with a format description and test again.
Can I generate schemas from my code?
Yes, typed signatures are a good starting point. Review the result, since generated text rarely explains when to use a tool.
Does strict mode replace validation?
No. It improves the shape of model output. Your service must still validate values, check permissions and apply business rules.
References and further reading
- JSON Schema draft 2020-12
- MCP specification: tools
- MCP blog: tool annotations
- Claude documentation: strict tool use
- Anthropic: writing effective tools for agents
Next steps
Reliable Tool Execution and Error Recovery
Run calls safely when things fail.
Tool Permissions, Approvals and Abuse Risks
Decide who may call what.
MCP Tool Design and MCP vs APIs
Apply contracts to MCP servers.