All skills
Skillintermediate

Claude Code Comprehensive Reference Guide (2024-2026)

> A complete reference covering hooks, skills, MCP integration, Agent SDK, configuration, subagent patterns, and IDE integrations.

Claude Code Knowledge Pack7/10/2026

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

  1. Hooks System Deep Dive
  2. Skills and Slash Commands
  3. MCP Server Implementation
  4. Agent SDK Patterns
  5. Configuration Best Practices
  6. Subagent Orchestration
  7. IDE Integrations
  8. Production Examples
  9. Context Window Management
  10. 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:

  1. SessionStart - Session begins or resumes
  2. UserPromptSubmit - User submits a prompt
  3. PreToolUse - Before tool execution (can modify/block)
  4. PermissionRequest - When permission dialog appears
  5. PostToolUse - After tool succeeds
  6. SubagentStart - When spawning a subagent
  7. SubagentStop - When subagent finishes
  8. Stop - Claude finishes responding
  9. PreCompact - Before context compaction
  10. SessionEnd - Session terminates
  11. 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

PatternDescription
WriteMatch 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 CodeBehavior
0Success - stdout shown to user or added as context
2Blocking error - stderr shown, action blocked
OtherNon-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

VariableDescription
CLAUDE_PROJECT_DIRAbsolute path to project root
CLAUDE_CODE_REMOTE"true" if remote session
CLAUDE_ENV_FILEPath to persist env vars (SessionStart/Setup only)
CLAUDE_FILE_PATHSSpace-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

FeatureSlash CommandsSkills
InvocationManual /commandAuto or manual
StructureSingle markdown fileDirectory with SKILL.md + resources
ComplexitySimple, repeatable tasksRich workflows with supporting files
DiscoveryMust know command nameClaude 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:

LocationPathScope
EnterpriseSee managed settingsAll organization users
Personal~/.claude/skills/<name>/SKILL.mdAll your projects
Project.claude/skills/<name>/SKILL.mdCurrent 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

FieldRequiredDescription
nameNoDisplay name (lowercase, max 64 chars). Defaults to directory name
descriptionRecommendedWhat skill does and when to use it (max 1024 chars)
argument-hintNoAutocomplete hint, e.g., [issue-number]
disable-model-invocationNotrue = manual only. Default: false
user-invocableNofalse = hidden from / menu. Default: true
allowed-toolsNoTools Claude can use without permission
modelNoSpecific model when skill is active
contextNofork = run in isolated subagent context
agentNoSubagent type: Explore, Plan, general-purpose
hooksNoLifecycle 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

VariableDescription
$ARGUMENTSAll 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:

CapabilityDescription
ToolsFunctions that can perform actions or fetch data
ResourcesRead-only content accessible via @ mentions
PromptsReusable 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

TransportDescription
stdioSubprocess with JSON-RPC over stdin/stdout (most common)
httpRemote HTTP server (recommended for cloud services)
sseServer-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: