Claude Code Context Install (2026): A Complete Setup and Context Engineering Guide for Engineers
You’ve heard the hype. You’ve seen the demos. And then you actually tried to install Claude Code, get it pointed at your codebase, and have it do something useful — and hit a wall.
Maybe npm install -g @anthropic-ai/claude-code worked but the tool ignored your project structure. Maybe your CLAUDE.md got too long and the model started behaving strangely. Maybe you watched a subagent spawn and silently fail without any useful error.
This guide cuts through all of that. It covers the full path from a clean machine to a productive Claude Code workflow: install steps, CLAUDE.md architecture, context budgeting, hooks, and the subagent model — with concrete examples at each stage.
TL;DR
Claude Code is Anthropic’s terminal-based AI coding agent, installed via npm and authenticated with an Anthropic API key. The two biggest productivity levers aren’t in the install — they’re in (1) authoring a well-structured CLAUDE.md file that gives the model persistent context, and (2) understanding how context windows fill up so you don’t hit invisible limits mid-task. By the end of this guide, you’ll have a working install, a reusable CLAUDE.md template, and a mental model for the context engineering decisions that separate productive Claude Code users from frustrated ones.
Quick answer: Install with npm install -g @anthropic-ai/claude-code, run claude in your project root, and create a CLAUDE.md file there to give the model persistent project context. That’s the minimum viable setup.
Why Context Engineering Is the Real Learning Curve
Most engineers get the install right on the first try. The friction comes later — usually within the first hour of serious use.
GitHub Issues and community discussions consistently surface three pain points:
1. CLAUDE.md setup and context size limits. Engineers write a thorough CLAUDE.md — architecture decisions, coding conventions, environment variables, dependency notes — and then discover that Claude Code’s context window has a hard limit. Long CLAUDE.md files eat into the budget for actual code. The model starts losing track of earlier instructions. Tasks that worked yesterday start producing worse output today because the codebase grew and the context filled up.
2. Install steps on macOS and Linux. The npm install is straightforward, but first-time users frequently hit issues with Node version requirements, global npm permission errors on macOS, and PATH issues in non-standard shell setups (fish, zsh with unusual configs, or nix-managed environments).
3. Understanding subagents and hook configuration. Claude Code can spawn subagents — specialized instances that run subtasks in parallel or in sequence. This is powerful, but the failure modes are opaque. Hooks let you run pre/post commands around agent actions, but the configuration syntax isn’t obvious, and mistakes produce silent failures rather than clear errors.
None of these are blockers. They’re configuration problems with known solutions. Let’s work through all three.
Step 1: Install Claude Code
Prerequisites
Claude Code requires Node.js 18 or higher. Check your version:
node --version
If you’re below 18, update via nvm (recommended) or the official Node.js installer:
nvm install 20
nvm use 20
You also need an Anthropic API key. Claude Code calls the API directly — there’s no separate subscription at the tool level, but you’re billed for API usage per token.
Install the Package
npm install -g @anthropic-ai/claude-code
Fixing Permission Errors on macOS
If you hit EACCES: permission denied on a system-managed npm, don’t use sudo npm install -g. Instead, configure npm to use a user-writable directory:
mkdir -p ~/.npm-global
npm config set prefix '~/.npm-global'
echo 'export PATH=~/.npm-global/bin:$PATH' >> ~/.zshrc
source ~/.zshrc
npm install -g @anthropic-ai/claude-code
Installing on Linux
The same pattern applies on Linux. If you’re using a package-manager-installed Node (apt, dnf), consider switching to nvm to avoid permission issues:
curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
source ~/.bashrc
nvm install 20
npm install -g @anthropic-ai/claude-code
Authenticate
Set your API key as an environment variable. The recommended approach is adding it to your shell profile so it persists:
export ANTHROPIC_API_KEY="sk-ant-..."
Add this line to ~/.zshrc, ~/.bashrc, or ~/.profile depending on your shell.
Alternatively, Claude Code will prompt you for the key on first run and store it in its local config.
Verify the Install
claude --version
Then run it for the first time:
cd your-project-directory
claude
You’ll drop into an interactive session. Claude Code reads your current directory automatically. Type a question about your codebase to confirm it’s reading files correctly.
The official Claude Code documentation covers additional install options including enterprise proxy configurations.
Step 2: Understand the Context Window
Before writing a single line of CLAUDE.md, you need to understand what you’re working with.
Claude Code uses Claude models under the hood. The context window — the total amount of text the model can “see” at once — has a fixed token budget. Everything counts against it:
- The contents of your CLAUDE.md file
- The current conversation history
- Files the agent reads during a task
- Subagent outputs that get pulled back into the main session
- Tool call results (bash output, file reads, search results)
The window doesn’t scroll. Once it fills, older content gets truncated — and the model has no memory of it. This is the most common source of degraded performance mid-session.
Practical Implications
A CLAUDE.md file that reads like a comprehensive internal wiki — 3,000 tokens of architecture notes — leaves 197,000 tokens for the actual task on a 200k-context model. That sounds fine until the agent starts reading large source files, generating long diffs, and chaining tool calls. Context pressure builds fast.
The right mental model: CLAUDE.md is a context allocation decision, not a documentation exercise. Every sentence you add competes with actual code.
Monitoring Context Usage
Claude Code shows a context usage indicator in the UI. Pay attention to it during long sessions. When the indicator shows high usage, start a fresh session rather than pushing through — response quality degrades noticeably as context fills up.
Step 3: Write an Effective CLAUDE.md
CLAUDE.md is a markdown file placed at your project root (or at ~/.claude/CLAUDE.md for global settings). Claude Code reads it at the start of every session, making it the primary mechanism for persistent context.
What Belongs in CLAUDE.md
The goal is to give the model the information it couldn’t infer from reading your code — constraints, conventions, and environment facts.
High-value content:
## Tech Stack
- Backend: Python 3.11, FastAPI
- Database: PostgreSQL 15, SQLAlchemy 2.x with async sessions
- Testing: pytest, factory_boy for fixtures
- Deploy target: AWS Lambda (container image, not zip)
## Code Conventions
- All database queries go in `src/repositories/`, not in route handlers
- Use `src/services/` for business logic
- Type hints required on all public functions
- Error handling: raise domain exceptions from services, convert to HTTP responses in routes
## Environment
- Local dev: Docker Compose (`docker-compose up`)
- `.env.example` shows required vars — copy to `.env`, never commit `.env`
- Database migrations: `alembic upgrade head`
## What NOT to Do
- Never use synchronous SQLAlchemy calls in async route handlers
- Don't put business logic in Pydantic models
- Don't modify migrations that have already been applied to staging
Low-value content to avoid:
- Project history (“we used to use Django but switched in 2023”)
- Aspirational statements (“we aim for full test coverage”)
- Information the model can read from package.json, pyproject.toml, or README
- Lengthy API documentation for libraries the model already knows
Layered CLAUDE.md Strategy
For large codebases, use a hierarchy:
project-root/
├── CLAUDE.md # Top-level: stack, conventions, critical constraints
├── src/
│ ├── api/
│ │ └── CLAUDE.md # API-specific rules, route conventions
│ └── workers/
│ └── CLAUDE.md # Worker-specific patterns, retry logic
Claude Code reads subdirectory CLAUDE.md files when it navigates into those directories. This keeps top-level context tight while providing depth where needed.
CLAUDE.md Size Budget
A practical ceiling is 500-800 tokens for a top-level CLAUDE.md (roughly 400-600 words). Beyond this, you’re paying a fixed per-session tax for diminishing returns. If your CLAUDE.md is growing beyond this, it’s a signal to move documentation into code comments, README sections, or subdirectory CLAUDE.md files.
Check your CLAUDE.md token count with any tokenizer. Anthropic’s tokenizer documentation covers the approach for Claude models.
Step 4: Structure Your Workflow
Claude Code works best when you treat it as a collaborator that handles discrete, well-defined tasks — not as an autopilot you set running on an entire feature.
Effective Task Framing
Weak prompt:
Refactor the authentication module.
Strong prompt:
Refactor src/auth/jwt_handler.py to use the jose library instead of PyJWT.
- The function signatures in auth/jwt_handler.py must not change (other modules depend on them)
- Update requirements.txt
- Run existing tests and show me the output
- Don't touch src/auth/oauth.py
The more specific you are about scope and constraints, the less context gets consumed by clarifying back-and-forth, and the less likely the model is to make changes you didn’t intend.
Session Discipline
Start a fresh Claude Code session for each distinct task. Don’t carry a session through “fix the bug → write the tests → update the docs → refactor the related module” in one sitting. Each task boundary is an opportunity to reset context and start clean.
For multi-step workflows that genuinely need continuity, use Claude Code’s memory features — storing important intermediate results in files and having the model read them back at the start of the next step.
Step 5: Configure Hooks
Hooks run shell commands before or after specific Claude Code actions. They’re the mechanism for integrating Claude Code into your existing toolchain — running linters before the model commits code, triggering test suites after file writes, or logging agent activity.
Hook Configuration
Hooks are configured in ~/.claude/settings.json (global) or .claude/settings.json (project-local):
{
"hooks": {
"PreToolUse": [
{
"matcher": "Bash",
"hooks": [
{
"type": "command",
"command": "echo 'About to run bash command'"
}
]
}
],
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "cd $PROJECT_ROOT && npm run lint --silent"
}
]
}
]
}
}
Common Hook Patterns
Run tests after file writes:
{
"hooks": {
"PostToolUse": [
{
"matcher": "Write",
"hooks": [
{
"type": "command",
"command": "cd $PROJECT_ROOT && pytest tests/ -q --tb=short 2>&1 | tail -20"
}
]
}
]
}
}
Format code before the model sees it:
{
"hooks": {
"PreToolUse": [
{
"matcher": "Read",
"hooks": [
{
"type": "command",
"command": "cd $PROJECT_ROOT && black --check . --quiet || true"
}
]
}
]
}
}
Hook Debugging Tips
Hook failures are logged but don’t always surface clearly in the UI. If a hook seems to be silently failing:
- Test the command manually in your terminal first
- Use absolute paths or
$PROJECT_ROOT— relative paths in hooks can fail depending on the working directory - Add
2>&1to capture stderr - Keep hook commands fast — slow hooks block the agent and burn context on waiting
See the hooks documentation for the complete event list and configuration reference.
Step 6: Work With Subagents
Claude Code can spawn subagents — separate agent instances that handle subtasks and return results to the main session. This enables parallelism and specialization, but adds complexity.
When Subagents Help
Subagents are useful when a task has genuinely independent components:
- Running a test suite while the main agent continues writing code
- Analyzing multiple files in parallel before synthesizing conclusions
- Delegating a well-defined subtask (e.g., “write unit tests for this module”) while the main session handles the implementation
When Subagents Hurt
Subagents consume context. Each subagent spawns its own session, does work, and returns output — that output then gets pulled back into the main session’s context window. A subagent that reads large files and produces verbose output can significantly accelerate context exhaustion.
Don’t use subagents for:
– Tasks where the subtask output will be large and mostly irrelevant
– Simple sequential tasks that don’t benefit from parallelism
– Cases where you need tight control over what the model does step by step
Monitoring Subagent Behavior
Claude Code surfaces subagent activity in its output. When a subagent completes, review what it actually did — the model’s summary of subagent work can omit important details. If a subagent touched files you didn’t expect, check git diff.
The Claude Code subagents documentation covers the full API for configuring custom subagent behaviors.
Common Mistakes to Avoid
-
Writing CLAUDE.md as documentation, not instructions. The model doesn’t need project history or aspirational goals. It needs constraints, conventions, and facts it can’t infer from the code itself.
-
Running long sessions without checking context usage. Performance degrades before the context limit is hit. Monitor the indicator; restart sessions proactively.
-
Using vague task descriptions. “Fix the authentication bug” forces the model to explore broadly, burning context on investigation. Narrow the scope: “The JWT expiry check in
src/auth/jwt_handler.pyline 47 is comparing timestamps incorrectly — fix it and update the test intests/test_jwt.py.” -
Ignoring hook stderr. Hooks that fail silently are worse than no hooks — they create a false impression that the step ran. Always capture stderr in hook commands.
-
Treating subagent output as authoritative. Subagents can hallucinate or make mistakes just like the main agent. Review their output, especially when they make file changes.
Quick Reference
| Task | Command / Action |
|---|---|
| Install Claude Code | npm install -g @anthropic-ai/claude-code |
| Set API key | export ANTHROPIC_API_KEY="sk-ant-..." in shell profile |
| Start a session | cd your-project && claude |
| Global CLAUDE.md location | ~/.claude/CLAUDE.md |
| Project CLAUDE.md location | {project-root}/CLAUDE.md |
| Project settings/hooks | .claude/settings.json |
| Global settings/hooks | ~/.claude/settings.json |
| Check context usage | UI indicator during session |
| Recommended CLAUDE.md size | 500-800 tokens (~400-600 words) |
| Node.js minimum version | Node 18+ (Node 20 LTS recommended) |
| Official docs | docs.anthropic.com/en/docs/claude-code |
| Claude Code homepage | claude.ai/code |
CLAUDE.md Minimal Template
## Stack
- [Language/runtime version]
- [Framework and version]
- [Database]
- [Test runner]
## Project Structure
- [Key directory conventions, e.g., "business logic in src/services/"]
## Code Conventions
- [Style rules not enforced by linter]
- [Naming conventions]
- [Error handling patterns]
## Environment
- [How to run locally]
- [Key environment variables]
- [Migration or seed commands]
## Constraints
- [What the model must NOT do]
- [Files/directories to leave alone]
FAQ
Q: What Node.js version does Claude Code require?
Claude Code requires Node.js 18 or higher. Node 20 LTS is the recommended version for stability. Check your current version with node --version. If you need to manage multiple Node versions, nvm is the most reliable tool on both macOS and Linux — it avoids the permission issues that come with system-level Node installs and makes version switching simple.
Q: How big should my CLAUDE.md file be?
Aim for 500-800 tokens, roughly 400-600 words. CLAUDE.md content is loaded at the start of every session and counts against the context window for the entire session. A 2,000-token CLAUDE.md isn’t catastrophic on a 200k-context model, but it’s a fixed overhead that compounds with long sessions and large files. Prioritize constraints and conventions the model can’t infer from reading your code. Move general documentation to README or inline comments.
Q: Why does Claude Code perform worse later in a long session?
Context pressure. The context window is fixed — as the session accumulates conversation history, tool call results, and file contents, older information gets truncated. The model loses access to earlier instructions and context. This isn’t a bug; it’s a fundamental property of how transformer models work. The mitigation is session discipline: start a fresh session for each distinct task, and use files to pass state between sessions rather than relying on the model to remember earlier conversation.
Q: Can I use Claude Code on Linux?
Yes. The install process is identical — Node 18+, npm install -g @anthropic-ai/claude-code, set ANTHROPIC_API_KEY. The main gotcha on Linux is Node permission issues when using a system package manager. Use nvm to install Node in user space to avoid EACCES errors on global npm installs. Claude Code’s file access and bash tool work the same on Linux as on macOS.
Q: What’s the difference between global and project-level CLAUDE.md?
Global CLAUDE.md (~/.claude/CLAUDE.md) applies to every Claude Code session regardless of which project you’re in. Use it for personal preferences — your preferred coding style, how you want the model to communicate, global toolchain facts. Project CLAUDE.md ({project-root}/CLAUDE.md) applies only when Claude Code runs in that directory tree. Use it for project-specific conventions, stack details, and constraints. When both exist, Claude Code reads both — global first, then project-level — so project settings can override or extend global ones.
Q: How do I debug a hook that isn’t working?
Three steps: (1) Run the hook command manually in your terminal from the same directory Claude Code would use — if it fails there, it’ll fail in the hook. (2) Add 2>&1 to the command to capture stderr, which often contains the actual error. (3) Use absolute paths or the $PROJECT_ROOT environment variable rather than relative paths — the working directory in hook execution can be different from what you expect. Hook output appears in Claude Code’s session log; check there for command exit codes.
Where to Go From Here
The Claude Code documentation covers the full feature set, including the settings schema, all available hook events, and the subagent API. The GitHub repository has open issues that reflect real-world friction points — useful reading for understanding edge cases and current limitations.
The most productive Claude Code users tend to share one trait: they treat context as a finite resource and make deliberate decisions about how to spend it, rather than assuming the model will figure things out from a firehose of information. That discipline, more than any specific config, is what separates frustrating sessions from productive ones.
Start with a clean install, a tight CLAUDE.md, and a single well-scoped task. Build from there.

답글 남기기