opencode 内置工具
opencode 内置一套工具供 LLM 在对话中调用,用于读写文件、执行命令、搜索代码等操作。默认所有工具已启用,无需额外权限配置。
工具总览
| 工具 | 权限 key | description 类型 | 说明 |
|---|---|---|---|
bash |
bash |
静态 | 执行 shell 命令 |
read |
read |
静态 | 读取文件内容 |
edit |
edit |
静态 | 精确字符串替换修改文件 |
write |
edit |
静态 | 创建或覆盖文件 |
apply_patch |
edit |
静态 | 应用 patch 到文件 |
glob |
glob |
静态 | 按 glob 模式查找文件 |
grep |
grep |
静态 | 用正则搜索文件内容 |
webfetch |
webfetch |
静态 | 抓取指定网页内容 |
websearch |
websearch |
静态 | 联网搜索(需启用) |
question |
question |
静态 | 向用户提问,获取输入 |
todowrite |
todowrite |
静态 | 管理任务列表 |
skill |
skill |
动态 ★ | 加载 Skill 文件内容,运行时追加可用 Skill 列表 |
task |
task |
动态 ★ | 派发子 Agent 执行任务,运行时追加可用 Agent 列表 |
lsp |
lsp |
静态 | 代码智能(实验性,需启用) |
★ 动态 description :由
packages/opencode/src/tool/registry.ts在每次工具初始化时实时拼接,静态.txt内容 + 运行时查询结果。此外,所有工具 的 description 均可被插件通过
tool.definition钩子在运行时修改(见 插件文档)。
权限配置
所有工具的行为可通过 permission 字段统一控制:
kotlin
{
"$schema": "https://opencode.ai/config.json",
"permission": {
"bash": "ask", // 每次执行前询问
"edit": "allow", // 直接允许
"webfetch": "deny" // 禁止使用
}
}
支持通配符,例如对某个 MCP 服务器的所有工具要求确认:
json
{
"permission": {
"mymcp_*": "ask"
}
}
内置工具详解
源码目录:
packages/opencode/src/tool/
bash
源码:
packages/opencode/src/tool/bash.ts
vbnet
Executes a given bash command in a persistent shell session with optional timeout, ensuring proper
handling and security measures.
IMPORTANT: This tool is for terminal operations like git, npm, docker, etc. DO NOT use it for file
operations (reading, writing, editing, searching, finding files) - use the specialized tools instead.
Usage notes:
- The command argument is required.
- You can specify an optional timeout in milliseconds. Default: 120000ms (2 minutes).
- It is very helpful if you write a clear, concise description of what this command does in 5-10 words.
- Avoid using Bash with find, grep, cat, head, tail, sed, awk, or echo --- use dedicated tools instead.
- AVOID using `cd <dir> && <command>`. Use the `workdir` parameter instead.
- If the output exceeds the limit, it will be truncated and written to a file for later reading.
json
{ "permission": { "bash": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
command |
string | 是 | 要执行的 shell 命令 |
description |
string | 是 | 对该命令的简短描述(5-10 个词),如 "Lists files in current directory" |
timeout |
number | 否 | 超时时间(毫秒),默认 120000(2 分钟) |
workdir |
string | 否 | 命令运行的工作目录,默认当前目录。用此参数替代 cd 命令 |
注意事项:
- 避免使用
find、grep、cat、head、tail------请用专用工具 - 多个独立命令应并行调用,而非用
&&串联 - 路径含空格时需加双引号:
rm "path with spaces/file.txt" - 输出超过限制时会被截断并写入文件,可用
read工具读取
在
tool.execute.before钩子中通过output.args.command可读取或修改命令。
read
源码:
packages/opencode/src/tool/read.ts
vbnet
Read a file or directory from the local filesystem. If the path does not exist, an error is returned.
Usage:
- The filePath parameter should be an absolute path.
- By default, this tool returns up to 2000 lines from the start of the file.
- The offset parameter is the line number to start from (1-indexed).
- To read later sections, call this tool again with a larger offset.
- Use the grep tool to find specific content in large files or files with long lines.
- Contents are returned with each line prefixed by its line number as `<line>: <content>`.
- Any line longer than 2000 characters is truncated.
- Call this tool in parallel when you know there are multiple files you want to read.
- This tool can read image files and PDFs and return them as file attachments.
json
{ "permission": { "read": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
filePath |
string | 是 | 文件或目录的绝对路径 |
offset |
number | 否 | 起始行号(从 1 开始) |
limit |
number | 否 | 最多读取的行数,默认 2000 |
注意事项:
- 返回内容每行带行号前缀,格式为
<行号>: <内容> - 超过 2000 字符的行会被截断
- 目录路径返回子项列表,子目录以
/结尾 - 需要读多个文件时可并行调用
edit
源码:
packages/opencode/src/tool/edit.ts
swift
Performs exact string replacements in files.
Usage:
- You must use your `Read` tool at least once in the conversation before editing. This tool will
error if you attempt an edit without reading the file.
- When editing text from Read tool output, preserve the exact indentation as it appears AFTER the
line number prefix. Never include any part of the line number prefix in oldString or newString.
- The edit will FAIL if `oldString` is not found in the file.
- The edit will FAIL if `oldString` is found multiple times --- provide more surrounding context or
use `replaceAll`.
- Use `replaceAll` for replacing and renaming strings across the file.
json
{ "permission": { "edit": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
filePath |
string | 是 | 要修改文件的绝对路径 |
oldString |
string | 是 | 要被替换的原始文本 |
newString |
string | 是 | 替换后的新文本(必须与 oldString 不同) |
replaceAll |
boolean | 否 | 替换文件中所有匹配项,默认 false |
注意事项:
- 调用前必须先用
read读取过该文件,否则报错 oldString在文件中必须唯一 ,否则报错(需提供更多上下文或使用replaceAll)- 保留原始缩进(tab/空格)
edit权限同时控制edit、write、apply_patch三个工具
write
源码:
packages/opencode/src/tool/write.ts
vbnet
Writes a file to the local filesystem.
Usage:
- This tool will overwrite the existing file if there is one at the provided path.
- If this is an existing file, you MUST use the Read tool first to read the file's contents.
This tool will fail if you did not read the file first.
- ALWAYS prefer editing existing files in the codebase. NEVER write new files unless explicitly required.
json
{ "permission": { "edit": "allow" } } // 由 edit 权限控制
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
filePath |
string | 是 | 写入文件的绝对路径(不能是相对路径) |
content |
string | 是 | 写入文件的完整内容 |
注意事项:
- 优先使用
edit修改已有文件,仅在需要全量重写或新建时使用write - 写已有文件前必须先用
read读取
apply_patch
源码:
packages/opencode/src/tool/apply_patch.ts
sql
Use the `apply_patch` tool to edit files. Your patch language is a stripped-down, file-oriented
diff format designed to be easy to parse and safe to apply.
Each operation starts with one of three headers:
*** Add File: <path> - create a new file. Every following line is a + line (initial contents).
*** Delete File: <path> - remove an existing file. Nothing follows.
*** Update File: <path> - patch an existing file in place (optionally with a rename via *** Move to:).
Important:
- You must include a header with your intended action (Add/Delete/Update).
- You must prefix new lines with `+` even when creating a new file.
json
{ "permission": { "edit": "allow" } } // 由 edit 权限控制
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
patchText |
string | 是 | 完整的 patch 文本,包含所有文件变更描述 |
patch 格式:
diff
*** Begin Patch
*** Add File: src/new-file.ts
+文件内容行(以 + 开头)
*** Update File: src/existing.ts
*** Move to: src/renamed.ts
@@ def greet():
-旧代码行
+新代码行
*** Delete File: src/obsolete.ts
*** End Patch
注意事项:
- 路径相对于项目根目录
- 在钩子中检查工具时用
input.tool === "apply_patch",参数从output.args.patchText获取(不是filePath)
glob
源码:
packages/opencode/src/tool/glob.ts
sql
- Fast file pattern matching tool that works with any codebase size
- Supports glob patterns like "**/*.js" or "src/**/*.ts"
- Returns matching file paths sorted by modification time
- Use this tool when you need to find files by name patterns
- When doing an open-ended search requiring multiple rounds of globbing and grepping, use the Task tool instead
- It is always better to speculatively perform multiple searches as a batch that are potentially useful
json
{ "permission": { "glob": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
pattern |
string | 是 | glob 匹配模式,如 **/*.ts、src/**/*.vue |
path |
string | 否 | 搜索的根目录,默认为当前工作目录 |
注意事项:
-
底层使用 ripgrep,自动遵守
.gitignore规则 -
需要包含被忽略的目录,在项目根创建
.ignore文件:diff!node_modules/ !dist/
grep
源码:
packages/opencode/src/tool/grep.ts
sql
- Fast content search tool that works with any codebase size
- Searches file contents using regular expressions
- Supports full regex syntax (eg. "log.*Error", "function\s+\w+", etc.)
- Filter files by pattern with the include parameter (eg. "*.js", "*.{ts,tsx}")
- Returns file paths and line numbers with at least one match sorted by modification time
- Use this tool when you need to find files containing specific patterns
- If you need to identify/count the number of matches within files, use the Bash tool with `rg` directly. Do NOT use `grep`.
- When doing an open-ended search requiring multiple rounds of globbing and grepping, use the Task tool instead
json
{ "permission": { "grep": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
pattern |
string | 是 | 正则表达式搜索模式,如 "log.*Error"、"function\s+\w+" |
path |
string | 否 | 搜索目录,默认为当前工作目录 |
include |
string | 否 | 文件过滤 glob 模式,如 *.js、*.{ts,tsx} |
注意事项:
- 底层使用 ripgrep,默认遵守
.gitignore - 需要统计匹配数量时,用
bash工具调用rg命令
webfetch
源码:
packages/opencode/src/tool/webfetch.ts
vbnet
- Fetches content from a specified URL
- Takes a URL and optional format as input
- Fetches the URL content, converts to requested format (markdown by default)
- Returns the content in the specified format
- Use this tool when you need to retrieve and analyze web content
Usage notes:
- IMPORTANT: if another tool offers better web fetching capabilities, prefer using that instead.
- The URL must be a fully-formed valid URL
- HTTP URLs will be automatically upgraded to HTTPS
- Format options: "markdown" (default), "text", or "html"
- This tool is read-only and does not modify any files
- Results may be summarized if the content is very large
json
{ "permission": { "webfetch": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
url |
string | 是 | 要抓取内容的完整 URL |
format |
"text" \ |
"markdown" \ |
"html" |
timeout |
number | 否 | 超时时间(秒),最大 120 |
已知 URL 用
webfetch(精确获取),需要发现内容用websearch(搜索)。
websearch
源码:
packages/opencode/src/tool/websearch.ts
sql
- Search the web using Exa AI - performs real-time web searches and can scrape content from specific URLs
- Provides up-to-date information for current events and recent data
- Supports configurable result counts and returns the content from the most relevant websites
- Use this tool for accessing information beyond knowledge cutoff
- Searches are performed automatically within a single API call
Usage notes:
- Supports live crawling modes: 'fallback' (backup if cached unavailable) or 'preferred' (prioritize live crawling)
- Search types: 'auto' (balanced), 'fast' (quick results), 'deep' (comprehensive search)
- Configurable context length for optimal LLM integration
json
{ "permission": { "websearch": "allow" } }
启用条件(满足其一):
- 使用 OpenCode 官方提供商
- 设置环境变量
OPENCODE_ENABLE_EXA=1
ini
OPENCODE_ENABLE_EXA=1 opencode
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
query |
string | 是 | 搜索查询词 |
numResults |
number | 否 | 返回结果数量,默认 8 |
type |
"auto" \ |
"fast" \ |
"deep" |
livecrawl |
"fallback" \ |
"preferred" |
否 |
contextMaxCharacters |
number | 否 | 返回上下文的最大字符数,默认 10000 |
question
源码:
packages/opencode/src/tool/question.ts
vbnet
Use this tool when you need to ask the user questions during execution. This allows you to:
1. Gather user preferences or requirements
2. Clarify ambiguous instructions
3. Get decisions on implementation choices as you work
4. Offer choices to the user about what direction to take.
Usage notes:
- When `custom` is enabled (default), a "Type your own answer" option is added automatically;
don't include "Other" or catch-all options.
- Answers are returned as arrays of labels; set `multiple: true` to allow selecting more than one.
- If you recommend a specific option, make that the first option in the list and add "(Recommended)"
at the end of the label.
json
{ "permission": { "question": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
questions |
Question[] | 是 | 问题列表,每项为一个 Question 对象 |
Question 对象结构:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
question |
string | 是 | 完整的问题文本 |
header |
string | 是 | 简短标签(最多 30 个字符),显示在问题标题处 |
options |
Option[] | 是 | 可选项列表(见 Option 结构) |
multiple |
boolean | 否 | 是否允许多选,默认 false |
Option 对象结构:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
label |
string | 是 | 选项显示文本(1-5 个词,简洁) |
description |
string | 是 | 选项的详细说明 |
行为说明:
- 默认自动追加「输入自定义答案」选项,无需手动添加「其他」选项
- 推荐选项应放在第一位,标签末尾加
"(Recommended)" - 返回值为选中的
label数组,多选时包含多个元素
示例:
css
{
"questions": [
{
"question": "你希望使用哪种状态管理方案?",
"header": "状态管理",
"options": [
{ "label": "Zustand (Recommended)", "description": "轻量级,API 简单,适合中小型项目" },
{ "label": "Redux Toolkit", "description": "功能完整,适合大型复杂应用" },
{ "label": "Jotai", "description": "原子化状态管理,灵活" }
],
"multiple": false
}
]
}
todowrite
源码:
packages/opencode/src/tool/todo.ts
sql
Use this tool to create and manage a structured task list for your current coding session. This
helps you track progress, organize complex tasks, and demonstrate thoroughness to the user.
It also helps the user understand the progress of the task and overall progress of their requests.
When to Use This Tool:
1. Complex multistep tasks - When a task requires 3 or more distinct steps or actions
2. Non-trivial and complex tasks - Tasks that require careful planning or multiple operations
3. User explicitly requests todo list
4. User provides multiple tasks (numbered or comma-separated)
5. After receiving new instructions - Immediately capture user requirements as todos
6. After completing a task - Mark it complete and add any new follow-up tasks
7. When you start working on a new task, mark the todo as in_progress.
Ideally only ONE todo should be in_progress at a time.
When NOT to Use This Tool:
1. There is only a single, straightforward task
2. The task is trivial and tracking it provides no organizational benefit
3. The task can be completed in less than 3 trivial steps
4. The task is purely conversational or informational
Task States: pending | in_progress | completed | cancelled
json
{ "permission": { "todowrite": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
todos |
TodoItem[] | 是 | 完整的任务列表(全量替换,非增量更新) |
TodoItem 对象结构:
| 字段 | 类型 | 必填 | 说明 |
|---|---|---|---|
content |
string | 是 | 任务的简短描述 |
status |
string | 是 | 任务状态:pending、in_progress、completed、cancelled |
priority |
string | 是 | 优先级:high、medium、low |
子 Agent(subagent)默认禁用此工具,需手动启用。
skill
源码:
packages/opencode/src/tool/skill.ts
vbnet
Load a specialized skill when the task at hand matches one of the skills listed in the system prompt.
Use this tool to inject the skill's instructions and resources into current conversation. The output
may contain detailed workflow guidance as well as references to scripts, files, etc in the same
directory as the skill.
The skill name must match one of the skills listed in your system prompt.
json
{ "permission": { "skill": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
name |
string | 是 | Skill 名称,必须匹配 description 中 Available Skills 列出的名称 |
模型如何知道有哪些 skill 可用?
与 task 工具相同,skill 工具的 description 也是运行时动态拼接 的。registry.ts 中的 describeSkill() 函数在每次工具初始化时查询当前可用的 Skill 列表,追加到静态描述末尾:
markdown
## Available Skills
- **my-skill**: This skill does X
- **another-skill**: This skill does Y
若无任何 skill,则追加:No skills are currently available.
源码:
packages/opencode/src/tool/registry.ts---describeSkill()函数 Skill 格式化:packages/opencode/src/skill/index.ts---fmt()函数
筛选逻辑: 加载所有已发现的 skill,过滤掉当前 Agent permission 中 skill 被 deny 的项,按名称排序后注入描述。
Skill 来源目录(按优先级加载):
- 项目级:
.opencode/skills/ - 全局:
~/.config/opencode/skills/
完整运行时 description 示例:
vbnet
Load a specialized skill when the task at hand matches one of the skills listed in the system prompt.
Use this tool to inject the skill's instructions and resources into current conversation. The output
may contain detailed workflow guidance as well as references to scripts, files, etc in the same
directory as the skill.
The skill name must match one of the skills listed in your system prompt.
Load a specialized skill that provides domain-specific instructions and workflows.
When you recognize that a task matches one of the available skills listed below, use this tool to
load the full skill instructions.
The following skills provide specialized sets of instructions for particular tasks.
Invoke this tool to load a skill when a task matches one of the available skills listed below:
## Available Skills
- **commit**: Guidelines for creating git commits
- **code-review**: Standards for reviewing pull requests
task
源码:
packages/opencode/src/tool/task.ts
vbnet
Launch a new agent to handle complex, multistep tasks autonomously.
When using the Task tool, you must specify a subagent_type parameter to select which agent type to use.
When to use the Task tool:
- When you are instructed to execute custom slash commands.
When NOT to use the Task tool:
- If you want to read a specific file path, use the Read or Glob tool instead.
- If you are searching for a specific class definition, use the Glob tool instead.
- If you are searching for code within a specific file or set of 2-3 files, use the Read tool instead.
Usage notes:
1. Launch multiple agents concurrently whenever possible, to maximize performance.
2. When the agent is done, it will return a single message. The result is not visible to the user ---
send a text message to the user with a concise summary. The output includes a task_id you can
reuse later to continue the same subagent session.
3. Each agent invocation starts with a fresh context unless you provide task_id to resume.
4. Clearly tell the agent whether you expect it to write code or just do research.
json
{ "permission": { "task": "allow" } }
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
description |
string | 是 | 任务的简短描述(3-5 个词) |
prompt |
string | 是 | 子 Agent 要执行的完整详细任务描述,需明确说明期望的返回内容 |
subagent_type |
string | 是 | 指定使用的 Agent 类型 |
task_id |
string | 否 | 传入已有 task_id 可续接之前的子 Agent 会话(保留历史上下文) |
command |
string | 否 | 触发此任务的命令名称 |
模型如何知道有哪些 subagent 可用?
task 工具的 description 是运行时动态拼接 的,并非全部来自静态 task.txt。每次调用前,registry.ts 中的 describeTask() 函数会实时查询当前可用的 Agent 列表,并追加到工具描述末尾:
yaml
Available agent types and the tools they have access to:
- explore: Fast agent specialized for exploring codebases...
- general: General-purpose agent for researching complex questions...
源码:
packages/opencode/src/tool/registry.ts---describeTask()函数
追加逻辑: 筛选出 mode !== "primary" 且当前 Agent 有权使用 task 工具的所有 Agent,按名称排序后拼接到描述中。hidden: true 的 Agent(如 compaction、title、summary)不会出现在列表中。
内置可用 subagent(mode 为 subagent):
| 名称 | 说明 |
|---|---|
general |
General-purpose agent for researching complex questions and executing multi-step tasks. |
explore |
Fast agent specialized for exploring codebases. Supports file search, keyword search, and codebase Q&A. |
源码:
packages/opencode/src/agent/agent.ts
如何查看当前所有可用 Agent:
opencode agent list
或通过 API:
bash
curl http://localhost:4096/agent
自定义 Agent 作为 subagent: 在 opencode.json 中配置 mode: "subagent" 或 mode: "all" 的 Agent,会自动出现在运行时 description 中:
css
{
"agent": {
"code-reviewer": {
"description": "专注代码审查的 Agent",
"mode": "subagent",
"prompt": "你是一个专业的代码审查员..."
}
}
}
注意事项:
- 多个独立任务应并行启动(单次消息中发起多个 task 调用)
- 子 Agent 完成后返回单条消息,结果对用户不可见,需主动汇报
task_id可复用,续接时子 Agent 保留完整历史上下文- 传入不存在的
subagent_type会报错:Unknown agent type: xxx is not a valid agent type
lsp(实验性)
源码:
packages/opencode/src/tool/lsp.ts
sql
Interact with Language Server Protocol (LSP) servers to get code intelligence features.
Supported operations:
- goToDefinition: Find where a symbol is defined
- findReferences: Find all references to a symbol
- hover: Get hover information (documentation, type info) for a symbol
- documentSymbol: Get all symbols (functions, classes, variables) in a document
- workspaceSymbol: List project-wide symbols matching a query string
- goToImplementation: Find implementations of an interface or abstract method
- prepareCallHierarchy: Get call hierarchy item at a position (functions/methods)
- incomingCalls: Find all functions/methods that call the function at a position
- outgoingCalls: Find all functions/methods called by the function at a position
All operations require: filePath, line, character.
workspaceSymbol also accepts: query (empty string requests all symbols).
Note: LSP servers must be configured for the file type. If no server is available, an error will be returned.
json
{ "permission": { "lsp": "allow" } }
启用方式:
ini
OPENCODE_EXPERIMENTAL_LSP_TOOL=true opencode
# 或
OPENCODE_EXPERIMENTAL=true opencode
参数:
| 参数 | 类型 | 必填 | 说明 |
|---|---|---|---|
operation |
string | 是 | LSP 操作类型(见下表) |
filePath |
string | 是 | 文件的绝对或相对路径(也用于选择匹配的 LSP 服务器) |
line |
number | 是 | 行号(从 1 开始,同编辑器显示) |
character |
number | 是 | 字符偏移(从 1 开始,同编辑器显示) |
query |
string | 否 | 仅 workspaceSymbol 使用,搜索词;空字符串返回所有符号 |
operation 可选值:
| 操作 | 说明 |
|---|---|
goToDefinition |
跳转到符号定义处 |
findReferences |
查找所有引用位置 |
hover |
获取悬停信息(类型、文档注释) |
documentSymbol |
列出当前文件内所有符号(函数、类、变量等) |
workspaceSymbol |
在整个工作区搜索符号(需提供 query) |
goToImplementation |
跳转到接口/抽象方法的具体实现 |
prepareCallHierarchy |
在指定位置准备调用层级分析 |
incomingCalls |
查找所有调用当前函数的调用方 |
outgoingCalls |
查找当前函数内调用的所有函数 |
若对应文件类型没有配置 LSP 服务器,工具会返回错误。LSP 服务器配置参见 LSP 文档。