// ai

Claude Code

Comprehensive guide for using Claude Code CLI, project configuration, and advanced features

claude · ai · cli · automation · coding-assistant

Getting Started

Installation & Setup

# Install Claude Code CLI
npm install -g @anthropic-ai/claude-code

# Login to Claude
claude login

# Check version
claude --version

# Get help
claude help
claude --help

Basic Usage

# Start Claude Code in current directory
claude

# Start in specific directory
claude /path/to/project

# Start with specific message
claude "help me fix this bug"

# Continue previous conversation
claude --continue

# List recent conversations
claude --list

# Clear conversation history
claude --clear

Project Configuration

CLAUDE.md File

# Create project-specific instructions
# File: /path/to/project/CLAUDE.md

# CLAUDE.md

This file provides guidance to Claude Code when working with code in this repository.

## Project Overview

Brief description of what this project does and its key components.

## Tech Stack

- Framework: React, Vue, Angular, etc.
- Language: TypeScript, Python, Go, etc.
- Database: PostgreSQL, MongoDB, etc.
- Infrastructure: AWS, Docker, Kubernetes, etc.

## Development Commands

```bash
# Install dependencies
npm install

# Start development server
npm run dev

# Run tests
npm test

# Build for production
npm run build

Project Structure

/
├── src/
│   ├── components/
│   ├── services/
│   └── utils/
├── tests/
└── docs/

Code Style Preferences

  • Use TypeScript strict mode
  • Prefer functional components
  • Use async/await over promises
  • Follow ESLint configuration

Testing Requirements

  • Write unit tests for all new functions
  • Ensure >80% code coverage
  • Run tests before committing

Important Notes

  • Always update documentation when changing APIs
  • Use semantic commit messages
  • Never commit secrets or API keys

### Global CLAUDE.md

```bash
# Create global instructions for all projects
# File: ~/.claude/CLAUDE.md

# CLAUDE.md - Global Configuration

## Development Workflow

### Git Commit Instructions
- Use conventional commits (feat:, fix:, docs:, etc.)
- Keep commits atomic and focused
- Write clear, descriptive commit messages

## Code Style Preferences

- Prefer readable code over clever code
- Add comments for complex logic
- Use descriptive variable names

## Testing Requirements

- Always create unit tests for new functions
- Run test suite before committing

Slash Commands

Built-in Commands

# Get help
/help

# Clear conversation
/clear

# Show conversation history
/history

# Exit Claude Code
/exit
/quit

# Continue previous conversation
/continue

# Show current context
/context

# List available commands
/commands

Custom Slash Commands

# Create custom slash command
# File: .claude/commands/review.md

Review the current changes and suggest improvements:
- Check for code smells
- Verify error handling
- Ensure proper logging
- Check for security issues
- Verify test coverage

# Usage in Claude:
/review

Common Custom Commands

# .claude/commands/test.md
Run the full test suite and report any failures. If tests fail, analyze the failures and suggest fixes.

# .claude/commands/deploy.md
Prepare the application for deployment:
1. Run linter and fix any issues
2. Run test suite
3. Build the project
4. Verify build output

# .claude/commands/docs.md
Update documentation for recent code changes:
1. Review git diff since last commit
2. Update README.md if needed
3. Update API documentation
4. Update code comments

# .claude/commands/security.md
Perform security audit:
- Check for hardcoded secrets
- Verify input validation
- Check for SQL injection vulnerabilities
- Verify authentication/authorization
- Check dependencies for known vulnerabilities

MCP (Model Context Protocol) Servers

What is MCP?

MCP allows Claude Code to connect to external tools and data sources:
- Database access
- API integrations
- File system operations
- Custom tooling

Installing MCP Servers

# MCP servers are configured in Claude settings
# Common MCP servers:

# Filesystem MCP (file operations)
# Database MCP (PostgreSQL, MySQL, SQLite)
# Web Search MCP
# GitHub MCP
# Notion MCP
# Slack MCP

Example MCP Configuration

// File: ~/.claude/mcp_servers.json
{
  "mcpServers": {
    "filesystem": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/directory"]
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://user:pass@localhost/db"]
    },
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": {
        "GITHUB_TOKEN": "your_github_token"
      }
    }
  }
}

Using MCP Tools

# Once configured, MCP tools appear as mcp__toolname__operation
# Claude automatically uses them when appropriate

# Example: Reading files via filesystem MCP
"Read the contents of config.json"
# Claude uses mcp__filesystem__read_file

# Example: Querying database via postgres MCP
"Show me all users in the database"
# Claude uses mcp__postgres__query

# Example: Creating GitHub issue
"Create a GitHub issue for this bug"
# Claude uses mcp__github__create_issue

Skills

What are Skills?

Skills are specialized capabilities that extend Claude's functionality:
- PDF processing
- Excel/spreadsheet handling
- Image analysis
- Data visualization
- Custom domain-specific tasks

Using Skills

# Skills are invoked automatically or manually
# Example: PDF skill
"Analyze this PDF file: document.pdf"

# Example: Excel skill
"Create a spreadsheet summarizing this data"

# List available skills
# Skills appear in Claude Code's skill directory

Hooks

What are Hooks?

Hooks are shell commands that run in response to events:
- Before/after tool calls
- On user prompt submission
- On conversation start/end

Hook Configuration

// File: ~/.claude/settings.json
{
  "hooks": {
    "user-prompt-submit": {
      "command": "echo 'User submitted: $PROMPT'",
      "blocking": false
    },
    "tool-use-bash": {
      "command": "echo 'Running bash command: $TOOL_INPUT'",
      "blocking": false
    },
    "conversation-start": {
      "command": "notify-send 'Claude Code session started'",
      "blocking": false
    }
  }
}

Common Hook Examples

{
  "hooks": {
    // Play sound when Claude is waiting for input
    "ask-user-question": {
      "command": "paplay /usr/share/sounds/freedesktop/stereo/message.oga",
      "blocking": false
    },

    // Play sound when task completes
    "todo-all-completed": {
      "command": "paplay /usr/share/sounds/freedesktop/stereo/complete.oga",
      "blocking": false
    },

    // Log all bash commands
    "tool-use-bash": {
      "command": "echo \"$(date): $TOOL_INPUT\" >> ~/.claude/bash_log.txt",
      "blocking": false
    },

    // Require approval for git push
    "tool-use-bash": {
      "command": "if echo \"$TOOL_INPUT\" | grep -q 'git push'; then zenity --question --text='Allow git push?'; fi",
      "blocking": true
    }
  }
}

Working with Files

Reading Files

# Claude can read files directly
"Read the file src/app.js"
"Show me the contents of package.json"

# Read multiple files
"Read all files in src/components/"

# Read specific sections
"Show me the authentication function in auth.js"

Editing Files

# Claude edits files precisely
"Change the port from 3000 to 8080 in server.js"
"Add error handling to the login function"
"Refactor this function to use async/await"

# Bulk edits
"Rename all instances of 'oldName' to 'newName' in the project"
"Update all import statements to use new module path"

Creating Files

# Create new files
"Create a new component called UserProfile"
"Add a new API endpoint for user registration"
"Create a test file for the auth service"

File Patterns

# Search for files
"Find all TypeScript files that import 'express'"
"Show me all test files"
"Find files containing TODO comments"

# Work with patterns
"Update all .env.example files"
"Read all configuration files"

Git Integration

Basic Git Operations

# Check status
"What's the git status?"
"Show me uncommitted changes"

# View changes
"Show me the git diff"
"What files have changed?"

# Commit changes
"Commit these changes with message 'Add user authentication'"
"Create a commit for the bug fix"

# Push/Pull
"Push changes to origin"
"Pull latest from main branch"

Creating Pull Requests

# Claude uses GitHub CLI (gh)
"Create a pull request for this feature"
"Create PR with title 'Add authentication' and description of changes"

# Claude will:
# 1. Review all commits in the branch
# 2. Generate comprehensive PR description
# 3. Create PR using gh command

Commit Best Practices

# Claude follows these by default:
# - Analyzes all changes (not just latest commit)
# - Creates semantic commit messages
# - Focuses on "why" not "what"
# - Keeps commits atomic and focused

# Example commit flow:
"Commit the authentication changes"

# Claude will:
# 1. Run git status
# 2. Run git diff to see changes
# 3. Check recent commits for style
# 4. Stage relevant files
# 5. Create descriptive commit message
# 6. Verify with git status after commit

Task Management

Todo Lists

# Claude automatically creates todos for multi-step tasks
"Add user authentication to the application"

# Claude creates todos:
# ✓ Create user model
# ✓ Add authentication middleware
# ✓ Create login endpoint
# ✓ Add password hashing
# ⏳ Write tests for auth flow
# ⏹ Update documentation

# You can see progress in real-time

When Todos are Created

Claude creates todos for:
- Multi-step tasks (3+ steps)
- Complex implementations
- User-provided lists
- Tasks requiring tracking

Claude skips todos for:
- Single straightforward tasks
- Simple file operations
- Quick questions

Code Analysis

Understanding Code

# Ask about code structure
"Explain how authentication works in this app"
"What does this function do?"
"How are API routes organized?"

# Find specific code
"Where is the database connection configured?"
"Show me the login logic"
"Find all uses of the User model"

Code Review

# Request code review
"Review this code for best practices"
"Check for security vulnerabilities"
"Suggest improvements for this function"

# Specific reviews
"Review error handling in this service"
"Check if this code follows our style guide"
"Verify this function has proper tests"

Refactoring

# Request refactoring
"Refactor this to use dependency injection"
"Split this large function into smaller ones"
"Convert this class to functional component"

# Modernization
"Update this code to use ES6 syntax"
"Convert callbacks to async/await"
"Update to use latest API version"

Testing

Writing Tests

# Claude writes comprehensive tests
"Write unit tests for the auth service"
"Add tests for the user registration function"
"Create integration tests for the API"

# Test patterns
"Write tests covering edge cases"
"Add error handling tests"
"Create mocks for external dependencies"

Running Tests

# Run and analyze tests
"Run the test suite"
"Run tests for the auth module"

# If tests fail, Claude can:
# - Analyze failure reasons
# - Suggest fixes
# - Update code or tests as needed

Debugging

Finding Bugs

# Report bugs to Claude
"There's a bug in the login function - it returns 500"
"The app crashes when submitting the form"
"Users can't upload files larger than 1MB"

# Claude will:
# 1. Read relevant code
# 2. Analyze the issue
# 3. Suggest fixes
# 4. Implement solution
# 5. Test the fix

Analyzing Errors

# Share error messages
"I'm getting this error: [paste error]"
"The build is failing with this message: [paste]"

# Share logs
"Here are the server logs: [paste logs]"

Performance Optimization

Code Optimization

# Request performance improvements
"Optimize this database query"
"This function is slow, can you improve it?"
"Reduce memory usage in this component"

# Specific optimizations
"Add caching to this API endpoint"
"Optimize this image processing function"
"Reduce bundle size"

Performance Analysis

# Analyze performance
"Review this code for performance issues"
"What's causing the slow page load?"
"Find bottlenecks in this service"

Documentation

Generating Documentation

# Create documentation
"Generate API documentation"
"Document this function"
"Create README for this project"

# Update documentation
"Update docs to reflect recent changes"
"Add examples to the README"
"Document the new API endpoints"

Code Comments

# Add comments
"Add comments to this complex function"
"Document these API parameters"
"Add JSDoc comments to this module"

Best Practices

Effective Prompts

# Good prompts are specific and clear

# ✓ Good:
"Add input validation to the login function to check email format and password length"

# ✗ Too vague:
"Fix the login"

# ✓ Good:
"Refactor the user service to separate database logic from business logic"

# ✗ Too vague:
"Clean up the code"

# ✓ Good:
"Add error handling to the file upload endpoint to handle large files and invalid types"

# ✗ Too vague:
"Make it better"

Context Management

# Provide context
"I'm using Express.js and PostgreSQL"
"This is a React application with TypeScript"
"We follow Airbnb style guide"

# Reference files
"Looking at auth.js, the login function needs error handling"
"In the README, update the installation section"

# Show errors/logs
"Here's the error I'm getting: [paste error]"
"The test output shows: [paste output]"

Iterative Development

# Start simple, then refine
1. "Create a basic user authentication system"
2. "Add password reset functionality"
3. "Add email verification"
4. "Add OAuth integration"

# Review and improve
1. "Implement the feature"
2. "Review the code for improvements"
3. "Add tests"
4. "Update documentation"

Advanced Features

Agent System

# Claude can launch specialized agents

# Explore agent - for codebase exploration
"Find all API endpoints in this project"
# Claude launches Explore agent automatically

# General-purpose agent - for complex tasks
"Refactor the entire authentication system to use JWT"
# Claude may use Task agent for complex work

Parallel Operations

# Run multiple operations in parallel
"Read auth.js, user.js, and session.js"
# Claude reads all three files simultaneously

# Parallel searches
"Find all TODO comments and all FIXME comments"
# Runs both searches in parallel

File Globbing

# Use patterns to match files
"Read all files matching src/**/*.test.js"
"Find all TypeScript files in components/"
"Show me all .env* files"

Troubleshooting

Common Issues

# Permission Errors
# - Check file permissions (chmod)
# - Verify directory access
# - Check SSH keys for remote operations

# Build Failures
# - Share full error output with Claude
# - Check node_modules (try npm install)
# - Verify dependencies in package.json

# Git Issues
# - Verify git config
# - Check remote repository access
# - Ensure branch is up to date

# Can't Find Files
# - Verify current working directory
# - Check file paths (absolute vs relative)
# - Use glob patterns for searching

Debug Mode

# Get verbose output
"Show verbose SSH connection details"
"Run with debug logging enabled"

# Check what Claude sees
"What's the current working directory?"
"List all files in the current directory"
"Show git status"

Tips & Tricks

Productivity Tips

# 1. Use CLAUDE.md for project context
# - Add tech stack, coding standards, common commands
# - Include project-specific guidelines
# - Document architecture decisions

# 2. Create custom slash commands
# - Common workflows (/deploy, /test, /review)
# - Project-specific tasks
# - Team standards enforcement

# 3. Use hooks for notifications
# - Sound alerts when waiting for input
# - Desktop notifications for long tasks
# - Logging for audit trails

# 4. Leverage MCP for integrations
# - Database queries without switching tools
# - GitHub operations inline
# - File system operations

# 5. Clear, specific requests
# - Include relevant context
# - Specify expected outcome
# - Provide error messages/logs

Workflow Patterns

# Feature Development Pattern:
1. "Create a new feature for [description]"
2. "Add error handling and validation"
3. "Write unit tests"
4. "Update documentation"
5. "Create a commit and PR"

# Bug Fix Pattern:
1. "There's a bug: [description]"
2. "Show me the relevant code"
3. "Fix the issue"
4. "Add test to prevent regression"
5. "Commit the fix"

# Refactoring Pattern:
1. "Review [file] for code smells"
2. "Refactor based on suggestions"
3. "Ensure tests still pass"
4. "Update documentation"
5. "Commit changes"

# Code Review Pattern:
1. "Show me the git diff"
2. "Review changes for:"
   - Code quality
   - Security issues
   - Test coverage
   - Documentation
3. "Make suggested improvements"
4. "Create PR"

Quick Reference

# Start Claude Code
claude

# Get help
/help
claude --help

# Project setup
# Create .claude/CLAUDE.md with project instructions
# Create ~/.claude/CLAUDE.md for global settings

# Custom commands
# Create .claude/commands/commandname.md

# Common requests
"Read [file]"                          # Read file
"Edit [file] to [change]"              # Edit file
"Create [file]"                        # Create file
"Run tests"                            # Execute tests
"Show git diff"                        # View changes
"Commit changes"                       # Create commit
"Create PR"                            # Make pull request
"Find all [pattern]"                   # Search code
"Explain [code/function]"              # Understand code
"Fix [bug description]"                # Debug issues
"Add tests for [function]"             # Write tests
"Refactor [code]"                      # Improve code
"Document [code]"                      # Add documentation

# Hooks
# Configure in ~/.claude/settings.json
# Use for notifications, logging, approvals

# MCP Servers
# Configure in ~/.claude/mcp_servers.json
# Extends Claude with external tools

# Best Practices
✓ Use CLAUDE.md for project context
✓ Be specific in requests
✓ Include error messages
✓ Review changes before committing
✓ Use custom commands for workflows
✓ Leverage hooks for automation
✓ Keep conversations focused

Resources

# Official Documentation
https://code.claude.com/docs

# GitHub Repository
https://github.com/anthropics/claude-code

# Report Issues
https://github.com/anthropics/claude-code/issues

# Community
# Discord, forums, and community resources

# MCP Documentation
https://modelcontextprotocol.io

# Example Configurations
# Check GitHub for community-shared configs
# CLAUDE.md examples
# Custom slash commands
# Hook configurations

Summary

Claude Code is a powerful CLI tool that combines AI assistance with development workflows. Key capabilities:

  1. Intelligent Code Understanding: Reads, analyzes, and works with your codebase
  2. File Operations: Read, write, edit files with precision
  3. Git Integration: Commits, PRs, with thoughtful commit messages
  4. Testing: Writes and runs tests, analyzes failures
  5. Debugging: Identifies and fixes issues
  6. Documentation: Generates and maintains docs
  7. Customization: CLAUDE.md, slash commands, hooks, MCP
  8. Task Management: Automatic todo tracking for complex tasks
  9. Performance: Parallel operations, efficient context usage

Use CLAUDE.md to teach Claude about your project, create custom slash commands for common workflows, and leverage hooks and MCP for advanced automation.