Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Generative AI & LLM · Chapter 16 / 20

Generative AI & LLM

Evaluating agents and tool use

An agent is a model in a loop: it reads the task and what has happened so far, chooses an action such as a tool call, observes the result, and repeats until it decides that the task is done. Tools let a model look up an order, issue a refund or send an e-mail; the loop lets it combine them into multi-step work.

Agents are harder to test than single answers. Many different action sequences can complete a task, actions change the state of real systems, one early mistake compounds over later steps, and the same task can succeed on one run and fail on the next. This chapter covers how tool calling works, what goes wrong, and how to test tool definitions, individual calls, outcomes, trajectories, failure handling, reliability, safety and MCP servers.

Prerequisites: LLM application anatomy and APIs, Testing LLM code without the model, Statistics for evaluation.

This chapter is about testing agents. How agents, their tools and MCP servers are built and connected is covered in AI agents & MCP.

How tool calling and agents work

Application sends: task + conversation + tool definitions (name, description, JSON Schema of arguments)
        ↓
Model replies with a tool call: {"name": "lookup_order", "arguments": {"order_id": "A-1042"}}
        ↓
Application validates the call, checks permissions, executes the tool
        ↓
Application sends the tool result back to the model
        ↓
Model calls another tool, or writes the final answer          (repeat until done or out of budget)

The model never executes anything itself. It proposes calls; the application decides whether to run them. This boundary is where most tests live: the application validates every call against the tool's schema, enforces permissions and budgets, executes the tool, and returns the result, including errors, in a form the model can act on.

The Model Context Protocol (MCP) standardizes the tool side of this loop: a server lists its tools (tools/list, with a JSON Schema per tool) and executes them (tools/call), so the same tools can be used by different clients and models.

What goes wrong

FailureExampleHow to detect it
Wrong toolSearches the FAQ instead of looking up the orderExpected tool per scenario; trajectory checks
Wrong or invented argumentsorder_id: "1042", or an order number the user never gaveSchema validation; argument checks against the task
Ignored tool errorClaims success after the refund call failedFault injection; compare the claim with the final state
Invented tool resultStates a delivery date the tool never returnedCompare statements with logged tool outputs
Loops and wasteCalls the same lookup again and againRepeated-call detection; step and cost budgets
Unsafe actionRefunds without checking the order status, or deletes dataForbidden tools; required preconditions; approval gates
Gives up or over-asksAsks for the order number the customer already gaveCounts of clarifying questions; simulated users
Prompt injection through toolsA tool result contains instructions that the agent followsAdversarial tool results (Security, red teaming and guardrails)

Testing tool definitions and calls

A tool definition is an interface contract for a model. Its name and description decide when the model uses it, and its schema decides which calls are valid. Validate every call before executing it, and phrase validation errors so that the model can correct the call:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

lookup_order({'order_id': 'A-1042'}) -> ok
lookup_order({'order_id': '1042'}) -> order_id '1042' does not match the format ^A-\d{4}$
issue_refund({'order_id': 'A-1042', 'amount_eur': '89.90', 'reason': 'return'}) -> amount_eur must be a number, got str
issue_refund({'order_id': 'A-1042', 'amount_eur': 89.9, 'reason': 'changed my mind'}) -> reason must be one of ['return', 'damaged', 'late'], got 'changed my mind'
issue_refund({'order_id': 'A-1042', 'amount_eur': 89.9}) -> missing argument 'reason'
cancel_order({'order_id': 'A-1042'}) -> unknown tool 'cancel_order'; available: ['issue_refund', 'lookup_order']

What to test around tools:

  • Every tool executor rejects invalid arguments, even when the provider promises schema-conformant calls: the executor is also called by code, by other clients and by tests.
  • Error messages are actionable. "order_id '1042' does not match ^A-\d{4}$" lets the model retry correctly; "invalid input" does not. MCP makes the same distinction: an unknown tool is a protocol error, while invalid input and business errors are returned as tool results marked isError, so that the model can recover.
  • Tool selection is tested with scenarios: for each kind of request, which tool should be called first, and which must not be called at all.
  • Descriptions are part of the prompt. Changing a tool's description changes behaviour, so tool definitions are versioned and evaluated like prompts (Prompts as testable artifacts).

Outcome and trajectory evaluation

An agent run can be evaluated by where it ended and by how it got there:

ApproachWhat is checkedStrengthWeakness
OutcomeThe state of the environment after the run: records, refunds, sent messages, the final answerAccepts every valid pathMisses risky or wasteful paths that happened to end well
TrajectoryThe sequence of tool calls and their argumentsCatches unsafe order, loops and wasteBrittle if it demands one exact path

Use both, and keep trajectory checks to rules (preconditions, forbidden tools, budgets, no repeats) instead of one golden path:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

good: outcome ok
      trajectory ok
lucky: outcome ok
       trajectory ['refund issued before the order status was checked', 'repeated call lookup_order']
wrong: outcome ["refunds should be exactly [{'order_id': 'A-1042', 'amount_eur': 89.9}], got [{'order_id': 'A-2210', 'amount_eur': 45.5}]", 'an unrelated order was changed']
       trajectory ok

The lucky run ends in the right state but refunded before checking that the boots had come back; the same habit refunds unreturned orders tomorrow. The wrong run follows every rule and refunds the wrong customer. Outcome checks catch the second, trajectory rules catch the first, and neither alone is enough.

Fault injection and honest failure

Real tools time out, return errors and return surprising data. An agent must recover where it can and admit failure where it cannot. A tool that always works in tests never exercises that behaviour, so inject faults deliberately:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

careful_agent   failures=0  calls=1  refunded=True   consistent
careful_agent   failures=1  calls=2  refunded=True   consistent
careful_agent   failures=3  calls=3  refunded=False  consistent
careless_agent  failures=0  calls=1  refunded=True   consistent
careless_agent  failures=1  calls=1  refunded=False  FALSE CLAIM
careless_agent  failures=3  calls=1  refunded=False  FALSE CLAIM

Without fault injection both agents pass every test. With it, the careless agent tells a customer that money is on its way when nothing happened. Faults worth injecting: timeouts and rate limits, error results, empty and partial results, malformed results, slow responses that hit the step budget, and results that contradict the user's claim (the order was never delivered).

A deterministic test environment

Agents act on state, so tests need an environment that is cheap to reset and safe to change:

  • Fake tools with real state: an in-memory orders table, a refunds ledger and an outbox instead of production systems. Every test starts from a known snapshot.
  • Recorded or scripted model decisions for tests of the loop itself (Testing LLM code without the model), and a real model only in evaluation runs.
  • Budgets enforced by the loop: maximum steps, tokens and cost per task; exceeding them ends the run with a clear status.
  • A full trace of every run: model inputs and outputs, tool calls, arguments, results and timing, so that every failure can be replayed.
  • Sandboxes for agents that run code or browse: containers without network access or with an allow-list, and resource limits (Code-based scorers and metrics discusses executing generated code).

Simulated users and multi-turn tasks

Many agent tasks are conversations: the customer gives information in pieces, changes their mind, or asks something the agent cannot do. τ-bench made this measurable: a language model plays the user from a written persona and goal, the agent works with tools against a database, and success is judged by comparing the final database state with the expected one. The same design works for your product: write user scenarios with goals and the information each user knows, let a simulated user hold the conversation, and check the final state and the conversation rules (no repeated questions, confirmation before irreversible actions).

Simulated users are themselves models, so validate a sample of simulated conversations by reading them, and keep a set of scripted conversations for regression tests that must not vary.

Reliability across repeated runs

The same task can succeed on one run and fail on the next. For agents the relevant number is usually pass^k, the chance that all k attempts at a task succeed, because a customer who uses the agent every day experiences every run (Statistics for evaluation). Run every scenario several times, report pass^k next to the average success rate, and treat scenarios that sometimes fail as defects to investigate, not as flaky tests to retry.

Safety: permissions and approvals

  • Least privilege: give the agent only the tools a task needs, and scope each tool to the current user (the refund tool can refund only orders of the authenticated customer).
  • Approval gates for irreversible or expensive actions: a refund above a limit, a deletion, an external message. Test that the gate cannot be bypassed by arguments, retries or other tools.
  • Treat tool results as untrusted input. A product review, an e-mail or a web page returned by a tool can contain instructions; the agent must not follow them (Security, red teaming and guardrails).
  • Log every action with the user, the arguments and the reason, so that an incident can be reconstructed.

Testing MCP servers

An MCP server is an API whose client is a model, and it is tested like an API plus like a tool:

  • Protocol contract: initialize, tools/list and tools/call behave as the specification says; an unknown tool returns a JSON-RPC error; invalid input returns a result with isError: true and a message that explains the problem.
  • Schemas: every tool has a precise input schema, and an output schema where results are structured; results conform to them.
  • Behaviour: each tool does what its description says, including edge cases, and fails safely.
  • Security: inputs are validated, access is checked per user, calls are rate-limited, and outputs that will reach a model are sanitized. The specification also asks clients to confirm sensitive operations with the user.
  • Interactive checks with the MCP Inspector, and automated contract tests that call the server in memory or over its transport.

Benchmarks

Public agent benchmarks show how agent evaluation is designed in practice, and where models still fail:

BenchmarkTasksSuccess measured by
τ-benchCustomer-service conversations with tools and a simulated userFinal database state, pass^k over repeated trials
SWE-benchResolving real GitHub issues in Python repositoriesThe repository's tests pass after the change
WebArenaTasks on realistic self-hosted websitesFunctional checks of the final state
GAIAQuestions that need browsing, tools and reasoningExact answers
AgentBenchEight environments from operating systems to gamesEnvironment-specific success
Berkeley Function Calling LeaderboardSingle and multiple function callsCorrect function and arguments

Benchmarks rank models; they do not test your agent. Use them to learn evaluation designs and to choose candidate models, then evaluate on scenarios from your own product.

Example project

The methods of this chapter are implemented and tested in examples/llm-testing/13-agent-testing: a support-agent environment with orders, refunds and an outbox, tool definitions with argument validation, an agent loop with step budgets and an approval gate, scripted policies with injectable mistakes, outcome and trajectory checks, fault injection with false-claim detection, pass^k over seeded runs, and an in-memory MCP-style server with protocol contract tests. All tests run offline, without a model or API keys:

uv sync --project examples/llm-testing
uv run --project examples/llm-testing pytest examples/llm-testing/13-agent-testing

Common mistakes

  • Executing tool calls without validating them because the provider enforces schemas.
  • Error messages the model cannot act on, or errors raised in a way that ends the run instead of informing the model.
  • Only outcome checks, which accept risky paths that happened to end well, or only one golden trajectory, which rejects valid alternatives.
  • Tests with tools that never fail.
  • Trusting the agent's final message instead of the state of the environment.
  • One run per scenario for a system that users run every day.
  • Approval gates that other tools or retries can bypass, and tool results treated as trusted instructions.
  • MCP servers tested only by hand in an inspector.

Summary

  • An agent is a model in a loop that proposes tool calls; the application validates, authorizes and executes them, and that boundary is where most tests live.
  • Validate every call against its schema and return actionable errors; test tool selection with scenarios and version tool descriptions like prompts.
  • Evaluate both the outcome (final state) and the trajectory (rules about order, forbidden tools, repeats and budgets).
  • Inject faults and check that the agent recovers or admits failure, comparing its claims with the real state.
  • Test in a deterministic environment with fake tools, budgets and full traces; use simulated users for multi-turn tasks.
  • Report pass^k across repeated runs, enforce least privilege and approval gates, and treat tool results as untrusted.
  • Test MCP servers for protocol behaviour, schemas, tool behaviour and security.

Source registry

12 chapter references
ReAct: Synergizing Reasoning and Acting in Language Models

The pattern of interleaving reasoning with actions and observations that most agent loops follow.

Yao et al. — arXiv / ICLR 2023 · paper
Source ↗
Building Effective AI Agents

Workflows versus agents, simple composable patterns, and the importance of tool design and testing in sandboxes.

Anthropic · article
Source ↗
Tool use with Claude

Tool definitions with JSON Schemas, tool calls and tool results in the Messages API.

Anthropic · official docs
Source ↗
Function calling

Function definitions, strict schemas and the tool-call loop in the OpenAI API.

OpenAI · official docs
Source ↗
Model Context Protocol specification: Tools

tools/list and tools/call, input and output schemas, protocol errors versus tool execution errors, and security requirements.

Model Context Protocol · standard
Source ↗
MCP Inspector

Interactive testing and debugging of MCP servers.

Model Context Protocol · tool
Source ↗
τ-bench: A Benchmark for Tool-Agent-User Interaction in Real-World Domains

Introduces pass^k, the reliability of an agent across repeated trials of the same task.

Yao et al. — arXiv 2024 · paper
Source ↗
SWE-bench: Can Language Models Resolve Real-World GitHub Issues?

Agent tasks on real repositories, judged by the repository's own tests.

Jimenez et al. — arXiv / ICLR 2024 · paper
Source ↗
WebArena: A Realistic Web Environment for Building Autonomous Agents

Self-hosted websites as a reproducible environment, with functional checks of the final state.

Zhou et al. — arXiv / ICLR 2024 · paper
Source ↗
GAIA: a benchmark for General AI Assistants

Questions that require tools, browsing and reasoning, scored by exact answers.

Mialon et al. — arXiv / ICLR 2024 · paper
Source ↗
AgentBench: Evaluating LLMs as Agents

Eight interactive environments for evaluating models as agents.

Liu et al. — arXiv / ICLR 2024 · paper
Source ↗
Berkeley Function Calling Leaderboard

Evaluation of function selection and arguments, from single calls to agentic tasks.

Gorilla LLM, UC Berkeley · benchmark
Source ↗