Claude Code Complete Tutorial
Claude Code In-Depth Tutorial - Installation, Configuration, Use Cases & Programming Best Practices
Overview
Claude Code is a command-line AI programming assistant developed by Anthropic that can automatically write, test, and debug code. It works directly in your terminal with 200,000 tokens of context memory, seamlessly navigates multi-file projects, and autonomously handles cross-codebase refactoring tasks.
Core Features
- Autonomous Code Operations: Automatically write, edit, test, and debug code
- Multi-File Editing: Handle modifications across multiple files simultaneously
- Command Execution: Run terminal commands to verify work
- IDE Integration: Native support for VS Code and JetBrains
- Sandbox Isolation: Filesystem and network isolation reduces permission prompts by 84%
- Checkpoint System: Automatically save code state with instant rollback support
- MCP Protocol Support: Connect to external tools, databases, and APIs
Supported Models
- Claude Sonnet 4.5: Default model, suitable for daily development tasks
- Claude Opus 4: Best coding model for complex long-term tasks and agentic workflows
System Requirements
Operating Systems
- macOS: 10.15 or higher
- Linux: Ubuntu 20.04+, Debian 10+ or other mainstream distributions
- Windows: Windows 10+ (requires WSL 1, WSL 2, or Git for Windows)
Other Requirements
- Active Anthropic account (billing must be activated at console.anthropic.com)
- Internet connection (for OAuth authentication and API calls)
Installation Guide
Method 1: Native Installation (Recommended)
Native installation provides improved auto-updater stability without Node.js dependency.
macOS / Linux / WSL
curl -fsSL https://claude.ai/install.sh | bashWindows PowerShell
irm https://claude.ai/install.ps1 | iexMethod 2: Using Homebrew (macOS Only)
brew install claude-codeMethod 3: Using npm
npm install -g @anthropic-ai/claude-codeNote: Requires Node.js 18 or higher.
Verify Installation
After installation, run the following command to verify:
claude doctorThis command displays your installation type, version information, and configuration status.
Initial Configuration
Authentication Setup
First-time use requires OAuth authentication:
- Start Claude Code in your project directory:
claude- Follow the prompt to open the authentication link in your browser
- Log in to your Anthropic account and authorize
- Return to terminal to continue
Configuration File Structure
Claude Code uses a hierarchical configuration system with support for the following configuration files:
User-Level Configuration
~/.claude/settings.local.jsonProject-Level Configuration
your-project/.claude/settings.local.jsonMCP Server Configuration
your-project/.mcp.jsonConfiguration File Example
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/path/to/allowed/files"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
}
},
"defaultModel": "claude-sonnet-4.5",
"experimental": {
"sandboxing": true
}
}Basic Usage
Starting Claude Code
Run directly in your project directory:
claudeThis starts an interactive session.
Direct Command Mode
Execute tasks directly without entering interactive session:
claude "checkout a new branch and lint this project"Headless Mode
Use the -p flag to output results directly to terminal:
claude -p "analyze this project's dependencies"Core Features In-Depth
1. CLAUDE.md File
Create a CLAUDE.md file in your project root, and Claude Code will automatically load its contents into the context of every conversation.
Example CLAUDE.md
# Project Guidelines
This is a web application project.
## Architecture
- Backend: Node.js + Express
- Frontend: React + TypeScript
- Database: PostgreSQL
- Cache: Redis
## Code Conventions
- Use async/await for asynchronous operations
- Follow REST API design principles
- Use ESLint and Prettier for code formatting
- Run tests and lint checks before committing
## Testing
- Unit Tests: Jest
- Integration Tests: Supertest
- Run Tests: npm test
- Coverage Report: npm run coverage
## Common Commands
- Start dev server: npm run dev
- Production build: npm run build
- Database migration: npm run migrate2. Checkpoint System
Claude Code automatically saves code state before each change.
Rollback to Previous State
- Press
Esctwice - Or use command:
/rewind
View Checkpoint List
Hold Shift while dragging files to see all checkpoints.
3. Custom Slash Commands
Create Markdown files in the .claude/commands/ directory to define custom commands.
Example: Create Code Review Command
File: .claude/commands/review.md
Please conduct a comprehensive code review:
1. Check for potential security vulnerabilities (SQL injection, XSS, CSRF, etc.)
2. Evaluate code quality and maintainability
3. Check adherence to project coding standards
4. Provide specific improvement suggestions
$ARGUMENTSUsage:
/review src/Services/UserService.csExample: Create Performance Optimization Command
File: .claude/commands/optimize.md
Analyze performance bottlenecks in the following code and provide optimization solutions:
Focus areas:
- Database query efficiency (N+1 issues, missing indexes)
- Memory usage (memory leaks, unnecessary object allocation)
- Algorithm complexity
- Concurrency handling
- Caching strategy
$ARGUMENTS4. Keyboard Shortcuts
- Esc: Stop Claude's current operation (doesn't exit session)
- Esc Esc (press twice): Display message history list with jump support
- Ctrl+C: Exit Claude Code completely
- Shift + Drag Files: Properly reference file contents
MCP Server Integration
Model Context Protocol (MCP) allows Claude Code to connect to external tools and data sources.
Adding MCP Servers
Method 1: Using CLI Commands
# Add stdio-based server
claude mcp add --transport stdio <name> <command> [args...]
# Add HTTP-based server
claude mcp add --transport http --scope local <name> <url>Method 2: Direct Configuration File Editing
Edit .mcp.json or .claude/settings.local.json:
{
"mcpServers": {
"database": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"POSTGRES_CONNECTION_STRING": "${DATABASE_URL}"
}
},
"slack": {
"command": "node",
"args": ["./mcp-servers/slack-server.js"],
"env": {
"SLACK_BOT_TOKEN": "${SLACK_TOKEN}"
}
},
"custom-api": {
"transport": "http",
"url": "https://your-mcp-server.com",
"headers": {
"Authorization": "Bearer ${API_KEY}"
}
}
}
}Configuration Scope Priority
When servers with the same name exist in multiple configuration files, priority order is:
- Local scope (
.mcp.json, project-level, highest priority) - Project scope (
.claude/settings.local.json, project-specific) - User scope (
~/.claude/settings.local.json, user-level)
Common MCP Servers
Filesystem Access
{
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"]
}
}GitHub Integration
{
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
}
}Google Drive Access
{
"google-drive": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-google-drive"],
"env": {
"GOOGLE_APPLICATION_CREDENTIALS": "${GOOGLE_CREDS_PATH}"
}
}
}Programming Project Use Cases
Case 1: Quick Legacy Code Refactoring
Scenario: Refactor old synchronous code to asynchronous pattern
claude "Convert all service methods in src/Services/ directory to async pattern using async/await, ensure proper exception handling"Claude Code will:
- Scan all files in the directory
- Identify synchronous methods
- Rewrite as async methods
- Update callers
- Add appropriate exception handling
Case 2: Automated Test Generation
Scenario: Generate unit tests for existing code
claude "Generate complete unit tests for UserService.cs using xUnit and Moq, covering all public methods and edge cases"Or use custom command:
Create .claude/commands/generate-tests.md:
Generate complete unit tests for the following code:
Test Framework: xUnit
Mock Framework: Moq
Coverage Requirements:
- All public methods
- Normal and exception flows
- Boundary conditions
- Null handling
Test Naming Convention: MethodName_Scenario_ExpectedBehavior
$ARGUMENTSUsage:
/generate-tests src/Services/UserService.csCase 3: API Endpoint Implementation
Scenario: Quickly implement RESTful API endpoints
claude "Create a complete user management API including CRUD operations, using Minimal APIs, following project's ResponseWrapper pattern, add JWT authentication, include input validation"Case 4: Database Migration
Scenario: Create and apply EF Core migrations
claude "Add EmailVerified and EmailVerificationToken fields to User entity, create migration and apply to database"Claude Code will:
- Modify entity class
- Run
dotnet ef migrations add AddEmailVerification - Review generated migration code
- Run
dotnet ef database update
Case 5: Performance Analysis and Optimization
Scenario: Identify and fix N+1 query issues
claude "Analyze database queries in OrderService.cs, identify N+1 issues, optimize query performance using Include and ThenInclude"Case 6: Git Workflow Automation
Scenario: Create feature branch and commit code
claude "Create new branch feature/user-email-verification, commit current changes, push to remote, and create PR"Case 7: Cross-Project Refactoring
Scenario: Rename classes or methods used across multiple files
claude "Rename UserRepository to UserDataRepository, update all references including interfaces, implementations, and dependency injection configuration"Case 8: Dependency Injection Configuration
Scenario: Automatically configure service registration
claude "Scan all service classes in Services directory, add corresponding AddScoped registrations in Program.cs"Case 9: Enhanced Logging
Scenario: Add structured logging to existing code
claude "Add detailed Serilog structured logging to PaymentService.cs, including method entry/exit, parameters, execution time, and exceptions"Case 10: Dockerizing Application
Scenario: Create Docker configuration for project
claude "Create multi-stage Dockerfile for building .NET API application, create docker-compose.yml including API, PostgreSQL, Redis, and RabbitMQ"Advanced Techniques
1. Unattended Mode
Skip permission checks, suitable for CI/CD or automation scripts:
claude --dangerously-skip-permissions "fix all ESLint errors"Warning: Only use this option in trusted environments.
2. Pipeline Integration
Pass output from other commands to Claude Code:
# Monitor logs and notify on anomalies
tail -f app.log | claude -p "if you see any anomalies, notify me via Slack"
# Analyze test failure reasons
dotnet test | claude -p "analyze failed tests and suggest fixes"3. Batch File Processing
Process multiple files matching a pattern:
claude "Replace all var declarations with explicit type declarations in src/**/*.cs"4. Automated Code Review
Integrate Claude Code in Git hooks:
Create .git/hooks/pre-commit:
#!/bin/bash
claude -p "review staged changes, check for security vulnerabilities and code quality issues" --dangerously-skip-permissions5. Continuous Monitoring Mode
Use background tasks to continuously monitor project:
# Monitor performance metrics
claude "monitor app.log, if response time exceeds 500ms analyze and suggest optimizations" &
# Monitor error rate
claude "monitor error logs, aggregate common errors and generate daily report" &6. Template Generation
Use custom commands to quickly generate common code templates:
Create .claude/commands/scaffold-service.md:
Create new service in src/Services/ directory:
Service Name: $ARGUMENTS
Include:
1. Interface definition (I$ArgumentsService)
2. Implementation class ($ArgumentsService)
3. Unit test file ($ArgumentsServiceTests)
4. Service registration in Program.cs
Follow project's Repository Pattern and dependency injection conventions.Usage:
/scaffold-service Payment7. Documentation Generation
Automatically generate project documentation:
claude "scan src/ directory, generate API documentation (Markdown format) including all public endpoints, request/response formats, and usage examples"8. Dependency Update Management
Safely update dependency packages:
claude "check outdated dependencies in package.json, update each to latest stable version one by one, run tests to ensure no breaking changes"Sandbox Mode
Claude Code's sandbox feature provides filesystem and network isolation for improved security.
Enable Sandbox
Add to configuration file:
{
"experimental": {
"sandboxing": true
}
}Sandbox Restrictions
In sandbox mode, Claude Code:
- Can only access files within project directory
- Network requests require explicit authorization
- Automatically reduces permission prompts by 84%
Best Practices
1. Project Initialization Checklist
When starting a new project:
- Create
CLAUDE.mddescribing project architecture and conventions - Configure
.claude/settings.local.jsonto set default model and options - Set up MCP servers to connect common tools
- Create common custom commands (review, test, scaffold, etc.)
- Add
.gitignoreentry:.claude/settings.local.json(contains sensitive info)
2. Security Recommendations
- Use environment variables to store API keys and tokens
- Rotate keys regularly
- Add
.claude/settings.local.jsonto.gitignore - Ensure trusted environment when using
--dangerously-skip-permissionsin CI/CD - Enable sandbox mode for enhanced security
3. Performance Optimization
- Keep
CLAUDE.mdconcise (reduce token consumption) - Use project-level configuration instead of user-level (faster loading)
- Use
-pflag for simple tasks (avoid interactive overhead) - Set reasonable MCP server timeout values
4. Team Collaboration
- Commit
.claude/commands/to version control (share commands) - Use
.mcp.jsonto configure team-shared MCP servers - Create team coding standards and document in
CLAUDE.md - Regularly sync custom command library
5. Debugging Tips
- Use
claude doctorto diagnose configuration issues - Check log files:
~/.claude/logs/ - Use
claude --verbosefor detailed output - Use checkpoint system to rollback when encountering issues
GitHub Actions Integration
Use Claude Code in CI/CD pipelines to automate workflows.
Example: Automated Code Review
Create .github/workflows/claude-review.yml:
name: Claude Code Review
on:
pull_request:
types: [opened, synchronize]
jobs:
review:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Claude Code
run: curl -fsSL https://claude.ai/install.sh | bash
- name: Run Code Review
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude -p "review PR changes, check for security vulnerabilities, code quality, and best practices" > review.md
- name: Post Review Comment
uses: actions/github-script@v6
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: review
});Example: Auto-Fix Lint Errors
Create .github/workflows/auto-fix-lint.yml:
name: Auto Fix Lint Errors
on:
push:
branches: [develop]
jobs:
auto-fix:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Claude Code
run: curl -fsSL https://claude.ai/install.sh | bash
- name: Fix Lint Errors
env:
ANTHROPIC_API_KEY: ${{ secrets.ANTHROPIC_API_KEY }}
run: |
claude --dangerously-skip-permissions "fix all ESLint errors"
- name: Commit Changes
run: |
git config user.name "Claude Code Bot"
git config user.email "bot@example.com"
git add .
git commit -m "chore: auto-fix lint errors" || echo "No changes"
git pushTroubleshooting
Common Issues
Issue: Authentication Failure
# Clear existing credentials and re-authenticate
rm -rf ~/.claude/auth
claudeIssue: MCP Server Cannot Connect
# Check MCP server configuration
claude mcp list
# Test specific server
claude mcp test <server-name>Issue: Slow Performance
- Reduce
CLAUDE.mdfile size - Disable unnecessary MCP servers
- Use faster model (Sonnet instead of Opus)
Issue: Permission Denied
- Check file permissions:
ls -la - Ensure Claude Code has execute permission:
chmod +x $(which claude) - Grant necessary permissions in sandbox mode
Diagnostic Commands
# System health check
claude doctor
# View configuration
claude config list
# View logs
tail -f ~/.claude/logs/claude.log
# Clear cache
rm -rf ~/.claude/cacheConnecting to Meteor API Platform
Configure Custom API Endpoint
While Claude Code uses Anthropic's official API by default, you can configure a custom endpoint via environment variables.
Create .env file:
ANTHROPIC_BASE_URL=https://routin.ai/
ANTHROPIC_API_KEY=your-meteor-platform-api-keyOr set in configuration file:
{
"apiEndpoint": "https://routin.ai/",
"apiKey": "${ANTHROPIC_API_KEY}"
}Verify Configuration
# Test connection
claude -p "hello world"If connection is successful, Claude Code will call AI models through the Meteor platform.
Reference Resources
- Official Documentation: docs.claude.com
- Best Practices: Claude Code Best Practices
- MCP Protocol: docs.anthropic.com/mcp
- GitHub Actions: Official Integration Examples
- Community Resources: Awesome Claude Code