Step 1
Every route installs the same native binary. They differ in auto-update, whether Node.js is needed, and which interface you work in.
Older tutorials tell you to install Node.js first. Today only the npm route needs Node.js 22 or later; on an older Node, npm prints an EBADENGINE warning and the install still completes.
On shared home directories (NFS, common on HPC clusters), a running session keeps reading the executable. An in-place npm upgrade on another node deletes the old binary, and the running session exits with Bus error. On clusters, install the binary on local disk, or set DISABLE_UPDATES and let the admin upgrade centrally. An older bug where Claude Code exited immediately on SLURM compute nodes was fixed in 2.1.76 (GitHub #12507).
# macOS / Linux / WSL: native install (recommended, updates in the background)
curl -fsSL https://claude.ai/install.sh | bash
# Stable channel: about one week behind latest, skips releases with major regressions
curl -fsSL https://claude.ai/install.sh | bash -s stable
# Windows PowerShell (prompt starts with PS)
irm https://claude.ai/install.ps1 | iex
# Windows CMD (prompt without PS)
curl -fsSL https://claude.ai/install.cmd -o install.cmd && install.cmd && del install.cmd
# Package managers (no auto-update)
brew install --cask claude-code # stable channel; claude-code@latest follows latest
winget install Anthropic.ClaudeCode
# npm (requires Node.js 22+; do not use sudo)
npm install -g @anthropic-ai/claude-code
npm install -g @anthropic-ai/claude-code@latest # use this to upgrade, not npm update -g
# Verify
claude --version # tested on this page: 2.1.296 (Claude Code)
claude doctor # read-only diagnostics: install method, auto-update, settings validation| Route | Command or entry point | Auto-update | Best for | Notes |
|---|---|---|---|---|
| Native install script | curl -fsSL https://claude.ai/install.sh | bash | Yes, in the background | Personal machines, WSL, servers without root | Installs to ~/.local/bin without admin rights; open a new terminal before running claude |
| Homebrew | brew install --cask claude-code | No, brew upgrade | macOS users who manage software with brew | claude-code follows the stable channel, claude-code@latest follows latest |
| WinGet | winget install Anthropic.ClaudeCode | No, winget upgrade | Native Windows | Upgrading while running can fail because the file is locked |
| npm | npm install -g @anthropic-ai/claude-code | Possible, if the global directory is writable | Existing Node 22+ setups | npm only downloads the native binary; Node is not used at runtime; no sudo |
| apt / dnf / apk | Official signed repositories | No | Cluster admins deploying centrally | Suits machines with NFS-shared homes; see Bus error below |
| Desktop app | claude.com/download | Yes | People who prefer not to use a terminal | Linux has its own page; the GUI shows diffs and parallel sessions |
| VS Code / JetBrains extension | Search Claude Code in the marketplace | With the extension | Reviewing diffs in the IDE | The VS Code extension reads its own setting for the starting permission mode, not project settings |
| Web cloud sessions | claude.ai/code | Not needed | Long tasks that continue offline | Subscription accounts only, needs a connected GitHub repository; local API keys are not used |
Windows
Use native Windows when your projects and tools live on Windows. Use WSL 2 when you depend on a Linux toolchain (conda, gcc, HPC scripts) or need the sandbox.
Native Windows
No admin rights needed. Git for Windows is optional: with it, commands run in Git Bash; without it, Claude Code falls back to the PowerShell tool. If Claude Code cannot find Git Bash, set CLAUDE_CODE_GIT_BASH_PATH to C:\Program Files\Git\bin\bash.exe in the env block of settings.json. Native Windows does not support the Bash sandbox.
WSL 2
Run the Linux install script inside the WSL terminal, not from PowerShell. Keep projects under /home: under /mnt/c, cross-filesystem I/O is slow and the official docs note that search returns fewer results, while claude doctor still reports Search OK.
npm installs inside WSL
If which node prints a path starting with /mnt/c/, WSL is using the Windows Node and you get exec: node: not found or a platform mismatch. Run npm config set os linux first, or install Node inside WSL with nvm. The native install script avoids this class of problems.
Logging in from WSL, SSH or containers
When the browser cannot call back to the local port, the login page shows a code; paste it at the Paste code here if prompted line in the terminal. If the browser does not open, press c to copy the login URL.
A file named nul appears in the project
Early versions wrote Unix-style /dev/null redirects on Windows (GitHub #4928). Upgrade to the latest version; if Explorer cannot delete an existing nul file, remove it from Git Bash with rm ./nul.
Install command in the wrong shell
The token '&&' is not a valid statement separator means you ran the CMD command in PowerShell; 'irm' is not recognized means you ran the PowerShell command in CMD. A prompt starting with PS is PowerShell.
Step 2
The first run of claude opens a browser login. When several credentials exist, Claude Code picks one in a fixed order; /status shows which one is active.
Credential precedence from high to low: cloud provider variables (CLAUDE_CODE_USE_BEDROCK and others), ANTHROPIC_AUTH_TOKEN, ANTHROPIC_API_KEY, an apiKeyHelper script, CLAUDE_CODE_OAUTH_TOKEN, browser login. A subscriber with a stale ANTHROPIC_API_KEY left in the shell sees a successful login followed by authentication errors on requests; unset ANTHROPIC_API_KEY and confirm with /status that the subscription is active again.
Login credentials are stored in the macOS Keychain, and in ~/.claude/.credentials.json on Linux and Windows. To use two accounts on one machine, separate them with CLAUDE_CONFIG_DIR, for example alias claude-lab='CLAUDE_CONFIG_DIR=~/.claude-lab claude'.
After upgrading your plan on claude.ai, the token in an existing session still reflects the old plan, and choosing Opus reports not available with the Claude Pro plan; run /logout and then /login.
| Method | How to set it | Billing | Differences |
|---|---|---|---|
| Claude subscription (Pro, Max, Team, Enterprise) | Run claude and sign in to your claude.ai account in the browser | Included in the plan, limited by 5-hour session and weekly allowances | 1-hour prompt cache; web cloud sessions and Remote Control available; the free plan does not include Claude Code |
| Console API key | export ANTHROPIC_API_KEY=...; interactive mode asks once to approve it | Per token, see the pricing table below | Prompt cache defaults to 5 minutes; the dollar figure in /usage is a local estimate at list price |
| Gateway or relay (ANTHROPIC_BASE_URL) | ANTHROPIC_BASE_URL + ANTHROPIC_AUTH_TOKEN or ANTHROPIC_API_KEY | Set by the gateway operator | No Remote Control; MCP tool search off by default; model names mapped with environment variables |
| Bedrock / Agent Platform / Foundry | CLAUDE_CODE_USE_BEDROCK=1 and similar, or choose 3rd-party platform at the login screen | Cloud provider bill | Auto mode supports only newer models such as Sonnet 5 and Opus 4.7 or later |
| Long-lived token | claude setup-token creates a one-year token; set it as CLAUDE_CODE_OAUTH_TOKEN | Subscription | For CI and servers without a browser; --bare mode does not read it |
Use in China
For choosing an approach in mainland China (official subscription, relay, domestic models, cloud environment), see the comparison page How to use Codex and Claude Code in China. This section covers operations only: where the variables go, how to verify them and how to debug errors.
The model set in ANTHROPIC_DEFAULT_HAIKU_MODEL also runs background tasks such as session titles and summaries. Many relay tutorials point it at the retired claude-3-5 series, and background requests then fail repeatedly; point it at a model the gateway currently serves.
When the same variable is set both in the shell and in the env block of settings.json, settings.json wins. CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1 also turns off auto-updates, so run claude update manually from time to time.
# Export the two variables in your shell, then verify the URL and credential with a 1-token request
export ANTHROPIC_BASE_URL=https://gateway.example.com
export ANTHROPIC_AUTH_TOKEN=sk-xxxx
curl -sS -w '\n%{http_code}\n' -X POST "$ANTHROPIC_BASE_URL/v1/messages" \
-H "Authorization: Bearer $ANTHROPIC_AUTH_TOKEN" \
-H "anthropic-version: 2023-06-01" -H "content-type: application/json" \
-d '{"model":"claude-sonnet-4-6","max_tokens":1,"messages":[{"role":"user","content":"."}]}'
# {"id":"msg_... means it works; an "unknown model" error also proves the URL and credential are valid;
# 401 means switch to the x-api-key header and ANTHROPIC_API_KEY
# Inside claude, run /status and confirm the Anthropic base URL and Auth token lines{
"env": {
"ANTHROPIC_BASE_URL": "https://gateway.example.com",
"ANTHROPIC_AUTH_TOKEN": "sk-xxxx",
"ANTHROPIC_DEFAULT_SONNET_MODEL": "model-name-from-your-gateway",
"ANTHROPIC_DEFAULT_HAIKU_MODEL": "small-model-name-from-your-gateway",
"CLAUDE_CODE_MAX_CONTEXT_TOKENS": "128000",
"CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC": "1",
"API_TIMEOUT_MS": "600000"
}
}| Symptom | Cause | Fix |
|---|---|---|
| curl works but claude still asks you to log in | The credential is in the project .claude/settings.json, which interactive sessions read only after the first-run wizard and trust dialog | Move env to ~/.claude/settings.json, or export it in the shell that starts claude |
| 401 invalid token | AUTH_TOKEN goes in Authorization: Bearer, API_KEY in x-api-key, and the gateway reads only one | Switch to the other variable; do not set both |
| Startup warns about two credential sources and auth may not work as expected | A gateway variable and a saved login are both present | Run /logout to use the gateway; unset the variable to use the subscription |
| 400 Extra inputs are not permitted or context_management | The upstream rejects pre-release fields that Claude Code sends | Add CLAUDE_CODE_DISABLE_EXPERIMENTAL_BETAS=1 to env |
| 400 Input tag 'adaptive' or thinking type should be enabled or disabled | The upstream model does not support adaptive thinking | The official CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING=1 only affects Opus 4.6 and Sonnet 4.6; for other models the gateway operator must upgrade the upstream |
| 400 ContextWindowExceededError or prompt token count exceeds the limit | The gateway's context is smaller than Claude Code assumes, and the rewritten error does not trigger auto-compaction | Run /compact first; then set CLAUDE_CODE_MAX_CONTEXT_TOKENS or CLAUDE_CODE_AUTO_COMPACT_WINDOW (plain integers; 500k is read as 500) |
| Gateway models missing from /model | Model names are not in the built-in list | Set CLAUDE_CODE_ENABLE_GATEWAY_MODEL_DISCOVERY=1, or map names with ANTHROPIC_DEFAULT_SONNET_MODEL and related variables |
| Connection refused (ECONNREFUSED) after a long silent wait | Wrong address or the gateway is down; Claude Code retries 10 times by default | Tested here: 2 min 56 s before the error by default, 5.9 s with CLAUDE_CODE_MAX_RETRIES=0; remove the variable after debugging |
| Still no connection after setting a proxy | Claude Code does not support SOCKS proxies | Point HTTPS_PROXY at your proxy client's HTTP port, for example http://127.0.0.1:<HTTP port> |
| SSL certificate verification failed while curl works | The runtime does not trust your company's or proxy client's root certificate | Set NODE_EXTRA_CA_CERTS to the CA certificate file |
Pricing
Choose a subscription if you use it several hours a day. Choose the API for occasional use, scripts and CI, or when you need exact accounting. Prices below are the official public prices on 2026-10-10 (USD, before tax).
Reference spend
Official figures from enterprise deployments: about $13 per developer per active day and $150–250 per month, with 90% of users below $30 per active day.
Cache lifetime sets the cost of a break
The prompt cache lives 1 hour on a subscription and 5 minutes by default on an API key. With an API key, a question after a break longer than 5 minutes rereads the whole context at the uncached price. In a long session, even a one-line question is billed against the whole context.
Checking usage
/usage (aliases /cost and /stats) shows session tokens and the estimated cost; subscribers see allowance bars and reset times. A warning appears at about 85% of an allowance. When the separate Opus or Sonnet limit runs out, /model to the other family keeps you working; session and weekly limits are shared across models.
Caps for scripts
claude -p supports --max-budget-usd and --max-turns and stops when a cap is reached. The amount is a client-side estimate and can slightly overshoot, so leave headroom.
| Plan | Price | Notes |
|---|---|---|
| Free | $0 | Does not include Claude Code |
| Pro | $20 billed monthly; $17/month billed annually ($200 up front) | Includes Claude Code; allowance counted in 5-hour session windows and weekly windows |
| Max | From $100/month, with 5x or 20x Pro usage | Priority access at peak times; includes monthly API credits |
| API: Claude Sonnet 5.5 | $2 input / $10 output per million tokens; cache hits $0.10 | Default choice for everyday coding |
| API: Claude Opus 5.5 | $4 input / $20 output; cache hits $0.20 | Complex planning and multi-step reasoning |
| API: Claude Haiku 5.5 | $0.10 input / $0.50 output ($0.50 / $2.50 for prompts over 100,000 tokens) | Simple subagent tasks |
| API: Claude Fable 5.1 | $10 input / $50 output; cache hits $0.25 | Top tier |
Step 3
CLAUDE.md is an instruction file read at the start of each session. It shapes how Claude works; it does not limit what Claude can do. Limits that must hold go in permission rules or hooks.
# Project: differential expression analysis of single-cell data
## Directory conventions
- data/raw/: raw data, read-only. Do not modify, move or delete, and do not unpack or sort in place.
- data/processed/: generated from raw by scripts in scripts/; can be deleted and rebuilt at any time.
- scripts/: every analysis step, numbered 01_, 02_, each runnable on its own.
- results/: figures and tables, file names prefixed with the script number, e.g. 03_volcano.pdf.
- logs/: one log per run, file names with a timestamp.
## Environment
- Use the conda environment scrna-2026 (versions pinned in environment.yml). Ask me before installing packages.
- Run scripts as: python scripts/<name>.py 2>&1 | tee logs/$(date +%Y%m%d-%H%M%S)-<name>.log
## Reproducibility
- Fix seed=20261010 for every random process and record it in the result table metadata.
- Every number in the results must be regenerable by a script in scripts/; no hand calculation in chat.
- When an analysis parameter changes, update the parameter table and the reason in docs/params.md.
## Statistics
- Differential expression: Wilcoxon test, BH correction, padj < 0.05 and |log2FC| > 1.
- Sample information comes from data/raw/metadata.csv; keep group names as they are.
## Long jobs
- Commands expected to run longer than 5 minutes run in the background with nohup and write a log; report progress by reading the log.
<!-- Maintainer note: this HTML comment does not enter Claude's context -->
See @docs/params.md for current parameters.Files are concatenated
All discovered files are concatenated from the filesystem root down to the launch directory; none overrides another. When two rules conflict, Claude may pick either, so do not write contradictory requirements at different levels.
@ imports
@path resolves relative to the file containing it, up to 4 levels deep. Escape spaces with backslashes; a quoted path is not imported; a path inside backticks is not imported. Imported files all load at launch, so imports do not save context. A project file that imports a path outside the project triggers a one-time approval dialog.
Length
The official advice is under 200 lines per file; longer files trigger a warning at startup and in /status, and files over 4 MiB are skipped. Move rules that apply to only some directories into subdirectory CLAUDE.md files or .claude/rules/. HTML comments <!-- --> do not enter context and can hold notes for human maintainers.
Confirm it loaded
Run /context and look under Memory files for files loaded at launch; subdirectory CLAUDE.md files are not listed there, and a Loaded line appears in the terminal when they load. /memory opens the files for editing. /init drafts a file from your code, and only proposes edits when a file already exists.
After compaction
After /compact, the project-root CLAUDE.md and unscoped rules are re-injected from disk; subdirectory CLAUDE.md files and path-scoped rules return only when a related file is read or written again; requirements stated only in chat get summarized away. Put requirements that must always apply in the root CLAUDE.md.
Coexisting with AGENTS.md
When a directory has both CLAUDE.md and AGENTS.md, Claude reads only CLAUDE.md by default (reading AGENTS.md directly needs 2.1.277 or later). Groups that also use Codex can put a line @AGENTS.md in CLAUDE.md and maintain one set of rules.
| Level | Location | When it loads | What goes in it |
|---|---|---|---|
| Organization | macOS /Library/Application Support/ClaudeCode/CLAUDE.md; Linux /etc/claude-code/CLAUDE.md | At launch | Rules distributed by admins |
| User | ~/.claude/CLAUDE.md | At launch, every project | Personal habits: reply language, code style |
| Project | ./CLAUDE.md or ./.claude/CLAUDE.md | At launch | Directory conventions, run commands, statistics conventions; shared via the repository |
| Local | ./CLAUDE.local.md (add to .gitignore) | At launch, after CLAUDE.md in the same directory | Your own paths and test data |
| Parent directories | CLAUDE.md in every directory above the launch directory | At launch | Conventions shared by several projects |
| Subdirectories | CLAUDE.md below the launch directory | When Claude reads or writes a file in that subdirectory | Rules for one submodule |
| Path rules | .claude/rules/*.md with paths in frontmatter | When a matching file is read or written | Rules only for R scripts, only for notebooks, and so on |
Step 4
The permission mode decides which actions run without asking you; rules in settings.json allow or block specific actions on top of the mode. Deny rules apply in every mode, including bypassPermissions.
{
"$schema": "https://json.schemastore.org/claude-code-settings.json",
"permissions": {
"defaultMode": "acceptEdits",
"allow": [
"Bash(python scripts/*)",
"Bash(Rscript scripts/*)",
"Bash(git diff *)",
"Bash(git status)"
],
"ask": [
"Bash(git push *)",
"Bash(pip install *)",
"Bash(conda install *)"
],
"deny": [
"Edit(data/raw/**)",
"Bash(rm -rf *)",
"Read(./.env)"
]
},
"env": { "BASH_DEFAULT_TIMEOUT_MS": "600000" },
"cleanupPeriodDays": 365
}# Make raw data read-only at the OS level (tested on this page: Python appends then raise
# PermissionError and rm -f returns Permission denied)
chmod -R a-w data/raw
# Lift it yourself when raw data must be updated
chmod -R u+w data/rawEvaluation order
Deny first, then ask, then allow; the first match wins regardless of how specific the rule is. A deny on Bash(git *) blocks an allow on Bash(git status). Lists with the same key in several settings files are merged, not overridden.
Where the wildcard goes
Put * after the subcommand. Bash(git log *) allows only git log; Bash(git *) allows every git subcommand, including git -c, which can run any program. Bash(ls *) does not match lsof; Bash(ls*) does.
Path syntax
In Edit(/data/**), a single leading slash is relative to the project of the settings file; absolute paths are written //home/me/data/** and home paths ~/. A /secrets/** rule in user settings means ~/.claude/secrets. Path rules written as Write(...) or NotebookEdit(...) are accepted but never consulted; write Edit(...) instead.
Deny rules do not reach scripts
Read and Edit rules apply to the built-in file tools and to cat, sed, tee and redirections that Claude Code recognizes, not to open() or write.csv() inside a Python or R script. A .claudeignore file has no effect. The reliable protection for raw data is chmod -R a-w plus a PreToolUse hook that blocks writes.
What overly broad permissions cost
acceptEdits auto-approves rm inside the working directory. Checkpoints (Esc Esc or /rewind) roll back only files Claude changed with its edit tools; files deleted or moved by Bash commands are not tracked. The built-in critical-path protection blocks rm on the root, home and working directory themselves, not on data/ under the working directory.
Values that only work at user level
defaultMode set to auto or bypassPermissions has no effect in the project .claude/settings.json or settings.local.json; put it in ~/.claude/settings.json or pass --permission-mode. Tested on this page: claude doctor does not flag this.
| Mode | Runs without asking | Use in research work |
|---|---|---|
| default (shown as Manual) | Reads only | First contact with unfamiliar code, sensitive data |
| acceptEdits | Reads, file edits, and mkdir, touch, rm, rmdir, mv, cp, sed inside the working directory | Iterate and review with git diff; raw data needs separate protection |
| plan | File reads and exploratory commands; no source edits until you approve the plan | Propose a plan before changing an analysis pipeline; /plan enters it for one prompt |
| auto | Nearly everything, reviewed in the background by a separate classifier model | Long tasks with a clear direction; the default for interactive sessions since 2.1.283 |
| dontAsk | Only actions already allowed; everything else is denied | Unattended claude -p batches and CI |
| bypassPermissions | Everything except deny rules, ask rules and critical-path removals | Only in containers or VMs without network access; refuses to start as root or under sudo |
Commands
Commands from older tutorials that no longer work: claude config set was deprecated in 1.0.7 and removed in 2.0.0; edit settings.json or use /config instead (tested on this page: 2.1.296 lists no config subcommand). The # prefix for quick memory entries was removed in 2.0.70. /vim was removed in 2.1.92; set Editor mode in /config. npm update -g may stay on an old version; upgrade with npm install -g @anthropic-ai/claude-code@latest.
| Command or key | What it does | Notes |
|---|---|---|
| /init | Draft a project CLAUDE.md | Only proposes edits when a file already exists |
| /context | Show context usage as a grid | See how much Memory files, MCP tools and the conversation take |
| /compact [focus] | Summarize the conversation to free context | Add a focus, for example /compact keep the parameter table and the last error |
| /clear [name] | Start a new conversation | Free; the old one is available via /resume |
| /resume, /rename | Resume and name sessions | Name before /clear so you can resume by name later |
| /rewind (Esc Esc) | Return to an earlier message and optionally restore code | Does not undo changes made by Bash commands |
| /model, /effort | Switch model and reasoning effort | /model saves the choice as the default for new sessions |
| /permissions, /config, /status | Manage rules and settings; show account and gateway | /status is the first step when debugging login or gateway issues |
| /usage | Usage and cost | /cost and /stats are aliases |
| /memory, /hooks, /mcp, /skills | Manage each extension type | The /agents wizard was removed in 2.1.198; ask Claude to create subagents or edit .claude/agents/ |
| /export [file] | Export the conversation as plain text | For keeping a record of the work |
| /doctor | In-session setup checkup | /doctor prompt-audit checks CLAUDE.md for conflicts and stale content |
| Shift+Tab | Cycle permission modes | Alt+M in some Windows terminals |
| Esc | Interrupt the current response or tool call | Work done so far is kept |
| Ctrl+O | Open the full transcript view | Shows each tool call and the model used |
| Ctrl+B | Move a running command or subagent to the background | Press twice in tmux |
| Ctrl+G | Edit the prompt or plan in an external editor | Useful for long instructions |
| ! prefix | Run a shell command directly and add its output to the conversation | For example !nvidia-smi |
| @ prefix | Reference a file path | With autocomplete |
| \ + Enter or Ctrl+J | Insert a newline | Works in every terminal |
Extensions
Each has a different job: a subagent completes one kind of task in its own context; a hook runs a shell command at a fixed point, independent of the model's judgment; a skill is a procedure loaded on demand; MCP connects external tools and data.
---
name: stats-reviewer
description: Reviews analysis scripts and result tables for statistical errors. Use after an analysis script changes or before results go into a figure or manuscript.
tools: Read, Grep, Glob, Bash
model: sonnet
---
You are a statistical methods reviewer. Check that sample sizes and groups match data/raw/metadata.csv,
that multiple comparisons are corrected, that random seeds are fixed, and that every number in the result
tables can be regenerated by a script in scripts/. Report problems with evidence only; do not modify files.#!/bin/bash
# .claude/hooks/protect-raw.sh: block Edit/Write calls that target data/raw/
# Exit code 2 blocks the call; stderr is sent back to Claude as the reason
INPUT=$(cat)
FILE_PATH=$(echo "$INPUT" | jq -r '.tool_input.file_path // empty')
FILE_PATH="${FILE_PATH//\\//}"
if [[ "$FILE_PATH" == *"/data/raw/"* ]]; then
echo "Blocked: $FILE_PATH is raw data (read-only). Write to data/processed/ or results/." >&2
exit 2
fi
exit 0{
"hooks": {
"PreToolUse": [
{
"matcher": "Edit|Write",
"hooks": [
{ "type": "command", "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/protect-raw.sh" }
]
}
]
}
}---
name: run-analysis
description: Run one analysis script reproducibly and log the environment. Use when the user asks to run or rerun an analysis.
disable-model-invocation: true
---
1. Record `git rev-parse --short HEAD`, `python --version` and `conda env export --no-builds` in logs/.
2. Run `python scripts/$ARGUMENTS 2>&1 | tee logs/$(date +%Y%m%d-%H%M%S)-run.log`.
3. Report output file paths and key numbers. Do not modify data/raw/.# Add an MCP server (local scope by default: only you, only this project; stored in ~/.claude.json)
claude mcp add --transport http sentry https://mcp.sentry.dev/mcp
claude mcp add my-db -e DB_URL=postgres://... -- npx -y some-db-mcp
# Share with your group: written to .mcp.json at the project root (teammates approve it on first run)
claude mcp add --scope project zotero -- npx -y zotero-mcp
claude mcp list # unapproved .mcp.json servers show as Pending approval
# Check agent and skill file format (tested on this page: a missing description only gives a warning,
# but the agent is skipped at runtime)
claude plugin validate .claude/agentsSubagent files skipped silently
If the frontmatter lacks name or description, the YAML does not parse, or the opening --- is not on the first line, the file does not load and the session says nothing. Check with claude plugin validate .claude/agents, then read the log from claude --debug. A subagent's system prompt is only the file body plus environment details such as the working directory; it does not see the main conversation, so put the background it needs in the body or in the delegation request.
Hooks are more reliable than CLAUDE.md
A PreToolUse hook that returns deny or exits with code 2 blocks the call even in bypassPermissions mode. A hook that returns allow cannot override a deny rule in settings. PostToolUse runs after the tool and cannot undo it. Command hooks time out after 10 minutes by default.
MCP config is not in settings.json
Personal MCP servers are stored in ~/.claude.json; shared project servers in .mcp.json at the project root. Prefer command-line tools (gh, aws) when they can do the job, since MCP servers take context; disable unused servers with /mcp. Behind a gateway set with ANTHROPIC_BASE_URL, MCP tool search is off by default and every tool definition enters context.
Skills versus CLAUDE.md
Facts that must hold in every session go in CLAUDE.md; multi-step procedures go in a skill, which loads only when invoked. disable-model-invocation: true means only you can invoke it with /name. After compaction each skill keeps at most its first 5,000 tokens, so put the key steps near the top of SKILL.md.
Scripts and sessions
# One run, result as JSON so a script can read result, session_id and total_cost_usd
claude -p "Read results/03_de_genes.csv and list the 20 genes with the smallest padj and their log2FC" \
--output-format json --permission-mode dontAsk --allowedTools "Read" \
--max-turns 5 --max-budget-usd 0.50 < /dev/null > logs/summary.json
jq -r '.result' logs/summary.json
# Batch: one independent run per sample; a non-zero exit code marks failure
for s in S01 S02 S03; do
claude -p "Check cell count, gene count and mitochondrial fraction in data/processed/$s.h5ad and write a QC summary" \
--permission-mode dontAsk --allowedTools "Read" "Bash(python scripts/qc_summary.py *)" \
< /dev/null > logs/qc-$s.md || echo "$s failed" >> logs/failed.txt
done
# Resume sessions
claude --continue # most recent interactive session in this directory
claude --resume # open the session picker (Ctrl+A shows every project on this machine)
claude --resume de-analysis # resume by name (name it in-session with /rename de-analysis)
claude -p --resume <session-id> "Summarize which parameters changed" --output-format json | jq -r '.result'Run interactively once in the directory first
Tested on this page: claude -p in an untrusted directory prints Ignoring 4 permissions.allow entries from .claude/settings.json: this workspace has not been trusted. None of the project allow rules apply, while env from the same settings file still applies. In a fresh clone or a new directory on a cluster, run claude once and accept the trust dialog.
stdin and exit codes
When stdin is not a terminal, claude -p waits 3 seconds and prints Warning: no stdin data received in 3s; add < /dev/null in scripts. When not logged in, stdout reads Not logged in · Please run /login and the exit code is 1 (tested on this page). In -p mode, settings files that fail validation are ignored silently, so run claude doctor before a batch.
-p sessions are not in the picker
Sessions created by claude -p do not appear in the claude --resume picker, and claude --continue skips them; continue one with the session_id from --output-format json and claude --resume <id>. When resuming, pass launch flags such as --mcp-config, --add-dir and --settings again.
Starting permission mode for -p
The starting mode of claude -p depends on the version and on whether feature flags are fetched; it can be default or auto. Pass --permission-mode dontAsk with an --allowedTools allowlist in scripts for predictable results.
Context
- 01
Check usage first
/context shows how much the system prompt, Memory files, MCP tools and the conversation each take. If a large share is used at startup, trim CLAUDE.md, skills or MCP servers.
- 02
/clear when you switch tasks
Old conversation unrelated to the current task is billed again on every request. Before switching, name the session with /rename, then /clear. /clear costs nothing; /compact reads the whole conversation, so on a large context it is itself a large request.
- 03
Say what to keep when compacting
For example, /compact keep the parameter table, the last error and the unfinished steps. You can also add a # Compact instructions section to CLAUDE.md. /autocompact 300000 makes automatic compaction trigger earlier.
- 04
Do not read whole data files
Have Claude inspect structure with head, wc -l, pandas nrows or df.info() instead of reading a whole CSV. A very large output can trigger Autocompact is thrashing: context refills right after compaction and Claude Code stops retrying. Read in chunks, or hand large-file processing to a subagent so it happens in a separate context.
- 05
Command output limits
By default only about 30,000 characters of Bash output enter context inline; the rest is saved to a file that Claude reads on demand. Failed commands keep a head-and-tail excerpt of about 10,000 characters. grep or tail long logs before handing them to Claude.
Research practice
Research work runs long, raw data cannot be regenerated, and results must be reproducible. The practices below address these three points.
# Have Claude start long jobs this way: the job is independent of Claude's process and logs to disk
nohup python scripts/05_train.py --config configs/run3.yaml \
> logs/run3-$(date +%Y%m%d-%H%M).log 2>&1 &
echo $! > logs/run3.pid
# On HPC, submit to the scheduler instead of running on the login node
sbatch scripts/05_train.slurm
# Then have Claude read tail -n 50 logs/run3-*.log to report progress instead of waiting in the foreground- 01
Confirm the approach in plan mode
Before changing an analysis pipeline, press Shift+Tab into plan mode or prefix the prompt with /plan. Claude only reads files and writes a plan; edit the plan in your editor with Ctrl+G and approve it before execution. The plan file is re-injected from disk after compaction, so it works as the outline of a long task.
- 02
Keep long jobs outside Claude's process
Foreground Bash commands time out after 2 minutes by default, 10 minutes at most, and then move to the background. Background commands in a local interactive session have no time limit, but in claude -p they stop after 10 minutes by default and 2 hours at most. Start model training or molecular simulations with nohup or sbatch, write logs to files, and have Claude read the logs to report progress.
- 03
Activate the environment before starting claude
Each Bash command runs in a separate process and variables set with export do not carry over to the next command, so a conda activate that Claude runs mid-session only lasts for that one command. Run conda activate first, then claude; for extra variables, point CLAUDE_ENV_FILE at a setup script.
- 04
Keep a record of the work
Transcripts are stored as JSONL under ~/.claude/projects/<directory name>/ and deleted silently after 30 days by default. For projects that need an archive, raise cleanupPeriodDays in settings.json (for example 365), export key sessions with /export, and commit them with the run logs in logs/.
- 05
Make results reproducible
In CLAUDE.md, require that every number comes from a script, that random seeds are fixed, and that parameter changes go into a parameter table. Fix the run procedure in a skill (record the git commit and conda env export). Before delivery, have a subagent such as stats-reviewer review the work separately.
- 06
Control cost
Configure the status line to show context usage and cost (/statusline). Use Sonnet day to day and switch to Opus for complex planning; give simple subagents model: haiku. Start a new session for each independent question, since a long session bills even a one-line question against the whole context. Add --max-budget-usd to batches.
Chinese community
These items come from hands-on posts on CSDN and the Alibaba Cloud developer community. Each was checked against the official docs or tests on this page, with its conditions and corrections noted.
First run stuck at Unable to connect to Anthropic services
Three authors reported independently (CSDN, March to June 2026): with a relay, the first run fails with Failed to connect to api.anthropic.com: ERR_BAD_REQUEST, and adding "hasCompletedOnboarding": true to ~/.claude.json gets past it. The official docs say the first-run wizard probes api.anthropic.com and platform.claude.com. Correction: add the key with an editor instead of overwriting the file with cat > ~/.claude.json, which also holds project trust, OAuth and personal MCP servers; the key has no effect in settings.json, and claude doctor does not flag it there (tested on this page).
requires git-bash error
A CSDN author hit Claude Code on Windows requires git-bash and fixed it by setting CLAUDE_CODE_GIT_BASH_PATH. Current versions fall back to PowerShell without Git for Windows; the message now reads requires either Git for Windows (for bash) or PowerShell and appears only when neither is available.
Third-party model returns thinking type should be enabled or disabled
The cause given in an Alibaba Cloud community post (the upstream does not support adaptive thinking) matches the official troubleshooting table, but the post writes the variable in lowercase as claude_code_disable_adaptive_thinking. Environment variables are case-sensitive; the name is CLAUDE_CODE_DISABLE_ADAPTIVE_THINKING, and the official docs say it only affects Opus 4.6 and Sonnet 4.6.
Lab servers without root
A CSDN post installs Node with nvm and then Claude Code with npm, which works without root. The native install script already installs to ~/.local/bin and needs neither Node nor root. The same post points ANTHROPIC_DEFAULT_HAIKU_MODEL at the retired claude-3-5-haiku; that model also runs background tasks, so use a model the gateway currently serves.
Putting "ask me before deleting" in CLAUDE.md
Many tutorials put file deletion and git push as hard rules in CLAUDE.md. The official docs say CLAUDE.md is context rather than enforced configuration, and GitHub #2544 records such rules being ignored. Write these as ask or deny rules in settings.json, or as a PreToolUse hook.
Errors
Debug order: claude --version to confirm the version; claude doctor to check the install and settings files; /status in a session to confirm the account, gateway and loaded settings files; if still unclear, start with claude --debug and read the log under ~/.claude/debug/; if you suspect your own configuration, compare with claude --safe-mode.
| Error message | Cause | Fix |
|---|---|---|
| command not found: claude / 'claude' is not recognized | The install directory is not on PATH, or you are in a terminal opened before the install | Open a new terminal; add ~/.local/bin (%USERPROFILE%\.local\bin on Windows) to PATH |
| syntax error near unexpected token '<' | The install URL returned a web page instead of the script, common with network routing or regional restrictions | Retry later or use brew / winget; App unavailable in region in the output means your region is not supported |
| curl: (22) ... error: 403 | A proxy or firewall blocks the download, or a regional restriction | Check connectivity to downloads.claude.ai and your proxy settings |
| Killed (during install on Linux) | Out of memory | The official minimum is 4 GB RAM; free memory or add swap and reinstall |
| Bus error / oh no: Bun has crashed | The running executable was deleted or truncated, common on NFS-shared homes | Install the binary on local disk and turn off self-updates for central upgrades |
| OAuth error: Invalid code | The login code expired or was copied incompletely | Run /login again and paste soon after the browser opens |
| API Error: 403 Request not allowed | Subscription inactive, the Console account lacks the Claude Code role, or proxy interference | Check the subscription at claude.ai/settings; ask the Console admin for the Developer or Claude Code role |
| Not logged in · Please run /login | No usable credential | /login, or set ANTHROPIC_API_KEY / ANTHROPIC_AUTH_TOKEN |
| Unable to connect to API (ECONNREFUSED / ENOTFOUND / ERR_PROXY_TUNNEL) | No network route, proxy not set, or a stale ANTHROPIC_BASE_URL | Test with curl -I https://api.anthropic.com; check echo $ANTHROPIC_BASE_URL; on WSL check /etc/resolv.conf |
| You've hit your session limit · resets 3:45pm | Subscription allowance used up | Wait for the reset; check /usage; for a separate Opus or Sonnet limit, switch family with /model |
| Context limit reached · /compact or /clear to continue | Conversation plus attachments exceed the context window | /compact with a focus; /clear if the old conversation is not needed |
| Autocompact is thrashing | A large file or output refills context right after compaction | Read in chunks; hand large files to a subagent; drop large output when compacting |
| Claude Opus is not available with the Claude Pro plan | The plan does not include the model, or the token was not refreshed after an upgrade | /model to another model; after an upgrade, /logout then /login |
| --dangerously-skip-permissions cannot be used with root/sudo privileges | Bypass mode run as root | Run as a regular user, or inside the official dev container |
| Claude Code on Windows requires either Git for Windows (for bash) or PowerShell | Neither shell can be found | Install Git for Windows, or set CLAUDE_CODE_GIT_BASH_PATH |
Hand it to an agent
Example instruction: "This is my analysis repository. First browse the code and data/README.md read-only, write a CLAUDE.md and .claude/settings.json following the directory conventions on this page, and make data/raw read-only. Then rerun the differential expression analysis from raw counts using the pipeline in scripts/, run long steps in the background with logs, and deliver the result tables, figures and a record of parameters and environment."
Steps the agent takes: clones the repository in an isolated cloud computer and builds the environment from environment.yml; writes a plan first, then generates CLAUDE.md and the permission configuration; rents a GPU automatically when a step needs one, runs long steps in the background and reports from the logs; reviews the results adversarially, checking sample groups, multiple-comparison correction and random seeds.
Output files: CLAUDE.md, .claude/settings.json, a run log for each step, tables and figures in results/, and a reproduction note recording the git commit and conda environment. The task continues after you close your machine.
What you still need to check: whether the statistical method fits your experimental design, whether groups and covariates match the sample information, and whether thresholds and parameters match your group's earlier analyses.
Checklist
- claude --version meets the version required by the features you rely on; on clusters the binary is on local disk
- /status shows the account or gateway you expect, with no stale ANTHROPIC_API_KEY
- The project root has a CLAUDE.md under 200 lines with directory conventions, run commands, random seeds and statistics conventions
- data/raw is chmod -R a-w, and settings.json has an Edit(data/raw/**) deny rule
- Actions that need confirmation (git push, installing dependencies) are ask rules; bypassPermissions is not used
- cleanupPeriodDays is raised, a logs/ directory exists, and key sessions are saved with /export
- Batch scripts use --permission-mode dontAsk, an --allowedTools allowlist, < /dev/null and --max-budget-usd, and claude has been run interactively once in that directory
- Long jobs start with nohup or sbatch, and Claude only reads their logs
Sources
- Claude Code Docs: Advanced setup — Install routes, auto-update, Node version for npm, Bus error on NFS, native Windows versus WSL
- Claude Code Docs: Authentication — Account types, credential precedence, credential storage, setup-token
- Claude Code Docs: Connect Claude Code to an LLM gateway — ANTHROPIC_BASE_URL and credential variables, curl verification, gateway troubleshooting table
- Claude Code Docs: Environment variables — Meaning and defaults of timeout, retry, context window and model mapping variables
- Claude Code Docs: Network configuration — HTTPS_PROXY, no SOCKS support, hosts to allow
- Claude Code Docs: How Claude remembers your project — CLAUDE.md levels, load order, @ imports, AGENTS.md, length advice
- Claude Code Docs: Choose a permission mode — Six modes, auto as the starting mode, protected and critical paths
- Claude Code Docs: Configure permissions — Rule evaluation order, wildcards, path syntax, scope of Read/Edit rules
- Claude Code Docs: Settings files and precedence — Scope and precedence of the four settings files, values that only work at user level
- Claude Code Docs: Commands and Interactive mode — Slash commands and shortcuts, removed commands
- Claude Code Docs: Create custom subagents — Subagent file format and cases where files are skipped silently
- Claude Code Docs: Automate actions with hooks — PreToolUse blocking script, hooks and permission modes
- Claude Code Docs: Run Claude Code programmatically — claude -p, output formats, waiting for background tasks, unattended flags
- Claude Code Docs: Manage sessions — --resume / --continue, transcript location and 30-day retention
- Claude Code Docs: Tools reference — Bash timeouts, background command limits, output limits, environment activation
- Claude Code Docs: Explore the context window — What survives compaction and what is lost
- Claude Code Docs: Manage costs effectively — Average spend, cache lifetime, why usage climbs in long sessions
- Claude Code Docs: Troubleshoot installation and login, and Error reference — Error messages and fixes
- Claude Code Docs: Changelog — Versions that removed claude config, the /agents wizard and the # memory shortcut
- Claude pricing page — Free, Pro and Max prices and whether Claude Code is included
- Claude API Pricing — Per-million-token prices by model
- GitHub anthropics/claude-code #12507 — Immediate exit on HPC compute nodes, fixed in 2.1.76
- GitHub anthropics/claude-code #4928 — nul files created on Windows
- GitHub anthropics/claude-code #2544 — Mandatory rules in CLAUDE.md being ignored
- Community post: CSDN, fixing incomplete first-run onboarding in Claude Code — hasCompletedOnboarding and the original error text; two other authors give the same fix
- Community post: CSDN, Claude Code on a remote server without root — Rootless server setup; the retired models and the ~/.claude.json overwrite need correcting
- Community post: CSDN, claude --version reports requires git-bash — Setting CLAUDE_CODE_GIT_BASH_PATH on Windows
- Community post: Alibaba Cloud developer community, installing Claude Code in China — Adaptive thinking error with third-party models; the variable name's case needs correcting