Claude Code Complete Tutorial
Claude Code In-Depth Tutorial - Installation to Advanced Features, Including Ultrathink Mode and Practical Use Cases
Overview
Claude Code is a command-line AI programming assistant developed by Anthropic that autonomously writes, tests, and debugs code. It works directly in the terminal with a 200,000 token context memory, enabling seamless navigation of multi-file projects and autonomous handling of 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 results
- IDE Integration: Native support for VS Code, Cursor, Windsurf, and JetBrains
- Sandbox Isolation: OS-level filesystem and network isolation, reducing permission prompts by 84%
- Checkpoint System: Automatically save code state with instant rollback support (Esc Esc)
- MCP Protocol Support: Connect to external tools, databases, and APIs
- Extended Thinking Mode: Ultrathink provides up to 31,999 tokens of deep reasoning capability
- Multi-Instance Parallel Development: Run multiple Claude instances simultaneously for different tasks
- Vision Capabilities: Analyze screenshots and images, reverse engineer UI designs
Supported Models
- Claude Sonnet 4.5: Default model, suitable for daily development tasks (fast, cost-effective)
- Claude Opus 4.5: Best coding model, suitable for complex long-term tasks and strategic planning
- Claude Haiku 4.5: Lightweight model, suitable for simple tasks and quick responses
System Requirements
Operating Systems
- macOS: 10.15 or higher
- Linux: Ubuntu 20.04+, Debian 10+, or other major distributions
- Windows: Windows 10+ (WSL 2 or Git for Windows recommended)
Other Requirements
- Active Anthropic account (billing must be activated at console.anthropic.com)
- Internet connection (for OAuth authentication and API calls)
- Modern terminal: Bash, Zsh, Fish, PowerShell, or Git Bash
- 8GB+ RAM recommended (minimum 4GB)
Installation Guide
Method 1: Native Installation (Recommended)
Native installation provides improved auto-update stability without Node.js dependencies.
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 will display 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 the terminal to continue
Initialize Project Documentation
Run in your project root directory:
/initThis will generate a CLAUDE.md file that automatically analyzes your codebase and documents:
- Project architecture and structure
- Technology stack and dependencies
- Development standards and conventions
- Common commands and workflows
Claude Code will automatically load CLAUDE.md as context in every conversation.
Configuration File Structure
Claude Code uses a layered configuration system:
User-Level Configuration
~/.claude/settings.jsonProject-Level Configuration
your-project/.claude/settings.jsonMCP Server Configuration
your-project/.claude/mcp.json
~/.claude/mcp.jsonConfiguration File Example
{
"env": {
"ANTHROPIC_API_KEY": "your-api-key",
"ANTHROPIC_BASE_URL": "https://api.anthropic.com"
},
"model": "sonnet",
"alwaysThinkingEnabled": true,
"permissions": {
"allow": [
"Bash(git commit:*)",
"Bash(npm install:*)",
"Bash(dotnet build:*)"
]
},
"mcpServers": {
"database": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
}
}
}Basic Usage
Starting Claude Code
Run directly in your project directory:
claudeThis will start an interactive session.
Direct Command Mode
Execute tasks without entering an interactive session:
claude "Create a new branch and fix all lint errors"Headless Mode
Use the -p flag to output results directly to the terminal:
claude -p "Analyze this project's dependencies and generate a report"Skip Permission Checks
Suitable for CI/CD or automation scripts (use only in trusted environments):
claude --dangerously-skip-permissions "Run the full test suite"Core Features Explained
1. CLAUDE.md File
Create a CLAUDE.md file in your project root, and Claude Code will automatically load its content into every conversation's context.
Best Practice CLAUDE.md Template
# Project Guide
This is a .NET 10-based Web API project providing a unified AI model interface aggregation platform.
## Architecture
- Backend: .NET 10 + Minimal APIs + Clean Architecture
- Database: PostgreSQL + Entity Framework Core
- Cache: Redis + FusionCache
- Message Queue: RabbitMQ
- Frontend: Next.js 16 + React 19 (web), Vite + React 19 (admin)
- Orchestration: .NET Aspire
## Code Conventions
- Define endpoints using Minimal APIs pattern (in `/Common/*EndpointExtensions.cs`)
- All business logic in Service layer (`src/Routin.ApiService/Services/`)
- Endpoints should never directly access DbContext, must go through Service layer
- All API responses automatically wrapped in `{data, code, error}` format
- Use async/await for asynchronous operations
- Follow REST API design standards
- Run tests and build checks before committing
## Response Wrapping
All `/api/*` endpoint responses are automatically wrapped:
- Success: `{data: {...}, code: 200, error: null}`
- Error: `{data: null, code: 4xx/5xx, error: {Status, Title, Detail}}`
`/v1/*` (OpenAI compatible) endpoints return raw responses, not wrapped.
## Testing
- Unit tests: xUnit
- Run tests: `dotnet test`
- Run API: `dotnet run --project Routin.AppHost`
## Common Commands
- Start full application (Aspire): `dotnet run --project Routin.AppHost`
- Build solution: `dotnet build Routin.slnx`
- Create migration: `dotnet ef migrations add MigrationName --project src/Routin.EntityFrameworkCore --startup-project src/Routin.ApiService`
- Apply migration: `dotnet ef database update --project src/Routin.EntityFrameworkCore --startup-project src/Routin.ApiService`
- Start Web frontend: `cd web && bun run dev`
- Start Admin frontend: `cd admin && bun run dev`
## Database Migration Notes
**Important**: Stop running application before creating or applying migrations to avoid file locking issues.
## Development Workflow
1. Stop all running services
2. Create feature branch: `git checkout -b feature/name`
3. Modify code and entities
4. Create migration (if entities were modified)
5. Apply migration to database
6. Start Aspire: `dotnet run --project Routin.AppHost`
7. Test functionality
8. Commit and create PR
## Known Issues
- EF Core migrations fail when app is running (file locking) - stop app first
- Redis and RabbitMQ must be running before startup (via docker-compose)
- Frontend uses shadcn/ui component library - never use browser native `alert()`, `confirm()`, `prompt()`, must use Dialog components
## Steps to Add New Features
### Adding New API Endpoints
1. Create extension method file in `src/Routin.ApiService/Common/`
2. Register in `Program.cs`: `app.Map*Endpoints()`
3. Endpoints automatically get response wrapping (via `ResponseWrapperFilter`)
### Adding New Services
1. Create Service class in `src/Routin.ApiService/Services/`
2. Register in `Program.cs` DI container: `AddScoped<IService, Service>()`
3. Services should never directly access DbContext in endpoints
### Adding Distributed Events
1. Define event DTO in `src/Routin.ApiService/Events/`
2. Implement `IDistributedEventHandler<TEvent>`
3. Register in `Program.cs`: `AddScoped<IDistributedEventHandler<TEvent>, THandler>()`
4. Publish events via `IDistributedEventBus.PublishAsync(event)`2. Keyboard Shortcuts
| Shortcut | Function |
|---|---|
| Ctrl+A / Ctrl+E | Beginning/end of line |
| ↑ / ↓ | Browse command history |
| Tab | Auto-complete |
| Ctrl+C | Cancel current operation (press twice to force quit) |
| Escape | Stop Claude execution |
| Escape Escape | Open rollback menu, restore previous state |
| Ctrl+B | Run bash command in background |
| Ctrl+O | Toggle verbose mode (show thinking process) |
| Ctrl+D | Exit Claude Code |
| Shift+Tab (twice) | Enter plan mode (analyze only, no modifications) |
| ? | Display available shortcuts |
| Shift+Enter | Send multi-line message (requires /terminal-setup configuration) |
3. Checkpoint System
Claude Code automatically saves code state before each change.
Rollback to Previous State
- Press Esc twice
- Or use command:
/rewind
The system will display a list of all checkpoints, allowing you to select the point to restore.
4. Custom Slash Commands
Create Markdown files in the .claude/commands/ directory to define custom commands.
Example: Creating a Code Review Command
File: .claude/commands/review.md
---
name: review
description: Comprehensive code review including security analysis
---
Please perform a comprehensive review of the following code:
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
5. Identify performance issues
After analysis, generate a detailed review report.Usage:
/review src/Services/UserService.csExample: Creating a Performance Optimization Command
File: .claude/commands/optimize.md
---
name: optimize
description: Performance analysis and optimization suggestions
---
Analyze the following code for performance bottlenecks and provide optimization solutions:
Focus on:
- Database query efficiency (N+1 problem, missing indexes)
- Memory usage (memory leaks, unnecessary object allocations)
- Algorithm complexity
- Concurrency handling
- Caching strategies
Provide specific optimized code implementations.Namespace Organization
Use directory structure to organize commands:
.claude/commands/
├── backend/
│ ├── migrations.md
│ ├── api.md
│ └── test.md
├── frontend/
│ ├── components.md
│ └── styles.md
└── deployment/
├── docker.md
└── ci-cd.mdUsage:
/backend/migrations Add new field to User table
/frontend/components Create login form componentExtended Thinking Mode and Ultrathink
What is Extended Thinking?
Claude Code supports progressively enhanced thinking budgets for solving complex problems. Thinking modes are triggered by specific keywords, allocating more reasoning tokens for Claude to analyze problems in depth.
Thinking Mode Tiers
| Mode | Thinking Budget | Use Cases |
|---|---|---|
| Default | None | Simple tasks, code refactoring |
| think | ~4,000 tokens | Initial reasoning for medium complexity problems |
| think hard / megathink | ~10,000 tokens | Complex architectural decisions |
| think harder / ultrathink | ~31,999 tokens | Maximum reasoning capability for unfamiliar codebase analysis |
How to Use Ultrathink
Activation Methods
Simply include the magic keyword in your prompt:
# Method 1: Direct use of ultrathink
claude "ultrathink: Analyze this legacy system's architecture and propose a modernization plan"
# Method 2: Use think harder
claude "think harder about the best approach to refactor this authentication system"
# Method 3: In interactive mode
"Please ultrathink this problem: How to optimize this API's performance to reduce response time by 50%"Viewing the Thinking Process
Press Ctrl+O to toggle verbose mode, and Claude's internal reasoning process will be displayed in gray italic text.
Ultrathink Practical Scenarios
Scenario 1: Architectural Decisions
claude "ultrathink: Our e-commerce platform needs to handle high-concurrency orders.
Please analyze the following options and recommend the best solution:
1. Monolithic application + Redis cache
2. Microservices + Message queue
3. Serverless + Event-driven
Consider maintainability, cost, team skills, and scalability."Scenario 2: Performance Optimization
claude "ultrathink: This API endpoint has a response time of 3 seconds in production.
Please deeply analyze performance bottlenecks and provide specific optimization solutions.
src/Services/OrderService.cs"Scenario 3: Security Audit
claude "ultrathink: Conduct a comprehensive security audit of the entire authentication system.
Focus on:
- Security of JWT implementation
- Password storage and verification
- OAuth integration
- API permission control
- Potential OWASP Top 10 vulnerabilities"Scenario 4: Unfamiliar Codebase Analysis
claude "ultrathink: This is a newly inherited legacy project.
Please analyze codebase structure, identify technical debt, evaluate code quality,
and provide a refactoring roadmap."Using with Plan Mode
Best Practice: Ultrathink + Plan Mode
Press Shift+Tab twice to enter plan mode, combined with ultrathink:
# In plan mode
"ultrathink: Design a distributed caching system"This combination provides:
- Maximum reasoning capability (31,999 tokens)
- Analysis only without file modifications (safe)
- Suitable for complex architectural design and upfront planning
When to Use Ultrathink
Recommended Use:
- ✅ Complex architectural decisions (choosing databases, caching strategies, API design)
- ✅ Performance optimization (requires deep analysis across multiple layers)
- ✅ Security audits and vulnerability analysis
- ✅ Unfamiliar technology integration
- ✅ Large-scale refactoring planning
- ✅ Multi-option comparison and trade-offs
Not Recommended:
- ❌ Simple code fixes
- ❌ Formatting and lint errors
- ❌ Single-file minor modifications
- ❌ Regular CRUD operations
Performance and Cost Considerations
Ultrathink consumes significantly more tokens (up to 31,999), therefore:
- Use only for truly complex problems
- Use default or
thinkmode for simple tasks - Combine with plan mode to avoid unnecessary code modifications
- Use Opus model for best reasoning results
Ultrathink Limitations
⚠️ Important: Ultrathink only works in Claude Code CLI, not applicable to:
- Claude web chat interface
- Direct Anthropic API calls
- Other IDE integration tools
Plan Mode
What is Plan Mode?
Plan mode allows Claude to analyze code without making modifications or executing commands, equivalent to "architect mode."
Activating Plan Mode
Press Shift+Tab twice, and the interface will display [PLAN MODE] indicator.
Plan Mode Advantages
- ✅ Analyze large unfamiliar codebases (no risk)
- ✅ Architecture review and design decisions
- ✅ Performance optimization strategy planning
- ✅ Security audits (identify issues only)
- ✅ Refactoring roadmap development
Practical Workflow
Research → Plan → Implement Method
# Step 1: Enter plan mode (Shift+Tab twice)
"ultrathink: Analyze this project's architecture, identify improvement points"
# Claude generates detailed analysis report and recommendations
# Step 2: Exit plan mode (Shift+Tab twice)
"Based on the previous analysis, implement the top 3 most important improvements"
# Claude starts modifying codeThis approach significantly improves the quality of solving complex problems because Claude thinks deeply before taking action.
MCP Server Integration
What is Model Context Protocol (MCP)?
MCP is an open standard that allows Claude Code to connect to hundreds of external tools, databases, and APIs, greatly extending Claude's capabilities.
Adding MCP Servers
Method 1: Using CLI Commands
# Add MCP server
claude mcp add my-database --scope user
# List configured servers
claude mcp list
# Remove server
claude mcp remove my-databaseMethod 2: Direct Configuration File Editing
Edit .claude/mcp.json or ~/.claude/mcp.json:
{
"mcpServers": {
"database": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"DATABASE_URL": "${DATABASE_URL}"
}
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
},
"custom-api": {
"transport": "http",
"url": "https://your-mcp-server.com",
"headers": {
"Authorization": "Bearer ${API_KEY}"
}
}
}
}Configuration Scope Priority
When multiple configuration files contain servers with the same name, priority order is:
- Local scope (
.claude/mcp.json, project level, highest priority) - Personal scope (
~/.claude/mcp.json, user level)
Common MCP Servers
PostgreSQL Database
{
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres"],
"env": {
"POSTGRES_CONNECTION_STRING": "${DATABASE_URL}"
}
}
}Usage:
claude "Connect to database, analyze Users table structure and optimize indexes"GitHub Integration
{
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "${GITHUB_TOKEN}"
}
}
}Usage:
claude "List all open PRs and summarize key changes"Filesystem Access
{
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"]
}
}Transport Types
- HTTP - Recommended for remote MCP servers (cloud services)
- Local Process - For direct tool integration
- Docker - For containerized services
Security Considerations
⚠️ Use third-party MCP servers at your own risk. Verify source and trustworthiness before installation.
IDE Integration
VS Code Integration
Automatic Installation
Run claude in VS Code's integrated terminal, and the extension will install automatically.
Features
- Real-time change visualization (graphical interface showing file differences)
- Review and edit plans before accepting
- Auto-accept edits (apply changes in real-time)
- @-mention files (supports specifying line ranges)
- Access conversation history
- Multi-tab/window support
Shortcuts
- Cmd+Option+K (Mac) or Alt+Ctrl+K (Windows/Linux): Reference current file
- Automatically share lint and syntax errors
Configuration
VS Code automatically detects Claude Code settings and shares context.
Supported IDEs
- VS Code
- Cursor (based on VS Code)
- Windsurf
- VSCodium
- JetBrains Family (IntelliJ, PyCharm, WebStorm, etc.)
JetBrains Integration
"Claude Agent in JetBrains" plugin provides specialized integration:
- Unified project navigation
- Automatic error detection
- Context-aware code analysis
- Built-in terminal integration
Vision Capabilities
Using Screenshots for UI Development
Claude Code supports analyzing images and screenshots, enabling reverse engineering of UI designs.
Workflow
# Step 1: Screenshot your design (Figma, web page, etc.)
# macOS
Cmd+Ctrl+Shift+4
# Windows
Win+Shift+S
# Linux
Use your screenshot tool
# Step 2: Paste in Claude Code
Ctrl+V
# Step 3: Describe requirements
"Convert this design into a React component using Tailwind CSS"Practical Applications
Scenario 1: UI Reverse Engineering
# Paste design mockup screenshot
"Based on this design, create a login page:
- React 19 + TypeScript
- shadcn/ui components
- Responsive layout
- Form validation (react-hook-form + zod)"Scenario 2: UI Debugging
# Paste incorrect UI screenshot
"This button's alignment is wrong, fix it"Scenario 3: Data Extraction
# Paste chart or table screenshot
"Extract data from this chart and generate JSON format"Sandbox Mode and Security
OS-Level Sandbox
Claude Code implements OS-level sandbox isolation:
- Linux: Bubblewrap provides filesystem/network isolation
- macOS: Seatbelt security framework
- Windows: Windows Sandbox (WSL environment)
Sandbox Advantages
- 84% reduction in permission prompts (internal testing data)
- Even if Claude is injected with malicious prompts, it cannot:
- Access SSH keys
- Steal credentials
- Connect to unauthorized servers
- Modify system files outside project scope
Permission Levels
Level 1: Read-only (default)
├── Auto-allowed: echo, cat, ls commands
└── Requires permission: most operations
Level 2: Plan Mode
├── Analyze code only
└── No file modifications or command execution
Level 3: Auto-accept Edits
├── Bypass file edit permission prompts
└── Still asks for command execution
Level 4: Bypass All Permissions
├── Fully autonomous
└── Use cautiously - only for trusted tasksActivation Modes
# Plan mode (analyze only)
claude --mode plan
# Auto-accept edits
claude --acceptEdits
# Fully autonomous (CI/CD use)
claude --dangerously-skip-permissionsSecurity Best Practices
- ✅ Save sensitive credentials outside project directory
- ✅ Use environment variables to manage keys (don't hardcode)
- ✅ Review MCP servers before installation (third-party risk)
- ✅ Use plan mode for unfamiliar codebases
- ✅ Enable verbose mode (Ctrl+O) to review reasoning process
Multi-Instance Parallel Development
Running Multiple Claudes Simultaneously
Claude Code supports running multiple instances in parallel to handle different tasks.
Practical Example
# Terminal 1: Backend API development
cd backend
claude "Implement REST endpoints for user management"
# Terminal 2: Frontend component development
cd web
claude "Create React components for user profile page"
# Terminal 3: Testing and documentation
cd docs
claude "Generate OpenAPI documentation for API endpoints"
# Terminal 4: Infrastructure
claude "Configure Docker Compose for production deployment"Using Subagents
Subagents are specialized AI assistants with independent:
- Instruction sets
- Context windows
- Tool permissions
Configuring Subagents
Create .claude/agents/backend.md:
---
name: backend
description: Backend API development expert
---
You are an assistant focused on backend API development.
Use:
- .NET 10 + Minimal APIs
- Entity Framework Core
- PostgreSQL
- Clean Architecture
Always follow the project's response wrapping pattern.Using Subagents
claude @backend "Implement payment interface"Advanced Workflows
Workflow 1: Test-Driven Development (TDD)
# Step 1: Write tests
claude "Write complete unit tests for the user authentication module (xUnit + Moq),
including edge cases and exception handling"
# Step 2: Implement functionality
claude "Implement authentication module to pass these tests"
# Step 3: Verification
claude "Run test suite and fix any failing tests"Workflow 2: GitHub PR Automation
# Install GitHub App
/install-github-app
# Claude will now automatically review all PRsOr manual review:
claude "Review changes in PR #123, focus on security and performance"Workflow 3: Architecture Decision Records (ADR)
claude "ultrathink: We need to choose a caching solution.
Compare Redis, Memcached, and in-memory caching.
Consider performance, reliability, cost, and operational complexity.
Generate an ADR document (Architecture Decision Record)."Workflow 4: Database Migration Management
# Create and apply migration
claude "Add EmailVerified and EmailVerificationToken fields to User entity,
create EF Core migration and apply to database"
# Claude will:
# 1. Modify entity class
# 2. Run dotnet ef migrations add
# 3. Review generated migration code
# 4. Run dotnet ef database updateWorkflow 5: Continuous Refactoring
claude "Scan entire codebase, identify code smells and technical debt.
Prioritize and refactor one by one."Workflow 6: Performance Optimization
claude "ultrathink: Analyze OrderService's performance bottlenecks:
1. Identify N+1 query problems
2. Evaluate memory usage
3. Check algorithm complexity
4. Provide specific optimized code"Claude Agent SDK
What is Claude Agent SDK?
Python and TypeScript frameworks for building production-grade autonomous agents. Based on Claude Code's core, providing programmable control.
SDK Capabilities
- Automatic context management and token compression
- Rich tool ecosystem (bash, file operations, web search, MCP)
- Fine-grained permission system
- Session management and monitoring
- Error handling and recovery
Installation
Prerequisites
# Install Claude Code CLI
curl -fsSL https://claude.ai/install.sh | bash
# Python
pip install anthropic-agent
# TypeScript/Node.js
npm install @anthropic-ai/agentPython Basic Example
from anthropic_agent import Agent
# Create agent
agent = Agent(
model="claude-opus-4-5",
instructions="You are a professional code review assistant"
)
# Run agent
result = agent.run("Review this codebase and provide improvement suggestions")
print(result)TypeScript Basic Example
import { Agent } from "@anthropic-ai/agent";
const agent = new Agent({
model: "claude-opus-4-5",
instructions: "You are a professional code review assistant"
});
const result = await agent.run("Review this codebase");
console.log(result);Practical Use Cases
1. Financial Analysis Agent
agent = Agent(
model="claude-opus-4-5",
instructions="""
You are a financial analyst.
Use external APIs to fetch stock data and perform portfolio analysis.
""",
mcp_servers=["finance-api"]
)
result = agent.run("Analyze my investment portfolio and provide optimization suggestions")2. Customer Support Agent
const supportAgent = new Agent({
model: "claude-sonnet-4-5",
instructions: `
You are a customer support assistant.
- Handle user requests
- Collect necessary information
- Escalate to human when necessary
`,
mcpServers: ["crm-system", "ticket-system"]
});
await supportAgent.run("Help user #12345 resolve login issue");3. Development Agent
dev_agent = Agent(
model="claude-opus-4-5",
instructions="""
You are a full-stack development assistant.
Responsible for code review, refactoring, testing, and deployment.
""",
tools=["bash", "file_operations", "git"]
)
dev_agent.run("Refactor authentication system and add unit tests")Subagent Parallel Workflow
from anthropic_agent import Agent, Orchestrator
# Create orchestrator
orchestrator = Orchestrator()
# Define subagents
backend_agent = Agent(
model="claude-sonnet-4-5",
instructions="Focus on backend API development"
)
frontend_agent = Agent(
model="claude-sonnet-4-5",
instructions="Focus on frontend component development"
)
infra_agent = Agent(
model="claude-sonnet-4-5",
instructions="Focus on infrastructure and deployment"
)
# Parallel execution
results = orchestrator.run_parallel([
(backend_agent, "Implement user management API"),
(frontend_agent, "Create user interface"),
(infra_agent, "Configure CI/CD pipeline")
])Practical Case Studies
Case 1: Quick Refactoring of Legacy Code
Scenario: Refactor old synchronous code to asynchronous pattern
claude "Convert all service methods in src/Services/ directory to async pattern,
use async/await, ensure proper exception handling, update all callers"Claude Code will:
- Scan all files in directory
- Identify synchronous methods
- Rewrite as async methods
- Update callers
- Add appropriate exception handling
- Run tests for verification
Case 2: Automated Test Generation
Scenario: Generate complete unit tests for existing code
claude "Generate complete unit tests for UserService.cs:
- Use xUnit and Moq
- Cover all public methods
- Include normal and exception flows
- Test boundary conditions and null handling
- Naming convention: MethodName_Scenario_ExpectedBehavior"Case 3: API Endpoint Implementation
Scenario: Quickly implement RESTful API endpoints
claude "Create a complete user management API:
- CRUD operations
- Use Minimal APIs pattern
- Follow project's ResponseWrapper pattern
- Add JWT authentication
- Include input validation (FluentValidation)
- Add Swagger documentation comments"Case 4: Performance Analysis and Optimization
Scenario: Identify and fix N+1 query problems
claude "ultrathink: Analyze database queries in OrderService.cs.
Identify N+1 problems, optimize query performance using Include and ThenInclude.
Add performance logging for monitoring."Case 5: Git Workflow Automation
Scenario: Create feature branch and commit code
claude "Create new branch feature/email-verification,
commit current changes, push to remote, and create PR"Claude Code will:
- Run
git checkout -b feature/email-verification - Run
git add . - Generate meaningful commit message
- Run
git commit - Run
git push -u origin feature/email-verification - Create PR using
gh pr create
Case 6: Dockerizing Application
Scenario: Create Docker configuration for project
claude "Create multi-stage Dockerfile for building .NET API application.
Create docker-compose.yml including:
- API service
- PostgreSQL
- Redis
- RabbitMQ
Include health checks and environment variable configuration."Case 7: Security Audit
Scenario: Comprehensive security review
claude "ultrathink: Conduct security audit of entire application.
Check OWASP Top 10 vulnerabilities:
1. SQL injection
2. XSS
3. CSRF
4. Authentication flaws
5. Authorization issues
6. Sensitive data exposure
7. Security misconfiguration
8. Dependency vulnerabilities
Generate detailed security report and remediation suggestions."Case 8: Logging Enhancement
Scenario: Add structured logging to existing code
claude "Add detailed Serilog structured logging to PaymentService.cs:
- Method entry/exit
- Parameter logging
- Execution time measurement
- Exception details
- Use log levels (Information, Warning, Error)"Case 9: Dependency Injection Configuration
Scenario: Automatically configure service registration
claude "Scan all service classes in Services directory,
add corresponding AddScoped registration in Program.cs.
Follow interface-implementation pattern (IService, Service)."Case 10: Documentation Generation
Scenario: Generate project documentation
claude "Scan src/ directory, generate API documentation (Markdown format):
- All public endpoints
- Request/response formats
- Authentication requirements
- Usage examples (curl commands)
- Error code explanations"Best Practices Checklist
Project Initialization Checklist
When starting a new project:
- Run
/initto createCLAUDE.md - Configure
.claude/settings.jsonto set default model and permissions - Set up MCP server connections for common tools
- Create common custom commands (review, test, scaffold, etc.)
- Add
.gitignoreentry:.claude/settings.json(if containing sensitive info) - Run
/terminal-setupto configure Shift+Enter binding
Pre-Session Checklist
Before starting each new task:
- Run
/clearto clear historical context - Confirm
CLAUDE.mdis up to date - Define task objectives and acceptance criteria
- Identify relevant files and dependencies
- Decide if plan mode is needed (Shift+Tab twice)
Quality Assurance Checklist
Before accepting Claude's changes:
- Review all file differences
- Run project's build command
- Run test suite
- Check lint and formatting
- Verify functionality works locally
- Run security review before committing (if needed)
Performance Optimization Checklist
- Keep
CLAUDE.mdconcise (reduce token consumption) - Use project-level config instead of user-level config (faster loading)
- Use
-pflag for simple tasks (avoid interactive overhead) - Frequently use
/clearto clear irrelevant history - Choose Haiku model for simple tasks
- Reserve Opus + Ultrathink for complex tasks
Security Checklist
- Use environment variables to store API keys and tokens
- Regularly rotate keys
- Add
.claude/settings.jsonto.gitignore(if containing keys) - Ensure environment is trusted when using
--dangerously-skip-permissionsin CI/CD - Review trustworthiness of third-party MCP servers
- Use plan mode for unfamiliar codebases
Team Collaboration Checklist
- Commit
.claude/commands/to version control (share commands) - Use
.claude/mcp.jsonto configure team-shared MCP servers - Document team coding standards in
CLAUDE.md - Regularly sync custom command library
- Establish team conventions for Claude Code usage
Troubleshooting
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
npx @modelcontextprotocol/server-postgresIssue: Performance Slowness
- Reduce
CLAUDE.mdfile size - Disable unnecessary MCP servers
- Use faster models (Sonnet or Haiku instead of Opus)
- Frequently run
/clearto clear history
Issue: Permission Denied
- Check file permissions:
ls -la - Ensure Claude Code has execute permission:
chmod +x $(which claude) - Use
--acceptEditsflag to bypass edit permissions
Issue: Token Limit
- Run
/clearto clear history - Reduce
CLAUDE.mdcontent - Use more specific instructions (avoid Claude exploring irrelevant files)
- Consider splitting large tasks into multiple smaller tasks
Diagnostic Commands
# System health check
claude doctor
# View configuration
cat ~/.claude/settings.json
# View logs
tail -f ~/.claude/logs/claude.log
# Clear cache
rm -rf ~/.claude/cacheGitHub Actions Integration
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 this PR's 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
});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 lint 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 pushConnecting to Routin API Platform
Configuring Custom API Endpoints
While Claude Code defaults to using Anthropic's official API, you can configure custom endpoints via environment variables.
Method 1: Environment Variables
Create .env file:
ANTHROPIC_BASE_URL=https://routin.ai/
ANTHROPIC_API_KEY=your-meteor-platform-api-keyMethod 2: Configuration File
Edit .claude/settings.json:
{
"env": {
"ANTHROPIC_API_KEY": "your-meteor-api-key",
"ANTHROPIC_BASE_URL": "https://routin.ai/"
},
"model": "sonnet"
}Verify Configuration
# Test connection
claude -p "hello world"If connection is successful, Claude Code will call AI models through the Routin platform.
Reference Resources
Official Documentation
- Claude Code Official Documentation
- Claude Code Best Practices
- Claude Agent SDK
- Model Context Protocol (MCP)
- Sandboxing and Security
Community Resources
- Awesome Claude Code - Curated commands, files, and workflows
- ClaudeLog - Documentation, guides, and tutorials
- Claude Code Complete Guide
Ultrathink Related
Practical Tutorials
Conclusion
Claude Code is a powerful AI programming assistant that can significantly improve development efficiency. By mastering:
- ✅ Extended Thinking Mode (Ultrathink): Handle complex architectural decisions
- ✅ Plan Mode: Deep analysis before implementation
- ✅ MCP Integration: Connect to external tools and data sources
- ✅ Multi-Instance Parallel Development: Handle multiple tasks simultaneously
- ✅ Vision Capabilities: Reverse engineer UI from screenshots
- ✅ Custom Commands: Build team workflows
- ✅ Agent SDK: Build production-grade autonomous agents
You will be able to fully leverage Claude Code's potential for truly autonomous development.
Remember the key principles:
- 🎯 Clear Instructions - The more specific, the better
- 🧠 Use Thinking Modes Appropriately - Use Ultrathink for complex problems
- 📋 Maintain CLAUDE.md - Keep project documentation up to date
- 🔄 Clear History Frequently - Save tokens and costs
- 🔒 Focus on Security - Use sandbox and permission controls
Sources:
- Claude Code Best Practices
- What is UltraThink in Claude Code
- Claude Code Thinking Modes Guide
- ClaudeCode Tutorial Center
- Claude Code Thinking Levels
- Cooking with Claude Code
- ClaudeLog - Claude Code Docs
- How I use Claude Code
- Claude Code overview
- Awesome Claude Code
- Making Claude Code more secure
- Building agents with the Claude Agent SDK