CLAUDE
CODE
DEEP DIVE
The complete reference for Claude Code โ Anthropic's command-line coding agent. Covers installation, CLAUDE.md, SKILL.md, hooks, MCP, subagents, plan mode, worktrees, plugins, the Agent SDK, GitHub Actions, 30+ battle-tested prompts, chained workflows, and 2 full app blueprints (RAG AI + FastAPI internal tool) with copy-paste-ready code.
Claude Code is Anthropic's terminal-native coding agent โ a CLI tool that runs inside your shell and has direct access to your filesystem, git, shell commands, and any MCP servers you connect. It is NOT the same as Claude.ai in a browser.
โ What Claude Code IS
CLI agentRuns in your terminal, reads/writes files directlyShell-enabledCan run bash, git, npm, tests, builds nativelyExtensiblePlugins, skills, hooks, MCP servers, subagentsMulti-fileEdits entire projects, not single files in isolationAgenticPlans, executes, verifies, iterates autonomouslyGit-awareCommits, branches, PRs, worktrees built-in
โ What Claude Code is NOT
Not Claude.aiDifferent product, different capabilitiesNot a chatIt's an agent โ it DOES things, not just talksNot auto-safeCan delete files, push commits โ review carefullyNot free foreverUses API tokens; costs scale with usageNot a replacementYou still drive the ship; it's a force multiplierNot magicNeeds good CLAUDE.md + good prompts to shine
Claude Code is built on a layered architecture. Understanding this helps you configure it properly:
claude binary, session loop, tool execution, model routing. This is the engine.Most Claude Code problems aren't about the model โ they're about Layer 2 (configuration). A good CLAUDE.md and well-scoped skills will 10ร your effectiveness. This tutorial focuses heavily on those layers.
Claude Code requires Node.js 18+ and either an Anthropic API key or a Claude Pro/Max subscription. On Windows, use PowerShell or WSL2 โ Git Bash has known issues with some subagent operations.
Install Node.js 18 or later
Install the Claude Code CLI globally
Log in via browser or API key
If you set ANTHROPIC_API_KEY in a .env file, add .env to .gitignore FIRST. Claude Code reads the env var automatically.
Navigate to a project and launch Claude Code
Install the VS Code extension (or Cursor / JetBrains)
The VS Code extension adds inline chat, code lens buttons, and file context. JetBrains plugin is in beta at this writing.
Run claude --version. If you see a version number (e.g. 1.x.y), you're good. If you see "command not found", add your global npm bin path to PATH: npm config get prefix shows where it lives.
Auto-generate your project's CLAUDE.md
The file will look something like this
Create your user-level CLAUDE.md
Configure what Claude Code can and cannot do
The deny list is your safety net. Always include it. See Section 13 (Rejected Commands) for more things to block.
Run the health check
Type / inside a Claude Code session to see the command picker. These are the built-in commands โ plugins and skills add more.
| Command | Purpose | Notes |
|---|---|---|
| /help | List all available commands | Shows both built-in and plugin commands |
| /init | Auto-generate CLAUDE.md for current project | Run once per new project |
| /clear | Clear conversation context | Preserves plan files and CLAUDE.md |
| /compact | Compress long context into summary | Great for long sessions to reclaim tokens |
| /resume | Resume a previous session | Lists recent sessions by date |
| /sessions | Manage session history | List, rename, delete saved sessions |
| /model | Switch model mid-session | Opus 4.7 / Sonnet 4.6 / Haiku 4.5 |
| /effort | Set reasoning effort level | low / medium / high for next turn |
| /review | Review recent changes | Built-in code review, runs as subagent |
| /security-review | Security-focused review | Scans for secrets, injection, unsafe patterns |
| /agents | List and manage subagents | See active agents, kill runaway ones |
| /mcp | Manage MCP servers | Add/remove/test servers |
| /plugin | Manage plugins | Install, update, list, marketplace |
| /memory | View/edit persistent memory | Cross-session memory via MCP |
| /config | Edit Claude Code config | Opens settings.json in $EDITOR |
| /cost | Show token usage + cost | Current session + rolling totals |
| /status | Show session status | Model, context used, active hooks |
| /doctor | Health check | Verify setup is working |
| /bug | Report a bug to Anthropic | Auto-includes session metadata |
| /keybindings | Edit keyboard shortcuts | Saves to ~/.claude/keybindings.json |
| /upgrade | Update Claude Code | Runs npm update behind scenes |
| /exit | Exit Claude Code | Also: Ctrl+C twice, or Ctrl+D |
| /vim | Toggle vim mode | Input mode with vim bindings |
| /terminal-setup | Configure terminal integration | Sets up shell hooks for better UX |
| /install-github-app | Install GitHub App integration | For automated PR reviews |
| /pr_comments | Fetch PR review comments | Pulls comments from current PR branch |
These are built-in skills that behave like slash commands:
CLAUDE.md is the single most important file in your Claude Code setup. It's the system prompt for every session โ Claude reads it first, every time. A great CLAUDE.md means Claude already knows your conventions before you type a single prompt.
1. User message (your prompt) ยท 2. Project CLAUDE.md (.claude/CLAUDE.md) ยท 3. User CLAUDE.md (~/.claude/CLAUDE.md) ยท 4. Imported @files ยท 5. Built-in system prompt
Keep CLAUDE.md small by importing other files
A CLAUDE.md over 300 lines bloats every session's context. Use @imports to keep the root file under 150 lines, then import detailed docs only when needed.
Real-world CLAUDE.md for a Next.js 15 app
Real-world CLAUDE.md for a Python API
Real-world CLAUDE.md for an ASP.NET Core API
What to NEVER put in CLAUDE.md
- โ Secrets / API keys โ CLAUDE.md gets committed. Use env vars.
- โ Walls of prose โ keep it scannable. Claude reads lists better than paragraphs.
- โ Conflicting conventions โ "use tabs" + "use 2 spaces" confuses the model.
- โ Stale commands โ outdated commands make Claude hallucinate failures.
- โ Over 300 lines โ use @imports to break it up.
- โ Opinions without justification โ "no classes" works better than "hate OOP".
- โ Every possible rule โ focus on what's non-obvious. Claude knows TypeScript basics.
CLAUDE.md vs AGENTS.md โ which to use?
AGENTS.md is the newer open standard (used by multiple AI coding tools โ Codex, OpenCode, Cursor). It serves the same purpose as CLAUDE.md but is tool-agnostic.
- Use CLAUDE.md if your team only uses Claude Code
- Use AGENTS.md if you share the project across Codex / Cursor / OpenCode / Claude Code
- You can have both โ Claude Code reads both, with CLAUDE.md winning conflicts
Skills are Claude Code's killer feature. A skill is a folder with a SKILL.md file that teaches Claude how to do a specific task. Skills can be auto-invoked by Claude when the context matches, or manually via /skill-name. They replaced the old "slash commands" system as the primary extension mechanism.
1. Project: .claude/skills/<name>/SKILL.md ยท 2. User: ~/.claude/skills/<name>/SKILL.md ยท 3. Plugin: <plugin-dir>/skills/<name>/SKILL.md
Every skill is a directory with a SKILL.md plus optional support files
All available frontmatter options
/deploy-to-vercel/ menu)claude-opus-4-7, claude-sonnet-4-6, etc.Explore / Plan / general-purpose or customFull skill with safety gates
Deploys have real consequences. We don't want Claude to accidentally deploy when it "thinks" the user asked for it. Only an explicit /deploy-to-vercel triggers this.
Auto-invoking review skill
Structured git commit skill
Hooks are scripts that fire at specific points in Claude Code's lifecycle. They let you inject context, block dangerous actions, or automate workflows. Every hook communicates via JSON on stdin / stdout.
| Hook | Fires When | Use Case |
|---|---|---|
| PreToolUse | Before Claude calls any tool | Block dangerous commands, inject context |
| PostToolUse | After tool completes | Log actions, notify, post-process output |
| UserPromptSubmit | User hits Enter on prompt | Rewrite prompts, add metadata, audit |
| Stop | Session ends | Cleanup, summary, cost report |
| SessionStart | New session begins | Auto-load context, check env, run linter |
| Notification | Claude needs user attention | Desktop notify, sound, Slack webhook |
| PermissionRequest | Claude asks for tool permission | Auto-approve safe patterns, deny risky ones |
Where and how to define hooks
PreToolUse hook that blocks dangerous deletions
PostToolUse hook that lints files after Claude edits them
Stop hook that logs session cost + summary
How hooks return decisions
Hooks communicate via JSON on stdout. To deny an action:
To allow:
To inject context (UserPromptSubmit):
MCP is Anthropic's open protocol for connecting external tools to AI agents. An MCP server exposes tools (functions) that Claude Code can call. Think of them as "plugins for data and actions" โ access databases, browse the web, control browsers, send emails, query APIs.
How MCP works
- MCP Server โ a process that exposes tools. Runs locally or remotely.
- MCP Client โ Claude Code is the client. It discovers and calls server tools.
- Transport โ stdio (local subprocess), SSE (HTTP Server-Sent Events), or WebSocket
- Config โ added via
claude mcp addor in~/.claude/mcp.json
Use claude mcp add command
The essential toolkit
Manual config file format
Turn Claude Code into an autonomous background agent
Combined with claude -p headless mode + dispatch API, this effectively replaces tools like Hermes or AutoGPT. Your agent becomes self-directing.
MCP servers are arbitrary code โ treat them accordingly
- โ ๏ธ Review before installing. MCP servers have full access to whatever their code does.
- โ ๏ธ Known CVEs exist. There's a database of 25+ known MCP vulnerabilities.
- โ ๏ธ Scope env vars. Pass only what's needed โ don't export your whole
.envto every MCP. - โ ๏ธ Audit with AgentShield. Run
npx ecc-agentshield scanperiodically. - โ ๏ธ Prefer official servers.
@modelcontextprotocol/*are maintained by Anthropic and partners.
Subagents are isolated Claude instances spawned by the main session to handle specific tasks in parallel. Each runs in its own context window, returns results to the orchestrator, and doesn't pollute the main conversation. This is how Claude Code handles complex multi-file work.
Explore โ fast codebase navigation & search ยท Plan โ design implementation strategies ยท general-purpose โ catch-all for research & multi-step tasks
Two ways subagents launch
- Automatic (Task tool) โ Claude's main session calls the
Tasktool with a prompt + agent type. A fresh subagent runs, returns a summary. - Manual (via skill frontmatter) โ A skill with
agent: Exploreruns in that agent's context.
Write your own subagent
Dispatch multiple subagents in one message
When the main session calls Task multiple times in a single message, they run in parallel. Use this for independent workstreams.
Three 30-second subagent calls serially = 90s. In parallel = 30s. For research-heavy tasks this is a huge speedup.
Spec compliance + code quality as separate subagents
Battle-tested pattern from Superpowers & ECC: never trust a single-agent review.
Subagents see ONLY what you send them
A subagent starts with a fresh context. It doesn't see your main conversation. This is a feature, not a bug:
- โ No context pollution โ subagent outputs don't clog your main session
- โ Focused work โ subagent has a clear single task
- โ ๏ธ But you must send context โ paths, spec, constraints all go in the prompt
Don't let subagents spawn subagents unchecked
A subagent that spawns 3 more subagents that each spawn 3 more = runaway costs. Many frameworks (Superpowers v5, ECC) have anti-recursion guards. Your custom subagents should too:
Plan mode forces Claude to produce a written plan before touching any code. Git worktrees isolate parallel tasks in separate branches. Together they enable complex multi-step work without chaos.
Three ways to activate
What Claude does in plan mode
- Reads context โ relevant files, CLAUDE.md, git state
- Researches โ may dispatch Explore subagent, MCP queries (Context7, Exa)
- Drafts plan โ structured markdown: goals, approach, files, steps, risks
- Calls ExitPlanMode tool โ submits plan for approval
- Awaits user decision โ approve / request changes / deny
- On approve โ proceeds to implement
The Plannotator plugin (see sibling tutorial) gives you a visual browser UI to annotate plans before approving. Massive upgrade over terminal-only.
Use --worktree flag to isolate tasks
You can have 3 Claude sessions running in parallel โ one on feature-auth, one on feature-billing, one on bug-fix-42. They don't collide. Combined with /batch skill, Claude can ship multiple features autonomously.
File snapshots for rollback
The 3-state cycle
| Press | Mode | Behavior |
|---|---|---|
| Shift+Tab (1ร) | Auto-accept | Claude skips permission prompts โ for non-destructive tools only |
| Shift+Tab (2ร) | Plan mode | Claude MUST plan before acting; no file writes until approved |
| Shift+Tab (3ร) | Normal | Default โ Claude asks before each tool call |
Plugins package skills, subagents, hooks, and commands into installable bundles. A marketplace is a GitHub repo that lists multiple plugins. Claude Code discovers and installs them via the /plugin command.
Install a plugin from a marketplace
Battle-tested plugins worth installing
The structure of a plugin repo
The plugin manifest
Claude Code v2.1+ auto-loads hooks/hooks.json. Explicit declaration causes duplicate-hook errors. This is the #1 plugin authoring gotcha.
How to build a marketplace
Claude Code's underlying engine is exposed via the Claude Agent SDK (@anthropic-ai/claude-agent-sdk). You can embed agent functionality in scripts, CI jobs, webhooks, and custom tools. Same loop, same tools, no interactive UI.
Run Claude Code non-interactively
TypeScript/Node SDK
Programmatic agent calls
Inline subagent configuration
Load MCP inside an SDK call
Trigger Claude Code from webhooks / CI
Claude Code can run inside GitHub Actions to auto-review PRs, respond to mentions, fix CI failures, and more. The official action is anthropics/claude-code-action@v1.
Two options for auth
- Option A: Install the Claude GitHub App โ uses OAuth, no tokens to manage
- Option B: Set
ANTHROPIC_API_KEYas a repo secret โ pay-per-use via API
Auto-review on pull request
Auto-fix on CI failure
Claude responds when @claude-code is mentioned in issues/PRs
Critical safeguards
- โ ๏ธ Use
permissions:block โ grant minimum needed, never default - โ ๏ธ Fork PRs run with different permissions โ Claude cannot commit to forks automatically
- โ ๏ธ Secret masking โ never echo secrets; Claude never outputs them
- โ ๏ธ Cost caps โ set
max_turnsto avoid runaway costs - โ ๏ธ Branch protection โ require human review on Claude-authored PRs
- โ ๏ธ Review the action version โ pin to
@v1or a SHA, never@main
๐ Install Commands
npm i -g @anthropic-ai/claude-codeInstall CLI globallyclaude loginOAuth login (Pro/Max/Team)claude --versionVerify installclaudeLaunch in current dirclaude --project /pathLaunch for specific projectclaude --worktree <branch>Launch in isolated worktreeclaude --resumeResume previous sessionclaude -p "prompt"Headless (non-interactive)npm update -g @anthropic-ai/claude-codeUpdate to latest
โก Core Slash Commands
/helpList all commands/initGenerate CLAUDE.md/clearClear conversation/compactCompress context/resumeResume session/sessionsManage session history/modelSwitch model/effortSet reasoning effort (low/med/high)/reviewCode review subagent/security-reviewSecurity-focused review/agentsManage subagents/mcpManage MCP servers/pluginPlugin manager/doctorHealth check/costToken usage + $$$/bugReport bug to Anthropic/exitExit session
โจ Keyboard Shortcuts
Shift+Tab ร 1Auto-accept modeShift+Tab ร 2Plan modeShift+Tab ร 3Back to normalCtrl+BSend current subagent to backgroundCtrl+RSearch command historyCtrl+C(once)Cancel current operationCtrl+C(twice)Exit Claude CodeCtrl+DExit (EOF)EscCancel tool prompt@filenameReference a file# topicAdd inline context tagultrathinkForce high-effort reasoning (1 turn)
๐ CLAUDE.md Patterns
## StackEnumerate tech stack## ConventionsNon-obvious project rules## CommandsDev/test/build/lint commands## Do NotExplicit blacklist## Imports@file references to other docs@docs/api.mdImport another markdown file## Project LayoutFolder structure overview## TestingTest conventions and commands
๐ง SKILL.md Frontmatter
name:Slash command namedescription:When to auto-invokeallowed-tools:Pre-authorised toolsdisable-model-invocation: trueUser-only invocationuser-invocable: falseHidden from / menumodel: claude-opus-4-7Pin modelcontext: forkSeparate context windowagent: ExploreRun in agent type
๐ช Hook Triggers
PreToolUseBefore tool callPostToolUseAfter tool completesUserPromptSubmitUser hits EnterStopSession endsSessionStartNew session beginsNotificationClaude needs attentionPermissionRequestTool permission asked
๐ MCP Setup
claude mcp add <name> -- <cmd>Add serverclaude mcp listList configured serversclaude mcp test <name>Test connectionclaude mcp remove <name>Remove server@upstash/context7-mcpLibrary docs@modelcontextprotocol/server-playwrightBrowser automation@modelcontextprotocol/server-githubGitHub API@anthropic/scheduled-tasks-mcpCron agent scheduling
๐ค Subagents
ExploreFast codebase navigationPlanDesign implementation strategiesgeneral-purposeCatch-all.claude/agents/*.mdCustom subagentsTask toolOrchestrator dispatchesParallel dispatchMultiple Task() in one msgcontext: forkIsolated context window
โ Rejected / Never Do This
API keys in CLAUDE.mdโ CLAUDE.md is committed โ use env vars--dangerously-skip-permissionsโ In untrusted repos โ instant RCE riskCommit .claude/ with secretsโ Add .claude/local/ to .gitignoreCLAUDE.md over 500 linesโ Bloats every session; use @importsSkipping plan mode on complex tasksโ Leads to wasted tokens, bad codeSubagents spawning subagentsโ Runaway cost; add anti-recursion guardclaude -p on prod DBโ Use read-only creds + --dry-run"hooks" field in plugin.jsonโ Duplicate-hook error โ auto-loaded nowMCP from unknown sourceโ Audit first; 25+ known CVEs existInstalling all plugins at onceโ Context bloat; install as neededAuto-approving git pushโ Always require human confirmationHardcoding prod URLs in skillsโ Use env vars; skills are committedDisabling security-reviewer hookโ Core safety layer โ keep enabledRunning unknown .sh hooksโ Read every hook script before installSharing sessions with secretsโ /sessions export may leak creds
๐ฆ Troubleshooting
| Problem | Fix |
|---|---|
| claude: command not found | Add npm global bin to PATH: export PATH="$(npm config get prefix)/bin:$PATH" |
| CLAUDE.md not being read | Check file is at repo root OR .claude/CLAUDE.md. Run /doctor to verify. |
| Skill not auto-invoking | Description too vague. Be specific: "Use when user says X" with exact trigger phrases. |
| Hook not firing | Check hooks.json syntax, make script executable (chmod +x), check matcher glob. |
| MCP server timeout | Run claude mcp test <name>. Check network/env vars. Some servers need API keys. |
| Costs too high | Run /compact mid-session. Use /effort low for simple tasks. Prefer Sonnet over Opus for code gen. |
| Subagent context lost | You must send all context in the prompt โ subagent doesn't see main conversation. |
| Plugin not found after install | Restart Claude Code. Plugins load at session start, not mid-session. |
| Plan mode not activating | Shift+Tab cycles modes; terminal may eat the signal โ use explicit "do not write code, just plan." |
| Worktree remains after session | Only cleans if no changes. Run git worktree remove <path> manually. |
| Permissions prompts every time | Add patterns to settings.json allow list, or use skill's allowed-tools frontmatter. |
| GitHub Action runs but does nothing | Check permissions: block โ needs contents: write + pull-requests: write. |