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

> Claude Code: complete guide to Anthropic's agentic CLI. Installation, CLAUDE.md, MCP servers, subagents, skills, hooks, and best practices for developers.
> Author: Roman Belov · Published: 2026-04-13 · Source: https://futurecraft.pro/blog/claude-code-complete-guide/

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

| Feature | Claude.ai | Cursor/Windsurf | Claude Code |
|---|---|---|---|
| Interface | Web/desktop chat | IDE (VS Code fork) | Terminal CLI |
| File access | Manual upload | Open project | Entire project automatically |
| Command execution | Sandbox (limited) | Built-in terminal | Full shell access |
| MCP servers | Via Connectors | Limited | Full support |
| Automation | No | Limited | SDK, hooks, CI/CD |
| Git operations | No | Basic | Full workflow |
| Subagents | No | No | Built-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):

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

Alternative options:

```bash
# 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:

```bash
claude --version
```

### Authentication

Two authentication methods:

**Via Pro/Max subscription** — the primary option:

```bash
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:

```bash
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:

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

### First Run

```bash
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:

```json
{
  "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

```bash
claude update
```

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

```bash
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](/blog/context-engineering-guide/).

### Location and Priority

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

| Level | Location | Purpose |
|---|---|---|
| Managed policy | `/Library/Application Support/ClaudeCode/CLAUDE.md` | Corporate standards (deployed via MDM) |
| Project | `./CLAUDE.md` or `./.claude/CLAUDE.md` | Team instructions, committed to the repository |
| User | `~/.claude/CLAUDE.md` | Personal preferences for all projects |
| Local | `./CLAUDE.local.md` | Personal 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.

```markdown
# 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:

```markdown
@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:

```bash
claude
> /init
```

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

Extended mode with interactive flow:

```bash
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:

```markdown
---
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 — see [how MCP servers work under the hood](/blog/mcp-servers-explained/) for the protocol-level details. 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):

```json
{
  "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`):

```bash
# 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:**

| Server | Purpose | Package |
|---|---|---|
| GitHub | Issues, PR, code search | `@modelcontextprotocol/server-github` |
| PostgreSQL | SQL queries to the database | `@modelcontextprotocol/server-postgres` |
| Sentry | Errors and monitoring | `@sentry/mcp-server-sentry` |
| Supabase | Project management | `@supabase/mcp-server-supabase` |

**Productivity:**

| Server | Purpose | Package |
|---|---|---|
| Notion | Pages, databases | `@notionhq/notion-mcp-server` |
| Linear | Tasks and projects | `linear-mcp` (via OAuth) |
| Slack | Messages and channels | `@modelcontextprotocol/server-slack` |
| Google Workspace | Docs, Sheets, Gmail | Community servers |

**Data and Search:**

| Server | Purpose | Package |
|---|---|---|
| Brave Search | Web search | `@modelcontextprotocol/server-brave-search` |
| Exa | AI-powered search | Community server |
| Filesystem | File access | `@modelcontextprotocol/server-filesystem` |

### Managing Servers

```bash
# List servers
claude mcp list

# Status, enable and disable servers within a session
> /mcp

# Remove a server
claude mcp remove 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](/blog/mcp-production-custom-servers/).

Minimal server in Node.js:

```typescript
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](https://modelcontextprotocol.io).

### Claude Code as an MCP Server

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

```bash
claude mcp serve
```

Configuration for Claude Desktop:

```json
{
  "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:

```markdown
---
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:

| Field | Required | Description |
|---|---|---|
| `name` | Yes | Identifier (lowercase, hyphens) |
| `description` | Yes | When to use the subagent |
| `tools` | No | Allowed tools. Without this field — all tools are available |
| `model` | No | Model (haiku, sonnet, opus) |

### Example: Parallel Code Review

```markdown
---
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.
```

```markdown
---
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](/blog/ai-code-review-checklist/).

### Auto Memory for Subagents

Subagents accumulate knowledge between sessions through persistent memory:

```markdown
---
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. For advanced patterns — dynamic arguments, subagents, hooks, memory — see the [dedicated guide to Claude Code skills and agents](/blog/claude-code-skills-agents/).

### 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`:

```markdown
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`:

```markdown
---
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:

```markdown
---
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:

```markdown
---
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

```bash
> /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

| Hook | When Triggered | Can Block |
|---|---|---|
| `PreToolUse` | Before a tool invocation | Yes |
| `PostToolUse` | After a tool completes | No |
| `UserPromptSubmit` | When the user submits a prompt | Yes |
| `Notification` | On notification | No |
| `Stop` | When Claude finishes a response | Yes |
| `SubagentStop` | When a subagent completes a task | Yes |
| `PreCompact` | Before a compact operation | No |
| `PostCompact` | After a compact operation | No |
| `SessionStart` | At session start | No |
| `SessionEnd` | At session end | No |

### Configuration

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

```json
{
  "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:**

```json
{
  "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:**

```json
{
  "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:**

```json
{
  "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:**

```json
{
  "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`:

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

## Limits and Pricing

### Subscription Plans

| Plan | Price | Usage Limit | Claude Code |
|---|---|---|---|
| Free | $0 | Basic | No |
| Pro | $20/mo | Standard | Included |
| Max 5x | $100/mo | 5x of Pro | Included |
| Max 20x | $200/mo | 20x of Pro | Included |
| Team (Premium seat) | $100/mo (annual) / $125/mo (monthly) | 5x | Included |
| Enterprise | Custom pricing (via sales) | Individual | Included |

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:

| Model | Input (per 1M tokens) | Output (per 1M tokens) |
|---|---|---|
| Opus 4.8 | $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

Per Anthropic's data across enterprise deployments, the average API cost is **$13 per active day** per developer, with 90% of users staying below $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:

```bash
> /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:

```bash
> /memory              # View and edit
```

Enable/disable:

```json
{
  "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:

```bash
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:

```markdown
---
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:

```bash
> /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:

```markdown
# 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:

```bash
> /model
```

Recommendations:

| Task | Model | Why |
|---|---|---|
| Day-to-day development | Sonnet 4.6 | Balance of speed and quality |
| Architectural decisions | Opus 4.8 | Deep multi-step reasoning |
| Simple subagents | Haiku 4.5 | Minimal cost |

### Extended Thinking

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

Control:

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

Environment variable to limit the budget:

```bash
export MAX_THINKING_TOKENS=8000
```

### Session Context

What is loaded into context:

```bash
> /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

```bash
# 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](/blog/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:

```bash
# In GitHub Actions
claude -p "Review the diff and report critical issues" \
  --output-format json \
  --dangerously-skip-permissions
```

```bash
# Automatic linter error fixes
claude -p "Fix all ESLint errors in the staged files" --dangerously-skip-permissions
```

## Tips & Tricks

### Effective Prompts

Specificity saves tokens. Instead of "improve this code" — "add input validation to the `processPayment` function in `src/billing/processor.ts`." For a systematic breakdown of what makes a prompt work — anatomy, principles, production system prompts — see [how to write prompts for developers](/blog/how-to-write-prompts/).

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

### Navigation and Undo

- `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

```bash
# 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" --dangerously-skip-permissions
```

### SDK for Programmatic Use

npm/Python package for integration into your own tools:

```typescript
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);
  }
}
```

```python
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](/blog/ai-security-audit/).

### Useful Built-in Commands

| Command | Purpose |
|---|---|
| `/init` | Generate CLAUDE.md |
| `/compact` | Manual context compression |
| `/clear` | Clear conversation |
| `/model` | Switch model |
| `/cost` | Token consumption for the session (API) |
| `/stats` | Usage statistics and session history |
| `/status` | Version, model, account, and connections |
| `/memory` | Memory management |
| `/hooks` | Hook configuration |
| `/mcp` | MCP server status |
| `/skills` | Available skills |
| `/rewind` | Roll back to checkpoint |
| `/resume` | Continue a previous session |
| `/rename` | Rename session |
| `/login` | Switch authentication |
| `/logout` | Log out |
| `/effort` | Thinking level |
| `/permissions` | Current 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:

```bash
> /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.

```bash
> /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

```bash
> /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:

```bash
unset ANTHROPIC_API_KEY
claude auth logout
claude auth login  # Choose subscription
```

## 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](https://code.claude.com/docs). Example repository: [github.com/anthropics/claude-code](https://github.com/anthropics/claude-code).

---

*Need help setting up Claude Code, MCP servers, or AI-powered development workflows? I help startups build AI products and automate processes — [belov.works](https://belov.works).*
