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.
claude-agent-sdk and TypeScript @anthropic-ai/claude-agent-sdkClaude 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.
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.
UserPromptSubmit hooks can add context or block the prompt before Claude sees it.
System prompt, tool schemas, CLAUDE.md files, skill descriptions, conversation so far.
Thinks, writes text, and emits one or more tool_use blocks in parallel.
PreToolUse can allow, deny, ask, or rewrite the tool input.
deny → ask → allow rules and the current mode decide; the user may be prompted.
Edits a file, runs a command, queries an MCP server, or spawns a subagent.
PostToolUse runs formatters or linters and can feed findings back.
tool_result joins the transcript; the loop calls the model again.
Stop hooks run and may send it back to work.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.
Illustrative proportions for a mid-session coding task, not a measurement. Run /context in Claude Code to see your own breakdown.
/compactSummarize history into a short brief and keep going. Happens automatically near the limit; PreCompact hooks fire first.
/clearStart fresh for an unrelated task. CLAUDE.md reloads; the old transcript can still be resumed.
SubagentsDo heavy reading in a separate window and return only a summary to the main thread.
Prompt cachingThe stable prefix (system, tools, memory) is cached, so long sessions stay fast and cheaper.
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.
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.
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.
| Extension | What it is | Lives in | Triggered by | Context cost |
|---|---|---|---|---|
| CLAUDE.md | Standing instructions: build commands, conventions, project facts. Supports @path imports. | ./CLAUDE.md · ~/.claude/CLAUDE.md · managed policy | always loaded | |
| Slash commands | Reusable prompts with $ARGUMENTS, invoked as /name. | .claude/commands/*.md | you type it | |
| Skills | Folders of instructions, scripts and references the model loads when relevant. | .claude/skills/<name>/SKILL.md | model decides | |
| Subagents | Specialists with their own prompt, tool list, model and fresh context window. | .claude/agents/*.md | model delegates | |
| Hooks | Shell commands (or prompts) run on lifecycle events; deterministic guardrails. | settings.json → hooks | harness event | |
| MCP servers | External tools, resources and prompts over the Model Context Protocol. | .mcp.json · claude mcp add | model calls tool | |
| Plugins | Installable bundles of commands, agents, skills, hooks and MCP servers, shared via marketplaces. | .claude-plugin/plugin.json | installed once | |
| Output styles | Replace the coding-focused parts of the system prompt to repurpose the agent. | .claude/output-styles/*.md | always loaded |
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.
# .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.
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.
name + description, roughly a sentence per skill.# .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.
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.
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, …
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.
planRead and research only. Claude proposes a plan and edits nothing until you approve.
defaultAsks the first time each kind of action needs approval.
acceptEditsFile edits go through; other risky actions still ask.
autoA classifier approves routine actions and stops risky ones.
bypassPermissionsNo prompts. Only for isolated containers and throwaway VMs.
"Bash(rm -rf:*)", "Read(./.env)"Never allowed, whatever the mode or other rules say.
"Bash(git push:*)", "WebFetch"Always prompts, even if an allow rule would match.
"Bash(npm run test:*)", "Edit(src/**)"Runs without asking. Prefix and glob patterns keep it narrow.
CLAUDE.md memory follows a similar layering: organization, user, project, and subdirectory files read on demand.
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 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
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())
// npm install @anthropic-ai/claude-agent-sdk zod import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk"; import { z } from "zod"; const getWeather = tool("get_weather", "Current weather for a city", { city: z.string() }, async ({ city }) => ({ content: [{ type: "text", text: `Sunny in ${city}` }] })); const weather = createSdkMcpServer({ name: "weather", version: "1.0.0", tools: [getWeather] }); // custom in-process tools use streaming input: pass an async generator as the prompt async function* prompt() { yield { type: "user" as const, message: { role: "user" as const, content: "Plan a rain-proof day in Lisbon" } }; } for await (const message of query({ prompt: prompt(), options: { systemPrompt: "You are a concise travel planner.", mcpServers: { weather }, allowedTools: ["mcp__weather__get_weather", "WebSearch"], maxTurns: 8, }, })) { if (message.type === "result") console.log(message.result); }
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher, AgentDefinition async def block_force_push(input_data, tool_use_id, context): cmd = input_data["tool_input"].get("command", "") if "push --force" in cmd: return {"hookSpecificOutput": { "hookEventName": "PreToolUse", "permissionDecision": "deny", "permissionDecisionReason": "Force-push is not allowed."}} return {} options = ClaudeAgentOptions( cwd="./repo", allowed_tools=["Read", "Grep", "Glob", "Edit", "Bash", "Agent"], permission_mode="acceptEdits", hooks={"PreToolUse": [HookMatcher(matcher="Bash", hooks=[block_force_push])]}, agents={"reviewer": AgentDefinition( description="Reviews diffs for bugs. Use after edits.", prompt="Report only real defects with file:line.", tools=["Read", "Grep"], model="sonnet")}, setting_sources=["project"], # load CLAUDE.md, skills, commands from the repo ) async for msg in query(prompt="Fix the failing date test, then have reviewer check it", options=options): print(msg)
system_promptYour own prompt, or the Claude Code preset plus an append.
allowed_toolsWhitelist of built-in and MCP tools.
permission_modedefault · acceptEdits · plan · bypassPermissions.
can_use_toolCallback that approves or denies each call at runtime.
mcp_serversstdio, HTTP or in-process servers by name.
hooksPython or JS callbacks on lifecycle events.
agentsSubagent definitions in code.
setting_sourcesOpt in to user, project and local settings and CLAUDE.md.
cwd · max_turns · modelWorking directory, loop limit, model choice.
resume · fork_sessionContinue or branch a previous session by ID.
Authenticate with ANTHROPIC_API_KEY, or route through Amazon Bedrock, Google Vertex AI or Microsoft Foundry with environment flags.
The questions that separate them: who writes the loop, which tools come built in, and who hosts the compute.
| Approach | You write | Loop | Built-in tools | Hosting | Pick it when |
|---|---|---|---|---|---|
| Messages API, manual loop | The whole while stop_reason == "tool_use" loop | You | None | You | You need full control of every step |
| API SDK Tool Runner | Tool functions only | SDK helper | None | You | A lightweight agent over your own tools |
| Claude Agent SDK | A prompt and options | Claude Code harness | Files, shell, search, web, subagents, MCP | You | A capable coding or filesystem agent on your own infrastructure |
| Managed Agents | Agent config + session calls | Anthropic | Sandboxed bash, files, code, Skills, MCP | Anthropic | Long-running hosted agents without running servers |
A lead agent plans and delegates to subagents that each own one slice, then merges their summaries.
Research → implement → verify as fixed stages, each a subagent or a headless claude -p step in CI.
One agent produces, another grades against a rubric or test suite and sends it back until it passes.
Many independent subagents or git worktrees at once, for per-file migrations or wide searches.
One sentence on the outcome, who it serves, and how you will know a run succeeded.
Start with the fewest built-ins that do the job; add MCP or in-process tools for your own systems.
System prompt or CLAUDE.md with commands, conventions and constraints. Package know-how as skills.
Permission mode, allow and deny rules, can_use_tool, and hooks for anything that must always happen.
Add subagents where reading would swamp the main context or where steps can run in parallel.
Let the agent run tests, linters or screenshots itself. Agents that can check their work finish more tasks.
Replay a set of real tasks; read transcripts; track success rate, turns and total_cost_usd.
Run in a container or CI with claude -p or the SDK; stream JSON output; resume sessions by ID.
An interactive course in agentic engineering with Claude, with tracks for learners, coders and engineers.
claude -p, for scripts and CI.