⏳
Loading cheatsheet...
Claude Code installation, auth, workflows, MCP integration, autonomous coding patterns, and terminal-first best practices.
| Capability | Details |
|---|---|
| Code Understanding | Reads & comprehends entire codebases, cross-file references, dependency trees |
| File Editing | Creates, modifies, deletes files with surgical precision |
| Command Execution | Runs shell commands, tests, builds, linters directly in terminal |
| Git Integration | Commits, branches, PRs, conflict resolution, cherry-picking |
| Multi-file Refactors | Coordinates changes across dozens of files atomically |
| MCP Tools | Connects to databases, APIs, browsers, and external services |
| Computer Use | Interacts with GUI applications (2026) |
| Auto Mode | Runs autonomously with minimal human intervention (2026) |
| Remote Control | API-driven remote sessions and scheduled tasks (2026) |
# ── Install Claude Code ──
npm install -g @anthropic-ai/claude-code
# Verify installation
claude --version
# ── Authentication Methods ──
# Method 1: Anthropic API Key (set environment variable)
export ANTHROPIC_API_KEY="sk-ant-..."
# Method 2: Claude Pro/Max subscription
claude auth login
# Opens browser → authenticate with Anthropic account
# Method 3: Amazon Bedrock (for AWS users)
export ANTHROPIC_BEDROCK_BASE_URL="https://..."
export AWS_REGION="us-east-1"
export AWS_ACCESS_KEY_ID="..."
export AWS_SECRET_ACCESS_KEY="..."
# Method 4: Google Vertex AI
export ANTHROPIC_VERTEX_PROJECT="your-project"
export ANTHROPIC_VERTEX_REGION="us-east5"
# ── Start Claude Code ──
# Interactive REPL
claude
# With a specific model
claude --model claude-sonnet-4-20250514
# Non-interactive (piped / one-shot)
echo "Fix the bug in app.ts" | claude
claude -p "Explain this codebase in 3 sentences"
# Resume a previous conversation
claude --resume
# Continue the last conversation
claude --continueclaude auth login for the easiest setup if you have a Claude Pro/Max subscription ($20/mo or $100/mo). For API key usage, set ANTTHROPIC_API_KEY in your shell profile (.bashrc, .zshrc). The API key method gives you more control over model selection and spending limits.| Flag | Description | Example |
|---|---|---|
| --model | Choose model | claude --model claude-opus-4-20250514 |
| --allowedTools | Restrict available tools | claude --allowedTools "Read,Write" |
| --max-turns | Limit conversation turns | claude --max-turns 20 |
| --output-format | Output format | claude --output-format json |
| --print (-p) | Print & exit (non-interactive) | claude -p "List all TODOs" |
| --verbose | Verbose logging | claude --verbose |
| --system-prompt | Custom system prompt | claude --system-prompt "..." |
| --continue | Continue last conversation | claude --continue |
| --resume | Resume a specific session | claude --resume |
| --dangerously-skip-permissions | Skip all permission checks | claude --dangerously-skip-permissions |
| Pattern | Description |
|---|---|
| echo "prompt" | claude | Pipe a single prompt |
| claude -p "prompt" | Print mode — output to stdout |
| claude -p "prompt" -o json | JSON structured output |
| claude -p "prompt" --max-turns 5 | Limit agent autonomy |
| cat file.ts | claude -p "refactor" | Pipe file contents as context |
| git diff | claude -p "review" | Pipe git diff for code review |
| claude -p "$(cat prompt.txt)" | Read prompt from file |
# ── CI/CD Integration ──
claude -p "Run tests and report failures" --max-turns 10 --allowedTools "Bash"
# ── Batch Processing ──
for file in src/**/*.test.ts; do
claude -p "Fix failing test in $file" --max-turns 5
done
# ── JSON Output for Scripts ──
claude -p "List all API endpoints" -o json | jq '.response'
# ── Git Workflow ──
claude -p "Review this PR: $(git diff main)" --model claude-opus-4-20250514| Key | Action |
|---|---|
| Escape | Cancel / interrupt current operation |
| Ctrl + C | Cancel current action or stop generation |
| Ctrl + D | Exit Claude Code session |
| / (at prompt) | Enter slash command mode |
| ↑ / ↓ | Navigate command history |
| Tab | Auto-complete file paths and commands |
| Shift + Tab | Accept partial suggestion (multi-line) |
| Enter | Send message / accept full suggestion |
| Feature | Description |
|---|---|
| Multi-line input | Shift+Enter or paste multi-line text into the prompt |
| File drag & drop | Drag files into terminal to add as context |
| Image paste | Paste images (screenshots) directly into the prompt |
| @ mentions | Reference files: @file.ts, @folder/, @*.tsx patterns |
| Syntax highlighting | Code output is syntax-highlighted in terminal |
| Diff view | See exact file changes before Claude applies them |
| Undo | Claude can revert changes via git or file backup |
| Vim mode | Enable with /vim — use vim keybindings in prompt |
@ mentions to give Claude specific file context. Type @ followed by a filename pattern to attach files without copying content. Use @folder/ to include an entire directory. This is much more efficient than pasting large files.| Command | Description | Use Case |
|---|---|---|
| /help | Show all available commands and usage | Discovery & onboarding |
| /clear | Clear conversation history (fresh start) | Reset context when switching tasks |
| /compact | Compact/summarize conversation to free context | Long sessions hitting token limits |
| /config | Open Claude Code configuration (claude.json) | Adjust settings, permissions, model |
| /cost | Show current session token usage and cost | Budget monitoring |
| /doctor | Run diagnostics — check auth, tools, env | Troubleshooting setup issues |
| /init | Create CLAUDE.md in the current project | Project onboarding |
| /logout | Log out of Anthropic account | Switch accounts or revoke access |
| /permissions | View and manage tool permissions | Security configuration |
| /review | Enter code review mode | PR reviews, code quality audits |
| /status | Show Claude Code status and session info | Debug session state |
| /vim | Toggle vim keybinding mode | For vim users |
| /terminal-setup | Set up terminal integration (shell hooks) | Better shell experience |
/compact — As conversations grow, they consume context window tokens. When Claude starts losing track of earlier context, run /compact to summarize the conversation while preserving key decisions and context. This is essential for long coding sessions.| File Location | Scope | Git-tracked? | Priority |
|---|---|---|---|
| ~/.claude/CLAUDE.md | Global — all projects | No | Lowest (fallback) |
| <project>/CLAUDE.md | Project-level instructions | Yes | Standard |
| <project>/src/CLAUDE.md | Directory-specific rules | Yes | Overrides parent |
| <project>/CLAUDE.md.local | Local overrides (personal) | No (gitignored) | Highest |
| Aspect | Details |
|---|---|
| Nature | Advisory — Claude follows suggestions but can override when needed |
| Precedence | Child directories override parent, .local overrides tracked files |
| Max size | Keep under ~200 lines for optimal context usage |
| Auto-loading | Claude reads relevant CLAUDE.md files based on working directory |
| Dynamic | Changes to CLAUDE.md take effect on next message (no restart needed) |
| Team sharing | Project CLAUDE.md is shared via git; CLAUDE.md.local is personal |
# Project: My Next.js App
## Tech Stack
- Framework: Next.js 15 with App Router
- Language: TypeScript (strict mode)
- Styling: Tailwind CSS 4 + shadcn/ui
- Database: Prisma ORM with SQLite
- Package Manager: pnpm
## Coding Rules
- Use 'use client' for all interactive components
- Prefer shadcn/ui components over custom implementations
- Use Zustand for client state, TanStack Query for server state
- All API routes use Next.js Route Handlers (not Server Actions)
- No blue/indigo colors unless explicitly requested
## Commands
- Install deps: pnpm install
- Run dev: pnpm dev
- Lint: pnpm lint
- Type check: pnpm tsc --noEmit
- Run tests: pnpm test
## Code Style
- Use early returns in functions
- Prefer const over let
- All components use PascalCase
- Utility functions in src/lib/
- Types/interfaces in src/types/
## Git
- Commit messages follow Conventional Commits
- Always run lint before committing| Type | Examples | Customizable? |
|---|---|---|
| Built-in Skills | Code review, test generation, git operations, refactoring | Via CLAUDE.md preferences |
| Custom Skills | Team-specific workflows, deployment pipelines, documentation gen | Fully — create SKILL.md |
| MCP-powered Skills | Database queries, API testing, browser automation | Via MCP server config |
# Code Review Skill
## Trigger
Use when the user asks for a code review or PR review.
## Process
1. Read all changed files in the PR/diff
2. Analyze each file for the following categories:
### Security
- SQL injection, XSS, CSRF vulnerabilities
- Hardcoded secrets, API keys, passwords
- Improper input validation
- Insecure dependency versions
### Performance
- N+1 queries, unnecessary re-renders
- Missing indexes, unbounded loops
- Memory leaks, large bundle imports
### Code Quality
- DRY violations, dead code
- Naming conventions, type safety
- Error handling completeness
- Test coverage gaps
## Output Format
Provide findings in a table:
| Severity | File | Line | Issue | Suggestion |# Deployment Skill
## Trigger
Use when the user asks to deploy the project.
## Steps
1. Run lint: pnpm lint
2. Run type check: pnpm tsc --noEmit
3. Run tests: pnpm test
4. Build: pnpm build
5. Check for uncommitted changes: git status
6. Create release tag: git tag v${VERSION}
7. Deploy to Vercel: vercel --prod
## Rollback
If any step fails:
- Stop immediately
- Report the failure
- Suggest rollback command: vercel rollback| Event | Timing | Use Cases |
|---|---|---|
| PreToolUse | Before a tool executes | Lint before write, validate before git commit |
| PostToolUse | After a tool completes | Format after write, run tests after edit |
| Notification | System notifications | Alert on errors, notify on long tasks |
| SubagentStart | When a subagent spawns | Log, inject context, rate-limit |
| Stop | When Claude stops generating | Cleanup, summary generation |
{
"hooks": {
"PreToolUse": [
{
"matcher": "Write",
"command": "echo 'About to write a file...'"
},
{
"matcher": "Bash(git commit *)",
"command": "pnpm lint && pnpm test",
"if": "Bash(git commit *)"
},
{
"matcher": "Bash(npm publish *)",
"command": "echo 'BLOCKED: Use pnpm publish instead'",
"exit_code": 1
}
],
"PostToolUse": [
{
"matcher": "Write",
"command": "pnpm prettier --write $FILE"
},
{
"matcher": "Write(src/**/*.ts)",
"command": "pnpm tsc --noEmit"
}
],
"Notification": [
{
"matcher": "",
"command": "osascript -e 'display notification "$MESSAGE"'"
}
]
}
}exit_code: 1 pattern blocks the tool from executing.| Level | Behavior | Example Use |
|---|---|---|
| allow | Auto-approve — no prompt | Read, Write(src/**), Bash(git *) |
| deny | Block entirely — cannot execute | Bash(rm -rf *), Write(.env*) |
| ask | Prompt user each time | Bash(*), Write(production/**) |
| Pattern | Matches | Notes |
|---|---|---|
| Read | All read operations | Low risk — usually auto-allowed |
| Write | All file writes | Can be scoped: Write(src/**) |
| Bash(git commit *) | Git commits (any message) | Wildcard * in matcher |
| Bash(npm test) | Exact command only | No wildcards — exact match |
| Bash(rm -rf *) | Dangerous pattern | Should always be denied |
| Edit(src/**) | Edit files in src/ | Path-scoped tool permissions |
| mcp__* | All MCP server tools | Scope by server: mcp__github__* |
{
"permissions": {
"allow": [
"Read",
"Write(src/**)",
"Write(src/components/**)",
"Edit(src/**)",
"Bash(git *)",
"Bash(pnpm *)",
"Bash(node *)",
"mcp__github__*"
],
"deny": [
"Bash(rm -rf *)",
"Bash(sudo *)",
"Write(.env*)",
"Write(secrets/**)",
"Bash(npm publish *)",
"Bash(curl * | bash)"
],
"ask": [
"Write",
"Bash(*)",
"mcp__*"
]
}
}ask, then explicitly allow safe operations. Always deny dangerous patterns like rm -rf, sudo, and writing to .env files. Permissions persist across sessions in your project's claude.json.| Concept | Details |
|---|---|
| Definition | Claude can spawn child agents with their own context windows |
| Context | Each subagent gets its own fresh context (does not share parent context) |
| Communication | Subagents return results to the parent agent upon completion |
| Use cases | Parallel research, multi-file analysis, independent subtasks |
| Control | Configured via CLAUDE.md, permissions, or task delegation prompts |
| Depth limit | Subagents cannot spawn further subagents (one level deep) |
| Scenario | Why Subagents? |
|---|---|
| Analyzing 10+ files | Parallel file analysis is faster than sequential reading |
| Research + Implementation | One subagent researches, parent implements |
| Multi-component feature | Each component gets its own focused context window |
| Code review + fixes | Review in one pass, apply fixes in parallel |
| Testing & validation | Run multiple test suites concurrently |
{
"permissions": {
"allow": [
"Bash(claude *)"
]
}
}| Server | Package | Capabilities |
|---|---|---|
| GitHub | @anthropic-ai/mcp-github | Issues, PRs, repos, code search, actions |
| PostgreSQL | @anthropic-ai/mcp-postgres | Query, schema introspection, migrations |
| Puppeteer | @anthropic-ai/mcp-puppeteer | Browser automation, screenshots, PDFs |
| Filesystem | @anthropic-ai/mcp-filesystem | Extended file operations beyond Read/Write |
| Slack | @anthropic-ai/mcp-slack | Messages, channels, file uploads |
| Google Drive | @anthropic-ai/mcp-gdrive | Docs, sheets, file management |
| Brave Search | @anthropic-ai/mcp-brave-search | Web search results |
| Sentry | @anthropic-ai/mcp-sentry | Error tracking, issue management |
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@anthropic-ai/mcp-github"],
"env": {
"GITHUB_TOKEN": "${GITHUB_TOKEN}"
}
},
"postgres": {
"command": "npx",
"args": ["-y", "@anthropic-ai/mcp-postgres", "postgresql://..."]
},
"puppeteer": {
"command": "npx",
"args": ["-y", "@anthropic-ai/mcp-puppeteer"]
},
"remote-server": {
"type": "sse",
"url": "https://my-mcp-server.example.com/sse"
}
}
}| Feature | Details |
|---|---|
| Capability | Claude can interact with GUI applications — click, type, navigate |
| Setup | Requires display access (macOS, Linux X11/Wayland) |
| Use cases | Browser testing, GUI app automation, visual debugging, E2E testing |
| Safety | Requires explicit permission — Claude asks before each GUI action |
| Commands | Claude uses tools: computer_screenshot, computer_mouse_move, computer_click, computer_type |
| Feature | Details |
|---|---|
| Capability | Claude runs autonomously with minimal human intervention |
| Activation | claude --auto or enable via /auto command |
| Behavior | Auto-accepts most permissions, makes decisions independently |
| Limits | Still respects deny rules and hard limits (max-turns) |
| Best for | Refactoring, migration, test writing, documentation generation |
| Monitor | Use /cost to track spending, review changes periodically |
# ── Auto Mode Examples ──
# Migrate all .js files to .ts
claude --auto "Migrate all files in src/ from JavaScript to TypeScript"
# Generate tests for all components
claude --auto "Write unit tests for every component in src/components/"
# Refactor API to new pattern
claude --auto "Refactor all API routes to use the new error handling pattern"
# With limits
claude --auto --max-turns 50 "Add TypeScript types to all utility functions"
# Computer Use: E2E testing
claude "Open localhost:3000 in the browser, test the login flow, report any issues"--max-turns to prevent runaway sessions. Start with a small scope, verify the results, then scale up. Use git to easily revert if needed.| Feature | Details |
|---|---|
| API Control | Control Claude Code sessions programmatically via REST API |
| Multi-line Deep Links | Share Claude Code sessions via claude:// URLs |
| Headless Mode | Run Claude Code without a terminal (CI/CD, servers) |
| WebSocket | Real-time streaming of Claude responses |
| Use cases | IDE integration, CI/CD pipelines, team automation, chatbots |
| Feature | Details |
|---|---|
| Cron-like scheduling | Run Claude Code tasks on a schedule (daily, weekly, etc.) |
| Recurring tasks | Code review, dependency updates, test maintenance |
| Configuration | Define in claude.json under scheduledTasks |
| Notifications | Get alerted when scheduled tasks complete or fail |
| Use cases | Nightly dependency audits, weekly code reviews, stale branch cleanup |
{
"scheduledTasks": {
"daily-review": {
"schedule": "0 9 * * *",
"prompt": "Review all commits from the last 24 hours for issues",
"model": "claude-sonnet-4-20250514",
"max-turns": 20
},
"weekly-deps": {
"schedule": "0 10 * * 1",
"prompt": "Check for outdated dependencies and suggest updates",
"allowedTools": ["Read", "Bash(pnpm *)"]
}
}
}| File | Location | Purpose |
|---|---|---|
| claude.json | <project>/.claude/claude.json | Project config: permissions, hooks, MCP, model prefs |
| settings.json | <project>/.claude/settings.json | User-specific project settings (gitignored) |
| CLAUDE.md | <project>/CLAUDE.md | Project-level instructions (advisory) |
| CLAUDE.md.local | <project>/CLAUDE.md.local | Local overrides (gitignored) |
| SKILL.md | <project>/.claude/skills/*/SKILL.md | Skill definitions |
| CLAUDE.md (global) | ~/.claude/CLAUDE.md | Global user instructions (all projects) |
| claude_desktop_config.json | ~/.claude/claude_desktop_config.json | MCP server config (desktop) |
| credentials.json | ~/.claude/credentials.json | Stored auth credentials (auto-managed) |
| conversations/ | ~/.claude/conversations/ | Stored conversation history |
{
"model": "claude-sonnet-4-20250514",
"permissions": {
"allow": ["Read", "Bash(git *)"],
"deny": ["Bash(rm -rf *)"],
"ask": ["Write", "Bash(*)"]
},
"hooks": {
"PreToolUse": [
{ "matcher": "Write", "command": "pnpm lint" }
]
},
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@anthropic-ai/mcp-github"]
}
}
}| Feature | Claude Code | Cursor | GitHub Copilot | Aider |
|---|---|---|---|---|
| Type | CLI agentic assistant | IDE extension + agent | IDE inline suggest | CLI pair programmer |
| Environment | Terminal | VS Code / Cursor IDE | VS Code, JetBrains, etc. | Terminal |
| Autonomy | High (full agent) | Medium (tab-complete + agent) | Low (suggestions only) | High (agentic CLI) |
| Model | Claude (Anthropic) | Multi-model (GPT, Claude) | OpenAI Codex | Multi-model |
| File editing | Direct (multi-file) | In-editor diffs | Inline suggestions | Direct (git-based) |
| Command execution | Yes (shell access) | Limited | No | Yes (shell access) |
| MCP support | Yes (first-class) | Plugin system | GitHub extensions | No (model-agnostic) |
| Hooks system | Yes (mandatory) | No | No | No |
| Skills system | Yes (SKILL.md) | No | Snippets | No |
| Pricing | API / Pro $20 / Max $100 | Free + $20/mo | Free + $10-39/mo | Free (BYOK) |
| Open source | No | No | No | Yes (Apache 2.0) |
| Best for | Complex refactors, CLI workflows | Daily coding in IDE | Quick completions | Open-source preference |
| Tip | Details |
|---|---|
| Use /compact early | Run /compact before context gets full — Claude stays sharper longer |
| Use /cost regularly | Monitor spending — complex tasks can get expensive quickly |
| @ mention files | Type @filename to add context without pasting entire contents |
| Paste images | Paste screenshots directly — Claude can analyze UI bugs from images |
| Multi-line prompts | Use Shift+Enter for complex instructions — Claude follows them better |
| Start with claude /init | Bootstrap CLAUDE.md for any new project instantly |
| Chain commands | Use && and ; in Bash calls to run multiple commands per turn |
| Use git aggressively | Let Claude commit frequently — easy to revert individual changes |
| Pattern | Implementation |
|---|---|
| Context injection | Use CLAUDE.md to always provide architecture docs to Claude |
| Gate quality with hooks | PreToolUse:Write → run linter (blocks bad code before write) |
| Template generation | Skills with SKILL.md for consistent boilerplate generation |
| Parallel research | Ask Claude to delegate to subagents for multi-file analysis |
| Budget control | Use --max-turns and model selection to control costs |
| Git workflow | claude -p "$(git diff)" for instant code review in terminal |
| Database exploration | MCP + Postgres server → natural language SQL queries |
| CI integration | claude -p in GitHub Actions for automated PR reviews |
@ mentions, CLAUDE.md for persistent context, and subagents for parallel work. Claude works best with focused, specific tasks. Break large requests into smaller, sequential steps.| Issue | Cause | Solution |
|---|---|---|
| Auth failed | Expired API key or bad subscription | Run claude auth logout then claude auth login |
| Context too large | Conversation exceeded token limit | Run /compact or /clear to free context |
| Slow responses | Model overloaded or complex task | Switch to Haiku for simple tasks: --model claude-haiku |
| Permission denied | Tool not in allow list | Edit claude.json permissions or run /permissions |
| MCP server crash | Server process exited | Check server logs, verify command/args in config |
| Claude ignores CLAUDE.md | File too large or conflicting rules | Keep under 200 lines, check .local overrides |
| Hook not firing | Matcher syntax wrong | Use exact tool names: Write, Bash(git *) |
| Git conflicts | Claude edited files during merge | Use git to resolve, then ask Claude to rebase |
| Stale context | Claude forgets earlier conversation | Run /compact more frequently |
| Install fails | Node.js version too old | Ensure Node.js 18+ and npm 9+ installed |
# ── Diagnostic Commands ──
# Check Claude Code version
claude --version
# Run diagnostics
claude /doctor
# Check auth status
claude auth status
# Clear all cached data
rm -rf ~/.claude/cache
rm -rf ~/.claude/conversations
# Reset permissions for current project
rm .claude/claude.json
# Test MCP server connectivity
claude -p "List available MCP tools"
# Check Node.js version (requires 18+)
node --version
# Reinstall Claude Code
npm install -g @anthropic-ai/claude-code@latest
# Verbose logging for debugging
claude --verbose 2>&1 | tee claude-debug.logclaude /doctor first when troubleshooting. It checks authentication, tool availability, MCP server status, and environment configuration. For persistent issues, use --verbose mode and redirect output to a log file for detailed diagnostics.