Select and apply built-in tools (Read, Write, Edit, Bash, Grep, Glob) effectively
Learning objectives
By the end of this topic, you should be able to:
- Distinguish filename discovery, content search, reading, targeted edits and complete-file writes.
- Handle truncation, ambiguous edit anchors and changing file state.
- Trace a function through aliases and wrapper exports.
- Use command execution where needed without mistaking a working directory for a security boundary.
Search for paths and content separately
Use Glob when the question concerns filenames or extensions, such as finding **/*.test.tsx. Use Grep when the question concerns file contents, such as locating a function, import statement or exact error message. A filename match does not establish that the desired code exists inside the file.
For content search, choose the useful result form supported by the tool: matching filenames for navigation, matching lines for local inspection or counts for measuring the search result. Interpret regular-expression metacharacters correctly and use an appropriate literal-search option when searching literal text.
Scope the search to relevant directories and file types, then broaden it when evidence requires that. A failed query, denied path or offset beyond the returned page is not proof that the symbol is absent. Check the tool's actual status and pagination instead of turning every empty display into "no matches."
Inspect limits and coverage
A returned file list may be truncated. A reported total may be exact or only a lower bound, depending on the interface and its completeness metadata. Narrow the query, request additional pages or use a more relevant scope before claiming an exhaustive result.
Do not rely on a universal fixed file cap, ordering or ignore-file behavior. Confirm the active tool's behavior, including whether generated, ignored or hidden files are in scope. Read restrictions still apply to discovery and search; the ability to name a path does not imply permission to inspect it.
A small relevant result set helps preserve context. Reading the entire repository before identifying the entry point usually adds noise and can crowd out the evidence needed for the actual question.
Read before making a supported change
Read provides current content; use it to establish the relevant definition and surrounding context. Edit performs a targeted replacement using exact anchor text. Write creates or replaces complete file content.
For a small change, prefer a unique anchor with enough context to distinguish the intended occurrence. If the anchor appears several times, inspect those occurrences and refine it. Enabling replacement of every match is correct only when the requested change genuinely applies to every occurrence.
A full-file write is a fallback when a targeted edit is unsuitable, not an excuse to discard unseen content. Load the complete current file, preserve unrelated material and construct the complete replacement. A partial or truncated read cannot safely support a reconstruction that assumes the missing portion is irrelevant. Write is not append or merge: the source placeholder “Updated file content here...” would replace the target with that placeholder, not preserve the unprovided remainder. It is an illustration to complete, not a safe replacement payload. In this source Write interface, file_path is the absolute target and content is the complete intended string payload.
Recheck current state if another process may have changed the file. For important files, retain a permitted pre-change backup or an appropriate version-control baseline for the authorized recovery path, and validate the intended inputs before applying the replacement. After the write, inspect the actual diff and run the checks appropriate to the change. A successful tool call confirms an operation, not semantic correctness of the resulting program.
Use Bash for actual execution needs
A command tool is appropriate for work such as running a test suite, a compiler or an approved project command. Prefer a purpose-built read or edit tool where the environment provides one and its instructions require it. When it does not, use the available authorized mechanism with equivalent care. The supplied client prompt specifically favors Grep over shell content search and Glob over find/ls; its reported model deviations show that instruction preference is not enforced capability removal.
A shell is powerful: it can read, modify files, invoke network clients and launch other programs. Removing Write or Edit does not make an agent read-only if unrestricted shell access remains. Conversely, forbidding Bash alone does not prevent writes through other tools.
Set the intended working directory for execution, but enforce real path and operation permissions separately. A cwd setting guides relative paths; it is not a complete sandbox. Serialize dependent modifications or provide clear file ownership rather than assuming every write tool is automatically conflict-free.
Build understanding through a focused investigation
Begin with a likely entry point or a search for the reported symptom. Read the matching definition, follow imports and inspect relevant callers. Use each observation to choose the next file. Keep a small map of the paths, symbols and assumptions already checked.
Symbol-navigation tools can assist in typed or indexed projects, but they do not eliminate the need to inspect code and run the relevant compiler or tests. Text search also has limits: dynamic imports, generated code and runtime registration may require additional evidence beyond a simple string match.
Distinguish "searched these directories and file types" from "proved there are no other callers." Report unsearched areas when they matter to the conclusion.
Trace exported names through wrappers
A function may be imported under an alias, re-exported from a package entry point and renamed again by a consumer. Searching only its original name can miss the effective public interface.
Read the definition and exports first. Build a list of the original name, aliases and wrapper names, then search each relevant name. Follow results into the consumers and verify that the references refer to the same symbol rather than an unrelated identically named function. The source entry-point examples are src/**/index.ts and **/__init__.py. Its suggestion to exclude original definition directories can hide legitimate internal calls; inspect those candidates instead of automatically discarding a directory merely because it also contains the definition.
For example, app/policy.py defines retry_budget, app/__init__.py re-exports it as active_budget, and worker.py calls active_budget(). Searching only retry_budget can find the definition and export while missing the actual caller. Search the exported alias and inspect the caller before deciding the impact of a change.
Worked example: a unique edit without collateral changes
In this invented module, the approved request changes only the active retry budget from 2 to 3; the preview budget must remain 2. These functions return teaching values and do not execute any retries.
Before the change:
def retry_budget():
return 2
def preview_budget():
return 2
The anchor return 2 occurs twice. A replace-all operation would change both functions and violate the request. A suitable targeted anchor includes the retry_budget definition and its return statement. If the available edit mechanism still cannot select it reliably, read the complete module and write a verified replacement preserving the other function.
The supported result is:
def retry_budget():
return 3
def preview_budget():
return 2
The checks are concrete: the active function returns 3, the preview function returns 2, the wrapper still exports the active function, and the caller uses that same export. The diff must contain no unrelated change. A claim that the edit succeeded without examining the resulting content would leave the original ambiguity unresolved.
This example can be checked locally as pure Python. It does not demonstrate a live Claude Code edit, a complete project test or permission behavior in a particular release.
Interpret the source tool contracts precisely
The source Grep uses ripgrep regex rather than POSIX grep. To match literal interface{} the regex is interface\{\}; in an enclosing JSON string it becomes "interface\\{\\}". Keep regex escaping separate from the tool/JSON/shell encoding. Invalid syntax is an error to correct, not a negative search. The source says pre-v2.1.208 rejected patterns could misleadingly report No files found; use actual diagnostics/version evidence before declaring absence.
Its Grep modes are files_with_matches (default paths), content (matching lines) and count (full-set totals). head_limit and offset page entries; a page's returned size is not the full total. The snapshot adds totalFiles in v2.1.208 and totalLines in v2.1.210, and describes an older sliced-count bug. Missing total metadata is unknown, not zero. No entries at this offset can mean a past-end page of a query with matches; reset/narrow the supported query and retain invalid/denied outcomes separately. Specifically, in the source count mode numFiles counts files with matches and numMatches counts matches across the full searched result set. Those units differ from returned path/line slices and from one another; the source older pagination bug did not justify reporting a slice as that population.
The source Grep normally skips gitignored files; its Glob normally includes them unless launch configuration CLAUDE_CODE_GLOB_NO_IGNORE=false changes that behavior. These are client/configuration claims. An ignored or denied scope is a coverage limitation; changing visibility does not grant access.
In the source Glob interface, pattern defines the path expression and optional path selects the search directory; omitting path uses the current working directory. These supported-client defaults are not confinement or authority. For a stated teaching root containing a.test.tsx, src/a.test.tsx, src/deep/b.test.tsx, src/a.test.ts, config.json and nested/config.yaml, the source glob conventions give these distinctions:
| Pattern | Expected included examples | Expected excluded examples |
|---|---|---|
**/*.test.tsx |
root and nested .test.tsx paths |
src/a.test.ts, config.json |
src/*.test.tsx |
src/a.test.tsx |
src/deep/b.test.tsx, root a.test.tsx |
*.{json,yaml} |
root config.json |
nested/config.yaml, test files |
Check the actual glob dialect's zero-directory ** behavior before relying on the root-file case. Path matching selects names, not code content or every TypeScript test extension. For a separate expanded teaching tree containing main.js, src/nested/main.js, src/main.ts, src/deep/helper.ts and other.ts, **/*.js includes the two JavaScript paths and excludes the TypeScript paths. src/**/*.ts includes the two TypeScript paths under src and excludes other.ts and the JavaScript paths. These expected mappings assume the stated zero-directory ** convention and permitted root; they do not inspect file contents or prove all files were discovered. For a further stated header set containing api.h, include/detail.h and include/api.hpp, the source **/*.h example includes the two .h paths and excludes .hpp under the same zero-directory ** convention. This is expected name matching, not observed discovery or matching source content.
The source Glob snapshot sorts by modification time, caps the default returned list at 100 and, from v2.1.191, exposes totalMatches/countIsComplete. totalMatches and countIsComplete are optional; if absent, unreported total/completeness metadata is unknown and must not be invented or read as zero. Their absence alone does not make an otherwise completed valid search fail. A zero-match conclusion additionally needs actual successful complete coverage of the intended scope, not merely an empty page; unperformed, denied, rejected and truncated searches remain separate. numFiles and filenames describe the returned list; truncated marks its incompleteness. If countIsComplete:false, totalMatches is a lower bound, not an exact population. Modification order is not relevance or verified currentness. Null bytes in pattern/path produce a rejected-input diagnostic. Source v2.1.208 Read-deny coverage belongs to that policy implementation. Matching a tool name differs from granting preapproval: the source uses mcp__* as a tool-name pattern, while unanchored allow globs such as * or B* are skipped with a warning and do not automatically approve content. A broad-looking pattern is not permission. Its GlobOutput.durationMs is search-execution duration in milliseconds, distinct from returned-file count, total matches or end-to-end investigation time.
Track real reads and change permissions
The source Read takes an absolute file_path with supported line offset/limit. Returned line-number decorations are a view, not original file bytes. Default overflow can return PARTIAL view; an explicit oversized range may error before delivering the requested content. Track actual received ranges and read smaller necessary ranges until a complete replacement baseline exists. A requested read is not proof every line was delivered.
For the source first-50-line example, supply the actual absolute file_path and the supported limit=50 request. Track the actual starting range and lines received; requesting fifty lines does not establish that fifty lines or the full file were delivered. This is a source-shaped teaching request, not an executed read here.
In the source snapshot, Opus 4.6, Haiku 4.5 and older models always require a current-conversation read before editing or overwriting an existing file. Newer models may skip that read only when Read is available and reading would require no permission prompt. Notebooks and previously partial views still require a full read. Before v2.1.228, every model required the read before overwriting an existing file. These are interface acceptance rules; safe overwrite still needs current full evidence and preserved unrelated bytes.
In this source Edit interface, file_path is the absolute target, old_string is the exact current text and new_string is its intended replacement. Exact matching includes whitespace and indentation. The source has first-match shorthand alongside later uniqueness rejection; do not infer that an ambiguous replace_all:false safely chooses the intended occurrence. Inspect the supported contract, refine a unique anchor or use a justified complete replacement. replace_all:true is appropriate only when every actual occurrence is intended. The fields describe that source interface, not a tested universal request wrapper.
One complete illustrative source-shaped wrapper for the earlier module is {"tool_name":"Edit","parameters":{"file_path":"/example/module.py","old_string":"def retry_budget():\n return 2","new_string":"def retry_budget():\n return 3","replace_all":false}}. The absolute path is fictional; this object is neither an observed invocation nor a universally accepted built-in wrapper. Its expected complete resulting module is the earlier example with the active value 3 and preview value 2.
The source text_editor_20250728/str_replace_based_edit_tool listing is a versioned API interface, distinct from Claude Code built-in Read/Write/Edit. Its generated view request and partial message history implement no actual full-read, correlated tool-result or replacement loop. The source view fragment is {"command":"view","path":"primes.py"} inside a requested str_replace_based_edit_tool call; it includes no observed result or full replacement.
A separate Grep illustration is {"tool_name":"Grep","arguments":{"pattern":"function_name","path":"src/","mode":"content"}}. That wrapper/key choice is conceptual source notation, not proof the actual installed tool accepts that shape or enforces a sandbox.
The source Read/Write illustration instead uses tool_use.name and tool_use.arguments: {"tool_use":{"name":"Read","arguments":{"file_path":"/absolute/path/to/file.txt"}}} and {"tool_use":{"name":"Write","arguments":{"file_path":"/absolute/path/to/file.txt","content":"Updated file content here..."}}}. These are conceptual source wrappers, not executed calls or correlated results. Do not generalize the displayed arguments key to all Messages API tool_use blocks, MCP tools/call requests or runtime-host tool schemas; each actual interface needs its own supported contract. The Write placeholder is not a usable whole-file payload; the intended complete real content must replace it. None of these differing object shapes implements a validated execution/recovery loop by itself.
In the source client's acceptEdits account, Edit/Write and named common filesystem commands (mkdir, touch, mv, cp, sed) can be preapproved for paths within the working directory; other Bash commands still require their actual approval path. In plan mode, file edits are not automatically approved and trigger the supported canUseTool callback. These source-client conditions leave actual target authorization and available capabilities binding.
In the source v2.1.208 account, Read-deny covers Edit, Write and NotebookEdit on that path; Edit-deny alone does not cover Write or NotebookEdit. A fallback must preserve the effective denial rather than switch interfaces to evade it.
On Windows without Git Bash, the source client can leave Bash unregistered. Inspect actual available tools before depending on Bash-only hooks or fallbacks.
Read-only concurrency and sequential Edit/Write describe a supporting scheduler scope, not a global file lock. readOnlyHint is metadata requiring appropriate trust/enforcement. Finish dependent reads before overwrite, recheck relevant concurrent changes and inspect actual bytes afterward.
Preserve worker evidence and reporting boundaries
Availability, preapproval, path rights and cwd are separate. A read-tools array or denying Bash alone does not establish global read-only confinement while other mutation/network paths remain. A useful output contains symbol identities/aliases, source locations, checked callers, unresolved dynamic paths and actual searched scope. A report title such as THREAT_MODEL.md does not establish a threat finding. More concretely, the source doc-reviewer is limited to Read and Grep but its later Step4 calls Write for THREAT_MODEL.md; that writing must go through a separately authorized actor/path. Its partial client.query sketch lists allowed_tools=["Read","Grep","Glob"], disallowed_tools=["Bash"], cwd=str(TARGET_DIR) and a claude_code system-prompt preset with an unfinished append. This is an unexecuted SDK-shape sketch, not a complete validated signature or proof all write tools are removed. The source separate tools-field account says omission inherits available tools; actual availability, preapproval and target policy still need independent inspection.
The supplied domain material is the factual basis for these tool operations; the glossary supplies terminology. Broad structural wording about JSON does not override actual code relationships, evidence coverage or access policy, and a shaped report does not establish a finding.
Fresh-worker context and concise final summaries describe that invocation boundary; an explicit inherited fork has different input context. In the adopted D01 account, a fork captures the parent conversation history, system prompt, available tools and historical model configuration at creation, receives a separate session identity, and keeps its subsequent tool calls outside the parent conversation.
This separates conversational branches, not file edits. Use separate worktrees when independent concurrent edits require filesystem isolation, and retain actual tool/path permissions. The adopted Context Isolation term specifically means intermediate worker tool calls remain inside that worker and only its final message returns to the parent. This output-isolation definition alone does not establish what a fork inherits.
Parallel independent searches can shorten their search phase toward the slowest worker under the source's assumptions. An end-to-end comparison must separately count planning, dispatch, integration, validation, retries and other actual overhead. That accounting is a comparison requirement, not a measured whole-workflow saving supplied by the search-phase statement, and it establishes no total labor saving.
CLAUDE.md, path-scoped .claude/rules/ files and the source ENGAGEMENT_CONTEXT block guide scope. The source passes that block through system_prompt to every agent so the pipeline shares its documented ground rules. For hard limits, use supported PreToolUse hooks and actual capability/path enforcement; advisory text does not implement a denial. Its first 200 lines or 25KB auto-memory preload is a client-specific auto-memory account, not a rule for every instruction file or proof of complete startup knowledge. Here CLAUDE denotes the persistent CLAUDE.md instruction file for coding, architecture and preferences, rather than the model name.
Supported symbol/AST intelligence can resolve paths text search misses, subject to current indexing/language/version/transport support. The source's stdio AST example is one integration, not an assertion that all MCP must use stdio. Navigation results do not prove every dynamic caller or type error is known without relevant compilation/runtime checks. MCP expands to Model Context Protocol here; the name itself does not guarantee a supported AST client, complete current index or compilation coverage.
Summary
Use Glob for path patterns, Grep for content and Read for current evidence. Use Edit for a uniquely identified change and Write only with a complete replacement based on the current file. Trace aliases and integration points, inspect truncation and actual permissions, and verify the resulting diff rather than equating a completed tool call with a correct change.
