Skip to main content

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 the tool() helper to define a tool:

Tool Structure

Description

The description tells the AI when and how to use the tool. Be clear and specific:
Good descriptions help the AI understand when to use your tool. Include:
  • What the tool does
  • When to use it
  • What kind of input it expects

Arguments

Define arguments using Zod schemas via tool.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

sessionID
string
Current session ID
messageID
string
Current message ID
agent
string
Current agent name (e.g., 'build', 'plan')
directory
string
Current project directory. Use this instead of process.cwd() for path resolution.
worktree
string
Project worktree root. Useful for generating stable relative paths.
abort
AbortSignal
Signal for cancellation. Check abort.aborted before long operations.

Context Methods

metadata()

Update tool status and metadata:
title
string
Tool status title shown in UI
metadata
Record<string, any>
Custom metadata attached to the tool execution

ask()

Request permission from the user:
permission
string
required
Permission type
patterns
string[]
required
Patterns affected by this permission
always
string[]
required
Patterns to always allow (empty for none)
metadata
Record<string, any>
required
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 use context.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