```
Progress messages appear in transcript mode (Ctrl-R) showing:
* Which hook is running
* Command being executed
* Success/failure status
* Output or error messages
---
Security & Permissions
#### Tool Permission Patterns
```bash
# Allow specific tools (read/edit files)
claude --allowedTools "Edit,Read"
# Allow tool categories incl. Bash (but still scoped below)
claude --allowedTools "Edit,Read,Bash"
# Scoped permissions (all git commands)
claude --allowedTools "Bash(git:*)"
# Multiple scopes (git + npm)
claude --allowedTools "Bash(git:*),Bash(npm:*)"
```
Dangerous Mode
> [!Warning]
> NEVER use in Production systems, shared machines, or any systems with important data
> Only use with isolated environments like a **Docker container**, using this mode can cause data loss and comprimise your system!
>
> `claude --dangerously-skip-permissions`
Security Best Practices
Start Restrictive
Protect Sensitive Data
- **Keep `~/.claude.json` private (`chmod 600`).**
- **Prefer environment variables for API keys over plain‑text.**
- Use `--strict-mcp-config` to only load MCP servers from specified config files
Automation & Integration
Automation & Scripting with Claude Code
> GitHub Actions you can copy/paste :p
1. **Install the Claude GitHub App** on your org/repo (required for Actions to comment on PRs/issues).
2. In your repo, add a secret **`ANTHROPIC_API_KEY`** Settings → Secrets and variables → Actions → New repository secret
3. Copy the workflows below into **`.github/workflows/`**.
4. Open a **test PR** (or a new issue) to see them run.
> [!TIP]
> Pin Actions to a release tag (e.g. `@v1`) when you adopt them long‑term. The snippets below use branch tags for readability.
> **Creates a structured review (with inline comments) as soon as a PR opens or updates.**
**File:** `.github/workflows/claude-pr-auto-review.yml`
```yaml
name: Auto review PRs
on:
pull_request:
types: [opened, synchronize, reopened, ready_for_review]
permissions:
contents: read
pull-requests: write
jobs:
auto-review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 1
- name: Claude PR review
uses: anthropics/claude-code-action@main
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
# Claude will fetch the diff and leave inline comments
direct_prompt: |
Review this pull request’s diff for correctness, readability, testing, performance, and DX.
Prefer specific, actionable suggestions. Use inline comments where relevant.
# GitHub tools permitted during the run:
allowed_tools: >-
mcp__github__get_pull_request_diff,
mcp__github__create_pending_pull_request_review,
mcp__github__add_comment_to_pending_review,
mcp__github__submit_pending_pull_request_review
```
Security Review on Every PR
> **Runs a focused security scan and comments findings directly on the PR.**
**File:** `.github/workflows/claude-security-review.yml`
```yaml
name: Security Review
on:
pull_request:
permissions:
contents: read
pull-requests: write
jobs:
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
ref: ${{ github.event.pull_request.head.sha || github.sha }}
fetch-depth: 2
- name: Claude Code Security Review
uses: anthropics/claude-code-security-review@main
with:
claude-api-key: ${{ secrets.ANTHROPIC_API_KEY }}
comment-pr: true
# Optional:
# exclude-directories: "docs,examples"
# claudecode-timeout: "20"
# claude-model: "claude-3-5-sonnet-20240620"
```
Issue Triage (suggest labels & severity)
> **When a new issue opens, Claude proposes labels/severity and posts a tidy triage comment. You can enable **auto‑apply labels** by flipping a single flag**
**File:** `.github/workflows/claude-issue-triage.yml`
```yaml
name: Claude Issue Triage
on:
issues:
types: [opened, edited, reopened]
permissions:
contents: read
issues: write
jobs:
triage:
runs-on: ubuntu-latest
env:
CLAUDE_MODEL: claude-3-5-sonnet-20240620
steps:
- name: Collect context & similar issues
id: gather
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
run: |
TITLE="${{ github.event.issue.title }}"
BODY="${{ github.event.issue.body }}"
# naive similar search by title words
Q=$(echo "$TITLE" | tr -dc '[:alnum:] ' | awk '{print $1" "$2" "$3" "$4}')
gh api -X GET search/issues -f q="repo:${{ github.repository }} is:issue $Q" -f per_page=5 > similars.json
echo "$TITLE" > title.txt
echo "$BODY" > body.txt
- name: Ask Claude for triage JSON
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
cat > payload.json << 'JSON'
{
"model": "${{ env.CLAUDE_MODEL }}",
"max_tokens": 1500,
"system": "You are a pragmatic triage engineer. Be specific, cautious with duplicates.",
"messages": [{
"role": "user",
"content": [{
"type":"text",
"text":"Given the issue and similar candidates, produce STRICT JSON with keys: labels (array of strings), severity (one of: low, medium, high, critical), duplicate_url (string or empty), comment_markdown (string brief). Do not include any extra keys."
},
{"type":"text","text":"Issue title:\n"},
{"type":"text","text": (include from file) },
{"type":"text","text":"\n\nIssue body:\n"},
{"type":"text","text": (include from file) },
{"type":"text","text":"\n\nSimilar issues (JSON):\n"},
{"type":"text","text": (include from file) }]
}]
}
JSON
# Inject files safely
jq --arg title "$(cat title.txt)" '.messages[0].content[2].text = $title' payload.json \
| jq --arg body "$(cat body.txt)" '.messages[0].content[4].text = $body' \
| jq --arg sims "$(cat similars.json)" '.messages[0].content[6].text = $sims' > payload.final.json
curl -s https://api.anthropic.com/v1/messages \
-H "x-api-key: $ANTHROPIC_API_KEY" \
-H "anthropic-version: 2023-06-01" \
-H "content-type: application/json" \
-d @payload.final.json > out.json
jq -r '.content[0].text' out.json > triage.json || echo '{}' > triage.json
# Validate JSON to avoid posting garbage
jq -e . triage.json >/dev/null 2>&1 || echo '{"labels":[],"severity":"low","duplicate_url":"","comment_markdown":"(triage failed to parse)"}' > triage.json
- name: Apply labels (optional)
if: ${{ false }} # flip to `true` to auto-apply labels
uses: actions/github-script@v7
with:
script: |
const triage = JSON.parse(require('fs').readFileSync('triage.json','utf8'))
if (triage.labels?.length) {
await github.rest.issues.addLabels({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
labels: triage.labels
})
}
- name: Post triage comment
uses: actions/github-script@v7
with:
script: |
const fs = require('fs')
const triage = JSON.parse(fs.readFileSync('triage.json','utf8'))
const md = `### 🤖 Triage
- **Suggested labels:** ${triage.labels?.join(', ') || '—'}
- **Severity:** ${triage.severity || '—'}
${triage.duplicate_url ? `- **Possible duplicate:** ${triage.duplicate_url}\n` : ''}
---
${triage.comment_markdown || ''}`
await github.rest.issues.createComment({
owner: context.repo.owner,
repo: context.repo.repo,
issue_number: context.issue.number,
body: md
})
```
> [!NOTE]
> The triage workflow posts a **suggestion comment** by default. Flip the `Apply labels` step to `true` if you want labels applied automatically.
>
> ### Configuration & Customization
> - **Model selection**: set `CLAUDE_MODEL` (e.g., `claude-3-5-sonnet-20240620`) where shown.
> - **Secrets**: `ANTHROPIC_API_KEY` is required. The built‑in `GITHUB_TOKEN` is sufficient for posting comments and applying labels.
> - **Permissions**: each workflow declares the least privileges it needs (`pull-requests: write` and/or `issues: write`). Adjust only if your org requires stricter policies.
> - **Scope**: use `paths:` filters on triggers to limit when workflows run (e.g., only for `/src` or exclude `/docs`).
>
> ### Troubleshooting
> Check the **Actions logs** first—most issues are missing secrets/permissions or a mis‑indented YAML block.
> - **No comments appear on PRs**: Verify the Claude GitHub App is installed and the workflow has `pull-requests: write` permission.
> - **403 when applying labels**: Ensure the job or step has `issues: write`. The default `GITHUB_TOKEN` must have access to this repo.
> - **Anthropic API errors**: Confirm `ANTHROPIC_API_KEY` is set at repository (or org) level and not expired.
> - **“YAML not well‑formed”**: Validate spacing—two spaces per nesting level; no tabs.
---
Help & Troubleshooting
> [!TIP]
> **Q:`claude` not found, but `npx claude` works?**
> > **A: Your `PATH` is missing the npm global bin. See the `PATH` issue section for [`Windows`](#windowspath) or [`Linux`](#linuxpath)**
>
> **Q:** **Which Node.js version do I need?**
> > **A:** **Node.js **18+** (ideally **20+**). Check with `node --version`.**
>
> **Q: Where do I see logs**
> > **A: Run `claude doctor` and `claude --verbose` the diagnostic window will point to log locations.**
>
> **Q: Do I need to reboot after editing PATH?**
> > **A: No reboot required, but you must open a new terminal window.**
Debug Quick Commands
*Check the output of `claude doctor` for log locations and environment checks.*
> [!Note]
>
> ```bash
> claude # Open Claude UI (if on PATH)
> claude --version # Show CLI version (e.g., 1.0.xx)
> claude update # Update the CLI (if supported)
>
> claude doctor # Open diagnostic / debug window
> npx claude /doctor # Opens diagnostic/debug window
>
> claude --debug # Launch claude with diagnostics
> claude --verbose # Verbose logging
>
> where claude # Windows (cmd)
> which claude # macOS/Linux (bash/zsh)
>
> npm bin -g # Linux Verify your global bin path
> npm prefix -g # Windows Verify your global bin path
> ```
|
Path Temp Fix
**Your **PATH** likely doesn’t include the global npm bin directory.**
> [!Note]
>
> #### Windows (CMD):
> ```bash
> set PATH=%USERPROFILE%\AppData\Roaming\npm;C:\Program Files\nodejs;%PATH%
> where claude
> claude --debugg
> ```
> #### Windows (PowerShell):
> ```powershell
> $env:Path = "$env:USERPROFILE\AppData\Roaming\npm;C:\Program Files\nodejs;$env:Path"
> where claude
> claude --debugg
> ```
> #### Linux/MacOS (bash/zsh)
> ```bash
> export PATH="$(npm config get prefix)/bin:$HOME/.local/bin:$PATH"
> which claude
> claude doctor
> ```
|
Windows Path Perm Fix
**Replace `` with your own Windows username (without the angle brackets)**
- **Start → type: Environment Variables**
- **Open Edit the system environment variables → Environment Variables**
- **Under User variables for select `Path` → `Edit` → `New` add:**
```path
C:\Users\\AppData\Roaming\npm
C:\Program Files\nodejs
```
> **Optional locations to add:**
```path
C:\Users\\.claude\local\bin
C:\Users\\.local\bin
```
- **Remove duplicates, any entry containing `%PATH%`, and stray quotes (`"`). Click `OK`.**
- **Open a `new` Command Prompt/PowerShell and verify:**
```C
where claude
claude doctor
```
> [!Tip]
> ### Optional Run directly (when PATH is broken)
>
> > **Windows (PowerShell/cmd)**
> ```powershell
> "%USERPROFILE%\AppData\Roaming\npm\claude.cmd" --version
> "%USERPROFILE%\AppData\Roaming\npm\claude.cmd" doctor
> ```
> > **Or via npx:**
> ```
> npx claude doctor
> ```
|
Installation / Node.js Issues
**Must be Node 18+ (20+ recommended)**
```bash
node --version
```
**Clean uninstall**
```bash
npm uninstall -g @anthropic-ai/claude-code
```
**Fresh install**
```bash
npm install -g @anthropic-ai/claude-code
```
|
Authentication Issues
> *Verify your Anthropic API key is available to the CLI.*
**PowerShell (Windows):**
```powershell
echo $env:ANTHROPIC_API_KEY
claude -p "test" --verbose
```
**bash/zsh (macOS/Linux):**
```bash
echo $ANTHROPIC_API_KEY
claude -p "test" --verbose
```
*If the variable is empty set it for your shell/profile or use your OS keychain/secrets manager.*
|
|
**Inspect permissions**
```bash
claude config get allowedTools
```
**Reset permissions**
```bash
claude config set allowedTools "[]"
```
**Minimal safe set (example)**
```bash
claude config set allowedTools '["Edit","View"]'
```
|
MCP (Model Context Protocol) Issues
> **Debug MCP servers**
```bash
claude --mcp-debug
```
> **List & remove MCP servers**
```bash
claude mcp list
claude mcp remove
```
|
Full Clean Reinstall (Windows / PowerShell)
> [!Caution]
> **The following removes Claude Code binaries, caches, and config under your user profile**
> 1) Uninstall the global npm package
```powershell
npm uninstall -g @anthropic-ai/claude-code
```
> 2) Remove leftover shim files
```powershell
Remove-Item -LiteralPath "$env:USERPROFILE\AppData\Roaming\npm\claude*" -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath "$env:USERPROFILE\AppData\Roaming\npm\node_modules\@anthropic-ai\claude-code" -Recurse -Force -ErrorAction SilentlyContinue
```
> 3) Delete cached installer & native files
```powershell
Remove-Item -LiteralPath "$env:USERPROFILE\.claude\downloads\*" -Recurse -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath "$env:USERPROFILE\.claude\local\bin\claude.exe" -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath "$env:USERPROFILE\.claude\local" -Recurse -Force -ErrorAction SilentlyContinue
```
> 4) Remove config and project-local files
```powershell
Remove-Item -LiteralPath "$env:USERPROFILE\.claude.json" -Force -ErrorAction SilentlyContinue
Remove-Item -LiteralPath "$env:USERPROFILE\.claude" -Recurse -Force -ErrorAction SilentlyContinue
```
> 5) Reinstall
```powershell
npm install -g @anthropic-ai/claude-code
```
|
One‑Shot Health Check (copy/paste)
**Windows (PowerShell):**
```powershell
Write-Host "`n=== Node & npm ==="; node --version; npm --version
Write-Host "`n=== Where is claude? ==="; where claude
Write-Host "`n=== Try doctor ==="; try { claude doctor } catch { Write-Host "claude not on PATH" }
Write-Host "`n=== API key set? ==="; if ($env:ANTHROPIC_API_KEY) { "Yes" } else { "No" }
```
**macOS/Linux (bash/zsh):**
```bash
echo "=== Node & npm ==="; node --version; npm --version
echo "=== Where is claude? ==="; which claude || echo "claude not on PATH"
echo "=== Try doctor ==="; claude doctor || true
echo "=== API key set? ==="; [ -n "$ANTHROPIC_API_KEY" ] && echo Yes || echo No
```
|
---
Appendix: Useful Paths
- **Windows npm global bin:** `C:\Users\\AppData\Roaming\npm`
- **Windows Node.js:** `C:\Program Files\nodejs`
- **Claude local data (Win):** `C:\Users\\.claude\`
- **Claude config (Win):** `C:\Users\\.claude.json`
- **macOS/Linux npm global bin:** `$(npm config get prefix)/bin` (often `/usr/local/bin` or `$HOME/.npm-global/bin`)
|
## Best Practices
> Curated guidance for safe, fast, and correct use of the Claude Code CLI and interactive REPL. All commands and flags here match the current Anthropic docs as of **Aug 23, 2025**.
Effective Prompting
```bash
# Good: Specific and detailed
claude "Review UserAuth.js for security vulnerabilities, focusing on JWT handling"
# Bad: Vague
claude "check my code"
```
Tip: `claude "query"` starts the interactive REPL pre-seeded with your prompt; `claude -p "query"` runs **print mode** (non‑interactive) and exits.
---
Security Best Practices
1. **Start with minimal permissions**
- Prefer explicit allows and denies, either on the CLI or in settings files.
```bash
# Allow only what you need for this run
claude --allowedTools "Read" "Grep" "LS" "Bash(npm run test:*)"
```
Or commit a project policy at `.claude/settings.json`:
```json
{
"permissions": {
"allow": ["Read", "Grep", "LS", "Bash(npm run test:*)"],
"deny": ["WebFetch", "Bash(curl:*)", "Read(./.env)", "Read(./secrets/**)"]
}
}
```
2. **Handle secrets correctly**
- Use environment variables for SDK/automation flows:
```bash
export ANTHROPIC_API_KEY="your_key" # for SDK/print mode
```
- In the interactive REPL, prefer `/login` instead of hard‑coding tokens.
- Deny access to sensitive files in settings (replaces older `ignorePatterns`):
```json
{ "permissions": { "deny": ["Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)"] } }
```
3. **Audit permissions regularly**
```bash
# Project settings
claude config list
claude config get permissions.allow
claude config get permissions.deny
# Global settings
claude config list -g
```
4. **Avoid bypass modes in production**
- Do **not** use `--dangerously-skip-permissions` outside isolated/dev sandboxes.
- For unattended runs, combine narrow `--allowedTools` with `--disallowedTools` and project settings.
---
1. **Use machine‑readable output in automations**
```bash
claude -p "summarize this error log" --output-format json
# valid: text | json | stream-json
```
2. **Bound non‑interactive work**
```bash
claude -p "run type checks and summarize failures" --max-turns 3
# optionally also bound thinking:
export MAX_THINKING_TOKENS=20000
```
3. **Keep sessions tidy**
```bash
# Retain recent sessions only (default is 30 days)
claude config set -g cleanupPeriodDays 20
```
4. **Limit context scope**
```bash
# Grant access only to relevant paths to reduce scanning/noise
claude --add-dir ./services/api ./packages/ui
```
5. **Pick the right model**
- CLI aliases: `--model sonnet` or `--model opus` (latest of that family).
- For reproducibility in settings, pin a full model ID (e.g., `"claude-3-5-sonnet-20241022"`).
---
Monitoring & Alerting
**1) Health checks**
Use the built‑in **doctor** command to verify installation and environment.
```bash
# Every 15 minutes
*/15 * * * * /usr/local/bin/claude doctor >/dev/null 2>&1 || \
mail -s "Claude Code doctor failed" admin@company.com /tmp/daily-analysis.json
```
**3) Telemetry (optional)**
Claude Code emits OpenTelemetry metrics/events. Set exporters in settings/env (e.g., OTLP) and ship to your observability stack (Datadog, Honeycomb, Prometheus/Grafana, etc.).
---
Collaboration Best Practices
Team Workflows
**1) Share versioned configuration**
```jsonc
// .claude/settings.json (checked into the repo)
{
"permissions": {
"allow": ["Read", "Grep", "LS", "Bash(npm run lint)", "Bash(npm run test:*)"],
"deny": ["WebFetch", "Read(./.env)", "Read(./.env.*)", "Read(./secrets/**)"]
},
// Pin a model here for reproducibility if desired, using a full model ID:
"model": "claude-3-5-sonnet-20241022"
}
```
**2) Documentation automation**
```bash
# Update docs with explicit tasks
claude "Update README.md to reflect the latest API endpoints and examples."
claude "Generate TypeScript types from schema.prisma and write to /types."
```
**3) Code review standards**
```bash
# Review a local diff with constrained tools
git fetch origin main
git diff origin/main...HEAD > /tmp/diff.patch
claude --allowedTools "Read" "Grep" "Bash(git:*)" \
"Review /tmp/diff.patch using team standards:
- Security best practices
- Performance considerations
- Code style compliance
- Test coverage adequacy"
```
Knowledge Sharing
**1) Project runbooks**
```bash
claude "Create a deployment runbook for this app: steps, checks, rollback."
claude "Document onboarding for new developers: setup, commands, conventions."
```
**2) Architecture docs**
```bash
claude "Update architecture docs to reflect new microservices."
claude "Create sequence diagrams for the authentication flow."
```
> Tip: Keep durable context in **CLAUDE.md** at the project root. In the REPL, use `/memory` to manage it and `@path` to import file content into prompts.
---
Common Pitfalls to Avoid
Security
**❌ Don’t**
- Use `--dangerously-skip-permissions` on production systems
- Hard‑code secrets in commands/config
- Grant overly broad permissions (e.g., `Bash(*)`)
- Run with elevated privileges unnecessarily
**✅ Do**
- Store secrets in env vars and credential helpers
- Start from minimal `permissions.allow` and expand gradually
- Audit with `claude config list` / `claude config get`
- Isolate risky operations in containers/VMs
**❌ Don’t**
- Load an entire monorepo when you only need a package
- Max out thinking/turn budgets for simple tasks
- Ignore session cleanup
**✅ Do**
- Use `--add-dir` for focused context
- Right‑size with `--max-turns` and `MAX_THINKING_TOKENS`
- Set `cleanupPeriodDays` to prune old sessions
Workflow
**❌ Don’t**
- Skip project context (`CLAUDE.md`)
- Use vague prompts
- Ignore errors/logs
- Automate without testing
**✅ Do**
- Maintain and update `CLAUDE.md`
- Be specific and goal‑oriented in prompts
- Monitor via logs/OTel as appropriate
- Test automation in safe environments first
---
Third-Party Integrations
DeepSeek Integration
1. ###### Have claude Code installed
```
npm install -g @anthropic-ai/claude-code
```
2. ###### Config Environment Variables
```bash
export ANTHROPIC_BASE_URL=https://api.deepseek.com/anthropic
export ANTHROPIC_AUTH_TOKEN=${YOUR_API_KEY}
export ANTHROPIC_MODEL=deepseek-chat
export ANTHROPIC_SMALL_FAST_MODEL=deepseek-chat
```
3. ###### Now all you need to do is launch `claude`
Find more information from the [Official Deepseek Docs](https://api-docs.deepseek.com/guides/anthropic_api)