# Agents 2 labs: the Claude Agent SDK

Three Python Agent SDK labs.
- **Offline (the default):** they run against `common/sdk_fake.py`, which has the SDK's own dataclass names, fields and defaults, and a `query()` that replays fixtures. Python 3.9+, stdlib only.
- **`--real`:** they import the real `claude-agent-sdk`, which needs Python 3.10+ and `pip install claude-agent-sdk` in a venv. Without it they exit 2 with that hint.

| Lab | What it teaches | Docs |
|---|---|---|
| `sdk_agent.py` | `query()` plus a custom tool. `@tool` + `create_sdk_mcp_server` serve `quote_cart`, which prices a cart with tiny-app's own code. `tools=[]` removes every built-in tool, `allowed_tools=["mcp__tinyapp__quote_cart"]` approves the one tool, and `permission_mode="dontAsk"` denies anything else. It also calls the handler directly and reads the message stream. | [custom tools](https://code.claude.com/docs/en/agent-sdk/custom-tools), [Python reference](https://code.claude.com/docs/en/agent-sdk/python), [agent loop](https://code.claude.com/docs/en/agent-sdk/agent-loop) |
| `sdk_permissions.py` | A PreToolUse hook callback and a `can_use_tool` callback, unit-tested directly, then run through a simulator of the documented order (hooks, deny rules, ask rules, mode, allow rules, `can_use_tool`) over 16 cases. | [permissions](https://code.claude.com/docs/en/agent-sdk/permissions), [user input](https://code.claude.com/docs/en/agent-sdk/user-input), [hooks](https://code.claude.com/docs/en/agent-sdk/hooks) |
| `sdk_structured.py` | `output_format={"type": "json_schema", "schema": ...}`, local re-validation, and the two documented failures: `error_max_structured_output_retries`, and `success` with no `structured_output`. | [structured outputs](https://code.claude.com/docs/en/agent-sdk/structured-outputs), [headless](https://code.claude.com/docs/en/headless#get-structured-output) |

`_sdk_common.py` holds the shared plumbing; run_all skips it because of the leading underscore.

## Run

```bash
cd labs
python3 agents-2/sdk_agent.py
python3 agents-2/sdk_permissions.py            # add --case 5 to walk one row step by step
python3 agents-2/sdk_structured.py             # add --schema for the schema and the matching claude -p command

# real runs (cost money): a venv with Python 3.10+
python3.13 -m venv .venv && . .venv/bin/activate && pip install claude-agent-sdk
python agents-2/sdk_agent.py --real --model haiku --max-budget-usd 0.05 --save
python agents-2/sdk_agent.py --real --setting-sources user ...   # if your provider auth lives in ~/.claude/settings.json
python agents-2/sdk_agent.py --real --cli-path "$(which claude)"  # drive your installed CLI instead of the bundled one
```

Real runs use the lab defaults from `_sdk_common.py`:
- **Where:** a temp copy of tiny-app as `cwd` (or `--repo PATH`).
- **Caps:** `max_turns` and `max_budget_usd`, range-checked by `common.cc.check_safe`.
- **Isolation:** `setting_sources=[]`, `strict_mcp_config=True`, `CLAUDE_CODE_DISABLE_AUTO_MEMORY=1` and `CLAUDE_CODE_SKIP_PROMPT_HISTORY=1` (no transcript under `~/.claude/projects/`).
- **Permissions:** never `bypassPermissions`. `sdk_permissions.py --real` makes Bash available on purpose, so the callbacks have something to gate: read-only built-in commands run, the hook blocks `rm` and pushes, and `can_use_tool` allows only `python3 -m unittest`.

## Output excerpts (offline)

`sdk_agent.py`:

```
[1] Call the quote_cart handler directly (no model)
  good cart: subtotal $6.10; discount -$0.61 (WELCOME10); tax $0.40 (CA, on the discounted subtotal); total $5.89
  zero quantity: bad item {'sku': 'apple', 'unit_cents': 120, 'qty': 0}: qty must be >= 1, got 0. Each item needs sku, unit_cents >= 0 and qty >= 1. is_error
  unknown code: subtotal $5.00; discount -$0.00 (welcome10); tax $0.20 (NY, on the discounted subtotal); total $5.20
...
[3] Run query() and read every message (replaying agents-2/fixtures/custom_tool.jsonl)
  SystemMessage init: model=claude-haiku-5-5 permissionMode=dontAsk tools=mcp__tinyapp__quote_cart
    mcp_servers: [{"name": "tinyapp", "status": "connected"}]
  AssistantMessage ToolUseBlock: mcp__tinyapp__quote_cart {"region": "CA", "code": "WELCOME10", "items": [{"sku": "apple", "uni…  (message_id msg_lab_tool_01)
  UserMessage ToolResultBlock: ok subtotal $6.10; discount -$0.61 (WELCOME10); tax $0.40 (CA, on the discounted s…
  AssistantMessage TextBlock: The total is $5.89: a $6.10 subtotal, minus $0.61 for WELCOME10 (10%), plus $0.40 Califor…
  ResultMessage: stop_reason=end_turn terminal_reason=completed subtype=success num_turns=2 cost=$0.000902
```

`sdk_permissions.py`, the evaluation-order matrix:

```
#   call                                           mode               resolved at     outcome      callback?  why
1   read a source file                             dontAsk            5 allow rules   ALLOW        no         Read matches; can_use_tool is never consulted
2   rm with a deny rule, in bypass                 bypassPermissions  2 deny rules    DENY         no         Bash(rm *) matches, which holds even in bypassPermissions
3   git push, hook on, in bypass                   bypassPermissions  1 hooks         DENY         no         pushing is blocked in this agent; ask a human to push
4   write .env, acceptEdits                        acceptEdits        1 hooks         DENY         no         .env looks like a secrets file; writes are blocked
5   edit in plan mode with an Edit allow rule      plan               6 can_use_tool  DENY         yes        the callback denied it: this agent proposes changes; it do
6   run the tests, default mode, no allow rule     default            6 can_use_tool  ALLOW        yes        the callback allowed it; updated_input command='python3 -m
7   run the tests, dontAsk, no allow rule          dontAsk            6 can_use_tool  DENY         no         dontAsk denies instead of prompting; the callback isn't ca
8   Bash in bypass, allowed_tools=['Read']         bypassPermissions  4 mode          ALLOW        no         bypassPermissions approves everything that reaches this st
9   ask rule in bypass                             bypassPermissions  6 can_use_tool  DENY         yes        the callback denied it: only `python3 -m unittest` may run
10  Read .env with a deny rule                     default            2 deny rules    DENY         no         Read(./.env) matches, which holds even in default
11  bare Bash deny                                 default            0 availability  not offered  no         bare deny rule 'Bash' removes the tool from Claude's conte
12  MCP tool in acceptEdits, no allow rule         acceptEdits        6 can_use_tool  ALLOW        yes        the callback allowed it
13  MCP tool with mcp__tinyapp__* allow rule       dontAsk            5 allow rules   ALLOW        no         mcp__tinyapp__* matches; can_use_tool is never consulted
14  AskUserQuestion in dontAsk with an allow rule  dontAsk            3 ask rules     DENY         no         needs user interaction; dontAsk never prompts, so it's den
15  read a source file, default, no allow rule     default            5 allow rules   ALLOW        no         a read inside the working directories needs no approval
16  read outside the working directory             default            6 can_use_tool  DENY         yes        the callback denied it: Read isn't approved for this agent
```

Rows 15 and 16 are the working-directory rule: a read inside the working directories needs no approval, and one
outside them goes on to `can_use_tool`. The simulator treats a relative path that stays inside as inside and any
absolute path as outside; it doesn't model network paths, which get a check of their own.

The `bypassPermissions` rows exist only in the simulator; no lab runs that mode. With the real SDK 0.2.168, building `ClaudeAgentOptions` with a bare `allowed_tools` entry and a `can_use_tool` callback emits nothing. The first `query()` (or `ClaudeSDKClient.connect()`) then emits a `CanUseToolShadowedWarning` through `warnings.warn`: an advisory, not an error, and the run goes on. With this lab's real allow list the text is `can_use_tool will not be invoked for: Read, Grep, Glob.`, so `sdk_permissions.py --real` prints it. It restates the documented rule that auto-approved tools never reach `canUseTool`.

`sdk_structured.py`:

```
[1] replay: success with structured_output
  ResultMessage: stop_reason=tool_use terminal_reason=completed subtype=success is_error=False
  result (string): '{"functions":["money","tax_for","apply_discount"]}'
  verdict: ACCEPT  structured_output = {"functions": ["money", "tax_for", "apply_discount"]}
[2] replay: success WITHOUT structured_output
  verdict: REJECT  success but no structured_output: the docs say to treat this as a failure
[3] replay: error_max_structured_output_retries
  query() raised: ResultError after yielding the result (subtype=error_max_structured_output_retries)
  verdict: REJECT  no valid output after retries; errors=['Failed to provide valid structured output after maximum retries']
```

## What real runs showed (2026-10-20, Claude Code v2.1.303, claude-agent-sdk 0.2.168)

Each SDK release bundles a specific CLI, and claude-agent-sdk 0.2.168 bundles Claude CLI 2.1.301 (its
CHANGELOG), and it prefers that bundled binary over a `claude` on your PATH. The recorded init message reports
`claude_code_version: 2.1.303`, so this run drove the installed CLI through `cli_path`
(`--cli-path "$(which claude)"`). Without `--cli-path` you get 2.1.301, which lacks 2.1.302+ behavior such as
`-p` and SDK runs starting in Manual mode; the labs pass `permission_mode` explicitly either way.

- `sdk_agent.py --real` with `setting_sources=[]` failed before reaching the model: `Could not load AWS credentials`, at a cost of $0.
  - **Why:** this machine's Bedrock credentials come from `awsCredentialExport` in `~/.claude/settings.json`, and `setting_sources=[]` doesn't load that file. If your provider auth lives there (`apiKeyHelper`, `awsCredentialExport`, `awsAuthRefresh`, `env`), pass `--setting-sources user` or export the credentials in your shell. The lab now prints that hint.
  - **The stream:** two `system/api_retry` events with `error: "cloud_credential_error"`, an assistant message with model `<synthetic>`, and a result with `subtype: "success"`, `is_error: true`, `terminal_reason: "api_error"`. `query()` then raised `ResultError`. The sanitized transcript is `agents-1/fixtures/api_error.jsonl`.
- **The init message** listed the in-process server as `{"name": "tinyapp", "status": "connected"}` and the tools as `["mcp__tinyapp__quote_cart"]`. With `tools=[]` no built-in tool appeared, not even `ToolSearch`.
- **Not run against a model** (each needs a funded call): `sdk_agent.py --real` after the fix, `sdk_permissions.py --real` and `sdk_structured.py --real`. Their options and callbacks were built and exercised offline with the real 0.2.168 types: `ToolAnnotations`, `create_sdk_mcp_server`, `HookMatcher`, `ToolPermissionContext`, `PermissionResultAllow/Deny`, and `_configure_can_use_tool`, which routes permissions to `stdio`.

## Fixtures

See `fixtures/README.md`. `custom_tool.jsonl` is built from documented shapes. Its init line comes from the real run above, and its `num_turns: 2` for one tool call plus an answer matches the real runs. Treat it as illustrative where the real stream may differ:
- whether a text-only SDK tool's `tool_result.content` arrives as a string or as a list of text blocks (the fixture uses a string, as observed for a stdio MCP tool in the agents-3 run);
- token counts and timings.
