# Claude Code Documentation This directory contains comprehensive documentation for Claude Code, Anthropic's official CLI tool for AI-assisted coding. ## Documentation Structure ### Core Documentation - **[Overview](overview.md)** - Introduction to Claude Code and its capabilities - **[CLI Usage](cli-usage.md)** - Complete guide to commands, flags, and slash commands - **[Quick Reference](quick-reference.md)** - Handy cheat sheet for common commands ### Configuration & Setup - **[Settings](settings.md)** - Configuration hierarchy and available settings - **[Memory Management](memory.md)** - Using CLAUDE.md files for instructions - **[Enterprise Proxies](bedrock-vertex-proxies.md)** - Bedrock and Vertex AI configuration ### Usage & Best Practices - **[Tutorials](tutorials.md)** - Common workflows and advanced techniques - **[Security](security.md)** - Permission system and security features - **[Cost Management](costs.md)** - Token usage and cost optimization ### Support & Resources - **[Troubleshooting](troubleshooting.md)** - Common issues and solutions - **[GitHub Documentation](github-readme.md)** - Information from the official repository ## Quick Start 1. **Install Claude Code**: ```bash npm install -g @anthropic-ai/claude-code ``` 2. **Start using Claude Code**: ```bash claude ``` 3. **Get help**: ```bash /help ``` ## Key Features - ๐Ÿš€ **Edit files and fix bugs** across your codebase - ๐Ÿ” **Search and understand** complex codebases - ๐Ÿงช **Write and run tests** automatically - ๐Ÿ“ **Create commits and PRs** with natural language - ๐Ÿ›ก๏ธ **Secure by design** with granular permissions - ๐Ÿ’ผ **Enterprise ready** with Bedrock/Vertex support ## Resources - **Official Docs**: [docs.anthropic.com/en/docs/claude-code](https://docs.anthropic.com/en/docs/claude-code) - **GitHub**: [github.com/anthropics/claude-code](https://github.com/anthropics/claude-code) - **Website**: [claude.ai/code](https://claude.ai/code) - **Report Issues**: [GitHub Issues](https://github.com/anthropics/claude-code/issues) ## Documentation Version This documentation is based on Claude Code as of January 2025. For the latest updates, please refer to the official documentation sources listed above. # Claude Code Overview ## What is Claude Code? Claude Code is an "agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster through natural language commands." ## Key Capabilities Claude Code can: - Edit files and fix bugs across a codebase - Answer questions about code architecture and logic - Execute and fix tests, linting, and other commands - Search git history and resolve merge conflicts - Create commits and pull requests - Browse documentation using web search ## Installation ```bash npm install -g @anthropic-ai/claude-code ``` ## Enterprise Features - Integrates with Amazon Bedrock and Google Vertex AI - Designed for secure, compliant enterprise deployments ## Security Highlights - Direct API connection to Anthropic - Operates directly in terminal - Maintains project structure awareness - Performs real coding operations ## Quick Usage Examples ```bash # Ask about authentication system claude > how does our authentication system work? # Create a commit claude commit # Fix type errors claude "fix the type errors in the auth module" ``` ## Data Usage and Privacy - Feedback may be used to improve functionality - User feedback transcripts stored for only 30 days - Will not train generative models using feedback ## Licensing ยฉ Anthropic PBC. Use subject to [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms). # Claude Code Quick Reference ## Installation ```bash npm install -g @anthropic-ai/claude-code ``` ## Basic Commands ```bash claude # Start interactive session claude "query" # Start with initial prompt claude -p "query" # One-shot mode claude -c # Continue last session claude --resume # Show session picker claude config # Configure settings claude update # Update to latest version ``` ## Common Slash Commands ``` /memory - Edit memory files /cost - Show token usage /compact - Reduce context size /clear - Clear conversation /help - Show help /model - Change model /logout - Sign out /exit - Exit Claude Code ``` ## Keyboard Shortcuts - `Ctrl+C` - Cancel current operation - `Ctrl+D` - Exit Claude Code (in empty prompt) - `Tab` - Autocomplete commands - `โ†‘/โ†“` - Navigate command history ## Tool Permissions ```bash # Allow tools without prompting claude config add allowedTools "Bash(npm test)" claude config add allowedTools "Write" # Disallow dangerous commands claude config add disallowedTools "Bash(rm -rf *)" ``` ## Memory Files - Project: `./CLAUDE.md` - Team instructions - User: `~/.claude/CLAUDE.md` - Personal preferences - Import: `@path/to/file` - Include other files ## Models - `claude-opus-4-20250514` - Most capable - `claude-sonnet-4-20250514` - Fast & capable - `claude-3-5-haiku-20241022` - Lightweight ## Cost Management - Average: $6/developer/day - Check usage: `/cost` - Reduce costs: `/compact`, `/clear` - Auto-compact: `claude config set autoCompact true` ## Common Tasks ```bash # Debug errors claude "fix this error: [paste error]" # Explain code claude "explain how authentication works" # Create commits claude commit # Generate tests claude "write tests for UserService" # Refactor code claude "refactor this to use dependency injection" ``` ## Best Practices 1. Be specific in queries 2. Use `/compact` for long sessions 3. Clear between unrelated tasks 4. Set up CLAUDE.md for project standards 5. Review commands before approval ## Troubleshooting ```bash # Authentication issues /logout && claude # High memory usage /compact # Update issues claude config set -g autoUpdaterStatus disabled # Debug mode claude --verbose ``` ## Enterprise Setup ```bash # Bedrock export CLAUDE_CODE_USE_BEDROCK=1 # Vertex AI export CLAUDE_CODE_USE_VERTEX=1 export CLOUD_ML_REGION=us-east5 export ANTHROPIC_VERTEX_PROJECT_ID=your-project ``` ## Get Help - In-app: `/help` - Issues: github.com/anthropics/claude-code/issues - Docs: docs.anthropic.com/en/docs/claude-code # Claude Code Settings Documentation ## Configuration Hierarchy Claude Code uses a hierarchical settings system with three levels of configuration: 1. **User Settings**: Defined in `~/.claude/settings.json`, applying to all projects 2. **Project Settings**: - Shared settings in `.claude/settings.json` - Local project settings in `.claude/settings.local.json` 3. **Enterprise Managed Policy Settings**: - macOS: `/Library/Application Support/ClaudeCode/policies.json` - Linux/Windows: `/etc/claude-code/policies.json` ## Available Settings ### Key Configuration Options | Setting | Description | Example | |---------|-------------|---------| | `apiKeyHelper` | Custom script to generate Anthropic API key | `/bin/generate_temp_api_key.sh` | | `cleanupPeriodDays` | Locally retain chat transcripts duration | `20` | | `env` | Environment variables for every session | `{"FOO": "bar"}` | | `includeCoAuthoredBy` | Include "co-authored-by Claude" in git commits | `false` | | `allowedTools` | Tools allowed to run without prompting | `["Bash(npm test)", "Write"]` | | `disallowedTools` | Tools disallowed without prompting | `["Bash(rm -rf *)"]` | | `autoCompact` | Enable automatic context compaction | `true` | | `theme` | Color theme | `dark`, `light`, `light-daltonized` | | `verbose` | Show full command outputs | `true` | | `preferredNotifChannel` | Notification delivery method | `iterm2`, `terminal_bell` | | `autoUpdaterStatus` | Enable/disable auto-updates | `disabled` | ## Settings Precedence Settings are applied in this order: 1. Enterprise policies 2. Command line arguments 3. Local project settings 4. Shared project settings 5. User settings ## Configuration Commands - List settings: `claude config list` - View a setting: `claude config get ` - Change a setting: `claude config set ` - Add to a list setting: `claude config add ` - Remove from a list setting: `claude config remove ` ## Global Configuration Options | Key | Description | Example Values | |-----|-------------|----------------| | `autoUpdaterStatus` | Enable/disable auto-updates | `disabled` | | `preferredNotifChannel` | Notification delivery method | `iterm2`, `terminal_bell` | | `theme` | Color theme | `dark`, `light`, `light-daltonized` | | `verbose` | Show full command outputs | `true` | ## Permissions Management Claude Code allows fine-grained tool permissions through the `allowedTools` and `disallowedTools` settings. ### Pattern Syntax ```json { "allowedTools": [ "Bash(npm test)", // Allow exact command "Bash(npm test:*)", // Allow command with any arguments "Write", // Allow all Write operations "Edit(*.test.js)" // Allow editing test files ] } ``` ## Environment Variables Custom environment variables can be set for all Claude Code sessions: ```json { "env": { "NODE_ENV": "development", "API_URL": "https://api.example.com" } } ``` ## Example Configuration Files ### User Settings (`~/.claude/settings.json`) ```json { "theme": "dark", "verbose": true, "autoCompact": true, "cleanupPeriodDays": 30 } ``` ### Project Settings (`.claude/settings.json`) ```json { "allowedTools": [ "Bash(npm test:*)", "Bash(npm run build)", "Write" ], "env": { "PROJECT_ENV": "development" } } ``` ### Enterprise Policy (`/etc/claude-code/policies.json`) ```json { "disallowedTools": [ "Bash(rm -rf *)", "Bash(sudo *)" ], "autoUpdaterStatus": "disabled" } ``` # Claude Code Tutorials ## Key Workflows ### Resume Previous Conversations Use `--continue` to automatically resume the most recent conversation: ```bash claude --continue ``` Use `--resume` to show a conversation picker: ```bash claude --resume ``` ### Understand New Codebases 1. Navigate to project root 2. Start Claude Code 3. Ask for overview: - `> give me an overview of this codebase` - `> explain the main architecture patterns` ### Fix Bugs Efficiently 1. Share error details 2. Ask for recommendations 3. Apply suggested fixes ### Work with Images Methods to add images: - Drag and drop into Claude Code window - Copy and paste (cmd+v on Mac) - Provide image path ### Extended Thinking Use "think" prompts for complex tasks: - `> think about potential security vulnerabilities` - Intensify with phrases like "think harder" or "think longer" ### Model Context Protocol (MCP) Add MCP servers: ```bash claude mcp add my-server -e API_KEY=123 -- /path/to/server ``` ### Custom Slash Commands Create project-specific commands in `.claude/commands/`: ```bash > /project:optimize ``` ### Git Worktrees Run parallel Claude Code sessions: ```bash git worktree add ../project-feature-a -b feature-a ``` ## Tips - Start with broad questions - Use domain-specific language - Break complex tasks into smaller steps - Leverage Claude's extended thinking for architectural decisions ## Common Workflows ### 1. Debugging Production Issues ```bash # Start Claude Code claude # Provide error context > I'm seeing this error in production: [paste error] > The error happens when users try to upload files larger than 10MB # Let Claude investigate > can you help me trace through the upload flow and find the issue? ``` ### 2. Code Refactoring ```bash # Ask for analysis first > analyze the user authentication module and suggest improvements # Then implement changes > refactor the authentication to use the suggested pattern ``` ### 3. Writing Tests ```bash # Understand existing test patterns > show me how tests are structured in this project # Generate new tests > write comprehensive tests for the PaymentService class ``` ### 4. API Integration ```bash # Research API > fetch the documentation for the Stripe API and help me integrate payment processing # Implement integration > create a service to handle Stripe webhooks ``` ## Advanced Techniques ### Memory-Driven Development Create a CLAUDE.md file with project-specific instructions: ```markdown # Project Guidelines ## Architecture - Use dependency injection - Follow repository pattern - Implement unit of work ## Testing - Minimum 80% coverage - Use AAA pattern - Mock external dependencies ## Git Workflow - Conventional commits - Squash before merging - Update changelog ``` ### Batch Operations Process multiple files efficiently: ```bash > find all React components that use inline styles and refactor them to use CSS modules ``` ### Interactive Debugging ```bash # Set up debugging session > I need to debug the order processing flow # Step through code > show me what happens when an order is placed # Test fixes > let's add logging to trace the issue ``` ### Documentation Generation ```bash # Generate API docs > document all public methods in the API controllers # Create user guides > write a guide for setting up the development environment ``` ## Performance Optimization ### 1. Profile First ```bash > analyze this function for performance bottlenecks ``` ### 2. Implement Improvements ```bash > optimize the data processing pipeline based on your analysis ``` ### 3. Verify Results ```bash > write benchmarks to compare the before and after performance ``` ## Best Practices 1. **Be Specific**: Provide context and examples 2. **Iterate**: Start broad, then narrow focus 3. **Verify**: Always test Claude's suggestions 4. **Learn**: Use explanations to understand changes 5. **Collaborate**: Treat Claude as a pair programmer ## Example: Full Feature Implementation ```bash # 1. Planning > I need to add a notification system. Users should get email and in-app notifications for important events # 2. Architecture > design the notification system architecture # 3. Implementation > implement the notification service with email and in-app channels # 4. Testing > write tests for the notification system # 5. Documentation > document the notification API endpoints ``` # Claude Code CLI Usage Documentation ## Getting Started Claude Code offers two primary interaction modes: 1. **Interactive Mode**: Start a REPL session ```bash claude ``` 2. **One-Shot Mode**: Run quick commands ```bash claude -p "query" ``` ## CLI Commands | Command | Description | Example | |---------|-------------|---------| | `claude` | Start interactive REPL | `claude` | | `claude "query"` | Start REPL with initial prompt | `claude "explain this project"` | | `claude -p "query"` | Run one-off query and exit | `claude -p "explain this function"` | | `claude -c` | Continue most recent conversation | `claude -c` | | `claude -r "" "query"` | Resume session by ID | `claude -r "abc123" "Finish this PR"` | | `claude config` | Configure settings | `claude config set --global theme dark` | | `claude update` | Update to latest version | `claude update` | | `claude mcp` | Configure Model Context Protocol servers | (See MCP tutorials) | ## CLI Flags | Flag | Description | Example | |------|-------------|---------| | `--allowedTools` | List tools allowed without prompting | `"Bash(git log:*)" "Write"` | | `--disallowedTools` | List tools disallowed without prompting | `"Bash(git diff:*)"` | | `--print`, `-p` | Print response without interactive mode | `claude -p "query"` | | `--output-format` | Specify output format (`text`, `json`, `stream-json`) | `claude -p "query" --output-format json` | | `--verbose` | Enable detailed logging | `claude --verbose` | | `--max-turns` | Limit agentic turns in non-interactive mode | `claude -p --max-turns 3 "query"` | | `--model` | Set session model | `claude --model claude-sonnet-4-20250514` | ## Slash Commands | Command | Description | Example | |---------|-------------|---------| | `/memory` | Open memory files in editor | `/memory` | | `/cost` | Show current session token usage | `/cost` | | `/compact` | Reduce context size | `/compact` | | `/clear` | Clear conversation history | `/clear` | | `/logout` | Sign out of Claude Code | `/logout` | | `/help` | Show available commands | `/help` | | `/config` | Manage configuration settings | `/config` | | `/model` | Change current model | `/model claude-opus-4-20250514` | ## SDK Integration Claude Code also provides a Python SDK for programmatic usage: ```python from claude_code import claude_code result = await claude_code("fix the authentication bug") print(result) ``` ## Output Formats - **text**: Default human-readable format - **json**: Structured JSON output - **stream-json**: Streaming JSON for real-time processing ## Advanced Usage ### Pattern-Based Tool Permissions Allow specific commands: ```bash claude --allowedTools "Bash(npm test:*)" "Bash(git commit:*)" ``` ### Batch Operations Run multiple queries: ```bash claude -p "fix all type errors" --max-turns 10 ``` ### Session Management List recent sessions: ```bash claude --resume ``` Resume specific session: ```bash claude -r "session-id-123" ``` # Claude Code Troubleshooting Guide ## Common Installation Issues ### Linux Permission Issues When installing Claude Code with npm, you may encounter permission errors if your npm global prefix is not user writable. #### Recommended Solution: Create a User-Writable npm Prefix Steps to configure a user-writable npm directory: ```bash # Save existing global packages npm list -g --depth=0 > ~/npm-global-packages.txt # Create directory for global packages mkdir -p ~/.npm-global # Configure npm to use new directory npm config set prefix ~/.npm-global # Update PATH in shell configuration echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc source ~/.bashrc # Reinstall Claude Code npm install -g @anthropic-ai/claude-code ``` Benefits of this approach: - Avoids modifying system directory permissions - Creates a dedicated location for global npm packages - Follows security best practices ## Auto-Updater Issues If Claude Code can't update automatically, you can: - Follow the recommended npm prefix solution - Disable auto-updates: `claude config set -g autoUpdaterStatus disabled` ## Permissions and Authentication ### Repeated Permission Prompts To allow specific tools to run without approval: ```bash # Allow npm test to run without approval claude config add allowedTools "Bash(npm test)" # Allow npm test and sub-commands claude config add allowedTools "Bash(npm test:*)" ``` ### Authentication Issues If experiencing authentication problems: 1. Run `/logout` 2. Close Claude Code 3. Restart with `claude` For persistent issues: ```bash rm -rf ~/.config/claude-code/auth.json claude ``` ## Performance and Stability ### High CPU or Memory Usage Performance optimization tips: - Use `/compact` to reduce context size - Close and restart Claude Code between major tasks - Add large build directories to `.gitignore` ### Command Hangs or Freezes If unresponsive: - Press Ctrl+C to cancel operation - Close terminal and restart if needed ### JetBrains Terminal ESC Key Issue To fix ESC key not working: 1. Go to Settings โ†’ Tools โ†’ Terminal 2. Uncheck "Override IDE shortcuts" 3. Restart terminal ## Network and Connectivity ### Proxy Configuration For corporate proxies: ```bash export HTTP_PROXY=http://proxy.company.com:8080 export HTTPS_PROXY=http://proxy.company.com:8080 ``` ### SSL Certificate Issues If encountering SSL errors: ```bash export NODE_TLS_REJECT_UNAUTHORIZED=0 # Use with caution ``` ## Model and API Issues ### Model Not Available If a model is unavailable: 1. Check available models: `/model` 2. Switch to alternative: `/model claude-sonnet-4-20250514` 3. Verify API access permissions ### Rate Limiting If hitting rate limits: - Wait before retrying - Break large tasks into smaller chunks - Use `/cost` to monitor usage ## File and Project Issues ### Large File Handling For files over 2MB: - Use specific line ranges: `Read file.txt:100-200` - Break into smaller operations - Consider using grep for searches ### Git Repository Issues If Claude Code can't access git: ```bash # Initialize git if needed git init # Check git status git status ``` ## Common Error Messages ### "Permission denied" - Check file permissions: `ls -la` - Ensure write access to directory - Run with appropriate user permissions ### "Command not found" - Verify tool installation - Check PATH environment variable - Use full path to executables ### "Context limit exceeded" - Use `/compact` to reduce context - Clear conversation with `/clear` - Break task into smaller parts ## Debug Mode Enable verbose logging for troubleshooting: ```bash claude --verbose ``` Or set permanently: ```bash claude config set verbose true ``` ## Reporting Issues When reporting issues: 1. Include Claude Code version: `claude --version` 2. Describe steps to reproduce 3. Include relevant error messages 4. Report at: https://github.com/anthropics/claude-code/issues ## Recovery Steps If Claude Code becomes unresponsive: 1. **Soft Reset** ```bash # Cancel current operation Ctrl+C # Clear context /clear ``` 2. **Hard Reset** ```bash # Exit Claude Code /exit # Clear cache rm -rf ~/.cache/claude-code # Restart claude ``` 3. **Full Reset** ```bash # Remove all Claude Code data rm -rf ~/.config/claude-code rm -rf ~/.cache/claude-code rm -rf ~/.claude # Reinstall npm install -g @anthropic-ai/claude-code ``` # Claude Code Security Documentation ## Permission System Claude Code uses a tiered permission system to balance power and safety: ### Permission Levels | Tool Type | Example | Approval Required | "Yes, don't ask again" Behavior | |-----------|---------|-------------------|----------------------------------| | Read-only | File reads, LS, Grep | No | N/A | | Bash Commands | Shell execution | Yes | Permanently per project directory and command | | File Modification | Edit/write files | Yes | Until session end | ## Tools Available to Claude Claude Code has access to various tools with different permission requirements: | Tool | Description | Permission Required | |------|-------------|---------------------| | Agent | Runs a sub-agent for complex tasks | No | | Bash | Executes shell commands | Yes | | Edit | Makes targeted file edits | Yes | | Glob | Finds files via pattern matching | No | | Grep | Searches file contents | No | | LS | Lists files and directories | No | | WebFetch | Fetches content from URLs | Yes | | Write | Creates or overwrites files | Yes | ## Protecting Against Prompt Injection Claude Code includes several safeguards: - **Permission system** requiring explicit approval for sensitive operations - **Context-aware analysis** to detect potentially harmful instructions - **Input sanitization** to prevent command injection - **Command blocklist** blocking risky web-fetching commands ### Best Practices 1. Review suggested commands before approval 2. Avoid piping untrusted content directly to Claude 3. Verify proposed changes to critical files 4. Report suspicious behavior ## Network Access Configuration Required URLs: - api.anthropic.com - statsig.anthropic.com - sentry.io ## Development Container Security The reference implementation provides: - Precise network access control - Default-deny network policy - Startup firewall rule verification - Isolated development environment **Warning**: While protections are robust, no system is completely immune to all attacks. ## Security Configuration Examples ### Allow Specific Commands ```bash # Allow npm test to run without approval claude config add allowedTools "Bash(npm test)" # Allow all npm commands claude config add allowedTools "Bash(npm *)" ``` ### Disallow Dangerous Commands ```bash # Prevent destructive commands claude config add disallowedTools "Bash(rm -rf *)" claude config add disallowedTools "Bash(sudo *)" ``` ### Enterprise Security Policies Organizations can enforce security policies via `/etc/claude-code/policies.json`: ```json { "disallowedTools": [ "Bash(curl *)", "Bash(wget *)", "WebFetch" ], "allowedTools": [ "Bash(git *)", "Bash(npm test:*)" ] } ``` ## Audit and Compliance - All tool usage is logged locally - Session transcripts retained based on `cleanupPeriodDays` setting - No automatic data transmission to Anthropic beyond API calls - Enterprise deployments can configure custom logging ## Reporting Security Issues Report security vulnerabilities to: security@anthropic.com # Claude Code: Bedrock, Vertex, and Proxy Configuration ## Model Configuration Claude Code supports multiple providers with default models: | Provider | Default Model | |----------|--------------| | Anthropic Console | `claude-sonnet-4-20250514` | | Claude Max | `claude-opus-4-20250514` or `claude-sonnet-4-20250514` | | Amazon Bedrock | `claude-3-7-sonnet-20250219` | | Google Vertex AI | `claude-sonnet-4-20250514` | ### Model Selection Precedence 1. `--model` CLI flag 2. `ANTHROPIC_MODEL` environment variable 3. User Settings in `~/.claude/settings.json` ## Amazon Bedrock Configuration ```bash # Enable Bedrock CLAUDE_CODE_USE_BEDROCK=1 # Disable prompt caching if needed DISABLE_PROMPT_CACHING=1 ``` ### Bedrock Requirements - AWS SDK credentials - Access to Claude Sonnet 3.7 and Haiku 3.5 models ### Optional Proxy Configuration ```bash # Set Bedrock proxy URL ANTHROPIC_BEDROCK_BASE_URL='https://your-proxy-url' # Skip Bedrock authentication if proxy handles credentials CLAUDE_CODE_SKIP_BEDROCK_AUTH=1 ``` ## Google Vertex AI Configuration ```bash # Enable Vertex AI CLAUDE_CODE_USE_VERTEX=1 CLOUD_ML_REGION=us-east5 ANTHROPIC_VERTEX_PROJECT_ID=your-project-id # Disable prompt caching if needed DISABLE_PROMPT_CACHING=1 ``` ### Vertex AI Requirements - GCP credentials - Access to Claude Sonnet 3.7 and Haiku 3.5 models - Quota in `us-east5` region ### Optional Proxy Configuration ```bash # Set Vertex AI proxy URL ANTHROPIC_VERTEX_BASE_URL='https://your-proxy-url' # Skip Vertex authentication if proxy handles credentials CLAUDE_CODE_SKIP_VERTEX_AUTH=1 ``` ## Model Selection ### Command Line ```bash # Use specific model for session claude --model claude-opus-4-20250514 ``` ### Slash Command ```bash # Change model mid-session /model claude-sonnet-4-20250514 ``` ### Configuration File ```json { "model": "claude-opus-4-20250514" } ``` ## Available Models ### Anthropic Direct - `claude-opus-4-20250514` - Most capable model - `claude-sonnet-4-20250514` - Fast and capable - `claude-3-5-haiku-20241022` - Lightweight tasks ### Bedrock/Vertex - `claude-3-7-sonnet-20250219` - Latest Sonnet - `claude-3-5-haiku-20241022` - Lightweight tasks ## Proxy Server Implementation ### Basic Proxy Requirements 1. Forward requests to appropriate provider 2. Handle authentication if `SKIP_AUTH` is set 3. Return responses in Anthropic API format ### Example Proxy Configuration ```javascript // Proxy server example app.post('/v1/messages', async (req, res) => { // Add provider-specific headers const headers = { 'x-api-key': process.env.ANTHROPIC_API_KEY, 'anthropic-version': '2023-06-01' }; // Forward to provider const response = await fetch(providerUrl, { method: 'POST', headers, body: JSON.stringify(req.body) }); // Return response res.json(await response.json()); }); ``` ## Troubleshooting ### Bedrock Issues 1. Verify AWS credentials: `aws sts get-caller-identity` 2. Check model access in AWS Console 3. Ensure correct region configuration ### Vertex AI Issues 1. Verify GCP credentials: `gcloud auth list` 2. Check project permissions 3. Confirm quota in us-east5 region ### Proxy Issues 1. Test proxy connectivity 2. Verify URL format 3. Check authentication handling 4. Review proxy logs ## Enterprise Deployment ### Centralized Configuration ```bash # /etc/claude-code/policies.json { "env": { "CLAUDE_CODE_USE_BEDROCK": "1", "ANTHROPIC_BEDROCK_BASE_URL": "https://internal-proxy.company.com" } } ``` ### Security Considerations - Use internal proxies for compliance - Implement request logging - Add rate limiting - Monitor usage per team/user # Manage Costs Effectively with Claude Code ## Cost Overview "Claude Code consumes tokens for each interaction. The average cost is $6 per developer per day, with daily costs remaining below $12 for 90% of users." ## Tracking Costs - Use `/cost` to see current session usage - For Anthropic Console users: - Check [historical usage](https://support.anthropic.com/en/articles/9534590-cost-and-usage-reporting-in-console) - Set [workspace spend limits](https://support.anthropic.com/en/articles/9796807-creating-and-managing-workspaces) - Max plan users: Usage included in subscription ## Reducing Token Usage ### Strategies - Use auto-compact when context exceeds 95% capacity - Toggle auto-compact via `/config` - Manually compact with `/compact` - Add custom compaction instructions - Write specific, focused queries - Break down complex tasks - Clear history between tasks with `/clear` ## Factors Affecting Costs Costs vary based on: - Codebase size - Query complexity - Number of files searched/modified - Conversation history length - Compaction frequency - Background processes ## Background Token Usage Small token consumption from: - Haiku generation (~1 cent/day) - Conversation summarization - Command processing **Recommendation**: Start with a small pilot group to establish usage patterns. ## Cost Management Best Practices ### 1. Optimize Queries ```bash # Instead of: > explain everything about this codebase # Use: > explain the authentication module ``` ### 2. Use Context Management ```bash # Clear context between unrelated tasks /clear # Compact when working on long sessions /compact ``` ### 3. Configure Auto-Compact ```bash # Enable auto-compact claude config set autoCompact true # Set custom compaction threshold claude config set compactThreshold 0.90 ``` ### 4. Monitor Usage Patterns - Review `/cost` regularly during development - Track usage across team members - Identify high-cost operations ## Token Usage by Operation | Operation Type | Typical Token Usage | |----------------|-------------------| | Simple file read | 500-2,000 tokens | | Code explanation | 1,000-5,000 tokens | | Bug fix | 5,000-20,000 tokens | | Feature implementation | 20,000-100,000 tokens | | Codebase analysis | 50,000-200,000 tokens | ## Enterprise Cost Controls Organizations can implement cost controls: 1. **Set spending limits** in Anthropic Console 2. **Monitor team usage** via usage reports 3. **Implement approval workflows** for high-cost operations 4. **Train developers** on efficient Claude Code usage ## Cost-Effective Workflows ### For Bug Fixes 1. Provide specific error messages 2. Point to relevant files 3. Use targeted searches 4. Clear context after resolution ### For Feature Development 1. Break into smaller tasks 2. Implement incrementally 3. Compact between major steps 4. Review and clear completed work ### For Code Reviews 1. Focus on specific modules 2. Use grep for targeted searches 3. Clear between different reviews 4. Leverage memory for standards # Claude Code GitHub Documentation ## Official Repository The official Claude Code repository is available at: [github.com/anthropics/claude-code](https://github.com/anthropics/claude-code) ## About Claude Code Claude Code is an agentic coding tool that lives in your terminal, understands your codebase, and helps you code faster by executing routine tasks, explaining complex code, and handling git workflows - all through natural language commands. ## Key Features from GitHub - **Edit files and fix bugs** across your entire codebase - **Transform hours of debugging** into seconds with a single command - **Integrates with GitHub, GitLab**, and command line tools - **Handles the entire workflow** - reading issues, writing code, running tests, and submitting PRs - **Search and read code** intelligently - **Write and run tests** automatically - **Commit and push code** to GitHub - **Use command line tools** seamlessly ## Installation Best Practices The GitHub repository recommends: - Install as a non-privileged user (not as root) for security and stability - Use the standard npm installation method: `npm install -g @anthropic-ai/claude-code` ## System Requirements - **Operating Systems**: macOS, Linux, and Windows (via WSL) - **Authentication**: Requires one-time OAuth with Claude Max or Anthropic Console account - **Network**: Direct API connection to Anthropic's servers ## Security Highlights from GitHub - Runs locally in your terminal - Direct connection to model APIs - No backend server required - No remote code indexing - Your code stays on your machine ## Development and Contribution Check the official GitHub repository for: - Latest releases and updates - Issue reporting - Feature requests - Community contributions - Development guidelines ## Related Resources - **Official Documentation**: [docs.anthropic.com/en/docs/claude-code](https://docs.anthropic.com/en/docs/claude-code) - **Comprehensive Guide**: [claude.ai/code](https://claude.ai/code) - **API Documentation**: For SDK integration details - **Best Practices**: [anthropic.com/engineering/claude-code-best-practices](https://www.anthropic.com/engineering/claude-code-best-practices) # Manage Claude's Memory Claude Code offers three memory locations for storing instructions and preferences: ## Memory Types 1. **Project Memory** (`./CLAUDE.md`) - Purpose: Team-shared instructions for the project - Examples: Project architecture, coding standards, workflows 2. **User Memory** (`~/.claude/CLAUDE.md`) - Purpose: Personal preferences across all projects - Examples: Code styling preferences, personal tooling shortcuts 3. **Project Memory (Local)** (Deprecated) - Previously used for personal project-specific preferences ## CLAUDE.md Features ### Imports - Use `@path/to/import` syntax to include additional files - Supports relative and absolute paths - Can import files from home directory - Maximum recursive import depth of 5 hops ### Example Import ```markdown See @README for project overview and @package.json for available npm commands. # Additional Instructions - git workflow @docs/git-instructions.md ``` ## Memory Lookup Process - Reads memories recursively from current working directory up to root - Discovers nested CLAUDE.md files in subtrees - Automatically loads memory files at launch ## Quick Memory Management ### Adding Memories - Start input with `#` to quickly add a memory - Prompted to select which memory file to store in ### Editing Memories - Use `/memory` slash command to open memory files in system editor ## Best Practices - Be specific in instructions - Use structured markdown - Organize memories with headings and bullet points - Periodically review and update memories ## Example CLAUDE.md Structure ```markdown # Project Overview This is a React TypeScript application with... ## Architecture - Frontend: React with TypeScript - State Management: Redux Toolkit - Testing: Jest and React Testing Library ## Coding Standards - Use functional components with hooks - Follow ESLint configuration - Write tests for all new features ## Common Commands - `npm run dev` - Start development server - `npm test` - Run test suite - `npm run build` - Build for production ## Workflow Instructions 1. Always run tests before committing 2. Use conventional commit messages 3. Update documentation for API changes ``` ## Memory Precedence When multiple memory files exist, they are loaded in this order: 1. Project-specific CLAUDE.md files (from current directory up to root) 2. User memory (~/.claude/CLAUDE.md) Instructions in more specific memories take precedence over general ones.