Skip to content

feat: control which Claude Code subagents are loaded into context #40

@gsong

Description

@gsong

Summary

Similar to how ccmcp provides selective loading of MCP server configurations, we should enable control over which Claude Code subagents are loaded into context. This would help manage context size and focus on relevant subagents for specific projects.

Current State

Claude Code Subagent Discovery

Claude Code currently discovers and loads subagents from multiple locations with a fixed precedence order:

  1. Project-level agents: .claude/agents/ (highest priority)
  2. User-level agents: ~/.claude/agents/ (global, available across all projects)
  3. Plugin-provided agents: From plugin agents/ directories
  4. CLI-defined agents: Via --agents flag for session-specific definitions

Key characteristics:

  • All discovered subagents are automatically loaded into context
  • Project-level subagents override user-level subagents when names conflict
  • No built-in mechanism to exclude specific subagents from being loaded
  • Subagents are defined as Markdown files with YAML frontmatter

This Project's Approach to MCP Configuration

ccmcp demonstrates an effective pattern for selective configuration loading:

// Configuration discovery precedence
const configDir = values["config-dir"] || process.env.CCMCP_CONFIG_DIR;
const resolvedConfigDir = configDir || join(homedir(), ".claude", "mcp-configs");

Architecture:

  • Single configuration directory (not hierarchical global + project)
  • CLI flag (--config-dir) and environment variable (CCMCP_CONFIG_DIR) for flexibility
  • Interactive selection UI to choose which configs to activate
  • Validation schema (src/schemas/mcp-config.ts) ensuring configuration integrity

Problem / Use Case

Context Management Challenges:

  1. Context pollution: All subagents in .claude/agents/ and ~/.claude/agents/ are loaded regardless of project needs
  2. Relevance filtering: No way to exclude irrelevant subagents for specific projects
  3. Resource efficiency: Larger context means higher token usage and potentially slower responses
  4. Project-specific workflows: Different projects need different subagent combinations

Example scenarios:

  • A data science project doesn't need GitHub-focused subagents
  • A documentation project doesn't need deployment/DevOps subagents
  • Testing different subagent combinations without moving files around
  • Sharing subagent collections while allowing per-project customization

Proposed Solutions

Option 1: Two-Tier System (Global + Project)

Mirror Claude Code's existing MCP server pattern with global and project-level registries.

Structure:

~/.claude/
├── subagent-configs/           # Global configurations
│   ├── default.json            # Default set of subagents
│   ├── data-science.json       # Data science workflow
│   └── web-dev.json            # Web development workflow
│
.claude/
└── subagent-config.json        # Project-level configuration (overrides global)

Configuration schema:

{
  "subagents": {
    "include": ["github-project-manager", "date-calculator"],
    "exclude": ["github-issue-creator"],
    "includeAll": false
  },
  "description": "Web development project subagents"
}

Pros:

  • Aligns with MCP server configuration patterns
  • Supports both global defaults and project-specific overrides
  • Clear precedence rules

Cons:

  • More complex than single-tier approach
  • Potential confusion with which configuration is active
  • May be over-engineered for simpler use cases

Option 2: Single Central Location with Subdirectory Namespacing

Simpler approach using directory structure for organization.

Structure:

~/.claude/agents/
├── _collections/               # Named collections
│   ├── github/                 # GitHub-related subagents
│   │   ├── github-project-manager.md
│   │   └── github-issue-creator.md
│   ├── dev-tools/              # Development tools
│   │   ├── date-calculator.md
│   │   └── test-runner.md
│   └── data-science/           # Data science workflow
│       └── jupyter-helper.md
│
.claude/
└── agents.config.json          # Project specifies which collections/agents to load

Configuration schema:

{
  "collections": ["github", "dev-tools"],
  "additionalAgents": ["custom-agent"],
  "excludeAgents": ["github-issue-creator"]
}

Pros:

  • Simpler mental model
  • Natural organization through directories
  • Easy to share collections
  • Less configuration overhead

Cons:

  • Requires restructuring existing agent directories
  • Less flexible than two-tier approach
  • May not align with Claude Code's discovery patterns

Option 3: Selection-Based Launcher (Extending ccmcp's Pattern)

Add subagent selection to ccmcp's existing MCP selection flow.

Features:

  • Extend existing TUI to show both MCP configs AND subagents
  • Launch Claude Code with both selected MCPs and selected subagents
  • Save selection preferences per project or globally

Implementation sketch:

interface SubagentConfig {
  name: string;
  path: string;
  description?: string;
  valid: boolean;
  error?: string;
}

// Parallel to scanMcpConfigs
async function scanSubagents(agentsDir?: string): Promise<SubagentConfig[]>

// Modified launcher
await launchClaudeCode({ 
  selectedConfigs: McpConfig[], 
  selectedSubagents: SubagentConfig[],
  passthroughArgs: string[] 
})

Pros:

  • Leverages existing ccmcp patterns and UI
  • Familiar workflow for users already using ccmcp
  • Single tool for both MCP and subagent management
  • Interactive selection avoids configuration file complexity

Cons:

  • Tighter coupling between MCP management and subagent management
  • May require Claude Code CLI to support subagent filtering
  • Could be scope creep for a tool focused on MCP selection

Questions to Consider

  1. Scope complexity: Is a two-tier system (global + project) necessary for subagents, or would a simpler single-tier approach suffice?

  2. Discovery vs. Selection: Should we modify subagent discovery (what gets loaded by Claude Code) or add a selection layer (similar to ccmcp's approach)?

  3. Integration level: Should this be:

    • Part of ccmcp (unified MCP + subagent selector)?
    • Separate tool following similar patterns?
    • Built into Claude Code itself?
  4. Backward compatibility: How do we ensure existing .claude/agents/ setups continue working?

  5. Configuration format: JSON schema like MCP configs, or YAML frontmatter like subagents themselves?

  6. MCP interaction: Should subagent configuration coexist with MCP configuration or remain separate?

Implementation Suggestions

Based on this codebase's patterns, a phased approach could be:

Phase 1: Research & Design

  • Investigate Claude Code's --agents CLI flag capabilities
  • Determine if Claude Code supports dynamic subagent loading
  • Design configuration schema (extend src/schemas/ patterns)
  • Decide on single-tier vs. two-tier approach

Phase 2: Core Infrastructure

  • Create src/schemas/subagent-config.ts (mirror mcp-config.ts)
  • Implement src/subagent-scanner.ts (mirror mcp-scanner.ts)
  • Add validation and error handling

Phase 3: UI Integration

  • Extend TUI components (src/tui/) for subagent selection
  • Add subagent preview component (similar to ConfigPreview.tsx)
  • Update main selection flow

Phase 4: Launcher Integration

  • Modify claude-launcher.ts to pass selected subagents
  • Implement subagent configuration merging logic
  • Add CLI flags (--agents-dir, environment variables)

Phase 5: Testing & Documentation

  • Unit tests for subagent scanning and validation
  • Integration tests for TUI
  • Update README and DEVELOPMENT.md
  • Create migration guide for existing setups

Related Patterns in Codebase

Key files to reference for implementation:

Configuration Schema & Validation:

  • /Users/george/src/gsong/ccmcp/src/schemas/mcp-config.ts - Zod schema patterns
  • /Users/george/src/gsong/ccmcp/src/mcp-scanner.ts - Discovery and validation logic

CLI Argument Handling:

  • /Users/george/src/gsong/ccmcp/src/index.ts - Argument parsing, precedence (CLI > env > default)

User Interface:

  • /Users/george/src/gsong/ccmcp/src/tui/ConfigSelector.tsx - Main selection component
  • /Users/george/src/gsong/ccmcp/src/tui/ConfigPreview.tsx - Preview display patterns

Error Handling:

  • /Users/george/src/gsong/ccmcp/src/utils.ts - Error formatting utilities

References

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions