Skip to main content
OpenCode’s AI assistant has access to a powerful suite of tools that enable it to interact with your codebase, execute commands, and provide intelligent assistance. All tools follow a consistent permission model and provide detailed feedback.

File search and analysis tools

glob

Fast file pattern matching tool that finds files by name and pattern.
pattern
string
required
The glob pattern to match files against
path
string
The directory to search in (defaults to current working directory)
Pattern syntax:
  • * matches any sequence of non-separator characters
  • ** matches any sequence of characters, including separators
  • ? matches any single non-separator character
  • [...] matches any character in the brackets
  • [!...] matches any character not in the brackets
Examples:
# Find all JavaScript files in current directory
pattern: "*.js"

# Find all TypeScript files in any subdirectory
pattern: "**/*.ts"

# Find TypeScript and TSX files in src directory
pattern: "src/**/*.{ts,tsx}"
Limitations:
  • Results limited to 100 files (newest first)
  • Hidden files (starting with .) are skipped
  • Does not search file contents

grep

Fast content search tool that finds files containing specific text or regex patterns.
pattern
string
required
The regex pattern to search for in file contents
path
string
The directory to search in (defaults to current working directory)
include
string
File pattern to include in search (e.g., "*.js", "*.{ts,tsx}")
literal_text
boolean
default:false
If true, pattern is treated as literal text with special regex characters escaped
Response format:
Found 3 matches

/path/to/file1.ts:
  Line 42: export function handleRequest() {
  Line 56: const result = handleRequest();

/path/to/file2.ts:
  Line 12: import { handleRequest } from './utils';
Examples:
# Search for function declarations
pattern: "function\\s+\\w+"

# Search for exact text with special characters
pattern: "log.Error"
literal_text: true

# Search only in Go files
pattern: "func.*Handler"
include: "*.go"
Limitations:
  • Results limited to 100 files (newest first)
  • Hidden files are skipped
  • Very large binary files may be skipped

ls

List directory contents with detailed information.
path
string
The directory path to list (defaults to current working directory)
ignore
array
Array of glob patterns to ignore (e.g., ["node_modules", "*.log"])
Response includes:
  • File/directory names
  • File sizes
  • Last modified timestamps
  • File types (directory, file, symlink)

File operation tools

view

Read and display file contents with line numbers.
file_path
string
required
The path to the file to read
offset
integer
default:0
Line number to start reading from (0-based)
limit
integer
default:2000
Number of lines to read
Response format:
<file>
     1|import { useState } from 'react';
     2|
     3|export function MyComponent() {
     4|  const [count, setCount] = useState(0);
     5|  return <div>{count}</div>;
     6|}
</file>
Features:
  • Displays line numbers for easy reference
  • Can read specific sections using offset
  • Automatically truncates very long lines (>2000 characters)
  • Suggests similar file names when file not found
  • Shows LSP diagnostics if available
Limitations:
  • Maximum file size: 250KB
  • Cannot display binary files or images
  • Lines longer than 2000 characters are truncated

write

Create or overwrite files with new content.
file_path
string
required
The path to the file to write
content
string
required
The content to write to the file
Safety features:
  • Creates parent directories automatically
  • Checks if file was modified since last read
  • Tracks file history for session
  • Avoids unnecessary writes when content unchanged
  • Shows diff of changes
  • Displays LSP diagnostics after write
Response includes:
  • Success message with file path
  • Diff showing additions/removals
  • LSP diagnostics (errors, warnings)
You should read a file using view before writing to it to ensure you’re not overwriting recent changes.

edit

Edit files by replacing specific text sections.
file_path
string
required
The absolute path to the file to modify
old_string
string
required
The text to replace (must be unique within the file)
new_string
string
required
The text to replace it with
Critical requirements:
1

Use the view tool first

You must read the file using view before editing to understand its contents
2

Ensure uniqueness

The old_string MUST uniquely identify the section to change:
  • Include 3-5 lines of context BEFORE the change point
  • Include 3-5 lines of context AFTER the change point
  • Match all whitespace and indentation exactly
3

Single instance only

This tool changes ONE instance at a time. For multiple instances, make separate calls with unique context for each.
Special cases:
# Create a new file
file_path: "/path/to/new/file.ts"
old_string: ""  # Empty for new file
new_string: "export const value = 42;"

# Delete content
file_path: "/path/to/file.ts"
old_string: "const unused = 123;\n"  # Content to remove
new_string: ""  # Empty to delete
Error handling:
  • Returns error if old_string not found
  • Returns error if old_string appears multiple times
  • Returns error if file modified since last read
  • Returns error if file is a directory

patch

Apply multiple coordinated changes across multiple files in one operation.
patch_text
string
required
The full patch text describing all changes
Patch format:
*** Begin Patch
*** Update File: /path/to/file.ts
@@ Context line (unique within the file)
 Line to keep
-Line to remove
+Line to add
 Line to keep

*** Add File: /path/to/new/file.ts
+Content of the new file
+More content

*** Delete File: /path/to/old/file.ts
*** End Patch
Features:
  • Atomic operation (all changes or none)
  • Updates file history for all modified files
  • Shows aggregated statistics
  • Runs LSP diagnostics on all changed files
Requirements:
  • All files being updated must be read first using view
  • New files must not already exist
  • Context lines must uniquely identify sections
  • All paths must be absolute
Response includes:
  • Number of files changed
  • Total additions and removals
  • LSP diagnostics for all modified files

System interaction tools

bash

Execute shell commands in a persistent shell session.
command
string
required
The command to execute
timeout
integer
default:60000
Timeout in milliseconds (max 600000 / 10 minutes)
Persistent shell:
  • All commands share the same shell session
  • Environment variables persist between commands
  • Current directory persists
  • Virtual environments remain active
Security features:
Some commands are banned for security:
  • Network tools: curl, wget, nc, telnet
  • Browsers: chrome, firefox, safari
  • Use specialized tools like fetch instead
Safe read-only commands (auto-approved):
  • File listing: ls, pwd, df, du
  • Process info: ps, top, uptime
  • Git read operations: git status, git log, git diff, git show
  • Go commands: go version, go list, go env
Output handling:
  • Output exceeding 30,000 characters is truncated
  • Both stdout and stderr are captured
  • Exit codes are reported
  • Execution time is tracked
Git integration: When creating commits:
1

Gather context

Run git status, git diff, and git log in parallel
2

Analyze changes

Draft a meaningful commit message focusing on “why” not “what”
3

Create commit

Use HEREDOC format for proper message formatting:
git commit -m "$(cat <<'EOF'
Add user authentication

🤖 Generated with opencode
Co-Authored-By: opencode <[email protected]>
EOF
)"
4

Verify success

Run git status to confirm commit succeeded

diagnostics

Get LSP diagnostics (errors, warnings, hints) for files or the entire project.
file_path
string
Path to file for diagnostics (leave empty for project-wide diagnostics)
Response format:
<file_diagnostics>
Error: /path/to/file.ts:42:10 [typescript][2304] Cannot find name 'variableName'
Warn: /path/to/file.ts:56:5 [typescript][6133] 'unused' is declared but never used
</file_diagnostics>

<project_diagnostics>
Error: /path/to/other.ts:12:1 [typescript][1005] ';' expected
</project_diagnostics>

<diagnostic_summary>
Current file: 1 errors, 1 warnings
Project: 1 errors, 0 warnings
</diagnostic_summary>
Severity levels:
  • Error: Code will not compile/run
  • Warning: Potential issues or bad practices
  • Hint: Suggestions for improvement
  • Info: Informational messages
Features:
  • Automatically opens file if not already open
  • Waits for LSP server to process file
  • Groups diagnostics by severity
  • Limits output to 10 diagnostics per category
  • Shows source (e.g., typescript, gopls, rust-analyzer)

fetch

Fetch data from URLs (when MCP web-search tools are not available).
url
string
required
The URL to fetch
format
string
required
Response format: html, json, text, or markdown
timeout
integer
default:30000
Timeout in milliseconds
Use cases:
  • Fetching API documentation
  • Reading online resources
  • Accessing project documentation
For searching public code repositories, use the sourcegraph tool instead.

sourcegraph

Search code across public repositories using Sourcegraph.
query
string
required
The search query
count
integer
default:5
Number of results to return
context_window
integer
default:3
Number of lines of context to show around matches
timeout
integer
default:30000
Timeout in milliseconds
Query syntax:
# Search for function in a specific repository
repo:openai/openai-python def chat_completion

# Search by file pattern
file:\.go$ http\.Handler

# Search by language
lang:typescript async function
Use cases:
  • Finding implementation examples
  • Researching API usage patterns
  • Discovering best practices
  • Learning from open source projects

Tool interaction patterns

Reading and modifying files

1

Search for files

Use glob to find files by pattern or grep to search contents
2

Read file contents

Use view to examine the file with line numbers
3

Make changes

Use edit for single replacements or write for complete rewrites
4

Verify changes

Use diagnostics to check for errors

Multi-file refactoring

1

Identify files

Use grep to find all files needing changes
2

Read all files

Use view on each file to understand context
3

Plan changes

Prepare patch with all coordinated changes
4

Apply patch

Use patch tool for atomic multi-file updates

Debugging workflow

1

Get diagnostics

Use diagnostics to identify errors
2

Examine code

Use view to read relevant files
3

Run tests

Use bash to execute test commands
4

Fix issues

Use edit to make corrections
5

Verify fix

Use diagnostics to confirm errors resolved

Permission model

All tools follow a consistent permission system:
Auto-approved operations:
  • Reading files with view
  • Listing directories with ls
  • Searching with glob and grep
  • Getting diagnostics
  • Safe read-only bash commands
Operations requiring user approval:
  • Writing files with write
  • Editing files with edit
  • Applying patches with patch
  • Executing commands with bash (non-read-only)
  • Creating/deleting files
Grant permission for entire session:
  • Press A in permission dialog
  • Permission persists until session ends
  • Useful for iterative workflows

Best practices

Always read first

Use view before edit or write to avoid conflicts and understand context

Use unique context

Include sufficient surrounding code in edit operations to ensure uniqueness

Batch operations

Use patch for coordinated multi-file changes instead of sequential edit calls

Check diagnostics

Run diagnostics after file modifications to catch errors early

Parallel tool calls

Send multiple independent tool calls in a single message for better performance

Use absolute paths

Always use absolute paths for file operations to avoid ambiguity

Build docs developers (and LLMs) love