Skip to content

Latest commit

 

History

History
292 lines (186 loc) · 30.9 KB

File metadata and controls

292 lines (186 loc) · 30.9 KB

Claude Code CLI Advanced Features Guide

Claude Code CLI offers three powerful extensibility features that transform how you work with AI: custom sub agents enable specialized AI assistants for parallel task execution, slash commands provide interactive workflow automation through simple keyboard shortcuts, and skills deliver model-invoked capabilities that Claude automatically applies when relevant. Together, these features turn Claude from a general-purpose assistant into a programmable, specialized development partner that adapts to your workflows and team standards.

The most important distinction to understand: sub agents and slash commands require explicit invocation (you tell Claude when to use them), while skills are automatically discovered and applied (Claude decides when they're relevant). Sub agents excel at complex, multi-step tasks requiring fresh context; slash commands streamline repetitive workflows you trigger manually; and skills package reusable expertise that activates automatically. For development teams, project-level configurations for all three features can be version-controlled, ensuring everyone works with the same specialized capabilities and standardized processes.

Custom sub agents: specialized AI for complex workflows

Custom sub agents are specialized AI assistants that handle specific tasks with dedicated 200k token context windows, custom system prompts, and granular tool permissions. Introduced in Claude Code v1.0.60, they represent a paradigm shift from monolithic AI assistance to specialized expert systems working in concert. Each subagent operates independently with its own configuration, preventing context pollution and enabling true parallel execution across different aspects of your project.

Sub agents are stored as Markdown files with YAML frontmatter in either .claude/agents/ for project-wide sharing or ~/.claude/agents/ for personal use. The architecture is elegant: each file contains metadata defining when the agent should be invoked, which tools it can access, and detailed instructions guiding its behavior. Claude automatically delegates tasks to appropriate specialists based on your requests and the agent descriptions, similar to how it selects tools—but with far more sophisticated capabilities.

Creating your first custom sub agent

The recommended approach uses the interactive /agents command during a Claude Code session. This opens a management interface where you select "Create New Agent" and choose between project-level (shared with your team) or user-level (personal) scope. The most effective pattern is generating the initial agent with Claude's help, then customizing the result. Describe what you want the agent to do, specify when it should activate, and let Claude generate a solid foundation you can refine.

The file structure follows a consistent pattern with YAML frontmatter and markdown instructions. Here's a production-ready code reviewer subagent:

---
name: code-reviewer
description: Expert code review specialist. Proactively reviews code for quality, security, and maintainability. Use immediately after writing or modifying code.
tools: Read, Grep, Glob, Bash
model: sonnet
---

You are a senior code reviewer ensuring high standards of code quality and security.

When invoked:
1. Run git diff to see recent changes
2. Focus on modified files
3. Begin review immediately

Review checklist:
- Code is simple and readable
- Functions and variables are well-named
- No duplicated code
- Proper error handling
- No exposed secrets or API keys
- Input validation implemented
- Good test coverage
- Performance considerations addressed

Provide feedback organized by priority:
- Critical issues (must fix)
- Warnings (should fix)
- Suggestions (consider improving)

Include specific examples of how to fix issues.

This example demonstrates the four essential frontmatter fields: name (unique identifier using lowercase and hyphens), description (natural language explanation of purpose and trigger conditions), tools (comma-separated list of allowed tools), and model (sonnet for default depth, haiku for lightweight tasks). The description field is critical for automatic delegation—it tells Claude when to route work to this specialist.

Available tools and model selection strategy

Sub agents can access Claude Code's core tools including Read (file contents), Write (create/overwrite), Edit (targeted modifications), MultiEdit (multiple files), Grep (pattern search), Glob (list files), and Bash (shell commands). They also inherit access to configured MCP (Model Context Protocol) tools unless you explicitly restrict them. The principle of least privilege applies: only grant tools necessary for the agent's purpose to improve security and help it maintain focus.

Model selection significantly impacts both performance and cost. Claude Haiku delivers 90% of Sonnet's performance at 2x speed and 3x cost savings, making it optimal for lightweight agents requiring frequent invocation like test runners or simple reviews. Claude Sonnet provides balanced performance for most general-purpose subagents and serves as the default. Reserve Claude Opus for complex tasks requiring highest capability: orchestration, quality validation, architectural decisions, and sophisticated planning. A well-designed agent ecosystem uses each model strategically.

Automatic delegation and context isolation

Claude automatically routes tasks to appropriate specialists based on your natural language requests and the agent descriptions. When you say "review my latest code changes for security issues," Claude recognizes this matches a security-auditor subagent and delegates accordingly. You can also invoke manually with explicit instructions like "Use the code-reviewer subagent to analyze my pull request."

Context isolation is the secret weapon that makes subagents powerful for complex projects. Each agent starts with a clean 200k token context window when invoked, analyzes the specific task without pollution from unrelated conversations, completes its work, and returns results to the main agent. This prevents the quality degradation that occurs when a single context window becomes overloaded with disparate information. For large-scale refactoring, the primary agent identifies all files needing changes, spawns isolated subagents for each file, and synthesizes the results—each operation gets dedicated focus and full context capacity.

Practical patterns for development workflows

The parallel feature scaffolding pattern demonstrates subagent power: the main agent dispatches a backend-specialist for API endpoints, frontend-specialist for UI components, qa-specialist for test suites, and docs-specialist for documentation—all working simultaneously. When complete, the main agent synthesizes the parallel work into a coherent feature implementation. This dramatically accelerates development compared to sequential processing.

Sequential engineering lifecycle offers another powerful pattern. A product-manager agent creates detailed tickets, senior-software-engineer implements the feature, code-reviewer provides iterative feedback until approved, test-runner validates everything works, and deployment-engineer handles production release. Each specialist brings focused expertise without carrying forward irrelevant context from previous stages. This mimics real team structures but with AI specialists working at machine speed.

For test-driven development, create a test-runner subagent that automatically executes after code changes, diagnoses failures, fixes them while preserving test intent, and reports results. The automation happens proactively when you use phrases like "Use PROACTIVELY after code changes" in the description field. Similarly, documentation can stay synchronized with code through a doc-generator agent that analyzes implementations and maintains comprehensive README files and API documentation.

Configuration methods and team collaboration

Beyond the interactive /agents command, you can manually create Markdown files in the appropriate directory or use the CLI flag for dynamic definition. The --agents flag accepts JSON defining agent configurations, useful for programmatic workflows or temporary specialists. Priority order follows: project-level agents override CLI-defined agents, which override user-level agents. This allows teams to standardize on project agents while individuals maintain personal productivity agents.

Version control project agents in .claude/agents/ so your entire team benefits from and collaboratively improves them. Treat agent definitions like code: review changes, test thoroughly, document usage patterns, and iterate based on real-world results. Many teams establish a shared agents repository or include standard agents in project templates. The community maintains curated collections like VoltAgent/awesome-claude-code-subagents with 100+ production-ready definitions organized by category.

Slash commands: interactive workflow automation

Slash commands provide keyboard-driven control over Claude's behavior, configuration, and custom workflows through simple /command syntax during interactive sessions. They include both built-in system commands managing Claude Code itself and user-defined custom commands automating frequently-used prompts. The key value proposition is token efficiency: extracting fixed workflows from conversation into slash commands reduces context window usage by 15-20% while standardizing processes across team members.

Built-in commands cover session management (/clear for wiping context, /compact for condensing conversation), configuration (/config for settings, /permissions for tool access, /model for AI model selection), advanced features (/agents for subagent management, /mcp for protocol servers), and utilities (/status for system health, /cost for token usage). The /help command reveals all available commands including your custom ones, making it essential for discovery.

Creating custom slash commands for your workflows

Custom commands are Markdown files stored in .claude/commands/ for project-level sharing or ~/.claude/commands/ for personal use. The simplest command is just a text file containing the prompt you want to automate. Create a commit workflow with:

mkdir -p .claude/commands
cat > .claude/commands/commit.md << 'EOF'
# Commit and Push Changes

## Steps
1. Run `git status` to see all changes
2. Run `git diff` to review changes
3. Analyze changes and determine conventional commit type:
   - `feat:` for new features
   - `fix:` for bug fixes
   - `docs:` for documentation
   - `refactor:` for code refactoring
4. Stage all changes with `git add -A`
5. Create descriptive conventional commit
6. Push to current branch with `git push`
EOF

Now typing /commit in any Claude Code session executes this complete workflow. The power comes from making implicit team knowledge explicit and automatable. Every developer gets the same consistent process without remembering all the steps.

Advanced command features with frontmatter

Adding YAML frontmatter enables sophisticated control over command behavior. The description field provides a brief explanation shown in /help. The allowed-tools field restricts which tools the command can use, improving security and focus. The model field specifies which Claude model executes the command. The argument-hint field documents expected parameters. The disable-model-invocation field prevents Claude from automatically executing this command via the SlashCommand tool.

Here's a GitHub issue resolution command demonstrating advanced features:

---
description: Analyze and fix a GitHub issue
argument-hint: [issue-number]
allowed-tools: Read, Write, Edit, Bash(git *), Bash(gh *)
---

Please analyze and fix GitHub issue: $ARGUMENTS

## Steps
1. Use `gh issue view $ARGUMENTS` to get issue details
2. Understand the problem
3. Search codebase for relevant files
4. Implement necessary changes
5. Write and run tests
6. Ensure code passes linting
7. Create descriptive commit message
8. Push and create a PR

Remember to use GitHub CLI (`gh`) for all GitHub-related tasks.

The $ARGUMENTS variable captures everything you type after the command name. Invoke with /fix-issue 234 and Claude receives "234" as the argument value. For multiple arguments, use $1, $2, $3, etc., allowing sophisticated parameterization.

Organizing commands and namespace patterns

Commands can be organized into subdirectories for better structure. Create .claude/commands/workflows/ for development processes and .claude/commands/tools/ for utilities. Access nested commands with colon notation: /project:workflows:feature-development or /project:tools:security-scan. This namespacing prevents collision between similarly-named commands and provides logical grouping visible in /help.

Best practices favor abstraction with context over hardcoded specifics. Make commands reusable across similar situations but provide enough detail that Claude understands intent. Avoid time-sensitive information that will become outdated. Use consistent terminology throughout each command. Document important commands in your project's CLAUDE.md file so team members know what's available and when to use each one.

MCP slash commands for dynamic capabilities

MCP (Model Context Protocol) servers can expose prompts as dynamically-available slash commands. When you connect an MCP server, its capabilities automatically appear as commands using the format /mcp__servername__toolname. For example, connecting a GitHub MCP server might provide /mcp__github__list_prs to list pull requests or /mcp__github__pr_review 456 to review PR 456.

Set up MCP servers with claude mcp add my-server -e API_KEY=123 -- /path/to/server arg1 arg2, then check status with /mcp. You must approve MCP tools through permissions—either approve all tools from a server with mcp__servername or specific tools like mcp__github__get_issue. Wildcards are not supported. MCP integration dramatically expands available functionality by connecting Claude to external APIs, databases, and services through standardized protocols.

The SlashCommand tool and automatic invocation

The SlashCommand tool allows Claude to programmatically execute your custom slash commands when appropriate based on conversation context. When enabled, Claude can invoke commands on your behalf if you reference them in CLAUDE.md with keyword mappings or when natural language matches command descriptions. For example, configure "commit my changes" to automatically execute /commit without explicitly typing the slash command.

This feature only supports user-defined custom commands with populated description frontmatter fields, not built-in commands. Control it through /permissions by adding SlashCommand to deny rules if you want purely manual command invocation. Individual commands can opt out with disable-model-invocation: true in frontmatter. For debugging which commands are available to the SlashCommand tool, use claude --debug with versions 1.0.124 or later.

Integration patterns with other features

Slash commands become extraordinarily powerful when combined with sub agents and skills. Create commands that orchestrate multiple subagents for comprehensive workflows. A /review-pr command might invoke code-reviewer for quality, security-auditor for vulnerabilities, test-runner for validation, and performance-engineer for bottlenecks, then compile a comprehensive report. This transforms slash commands into high-level workflow controllers that coordinate specialized agents.

Hooks provide another integration layer, automatically running after command execution. Configure PostToolUse hooks to format code after edits, validate outputs before proceeding, or send notifications when deployments complete. The combination of slash commands (user intent), sub agents (specialized execution), and hooks (automated follow-up) creates sophisticated development pipelines that feel like having a full engineering team at your command.

Skills: automatic capabilities discovery

Skills are self-contained folders containing a SKILL.md file with YAML frontmatter and markdown instructions, optionally including scripts, templates, and data files. Unlike sub agents and slash commands that require explicit invocation, skills are model-invoked—Claude automatically decides when to apply them based on relevance to your request. This automatic discovery makes skills ideal for packaging repeatable expertise that should activate whenever applicable.

Skills work identically across Claude.ai, Claude Code CLI, and Claude API, providing portability for your invested effort. Each skill consumes only 30-50 tokens until Claude decides to load it, implementing progressive disclosure that keeps context efficient. Multiple skills automatically compose together for complex workflows. Skills can include executable Python or JavaScript code for deterministic operations beyond Claude's native capabilities.

How skills work and when Claude uses them

At startup, Claude scans all available skills and reads the name and description from YAML frontmatter. When you make a request, Claude evaluates which skills might be relevant based on descriptions. Only relevant skills are fully loaded—Claude reads the complete SKILL.md and additional files on-demand. Multiple skills can be loaded and coordinated automatically without your intervention. The description field is absolutely critical for discovery; it must explain both what the skill does and when Claude should use it, including key trigger terms users would naturally mention.

Skills run in Claude's code execution environment with filesystem access, bash command execution, and Python/JavaScript code execution. On claude.ai, skills can install npm and PyPI packages with network access. In the API, there's no network access and no runtime package installation. Claude Code CLI capabilities depend on your platform. All environments provide isolated execution with no data persistence between sessions, ensuring security.

Creating a basic skill structure

The minimum requirement is a folder with a SKILL.md file. Start with the simplest possible structure:

~/.claude/skills/commit-message-generator/
└── SKILL.md

The SKILL.md format uses YAML frontmatter followed by markdown instructions:

---
name: generating-commit-messages
description: Generates clear commit messages from git diffs. Use when writing commit messages or reviewing staged changes.
---

# Generating Commit Messages

## Instructions
1. Run `git diff --staged` to see changes
2. Suggest a commit message with:
   - Summary under 50 characters
   - Detailed description
   - Affected components

## Best Practices
- Use present tense
- Explain what and why, not how
- Be specific about changes

Required fields are name (unique identifier with lowercase, hyphens, max 64 characters) and description (what it does and when to use it, max 1024 characters). The description determines whether Claude loads your skill, so invest time making it specific and actionable. Include trigger terms users would naturally say: "git", "commit", "staged changes", "version control".

Advanced skill patterns with supporting files

For complex skills, add supporting resources using clear directory structure:

pdf-analyzer/
├── SKILL.md              # Main instructions
├── reference/            # Additional documentation
│   ├── guide.md
│   └── examples.md
├── scripts/              # Executable utilities
│   ├── validator.py
│   └── helper.sh
├── templates/            # Reusable templates
│   └── report_template.md
└── data/                 # Sample data, configs
    └── sample.json

Example layout — script names shown for illustration only.

Progressive disclosure patterns keep initial loading efficient while providing depth when needed. In SKILL.md, provide high-level guidance and reference detailed documentation: "See schema documentation for table structures." Keep SKILL.md under 500 lines; split larger content into referenced files Claude can load conditionally.

Skills can include executable scripts that perform deterministic operations. A PDF form analyzer might have a Python script that extracts field metadata. In SKILL.md, instruct Claude: "Run python scripts/extract_forms.py <pdf_file> to extract form fields, then analyze the output JSON." This combines Claude's intelligence with programmatic precision for reliable results.

Using skills in Claude Code CLI

Install pre-built skills via the marketplace with /plugin marketplace add anthropics/skills then /plugin install document-skills@anthropic-agent-skills. Anthropic provides official document skills for Word (docx), Excel (xlsx), PowerPoint (pptx), and PDF files, plus example skills for creative work, technical tasks, and enterprise needs. Community collections offer additional options through repositories like travisvn/awesome-claude-skills.

Manual installation copies skill folders to ~/.claude/skills/ for personal use or .claude/skills/ for project sharing. Team collaboration works best with project skills committed to version control—everyone automatically gets standardized procedures when they clone the repository. Personal skills let individuals maintain productivity tools without cluttering shared projects.

Using skills requires no special syntax—just ask naturally and Claude decides when they're relevant. "Can you extract text from this PDF?" triggers the PDF skill. "Create an Excel spreadsheet with sales data" activates the xlsx skill. "Generate a commit message for these changes" loads your commit-message-generator. The automatic invocation eliminates cognitive overhead compared to remembering which subagent to invoke or which slash command to type.

Best practices for skill development

Descriptions must be specific and actionable rather than vague. Good: "Analyze sales data in Excel files and CRM exports. Use for sales reports, pipeline analysis, and revenue tracking." Bad: "Helps with documents." Include concrete use cases and trigger terminology users would naturally say. Test your description by asking: would someone unfamiliar with this skill understand when it applies?

Naming conventions favor gerund form (verb + -ing) for discoverability: "Processing PDFs", "Analyzing spreadsheets", "Managing databases". Avoid generic terms like "Helper", "Utils", or "Tools". The name appears in Claude's reasoning when loading skills, helping you understand what's happening.

Keep content concise—every sentence must justify its token cost. Remove explanations Claude already knows from general training. Use templates instead of prose descriptions when possible. Employ consistent terminology throughout; choose one term like "extract" and avoid mixing "pull", "get", "retrieve". Provide concrete examples showing input/output pairs and real-world scenarios rather than abstract explanations.

Test with all target models. Haiku needs more explicit guidance; Sonnet wants clarity and efficiency; Opus benefits from nuance but doesn't need over-explanation. Build test scenarios first using an evaluation-driven approach: identify gaps in Claude's capabilities, create 3+ test cases, measure baseline performance, write minimal instructions to pass tests, and iterate based on results. Iterative development with helper Claude works well: complete a task with Claude A, ask it to create a skill from the interaction, test with fresh Claude B instance, observe behavior, refine with Claude A based on feedback.

Skills versus other extensibility features

Skills differ fundamentally from slash commands in invocation: skills are model-invoked (automatic based on relevance) while slash commands are user-invoked (manual typing). This makes skills perfect for repeatable workflows that should activate whenever relevant, while slash commands suit workflows you explicitly trigger. Use skills for coding standards, analysis patterns, and document generation; use slash commands for deployment, git operations, and workflows requiring human judgment about timing.

Skills differ from sub agents in scope and persistence. Skills provide instructions and procedures; sub agents are independent AI assistants with their own context. Skills teach Claude how to do something; sub agents do the work autonomously. A skill might teach Claude how to review code following your team's checklist. A sub agent receives code and performs the review in its own context window. Skills are lighter weight and more portable; sub agents offer more power for complex, multi-step tasks.

Skills and custom instructions serve different purposes. Custom instructions apply universally to all Claude interactions but have limited space. Skills are task-specific, can be extensively detailed, only load when relevant, and are shareable via git or plugins. Use custom instructions for fundamental behaviors and preferences; use skills for domain expertise and specific workflows.

Security considerations and trust requirements

Skills can execute arbitrary code in Claude's environment, access files in the working directory, run system commands, and install third-party packages. Only install skills from trusted sources. Anthropic implements security measures in the code execution environment, but prompt injection, data exfiltration, and unintended actions remain possible with malicious skills. Always audit skills before installing from community sources—read all files, especially scripts and bundled resources, checking for suspicious network connections or data handling.

Mitigate risks by starting with Anthropic pre-built skills, thoroughly auditing community skills, using read-only skills when possible, testing in non-production environments first, keeping skills focused and minimal, and documenting expected behavior. Use the optional allowed-tools frontmatter field to restrict capabilities: a read-only analyzer should specify allowed-tools: [Read, Grep, Glob] to prevent file modifications.

Configuration, setup, and getting started

All three features require Claude Code CLI installed via npm install -g @anthropic-ai/claude-code with Node.js 18+ and authentication through Anthropic account or API key. Skills additionally require code execution enabled in Settings > Capabilities, available only on Pro, Max, Team, or Enterprise plans—the free tier cannot use skills. Sub agents and slash commands work on all plans including free tier.

Directory structure determines scope and sharing. Personal configurations in ~/.claude/ apply across all your projects: ~/.claude/agents/ for personal sub agents, ~/.claude/commands/ for personal slash commands, ~/.claude/skills/ for personal skills. Project configurations in .claude/ share via version control: .claude/agents/, .claude/commands/, .claude/skills/. Best practice commits project configurations to git so teams work with identical capabilities.

Getting started follows a natural progression. First, use the interactive managers: /agents to explore and create sub agents, /help to discover available slash commands, /plugin marketplace add anthropics/skills to access official skills. Second, try built-in and pre-built capabilities to understand how each feature works. Third, create simple custom versions: a basic code reviewer sub agent, a git commit slash command, a team standards skill. Fourth, iterate based on real usage—these features improve dramatically with refinement from actual workflows.

Start simple and expand progressively. A code-reviewer sub agent, /test slash command, and commit-message-generator skill provide immediate value. Build your ecosystem gradually based on pain points and repetitive workflows. The combination of all three features creates a development environment that feels like having an entire specialized team working alongside you, each member (or capability) focused on their domain of expertise.

Combining features for powerful workflows

The true power emerges when you orchestrate these features together. Create a /feature-complete slash command that automatically invokes multiple sub agents (backend-specialist, frontend-specialist, test-engineer) while leveraging skills for code standards, documentation generation, and commit messages. This turns a single command into a comprehensive workflow coordinating AI specialists using standardized procedures.

Sub agents can be designed to work with specific skills. A documentation-engineer sub agent's instructions might say "leverage the technical-writing skill when creating API documentation" or "use the markdown-formatting skill for consistency." The sub agent handles orchestration; skills provide the expertise. Similarly, slash commands can explicitly invoke sub agents while ensuring skills are available: your /deploy command delegates to a deployment-engineer sub agent that uses the infrastructure-validation skill.

Hooks integrate with all three features for complete automation. PostToolUse hooks can trigger slash commands after file edits, spawn sub agents for validation, or verify that skills were applied correctly. PreToolUse hooks can enforce that certain skills are always active for specific operations. The synergy creates development pipelines where simple user intent activates sophisticated multi-agent workflows with automatic quality checks and standardized procedures.

Conclusion: programmable AI for modern development

Custom sub agents, slash commands, and skills transform Claude Code CLI from a conversational AI into a programmable development platform. Sub agents provide specialized intelligence with isolated context; slash commands offer interactive workflow automation; skills deliver automatic expertise application. Understanding when to use each—and how to combine them—unlocks productivity that feels like having an expert team customized to your exact workflows and standards.

The investment in creating these configurations pays dividends through consistency, efficiency, and team scalability. Version-controlled project configurations ensure everyone works the same way without coordination overhead. Accumulated expertise in sub agents, commands, and skills becomes organizational assets that improve over time. New team members inherit specialized capabilities immediately, achieving productivity faster than traditional onboarding allows.

Start by identifying pain points in your current workflow: repetitive tasks, complex multi-step processes, specialized knowledge that isn't consistently applied. Build the simplest possible solution using the most appropriate feature—a slash command for manual workflows, a skill for automatic expertise, a sub agent for complex tasks. Test thoroughly, refine based on real usage, share with your team, and iterate. The ecosystem you build becomes increasingly powerful as configurations compound, creating a development environment uniquely optimized for your team's work.