Skip to content

Tool Guide · Coding

Claude Code Guide

The definitive guide to Anthropic's terminal-native AI coding agent — install, configure, MCP, hooks, skills, sub-agents, plan mode, cost, security, limitations.

16 min readSubscription (Pro $20 / Max $200 / Team / Enterprise) or API-key pay-as-you-goUpdated May 2026
ClaudeCodingAgentCLIMCPHooksSkills
Visit official site
Edited by The AIKnowHub team · Editorial team

Key takeaways

  • 1Native multi-file editing with whole-codebase awareness (Read/Grep/Glob built in)
  • 2Plan mode — proposes a numbered plan before any edit, requires explicit approval
  • 3Sub-agents — spawn focused workers (Explore, code-reviewer, custom) without polluting main context
  • 4Skills — folder-based packages of prompts + scripts Claude invokes by name
  • 5Hooks — shell commands fired on events (PreToolUse, PostEdit, Stop) to enforce conventions
  • 6MCP (Model Context Protocol) — first-class support for Postgres, GitHub, Linear, Slack, Sentry, custom
  • 7Slash commands — built-ins (/cost, /clear, /review, /compact) + your own in .claude/commands/
  • 8Background runs with run_in_background — long tasks (builds, deploys) don't block the loop
  • 9Worktree isolation — agents can work on a detached branch in a temp tree (no main mutation)
  • 10Cost & usage live in /cost; per-session and rolling totals visible
  • 11Model picker — Opus for thinking-heavy work, Sonnet for fast loops, Haiku for low-cost glue
  • 12Settings.json for permissions (allow-listed bash patterns) — explicit, project-scoped

Best for

  • Multi-file refactors that span the whole codebase
  • Migrations: framework upgrades, library swaps, monorepo splits
  • Bug hunts across logs + code + git history
  • Implementing features from a spec + running the test loop until green
  • Onboarding to unfamiliar repos (read everything, write a CLAUDE.md)
  • Production-grade work in repos with real tests and CI
  • Building agents/tools by composing MCP servers + skills + sub-agents

Not for

  • One-line snippets — use editor autocomplete (Cursor, Windsurf, Copilot)
  • Untested repos — the agent has no feedback signal and drifts
  • Pure visual/UX iteration — Cursor or Zed give faster design feedback loops
  • Quick chat-style questions — open claude.ai in a browser instead
  • Anything where you need a real-time visual diff before each save (turn it off, work in plan mode)

What it is

Claude Code is Anthropic's interactive CLI agent — a real coding collaborator that lives in your terminal, reads your repo, edits files, runs commands, and reports back. It isn't a chat window with a "send to editor" button. It's a process that takes natural-language tasks and drives them to completion by calling tools (Read, Write, Edit, Grep, Bash, etc.) under its own control.

If you've used GitHub Copilot, Cursor, or Continue, think of Claude Code as the "agentic" end of that spectrum: less autocomplete, more autonomous engineer. It pairs especially well with strong test suites and clean module boundaries — the more feedback the codebase gives, the better the agent loop runs.

When to reach for it (and when not to)

Reach for Claude Code when:

  • You have a multi-file change with non-trivial coordination across files
  • You need to investigate before you edit (bug hunts, perf audits, security sweeps)
  • You're migrating: framework upgrades, library swaps, monorepo splits
  • You want a feature implemented from a spec, with tests passing as the success criterion
  • You're onboarding to an unfamiliar repo and want a written architecture summary

Don't reach for Claude Code when:

  • The task is a one-line snippet — use editor autocomplete
  • The repo has no tests — Claude is flying blind without feedback signals
  • You need real-time visual feedback on a design (CSS tweaks, layout iteration)
  • You want a quick conversational answer — open claude.ai in a browser

Setup

Install

npm install -g @anthropic-ai/claude-code

You'll need Node.js 18+ and npm. Homebrew and other package managers also ship Claude Code on most platforms.

Authenticate

Run claude from any directory. On first launch it opens a browser to log in with your Claude account. Choose:

  • Subscription auth — uses your Pro / Max / Team quota. Best for daily human-in-the-loop work.
  • API key auth — pay-as-you-go from an Anthropic console key. Better for CI, scripts, and team-shared automations.

You can switch between them later via claude config.

First five minutes

cd ~/code/your-project
claude

Then type your first task. The strongest first move on any new repo:

Read this codebase and create a CLAUDE.md file summarizing the architecture, conventions, test commands, and anything quirky. Save only that file.

Claude will spend a minute reading. You'll end up with a markdown file that future sessions automatically pick up as ambient context. Drop subdirectory CLAUDE.md files inside larger monorepos for area-specific guidance.

The agent loop

Every Claude Code session is a loop:

  1. You give a task (or it continues from the last one).
  2. Claude reads files, runs commands, and writes/edits as needed.
  3. Each tool call surfaces in the terminal — you can approve, deny, or interrupt.
  4. When done (or when it hits a limit it can't resolve), it reports.

What makes it work: Claude treats each tool result as new information and continues planning. A failing test triggers a fix attempt, then a re-run. A missing file triggers a search, then a creation. This is the "agent loop" — most things in Claude Code are tuning how that loop behaves.

Plan mode (the killer feature)

Activate plan mode with the /plan slash command or by prefacing a task with "plan only." Claude then outputs a numbered plan — files to change, in what order, with rationale — and waits for your approval before any edit.

Use plan mode for any change you'd want a code review on. The cost is one extra round-trip; the benefit is catching misunderstandings before they generate a 200-line diff.

> /plan
> Migrate the auth module from Passport to NextAuth.

[Claude outputs a 9-step plan]

> Step 3 should also update the e2e tests. Add that and proceed.

Skills

Skills are folder-based packages Claude can invoke by name. Each skill has a SKILL.md (the instructions) plus optional scripts, templates, and resources.

Example skill structure:

.claude/skills/release-checklist/
├── SKILL.md
├── scripts/
│   └── check-changelog.sh
└── templates/
    └── release-notes.md

Claude reads SKILL.md only when the skill is relevant (matched by description keywords or invoked explicitly). Use skills to capture team-specific procedures: release checklists, code review templates, security audit steps, post-incident routines.

Skills can also live globally at ~/.claude/skills/ for cross-project reuse.

Hooks

Hooks are shell commands fired automatically on session events:

  • PreToolUse — before any tool call. Often used to gate destructive operations or run pre-flight checks.
  • PostToolUse — after a tool call. Auto-format, auto-test, or notify.
  • Stop — when the session ends. Save a summary, push commits, ping Slack.

Configure in .claude/settings.json:

{
  "hooks": {
    "PostToolUse": [
      {
        "matcher": "Edit|Write",
        "hooks": [{ "type": "command", "command": "npm run lint --silent --fix" }]
      }
    ]
  }
}

A typical pattern: PostEdit auto-runs prettier + eslint --fix, and PreCommit runs the test suite. The agent then sees any test failures in its own loop and tries to fix them.

Sub-agents

Sub-agents are focused workers spawned via the Agent tool. They run in their own context, do one job, and return a summary. The main thread sees only the summary — keeping context lean.

Three patterns where sub-agents shine:

  1. Explore — "find every usage of X across the codebase, return file:line list"
  2. Code review — "review this PR diff for security and correctness, return a punch list"
  3. Specialized agents — custom sub-agents you define in .claude/agents/ for recurring tasks

Sub-agents can also run in worktree isolation (isolation: "worktree") so their changes don't touch your main checkout until you merge them in.

MCP (Model Context Protocol)

MCP is how Claude Code plugs into your stack. An MCP server exposes tools that Claude can call — Postgres queries, GitHub PRs, Sentry issues, Linear tickets, Slack messages, anything.

Install MCP servers in .claude/mcp.json:

{
  "mcpServers": {
    "github": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-github"],
      "env": { "GITHUB_TOKEN": "ghp_..." }
    },
    "postgres": {
      "command": "npx",
      "args": ["-y", "@modelcontextprotocol/server-postgres", "postgresql://..."]
    }
  }
}

Once installed, Claude can query Postgres, open PRs, file Linear tickets, and so on — without you ever leaving the terminal. The MCP registry has dozens of servers; write your own when none fits.

Slash commands

Built-in:

  • /cost — current session cost + rolling totals
  • /clear — wipe the context (start fresh, keep settings)
  • /compact — summarize long history into a compact form (saves tokens, keeps gist)
  • /review — structured code review on the current branch diff
  • /model — switch model (Opus / Sonnet / Haiku) mid-session
  • /plan — toggle plan mode
  • /help — list all commands

Custom: drop a markdown file in .claude/commands/ and the filename becomes a slash command. The body is the prompt template.

.claude/commands/refactor-tests.md
─────────────────────────────────
Find all test files in the touched directory, refactor them to use the new test helper at src/test/helper.ts, and run the suite.

Now /refactor-tests runs that prompt anywhere in the repo.

Cost discipline

Heavy agent sessions cost real money. Tactics that work:

  1. Default to Sonnet. Opus only for design work, hard debugging, or thinking-heavy tasks. /model sonnet is the right starting point.
  2. /clear between unrelated tasks. Token cost grows roughly linearly with conversation length — fresh context is the cheapest context.
  3. /compact when context gets long. Compresses the history into a summary without losing the important threads.
  4. Use sub-agents for searches. A sub-agent that returns "found in 4 files: a.ts, b.ts, c.ts, d.ts" costs less than dumping all four files into your main context.
  5. Check /cost at the start of each new task. Builds the habit; surprises don't accumulate.

The Pro plan ($20/mo) covers most solo daily work. The Max plan ($200/mo) raises caps significantly — worth it for engineers running multi-hour agent sessions every day. API-key mode is pay-per-token; use it for one-off jobs or CI.

Security & sandboxing

Claude Code is powerful — give it real bash access and you should think about blast radius.

  • .claude/settings.json permissions. Set an allow-list of bash patterns. Anything outside requires explicit consent in the session.
  • Never expose production credentials. Use scoped DB users, read-only API tokens, or local dev secrets. Treat any session as if a junior engineer were typing — same precautions.
  • Worktree isolation for risky changes. Sub-agents can run in detached git worktrees so their edits don't touch your main checkout until you review and merge.
  • Don't use --dangerously-skip-permissions on a host machine. Reserve it for disposable Docker containers.
  • Read MCP server source before installing. Community MCP servers are arbitrary processes with access to your filesystem and network.

Honest limitations

  • Bad without tests. Without a feedback signal, the agent guesses. It will look like it's working — green checks, confident summaries — and you'll find the bugs in code review. Invest in tests before you invest in heavy Claude Code use.
  • Cost can balloon on long sessions. /cost is your friend; don't let it sit in the background unchecked.
  • Less visual. You give up the GUI diff workflow that Cursor and editor-bound tools give for free. Pair Claude Code with a GUI editor side-by-side for the best of both.
  • Subagent failures cascade. If a sub-agent returns garbage, the main thread acts on garbage. Read the summaries — don't just approve everything.
  • MCP server quality varies. Some are rock-solid (the official ones from Anthropic, GitHub, Linear). Others are community experiments — test them in throwaway repos first.

When it shines vs alternatives

  • vs Cursor: Claude Code wins on long agent loops, MCP depth, scripting, and CI. Cursor wins on editor-time autocomplete and visual diff workflows. Most engineers use both — Cursor when typing, Claude Code when delegating.
  • vs Codex (OpenAI): Claude Code is terminal-first and synchronous; Codex Cloud is delegation-first ("kick off a task, come back to a PR"). Use Claude Code for interactive deep work and Codex Cloud for parallelizable background tasks.
  • vs Aider: Aider was the original terminal AI coder and is excellent. Claude Code has more ecosystem now (MCP, hooks, skills, sub-agents) and a polished Anthropic-backed support story, but Aider remains a clean, model-agnostic, lightweight option.
  • vs Continue: Continue lives inside VS Code as an extension; Claude Code is a standalone CLI. Different homes, similar agent goals.

Pairs well with

  • A clean, fast test suite (Vitest, Jest, pytest — whatever runs in seconds).
  • A monorepo or codebase with clear module boundaries.
  • The MCP servers for your stack (Postgres, Linear, GitHub, Sentry, your own).
  • A pre-commit hook setup that enforces lint/format/test gates.
  • A second GUI editor open side-by-side for diff review.

Next steps

  • Read the Claude Code docs for the canonical reference.
  • Browse the MCP server registry and install one for your stack.
  • Write a CLAUDE.md for your current project — best ROI of any 10-minute task.
  • Set up PostEdit hooks for lint + test so your agent loops self-correct.
  • Try plan mode on your next non-trivial change.

Pros and cons

Pros

  • Strongest agent loop on the market in 2026 — fewest 'lost the plot' failures
  • Composable: CLI fits any workflow (background jobs, CI, scripts, Makefiles)
  • MCP + hooks + skills + sub-agents = real extensibility, not marketing pixels
  • Plan mode is the killer feature for production-grade work — explicit consent before edits
  • First-party security model: tool permissions, sandboxed bash, worktrees
  • Honest cost visibility built in via /cost; no surprises at month end
  • Backed by the Claude model family — Opus 4.7 / Sonnet 4.6 / Haiku 4.5 picker

Cons

  • Token costs add up fast on long agent sessions — needs deliberate /clear and /compact discipline
  • Steeper learning curve than IDE-bundled tools (it's a real CLI, not a chat box)
  • No native GUI diff — you rely on terminal output or pair it with a GUI editor
  • Works best in well-tested repos; degrades fast without test signals
  • Some MCP servers are still flaky in the wild — vet before depending on them
  • Subscription gating: API-key mode exists but Pro/Max plans give better economics for daily use

Real workflows using this tool

Prompt examples

Copy any of these, replace the placeholders, run.

Onboard Claude to a new repo

Read this codebase and create a CLAUDE.md at the root.

Include:
- 2-paragraph architecture summary
- Conventions to respect (naming, testing, commit style, branch policy)
- Where the main entry point and config files live
- A "How we run tests" section with the actual commands
- A "Quirks" section — anything that doesn't follow convention (call it out, don't fix)

Save only CLAUDE.md. Do not modify other files.

Plan-first refactor (consent before edit)

I want to refactor {{module}} to {{goal}}.

Before changing any code:
1. Read the existing module and every file that imports it.
2. Output a numbered plan: file → exact change (under 12 steps).
3. Flag risks, assumptions, and any tests that will need to change.
4. Wait for my explicit approval before editing anything.

Bug investigation (diagnose, don't fix)

Investigate this bug: {{symptom}}.

DO NOT propose a fix yet. Report:
- Where the symptom likely originates (file:line ranges with confidence)
- Whether the bug is reproducible from any existing test
- Top 3 hypotheses, most-likely first, each with a one-line check to verify
- What I should add to a CLAUDE.md so this doesn't recur

Migration sweep (large refactor)

Migrate this repo from {{old}} to {{new}}.

Phase 1: Read the codebase. Find every usage of {{old}}. Group by pattern.
Phase 2: For each pattern group, write a sample migration in plan-mode output.
Phase 3: I'll approve groups one by one. For each approved group:
  - Apply the migration in a new commit per group
  - Run tests
  - If failing, fix and re-run
  - Stop and report when green

Use sub-agents (Explore) for the find phase to keep my context lean.

Review your own diff

Run /review on the staged changes.

Score against:
- Correctness vs the original task
- Test coverage (gaps?)
- Naming + style consistency with CLAUDE.md
- Security: any new external input not validated?
- Risk: anything reversible vs irreversible?

If anything is below bar, fix it in this same session. Don't leave TODOs.

Add CI gate via hooks

Set up a PreToolUse hook that runs npm test before any Edit tool call.

If tests fail, the hook should block the edit and surface the failing output. Document the hook in CLAUDE.md.

Also: a PostToolUse hook that runs npm run lint --fix after every Edit. Don't block on lint warnings — just auto-fix.

Spin up an MCP-driven debugging loop

Add the Sentry MCP server and the Postgres MCP server to my .claude/mcp.json. Then:

1. Pull the latest 5 unresolved Sentry issues for project {{key}}
2. For each, query Postgres for the user/org context
3. Cross-reference with the relevant code paths
4. Prioritize: severity × user count × time-to-fix estimate
5. Output a triaged list as a Linear-ready CSV

Alternatives

Cursor agent modeOpenAI Codex (codex CLI)AiderContinueZed AIWindsurf Cascade

Frequently asked questions

Yes for daily use — Pro ($20/mo), Max ($200/mo), Team, or Enterprise. Pro is enough for most solo work; Max removes effective rate limits and unlocks the latest Opus thinking budget. You can also run with an Anthropic API key (pay-as-you-go) — useful for CI/automation, but for human-in-the-loop coding the subscription is usually cheaper.

Watch

Hand-picked videos from official + trusted channels. Opens in a new tab.