Claude Code · Quick Reference

Code with Claude — Cheat Sheets

Your complete quick-reference companion for Claude Code. Power commands, prompt formulas, CLAUDE.md templates, MCP patterns, and daily workflow recipes — everything you need in one bookmark.

⚡ CLI Commands 📄 CLAUDE.md Templates 🔌 MCP Patterns 🎯 Prompt Formulas ✅ Workflow Checklists
⚡ Claude Code CLI — Power Commands
Essential commands for daily development with Claude Code

🚀 Starting Sessions

claude
Start interactive session (loads CLAUDE.md automatically from current dir)
claude "task description"
One-shot task — Claude completes it and exits (great for CI/CD scripts)
claude --plan "task"
Enter plan mode — Claude proposes implementation before starting
claude --no-interactive "task"
Fully non-interactive mode for CI/CD pipelines (no confirmation prompts)
claude --model claude-haiku-4-5 "task"
Use a specific model (Haiku for speed/cost, Sonnet for quality)

💬 In-Session Commands

/plan "subtask"
Get an implementation plan before Claude starts coding on a specific subtask
/review
Run your custom review command (defined in .claude/commands/review.md)
/add-tests src/auth.ts
Run custom command with argument (defined with $ARGUMENTS placeholder)
/clear
Clear conversation context — start fresh with same project CLAUDE.md
/cost
Show current session token usage and estimated API cost

🔧 Management

claude config list
Show current Claude Code configuration (model, MCP servers, etc.)
claude config set model claude-sonnet-4-5
Set default model for all sessions
claude mcp list
List all configured MCP servers and their status
claude update
Update Claude Code to latest version
📄 CLAUDE.md — Templates
Copy and adapt for your project. A good CLAUDE.md pays back 10× its writing time.

🔑 Minimal Effective CLAUDE.md (All Projects)

markdown — CLAUDE.md minimum viable
# [Project Name] ## What This Is [One paragraph: what the project does, who uses it, tech stack] ## Architecture - [Framework/language] for [backend/frontend/both] - [Database] for storage - Key directories: [/src, /tests, /config - describe each] ## Coding Rules - [Rule 1 - e.g., always use async/await not .then()] - [Rule 2 - e.g., all functions need JSDoc comments] - [Rule 3 - naming convention, e.g., use snake_case for Python] ## DO NOT Touch - [File/dir 1] — [why: e.g., auto-generated, don't edit directly] - [File/dir 2] — [why: e.g., requires security review first] ## How to Run - Tests: [command] - Dev server: [command] - Build: [command]

🏢 Full Enterprise CLAUDE.md Template

markdown — CLAUDE.md enterprise template
# Project: [Name] | Last Updated: [Date] ## Project Context - **Purpose:** [What problem this solves, for whom] - **Stack:** [Full tech stack with versions] - **Environment:** [dev/staging/prod setup] - **Team size:** [N engineers], [N month old codebase] ## Directory Structure /src - Application source code /api - REST API routes (Express/FastAPI) /services - Business logic layer (never in routes!) /models - Data models and DB schema /utils - Pure utility functions (no side effects) /tests - Test files (mirror src structure) /migrations - DB migrations (NEVER edit manually) /scripts - Utility scripts for deployment/data tasks ## Critical Conventions ### Code Style - Async: always use async/await (never .then() callbacks) - Error handling: never swallow errors, always propagate or log - Types: strict TypeScript — never use `any` or `!` non-null assertions - Imports: use path aliases (@/services/user, not ../../services/user) ### Business Logic - ALL business logic in /services, NEVER in route handlers - Services must be stateless and independently testable - Database calls only from services (not from routes or models) - Never expose internal IDs directly in API responses ### Database - Use Prisma ORM for all DB operations - Never write raw SQL unless performance-critical (justify in comment) - All schema changes via migrations (npx prisma migrate dev) - Index all foreign keys and frequently-queried columns ## DO NOT EVER - Modify /migrations — these are immutable - Commit secrets, API keys, or credentials to ANY file - Use synchronous file I/O (fs.readFileSync) in request handlers - Skip input validation on any user-supplied data - Make architectural changes without running security tests ## Testing Requirements - Framework: Vitest + supertest for integration - Coverage target: 80% branches on all new code - Required: unit tests for all service functions - Required: integration tests for all API endpoints - Mocks: mock ALL external services (no real API calls in tests) ## How to Run - Dev: npm run dev - Tests: npm test - Test coverage: npm run test:coverage - Lint: npm run lint - Type check: npm run typecheck - DB migrate: npx prisma migrate dev ## MCP Servers Available - database: PostgreSQL read access for debugging - github: Repository management and PR creation ## Team Notes - [Add any context that would help a new engineer understand the most non-obvious things]
🎯 Prompt Formulas — Copy-Paste Templates
Proven prompt patterns for every common development task

Feature Implementation

Formula
Implement [feature name] according to [specification/description]. Requirements: - [Functional requirement 1] - [Functional requirement 2] - [Non-functional: performance, security, etc.] Context: - [Relevant existing code/patterns to follow] - [Constraints: don't modify X, must work with Y] Success criteria: - All existing tests still pass - [New behavior you can verify]

Bug Fix with Root Cause

Formula
Bug: [One sentence description] Error message/Stack trace: [Full error text] Expected behavior: [What should happen] Actual behavior: [What does happen] Reproducibility: [Always / Sometimes / Only when X] Relevant files attached: [list] Task: 1. Identify the root cause (not just the symptom) 2. Implement the fix 3. Explain why this fix prevents recurrence 4. Write tests for the exact conditions that caused this bug

Code Review

Formula
Review the following code as a [senior/staff] engineer at [company type/domain]. Check for (in priority order): 1. Security vulnerabilities 2. Logic errors and edge cases 3. Missing error handling 4. Performance issues 5. Test coverage gaps 6. Violations of our CLAUDE.md conventions For each issue found: - File + line number - Severity: CRITICAL / HIGH / MEDIUM / LOW - What the issue is - Why it matters - Suggested fix with code example End with: APPROVE or REQUEST_CHANGES + one sentence summary.

Test Generation

Formula
Generate comprehensive tests for: [file/function/module] Requirements: - Framework: [Vitest/Jest/pytest/etc.] - Cover: happy path, error states, edge cases, boundary values - Mock: all external dependencies (no real API/DB calls in tests) - Target: [X]% branch coverage - Style: follow pattern in [existing test file for reference] For each test group, add a comment explaining what behavior is being verified. Run the tests after writing them and fix any failures.

Refactoring

Formula
Refactor [file/module/function] to [goal: use repository pattern / reduce complexity / improve readability / etc.] Constraints: - External behavior must be identical after refactoring - Existing tests must still pass (don't delete tests, fix them if needed) - Don't change the public API/interface Process: 1. First, run existing tests to capture baseline behavior 2. Make the refactoring changes 3. Run tests again — fix any regressions 4. Report: what changed, why, any concerns
🔌 MCP — Quick Reference
Essential patterns for building and connecting MCP servers

MCP Server Setup Checklist

📦

Installation

pip install mcp (Python)
npm install @modelcontextprotocol/sdk (TypeScript)
Server entry: asyncio.run(stdio_server(server))

⚙️

Registration

Add to ~/.claude/config.json under "mcpServers".
Specify: command, args, env vars.
Test with: claude mcp list

Tool Description Formula

Write tool descriptions as if Claude has never seen your system
[WHAT]: This tool [does what, specifically] [WHEN TO USE]: Use this when [specific scenario] [WHEN NOT TO USE]: Do NOT use this when [alternative scenario] [OUTPUT FORMAT]: Returns [format] with keys: [list key fields] [EXAMPLE]: For example, to [common use case]: [example call]

Error Response Patterns

Retryable Error

{"error": true,
 "retryable": true,
 "message": "Query timed out",
 "suggestion": "Add date filter"}

Human-Required Error

{"error": true,
 "retryable": false,
 "message": "Auth failed",
 "suggestion": "Admin: update credentials"}

Popular Pre-Built MCP Servers

@anthropic/mcp-server-github
GitHub: repos, PRs, issues, commits — full GH API access
@anthropic/mcp-server-filesystem
Secure filesystem access with configurable path restrictions
mcp-server-postgres
PostgreSQL read/write access with automatic schema introspection
mcp-server-sqlite
SQLite local database access for scripts and tools
@anthropic/mcp-server-brave-search
Web search capability for Claude via Brave Search API
mcp-server-slack
Slack messaging: send messages, read channels, manage threads
🔄 CI/CD Integration — Setup Checklist
Step-by-step checklist for adding Claude to your deployment pipeline

✅ Prerequisites

  • ANTHROPIC_API_KEY added to CI/CD secrets
  • Node.js 18+ in your pipeline runner image
  • CLAUDE.md committed to repo root
  • Pull request write permissions on GitHub Actions
  • Rate limit budget planned (reviews per day estimate)

✅ Pipeline Steps to Add

  • PR review step (on pull_request trigger)
  • Security gate step (blocks merge on CRITICAL)
  • Test gap detection step
  • PR description auto-generation (if body empty)
  • Changelog generation step (on release)

Security Gate Template — Copy/Paste

yaml — minimal security gate
- name: Claude Security Gate
  env:
    ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
  run: |
    git diff origin/${{ github.base_ref }}..HEAD > diff.txt
    
    RESULT=$(claude --no-interactive "
      Security audit this diff for OWASP Top-10 vulnerabilities,
      hardcoded secrets, and auth bypass risks.
      If ANY critical vulnerability found, output: SECURITY_GATE: FAIL
      Otherwise output: SECURITY_GATE: PASS
      $(cat diff.txt)
    ")
    
    echo "$RESULT"
    if echo "$RESULT" | grep -q "SECURITY_GATE: FAIL"; then
      echo "❌ Security gate failed"
      exit 1
    fi
🗓️ Daily Developer Workflow Recipes
What experienced Claude Code users actually type every day

Morning Startup

Run at start of day
claude "Review git log since yesterday, summarize what changed, identify any technical debt introduced, and suggest what needs attention today based on pending work."

Before Creating a PR

Pre-PR checklist command
claude "Prepare this branch for review: 1. Run all tests — fix any failures 2. Run lint — fix all errors 3. Review my staged changes for security and quality issues 4. Generate a PR description with: Summary, Changes, Testing, Breaking Changes 5. Verify new code has adequate test coverage Report final status: READY or what needs attention."

Understanding New Code

For unfamiliar codebases or files
claude "Explain [file/module/system] to me like I'm a senior engineer who just joined this team. Cover: what it does, why it's designed this way, how it connects to the rest of the system, any non-obvious gotchas, and what I should NOT change without careful review."

Performance Investigation

When something is slow
claude "Analyze [file/endpoint/query] for performance issues. Check for: N+1 queries, missing indexes, synchronous blocking operations, unnecessary re-renders, large payload sizes, missing caching opportunities. Prioritize by impact. Suggest fixes with code examples. Estimate performance improvement for each fix."

The "Explain This Error" Template

Universal bug report
Error: [error message] Stack: [stack trace] Expected: [what should happen] Actual: [what does happen] When: [the exact conditions that trigger it] File: [read the relevant file] Top 3 hypotheses for root cause, ranked by likelihood. Fix for highest likelihood hypothesis. Tests that would catch this in future.

Model Selection Guide

TaskRecommended ModelReason
Complex architecture, multi-file refactorClaude Sonnet 4 / Sonnet 4.5Best reasoning for complex tradeoffs
Routine bug fixes, simple featuresClaude Sonnet 4.5Fast + high quality for well-defined tasks
CI/CD subagents, repetitive analysisClaude Haiku 4.510× cheaper, sufficient for scoped tasks
Coordinator agent (multi-agent)Claude Sonnet 4.5Better orchestration decisions
Security audit of critical codeClaude Sonnet 4.5+Thoroughness worth the cost on high-risk
🧠 Core Concepts — Quick Reference
The vocabulary every Claude Code user needs to know
ConceptWhat It IsWhy It Matters
CLAUDE.mdProject config file Claude reads at startup — architecture, conventions, forbidden actions10× better output with a good CLAUDE.md vs. none
Agentic LoopThe observe → plan → act → evaluate cycle Claude runs autonomouslyUnderstanding this helps you write better tasks
Plan ModeClaude proposes implementation plan before starting — you approve or redirectCritical for complex/high-risk tasks
MCPModel Context Protocol — universal standard for connecting Claude to external tools/dataMakes Claude infinitely extensible to your toolchain
Agent SDKPython/TS library for building Claude agents programmatically in your appsEnables production multi-agent systems and pipelines
Slash CommandsCustom task templates stored as .md files in .claude/commands/Turn common tasks into one-keystroke operations
HooksFunctions that intercept tool calls before/after executionSafety gates, audit logs, PII redaction in agents
Context Window200K tokens ≈ entire mid-size codebase in a single sessionClaude can understand your whole project simultaneously
Coordinator/SubagentArchitecture pattern: coordinator orchestrates specialist subagentsMost versatile pattern for complex enterprise workflows
🏆 The 80/20 Rules of Code with Claude