Skip to main content
🎓 Claude Code Masterclass Learn AI-assisted development on Udemy — plus the companion book on Leanpub & Amazon. Start Learning
Claude Code Complete Guide Hooks MCP SDK 2026
AI

Claude Code: Complete Guide to Hooks, MCP, and the SDK

Deep dive into Claude Code: context, Plan mode, hooks, MCP, SDK, and environment variables for web search, subagents, concurrency, and runtime guardrails.

LB
Luca Berton
· 9 min read

Claude Code is not just another AI coding assistant. It is a tool-use engine that can read files, run commands, control browsers, review pull requests, and integrate into your CI/CD pipeline. Here is everything you need to know to use it effectively.

How Claude Code Actually Works

Every AI coding assistant follows the same core process:

  1. Receives a task — fix a bug, implement a feature, analyze data
  2. Gathers context — reads files, understands the codebase structure
  3. Formulates a plan — determines what needs to change
  4. Takes action — updates files, runs tests, verifies the result

The key limitation is that language models only process text input and output. They cannot directly read files, run commands, or interact with external systems. This is where tool use comes in.

The Tool Use System

Claude Code uses a structured system where:

  • The assistant appends instructions specifying how to request actions
  • The language model responds with formatted action requests (e.g., “read file: filename”)
  • Claude Code executes the actual action and returns the result
  • The language model processes the result and continues

Claude’s advantage over other models is superior tool use capabilities — it is better at understanding tool functions and combining them for complex multi-step tasks. This directly impacts coding assistant effectiveness because every non-trivial task requires chaining multiple tools together.

Context Management: The Make-or-Break Factor

Too much irrelevant context decreases performance. Too little context means Claude misses important details. Getting this right is critical.

CLAUDE.md Files

The /init command analyzes your entire codebase and creates a CLAUDE.md file with a project summary, architecture overview, and key file references. This file is included in every request.

Three levels of CLAUDE.md files:

  • Project level — shared with your team, committed to source control
  • Local level — personal instructions, not committed (.claude/settings.local.json)
  • Machine level — global instructions applied to all projects

The @ Symbol

Use @filename to mention specific files in your requests. This provides targeted context instead of forcing Claude to search the codebase. For critical files like database schemas, reference them in CLAUDE.md so they are always available.

Memory Mode

Type # followed by a natural language instruction to edit CLAUDE.md files. For example: # Always run tests after modifying API endpoints. This builds up institutional knowledge over time.

Plan Mode and Thinking Mode

Two modes that boost Claude’s performance on complex tasks:

Plan Mode (Shift + Tab twice)

Makes Claude research more files and create a detailed implementation plan before executing. This handles breadth — useful for multi-step tasks that require understanding across the codebase.

Thinking Mode (“Ultra think”)

Gives Claude an extended reasoning budget for complex logic. This handles depth — useful for tricky debugging, intricate algorithms, or subtle architectural decisions.

You can combine both modes for complex tasks. Both consume additional tokens, so use them intentionally.

Custom Commands

Create reusable automation commands accessible via /commandname:

  1. Create a .claude/commands/ folder in your project
  2. Add markdown files — the filename becomes the command name
  3. Write instructions for Claude to follow when the command is invoked
  4. Use $arguments as a placeholder for runtime parameters
  5. Restart Claude Code to activate

Example: .claude/commands/audit.md creates the /audit command. Run it with /audit src/api/ to audit a specific directory.

Use cases include dependency auditing, test generation, security scans, and code style enforcement.

MCP Servers: Extending Claude’s Capabilities

MCP (Model Context Protocol) servers are external tools that give Claude new capabilities beyond file editing and command execution.

Adding an MCP Server

claude mcp add playwright npx @anthropic/mcp-playwright

This adds the Playwright MCP server, enabling Claude to control a browser — navigate pages, take screenshots, click elements, and fill forms.

Permission Management

Initial tool usage requires approval. Auto-approve specific MCP tools by adding them to your settings.local.json allow array:

{
  "allowTools": ["MCP__playwright"]
}

Practical Example

Claude used Playwright to:

  1. Navigate to localhost:3000
  2. Take a screenshot of a UI component
  3. Analyze styling quality
  4. Update generation prompts based on visual feedback
  5. Iterate until the design met quality standards

This transforms Claude from a code editor into a full development automation tool.

Hooks: Automated Guardrails

Hooks are commands that run before or after Claude executes tools. They are the mechanism for enforcing rules, catching errors, and providing automated feedback.

Hook Types

  • Pre-tool use hooks — run before tool execution, can inspect and block operations
  • Post-tool use hooks — run after tool execution, provide feedback but cannot block

Configuration

Add hooks to your Claude settings file:

{
  "hooks": {
    "preToolUse": [
      {
        "matcher": "read|grep",
        "command": "node ./hooks/read_hook.js"
      }
    ],
    "postToolUse": [
      {
        "matcher": "edit",
        "command": "node ./hooks/type_check.js"
      }
    ]
  }
}

Example: Blocking Sensitive File Access

Prevent Claude from reading .env files:

// hooks/read_hook.js
const stdin = await readStdin();
const data = JSON.parse(stdin);

if (data.tool_input?.path?.includes('.env')) {
  console.error('Blocked: cannot read .env files');
  process.exit(2); // Exit code 2 = block
}

process.exit(0); // Exit code 0 = allow

Exit codes:

  • 0 — allow the tool call to proceed
  • 2 — block the tool call (pre-tool use only), stderr output sent as feedback to Claude

Practical Hooks for Production

TypeScript Type Checker Hook: Run tsc --no-emit after file edits. When Claude changes a function signature but misses call sites, the hook catches type errors and feeds them back for automatic correction.

Duplicate Code Prevention Hook: Monitor critical directories (like queries/) for new additions. Launch a separate Claude instance via the SDK to compare against existing code. If duplicates are found, block and redirect Claude to reuse existing implementations.

Both patterns use post-tool-use hooks to create automated feedback loops that catch common weaknesses.

The Claude Code SDK

The SDK provides a programmatic interface for integrating Claude Code into larger pipelines and workflows. Available as CLI, TypeScript, and Python libraries.

Key characteristics:

  • Default permissions are read-only — files, directories, grep operations
  • Write permissions must be explicitly enabled via options.allowTools or settings files
  • Output is conversational — shows the full message exchange with the final response as the last message

Best suited for helper commands, scripts, hooks within existing projects, and CI/CD integration.

GitHub Actions Integration

Claude Code has an official GitHub integration that runs inside GitHub Actions:

Setup

  1. Run /install GitHub app in Claude Code
  2. Install the Claude Code app on your GitHub repository
  3. Add your API key
  4. An auto-generated pull request adds two GitHub Actions workflows

Default Actions

  • Mention support — @claude in issues and PRs to assign tasks
  • PR review — automatic code review on new pull requests

Advanced: MCP in CI/CD

You can integrate MCP servers into GitHub Actions. For example, adding Playwright enables Claude to:

  • Start a development server
  • Visit the app in a browser
  • Test functionality visually
  • Create checklists for verification
  • Verify fixes before approving PRs

All permissions must be explicitly listed — there are no shortcuts for MCP server tools in Actions.

Context Control: Staying on Track

Long conversations accumulate noise. Use these techniques to stay focused:

CommandEffectWhen to Use
EscapeStop current responseRedirect mid-output
Escape + #Stop and add memoryPrevent repeated mistakes
Double EscapeRewind conversationSkip irrelevant debugging history
CompactSummarize historyLong conversations with accumulated clutter
ClearDelete all historySwitching to unrelated tasks

The Compact command is particularly powerful — it summarizes the entire conversation while preserving Claude’s learned knowledge about the current task.

Runtime Guardrails: Claude Code Environment Variables Worth Knowing

Claude Code has two different kinds of limits that are easy to confuse:

  • Account usage limits control how much Claude usage your plan allows over rolling session and weekly windows.
  • Runtime guardrails control what one Claude Code process can do: how many web searches it can make, how many tools or subagents can run in parallel, how deep subagents can nest, and how long MCP calls stay in the foreground.

The second category is configured with environment variables. These are especially useful for long-running research, CI jobs, and heavily agentic workflows where a bad loop can consume a surprising amount of time and context.

The WebSearch session cap

Since Claude Code v2.1.212, built-in WebSearch calls are capped at 200 per session by default. I raised mine to 1000 for research-heavy sessions:

export CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION=1000
claude

CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION accepts a positive whole number. You can raise the cap, but you cannot disable it entirely. Once the limit is reached, later WebSearch calls return a notice telling Claude to continue with the information already collected instead of performing another search.

That makes the variable useful for deep-research sessions and subagent-heavy workflows, but raising it should be intentional. A higher ceiling does not make searches free: it simply allows a session to keep searching longer before the guardrail stops it.

This runtime cap is separate from the Claude Code session and weekly usage limits shown in the Claude Usage screen.

High-value Claude Code runtime variables

VariableDefaultWhat it controls
CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION200Total built-in WebSearch calls allowed in one session. Requires v2.1.212+.
CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY10Maximum number of read-only tools and subagents that can execute in parallel.
CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS20Maximum number of subagents running at once before new spawns are refused. Requires v2.1.217+.
CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH3Maximum nesting depth below the main conversation. Set 1 to prevent subagents from spawning subagents.
CLAUDE_CODE_MAX_TURNSunsetCaps agentic turns when no explicit --max-turns value is passed. The CLI flag takes precedence.
CLAUDE_CODE_MCP_AUTO_BACKGROUND_MS120000Moves a still-running MCP call to a background task after the configured delay. Set 0 to disable automatic backgrounding.
CLAUDE_CODE_DISABLE_WEB_FETCHoffSet 1 to disable WebFetch while leaving WebSearch available. Requires v2.1.285+.
CLAUDE_AUTOCOMPACT_PCT_OVERRIDEunsetTriggers auto-compaction earlier at a percentage from 1–100. It can lower the threshold, not raise it above Claude Code’s default.

One variable to avoid copying from older examples is CLAUDE_CODE_MAX_SUBAGENTS_PER_SESSION. It previously limited total subagent spawns, but it was removed in v2.1.224 and is now a no-op. Use the concurrent-subagent and spawn-depth controls instead.

A practical configuration for research-heavy sessions

For a session that needs more web research while keeping parallelism under control:

export CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION=1000
export CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY=6
export CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS=8
export CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH=2

claude

My persistent user-level configuration lives in ~/.claude/settings.json. You can also scope the same variables to a project with .claude/settings.json:

{
  "env": {
    "CLAUDE_CODE_MAX_WEB_SEARCHES_PER_SESSION": "1000",
    "CLAUDE_CODE_MAX_TOOL_USE_CONCURRENCY": "6",
    "CLAUDE_CODE_MAX_CONCURRENT_SUBAGENTS": "8",
    "CLAUDE_CODE_MAX_SUBAGENT_SPAWN_DEPTH": "2"
  }
}

I use 1000 as a personal ceiling for research-heavy sessions; the official default remains 200. Use user-level settings for personal defaults and project settings when the whole team should inherit the same guardrails. For the complete and version-specific list, use Anthropic’s Claude Code environment variable reference.

My Take

Claude Code represents a shift from “AI that writes code” to “AI that participates in the full development lifecycle.” The combination of tool use, MCP servers, hooks, and the SDK creates a system that can be shaped to fit any team’s workflow.

The hooks system is where it gets really interesting for enterprises. Being able to enforce security policies (block sensitive file access), maintain code quality (type checking), and prevent technical debt (duplicate detection) — all automatically, without relying on developer discipline — is a significant operational improvement.

For teams already running AI workloads on Kubernetes and building agentic workflows, Claude Code’s extensibility model through MCP and hooks maps well to the Agent Client Protocol vision of composable, interoperable AI tooling.

About the Author

I am Luca Berton, AI and Cloud Advisor. I help enterprises integrate AI tools into their development workflows for measurable productivity gains. Book a consultation.

Free 30-min Production AI consultation

Book Now