Overview
defineTool() is a helper function for creating type-safe server-side tools that execute in your runtime environment. It provides a clean API for defining tool schemas and execution logic with full TypeScript type inference.
Function Signature
Parameters
Unique identifier for the tool. Used by the LLM to call the tool.Convention: Use camelCase or snake_case.
Human-readable description of what the tool does. This is shown to the LLM to help it decide when to use the tool.Best practices:
- Be specific about what the tool does
- Mention the type of data it returns
- Include any important constraints or requirements
Zod schema defining the tool’s input parameters. Provides type safety and validation.
Async function that executes the tool logic. Receives validated parameters and returns the result.
- Parameters are automatically validated against the Zod schema
- Return value should be JSON-serializable
- Errors are caught and returned as error responses
Return Value
Returns aToolDefinition object that can be used with BuiltInAgent:
Usage Examples
Basic Tool
Database Query Tool
API Integration Tool
File System Tool
Complex Validation Tool
Tool with Dependencies
Using Tools with BuiltInAgent
Type Safety
defineTool provides full TypeScript type inference:
Error Handling
Errors thrown inexecute are caught and returned as error responses:
Validation
Parameters are automatically validated against the Zod schema:Best Practices
- Clear descriptions: Help the LLM understand when to use the tool
- Specific parameters: Use Zod’s rich validation features
- Add descriptions to parameters: Use
.describe()for better LLM understanding - Return structured data: Return objects, not primitive values
- Handle errors gracefully: Throw descriptive errors
- Keep tools focused: One tool should do one thing well
- Use TypeScript: Leverage type inference for safety
Common Patterns
Optional Parameters with Defaults
Enums for Fixed Values
Nested Objects
Arrays
Union Types
See Also
- BuiltInAgent - Using tools with agents
- AbstractAgent - Agent interface
- Zod Documentation - Schema validation library
