Guides building a first agent with the Claude Agent SDK (TypeScript or Python): install, run query(), read result messages, restrict tools/permissions, add custom tools via in-process MCP server, and guard tool calls with hooks. Also compares Agent SDK vs Client SDK vs Managed Agents.
Ships in agent-sdk. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
The Agent SDK packages Claude Code's agent loop, built-in tools, permissions, sessions, and hooks as a library for TypeScript and Python. You run it in a process you operate; it drives the loop for you.
messages.create tool loop with a maintained harnessThe SDK docs compare four options:
| You want to | Use |
|---|---|
| Embed Claude Code's agent in your own app, in a process you operate | Agent SDK |
| Interactive development or one-off tasks in a terminal | Claude Code CLI |
| Call the Claude API directly and own the tool loop (or use the client SDK's beta tool runner) | Client SDK (@anthropic-ai/sdk, anthropic) |
| Have Anthropic host the agent loop and sandbox | Managed Agents (see managed-agents-api) |
The Agent SDK and the Client SDK are different packages: the Client SDK has no built-in tools.
npm install @anthropic-ai/claude-agent-sdk # TypeScript
pip install claude-agent-sdk # Python
Authenticate with an API key (ANTHROPIC_API_KEY) as described in the SDK quickstart. The docs state that third-party products may not offer claude.ai login or rate limits unless previously approved.
query() returns an async iterator of messages. The final result message carries the outcome, a cost estimate, and the session ID.
import { query } from "@anthropic-ai/claude-agent-sdk";
for await (const message of query({
prompt: "Find and fix the failing test in src/utils",
options: {
allowedTools: ["Read", "Glob", "Grep", "Edit"],
maxTurns: 20,
},
})) {
if (message.type === "result") {
console.log(message.subtype, message.total_cost_usd, message.session_id);
if (message.subtype === "success") console.log(message.result);
}
}
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, ResultMessage
async def main():
async for message in query(
prompt="Find and fix the failing test in src/utils",
options=ClaudeAgentOptions(allowed_tools=["Read", "Glob", "Grep", "Edit"], max_turns=20),
):
if isinstance(message, ResultMessage):
print(message.subtype, message.total_cost_usd, message.session_id)
asyncio.run(main())
Leave model unset to use the default, or pass a model alias or a current full model ID. A single-shot query() throws (TypeScript) or raises (Python) after yielding an error result such as error_max_turns or error_max_budget_usd, so wrap it in try/catch.
allowedTools pre-approves tools; it does not restrict Claude to them. Unlisted tools fall through to the permission mode and your canUseTool callback. To remove a tool entirely, put its bare name in disallowedTools (or limit built-ins with the tools option).
permissionMode | Behavior (per docs) |
|---|---|
default | Calls needing approval go to canUseTool |
dontAsk | Anything that would prompt is denied |
acceptEdits | File edits and common filesystem commands in the working directory are auto-approved |
plan | Explores and plans without editing source files |
auto | A classifier model reviews actions |
bypassPermissions | Approves nearly everything; use only in an isolated environment |
For a locked-down headless agent, pair allowedTools with permissionMode: "dontAsk". Note that allowedTools does not constrain bypassPermissions.
Custom tools run in an in-process MCP server. Pre-approve them by their fully qualified name mcp__{server}__{tool}.
import { query, tool, createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk";
import { z } from "zod";
const lookupOrder = tool(
"lookup_order",
"Look up an order by ID",
{ orderId: z.string().describe("Order ID") },
async ({ orderId }) => ({ content: [{ type: "text", text: JSON.stringify(await db.orders.get(orderId)) }] }),
{ annotations: { readOnlyHint: true } },
);
const orders = createSdkMcpServer({ name: "orders", version: "1.0.0", tools: [lookupOrder] });
for await (const message of query({
prompt: "What is the status of order 1234?",
options: { mcpServers: { orders }, allowedTools: ["mcp__orders__lookup_order"] },
})) {
if (message.type === "result" && message.subtype === "success") console.log(message.result);
}
In Python the equivalents are the @tool decorator and create_sdk_mcp_server. Return isError: true (Python: "is_error": True) to give Claude a composed error message instead of a raw exception.
Hooks run before every other permission step, and a hook deny applies even in bypassPermissions mode.
import { query, type HookCallback, type PreToolUseHookInput } from "@anthropic-ai/claude-agent-sdk";
const protectEnv: HookCallback = async (input) => {
const pre = input as PreToolUseHookInput;
const path = (pre.tool_input as Record<string, unknown>)?.file_path as string | undefined;
if (path?.split("/").pop()?.toLowerCase() === ".env") {
return { hookSpecificOutput: { hookEventName: pre.hook_event_name, permissionDecision: "deny",
permissionDecisionReason: "Cannot modify .env files" } };
}
return {};
};
const options = { hooks: { PreToolUse: [{ matcher: "Write|Edit", hooks: [protectEnv] }] } };
Matchers match tool names only; check arguments such as file_path inside the callback. A Write|Edit matcher does not catch the same write done through Bash.
Set maxTurns and maxBudgetUsd (Python: max_turns, max_budget_usd). The budget is a client-side estimate that can be exceeded slightly, so leave headroom.
dontAsk, then widen deliberatelyPreToolUse hooks, not only in canUseToolresult message and its error subtypesmaxTurns and maxBudgetUsd on every unattended runWhat SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
/agent-sdk:agent-sdk-quickstartfrom agent-sdk
npx claudepluginhub latestaiagents/agent-skills --plugin agent-sdk5 skills in this plugin
/agent-sdk-streamingStream Claude Agent SDK output to a UI: the default message flow, enabling partial messages with includePartialMessages / include_partial_messages, handling stream_event deltas for text and tool input, attributing subagent output, and handling cut-off streams.
Use this skill when building a chat or progress UI on top of the Agent SDK, showing tool activity live, or debugging missing or out-of-order streamed output.
Activate when: agent SDK streaming, includePartialMessages, include_partial_messages, stream_event, StreamEvent, SDKPartialAssistantMessage, text_delta, input_json_delta, real-time agent output.
/managed-agents-apiUse Claude Managed Agents (beta), where Anthropic runs the agent loop and a per-session sandbox: create a versioned agent once, an environment, then sessions that you drive with events over SSE. Covers the correct object model, tool permission policies, custom tools, outcomes, session budgets, data-retention limits, and when to choose it over the Agent SDK.
Use this skill when building hosted, long-running, or scheduled agents on the Claude API, deciding between Managed Agents and the Agent SDK, or fixing code that puts model or tools on the session or calls agents.create on every run.
Activate when: Managed Agents, Claude Managed Agents, /v1/agents, /v1/sessions, /v1/environments, client.beta.agents, client.beta.sessions, sessions.events.stream, agent_toolset, server-side agent.
Other plugins' skills for the same job
2 plugins in one repository ship this exact skill · first indexed Nov 5, 2026