# Claude Code Complete Setup Guide > **Comprehensive documentation for the Claude Code Setup project** > **Version**: 3.0.0 | **Last Updated**: 2025-10-20 > **Completeness**: ~95% of Claude Code capabilities implemented --- ## Table of Contents 1. [Overview](#overview) 2. [Project Structure](#project-structure) 3. [Core Features](#core-features) 4. [MCP Servers](#mcp-servers) 5. [Agents & Subagents](#agents--subagents) 6. [Slash Commands](#slash-commands) 7. [Output Styles](#output-styles) 8. [Hooks System](#hooks-system) 9. [Templates](#templates) 10. [Configuration](#configuration) 11. [Memory & Context](#memory--context) 12. [Advanced Features](#advanced-features) 13. [Best Practices](#best-practices) 14. [Troubleshooting](#troubleshooting) --- ## Overview ### What is This Project? This is a **production-ready Claude Code setup** demonstrating comprehensive configuration of all major features, including: - ✅ 8 MCP servers configured (code navigation, memory, documentation, automation) - ✅ 8 specialized agents (architecture, code review, debugging, security, testing) - ✅ 9 slash commands (adr, analyze, review, implement, test, optimize, explain, scaffold) - ✅ 6 custom output styles (concise, professional, verbose, learning, explanatory, security) - ✅ 6 event hooks (session lifecycle, bash commands, file operations, stop tracking) - ✅ Comprehensive templates for extending all features - ✅ Custom status line and plugin marketplace access - ✅ Automatic status summaries showing tool usage for every task ### Claude Code Capabilities Overview Claude Code is an AI-powered development assistant that operates through: **Core Mechanisms**: - **Tools**: File operations (Read, Write, Edit), code search (Grep, Glob), shell execution (Bash) - **MCP Servers**: External integrations extending Claude's capabilities - **Agents/Subagents**: Specialized AI assistants for specific domains - **Slash Commands**: User-invoked workflows and routines - **Output Styles**: Customizable response behaviors - **Hooks**: Event-driven automation - **Memory**: Persistent and temporary context storage --- ## Project Structure ``` Claude Code Setup/ │ ├── .claude/ # Main Claude Code configuration directory │ │ │ ├── agents/ # Specialized AI agents (8 agents) │ │ ├── architect.md # System design & technical planning │ │ ├── code-reviewer.md # Code quality & review │ │ ├── debugger.md # Bug diagnosis & fixing │ │ ├── documentation-writer.md # Technical documentation │ │ ├── project-manager.md # Project coordination │ │ ├── refactoring-specialist.md # Code improvement │ │ ├── security-analyst.md # Security analysis │ │ ├── test-engineer.md # Testing strategy │ │ └── .AGENT_TEMPLATE.md # Template for new agents │ │ │ ├── commands/ # Slash commands (8 commands) │ │ ├── analyze.md # Comprehensive code analysis │ │ ├── explain.md # Code explanation │ │ ├── implement.md # Feature implementation │ │ ├── optimize.md # Performance optimization │ │ ├── review.md # Code review │ │ ├── scaffold.md # Project scaffolding │ │ ├── setup-info.md # Display setup information │ │ ├── test.md # Test execution │ │ └── .COMMANDS_TEMPLATE.md # Template for new commands │ │ │ ├── output-styles/ # Custom output behaviors (6 styles) │ │ ├── concise.md # Brief responses │ │ ├── professional.md # Formal tone │ │ ├── verbose.md # Detailed explanations │ │ ├── explanatory.md # Educational insights │ │ ├── learning.md # Interactive learning mode │ │ ├── security-reviewer.md # Security-focused │ │ └── .OUTPUT_STYLES_TEMPLATE.md # Template for new styles │ │ │ ├── skills/ # Agent skills (model-invoked) │ │ └── .SKILL_TEMPLATE.md # Template for new skills │ │ │ ├── hooks/ # Event automation (6 hooks) │ │ ├── session-start.sh # Session initialization │ │ ├── session-end.sh # Session cleanup │ │ ├── stop.sh # Stop event logging │ │ ├── pre-bash.sh # Before bash commands │ │ ├── post-write.sh # After file writes │ │ └── user-prompt-submit.sh # After prompt submission │ │ │ ├── tools/ # Utility scripts │ │ ├── start-memory.ps1 # PowerShell memory MCP launcher │ │ └── statusline.sh # Custom status line script │ │ │ ├── logs/ # Session logs │ │ ├── session.log # Session activity │ │ ├── bash.log # Bash command log │ │ └── writes.log # File write log │ │ │ ├── settings.json # Main configuration (shared) │ ├── settings.local.json # Local configuration (personal) │ ├── statusline.sh # Status line configuration │ │ │ └── [Documentation Files] # Various guides (see below) │ ├── .mcp.json # MCP servers configuration (9 servers) ├── CLAUDE.md # Project instructions for Claude ├── CLAUDE_TEMPLATE.md # Template for CLAUDE.md files └── TEMPLATES_SUMMARY.md # Quick reference for all templates ``` ### Documentation Files (in .claude/) - **TEMPLATES_README.md** - Master guide for all templates - **agents/MCP_USAGE_TEMPLATES.md** - MCP usage templates for agents - **CHECKPOINTING_GUIDE.md** - Session checkpointing guide - **SETUP_COMPLETE.md** - Setup completion summary - **PLUGIN_SETUP.md** - Plugin marketplace guide - **STATUS_LINE_SETUP.md** - Status line customization - **TEMPLATE_CAPABILITIES_ANALYSIS.md** - Template review analysis --- ## Core Features ### 1. File Operations Claude Code has direct file access through specialized tools: **Read Tool**: - Read any file by absolute path - Support for images, PDFs, Jupyter notebooks - Optional line offset and limit for large files **Write Tool**: - Create new files (overwrites existing) - Must read file first before writing existing files **Edit Tool**: - Exact string replacement - Must read file first - Supports `replace_all` for renaming **Glob Tool**: - Fast file pattern matching - Returns files sorted by modification time - Examples: `**/*.js`, `src/**/*.ts` **Grep Tool**: - Built on ripgrep for fast searching - Supports regex patterns - Context lines (-A, -B, -C options) - Multiple output modes (content, files_with_matches, count) ### 2. Shell Execution **Bash Tool**: - Execute shell commands with timeout (default 2 min, max 10 min) - Background execution supported - Parallel execution for independent commands - Sequential execution with `&&` for dependencies **Pre-approved commands** (no permission needed): - `ls`, `dir`, `git status`, `git diff`, `git log` - `mkdir`, `echo`, `findstr`, `tree` - `npx`, `uvx`, `where` ### 3. Specialized Tools - **WebSearch**: Search the web for current information - **WebFetch**: Retrieve and process web content - **SlashCommand**: Execute custom slash commands - **Task**: Launch specialized subagents - **TodoWrite**: Manage task lists during sessions - **NotebookEdit**: Edit Jupyter notebooks --- ## MCP Servers ### Overview This project has **8 MCP servers** configured, providing extensive capabilities beyond Claude's native tools. ### 1. Serena MCP **Purpose**: IDE assistant with code navigation and persistent memory **Command**: `uvx --from git+https://github.com/oraios/serena serena start-mcp-server` **Capabilities**: *Code Navigation*: - `find_symbol` - Locate code symbols by name/pattern - `find_referencing_symbols` - Find all references to a symbol - `get_symbols_overview` - Get file structure overview - `search_for_pattern` - Search for patterns in code - `rename_symbol` - Safely rename across codebase - `replace_symbol_body` - Replace function/class body - `insert_after_symbol` / `insert_before_symbol` - Add code at specific locations *Persistent Memory*: - `write_memory` - Store information that persists across sessions - `read_memory` - Recall stored information - `list_memories` - Browse all memories - `delete_memory` - Remove outdated information **Storage**: `.serena/memories/` (survives across sessions) **Best Used For**: - ✅ Architectural Decision Records (ADRs) - ✅ Code review findings and summaries - ✅ Lessons learned from implementations - ✅ Project-specific patterns discovered - ✅ Technical debt registry - ✅ Security audit results - ✅ Performance optimization notes **Current Memory**: `serena-persistence-test` ### 2. Sequential Thinking MCP **Purpose**: Enhanced reasoning and complex problem-solving **Command**: `npx -y @modelcontextprotocol/server-sequential-thinking` **Capabilities**: - `sequentialthinking` - Multi-step reasoning with revision capability - Adjust thought count dynamically - Branch and revise previous thoughts - Generate and verify hypotheses **Best Used For**: - Complex architectural decisions - Multi-step debugging - Design pattern selection - Security analysis ### 3. Database Server MCP **Purpose**: Database query support **Command**: `npx -y @executeautomation/database-server` **Note**: Requires database connection configuration ### 4. Context7 MCP **Purpose**: Real-time library documentation lookup **Command**: `npx -y @upstash/context7-mcp` **Capabilities**: - `resolve-library-id` - Find library identifier for documentation - `get-library-docs` - Get current framework/library documentation **Best Used For**: - Learning new frameworks - Getting up-to-date API references - Finding best practices for libraries - Code examples from official docs **API Key**: Configured in `.mcp.json` ### 5. Memory MCP (Knowledge Graph) **Purpose**: Temporary in-memory knowledge graph for current session **Command**: `powershell -ExecutionPolicy Bypass -File .\.claude\tools\start-memory.ps1` **Capabilities**: - `create_entities` - Create entities (Features, Classes, Services, etc.) - `create_relations` - Define relationships between entities - `add_observations` - Add details to entities - `search_nodes` - Search the knowledge graph - `read_graph` - View entire graph state - `open_nodes` - Retrieve specific entities - `delete_entities` / `delete_relations` / `delete_observations` - Remove items **Storage**: In-memory only, **cleared after session ends** **Best Used For**: - ✅ Current conversation context - ✅ Temporary analysis during current task - ✅ Entity relationships in current work - ✅ Cross-file refactoring state - ✅ Session-specific tracking **Storage Location**: `.mcp-data\memory\` (managed by PowerShell script) ### 6. Fetch MCP **Purpose**: Web content retrieval and processing **Command**: `uvx mcp-server-fetch` **Capabilities**: - `fetch` - Retrieve URLs and convert to markdown - Support for HTML parsing - Configurable content length **Best Used For**: - API documentation scraping - Web content analysis - Integration documentation ### 7. Windows MCP **Purpose**: Windows desktop automation **Command**: `uv --directory ./.windows-mcp run main.py` **Capabilities**: - Launch applications - PowerShell execution - Desktop state capture - Clipboard operations - Mouse and keyboard control - Window management - Screen scraping **Best Used For**: - GUI automation - Desktop testing - Windows-specific operations ### 8. Playwright MCP **Purpose**: Browser automation and testing **Command**: `npx -y @playwright/mcp` **Capabilities**: - Browser navigation and interaction - Form filling and clicking - Screenshot capture - Network request monitoring - Console message capture - File uploads - JavaScript evaluation **Best Used For**: - E2E testing - Web scraping - UI automation - Browser-based workflows ### MCP Quick Decision Tree **Question**: Should this information exist next week? - **YES** → Use Serena `write_memory` - **NO** → Use Memory graph **Question**: Am I navigating or editing code? - **YES** → Use Serena code functions **Question**: Am I building temporary context for current task? - **YES** → Use Memory graph **Question**: Do I need current library documentation? - **YES** → Use Context7 **Question**: Do I need to automate a browser? - **YES** → Use Playwright --- ## Agents & Subagents ### Overview **8 specialized agents** handle specific domains, each with isolated context and focused expertise. ### How Agents Work **Invocation**: - **Automatic**: Claude invokes based on task description matching - **Manual**: User explicitly requests with "Use the [agent-name] agent to..." **Isolation**: Each agent operates in its own context window, preventing main conversation pollution. **Configuration**: Agents can have custom: - `allowed-tools` - Restricted tool access - `model` - Specific Claude model (Sonnet, Opus, Haiku) - `description` - Triggers automatic invocation ### Available Agents #### 1. Architect Agent **File**: [.claude/agents/architect.md](.claude/agents/architect.md) **Purpose**: System design, architecture planning, technical decisions **Keywords**: architecture, design, technical decisions, scalability, system design **Responsibilities**: - System architecture design - Technology evaluation - Technical planning - Architecture review - Technical documentation **When to Use**: - Designing new systems - Evaluating technology choices - Planning major refactors - Reviewing architecture - Creating ADRs #### 2. Code Reviewer Agent **File**: [.claude/agents/code-reviewer.md](.claude/agents/code-reviewer.md) **Purpose**: Code quality review and best practices enforcement **Keywords**: code review, quality, best practices, review **Responsibilities**: - Code quality assessment - Best practices verification - Security review - Performance analysis - Documentation review **When to Use**: - Reviewing pull requests - Pre-commit quality checks - Security audits - Performance reviews #### 3. Debugger Agent **File**: [.claude/agents/debugger.md](.claude/agents/debugger.md) **Purpose**: Bug diagnosis and troubleshooting **Keywords**: debug, troubleshoot, error, bug, issue **Responsibilities**: - Error analysis - Stack trace interpretation - Root cause identification - Fix recommendations - Debugging strategies **When to Use**: - Investigating bugs - Analyzing errors - Troubleshooting issues - Performance problems #### 4. Documentation Writer Agent **File**: [.claude/agents/documentation-writer.md](.claude/agents/documentation-writer.md) **Purpose**: Technical documentation creation **Keywords**: documentation, docs, readme, comments, docstrings **Responsibilities**: - API documentation - README files - Code comments - User guides - Architecture docs **When to Use**: - Creating documentation - Updating docs - Generating API references - Writing user guides #### 5. Project Manager Agent **File**: [.claude/agents/project-manager.md](.claude/agents/project-manager.md) **Purpose**: Project coordination and workflow management **Keywords**: project, manage, coordinate, workflow, plan **Responsibilities**: - Task breakdown - Workflow coordination - Progress tracking - Resource allocation - Timeline planning **When to Use**: - Planning large features - Coordinating multiple tasks - Breaking down projects - Managing workflows #### 6. Refactoring Specialist Agent **File**: [.claude/agents/refactoring-specialist.md](.claude/agents/refactoring-specialist.md) **Purpose**: Code improvement and refactoring **Keywords**: refactor, improve, cleanup, optimize code structure **Responsibilities**: - Code structure improvement - Pattern implementation - Technical debt reduction - Code cleanup - Maintainability enhancement **When to Use**: - Refactoring legacy code - Improving code structure - Applying design patterns - Reducing technical debt #### 7. Security Analyst Agent **File**: [.claude/agents/security-analyst.md](.claude/agents/security-analyst.md) **Purpose**: Security analysis and vulnerability assessment **Keywords**: security, vulnerability, threat, audit, security analysis **Responsibilities**: - Vulnerability scanning - Security best practices - Threat modeling - Compliance checking - Security recommendations **When to Use**: - Security audits - Vulnerability assessment - Compliance reviews - Threat analysis #### 8. Test Engineer Agent **File**: [.claude/agents/test-engineer.md](.claude/agents/test-engineer.md) **Purpose**: Testing strategy and implementation **Keywords**: test, testing, unit test, integration test, test coverage **Responsibilities**: - Test strategy - Test implementation - Coverage analysis - Test automation - Quality assurance **When to Use**: - Writing tests - Test planning - Coverage improvement - Test automation ### Agent Usage Examples ```bash # Automatic invocation (based on description matching) > "I need to design a microservices architecture for our API" # → Architect agent automatically invoked # Manual invocation > "Use the security-analyst agent to review this code for vulnerabilities" # → Security analyst explicitly invoked # Parallel agents (use Task tool with multiple calls) > "I need code review and security analysis" # → Both code-reviewer and security-analyst invoked in parallel ``` --- ## Slash Commands ### Overview **9 slash commands** provide explicit workflows for common tasks. ### How Commands Work **Invocation**: User types `/command-name [arguments]` **Arguments**: - `$ARGUMENTS` - All arguments as single string - `$1`, `$2`, `$3` - Individual arguments - `$@` - All arguments as array **File References**: Use `@path/to/file` to include file content **Bash Execution**: Prefix with `!` for inline bash commands ### Available Commands #### 1. /adr [list|view|create|update] [adr-number-or-name] **File**: [.claude/commands/adr.md](.claude/commands/adr.md) **Purpose**: Manage Architectural Decision Records (ADRs) **Arguments**: - `[action]` - list, view, create, or update - `[adr-number-or-name]` - ADR identifier (optional for list/create) **Features**: - List all architectural decisions - View specific ADR with full context - Create new ADRs (invokes architect agent) - Update/supersede/deprecate existing ADRs - Track decision lifecycle and relationships - Store ADRs in Serena persistent memory **Usage**: ```bash > /adr list # List all ADRs > /adr view adr-001 # View specific ADR > /adr view adr-003-authentication-strategy # View by name > /adr create # Create new ADR > /adr update adr-002 # Update/supersede ADR ``` **Allowed Tools**: Read(*), mcp__serena__list_memories(*), mcp__serena__read_memory(*), mcp__serena__write_memory(*), Task(*) **Storage**: ADRs are stored in Serena memory (`.serena/memories/`) and persist across sessions **Integration**: Works with architect agent for ADR creation and formatting #### 2. /analyze [path] **File**: [.claude/commands/analyze.md](.claude/commands/analyze.md) **Purpose**: Comprehensive code analysis **Arguments**: `[path]` - File or directory to analyze **Features**: - Code complexity analysis - Dependency mapping - Quality metrics - Architecture review - Performance profiling **Usage**: ```bash > /analyze src/components/ > /analyze src/utils/api.ts ``` **Allowed Tools**: Read(*), Grep(*), Glob(*), Bash(*) #### 3. /explain [file-or-selection] **File**: [.claude/commands/explain.md](.claude/commands/explain.md) **Purpose**: Detailed code explanation **Arguments**: `[file-or-selection]` - What to explain **Features**: - Step-by-step breakdown - Pattern identification - Design rationale - Best practices - Learning insights **Usage**: ```bash > /explain src/auth/middleware.ts > /explain @src/utils/parser.js ``` #### 4. /implement [feature-description] **File**: [.claude/commands/implement.md](.claude/commands/implement.md) **Purpose**: Feature implementation **Arguments**: `[feature-description]` - What to implement **Features**: - Feature planning - Code generation - Pattern following - Testing included - Documentation **Usage**: ```bash > /implement user authentication with JWT > /implement payment integration with Stripe ``` #### 5. /optimize [file-or-function] **File**: [.claude/commands/optimize.md](.claude/commands/optimize.md) **Purpose**: Performance optimization **Arguments**: `[file-or-function]` - What to optimize **Features**: - Bottleneck identification - Algorithm optimization - Memory profiling - Performance testing - Recommendations **Usage**: ```bash > /optimize src/utils/dataProcessor.ts > /optimize database queries ``` #### 6. /review [file-or-path] **File**: [.claude/commands/review.md](.claude/commands/review.md) **Purpose**: Comprehensive code review **Arguments**: `[file-or-path]` - What to review **Features**: - Quality assessment - Best practices check - Security review - Performance analysis - Improvement suggestions **Usage**: ```bash > /review src/api/routes/ > /review @src/components/UserProfile.tsx ``` #### 7. /scaffold [type] [name] **File**: [.claude/commands/scaffold.md](.claude/commands/scaffold.md) **Purpose**: Generate boilerplate code **Arguments**: `[type]` - What to scaffold, `[name]` - Name **Features**: - Component generation - Service scaffolding - API endpoint creation - Test file generation - Configuration setup **Usage**: ```bash > /scaffold component UserDashboard > /scaffold service PaymentService > /scaffold api /users/:id ``` #### 8. /setup-info **File**: [.claude/commands/setup-info.md](.claude/commands/setup-info.md) **Purpose**: Display complete setup information **Features**: - Configuration overview - Agent list - Command list - MCP server status - Hook configuration **Usage**: ```bash > /setup-info ``` #### 9. /test [file-path] **File**: [.claude/commands/test.md](.claude/commands/test.md) **Purpose**: Test execution and management **Arguments**: `[file-path]` - Test file or path **Features**: - Test running - Coverage analysis - Test generation - Failure analysis - Test strategy **Usage**: ```bash > /test > /test src/utils/__tests__/api.test.ts > /test --coverage ``` ### Creating Custom Commands Use the template at [.claude/commands/.COMMANDS_TEMPLATE.md](.claude/commands/.COMMANDS_TEMPLATE.md) **Example**: ```bash # 1. Copy template cp .claude/commands/.COMMANDS_TEMPLATE.md .claude/commands/deploy.md # 2. Edit frontmatter --- description: Deploy application to production argument-hint: [environment] allowed-tools: Bash(git *:*), Bash(npm *:*), Read(*) model: claude-3-5-sonnet-20241022 --- # 3. Write instructions Deploy the application to $1 environment... # 4. Use it > /deploy production ``` --- ## Output Styles ### Overview **6 custom output styles** modify Claude's behavior and communication style. ### How Output Styles Work **Activation**: `/output-style [style-name]` **Effect**: Completely replaces system prompt, changing how Claude responds **Scope**: Active for entire conversation until changed **Tool Access**: Inherits from conversation settings (not restricted by style) ### Available Styles #### 1. Default Style **Built-in**: Yes **Purpose**: Standard software engineering assistant **Characteristics**: - Efficient and task-focused - Technical accuracy - Concise explanations - Code-first approach **When to Use**: Normal development work #### 2. Concise Style **File**: [.claude/output-styles/concise.md](.claude/output-styles/concise.md) **Purpose**: Brief, to-the-point responses **Characteristics**: - Minimal explanation - Direct answers - Code without commentary - Short summaries **When to Use**: Quick fixes, simple tasks, time pressure **Activation**: ```bash > /output-style concise ``` #### 3. Professional Style **File**: [.claude/output-styles/professional.md](.claude/output-styles/professional.md) **Purpose**: Formal, business-appropriate tone **Characteristics**: - Formal language - Structured responses - Detailed documentation - Business-friendly **When to Use**: Client interactions, stakeholder communication, reports **Activation**: ```bash > /output-style professional ``` #### 4. Verbose Style **File**: [.claude/output-styles/verbose.md](.claude/output-styles/verbose.md) **Purpose**: Detailed, comprehensive explanations **Characteristics**: - Extensive detail - Multiple examples - Thorough rationale - Educational depth **When to Use**: Learning, onboarding, complex topics **Activation**: ```bash > /output-style verbose ``` #### 5. Explanatory Style **File**: [.claude/output-styles/explanatory.md](.claude/output-styles/explanatory.md) **Purpose**: Educational insights and learning **Characteristics**: - Explains "why" decisions - Pattern identification - Learning opportunities - Best practices focus **When to Use**: Understanding codebases, learning patterns, educational context **Activation**: ```bash > /output-style explanatory ``` #### 6. Learning Style **File**: [.claude/output-styles/learning.md](.claude/output-styles/learning.md) **Purpose**: Interactive learning mode **Characteristics**: - Claude asks YOU to code - Provides guidance, not solutions - Marks sections with `TODO(human)` - Socratic method **When to Use**: Skill development, hands-on learning, teaching **Activation**: ```bash > /output-style learning ``` #### 7. Security Reviewer Style **File**: [.claude/output-styles/security-reviewer.md](.claude/output-styles/security-reviewer.md) **Purpose**: Security-focused analysis **Characteristics**: - Security-first mindset - Vulnerability scanning - Threat modeling - Compliance checking **When to Use**: Security audits, vulnerability assessment, compliance reviews **Activation**: ```bash > /output-style security-reviewer ``` ### Creating Custom Output Styles Use the template at [.claude/output-styles/.OUTPUT_STYLES_TEMPLATE.md](.claude/output-styles/.OUTPUT_STYLES_TEMPLATE.md) **Example**: ```markdown --- name: debugging-mode description: Systematic debugging approach with detailed logging --- # Debugging Mode Output Style You are Claude in debugging mode... ## Characteristics - Step-by-step analysis - Hypothesis generation and testing - Detailed logging - Root cause identification ## Response Format 1. **Problem Analysis**: [Describe the issue] 2. **Hypotheses**: [List possible causes] 3. **Testing**: [Test each hypothesis] 4. **Solution**: [Recommended fix] ``` --- ## Hooks System ### Overview **5 event hooks** enable automatic execution of scripts at specific points in Claude Code's lifecycle. ### How Hooks Work **Event Triggers**: Hooks fire automatically when specific events occur **Script Execution**: Shell scripts (.sh) or PowerShell (.ps1) execute with current environment **Security**: Hooks run with your credentials - review before using **Configuration**: Defined in `.claude/settings.json` under `hooks` key ### Available Hooks #### 1. session-start Hook **File**: [.claude/hooks/session-start.sh](.claude/hooks/session-start.sh) **Trigger**: When Claude Code session begins or resumes **Purpose**: Initialize session, setup logging, create directories **Current Implementation**: ```bash # Create logs directory if it doesn't exist mkdir -p .claude/logs # Log session start echo "[$(date)] Session started in $(pwd) by $USER" >> .claude/logs/session.log ``` **Use Cases**: - Initialize logging - Setup environment variables - Create required directories - Display welcome messages #### 2. session-end Hook **File**: [.claude/hooks/session-end.sh](.claude/hooks/session-end.sh) **Trigger**: When Claude Code session terminates **Purpose**: Cleanup, final logging, backups **Use Cases**: - Final log entries - Cleanup temporary files - Create session backups - Generate reports #### 3. pre-bash Hook **File**: [.claude/hooks/pre-bash.sh](.claude/hooks/pre-bash.sh) **Trigger**: Before Bash tool executes commands **Purpose**: Command validation, logging, permission checks **Use Cases**: - Log commands before execution - Validate command safety - Check permissions - Block dangerous commands #### 4. post-write Hook **File**: [.claude/hooks/post-write.sh](.claude/hooks/post-write.sh) **Trigger**: After Write or Edit tool modifies files **Purpose**: Post-processing, formatting, logging **Current Implementation**: ```bash # Log file writes echo "[$(date)] File written: $FILEPATH" >> .claude/logs/writes.log # Auto-format certain files (commented out by default) # if [[ $FILEPATH =~ \.(js|ts|tsx)$ ]]; then # npx prettier --write "$FILEPATH" # fi ``` **Use Cases**: - Auto-formatting (Prettier, Black, etc.) - Linting - Git add - File logging - Backup creation #### 5. user-prompt-submit Hook **File**: [.claude/hooks/user-prompt-submit.sh](.claude/hooks/user-prompt-submit.sh) **Trigger**: After user submits a prompt, before processing **Purpose**: Prompt logging, validation, preprocessing **Use Cases**: - Log all user prompts - Count prompt usage - Validate input - Track costs ### Hook Configuration **Location**: `.claude/settings.json` **Format**: ```json { "hooks": { "PreToolUse": { "*": "bash .claude/hooks/pre-bash.sh" }, "PostToolUse": { "Write": "bash .claude/hooks/post-write.sh", "Edit": "bash .claude/hooks/post-write.sh" }, "SessionStart": "bash .claude/hooks/session-start.sh", "SessionEnd": "bash .claude/hooks/session-end.sh", "UserPromptSubmit": "bash .claude/hooks/user-prompt-submit.sh" } } ``` ### Creating Custom Hooks **Example: Auto-commit Hook** ```bash # .claude/hooks/post-write.sh #!/bin/bash # Auto-commit changed files if [[ -n "$FILEPATH" ]]; then git add "$FILEPATH" git commit -m "Auto-commit: Updated $FILEPATH via Claude Code" fi ``` **Example: Cost Tracking Hook** ```bash # .claude/hooks/user-prompt-submit.sh #!/bin/bash # Track prompt count COUNT_FILE=".claude/logs/prompt_count.txt" COUNT=$(cat "$COUNT_FILE" 2>/dev/null || echo "0") echo $((COUNT + 1)) > "$COUNT_FILE" ``` --- ## Templates ### Overview **4 comprehensive templates** for extending Claude Code functionality. ### Available Templates #### 1. SKILL_TEMPLATE.md **Location**: [.claude/skills/.SKILL_TEMPLATE.md](.claude/skills/.SKILL_TEMPLATE.md) **Purpose**: Create model-invoked capabilities **Features**: - YAML frontmatter with `allowed-tools` - Progressive disclosure pattern - Multi-file organization - Testing checklist - Version history **When to Use**: Auto-activated capabilities based on context **Example Use Cases**: - PDF processing skill - Excel analysis skill - Documentation generation skill #### 2. COMMANDS_TEMPLATE.md **Location**: [.claude/commands/.COMMANDS_TEMPLATE.md](.claude/commands/.COMMANDS_TEMPLATE.md) **Purpose**: Create user-invoked slash commands **Features**: - Argument handling ($ARGUMENTS, $1, $2) - Bash execution (! prefix) - File references (@ prefix) - Model selection - Tool restrictions **When to Use**: Explicit workflows and routines **Example Use Cases**: - `/commit` - Create git commits - `/deploy` - Deployment workflow - `/generate-tests` - Test generation #### 3. AGENT_TEMPLATE.md **Location**: [.claude/agents/.AGENT_TEMPLATE.md](.claude/agents/.AGENT_TEMPLATE.md) **Purpose**: Create specialized subagents **Features**: - YAML frontmatter configuration - Tool restrictions - Model selection - Workflow definitions - Context management **When to Use**: Domain-specific expertise needed **Example Use Cases**: - Research agent - Implementation agent - Review agent #### 4. OUTPUT_STYLES_TEMPLATE.md **Location**: [.claude/output-styles/.OUTPUT_STYLES_TEMPLATE.md](.claude/output-styles/.OUTPUT_STYLES_TEMPLATE.md) **Purpose**: Create custom response behaviors **Features**: - Behavior definition - Response structure - Use case guidance - Testing checklist **When to Use**: Need different communication style **Example Use Cases**: - Debugging mode - Documentation mode - Teaching mode ### Template Usage Guide See [.claude/TEMPLATES_README.md](.claude/TEMPLATES_README.md) for comprehensive guide including: - Template comparison matrix - Quick start guides - Decision trees - Best practices - Troubleshooting --- ## Configuration ### Settings Files Hierarchy Claude Code uses a **5-level hierarchy** (highest to lowest priority): 1. **Enterprise Policies** - IT-deployed, cannot be overridden 2. **Command Line Arguments** - Session-specific (`--model`, `--max-tokens`, etc.) 3. **Local Project Settings** - `.claude/settings.local.json` (personal, not in git) 4. **Shared Project Settings** - `.claude/settings.json` (team-shared, in git) 5. **User Settings** - `~/.claude/settings.json` (global personal) ### Main Settings File **Location**: [.claude/settings.json](.claude/settings.json) **Key Sections**: #### Permissions ```json { "permissions": { "allowed": [ "Read(*)", "Write(*)", "Edit(*)", "Glob(*)", "Grep(*)", "Bash(git status:*)", "Bash(git diff:*)", "Bash(npm test:*)", "mcp__serena__*", "mcp__memory__*", "mcp__context7__*", "WebSearch", "WebFetch" ], "ask": [ "Bash(npm install:*)", "Bash(npm uninstall:*)" ], "denied": [ "Bash(rm -rf /:*)", "Bash(mkfs:*)", "Bash(dd if=:*)" ] } } ``` #### MCP Server Configuration ```json { "mcpServers": { "serena": { "enabled": true }, "memory": { "enabled": true }, "context7": { "enabled": true } } } ``` #### Hooks Configuration ```json { "hooks": { "SessionStart": "bash .claude/hooks/session-start.sh", "SessionEnd": "bash .claude/hooks/session-end.sh", "PreToolUse": { "*": "bash .claude/hooks/pre-bash.sh" }, "PostToolUse": { "Write": "bash .claude/hooks/post-write.sh", "Edit": "bash .claude/hooks/post-write.sh" }, "UserPromptSubmit": "bash .claude/hooks/user-prompt-submit.sh" } } ``` #### Status Line ```json { "statusLine": { "enabled": true, "command": "bash .claude/statusline.sh" } } ``` #### Plugin Marketplace ```json { "extraKnownMarketplaces": [ { "name": "anthropic-official", "url": "https://raw.githubusercontent.com/anthropics/skills/main/marketplace.json", "description": "Official Anthropic Skills Marketplace" } ] } ``` ### MCP Configuration **Location**: [.mcp.json](.mcp.json) (project root) **Format**: ```json { "mcpServers": { "serena": { "command": "uvx", "args": ["--from", "git+https://github.com/oraios/serena", "serena", "start-mcp-server", "--context", "ide-assistant", "--project", "Claude Code Setup"] }, "memory": { "command": "powershell", "args": ["-ExecutionPolicy", "Bypass", "-File", ".\.claude\tools\start-memory.ps1"] }, "context7": { "command": "npx", "args": ["-y", "@upstash/context7-mcp"], "env": { "CONTEXT7_API_KEY": "your-api-key-here" } } } } ``` ### Environment Variables Key environment variables (set in settings.json or shell): **Authentication**: - `ANTHROPIC_API_KEY` - API key for Claude - `ANTHROPIC_AUTH_TOKEN` - OAuth token **Model Configuration**: - `DEFAULT_MODEL` - Default Claude model - `MAX_TOKENS` - Response token limit - `THINKING_TOKEN_LIMIT` - Extended thinking budget **Features**: - `DISABLE_TELEMETRY` - Disable usage tracking - `DISABLE_AUTOUPDATER` - Disable auto-updates **Network**: - `HTTPS_PROXY` - Proxy server - `SSL_CERT_FILE` - Custom CA certificate --- ## Memory & Context ### Memory System Overview Claude Code has **hierarchical memory** across 4 locations: 1. **Enterprise Policy** - Organization-wide instructions 2. **Project Memory** - `./CLAUDE.md` or `./.claude/CLAUDE.md` (team-shared) 3. **User Memory** - `~/.claude/CLAUDE.md` (personal, all projects) 4. **Project Memory (Local)** - Deprecated ### Project Instructions (CLAUDE.md) **Location**: [CLAUDE.md](CLAUDE.md) **Purpose**: Provide project context, conventions, and guidelines to Claude **Sections**: - Project overview - Technology stack - Code style guidelines - Testing requirements - Commit message format - Development workflow - Security considerations - Performance optimization **Best Practices**: - Keep current and updated - Be specific and concrete - Use examples liberally - Structure with clear headings - Link to external docs - Review periodically **Import Files**: Use `@path/to/file` syntax (max depth: 5) ### Persistent Memory (Serena) **Storage**: `.serena/memories/` **Persistence**: Survives across sessions **Management**: ```bash # Write memory mcp__serena__write_memory("adr-001-architecture", content) # Read memory mcp__serena__read_memory("adr-001-architecture") # List all mcp__serena__list_memories() # Delete mcp__serena__delete_memory("adr-001-architecture") ``` **Current Memory**: `serena-persistence-test` **Naming Conventions**: - ADRs: `adr-001-database-choice-postgresql` - Reviews: `code-review-2024-10-payment-service` - Lessons: `lesson-async-error-handling` - Patterns: `pattern-repository-implementation` - Debt: `debt-legacy-api-authentication` - Security: `security-audit-2024-10-full` - Performance: `performance-optimization-query-caching` ### Temporary Memory (Knowledge Graph) **Storage**: In-memory, cleared on session end **Management**: ```bash # Create entities mcp__memory__create_entities([{name, entityType, observations}]) # Create relations mcp__memory__create_relations([{from, to, relationType}]) # Search mcp__memory__search_nodes("query") # Read graph mcp__memory__read_graph() ``` **Best For**: Current session context, temporary analysis ### Context Management **File References**: - Include files in prompts with `@path/to/file` - Glob patterns supported: `@src/**/*.ts` **Directory Context**: - Use `/add-dir` to add entire directories - Claude maintains awareness of directory structure **Conversation History**: - Full history maintained in session - Use `/compact` to condense long conversations - Use `/clear` to start fresh --- ## Advanced Features ### 1. Extended Thinking **What**: Gives Claude more computation time for complex problems **Activation**: - Use keywords: `think`, `think hard`, `think harder`, `ultrathink` - Each level increases computational budget - Shown as thinking process in UI **When to Use**: - Architecture decisions - Complex debugging - Security analysis - Algorithm optimization - Design pattern selection **Example**: ```bash > "Think hard about the best architecture for this microservices system" ``` **Token Limits**: Configure with `THINKING_TOKEN_LIMIT` environment variable ### 2. Plan Mode **What**: Read-only exploration before making changes **Activation**: Toggle with `Tab` key **Benefits**: - Safe exploration - No file modifications - Understanding phase - Review before action **Workflow**: 1. Enter plan mode (Tab) 2. Explore and understand 3. Get approval for plan 4. Exit plan mode (Tab) 5. Execute changes **When to Use**: - Complex multi-file changes - Unfamiliar codebases - Major refactoring - Architecture changes ### 3. Checkpointing **What**: Rewind conversation and/or code to previous states **Activation**: Press `ESC ESC` or `/rewind` **Options**: 1. **Code Only** - Revert files, keep conversation 2. **Conversation Only** - Revert conversation, keep files 3. **Both** - Complete rollback **Retention**: 30 days **When to Use**: - Experimental changes - Wrong direction - Need to try alternatives - Accidental modifications ### 4. Git Integration **Pre-approved commands**: - `git status` - `git diff` - `git log` - `git show` **Commit Creation**: See [Git Workflow](#git-workflow) in CLAUDE.md **Branch Management**: Supported with appropriate permissions ### 5. Parallel Execution **Independent Commands**: Run multiple bash commands in parallel ```bash # Claude executes these simultaneously git status && npm test && docker ps ``` **Multiple Agents**: Invoke multiple agents in parallel with Task tool **File Operations**: Multiple Reads in parallel for efficiency ### 6. Session Resume **Resume Previous**: `claude --continue` or `claude --resume` **Named Sessions**: `claude --session [name]` **List Sessions**: View available sessions to resume ### 7. Cost Tracking **View Costs**: `/cost` command **Token Usage**: Tracked per session **Breakdown**: - Input tokens - Output tokens - Thinking tokens (if used) - Tool calls **Export**: Available in settings for monitoring ### 8. Plugin Marketplace **Access**: `/plugin` command **Sources**: - Official Anthropic marketplace - Custom marketplaces (configured in settings) **Installation**: Browse and install skills/commands/agents **Management**: `/plugin list`, `/plugin install [name]` --- ## Best Practices ### General Guidelines 1. **Start Broad, Then Narrow** - Ask high-level questions first - Progressively dive into specifics - Use agents for focused deep-dives 2. **Use Appropriate Tools** - Agents for domains - Commands for workflows - Skills for auto-capabilities - Output styles for communication 3. **Leverage Memory** - Store ADRs in Serena memory - Use knowledge graph for session context - Keep CLAUDE.md updated 4. **Optimize Performance** - Use concise style for quick tasks - Leverage extended thinking for complex problems - Parallel execution when possible 5. **Maintain Security** - Review hooks before using - Restrict sensitive tool access - Use security-analyst agent for audits - Never commit secrets ### Development Workflows #### New Feature Development ```bash # 1. Architecture planning > "Use the architect agent to design user authentication feature" # 2. Implementation > /implement user authentication with JWT # 3. Testing > /test src/auth/ # 4. Review > /review src/auth/ # 5. Documentation > "Use documentation-writer agent to document authentication" # 6. Commit > "Create a git commit for this feature" ``` #### Debugging ```bash # 1. Use debugger agent > "Use the debugger agent to investigate this error: [paste error]" # 2. Extended thinking for complex issues > "Think hard about why this race condition occurs" # 3. Review fix > /review [fixed file] # 4. Test > /test ``` #### Code Review ```bash # 1. Review changes > /review src/ # 2. Security check > "Use security-analyst agent to check for vulnerabilities" # 3. Generate suggestions > "Use refactoring-specialist agent to suggest improvements" ``` ### MCP Usage Patterns #### Code Navigation ```bash # Find symbol find_symbol("UserService") # Find references find_referencing_symbols("UserService", "src/services/user.ts") # Get overview get_symbols_overview("src/services/user.ts") ``` #### Persistent Knowledge ```bash # Store ADR write_memory("adr-001-auth-jwt", "Decision: Use JWT for auth...") # Recall later read_memory("adr-001-auth-jwt") ``` #### Documentation Lookup ```bash # Resolve library resolve-library-id("react") # Get docs get-library-docs("/facebook/react") ``` ### Optimization Tips 1. **Model Selection** - Haiku for simple tasks (fast, cheap) - Sonnet for general development (balanced) - Opus for complex reasoning (powerful) 2. **Token Efficiency** - Use concise style when appropriate - Leverage Glob/Grep instead of reading all files - Use Serena symbol tools instead of full file reads 3. **Parallel Work** - Multiple file reads in one message - Parallel agent invocation - Independent bash commands together 4. **Context Management** - Regular `/compact` for long sessions - Use knowledge graph for session state - Clear when switching major tasks --- ## Troubleshooting ### Common Issues #### Agents Not Activating **Problem**: Agent doesn't activate automatically **Solutions**: 1. Check description has relevant keywords 2. Try manual invocation 3. Verify agent file is in `.claude/agents/` 4. Restart Claude to reload agents 5. Check YAML frontmatter is valid #### Commands Not Found **Problem**: `/command` not recognized **Solutions**: 1. Verify file is `.claude/commands/[name].md` 2. Filename must match command name 3. Restart Claude to reload commands 4. Check `/help` to see available commands 5. Validate frontmatter syntax #### MCP Server Failures **Problem**: MCP server not connecting **Solutions**: 1. Check `.mcp.json` configuration 2. Verify command path is correct 3. Test command manually in terminal 4. Check logs for error messages 5. Ensure dependencies installed (npx, uvx, etc.) #### Hook Not Executing **Problem**: Hook script doesn't run **Solutions**: 1. Check hook is configured in `settings.json` 2. Verify script path is correct 3. Ensure script has execute permissions 4. Check script syntax (bash/PowerShell) 5. Look for errors in logs #### Permission Denied **Problem**: Tool execution blocked **Solutions**: 1. Check permissions in `settings.json` 2. Add tool to `allowed` array 3. Use wildcards for patterns 4. Restart Claude after changes 5. Check for enterprise policies overriding ### Debugging Steps 1. **Check Logs** - Session log: `.claude/logs/session.log` - Bash log: `.claude/logs/bash.log` - Write log: `.claude/logs/writes.log` 2. **Verify Configuration** ```bash # Check settings cat .claude/settings.json | jq '.permissions' # Check MCP config cat .mcp.json | jq '.mcpServers' ``` 3. **Test Components** ```bash # Test MCP server manually npx -y @modelcontextprotocol/server-sequential-thinking # Test hook script bash .claude/hooks/session-start.sh ``` 4. **Use Diagnostic Commands** ```bash > /setup-info # Display configuration > /doctor # Diagnose installation > /mcp # Check MCP status ``` ### Getting Help 1. **Built-in Help**: `/help` command 2. **Setup Info**: `/setup-info` command 3. **Official Docs**: https://docs.claude.com/en/docs/claude-code/ 4. **GitHub Issues**: https://github.com/anthropics/claude-code/issues 5. **This Documentation**: Review relevant sections above --- ## Appendix ### Quick Reference #### Key Files - `.claude/settings.json` - Main configuration - `.mcp.json` - MCP servers - `CLAUDE.md` - Project instructions - `.claude/agents/` - Specialized agents - `.claude/commands/` - Slash commands - `.claude/output-styles/` - Response styles - `.claude/hooks/` - Event automation #### Key Commands - `/help` - Get help - `/setup-info` - Display setup - `/plugin` - Plugin marketplace - `/output-style [style]` - Change style - `/cost` - View costs - `/rewind` - Checkpointing - `/memory` - Edit memory - `/compact` - Condense conversation - `/clear` - Clear history #### Key Shortcuts - `Tab` - Toggle plan mode - `ESC ESC` - Access checkpoints - `Ctrl+C` - Interrupt Claude - `@file` - Reference file - `#` - Quick memory capture ### File Naming Conventions **Agents**: `kebab-case.md` in `.claude/agents/` **Commands**: `kebab-case.md` in `.claude/commands/` **Skills**: Directory with `SKILL.md` in `.claude/skills/[name]/` **Output Styles**: `kebab-case.md` in `.claude/output-styles/` **Hooks**: `event-name.sh` or `event-name.ps1` in `.claude/hooks/` ### Version History - **v3.0.0** (2025-10-20): Complete documentation overhaul, added missing capabilities - **v2.0.0** (2025-10-17): Added output styles, plugins, status line - **v1.0.0** (Initial): Basic setup with agents, commands, MCP ### Credits **Based on**: - Official Anthropic Claude Code documentation - Claude Agent SDK best practices - Community contributions - Real-world production experience --- **Documentation Version**: 3.0.0 **Last Updated**: 2025-10-20 **Maintained by**: Claude Code Setup Project **License**: Use and modify freely **For the most current information, always refer to official documentation at**: https://docs.claude.com/en/docs/claude-code/ --- *This setup represents ~95% of available Claude Code capabilities. The remaining 5% includes enterprise features (SSO, analytics), headless mode (CI/CD), and specialized network configurations (proxies, certificates) which are optional and environment-specific.*