Tool Reviews

Claude Code: Complete Guide — Setup, MCP, Agents, Skills

What is Claude Code?

Claude Code is an agentic CLI tool from Anthropic that runs in the terminal and interacts with your codebase directly: reads and edits files, executes commands, searches code, and manages git workflows. Unlike chat interfaces, Claude Code operates in the context of a real project — it sees file structure, dependencies, and configurations. Supports extension through MCP servers, custom skills, subagents, and hooks. Works with a Pro ($20/mo), Max ($100-200/mo) subscription or via API.

TL;DR

  • -Claude Code is an agentic CLI that works with your codebase directly: reads files, executes commands, edits code, manages git — no need to copy context into a chat
  • -One-command install: curl -fsSL https://claude.ai/install.sh | bash (macOS/Linux) or via Homebrew/npm; authentication through Pro/Max subscription or API key
  • -CLAUDE.md is a project instructions file loaded into every session: build commands, code standards, architectural decisions; recommended size is under 200 lines
  • -MCP servers extend Claude Code with external tools (GitHub, Notion, databases); configured in .mcp.json at the project level or in ~/.claude.json for personal servers
  • -Subagents are specialized AI instances with separate context; defined as markdown files in .claude/agents/, can run in parallel and have restricted tool sets
  • -Average API cost is $13/day per developer (90% of users spend less than $30/day); Pro plan is $20/mo, Max 5x is $100/mo, Max 20x is $200/mo

Claude Code is an agentic CLI from Anthropic. It runs in the terminal, works with your project directly: reads files, executes shell commands, edits code, manages git. No need to copy code into a chat — Claude sees the entire codebase.

It is a standalone CLI, not an IDE extension like Cursor or Windsurf. Not tied to any editor. Operates via stdin/stdout, integrates into any process — from interactive development to CI/CD.

What Claude Code Can Do

Built-in tools:

  • Read/Write/Edit — reading, creating, and editing files with support for targeted replacements. Edit uses exact string matching for precise changes — it does not rewrite the entire file
  • Bash — executing shell commands with full access to the environment. Each command requires user approval (unless added to the allowlist)
  • Glob — file search by patterns (**/*.ts, src/**/*.test.js). Returns paths sorted by modification time
  • Grep — content search across files via ripgrep. Supports regex, file type filtering, context lines
  • Agent — launching subagents for parallel tasks with isolated context
  • WebSearch/WebFetch — web search and page fetching for up-to-date information
  • LSP — code navigation via Language Server Protocol (go to definition, find references)
  • MCP tools — any external integrations via Model Context Protocol

Claude Code works agentically: it receives a task, decomposes it, uses tools, verifies the result. A single prompt triggers a chain of dozens of actions — from code analysis to commit.

A typical workflow for a request like “fix the authentication bug”:

  1. Claude searches for files related to authentication (Grep/Glob)
  2. Reads the code and analyzes the logic (Read)
  3. Finds the issue and edits files (Edit)
  4. Runs tests for verification (Bash)
  5. If needed — fixes the tests
  6. Creates a commit with a meaningful message (Bash: git commit)

Comparison with Claude.ai, Cursor, Windsurf

FeatureClaude.aiCursor/WindsurfClaude Code
InterfaceWeb/desktop chatIDE (VS Code fork)Terminal CLI
File accessManual uploadOpen projectEntire project automatically
Command executionSandbox (limited)Built-in terminalFull shell access
MCP serversVia ConnectorsLimitedFull support
AutomationNoLimitedSDK, hooks, CI/CD
Git operationsNoBasicFull workflow
SubagentsNoNoBuilt-in support

Installation and First Run

System Requirements

  • macOS, Linux, or Windows (via WSL2)
  • Node.js 18+ (for npm installation)
  • Git (recommended)
  • Pro/Max subscription or Anthropic API key

Installation

Recommended method — via curl (macOS/Linux):

curl -fsSL https://claude.ai/install.sh | bash

Alternative options:

# Homebrew (macOS/Linux)
brew install --cask claude-code

# npm (deprecated, but works)
npm install -g @anthropic-ai/claude-code

# Windows (PowerShell)
irm https://claude.ai/install.ps1 | iex

# Windows Package Manager
winget install Anthropic.ClaudeCode

Verify installation:

claude --version

Authentication

Two authentication methods:

Via Pro/Max subscription — the primary option:

claude
# On first launch, a browser window opens for authentication
# Sign in with your claude.ai account

Via API key — for API billing or corporate use:

export ANTHROPIC_API_KEY="sk-ant-..."
claude

If ANTHROPIC_API_KEY is set, Claude Code uses it instead of the subscription. Billing switches to API rates; Pro/Max quota is not consumed. To switch back:

claude auth logout
claude auth login  # Choose subscription-based authentication

First Run

cd /path/to/your/project
claude

Claude Code reads CLAUDE.md (if present), connects MCP servers from .mcp.json, loads auto memory and skills.

Commands are plain natural language:

> Explain the architecture of this project
> Find all TODOs in the code
> Add input validation to auth.ts
> Run tests and fix errors

Every file operation and bash command requires approval. Trusted commands can be skipped via permissions:

{
  "permissions": {
    "allow": [
      "Bash(npm test *)",
      "Bash(git log *)",
      "Bash(git diff *)",
      "Read(*)"
    ]
  }
}

This is saved in .claude/settings.json (project) or ~/.claude/settings.json (global).

To exit — Ctrl+C or the /exit command.

Updating

claude update

Or reinstall using the same method. Updates are released frequently. Check version:

claude --version

CLAUDE.md — Project Context Configuration

An instructions file loaded into the context of every session. Defines build commands, code standards, and architectural rules for the project. The principles behind effective context management are covered in depth in the context engineering guide.

Location and Priority

Files are loaded from multiple levels. More specific ones take priority:

LevelLocationPurpose
Managed policy/Library/Application Support/ClaudeCode/CLAUDE.mdCorporate standards (deployed via MDM)
Project./CLAUDE.md or ./.claude/CLAUDE.mdTeam instructions, committed to the repository
User~/.claude/CLAUDE.mdPersonal preferences for all projects
Local./CLAUDE.local.mdPersonal project settings (gitignored)

Claude Code traverses the directory tree upward from the current location: if launched in foo/bar/, it loads foo/bar/CLAUDE.md, foo/CLAUDE.md, and all CLAUDE.local.md files alongside them.

File Structure

A good CLAUDE.md is specific and concise. Target size — under 200 lines.

# Project conventions

## Commands
- Build: `npm run build`
- Test: `npm test -- --watch`
- Lint: `npm run lint`
- Deploy: `npm run deploy`

## Stack
- TypeScript 5.x, strict mode
- React 19, functional components only
- Prisma ORM, PostgreSQL

## Code standards
- Named exports, never default exports
- Tests next to source: `foo.ts``foo.test.ts`
- API routes return `{ data, error }` shape
- Use `zod` for input validation

## Architecture
- `src/api/` — API handlers
- `src/services/` — business logic
- `src/lib/` — shared utilities
- `src/types/` — TypeScript types

## Git
- Conventional commits: `feat:`, `fix:`, `refactor:`
- PR description required
- Squash merge into main

File Imports

Import via @path syntax:

@README.md
@docs/architecture.md
@package.json

# Additional rules
- Always check test coverage before committing

Files are expanded at session start. Nesting — up to 5 levels deep. Paths are relative to the importing file.

Automatic Generation

The /init command analyzes the codebase and generates a starter CLAUDE.md:

claude
> /init

If CLAUDE.md already exists, /init suggests improvements rather than overwriting the file.

Extended mode with interactive flow:

CLAUDE_CODE_NEW_INIT=1 claude
> /init

Claude will ask which artifacts to set up (CLAUDE.md, skills, hooks). It explores the codebase with a subagent, asks clarifying questions, then shows the proposal before writing files.

Organize rules — Structuring Rules

For large projects, instructions can be split into files within .claude/rules/:

.claude/rules/
├── testing.md        # Testing rules
├── api-design.md     # API conventions
├── security.md       # Security requirements
└── frontend/
    └── components.md # Component rules

Rules files can be scoped to file patterns via YAML frontmatter:

---
paths:
  - "src/api/**/*.ts"
---

All API handlers must validate input with zod schemas.
Return 400 for validation errors with field-level details.

This loads the rule only when working with files matching the pattern.

MCP Servers

Model Context Protocol (MCP) is a standard for integrating AI with external services. MCP servers give Claude Code access to GitHub, Notion, databases, monitoring, and other APIs.

How It Works

An MCP server is a process that starts with the session and exposes tools through a standardized protocol. Claude Code automatically discovers available tools and invokes them as needed.

Tool schemas are lazily loaded (deferred by default) — only names appear in the context, while full definitions are loaded on first use. This saves tokens.

Configuration

Project level (.mcp.json in the project root, committed to the repository):

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "${GITHUB_TOKEN}"
      }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "DATABASE_URL": "${DATABASE_URL}"
      }
    }
  }
}

User level (via CLI, saved in ~/.claude.json):

# Add a server for all projects
claude mcp add --scope user github \
  npx -y @modelcontextprotocol/server-github

# Add with environment variables
claude mcp add --scope user notion \
  npx -y @notionhq/notion-mcp-server \
  -e NOTION_API_KEY="${NOTION_API_KEY}"

Useful MCP Servers

Development and DevOps:

ServerPurposePackage
GitHubIssues, PR, code search@modelcontextprotocol/server-github
PostgreSQLSQL queries to the database@modelcontextprotocol/server-postgres
SentryErrors and monitoring@sentry/mcp-server-sentry
SupabaseProject managementBuilt into Claude Code

Productivity:

ServerPurposePackage
NotionPages, databases@notionhq/notion-mcp-server
LinearTasks and projectslinear-mcp (via OAuth)
SlackMessages and channels@modelcontextprotocol/server-slack
Google WorkspaceDocs, Sheets, GmailCommunity servers

Data and Search:

ServerPurposePackage
Brave SearchWeb search@modelcontextprotocol/server-brave-search
ExaAI-powered searchCommunity server
FilesystemFile access@modelcontextprotocol/server-filesystem

Managing Servers

# List servers
claude mcp list

# Status within a session
> /mcp

# Remove a server
claude mcp remove github

# Disable without removing
claude mcp disable github

Writing a Custom MCP Server

No existing server for your needs — build your own. An MCP server communicates via stdin/stdout using JSON-RPC. For a deeper look at designing and deploying custom MCP servers in production, see the MCP production servers guide.

Minimal server in Node.js:

import { Server } from "@modelcontextprotocol/sdk/server/index.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";

const server = new Server({
  name: "my-custom-server",
  version: "1.0.0",
});

server.setRequestHandler("tools/list", async () => ({
  tools: [{
    name: "get_status",
    description: "Get service status",
    inputSchema: {
      type: "object",
      properties: {
        service: { type: "string", description: "Service name" }
      },
      required: ["service"]
    }
  }]
}));

server.setRequestHandler("tools/call", async (request) => {
  if (request.params.name === "get_status") {
    const status = await checkStatus(request.params.arguments.service);
    return { content: [{ type: "text", text: JSON.stringify(status) }] };
  }
});

const transport = new StdioServerTransport();
await server.connect(transport);

SDKs are available for TypeScript, Python, Go, Rust, and other languages. Documentation: modelcontextprotocol.io.

Claude Code as an MCP Server

Claude Code itself can serve as an MCP server for other applications:

claude mcp serve

Configuration for Claude Desktop:

{
  "mcpServers": {
    "claude-code": {
      "type": "stdio",
      "command": "claude",
      "args": ["mcp", "serve"]
    }
  }
}

Optimizing MCP Servers

MCP tools consume context. What to do:

  • Disable unused servers via /mcp
  • For CLI tools (gh, aws, gcloud), direct invocation via Bash is preferable — zero overhead for tool definitions
  • Check context consumption via /cost

Agents and Subagents

Agent Tool

Agent is a built-in tool for launching subagents. A subagent is a separate Claude instance with its own context, prompt, and (optionally) a restricted set of tools.

Why:

  • Context isolation — intermediate results do not clutter the main conversation
  • Parallelization — multiple subagents work simultaneously
  • Specialization — each subagent receives a prompt with expertise for a specific task
  • Tool restrictions — a subagent can be denied file writing or command execution

Creating Subagents

Subagents are defined as markdown files:

  • Project-level: .claude/agents/*.md
  • Global: ~/.claude/agents/*.md

File format is markdown with YAML frontmatter:

---
name: code-reviewer
description: Expert code review specialist. Use for quality, security, and maintainability reviews.
tools: Read, Grep, Glob
---

You are a code review specialist. Focus on:
1. Correctness — logic errors, edge cases, race conditions
2. Security — injection, auth bypass, data exposure
3. Performance — N+1 queries, unnecessary allocations
4. Maintainability — naming, abstraction level, test coverage

Provide specific, actionable feedback with code examples.
Prioritize issues by severity: critical > major > minor > suggestion.

Configuration fields:

FieldRequiredDescription
nameYesIdentifier (lowercase, hyphens)
descriptionYesWhen to use the subagent
toolsNoAllowed tools. Without this field — all tools are available
modelNoModel (haiku, sonnet, opus)

Example: Parallel Code Review

---
name: security-scanner
description: Scan code for security vulnerabilities
tools: Read, Grep, Glob
model: sonnet
---

Analyze code for OWASP Top 10 vulnerabilities:
- SQL injection, XSS, CSRF
- Hardcoded secrets and credentials
- Insecure deserialization
- Broken access control

Return findings as structured JSON with severity levels.
---
name: test-coverage
description: Analyze test coverage and suggest missing tests
tools: Read, Grep, Glob, Bash
model: sonnet
---

Analyze test coverage:
1. Find untested functions and edge cases
2. Check boundary conditions
3. Verify error handling paths
4. Suggest specific test cases to add

When asked to “do a full code review,” Claude Code can launch both subagents in parallel and aggregate the results. For a systematic approach to AI-assisted code review, see the AI code review checklist.

Auto Memory for Subagents

Subagents accumulate knowledge between sessions through persistent memory:

---
name: debugger
description: Debug complex issues across the codebase
tools: Read, Grep, Glob, Bash
memory: user
---

Subagent memory is stored in ~/.claude/agent-memory/ and loaded on every invocation. Available values: user (shared across all projects), project (tied to the repository), local (current directory).

Skills and Commands

Skills (formerly commands) are reusable prompts. Invoked as /name within a session.

Location

  • Project-level: .claude/commands/*.md or .claude/skills/<name>/SKILL.md
  • Global: ~/.claude/commands/*.md or ~/.claude/skills/<name>/SKILL.md

Simple Skill

File .claude/commands/review.md:

Review the current git diff for:
1. Code quality and readability
2. Security vulnerabilities
3. Performance implications
4. Missing test coverage

Provide actionable feedback organized by priority.

Usage: /review in a Claude Code session.

Skill with Frontmatter

.claude/commands/fix-issue.md:

---
allowed-tools: Read, Grep, Glob, Edit, Bash
argument-hint: [issue-number]
description: Fix a GitHub issue by number
---

Fix GitHub issue #$1:
1. Read the issue description from GitHub
2. Understand the requirements
3. Find relevant code
4. Implement the fix
5. Write tests
6. Create a commit with conventional message

Usage: /fix-issue 42

Dynamic Context

Two mechanisms for injecting context:

Bash substitution — command output is included in the prompt:

---
description: Create a git commit based on current changes
allowed-tools: Bash(git add:*), Bash(git status:*), Bash(git commit:*)
---

## Context
- Status: !`git status`
- Diff: !`git diff HEAD`

## Task
Create a commit with conventional commit message based on the changes above.

File references — file contents are inserted into the prompt:

---
description: Review project configuration
---

Review these configuration files:
- @package.json
- @tsconfig.json
- @.env.example

Check for security issues, outdated dependencies, and misconfigurations.

Organizing Skills

Subdirectories create a namespace:

.claude/commands/
├── frontend/
│   ├── component.md      # /component
│   └── style-check.md    # /style-check
├── backend/
│   ├── api-test.md       # /api-test
│   └── db-migrate.md     # /db-migrate
└── review.md             # /review

For skills with nested files — use the skills/ format:

.claude/skills/
└── deploy/
    ├── SKILL.md           # /deploy
    ├── checklist.md       # Resource file
    └── templates/
        └── release.md     # Template

Viewing Available Skills

> /skills    # List all skills
> /help      # Including built-in commands

Hooks — Behavior Automation

Hooks are shell commands triggered at specific stages of the Claude Code lifecycle. Unlike CLAUDE.md (recommendations), hooks are code that runs deterministically every time.

Hook Types

HookWhen TriggeredCan Block
PreToolUseBefore a tool invocationYes
PostToolUseAfter a tool completesNo
UserPromptSubmitWhen the user submits a promptYes
NotificationOn notificationNo
StopWhen Claude finishes a responseYes
SubagentStopWhen a subagent completes a taskYes
PreCompactBefore a compact operationNo
PostCompactAfter a compact operationNo
SessionStartAt session startNo
SessionEndAt session endNo

Configuration

Hooks are configured in settings.json (project or user level) or via /hooks:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | { read f; if echo \"$f\" | grep -q '\\.ts$'; then npx prettier --write \"$f\"; fi; }"
          }
        ]
      }
    ]
  }
}

This hook automatically formats TypeScript files with Prettier after every edit.

Hook Examples

Auto-formatting Go files:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '.tool_input.file_path' | { read f; if echo \"$f\" | grep -q '\\.go$'; then gofmt -w \"$f\"; fi; }"
          }
        ]
      }
    ]
  }
}

Protecting sensitive files from editing:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [
          {
            "type": "command",
            "command": "python3 -c \"import json, sys; data=json.load(sys.stdin); path=data.get('tool_input',{}).get('file_path',''); sys.exit(2 if any(p in path for p in ['.env', 'package-lock.json', '.git/']) else 0)\""
          }
        ]
      }
    ]
  }
}

sys.exit(2) blocks the operation and passes feedback to Claude about the reason for blocking.

Logging all bash commands:

{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "jq -r '\"\\(.tool_input.command) - \\(.tool_input.description // \"No description\")\"' >> ~/.claude/bash-command-log.txt"
          }
        ]
      }
    ]
  }
}

Desktop notification when awaiting input:

{
  "hooks": {
    "Notification": [
      {
        "matcher": "",
        "hooks": [
          {
            "type": "command",
            "command": "osascript -e 'display notification \"Awaiting your input\" with title \"Claude Code\"'"
          }
        ]
      }
    ]
  }
}

Configuration via UI

Instead of manually editing settings.json:

> /hooks
# Choose hook type → add matcher → specify command

Limits and Pricing

Subscription Plans

PlanPriceUsage LimitClaude Code
Free$0BasicNo
Pro$20/moStandardIncluded
Max 5x$100/mo5x of ProIncluded
Max 20x$200/mo20x of ProIncluded
Team (Premium seat)$100/mo (annual) / $125/mo (monthly)5xIncluded
EnterpriseCustom pricing (via sales)IndividualIncluded

Pro and Max limits are shared between Claude.ai and Claude Code — the same quota for both tools.

API Pricing

When using an API key (not a subscription) — pay-per-token billing:

ModelInput (per 1M tokens)Output (per 1M tokens)
Opus 4.6$5$25
Sonnet 4.6$3$15
Haiku 4.5$1$5

Prompt caching reduces the cost of repeated context (system prompt, CLAUDE.md):

  • Write cache: 1.25x of input price
  • Read cache: 0.1x of input price

Average API cost: $13 per day per developer. 90% of users spend less than $30/day. For teams — approximately $150-250/mo per developer.

What to Do When You Hit the Limit

Pro: upgrade to Max 5x, enable extra usage, switch to API, wait for the quota to reset.

Max: upgrade to Max 20x, enable extra usage, switch to API.

Checking status:

> /status     # Current configuration, version, and subscription
> /cost       # Token consumption for the session (API)
> /stats      # Usage statistics and session history

Optimizing Costs

  • Use Sonnet for everyday tasks, Opus for complex architecture and multi-step reasoning
  • Switch models on the fly: /model
  • Clear context between tasks: /clear
  • Delegate verbose operations (tests, logs) to subagents
  • Keep CLAUDE.md compact — it loads every session

Advanced Techniques

Auto Memory

Claude accumulates knowledge between sessions without manual input. It decides what to remember on its own: build commands, debugging insights, architectural notes, code style preferences.

Storage: ~/.claude/projects/<project>/memory/

memory/
├── MEMORY.md          # Index, loaded every session (first 200 lines / 25KB)
├── debugging.md       # Debugging patterns
├── api-conventions.md # API decisions
└── ...

MEMORY.md is the index that Claude reads at startup. Other files are read on demand.

Management:

> /memory              # View and edit

Enable/disable:

{
  "autoMemoryEnabled": false
}

All memory files are plain markdown that can be edited or deleted.

Plan Mode

A mode where Claude analyzes the codebase and proposes a plan without making changes. Toggle: Shift+Tab.

Use cases:

  • Before major refactorings — agree on the approach before starting work
  • Architecture analysis without the risk of accidental changes
  • Token savings: agreeing on a plan is cheaper than redoing an incorrect implementation

Git Worktrees

Claude works in an isolated repository clone:

claude --worktree

Claude creates a worktree, copies gitignored files from .worktreeinclude, performs the work, and returns to the main repository.

.worktreeinclude file in the project root:

.env
.env.local
node_modules/

Subagents can also use worktree isolation:

---
name: experimental-refactor
description: Try experimental refactoring approaches
isolation: worktree
tools: Read, Edit, Bash, Grep, Glob
---

Compact — Context Management

When the context window fills up, Claude Code automatically compresses the conversation history.

Manual invocation with custom instructions:

> /compact Focus on code changes and test results

CLAUDE.md files survive compaction — they are re-read from disk and re-injected into the session.

Configuring behavior in CLAUDE.md:

# Compact instructions
When compacting, preserve: test output, code changes, architectural decisions.
Discard: exploration steps, file listings, intermediate search results.

Model Selection

Switch models within a session:

> /model

Recommendations:

TaskModelWhy
Day-to-day developmentSonnet 4.6Balance of speed and quality
Architectural decisionsOpus 4.6Deep multi-step reasoning
Simple subagentsHaiku 4.5Minimal cost

Extended Thinking

Enabled by default — Claude “thinks” before responding. On complex tasks, this noticeably improves quality. Thinking tokens are billed as output.

Control:

> /effort        # Effort level: low, medium, high, max

Environment variable to limit the budget:

export MAX_THINKING_TOKENS=8000

Session Context

What is loaded into context:

> /cost          # Token consumption for the session (API)
> /memory        # CLAUDE.md and rules files
> /mcp           # MCP servers and tools
> /skills        # Available skills
> /permissions   # Current permissions
> /status        # Version, model, account, and connections

Resume — Continuing Sessions

# Show recent sessions
claude --resume

# Continue the last session
claude --continue

# Rename a session for convenience
> /rename refactoring-auth-module

Real-World Use Cases

Onboarding to a New Project

> Explain the project architecture: main modules, how they connect,
  what frameworks and patterns are used

Claude will read key files (package.json, configs, entry points), traverse the directory structure, and provide a concise overview. Then — follow-up questions:

> How is authentication structured? Show the flow from login to token retrieval
> What API endpoints exist? Create a table: path, method, purpose

Refactoring

> Convert all callback-based functions in src/services/ to async/await.
  Preserve existing behavior. Run tests after each file.

Claude will process files sequentially, running tests between changes. On error — it stops and fixes before moving to the next file.

Bug Investigation

> Production is throwing "Connection timeout" errors in the auth service.
  Logs: cat /tmp/auth-errors.log
  Find the root cause and propose a fix.

Claude will analyze the logs, find the error pattern, trace the code from the failure point to the root cause, and propose a fix.

Test Generation

For maximum effectiveness, test generation works best when combined with TDD with AI, where Claude Code drives development iteratively through the red-green-refactor cycle.

> Write tests for src/services/billing.ts.
  Cover: happy path, edge cases, error handling.
  Use vitest. Mock external dependencies.

CI/CD Integration

Claude Code integrates into CI pipelines for automated code review or fixes:

# In GitHub Actions
claude -p "Review the diff and report critical issues" \
  --output-format json \
  --yes \
  --max-turns 3
# Automatic linter error fixes
claude -p "Fix all ESLint errors in the staged files" --yes

Tips & Tricks

Effective Prompts

Specificity saves tokens. Instead of “improve this code” — “add input validation to the processPayment function in src/billing/processor.ts.”

Include verification criteria: “run tests and make sure they all pass,” “show the diff before committing.”

  • Escape — stop current generation
  • Double Escape/rewind to previous checkpoint (rolls back both conversation and code)
  • Shift+Tab — toggle plan mode

Multiple Instances

Claude Code runs in multiple terminals simultaneously. Each instance is a separate session with its own context.

Pattern: one instance for development, another for testing and debugging.

Incremental Development

Instead of “implement the entire feature at once”:

  1. Write one file → test → continue
  2. Use plan mode to agree on the approach before implementing
  3. /clear between unrelated tasks

Errors are caught early when they are cheap to fix.

CLI Flags for Automation

# One-off request without interactive session
claude -p "explain the auth flow in this project"

# With specific output format
claude -p "list all API endpoints" --output-format json

# Pipe stdin
cat error.log | claude -p "analyze these errors"

# Non-interactive with automatic approval
claude -p "fix all lint errors" --yes

SDK for Programmatic Use

npm/Python package for integration into your own tools:

import { query } from "@anthropic-ai/claude-agent-sdk";

for await (const message of query({
  prompt: "Fix the failing tests",
  options: { maxTurns: 5 }
})) {
  if (message.type === "result") {
    console.log(message.result);
  }
}
from claude_agent_sdk import query

result = query(
    prompt="Analyze test coverage",
    options={"max_turns": 3}
)

Security

  • Claude Code executes commands with the current user’s permissions. Do not run as root
  • Hooks run with your credentials — review them before adding
  • PreToolUse hooks can block operations — use them to protect production files
  • Reference secrets in .mcp.json via ${ENV_VAR}, do not hardcode them
  • /permissions — check current permissions

Before integrating AI tools into production workflows, it is worth running a dedicated AI security audit.

Useful Built-in Commands

CommandPurpose
/initGenerate CLAUDE.md
/compactManual context compression
/clearClear conversation
/modelSwitch model
/costToken consumption for the session (API)
/statsUsage statistics and session history
/statusVersion, model, account, and connections
/memoryMemory management
/hooksHook configuration
/mcpMCP server status
/skillsAvailable skills
/rewindRoll back to checkpoint
/resumeContinue a previous session
/renameRename session
/loginSwitch authentication
/logoutLog out
/effortThinking level
/permissionsCurrent permission rules

Common Issues and Solutions

Claude Does Not Follow CLAUDE.md Instructions

CLAUDE.md is context, not strict configuration. Claude tries to follow instructions, but 100% compliance is not guaranteed.

Diagnostics:

> /memory  # Verify the file is loaded
> /status  # Check version and configuration

Solutions:

  • Make instructions more specific: “use 2-space indentation” instead of “format code nicely”
  • Remove conflicting instructions between files
  • Reduce CLAUDE.md size (target — under 200 lines)
  • For critical rules, use hooks instead of instructions

Context Window Overflows

Symptoms: Claude forgets earlier decisions, response quality degrades.

> /compact  # Compress history while preserving key decisions
> /clear    # Full reset for an unrelated task

Prevention: /clear between tasks, delegate verbose operations to subagents, keep CLAUDE.md compact.

MCP Server Fails to Connect

> /mcp           # Server status
> /status        # General connection diagnostics

Common causes:

  • npx package not installed (first run may take time)
  • Token environment variable not set
  • Port occupied by another process (for HTTP servers)

API Key Instead of Subscription

If ANTHROPIC_API_KEY is set, Claude Code uses API billing even with an active Pro/Max subscription:

unset ANTHROPIC_API_KEY
claude auth logout
claude auth login  # Choose subscription

FAQ

Can I use Claude Code offline?

No. Claude Code sends requests to the Anthropic API with every action. There are no local models. Without a stable internet connection, the tool does not work.

How does Claude Code handle private code? Does data go to Anthropic servers?

Code is sent to the API for processing. Anthropic does not use API and Pro/Max user data for model training. For corporate scenarios, there is an Enterprise plan with additional guarantees and SSO. If company policy prohibits sending code to external services, Claude Code is not suitable.

Does Claude Code work with monorepos?

Yes. Claude Code operates from the current directory. In a monorepo, launch it from the root or from a specific package. CLAUDE.md at each level lets you set context: shared rules at the root, specific ones in packages. Git worktrees also work with monorepos.

Can I run Claude Code in a Docker container?

Yes. Claude Code is a standard Node.js CLI. Install it in a container, pass ANTHROPIC_API_KEY via environment variable, and run in non-interactive mode with claude -p "task" --yes. A popular scenario is a CI/CD pipeline where Claude performs code review or automatic fixes.

How do I restrict which files Claude Code can access?

Three mechanisms. Permissions in settings.json control which commands run without approval. PreToolUse hooks block operations by pattern (e.g., preventing writes to .env). A .claudeignore file (similar to .gitignore) excludes files from indexing.

Does Claude Code support Git branch operations?

Fully. Claude Code executes any git command through Bash: creates branches, switches between them, performs merge and rebase. The --worktree flag launches a session in an isolated git worktree. When committing, Claude generates meaningful messages based on the diff.

How do I use Claude Code in a team? Configuration conflicts?

Team settings are stored in committed files: CLAUDE.md, .mcp.json, .claude/settings.json, skills in .claude/commands/. Personal settings go in CLAUDE.local.md (gitignored) and ~/.claude/ (global). There are no conflicts: project files are identical for everyone, personal files are each developer’s own.

Can I use Claude Code with other LLMs (GPT-5.4, Gemini)?

Claude Code works only with Claude models (Anthropic API). Other providers are not supported natively. Through MCP servers you can connect external LLMs as tools — an MCP server for the OpenAI API, for instance — and call them from inside a Claude Code session.

What happens if Claude Code breaks code in the project?

Every action (Edit, Bash) requires user approval (except commands in the allowlist). Double Escape rolls back the last change along with the conversation history. Git worktrees provide full isolation. If something goes wrong, git diff shows all changes, git checkout . reverts everything. Claude Code does nothing that cannot be undone via git.

How do I debug MCP servers that are not working?

Check status via /mcp in the session. Verify that environment variables are set (tokens, keys). Run the server manually in the terminal (npx -y @package/name) — this will reveal startup errors. MCP logs are available in ~/.claude/logs/. For custom servers, check stdin/stdout: MCP communicates via JSON-RPC over standard streams, and any extra output to stdout breaks the protocol.

Conclusion

Claude Code removes the layer between AI and code — direct project interaction instead of copying into a chat. MCP servers, subagents, skills, and hooks adapt it to any stack and workflow.

Recommendations to get started:

  1. Set up CLAUDE.md with build commands and project standards
  2. Connect 2-3 MCP servers you use daily (GitHub, database)
  3. Create skills for recurring tasks (review, deploy, test)
  4. Add an auto-formatting hook for your stack
  5. Use plan mode before major changes

Start small: one project, a basic CLAUDE.md, no MCP. As you gain proficiency, add servers, subagents, and automation. Through auto memory, each subsequent session becomes more efficient than the last.

Claude Code documentation: code.claude.com/docs. Example repository: github.com/anthropics/claude-code.