The Agent Machine
Field manual · Claude Code & Claude Agent SDK

The Agent Machine

How Claude Code turns a model into a working agent: one loop, a belt of tools, a context window to manage, and a set of extension points you can build on with the Agent SDK.

Model Harness Tools Extensions & hooks MCP Permissions
Open Agent Lab Interactive course: lessons, simulators and adaptive checks
Read · Glob · Grep Bash Edit · Write MCP WebFetch Agent Tests Skills 1 · Gather context 2 · Take action tool calls 3 · Verify tests, lint, look Claude decides the next step stop_reason: tool_use ↻ end_turn ⏹
1 loopmodel → tool call → result → model, until the task ends
~15built-in tools, plus any MCP server you connect
8extension points: memory, commands, skills, subagents, hooks, MCP, plugins, output styles
2 SDKsPython claude-agent-sdk and TypeScript @anthropic-ai/claude-agent-sdk
Layer map

Six layers, one harness in the middle

Claude Code is a harness around the model. The model only produces text and tool calls; the harness assembles context, routes tool calls, enforces permissions, fires hooks and manages the session. The Agent SDK exposes that same harness as a library.

Surfaceswhere a person or program talks to it
Terminal CLIDesktop appWeb (claude.ai/code)VS Code · JetBrainsSlackGitHub Actionsclaude -p (headless)Agent SDK
Harnessthe agent runtime
Agent loopContext assemblerTool routerPermission engineHook busSession store · resume · forkAuto-compactionCheckpoints · rewind
Extensionswhat you add on top
CLAUDE.md memorySlash commandsSkillsSubagentsHooksPluginsOutput stylessettings.json
Toolsthe agent's hands
Read · Write · EditGlob · GrepBash · background tasksWebFetch · WebSearchAgent (subagents)TodoWritemcp__server__tool
Modelreasoning + tool choice
Claude via Messages APIadaptive thinkingeffort: low → maxprompt cachingparallel tool callsBedrock · Vertex · Foundry
Environmentwhat tools act on
Working directoryShell & processesGit · worktreesNetworkOS sandboxContainers · CI runners
Anatomy of a turn

What happens between Enter and the answer

Every user message starts a run of the loop. The colored tag on each step says who is in charge at that moment: the harness, the model, a tool, a hook you wrote, or the permission engine.

hook

Prompt submitted

UserPromptSubmit hooks can add context or block the prompt before Claude sees it.

harness

Context assembled

System prompt, tool schemas, CLAUDE.md files, skill descriptions, conversation so far.

model

Claude reasons

Thinks, writes text, and emits one or more tool_use blocks in parallel.

hook

Pre-tool check

PreToolUse can allow, deny, ask, or rewrite the tool input.

permission

Permission gate

deny → ask → allow rules and the current mode decide; the user may be prompted.

tool

Tool executes

Edits a file, runs a command, queries an MCP server, or spawns a subagent.

hook

Post-tool

PostToolUse runs formatters or linters and can feed findings back.

harness

Result appended

tool_result joins the transcript; the loop calls the model again.

Repeat steps 03–08 until Claude ends its turn; then Stop hooks run and may send it back to work.
Context window

The one resource every design decision spends

Everything the agent knows in a turn has to fit in its context window. Tool output fills it fastest. Claude Code compacts the conversation automatically as it nears the limit, and subagents, skills and deferred tools exist largely to keep it lean.

auto-compact zone
0%25%50%75%100% of window

Illustrative proportions for a mid-session coding task, not a measurement. Run /context in Claude Code to see your own breakdown.

System promptHarness instructions, environment, output style
Built-in tool schemasNames, descriptions, JSON input schemas
MCP toolsGrows with every server; tool search can defer them
Memory & skillsCLAUDE.md contents and one-line skill descriptions
ConversationYour messages and Claude's replies
Tool resultsFile reads, command output, search hits: the biggest consumer
/compact

Summarize history into a short brief and keep going. Happens automatically near the limit; PreCompact hooks fire first.

/clear

Start fresh for an unrelated task. CLAUDE.md reloads; the old transcript can still be resumed.

Subagents

Do heavy reading in a separate window and return only a summary to the main thread.

Prompt caching

The stable prefix (system, tools, memory) is cached, so long sessions stay fast and cheaper.

Tool belt

Built-in tools, grouped by job

Each tool is a schema the model sees and a function the harness runs. Purpose-built file tools beat shelling out: they are faster, permission-aware, and produce compact output.

Files
  • Readfiles, images, PDFs, notebooks
  • Writecreate or replace a file
  • Editexact string replacement
  • NotebookEditJupyter cells
Search
  • Globfind files by pattern
  • Grepripgrep content search
  • LSP / code intelwhere an IDE or plugin adds it
Execute
  • Bashshell commands with timeouts
  • Background taskslong jobs, dev servers
  • Monitorwatch output until a condition
Web & MCP
  • WebFetchread a URL as text
  • WebSearchsearch the web
  • mcp__srv__toolany connected MCP tool
Orchestrate
  • Agentspawn a subagent (formerly Task)
  • TodoWritevisible task list
  • Skillload a skill on demand
  • AskUserQuestionstructured question

Tool names and the exact set vary by version and surface. In the SDK, the allowed_tools / disallowed_tools options choose which ones the agent gets.

Extension points

Eight ways to shape the agent

The key difference between them is who pulls the trigger. Memory is always loaded. Skills and subagents are chosen by the model. Commands are typed by you. Hooks are fired by the harness, every time, without the model deciding.

ExtensionWhat it isLives inTriggered byContext cost
CLAUDE.mdStanding instructions: build commands, conventions, project facts. Supports @path imports../CLAUDE.md · ~/.claude/CLAUDE.md · managed policyalways loaded
Slash commandsReusable prompts with $ARGUMENTS, invoked as /name..claude/commands/*.mdyou type it
SkillsFolders of instructions, scripts and references the model loads when relevant..claude/skills/<name>/SKILL.mdmodel decides
SubagentsSpecialists with their own prompt, tool list, model and fresh context window..claude/agents/*.mdmodel delegates
HooksShell commands (or prompts) run on lifecycle events; deterministic guardrails.settings.json → hooksharness event
MCP serversExternal tools, resources and prompts over the Model Context Protocol..mcp.json · claude mcp addmodel calls tool
PluginsInstallable bundles of commands, agents, skills, hooks and MCP servers, shared via marketplaces..claude-plugin/plugin.jsoninstalled once
Output stylesReplace the coding-focused parts of the system prompt to repurpose the agent..claude/output-styles/*.mdalways loaded
Delegation & progressive disclosure

Subagents split the work. Skills defer the knowledge.

Subagents: separate windows, summary back

The main agent calls the Agent tool with a brief. Each subagent runs its own loop in a fresh context, with its own tools and model, and returns one final message. Independent subagents can run in parallel.

Main agent holds the plan explorer Read · Grep · Glob model: haiku test-runner Bash · Read model: sonnet reviewer Read · Grep model: inherit — brief down - - summary back
# .claude/agents/reviewer.md
---
name: reviewer
description: Reviews diffs for bugs. Use after edits.
tools: Read, Grep, Glob
model: sonnet
---
You are a careful code reviewer. Report only
real defects, each with file:line and a fix.

Skills: three levels of loading

A skill costs almost nothing until it is needed. Only its name and description sit in context; the body loads when Claude decides the skill applies, and bundled files load only when the body points to them.

L1
Metadata, alwaysYAML name + description, roughly a sentence per skill.
L2
SKILL.md body, on triggerStep-by-step instructions, loaded when the task matches.
L3
Resources, on demandReference docs, templates and scripts; scripts can run without being read.
# .claude/skills/release-notes/SKILL.md
---
name: release-notes
description: Write release notes from git log.
  Use when asked for a changelog or release.
---
1. Run scripts/collect.sh to list merged PRs.
2. Group by feat / fix / chore.
3. Follow the tone in reference/style.md.
Hook lifecycle

Hooks: code that always runs

Instructions in a prompt are followed most of the time. A hook runs every time. Use hooks for anything that must happen: formatting after edits, blocking dangerous commands, logging, notifications. Pick an event to see what it can do.

exit 0Success. Stdout may become added context for some events.
exit 2Blocking error. Stderr goes back to Claude and the action is stopped.
JSON outFine-grained control: permissionDecision, decision: "block", additionalContext.
// .claude/settings.json — format every file Claude edits
{
  "hooks": {
    "PostToolUse": [{
      "matcher": "Edit|Write",
      "hooks": [{ "type": "command", "command": ".claude/hooks/format.sh" }]
    }]
  }
}
// the hook receives the event as JSON on stdin: session_id, tool_name, tool_input, …
Permissions & settings

How much the agent may do on its own

Autonomy is a dial. Permission modes set the default posture; rules fine-tune it per tool and per argument pattern; a sandbox can bound what Bash can reach on disk and network.

plan

Read and research only. Claude proposes a plan and edits nothing until you approve.

default

Asks the first time each kind of action needs approval.

acceptEdits

File edits go through; other risky actions still ask.

auto

A classifier approves routine actions and stops risky ones.

bypassPermissions

No prompts. Only for isolated containers and throwaway VMs.

more oversightmore autonomy

Rules are checked deny → ask → allow

deny · wins first"Bash(rm -rf:*)", "Read(./.env)"

Never allowed, whatever the mode or other rules say.

ask"Bash(git push:*)", "WebFetch"

Always prompts, even if an allow rule would match.

allow"Bash(npm run test:*)", "Edit(src/**)"

Runs without asking. Prefix and glob patterns keep it narrow.

Settings precedence, highest first

Managed policyset by an organization, cannot be overridden
Command-line flags--model, --permission-mode, --allowedTools
Local project.claude/settings.local.json (git-ignored)
Shared project.claude/settings.json (committed)
User~/.claude/settings.json

CLAUDE.md memory follows a similar layering: organization, user, project, and subdirectory files read on demand.

Model Context Protocol

MCP: a universal port for tools

Claude Code is an MCP client. Any MCP server, whether local or remote, can add tools, resources (referenced with @) and prompts (which appear as slash commands). In the SDK you can also define a server in-process, with no subprocess at all.

Claude Code MCP client tools appear as mcp__server__tool stdio HTTP in-process Local processnpx / uvx server · database · files Remote serviceGitHub · Sentry · Linear · OAuth SDK custom toolscreate_sdk_mcp_server() in your app Scopes local · just you, this project project · .mcp.json, committed user · all your projects Server gives tools → actions resources → @mentions prompts → /commands
claude mcp add --transport http github https://api.githubcopilot.com/mcp/
claude mcp add db -- npx -y @modelcontextprotocol/server-postgres postgresql://localhost/app
claude mcp list
Claude Agent SDK

The same harness, as a library

The Agent SDK (formerly the Claude Code SDK) gives your program the loop, built-in tools, context management, permissions, hooks, subagents and sessions that power Claude Code. You supply a prompt and options; it streams back messages. It is the agent development kit for building your own agents on Claude.

# pip install claude-agent-sdk
import asyncio
from claude_agent_sdk import (ClaudeSDKClient, ClaudeAgentOptions,
                              tool, create_sdk_mcp_server)

@tool("get_weather", "Current weather for a city", {"city": str})
async def get_weather(args):
    return {"content": [{"type": "text", "text": f"Sunny in {args['city']}"}]}

weather = create_sdk_mcp_server(name="weather", version="1.0.0", tools=[get_weather])

options = ClaudeAgentOptions(
    system_prompt="You are a concise travel planner.",
    mcp_servers={"weather": weather},
    allowed_tools=["mcp__weather__get_weather", "WebSearch"],
    permission_mode="default",
    max_turns=8,
)

async def main():
    async with ClaudeSDKClient(options=options) as client:
        await client.query("Plan a rain-proof day in Lisbon")
        async for msg in client.receive_response():
            print(msg)

asyncio.run(main())
query() · one-shot or streamed prompt, returns an async iterator of messages. Good for tasks and scripts.
ClaudeSDKClient · a persistent, two-way session (Python) for chat-style apps: send follow-ups, interrupt, keep context.
tool() + create_sdk_mcp_server() · your functions become MCP tools that run in your own process.

Options you will reach for

system_prompt

Your own prompt, or the Claude Code preset plus an append.

allowed_tools

Whitelist of built-in and MCP tools.

permission_mode

default · acceptEdits · plan · bypassPermissions.

can_use_tool

Callback that approves or denies each call at runtime.

mcp_servers

stdio, HTTP or in-process servers by name.

hooks

Python or JS callbacks on lifecycle events.

agents

Subagent definitions in code.

setting_sources

Opt in to user, project and local settings and CLAUDE.md.

cwd · max_turns · model

Working directory, loop limit, model choice.

resume · fork_session

Continue or branch a previous session by ID.

What streams back

SystemMessagesubtype init: session_id, tools, MCP status, model
AssistantMessagetext, thinking, and tool_use blocks
UserMessagetool_result blocks the harness produced
AssistantMessagenext step … repeats per loop turn
ResultMessagefinal result, num_turns, duration, usage, total_cost_usd, is_error

Authenticate with ANTHROPIC_API_KEY, or route through Amazon Bedrock, Google Vertex AI or Microsoft Foundry with environment flags.

Choosing a build surface

Four ways to build a Claude agent

The questions that separate them: who writes the loop, which tools come built in, and who hosts the compute.

ApproachYou writeLoopBuilt-in toolsHostingPick it when
Messages API, manual loopThe whole while stop_reason == "tool_use" loopYouNoneYouYou need full control of every step
API SDK Tool RunnerTool functions onlySDK helperNoneYouA lightweight agent over your own tools
Claude Agent SDKA prompt and optionsClaude Code harnessFiles, shell, search, web, subagents, MCPYouA capable coding or filesystem agent on your own infrastructure
Managed AgentsAgent config + session callsAnthropicSandboxed bash, files, code, Skills, MCPAnthropicLong-running hosted agents without running servers
Architecture patterns

Shapes that work

Orchestrator · workers

A lead agent plans and delegates to subagents that each own one slice, then merges their summaries.

Pipeline

Research → implement → verify as fixed stages, each a subagent or a headless claude -p step in CI.

Generator · evaluator

One agent produces, another grades against a rubric or test suite and sends it back until it passes.

Parallel fan-out

Many independent subagents or git worktrees at once, for per-file migrations or wide searches.

Build path

From idea to a deployed agent

Define the job

One sentence on the outcome, who it serves, and how you will know a run succeeded.

Give it tools

Start with the fewest built-ins that do the job; add MCP or in-process tools for your own systems.

Write its memory

System prompt or CLAUDE.md with commands, conventions and constraints. Package know-how as skills.

Set the guardrails

Permission mode, allow and deny rules, can_use_tool, and hooks for anything that must always happen.

Split the work

Add subagents where reading would swamp the main context or where steps can run in parallel.

Verify inside the loop

Let the agent run tests, linters or screenshots itself. Agents that can check their work finish more tasks.

Evaluate

Replay a set of real tasks; read transcripts; track success rate, turns and total_cost_usd.

Ship it

Run in a container or CI with claude -p or the SDK; stream JSON output; resume sessions by ID.

Practice

Learn it by doing in Agent Lab

An interactive course in agentic engineering with Claude, with tracks for learners, coders and engineers.

  • Drive the agent loop yourself and watch the transcript build
  • Stay inside a context budget, predict permission decisions, build hooks
  • Configure real Agent SDK code for three missions
  • Adaptive checks with spaced review, XP and mastery tracking
Start Agent Lab 10 modules · 7 labs · 45 questions
Glossary

Terms on the drawing

Agent loopCall the model, run the tools it asks for, return results, repeat until it stops.
HarnessThe runtime around the model: context, tools, permissions, hooks, sessions.
tool_use / tool_resultThe model's request to run a tool, and the harness's reply.
CompactionSummarizing older conversation to free context space.
CLAUDE.mdMarkdown memory loaded at session start.
SubagentA child agent with its own context window, tools and prompt.
SkillA folder with SKILL.md that loads progressively when relevant.
HookA command run by the harness on a lifecycle event.
MCPModel Context Protocol: a standard for exposing tools, resources and prompts.
PluginAn installable bundle of commands, agents, skills, hooks and MCP servers.
Permission modeThe default approval posture: plan, default, acceptEdits, auto, bypass.
HeadlessNon-interactive runs with claude -p, for scripts and CI.
SessionA saved transcript you can resume, continue or fork.
CheckpointA snapshot of file edits you can rewind to.
WorktreeA separate git checkout so parallel agents don't collide.