{
"$type": "site.standard.document",
"bskyPostRef": {
"cid": "bafyreibw5dxqyq2pqzmny6mtrutm7utlzo5lsqn62ffqzyba6fbgzhlqim",
"uri": "at://did:plc:polv2nnc3avny5kh7tlseen4/app.bsky.feed.post/3mnftlkltxk2g"
},
"canonicalUrl": "https://kylestratis.com/posts/a-better-practices-guide-to-using-claude-code/index",
"description": "A comprehensive guide to getting the most out of Claude Code",
"path": "/posts/a-better-practices-guide-to-using-claude-code/index",
"publishedAt": "2026-01-21T23:04:57.000Z",
"site": "at://did:plc:polv2nnc3avny5kh7tlseen4/site.standard.publication/3mnfsfprnsv2u",
"tags": [
"claude code",
"ai",
"vibe coding",
"assisted coding"
],
"textContent": "{{% disclosure %}}\n\n>[!NOTE] Note\n>This is adapted from an internal document I built for a team I'm working on part-time. If some later sections feel AI-y that's because I had Claude help fill them out. I normally don't do this for writing I intend on publishing, but this was supposed to be a quick internal guidance document that turned into this deep dive. Even the few parts that AI fleshed out from many bullet points are useful, however, and I hope this serves as a solid reference guide to the many ways you can harness the power of Claude Code.\n>And do yourself a favor: use Opus 4.5 (or later) by default.\n\nOverview\n\nThis document aims to teach some discovered “best” practices to get the most out of Claude Code. These practices and tools are changing rapidly, so expect this to go out of date at some point. I'll do my best to keep this updated.. This is pretty long, so I’d recommend reading from the Introduction section through the Prompting Best Practices one, getting set up, and then reading the overviews of all the following sessions. \n\nWhen you’re ready to incorporate the section into your workflow, read through the whole section and try out some of the workflows, techniques, or tools described.\n\nIntroduction\n\nClaude Code is a CLI LLM coding assistant built by Anthropic to speed up the development process for individual coders and teams. It can read your codebase, run shell commands, edit files, and iterate autonomously until a task is complete. \n\nIt is intentionally unopinionated and customizable. It won't stop you from making bad decisions. Used well, it dramatically accelerates development. Used poorly, it can waste tokens, introduce bugs, or make changes you didn't intend.\n\nBut What About Claude Desktop?\n\nClaude Code is extremely useful as an all-around agent and assistant, and for many it’s their primary way of interacting with Claude models, even outside of coding.\n\nBut Claude Code isn’t workable for all use cases. If you are doing research or even a simple search that requires lots of obscure context located in many different places and/or is information from after the training cutoff, Claude Desktop’s research mode is your ideal tool. The table below summarizes when to use which tool.\n\nWhen to Use What\n\n| Tool | Best For | Key Strength |\n| :---- | :---- | :---- |\n| Claude Code CLI | Coding tasks, file manipulation, automation | Direct filesystem/terminal access |\n| Claude Desktop | Research, writing, rich formatted output | Deep research mode, shareable artifacts |\n| VS Code Extension | Claude Code with tighter IDE integration | Side-panel chat, better diff review |\n| Claude Mobile | Quick questions on the go | Convenience |\n\nNote: Claude Code can also run from Claude Desktop/Mobile via cloud containers, letting you work on repos without cloning locally.\n\n{{< newsletter >}}\n\nGetting Started with Claude Code\n\nInstallation\n\n Requirements (Node 18+, supported OS) \n npm install -g @anthropic-ai/claude-code \n Verify: claude --version\n\nFirst Run\n\n Run claude from your project root (Claude Code uses your working directory as context) \n Sign in (browser OAuth flow) \n Model selection: Opus (powerful, expensive) vs Sonnet (fast, cheaper) \n Default behavior: Opus until 50% usage, then Sonnet \n Override with --model opus or --model sonnet\n\nUnderstanding Permissions\n\nClaude asks before modifying files or running potentially destructive commands. This is intentional.\n\nWays to reduce interruptions: \n\n| Method | Scope | Use When |\n| :---- | :---- | :---- |\n| \"Always allow\" at prompt | Current session | One-off trust |\n| /permissions command | Persistent | Managing allowlists interactively |\n| .claude/settings.json | Project | Team-wide project-based defaults (check into git) |\n| \\/.claude.json | User | Personal preferences across projects |\n\nCommon allowlist patterns:\n\n Edit — allow all file edits \n Bash(git commit:) — allow git commits \n Bash(npm test:) — allow test runs \n mcp__<server>__<tool> — allow specific MCP tools\n\nAvoid: --dangerously-skip-permissions outside of sandboxed environments.\n\nSettings\n\n Scope hierarchy: user (/.claude.json) → project (<PROJECT ROOT>/.claude/settings.json) \n Full reference: https://code.claude.com/docs/en/settings\n\n| Setting | Location | What It Does |\n| :---- | :---- | :---- |\n| model | CLI flag or settings | Default model (opus, sonnet, haiku) |\n| allowedTools | .claude/settings.json | Pre-approved tools/commands |\n| mcpServers | .claude/settings.json | MCP server configurations |\n| sandbox | .claude/settings.json | Enable container isolation |\n\nFull settings reference: https://code.claude.com/docs/en/settings\n\nTeam Tip: Check .claude/settings.json into version control to share permissions and MCP configs across your team.\n\nSandboxing (Recommended for Autonomous Work)\n\nRunning Claude Code in a container lets you safely enable auto-approve mode for long-running tasks.\n\n Use Docker or VS Code Dev Containers \n Once sandboxed, --dangerously-skip-permissions becomes safe \n Reference implementation: https://github.com/anthropics/claude-code/tree/main/.devcontainer \n Full guide: https://code.claude.com/docs/en/sandboxing\n\nRecommended Tooling\n\n gh CLI — enables Claude to create PRs, manage issues, search git history \n Install: brew install gh / apt install gh \n Authenticate gh auth login \n No additional configuration required \n Optional: Run /install-github-app to enable automatic PR reviews via @claude mentions. This installs a GitHub App on your repo that triggers Claude to review PRs when you mention @claude in the PR.\n\n{{< hire >}}\n\nWorkflow Patterns\n\nThe PM Mindset\n\nThe biggest mistake new users make is typing a task and expecting perfect output.\n\nClaude Code works best when you treat it like a capable but context-blind junior developer. You're the PM. Your job is to:\n\n Provide context before asking for work \n Break down ambiguous tasks into verifiable steps \n Review output before approving changes \n Course correct early rather than letting Claude go down wrong paths\n\nA well-scoped task with clear success criteria will save you more time than a vague prompt that requires three do-overs.\n\nCore Workflow: Explore → Plan → Code → Commit\n\nThis is the canonical pattern for most non-trivial tasks.\n\nPhase 1: Explore and Plan (Plan Mode)\n\nEnter Plan Mode to prevent Claude from making changes while it researches.\n\n| Action | Method |\n| :---- | :---- |\n| Toggle Plan Mode | Shift+Tab or /plan |\n| Visual indicator | You'll see \"Plan Mode\" in the interface |\n\nIn Plan Mode, Claude:\n\n Reads files and explores the codebase \n Uses the built-in Plan subagent for research \n Proposes approaches and identifies edge cases \n Cannot edit files or run mutating commands\n\nExample session:\n\nWhy write the plan to a file? If implementation goes wrong, you can /clear, reload the plan file, and try again without re-doing the research phase.\n\nPhase 2: Implement (Exit Plan Mode)\n\nOnce the plan looks right, toggle back to normal mode.\n\nNow Claude can edit files and run commands. The plan file serves as the spec.\n\nPhase 3: Commit and Close\n\nIf you have gh installed, Claude handles the full PR flow.\n\nQuick Reference\n\n| Phase | Mode | Claude Can | Prompt Pattern |\n| :---- | :---- | :---- | :---- |\n| Explore | Plan Mode | Read, search, reason | \"Explore X. Don't write code yet.\" |\n| Plan | Plan Mode | Propose, document | \"Think hard. Write plan to file.\" |\n| Implement | Normal | Edit, run, test | \"Implement step by step. Verify each step.\" |\n| Commit | Normal | Git operations | \"Commit and create PR.\" |\n\nVariant: TDD Loop\n\nFor changes with clear correctness criteria, let tests drive the iteration.\n\n1. Write tests first: \"Write tests for the new rate limiter. Cover the happy path and the edge case where the user exceeds the limit. Don't implement the feature yet.\" \n2. Confirm tests fail: \"Run the tests and confirm they fail.\" \n3. Implement: \"Now implement the rate limiter to pass the tests. Don't modify the tests.\" \n4. Iterate: Claude runs tests, fixes failures, repeats until green. \n5. Commit: \"Commit the implementation.\"\n\nThis works because Claude has a clear target to iterate against. The tests are the spec.\n\nVariant: Visual Iteration (Frontend)\n\nFor UI work, give Claude a visual target.\n\n1. Provide a mock: Paste a screenshot, drag-drop an image, or give a file path \n2. Implement: \"Build this component to match the mock.\" \n3. Screenshot result: Use Puppeteer MCP or paste a screenshot manually \n4. Compare and iterate: \"Here's what it looks like now. Adjust to match the original more closely.\" \n5. Repeat until satisfied\n\nClaude's first attempt is usually 70% there. Two or three iterations get you to 95%.\n\nTechnique: Codebase Q\\&A\n\nUse Claude Code to learn unfamiliar codebases. No special prompting is required, just ask questions:\n\n \"How does logging work in this project?\" \n \"What's the data flow from API request to database write?\" \n \"Why does CustomerService extend BaseService instead of implementing an interface?\" \n \"Find all the places where we handle auth token refresh.\"\n\nThis replaces hours of grep and documentation diving. It's particularly useful for onboarding new team members.\n\nTechnique: Git and GitHub Operations\n\nClaude with gh installed can handle most git workflows:\n\n| Task | Example Prompt |\n| :---- | :---- |\n| Search history | \"Who last modified the payment module and why?\" |\n| Write commits | \"Commit these changes with a descriptive message\" |\n| Create PRs | \"Create a PR for this branch with a summary of changes\" |\n| Resolve conflicts | \"Help me resolve this merge conflict\" |\n| Review PRs | \"Review the open PR and summarize the changes\" |\n\nTip: Explicitly prompt Claude to check git history when asking \"why\" questions. \"Look through git history to understand why this API was designed this way.\"\n\nPrompting Best Practices\n\nThe Core Principle: Encode Intent Upfront\n\nThe biggest prompting mistake isn't poor phrasing — it's correcting Claude after it writes bad code instead of preventing bad code in the first place.\n\nClaude has no knowledge of your team's conventions, architectural decisions, or hard-won lessons. By default, it generates whatever patterns it saw most often in training data. The fix: encode your standards into CLAUDE.md or Skills so every prompt starts with your context.\n\nExample: Dagster's team codified their Python philosophy into rules they load into every Claude session. Instead of reviewing and rewriting LLM output, they get code that matches their standards on the first pass. See: Dignified Python: 10 Rules to Improve Your LLM Agents\n\nWhat belongs in your team's rules (see the CLAUDE.md section for an example CLAUDE.md file):\n\n Language idioms (e.g., \"prefer LBYL over EAFP,\" \"never swallow exceptions\") \n Architectural patterns (e.g., \"use repository pattern for data access\") \n Naming conventions (e.g., \"use snake\\_case, prefix private methods with \\_\") \n Testing philosophy (e.g., \"no mocks for unit tests,\" \"integration tests hit real DB\") \n Error handling (e.g., \"let exceptions bubble up unless at an API boundary\")\n\nSpecificity: Vague vs. Precise Prompts\n\nClaude can infer intent, but it can't read minds. Specific prompts reduce iterations.\n\n| Vague | Precise |\n| :---- | :---- |\n| \"Add tests for foo.py\" | \"Write a test case for foo.py covering the edge case where the user is logged out. Don't use mocks.\" |\n| \"Why is this API weird?\" | \"Look through git history to find when ExecutionFactory was introduced and summarize why its API evolved this way.\" |\n| \"Add a calendar widget\" | \"Look at HotDogWidget.php to understand our widget patterns. Build a calendar widget that lets users select a month and paginate years. No external libraries beyond what we already use.\" |\n\nPatterns that improve specificity:\n\n Name the files, functions, or modules involved \n State what not to do (no mocks, don't modify tests, don't use library X) \n Reference existing code as a pattern to follow \n Define the success criteria explicitly\n\nThinking Triggers\n\nUse these phrases to allocate more reasoning time during planning:\n\n| Phrase | Budget | Use When |\n| :---- | :---- | :---- |\n| think | Standard | Default exploration |\n| think hard | Extended | Multiple valid approaches |\n| think harder | More extended | Complex tradeoffs, edge cases |\n| ultrathink | Maximum | Architecture decisions, subtle bugs |\n\nThese are mapped to actual token allocations in Claude Code, not just suggestions.\n\nExample:\n\nProviding Context\n\nClaude works better with more context. Use these methods:\n\n| Method | How | Best For |\n| :-------------- | :-------------------------------------- | :------------------------------------ |\n| File references | Tab-complete paths in prompt | Pointing to specific code |\n| Images | Paste (Ctrl+V), drag-drop, or file path | UI mocks, diagrams, error screenshots |\n| URLs | Include URL in prompt | Documentation, Stack Overflow, specs |\n| Piped data | cat log.txt \\| claude | Logs, CSVs, large text files |\n| @ mentions | @filename.py | Quick file references |\n\nTip: On macOS, Cmd+Ctrl+Shift+4 screenshots to clipboard, then Ctrl+V (not Cmd+V) to paste into Claude Code.\n\nCourse Correction\n\nDon't wait for Claude to finish if it's heading the wrong direction.\n\n| Action | Shortcut | When to Use |\n| :------------ | :---------------------- | :---------------------------------------- |\n| Interrupt | Escape | Claude is going off-track |\n| Rewind | Escape twice | Try a different approach from earlier |\n| Reset context | /clear | Starting a new task; old context is noise |\n| Checkpoint | \"Write this to PLAN.md\" | Before risky implementation work |\n\nThe /clear habit: Use it liberally between tasks. Accumulated context from previous work can confuse Claude and waste tokens.\n\nChecklists for Complex Tasks\n\nFor large tasks (migrations, bulk refactors), have Claude maintain external state:\n\nThis prevents drift, gives you visibility, and lets Claude track progress across a long session.\n\nOutput Styles\n\nYou can set output styles with /output-style, these are the available styles currently:\n\n Default - Focused on efficiency and short responses. \n Explanatory - Explains choices Claude takes and patterns in the codebase. This is a good default to balance speed and understanding. \n Learning - A more pedagogical approach where Claude will ask you to write some code for practice. Useful to learn patterns in a codebase or a new language.\n\nAnti-Patterns to Avoid\n\n| Anti-Pattern | Why It Fails | Instead |\n| :---- | :---- | :---- |\n| \"Make it better\" | No success criteria | \"Reduce latency by caching X\" |\n| Multi-part prompts | Claude loses track | One task per prompt, then follow-up |\n| Assuming context | Claude doesn't know your codebase | Reference files explicitly |\n| Correcting after | Slower than preventing | Encode standards in CLAUDE.md |\n| Never interrupting | Wasted tokens, wrong direction | Escape early, redirect |\n\nMemory with CLAUDE.md\n\nCLAUDE.md is a special file that Claude automatically loads into context at the start of every session. Think of it as onboarding documentation for Claude, it holds the things a new team member would need to know to contribute effectively.\n\nUnlike Skills (which are invoked on-demand) or subagents (which run in isolated contexts), CLAUDE.md is always present. This makes it ideal for:\n\n Project-wide conventions that apply to every task \n Commands Claude should know how to run \n Gotchas and warnings specific to your codebase \n Style guidelines and architectural decisions\n\nWhere It Lives\n\nClaude Code looks for CLAUDE.md files in multiple locations, loading them in order of specificity:\n\n| Location | Scope | Use For |\n| :---- | :---- | :---- |\n| /.claude/CLAUDE.md | All sessions | Personal preferences, global shortcuts |\n| Project root /CLAUDE.md | This project | Team conventions, shared with git |\n| Parent directories | Monorepo | Shared config across subprojects |\n| Child directories | Submodules | Module-specific overrides |\n| CLAUDE.local.md | Personal, not committed | Your preferences for this project |\n\nResolution order: Global → parent → project root → child directories. More specific files add to (not replace) broader ones.\n\nTip for monorepos: Put shared conventions in root/CLAUDE.md and module-specific instructions in root/packages/foo/CLAUDE.md. Claude loads both when you run from root/packages/foo/.\n\nGetting Started: /init\n\nThe fastest way to create a CLAUDE.md is to let Claude generate one:\n\nClaude will analyze your project structure, detect frameworks and tools, and generate a starter CLAUDE.md. Review and edit the result — it's a starting point, not gospel.\n\nWhat to Include\n\nA good CLAUDE.md is concise and actionable. Aim for instructions Claude can follow, not documentation for humans.\n\nRecommended sections:\n\nKeep it short. If your CLAUDE.md exceeds \\100 lines, consider moving detailed reference material to Skills to take advantage of progressive disclosure.\n\nTuning Your CLAUDE.md\n\nCLAUDE.md is just a prompt. Treat it like one.\n\nTechniques that improve adherence:\n\n Use emphasis for critical rules: IMPORTANT: or YOU MUST \n Be specific: \"Use snake\\_case\" not \"Follow naming conventions\" \n Include examples of correct patterns \n Run it through Anthropic's prompt improver periodically\n\nIterate based on results. If Claude keeps making the same mistake, add a rule. If a rule isn't being followed, rephrase it with more emphasis or examples.\n\nAdding Instructions During Sessions\n\nPress # during any session to add an instruction to CLAUDE.md without leaving the conversation:\n\nClaude will add this to the appropriate CLAUDE.md file. This is useful for capturing lessons as you discover them.\n\nTeam Sharing and Governance\n\nPersonal CLAUDE.md (/.claude/CLAUDE.md): Configure however you like. Your shortcuts, your preferences.\n\nProject CLAUDE.md: Treat like code.\n\n| Practice | Why |\n| :---- | :---- |\n| Check into git | Everyone gets the same Claude behavior |\n| Require code review for changes | Conventions affect the whole team |\n| Keep a CLAUDE.local.md for personal overrides | Don't pollute shared config with individual preferences |\n| Document why, not just what | Future teammates need context |\n\nSuggested workflow:\n\n1. Start with /init to generate a baseline \n2. Review as a team; merge to main \n3. Add rules incrementally via # or PRs \n4. Periodically audit: are rules being followed? Are any obsolete?\n\n> [!WARNING] Anti-Pattern Example\nA 500-line CLAUDE.md that nobody maintains is a common anti-pattern. Start small, iterate based on actual problems.\n\nStarter Template\n\nCopy this as a starting point for new projects:\n\nCLAUDE.md vs. Skills vs. Subagents\n\n| Mechanism | Loaded | Scope | Use For |\n| :---- | :---- | :---- | :---- |\n| CLAUDE.md | Always | Every task | Universal project conventions |\n| Skills | On-demand | Matching tasks | Specialized workflows (PDF, testing, etc.) |\n| Subagents | When invoked | Isolated context | Delegated subtasks (review, research) |\n\nIf you find yourself adding task-specific instructions to CLAUDE.md, consider creating a Skill instead.\n\nImporting Other Files\n\nFor larger projects, you can split conventions across multiple files and import them into CLAUDE.md:\n\nHow it works:\n\n Add @path/to/file.md on its own line \n Claude loads the referenced file into context at session start \n Paths are relative to the CLAUDE.md file's location\n\nWhen to use imports:\n\n| Scenario | Approach |\n| :---- | :---- |\n| Small project (\\<100 lines of conventions) | Single CLAUDE.md |\n| Large monorepo with shared \\+ module-specific rules | Root CLAUDE.md imports shared files; module CLAUDE.md files import module-specific |\n| Team with existing style guides | Import existing docs rather than duplicating |\n| Conventions that change frequently | Separate file \\= smaller PR diffs |\n\nExample structure for a monorepo:\n\nRoot CLAUDE.md:\n\npackages/api/CLAUDE.md:\n\n>[!TIP] Tip\nImported files don't need YAML frontmatter — they're just markdown that gets concatenated into context. Keep them focused on instructions, not documentation.\n\nCustom Slash Commands\n\nSlash commands are reusable prompt templates stored as markdown files. When you type / in Claude Code, your custom commands appear alongside built-in ones.\n\nUse slash commands for:\n\n Repeated workflows you run frequently (debug loops, PR creation, code review) \n Team-standardized processes (everyone runs the same deployment checklist) \n Complex prompts you don't want to retype (multi-step tasks with specific instructions)\n\nThink of them as saved prompts with optional parameters.\n\nWhere They Live\n\n| Location | Scope | Invoked As |\n| :---- | :---- | :---- |\n| .claude/commands/ | Project (check into git) | /project:command-name |\n| /.claude/commands/ | Personal (all projects) | /user:command-name |\n\nFile naming: The filename becomes the command name. fix-issue.md becomes /project:fix-issue.\n\nBasic Structure\n\nA slash command is a markdown file with optional YAML frontmatter:\n\nThe description field is optional but recommended — it helps you (and teammates) understand what the command does when browsing the / menu.\n\nParameterization with $ARGUMENTS\n\nUse $ARGUMENTS to pass values from the command invocation into your template:\n\nFile: .claude/commands/fix-issue.md\n\nInvocation:\n\nClaude sees the fully substituted prompt with 1234 replacing $ARGUMENTS.\n\nUser vs. Project Commands\n\n| Aspect | User Commands | Project Commands |\n| :---- | :---- | :---- |\n| Location | /.claude/commands/ | .claude/commands/ |\n| Shared with team | No | Yes (via git) |\n| Prefix | /user: | /project: |\n| Use for | Personal shortcuts | Team workflows |\n\nRecommendation: Start with project commands. They're version-controlled, reviewed, and shared. Use user commands only for personal preferences that wouldn't benefit the team.\n\nExamples\n\nGitHub Issue Fixer\n\n.claude/commands/fix-issue.md\n\nQuick Code Review\n\n.claude/commands/review.md\n\nTest Coverage Check\n\n.claude/commands/coverage.md\n\nStart of Day\n\n/.claude/commands/standup.md (user command)\n\n---\n\nSlash Commands vs. Skills\n\n| Aspect | Slash Commands | Skills |\n| :---- | :---- | :---- |\n| Invocation | Explicit (/project:name) | Automatic (Claude matches based on task) |\n| Structure | Single markdown file | Directory with SKILL.md \\+ supporting files |\n| Parameters | $ARGUMENTS | None (context comes from the task) |\n| Use for | Explicit, repeatable workflows | Domain expertise Claude applies automatically |\n\n>[!TIP] Rule of Thumb\nIf you want Claude to always apply certain knowledge when relevant, use a Skill. If you want to explicitly trigger a specific workflow, use a slash command.\n\nOrchestrating Subagents from Commands\n\nSlash commands can explicitly invoke subagents, combining repeatable workflows with specialized expertise:\n\nFile: .claude/commands/review-and-fix.md\n\nThis pattern lets you:\n\n Define the workflow in the slash command \n Delegate expertise to purpose-built subagents \n Keep the main context clean (subagents run in isolated contexts)\n\nSee the Subagents section for how to create and configure subagents.\n\nTips\n\n Keep commands focused. One workflow per command. Chain commands manually if needed. \n Use $ARGUMENTS liberally. Commands without parameters are just saved prompts, meaning they’re less flexible. \n Include escape hatches. Add \"If X isn't clear, ask me before proceeding\" to avoid runaway automation. \n Version control project commands. Treat them like code: review changes, document purpose.\n\nAgent Skills\n\n> [!TIP] Read Also\n> My personal experience working with Agent Skills here.\n\nWhat They Are\n\nSkills are folders containing instructions, scripts, and resources that Claude loads dynamically when relevant to your task. Unlike CLAUDE.md (always loaded) or slash commands (explicitly invoked), Skills are automatically activated when Claude determines they're relevant based on the task.\n\nThink of Skills as onboarding guides for specialized tasks: everything Claude needs to know to handle a specific domain well.\n\nWhere They Live\n\n| Location | Scope |\n| :---- | :---- |\n| .claude/skills/ | Project (check into git) |\n| /.claude/skills/ | Personal (all projects) |\n\nEach Skill is a directory containing at minimum a SKILL.md file:\n\nHow Skills Are Loaded (Progressive Disclosure)\n\nSkills use a three-tier loading system to conserve context:\n\n| Tier | What Loads | When |\n| :---- | :---- | :---- |\n| Metadata | name and description from frontmatter | Session start (all skills) |\n| Instructions | Body of SKILL.md | When Claude matches the skill to your task |\n| Supporting files | Other .md files, scripts | When Claude determines they're needed |\n\nThis means you can install many Skills without context penalty — Claude only knows each exists until it needs one.\n\nImplication for authoring: Put essential instructions in SKILL.md. Put detailed reference material in separate files that Claude reads only when needed.\n\nSKILL.md Structure\n\nFrontmatter fields:\n\n| Field | Required | Description |\n| :---- | :---- | :---- |\n| name | Yes | Identifier for the skill |\n| description | Yes | How Claude decides to use this skill — be specific |\n| allowed-tools | No | Restrict which tools the skill can use |\n| context | No | Set to fork to run in isolated subagent context |\n\n---\n\nWriting Good Descriptions\n\nThe description field determines whether Claude activates your Skill. Vague descriptions won't match; specific ones will.\n\n| Bad | Good |\n| :---- | :---- |\n| \"Helps with documents\" | \"Extract text and tables from PDF files, fill forms, merge documents. Use when working with PDFs or when user mentions forms or document extraction.\" |\n| \"Testing utilities\" | \"Write and debug Playwright end-to-end tests. Use when creating browser tests, debugging selectors, or handling authentication flows in E2E tests.\" |\n\nInclude in your description:\n\n Specific actions the skill enables \n Trigger words users would say \n File types or technologies involved\n\nPre-Built Skills\n\nAnthropic provides Skills for common document tasks, available to all paid plans:\n\n| Skill | What It Does |\n| :---- | :---- |\n| PDF | Extract text/tables, fill forms, merge/split documents |\n| DOCX | Create and edit Word documents with formatting |\n| PPTX | Create presentations with layouts and speaker notes |\n| XLSX | Create spreadsheets with formulas, charts, data analysis |\n\nThese are automatically available — no installation needed. Claude invokes them when you work with these file types.\n\nCreating Custom Skills\n\nOption 1: Use the skill-creator skill\n\nClaude will interactively ask about your workflow, then generate the folder structure and SKILL.md.\n\nOption 2: Create manually\n\n1. Create the directory:\n\n2. Create SKILL.md with frontmatter:\n\n3. (Optional) Add supporting files for detailed reference material\n\nTip: Keep SKILL.md under 500 lines. If you exceed this, split detailed content into separate files and link to them.\n\nSkills with Executable Scripts\n\nSkills can include scripts that Claude runs as tools:\n\nIn your SKILL.md:\n\nClaude will execute these scripts when appropriate, using the output to inform its work.\n\nSkills vs. CLAUDE.md vs. Slash Commands\n\n| Aspect | CLAUDE.md | Slash Commands | Skills |\n| :---- | :---- | :---- | :---- |\n| Loaded | Always | When invoked (/command) | When Claude matches task |\n| Invocation | Automatic | Explicit | Automatic |\n| Structure | Single file | Single file | Directory with files |\n| Parameters | None | $ARGUMENTS | None (context from task) |\n| Best for | Universal project conventions | Explicit, repeatable workflows | Domain expertise applied automatically |\n| Example | \"Use snake\\_case everywhere\" | /fix-issue 1234 | \"PDF form filling\" |\n\nDecision guide:\n\n Rules that apply to every task → CLAUDE.md \n Workflows you trigger explicitly → Slash Command \n Expertise Claude should apply when relevant → Skill\n\nTips\n\n Start with pre-built skills. See how Anthropic structures them before creating your own. \n Be specific in descriptions. Claude can't use a skill it doesn't know to match. \n Use progressive disclosure. Don't put everything in SKILL.md — link to supporting files. \n Test activation. Ask Claude \"what skills are available?\" and try tasks that should trigger your skill. \n Version control project skills. They're code: review and iterate.\n\nSubagents\n\nSubagents are specialized Claude instances that run in isolated context windows. When Claude delegates to a subagent, the subagent works independently and returns only its findings — not its full context — to the main conversation.\n\nWhy this matters:\n\n Context isolation: Subagent exploration doesn't bloat your main conversation \n Specialization: Each subagent has tailored instructions for its domain \n Tool restrictions: Subagents can be limited to read-only operations or specific tools \n Model flexibility: Use cheaper models (Haiku) for simple tasks, powerful models (Opus) for complex ones\n\nThink of subagents as specialists you call in for specific jobs. The generalist (main Claude) coordinates while the specialists execute.\n\nWhere They Live\n\n| Location | Scope |\n| :---- | :---- |\n| .claude/agents/ | Project (check into git) |\n| /.claude/agents/ | Personal (all projects) |\n\nEach subagent is a single markdown file:\n\nBuilt-In Subagents\n\nClaude Code includes two subagents you don't need to create:\n\nPlan Subagent\n\nUsed automatically in Plan Mode (Shift+Tab or /plan).\n\n Purpose: Research and gather context before proposing a plan \n Behavior: Explores codebase, reads files, analyzes patterns \n Restrictions: Cannot edit files or run mutating commands \n Why it exists: Prevents infinite nesting (subagents can't spawn subagents)\n\nWhen you're in Plan Mode and ask Claude to understand something, it delegates research to the Plan subagent, keeping your main context clean.\n\nExplore Subagent\n\nA fast, lightweight agent for codebase searches.\n\n Purpose: Rapid file discovery and code analysis \n Tools: Read-only only — ls, cat, find, git log, git diff, grep \n Thoroughness levels: Claude specifies quick, standard, or thorough based on the task\n\nClaude uses Explore when it needs to search or understand code but doesn't need to make changes.\n\nCreating Custom Subagents\n\nOption 1: Interactive creation with /agents\n\nThis opens an interactive interface where you can:\n\n View existing subagents \n Create new subagents with Claude's help \n Edit subagent configuration \n See all available tools (including MCP tools) for the tools field\n\nOption 2: Create manually\n\nCreate a markdown file in .claude/agents/ with this structure:\n\nFrontmatter Configuration\n\n| Field | Required | Default | Description |\n| :---- | :---- | :---- | :---- |\n| name | Yes | — | Identifier for the subagent |\n| description | Yes | — | When Claude should use this subagent |\n| tools | No | Inherit all | Comma-separated list of allowed tools |\n| model | No | sonnet | opus, sonnet, haiku, or inherit |\n| permissionMode | No | default | Permission handling for the subagent |\n| skills | No | None | Skills to auto-load for this subagent |\n| hooks | No | None | Lifecycle hooks (PreToolUse, PostToolUse, Stop) |\n\nModel Selection\n\n| Value | When to Use |\n| :---- | :---- |\n| opus | Complex analysis, architectural decisions |\n| sonnet | General-purpose tasks (default) |\n| haiku | Simple, fast tasks (linting, formatting checks) |\n| inherit | Match the main conversation's model |\n\nTool Restrictions\n\nRestrict tools based on the subagent's purpose:\n\n| Subagent Type | Recommended Tools |\n| :---- | :---- |\n| Reviewers, auditors | Read, Grep, Glob (read-only) |\n| Researchers | Read, Grep, Glob, WebFetch, WebSearch |\n| Code writers | Read, Write, Edit, Bash, Glob, Grep |\n| Documentation | Read, Write, Edit, Glob, Grep, WebFetch |\n\nMCP tools: Subagents can access MCP tools from configured servers. Use the format mcp__servername__toolname. When tools is omitted, subagents inherit all tools including MCP tools.\n\nWhen Claude Auto-Delegates vs. Explicit Invocation\n\nAuto-delegation: Claude reads your subagent descriptions and decides when to use them:\n\nExplicit invocation: You can request a specific subagent:\n\nWhat triggers auto-delegation:\n\n Task matches a subagent's description \n Task would benefit from isolated context \n Task matches a subagent's specialized expertise\n\nTip: Write descriptions with trigger words users would actually say. \"Use for PR reviews\" helps Claude match \"review this PR\" to your subagent.\n\nExample Subagents\n\nSecurity Auditor (Read-Only)\n\nTest Writer\n\nDocumentation Writer\n\nHooks\n\nSubagents can define lifecycle hooks for custom behavior:\n\n| Hook | When It Runs |\n| :---- | :---- |\n| PreToolUse | Before the subagent uses a tool |\n| PostToolUse | After the subagent uses a tool |\n| Stop | When the subagent tries to finish |\n\nSharing Across Projects\n\nProject subagents (.claude/agents/):\n\n Check into git for team sharing \n Include in code review like any other code \n Document purpose in the subagent file itself\n\nUser subagents (/.claude/agents/):\n\n Personal across all your projects \n Won't be available to teammates\n\nTip: Start with project subagents. Promote to user subagents only if you find yourself copying them to every project.\n\nSubagents vs. Skills vs. Slash Commands\n\n| Aspect | Subagents | Skills | Slash Commands |\n| :---- | :---- | :---- | :---- |\n| Context | Isolated | Shared with main | Shared with main |\n| Invocation | Auto or explicit | Automatic | Explicit (/command) |\n| Structure | Single .md file | Directory with files | Single .md file |\n| Best for | Delegated tasks needing isolation | Domain expertise | Repeatable workflows |\n| Example | Code review, security audit | PDF handling | /fix-issue 1234 |\n\nDecision guide:\n\n Task benefits from isolated context → Subagent \n Expertise Claude should apply in main context → Skill \n Explicit workflow you trigger → Slash Command\n\nTips\n\n Start with read-only subagents. Reviewers and auditors are safe to experiment with. \n Use Haiku for simple tasks. Linting, formatting checks, and quick searches don't need Opus. \n Write specific descriptions. Auto-delegation depends on Claude matching your description to the task. \n Test with explicit invocation first. \"Use the code-reviewer subagent on X\" confirms it works before relying on auto-delegation. \n Keep subagent prompts focused. One specialty per subagent. Create multiple subagents rather than one that does everything.\n\nMCP & Plugins\n\n> [!TIP] Read Also\n> My book AI Agents with MCP (physical; non-affiliate) covers everything you need to know and then some about working with MCP.\n\nMCP (Model Context Protocol) is a standardized protocol that connects Claude Code to external tools and data sources. Think of it as a universal adapter for databases, APIs, browsers, and services. Plugins are a higher-level abstraction that can bundle MCP servers, commands, agents, skills, and hooks into installable packages.\n\nClaude Code can act as both:\n\n MCP Client: Connects to external MCP servers (Playwright, GitHub, Linear, etc.) \n MCP Server: Exposes Claude Code's capabilities to other tools\n\nPlugins vs. MCP Servers: \n\n| Concept | What It Is | Contains |\n| :---- | :---- | :---- |\n| MCP Server | A single external service connection | Tools from that service |\n| Plugin | A distributable package | MCP servers, commands, agents, skills, hooks |\n\nMost users interact with plugins, which handle MCP configuration automatically.\n\nAdding MCP Servers and Plugins\n\nMCP Servers (Direct)\n\nAdd an MCP server directly using the CLI:\n\nNote: Refer to your particular server’s installation instructions for exact commands, if available.\n\nPlugins (Recommended)\n\nPlugins bundle pre-configured MCP servers with setup instructions:\n\nThe official Anthropic marketplace (claude-plugins-official) is automatically available.\n\nConfiguration Locations\n\n| Location | Scope | Use For |\n| :---- | :---- | :---- |\n| .mcp.json in project root | Project (check into git) | Team-shared MCP servers |\n| .claude/settings.json | Project | Plugin and permission settings |\n| /.claude.json | User (all projects) | Personal MCP servers |\n| ~/.claude/settings.json | User | Global plugin settings |\n\nExample .mcp.json (shareable with team):\n\nCheck .mcp.json into git so teammates get the same tool access.\n\nCaution: Tool Collision and Context Cost\n\nTool Collision\n\nMultiple MCP servers can expose similarly-named tools, causing confusion:\n\n GitHub MCP and gh CLI both handle issues/PRs \n Multiple LSP servers for the same language\n\nFix: Disable or remove overlapping servers. Use /mcp to see all active tools.\n\nContext Cost\n\nEach MCP server consumes context. Too many servers \\= wasted tokens.\n\nBest practice: Install only what you actively use. Disable servers for projects that don't need them.\n\nSecurity\n\nPlugins and MCP servers execute code on your machine.\n\n Review before installing: Check the source repository \n Prefer official marketplaces: Anthropic-maintained plugins are vetted \n Be cautious with env vars: Tokens in .mcp.json may be committed accidentally\n\nUseful Plugins and MCP Servers\n\nLanguage Server Protocol (LSP)\n\nGive Claude real-time code intelligence: type checking, go-to-definition, find references.\n\nRequirements: The underlying language server binary must be in your PATH:\n\nNote: LSP support is maturing. As of v2.1.0+, most issues are resolved, but check the boostvolt/claude-code-lsps repo for current status.\n\nBrowser Automation: Playwright\n\nAutomate browser testing and visual verification.\n\nUse cases:\n\n Visual iteration: screenshot → compare → adjust \n E2E test generation \n Form filling and UI testing \n Debugging frontend issues with real browser\n\nProject Management: Linear\n\nCreate issues, manage projects, track work.\n\nCode Collaboration: GitHub\n\nBeyond gh CLI — deeper GitHub integration.\n\nOr configure directly:\n\nTeam Communication: Slack\n\nSearch messages and channel history.\n\nHooks Made Easy: Hookify\n\nCreate hooks without editing JSON — use markdown config files instead.\n\nThen create rules conversationally:\n\nHookify generates .claude/hookify..md files that take effect immediately.\n\nAutonomous Loops: Ralph Wiggum\n\nRun Claude in a persistent loop until a task completes.\n\nUsage:\n\nHow it works: A Stop hook intercepts Claude's exit, re-injects the prompt, and Claude continues. Each iteration sees the modified files from previous runs.\n\nBest for: Batch operations with clear success criteria (migrations, refactors, test coverage). Not for judgment-heavy work.\n\nSee the Multi-Agent Patterns section for more on autonomous workflows.\n\nCode Review Agents\n\nMulti-agent code review with specialized passes:\n\nDeploys multiple agents that review from different angles: security, performance, readability, testing, each with confidence scores.\n\nDebugging MCP Issues\n\n\\--mcp-debug Flag\n\nLaunch Claude Code with debug output for MCP:\n\nThis logs MCP server startup, connection issues, and tool registration.\n\nCommon Issues\n\n| Symptom | Likely Cause | Fix |\n| :---- | :---- | :---- |\n| \"No tools available\" | Server didn't start | Check binary is in PATH |\n| Tool not appearing | Server not registered | Run claude mcp list |\n| Authentication failed | Missing/invalid token | Check env vars in config |\n| \"Connection refused\" | Server crashed on start | Check --mcp-debug output |\n\nChecking Active Tools\n\nNavigate to a specific server to see its available tools and test them.\n\nTips\n\n Start with plugins over raw MCP. Plugins handle configuration and provide setup commands. \n Check .mcp.json into git. Team members get the same tools automatically. \n Use /context to monitor. MCP servers consume context — disable unused ones. \n One server per concern. Don't install GitHub MCP if gh CLI handles your needs. \n Read plugin docs. Many plugins have /plugin-name:setup commands for OAuth or configuration.\n\nMulti-Agent Patterns\n\nWhy Multiple Agents?\n\nA single Claude session works well for focused tasks. But complex work benefits from parallelization and separation of concerns:\n\n Parallel execution: Multiple Claudes work on different parts simultaneously \n Context isolation: Each agent has clean context, no drift from accumulated history \n Specialization: Dedicated agents for writing, reviewing, testing \n Verification: Independent agents catch mistakes the original missed\n\nThe patterns below range from simple (git worktrees) to sophisticated (adversarial validation).\n\nGit Worktrees for Parallel Work\n\nGit worktrees let you check out multiple branches from the same repo into separate directories. Each worktree is isolated — run a separate Claude session in each.\n\nSetup\n\nWorkflow\n\n1. Identify independent tasks — features, bugfixes, refactors that don't overlap \n2. Create a worktree per task with its own branch \n3. Open terminal tabs for each worktree \n4. Run Claude in each — they work in parallel \n5. Cycle through to check progress, approve permissions, provide guidance \n6. Clean up when done: git worktree remove ../project-feature-a\n\nTips\n\n Use consistent naming: ../project-{task-name} \n Set up terminal notifications: Claude Code can notify when it needs attention (see /terminal-setup) \n Open separate IDE windows for each worktree if reviewing code \n Don't overlap files: If two agents edit the same file, you'll have merge conflicts\n\nWrite → Review → Integrate Cycles\n\nUse separate Claude sessions for different roles, similar to human code review.\n\nPattern\n\nWhy This Works\n\n Fresh context: The reviewer hasn't seen the implementation journey, only the result \n No confirmation bias: A separate agent is more likely to spot issues \n Documented feedback: Writing issues to a file creates an artifact for the integrator\n\nVariations\n\n Writer \\+ Tester: One agent writes code, another writes tests to verify it \n Implement \\+ Security Audit: Implementation agent, then security-auditor subagent \n Draft \\+ Edit: One agent drafts documentation, another edits for clarity\n\nHeadless Mode for Automation\n\nHeadless mode (-p) runs Claude without interactive prompts — ideal for CI, scripts, and batch operations.\n\nBasic Usage\n\nCI Integration Examples\n\nPre-commit hook:\n\nPR Labeling (GitHub Action):\n\nFan-Out Pattern\n\nProcess many items in parallel by spawning multiple headless Claude calls:\n\nPipeline Pattern\n\nChain Claude into data processing pipelines:\n\nAdversarial Validation\n\nUse multiple models or agents to reach consensus on critical code.\n\nThe Problem\n\nA single model can confidently produce incorrect code. For high-stakes changes (auth, payments, data handling), independent verification catches errors.\n\nPattern: 2-of-3 Consensus\n\nMulti-Model Orchestration\n\nSome teams use the multi-agent-ralph-loop pattern:\n\n Claude, Codex, and Gemini review critical code in parallel \n 2-of-3 must approve for the change to pass \n Disagreements trigger iteration until consensus\n\nWhen to Use\n\n Authentication and authorization code \n Payment processing \n Data validation and sanitization \n Security-sensitive operations \n Breaking API changes\n\nWhen It's Overkill\n\n Routine refactors with good test coverage \n Documentation changes \n UI tweaks with visual verification\n\nRalph Wiggum: Autonomous Loops\n\nRalph Wiggum is a plugin that runs Claude in a persistent loop until a task completes or iterations run out.\n\nHow It Works\n\n1. You define a task and completion criteria \n2. Claude attempts the task \n3. When Claude tries to exit, a Stop hook intercepts \n4. The original prompt is re-injected \n5. Claude sees modified files from previous attempts and continues \n6. Loop until success or max iterations\n\nInstallation\n\nUsage\n\nKey Parameters\n\n| Parameter | Purpose |\n| :---- | :---- |\n| --max-iterations | Safety limit (default varies) |\n| --completion-promise | String Claude must output to signal completion |\n\nWhen to Use Ralph Wiggum\n\n| Good Fit | Why |\n| :---- | :---- |\n| Test migrations | Clear success: tests pass |\n| Linter fixes | Clear success: no lint errors |\n| Bulk refactors | Clear success: code compiles, tests pass |\n| Documentation generation | Clear success: all files documented |\n| Type annotation | Clear success: type checker passes |\n\nWhen NOT to Use\n\n| Bad Fit | Why |\n| :---- | :---- |\n| Architecture decisions | No objective success criteria |\n| UI design | Subjective quality judgment |\n| Code that needs human review | Loop won't stop for feedback |\n| Exploratory work | No clear endpoint |\n\nCost Awareness\n\nAutonomous loops consume tokens continuously. Set realistic --max-iterations and monitor costs. A 50-iteration loop on a large refactor can cost $10-50+ in API usage.\n\nAlternative: DIY Loops\n\nWithout the plugin, you can script similar behavior:\n\nChoosing a Pattern\n\n| Situation | Pattern |\n| :---- | :---- |\n| Multiple independent features | Git worktrees |\n| Need fresh eyes on code | Write → Review → Integrate |\n| CI/CD automation | Headless mode |\n| Processing many similar items | Fan-out |\n| Security-critical changes | Adversarial validation |\n| Batch work with clear success criteria | Ralph Wiggum |\n\nTips\n\n Start simple. Git worktrees \\+ multiple terminals cover most parallel needs. \n Define success criteria. Autonomous patterns require objective verification (tests, linters, type checkers). \n Monitor costs. Parallel and looping patterns multiply token usage. \n Use subagents first. Before spawning separate sessions, check if a subagent provides enough isolation. \n Set iteration limits. Always cap autonomous loops to prevent runaway costs. \n Log progress. Have agents write to files so you can track what happened across sessions.\n\nFurther Reading\n\nClaude Agent SDK\n\nFor building custom agents programmatically (rather than using Claude Code interactively), Anthropic provides the Claude Agent SDK. It exposes the same primitives that power Claude Code — tools, context management, compaction — in TypeScript and Python.\n\n Claude Agent SDK documentation \n Building Agents with the Claude Agent SDK\n\nRelated Tools\n\nTools in the broader agent ecosystem that complement Claude Code:\n\n| Tool | Purpose | Link |\n| :------------ | :----------------------------------------------------------------------------------------------------------------- | :------------------------------- |\n| Deciduous | Decision logging: capture and review decisions made during agent sessions | GitHub |\n| Letta | Persistent agent memory based on the MemGPT paper: for long-running agents that need memory beyond context windows | letta.com |\n\nOfficial Resources\n\n Claude Code Documentation \n Claude Code Best Practices (Anthropic) \n How Anthropic Teams Use Claude Code",
"title": "A Better Practices Guide to Using Claude Code"
}