Loading lesson…
Loading lesson…
Hooks let you inject custom code at critical moments of agent execution - for example, logging, intercepting risky operations, and auditing file changes.
Supported hook types include: PreToolUse (before tool execution), PostToolUse (after tool execution), Stop (when the agent stops), SessionStart, SessionEnd, and more.
from datetime import datetime
from claude_agent_sdk import query, ClaudeAgentOptions, HookMatcher
# Record an audit log every time a file is modified
async def log_file_change(input_data, tool_use_id, context):
file_path = input_data.get("tool_input", {}).get("file_path", "unknown")
with open("./audit.log", "a") as f:
f.write(f"{datetime.now()}: modified {file_path}\n")
return {}
async def main():
async for message in query(
prompt="Refactor utils.py for better readability",
options=ClaudeAgentOptions(
permission_mode="acceptEdits",
hooks={
"PostToolUse": [
HookMatcher(matcher="Edit|Write", hooks=[log_file_change])
]
},
),
):
if hasattr(message, "result"):
print(message.result)
Real-world uses:
When a task is complex enough, you can define multiple specialized sub-agents and let the main agent delegate sub-tasks to them. Each sub-agent has its own instructions and tool permissions, isolated from each other.
from claude_agent_sdk import query, ClaudeAgentOptions, AgentDefinition
async for message in query(
prompt="Use the code-reviewer agent to review this project's code quality",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep", "Task"],
agents={
"code-reviewer": AgentDefinition(
description="Professional code reviewer responsible for quality and security reviews",
prompt="Analyze code quality, identify potential issues, and provide improvement suggestions.",
tools=["Read", "Glob", "Grep"],
),
"test-writer": AgentDefinition(
description="Testing specialist responsible for writing unit tests",
prompt="Write unit tests for functions that are missing tests.",
tools=["Read", "Write", "Bash"],
),
},
),
):
if hasattr(message, "result"):
print(message.result)
Messages from sub-agents include a parent_tool_use_id field, making it easy to track which messages came from which sub-agent.
Through Model Context Protocol (MCP), your agent can connect to external systems such as databases, browsers, and third-party APIs. The community already provides hundreds of MCP servers you can use directly.
# Connect Playwright so the agent can operate a browser
async for message in query(
prompt="Open example.com and describe what you see",
options=ClaudeAgentOptions(
mcp_servers={
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
}
}
),
):
if hasattr(message, "result"):
print(message.result)
Common MCP integration scenarios:
After understanding features, the most important question is: what can this actually do? Below are real scenarios validated by the community.
Give it a bug description, and it can find code, locate the issue, fix it, and run tests to verify:
async for message in query(
prompt="Users report occasional HTTP 500 errors during login. Investigate and fix code under src/auth/",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Bash", "Glob", "Grep"],
permission_mode="acceptEdits",
),
):
print(message)
Claude will grep logs, read related code, find the bug, modify code, and run tests to confirm the fix.
Build a read-only code review agent that audits quality without making any modifications:
async for message in query(
prompt="Review code under src/ with focus on security vulnerabilities, performance issues, and coding conventions",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Glob", "Grep"],
permission_mode="bypassPermissions",
),
):
if hasattr(message, "result"):
print(message.result)
In a CI pipeline, let the agent analyze failing tests and attempt automatic fixes:
async for message in query(
prompt="Run npm test, analyze failing test cases, and fix the code so all tests pass",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Bash", "Glob"],
max_turns=20,
),
):
print(message)
This is a major advantage of Agent SDK over CLI - CLI is good when a human sits at the terminal, while SDK is ideal for embedding into automated workflows.
Let the agent search the web, read documentation, synthesize information, and produce a report:
async for message in query(
prompt="Research mainstream Python Web frameworks in 2026. Compare FastAPI, Django, and Litestar, then write a technical selection report to report.md",
options=ClaudeAgentOptions(
allowed_tools=["WebSearch", "WebFetch", "Write"],
),
):
print(message)
By connecting Playwright through MCP, the agent can not only write code but also open a browser to verify results:
async for message in query(
prompt="Fix the homepage style issue, then open a browser and take screenshots to verify the result",
options=ClaudeAgentOptions(
allowed_tools=["Read", "Edit", "Bash"],
mcp_servers={
"playwright": {
"command": "npx",
"args": ["@playwright/mcp@latest"]
}
},
),
):
print(message)
| Scenario | Core Tools | Difficulty |
|---|---|---|
| Auto bug fixing | Read, Edit, Bash, Grep | Beginner |
| Code review | Read, Glob, Grep | Beginner |
| CI/CD auto-fix | Read, Edit, Bash | Intermediate |
| Technical research report | WebSearch, WebFetch, Write | Beginner |
| Browser automation | MCP (Playwright) | Intermediate |
| Multi-agent collaboration | Task + AgentDefinition | Advanced |
| Database operations | MCP (PostgreSQL/MySQL) | Intermediate |
| Email/notification assistant | MCP (Slack/Email) | Intermediate |
Not every scenario needs Agent SDK. Choosing the right tool matters:
| What You Want to Do | Recommended Tool |
|---|---|
| Simple chat, text generation, translation | Basic anthropic SDK |
| One-shot tool use (weather lookup, arithmetic) | Basic anthropic SDK |
| Autonomously complete multi-step development tasks | Agent SDK |
| Embed into CI/CD pipelines | Agent SDK |
| Build apps that operate on a file system | Agent SDK |
| Daily interactive development | Claude Code CLI |
| One-off quick tasks | Claude Code CLI |
In short: if your task requires Claude to "work hands-on" by itself (reading files, editing code, running commands), use Agent SDK. If you only need Q&A, the basic SDK is enough.