Validate & Coerce Model Tool Calls
In agentic systems, LLMs occasionally output loosely formatted tool arguments (e.g., passing numbers as strings "100" or omitting required schema properties).
Write a function validateToolCall(call, schema) that sanitizes and validates an incoming tool call against a simplified JSON Schema.
Specifications:
- Tool Name Matching: If
call.name !== schema.name, return:{ valid: false, errors: ["Unknown tool: expected " + schema.name] } - Required Fields: Ensure all fields listed in
schema.requiredexist incall.arguments. If missing, add an error:"Missing required field: " + fieldName - Number Coercion: If a property has
type: "number"inschema.properties:- Coerce numeric strings like
"50"to number50. - If coercion results in
NaN, add an error:"Field " + fieldName + " must be a valid number".
- Coerce numeric strings like
- Output Format:
- If valid:
{ valid: true, coercedArgs: { ... } } - If invalid:
{ valid: false, errors: [ ... ] }
- If valid: