Module: L1-M05 · Duration: ~180 min (estimate, including the independent exercise) · Previous: L03 · Next: L05 - Testing a tool-using chat agent (single agent, mock tools)
1. Introduction
In L03, the model asks and the application runs. But should it run? A tool call can be structurally valid and still be wrong: returning 3 items when the order has only 2, returning an order that has not been delivered, creating a return order when the customer has not agreed. With a tool that has side effects, a wrong call does not just give a wrong answer; it also changes real data, for example by issuing a refund.
OWASP calls this risk Excessive Agency: "the vulnerability that enables damaging actions to be performed in response to unexpected, ambiguous or manipulated outputs from an LLM" [R1]. This lesson teaches you to test the application's layers of protection: argument validation, business rules, user approval, and how the application answers the model when a call is rejected.
2. Learning objectives
- Explain why
strict: truecannot replace argument validation in code. - Design argument-validation cases by group: type, range, enum, pattern, missing, extra, business rule.
- Verify that a bad call is not run and is answered with
is_error: true. - Verify the approval gate for a tool with side effects, both when it is approved and when it is declined.
- Verify the behaviour when a turn is cut off (
max_tokens) or refused, when a tool fails and when the loop runs too long.
3. Prerequisites and tools
4. Concepts
4.1 What strict guarantees, and what it does not
strict: true guarantees that the tool's input matches the schema that is sent (L02). But:
- The schema that is sent has dropped
minimum,maximum(not supported) andpattern(the lab's choice, L02), so in the labquantity: 0ororder_id: "se1003"can still appear. - Business rules are not in the schema: does the order exist, has it been delivered, does the quantity exceed the number ordered.
- A call that is right in every respect can still be not what the customer wants, for example because of a misunderstanding or of prompt injection (L1-M04-L04).
That is why OWASP advises treating the model's output like input from an untrusted user [R2], and for high-impact actions: "Utilise human-in-the-loop control to require a human to approve high-impact actions before they are taken" [R1].
Everyday example. An ATM checks that the recipient's account number has the right number of
digits: that is strict, the right shape. But the machine does not know whether the account exists,
whether you have enough money, or whether you really want to send money to a stranger who just texted
you. So the bank adds business rules and an OTP code (approval). The right shape is not yet the right
action.
4.2 The layers of protection in the lab
| Layer | Question | In the lab |
|---|---|---|
| 1. Full schema | Do the arguments have the right type, range, format? | validate_call() uses INPUT_SCHEMAS |
| 2. Business rules | Is the action valid against the real data? | validate_call(): the order exists, is delivered, the quantity |
| 3. Approval | Does the customer agree to the action with side effects? | approve(name, args), declines by default |
| 4. Loop limit | Can the agent loop forever? | max_steps |
OWASP lists three root causes of Excessive Agency: "excessive functionality; excessive permissions; excessive autonomy" [R1]. Layer 3 reduces "autonomy", layer 4 stops infinite loops. Permissions (for example, a customer may only return their own orders) are an extension in Level 2.
Worked example: one call through layers 1 and 2. Four create_return calls, each changing one
thing compared with the demo's valid call:
python -c "from lab.tools import validate_call; ok = {'order_id': 'SE1003', 'reason': 'damaged', 'quantity': 1}; [print(validate_call('create_return', a)) for a in ({**ok, 'order_id': 'SE9999'}, {**ok, 'reason': 'Damaged'}, {**ok, 'refund_to': 'cash'}, {**ok, 'order_id': 'SE1001', 'quantity': 3})]"
['order SE9999 does not exist']
["$.reason: 'Damaged' is not one of ['damaged', 'wrong_item', 'changed_mind']"]
["$: Additional properties are not allowed ('refund_to' was unexpected)"]
['order SE1001 is shipped, not delivered']
| Call | Blocked by layer | Why |
|---|---|---|
order_id: "SE9999" |
2 | Matches the pattern, but the order is not in ORDERS |
reason: "Damaged" |
1 | The enum is case-sensitive |
adds refund_to |
1 | additionalProperties: false |
SE1001, quantity: 3 |
2 | The order is not delivered. SE1001 only has 1 item, but the quantity problem is not reported: layer 2 stops at the first broken rule |
The last row is why each business rule needs its own case, breaking only that rule. Output run on 2026-11-06 on Python 3.14.6 and 3.12.3, Linux, identical on both versions; so is every other output in this lesson.
4.3 Answering the model when a call is rejected
When it does not run a call, the application must still answer that tool_use (L03), with a tool_result that has
is_error. The documentation: "is_error (optional): Set to true if the tool execution resulted in an error" [R3].
The content should be:
- short and useful, so that the model can correct itself (for example "quantity 3 is more than the 2 items ordered");
- free of internal details (stack traces, table names, file paths).
Good vs bad: the content of a tool_result when a call is rejected or a tool fails.
| Weak | Good |
|---|---|
tool error: KeyError('internal_table_7') at /srv/shop/returns.py line 88 |
tool error: the service is unavailable |
error |
invalid arguments: quantity 3 is more than the 2 items ordered |
The first weak one leaks a table name and a path, and the model may repeat them to the customer (situation 2, section 7). The second weak one does not tell the model what to fix, so it may well make the same call again. The two good ones are exactly the sentences the lab's agent sends.
4.4 A cut-off or refused turn
The "Stop reasons and fallback" page says: if "the truncated response contains an incomplete tool use block,
you'll need to retry the request with a higher max_tokens value to get the full tool use" [R4]. A cut-off
tool_use may have an input with missing fields. Never run a tool from a max_tokens or refusal turn.
The agent in the lab ends the turn with an error and rolls back the history, that is, it deletes the messages of
that turn. Otherwise, the tool_use block without a tool_result would make the next request be rejected (L03).
Worked example: a turn cut off in the middle of a tool_use. The (fake) model is cut off while
writing a create_return call, so the input lacks reason and quantity. Save this as
try_l04_cut.py in the lab folder and run python try_l04_cut.py:
import os
os.environ["ANTHROPIC_API_KEY"] = "sk-test-fake-key-0000" # fake key: the fake API only
from lab.agent import OrderAgent, make_client
from lab.fake_api import FakeClaudeAPI, message, text, tool_use
from lab.tools import MockOrderSystem
with FakeClaudeAPI() as api:
backend = MockOrderSystem()
agent = OrderAgent(make_client(api.base_url), backend, approve=lambda n, a: True)
api.queue(message(tool_use("create_return", {"order_id": "SE1003"}, "toolu_01"), stop_reason="max_tokens"))
turn = agent.send("Trả 1 cái đơn SE1003, hàng hỏng")
print("turn 1:", turn.error, "| backend.calls:", backend.calls, "| history:", len(agent.messages))
api.queue(message(text("Bạn muốn trả mấy sản phẩm?")))
turn = agent.send("Bạn còn đó không?")
print("turn 2:", turn.error, "|", turn.text, "| history:", len(agent.messages))
turn 1: truncated | backend.calls: [] | history: 0
turn 2: None | Bạn muốn trả mấy sản phẩm? | history: 2
| Step | Observation | Meaning |
|---|---|---|
| Turn 1 | truncated, backend.calls: [] |
No tool ran, even though approve always returns True |
| After turn 1 | history: 0 |
The rollback removed both the customer's message and the cut-off tool_use |
| Turn 2 | No error, history: 2 |
The next request is valid; no tool_use is left without a result |
Delete the file when you are done.
5. Technical deep dive
5.1 validate_call(name, args)
problems = validate(args, INPUT_SCHEMAS[name]) # lớp 1: schema đầy đủ
if problems: return problems
if name == "create_return": ... # lớp 2: đơn tồn tại, đã giao, số lượng
In English: the comments read "layer one: the full schema" and "layer two: the order exists, is delivered, the quantity".
Layer 2 runs only when layer 1 has passed, so args["quantity"] is certainly an integer.
5.2 OrderAgent._run()
The order in the lab: validate the arguments, then ask for approval (only for tools with side effects), then run.
Each branch creates a tool_result and records the outcome (ok, invalid, declined, failed) in
turn.tool_calls. An unexpected exception is replaced by a generic sentence that reveals no details.
5.3 MockOrderSystem
The fake backend records every call in backend.calls. backend.side_effects() returns only the calls with side
effects. The strongest oracle in this lesson is backend.side_effects() == []: it checks the consequence, and it
does not depend on the model's wording.
Everyday example. To know whether a crate has left the warehouse, a manager reads the dispatch
log, not what the salesperson told the customer. "I have sent it" may be wrong; the dispatch log
records what actually happened. backend.side_effects() is the dispatch log; the model's answer is the
salesperson's words.
5.4 The Python you need for this lesson
lambda n, a: Trueis a short function that takes two arguments and always returnsTrue. The tests use it asapprove.seen.append(x) or True:appendreturnsNone, andNone or TrueisTrue. This trick both records the call and approves it.A subclass that overrides
runto simulate an unexpected error:class Broken(MockOrderSystem): def run(self, name, args): raise KeyError("internal_table_7")Simulating an API error (contract A9):
api.queue(Reply(status=500, body=error_body("api_error", "boom"))).Replyanderror_bodyare inlab/fake_api.py; the argument order is the same as in the fake of L1-M03.
6. The QA perspective
| Case group | Example with create_return |
Expected |
|---|---|---|
| Type | quantity: "1", quantity: 1.5 |
Not run; is_error |
| Range | quantity: 0, quantity: 6 |
Not run |
| Enum (including capitalisation) | reason: "Damaged" |
Not run |
| Pattern | order_id: "se1003" |
Not run |
| Missing, extra | reason missing; refund_to added |
Not run |
| Business | the order does not exist; not delivered; returning 3 when there are 2 | Not run; the message states the reason |
| Approval | the customer does not agree / agrees | No side effect / exactly one side effect |
| Tool error | backend timeout; unexpected exception | is_error; no stack trace |
| Abnormal turn | max_tokens, refusal |
No tool runs; the history stays valid |
| Loop | the model keeps calling tools | Stops after max_steps |
- Severity: a side effect that was not approved, or that ran with wrong arguments, is the most serious bug, because it changes real data.
- How to report: the tool, the exact arguments, which layer of protection should have blocked it, and the
consequence (
side_effects).
7. Real-world scenarios
Scenario 1 (fictional): "approve damaged items straight away". To reduce manual steps, the team allows return orders with the reason "damaged" to be approved automatically. A customer writes "hàng hỏng" ("damaged goods") even for an order not yet received, and the model creates a return order. A test "every reason needs approval" would have blocked this change before the merge.
Scenario 2 (fictional): a stack trace in the answer. A failing tool returns repr(exception) to the model,
including the name of an internal table. The model repeats part of it to the customer. A test "the error message
contains no internal details" catches this bug with a fake backend that raises an exception carrying the table
name.
8. Hands-on tutorial
8.1 Running the demo
python -m lab.demo l04
Output (copied from a real run, 2026-10-31):
{"order_id": "SE1003", "reason": "damaged", "quantity": 1} -> OK
{"order_id": "SE1003", "reason": "damaged", "quantity": 0} -> ['$.quantity: 0 is less than the minimum of 1']
{"order_id": "SE1003", "reason": "damaged", "quantity": "1"} -> ["$.quantity: '1' is not of type 'integer'"]
{"order_id": "SE1003", "reason": "damaged", "quantity": 3} -> ['quantity 3 is more than the 2 items ordered']
{"order_id": "SE1001", "reason": "damaged", "quantity": 1} -> ['order SE1001 is shipped, not delivered']
without approval: [('create_return', {'order_id': 'SE1003', 'reason': 'damaged', 'quantity': 1}, 'declined')] | side effects: []
tool_result sent: {'type': 'tool_result', 'tool_use_id': 'toolu_01', 'content': 'the customer did not approve this action', 'is_error': True}
The first five lines show layer 1 (schema) and layer 2 (business rules). The last two lines: without approval there
is no side effect, and the model receives a tool_result with is_error: True.
8.2 Running the tests
python -m pytest tests/test_l04_tool_args.py -v
Read test_no_tool_runs_on_an_incomplete_turn_and_history_stays_valid: after a cut-off turn, the next send() still
works. That is the evidence that the rollback works.
8.3 Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
| The approval test always passes even when the code is wrong | The test's default approve returns True |
Test both branches: approved and not approved |
BadRequestError on the turn after a max_tokens |
The history still has a tool_use without a result |
Roll back, or do not add the assistant message of the cut-off turn |
KeyError in validate_call |
Layer 2 was called before layer 1 passed | Keep the right order: schema first, business rules after |
9. Independent exercise
Problem: Prove that no bad create_return call is run, even when the customer has agreed.
Requirements: complete exercises/test_l04_bad_calls.py:
- Add at least 6 bad argument dicts to
BAD_CALLS, each wrong in a different way (the table in §6), named withpytest.param(args, id="..."). - Include at least one business-rule case and one enum-capitalisation case.
- Write 3-5 sentences: why does this test use
approve=lambda n, a: True?
Test data: ORDERS in lab/tools.py.
Deliverable: the completed test file and the explanation.
Acceptance criteria: the test file passes; each case has a descriptive id; the explanation states that if
approve returned False, the test would pass for a different reason (the approval was declined) and would not
prove the argument validation.
Hint: pytest.param({...}, id="range-low") names a case in pytest's output.
9.1 Extra exercise: an oracle for the outcome of one call (20-30 minutes)
Problem: OrderAgent._run() checks the arguments, then asks for approval (side-effect tools
only), then runs the tool (section 5.2). You write an independent oracle that says beforehand what
must happen to one call, and let the tests compare it with what the agent really does.
Requirements:
- Run
python -m pytest exercises/test_l04_extra_outcome_oracle.pyonce, untouched:13 failed, each failure starting withTODO. - Write
expected_outcome(args, approved)returning"invalid","declined"or"ok". You may usevalidate_call()for layers 1-2; this exercise checks the order of layers 1-3. - In TODO 2, fill in the outcome of three cases by hand before running, using
ORDERSinlab/tools.py.
Acceptance criteria: 13 passed. The tests check at once the outcome, the is_error flag sent to
the model, whether approval was asked, and the number of side effects.
Hint: the case too-many-not-approved (returning 3 when the order has 2, not approved) is the case
that tells the two orders apart. If your oracle returns "declined" for it, reread section 5.2.
9.2 Real-world scenario: a money-transfer tool in an e-wallet (fictional)
Context. The fictional e-wallet ViXanh adds a chat assistant with the tool transfer_money(to_phone, amount_vnd, note). Current design: a strict schema; at most 20.000.000 VND per transfer; every
transfer needs the customer to enter an OTP, except transfers under 500.000 VND, "to save hassle";
the agent makes at most 5 requests per turn. A tester has already seen the model call transfer_money
twice in a row for one request when the recipient had just changed phone number.
Task: write (a) a risk list following the four protection layers in section 4.2, each risk with a severity; (b) at least 6 test cases; (c) a recommendation (3-5 sentences) on the exception "under 500.000 VND needs no OTP".
A good answer has:
- Tests the approval gate on both branches: with the OTP, exactly one transfer; without it, no transfer at all, checked in a fake transaction log, not in the model's answer
- Tests wrong arguments with approval switched on (for example
amount_vnd: 0,amount_vnd: 20000001, a badly formatted phone number), expecting no transaction - Tests a turn cut off in the middle of a
tool_use(max_tokens), expecting no transaction - Spots the duplicate-call risk: two identical calls in one turn can become two transactions; proposes a test and a safeguard (duplicate lock, idempotency key)
- The recommendation on the 500.000 VND exception gives reasons: many small transfers still add up, and prompt injection can exploit the threshold (Excessive Agency)
- A
tool_resultfor a rejection contains no internal details and not the customer's balance
10. Knowledge check
0/20 done · Results are kept in this browser only.
P02 · True or false
P03 · Short answer
Why must you never run a tool from a response with stop_reason: "max_tokens"?
P04 · Short answer
Name two requirements for the content of an error tool_result.
P05 · Essay
(Scenario) The product owner wants return orders below 100,000 dong to be approved automatically. Write 4-6 sentences: which tests do you need to add before you agree?
P06 · Match
P08 · Multiple choice
P09 · Spot the bug
The business-rule part below was copied from validate_call() in lab/tools.py but has one bug. Find it.
if name == "create_return":
order = ORDERS.get(args["order_id"])
if order is None:
return [f"order {args['order_id']} does not exist"]
if order["status"] != "delivered":
return [f"order {args['order_id']} is {order['status']}, not delivered"]
if args["quantity"] >= order["quantity"]:
return [f"quantity {args['quantity']} is more than the {order['quantity']} items ordered"]
return []P10 · True or false
P11 · Select all that apply
P12 · Recall
Lesson: L1-M05-L03P13 · Short answer
Why does approve=lambda n, a: seen.append((n, a)) or True both record and approve? Which test in the lab uses it, to prove what?
P14 · True or false
P15 · Short answer
With the Broken backend in §5.4 (raising KeyError("internal_table_7")), what must a test assert about the tool_result sent to the model?
P17 · Multiple choice
P18 · True or false
P19 · Spot the bug
Here is a wrong solution to extra exercise §9.1. Find the defect.
def expected_outcome(args, approved):
if not approved:
return "declined"
if validate_call("create_return", args):
return "invalid"
return "ok"P20 · Apply now
In code-labs/l1-m05, run python -m pytest exercises/test_l04_extra_outcome_oracle.py once untouched, then do extra exercise §9.1 and run it again.
11. Summary
- Concepts: Excessive Agency; the limits of
strict; the four layers of protection;is_error; never running a tool from a cut-off turn; rolling back the history. - Skills: designing argument cases by group; checking side effects with a fake backend; testing both branches of the approval gate.
- Pitfalls: believing
strictis enough; testing only the approved branch; leaking internal details in errors; running a tool from a cut-off turn. - You can now: assess and verify the layers of protection around a tool with side effects.
12. References
| ID | Title | Publisher | URL | Accessed | Relevance |
|---|---|---|---|---|---|
| R1 | LLM06:2025 Excessive Agency | OWASP GenAI Security Project | https://genai.owasp.org/llmrisk/llm062025-excessive-agency/ | 2026-10-31 | Definition, three root causes, human approval |
| R2 | LLM05:2025 Improper Output Handling | OWASP GenAI Security Project | https://genai.owasp.org/llmrisk/llm052025-improper-output-handling/ | 2026-10-31 | Zero trust towards model output |
| R3 | Handle tool calls | Anthropic | https://platform.claude.com/docs/en/agents-and-tools/tool-use/handle-tool-calls | 2026-10-31 | is_error |
| R4 | Stop reasons and fallback | Anthropic | https://platform.claude.com/docs/en/build-with-claude/handling-stop-reasons | 2026-10-31 | A tool_use cut off at max_tokens |
Key terms (English ↔ Vietnamese)
| English | Tiếng Việt |
|---|---|
| Excessive Agency | Trao quá nhiều quyền hành động cho model |
| Business rule | Quy tắc nghiệp vụ |
| Human-in-the-loop / approval gate | Con người phê duyệt / cổng phê duyệt |
| Rollback | Hoàn tác lịch sử về trạng thái trước |
| Side effect | Tác dụng phụ |