Skip to content
jsmanifest logojsmanifest

The Claude Code Full Stack: When to Use CLAUDE.md, Skills, MCP, Subagents, and Hooks

The Claude Code Full Stack: When to Use CLAUDE.md, Skills, MCP, Subagents, and Hooks

Most Claude Code integration failures stem from misunderstanding the four-layer extension stack. Learn when to use CLAUDE.md, skills, MCP servers, subagents, and hooks—and why the distinction matters in production.

Correction (2026-10-28): an earlier version of this post described a skill as a TypeScript function with a JSON schema and an autoInvoke flag, including a full code sample defining one as an exported object. A skill is actually a markdown file (SKILL.md) with YAML frontmatter and instructions Claude follows using its existing tools—there's no separate function or execution runtime—checked against the official skills docs.

The Claude Code Full Stack: When to Use CLAUDE.md, Skills, MCP, Subagents, and Hooks

Most Claude Code integration failures stem from treating the extension as a monolithic tool. Teams reach for MCP servers when a simple skill would suffice, or they embed critical context in chat when it belongs in CLAUDE.md. The result: brittle workflows that break when context shifts or dependencies change.

The Claude Code extension operates as a four-layer stack: CLAUDE.md for project memory, skills for reusable instructions and workflows, MCP servers for external system integration, and hooks/subagents for orchestration. Each layer solves a specific class of problem. Mixing these layers—or choosing the wrong one—introduces failure modes that compound as codebases scale.

This post maps the entire Claude Code extension stack. The mental model here eliminates the guesswork that causes most integration bugs.

Understanding the Claude Code Extension Stack: A Mental Model

The Claude Code extension architecture separates concerns across four distinct layers. CLAUDE.md provides persistent project context that survives across sessions. Skills are markdown files of instructions and workflows that Claude loads when a task matches their description, or when you invoke them with /skill-name. MCP servers connect to external systems through a protocol-based interface. Hooks and subagents orchestrate multi-step workflows by delegating to specialized agents.

The failure mode here is subtle but expensive: teams conflate these layers and end up with context bleeding into skills, or MCP servers performing tasks that belong in CLAUDE.md. The distinction matters because each layer has different guarantees around state, execution model, and failure handling.

CLAUDE.md: Your Project's Single Source of Truth

CLAUDE.md functions as the project's persistent memory layer. Every time Claude Code starts a new conversation, it reads this file first. The content shapes how the agent interprets requests, understands the codebase structure, and makes decisions about implementation patterns.

Claude Code CLAUDE.md architecture

Effective CLAUDE.md files follow a four-section structure: project overview, architecture decisions, coding standards, and current focus. The project overview documents the tech stack, directory structure, and primary dependencies. Architecture decisions capture patterns like state management approach or API design conventions. Coding standards define style rules and testing requirements. Current focus directs the agent's attention to active work streams.

// Example CLAUDE.md structure
# Project: E-commerce Platform
 
## Tech Stack
- Next.js 14 (App Router)
- TypeScript 5.3
- Prisma ORM with PostgreSQL
- TanStack Query for data fetching
 
## Architecture Decisions
- Server Actions for mutations, Route Handlers for queries
- Parallel data fetching at layout boundaries
- Optimistic updates with TanStack Query's useMutation
- Form validation with Zod schemas
 
## Coding Standards
- Collocate feature code in src/features/[feature-name]
- Extract reusable UI to src/components/ui
- Keep Server Components async, Client Components synchronous
- All database queries through src/lib/db module
 
## Current Focus
- Implementing product search with Elasticsearch
- Migrating payment flow to Stripe Checkout
- Adding OpenTelemetry instrumentation

The implication here is that CLAUDE.md replaces the need to repeat context in every conversation. When the agent knows the project structure and conventions upfront, it generates code that matches existing patterns without explicit instruction. This distinction is critical: context in CLAUDE.md persists across sessions, while chat context expires when the conversation ends.

%% alt: CLAUDE.md feeds project context to every Claude Code session
flowchart TD
    Start["New Claude Code Session"] --> Read["Read CLAUDE.md"]
    Read --> Context["Load Project Context"]
    Context --> Decisions["Architecture Patterns"]
    Context --> Standards["Coding Standards"]
    Context --> Focus["Current Work"]
    Decisions --> Agent["Claude Code Agent"]
    Standards --> Agent
    Focus --> Agent
    Agent --> Generate["Generate Code Following Patterns"]
CLAUDE.md feeds project context to every Claude Code session

Skills vs MCP Servers: When to Use Each

The choice between skills and MCP servers determines execution model and failure boundaries. Skills are markdown files whose instructions load directly into Claude's context, and Claude carries them out with its existing tools. MCP servers run as separate processes and communicate through a JSON-RPC protocol.

Skills excel at workspace-local operations: reading files, generating code, running linters, executing tests. Claude loads the skill's instructions into context and continues working with its own tools—there's no network boundary, no external process lifecycle, and no protocol negotiation.

MCP servers handle external system integration: querying databases, calling APIs, reading cloud resources, interacting with third-party services. The protocol boundary provides isolation—if the database is down, the MCP server fails without crashing Claude Code. The tradeoff: latency increases due to IPC overhead and JSON serialization.

%% alt: Skills load instructions into context while MCP servers isolate external systems
flowchart LR
    subgraph SkillPattern["Skills: In-Context Instructions"]
        SkillRequest["Skill Loaded"] --> SkillExec["Claude Follows Instructions"]
        SkillExec --> SkillResult["Claude Uses Its Own Tools"]
    end
    
    subgraph MCPPattern["MCP: External Process"]
        MCPRequest["MCP Request"] --> Protocol["JSON-RPC Protocol"]
        Protocol --> Server["MCP Server Process"]
        Server --> External["External System"]
        External --> Response["Response"]
    end
Skills load instructions into context while MCP servers isolate external systems

The practical guideline: use skills for operations that manipulate workspace state, use MCP servers for operations that query or modify external systems. Mixing these patterns introduces unnecessary complexity. A skill that shells out to curl is fighting the abstraction—that operation belongs in an MCP server.

Implementing Claude Code Skills with Auto-Invocation

Skills give Claude reusable knowledge and invocable workflows. Claude sees every skill's description at session start, and matches your request against those descriptions to decide which skill's full content to load automatically—or you can invoke one directly with /skill-name.

A skill is a markdown file, SKILL.md, not a TypeScript function. It needs YAML frontmatter between --- markers—a description that tells Claude when to use it, plus optional fields like name and allowed-tools—and markdown content with the instructions Claude follows when the skill runs.

---
name: review-code
description: Reviews a TypeScript or JavaScript file for performance, security, and maintainability issues. Use when the user asks to review, analyze, or improve a file.
allowed-tools: Read, Grep
---
 
## Instructions
 
Read the file at the path the user gave you (ask for one if it's missing).
Check it for:
 
- **Performance**: unnecessary re-renders, N+1 queries, unbounded loops
- **Security**: unsanitized input, hardcoded secrets, unsafe deserialization
- **Maintainability**: duplicated logic, unclear naming, missing error handling
 
Report each issue with its line number, severity, and a one-line suggestion.
If the user asked to focus on one category, only report issues in that category.

By default, Claude loads a skill automatically once its description matches the request—no explicit invocation required. This works well for low-risk operations like linting or formatting. For higher-risk workflows—file deletion, database writes, API calls—set disable-model-invocation: true in the frontmatter so the skill only runs when a developer explicitly types /review-code.

Claude Code skills execution flow

Hooks, Subagents, and Delegation Patterns

Hooks provide lifecycle interception points where developers can inject custom behavior into Claude Code's execution flow. The system supports hooks at conversation start, before and after skill execution, on file changes, and at conversation end.

Subagents implement delegation through specialized agent instances. When the primary Claude Code agent encounters a task outside its expertise, it spawns a subagent with domain-specific context. The subagent completes the task and returns control to the primary agent.

The delegation pattern appears in multi-step workflows where different steps require different expertise. A refactoring task might spawn a test-writing subagent, a documentation subagent, and a migration subagent—each with focused context that eliminates irrelevant information.

%% alt: Hook and subagent orchestration for complex workflows
flowchart TD
    Request["Developer Request"] --> Hook["Pre-Execution Hook"]
    Hook --> Primary["Primary Claude Agent"]
    Primary --> Evaluate["Evaluate Task Complexity"]
    Evaluate -->|Simple| Direct["Execute Directly"]
    Evaluate -->|Complex| Delegate["Spawn Subagent"]
    Delegate --> Test["Test Writing Subagent"]
    Delegate --> Docs["Documentation Subagent"]
    Delegate --> Migration["Migration Subagent"]
    Test --> Aggregate["Aggregate Results"]
    Docs --> Aggregate
    Migration --> Aggregate
    Aggregate --> PostHook["Post-Execution Hook"]
    Direct --> PostHook
    PostHook --> Complete["Return to Developer"]
Hook and subagent orchestration for complex workflows

The hook system enables observability without modifying Claude Code internals. A pre-execution hook can log the request and skill parameters. A post-execution hook can validate output, update external systems, or trigger notifications. The separation of concerns here prevents coupling between Claude Code and custom tooling.

Building Your 4-Layer Extension Stack in Production

Production Claude Code setups layer CLAUDE.md, skills, MCP servers, and hooks into a coherent system. The stack architecture determines which layer handles each category of operation.

Layer 1 (CLAUDE.md) contains project-wide context: architecture patterns, coding standards, dependency constraints, and current priorities. This layer updates infrequently—typically during onboarding, after major refactors, or when adopting new patterns.

Layer 2 (Skills) holds reusable instructions and invocable workflows for workspace operations: code generation, refactoring, testing, linting. A skill is a markdown file—there's no separate execution runtime—and Claude carries out its instructions with the tools it already has. The skill library grows as teams identify repetitive operations worth documenting as a workflow.

Layer 3 (MCP Servers) bridges external systems: databases, APIs, cloud services, monitoring platforms. Each MCP server isolates a specific integration and handles connection management, authentication, and error recovery.

Layer 4 (Hooks + Subagents) orchestrates complex workflows: multi-step refactors, parallel code generation, cross-file analysis. Hooks inject observability and validation. Subagents delegate specialized tasks to focused agent instances.

// Example: Production Claude Code configuration
export const claudeCodeConfig = {
  // Layer 1: Project context
  claudeMd: './CLAUDE.md',
  
  // Layer 2: Skills registry (SKILL.md directories, not TS modules)
  skills: [
    'review-code',
    'generate-tests',
    'refactor',
    'migrate'
  ],
  
  // Layer 3: MCP servers
  mcpServers: {
    database: {
      command: 'npx',
      args: ['@anthropic-ai/mcp-server-postgres'],
      env: {
        DATABASE_URL: process.env.DATABASE_URL
      }
    },
    monitoring: {
      command: 'node',
      args: ['./mcp-servers/datadog.js'],
      env: {
        DD_API_KEY: process.env.DD_API_KEY
      }
    }
  },
  
  // Layer 4: Hooks and orchestration
  hooks: {
    preExecution: async (context) => {
      await logRequest(context);
      await checkRateLimit(context);
    },
    
    postExecution: async (context, result) => {
      await validateOutput(result);
      await updateMetrics(context, result);
      await notifyIfError(result);
    },
    
    onFileChange: async (file) => {
      await runLinter(file);
      await updateDependencyGraph(file);
    }
  },
  
  // Subagent delegation rules
  subagents: {
    maxConcurrent: 3,
    timeout: 300000, // 5 minutes
    specializations: [
      'testing',
      'documentation',
      'migration',
      'performance'
    ]
  }
};

Decision Framework: Choosing the Right Tool for Each Task

The decision tree for Claude Code extensions starts with two questions: Does this operation modify external state? Does this operation require specialized context?

If the operation modifies external state (database writes, API calls, cloud resource changes), use an MCP server. The protocol boundary provides isolation and enables independent failure handling. If the operation reads external state but doesn't modify it, MCP servers still apply—the abstraction keeps authentication and connection management separate from Claude Code.

If the operation works entirely within the workspace (file reads, code generation, local testing), use a skill. Skills load their instructions directly into Claude's context, avoiding the serialization overhead of the MCP protocol.

If the operation requires specialized context that differs from the primary task, spawn a subagent. Subagents receive focused prompts that eliminate irrelevant information. A test-writing subagent doesn't need to know about deployment pipelines. A documentation subagent doesn't need to understand database schemas.

If the operation needs to observe or modify Claude Code's behavior at specific lifecycle points, implement a hook. Hooks inject custom logic without modifying Claude Code internals. Pre-execution hooks validate inputs. Post-execution hooks enforce constraints or trigger side effects.

%% alt: Decision tree for selecting the right Claude Code extension pattern
flowchart TD
    Task["New Task"] --> External["Modifies External State?"]
    External -->|Yes| MCP["Use MCP Server"]
    External -->|No| Workspace["Workspace Operation?"]
    Workspace -->|Yes| Skill["Use Skill"]
    Workspace -->|No| Context["Needs Specialized Context?"]
    Context -->|Yes| Subagent["Spawn Subagent"]
    Context -->|No| Lifecycle["Lifecycle Interception?"]
    Lifecycle -->|Yes| Hook["Implement Hook"]
    Lifecycle -->|No| Claude["Standard Claude Code"]
    
    style MCP fill:#064e3b,stroke:#34d399,color:#6ee7b7
    style Skill fill:#1e3a8a,stroke:#60a5fa,color:#e0eaff
    style Subagent fill:#3b0764,stroke:#a855f7,color:#e9d5ff
    style Hook fill:#1e293b,stroke:#64ffda,color:#e2e8f0
Decision tree for selecting the right Claude Code extension pattern

Real-World Patterns: Memory, Context, and Parallel Execution

Production Claude Code setups handle three recurring patterns: long-term memory across sessions, context management for large codebases, and parallel execution for independent operations.

Long-term memory emerges from disciplined CLAUDE.md maintenance. Teams update the file after completing major features, making architectural decisions, or identifying recurring issues. The document evolves as the project grows. The alternative—relying on chat history—fails when conversations reset or when new team members join.

Context management for large codebases requires strategic skill design. Instead of loading entire files, a well-written skill instructs Claude to read only the relevant sections. Instead of analyzing the entire dependency graph, skills focus on changed files and their direct dependencies. The context window is finite—effective skills maximize information density.

Parallel execution happens through subagent delegation. When a refactor affects multiple independent modules, the primary agent spawns one subagent per module. Each subagent completes its work without waiting for the others. The primary agent aggregates results and handles conflicts. This pattern scales to dozens of parallel operations without overwhelming the context window.

That covers the essential patterns for the Claude Code extension stack. Apply these in production and the distinction between brittle chat-driven workflows and robust agent-driven automation becomes immediate. The four-layer architecture—CLAUDE.md, skills, MCP servers, hooks/subagents—maps directly to the separation of concerns that makes complex systems maintainable.