Test an agent
Run an agent against the real page with a scripted model: check which tools it called, in what order, what it answered and what it was offered.
An agent’s behavior depends on a model, which is slow, costs money and answers differently each time. To test your side
of it (the tools are there, they run in order, the agent sees only the tools it should), replace the model with a
script. mockAdapter plays the script as if a model had sent it: a tool call, then another, then text.
A complete example
The page and the agent:
import { defineWebAgent } from "@webmcp-agents/chat/agent";
import { useWebTool } from "@webmcp-agents/react";
import { addToCart } from "./add-to-cart";
export const storeAgent = defineWebAgent({
id: "store",
instructions: [
"You help people shop at Field Store.",
"track_last_order says what they bought last.",
],
});
export function Store() {
useWebTool({
id: "track_last_order",
description: "Read the last order: what was bought.",
readOnly: true,
execute: () => ({ id: "mug-01", qty: 2 }),
});
useWebTool(addToCart);
return <h1>Field Store</h1>;
}
The test:
import { expect, test } from "@webmcp-agents/testing";
import {
mockAdapter,
text,
toolCall,
} from "@webmcp-agents/testing/chat";
import { WebAgentsProvider } from "@webmcp-agents/react";
import { Store, storeAgent } from "./app/store";
test("reorders the last purchase", async ({ tools, mount }) => {
mount(
<WebAgentsProvider>
<Store />
</WebAgentsProvider>,
);
await expect.poll(() => tools.list()).toContain("add_to_cart");
const adapter = mockAdapter([
toolCall("track_last_order"),
toolCall("add_to_cart", { id: "mug-01", qty: 2 }),
text("Back in your cart."),
]);
const run = await storeAgent.invoke("Reorder my last purchase.", {
adapter,
});
expect(run).toHaveCalledTools(["track_last_order", "add_to_cart"]);
expect(run).toHaveAnswered("Back in your cart.");
expect(adapter).toHaveBeenOfferedTools(
expect.not.arrayContaining(["place_order"]),
);
});
storeAgent.invoke runs the real loop: each scripted tool call goes through document.modelContext to the tool on the
page, and its result goes back to the “model”. Only the model’s choices are fixed.
What to check
toHaveCalledTools([...]): exactly these tools, in this order.toHaveCalledTool(name, input?)for one of them.toHaveAnswered(text): the final text.toHaveFinishedWith("stop"): how the run ended ("max-steps","aborted","error").toHaveBeenOfferedTools(...)on the adapter: what the model was shown. Use it to check an agent’stoolssubset, or that a tool on another page was not offered.
The runs fixture records the run events of every run in the test (onAgentRun),
and the same matchers read it, which helps when the run is started by the chat rather than by your test.