Claude Code Comprehensive Reference Guide (2024-2026)
> A complete reference covering hooks, skills, MCP integration, Agent SDK, configuration, subagent patterns, and IDE integrations.
Overview
Claude Code Comprehensive Reference Guide (2024-2026)
A complete reference covering hooks, skills, MCP integration, Agent SDK, configuration, subagent patterns, and IDE integrations.
Last Updated: January 2026 Applicable Versions: Claude Code 2.x+
Table of Contents
- Hooks System Deep Dive
- Skills and Slash Commands
- MCP Server Implementation
- Agent SDK Patterns
- Configuration Best Practices
- Subagent Orchestration
- IDE Integrations
- Production Examples
- Context Window Management
- Tools Reference
1. Hooks System Deep Dive
Hooks are automated actions triggered at specific points in a Claude Code session. They enable validation, monitoring, and control of Claude's actions through bash commands or LLM-based evaluation.
Sources:
1.1 Hook Lifecycle
Hooks fire in this sequence:
- SessionStart - Session begins or resumes
- UserPromptSubmit - User submits a prompt
- PreToolUse - Before tool execution (can modify/block)
- PermissionRequest - When permission dialog appears
- PostToolUse - After tool succeeds
- SubagentStart - When spawning a subagent
- SubagentStop - When subagent finishes
- Stop - Claude finishes responding
- PreCompact - Before context compaction
- SessionEnd - Session terminates
- Notification - Claude Code sends notifications
1.2 Hook Types
Command Hooks (type: "command"):
Execute bash commands with full stdin/stdout control.
Prompt Hooks (type: "prompt"):
Use LLM evaluation for intelligent, context-aware decisions. Currently only supported for Stop and SubagentStop events.
1.3 Configuration Structure
Hooks are configured in settings files:
~/.claude/settings.json- User settings (all projects).claude/settings.json- Project settings (shared with team).claude/settings.local.json- Local project settings (not committed)
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": ".claude/hooks/validate-bash.sh",
"timeout": 30
}
]
}
],
"PostToolUse": [
{
"matcher": "Write|Edit",
"hooks": [
{
"type": "command",
"command": "\\"$CLAUDE_PROJECT_DIR\\"/.claude/hooks/format-code.sh"
}
]
}
],
"Stop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Check if all requested tasks are complete. If not, list what remains.",
"timeout": 30
}
]
}
]
}
}
1.4 Matcher Syntax
| Pattern | Description |
|---|---|
Write | Match exact tool name |
| `Edit\ | Write` |
Notebook.* | Regex pattern matching |
* or "" | Match all tools |
| (omitted) | Required for Stop, SubagentStop, UserPromptSubmit |
1.5 Hook Input Schema
All hooks receive JSON via stdin:
{
"session_id": "abc123",
"transcript_path": "/path/to/transcript",
"cwd": "/project/root",
"permission_mode": "default",
"hook_event_name": "PreToolUse",
"tool_name": "Bash",
"tool_input": {
"command": "npm test",
"description": "Run test suite"
}
}
1.6 Hook Output and Exit Codes
| Exit Code | Behavior |
|---|---|
| 0 | Success - stdout shown to user or added as context |
| 2 | Blocking error - stderr shown, action blocked |
| Other | Non-blocking error - stderr shown in verbose mode |
PreToolUse Decision Control:
{
"hookSpecificOutput": {
"hookEventName": "PreToolUse",
"permissionDecision": "allow|deny|ask",
"permissionDecisionReason": "Reason for decision",
"updatedInput": {
"command": "modified command"
},
"additionalContext": "Context for Claude"
}
}
Stop/SubagentStop Control:
{
"decision": "block",
"reason": "Tasks incomplete: missing test coverage"
}
1.7 Environment Variables
| Variable | Description |
|---|---|
CLAUDE_PROJECT_DIR | Absolute path to project root |
CLAUDE_CODE_REMOTE | "true" if remote session |
CLAUDE_ENV_FILE | Path to persist env vars (SessionStart/Setup only) |
CLAUDE_FILE_PATHS | Space-separated file paths (PostToolUse for Write/Edit) |
1.8 Practical Hook Examples
Security Firewall (block dangerous commands):
#!/usr/bin/env bash
# .claude/hooks/pre-bash-firewall.sh
set -euo pipefail
cmd=$(jq -r '.tool_input.command // ""')
# Block dangerous patterns
if echo "$cmd" | grep -qE 'rm -rf|git reset --hard|curl.*\\|.*sh'; then
echo '{"decision": "block", "reason": "Dangerous command blocked by security policy"}' >&2
exit 2
fi
exit 0
Auto-formatter (run after file changes):
#!/usr/bin/env bash
# .claude/hooks/format-code.sh
set -euo pipefail
# Get changed files
files=$(jq -r '.tool_input.file_path // ""')
# Format based on extension
for file in $files; do
case "$file" in
*.py) black "$file" 2>/dev/null || true ;;
*.js|*.ts) prettier --write "$file" 2>/dev/null || true ;;
esac
done
exit 0
Command Logger:
#!/usr/bin/env bash
set -euo pipefail
cmd=$(jq -r '.tool_input.command // ""')
printf '%s %s\
' "$(date -Is)" "$cmd" >> .claude/bash-commands.log
exit 0
1.9 SubagentStop Hooks for Workflow Control
SubagentStop hooks fire when a subagent (Task tool) completes. This enables workflow orchestration:
{
"hooks": {
"SubagentStop": [
{
"hooks": [
{
"type": "prompt",
"prompt": "Review the subagent's work. Did it complete all assigned tasks? Are there any issues that need escalation to the main agent?"
}
]
}
]
}
}
2. Skills and Slash Commands
Skills are structured, auto-discovered capabilities that extend Claude's functionality. Custom slash commands have been merged into skills - a file at .claude/commands/review.md and a skill at .claude/skills/review/SKILL.md both create /review.
Sources:
2.1 Key Differences
| Feature | Slash Commands | Skills |
|---|---|---|
| Invocation | Manual /command | Auto or manual |
| Structure | Single markdown file | Directory with SKILL.md + resources |
| Complexity | Simple, repeatable tasks | Rich workflows with supporting files |
| Discovery | Must know command name | Claude auto-triggers when relevant |
2.2 Directory Structure
my-skill/
├── SKILL.md # Required - instructions and metadata
├── reference.md # Optional - detailed documentation
├── examples.md # Optional - usage examples
└── scripts/
└── helper.py # Optional - executable scripts
Storage Locations:
| Location | Path | Scope |
|---|---|---|
| Enterprise | See managed settings | All organization users |
| Personal | ~/.claude/skills/<name>/SKILL.md | All your projects |
| Project | .claude/skills/<name>/SKILL.md | Current project only |
2.3 SKILL.md Format
---
name: explain-code
description: Explains code with visual diagrams and analogies. Use when explaining how code works, teaching about a codebase, or when the user asks "how does this work?"
argument-hint: [file-path]
disable-model-invocation: false
user-invocable: true
allowed-tools: Read, Grep, Glob
model: claude-sonnet-4-20250514
context: fork
agent: Explore
---
When explaining code, always include:
1. **Start with an analogy**: Compare the code to something from everyday life
2. **Draw a diagram**: Use ASCII art to show flow, structure, or relationships
3. **Walk through the code**: Explain step-by-step what happens
4. **Highlight a gotcha**: What's a common mistake or misconception?
Keep explanations conversational. For complex concepts, use multiple analogies.
2.4 Frontmatter Reference
| Field | Required | Description |
|---|---|---|
name | No | Display name (lowercase, max 64 chars). Defaults to directory name |
description | Recommended | What skill does and when to use it (max 1024 chars) |
argument-hint | No | Autocomplete hint, e.g., [issue-number] |
disable-model-invocation | No | true = manual only. Default: false |
user-invocable | No | false = hidden from / menu. Default: true |
allowed-tools | No | Tools Claude can use without permission |
model | No | Specific model when skill is active |
context | No | fork = run in isolated subagent context |
agent | No | Subagent type: Explore, Plan, general-purpose |
hooks | No | Lifecycle hooks for this skill |
2.5 Invocation Control Patterns
Manual Only (side effects):
---
name: deploy
description: Deploy to production
disable-model-invocation: true
---
Background Knowledge (auto-only):
---
name: legacy-context
description: How the legacy payment system works
user-invocable: false
---
Full Access (default):
---
name: review
description: Code review with best practices
---
2.6 Dynamic Context Injection
Use shell command syntax to inject dynamic content:
---
name: pr-summary
description: Summarize PR changes
context: fork
agent: Explore
allowed-tools: Bash(gh:*)
---
## Pull request context
- PR diff: !`gh pr diff`
- PR comments: !`gh pr view --comments`
- Changed files: !`gh pr diff --name-only`
Summarize this pull request...
2.7 String Substitutions
| Variable | Description |
|---|---|
$ARGUMENTS | All arguments passed when invoking |
${CLAUDE_SESSION_ID} | Current session ID |
2.8 Subagent Execution
---
name: deep-research
description: Research a topic thoroughly
context: fork
agent: Explore
---
Research $ARGUMENTS thoroughly:
1. Find relevant files using Glob and Grep
2. Read and analyze the code
3. Summarize findings with specific file references
2.9 Skill-Scoped Hooks
---
name: secure-operations
hooks:
PreToolUse:
- matcher: "Bash"
hooks:
- type: command
command: "./scripts/security-check.sh"
once: true
---
2.10 Context Budget
Skill descriptions are loaded into context. Default budget: 15,000 characters.
# Check for warnings
/context
# Increase limit
3. MCP Server Implementation
The Model Context Protocol (MCP) is an open standard for connecting AI models to external tools, data sources, and services.
Sources:
3.1 Overview
MCP provides three core capabilities:
| Capability | Description |
|---|---|
| Tools | Functions that can perform actions or fetch data |
| Resources | Read-only content accessible via @ mentions |
| Prompts | Reusable prompt templates available as /mcp__server__prompt |
3.2 Configuration Methods
CLI Wizard:
claude mcp add
Direct Configuration (.mcp.json or settings):
{
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "/allowed/path"]
},
"github": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-github"],
"env": {
"GITHUB_PERSONAL_ACCESS_TOKEN": "your-token"
}
},
"custom-api": {
"url": "https://your-api.com/mcp",
"transport": "http"
}
}
}
3.3 Transport Types
| Transport | Description |
|---|---|
stdio | Subprocess with JSON-RPC over stdin/stdout (most common) |
http | Remote HTTP server (recommended for cloud services) |
sse | Server-Sent Events |
3.4 Building Custom MCP Servers
Python SDK:
pip install mcp
TypeScript SDK:
npm install @modelcontextprotocol/sdk
Example Server (TypeScript):
const server = new Server({
name: 'my-server',
version: '1.0.0',
}, {
capabilities: {
tools: {},
resources: {},
prompts: {},
},
});
// Define a tool
server.setRequestHandler('tools/list', async () => ({
tools: [{
name: 'get_weather',
description: 'Get current weather for a location',
inputSchema: {
type: 'object',
properties: {
location: { type: 'string', description: 'City name' },
},
required: ['location'],
},
}],
}));
server.setRequestHandler('tools/call', async (request) => {
if (request.params.name === 'get_weather') {
const { location } = request.params.arguments;
// Fetch weather data...
return { content: [{ type: 'text', text: `Weather in ${location}: Sunny, 72F` }] };
}
});
// Start server
const transport = new StdioServerTransport();
await server.connect(transport);
3.5 Using MCP Resources
@mcp__filesystem__readme.md
Resources appear alongside files in the @ autocomplete menu.
3.6 Dynamic Tool Loading
When MCP tool descriptions exceed 10% of context, Tool Search activates automatically, loading tools on-demand.
3.7 Security Considerations
- MCP servers run with your user permissions
- Validate and sanitize all inputs
- Be cautious with servers that fetch untrusted content (prompt injection risk)
- Review third-party servers before installation
4. Agent SDK Patterns
The Claude Agent SDK lets you build AI agents programmatically with the same capabilities that power Claude Code.
Sources:
- Agent SDK Overview
- Python SDK
- TypeScript SDK
- [Building Agents Blog](ht