Testing AI Agent Tool Use: Simulators, Contracts, and Side Effects
Test AI agent tool use with stateful simulators, contract checks, fault injection, and side-effect assertions that expose failures fluent answers can hide.
Abhishek Raj · · 8 min read
Prepared with AI research assistance. Sources are linked throughout; worked examples are illustrative unless stated otherwise. Editorial approach.
Testing an AI agent's tool use means checking what the system changed, what it was permitted to change, and what it told the user afterward. A valid function name and well-formed arguments are useful observations, but they do not establish that the intended order was canceled or that another customer's records remained untouched.
This guide proposes a test architecture for a hypothetical appointment-rescheduling agent. The scenario, simulator behavior, and assertions are illustrative engineering designs. They are not results from a deployed system or a complete testing library.
Separate four questions that a successful tool call can hide
Evaluate tool use at four layers:
| Layer | Question | Example assertion |
|---|---|---|
| Contract | Can the executor interpret the request and response? | The appointment identifier is present and the result has a recognized status |
| Authority | Is this actor allowed to perform this operation now? | A patient cannot change another patient's appointment |
| Effects | Did the intended state transition happen? | Exactly the selected appointment moved to the approved slot |
| Communication | Does the answer accurately describe the observed outcome? | A pending operation is not reported as a confirmed change |
Anthropic's evaluation guidance distinguishes an agent's transcript from the outcome in its environment. A booking claim in the transcript does not prove that a reservation exists. It also recommends combining graders and avoiding unnecessarily rigid expectations about the exact sequence an agent follows. Those principles support separating state assertions from conversational grading. Demystifying evals for AI agents.
Write the outcome contract before recording an expected conversation. Otherwise, the first successful demonstration can accidentally become the definition of correctness, including its unnecessary searches and incidental wording.
Use a stateful simulator instead of a bag of canned responses
A response stub that always returns rescheduled: true cannot expose duplicate changes, capacity conflicts, or incorrect appointment selection. A useful simulator represents the minimum business state needed to distinguish acceptable and unacceptable behavior.
For the proposed appointment service, that state includes patients, appointments, available slots, authorizations, operation identities, and a virtual clock. Tool handlers read and modify these records. A second request sees the state produced by the first request; it does not receive the same fixture regardless of history.
The original tau-bench research evaluates interactive agents with domain tools and policy guidelines, comparing the final database state with an annotated goal. Its design is a concrete precedent for checking outcomes in a simulated environment. Its published scores describe that benchmark's original models and tasks, not the reliability of a contemporary scheduling application. Tau-bench paper.
Keep the simulator intentionally smaller than production. Model relevant rules, such as slot capacity and authorization expiry, without reproducing unrelated billing systems. Document omissions. If the simulator assumes instantaneous consistency while the real API exposes delayed confirmation, it cannot establish that the agent handles pending operations correctly.
A useful state snapshot might contain the following fictional values:
{
"patient_id": "patient_example_7",
"appointment_id": "appointment_example_12",
"current_slot": "slot_monday_0900",
"requested_slot": "slot_tuesday_1100",
"appointment_revision": 4,
"authorization_expires_at": 120,
"virtual_time": 80,
"operations": {}
}
Keep identity in trusted executor context. Allowing the model to choose patient_id as its effective identity would test a different, weaker security model.
Make simulator fidelity a separate test target
The simulator is part of the measurement instrument. A bug in its transition rules can make a broken agent look correct or reject a valid recovery.
Create conformance cases that run against both the simulator and a controlled integration environment. Examples include changing an unavailable slot, repeating the same operation identity, reading an appointment after a successful mutation, and using an expired authorization. Compare meaningful state transitions and error classes rather than unstable timestamps or generated identifiers.
Maintain a coverage table connecting each production behavior to a simulator feature and a test. Mark unsupported behavior explicitly. For example, if production permits a clinician override but the simulator does not, exclude override tasks from claims based on that simulator.
Use recorded responses carefully. They help preserve real payload shapes, but can contain personal data and cannot by themselves represent business-state changes. Redact fixtures and keep a record of the API version they describe. The broader interface requirements belong in AI agent tool design.
Inject faults at the boundary where meaning changes
Network failure and business failure need different scenarios. A request rejected before processing is different from a request committed successfully whose response was lost. The agent may observe a timeout in both cases, yet the safe recovery differs.
WireMock's official documentation describes fixed and random delays, chunked response delays, and malformed or interrupted responses. Such facilities are useful for exercising transport behavior. They do not automatically model whether the remote business operation committed; the test environment must represent that separately. WireMock fault simulation.
For this proposed harness, define a fault schedule with explicit phases:
- Before admission: reject the request without changing appointment state.
- After validation: change slot availability before committing the requested move.
- After commit: persist the change, then discard the response.
- During reconciliation: return a temporary status-service failure.
- After cancellation: deliver a late completion event from a previously dispatched request.
Store the schedule independently of the model transcript. A model can paraphrase the same intent, so trigger faults by logical operation identity and execution phase rather than by matching a particular sentence.
Walk through a lost-response rescheduling test
Assume the patient has authorized moving appointment A from Monday to Tuesday. The agent reads revision 4, verifies the selected Tuesday slot, and proposes the move. The executor records a stable operation identity and submits the mutation.
The simulator commits the move and increments the appointment revision, but the fault schedule drops the response. The agent now sees a timeout. A correct result is not necessarily an immediate success sentence: the executor may need to query the operation record and then verify the appointment.
The test checks that the appointment occupies Tuesday's slot, Monday's capacity is released, and no second appointment was created. It also checks that recovery reused the original logical operation identity. A new identity could accidentally create an additional reservation in an API with a different booking contract.
If the status service remains unavailable, the acceptable terminal outcome may be escalation with an explicitly uncertain result. The test should allow that outcome only when the workflow preserves enough evidence for reconciliation. It should reject a confident claim that nothing changed.
The important property is bounded, truthful recovery under uncertainty. See idempotency for agent actions for the execution contract underlying this scenario.
Generate sequences, then preserve minimal failures
Handwritten cases cover known incidents. Generated sequences can explore combinations such as authorize, wait, change availability, retry, cancel, and receive a delayed result.
Hypothesis's stateful testing documentation describes generating sequences of primitive actions and comparing behavior with a simpler reference model. This approach is useful for the deterministic executor and simulator even when invoking a live language model for every generated sequence would be too expensive. Hypothesis stateful tests.
In the proposed design, first generate action sequences against the executor using controlled decision inputs. Check invariants after each transition: capacity never becomes negative, identity boundaries remain intact, and the same logical action does not produce multiple committed effects. Then convert important minimal failures into a smaller agent-level evaluation suite.
Do not expect a random seed alone to reproduce a live model's decisions. Preserve the task snapshot, model and harness versions, observed tool requests, fault schedule, and grader version. Recorded decision replay reproduces one execution path; a fresh model run measures whether current behavior handles the case again. Those are different experiments.
Grade outcomes without hiding prohibited intermediate actions
Final-state checks can miss an unauthorized read that left no mutation behind. Transcript checks can miss an external effect that the tool reported incorrectly. Combine both with an executor-side action ledger.
For each trial, collect separate results for task completion, prohibited actions, outcome-reporting accuracy, and resource limits. A task that reaches the right appointment by reading another patient's records must fail its authority requirement even if the final state is correct.
Use set-based or relational assertions where multiple outcomes are valid. If the patient accepts any Tuesday morning slot, hard-coding 09:00 rejects legitimate alternatives. Conversely, a loose assertion that only checks the day can miss a forbidden clinician change. Define the equivalence class precisely.
Reset all mutable state between trials, including caches, virtual clocks, operation records, and user-simulator memory. Count harness errors separately from agent failures, and investigate both. Run repeated agent trials when estimating consistency; never treat one successful trajectory as a reliability measurement.
Frequently asked questions
Should tests require a specific tool-call order?
Require ordering when it enforces a real dependency, such as authorization before mutation. Otherwise, assert permitted actions and verified outcomes. Different valid investigation paths should be able to pass.
Can a simulator replace integration testing?
No. It makes controlled scenarios and faults repeatable, but its fidelity is limited by its model of the service. Retain integration checks for authentication, real payloads, actual error semantics, and consistency behavior.
Where should an LLM judge be used?
Use deterministic checks for identifiers, effects, permissions, and invariants. A calibrated judge can assess whether the final explanation communicates uncertainty clearly. It should not guess database state from a fluent answer.
Source reference list
Related reading
- AI Agent Tool Design: Schemas, Contracts, and Error Semantics
Design reliable AI agent tools with precise schemas, bounded permissions, structured results, and error contracts that handle retries and uncertain outcomes.
- Idempotency for AI Agent Actions: Preventing Duplicate Side Effects
Prevent duplicate AI agent actions with stable intent identities, immutable request fingerprints, durable ledgers, and recovery for uncertain outcomes.
- AI Agent Regression Testing in CI: Gates That Catch Real Failures
Build AI agent regression gates with versioned manifests, isolated trials, matched comparisons, and release rules that distinguish regressions from noise.