A custom tool through an in-process MCP server

Give Claude one tool, a Python function, and nothing else. @tool and 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 approves the one MCP tool, and permission_mode="dontAsk" denies anything else. Then read every message query() yields.

  • Python 3.9+
  • standard library only
  • offline: the fake SDK, common/sdk_fake.py
  • the agents-2/fixtures/custom_tool.jsonl replay
python3 agents-2/sdk_agent.py

Offline, every agents-2 lab imports common/sdk_fake.py in place of claude-agent-sdk. The fake copies the SDK's public type names, fields and defaults, so code written against the real SDK runs unchanged against it. Its query() replays a fixture: it calls no model and runs no tools, hooks or can_use_tool. That's why step [1] calls the handler directly. This fixture's init line comes from a real SDK run; the rest is built from documented shapes, with the handler's own output as the tool result.

┌───────────────────────────────────────────────────────────────────────┐
│ Agents 2 · sdk_agent: query() + an in-process MCP tool (offline fake) │
└───────────────────────────────────────────────────────────────────────┘
[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
[2] The options: what exists, what is approved, and the caps
  mcp_servers: {'tinyapp': create_sdk_mcp_server(...)}  -> tool name mcp__tinyapp__quote_cart
  tools: []  (no built-ins)
  allowed_tools: ['mcp__tinyapp__quote_cart']
  permission_mode: dontAsk
  caps: max_turns=3, max_budget_usd=0.05
[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
    result: The total is $5.89: a $6.10 subtotal, minus $0.61 for WELCOME10 (10%), plus $0.40 California tax on the discounted $5.4…

  tool calls: mcp__tinyapp__quote_cart

The model never saw a built-in tool: everything it did went through quote_cart.
  1. A bad input comes back as a result with is_error and a message that says how to fix it. Claude reads that like any tool result and can retry; the loop keeps going.
  2. An unknown code isn't an error: the pricing rules give 0% off (codes are case-sensitive here). Keep business outcomes out of is_error.
  3. Availability and approval are separate settings: tools=[] decides what exists, allowed_tools only pre-approves, and dontAsk turns every other call into a denial instead of a prompt.
  4. The init message is where you confirm the in-process server connected and that the MCP tool is the only tool in the session.
  5. Claude sees your function as mcp__<server>__<tool>. That full name is what allowed_tools and permission rules match.
  6. One tool call plus an answer reports num_turns=2, as the real runs did. Read turns and cost from the ResultMessage, after iterating to the end.
  • Handlers are plain async functions, so you can call one with your own input, no model involved. The first call prices four pears in CA ($10.00 plus $0.73 tax). The second breaks it: without unit_cents the handler returns 'is_error': True and its fix-it text instead of raising.
    python3 -c '
    import asyncio, sys; sys.dont_write_bytecode = True; sys.path.insert(0, "agents-2")
    import _sdk_common as lab, sdk_agent
    quote = sdk_agent.make_tools(lab.load_sdk(False))[0].handler
    pears = {"sku": "pear", "unit_cents": 250, "qty": 4}
    print(asyncio.run(quote({"region": "CA", "items": [pears]})))
    print(asyncio.run(quote({"region": "CA", "items": [{"sku": "pear"}]})))'
  • Extend it with the docstring's exercises: a second tool with ToolAnnotations(readOnlyHint=True), or an exception raised inside the handler instead of is_error. The fake doesn't run tools, so test the handler directly as above.

Run the same agent against a model. It costs money and needs Python 3.10+ with claude-agent-sdk in a virtual environment; without the SDK, --real exits 2 with that hint. The run uses a temp copy of tiny-app, setting_sources=[], strict_mcp_config=True, auto memory and transcripts off, and range-checked caps (defaults max_turns=3, max_budget_usd=0.05).

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

--save writes the messages to agents-2/out/sdk_agent_real.json. If your provider credentials live in ~/.claude/settings.json (apiKeyHelper, awsCredentialExport, awsAuthRefresh, env), add --setting-sources user: the course's own real run with setting_sources=[] failed on credentials before reaching the model, at $0. claude-agent-sdk 0.2.168 (checked 2026-10-20) bundles CLI 2.1.301 and prefers it over the claude on your PATH; --cli-path "$(which claude)" drives your installed CLI instead. The budget is checked against Claude Code's client-side estimate and can pass the cap by up to one response.

  • tools decides what exists; allowed_tools only pre-approves. With dontAsk, a call nothing approved is denied, never prompted.
  • A tool error is a result Claude reads: return is_error with a message it can act on.
  • The init SystemMessage is the place to check which tools and MCP servers the session really has.
  • Iterate query() to the end and read cost, turns and the ending from the ResultMessage, stop_reason first.

canUseTool and hooks, in the documented order

Write a PreToolUse hook callback and a can_use_tool callback, unit-test them as plain async functions, then run them through a simulator of the order the SDK documents: hooks, deny rules, ask rules, permission mode, allow rules, can_use_tool. The first step that resolves a call wins, so where you put a check decides whether it ever runs.

  • Python 3.9+
  • standard library only
  • offline: the fake SDK's permission types
  • 16 matrix cases
python3 agents-2/sdk_permissions.py

The simulator is a teaching model of the documented order, not Claude Code's implementation: it leaves out critical paths, protected paths, network paths, mods and auto mode. The bypassPermissions rows exist only here; no lab runs that mode.

┌────────────────────────────────────────────────────────────────────────────┐
│ Agents 2 · sdk_permissions: hooks, rules, modes and can_use_tool, in order │
└────────────────────────────────────────────────────────────────────────────┘
[1] Unit-test the two callbacks directly
      test                                    detail                                                      
────  ──────────────────────────────────────  ────────────────────────────────────────────────────────────
PASS  hook denies rm -rf                      recursive rm is blocked by the lab guard hook               
PASS  hook passes ls with {}                  {} lets the call continue to the next step                  
PASS  hook denies a .env write                                                                            
PASS  can_use_tool rewrites the test command  updated_input adds -q                                       
PASS  can_use_tool denies other shell         only `python3 -m unittest` may run here, not 'curl https://e
PASS  can_use_tool denies edits               interrupt=False: Claude may try something else              
PASS  several hooks: most restrictive wins    deny > defer > ask > allow                                  
[2] The evaluation order: 1 hooks > 2 deny > 3 ask > 4 mode > 5 allow > 6 can_use_tool
#   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

Toy model of the documented order: no critical paths, protected paths, network paths, mods or auto mode.
[3] Wiring it into a real session
  options = ClaudeAgentOptions(
      tools=["Read", "Grep", "Glob", "Bash"],          # availability
      allowed_tools=["Read", "Grep", "Glob"],          # step 5: auto-approved, never reach can_use_tool
      permission_mode="default",                        # step 4 falls through, so step 6 runs
      hooks={"PreToolUse": [HookMatcher(matcher="Bash|Write|Edit", hooks=[guard_hook])]},  # step 1
      can_use_tool=can_use_tool,                        # step 6
      max_turns=4, max_budget_usd=0.05)
  async for msg in query(prompt=prompt_stream(), options=options): ...   # prompt as an async generator
  1. Both callbacks are tested with no model: a hook deny, a pass-through {}, an updated_input rewrite, and a deny with interrupt=False so Claude can try something else.
  2. Row 2 against row 8: bypassPermissions approves Bash at step 4, unless a deny rule at step 2 matches first. Deny rules hold in every mode.
  3. Plan mode sends an allowed Edit to can_use_tool anyway, and the callback refuses it.
  4. dontAsk never calls the callback: anything not approved earlier is denied.
  5. acceptEdits approves file edits and filesystem Bash commands, not MCP tools, so this call reaches the callback.
  6. This comment restates the docs' warning: "Auto-approved tools never reach canUseTool" (SDK permissions). A check that must always run belongs in the hook.

Walk one row through the steps:

python3 agents-2/sdk_permissions.py --case 5
┌────────────────────────────────────────────────────────────────────────────┐
│ Agents 2 · sdk_permissions: hooks, rules, modes and can_use_tool, in order │
└────────────────────────────────────────────────────────────────────────────┘
[2] The evaluation order: 1 hooks > 2 deny > 3 ask > 4 mode > 5 allow > 6 can_use_tool
  call: Edit {'file_path': 'tinyapp/cart.py', 'old_string': 'a', 'new_string': 'b'}
  config: mode=plan allow=['Edit'] deny=[] ask=[] hook=on
   1 hooks: pass
   2 deny rules: no match
   3 ask rules: no match
   4 mode: plan sends file edits to can_use_tool regardless of allow rules and hooks
   6 can_use_tool: DENY (the callback denied it: this agent proposes changes; it doesn't edit files)
  1. An Edit allow rule, plan mode and the hook on.
  2. The hook has no opinion on this edit. Even a hook allow wouldn't skip the deny and ask rules.
  3. Plan mode sends the edit straight to step 6, so the Edit allow rule at step 5 never applies, and the callback's deny is the answer.
  • --case 7: the same test command in dontAsk stops at step 6 without calling the callback. --case 12: acceptEdits falls through for an MCP tool and the callback allows it. --case 11: a bare Bash deny means the tool is never offered at all.
  • Break it: move the .env check out of the hook. Row 4 with the hook off goes to step 4, where acceptEdits approves the write, so a check in can_use_tool would never see it:
    python3 -c '
    import asyncio, sys; sys.dont_write_bytecode = True; sys.path.insert(0, "agents-2")
    import sdk_permissions as p
    sdk = p.lab.load_sdk(False)
    env = p.Case("write .env, no hook", "Write", {"file_path": ".env"},
                 p.Config("acceptEdits", use_hook=False))
    for line in asyncio.run(p.evaluate(sdk, env, p.make_can_use_tool(sdk)))["trail"]:
        print(line)'
  • An out-of-range --case 99 exits 2 with error: --case must be 1..16.

Gate a real session with the same two callbacks. It costs money and needs Python 3.10+ with claude-agent-sdk. The run 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. Defaults: max_turns=4, max_budget_usd=0.05.

python3.13 -m venv .venv && . .venv/bin/activate
pip install claude-agent-sdk
python agents-2/sdk_permissions.py --real --model haiku \
    --max-budget-usd 0.05

Expect one advisory, not an error: with this lab's allow list the real SDK 0.2.168 prints can_use_tool will not be invoked for: Read, Grep, Glob. (a CanUseToolShadowedWarning) on the first query(), and the run goes on. This --real path hasn't been run against a model by the course; its options and callbacks were exercised offline with the real 0.2.168 types. The budget can pass the cap by up to one response.

  • Read the "resolved at" column: can_use_tool runs only in rows where nothing earlier decided.
  • Hooks run first, and a hook deny holds in every mode. Allow rules, acceptEdits and bypassPermissions approve before your callback.
  • dontAsk is the locked-down mode: allow rules plus denial for everything else.

Structured output and every way it fails

Ask for output_format={"type": "json_schema", "schema": …}, accept a result only by the documented rule, and validate it again on your side. Three replays show the one usable result and the two documented failures: success with no structured_output, and error_max_structured_output_retries.

  • Python 3.9+
  • standard library only
  • offline: the fake SDK
  • 3 result fixtures (one sanitized real capture, two derived)
python3 agents-2/sdk_structured.py
┌─────────────────────────────────────────────────────────────────────┐
│ Agents 2 · sdk_structured: output_format json_schema (offline fake) │
└─────────────────────────────────────────────────────────────────────┘
[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
  ResultMessage: stop_reason=end_turn terminal_reason=completed subtype=success is_error=False
  result (string): 'The functions are money, tax_for and apply_discount.'
  verdict: REJECT  success but no structured_output: the docs say to treat this as a failure
[3] replay: error_max_structured_output_retries
  ResultMessage: stop_reason=tool_use terminal_reason=structured_output_retry_exhausted subtype=error_max_structured_output_retries is_error=True
  result (string): None (result exists only on success)
  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']

Only the first replay is usable. A pipeline that checked subtype alone would accept the second.
  1. In the real capture this replays, a structured run ends with stop_reason=tool_use and result holds the same JSON as a string. Read structured_output, not result.
  2. Success, completed, no error, and still unusable: no structured_output. The docs say to "Treat that case as a failure as well" (structured outputs).
  3. Retries ran out: result is None (it exists only on success), and the single-shot query() raises ResultError after yielding the result. Catch it and keep the ResultMessage.
  4. Check errors to tell a validation failure from a model-fallback retraction; the text here is illustrative.
  • --schema prints the schema (draft-07, additionalProperties: false) and the matching claude -p … --output-format json --json-schema '…' command. That command is a real, paid run with --max-turns 4 --max-budget-usd 0.05; the lab doesn't run it.
  • Break it: feed the lab's local validator a value the schema rejects. It reports both problems, the extra key and the wrong item type:
    python3 -c 'import sys; sys.dont_write_bytecode = True; sys.path.insert(0, "agents-2")
    import sdk_structured as s
    print(s.validate({"functions": ["money", 3], "author": "me"}, s.SCHEMA))'

Ask a model for the structured answer. It costs money and needs Python 3.10+ with claude-agent-sdk; it runs read-only (Read, Grep, Glob) in a temp copy of tiny-app. Defaults: max_turns=4, max_budget_usd=0.05.

python3.13 -m venv .venv && . .venv/bin/activate
pip install claude-agent-sdk
python agents-2/sdk_structured.py --real --model haiku \
    --max-budget-usd 0.05

Leave at least two or three turns: in real CLI runs the structured answer arrived through a tool call, so --max-turns 1 ended in error_max_turns. This --real path hasn't been run against a model by the course. The budget can pass the cap by up to one response.

  • The acceptance rule, in order: stop_reason isn't refusal, terminal_reason (when present) is completed, subtype is success, and structured_output is present.
  • A pipeline that checks subtype alone accepts replay 2.
  • Validating again locally is cheap insurance: your code checks exactly the shape it depends on.