> 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_15_oh-my-opencode_deep_dive/15.4_custom_tool_system.md). Agents can also search and read this documentation through its [MCP server](https://www.opencodebook.xyz/~gitbook/mcp).

# 15.4 Custom Tool System

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

***

oh-my-opencode registers 15 custom tools through OpenCode's Plugin `tool` interface, providing Agents with capabilities far beyond OpenCode's built-in tool set. This section provides an overview of these tools and takes a deep dive into the two most innovative ones: AST-Grep and Hashline Edit.

## 15.4.1 Tool List and Implementation

The following is the complete set of tools registered by oh-my-opencode:

| Tool                | Source Location           | Function                                                  | Tech Stack       |
| ------------------- | ------------------------- | --------------------------------------------------------- | ---------------- |
| `ast_grep_search`   | `tools/ast-grep/`         | AST-level code pattern search                             | ast-grep CLI     |
| `ast_grep_replace`  | `tools/ast-grep/`         | AST-level code pattern replacement                        | ast-grep CLI     |
| `background_output` | `tools/background-task/`  | Retrieve background task output                           | OpenCode SDK     |
| `background_cancel` | `tools/background-task/`  | Cancel background tasks                                   | OpenCode SDK     |
| `call_omo_agent`    | `tools/call-omo-agent/`   | Directly invoke a specified Agent                         | OpenCode SDK     |
| `delegate_task`     | `tools/delegate-task/`    | Delegate tasks to sub-Agents                              | OpenCode SDK     |
| `glob`              | `tools/glob/`             | Enhanced file pattern matching                            | Node.js fs       |
| `grep`              | `tools/grep/`             | Enhanced content search                                   | ripgrep          |
| `hashline_edit`     | `tools/hashline-edit/`    | Precise editing based on line number hashes               | xxHash32         |
| `interactive_bash`  | `tools/interactive-bash/` | tmux interactive terminal                                 | tmux             |
| `look_at`           | `tools/look-at/`          | Multimodal file analysis                                  | Multimodal LLM   |
| `lsp_*` (6 tools)   | `tools/lsp/`              | LSP integration (go-to-definition, find references, etc.) | LSP Protocol     |
| `session_*`         | `tools/session-manager/`  | Session history querying and searching                    | OpenCode Storage |
| `skill_mcp`         | `tools/skill-mcp/`        | Skill embedded MCP invocation                             | MCP SDK          |
| `skill`             | `tools/skill/`            | Skill file loading                                        | Filesystem       |
| `slashcommand`      | `tools/slashcommand/`     | Slash command execution                                   | Command system   |
| `task`              | `tools/task/`             | Enhanced task delegation                                  | OpenCode SDK     |

The tool registration entry point is in `tools/index.ts`:

```typescript
// oh-my-opencode/src/tools/index.ts

// LSP tool set (6 tools)
export const builtinTools: Record<string, ToolDefinition> = {
  lsp_goto_definition,
  lsp_find_references,
  lsp_symbols,
  lsp_diagnostics,
  lsp_prepare_rename,
  lsp_rename,
}

// AST-Grep tools
export { createAstGrepTools } from "./ast-grep"

// Background task management
export function createBackgroundTools(manager, client): Record<string, ToolDefinition> {
  return {
    background_output: createBackgroundOutput(manager, client),
    background_cancel: createBackgroundCancel(manager, client),
  }
}

// Hashline Edit
export { createHashlineEditTool } from "./hashline-edit"

// Task system (new version)
export {
  createTaskCreateTool,
  createTaskGetTool,
  createTaskList,
  createTaskUpdateTool,
} from "./task"
```

Tools fall into two registration patterns:

1. **Static tools** (such as the LSP tools in `builtinTools`): Do not need runtime context and are exported directly
2. **Factory tools** (such as `createAstGrepTools(ctx)`): Need Plugin context injection (directory path, client references, etc.) and are created through factory functions

## 15.4.2 AST-Grep Tool Deep Dive

AST-Grep is one of the most complex tools in oh-my-opencode. It provides code search and replace capabilities based on the **Abstract Syntax Tree (AST)**, far surpassing traditional text-based search (grep).

> **Extended Explanation: What is an AST (Abstract Syntax Tree)?**
>
> An AST (Abstract Syntax Tree) is a tree-shaped data structure generated by a programming language compiler/interpreter when parsing source code. It represents the syntactic structure of code as a tree, where each node represents a syntactic construct (such as a variable declaration, function call, if statement, etc.).
>
> For example, the AST for `const x = 1 + 2` looks approximately like:
>
> ```
> VariableDeclaration
> ├── kind: "const"
> └── declarations
>     └── VariableDeclarator
>         ├── id: Identifier("x")
>         └── init: BinaryExpression
>             ├── operator: "+"
>             ├── left: Literal(1)
>             └── right: Literal(2)
> ```
>
> The key difference between **AST-level search** and **text-level search** is:
>
> * **Text search** `grep "console.log"` matches all lines containing that string, including `// console.log` in comments and `"console.log"` in strings
> * **AST search** `ast-grep -p "console.log($MSG)"` matches only actual `console.log` function calls, ignoring comments and strings
>
> AST search also supports **meta-variables**: `$VAR` matches a single AST node, `$$$` matches multiple nodes. This enables search patterns to express complex code structures.

### Architecture

The AST-Grep tool implementation spans 13 source files with the following architecture:

```
tools/ast-grep/
├── tools.ts              # Tool definitions (search + replace)
├── cli.ts                # ast-grep CLI process management
├── cli-binary-path-resolution.ts  # Binary file path resolution
├── sg-cli-path.ts        # CLI path caching
├── downloader.ts         # Automatic ast-grep binary download
├── environment-check.ts  # Environment compatibility checks
├── language-support.ts   # Supported language list
├── result-formatter.ts   # Result formatting
├── sg-compact-json-output.ts  # JSON output parsing
├── process-output-timeout.ts  # Process timeout management
├── constants.ts          # Constant definitions
├── types.ts              # Type definitions
└── index.ts              # Exports
```

### Tool Definitions

oh-my-opencode provides two AST-Grep tools: **search** and **replace**.

```typescript
// oh-my-opencode/src/tools/ast-grep/tools.ts
export function createAstGrepTools(ctx: PluginInput): Record<string, ToolDefinition> {
  const ast_grep_search = tool({
    description:
      "Search code patterns across filesystem using AST-aware matching. " +
      "Supports 25 languages. " +
      "Use meta-variables: $VAR (single node), $$$ (multiple nodes). " +
      "IMPORTANT: Patterns must be complete AST nodes (valid code).",
    args: {
      pattern: tool.schema.string(),
      lang: tool.schema.enum(CLI_LANGUAGES),
      paths: tool.schema.array(tool.schema.string()).optional(),
      globs: tool.schema.array(tool.schema.string()).optional(),
      context: tool.schema.number().optional(),
    },
    execute: async (args, context) => {
      const result = await runSg({
        pattern: args.pattern,
        lang: args.lang,
        paths: args.paths ?? [ctx.directory],
        // ...
      })

      let output = formatSearchResult(result)

      // Provide pattern correction suggestions on empty results
      if (result.matches.length === 0 && !result.error) {
        const hint = getEmptyResultHint(args.pattern, args.lang)
        if (hint) output += `\n\n${hint}`
      }

      return output
    },
  })

  const ast_grep_replace = tool({
    description: "Replace code patterns with AST-aware rewriting. Dry-run by default.",
    args: {
      pattern: tool.schema.string(),
      rewrite: tool.schema.string(),
      lang: tool.schema.enum(CLI_LANGUAGES),
      dryRun: tool.schema.boolean().optional(),
      // ...
    },
    execute: async (args, context) => {
      const result = await runSg({
        pattern: args.pattern,
        rewrite: args.rewrite,
        lang: args.lang,
        updateAll: args.dryRun === false,  // Dry-run by default
      })
      return formatReplaceResult(result, args.dryRun !== false)
    },
  })

  return { ast_grep_search, ast_grep_replace }
}
```

### Intelligent Empty Result Hints

A thoughtful design is the `getEmptyResultHint()` function -- when a search returns no results, it analyzes the search pattern and provides correction suggestions:

```typescript
function getEmptyResultHint(pattern: string, lang: CliLanguage): string | null {
  // Python: suggest removing trailing colon
  if (lang === "python") {
    if (src.startsWith("class ") && src.endsWith(":")) {
      return `Hint: Remove trailing colon. Try: "${src.slice(0, -1)}"`
    }
  }

  // JS/TS: suggest function patterns need params and body
  if (["javascript", "typescript", "tsx"].includes(lang)) {
    if (/^(export\s+)?(async\s+)?function\s+\$[A-Z_]+\s*$/i.test(src)) {
      return `Hint: Function patterns need params and body. Try "function $NAME($$$) { $$$ }"`
    }
  }

  return null
}
```

This addresses a common pitfall with AST-Grep: AST patterns must be **complete AST nodes**. Searching for `function $NAME` will not match anything because it is not a valid JavaScript AST node -- it is missing the parameter list and function body. The correct pattern should be `function $NAME($$$) { $$$ }`.

### CLI Process Management

AST-Grep's underlying implementation works by calling the `ast-grep` CLI binary:

```typescript
// oh-my-opencode/src/tools/ast-grep/cli.ts
export async function runSg(options: RunOptions): Promise<SgResult> {
  // Build command-line arguments
  const args = ["run", "-p", options.pattern, "--lang", options.lang, "--json=compact"]

  if (options.rewrite) {
    args.push("-r", options.rewrite)
  }

  // Resolve CLI path (auto-download if not present)
  let cliPath = getSgCliPath()
  if (!cliPath || !existsSync(cliPath)) {
    cliPath = await getAstGrepPath()
    if (!cliPath) {
      cliPath = await ensureAstGrepBinary()
    }
  }

  // Spawn child process
  const proc = spawn({ cmd: [cliPath, ...args], /* ... */ })
  const result = await collectProcessOutputWithTimeout(proc, DEFAULT_TIMEOUT_MS)
  return createSgResultFromStdout(result.stdout)
}
```

oh-my-opencode automatically handles acquisition of the `ast-grep` binary -- if it is not installed on the system, the tool automatically downloads the precompiled binary for the appropriate platform.

## 15.4.3 The Innovative Design of Hashline Edit

Hashline Edit is an original file editing tool created by oh-my-opencode. By attaching a **line number hash** to each line of code, it solves a fundamental problem that LLMs face when editing files: **accuracy of edit target positioning**.

### Problem Background

Traditional text editing tools (such as OpenCode's built-in Edit tool) use an "old text -> new text" replacement pattern:

```json
{
  "oldString": "const x = 1",
  "newString": "const x = 2"
}
```

The problem with this approach: if the file contains multiple instances of `const x = 1`, the tool cannot determine which one to replace. OpenCode's Edit tool requires `oldString` to match uniquely -- if multiple matches are found, the edit fails.

This forces the LLM to provide more surrounding context code to ensure uniqueness, increasing token consumption and error probability.

### The Hashline Solution

Hashline Edit's core idea is: **attach a short hash value to each line of code, serving as a line-level "identity tag"**.

```
Original file content:              Hashline format:
const x = 1                    1:a3|const x = 1
const y = 2                    2:b7|const y = 2
const x = 1                    3:a3|const x = 1
```

The format is `line_number:hash|content`, where:

* **Line number**: 1-based line number
* **Hash**: The first 2 hexadecimal characters of the line content's xxHash32 hash value (256 possible values)
* **Content**: The original text of the line

### Hash Computation

```typescript
// oh-my-opencode/src/tools/hashline-edit/hash-computation.ts
export function computeLineHash(_lineNumber: number, content: string): string {
  const stripped = content.replace(/\s+/g, "")   // Remove all whitespace
  const hash = Bun.hash.xxHash32(stripped)        // Use xxHash32 hashing
  const index = hash % 256                        // Modulo to get index 0-255
  return HASH_DICT[index]                         // Map to 2-character hexadecimal
}
```

Several design choices in the hash computation:

1. **Hash after whitespace removal**: `content.replace(/\s+/g, "")`. This means indentation changes do not alter the hash value, enhancing robustness.
2. **Using xxHash32**: A very fast non-cryptographic hash function, suitable for rapidly hashing large numbers of small strings.
3. **256 possible values**: The hash is only 2 hexadecimal characters (`00` to `ff`). This is intentional -- too short risks collisions, too long wastes tokens. 256 values strike a balance between "positioning accuracy" and "token efficiency."

### Four Edit Operations

Hashline Edit supports four edit operations:

```typescript
// 1. set_line: Replace a single line
{ "type": "set_line", "line": "5:a3", "text": "const y = 2" }

// 2. replace_lines: Replace a range of lines
{ "type": "replace_lines", "start_line": "5:a3", "end_line": "7:b2", "text": "new\ncontent" }

// 3. insert_after: Insert after a specified line
{ "type": "insert_after", "line": "5:a3", "text": "console.log('hi')" }

// 4. replace: Traditional text replacement (without hashes)
{ "type": "replace", "old_text": "foo", "new_text": "bar" }
```

### Hash Mismatch Protection

Hashline Edit's most important feature is **hash validation**. When the hash provided by the LLM when referencing a line does not match the hash of the file's current content, the edit fails and returns an error:

```
Hash mismatch at line 5: expected "a3" but got "b7".
The file has been modified since you last read it.
Please re-read the file to get current content.
```

This solves the "stale edit" problem -- if the file has been modified after the LLM read it (possibly by another parallel Agent), Hashline Edit will reject the edit rather than writing content at the wrong location.

### Bottom-Up Application

Edit operations are applied in **bottom-to-top** order (highest line number first). This is a critical design choice -- because inserting or deleting lines changes the line numbers of subsequent lines. If applied top-to-bottom, earlier edits would invalidate later line number references; applying bottom-to-top avoids this problem.

### Integration with the Read Tool

Hashline Edit is not an isolated tool -- it works in conjunction with the Read tool. oh-my-opencode enhances OpenCode's Read tool output through the `hashline-read-enhancer` hook:

```
// Standard Read output:
1: const x = 1
2: const y = 2

// Hashline-enhanced Read output:
1:a3|const x = 1
2:b7|const y = 2
```

This way, the LLM automatically obtains each line's hash value when reading a file, which can be directly used for Hashline Edit operations.

> **Extended Explanation: Advantages of AST-Level Code Search**
>
> Traditional code search tools (such as `grep`, `ripgrep`) are **text-based** -- they treat code as sequences of characters and use regular expressions for pattern matching. This approach is simple and fast but has clear limitations:
>
> 1. **Cannot understand code structure**: Searching for `function add` matches function definitions, descriptions in comments, references in strings -- with no way to distinguish between them
> 2. **Cannot handle formatting differences**: `function add(a, b)` and `function add( a, b )` are textually different but identical in AST
> 3. **Cannot express structural patterns**: Requirements like "find all functions that accept two parameters" are nearly impossible to express with regular expressions
>
> AST search overcomes these limitations by first **parsing** code into an AST, then performing pattern matching on the AST. ast-grep supports AST parsing for 25 programming languages, using Tree-sitter parsers (an incremental parsing library widely used by GitHub, Neovim, and others).
>
> However, AST search comes at a cost: it requires fully parsing source files, making it slower than text search. oh-my-opencode mitigates this by invoking the `ast-grep` CLI rather than parsing in-process -- the CLI is implemented in Rust and delivers extremely high performance.

## Section Summary

oh-my-opencode's custom tool system registers 15 tools through the Plugin's `tool` interface, covering everything from code search to background task management.

The two most innovative tools are:

1. **AST-Grep**: AST-based code search and replace, supporting 25 languages and expressing structural patterns through meta-variables. It includes polished engineering features such as automatic binary download, intelligent empty result hints, and process timeout management.
2. **Hashline Edit**: Through the combination of line numbers and xxHash32 short hashes, it provides precise "identity tags" for each line of code. This solves the edit target positioning accuracy problem that LLMs face, while preventing incorrect edits to stale file content through hash validation.
