Anthropic officially releases Claude Code Best Practices

Anthropic releases Claude Code to improve AI programming efficiency and security.
Core content:
1. Design concept and functional features of Claude Code
2. Overview of common patterns and best practices
3. Guide to creating and using CLAUDE.md files
Below is the translation of the verification. Let’s see how to program AI better!
We recently released Claude Code, a command-line tool for agentic coding. Developed as a research project, Claude Code provides Anthropic engineers and researchers with a more native way to integrate Claude into their coding workflow.
Claude Code is intentionally designed to be low-level and unopinionated, providing access to close-to-the-raw models without forcing users to follow a specific workflow. This design philosophy creates a powerful tool that is flexible, customizable, scriptable, and secure. While powerful, this flexibility means that engineers who are new to agent programming tools need a certain learning curve—at least until they develop their own best practices.
This article outlines some common patterns that have proven effective both within Anthropic and for external engineers using Claude Code in a variety of codebases, languages, and environments. Nothing in this list is set in stone or universally applicable; please consider these suggestions as starting points. We encourage you to experiment and find what works best for you!
Want to learn more? Our comprehensive documentation at claude.ai/code covers all the features mentioned in this post and provides additional examples, implementation details, and advanced tips.
1. Customize your settings
Claude Code is an agent-based programming assistant that automatically pulls contextual information into prompts. This context gathering process consumes time and tokens, but you can optimize it by tweaking the environment.
a. Create CLAUDE.md file
CLAUDE.md
is a special file whose contents Claude automatically pulls into context when you start a conversation. This makes it an ideal place to record the following information:
Common bash commands Core files and utility functions Coding style guide Test Description Code repository specifications (for example, branch naming, whether to use merge or rebase, etc.) Developer environment setup (e.g., use of pyenv, which compilers are available) Any unexpected behavior or warnings specific to your project Any other information you would like Claude to remember
CLAUDE.md
There is no required format for the file. We recommend keeping it concise and human-readable. For example:
# Bash commands
- npm run build: Build the project
- npm run typecheck: Run the typechecker
# Code style
- Use ES modules (import/ export ) syntax, not CommonJS (require)
- Destructure imports when possible (eg. import { foo } from 'bar' )
# Workflow
- Be sure to typecheck when you're done making a series of code changes
- Prefer running single tests, and not the whole test suite, for performance
You can CLAUDE.md
The files are placed in the following locations:
The root directory of the repository , or you run claude
The directory for commands (most common usage). Name itCLAUDE.md
and commit it to git so that it can be shared between different sessions and team members (recommended), or namedCLAUDE.local.md
and add it to.gitignore
middle.run claude
Any parent directory of the command's directory . This is most useful for monorepo (a single codebase that manages multiple projects), which you mightroot/foo
Run in the directoryclaude
, and inroot/CLAUDE.md
androot/foo/CLAUDE.md
There areCLAUDE.md
Both files are automatically pulled into the context.run claude
This is the opposite of the above, in which case Claude will pull in files on demand when you process files in subdirectories .CLAUDE.md
document.Your home folder ( ~/.claude/CLAUDE.md
), which will apply to all yourclaude
Conversation.
When you run /init
command, Claude will automatically generate a CLAUDE.md
document.
b. Optimize your CLAUDE.md file
your CLAUDE.md
The files will become part of Claude's prompts, so they should be refined like any frequently used prompts. A common mistake is to add a lot of content without iterating to see how effective it is. Take the time to experiment and determine which content makes the model follow instructions best.
You can manually CLAUDE.md
Add content, or press #
key to give Claude a command, and it will automatically integrate the command into the relevant CLAUDE.md
Many engineers often use #
to document commands, files, and style guidelines, and then CLAUDE.md
The changes are included in the commit so that team members can also benefit.
At Anthropic, we occasionally use a prompt improver to handle CLAUDE.md
files, and often adjust instructions (for example, using "IMPORTANT" or "YOU MUST" for emphasis) to improve compliance.
Figure: Claude Code tool allow list setting interface
c. Manage Claude's list of allowed tools
By default, Claude Code asks for permission for any operation that might modify your system: file writing, many bash commands, MCP tools, etc. We intentionally took this conservative approach to designing Claude Code to prioritize security. You can customize the allow list to allow additional tools that you know are safe, or to allow potentially unsafe tools that are easily revoked (e.g., file editing,git commit
).
There are four ways to manage allowed tools:
Select "Always allow" when prompted in the session. After starting Claude Code, use /allowed-tools
command to add or remove tools from the allowed list. For example, you can addEdit
to always allow file editing,Bash(git commit:*)
to allow git commits, ormcp__puppeteer__puppeteer_navigate
to allow navigation using a Puppeteer MCP server.Manually edit your .claude/settings.json
or~/.claude.json
(We recommend checking the former into source control to share with your team).use --allowedTools
Command line flags to make session-specific permission settings.
d. If using GitHub, install the gh CLI
Claude knows how to use gh
The CLI interacts with GitHub to create issues, open pull requests, read comments, etc. If you don't have it installed gh
If you have the GitHub API or MCP server installed, Claude can still use them.
2. Give Claude more tools
Claude has access to your shell environment, where you can build a bunch of handy scripts and functions for it, just as you would for yourself. It can also leverage more sophisticated tools through MCP and the REST API.
a. Using Claude with bash tools
Claude Code inherits your bash environment, giving it access to all your tools. Although Claude knows common utilities such as unix tools and gh
, but without the directive it won't know about your custom bash tool:
Tell Claude the tool name and usage examples Tell Claude to run --help
To view the tool documentationexist CLAUDE.md
Commonly used tools are recorded in
b. Using Claude with MCP
Claude Code acts as both an MCP server and a client. As a client, it can connect to any number of MCP servers to access their tools in three ways:
In the project configuration (available when running Claude Code in that directory) In the global configuration (available in all projects) At check-in .mcp.json
files (available to anyone working in your codebase). For example, you can add Puppeteer and Sentry servers to your.mcp.json
so that every engineer working in your repository can use these tools out of the box.
When using MCP, use --mcp-debug
Starting Claude with flags can also help identify configuration problems.
c. Using custom slash commands
For repetitive workflows - debugging loops, log analysis, etc. - store prompt templates in .claude/commands
In the Markdown file in the folder. When you type /
, these templates will be available through the slash command menu. You can check these commands into git to make them available to other team members.
Custom slash commands can contain special keywords $ARGUMENTS
to pass arguments from the command call.
For example, here is a slash command that can be used to automatically pull and fix Github issues:
Please analyze and fix the GitHub issue: $ARGUMENTS .
Follow these steps:
1. Use `gh issue view` to get the issue details
2. Understand the problem described in the issue
3. Search the codebase for relevant files
4. Implement the necessary changes to fix the issue
5. Write and run tests to verify the fix
6. Ensure code passes linting and type checking
7. Create a descriptive commit message
8. Push and create a PR
Remember to use the GitHub CLI (`gh`) for all GitHub-related tasks.
Put the above content into .claude/commands/fix-github-issue.md
file, so that it appears in Claude Code as /project:fix-github-issue
command is available. Then you can use /project:fix-github-issue 1234
to let Claude fix issue #1234. Similarly, you can add your own personal commands to ~/.claude/commands
folder for use in all sessions.
3. Try common workflows
Claude Code does not impose a specific workflow, giving you the flexibility to use it your way. Within the space provided by this flexibility, several patterns for using Claude Code successfully and effectively have emerged in our user community:
a. Explore, plan, code, commit
This general workflow applies to many problems:
Tell Claude to read a file, image, or URL of interest . You can provide general instructions ("Read the file that handles logging") or a specific file name ("Read logging.py"), but explicitly tell it not to write any code yet. This is the part of the workflow where you should consider focusing on using subagents, especially for complex problems. Having Claude use subagents to verify details or investigate specific questions it may have, especially early in a conversation or task, can often keep context available without sacrificing too much efficiency. Ask Claude to develop a plan to solve a specific problem . We recommend using the word "think" to trigger extended thinking mode, which gives Claude extra computational time to more thoroughly evaluate alternatives. These specific phrases map directly to increasing levels of thinking budget in the system: "think" < "think hard" < "think harder" < "ultrathink". Each level allocates a progressively larger amount of thinking budget for Claude to use. If the results of this step look reasonable, you can have Claude create a document or a GitHub issue with its plans, so that if the implementation (step 3) doesn't meet your requirements, you can reset to this point. Have Claude implement his solution in code . This is also a good time to have him explicitly validate his solution as he implements each piece of it. Have Claude commit the results and create a pull request . If relevant, this is also a good time to have Claude update any README or changelog to explain what it just did.
Steps #1-#2 are critical - without them, Claude would tend to jump right into coding a solution. While sometimes that's what you want, requiring Claude to research and plan first can significantly improve performance for problems that require deeper upfront thinking.
b. Write tests, commit; code, iterate, commit
This is one of our favorite workflows at Anthropic, and is useful for changes that can be easily verified with unit tests, integration tests, or end-to-end tests. Test-driven development (TDD) becomes even more powerful with agent-based programming:
Let Claude write tests based on expected input/output pairs . Make it clear that you are doing test-driven development so that it avoids creating mock implementations, even for features that don't exist yet in the code base. Tell Claude to run the tests and confirm that they fail . It is often helpful to explicitly tell it not to write any implementation code at this stage. When you are satisfied with the test, have Claude submit the test . Have Claude write code that passes the tests , instructing him not to modify the tests. Tell Claude to continue until all tests pass. It usually takes several iterations for Claude to write code, run the tests, tweak the code, and then run the tests again. At this stage, it might be helpful to run a test on it using independent sub-agents to verify whether the implementation is overfitting. When you are happy with your changes, have Claude commit the code .
Claude works best when it has a clear goal to iterate on—a visual model, a test case, or some other type of output. By providing an expected output like a test, Claude can make changes, evaluate the results, and incrementally improve until it succeeds.
c. Write code, screenshot result, iterate
Similar to the testing workflow, you can provide Claude with a visual goal:
Give Claude a way to take screenshots of the browser screenshots (e.g., use a Puppeteer MCP server, an iOS simulator MCP server, or manually copy/paste the screenshots into Claude). **Give Claude a visual mock** by copying/pasting or dragging and dropping an image, or by providing an image file path.** Have Claude implement the design in code , take screenshots of the results, and iterate until his results match the model. When you are satisfied, have Claude commit .
Like humans, Claude's output will often improve significantly through iteration. While the first version may be good, after 2-3 iterations it will often look much better. Give Claude the tool to see its own output for the best results.
Figure: Using secure YOLO mode in an isolated container
d. Safe YOLO mode
Instead of supervising Claude, you can use claude --dangerously-skip-permissions
to bypass all permission checks and let Claude work uninterrupted until completion. This is very useful for workflows such as fixing lint errors or generating boilerplate code.
Warning: Allowing Claude to run arbitrary commands is risky and can lead to data loss, system corruption, or even data leakage (e.g., via prompt injection attacks). To minimize these risks, use Claude in a container without internet access. --dangerously-skip-permissions
You can follow this reference implementation using Docker Dev Containers.
e. Codebase Q&A
Use Claude Code to learn and explore when you're exposed to a new codebase. You can ask Claude questions just like you would ask other engineers on the project when pair programming. Claude can intelligently search the codebase to answer general questions, such as:
How does logging work? How do I create a new API endpoint? foo.rs file, line 134 async move { ... }
What does it do?CustomerOnboardingFlowImpl
What edge cases are handled?Why do we call foo()
Rather thanbar()
?baz.py
What is the Java equivalent of line 334 of the file?
At Anthropic, using Claude Code in this way has become our core onboarding workflow, significantly reducing the time to familiarize yourself with a project and reducing the burden on other engineers. No special prompts needed! Just ask questions and Claude will explore the code to find the answers.
Figure: Using Claude to write git commit messages
f. Using Claude to interact with git
Claude can handle many git operations efficiently. Many Anthropic engineers use Claude to handle more than 90% of git
Interaction:
search git
history to answer questions like “What changes did version v1.2.3 include?”, “Who was responsible for this particular feature?”, or “Why was this API designed this way?” It is helpful to explicitly prompt Claude to look in the git history to answer these kinds of queries.Write a commit message . Claude automatically looks at your changes and recent history to compose a message that takes into account all relevant context. Handle complex git operations such as reverting files, resolving rebase conflicts, and comparing and grafting patches.
g. Using Claude to interact with GitHub
Claude Code can manage many GitHub interactions:
Creating pull requests : Claude understands the shorthand "pr", and will generate an appropriate commit message based on the diff and surrounding context. Implement a one-click solution for simple code review comments : just tell it to fix the comment on your PR (optionally, give it more specific instructions), and push back to the PR branch when you're done. Fix failed builds or linter warnings. Categorize and triage open issues by having Claude traverse open GitHub issues.
This eliminates the need to remember gh
The need for command line syntax while automating routine tasks.
h. Using Claude to process Jupyter notebooks
Anthropic researchers and data scientists use Claude Code to read and write Jupyter notebooks. Claude can interpret output, including images, providing a fast way to explore and interact with data. There are no required tips or workflows, but one workflow we recommend is to open Claude Code side by side with a .ipynb
document.
You can also have Claude clean up or beautify your Jupyter notebook before showing it to a colleague. Explicitly telling it to make a notebook or its data visualizations “aesthetically pleasing” often helps remind it that it’s optimizing for a human viewing experience.
4. Optimize your workflow
The following recommendations apply to all workflows:
a. Be specific in your instructions
The success rate of Claude Code increases significantly with more specific instructions, especially on first attempts. Giving clear directions up front reduces the need for subsequent revisions.
For example:
Claude can infer intent, but it can't read your mind. Specificity allows for better alignment with expectations.
Figure: Providing images as context to Claude
b. Give Claude a picture
Claude works well with images and charts in a number of ways:
Paste the screenshot (Pro tip: in macOS press cmd+ctrl+shift+4 to capture to clipboard, then press ctrl+v to paste) Drag and drop the image directly into the prompt input box Provide the file path of the image
This is particularly useful when working with design mocks as reference points for UI development, and when using visual diagrams for analysis and debugging. Even if you don’t add visuals to the context, it’s still helpful to make clear to Claude the importance of the results being visually appealing.
Figure: Using tab completion to reference files
c. Mention the files you would like Claude to review or process
Use tab completion to quickly reference files or folders anywhere in the repository, helping Claude find or update the correct resource.
Figure: Providing URL as context to Claude
d. Give Claude the URL
Paste the specific URL next to your prompt to have Claude fetch and read it. To avoid repeated permission prompts for the same domain (e.g. docs.foo.com), use /allowed-tools
Add the domain name to your allow list.
e. Course correct early and often
While Auto Accept mode (toggle by pressing shift+tab) lets Claude work autonomously, you'll generally get better results by being an active collaborator and guiding Claude's approach. You can get the best results by explaining the task to Claude thoroughly at the beginning, but you can also correct Claude's direction at any time.
These four tools can help correct course:
Ask Claude to make a plan before coding . Tell it explicitly not to code until you've confirmed that its plan looks good. Pressing the Escape key at any stage (thinking, tool invocation, file editing) interrupts Claude while preserving the context so you can redirect or extend the instruction. Double-click the Escape key to jump back into history , edit previous prompts, and explore different directions. You can edit prompts and repeat until you get the result you want. Asking Claude to undo the changes is often used in conjunction with option #2 to take a different approach.
Although Claude Code can occasionally solve a problem perfectly on the first try, using these correction tools can often produce a better solution more quickly.
f. Use /clear to keep the context focused
During long sessions, Claude's context window can become filled with irrelevant conversations, file contents, and commands. This can degrade performance and sometimes distract Claude. Use the /clear
command to reset the context window.
g. Use checklists and scratchpads for complex workflows
For larger tasks that involve multiple steps or require exhaustive solutions — such as code migration, fixing a large number of lint errors, or running a complex build script — you can improve performance by having Claude use Markdown files (or even GitHub issues!) as checklists and working scratchpads:
For example, to fix a large number of lint issues, you could do:
Tells Claude to run the lint command and write any resulting errors (including filename and line number) to a Markdown listing. Instruct Claude to address each issue one by one , fixing and verifying before checking and moving on to the next issue.
h. Passing data to Claude
There are several ways to provide data to Claude:
Copy and paste directly into your prompt (the most common method) Pipe the input to Claude Code (e.g. cat foo.txt | claude
), especially useful for logs, CSV, and large dataTell Claude to pull data via bash commands, MCP tools, or custom slash commands Let Claude read a file or get a URL (also works for images)
Most sessions will involve a combination of these approaches. For example, you can pipe a log file into it and then tell Claude to use a tool to pull additional context for debugging the log.
5. Automate your infrastructure using headless mode
Claude Code includes a headless mode, suitable for non-interactive environments such as CI (continuous integration), pre-commit hooks, build scripts and automation. -p
Flag to enable headless mode, and use --output-format stream-json
to get streaming JSON output.
Note that headless mode does not persist between sessions. You have to trigger it in each session.
a. Use Claude for issue triage
Headless mode can drive automation triggered by GitHub events, such as when a new issue is created in your repository. For example, the public Claude Code repository uses Claude to check new incoming issues and assign appropriate labels.
b. Use Claude as a linter (code checker)
Claude Code can provide subjective code reviews that go beyond the issues detected by traditional linting tools, identifying issues such as spelling errors, outdated comments, and misleading function or variable names.
6. Improve efficiency through multi-Claude workflow
Besides standalone use, some of the most powerful applications involve running multiple Claude instances in parallel:
a. Let one Claude write the code; use another Claude to verify
A simple but effective approach is to have one Claude write the code while another reviews or tests it. Similar to working with multiple engineers, sometimes it is beneficial to have independent contexts:
Write code using Claude. run /clear
Or start a second Claude in another terminal.Have the second Claude review the work of the first Claude. Start another Claude (or again /clear
) to read the code and review the feedback.Let this Claude edit the code based on the feedback.
You can do something similar with tests: have one Claude write the tests, and then have another Claude write the code to make the tests pass. You can even have your Claude instances communicate by giving them separate scratchpads and telling them which one to write to and which one to read from.
This separation usually produces better results than having a single Claude handle everything.
b. Having multiple codebase checkouts
Rather than waiting for Claude to complete each step, many engineers at Anthropic do this:
Create 3-4 git checkouts in different folders . Open each folder in a different terminal tab . Start Claude in each folder and assign different tasks. Take turns to check progress and approve/deny permission requests.
c. Using git worktrees
This approach is particularly effective for multiple independent tasks, providing a more lightweight alternative to multiple checkouts. Git worktrees allow you to check out multiple branches of the same repository into different directories. Each worktree has its own independent working directory and files, while sharing the same Git history and reflog.
Using git worktrees enables you to run multiple Claude sessions on different parts of your project at the same time, with each session focusing on its own independent task. For example, you might have one Claude refactoring your authentication system while another builds a completely unrelated data visualization component. Since the tasks don't overlap, each Claude can work at full speed without having to wait for the other's changes or deal with merge conflicts:
Create worktrees : git worktree add ../project-feature-a feature-a
Start Claude in each worktree : cd ../project-feature-a && claude
Create additional worktrees as needed (repeat steps 1-2 in a new terminal tab)
Some tips:
Use consistent naming conventions. Maintain a terminal tab for each worktree. If you use iTerm2 on a Mac, set up notifications for when Claude needs attention. Use separate IDE windows for different worktrees. Clean up when you are done: git worktree remove ../project-feature-a
d. Using headless mode with a custom harness
claude -p
(Headless Mode) You can programmatically integrate Claude Code into a larger workflow while taking advantage of its built-in tools and system prompts. There are two main modes for using headless mode:
Fanning out large migrations or analyses (e.g. analyzing sentiment from hundreds of logs or analyzing thousands of CSVs):
Have Claude write a script to generate a list of tasks. For example, generate a list of 2000 files that need to be migrated from Framework A to Framework B. Loop through the tasks, calling Claude programmatically for each one, giving it a task and a set of tools it can use. For example: claude -p "Migrate foo.py from React to Vue. When finished, you must return the string OK if successful, or FAIL if the task failed." --allowedTools Edit Bash(git\ commit:*)
Run the script multiple times and refine your prompts to get the desired results. Pipelining: Integrate Claude into existing data/processing pipelines:
Call claude -p "<your prompt>" --json | your_command
,inyour_command
is the next step in your processing pipeline.That's it! JSON output (optional) can help provide structure for easier automated processing.
For both use cases, use --verbose
Flag to debug Claude calls. We generally recommend turning off verbose mode in production environments to get clearer output.