Catalogue / python-agent-sdk-workflows
python-agent-sdk-workflows
Older skill: source not recordedSignedBuilds Python applications on the Claude Agent SDK: one-shot query() versus streaming clients, programmatic subagents, system prompts, hooks, permission callbacks, in-process MCP tools, session resume and fork, settings sources, and slash commands. Use when the user asks to "build an SDK orchestrato…--- name: python-agent-sdk-workflows description: >- Builds Python applications on the Claude Agent SDK: one-shot query() versus streaming clients, programmatic subagents, system prompts, hooks, permission callbacks, in-process MCP tools, session resume and fork, settings sources, and slash commands. Use when the user asks to "build an SDK orchestrator", "add a custom tool", "control agent permissions", "set up hooks", "resume a session", or "debug streaming responses". Not for direct model API clients without the SDK, TypeScript SDK implementations, or unattended privileged automation. ---
Python agent SDK workflows
Start with a capability contract
The examples use the Python SDK's 0.1.6-era contract. Check the independently installed package and CLI before implementation: newer versions can change hooks, permission modes, tool names and option fields. No dependency is downloaded or executed by this skill.
The owner configures authentication privately outside the agent. Do not inspect, print or edit credentials. SDK requests may transmit project material and incur costs; confirm the intended prompt/data, workspace, tools and budget before the first live request.
An explicit user request confirms that exact scope. Confirm additional file edits, executable tools, session-history changes, settings/plugin loading, or outbound service operations separately. Tool permission settings are implementation mechanisms, not user consent.
Never
- Use
eval, shell substring blacklists, or a path prefix string as the security boundary for an untrusted tool call. - Grant unrestricted Bash, inherited subagent tools, or
bypassPermissionsto solve a configuration problem. - Load unreviewed settings, plugins, hooks, commands, or session transcripts into a live agent.
- Log raw tool inputs, credentials, private files, thinking content, or complete transcripts without approved retention/redaction.
- Treat a model's tool request or claimed completion as evidence that an operation was authorized or succeeded.
| Design question | Choose | |---|---| | Independent result | query() async iterator | | Follow-ups and context | ClaudeSDKClient with explicit lifecycle | | Custom in-process MCP/hook control | Client streaming mode, tested against installed release | | Interruptible operation | Active background receiver + interrupt() | | Parallel specialist work | Named subagents with narrow tools and separate contexts | | Repeat a known session | resume; decide continuation vs fork explicitly | | Filesystem capabilities | Explicit approved setting_sources, cwd, tools and local plugin paths |
Do not assert that every query() starts without history: resume and continue_conversation explicitly change that behavior. The historical quick comparison excludes hooks/custom tools from query(), while other examples use them; use the client baseline and verify installed support.
A minimal one-shot request
import asyncio
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock, ResultMessage
async def summarize_contract():
options = ClaudeAgentOptions(
system_prompt="Explain the supplied interface contract in plain language.",
allowed_tools=[], disallowed_tools=["Bash", "Write", "Edit"],
setting_sources=[], max_turns=1,
)
async for message in query(prompt="A queue accepts jobs and returns a receipt. Explain the receipt.",
options=options):
if isinstance(message, AssistantMessage):
for block in message.content:
if isinstance(block, TextBlock): print(block.text)
elif isinstance(message, ResultMessage):
print({"error": message.is_error, "duration_ms": message.duration_ms,
"cost_usd": message.total_cost_usd})
# Run only after the request scope and cost have been authorized.
# asyncio.run(summarize_contract())anyio.run(main) is also supported by the examples; choose one runtime consistent with the application. Python 3.11 enables asyncio.timeout. UV/PEP 723 metadata can document prerequisites, but an automatic-fetch UV shebang is not needed.
Turn-taking and result handling
from claude_agent_sdk import ClaudeSDKClient
async def conversation(options, prompts, consume):
async with ClaudeSDKClient(options=options) as client:
for prompt in prompts:
await client.query(prompt)
async for message in client.receive_response():
await consume(message)Drain each turn through its ResultMessage before sending a dependent follow-up. receive_messages() streams beyond one response; use one designated reader and explicit result counting when sending multiple independent inputs concurrently.
| Message | Fields/use | |---|---| | UserMessage | content string or list; may include tool results | | AssistantMessage | content list, model; inspect each block type | | SystemMessage | subtype, data; init metadata and compaction boundaries | | ResultMessage | subtype, duration_ms, duration_api_ms, is_error, num_turns, session_id, optional total_cost_usd, usage, result | | Partial streaming event | Enable include_partial_messages; inspect actual installed event schema |
| Content block | Fields | |---|---| | TextBlock | text | | ThinkingBlock | thinking, signature; do not expose by default | | ToolUseBlock | id, name, input; a request, not proof of completion | | ToolResultBlock | tool_use_id, optional string/list/None content, optional is_error |
Do not loop over a string user message as though it were a block list. Check optional cost against None, not truthiness, so zero is preserved. Validate structured answers by schema; text may not be JSON and the first block may not be text.
import json
def find_json_object(message):
for block in getattr(message, "content", []) if isinstance(getattr(message, "content", None), list) else []:
text = getattr(block, "text", None)
if not isinstance(text, str): continue
try: result = json.loads(text)
except json.JSONDecodeError: continue
if isinstance(result, dict): return result
return NoneIf the result is absent or fails the application's required fields, report an invalid response. Do not accept a partial/malformed report or assume a tool finished because its request was seen.
Client lifecycle methods
| Method | Contract | |---|---| | ClaudeSDKClient(options=None) | Construct without connecting | | connect(prompt=None) | Async connect; optional string or async iterable | | query(prompt, session_id="default") | Async send string/iterable | | receive_response() | Async iterator through a result | | receive_messages() | Async iterator for general streaming | | interrupt() | Async interrupt while messages are actively consumed | | disconnect() | Async cleanup; context manager does this automatically | | get_server_info() | When available, inspect commands/output style/available styles |
The interactive UI can support exit, interrupt, and new: exit disconnects; interrupt signals the active reader; new disconnects/reconnects and resets turn count. Use asyncio.to_thread(input, ...) for terminal input instead of blocking the event loop.
Cancellation is not rollback. If interrupted tools wrote files or started background jobs, inspect their actual state before proceeding. Do not break an async stream immediately after init metadata; preserve it, then drain or interrupt cleanly.
Define specialists by the work they can do
from claude_agent_sdk import AgentDefinition, ClaudeAgentOptions
def orchestrator(workspace):
return ClaudeAgentOptions(
cwd=workspace, setting_sources=[],
system_prompt={"type": "preset", "preset": "claude_code",
"append": "Stay within the approved queue-adapter review scope."},
allowed_tools=["Task", "Read", "Grep", "Glob"],
agents={
"receipt-review": AgentDefinition(
description="Check receipt decoding and failure cases without changes.",
prompt="Review the queue receipt interface; return file/line evidence and edge cases.",
tools=["Read", "Grep", "Glob"], model="inherit"),
"contract-review": AgentDefinition(
description="Compare implementation behavior to the approved contract.",
prompt="Check compatibility and missing tests; return a structured review only.",
tools=["Read", "Grep", "Glob"], model="sonnet"),
}, max_turns=4,
)Match invocation names exactly: Use receipt-review to inspect receipt decoding. Descriptions guide automatic routing; explicit names guide deliberate routing. Programmatic definitions make configuration visible and override equal-named filesystem agents under the documented contract.
| Specialist | Minimal capability | |---|---| | Structure, documentation, security review | Read, Grep, Glob | | Approved code modification | Read, Write, Edit, Grep, Glob; exact file policy | | Approved test execution | Narrow custom runner preferred; otherwise scoped Bash, Read, Grep plus OS isolation | | Debugger | Read evidence first; authorize additional execution explicitly | | Documentation writer | Read context; approved output path; no arbitrary execution |
AgentDefinition requires description and prompt. tools=None inherits capabilities, so list tools explicitly. Model aliases include sonnet, opus, haiku, inherit; actual model availability/cost is verified at runtime, not guaranteed by an old example ID.
| Benefit | Limit | |---|---| | Separate contexts | Return concise evidence rather than every intermediate result | | Parallelization | Bound concurrency/cost; don't let specialists race on the same files | | Domain instructions | Align prompt and granted tools | | Restricted tools | Scope paths/service destinations as well as tool names |
For a modify/test workflow use discovery → triage → focused investigation → approved patch → verification. Simple questions do not need an orchestrator. The preset helps describe delegation; it is not a substitute for the actual Task capability.
System prompt choices
# None: no custom system instructions.
custom = "Describe the queue interface without editing it."
preset = {"type": "preset", "preset": "claude_code"}
extended = {"type": "preset", "preset": "claude_code", "append": "Return compatibility findings."}Use the explicit preset dictionary. A plain string such as "claude_code" may be interpreted as literal custom text in the installed SDK; do not rely on undocumented shorthand equivalence. Prompt constraints must agree with tools and cannot enforce isolation alone.
The preset includes tool workflows, delegation, code editing, Git/PR patterns and security guidance. Adding those capabilities does not authorize a commit or PR. Domain prompts can address security review, CSV validation, documentation/docstrings, or parametrized tests with concrete requirements.
Local reusable primitives
The following original standard-library helpers provide bounded arithmetic, robust frontmatter parsing, workspace checks, exact-operation approvals, redacted audit records, hook adapters, response draining and interruption. PyYAML is used only by the optional frontmatter loader.
import ast, asyncio, hashlib, json, math, operator, pathlib, re
def load_agent_text(text):
import yaml
lines=text.splitlines()
if not lines or lines[0].strip()!='---': raise ValueError('missing frontmatter')
boundary=next((i for i in range(1,len(lines)) if lines[i].strip()=='---'),None)
if boundary is None: raise ValueError('unterminated frontmatter')Preview shortened. The full SKILL.md is in the pack.
| File | Size | SHA-256 |
|---|---|---|
| SKILL.md | 39.7 kB | af5ef9676bb8 |
| examples.json | 2.0 kB | 1a84807faf95 |
Published verbatim from the pinned commit. Nothing is rewritten.
| Version | Pinned commit | Signed | |
|---|---|---|---|
| 1.0.0 Current | Not recorded | 3 Oct 2026 |
Locking a skill to one version needs Pro.