### Clone and Run Prometheus Setup Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Clone the necessary configuration repository and start the Docker Compose services to set up Prometheus and related tools. ```bash # Clone the configuration repo git clone https://github.com/katchu11/claude-code-guide docker-compose up -d ``` -------------------------------- ### Start Docker Compose Stack Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Clones the repository and starts the full observability stack including OTel Collector, Prometheus, and Grafana. Use `docker-compose ps` to verify container health. ```bash git clone https://github.com/katchu11/claude-code-guide cd claude-code-guide docker-compose up -d docker-compose ps ``` -------------------------------- ### Console Metrics Output Example Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Example of raw metric payloads printed to stdout when `OTEL_METRICS_EXPORTER` is set to `console`. Shows resource attributes and cost usage data points. ```text === Resource Attributes === { 'service.name': 'claude-code', 'service.version': '1.0.17' } =========================== { descriptor: { name: 'claude_code.cost.usage', type: 'COUNTER', description: 'Cost of the Claude Code session', unit: 'USD', valueType: 1 }, dataPoints: [ { attributes: { 'user.id': '7b673f5715f2da49af2cdd341e0cad17fb3274f32d4ceed00d57d53da4e76fb2', 'session.id': '092d99fc-ac17-4ee7-b310-57d387777c91', 'model': 'claude-4-sonnet-20250514' }, value: 0.000297 } ] } ``` -------------------------------- ### Verify Telemetry Output Structure Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Example of the console output when telemetry is enabled and a command is run. This shows resource attributes and metric data points. ```json === Resource Attributes === { 'service.name': 'claude-code', 'service.version': '1.0.17' } =========================== { descriptor: { name: 'claude_code.cost.usage', type: 'COUNTER', description: 'Cost of the Claude Code session', unit: 'USD', valueType: 1 }, dataPointType: 3, dataPoints: [ { attributes: { 'user.id': '7b673f5715f2da49af2cdd341e0cad17fb3274f32d4ceed00d57d53da4e76fb2', 'session.id': '092d99fc-ac17-4ee7-b310-57d387777c91', 'model': 'claude-4-sonnet-20250514' }, value: 0.000297 } ] } ``` -------------------------------- ### Query Prometheus API for Total Cost Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Example of how to query the Prometheus HTTP API directly for the total cost and parse the JSON output using `jq`. ```bash # Query via Prometheus HTTP API curl -s "http://localhost:9090/api/v1/query?query=sum(claude_code_cost_usage_USD_total)" \ | jq '.data.result[0].value[1]' ``` -------------------------------- ### Generate Automated Productivity Report Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Generates a productivity report by combining Linear MCP data with Claude Code metrics. This example shows how to prompt Claude to analyze team velocity and integrate provided metrics. ```bash claude -p "Using the Linear MCP, analyze our team's velocity for the last sprint and combine with these Claude Code metrics: { \"claude_code_sessions\": 42, \"total_cost\": 103.45, \"avg_session_duration\": \"28.5 minutes\", \"tool_acceptance_rates\": {\"Edit\": 0.81, \"MultiEdit\": 0.92} } Generate a comprehensive productivity report with visualizations." ``` -------------------------------- ### Run Claude Code Diagnostics Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Execute the built-in diagnostic tool for Claude Code. This command gathers information about your setup and can help identify potential problems. ```bash claude /doctor ``` -------------------------------- ### Troubleshoot Telemetry Diagnostics Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt A step-by-step guide to diagnose why metrics are not appearing in Prometheus or Grafana. This includes verifying environment variables, testing console output, checking network reachability, and inspecting Docker containers. ```bash # Step 1: Verify environment variables are set correctly echo "Telemetry: $CLAUDE_CODE_ENABLE_TELEMETRY" # Must be 1 echo "Exporter: $OTEL_METRICS_EXPORTER" # Must be 'otlp' echo "Endpoint: $OTEL_EXPORTER_OTLP_ENDPOINT" # Must be set # Step 2: Test console output (bypasses network issues) export OTEL_METRICS_EXPORTER=console export OTEL_METRIC_EXPORT_INTERVAL=1000 claude -p "test" # Should print metric payloads to stdout # Step 3: Verify OTel Collector is reachable curl -v http://localhost:4317 curl http://localhost:8888/metrics # Collector self-metrics # Step 4: Check Docker containers docker-compose ps docker-compose logs otel-collector --tail=50 # Step 5: Verify Prometheus targets are healthy curl "http://localhost:9090/api/v1/targets" | jq '.data.activeTargets[].health' # All should return "up" # Step 6: Run Claude Code diagnostics claude /doctor # Step 7: Clean reinstall if Claude Code hangs after enabling telemetry npm uninstall -g @anthropic-ai/claude-code rm -rf ~/.config/claude-code/ npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Reinstall Claude Code with npm Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Perform a clean reinstallation of the Claude Code npm package to resolve potential issues caused by corrupted installations. This involves uninstalling the current version and then installing it again. ```bash npm uninstall -g @anthropic-ai/claude-code npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### PromQL: Total Cumulative Cost Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Use this query to get the total cumulative cost across all sessions. It aggregates the `claude_code_cost_usage_USD_total` metric. ```promql # Total cumulative cost across all sessions sum(claude_code_cost_usage_USD_total) ``` -------------------------------- ### Configure User-Writable npm Prefix on Linux Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Fixes npm permission errors on Linux by setting a user-specific directory for global package installations. This involves creating a new npm prefix, updating the PATH environment variable, and then reinstalling packages. ```bash # Save existing global packages npm list -g --depth=0 > ~/npm-global-packages.txt # Create user directory for npm mkdir -p ~/.npm-global npm config set prefix ~/.npm-global # Add to PATH (use ~/.zshrc for zsh) echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc source ~/.bashrc # Install Claude Code npm install -g @anthropic-ai/claude-code ``` -------------------------------- ### Fix npm Permission Errors on Linux Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Resolves `EACCES` errors when installing Claude Code globally on Linux by configuring a user-writable npm prefix and updating the PATH. This also helps prevent auto-update failures. ```bash # Save current global packages list npm list -g --depth=0 > ~/npm-global-packages.txt # Create user-writable npm prefix directory mkdir -p ~/.npm-global npm config set prefix ~/.npm-global # Add to PATH permanently echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.bashrc source ~/.bashrc # Now install without sudo npm install -g @anthropic-ai/claude-code # Verify installation claude --version # If auto-update still fails, disable it export DISABLE_AUTOUPDATER=1 ``` -------------------------------- ### Detect Problematic Claude Code Usage Patterns Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Identify developers getting stuck by detecting problematic usage patterns such as long sessions with no commits, high tool rejection rates, or frequent API errors. This helps in pinpointing areas for improvement. ```python // Detect problematic usage patterns problemPatterns = { // Long sessions with no commits longUnproductiveSessions = filter( duration > 30min AND claude_code.commit.count == 0, group by (developerId, sessionId) ), // High rejection rates toolRejectionHotspots = filter( claude_code.code_edit_tool.decision{decision="reject"} > 10, group by (developerId, tool) ), // API errors apiErrorPatterns = group by (error, model) { count(claude_code.api_error) } } ``` -------------------------------- ### PromQL: Cost Breakdown by Developer Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Aggregates the total cost by individual developer's email address for per-developer cost analysis. ```promql # Cost broken down by individual developer sum(claude_code_cost_usage_USD_total) by (user_email) ``` -------------------------------- ### PromQL: Token Usage by Type Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt This query breaks down token consumption by type, including input, output, cache creation, and cache read. Useful for understanding token distribution. ```promql # Token usage by type sum(claude_code_token_usage_tokens_total) by (type) ``` -------------------------------- ### Configure Claude Code for Prometheus Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Set environment variables to enable telemetry, configure the OTLP exporter for gRPC, and specify the Prometheus endpoint. ```bash # Enable telemetry export CLAUDE_CODE_ENABLE_TELEMETRY=1 # Configure OTLP exporter export OTEL_METRICS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 # Optional: Set authentication if required # export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token" # Run Claude Code claude ``` -------------------------------- ### Generate Report with Live Data Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Use this prompt with the Claude CLI to analyze team velocity and combine it with live Claude Code metrics for a comprehensive productivity report. ```bash claude -p "Using the Linear MCP, analyze our team's velocity and combine with these live Claude Code metrics: { "total_cost": $TOTAL_COST, "input_tokens": $INPUT_TOKENS, "output_tokens": $OUTPUT_TOKENS, "cost_per_token": $(echo \"$TOTAL_COST / ($INPUT_TOKENS + $OUTPUT_TOKENS)\" | bc -l) } Generate a comprehensive productivity report with visualizations." ``` -------------------------------- ### Enable and Verify Claude Code Telemetry Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Set environment variables to enable telemetry and export metrics to the console for verification. Run a sample command to generate output. ```bash export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=console export OTEL_METRIC_EXPORT_INTERVAL=1000 claude -p "hello world" ``` -------------------------------- ### Verify Required Telemetry Environment Variables Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Check the values of essential environment variables for telemetry. Ensure CLAUDE_CODE_ENABLE_TELEMETRY is set to 1, OTEL_METRICS_EXPORTER is set to 'otlp', and OTEL_EXPORTER_OTLP_ENDPOINT points to your collector. ```bash echo $CLAUDE_CODE_ENABLE_TELEMETRY echo $OTEL_METRICS_EXPORTER echo $OTEL_EXPORTER_OTLP_ENDPOINT ``` -------------------------------- ### PromQL: Token Consumption Rate Over Time Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Calculates the rate of token consumption per second over a 5-minute window. Requires multiple data points to be meaningful and indicates real-time usage. ```promql # Token consumption rate over time (requires multiple data points) rate(claude_code_token_usage_tokens_total[5m]) ``` -------------------------------- ### Correlate Developer Tenure with Claude Code Usage Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Analyze how developer experience levels correlate with the acceptance rates of Claude Code suggestions. Assumes developer tenure data is available. Tracks progression over a 90-day onboarding timeline. ```python // Assuming you have developer tenure data available in your analytics platform // Calculate tool acceptance rates per developer acceptanceRates = sum(claude_code.code_edit_tool.decision{decision="accept"}) by (developerId) / count(claude_code.code_edit_tool.decision) by (developerId) // Correlate with developer experience data // Experience categories: junior, mid, senior correlate(developerExperienceCategory, acceptanceRates) // Track progression over onboarding timeline timeSeriesAnalysis(acceptanceRates, timeWindow=90d, groupBy=experienceLevel) ``` -------------------------------- ### PromQL: Session Count by User Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Tracks the total number of Claude Code sessions initiated by each user, useful for adoption and engagement tracking. ```promql # Session count (adoption tracking) sum(claude_code.session.count) by (user_email) ``` -------------------------------- ### Check Docker Compose Services Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Verify that all necessary Docker containers defined in your docker-compose configuration are running. This is crucial for ensuring that services like Prometheus and the OTel collector are active. ```bash docker-compose ps ``` -------------------------------- ### PromQL: Cost Breakdown by Model Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt This query breaks down the total cost by the model used, allowing for comparison between different Claude models like Haiku, Sonnet, and Opus. ```promql # Cost broken down by model (compare Haiku vs Sonnet vs Opus spend) sum(claude_code_cost_usage_USD_total) by (model) ``` -------------------------------- ### Deploy Managed Settings via Ansible Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Use this Ansible command to copy the managed telemetry settings JSON file to all developer machines. Ensure the destination path is correct for the target operating system. ```bash # Deploy managed-settings.json via Ansible to all developer machines # Path: ~/.config/claude-code/managed-settings.json (macOS/Linux) # %APPDATA%\claude-code\managed-settings.json (Windows) ansible all -m copy \ -a "src=managed-settings.json dest=~/.config/claude-code/managed-settings.json mode=0644" ``` -------------------------------- ### Compare Claude Code Subscription Costs Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Project costs for different Claude Code subscription tiers (Pro, Max 5x, Max 20x) based on active users and compare with the current pay-as-you-go model. Helps in evaluating the financial viability of subscription plans. ```python // Calculate total cost under current pay-as-you-go model currentMonthlyCost = sum(claude_code.cost.usage) over last_30d // Project costs for different subscription tiers // Claude Pro: $20/mo per user with 1x capacity // Claude Max 5x: $100/mo per user with 5x capacity // Claude Max 20x: $200/mo per user with 20x capacity activeUsers = count(distinct user.account_uuid) where claude_code.session.count > 0 proTierCost = activeUsers * 20 maxTier5xCost = activeUsers * 100 maxTier20xCost = activeUsers * 200 // Analyze typical usage patterns to determine capacity needs avgTokensPerUserPerMonth = sum(claude_code.token.usage) by (user.account_uuid) / activeUsers // Determine if users would hit subscription limits based on usage patterns usersExceedingProTier = count(users where avgTokensPerUserPerMonth > proTierLimit) // Calculate projected cost savings or additional expense subscriptionSavings = currentMonthlyCost - recommendedTierCost ``` -------------------------------- ### Verify Docker Compose Stack Output Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Expected output from `docker-compose ps` showing the status and ports of the running containers: otel-collector, prometheus, and grafana. ```text NAME STATUS PORTS otel-collector running 0.0.0.0:4317->4317/tcp, 0.0.0.0:4318->4318/tcp, 0.0.0.0:8889->8889/tcp prometheus running 0.0.0.0:9090->9090/tcp grafana running 0.0.0.0:3000->3000/tcp ``` -------------------------------- ### Add Linear MCP Server Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Adds the Linear project management API as an MCP server to Claude Code for integrating telemetry with sprint data. Requires the 'claude' CLI tool. ```bash # Add Linear MCP server to Claude Code claude mcp add linear -s user -- npx -y mcp-remote https://mcp.linear.app/sse # Verify integration is active claude mcp list ``` -------------------------------- ### PromQL: Commits Made with Assistance Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Tracks the number of commits made with Claude assistance. This metric has medium reliability and can be used for productivity analysis. ```promql # Commits made with Claude assistance (medium reliability) sum(claude_code.commit.count) by (user_email) ``` -------------------------------- ### Configure Linear MCP in .claude.json Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Configures the Linear MCP server directly within the .claude.json file. This is an alternative to using the CLI command and requires restarting Claude Code. ```bash # Alternative: configure directly in .claude.json cat > .claude.json << 'EOF' { "mcpServers": { "linear": { "type": "stdio", "command": "npx", "args": ["-y", "mcp-remote", "https://mcp.linear.app/sse"] } } } EOF # Restart Claude Code to activate ``` -------------------------------- ### PromQL Query: Cost by Model Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Analyze the total cost of Claude Code usage, categorized by the specific model employed. ```promql # Cost by model type sum(claude_code_cost_usage_USD_total) by (model) {model="claude-opus-4-20250514"} 0.429 {model="claude-3-5-haiku-20241022"} 0.0006 ``` -------------------------------- ### Generate Manual Productivity Report Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Generates a one-shot productivity report by passing live Prometheus metrics and Linear sprint data to Claude via the CLI. Useful for ad-hoc analysis. ```bash # One-shot manual report generation claude -p "Using the Linear MCP, analyze our team's velocity for the last sprint and combine with these Claude Code metrics: { \"claude_code_sessions\": 42, \"total_cost\": 103.45, \"pull_requests\": 23, \"avg_session_duration\": \"28.5 minutes\", \"top_users\": [\"alice@company.com\", \"bob@company.com\"], \"cost_per_pr\": 4.50, \"token_usage\": { \"input_tokens\": 3245670, \"output_tokens\": 2156780, \"input_cost\": 32.46, \"output_cost\": 70.99 }, \"tool_acceptance_rates\": { \"Edit\": 0.81, \"MultiEdit\": 0.92, \"Write\": 0.65 } } Generate a comprehensive productivity report with: 1. Executive summary with velocity improvements 2. Usage patterns and engagement metrics 3. Linear issue completion metrics 4. Cost analysis with visualizations 5. Actionable insights based on tool usage patterns Use Mermaid diagrams for visualizations." ``` -------------------------------- ### PromQL: Token Usage by User Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Aggregates total token usage by developer email, enabling per-developer analysis of token consumption. ```promql # Token usage by user (for per-developer analysis) sum(claude_code_token_usage_tokens_total) by (user_email) ``` -------------------------------- ### OTel Collector Configuration (`otel-collector-config.yaml`) Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Defines the OpenTelemetry Collector's metrics pipeline, including OTLP receivers, batching and memory limiting processors, and a Prometheus exporter. The Prometheus exporter is configured to expose metrics on port 8889. ```yaml receivers: otlp: protocols: grpc: endpoint: 0.0.0.0:4317 http: endpoint: 0.0.0.0:4318 processors: batch: timeout: 1s send_batch_size: 1024 memory_limiter: check_interval: 1s limit_mib: 512 exporters: prometheus: endpoint: "0.0.0.0:8889" send_timestamps: true metric_expiration: 180m enable_open_metrics: true debug: verbosity: detailed sampling_initial: 5 sampling_thereafter: 200 service: pipelines: metrics: receivers: [otlp] processors: [memory_limiter, batch] exporters: [prometheus, debug] ``` -------------------------------- ### Analyze User Prompts with Claude Haiku Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Extracts user prompt data from OpenTelemetry logs and processes it through Claude Haiku to identify patterns in prompts, quality, developer skills, and areas for improvement. Requires setting OTEL_LOG_USER_PROMPTS=1. ```javascript // Extract user prompt data from OpenTelemetry logs // Note: requires setting OTEL_LOG_USER_PROMPTS=1 to capture actual prompt content userPromptEvents = query { from: claude_code.user_prompt select: [user.account_uuid, prompt, prompt_length, event.timestamp] where: event.timestamp >= now() - 30d } // Process batches of prompts through Claude Haiku function analyzePromptPatterns(prompts) { // Structure the analysis request const request = { model: "claude-3-5-haiku-20241022", messages: [{ role: "user", content: `Analyze these developer prompts and identify: 1. Common task categories (debugging, feature development, refactoring, etc.) 2. Prompt quality patterns (specificity, context provided, clarity) 3. Developer skill indicators in the prompts 4. Recommended prompt improvements for better results 5. Areas where developers need additional training Prompts to analyze: ${JSON.stringify(prompts)} Format your response as structured JSON with the categories above.` }] }; // Process through Haiku (low-cost analysis) return callClaudeAPI(request); } // Categorize developers by usage patterns developerSegments = analyzePromptPatterns(userPromptEvents) .groupBy(user.account_uuid) .calculateMetrics([ "avgPromptQuality", "dominantTaskCategory", "skillLevel", "improvementAreas" ]); // Generate customized training recommendations trainingRecommendations = developerSegments .filter(segment => segment.improvementAreas.length > 0) .map(segment => ({ userId: segment.user.account_uuid, recommendations: segment.improvementAreas.map(area => trainingModules[area]) })); ``` -------------------------------- ### Automate Weekly Reports with Script Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/report-generation-prompt.md A bash script to automate the generation of weekly reports. It fetches metrics from Prometheus and then uses Claude Code to generate the report. ```bash #!/bin/bash # weekly-report.sh # Gather metrics from Prometheus METRICS=$(curl -s "http://localhost:9090/api/v1/query?query=..." | jq '...') # Generate report claude -p "Using the Linear MCP, analyze our team's velocity... $METRICS ..." ``` -------------------------------- ### Enable Console Metrics Export Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Enables OpenTelemetry metrics export to the console for quick verification. Sets the exporter to 'console' and specifies a 1000ms export interval. Useful for debugging before setting up Prometheus. ```bash export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=console export OTEL_METRIC_EXPORT_INTERVAL=1000 claude -p "hello world" ``` -------------------------------- ### PromQL Query: Token Usage by User Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Calculate total token usage, grouped by the user's email address. ```promql # Token usage by user email sum(claude_code_token_usage_tokens_total) by (user_email) {user_email="user@company.com"} 83215 ``` -------------------------------- ### Fetch Claude Metrics from Prometheus Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md A bash script to automate fetching live Claude Code metrics (total cost, input/output tokens) from Prometheus. Uses curl to query the Prometheus API and jq to parse the JSON response. ```bash #!/bin/bash # fetch-claude-metrics.sh - Automate report generation with live data # Fetch metrics from Prometheus TOTAL_COST=$(curl -s "http://localhost:9090/api/v1/query?query=sum(claude_code_cost_usage_USD_total)" | jq -r '.data.result[0].value[1] // "0"') INPUT_TOKENS=$(curl -s "http://localhost:9090/api/v1/query?query=sum(claude_code_token_usage_tokens_total{type=\"input\"})" | jq -r '.data.result[0].value[1] // "0"') OUTPUT_TOKENS=$(curl -s "http://localhost:9090/api/v1/query?query=sum(claude_code_token_usage_tokens_total{type=\"output\"})" | jq -r '.data.result[0].value[1] // "0"') ``` -------------------------------- ### Configure Linear MCP Server in .claude.json Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Configures the Linear MCP server directly within the .claude.json configuration file. Specifies the type, command, and arguments for the mcp-remote process. ```json { "mcpServers": { "linear": { "type": "stdio", "command": "npx", "args": ["-y", "mcp-remote", "https://mcp.linear.app/sse"] } } } ``` -------------------------------- ### Calculate Subscription vs API Cost Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Compares the cost of API pay-per-token against different subscription tiers based on active users and usage patterns. Useful for determining the most cost-effective billing model. ```javascript // Fetch actual usage data const currentMonthlyCost = sum("claude_code.cost.usage", { window: "last_30d" }); const activeUsers = countDistinct("user.account_uuid", { filter: "session.count > 0" }); // Project subscription tier costs const proTierCost = activeUsers * 20; // $20/user/month const max5xTierCost = activeUsers * 100; // $100/user/month const max20xTierCost = activeUsers * 200; // $200/user/month // Example output for 10 developers at $103.45 current API cost: // API (current): $103.45/month // Pro tier: $200.00/month → API cheaper // Max 5x tier: $1,000.00/month → API cheaper // Recommendation: Stay on API // Analyze if users would hit subscription capacity limits const avgTokensPerUserPerMonth = sum("claude_code.token.usage") / activeUsers; const usersExceedingProLimit = count("users", { filter: `avgTokens > ${proTierLimit}` }); ``` -------------------------------- ### PromQL Query: Total Cost Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Calculate the sum of all costs recorded for Claude Code sessions. ```promql # Total cost across all sessions sum(claude_code_cost_usage_USD_total) {} 0.43 ``` -------------------------------- ### Generate Weekly Productivity Report Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Use this command to generate a weekly productivity report combining Linear MCP data with live Claude Code metrics. The output is saved to a markdown file. ```bash claude -p "Using the Linear MCP, analyze our team's velocity and combine with these live Claude Code metrics: { "total_cost": $TOTAL_COST, "input_tokens": $INPUT_TOKENS, "output_tokens": $OUTPUT_TOKENS, "session_count": $SESSION_COUNT } Generate a comprehensive weekly productivity report with cost breakdown and velocity trends." > "reports/weekly-$(date +%Y-%m-%d).md" echo "Report saved to reports/weekly-$(date +%Y-%m-%d).md" ``` -------------------------------- ### PromQL Query: Rate of Token Consumption Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Calculate the rate at which tokens are consumed over a 5-minute interval, broken down by type. ```promql # Rate of token consumption over time (requires multiple data points) rate(claude_code_token_usage_tokens_total[5m]) {type="input"} 2.5 {type="output"} 6.2 {type="cacheRead"} 261.5 ``` -------------------------------- ### Mermaid Graph for Session Duration Analysis Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Visualizes session duration categories and their relation to developer activities. Useful for understanding engagement patterns. ```mermaid graph TD A[Session Start] --> B[Duration Tracking] B --> C{< 5 minutes} B --> D{5-30 minutes} B --> E{> 30 minutes} C --> F[Quick Questions/Fixes] D --> G[Feature Development] E --> H[Deep Work Sessions] ``` -------------------------------- ### Enable Telemetry in Claude Code Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Set this environment variable to 1 to enable telemetry collection for Claude Code. Ensure it's exported before running Claude Code. ```bash export CLAUDE_CODE_ENABLE_TELEMETRY=1 ``` -------------------------------- ### Configure OTLP Production Export Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Configures Claude Code to export metrics to a local OTel Collector via gRPC. Sets `CLAUDE_CODE_ENABLE_TELEMETRY` to 1 and `OTEL_METRICS_EXPORTER` to `otlp`. Includes common endpoint variants and optional header configuration. ```bash # Enable telemetry and point to local OTel Collector export CLAUDE_CODE_ENABLE_TELEMETRY=1 export OTEL_METRICS_EXPORTER=otlp export OTEL_EXPORTER_OTLP_PROTOCOL=grpc export OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317 # Common endpoint variants: # Kubernetes: http://otel-collector.monitoring.svc.cluster.local:4317 # DataDog: https://otlp.datadoghq.com # Honeycomb: https://api.honeycomb.io:443 # AWS ALB: https://your-alb-endpoint.amazonaws.com # Optional authentication (for secured collectors) # export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-token" # Run Claude Code — metrics flow automatically claude ``` -------------------------------- ### Calculate ROI per Developer with Claude Code Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Calculate the cost-to-value ratio for each developer by analyzing usage costs, pull requests, commits, and lines of code added. This helps in understanding individual developer efficiency. ```python // Calculate cost-to-value ratio developerId = user.account_uuid totalCost = sum(claude_code.cost.usage) by (developerId) prCount = sum(claude_code.pull_request.count) by (developerId) commitCount = sum(claude_code.commit.count) by (developerId) linesAdded = sum(claude_code.lines_of_code.count{type="added"}) by (developerId) avgCostPerCommit = totalCost / commitCount avgCostPerLine = totalCost / linesAdded ``` -------------------------------- ### Add Linear MCP Integration Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/report-generation-prompt.md Configure the Linear MCP integration for Claude Code. Ensure this is set up before generating reports. ```bash claude mcp add linear -s user -- npx -y mcp-remote https://mcp.linear.app/sse ``` -------------------------------- ### Bash Script: Fetch Key Claude Code Metrics Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt A bash script that fetches total cost, input tokens, and output tokens from Prometheus using `curl` and `jq`, then prints them to the console. ```bash # Bash script to fetch and calculate key metrics TOTAL_COST=$(curl -s "http://localhost:9090/api/v1/query?query=sum(claude_code_cost_usage_USD_total)" \ | jq -r '.data.result[0].value[1] // "0"') INPUT_TOKENS=$(curl -s "http://localhost:9090/api/v1/query?query=sum(claude_code_token_usage_tokens_total{type=\"input\"})" \ | jq -r '.data.result[0].value[1] // "0"') OUTPUT_TOKENS=$(curl -s "http://localhost:9090/api/v1/query?query=sum(claude_code_token_usage_tokens_total{type=\"output\"})" \ | jq -r '.data.result[0].value[1] // "0"') echo "Total cost: \$$TOTAL_COST" echo "Input tokens: $INPUT_TOKENS" echo "Output tokens: $OUTPUT_TOKENS" ``` -------------------------------- ### JavaScript Pseudo-code: Cost-per-Developer ROI Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Pseudo-code demonstrating how to calculate average cost per commit, per pull request, and per line of code by combining Prometheus query results. ```javascript // Pseudo-code using Prometheus query results const developerId = "user.account_uuid"; const totalCost = sum("claude_code.cost.usage", { by: developerId }); const prCount = sum("claude_code.pull_request.count", { by: developerId }); const commitCount = sum("claude_code.commit.count", { by: developerId }); const linesAdded = sum("claude_code.lines_of_code.count", { by: developerId, filter: { type: "added" } }); const avgCostPerCommit = totalCost / commitCount; // Example: $103.45 / 42 sessions = $2.46 per session const avgCostPerPR = totalCost / prCount; // Example: $103.45 / 23 PRs = $4.50 per PR const avgCostPerLine = totalCost / linesAdded; ``` -------------------------------- ### Detect Developer Friction Patterns Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Identifies common developer friction points such as long unproductive sessions, high tool rejection rates, and API errors. Helps pinpoint areas for workflow or prompt improvement. ```javascript const problemPatterns = { // Sessions > 30 min with zero commits (stuck or exploring) longUnproductiveSessions: filter({ condition: "duration > 30min AND claude_code.commit.count == 0", groupBy: ["developerId", "sessionId"] }), // Tools being rejected frequently (prompting or workflow issues) toolRejectionHotspots: filter({ condition: "claude_code.code_edit_tool.decision{decision='reject'} > 10", groupBy: ["developerId", "tool"] }), // API error patterns by model and error type apiErrorPatterns: groupBy(["error", "model"], { count: "claude_code.api_error" }) }; // Example findings: // {developerId: "alice", tool: "Write", rejectCount: 18} // → Write tool prompts need improvement for Alice // {error: "context_length_exceeded", model: "claude-haiku", count: 7} // → Switch to Sonnet for complex tasks ``` -------------------------------- ### Add Linear MCP Server via CLI Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Adds the Linear MCP server to Claude Code using the command-line interface. This command sets up the server to use npx to run the mcp-remote command. ```bash # Add Linear MCP server to Claude Code claude mcp add linear -s user -- npx -y mcp-remote https://mcp.linear.app/sse # Verify it's working claude mcp list # Restart Claude Code to activate the integration ``` -------------------------------- ### PromQL: Pull Requests Created Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Tracks the number of pull requests created during Claude Code sessions. This metric has high reliability for measuring output. ```promql # Pull requests created during Claude Code sessions (high reliability) sum(claude_code.pull_request.count) by (user_email) ``` -------------------------------- ### Managed Telemetry Configuration Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt This JSON configuration enables telemetry collection and specifies the endpoint and headers for the OpenTelemetry collector. Deploy this configuration centrally via MDM or configuration management tools. ```json { "telemetry": { "enabled": true, "endpoint": "https://your-otel-collector.company.com:4317", "headers": { "Authorization": "Bearer ${OTEL_TOKEN}" } }, "exporters": { "metrics": "otlp", "logs": "otlp" } } ``` -------------------------------- ### Test Telemetry with Console Exporter Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Temporarily configure OpenTelemetry to export metrics to the console for debugging. This helps verify if metrics are being generated before sending them to an OTLP endpoint. Set the export interval to 1000ms. ```bash export OTEL_METRICS_EXPORTER=console export OTEL_METRIC_EXPORT_INTERVAL=1000 claude -p "test" ``` -------------------------------- ### Automated Weekly Report Script Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt A bash script designed to be run via cron for automated weekly report generation. It fetches live metrics from Prometheus and sends them to Claude for analysis and summarization. ```bash #!/bin/bash # weekly-report.sh — run via cron: 0 9 * * 1 /path/to/weekly-report.sh PROMETHEUS="http://localhost:9090/api/v1/query" # Fetch live metrics TOTAL_COST=$(curl -s "$PROMETHEUS?query=sum(claude_code_cost_usage_USD_total)" \ | jq -r '.data.result[0].value[1] // "0"') INPUT_TOKENS=$(curl -s "$PROMETHEUS?query=sum(claude_code_token_usage_tokens_total{type=\"input\"})" \ | jq -r '.data.result[0].value[1] // "0"') OUTPUT_TOKENS=$(curl -s "$PROMETHEUS?query=sum(claude_code_token_usage_tokens_total{type=\"output\"})" \ | jq -r '.data.result[0].value[1] // "0"') SESSION_COUNT=$(curl -s "$PROMETHEUS?query=sum(claude_code_session_count_total)" \ | jq -r '.data.result[0].value[1] // "0"') ``` -------------------------------- ### Check Prometheus Targets Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Access the Prometheus web UI to check the status of its configured targets. This helps verify if Prometheus is successfully scraping metrics from your OpenTelemetry collector and other sources. ```bash http://localhost:9090/targets ``` -------------------------------- ### Add Build Directories to .gitignore Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Exclude common build and dependency directories from version control to potentially reduce Claude Code's memory usage when analyzing large codebases. This is a standard practice for managing project dependencies. ```gitignore node_modules/ dist/ build/ .next/ ``` -------------------------------- ### Check OTLP Endpoint Accessibility Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Use curl to verify that your OpenTelemetry Protocol (OTLP) endpoint is accessible. This command checks if the collector is running and responding on the default port 4317. ```bash curl -v http://localhost:4317 ``` -------------------------------- ### Generate Productivity Report with Claude Code Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/report-generation-prompt.md Command to generate a comprehensive productivity report using Claude Code and Linear MCP. Includes sample telemetry data and specifies desired report sections. ```bash claude -p "Using the Linear MCP, analyze our team's velocity for the last sprint and combine with these Claude Code metrics: { \"claude_code_sessions\": 42, \"total_cost\": 103.45, \"pull_requests\": 23, \"avg_session_duration\": \"28.5 minutes\", \"top_users\": [\"alice@company.com\", \"bob@company.com\"], \"cost_per_pr\": 4.50, \"token_usage\": { \"input_tokens\": 3245670, \"output_tokens\": 2156780, \"input_cost\": 32.46, \"output_cost\": 70.99 }, \"tool_usage\": { \"Edit\": 356, \"MultiEdit\": 128, \"Write\": 73, \"Read\": 892, \"Bash\": 204 }, \"tool_acceptance_rates\": { \"Edit\": 0.81, \"MultiEdit\": 0.92, \"Write\": 0.65 } } Generate a comprehensive productivity report that includes: 1. Executive summary with velocity improvements 2. Usage patterns and engagement metrics 3. Linear issue completion metrics (use actual Linear data) 4. Cost analysis with visualizations 5. Actionable insights based on tool usage patterns 6. Productivity comparison (before/after Claude Code) 7. Recommendations for optimization Use Mermaid diagrams for visualizations. Reference specific Linear ticket IDs where relevant." ``` -------------------------------- ### Report a Bug in Claude Code Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Use this command to initiate the bug reporting process for Claude Code. It typically opens an interface or provides instructions for submitting bug reports. ```bash claude /bug ``` -------------------------------- ### PromQL: Code Edit Decision Rate Source: https://context7.com/anthropics/claude-code-monitoring-guide/llms.txt Monitors the acceptance and rejection rate of code edits suggested by Claude. This helps in understanding user trust and the quality of suggestions. ```promql # Code edits: track accept vs reject rate sum(claude_code.code_edit_tool.decision) by (decision) ``` -------------------------------- ### Verify Prometheus Reachability to OTel Collector Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Test if Prometheus can successfully reach the OpenTelemetry (OTel) collector by making a request to the collector's metrics endpoint. This helps diagnose network connectivity issues between Prometheus and the collector. ```bash curl http://localhost:8888/metrics ``` -------------------------------- ### Clear Claude Code Cache and Configuration Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Remove the local configuration and cache files for Claude Code to reset its state. This can resolve issues related to corrupted settings or lingering temporary data. The command targets the user's configuration directory. ```bash rm -rf ~/.config/claude-code/ ``` -------------------------------- ### Measure Claude Code Impact on MTTR for Bug Fixes Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/claude_code_roi_full.md Calculate the Mean Time To Resolution (MTTR) for bug fixes with and without Claude Code assistance by joining bug resolution data with Claude Code usage logs. This quantifies the impact on development efficiency. ```python // Join bug resolution data with Claude Code usage bugData = loadFromJira("bugs_resolved.csv") claudeUsageForBugs = filter( claude_code.user_prompt contains "bug" OR claude_code.user_prompt contains "fix" OR claude_code.session metadata.issue_id in bugData.issueIds, group by (developerId, issue_id) ) // Calculate MTTR with and without Claude assistance mttrWithClaude = avg(bugData.resolutionTime where bugData.issueId in claudeUsageForBugs.issue_id) mttrWithoutClaude = avg(bugData.resolutionTime where bugData.issueId not in claudeUsageForBugs.issue_id) improvementRatio = mttrWithoutClaude / mttrWithClaude ``` -------------------------------- ### Log Out and Log In Claude Code Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Force a clean logout and re-login sequence for Claude Code to resolve authentication issues. This involves logging out, closing the terminal, opening a new one, and then logging back in. ```bash claude /logout ``` -------------------------------- ### Clear Claude Code Authentication Data Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Remove the authentication token file for Claude Code to force a re-authentication. This can resolve persistent login failures or issues with expired tokens. ```bash rm -rf ~/.config/claude-code/auth.json claude ``` -------------------------------- ### Disable Claude Code Auto-Updater Source: https://github.com/anthropics/claude-code-monitoring-guide/blob/main/troubleshooting.md Prevent Claude Code from attempting to auto-update by setting this environment variable. This can be a workaround for auto-update failures or when manual control over updates is preferred. ```bash export DISABLE_AUTOUPDATER=1 ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.