Tool Testing and Observability

Test the tool, test how the model uses it, then watch both in real use.

BeginnerIntermediateExpert · 13 min read · Last updated:

In short

Tool quality has two sides: does the tool behave correctly, and does the agent choose and call it correctly? Test the first with ordinary deterministic tests and the second with repeated evaluation on realistic requests. In production, record each call as a structured trace event without leaking sensitive data, and watch success, errors, latency, cost and real effects per tool.

What you will learn: contract tests, test doubles, evaluating tool selection and arguments, trace design, privacy, metrics, alerts and turning incidents into tests.
Prerequisites: Designing Tool Schemas and Contracts and Reliable Tool Execution and Error Recovery.

Beginner Two things to test

Layers of testing

Function testslogic and edge cases
Contract testsschema, errors, effects, permissions
Integration testsreal or sandbox services
Tool-use evaluationmodel chooses and fills calls
End-to-end tasksoutcomes in the system of record
Upper layers in this list are fast and exact; lower ones are slower and statistical.

Contract tests

A contract test checks the promises a tool makes, whatever its implementation. State-changing tools should pass at least these.

PromiseTest
Valid requests succeedTypical input gives the declared shape
Forbidden callers failNo effect occurs
Invalid input failsSpecific error; no effect
Repeats are safeSame key gives one effect
Keys are not reusableSame key with different input is refused
Limits holdOversized input is rejected
Failures are classifiedDependency errors map to the right class
"""Contract tests that every state-changing tool should pass."""

class TicketTool:
    def __init__(self):
        self.tickets, self.keys = [], {}

    def create(self, user, title, key):
        if user != "agent-with-write":
            return {"ok": False, "error": "denied"}
        if not title.strip():
            return {"ok": False, "error": "invalid"}
        if key in self.keys:
            return {"ok": True, "id": self.keys[key]}
        self.tickets.append(title)            # bug: length is not limited
        self.keys[key] = len(self.tickets)
        return {"ok": True, "id": self.keys[key]}

def valid(t):
    return t.create("agent-with-write", "Printer down", "k1")["ok"]

def denied(t):
    out = t.create("reader", "Printer down", "k1")
    return out["error"] == "denied" and not t.tickets

def blank(t):
    out = t.create("agent-with-write", "   ", "k1")
    return out["error"] == "invalid" and not t.tickets

def repeat(t):
    a = t.create("agent-with-write", "Printer down", "k1")
    b = t.create("agent-with-write", "Printer down", "k1")
    return a == b and len(t.tickets) == 1

def oversized(t):
    out = t.create("agent-with-write", "x" * 10_000, "k1")
    return not out["ok"] and not t.tickets

def reused_key(t):
    t.create("agent-with-write", "Printer down", "k1")
    out = t.create("agent-with-write", "Delete account", "k1")
    return not out["ok"]

tests = [valid, denied, blank, repeat, oversized, reused_key]
results = [(test.__name__, test(TicketTool())) for test in tests]
for name, passed in results:
    print(f"{'PASS' if passed else 'FAIL'}  {name}")
print(sum(p for _, p in results), "of", len(results), "passed")

Output:

PASS  valid
PASS  denied
PASS  blank
PASS  repeat
FAIL  oversized
FAIL  reused_key
4 of 6 passed

The tool handles the usual cases and still fails two promises: it accepts a ten-thousand-character title, and it answers a reused key with the old ticket although the request differs. The second is subtle, because the caller believes "Delete account" was filed. The tests for denied, blank and oversized requests check state as well as the reply, which matters: a tool can report an error and still have changed something.

Test doubles

DoublePurpose
StubReturns fixed answers
FakeSmall working version with in-memory state
RecorderCaptures calls for assertions
Fault injectorAdds delay, errors, bad data and lost replies
Provider sandboxThe real interface with test data

Check your fakes against the real service regularly. A fake that accepts what production rejects gives false confidence.

Rehearse failures on purpose

Most surprising behavior appears when a dependency misbehaves. Configure the fake service to produce each condition and state what should happen.

Injected faultExpected result
Slow beyond the time limitCall stops; write reported as unknown
Reply lost after successLookup by key; no second effect
Rate limit replyWait as instructed, within the task budget
Malformed or missing fieldsClassified error, not a guessed value
Permission removed mid-taskClean denial, no workaround
Empty resultReported as empty, with the search scope

Keep these cases deterministic by controlling the clock and the order of replies. A test that fails now and then for timing reasons soon gets ignored.

Write a good contract test

  • Start from a known state and build it inside the test.
  • Check the reply and the state, including that nothing else changed.
  • Assert on error classes, not exact message wording.
  • Name the promise, so a failure reads as a broken rule.
  • Run the same suite against the fake and the provider sandbox.

When the schema changes, keep a few requests in the old form and decide whether they should still work. Callers such as saved workflows may send them long after you have moved on.

Intermediate How the model uses tools

Evaluate selection and arguments

Collect requests with the expected behavior, including cases where the right answer is to call nothing, ask a question or refuse.

Case typeExpected behavior
Clear requestCorrect tool, correct arguments
Missing informationAsk, do not invent
Look-alike toolsPick the intended one
No suitable toolSay so
Forbidden actionNo attempt, or a clean refusal
Tool errorRecover sensibly or report honestly
Hostile text in a resultNo unauthorized follow-up
MeasureDefinition
Selection accuracyCases with the expected tool or none
Argument accuracyCalls whose values are correct, not only valid
Unnecessary callsCalls that were not needed
Order correctnessRequired steps before consequential ones
Outcome successThe record ends in the intended state
Honest reportingThe reply matches what happened

Accept several valid routes where they exist; demanding one exact sequence punishes good behavior. Run each case more than once, report rates with sample sizes and treat safety cases as pass or fail. See Agent Evaluation Framework and Math, Search and Algorithms for Agent Engineers.

Where cases come from

Interview the people who do the task today, read support requests and, once live, mine traces for confusing or failed runs. Write each case with the starting state, the request, the acceptable behavior and the reason. Remove personal data before saving it. Include requests in the different words and languages your users really use. A case nobody can explain later is hard to maintain, so keep the reason short and specific.

When to run what

TriggerRun
Every code changeFunction and contract tests with doubles
Description, schema, prompt or model changeTool-use evaluation
Before releaseEnd-to-end and adversarial cases
Daily or weeklyChecks against provider sandboxes for drift

Reading the scores

Suppose 60 cases are each run three times and 162 of the 180 calls choose the expected tool: selection accuracy is 90 percent. That total can hide a concentrated problem. If 15 of the 18 failures come from one pair of look-alike tools, the fix is in those two descriptions, and the other tools are doing well. Break results down by tool and case type, read the failures, and compare a change with the previous version on the same cases. Small differences on a small set may be chance, so add cases before drawing a conclusion. Hold some cases back while tuning descriptions, otherwise you will fit the wording to the test.

Expert Seeing production

One event per call

Record the same fields for every tool so that questions can be answered across them.

  • Task, run and call identifiers, and the parent step.
  • Tool name and version.
  • Safe representation of arguments.
  • Policy decision and approval reference.
  • Outcome class, duration, attempts and result size.
  • Idempotency key and external reference.
"""Record one safe event per tool call, then summarize by tool."""
import hashlib
import json
from collections import defaultdict

SAFE = {"city", "limit"}                  # arguments safe to store as text
events = []

def record(run, tool, args, outcome, ms):
    shown = {k: (v if k in SAFE else "hidden:" + hashlib.sha256(
        str(v).encode()).hexdigest()[:8]) for k, v in args.items()}
    events.append({"run": run, "tool": tool, "args": shown,
                   "outcome": outcome, "ms": ms})

data = [("r1", "search", "ok", 120), ("r1", "book", "ok", 900),
        ("r2", "search", "ok", 140), ("r2", "book", "timeout", 5000),
        ("r2", "book", "ok", 950), ("r3", "search", "empty", 90),
        ("r3", "search", "empty", 95), ("r3", "search", "empty", 92),
        ("r4", "search", "ok", 130), ("r4", "book", "invalid", 20)]
for run, tool, outcome, ms in data:
    record(run, tool, {"city": "Oslo", "email": "kim@example.com"},
           outcome, ms)

print(json.dumps(events[0]))
by_tool = defaultdict(list)
for event in events:
    by_tool[event["tool"]].append(event)
for tool, rows in by_tool.items():
    bad = sum(r["outcome"] not in ("ok", "empty") for r in rows)
    slowest = max(r["ms"] for r in rows)
    print(f"{tool:<7} calls={len(rows)} errors={bad} slowest={slowest} ms")

runs = defaultdict(list)
for event in events:
    runs[(event["run"], event["tool"])].append(event["outcome"])
for (run, tool), outcomes in runs.items():
    if len(outcomes) >= 3 and set(outcomes) != {"ok"}:
        print(f"check {run}: {tool} called {len(outcomes)} times,",
              f"outcomes {sorted(set(outcomes))}")

Output:

{"run": "r1", "tool": "search", "args": {"city": "Oslo", "email": "hidden:5d9a0087"}, "outcome": "ok", "ms": 120}
search  calls=6 errors=0 slowest=140 ms
book    calls=4 errors=2 slowest=5000 ms
check r3: search called 3 times, outcomes ['empty']

Only listed arguments are stored as text; the email address appears as a short digest. The summary shows booking errors and a slow call, and flags a run that searched three times with nothing found, a pattern that deserves attention even though no call failed. A digest of a guessable value can be reversed by trying candidates, so it is not anonymization. Use a keyed digest, a token from a protected service or omit the value, according to your privacy rules.

Standard names

OpenTelemetry has conventions for generative AI, including a span for executing a tool with attributes such as the tool name and call identifier. As of late 2026 sources describe these conventions as still in Development status, maintained in a separate repository since June 2026, so names may change. Record which version you emit and put your own business fields in your own namespace. Propagate trace context to downstream services so that one trace shows the whole path. See Agent Tracing and OpenTelemetry.

Questions your traces should answer

Design the fields backward from the questions. Can you list every write made for one user yesterday? Which tool version produced this result? Was the action approved, and by whom? Did latency come from the tool, the model or waiting for a person? Which tasks ended after a denial? How many tokens did this tool's results add to context? If a question cannot be answered from a test trace, add the field now, while it is cheap. Use consistent names and units, record times with offsets, and keep clock differences between machines in mind when ordering events. Order steps by parent and child links where you can.

Safe logging

  • Default to metadata; capture content only with a purpose, access control and retention period.
  • Never log credentials or authorization headers.
  • Redact before export, not after storage.
  • Restrict and audit access to traces.
  • Honor deletion duties that apply to personal data.

Safe Logging, Sampling and Retention covers this in depth.

Dashboards and alerts

Signal per toolAlert when
Success rateIt falls below the agreed level
Invalid-argument rateIt jumps after a change
Denied callsUnusual volume or pattern
Latency high percentileIt approaches the timeout
Unknown outcomesAny for critical writes
Calls per taskLoops appear
Cost and result sizeContext or spend grows

Alert on things someone can act on, and name the person or team. An alert nobody owns becomes noise.

Verify real effects

Compare the agent's records with the downstream system: every claimed booking should exist, and every booking made with the agent's identity should have a matching approved call. Reconciliation finds lost replies, duplicates and actions that bypassed the execution layer. For important writes, run it continuously.

Sampling and retention

Recording everything can become expensive and risky. Many teams keep all errors, denials, unknown outcomes and consequential writes, and sample ordinary successful reads. Decide per trace where possible so that you do not keep half a story. Compute rates from counters that see every call, not from the sample. Set retention by purpose: short for detailed debugging data, longer for summary figures, and whatever your legal and audit duties require for action records. Record the sampling rate so that a later reader does not mistake a sample for the whole.

Turn production into tests

Observetraces and reports
Diagnosetool, model or data?
Add a caseprivacy cleaned
Fix and compareold against new
↺ The case stays in the suite
Each failure should make the next release harder to break.
Illustrative example: the quiet regression

After a description is reworded, an agent begins using the archive search for current orders. No errors appear, because both tools work. A drop in task success and a shift in calls per tool reveal it. The team adds look-alike cases to the evaluation and blocks releases when selection accuracy falls.

Debug one bad run

  1. Find the trace from the task identifier.
  2. List tools offered, then tools called.
  3. Check arguments against what the user said.
  4. Compare the result with the system of record.
  5. See how the model used the result.
  6. Decide whether the fix belongs in the contract, the tool, the instructions or the policy.

A starting set you can build this week

Pick the two tools with the greatest consequences. For each, write the seven contract tests above, a fake with fault injection and twenty tool-use cases drawn from real or realistic requests. Add one trace event with the fields listed, one dashboard panel for success and latency and one alert with a named owner. This modest set tends to expose the first serious problems quickly, and it gives you a pattern to copy for the remaining tools. Expand coverage where traces show real variety and where failures would cost most, instead of chasing equal depth everywhere.

Who owns what

Give every tool an owner who sees its dashboard, answers its alerts and approves changes to its contract. A platform team can supply the shared trace format and test harness, while the owning team writes the cases, because it knows what a wrong result looks like. Review the weakest tool together each month: read a few failed traces, choose one fix and confirm in the next review that the figures moved. Record the decision, so that a later change does not quietly reverse it. Without that routine, dashboards tend to be built once and then forgotten.

Common mistakes

  • Testing only successful calls.
  • Checking replies but not state.
  • Mocking away every realistic failure.
  • Judging tool use from one run.
  • Logging full content by default.
  • Averaging across tools and hiding a weak one.
  • Collecting traces nobody reads.

Checklist

  • Each tool has contract tests including refusals.
  • Doubles can inject realistic faults.
  • Tool-use cases include "call nothing" and "ask".
  • Changes to wording or models trigger evaluation.
  • One structured event is recorded per call.
  • Sensitive values are protected before export.
  • Alerts have owners.
  • Effects are reconciled with systems of record.

Frequently asked questions

How many tool-use cases do I need?

Start with a few per tool covering clear, unclear and forbidden requests, then grow from real failures. Use more where a mistake is costly.

Should tests call the real model?

Tool-use evaluation should, since behavior depends on it. Deterministic layers should use scripted replies so they stay fast and exact.

What if the same task has several correct paths?

Score the outcome and required constraints, and list acceptable alternatives instead of one exact sequence.

Can traces be used for audit?

Operational traces are often sampled and short-lived. Keep a separate, complete and protected record where audit duties require it.

References and further reading

Next steps