Overview
Tools are functions that AI agents can call to perform actions. OpenCode’s plugin system makes it easy to create custom tools with type-safe arguments and execution contexts.Basic Tool
Use thetool() helper to define a tool:
Tool Structure
Description
The description tells the AI when and how to use the tool. Be clear and specific:Arguments
Define arguments using Zod schemas viatool.schema:
Always add
.describe() to your arguments. These descriptions help the AI understand what values to provide.Execute Function
The execute function receives typed arguments and a context object:Tool Context
The execution context provides information and utilities:Context Properties
Current session ID
Current message ID
Current agent name (e.g.,
'build', 'plan')Current project directory. Use this instead of
process.cwd() for path resolution.Project worktree root. Useful for generating stable relative paths.
Signal for cancellation. Check
abort.aborted before long operations.Context Methods
metadata()
Update tool status and metadata:Tool status title shown in UI
Custom metadata attached to the tool execution
ask()
Request permission from the user:Permission type
Patterns affected by this permission
Patterns to always allow (empty for none)
Additional context for the permission request
Example Tools
Database Query Tool
API Request Tool
File Processing Tool
Shell Command Tool
Best Practices
1. Clear Descriptions
Be specific about what your tool does:2. Validate Input
Use Zod constraints to validate arguments:3. Handle Errors
Return error messages as strings:4. Check Cancellation
Respect the abort signal:5. Update Metadata
Keep the UI informed:6. Use Context Paths
Always usecontext.directory for path resolution:
7. Return Structured Data
Return JSON for complex data:8. Request Permissions
Ask before destructive operations:Debugging Tools
Add logging to debug your tools:Next Steps
Plugin Examples
See complete plugin examples
Plugin API
Learn about other plugin hooks