Claude Code: The Complete Guide (2025)
Claude Code is Anthropic's terminal-first AI coding agent. Unlike IDE-integrated assistants that suggest completions, Claude Code is a fully autonomous agent that reads your codebase, executes comm...
Claude Code: The Complete Guide (2025)
Claude Code is Anthropic's terminal-first AI coding agent. Unlike IDE-integrated assistants that suggest completions, Claude Code is a fully autonomous agent that reads your codebase, executes commands, writes tests, and iterates until tasks are complete.
This comprehensive guide covers everything you need to know—from installation to advanced workflows with subagents, hooks, and MCP servers.
Claude Code is an agentic coding tool that runs in your terminal. You describe what you want in natural language, and Claude Code plans, executes, tests, and refines until the task is done. It's not autocomplete—it's an autonomous developer assistant.
Why Claude Code?
Claude Code represents a paradigm shift in AI-assisted development:
| Traditional AI Assistants | Claude Code |
|--------------------------|-------------|
| Suggest next lines | Execute complete features |
| Work on single files | Understand entire codebases |
| Wait for your input | Act autonomously |
| IDE-dependent | Terminal-native, works anywhere |
| Session-limited context | Persistent memory with CLAUDE.md |
Key Capabilities
- Autonomous execution: Multi-step tasks without constant prompting
- Full codebase awareness: Reads and understands your entire project
- Tool integration: Runs commands, tests, linters directly
- Self-correction: Interprets errors and fixes them
- MCP extensibility: Connect to databases, APIs, and external services
- Subagent parallelism: Spawn specialized agents for concurrent work
---
Getting Started
Installation
Claude Code requires Node.js 18+ and a Claude subscription (Pro, Max, or Team).
``bash
Install globally via npm
npm install -g @anthropic-ai/claude-code
Or use npx without installation
npx @anthropic-ai/claude-code
`
First Run
Navigate to any project directory and start Claude Code:
`bash
cd your-project
claude
`
On first run, you'll authenticate with your Anthropic account. Claude Code will then analyze your project structure and be ready for instructions.
Basic Usage
Claude Code accepts natural language instructions:
`
Add error handling to the API endpoints in src/routes/
Refactor the authentication module to use JWT instead of sessions
Write unit tests for the payment processing service
`
Claude Code will:
- Analyze your codebase to understand the context
- Plan the necessary changes
- Execute changes across multiple files
- Run tests and fix any failures
- Report what it accomplished
---
Core Commands
Interactive Mode
The default mode when you run
claude:
`bash
claude # Start interactive session
claude -p "prompt" # Start with an initial prompt
claude --resume # Resume previous conversation
claude --continue # Continue most recent conversation
`
One-Shot Mode
Execute a single task and exit:
`bash
claude -p "Add TypeScript types to utils.js" --allowedTools Edit,Write,Bash
Useful for scripting and CI/CD
claude -p "Run tests and fix any failures" --json
`
Common Flags
| Flag | Description |
|------|-------------|
|
-p, --prompt | Initial prompt to start with |
|
--allowedTools | Restrict available tools |
|
--disallowedTools | Block specific tools |
|
--json | Output results as JSON |
|
--verbose | Show detailed execution info |
|
--model | Specify model (sonnet, opus) |
|
--max-turns | Limit conversation turns |
---
Slash Commands
Claude Code includes built-in slash commands for common operations:
Essential Commands
| Command | Description |
|---------|-------------|
|
/help | Show available commands |
|
/clear | Clear conversation history |
|
/compact | Summarize and compress context |
|
/memory | View or edit CLAUDE.md memory |
|
/config | Access configuration settings |
|
/cost | Show token usage and costs |
Memory Commands
`
/memory # View current memory files
/memory edit # Edit project CLAUDE.md
/memory edit --global # Edit user-level CLAUDE.md
`
Context Management
`
/compact # Compress context to save tokens
/clear # Start fresh conversation
`
Configuration
`
/config # View all settings
/config set model opus # Change model
`
---
The CLAUDE.md Memory System
CLAUDE.md is Claude Code's persistent memory—a markdown file that provides context across sessions. This is how Claude Code "remembers" your project.
Memory Hierarchy
Claude Code reads CLAUDE.md files from multiple locations, in order of precedence:
/etc/claude/CLAUDE.md — Organization-wide standards
~/.claude/CLAUDE.md — Personal preferences across all projects
./CLAUDE.md — Project-specific context (recommended)
./src/CLAUDE.md — Subdirectory-specific guidance
What to Include
A well-structured CLAUDE.md includes:
`markdown
Project: MyApp
Overview
E-commerce platform built with Next.js 14, TypeScript, and PostgreSQL.
Commands
bun dev — Start development server
bun test — Run test suite
bun lint — Check code style
Architecture
/src/app — Next.js App Router pages
/src/components — React components (use shadcn/ui)
/src/lib — Utilities and helpers
/src/db — Drizzle ORM schema and queries
Conventions
- Use TypeScript strict mode
- Prefer async/await over .then() chains
- Use Zod for runtime validation
- Write tests for all business logic
Important Notes
- Auth uses NextAuth.js with JWT strategy
- All API routes require authentication except /api/public/*
- Use React Query for server state, Zustand for client state
`
Memory Best Practices
title="Keep It Concise"
description="Every token in CLAUDE.md consumes context. Include what matters, omit what doesn't."
/>
title="Update Regularly"
description="As your project evolves, update CLAUDE.md. Use /memory edit for quick updates."
/>
title="Layer Appropriately"
description="Put personal preferences in user CLAUDE.md, project specifics in project CLAUDE.md."
/>
title="Include Commands"
description="Always document build, test, and lint commands so Claude Code can execute them."
/>
---
Subagents: Parallel Execution
Subagents are specialized mini-agents that execute tasks in parallel with isolated context. They're Claude Code's answer to complex, multi-part workflows.
When to Use Subagents
- Code review: Multiple files reviewed simultaneously
- Testing: Different test suites run in parallel
- Research: Multiple codepaths analyzed concurrently
- Refactoring: Separate concerns handled independently
Built-in Subagent Types
| Type | Use Case | Tools Available |
|------|----------|-----------------|
|
Explore | Codebase exploration | Read, Glob, Grep |
|
Plan | Implementation planning | All tools |
|
general-purpose | Complex multi-step tasks | All tools |
Using Subagents
Invoke subagents through natural language:
`
Use 3 subagents to review the modified files for security issues
Use an Explore agent to find all usages of the deprecated API
Use a Plan agent to design the authentication system
`
Custom Subagents
Create specialized subagents with custom prompts:
`markdown
---
name: security-auditor
model: opus
tools:
- Read
- Grep
- Glob
---
You are a security researcher auditing code for vulnerabilities.
Focus on:
- SQL injection
- XSS vulnerabilities
- Authentication flaws
- Data exposure risks
Report findings with severity levels and remediation steps.
`
Save as
.claude/agents/security-auditor.md and invoke:
`
Use the security-auditor agent to audit the authentication module
`
---
Hooks: Automated Workflows
Hooks let you run custom scripts at specific points in Claude Code's lifecycle. They're powerful for enforcing standards, automating checks, and integrating with external tools.
Hook Types
| Hook | Trigger | Use Case |
|------|---------|----------|
|
PreToolUse | Before any tool executes | Validation, logging |
|
PostToolUse | After any tool executes | Verification, cleanup |
|
Notification | When Claude sends a message | Alerts, logging |
|
Stop | When Claude completes a task | Finalization, reporting |
Configuring Hooks
Add hooks to your settings file (
~/.claude/settings.json):
`json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"command": ["./scripts/lint-file.sh", "$FILE_PATH"]
}
],
"PreToolUse": [
{
"matcher": "Bash",
"command": ["./scripts/validate-command.sh", "$COMMAND"]
}
]
}
}
`
Hook Examples
Auto-format on write:
`json
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write|Edit",
"command": ["prettier", "--write", "$FILE_PATH"]
}
]
}
}
`
Security check before execution:
`json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"command": ["./scripts/security-check.sh"]
}
]
}
}
`
Notification on completion:
`json
{
"hooks": {
"Stop": [
{
"command": ["./scripts/notify-slack.sh", "Claude Code task completed"]
}
]
}
}
`
---
MCP Server Integration
MCP (Model Context Protocol) extends Claude Code's capabilities by connecting it to external tools and data sources.
What MCP Provides
- Database access: Query PostgreSQL, SQLite, MongoDB directly
- API integration: GitHub, Slack, Linear, and more
- File systems: Extended access beyond local directories
- Custom tools: Build your own integrations
Adding MCP Servers
Using the CLI:
`bash
Add an MCP server
claude mcp add github -e GITHUB_TOKEN=ghp_xxx -- npx -y @modelcontextprotocol/server-github
List configured servers
claude mcp list
Remove a server
claude mcp remove github
`
Or configure in
.claude/mcp.json:
`json
{
"mcpServers": {
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_TOKEN": "ghp_your_token"
}
},
"postgres": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://localhost/mydb"]
}
}
}
`
Essential MCP Servers
| Server | Purpose |
|--------|---------|
| GitHub | Repository, issues, PRs |
| Filesystem | Extended file access |
| PostgreSQL | Database queries |
| Slack | Team communication |
| CAS | Persistent memory and tasks |
CAS: Memory Server for Development
CAS (Coding Agent System) is an MCP server purpose-built for Claude Code, providing:
- Persistent memory across sessions
- Task tracking with context restoration
- Coding rules that surface automatically
- Skills for repeated workflows
- Semantic search across all content
`bash
Add CAS to Claude Code
claude mcp add cas
`
Usage:
`
cas_remember: "This project uses React Query for server state"
cas_task_create: "Implement user authentication"
cas_search: "How did we handle rate limiting?"
`
---
Context Management
Effective context management is crucial for getting the best results from Claude Code.
Understanding Context
Claude Code has a 200K token context window. This includes:
- CLAUDE.md contents
- Conversation history
- File contents read during the session
- Tool execution results
Context Strategies
Use
/clear when switching to unrelated work to avoid context pollution.
Use
/compact to summarize and compress long conversations while preserving key information.
Instead of "look at the codebase," specify "review src/auth/jwt.ts for security issues."
Subagents get isolated context, preventing cross-contamination in complex workflows.
Monitoring Usage
`
/cost # Show token usage for current session
`
Plan complex tasks to avoid hitting context limits mid-execution.
---
Best Practices
Effective Prompting
title="Be Specific"
description="'Add JWT auth to the API' beats 'make it secure.' Specificity yields better results."
/>
title="Provide Context"
description="Mention relevant files, frameworks, or patterns. Claude Code will find them, but hints help."
/>
title="Define Success"
description="'Tests should pass and coverage should exceed 80%' gives clear completion criteria."
/>
title="Iterate"
description="Start with core functionality, then refine. Complex features benefit from incremental development."
/>
Project Setup
- Create CLAUDE.md with project overview and commands
- Configure MCP servers for external integrations
- Set up hooks for automated workflows
- Define custom subagents for specialized tasks
Security Considerations
Claude Code executes real commands on your system. Always review proposed changes, especially for sensitive operations. Use
--allowedTools to restrict capabilities when appropriate.
- Review changes before accepting destructive operations
- Use environment variables for secrets, never hardcode
- Restrict tool access with
--allowedTools for sensitive workflows
Test in development environments before production
---
Advanced Workflows
CI/CD Integration
Claude Code's terminal-native design makes it ideal for automation:
`yaml
GitHub Actions example
- name: Fix and Test
run: |
claude -p "Fix any failing tests" --allowedTools Edit,Read,Bash --max-turns 10
`
Scripting with Claude Code
Use Claude Code in shell scripts:
`bash
#!/bin/bash
Auto-fix script
Run tests, capture failures
TEST_OUTPUT=$(npm test 2>&1)
if [ $? -ne 0 ]; then
# Ask Claude Code to fix failures
claude -p "Fix these test failures: $TEST_OUTPUT" --allowedTools Edit,Read,Bash
fi
`
Multi-Agent Workflows
Orchestrate complex workflows with subagents:
`
- Use a Plan agent to design the feature architecture
- Use a general-purpose agent to implement the core logic
- Use 3 parallel agents to write tests for each module
- Use a security-auditor agent to review the implementation
`
---
Troubleshooting
Common Issues
Claude Code is slow:
- Large context can slow responses
- Use
/compact to reduce context size
Be more specific to reduce exploration time
Changes aren't what I expected:
- Provide more specific instructions
- Include relevant file paths
- Update CLAUDE.md with project conventions
MCP server not connecting:
- Verify server command works manually
- Check environment variables are set
- Restart Claude Code after configuration changes
Running out of context:
- Use
/compact before running out
Start new sessions for unrelated tasks
Use subagents for isolated work
Getting Help
`
/help # Built-in help
claude --help # CLI help
`
For issues: github.com/anthropics/claude-code/issues
---
Claude Code + CAS: The Complete Stack
While Claude Code provides powerful autonomous execution, CAS (Coding Agent System) adds the persistent context layer that makes it truly effective across sessions:
| Claude Code | CAS |
|-------------|-----|
| Executes tasks | Remembers context |
| Plans changes | Tracks progress |
| Writes code | Stores learnings |
| Runs tests | Surfaces relevant rules |
Together, they form a complete development environment where your AI assistant both executes effectively and remembers what it learned.
`
The combined workflow
cas_task_create: "Implement user dashboard"
cas_task_start: "cas-abc1"
Claude Code implements the feature...
cas_remember: "Dashboard uses React Query with 5-minute cache"
cas_task_close: "Implemented with tests passing"
``
---
Conclusion
Claude Code represents the future of AI-assisted development—autonomous agents that understand entire codebases and execute complete features. With CLAUDE.md for persistent context, subagents for parallel execution, hooks for automation, and MCP servers for extensibility, it's a complete platform for modern development.
Key takeaways:
- Set up CLAUDE.md — Your project's memory across sessions
- Use subagents — For parallel, specialized work
- Configure hooks — For automated workflows
- Add MCP servers — For external integrations
- Manage context — Keep it focused and relevant
Install Claude Code today and experience agentic development. Start with a simple CLAUDE.md, add CAS for persistent memory, and gradually expand with hooks and MCP servers as your workflow matures.
---