The claw code tools are the primary mechanism through which the AI agent interacts with the developer's environment. Defined in rust/crates/tools/src/lib.rs, each tool is registered as a ToolSpec containing a name, description, and JSON input_schema. At runtime, the agent selects tools based on the task at hand, and the framework validates inputs, checks permissions, executes the tool, and returns structured results. This page documents all 19 built-in tools, the Python orchestration layer, the ToolPool assembly process, and the permission gating architecture.

工具架構概覽

The claw code tools follow a consistent lifecycle: the LLM emits a tool_use content block specifying a tool name and JSON input, the runtime validates the input against the tool's input_schema, the permission engine checks whether the call is allowed, the tool executes, and the result is returned to the LLM as a tool_result content block. This architecture is split across two layers:

Every tool follows a uniform pattern in the Rust crate: parse the LLM's JSON input, validate required and optional fields against the schema, check permissions via the PermissionEngine, execute the operation, and return a typed result struct. This consistency makes it straightforward to add new tools or modify existing ones without disrupting the rest of the system.

Shell 執行工具

1. bash — Shell Command Execution

The bash tool is the most powerful and most heavily gated tool in the claw code tools suite. It executes arbitrary shell commands in a sandboxed environment, capturing stdout, stderr, and the exit code.

參數 類型 必填 描述
command string The shell command to execute
timeout integer Timeout in milliseconds. Maximum 600000 (10 minutes)
description string Human-readable description of what the command does
run_in_background boolean Run the command in the background, returning a background_task_id
dangerously_disable_sandbox boolean Disable the execution sandbox. Requires explicit permission

The output is a BashCommandOutput struct containing stdout, stderr, return_code_interpretation, an interrupted flag (set when the command was killed due to timeout), and an optional background_task_id for background commands.

沙箱強制執行

By default, all bash commands run inside a sandbox that restricts file system access, network egress, and process creation. The dangerously_disable_sandbox flag bypasses these restrictions but requires the user to have explicitly granted this permission in their settings.

19. PowerShell — Windows Shell Execution

The PowerShell tool provides Windows-native shell execution. It accepts two parameters: command (the PowerShell command to execute) and an optional timeout in milliseconds. This is a conditional tool — only available on Windows platforms — and provides the same sandbox enforcement as the bash tool.

檔案操作工具

2. read_file — File Reading with Offset/Limit

The read_file tool reads files from the local filesystem with optional offset and limit parameters for efficient partial reads of large files.

參數 類型 必填 描述
file_path string Absolute path to the file to read
offset integer Line number to start reading from
limit integer Number of lines to read
pages string Page range for PDF files (e.g. "1-5", "3", "10-20")

The tool supports reading text files, images (PNG, JPG — presented visually to the multimodal LLM), PDF files (with the pages parameter for large documents), and Jupyter notebooks (.ipynb files with all cells and outputs). Output is returned in cat -n format with line numbers starting at 1.

3. write_file — File Creation and Overwrite

The write_file tool creates new files or overwrites existing ones. It requires an absolute file_path and the full content to write. The output includes both a structured_patch and a git_diff, making it easy to review exactly what changed. This tool is permission-gated — the agent must have write access to the target path.

4. edit_file — String Replacement Editing

The edit_file tool performs precise string replacement within files. Rather than rewriting entire files, the agent specifies an old_string to find and a new_string to replace it with. This approach minimizes the risk of accidental data loss and produces clean, reviewable diffs.

參數 類型 必填 描述
file_path string Absolute path to the file to edit
old_string string The exact text to find and replace
new_string string The replacement text
replace_all boolean Replace all occurrences (default: false)

A critical design decision: the edit fails if old_string is not unique within the file (unless replace_all is true). This forces the agent to provide enough surrounding context to unambiguously identify the edit location, preventing accidental modifications to the wrong part of a file.

13. NotebookEdit — Jupyter Cell Editing

The NotebookEdit tool handles Jupyter notebook cell editing. It supports four commands: replace (overwrite a cell's content), insert_above (add a new cell above a given index), insert_below (add a new cell below a given index), and delete (remove a cell). Each command takes a cell_type (code or markdown), an index identifying the target cell, and optional content.

搜尋與探索工具

The glob_search tool provides fast file pattern matching across the entire codebase. It accepts a pattern (e.g. **/*.ts, src/**/*.rs) and an optional path to restrict the search directory. Results are sorted by modification time and truncated at 100 files to prevent excessive output.

The grep_search tool is built on ripgrep and provides powerful regex content search across the codebase. It is one of the most frequently invoked claw code tools during code exploration and debugging.

參數 類型 必填 描述
pattern string Ripgrep regex pattern to search for
path string File or directory to search in
glob string Glob filter (e.g. "*.js", "**/*.tsx")
output_mode string content, files_with_matches (default), or count
-B integer Lines of context before each match
-A integer Lines of context after each match
-C integer Lines of context before and after each match
-n boolean Show line numbers (default: true)
-i boolean Case insensitive search
type string File type filter (js, py, rust, go, java, etc.)
head_limit integer Limit output to first N entries (default: 250)
offset integer Skip first N entries before applying head_limit
multiline boolean Enable multiline mode where . matches newlines

The three output modes serve different purposes: files_with_matches is fastest for locating which files contain a pattern, content shows the actual matching lines with optional context, and count provides match counts per file. The type parameter uses ripgrep's built-in file type definitions, which is more efficient than glob filtering for standard file types.

The ToolSearch tool searches for deferred tools that have not yet been fully loaded into the agent's context. It accepts a query string and an optional max_results parameter (default: 5). Query forms include exact selection (select:Read,Edit,Grep), keyword search, and name-required search (+slack send). When matched, full JSON schema definitions are returned so the discovered tools can be immediately invoked.

網頁互動工具

7. WebFetch — URL Content Retrieval

The WebFetch tool retrieves content from a URL and passes it to the agent with an accompanying prompt. This enables the agent to read documentation, check API responses, and gather information from the web during task execution. All URLs are subject to the permission system's network access rules.

The WebSearch tool performs web searches with optional domain filtering. The agent can restrict results to specific domains (e.g. searching only within documentation sites) to improve relevance. Results are returned as structured data that the agent can parse and act upon.

代理協作工具

11. Agent — Sub-Agent Launcher

The Agent tool launches sub-agents for parallel task execution. Sub-agents run in isolated contexts and can be configured with different models and capabilities.

參數 類型 必填 描述
description string Brief description (3-5 words) of the sub-agent's task
prompt string Detailed instructions for the sub-agent
subagent_type string Type of sub-agent to launch
name string Human-readable name for the sub-agent
model string Model selection: sonnet, opus, or haiku
run_in_background boolean Run the sub-agent in the background
isolation string Isolation mode, e.g. "worktree" for git worktree isolation

Sub-agents inherit the parent agent's permission context but run in their own conversation thread. The isolation: "worktree" option creates a separate git worktree, allowing the sub-agent to make file changes without interfering with the parent agent's working directory. This is essential for parallel development tasks where multiple agents modify files simultaneously.

10. Skill — Skill Definition Loader

The Skill tool loads predefined skill definitions that provide specialized domain knowledge and capabilities. It accepts a skill name and optional args. Skills are higher-level abstractions that compose multiple tool calls into structured workflows — for example, a "commit" skill that stages changes, drafts a commit message, and creates the commit in sequence.

任務與工作階段管理工具

9. TodoWrite — Task List Management

The TodoWrite tool manages the agent's internal task list. It accepts a todos array where each item has:

The agent uses this tool to track multi-step tasks, mark progress, and ensure nothing is missed during complex operations.

14. Sleep — Execution Pause

The Sleep tool pauses execution for a specified duration without holding a shell process. It accepts a single parameter: duration_ms (milliseconds). Unlike running sleep via the bash tool, this dedicated tool does not occupy a shell resource slot and is the preferred way to introduce delays when waiting for external processes.

15. SendUserMessage — User Communication

The SendUserMessage tool sends a message to the user with optional attachments. It accepts a message string, an attachments array, and a status field (normal or proactive). The proactive status indicates that the agent is providing unsolicited information, such as a progress update during a long-running task.

16. Config — Runtime Settings

The Config tool reads and writes agent configuration settings at runtime. It supports three fields: action (get or set), key (the setting name), and value (for set operations). This allows the agent to inspect its own configuration and make adjustments without requiring a restart.

17. StructuredOutput — JSON Data Return

The StructuredOutput tool returns structured JSON data to the caller. It accepts a single data parameter containing any valid JSON value. This is used when the agent needs to return machine-parseable results rather than natural language — for example, returning a list of found issues as a JSON array for downstream processing.

18. REPL — Language REPL Execution

The REPL tool executes code in a language-specific REPL environment. It accepts a language parameter (identifying the runtime) and a code parameter (the code to execute). Unlike the bash tool, the REPL maintains state between invocations within the same session, making it suitable for exploratory programming and iterative data analysis.

Python 工具層

The Python side of the claw code tools system, defined in src/tools.py, provides the orchestration layer that bridges the LLM's tool calls with the Rust execution engine.

ToolExecution 資料類別

Every tool invocation is tracked as a ToolExecution dataclass with the following fields:

關鍵函式

函式 用途
load_tool_snapshot() Reads the tool registry from reference_data/tools_snapshot.json. Cached with @lru_cache(maxsize=1) for efficient repeated access.
get_tools(simple_mode, include_mcp, permission_context) Returns the available tool set. In simple_mode, restricts to BashTool, FileReadTool, and FileEditTool only.
filter_tools_by_permission_context() Removes tools blocked by the current ToolPermissionContext.
execute_tool(name, payload) Shim execution that dispatches the tool call and returns a ToolExecution instance.
find_tools(query, limit=20) Substring search across tool names and source hints. Returns up to limit matching tools.
# Simplified tool execution flow (src/tools.py) def execute_tool(name: str, payload: dict) -> ToolExecution: execution = ToolExecution( name=name, source_hint=resolve_source(name), payload=payload, handled=False, message=None ) # Dispatch to Rust runtime for actual execution result = runtime.dispatch_tool(name, payload) execution.handled = True execution.message = result return execution

ToolPool 組裝

The ToolPool (defined in src/tool_pool.py) is the runtime container for all available tools in a given session. It determines exactly which claw code tools the agent can see and invoke.

ToolPool 資料類別

The ToolPool dataclass holds three fields: tools (the filtered list of available tools), simple_mode (boolean restricting to core tools), and include_mcp (boolean controlling whether MCP tools are included).

組裝流程

The assemble_tool_pool() function builds the final tool set through a filtering pipeline:

  1. Load all registered base tools from the snapshot
  2. If simple_mode, restrict to BashTool, FileReadTool, FileEditTool
  3. If include_mcp, add tools from connected MCP servers
  4. Apply ToolPermissionContext filtering to remove denied tools
  5. Render up to 15 tools in markdown format for the system prompt

On the Rust side, the equivalent structures are ToolManifestEntry (pairing a tool name with a ToolSource — either Base or Conditional) and ToolRegistry (a wrapper around Vec<ToolManifestEntry>). The manifest distinguishes between tools that are always available and tools that are conditionally loaded based on context (e.g. platform-specific tools like PowerShell).

// Rust-side tool manifest (rust/crates/tools/src/lib.rs) pub struct ToolManifestEntry { pub name: String, pub source: ToolSource, } pub enum ToolSource { Base, // Always available Conditional, // Loaded based on context } pub struct ToolRegistry(Vec<ToolManifestEntry>);

權限控制

Every tool invocation passes through the permission gating system before execution. This is the security boundary that prevents the agent from performing unauthorized actions.

Python-Side: ToolPermissionContext

The ToolPermissionContext contains two filtering mechanisms:

The blocks(tool_name) method checks the tool name against both lists: first an exact match against deny_names, then a prefix match against deny_prefixes. If either matches, the tool is blocked and will not appear in the agent's available tool set.

# Permission checking (src/tools.py) class ToolPermissionContext: deny_names: frozenset[str] deny_prefixes: tuple[str, ...] def blocks(self, tool_name: str) -> bool: if tool_name in self.deny_names: return True return any( tool_name.startswith(prefix) for prefix in self.deny_prefixes )

Rust-Side: PermissionPolicy

The Rust permission system is more granular, built around three concepts:

概念 類型 描述
PermissionMode enum Three modes: Allow (auto-approve), Deny (block), Prompt (ask user)
PermissionPolicy struct Contains a default_mode and a per-tool BTreeMap of mode overrides
Per-tool overrides BTreeMap Maps specific tool names to specific PermissionMode values, overriding the default

When a tool call arrives, the permission engine first checks the per-tool BTreeMap for an explicit override. If none exists, it falls back to the default_mode. Tools in Allow mode execute immediately. Tools in Deny mode return a denial message to the LLM. Tools in Prompt mode pause execution and ask the user for confirmation before proceeding.

權限配置

Permissions are configured through the three-tier settings system (~/.claude/settings.json, .claude/settings.json, .claude/settings.local.json). Project-level settings can restrict tool access for all collaborators, while user-level settings provide personal overrides. See the Configuration System documentation for details on the merge strategy.

ToolSpec Schema 模式

Every one of the 19 claw code tools follows the ToolSpec pattern: a struct containing a name (string identifier used in tool calls), a description (natural language explanation sent to the LLM as part of the system prompt), and an input_schema (JSON Schema defining the accepted parameters). This uniform pattern ensures consistency across all tools and simplifies the tool registration process.

// ToolSpec definition (rust/crates/tools/src/lib.rs) pub struct ToolSpec { pub name: String, pub description: String, pub input_schema: serde_json::Value, } // Example: registering the bash tool ToolSpec { name: "bash".into(), description: "Execute a shell command in a sandboxed environment".into(), input_schema: json!({ "type": "object", "required": ["command"], "properties": { "command": { "type": "string" }, "timeout": { "type": "integer", "maximum": 600000 }, "description": { "type": "string" }, "run_in_background": { "type": "boolean" }, "dangerously_disable_sandbox": { "type": "boolean" } } }), }

The input schema is a standard JSON Schema object. The required array lists mandatory parameters, while optional parameters are defined in properties without appearing in required. The Rust runtime validates all incoming tool inputs against these schemas before execution, rejecting malformed inputs with a descriptive error message that helps the LLM correct its call.

完整工具參考表

The following table summarizes all 19 claw code tools with their primary function and category:

# Tool 分類 描述
1bashShellExecute shell commands with sandbox, timeout, and background support
2read_fileFileRead files with offset/limit, supports PDFs, images, and notebooks
3write_fileFileCreate or overwrite files with structured_patch and git_diff output
4edit_fileFilePrecise string replacement with uniqueness validation
5glob_searchSearchFile pattern matching, sorted by modification time, truncates at 100
6grep_searchSearchRegex content search built on ripgrep with 13 parameters
7WebFetchWebFetch URL content with prompt
8WebSearchWebWeb search with domain filtering
9TodoWriteTaskTask list management with id, content, status, and priority
10SkillAgentLoad skill definitions for specialized workflows
11AgentAgentLaunch sub-agents with model selection and worktree isolation
12ToolSearchDiscoverySearch deferred tool definitions by query
13NotebookEditFileJupyter notebook cell editing (replace, insert, delete)
14SleepUtilityWait for duration_ms without holding a shell process
15SendUserMessageCommunicationMessage the user with attachments, normal or proactive status
16ConfigSettingsGet/set agent configuration via action, key, value
17StructuredOutputOutputReturn machine-parseable JSON data to caller
18REPLExecutionExecute code in a language REPL with persistent state
19PowerShellShellWindows PowerShell execution with sandbox (conditional)