Complete Claude Code Guide: From Installation to Advanced Usage

Complete Claude Code Guide: From Installation to Advanced Usage

A comprehensive tutorial covering everything you need to know about Claude Code - from basic installation and setup to advanced features like MCP integration, automation, and security best practices.

Lesson 5 2025-07-03 08:05

Advanced Claude Code Features & Automation

Advanced Claude Code Features & Automation

Take your Claude Code usage to the next level with advanced features, automation patterns, and power-user techniques. This guide covers sophisticated workflows, CI/CD integration, custom configurations, and expert-level usage patterns.

Advanced Session Management

Named Sessions and Workspaces

Create and manage specialized sessions for different projects and contexts:

# Create named sessions for different projects
claude --session frontend "Working on React frontend"
claude --session backend "Backend API development"
claude --session devops "Infrastructure and deployment"

# Resume specific named sessions
claude --resume frontend "Continue frontend work"
claude --resume backend "Check API performance"

# List all named sessions
claude sessions list --filter named

# Export and share session configurations
claude sessions export frontend > frontend-session.json
claude sessions import frontend-session.json

Session Templates

Create reusable session templates:

# Create a template for React development
cat > ~/.claude/templates/react-dev.json << EOF
{
  "allowedTools": ["Edit", "View", "Bash(npm:*)", "Bash(git:*)"],
  "addDirectories": ["./src", "./test", "./docs"],
  "systemPrompt": "You are a senior React developer. Follow TypeScript best practices and focus on performance and accessibility.",
  "mcpServers": ["git", "filesystem"],
  "projectMemory": "React TypeScript project with Jest testing"
}
EOF

# Use template to start sessions
claude --template react-dev "Start React development session"

Advanced Memory Management

CLAUDE.md - Project Memory

Create comprehensive project memory files:

# Project: E-commerce Platform

## Architecture Overview
- **Frontend**: React 18 + TypeScript + Vite
- **Backend**: Node.js + Express + TypeScript
- **Database**: PostgreSQL 14 with Prisma ORM
- **Cache**: Redis for session storage
- **Deployment**: Docker + Kubernetes on AWS

## Current Sprint Goals
- [ ] Implement user authentication with JWT
- [ ] Add payment processing with Stripe
- [ ] Set up automated testing pipeline
- [ ] Optimize database queries for product search

## Development Standards
- Use TypeScript for all new code
- Follow ESLint + Prettier configuration
- Write unit tests for all business logic
- Use conventional commits for git messages
- Deploy to staging before production

## Known Issues
- Search performance degrades with > 10k products
- User session timeout needs configuration
- Email service rate limiting in production

## Recent Decisions
- Switched from REST to GraphQL for better frontend integration
- Using Tailwind CSS for styling consistency
- Implementing feature flags for gradual rollouts

Dynamic Memory Updates

# Update project memory with recent developments
claude /memory add "Implemented Redis caching for search results - 40% performance improvement"

# Set current focus
claude /memory set-focus "Working on user authentication system this week"

# Add architectural decisions
claude /memory add-decision "Using JWT tokens with 24h expiration and refresh token rotation"

Advanced Configuration Patterns

Hierarchical Configuration System

Create sophisticated configuration hierarchies:

# Global configuration (~/.claude.json)
{
  "defaultModel": "claude-sonnet-4",
  "globalAllowedTools": ["View"],
  "globalDisallowedTools": ["Bash(rm:*)", "Bash(sudo:*)"],
  "theme": "dark-daltonized",
  "editorMode": "vim"
}

# Organization configuration (~/.claude/org-config.json)
{
  "extends": "~/.claude.json",
  "allowedTools": ["Edit", "View", "Bash(git:*)", "mcp__git__*"],
  "mcpServers": {
    "company-git": {
      "command": "company-git-server",
      "env": {"COMPANY_TOKEN": "${COMPANY_GIT_TOKEN}"}
    }
  },
  "auditLogging": true,
  "complianceMode": "SOC2"
}

# Project configuration (./claude-config.json)
{
  "extends": "~/.claude/org-config.json",
  "projectName": "ecommerce-platform",
  "allowedTools": ["Edit", "View", "Bash(npm:*)", "Bash(git:*)", "mcp__*"],
  "systemPrompt": "You are working on an e-commerce platform. Focus on security, performance, and user experience.",
  "addDirectories": ["./src", "./tests", "./docs"],
  "mcpServers": {
    "project-db": {
      "command": "postgres-mcp-server",
      "env": {"DATABASE_URL": "${PROJECT_DATABASE_URL}"}
    }
  }
}

Environment-Specific Configurations

# Development environment
export CLAUDE_ENV=development
export CLAUDE_CONFIG_FILE=~/.claude/dev-config.json

# Staging environment
export CLAUDE_ENV=staging
export CLAUDE_CONFIG_FILE=~/.claude/staging-config.json

# Production environment (read-only)
export CLAUDE_ENV=production
export CLAUDE_CONFIG_FILE=~/.claude/prod-config.json

Automation and Scripting

CI/CD Integration

GitHub Actions Integration

# .github/workflows/claude-code-review.yml
name: Claude Code Review

on:
  pull_request:
    branches: [main, develop]

jobs:
  claude-review:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Get full history for better analysis

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '18'

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

      - name: Run Security Review
        env:
          ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
        run: |
          # Create safe configuration for CI
          cat > ci-config.json << EOF
          {
            "allowedTools": ["View"],
            "outputFormat": "json",
            "verbose": false
          }
          EOF

          # Run security analysis
          claude --config ci-config.json \
            -p "Analyze this pull request for security vulnerabilities, performance issues, and code quality problems. Focus on changes in src/ directory." \
            --output-format json > review-results.json

      - name: Post Review Comments
        uses: actions/github-script@v7
        with:
          script: |
            const fs = require('fs');
            const results = JSON.parse(fs.readFileSync('review-results.json', 'utf8'));

            // Post results as PR comment
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: `## πŸ€– Claude Code Review\n\n${results.analysis}\n\n### Security Issues: ${results.security_issues}\n### Performance Issues: ${results.performance_issues}\n### Code Quality: ${results.code_quality}`
            });

GitLab CI Integration

# .gitlab-ci.yml
claude_review:
  image: node:18
  stage: review
  script:
    - npm install -g @anthropic-ai/claude-code
    - |
      claude --allowedTools "View" \
        -p "Review this merge request for code quality and security issues" \
        --output-format json > review.json
    - cat review.json
  artifacts:
    reports:
      junit: review.json
  only:
    - merge_requests

Pre-commit Hooks

Create intelligent pre-commit hooks:

#!/bin/bash
# .git/hooks/pre-commit

# Get staged files
staged_files=$(git diff --cached --name-only --diff-filter=ACM)

if [ -z "$staged_files" ]; then
    exit 0
fi

echo "πŸ€– Running Claude Code analysis on staged files..."

# Create temporary file with staged changes
git diff --cached > /tmp/staged_changes.diff

# Analyze with Claude
analysis=$(claude --allowedTools "View" \
    -p "Analyze these git changes for potential issues before commit. Focus on: 1) Security vulnerabilities 2) Code quality 3) Performance issues 4) Breaking changes. Return JSON with severity levels." \
    --output-format json < /tmp/staged_changes.diff)

# Parse results
critical_issues=$(echo "$analysis" | jq -r '.critical_issues // []')
warning_issues=$(echo "$analysis" | jq -r '.warnings // []')

# Block commit if critical issues found
if [ "$critical_issues" != "[]" ] && [ "$critical_issues" != "null" ]; then
    echo "❌ Critical issues found:"
    echo "$critical_issues" | jq -r '.[]'
    echo "Commit blocked. Please fix critical issues before committing."
    exit 1
fi

# Show warnings but allow commit
if [ "$warning_issues" != "[]" ] && [ "$warning_issues" != "null" ]; then
    echo "⚠️  Warnings found:"
    echo "$warning_issues" | jq -r '.[]'
    echo "Consider addressing these issues."
fi

echo "βœ… Pre-commit analysis complete"
rm /tmp/staged_changes.diff

Automated Documentation

#!/bin/bash
# scripts/update-docs.sh

# Automated API documentation
claude --allowedTools "View,Edit" \
    --add-dir ./src/api \
    "Update API documentation in docs/api.md based on current TypeScript interfaces and endpoint implementations"

# Generate README updates
claude --allowedTools "View,Edit" \
    "Update README.md with current project status, installation instructions, and usage examples"

# Create changelog entries
git log --since="1 week ago" --pretty=format:"%h %s" | \
    claude -p "Generate changelog entries from these git commits. Focus on user-facing changes." \
    >> CHANGELOG.md

Advanced MCP Workflows

Custom MCP Server Development

Create specialized MCP servers for your workflow:

// custom-project-server.js
const { Server } = require('@modelcontextprotocol/sdk/server/index.js');
const { StdioServerTransport } = require('@modelcontextprotocol/sdk/server/stdio.js');
const fs = require('fs');
const path = require('path');

class ProjectServer extends Server {
  constructor() {
    super({
      name: 'project-server',
      version: '1.0.0',
    });

    this.setupTools();
  }

  setupTools() {
    // Project status tool
    this.setRequestHandler('tools/list', async () => ({
      tools: [
        {
          name: 'get_project_status',
          description: 'Get comprehensive project status including git, dependencies, and deployment',
          inputSchema: {
            type: 'object',
            properties: {}
          }
        },
        {
          name: 'run_tests',
          description: 'Run project tests with specified scope',
          inputSchema: {
            type: 'object',
            properties: {
              scope: { type: 'string', enum: ['unit', 'integration', 'e2e', 'all'] },
              coverage: { type: 'boolean', default: false }
            }
          }
        },
        {
          name: 'deploy_to_staging',
          description: 'Deploy current branch to staging environment',
          inputSchema: {
            type: 'object',
            properties: {
              branch: { type: 'string', default: 'main' },
              runMigrations: { type: 'boolean', default: true }
            }
          }
        }
      ]
    }));

    this.setRequestHandler('tools/call', async (request) => {
      const { name, arguments: args } = request.params;

      switch (name) {
        case 'get_project_status':
          return await this.getProjectStatus();
        case 'run_tests':
          return await this.runTests(args);
        case 'deploy_to_staging':
          return await this.deployToStaging(args);
        default:
          throw new Error(`Unknown tool: ${name}`);
      }
    });
  }

  async getProjectStatus() {
    // Implementation for project status
    const gitStatus = require('child_process').execSync('git status --porcelain').toString();
    const packageJson = JSON.parse(fs.readFileSync('package.json', 'utf8'));

    return {
      content: [{
        type: 'text',
        text: `Project Status:
- Git: ${gitStatus ? 'Uncommitted changes' : 'Clean'}
- Version: ${packageJson.version}
- Dependencies: ${Object.keys(packageJson.dependencies || {}).length}
- Last commit: ${require('child_process').execSync('git log -1 --format="%h %s"').toString().trim()}`
      }]
    };
  }

  async runTests(args) {
    const { scope = 'all', coverage = false } = args;
    // Implementation for running tests
    // ...
  }

  async deployToStaging(args) {
    // Implementation for deployment
    // ...
  }
}

// Start server
const server = new ProjectServer();
const transport = new StdioServerTransport();
server.connect(transport);

MCP Server Orchestration

Coordinate multiple MCP servers:

# Advanced MCP workflow script
#!/bin/bash

echo "πŸš€ Starting development workflow..."

# 1. Check project status
claude --allowedTools "mcp__project__get_project_status" \
    "Get current project status and identify any issues"

# 2. Run tests before starting work
claude --allowedTools "mcp__project__run_tests" \
    "Run unit tests to ensure clean baseline"

# 3. Check for security vulnerabilities
claude --allowedTools "mcp__security__scan" \
    "Scan project for security vulnerabilities"

# 4. Update dependencies if needed
claude --allowedTools "mcp__npm__audit,mcp__npm__update" \
    "Check for dependency updates and security patches"

# 5. Start development session
claude --allowedTools "Edit,View,mcp__git__*,mcp__project__*" \
    --add-dir ./src ./tests \
    "Ready for development. Project is clean and tested."

Performance Optimization

Context Window Management

Optimize Claude Code's context usage:

# Limit context to specific directories
claude --add-dir ./src/components ./src/utils \
    "Focus on components and utilities only"

# Use focused queries
claude --allowedTools "View" \
    -p "Analyze only the authentication module for security issues" \
    --context-files "src/auth/*.ts"

# Progressive context building
claude "Start with overview of project structure"
# Then add specific context as needed
claude "Now focus on the user management system"

Performance Monitoring

# Monitor Claude Code performance
claude --profile --timing \
    "Analyze application performance bottlenecks"

# Token usage optimization
export MAX_THINKING_TOKENS=30000  # Adjust based on needs
claude --cost-tracking "Optimize database queries"

# Memory usage monitoring
claude --memory-usage --verbose \
    "Large codebase analysis session"

Advanced Troubleshooting

Debug Mode Configuration

# Maximum debugging information
claude \
    --verbose \
    --debug \
    --mcp-debug \
    --trace-all \
    --log-api-calls \
    --show-tokens \
    --cost-tracking \
    "Debug complex integration issue"

# Selective debugging
claude \
    --mcp-debug \
    --allowedTools "mcp__postgres__*" \
    "Debug database connectivity issues"

Log Analysis and Monitoring

# Comprehensive logging setup
export CLAUDE_LOG_LEVEL=debug
export CLAUDE_LOG_FILE=/var/log/claude/session.log
export CLAUDE_AUDIT_LOG=/var/log/claude/audit.log

# Real-time log monitoring
tail -f /var/log/claude/session.log | \
    claude -p "Monitor these logs for errors and suggest fixes"

# Log analysis automation
cat /var/log/claude/session.log | \
    claude -p "Analyze logs for patterns, errors, and performance issues. Generate summary report."

Team Collaboration Features

Shared Configurations

# Team configuration repository
git clone https://github.com/company/claude-configs.git ~/.claude/team

# Use team configurations
claude --config ~/.claude/team/frontend-config.json \
    "Start frontend development session"

# Share session templates
cp ~/.claude/templates/react-dev.json \
   ~/.claude/team/templates/
git add . && git commit -m "Add React development template"

Knowledge Sharing

# Generate team documentation
claude --allowedTools "View,Edit" \
    "Create onboarding documentation for new developers based on current project structure and conventions"

# Share troubleshooting guides
claude --allowedTools "View" \
    "Generate troubleshooting guide for common development issues in this project"

# Create architectural decision records
claude "Document the decision to use GraphQL instead of REST, including rationale and implementation details"

Expert-Level Patterns

Complex Workflow Automation

# End-to-end feature development workflow
#!/bin/bash
feature_name=$1

echo "🎯 Starting feature development: $feature_name"

# 1. Create feature branch
claude --allowedTools "mcp__git__*" \
    "Create feature branch for $feature_name"

# 2. Generate initial implementation
claude --allowedTools "Edit,View" \
    "Generate initial implementation for $feature_name based on requirements in REQUIREMENTS.md"

# 3. Write tests
claude --allowedTools "Edit,View" \
    "Create comprehensive tests for the $feature_name feature"

# 4. Run quality checks
claude --allowedTools "mcp__project__run_tests,mcp__lint__*" \
    "Run tests and linting for the new feature"

# 5. Generate documentation
claude --allowedTools "Edit,View" \
    "Update documentation for the new $feature_name feature"

# 6. Create pull request
claude --allowedTools "mcp__github__*" \
    "Create pull request for $feature_name with appropriate description and reviewers"

echo "βœ… Feature development workflow complete"

Multi-Environment Deployment

# Progressive deployment workflow
claude --config ~/.claude/deploy-config.json \
    --allowedTools "mcp__k8s__*,mcp__aws__*" \
    "Deploy to development environment and run smoke tests"

# If successful, continue to staging
claude --allowedTools "mcp__k8s__*,mcp__monitoring__*" \
    "Deploy to staging and monitor for 10 minutes"

# Final production deployment
claude --allowedTools "mcp__k8s__apply,mcp__monitoring__*" \
    "Deploy to production with blue-green strategy"

Future-Proofing Your Setup

Configuration Version Control

# Version control all configurations
git init ~/.claude
cd ~/.claude
git add .
git commit -m "Initial Claude Code configuration"
git remote add origin https://github.com/yourusername/claude-config.git
git push -u origin main

Backup and Recovery

# Automated backup script
#!/bin/bash
DATE=$(date +%Y%m%d_%H%M%S)
BACKUP_DIR=~/.claude/backups

mkdir -p $BACKUP_DIR

# Backup configuration
cp ~/.claude.json $BACKUP_DIR/claude-config-$DATE.json

# Backup sessions
claude sessions export --all > $BACKUP_DIR/sessions-$DATE.json

# Backup project memories
tar -czf $BACKUP_DIR/memories-$DATE.tar.gz ~/.claude/memories/

echo "Backup completed: $BACKUP_DIR"

Migration Planning

# Configuration migration script
#!/bin/bash
OLD_VERSION=$1
NEW_VERSION=$2

echo "Migrating Claude Code configuration from $OLD_VERSION to $NEW_VERSION"

# Backup current configuration
cp ~/.claude.json ~/.claude.json.backup

# Apply migration
claude config migrate --from $OLD_VERSION --to $NEW_VERSION

# Verify migration
claude /doctor

echo "Migration complete. Check /doctor output for issues."

Conclusion

These advanced features and patterns transform Claude Code from a simple AI assistant into a comprehensive development automation platform. By mastering these techniques, you can:

  • Automate complex workflows with intelligent decision-making
  • Integrate with CI/CD pipelines for continuous quality assurance
  • Create custom tools for your specific needs
  • Collaborate effectively with team-shared configurations
  • Monitor and optimize performance at scale

The key to advanced Claude Code usage is progressive enhancement - start with basic patterns and gradually incorporate more sophisticated techniques as your confidence and requirements grow.

Remember to always maintain security best practices, even with advanced automation, and regularly review and update your configurations to keep pace with both Claude Code updates and your evolving development needs.