> For the complete documentation index, see [llms.txt](https://www.opencodebook.xyz/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://www.opencodebook.xyz/en/chapter_05_tool_system/5.3_built-in_tools_source_code_analysis.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 5.3 Built-in Tools: Source Code Analysis

> **Model**: claude-opus-4-6 (anthropic/claude-opus-4-6) **Generation Date**: 2025-02-17

***

OpenCode ships with 20+ built-in tools, which can be grouped into six categories. This section provides a source code analysis of representative tools from each category.

## 5.3.1 File Operation Tools

### `read.ts` -- File Reading

```typescript
parameters: z.object({
  filePath: z.string(),           // Absolute file path
  offset: z.number().optional(),  // Starting line number (1-indexed)
  limit: z.number().optional(),   // Maximum number of lines (default 2000)
})
```

Key implementation details:

* Each output line is prefixed with a line number (e.g., `"1: import fs from 'fs'"`), helping the LLM locate code positions
* Supports reading directories (returns a list of directory entries)
* Supports reading images/PDFs (returned as FilePart attachments)
* Automatically detects binary files and refuses to read them
* Lines exceeding 2000 characters are truncated

### `edit.ts` -- Precise String Replacement

This is one of the most complex tools. Parameter design:

```typescript
parameters: z.object({
  filePath: z.string(),
  oldString: z.string(),    // Text to replace
  newString: z.string(),    // Replacement text
  replaceAll: z.boolean().optional(), // Whether to replace all matches
})
```

**Core Algorithm**:

1. Read the file contents
2. Search for an exact match of `oldString`
3. If 0 matches are found, attempt **fuzzy match correction** (handling common LLM errors such as inconsistent indentation and blank line differences)
4. If multiple matches are found and `replaceAll` is false, return an error asking for more context
5. Perform the replacement
6. Generate a diff for display
7. Run LSP diagnostics to check the modified file

**Fuzzy Match Correction** (derived from the open-source implementations of Cline and Gemini CLI):

```typescript
// Comment at the top of edit.ts
// the approaches in this edit tool are sourced from
// https://github.com/cline/cline/blob/main/evals/diff-edits/diff-apply/
// https://github.com/google-gemini/gemini-cli/blob/main/packages/core/src/utils/editCorrector.ts
```

This demonstrates that OpenCode actively draws on community best practices -- AI frequently produces inconsistent indentation when generating code replacements, and fuzzy matching significantly improves the success rate of edits.

### `write.ts` -- File Writing

Creates a new file or completely overwrites an existing file. Intermediate directories are created automatically.

### `glob.ts` -- File Pattern Matching

Built on Bun's native Glob implementation, supporting patterns like `**/*.ts`. Includes safety limits (60-second timeout, 100-file cap).

### `grep.ts` -- Regular Expression Search

Uses ripgrep (`file/ripgrep.ts`) under the hood, with support for regular expressions and file type filtering.

## 5.3.2 Execution Tools

### `bash.ts` -- Shell Command Execution

```typescript
const DEFAULT_TIMEOUT = 2 * 60 * 1000  // Default 2-minute timeout

parameters: z.object({
  command: z.string(),
  description: z.string(), // Command description (5-10 words)
  timeout: z.number().optional(),
  workdir: z.string().optional(),
})
```

**Security Features**:

* **Tree-sitter Parsing**: Uses `web-tree-sitter`'s Bash grammar parser to analyze commands and extract file paths that may be involved
* **Permission Granularity Control** (`BashArity`): Based on the parsing results, commands are classified into different permission granularity levels
* **Timeout Protection**: Default is 2 minutes, adjustable via parameters or environment variables
* **Working Directory Isolation**: Commands execute in the project directory by default, with support for the `workdir` parameter

### `batch.ts` -- Batch Tool Invocation

```typescript
parameters: z.object({
  description: z.string(),
  invocations: z.array(z.object({
    tool_name: z.string(),
    input: z.record(z.string(), z.any()),
  })),
})
```

The `batch` tool allows the LLM to execute multiple tools in parallel within a single call -- for example, reading 5 files simultaneously or running 3 grep searches at once. This significantly reduces the number of turns in the Agentic Loop.

## 5.3.3 Code Intelligence Tools

### `lsp.ts` -- LSP Operations Suite

> **Extended Explanation: LSP (Language Server Protocol)**
>
> LSP is a protocol standard proposed by Microsoft that defines how code editors communicate with "language servers." Language servers provide code intelligence features: auto-completion, go-to-definition, find-references, error diagnostics, and more. Through LSP, OpenCode achieves code comprehension capabilities comparable to a full IDE.

`lsp.ts` wraps the following LSP operations:

| Operation           | Function                                                |
| ------------------- | ------------------------------------------------------- |
| `goto_definition`   | Jump to a symbol's definition                           |
| `find_references`   | Find all references to a symbol                         |
| `document_symbols`  | Get all symbols within a file                           |
| `workspace_symbols` | Search for symbols across the entire project            |
| `diagnostics`       | Get diagnostic information for a file (errors/warnings) |
| `prepare_rename`    | Check whether a symbol can be renamed                   |
| `rename`            | Rename a symbol (across files)                          |

## 5.3.4 Networking Tools

### `webfetch.ts` -- URL Content Fetching

Fetches the content of a specified URL, with support for conversion to Markdown, plain text, or HTML format.

### `websearch.ts` -- Web Search

Uses a search engine API to search web content.

## 5.3.5 Agent Collaboration Tools

### `task.ts` -- Sub-Agent Task Delegation

The `task` tool is the core of multi-Agent collaboration. It creates a child Session and uses the specified Agent to execute a task:

```typescript
parameters: z.object({
  description: z.string(),    // Brief task description
  prompt: z.string(),         // Detailed task description
  subagent_type: z.string(),  // Sub-Agent type
  task_id: z.string().optional(), // Optional: resume a previous task
  command: z.string().optional(),
})
```

Execution flow:

1. Look up the corresponding Agent configuration based on `subagent_type`
2. Perform a permission check (`ctx.ask({ permission: "task", patterns: [subagent_type] })`)
3. Create a child Session (`Session.create({ parentID: ... })`) or resume an existing Session (via `task_id`)
4. Execute the conversation in the child Session
5. Return the child Session's final result to the parent Session
6. The result includes a `session_id` for subsequent resumption

### `question.ts` -- Interactive Questioning

Allows an Agent to initiate structured Q\&A interactions with the user (such as multiple-choice questions).

## 5.3.6 Utility Tools

### `todo.ts` -- Todo List Management

`TodoWriteTool` and `TodoReadTool` provide task-tracking capabilities for the Agent. The LLM can create Todo lists to plan work steps and update their status upon completion.

### `skill.ts` -- Skill Loading

Loads Markdown-formatted Skill files into the conversation context.

### `plan.ts` -- Plan Mode

`PlanEnterTool` and `PlanExitTool` allow the Agent to switch between a read-only "planning mode" and a writable "execution mode."

### `apply_patch.ts` -- Diff Patch Application

Accepts a standard unified diff format patch and applies it to the filesystem.

## 5.3.7 Tool Prompt Templates

Each tool has a corresponding `.txt` description file (e.g., `bash.txt`, `edit.txt`) containing the tool description text sent to the LLM. This **separation of code and prompt** design provides:

* Prompt tuning without modifying TypeScript code
* Description text that can include complex Markdown formatting and examples
* Support for template variables (e.g., `${directory}` is replaced with the current directory)

For example, `bash.txt` might contain:

```
Executes a bash command in the working directory: ${directory}

IMPORTANT: Always quote file paths with spaces...
```

In `BashTool`'s `init`:

```typescript
description: DESCRIPTION.replaceAll("${directory}", Instance.directory)
```
