Claude Code Advanced Setup Guide: From Installation to Power Usage

Claude Code is Anthropic's terminal-based AI coding assistant that operates directly in your development environment. Unlike browser-based AI tools, Claude Code reads your codebase, runs commands, edi

Introduction#

Claude Code is Anthropic’s terminal-based AI coding assistant that operates directly in your development environment. Unlike browser-based AI tools, Claude Code reads your codebase, runs commands, edits files, and manages git operations — all from your terminal. This guide covers installation, configuration, and advanced usage patterns that move beyond basic prompting into integrated, automated workflows.

Installation and Initial Setup#

Prerequisites#

Claude Code requires Node.js 18 or later. Verify your version before installing:

1
2
node --version
# Should output v18.0.0 or higher

Installing Claude Code#

1
npm install -g @anthropic-ai/claude-code

Verify the installation:

1
claude --version

Authentication#

Claude Code uses your Anthropic API key. Set it as an environment variable:

1
export ANTHROPIC_API_KEY="your-api-key-here"

For persistence, add it to your shell profile:

1
2
3
4
5
6
7
# For zsh users
echo 'export ANTHROPIC_API_KEY="your-api-key-here"' >> ~/.zshrc
source ~/.zshrc

# For bash users
echo 'export ANTHROPIC_API_KEY="your-api-key-here"' >> ~/.bashrc
source ~/.bashrc

Launching Claude Code#

Navigate to your project directory and start a session:

1
2
cd /path/to/your/project
claude

Claude Code automatically reads your project structure, README, configuration files, and recent git history to build context before you issue your first prompt.

Project-Level Configuration with CLAUDE.md#

The most impactful setup step is creating a CLAUDE.md file at your project root. This file acts as persistent instructions that Claude Code reads at the start of every session — it eliminates the need to re-explain your project conventions repeatedly.

What to Include in CLAUDE.md#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# Project Overview
Brief description of what the project does and its tech stack.

# Architecture
Key architectural decisions and patterns in use.

# Development Workflow
- Branch naming conventions
- How to run tests
- How to build and serve locally

# Code Style
- Language-specific conventions
- Naming patterns
- Formatting rules

# Key Files and Directories
Explanation of non-obvious file organization.

# Do Not Touch
Files or directories that should never be modified directly.

# Common Commands
Frequently used commands for this project.

Example CLAUDE.md for a Microservices Project#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# Payments Service

## Stack
- Go 1.22, Gin framework, PostgreSQL, Redis
- Deployed to AWS ECS via Terraform

## Workflow
- Work on `develop` branch, never commit to `main`
- Run tests: `make test`
- Run locally: `docker-compose up`
- Lint: `golangci-lint run`

## Conventions
- All handlers must return structured errors using `pkg/apierror`
- New DB migrations go in `migrations/` using sequential numbering
- All config via environment variables, no hardcoded values
- Integration tests use the `testcontainers` library

## Never Edit
- `vendor/` directory — managed by `go mod vendor`
- `terraform/state/` — managed by remote state backend

With this in place, Claude Code understands your project constraints without you having to explain them each session.

Advanced Prompting Patterns#

Be Explicit About Scope#

Vague prompts produce vague results. Scope your requests precisely:

Instead of:

1
fix the login bug

Use:

1
2
3
The login handler at internal/handlers/auth.go returns 500 when the
user's email contains a + character. Trace the issue and fix it without
changing the response schema.

Multi-Step Task Delegation#

Claude Code handles complex, multi-step tasks well when you describe the full outcome:

1
2
3
4
5
6
Refactor the database layer:
1. Extract all raw SQL queries from the service layer into a repository pattern
2. Create interfaces for each repository
3. Move the concrete implementations to internal/repository/
4. Update all service files to use the new interfaces
5. Ensure all existing tests still pass

Reference Specific Files and Line Numbers#

1
2
3
Look at the retry logic in pkg/httpclient/client.go around line 145.
The backoff calculation doesn't account for jitter. Add exponential
backoff with jitter following the pattern in AWS SDK Go v2.

Asking for Analysis Before Changes#

For risky or large changes, ask for analysis first:

1
2
3
4
Before making any changes, analyze how the caching layer in
internal/cache/ interacts with the session management code.
Describe all the places where cache invalidation could produce
stale session data.

Custom Slash Commands#

Claude Code supports custom slash commands defined as Markdown files in .claude/commands/. These let you create reusable prompts for recurring tasks.

Setting Up Custom Commands#

1
mkdir -p .claude/commands

Example: Code Review Command#

Create .claude/commands/review.md:

1
2
3
4
5
6
7
8
9
10
11
Review the staged changes in this repository.

Check for:
1. Security vulnerabilities (injection, auth bypass, insecure defaults)
2. Missing error handling
3. Race conditions or concurrency issues
4. N+1 query patterns or missing database indexes
5. Violations of the patterns described in CLAUDE.md

For each issue found, cite the file and line number, explain the risk,
and suggest a concrete fix.

Invoke it with:

1
/review

Example: Pre-Commit Check Command#

Create .claude/commands/precommit.md:

1
2
3
4
5
6
7
8
Before I commit these changes:
1. Run the test suite and report any failures
2. Check for hardcoded secrets, API keys, or passwords in changed files
3. Verify all new public functions have docstrings/comments
4. Check that any new dependencies are documented in README or CLAUDE.md
5. Confirm the changes match the intent described in the recent git log

Report any issues that should block the commit.

Hooks for Automated Workflows#

Claude Code hooks allow you to run shell commands automatically when specific events occur — before a tool runs, after Claude responds, or when the session ends.

Configuring Hooks#

Hooks are configured in settings.json (project-level at .claude/settings.json or user-level at ~/.claude/settings.json).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Bash",
        "hooks": [
          {
            "type": "command",
            "command": "echo 'Running bash command: review carefully'"
          }
        ]
      }
    ],
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "cd $PROJECT_ROOT && golangci-lint run --fix 2>&1 | head -20"
          }
        ]
      }
    ],
    "Stop": [
      {
        "hooks": [
          {
            "type": "command",
            "command": "cd $PROJECT_ROOT && make test 2>&1 | tail -20"
          }
        ]
      }
    ]
  }
}

Practical Hook Use Cases#

Auto-format after edits:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "prettier --write \"$CLAUDE_TOOL_INPUT_FILE\" 2>/dev/null || true"
          }
        ]
      }
    ]
  }
}

Block accidental production file edits:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
{
  "hooks": {
    "PreToolUse": [
      {
        "matcher": "Edit",
        "hooks": [
          {
            "type": "command",
            "command": "if echo \"$CLAUDE_TOOL_INPUT_FILE\" | grep -q 'terraform/prod'; then echo 'BLOCKED: Cannot edit production Terraform files directly'; exit 1; fi"
          }
        ]
      }
    ]
  }
}

Permission Management#

Claude Code runs in a permission model where certain operations require explicit approval. Configure allowed operations in settings.json to avoid repeated approval prompts for trusted actions:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
{
  "permissions": {
    "allow": [
      "Bash(make:*)",
      "Bash(go test:*)",
      "Bash(docker-compose:*)",
      "Bash(git diff:*)",
      "Bash(git log:*)",
      "Bash(git status:*)"
    ],
    "deny": [
      "Bash(rm -rf:*)",
      "Bash(git push --force:*)",
      "Bash(kubectl delete:*)"
    ]
  }
}

This grants broad trust to safe read and build operations while explicitly blocking destructive commands.

MCP Server Integration#

Model Context Protocol (MCP) servers extend Claude Code with access to external systems — databases, APIs, ticketing systems, documentation platforms.

Configuring MCP Servers#

In .claude/settings.json:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
{
  "mcpServers": {
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres"],
      "env": {
        "POSTGRES_CONNECTION_STRING": "postgresql://localhost/mydb"
      }
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_PERSONAL_ACCESS_TOKEN": "your-token"
      }
    }
  }
}

With the Postgres MCP server configured, you can ask Claude Code to query your database schema directly:

1
2
Look at the users table schema and identify any missing indexes
for the queries in internal/repository/user_repository.go

Building a Custom MCP Server#

For internal tooling not covered by existing servers, you can build a minimal MCP server:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/usr/bin/env python3
"""
Minimal MCP server exposing internal deployment status API.
"""
import json
import sys
import requests

def handle_request(request: dict) -> dict:
    method = request.get("method")

    if method == "tools/list":
        return {
            "tools": [
                {
                    "name": "get_deployment_status",
                    "description": "Get the current deployment status for a service",
                    "inputSchema": {
                        "type": "object",
                        "properties": {
                            "service": {"type": "string", "description": "Service name"}
                        },
                        "required": ["service"]
                    }
                }
            ]
        }

    if method == "tools/call":
        tool_name = request["params"]["name"]
        args = request["params"]["arguments"]

        if tool_name == "get_deployment_status":
            service = args["service"]
            # Replace with your actual internal API
            response = requests.get(f"http://internal-api/deployments/{service}")
            return {"content": [{"type": "text", "text": json.dumps(response.json())}]}

    return {"error": "Unknown method"}

for line in sys.stdin:
    request = json.loads(line.strip())
    response = handle_request(request)
    print(json.dumps({"id": request.get("id"), "result": response}))
    sys.stdout.flush()

Headless and Automated Usage#

Claude Code supports non-interactive execution for CI/CD pipelines and automation scripts.

Running Non-Interactively#

1
2
3
4
5
# Single prompt, exits after completion
claude --print "Analyze the test coverage report at coverage.out and list the top 5 uncovered packages"

# Pipe output to files
claude --print "Generate a changelog entry for the commits since the last tag" > CHANGELOG_ENTRY.md

CI Pipeline Integration#

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# .github/workflows/ai-review.yml
name: AI Code Review

on:
  pull_request:
    types: [opened, synchronize]

jobs:
  review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Claude Code
        run: npm install -g @anthropic-ai/claude-code

      - name: Run AI Review
        env:
          ANTHROPIC_API_KEY: $
        run: |
          git diff origin/main...HEAD > changes.patch
          claude --print "$(cat <<'EOF'
          Review the attached diff for:
          1. Security vulnerabilities
          2. Missing error handling
          3. Performance issues

          Diff:
          $(cat changes.patch)
          EOF
          )" > review.md

      - name: Post Review Comment
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const review = fs.readFileSync('review.md', 'utf8');
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## AI Code Review\n\n${review}`
            });

Model Selection#

Claude Code supports multiple Claude models. Choose based on your task:

1
2
3
4
5
6
7
8
# Faster, lighter tasks (code formatting, simple edits)
claude --model claude-haiku-4-5

# Balanced performance (default for most tasks)
claude --model claude-sonnet-4-6

# Complex architecture decisions and deep analysis
claude --model claude-opus-4-6

Set a default model in settings to avoid specifying it each session:

1
2
3
{
  "model": "claude-sonnet-4-6"
}

Best Practices for Advanced Usage#

Keep Context Focused#

Claude Code works best with a clear, bounded context. For large codebases, guide it to the relevant area rather than letting it scan everything:

1
2
Focus only on the authentication subsystem in internal/auth/.
Ignore everything in internal/payments/ and internal/reporting/.

Iterate in Small Steps#

For complex refactors, break the work into stages and verify each stage before continuing:

1
2
3
Step 1 only: Extract the database connection logic from main.go into
a separate pkg/db package. Do not touch any other files yet. After
this step, run the tests and confirm they pass before we continue.

Use Git as a Safety Net#

Before large automated changes, commit your current state:

1
2
3
git add -A && git commit -m "checkpoint: before AI refactor"
claude
# Now instruct Claude to make the large change

If the result is unsatisfactory, you can reset cleanly.

Maintain a Session Log#

For complex multi-session tasks, maintain a WORKLOG.md at the project root that you update with Claude Code’s help:

1
2
3
4
Update WORKLOG.md with what we accomplished today:
- What was changed and why
- What remains to be done
- Any decisions made and the reasoning behind them

Troubleshooting Common Issues#

Context too large error: Use --dangerously-skip-permissions only in trusted environments. Instead, narrow scope by pointing to specific files.

Claude modifies wrong files: Add explicit exclusions to CLAUDE.md and use permission deny rules in settings.

Repeated approval prompts: Audit which commands are triggering prompts and add them to the permissions.allow list in settings.json.

Inconsistent results between sessions: Improve your CLAUDE.md. If Claude behaves inconsistently, the project context file likely needs more specificity.

Conclusion#

Claude Code’s value compounds with investment in configuration. A well-written CLAUDE.md, thoughtful custom commands, and appropriate permission settings transform it from a generic assistant into a tool that understands your project’s specific constraints and conventions. The headless and MCP integration capabilities extend it further into automated workflows and CI pipelines. Start with the configuration fundamentals, observe where friction remains, and layer in automation incrementally.

Contents