> ## Documentation Index
> Fetch the complete documentation index at: https://mintlify.com/opencode-ai/opencode/llms.txt
> Use this file to discover all available pages before exploring further.

# AI assistant tools

> Comprehensive guide to the tools available to OpenCode's AI assistant for file operations, code analysis, and system interaction

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.

<ParamField path="pattern" type="string" required>
  The glob pattern to match files against
</ParamField>

<ParamField path="path" type="string">
  The directory to search in (defaults to current working directory)
</ParamField>

**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:**

```bash theme={null}
# 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.

<ParamField path="pattern" type="string" required>
  The regex pattern to search for in file contents
</ParamField>

<ParamField path="path" type="string">
  The directory to search in (defaults to current working directory)
</ParamField>

<ParamField path="include" type="string">
  File pattern to include in search (e.g., `"*.js"`, `"*.{ts,tsx}"`)
</ParamField>

<ParamField path="literal_text" type="boolean" default={false}>
  If true, pattern is treated as literal text with special regex characters escaped
</ParamField>

**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:**

```bash theme={null}
# 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.

<ParamField path="path" type="string">
  The directory path to list (defaults to current working directory)
</ParamField>

<ParamField path="ignore" type="array">
  Array of glob patterns to ignore (e.g., `["node_modules", "*.log"]`)
</ParamField>

**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.

<ParamField path="file_path" type="string" required>
  The path to the file to read
</ParamField>

<ParamField path="offset" type="integer" default={0}>
  Line number to start reading from (0-based)
</ParamField>

<ParamField path="limit" type="integer" default={2000}>
  Number of lines to read
</ParamField>

**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.

<ParamField path="file_path" type="string" required>
  The path to the file to write
</ParamField>

<ParamField path="content" type="string" required>
  The content to write to the file
</ParamField>

**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)

<Warning>
  You should read a file using `view` before writing to it to ensure you're not overwriting recent changes.
</Warning>

***

### edit

Edit files by replacing specific text sections.

<ParamField path="file_path" type="string" required>
  The absolute path to the file to modify
</ParamField>

<ParamField path="old_string" type="string" required>
  The text to replace (must be unique within the file)
</ParamField>

<ParamField path="new_string" type="string" required>
  The text to replace it with
</ParamField>

**Critical requirements:**

<Steps>
  <Step title="Use the view tool first">
    You must read the file using `view` before editing to understand its contents
  </Step>

  <Step title="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
  </Step>

  <Step title="Single instance only">
    This tool changes ONE instance at a time. For multiple instances, make separate calls with unique context for each.
  </Step>
</Steps>

**Special cases:**

```bash theme={null}
# 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.

<ParamField path="patch_text" type="string" required>
  The full patch text describing all changes
</ParamField>

**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.

<ParamField path="command" type="string" required>
  The command to execute
</ParamField>

<ParamField path="timeout" type="integer" default={60000}>
  Timeout in milliseconds (max 600000 / 10 minutes)
</ParamField>

**Persistent shell:**

* All commands share the same shell session
* Environment variables persist between commands
* Current directory persists
* Virtual environments remain active

**Security features:**

<Warning>
  Some commands are banned for security:

  * Network tools: `curl`, `wget`, `nc`, `telnet`
  * Browsers: `chrome`, `firefox`, `safari`
  * Use specialized tools like `fetch` instead
</Warning>

**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:

<Steps>
  <Step title="Gather context">
    Run `git status`, `git diff`, and `git log` in parallel
  </Step>

  <Step title="Analyze changes">
    Draft a meaningful commit message focusing on "why" not "what"
  </Step>

  <Step title="Create commit">
    Use HEREDOC format for proper message formatting:

    ```bash theme={null}
    git commit -m "$(cat <<'EOF'
    Add user authentication

    🤖 Generated with opencode
    Co-Authored-By: opencode <noreply@opencode.ai>
    EOF
    )"
    ```
  </Step>

  <Step title="Verify success">
    Run `git status` to confirm commit succeeded
  </Step>
</Steps>

***

### diagnostics

Get LSP diagnostics (errors, warnings, hints) for files or the entire project.

<ParamField path="file_path" type="string">
  Path to file for diagnostics (leave empty for project-wide diagnostics)
</ParamField>

**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).

<ParamField path="url" type="string" required>
  The URL to fetch
</ParamField>

<ParamField path="format" type="string" required>
  Response format: `html`, `json`, `text`, or `markdown`
</ParamField>

<ParamField path="timeout" type="integer" default={30000}>
  Timeout in milliseconds
</ParamField>

**Use cases:**

* Fetching API documentation
* Reading online resources
* Accessing project documentation

<Note>
  For searching public code repositories, use the `sourcegraph` tool instead.
</Note>

***

### sourcegraph

Search code across public repositories using Sourcegraph.

<ParamField path="query" type="string" required>
  The search query
</ParamField>

<ParamField path="count" type="integer" default={5}>
  Number of results to return
</ParamField>

<ParamField path="context_window" type="integer" default={3}>
  Number of lines of context to show around matches
</ParamField>

<ParamField path="timeout" type="integer" default={30000}>
  Timeout in milliseconds
</ParamField>

**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

<Steps>
  <Step title="Search for files">
    Use `glob` to find files by pattern or `grep` to search contents
  </Step>

  <Step title="Read file contents">
    Use `view` to examine the file with line numbers
  </Step>

  <Step title="Make changes">
    Use `edit` for single replacements or `write` for complete rewrites
  </Step>

  <Step title="Verify changes">
    Use `diagnostics` to check for errors
  </Step>
</Steps>

### Multi-file refactoring

<Steps>
  <Step title="Identify files">
    Use `grep` to find all files needing changes
  </Step>

  <Step title="Read all files">
    Use `view` on each file to understand context
  </Step>

  <Step title="Plan changes">
    Prepare patch with all coordinated changes
  </Step>

  <Step title="Apply patch">
    Use `patch` tool for atomic multi-file updates
  </Step>
</Steps>

### Debugging workflow

<Steps>
  <Step title="Get diagnostics">
    Use `diagnostics` to identify errors
  </Step>

  <Step title="Examine code">
    Use `view` to read relevant files
  </Step>

  <Step title="Run tests">
    Use `bash` to execute test commands
  </Step>

  <Step title="Fix issues">
    Use `edit` to make corrections
  </Step>

  <Step title="Verify fix">
    Use `diagnostics` to confirm errors resolved
  </Step>
</Steps>

## Permission model

All tools follow a consistent permission system:

<AccordionGroup>
  <Accordion title="Safe read-only operations" icon="check">
    Auto-approved operations:

    * Reading files with `view`
    * Listing directories with `ls`
    * Searching with `glob` and `grep`
    * Getting diagnostics
    * Safe read-only bash commands
  </Accordion>

  <Accordion title="Requires permission" icon="shield">
    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
  </Accordion>

  <Accordion title="Session permissions" icon="key">
    Grant permission for entire session:

    * Press `A` in permission dialog
    * Permission persists until session ends
    * Useful for iterative workflows
  </Accordion>
</AccordionGroup>

## Best practices

<CardGroup cols={2}>
  <Card title="Always read first" icon="book-open">
    Use `view` before `edit` or `write` to avoid conflicts and understand context
  </Card>

  <Card title="Use unique context" icon="fingerprint">
    Include sufficient surrounding code in `edit` operations to ensure uniqueness
  </Card>

  <Card title="Batch operations" icon="layer-group">
    Use `patch` for coordinated multi-file changes instead of sequential `edit` calls
  </Card>

  <Card title="Check diagnostics" icon="stethoscope">
    Run `diagnostics` after file modifications to catch errors early
  </Card>

  <Card title="Parallel tool calls" icon="diagram-project">
    Send multiple independent tool calls in a single message for better performance
  </Card>

  <Card title="Use absolute paths" icon="route">
    Always use absolute paths for file operations to avoid ambiguity
  </Card>
</CardGroup>
