New: Earn 20% as an Agensi affiliate. Join now →

    Guides

    Claude Agent SDK: Build Your Own Agents

    Build an agent with the Claude Agent SDK in Python or TypeScript: setup, tools, subagents, permissions, cost and hosting. Checked 19-10-2026.

    October 19, 20269 min read
    Share:

    Published 19-10-2026. Last verified against the Anthropic documentation on 19-10-2026, reviewed monthly. SDK version we pinned: @anthropic-ai/claude-agent-sdk 0.3.303 for TypeScript (read on the npm registry on 19-10-2026).

    Quick answer

    This page is for the developer or small engineering team that wants an agent running inside its own Python or TypeScript service, for example a bot that reviews every pull request or a job that triages incoming tickets. The Claude Agent SDK is a library that gives you the agent loop, the built-in tools and the permission system of Claude Code, so you do not write the tool loop yourself. Install it, set ANTHROPIC_API_KEY and call query(). The SDK has no price of its own on the Anthropic pricing page we read, so you pay tokens, and the model you choose moves the bill more than any other setting. We send most teams here first, and we send the ones who do not want to run servers to Managed Agents.

    How we checked the information in this article

    We read the Anthropic documentation pages for the SDK on 19-10-2026: overview, quickstart, permissions, subagents, hosting and the pricing page. We did not run any of the code below against a live account, so every snippet is marked as copied from the documentation or as assembled by us from documented parts, and none of it is executed by us. Our gate for this page: a snippet or number goes in only if it appears on an Anthropic page we could open that day, and every cost we derive is labelled as our calculation from list prices.

    The gate rejected three things. We left out the savings figures on a vendor page that sells a router for the SDK, because we cannot reproduce them. We did not call allowed_tools a read-only switch, because the permissions page says it does not constrain bypassPermissions mode. And we dropped any advice on claude.ai logins for your own product, because Anthropic's documentation says third parties may not offer them without approval. We could not read the PyPI page for the Python package on 19-10-2026, so we pin the TypeScript version only.

    What is the Claude Agent SDK?

    It is Claude Code as a library. Anthropic describes an agent as an application that finishes a task by planning its own steps and calling tools that read files, run commands or edit code, and the SDK hands you the same tools, loop and context management that power Claude Code. It runs in Python 3.10 or newer and Node.js 18 or newer, and both packages bundle a native Claude Code binary, so most installs need nothing else. If you read older posts about the Claude Code SDK, it is the same project under its new name.

    The detail that surprises people: the SDK spawns a separate claude CLI process for each session and talks to it over stdio. You are hosting a long-lived process with a shell and local files, not a stateless API wrapper. We come back to that in the deployment section.

    Agent SDK, Claude Code CLI, Client SDK or Managed Agents: which one?

    Choose by who runs the agent and what you want built in. This table follows the comparison on Anthropic's overview page, read on 19-10-2026.

    You want toUseOur verdict
    Embed an agent in your own Python or TypeScript serviceAgent SDKWhere we send almost every developer who wants control
    Work interactively in a terminalClaude Code CLINot an SDK job, use it daily and skip the library
    Call the Claude API and write the tool loop yourselfClient SDKOnly if you need loop-level control the SDK hides
    Let Anthropic host the agent loopManaged AgentsThe one we would try first if nobody on your team wants to operate containers

    The Client SDK sits at the bottom of the stack and the SDK sits on top of it. If you mainly build endpoints and data layers around the Claude API, our APIs and backend skills cover the surrounding work, and our guide to creating an AI agent covers the decision before you pick a framework.

    How do you build a first agent in Python and TypeScript?

    Create a project, install the package and set your key. For TypeScript run npm install @anthropic-ai/claude-agent-sdk, and for Python run pip install claude-agent-sdk or uv add claude-agent-sdk. The SDK reads ANTHROPIC_API_KEY from the environment of the process and does not load .env files for you. It also runs on Amazon Bedrock, Google Cloud's Agent Platform and Microsoft Foundry through environment variables such as CLAUDE_CODE_USE_BEDROCK=1; our guide to Claude on Bedrock, Vertex AI and Foundry compares those routes.

    This is the Python quickstart agent from the documentation, copied from the quickstart page on 19-10-2026 and not executed by us. It finds and fixes bugs in a file called utils.py:

    import asyncio
    
    from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, ResultMessage
    
    async def main():
    
        async for message in query(
    
            prompt="Review utils.py for bugs that would cause crashes. Fix any issues you find.",
    
            options=ClaudeAgentOptions(
    
                allowed_tools=["Read", "Edit", "Glob"],
    
                permission_mode="acceptEdits",
    
            ),
    
        ):
    
            if isinstance(message, AssistantMessage):
    
                for block in message.content:
    
                    if hasattr(block, "text"):
    
                        print(block.text)
    
                    elif hasattr(block, "name"):
    
                        print(f"Tool: {block.name}")
    
            elif isinstance(message, ResultMessage):
    
                print(f"Done: {message.subtype}")
    
    asyncio.run(main())
    

    query() returns an async iterator, so the loop streams each reasoning step, tool call and result until Claude decides the task is done. According to the documentation the run ends with "Done: success". Writing the SKILL.md files your agent loads from .claude/skills/ is a separate job, and our skill-creator helps there. By its listing it creates, tests and optimizes new skills, and it is free. We did not run it.

    How do tools, subagents and hooks work in the SDK?

    Tools decide what the agent can do, and the documentation groups them simply: Read, Glob and Grep for analysis, add Edit to change code, add Bash for full automation. Hooks run your own code at points in the lifecycle, for example before a tool call. Subagents are separate agent instances that the main agent spawns for focused work, and they keep intermediate results out of the main context.

    A subagent needs a description and a prompt, and the main agent must be allowed to use the Agent tool or it cannot delegate. We assembled this example from the documented fields on the subagents page. It is not executed by us:

    import asyncio
    
    from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
    
    async def main():
    
        async for message in query(
    
            prompt="Use the code-reviewer agent to review the auth module",
    
            options=ClaudeAgentOptions(
    
                allowed_tools=["Read", "Grep", "Glob", "Agent"],
    
                agents={
    
                    "code-reviewer": AgentDefinition(
    
                        description="Expert code reviewer for security and quality.",
    
                        prompt="Review the code. Report findings by severity.",
    
                        tools=["Read", "Grep", "Glob"],
    
                        model="sonnet",
    
                        max_turns=15,
    
                    )
    
                },
    
                max_budget_usd=2.0,
    
            ),
    
        ):
    
            if hasattr(message, "result"):
    
                print(message.result)
    
    asyncio.run(main())
    

    Two limits are worth setting from the start. The documentation says a subagent can spawn subagents of its own, with a default nesting depth of 3 and up to 20 running at once, so one prompt can grow into a tree. The cap on spend, max_budget_usd in Python, ends the query with the error_max_budget_usd result when it is reached. It also says Claude Opus 5 delegates more readily than earlier models, which is a reason to set these caps before you pick that model.

    Whole teams of agents are a different pattern, and our Claude Code subagents guide shows it in the terminal. For the handoff between agents we would look at agent handoff orchestrator, which by its listing generates structured handoff packages for multi-agent work and is free. Our agents and orchestration skills hold more of them. We have not tested either.

    How do permissions and sandboxing work?

    Every tool request passes six checks in a fixed order, per the permissions page: hooks, deny rules, ask rules, the permission mode, allow rules and finally your canUseTool callback. The modes are default, dontAsk, acceptEdits, bypassPermissions, plan and auto.

    Two traps are documented. First, allowed_tools pre-approves the tools you list but does not restrict anything else: with bypassPermissions set, allowed_tools=["Read"] still approves Bash, Write and Edit. If you need a locked-down agent, the page recommends allowed tools together with dontAsk mode, and disallowed_tools for anything that must never run. Second, from TypeScript SDK v0.3.286 an omitted permissionMode is no longer the same as default, because a session can start in auto mode. If your application relies on default, pass it explicitly.

    Run the SDK as a non-root user or inside a sandbox, because Claude Code refuses to start in bypassPermissions mode as root outside a recognized sandbox. For the review side of this work, our security skills include audits of agent permissions, and evaluating AI harness dimensions assesses coding-agent platforms on five structural dimensions by its listing. We have not run it. Nothing here replaces your own review of what an agent is allowed to touch.

    What does the Claude Agent SDK cost?

    The pricing page we read on 19-10-2026 has no line for the SDK, so you pay for tokens and for wherever you host it. List prices per million tokens, vendor-stated: Haiku 5.5 $0.10 input and $0.50 output for prompts up to 100,000 tokens, Sonnet 5.5 $2 and $10, Opus 5.5 $4 and $20, Fable 5.1 $10 and $50. Our Claude API pricing guide covers caching, batch and spend limits.

    The table is our calculation, not a measured invoice. We assumed one task of 100,000 input tokens and 20,000 output tokens with no caching. A real agent resends context on every turn, so treat these as a floor.

    ModelInput costOutput costOne task, our calculation
    Haiku 5.5$0.01$0.01$0.02
    Sonnet 5.5$0.20$0.20$0.40
    Opus 5.5$0.40$0.40$0.80
    Fable 5.1$1.00$1.00$2.00

    Anthropic's own hosting guide says a minimally provisioned container costs roughly $0.05 per hour and that token cost usually dominates infrastructure cost by an order of magnitude or more. That matches how we would plan it: choose the model first, then cap turns and budget. Our LLM operations skills cover cost tracking, and prompt engineer is a free listing for prompt patterns that keep LLM applications robust. We have not tested it.

    How do you deploy an agent?

    Plan around the subprocess. Anthropic suggests 1 GiB of RAM, 5 GiB of disk and 1 CPU per agent as a starting point, and says memory grows with session length. Session transcripts live on local disk by default and do not survive a restart, so mirror them with a SessionStore if users expect to resume. There is no session timeout of its own, so set max_turns.

    The hosting page names four session patterns: ephemeral containers for one-off tasks, long-running containers for agents that serve ongoing traffic, hybrid containers that hydrate from a store, and several agents in one container. For a shared container with several customers, pass settingSources as an empty list, give each tenant its own working directory and set CLAUDE_CODE_DISABLE_AUTO_MEMORY=1. Our DevOps and cloud skills cover the container side.

    If you would rather not host the loop at all, Managed Agents is the alternative, covered in our Managed Agents guide. The documentation calls it beta, requires the managed-agents-2026-04-01 header and lists a $0.08 per session-hour runtime fee on top of tokens. It is also not eligible for Zero Data Retention or a HIPAA Business Associate Agreement, which decides the question for some teams on its own.

    When should you use MCP or a skill instead?

    Use the SDK when you need a program that decides and acts. Use an MCP server when the agent needs a live connection to a tool or a database, and a skill when it needs a written procedure it can load on demand. They combine: the SDK loads skills and MCP servers from your project like Claude Code does. Our comparison of agent skills and MCP draws the line, and our guide to testing and debugging AI agents is where we would go before shipping. We sell skills that load into Claude, Cursor, Codex CLI and Copilot, and we name ours in the sections above. No vendor paid to be listed.

    Where to start

    Copy the quickstart, run it on a throwaway folder and read the permissions page before you widen allowed_tools. Then add one subagent and one budget cap. We check the SDK documentation every month and update this page when the pinned version changes. Written by Samuel Rose, Founder of Agensi.

    Sources

    All read on 19-10-2026.