Tool Schemas & Argument Validation
Authoring bulletproof JSON schemas, enforcing strict types, and handling schema drift in production agent systems.
Tool calling is the bridge between probabilistic LLM generation and deterministic software execution. If your tool schemas are loose or ambiguous, your agent will hallucinate invalid arguments and fail silently.
Writing Strict JSON Schemas
Always author schemas with additionalProperties: false and explicit required lists. This prevents the LLM from hallucinating unexpected arguments.
{
"type": "function",
"function": {
"name": "query_customer_database",
"description": "Searches customer records by email or workspace domain. Returns account tier and usage.",
"parameters": {
"type": "object",
"properties": {
"search_term": {
"type": "string",
"description": "The exact user email or corporate domain to look up."
},
"limit": {
"type": "integer",
"description": "Maximum number of records to return. Min 1, Max 25.",
"default": 5
}
},
"required": ["search_term"],
"additionalProperties": false
}
}
}
Runtime Schema Validation with Zod
Never execute a tool based solely on raw model JSON. Always run incoming arguments through a strict validator (like Zod or Pydantic) before executing business logic:
import { z } from "zod";
const CustomerQuerySchema = z.object({
search_term: z.string().min(3).max(100),
limit: z.number().int().min(1).max(25).default(5)
});
export async function executeTool(rawArgs: unknown) {
const result = CustomerQuerySchema.safeParse(rawArgs);
if (!result.success) {
// Return structured validation error back to agent loop so model can self-correct
return {
error: "INVALID_ARGUMENTS",
details: result.error.format()
};
}
return await db.query(result.data);
}
Self-Correction on Validation Failure
When a tool validation fails, return the exact error message back into the message history with role tool. Modern models (Claude 3.5 Sonnet, GPT-4o) will recognize their mistake and re-issue the tool call with corrected arguments.
Continue to Memory & Context Management.