Add interactive `/context` commands for context tracking and optimization

Resolved 💬 3 comments Opened Aug 18, 2025 by nehalecky Closed Aug 18, 2025

Problem Statement

Claude Code users frequently hit context limits without visibility into what's consuming tokens, leading to:

  • Workflow disruption when sessions fail due to context explosion
  • Inefficient development without understanding token distribution
  • No actionable insights for context optimization
  • Limited awareness of MCP server overhead impact

Solution Overview

Add interactive /context commands that expose existing internal metrics Claude Code already tracks, providing immediate visibility and optimization guidance.

Proposed Commands

Core Command Suite

/context                    # Show detailed breakdown with visual indicators
/context history            # Show usage changes over current session  
/context tools              # MCP server and tool breakdown with recommendations
/context optimize           # Specific suggestions to reduce usage

Example Output

/context - Main Command:

Context Usage: 🟡 145k/200k (72%)

├─ Base Context: 15k (7.5%)
│  ├─ System instructions: 8k
│  ├─ CLAUDE.md: 6k  
│  └─ Environment: 1k
│
├─ MCP Tools: 47k (23.5%) ⚠️  
│  ├─ google-workspace: 12k (6 tools unused)
│  ├─ github: 11k (23 tools, 8 active)
│  ├─ zen: 8k (15 tools, 3 active) 
│  ├─ hf-mcp-server: 7k (10 tools unused)
│  ├─ atlassian-mcp: 6k (12 tools, 2 active)
│  └─ sequential-thinking: 3k (1 tool, active)
│
└─ Session History: 83k (41.5%)
   ├─ User messages: 45k
   ├─ Assistant responses: 28k
   └─ Tool results: 10k

Cache: 138k reads (context reloading detected)
Optimization potential: ~20k tokens (see '/context optimize')

/context tools - MCP Analysis:

MCP Server Analysis (47k total):

🔴 google-workspace (12k) - 0% utilization
   ├─ 6 tools loaded, none used this session
   └─ Recommendation: Disable unused MCP servers

🟡 github (11k) - 35% utilization  
   ├─ 23 tools loaded, 8 actively used
   └─ Consider: Scope to specific GitHub operations

🟢 zen (8k) - 20% utilization
   ├─ 15 tools loaded, 3 actively used  
   └─ Status: Reasonable usage pattern

🔴 hf-mcp-server (7k) - 0% utilization
   └─ Recommendation: Remove if not needed for current work

/context optimize - Actionable Suggestions:

🎯 Optimization Opportunities (-19k tokens):

High Impact:
├─ Remove unused MCP servers (-19k)
│  └─ google-workspace, hf-mcp-server currently unused
│
├─ Optimize CLAUDE.md imports (-3k)  
│  └─ Use references instead of full imports
│
└─ Session management (-2k)
   └─ Use /save and /clear to manage history

Medium Impact:  
├─ Scope MCP tools (-4k)
│  └─ Load only needed GitHub/Atlassian tools
│
└─ Cache optimization  
   └─ Context reloading detected (138k cache reads)

Quick wins: /mcp remove google-workspace hf-mcp-server

Technical Implementation

Building on Existing Infrastructure

This proposal leverages existing internal metrics that Claude Code already tracks:

  1. Context Token Counting (evidenced by 200k limits being enforced)
  2. MCP Tool Schema Loading (tool definitions consume ~24k tokens)
  3. Session History Tracking (for conversation continuity)
  4. Cache Metrics (lastTotalCacheCreationInputTokens, lastTotalCacheReadInputTokens)

Integration with Issue #5511

Extends the statusline JSON metrics proposal by:

  • Exposing same metrics via interactive commands
  • Adding historical tracking within session scope
  • Providing actionable optimization guidance
  • Enabling real-time monitoring of context usage

Implementation Approach

// Extend existing statusline JSON structure
interface ContextMetrics {
  tokenUsage: {
    total: number;
    limit: number;
    percentage: number;
    breakdown: {
      base: number;
      mcpTools: number;  
      sessionHistory: number;
    };
  };
  mcpServers: Array<{
    name: string;
    tokenCount: number;
    toolsLoaded: number;
    toolsUsed: number;
    utilization: number;
  }>;
  cacheMetrics: {
    reads: number;
    writes: number;
    reloadingDetected: boolean;
  };
}

User Experience Goals

Immediate Visibility

  • At-a-glance understanding of context distribution
  • Visual indicators for concerning usage patterns
  • Proactive warnings before hitting limits

Actionable Intelligence

  • Specific recommendations not generic advice
  • One-command optimizations where possible
  • Impact estimates for suggested changes

Session Workflow Integration

  • Context-aware development with usage monitoring
  • Preventive optimization before workflow disruption
  • Historical awareness of usage patterns within session

Related Issues

This addresses concerns raised in:

  • #5511 - MCP Server metrics in statusline JSON (builds upon)
  • #4464 - Context limit visibility requests
  • #4143 - Session management and context overflow
  • #4792 - MCP server resource usage visibility

Success Metrics

  1. Reduced context-related session failures by 80%
  2. Faster issue diagnosis when context problems occur
  3. Proactive optimization based on usage patterns
  4. Improved development workflow with context awareness

Future Enhancements

  • Integration with IDE extensions for persistent monitoring
  • Context usage analytics across multiple sessions
  • Smart MCP server auto-loading based on project context
  • Context budget allocation for long-running sessions

---

This feature request focuses on exposing existing capabilities rather than building new tracking infrastructure, providing immediate value while laying groundwork for the statusline JSON metrics in #5511.

View original on GitHub ↗

This issue has 3 comments on GitHub. Read the full discussion on GitHub ↗