Rehearse Your Agent's Worst Day for Free: Failure Tests for AI SDK 7 Tool Loops
Mock models let you script an agent's bad behavior and test it offline. Four failures tested in AI SDK 7, and why try/catch caught none of them.

Agents fail in ways a normal function doesn’t. The model calls the right tool with the wrong argument names. It invents a tool you never gave it. It gets stuck checking the same status over and over until something stops it. And when you try to reproduce any of this against a real model, you pay for every attempt and still might not get the same bad answer twice.
The Vercel AI SDK has a quieter answer than “watch it in a dashboard and hope”: a mock model you can script step by step. You decide exactly what the “model” says on each turn, including the dumb stuff, and then check how your agent code handles it. No API key, no tokens, same result every run.
I spent a session scripting four bad days for a small tool-calling agent. The useful finding wasn’t that the SDK handles these cases. It does. It was that none of the four failures throws an error, so the obvious try/catch test catches nothing.
Tested with: ai 7.0.181, @ai-sdk/devtools 1.0.84, zod 4.6.7, Node.js 22.23.5 and its built-in test runner, on x86_64 Linux with 2 vCPUs, no GPU, on November 24, 2026.
The agent under test
The agent is deliberately small: one tool that reports on a 3D printer, and a hard cap of five steps. One printer ID is rigged to throw, so there’s a failure to test.
// agent.mjs
import { ToolLoopAgent, tool, isStepCount } from 'ai';
import { z } from 'zod';
export const makeAgent = (model, { log = [] } = {}) =>
new ToolLoopAgent({
model,
instructions: 'You help check on a 3D printer.',
stopWhen: isStepCount(5),
tools: {
printerStatus: tool({
description: 'Get the status of a printer by id.',
inputSchema: z.object({ printerId: z.string() }),
execute: async ({ printerId }) => {
log.push(printerId);
if (printerId === 'offline-1') throw new Error('printer did not respond');
return { state: 'printing', progress: 0.42 };
},
}),
},
});
Taking the model as a parameter is the whole trick. In production you pass a real provider model. In tests you pass a script.
Scripting the model
MockLanguageModelV4 lives in ai/test. Give doGenerate an array and the mock returns one entry per call, in order. One call is one agent step. The response objects are verbose, so I wrapped them in three helpers:
// helpers.mjs
import { MockLanguageModelV4 } from 'ai/test';
const usage = {
inputTokens: { total: 10, noCache: 10, cacheRead: undefined, cacheWrite: undefined },
outputTokens: { total: 5, text: 5, reasoning: undefined },
};
export const callTool = (toolName, input, id = 'call-1') => ({
content: [{ type: 'tool-call', toolCallId: id, toolName, input: JSON.stringify(input) }],
finishReason: { unified: 'tool-calls', raw: undefined },
usage,
warnings: [],
});
// For sending input that isn't what your schema expects.
export const rawToolCall = (toolName, rawInput, id = 'call-1') => ({
...callTool(toolName, {}, id),
content: [{ type: 'tool-call', toolCallId: id, toolName, input: rawInput }],
});
export const say = (text) => ({
content: [{ type: 'text', text }],
finishReason: { unified: 'stop', raw: undefined },
usage,
warnings: [],
});
export const scripted = (...responses) => new MockLanguageModelV4({ doGenerate: responses });
Note that input in a tool call is a JSON string, just like it would be from a real provider. That’s what lets you send malformed input later.
The happy path, and what the model actually saw
First, a quick check that everything is wired up: the model calls the tool, then answers.
const log = [];
const model = scripted(
callTool('printerStatus', { printerId: 'mk4' }),
say('The printer is 42% through the job.'),
);
const result = await makeAgent(model, { log }).generate({ prompt: 'How is the print going?' });
// log → ['mk4'], result.steps.length → 2, result.stoppedBy → 'model'
The best part of the mock is model.doGenerateCalls. It records every prompt the SDK sent to the “model.” Printing the last message of the second call shows exactly what your tool result looked like from the model’s side:
{
"role": "tool",
"content": [
{
"type": "tool-result",
"toolCallId": "call-1",
"toolName": "printerStatus",
"output": { "type": "json", "value": { "state": "printing", "progress": 0.42 } }
}
]
}
This is the debugging question that matters most in agent work: what did the model actually get? You can now assert on it like any other value.
Four bad days
Here’s what happened when I scripted each failure. The surprises are in the error column.
The tool throws. The SDK catches it, puts a tool-error part in the step, and sends it back to the model as {"type":"error-text","value":"Error: printer did not respond"}. The loop carries on and the model gets a chance to apologize. error is a real Error instance.
The model sends input that fails the schema. I sent {"printer_id":"mk4"} where the schema wants printerId. The tool-calling docs say generateText throws for tool schema validation problems and show InvalidToolInputError.isInstance(error) in a catch block. In my run inside ToolLoopAgent, it did not throw. The step contained a tool-call part with invalid: true and a tool-error part, and the model was sent the validation message as error text on the next step. The message starts with AI_InvalidToolInputError: Invalid input for tool printerStatus.
The model calls a tool that doesn’t exist. Same pattern. No throw. The model got back AI_NoSuchToolError: Model tried to call unavailable tool 'cancelPrint'. Available tools: printerStatus. That’s helpful text for a model to recover from.
The model never stops. I scripted ten tool calls in a row. The agent stopped at five, as configured, and reported:
{ steps: 5, toolRuns: 5, stoppedBy: 'stop-condition', finishReason: 'tool-calls', text: '""' }
The empty text is the important part. If your UI just shows result.text, a capped run looks like the agent said nothing. The loop control docs explain why finishReason still says tool-calls here: it only describes the last model call. stoppedBy is the field that tells you the cap ended the run.
Turning it into a test suite
Since nothing throws, the tests have to look inside result.steps. One small helper does most of the work:
// agent.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { makeAgent } from './agent.mjs';
import { scripted, callTool, rawToolCall, say } from './helpers.mjs';
// Invalid tool calls don't throw. Find them yourself.
const invalidCalls = (result) =>
result.steps.flatMap((s) => s.content).filter((p) => p.type === 'tool-call' && p.invalid);
test('happy path: one tool call, then an answer', async () => {
const log = [];
const model = scripted(callTool('printerStatus', { printerId: 'mk4' }), say('42% done.'));
const result = await makeAgent(model, { log }).generate({ prompt: 'How is the print going?' });
assert.deepEqual(log, ['mk4']);
assert.equal(result.text, '42% done.');
assert.equal(result.stoppedBy, 'model');
assert.equal(invalidCalls(result).length, 0);
});
test('runaway loop is capped by stopWhen', async () => {
const model = scripted(
...Array.from({ length: 10 }, (_, i) => callTool('printerStatus', { printerId: 'mk4' }, `c${i}`)),
);
const result = await makeAgent(model).generate({ prompt: 'Status?' });
assert.equal(result.steps.length, 5);
assert.equal(result.stoppedBy, 'stop-condition');
assert.equal(result.finishReason, 'tool-calls');
assert.equal(result.text, ''); // nothing to show the user
});
test('a schema mismatch reaches the model as error text', async () => {
const model = scripted(rawToolCall('printerStatus', '{"printer_id":"mk4"}'), say('Retrying.'));
const result = await makeAgent(model).generate({ prompt: 'Status?' });
const [bad] = invalidCalls(result);
assert.equal(bad.toolName, 'printerStatus');
const err = result.steps[0].content.find((p) => p.type === 'tool-error');
assert.equal(typeof err.error, 'string');
assert.match(err.error, /AI_InvalidToolInputError/);
const fed = model.doGenerateCalls[1].prompt.at(-1).content[0].output;
assert.equal(fed.type, 'error-text');
});
test('a throwing tool becomes a real Error, and the loop keeps going', async () => {
const model = scripted(callTool('printerStatus', { printerId: 'offline-1' }), say('It is offline.'));
const result = await makeAgent(model).generate({ prompt: 'Status of offline-1?' });
const err = result.steps[0].content.find((p) => p.type === 'tool-error');
assert.ok(err.error instanceof Error);
assert.equal(err.error.message, 'printer did not respond');
assert.equal(result.text, 'It is offline.');
});
npm install ai@7.0.181 zod
node --test agent.test.mjs
ok 1 - happy path: one tool call, then an answer
ok 2 - runaway loop is capped by stopWhen
ok 3 - a schema mismatch reaches the model as error text
ok 4 - a throwing tool becomes a real Error, and the loop keeps going
# tests 4
# pass 4
# fail 0
# duration_ms 225.567859
A quarter of a second for four agent runs, offline. I used Node’s built-in runner to avoid adding dependencies. The testing docs use Vitest, and the same code works there with expect swapped in.
Watching the same run in DevTools
The original version of this post was about AI SDK DevTools, and it pairs well with mocks. Register it once and every call gets recorded to .devtools/generations.json, mock or not:
import { registerTelemetry } from 'ai';
import { DevToolsTelemetry } from '@ai-sdk/devtools';
registerTelemetry(DevToolsTelemetry());
I ran a three-step script (bad input, corrected call, answer) and opened the viewer with npx @ai-sdk/devtools, which serves on port 4983. The run showed up as three steps with token counts from my fake usage numbers. Here’s step two expanded:

The failed call is there, but you have to know where to look: inside the next step’s input, collapsed to { type: "error-text", … }. The run list didn’t flag it. The viewer’s own API returned "hasError": false for this run, even though step one had a tool-error. That makes sense, because the run itself didn’t fail. Still, it means DevTools won’t point you to a bad tool call. Your tests should.
What went wrong when I tested it
My first missing-tool check reported “no error.” I wrote err?.error?.name expecting an Error object and got undefined, which read as “nothing went wrong.” The error was there. It was a string. Execution errors are Error objects and invalid-call errors are strings, so check typeof or toolCall.invalid rather than reaching for .name or isInstance.
An older mock fixture failed silently. Earlier SDK versions used a flat usage object and a plain string for finishReason. I pasted that shape into a v4 mock to see what would happen:
finishReason: 'stop',
usage: { inputTokens: 10, outputTokens: 5, totalTokens: 15 },
It didn’t throw. The text came through, but finishReason came back undefined and usage came back as {"inputTokenDetails":{},"outputTokenDetails":{}}. Any test asserting on token counts would compare against nothing. If you’re upgrading old fixtures, convert them to the nested { unified, raw } and { total, ... } shapes shown above.
DevTools didn’t touch my .gitignore. The docs say the integration adds .devtools to .gitignore automatically. On my first run it didn’t, because there was no .gitignore yet. Reading the package source explained it: it only edits an existing .gitignore, and only at the moment it first creates the .devtools folder. Creating an empty .gitignore afterward did nothing until I deleted .devtools and ran again. Since that file holds full prompts and tool results in plain text, add the line yourself.
When to use this, and when not to
Use scripted mocks for the code around the model: what your agent does with an invalid call, whether a capped run shows the user something sensible, what your tools send back, and how retries and fallbacks behave. Those are the bugs that ship, and they’re all deterministic once the model’s output is fixed.
Don’t use them to judge whether a real model will pick the right tool. A mock never misreads your tool description. It does exactly what you scripted. For that, you need runs against real models and an evaluation set, which is a different (and more expensive) job.
The same habit applies to the tools themselves: Read-Only Isn’t tests a SQLite MCP server before an agent gets near it. And if your tools sit behind MCP, the round-trip problems in Stateless MCP, Two Workers, One Confirmation Prompt are the next layer down.
Sources
- AI SDK: Testing
- AI SDK: Loop Control
- AI SDK: Tools and Tool Calling (error handling)
- AI SDK: DevTools
aion npm and@ai-sdk/devtoolson npm
How this was made: researched and drafted with AI assistance, with every code sample run and tested before publishing, then reviewed by Colby.

