Claude Agent SDK in Python: First Agent, Tools and Hooks
👋 In plain words: The Claude Agent SDK gives you Claude Code’s agent engine as a Python library: the loop, file and shell tools, permissions and hooks are already built. You describe the task and the rules; it does the work. This lesson builds a QA agent with it, step by step, including hooks that enforce rules no prompt can override.
Writing your own loop (Lesson 32) teaches the mechanics; the Agent SDK gives you a production-grade harness. In this lesson you will run a first agent that reads files with the built-in Read tool, restrict what it may do with allowed tools and permission modes, add a custom tool through an in-process MCP server, and attach PreToolUse and PostToolUse hooks that block destructive commands and write an audit log, all running for real against a local stand-in for the API.
🔑 Key terms
- query(): the Agent SDK function that runs an agent for one prompt and yields its messages.
- ClaudeAgentOptions: settings for a run: allowed tools, permission mode, working folder, system prompt, model, hooks, MCP servers and more.
- Built-in tools: Claude Code’s tools such as Read, Write, Edit, Bash, Glob, Grep, WebSearch and WebFetch.
- Hook: your function that the harness calls at a fixed point (before or after a tool, at session start, on stop…). It can allow, deny or modify.
- Permission mode: how the harness decides about tool use without asking:
default,acceptEdits,plan,bypassPermissions,dontAskorauto.
🪜 Step 1: Install the SDK
⌨️ Terminal
pip install claude-agent-sdk
This course was built with claude-agent-sdk 0.2.187, which bundles the Claude Code engine it drives. Authentication uses the same ANTHROPIC_API_KEY as the API (or a cloud provider, configured through environment variables).
🪜 Step 2: Run a first agent with a built-in tool
Give the agent a question about a file in its working folder and allow only the Read tool:
📄 pytest.ini
[pytest]
addopts = -q --maxfail=3
timeout = 30
markers =
smoke: quick checks run on every commit
📄 first_agent.py
import asyncio
from pathlib import Path
from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, ResultMessage, query
async def main():
options = ClaudeAgentOptions(
allowed_tools=["Read"], # pre-approve only reading files
cwd=str(Path.cwd()), # the agent works in this folder
max_turns=5,
model="claude-opus-5-5",
)
async for message in query(prompt="What per-test timeout does pytest.ini set?", options=options):
if isinstance(message, AssistantMessage):
for block in message.content:
if type(block).__name__ == "ToolUseBlock":
print("TOOL ->", block.name, Path(block.input["file_path"]).name)
elif type(block).__name__ == "TextBlock":
print("CLAUDE:", block.text)
elif isinstance(message, ResultMessage):
print(f"RESULT: {message.subtype}, turns={message.num_turns}")
asyncio.run(main())⌨️ Terminal
python first_agent.py🖥️ Output (sample run)
TOOL -> Read pytest.ini
CLAUDE: pytest.ini sets a per-test timeout of 30 seconds (timeout = 30).
RESULT: success, turns=2
- The SDK ran the whole loop: Claude asked for
Read, the harness read the real file and sent its content back, and Claude answered. query()yields typed messages: aSystemMessageat start,AssistantMessages, tool results asUserMessages, and a finalResultMessagewith turns, duration and cost.
🪜 Step 3: Control tools and permissions
Least privilege starts with the options:
| Option | Effect |
|---|---|
allowed_tools=[...] |
Tools that run without asking |
disallowed_tools=[...] |
Tools that are never available |
permission_mode |
default (ask for anything not allowed), acceptEdits (auto-approve file edits), plan (plan only, no changes), bypassPermissions (no checks: avoid outside sandboxes), plus dontAsk and auto |
cwd / add_dirs |
The folders the agent works in |
max_turns, max_budget_usd, task_budget |
Limits on how long and how expensive a run can be |
can_use_tool |
Your callback that approves or denies each tool request at run time |
permission_mode="bypassPermissions" disables the safety checks. Use it only inside an isolated container or VM with no secrets, never on a developer laptop or a CI runner with production credentials.🪜 Step 4: Add a custom tool
Custom tools run in your Python process through an in-process MCP server. The tool name the model sees is mcp__<server>__<tool>:
📄 ci_tool.py
from claude_agent_sdk import create_sdk_mcp_server, tool
FAILURES = {"812": ["test_checkout_total"]}
@tool("get_failed_tests", "List the failed tests of a CI build. build is the numeric build number, e.g. 812.",
{"build": str})
async def get_failed_tests(args):
failed = FAILURES.get(args["build"], [])
return {"content": [{"type": "text", "text": f"build {args['build']}: {', '.join(failed) or 'no failures'}"}]}
ci_server = create_sdk_mcp_server("ci", tools=[get_failed_tests])
🪜 Step 5: Enforce rules with hooks
Prompts ask; hooks enforce. A PreToolUse hook runs before every matching tool call and can deny it. A PostToolUse hook runs after and is ideal for audit logs. Here the agent is allowed to use Bash, but a hook blocks destructive commands, and every tool call is logged:
📄 guarded_agent.py
import asyncio
import json
from claude_agent_sdk import AssistantMessage, ClaudeAgentOptions, HookMatcher, ResultMessage, UserMessage, query
from ci_tool import ci_server
BLOCKED = ("rm -rf", "git push --force", "DROP TABLE")
async def block_destructive(input_data, tool_use_id, context):
command = input_data["tool_input"].get("command", "")
if any(bad in command for bad in BLOCKED):
return {"hookSpecificOutput": {"hookEventName": "PreToolUse", "permissionDecision": "deny",
"permissionDecisionReason": f"Blocked by policy: {command!r}"}}
return {}
async def audit(input_data, tool_use_id, context):
with open("audit.log", "a") as f:
f.write(json.dumps({"tool": input_data["tool_name"], "input": input_data["tool_input"]}) + "\n")
return {}
async def main():
options = ClaudeAgentOptions(
mcp_servers={"ci": ci_server},
allowed_tools=["mcp__ci__get_failed_tests", "Bash"],
hooks={
"PreToolUse": [HookMatcher(matcher="Bash", hooks=[block_destructive])],
"PostToolUse": [HookMatcher(hooks=[audit])],
},
max_turns=6,
model="claude-opus-5-5",
)
async for m in query(prompt="Check build 812, then clean up the build folder.", options=options):
if isinstance(m, AssistantMessage):
for b in m.content:
if type(b).__name__ == "ToolUseBlock":
print("TOOL REQUEST ->", b.name, b.input)
elif type(b).__name__ == "TextBlock":
print("CLAUDE:", b.text)
elif isinstance(m, UserMessage) and isinstance(m.content, list):
for b in m.content:
print("TOOL RESULT <-", str(getattr(b, "content", ""))[:90])
elif isinstance(m, ResultMessage):
print(f"RESULT: {m.subtype}, turns={m.num_turns}")
print("audit.log:\n" + open("audit.log").read())
asyncio.run(main())⌨️ Terminal
python guarded_agent.py🖥️ Output (sample run)
TOOL REQUEST -> mcp__ci__get_failed_tests {'build': '812'}
TOOL RESULT <- [{'type': 'text', 'text': 'build 812: test_checkout_total'}]
TOOL REQUEST -> Bash {'command': 'rm -rf ./build', 'description': 'Clean the build folder'}
TOOL RESULT <- PreToolUse:Bash hook error: Blocked by policy: 'rm -rf ./build'
CLAUDE: Build 812 has one failure: test_checkout_total. I did not clean the build folder because the delete command was blocked by policy; ask an administrator if it really needs to be removed.
RESULT: success, turns=3
audit.log:
{"tool": "mcp__ci__get_failed_tests", "input": {"build": "812"}}
What really happened in that run:
- Claude called the custom tool; your Python function answered.
- Claude asked Bash to run
rm -rf ./build. YourPreToolUsehook denied it before anything ran, and the reason went back to Claude as the tool result. - Claude reported honestly that the cleanup did not happen.
- The
PostToolUsehook logged only the call that actually ran: the denied Bash command never executed, so it is not in the audit log.
can_use_tool) whenever a rule must hold every time: blocking destructive commands, requiring a test run before a commit, logging every tool call, or redacting secrets from tool output. A system-prompt instruction is not enforcement.🪜 Step 6: Read results and continue sessions
The final ResultMessage reports num_turns, duration_ms, total_cost_usd, usage and the session_id. Save the session ID to continue later with ClaudeAgentOptions(resume=session_id), or fork it to try an alternative without changing the original. For multi-turn interactive use, ClaudeSDKClient keeps one session open across several prompts.
🌍 Real-world example: Ravi’s nightly triage agent
Ravi moved his hand-written loop to the Agent SDK. The agent gets Read, Grep and a custom get_failed_tests tool, works only in the checked-out repository, and has max_turns=30 and a dollar budget. A PreToolUse hook blocks any Bash command outside an allow-list (pytest, git log, git diff), and a PostToolUse hook writes every call to the CI artifacts so reviewers can see exactly what the agent did.
🧪 Practice Questions
Question 1. A team’s agent must never run git push –force, even if a prompt-injected file tells it to. Which mechanism enforces this?
- A. A sentence in the system prompt
- B. A PreToolUse hook (or can_use_tool callback) that denies matching Bash commands
- C. A larger model
- D. max_turns=1
Show answer
Answer: B. Hooks run in code before the tool executes and cannot be talked out of their decision.
Question 2. In the Agent SDK, what name does the model see for a custom tool get_failed_tests on an SDK MCP server named ci?
- A. get_failed_tests
- B. ci.get_failed_tests
- C. mcp__ci__get_failed_tests
- D. tool_ci_get_failed_tests
Show answer
Answer: C. MCP tools are namespaced as mcp__
Question 3. Which two options apply least privilege to an Agent SDK agent? (Choose 2.)
- A. allowed_tools listing only the tools the task needs
- B. permission_mode=”bypassPermissions” on a developer laptop
- C. cwd set to the project folder the agent should work in
- D. Disabling all hooks
Show answer
Answer: A and C. Narrow tool lists and a bounded working folder limit what the agent can touch; bypassing permissions removes the checks.
Question 4. Which statement about the Agent SDK and the Tool Runner is correct?
- A. The Agent SDK includes Claude Code’s built-in tools, hooks and permissions; the Tool Runner loops only over tools you define
- B. They are the same package
- C. The Tool Runner has more built-in tools than the Agent SDK
- D. Neither can call custom tools
Show answer
Answer: A. The Agent SDK is the Claude Code harness as a library; the Tool Runner is a smaller helper in the anthropic SDK.
📝 Assignment
- Task 1: Run
first_agent.pywith your own key in one of your repositories and ask about its test configuration.
✅ Done when: the agent answers using the Read tool. - Task 2: Add a
PreToolUsehook that allows Bash only for commands starting withpytestorgit log.
✅ Done when: any other command is denied with a clear reason. - Stretch: Add a
PostToolUsehook that redacts strings matchingsk-ant-from tool output before it reaches the model (check the SDK docs for the hook output field that replaces tool output).
✅ Done when: a file containing a fake key is read and the model never sees the key.
❓ Frequently Asked Questions
🤔 What is the Claude Agent SDK?
A Python and TypeScript library that runs Claude Code’s agent harness inside your program, with built-in tools, permissions, hooks, subagents and sessions.
🤔 How do I add custom tools to the Agent SDK?
Decorate an async function with @tool, wrap it with create_sdk_mcp_server, pass the server in mcp_servers, and allow mcp__<server>__<tool>.
🤔 What are Agent SDK hooks?
Functions the harness calls at fixed points such as before and after tool use. They can deny, allow or modify actions, so rules are enforced deterministically.
🤔 Is the Agent SDK the same as Claude Code?
It uses the same engine. Claude Code is the interactive product; the Agent SDK lets you run that engine from your own code.
🏁 Summary
query(prompt, options)runs a full agent with Claude Code’s harness.- Limit power with
allowed_tools,disallowed_tools,permission_mode,cwdand budgets. - Add custom tools with
@toolandcreate_sdk_mcp_server; they appear asmcp__server__tool. - Use
PreToolUsehooks to enforce rules andPostToolUsehooks for audit logs. - Read the
ResultMessagefor turns, cost and session ID; resume or fork sessions as needed.
Next, continue with Claude Subagents and Multi-Agent Orchestration.
Independent study material by SQA Tools. Not affiliated with, endorsed by or sponsored by Anthropic. Claude is a trademark of Anthropic. Practice questions are original, not real exam content. Code outputs marked “sample run” come from running the exact code against a local stand-in for the Claude API, so real replies, IDs and token counts will differ. Exam facts checked against Anthropic’s official CCDV-F exam guide v1.1 on 24 Nov 2026.