Recipe · recipe:build-a-coding-agent

I want a loop that keeps calling tools until the task is done, an edit tool that lands the change in a real file, and a way to stop it before it burns money

Curated. Written from research and curation. Not run in our harness yet.

The job

We want a coding agent: a loop that keeps calling tools until the task is done, an edit tool that lands changes in real files, and a way to stop it before it burns money.

The approach

Wrap the Claude Agent SDK and let it own the loop. We install the SDK, which ships the Claude Code agent loop as a library, then write the agent as configuration plus our own tools and policies. We do not implement the loop, the tool dispatch, context compaction, the permission evaluator or the session store. We pass a prompt and an options object and consume an async stream of messages; the SDK calls the tools.

This is the recommended path because the loop, the built-in tools and the context manager are one maintained artefact with a weekly release cadence, and the built-in tool set (Read, Edit, Write, Glob, Grep, Bash) is already the set a coding agent needs, so the job collapses to scoping and gating rather than building. The documentation also states the failure modes explicitly, which makes the traps checkable rather than folklore.

One decision must be made before we write code, because it is a licence decision and not a technical one: the Python SDK is MIT and the TypeScript SDK is proprietary.

Alternatives and why not.

What you need

Every version, date and licence below was read from the source named in the row on 2026-10-14.

The bundled CLI is pinned to the SDK package version, so upgrading the SDK is how we upgrade the CLI. The licence split between the two SDKs is the single most decision-relevant fact in this table.

Isolation: pick one, not none. Telemetry is optional and cheap to add now.

Custom tools do not need a separate MCP server process: the SDK runs them in process through create_sdk_mcp_server (Python) or createSdkMcpServer (TypeScript), documented at https://code.claude.com/docs/en/agent-sdk/custom-tools

Deliberately not a component: a search tool. Glob and Grep are built in and the SDK bundles its own search backend, so installing ripgrep separately is a dependency for nothing.

Steps

  1. Make the licence decision first. If we must ship under a permissive licence or cannot accept Anthropic's Commercial Terms, we use the Python SDK (MIT) and skip the TypeScript instructions. This is step one because it is not refactorable later. See https://code.claude.com/docs/en/agent-sdk/overview
  2. Check prerequisites. Node.js 18+ for TypeScript, or Python 3.10+ for Python. See https://code.claude.com/docs/en/agent-sdk/quickstart
  3. Install. Python: uv init then uv add claude-agent-sdk, or pip install claude-agent-sdk in a virtual environment. TypeScript: npm init -y, npm pkg set type=module, npm install @anthropic-ai/claude-agent-sdk, and npm install --save-dev tsx. Both SDKs bundle a native Claude Code binary, so a normal install needs no separate Claude Code install.
  4. Create the agent's world. mkdir my-agent. Files in that directory and below are reachable by default. Add anything outside it explicitly with add_dirs (Python) or additionalDirectories (TypeScript). See https://code.claude.com/docs/en/agent-sdk/configuration
  5. Set credentials. Export ANTHROPIC_API_KEY in the shell that runs the agent. The SDK reads it from the process environment and does not load .env files; load them ourselves (for example with python-dotenv) before calling the SDK. Bedrock, Vertex and other routes use environment switches documented in the quickstart.
  6. Write the minimal loop and run it before adding anything. Python: import query, ClaudeAgentOptions, AssistantMessage, ResultMessage, then async for message in query(prompt=..., options=ClaudeAgentOptions(allowed_tools=["Read","Edit","Glob"], permission_mode="acceptEdits")) and print assistant text and tool names. TypeScript: the same shape with for await (const message of query({ prompt, options: { allowedTools, permissionMode } })).
  7. Decide the tool surface deliberately. Three separate controls, and they do not do what people assume. allowed_tools / allowedTools pre-approves the tools we list; tools we do not list remain available to Claude and fall through to the permission mode. disallowed_tools / disallowedTools blocks tools: a bare name such as Bash removes the tool definition from the request so Claude never sees it, while a scoped rule such as Bash(rm *) leaves the tool available and denies matching calls. permission_mode / permissionMode controls how much is auto-approved. Start from the smallest set that does the job: ["Read","Glob","Grep"] if the agent only analyses. Add Edit, Write and Bash only when the task requires them. See https://code.claude.com/docs/en/agent-sdk/permissions
  8. Pick a permission mode on purpose. The modes are default, acceptEdits, plan, dontAsk, auto and bypassPermissions. acceptEdits auto-approves file edits and common filesystem commands while still gating other shell commands. dontAsk never prompts and denies anything not pre-approved, which is the right mode for a headless agent. bypassPermissions runs everything, is for isolated environments only, and cannot be used when running as root on Unix. Pass default explicitly if that is what we mean.
  9. Put approval logic where it actually runs. canUseTool is the callback of last resort: it is reached only by calls nothing earlier auto-approved. A PreToolUse hook runs before every other step and a hook deny applies even in bypassPermissions mode. If a check must see every tool call, use the hook.
  10. Set the caps before running anything unattended. max_turns / maxTurns caps tool-use round trips and is unlimited by default. max_budget_usd / maxBudgetUsd caps estimated spend and is unlimited by default; the CLI rejects 0 as an invalid amount, while max_turns: 0 means unlimited. effort (low, medium, high, xhigh, max) trades reasoning depth against cost; low suits file lookups. See https://code.claude.com/docs/en/agent-sdk/agent-loop
  11. Handle the result message. The loop ends with a ResultMessage whose subtype says how: a normal completion, error_max_turns or error_max_budget_usd. In single-shot query() the SDK yields the cap result and then raises, so wrap the loop in a try block if we want to continue.
  12. Add our own tools. Define one with @tool (Python) or tool() (TypeScript): a name, a description Claude reads, an input schema, and an async handler returning content plus optionally structuredContent and isError. Wrap it in create_sdk_mcp_server / createSdkMcpServer and pass it to the mcpServers option. Set readOnlyHint: true on tools with no side effects if we want them to run in parallel; custom tools are sequential by default. See https://code.claude.com/docs/en/agent-sdk/custom-tools
  13. Make the context survive a long task. Persistent rules belong in CLAUDE.md, loaded through setting sources, not in the opening prompt, because CLAUDE.md is re-injected on every request while an opening prompt survives only until compaction. Add a summarisation-instructions section to CLAUDE.md telling the compactor what to preserve, and use a PreCompact hook if we need the full transcript archived.
  14. Persist sessions if a user expects to resume. Capture session_id from the ResultMessage, and pass a SessionStore adapter if transcripts must survive a container restart or a move to another node. Two limits: the store mirrors transcripts only, not CLAUDE.md or other working-directory files, and mirror writes are best-effort, emitting a mirror_error system message and continuing when a batch cannot be delivered. See https://code.claude.com/docs/en/agent-sdk/hosting
  15. Isolate it, then give it network. Do not run this on a host whose filesystem we care about. The documented hardened example runs Docker with --cap-drop ALL, --security-opt no-new-privileges, --read-only, --tmpfs mounts for /tmp and the agent home, --network none and a memory cap. Size a starting instance around 1 GiB RAM, 5 GiB disk and 1 CPU per agent, and remember memory grows with session length, so size for real session lengths rather than an idle baseline. Outbound HTTPS to api.anthropic.com is required, or to our provider's regional endpoint. See https://code.claude.com/docs/en/agent-sdk/secure-deployment
  16. Never let the agent hold a credential it can read. Put a proxy outside the agent's environment that injects the key into requests, so the agent can call the service but never sees the secret. This is the documented pattern for exactly this problem.
  17. Turn on telemetry and cost accounting. The SDK inherits OpenTelemetry configuration from the environment, so set the OTEL variables at the container or orchestrator level and every query() call exports spans, metrics and events. Track total_cost_usd from the result and per-step usage from the stream. See https://code.claude.com/docs/en/agent-sdk/cost-tracking
  18. Test on a task with a checkable answer. The quickstart's own exercise is a file with two deliberate bugs (an empty-list division and a null-user attribute error) and a prompt asking the agent to find and fix crashes. Keep an eval like that permanently: a coding agent whose loop runs is not the same as a coding agent whose edits are correct. See https://code.claude.com/docs/en/agent-sdk/quickstart

Traps

Trap 1. Believing allowed_tools constrains bypassPermissions. It does not. *Mistake:* a builder writes allowed_tools=["Read"] alongside permission_mode="bypassPermissions" and believes only reading is approved. *Why agents make it:* the name reads like an allowlist that bounds the session, so the mental model is "this is the set of permitted actions". In fact it is a pre-approval list; unlisted tools match no allow rule, fall through to the permission mode, and the mode approves them, so every tool including Bash, Write and Edit is approved. *Fix:* to block specific tools while keeping bypass, use disallowed_tools. Source: https://code.claude.com/docs/en/agent-sdk/permissions

Trap 2. Putting safeguards in canUseTool and finding they never run. *Mistake:* the builder writes the security check in canUseTool and assumes it runs on every tool call. *Why agents make it:* the callback name suggests "tool calls pass through here", and it is the first approval-shaped API in the docs. Auto-approved tools never reach it: a call approved by acceptEdits, by bypassPermissions or by an allow rule skips the callback entirely, so the check is silently bypassed for exactly the tools it was written to gate. The TypeScript SDK emits CLAUDE_SDK_CAN_USE_TOOL_SHADOWED when it detects this configuration. *Fix:* if a check must run on every call, use a PreToolUse hook, which runs before every other step and survives bypassPermissions.

Trap 3. Writing a deny rule that does not deny what we think. *Mistake:* disallowed_tools=["Bash"] is read as "no shell", and a scoped rule like Bash(rm *) is read as covering every rm. *Why agents make it:* two footguns coincide. A bare-name deny removes the tool from Claude's context entirely, so Claude cannot attempt it, but a scoped rule matches the command as written, so /bin/rm falls through. Path anchors differ the same way: a single leading slash anchors at the rule's source, so Edit(/secrets/) in allowed_tools resolves against the session working directory and does not block /secrets on disk, while Edit(//secrets/) is the absolute form. *Fix:* decide per rule whether we mean bare name or scoped pattern, and re-read both the allow and the deny list before trusting either.

Trap 4. Letting the loop run unbounded. *Mistake:* the agent is started with no cap and runs until it finishes or fails. *Why agents make it:* both caps are unlimited by default and nothing in the minimal example sets them, so an agent that works in testing appears complete. The specific failure mode is a tool call repeating: public trackers carry an unbounded agent tool-use loop burning API spend (jaypetez/famlobster issue 16, closed, 2026-10-09, https://github.com/jaypetez/famlobster/issues/16) and an agent looping on the same call until max iterations is exceeded (wso2/product-integrator issue 2693, closed, 2026-10-07, https://github.com/wso2/product-integrator/issues/2693). *Fix:* set both max_turns and max_budget_usd, below the point where we would be upset.

Trap 5. Trusting the budget cap to be a hard ceiling. *Mistake:* the cap is treated as an absolute spend limit. *Why agents make it:* the option is named as a budget, which implies a boundary. Claude Code compares spend with the cap only after each model response arrives, because cost comes from the token usage returned with that response, so the response that reaches the cap still completes and counts, and subagents still running may spend more before they stop. *Fix:* leave headroom between the cap and the number that actually hurts. Source: https://code.claude.com/docs/en/agent-sdk/agent-loop

Trap 6. Losing early instructions to compaction. *Mistake:* specific rules are given in the opening prompt and expected to hold for the whole session. *Why agents make it:* the prompt is right there at the start and the agent does follow it, so the configuration looks correct. When the context window fills, the SDK summarises older history and emits a system message with subtype compact_boundary; specific early instructions may not survive. This is the most common way a working agent quietly stops following a rule halfway through a long session. *Fix:* put persistent rules in CLAUDE.md, which is re-injected every request, and add explicit summarisation instructions telling the compactor what to preserve.

Trap 7. Filling the context with tool output before any work happens. *Mistake:* the agent is given every tool and reads large files freely. *Why agents make it:* more tools reads as more capability, and a single large read looks cheap in isolation. Large tool outputs consume significant context, several MCP servers with many tools add all their schemas to every request unless tool search defers them, and a read of one large file or a verbose command can cost thousands of tokens in a single turn. It accumulates. *Fix:* scope subagents to the minimum tool set, keep the main agent's tool list small, and use lower effort for routine steps.

Trap 8. Installing a CLI that is not there. *Mistake:* the SDK is installed without the bundled native binary. *Why agents make it:* the install command succeeds, so nothing looks wrong. TypeScript installs the binary through npm optional dependencies, so npm ci --omit=optional produces no binary, and a Python install that gets the source distribution instead of a platform wheel (for example on ARM64 Windows) bundles nothing. *Fix:* the symptom is CLINotFoundError; reinstall without skipping optional dependencies, install Claude Code natively and point pathToClaudeCodeExecutable at it, or ensure it is on PATH. Source: https://code.claude.com/docs/en/agent-sdk/troubleshooting

Trap 9. Expecting .env to be loaded. *Mistake:* the agent is pointed at a correct-looking .env and run. *Why agents make it:* almost every other framework loads .env automatically, so it reads as a default. The SDK reads the API key from the process environment only; the symptom is an authentication error from an agent whose .env looks right. *Fix:* load the file ourselves before calling the SDK, for example with python-dotenv.

Trap 10. Treating the sandbox as a security boundary when it is a speed bump. *Mistake:* sandbox-runtime is treated as the isolation guarantee. *Why agents make it:* it is the lightest option and it is shipped by the same vendor, which reads as the safe default. It uses OS primitives (bubblewrap on Linux, sandbox-exec on macOS) and shares the host kernel, so a kernel vulnerability is theoretically an escape; its proxy allowlists domains by client-supplied hostname and does not terminate or inspect TLS, so domain fronting can reach hosts outside the allowlist. *Fix:* for a stronger boundary use containers, gVisor or a VM. Source: https://code.claude.com/docs/en/agent-sdk/secure-deployment

Trap 11. Assuming the permission system is a sandbox. *Mistake:* the permission rules are treated as the containment layer. *Why agents make it:* it is called a permission system and it does parse shell commands into an AST, which looks like semantic understanding. It is a permission gate: commands that cannot be parsed cleanly require approval and a small set of constructs such as eval always require approval, but apart from the built-in critical-path and protected-path checks it does not infer whether a command is dangerous from its target or its effects. *Fix:* treat it as one layer, never as the boundary.

Trap 12. Ignoring prompt injection because the model is supposed to resist it. *Mistake:* untrusted repository content is handed to the agent with no network control behind the model. *Why agents make it:* the model usually does resist obvious injections, so the risk looks theoretical. The documented threat model says agents can take unintended actions due to prompt injection in content they process, or model error, and web search results are summarised rather than passed raw into context specifically to reduce injection risk. A coding agent reads untrusted repositories for a living. *Fix:* defence in depth: network controls that block the exfiltration request even if the model is fooled.

Trap 13. Assuming sequential means safe and parallel means fast, in the wrong direction. *Mistake:* a custom tool is assumed sequential, or readOnlyHint is set on a tool that writes. *Why agents make it:* the two facts are stated separately in the docs and are easy to hold backwards. Claude can request multiple tool calls in one turn; read-only tools run concurrently and state-modifying tools run sequentially, and custom tools are sequential by default, so parallel execution and side effects are coupled. *Fix:* set readOnlyHint: true only on tools with genuinely no side effects, and accept sequential execution otherwise.

Scope

This recipe covers:

This recipe does not cover:

Sources

Every URL below was fetched during the research on 2026-10-14.

Documentation (all read):

Registries and release feeds:

Licence files (read from raw.githubusercontent.com):

Demand evidence:

Refused: https://www.reddit.com/r/ChatGPTCoding/search.json (HTTP 403, with and without a browser user agent).

Unconfirmed: the tree-sitter Rust crate licence; the bodies of the two loop-failure issues in trap 4; whether the Reddit threads say anything the other venues do not.