Skip to content

Claude Code Reference: CLI Flags, Shortcuts, CLAUDE.md Templates & Troubleshooting

Last updated:

What’s inside: Complete command reference, troubleshooting guides, and daily checklists.

I need to…Go to
Look up a command10.1 Commands Table
Find keyboard shortcut10.2 Keyboard Shortcuts
Configure settings10.3 Configuration Reference
Fix an error10.4 Troubleshooting
Quick daily reference10.5 Cheatsheet
Set up workflow10.6 Daily Workflow
Copy ready-to-use templatesexamples/ directory: Commands, hooks, agents

Usage tip: Bookmark this section: you’ll reference it often.


Purpose: Quick lookup for all Claude Code information

Source of truth: code.claude.com/docs/en/commands is the official reference and always lists the current set. The tables below mirror it as of Claude Code v2.1.220 (July 2026), with the guide’s own notes and cross-references added. When the two disagree, the official page wins. For launch-time flags rather than in-session commands, see code.claude.com/docs/en/cli-reference and §10.3.

Not every command shows up for every user. Availability depends on platform, plan, and provider: /desktop only appears on macOS and x64 Windows with a Claude subscription, /setup-bedrock only when CLAUDE_CODE_USE_BEDROCK=1 is set, /upgrade never on Enterprise. Type / in a session to see what you actually have.

Notation: <arg> is required, [arg] is optional, aliases follow the command in parentheses.

CommandAction
/clear [name] (/reset, /new)Start a new conversation with empty context. A name labels the previous one in the /resume picker
/resume [session] (/continue)Resume a conversation by ID or name, or open the picker. Background sessions appear marked bg
/branch [name]Branch the conversation at this point and switch into the copy. The original stays reachable via /resume (v2.1.77+)
/fork [prompt]Copy the conversation into a new background session and keep working here. On v2.1.161 to v2.1.211 this launched a forked subagent instead (now /subtask); before that it aliased /branch
/subtask <task>Spawn a forked subagent that inherits the full conversation, works in the background, and reports its result back here (v2.1.212+)
/background [prompt] (/bg)Detach this session to run as a background agent and free the terminal. Monitor with claude agents
/stopStop the attached background session. Transcript and worktree are kept. Use /exit to detach without stopping
/rename [name]Name the session and show it on the prompt bar. Without an argument, generates a name from history
/recapOne-line summary of the current session on demand
/rewind (/checkpoint, /undo)Rewind conversation and/or code to a checkpoint, or summarize from a selected message
/copy [N]Copy the Nth-latest assistant response. With code blocks, opens a picker; press w to write to a file instead
/export [filename]Export the conversation as plain text, to a file or the clipboard
/teleport (/tp)Pull a Claude Code on the web session into this terminal, branch and conversation included
/remote-control (/rc)Make this session drivable from claude.ai or the mobile app
/desktop (/app)Continue the session in the Claude Code Desktop app
/exit (/quit)Exit the CLI. In an attached background session, detaches and leaves it running
CommandAction
/compact [instructions]Summarize the conversation to free context. Optional instructions focus the summary
/context [all]Colored grid of context usage with optimization suggestions. all expands the per-item breakdown in fullscreen
/btw [question]Side question in an ephemeral read-only overlay, no tools, no history pollution. Without a question, reopens the last overlay (v2.1.212+)
/memoryEdit CLAUDE.md files, toggle auto-memory, browse auto-memory entries
/add-dir <path>Add a working directory for file access this session. Most .claude/ config is not discovered from it
/cd <path>Move the session to a new working directory without losing the prompt cache (v2.1.169+)
CommandAction
/model [model]Switch model and save it as the default. Left/right arrows adjust effort. Press s on a row for session-only
/effort [level|auto]Set effort: low, medium, high, xhigh, max, or ultracode. max and ultracode are session-only, auto resets to the model default
/fast [on|off]Toggle fast mode (same model, faster output, higher price)
/plan [description]Enter plan mode, optionally with the task to start on
/goal [condition|clear]Set a completion condition. Claude works across turns until an evaluator confirms it, with a live overlay showing elapsed time, turns, and tokens (v2.1.139+)
/advisor [model|off]Enable the advisor tool: a second model consulted for guidance at key moments. Accepts opus, sonnet, or a model ID (Fable 5 rejected)
/permissions (/allowed-tools)Manage allow, ask, and deny rules; working directories; recent auto mode denials
/fewer-permission-promptsScan transcripts for common read-only Bash and MCP calls, then propose an allowlist for .claude/settings.json. Shipped as /less-permission-prompts in v2.1.111, renamed since
/sandboxToggle sandbox mode on supported platforms
CommandAction
/tasks (/bashes)View and manage this session’s background work, finished subagents included
/batch <instruction>Decompose a codebase-wide change into 5 to 30 units, then run one background subagent per unit in its own worktree, each opening a PR
/workflowsOpen the workflow progress view to watch, pause, resume, or save runs
/loop [interval] [prompt] (/proactive)Run a prompt repeatedly while the session stays open. No interval means Claude self-paces; no prompt runs the maintenance check or .claude/loop.md
/schedule [description] (/routines)Create, update, list, or run routines on Anthropic-managed cloud infrastructure
/deep-research <question>Fan out web searches, cross-check sources, synthesize a cited report. Manual-only since v2.1.218
/autofix-pr [prompt]Spawn a cloud session that watches the current branch’s PR and pushes fixes when CI fails or reviewers comment. Needs the gh CLI
/remote-envChoose the default environment for cloud agents
CommandAction
/diffInteractive viewer for uncommitted changes and per-turn diffs
/code-review [low|medium|high|xhigh|max|ultra] [--fix] [--comment] [target]Review the diff for correctness bugs and cleanups. --fix applies findings, --comment posts inline PR comments, ultra runs the cloud review. Runs as a background subagent since v2.1.218
/review [PR]Fast single-pass read-only review of a GitHub PR. No argument lists open PRs. Trailing text becomes extra review instructions
/ultrareview [PR or branch]Deep multi-agent cloud review. Now an alias of /code-review ultra. 3 free runs on Pro and Max, then usage credits
/security-reviewAnalyze the branch diff against origin’s default branch for injection, auth, and data-exposure risks. Needs an origin remote
/simplify [target]Four parallel agents review the changed code for reuse, simplification, efficiency, and altitude, then apply fixes. Since v2.1.154 it no longer hunts correctness bugs, that is /code-review
/verifyConfirm a change works by building the app, running it, and observing the result instead of trusting tests (v2.1.145+)
/runLaunch and drive the project’s app to see a change working (v2.1.145+)
/run-skill-generatorWrite a per-project skill that teaches /run and /verify how to build, launch, and drive your app (v2.1.145+)
CommandAction
/config [key=value ...] (/settings)Open the settings interface, or set a key directly: /config theme=dark. /config --help lists every settable key
/initGenerate a starter CLAUDE.md. ⚠️ output is LLM-generated; review and prune before committing (ETH Zürich research shows auto-generated context files reduce agent task success by ~3% and add 20%+ inference cost). CLAUDE_CODE_NEW_INIT=1 adds an interactive flow covering skills, hooks, personal memory
/hooksView hook configurations for tool events
/mcp [reconnect <server>|enable|disable [<server>|all]]Manage MCP connections and OAuth. In -p mode, prints a text status summary
/plugin [subcommand]Manage plugins. Subcommands: list, install, enable, disable
/reload-plugins [--force]Reload active plugins without restarting. Skips and warns when the reload would invalidate the prompt cache, unless forced
/reload-skillsRe-scan skill and command directories so on-disk changes take effect mid-session (v2.1.152+)
/skillsList skills. Filter by typing, sort by token count with t, cycle visibility with Space
/agentsPrints a reminder to ask Claude to manage subagents, or edit .claude/agents/ directly. Was an interactive manager before v2.1.198
/keybindingsOpen ~/.claude/keybindings.json
/statuslineConfigure the status line, or auto-configure it from your shell prompt
/terminal-setupConfigure terminal keybindings for Shift+Enter. Only appears in terminals that need it
/setup-bedrockInteractive Amazon Bedrock wizard. Visible only with CLAUDE_CODE_USE_BEDROCK=1
/setup-vertexInteractive Google Cloud Agent Platform wizard. Visible only with CLAUDE_CODE_USE_VERTEX=1
/web-setupConnect your GitHub account to Claude Code on the web using local gh credentials
/install-github-appInstall the Claude GitHub App for a repo, optionally wiring up GitHub Actions workflows and secrets
/install-slack-appInstall the Claude Slack app through a browser OAuth flow
/chromeConfigure Claude in Chrome settings
/design-loginAuthorize design-system access for /design-sync with your claude.ai account
/design-sync [hint]Convert the repo’s React design system and upload it to Claude Design so generated designs use your real components. First sync can take hours on a large repo. Anthropic API only
/claude-api [migrate|managed-agents-onboard]Load Claude API reference material for your language. migrate upgrades existing API code to a newer model, managed-agents-onboard walks through creating a Managed Agent
/dataviz [request]Chart and dashboard design guidance with a runnable colorblind and contrast validator (v2.1.198+)
CommandAction
/themeChange the color theme: auto, light, dark, daltonized, ANSI, or custom themes from ~/.claude/themes/
/color [color|default]Set the prompt bar color for the session. No argument picks one at random
/tui [default|fullscreen]Set the terminal renderer and relaunch into it with the conversation intact
/focusToggle focus view: last prompt, a one-line tool-call summary with diffstats, final response. Fullscreen only
/scroll-speedInteractive slider for mouse wheel speed, with a scrollable ruler for live preview. Fullscreen only, not in the JetBrains terminal
/voice [hold|tap|off]Toggle voice dictation or set its mode. Requires a claude.ai account
/ideManage IDE integrations and show status
CommandAction
/doctor (/checkup)Full setup checkup: install health, PATH, unparseable settings, unused skills and MCP servers versus their context cost, slow hooks, CLAUDE.md bloat, version drift. Reports first, asks before changing anything (v2.1.205+)
/skill-doctorReport visible skill context cost and never-invoked skills. Excludes bundled and enterprise skills, requires feature-flag fetching, and is unavailable through Remote Control. Run it in the terminal (v2.1.252+)
/debug [description]Turn on debug logging for the session and troubleshoot from the debug log
/heapdumpWrite a heap snapshot and memory breakdown to ~/Desktop for diagnosing high memory use. ⚠️ contains the full conversation and credentials, never share it
/statusSettings interface on the Status tab: version, model, account, connectivity. Works while Claude is responding
/usage (/cost, /stats)Session cost, plan limits, activity stats. On paid plans, breaks usage down by skill, subagent, plugin, and MCP server
/insightsReport analyzing your sessions: project areas, interaction patterns, friction points
/release-notesInteractive changelog picker. Since v2.1.208 the notes stay out of the conversation Claude sees
/helpShow help and available commands
/bug [report] (/share)Report a bug or share the conversation, with a consent screen. Falls back to a local archive under ~/.claude/feedback-bundles/ on third-party providers (v2.1.212+)
/feedback [report]Send product feedback. Same dialog and sending rules as /bug
/team-onboardingGenerate a teammate ramp-up guide from 30 days of sessions, commands, and MCP usage
/powerupInteractive lessons with animated demos for discovering features
CommandAction
/loginSign in to your Anthropic account
/logoutSign out
/upgradeOpen the plan upgrade page. Hidden on Enterprise
/usage-creditsConfigure usage credits, or request them from your admin when you hit a limit. Previously /extra-usage
/privacy-settingsView and update privacy settings. Pro and Max only
/passesShare a free week of Claude Code. Only visible if your account is eligible
/mobile (/ios, /android)QR code for the Claude mobile app
/stickersOrder Claude Code stickers
/radioOpen Claude FM lo-fi radio, or print the stream URL. Not on Bedrock, Agent Platform, Foundry, or Claude Platform on AWS

MCP servers add their own commands as /mcp__<server>__<prompt>, discovered from connected servers.

Removed, renamed, and commands that never existed

Section titled “Removed, renamed, and commands that never existed”
CommandStatus
/executeNot a Claude Code command. Absent from the official commands reference and from the entire CHANGELOG. Earlier versions of this guide listed it by mistake. Exit plan mode by approving the plan or pressing Shift+Tab
/less-permission-promptsRenamed /fewer-permission-prompts. The old name is what shipped in v2.1.111 and still appears in that release’s notes
/extra-usageRenamed /usage-credits
/pr-commentsRemoved in v2.1.91. Ask Claude to fetch PR comments instead
/vimRemoved in v2.1.92. Use /config → Editor mode
/output-styleDeprecated Oct 2025. Use /config → “Preferred output style” (Default / Explanatory / Learning)
Ctrl+DNot a command, the keyboard shortcut for exiting. See §10.2
ActionShortcut
Run shell command!command
Reference file@filename
Cancel operationCtrl+C
Search historyCtrl+R
Dismiss suggestionEsc
ShortcutAction
EnterSend message
Shift+EnterNew line in message
Ctrl+CCancel current operation
Ctrl+DExit Claude Code
Ctrl+RSearch command history
Ctrl+LClear screen (keeps context)
Ctrl+BRun command in background
EscStop Claude mid-action (context preserved)
Esc×2 (double-tap)Open rewind menu (same as /rewind)
ShortcutAction
Ctrl+AJump to beginning of line
Ctrl+EJump to end of line
Ctrl+WDelete previous word
Ctrl+GOpen plan in external text editor for editing
TabAutocomplete file paths
/ Navigate command history
ShortcutAction
Alt+T (Option+T on macOS)Toggle thinking mode on/off
Ctrl+OView thinking blocks
ShortcutAction
Space (hold)Push-to-talk: hold to speak, release to send (default binding)

Rebinding: The voice:pushToTalk binding is configurable in ~/.claude/keybindings.json (v2.1.71+). Add a custom binding if Space conflicts with your workflow:

{
"voice:pushToTalk": "ctrl+space"
}

Toggle voice on/off with /voice. The push-to-talk binding only activates when voice mode is active.

ShortcutAction
Shift+DownCycle through active teammates (in-process mode)
Ctrl+TToggle task list visibility
EnterView selected teammate’s session
EscapeInterrupt current turn, return to prompt
FlagsPurposeExample
-c -p "msg"Resume session + single promptclaude -c -p "run tests"
-r <id> -pResume specific session + promptclaude -r abc123 -p "check status"
-p -pNon-interactive automationclaude -p -p "lint fix" < errors.txt

Note: Combine resume flags with -p for scripting and CI/CD workflows.

LocationScopeCommitted
~/.claude/CLAUDE.mdAll projects (global)N/A
/project/CLAUDE.mdThis project (shared)✅ Yes
/project/CLAUDE.local.mdThis project (local overrides)❌ No (.gitignored)
/project/.claude/CLAUDE.mdPersonal project config❌ No
Parent/child directoriesAuto-loaded in monoreposDepends on location
FilePurposeCommitted
settings.jsonHook configuration✅ Yes
settings.local.jsonPermission overrides❌ No
PatternMatches
Bash(git *)Any git command
Bash(npm test)Exactly npm test
EditAll file edits
WriteAll file writes
WebSearchWeb search
mcp__serena__*All Serena tools
Read(file_path:*.env*)Block reading any .env* file path
Edit(file_path:*.pem)Block editing .pem certificates
Bash(command:*rm -rf*)Block destructive bash commands

Complete reference for all Claude Code command-line flags, subcommands, and startup environment variables.

FlagShortDescription
--continue-cContinue the most recent conversation in the current directory
--resume <ID>-rResume a specific session by UUID or name, or show interactive picker
--from-pr <NUMBER|URL>Resume sessions linked to a specific GitHub PR
--fork-sessionCreate a new session ID when resuming (use with --resume or --continue)
--session-id <UUID>Use a specific session UUID
--no-session-persistenceDisable session persistence (print mode only)
--name <NAME>-nSet a display name for the session, shown in /resume and the terminal title
--remoteCreate a new web session on claude.ai
--teleportResume a web session in your local terminal
--bgStart the session as a background agent and return immediately. Prints session ID and management commands
--exec <CMD>Run a shell command as a PTY-backed background job instead of starting a Claude session. Use with --bg
FlagShortDescription
--model <NAME>Set model with alias (sonnet, opus, haiku) or full model ID
--fallback-model <NAME>Auto-fallback model when default is overloaded (print mode only)
--effort <LEVEL>Set effort level: low, medium, high, xhigh, max. Available levels depend on the model
--betas <LIST>Beta headers to include in API requests (API key users only)
FlagShortDescription
--print-pPrint response and exit without interactive mode (headless/SDK mode)
--output-format <FORMAT>Output format: text, json, stream-json
--input-format <FORMAT>Input format: text, stream-json
--json-schema <SCHEMA>Get validated JSON matching schema (print mode only)
--include-partial-messagesInclude partial streaming events (requires --print and stream-json)
--include-hook-eventsInclude hook lifecycle events in output stream. Requires --output-format stream-json
--prompt-suggestionsEmit a predicted next prompt after each turn. Requires --print, --output-format stream-json, --verbose
--replay-user-messagesRe-emit user messages from stdin back on stdout for acknowledgment. Requires --input-format stream-json and --output-format stream-json
--verboseEnable verbose logging with full turn-by-turn output
FlagShortDescription
--dangerously-skip-permissionsSkip ALL permission prompts (use with extreme caution)
--allow-dangerously-skip-permissionsEnable permission bypassing as an option without activating it
--permission-mode <MODE>Begin in specified mode: default, plan, acceptEdits, bypassPermissions
--allowedTools <TOOLS>Tools that execute without prompting (permission rule syntax)
--disallowedTools <TOOLS>Tools removed from model context entirely
--tools <TOOLS>Restrict which built-in tools Claude can use (use "" to disable all)
--permission-prompt-tool <TOOL>MCP tool to handle permission prompts in non-interactive mode
FlagShortDescription
--system-prompt <TEXT>Replace entire system prompt with custom text
--system-prompt-file <PATH>Load system prompt from file, replacing default (print mode only)
--append-system-prompt <TEXT>Append custom text to default system prompt
--append-system-prompt-file <PATH>Append file contents to default prompt (print mode only)
--exclude-dynamic-system-prompt-sectionsMove per-machine sections (working dir, env info, memory paths) into the first user message. Improves prompt-cache reuse across different users running the same task. Use with -p for scripted multi-user workloads
FlagShortDescription
--agent <NAME>Specify an agent for the current session
--agents <JSON>Define custom subagents dynamically via JSON
--teammate-mode <MODE>Set agent team display: auto, in-process, tmux
FlagShortDescription
--mcp-config <PATH|JSON>Load MCP servers from JSON file or inline JSON string
--strict-mcp-configOnly use MCP servers from --mcp-config, ignore all others
--plugin-dir <PATH>Load plugins from a directory or .zip archive for this session only (repeatable). Multiple --plugin-dir flags supported. (.zip since v2.1.128)
--plugin-url <url>Fetch a plugin .zip archive from a URL and load it for the current session. Useful for CI pipelines sharing plugins via artifact storage. (v2.1.129)
FlagShortDescription
--add-dir <PATH>Add additional working directories for Claude to access
--worktree-wStart Claude in an isolated git worktree (branched from HEAD)
--tmuxCreate a tmux session for the worktree. Requires --worktree. Pass --tmux=classic for traditional tmux
FlagShortDescription
--max-budget-usd <AMOUNT>Maximum dollar amount for API calls before stopping (print mode only)
--max-turns <NUMBER>Limit number of agentic turns (print mode only)
FlagShortDescription
--chromeEnable Chrome browser integration for web automation
--no-chromeDisable Chrome browser integration for this session
--ideAutomatically connect to IDE on startup if exactly one valid IDE is available
--channelsEnable MCP channels (Research Preview). Supports claude.ai OAuth and API key auth. Managed orgs require channelsEnabled: true in managed-settings. (v2.1.128)
--remote-control--rcStart an interactive session with Remote Control enabled so you can also control it from claude.ai or the Claude app
--remote-control-session-name-prefix <PREFIX>Prefix for auto-generated Remote Control session names. Defaults to machine hostname
FlagShortDescription
--initRun initialization hooks and start interactive mode
--init-onlyRun initialization hooks and exit without starting a session
--maintenanceRun maintenance hooks and exit
FlagShortDescription
--debug <CATEGORIES>Enable debug mode with optional category filtering (e.g., "api,hooks")
--debug-file <PATH>Write debug logs to a specific file path. Implicitly enables debug mode. Takes precedence over CLAUDE_CODE_DEBUG_LOGS_DIR
--dangerously-load-development-channelsEnable channels not on the approved allowlist, for local development. Requires confirmation
FlagShortDescription
--bareMinimal mode: skip auto-discovery of hooks, skills, plugins, MCP servers, auto memory, and CLAUDE.md. Scripted calls start faster. Sets CLAUDE_CODE_SIMPLE
--settings <PATH|JSON>Path to settings JSON file or inline JSON string to load
--setting-sources <LIST>Comma-separated sources to load: user, project, local
--disable-slash-commandsDisable all skills and slash commands for this session
FlagShortDescription
--version-vOutput the current version number
--help-hShow help information

Top-level commands run as claude <subcommand>:

SubcommandDescription
claude "query"Start REPL with an initial prompt
claude agentsOpen Agent View: lists all sessions (running / waiting / done) with peek and inline reply (v2.1.139+)
claude attach <ID>Attach to a background session in the current terminal
claude auto-mode defaultsPrint the built-in auto mode classifier rules as JSON. Use claude auto-mode config to see effective config with settings applied
claude auth login / logout / statusManage Claude Code authentication
claude daemon statusPrint the background-session supervisor state, version, socket directory, and worker count. Exits 1 if supervisor is not running
claude daemon stop --anyStop the background-session supervisor and the sessions it hosts. Pass --keep-workers to leave background sessions running
claude doctorRun diagnostics from the command line
claude installInstall or switch Claude Code native builds
claude logs <ID>Print recent output from a background session
claude mcp add / remove / list / get / enableConfigure MCP servers
claude pluginManage Claude Code plugins
claude remote-controlStart a Remote Control server to control Claude Code from claude.ai or the Claude app
claude respawn <ID>Restart a background session (running or stopped) with its conversation intact. Use --all to restart all running sessions
claude rm <ID>Remove a background session from the list. The conversation transcript stays on disk for /resume
claude setup-tokenCreate a long-lived token for subscription usage
claude stop <ID>Stop a background session (alias: claude kill)
claude update / claude upgradeUpdate to the latest version
claude project purge [path]Delete all Claude Code state for a project: transcripts, tasks, file history, config entry. Options: --dry-run, -y/--yes, -i/--interactive, --all. (v2.1.126)
claude ultrareview [target]Run /ultrareview non-interactively from CI/scripts. target: PR number, branch, or current branch if omitted. --json for machine-readable output. Exits 0 on completion, 1 on failure. (v2.1.120)
claude plugin pruneRemove orphaned auto-installed plugin dependencies. Cascade with claude plugin uninstall --prune. (v2.1.121)
claude plugin details <name>Show plugin component inventory (skills, agents, commands, hooks, MCP servers) and projected per-session token cost. (v2.1.139)

Set these in your shell before launching Claude Code (these cannot be configured via settings.json):

VariableDescription
CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS=1Enable experimental agent teams
CLAUDE_CODE_TMPDIROverride temp directory for internal files
CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1Enable additional directory CLAUDE.md loading
DISABLE_AUTOUPDATER=1Disable automatic updates
CLAUDE_CODE_EFFORT_LEVELControl thinking depth for extended thinking models
USE_BUILTIN_RIPGREP=0Use system ripgrep instead of built-in (useful on Alpine Linux)
CLAUDE_CODE_SIMPLEEnable simple mode (Bash + Edit tools only, no agents/hooks/MCP)
CLAUDE_BASH_NO_LOGIN=1Skip login shell invocation for BashTool
CLAUDE_CODE_SESSION_IDUnique identifier for the current Claude Code session. Passed to all Bash tool subprocess environments. Matches session_id in hook stdin JSON. Use for correlating tool output with sessions in observability pipelines. (v2.1.132)
CLAUDE_CODE_DISABLE_ALTERNATE_SCREEN=1Opt out of the fullscreen alternate-screen renderer. Terminal output stays in the native scrollback buffer instead of the alternate screen. Use in environments that don’t support alternate screen (some log-capture setups, embedded terminals). (v2.1.132)
CLAUDE_CODE_PACKAGE_MANAGER_AUTO_UPDATE=1When set, Homebrew or WinGet auto-upgrades Claude Code in the background and prompts to restart when a new version is available. (v2.1.129)

For the full environment variable reference (190+ vars across 17 categories, including all ANTHROPIC_*, CLAUDE_CODE_*, DISABLE_*, and OTEL_* vars), see Settings Reference: Environment Variables.

Common Combinations:

Terminal window
# CI/CD mode - non-interactive with auto-accept
claude -p "fix linting errors" --dangerously-skip-permissions
# JSON output for scripting
claude -p "analyze code quality" --output-format json
# Economic analysis with Haiku
claude -p "review this file" --model haiku
# Allow access to a directory outside CWD
claude --add-dir ./src/components
# Plan mode for safety
claude --permission-mode plan
# Multi-directory project
claude --add-dir ../shared-lib ../utils ../config
# Limit agentic turns in automation
claude -p "refactor this module" --max-turns 10
# Resume specific session non-interactively
claude -r abc123 -p "summarize progress"

Safety Guidelines:

FlagRisk LevelUse When
--dangerously-skip-permissionsHighOnly in CI/CD, never on production
--allowedToolsSafeRestricting tool access
--disallowedToolsSafeBlocking specific tools
--permission-mode planSafeRead-only exploration
--debugMediumTroubleshooting (verbose logs)

Interactive Troubleshooting: Use the /diagnose command for guided, interactive problem-solving. It auto-scans your environment and provides targeted solutions. See examples/commands/diagnose.md.

Use this symptom-based guide for rapid issue identification and resolution:

SymptomLikely CauseQuick FixPrevention
”Context too long” errorSession accumulated too much context/compact first, then /clear if neededCompact regularly at 70%
Slow/delayed responsesHigh context usage (>75%)Check /status, run /compactMonitor context with /status
”Rate limit exceeded”API throttling from frequent requestsWait 2 minutes, use --model haiku for simple tasks, or use cc-copilot-bridge for flat-rate accessBatch operations, use /compact, consider Copilot Pro
Claude forgets instructionsContext overflow, CLAUDE.md lostCreate checkpoint, /clear, reload CLAUDE.mdKeep CLAUDE.md concise (<500 lines)
MCP server not connectingServer crashed or config errorclaude mcp list, check paths, restart serverTest servers after config changes
Permission prompts every timeTool not in allowedToolsAdd pattern to settings.json allowedToolsUse wildcards: Bash(git *)
Changes not taking effectCached configurationRestart Claude Code sessionUse /exit before config changes
Session won’t resumeCorrupted session fileStart fresh with /clearExit cleanly with /exit or Ctrl+D

Quick Diagnosis Flow:

  1. Check context: /status → If >70%, run /compact
  2. Check connectivity: Try simple command → If fails, check network
  3. Check configuration: claude mcp list → Verify MCP servers
  4. Check permissions: Review error message → Add to allowedTools if needed
  5. Still failing: /doctor → Run diagnostics and verify system health
SymptomCauseSolution
”Context too long”Used 100% context/clear or /compact
Slow responsesHigh context usage/compact
”Permission denied”Security settingsCheck settings.local.json
Hook not runningRegistration errorCheck settings.json matcher
MCP tool not foundServer not runningCheck mcp.json config
Agent not foundFile namingCheck .claude/agents/
Command not foundPath errorCheck .claude/commands/
Unexpected API charges despite active subscriptionANTHROPIC_API_KEY set in shell or .env bypasses subscriptionRun echo $ANTHROPIC_API_KEY: if it returns a value, Claude Code is billing at API rates. Unset it from your shell profile to restore subscription billing. Run claude /cost to check spend in the current session.
Context LevelRecommended Action
0-50%Continue normally
50-75%Be more specific in queries
75-90%Use /compact
90%+Use /clear

“Tool execution failed”

  • Check tool permissions in settings.local.json
  • Verify command syntax
  • Check for missing dependencies

“Agent not available”

  • Verify agent file exists in .claude/agents/
  • Check YAML frontmatter syntax
  • Restart Claude Code session

“Hook blocked operation”

  • Check hook exit code (2 = blocked)
  • Review hook error message
  • Adjust hook rules if needed

“Unexpected API charges despite subscription”

  • Run echo $ANTHROPIC_API_KEY in your shell: any output means Claude Code is routing via API billing, not your subscription
  • Remove the key from ~/.zshrc, ~/.bashrc, or .env files if subscription billing is intended
  • Use claude /cost (or /usage since v2.1.118) to check real-time spend in the current session
  • Use npx ccusage to review cross-session historical spend
  • See §9.13: The Interactive/Programmatic Billing Split for the full billing model and June 15 changes

Common MCP Errors and Solutions

API Error 400: "tools.11.custom.name: String should match pattern '^[a-zA-Z0-9_-]{1,64}'"

Cause: MCP server name contains invalid characters.

Solution:

  • Server names must only contain: letters, numbers, underscores, hyphens
  • Maximum 64 characters
  • No special characters or spaces

Example:

Terminal window
# ❌ Wrong
claude mcp add my-server@v1 -- npx server
# ✅ Correct
claude mcp add my-server-v1 -- npx server
MCP server 'my-server' not found

Cause: Server not properly registered or wrong scope.

Solution:

  1. Check scope settings (local/user/project)
    Terminal window
    claude mcp list # Verify server is listed
  2. Ensure you’re in the correct directory for local scope
  3. Restart Claude Code session
  4. Re-add server if needed:
    Terminal window
    claude mcp add my-server -s user -- npx @my/server
Error: Cannot find module 'C:UsersusernameDocuments'

Cause: Backslashes in Windows paths not properly escaped.

Solution:

Terminal window
# ❌ Wrong
claude mcp add fs -- npx -y @modelcontextprotocol/server-filesystem C:\Users\username\Documents
# ✅ Correct - Use forward slashes
claude mcp add fs -- npx -y @modelcontextprotocol/server-filesystem C:/Users/username/Documents
# ✅ Correct - Escape backslashes
claude mcp add fs -- npx -y @modelcontextprotocol/server-filesystem "C:\\Users\\username\\Documents"

Enable Debug Mode:

Terminal window
# Debug all MCP connections
claude --mcp-debug
# View MCP status inside Claude Code
/mcp

View Log Files:

Terminal window
# macOS
tail -f ~/Library/Logs/Claude/mcp*.log
# Linux
tail -f ~/.local/share/claude/logs/mcp*.log
# Windows (PowerShell)
Get-Content "$env:APPDATA\Claude\logs\mcp*.log" -Wait -Tail 50

Manual Server Test:

Terminal window
# Test if server works standalone
npx -y @modelcontextprotocol/server-filesystem ~/Documents
# Expected: Server should start and output JSON-RPC messages
# If it crashes immediately, check server logs

Quick Diagnostic Commands:

Terminal window
# List all configured servers
claude mcp list
# Test specific server
claude --mcp-debug -p "List available tools"
# Remove and re-add server
claude mcp remove my-server
claude mcp add my-server -s user -- npx @my/server

Connection Failed: Common Causes

ErrorCauseSolution
ECONNREFUSEDServer not runningCheck mcp.json command is correct
Timeout after 30sSlow initializationIncrease timeout or check server logs
Module not foundMissing dependenciesRun npm install in server directory
Permission deniedFile accessCheck file permissions on server executable
ENOENTServer binary not foundVerify npx/npm is in PATH
Invalid JSONServer output malformedCheck server version compatibility

Serena MCP specific issues:

Terminal window
# Index not found
serena list-memories
# If empty, re-index:
# In your project, ask Claude: "Index this project with Serena"
# Session not persisting
# Check mcp.json has correct data directory:
{
"mcpServers": {
"serena": {
"command": "npx",
"args": ["-y", "@serenaai/serena-mcp"],
"env": {
"SERENA_DATA_DIR": "/absolute/path/to/.serena"
}
}
}
}

Context7 MCP issues:

Terminal window
# Documentation not found
# Ensure you're searching for official libraries:
# ✅ "React useState documentation"
# ❌ "my-custom-lib documentation" (not in Context7)
# Slow lookups
# Context7 fetches from official docs - network dependent
# Check your internet connection

Sequential Thinking MCP issues:

Terminal window
# "Sequential not responding"
# Sequential uses significant compute - expect 10-30s responses
# Not an error, just be patient
# Quality seems off
# Sequential works best with specific, well-defined problems
# ✅ "Debug why user authentication fails on mobile"
# ❌ "Make the app better"

Pattern matching problems:

// ❌ Wrong - too specific
{
"allowedTools": ["Bash(npm test)"]
}
// This ONLY allows exactly "npm test"
// ✅ Right - use wildcards
{
"allowedTools": ["Bash(npm *)"]
}
// This allows any npm command

Common permission patterns:

{
"allowedTools": [
"Bash(git *)", // All git commands
"Bash(npm *)", // All npm commands
"Bash(pytest *)", // All pytest commands
"Edit", // All file edits
"Write", // All file writes
"Read", // All file reads
"mcp__serena__*", // All Serena tools
"mcp__context7__*", // All Context7 tools
"Task" // Allow agent delegation
]
}

Claude stops responding mid-task:

Possible causes:

  1. Network interruption - Check your internet connection
  2. API rate limit - Wait 1-2 minutes and retry
  3. Context exhausted - Use /compact or /clear
  4. Long-running operation - Some MCP operations take 30s+

Workaround for long operations:

Terminal window
# Instead of:
"Analyze all 500 files in the codebase"
# Break into chunks:
"Analyze files in /src/components/ first"
"Now analyze /src/utils/"
"Finally analyze /src/services/"

Windows-specific problems:

Terminal window
# npm global install fails
# Run PowerShell as Administrator
npm install -g @anthropic-ai/claude-code
# PATH not updated
# Manually add to PATH:
$env:Path += ";$env:APPDATA\npm"
# Permission errors
# Check antivirus isn't blocking Node.js

macOS-specific problems:

Terminal window
# "Command not found" after install
# Check shell config loaded:
source ~/.zshrc # or ~/.bashrc
# Permission denied on /usr/local
# Don't use sudo with npm
# Fix permissions:
sudo chown -R $(whoami) /usr/local
# curl install blocked
# Check firewall/VPN settings

Linux-specific problems:

Terminal window
# npm not found
# Install Node.js first:
curl -fsSL https://deb.nodesource.com/setup_lts.x | sudo -E bash -
sudo apt-get install -y nodejs
# Global install permission issues
# Configure npm to use home directory:
mkdir ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc
source ~/.bashrc

Diagnostic scripts for instant troubleshooting. Get them from:

⚠️ Nuclear option for corrupted installations. Use when all else fails.

Get the scripts from:

When to use clean reinstall:

  • Mysterious errors that persist after normal troubleshooting
  • Corrupted configuration files
  • Breaking changes after Claude Code updates
  • Migration to new machine (export/import workflow)

What gets deleted:

  • ✓ Claude Code binary and npm packages
  • ✓ Downloaded models and cache
  • ✓ Local session data
  • ⚠️ Config file (optional - backed up by default)

What survives:

  • ✓ Project-level .claude/ folders
  • ✓ Project CLAUDE.md files
  • ✓ Custom agents, skills, commands, hooks (in projects)
  • ✓ MCP server configurations (in mcp.json)
╔══════════════════════════════════════════════════════════╗
║ CLAUDE CODE CHEATSHEET ║
╠══════════════════════════════════════════════════════════╣
║ ║
║ ESSENTIAL COMMANDS ║
║ ───────────────── ║
║ /help Show commands /clear Fresh start ║
║ /status Session info /compact Save context ║
║ /plan Safe mode /rewind Undo changes ║
║ /exit Quit Ctrl+C Cancel ║
║ ║
║ QUICK ACTIONS ║
║ ───────────── ║
║ !command Run shell @file Reference file ║
║ Ctrl+R Search ↑/↓ History ║
║ ║
║ CONTEXT MANAGEMENT ║
║ ────────────────── ║
║ 🟢 0-50% Work freely ║
║ 🟡 50-75% Be selective ║
║ 🔴 75-90% /compact now ║
║ ⚫ 90%+ /clear required ║
║ ║
║ PERMISSION MODES ║
║ ──────────────── ║
║ Default Ask before changes ║
║ Auto-accept Execute without asking ║
║ Plan Mode Read-only exploration ║
║ ║
║ CONFIGURATION ║
║ ───────────── ║
║ ~/.claude/CLAUDE.md Global settings ║
║ /project/CLAUDE.md Project settings ║
║ .claude/settings.json Hooks config ║
║ .claude/settings.local.json Permission overrides ║
║ ║
║ .claude/ FOLDER ║
║ ─────────────── ║
║ agents/ Custom agents commands/ Slash commands ║
║ hooks/ Event scripts rules/ Auto-load rules ║
║ skills/ Knowledge modules ║
║ ║
║ THINKING MODE (Opus 4.6+: adaptive depth, xhigh in 4.8+) ║
║ ───────────────────────────────────────── ║
║ Alt+T Toggle on/off Current session ║
║ /config Global setting Persists across sessions ║
║ Note: "ultrathink" keywords are now cosmetic only ║
║ ║
║ MCP SERVERS ║
║ ─────────── ║
║ Serena Semantic code analysis ║
║ Context7 Library documentation ║
║ Sequential Structured reasoning ║
║ Postgres Database queries ║
║ Playwright Browser automation ║
║ ║
║ HOOKS (events) ║
║ ────────────── ║
║ PreToolUse Before tool (security) ║
║ PostToolUse After tool (format, log) ║
║ UserPromptSubmit On message (enrich context) ║
║ ║
║ WORKFLOW ║
║ ──────── ║
║ Describe → Analyze → Review → Accept/Reject → Verify ║
║ ║
║ BEST PRACTICE: Always read the diff before accepting! ║
║ ║
╚══════════════════════════════════════════════════════════╝
┌─────────────────────────────────────────────────────────────┐
│ DAILY WORKFLOW │
├─────────────────────────────────────────────────────────────┤
│ │
│ MORNING (Setup) │
│ ─────────────── │
│ □ Git pull latest changes │
│ □ Review context with /status │
│ □ Load project memory (/sc:load if using Serena) │
│ □ Review yesterday's progress │
│ │
│ WORK SESSION │
│ ──────────── │
│ □ Define task clearly before starting │
│ □ Use TodoWrite for multi-step work │
│ □ Commit after each completed task │
│ □ /compact when context >70% │
│ □ Take breaks every 90 minutes │
│ │
│ END OF DAY │
│ ────────── │
│ □ Commit all work in progress │
│ □ Save session (/sc:save) │
│ □ Note blockers or next steps │
│ □ Push to remote │
│ │
└─────────────────────────────────────────────────────────────┘

Use this before sending complex requests:

□ WHAT: Clear deliverable described?
□ WHERE: File paths/locations specified?
□ HOW: Constraints/approach mentioned?
□ WHY: Context for decision-making?
□ VERIFY: Success criteria defined?

Example applying checklist:

❌ Vague: "Add user authentication"
✅ Complete:
"Add JWT authentication to the /api/login endpoint.
- WHERE: src/api/auth/login.ts
- HOW: Use jsonwebtoken library (already in deps),
bcrypt for password comparison
- CONSTRAINTS: Token expires in 24h, include userId and role
- VERIFY: Test with wrong password, expired token, invalid token"

💡 Production-Ready Examples: For complete, battle-tested templates including advanced commands (/pr, /release-notes, /sonarqube) and security hooks, see the examples/ directory. The templates below are minimal starting points.

---
name: your-agent-name
description: Use this agent when [specific trigger]
model: sonnet
tools: Read, Write, Edit, Bash, Grep, Glob
skills: []
---
# Agent Name
## Role Definition
You are an expert in [domain].
## Activation Triggers
Use this agent when:
- [Trigger 1]
- [Trigger 2]
## Methodology
1. [Step 1]
2. [Step 2]
3. [Step 3]
## Output Format
[Expected deliverables]
## Examples
[Concrete usage examples]
---
name: skill-name
description: Expert guidance for [domain]
allowed-tools: Read Grep Bash
argument-hint: "[--option] <required_arg>" # if the skill accepts $ARGUMENTS
---
# Skill Name
## Expertise Areas
- [Area 1]
- [Area 2]
## Methodology
1. [Step 1]
2. [Step 2]
## Checklists
- [ ] [Check 1]
- [ ] [Check 2]
## Examples
[Good and bad patterns]
---
description: Brief description of what this command does
argument-hint: "<first_arg> [second_arg] [--flag]"
---
# Command Name
## Purpose
[What this command does]
## Process
1. **Step 1**: [Instructions]
2. **Step 2**: [Instructions]
## Arguments
- $ARGUMENTS[0] (or $0): First argument - [How to handle]
- $ARGUMENTS[1] (or $1): Second argument - [How to handle]
## Output Format
[Expected output]
#!/bin/bash
INPUT=$(cat)
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""')
# Block dangerous patterns
[[ "$COMMAND" =~ "dangerous-pattern" ]] && { echo "BLOCKED" >&2; exit 2; }
exit 0
#!/bin/bash
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // ""')
# Auto-format
[[ "$FILE_PATH" =~ \.(ts|tsx)$ ]] && npx prettier --write "$FILE_PATH" 2>/dev/null
exit 0
#!/bin/bash
CONTEXT="[Custom context here]"
cat << EOF
{"hookSpecificOutput":{"additionalContext":"$CONTEXT"}}
EOF
exit 0
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [{"type": "command", "command": ".claude/hooks/security.sh", "timeout": 5000}]
}
],
"PostToolUse": [
{
"matcher": "Edit|Write",
"hooks": [{"type": "command", "command": ".claude/hooks/format.sh"}]
}
],
"UserPromptSubmit": [
{
"matcher": "",
"hooks": [{"type": "command", "command": ".claude/hooks/context.sh"}]
}
]
}
}
{
"permissions": {
"allow": [
"Bash(git *)",
"Bash(npm test)",
"Bash(pnpm *)",
"Edit",
"Write"
],
"deny": [
"Bash(rm -rf *)",
"Bash(sudo *)"
],
"ask": [
"Bash(npm publish)",
"Bash(git push --force)"
]
}
}
# Project Name
## Tech Stack
- [Technology 1]
- [Technology 2]
## Code Conventions
- [Convention 1]
- [Convention 2]
## Architecture
- [Pattern 1]
- [Pattern 2]
## Commands
- `npm run dev` - Start development
- `npm test` - Run tests

Quick jump: Why Complementarity · Tool Matrix · Practical Workflows · Integration Patterns


Reading time: 10 minutes

Skill level: Intermediate

Goal: Chain Claude Code with the right AI tools for optimal workflows

TL;DR: Claude Code excels at contextual reasoning and multi-file implementation. Combine it with Perplexity (research), Gemini (images), Kimi (slides), and NotebookLM (synthesis) for a complete AI-powered development workflow.