onAgentRun
Count runs, failed tool calls and tokens in your own analytics with onAgentRun: no telemetry package, no OpenTelemetry, redacted by default.
Not every question needs a tracing backend. How many runs end in an error? Which tool fails most? How long do people
take to confirm? onAgentRun from @webmcp-agents/chat gives you each run’s events as plain objects, and you send
what you need to the analytics you already have. It is what observeAgents builds its spans from, and it needs no
telemetry package.
Example
Call it once, when the page starts. It returns a function that stops listening.
import { onAgentRun } from "@webmcp-agents/chat";
// A stand-in for your analytics client.
declare const analytics: {
track(event: string, data: Record<string, unknown>): void;
};
// No telemetry package: the run events, redacted, to your own
// analytics. Returns a function that stops listening.
export const stop = onAgentRun((event) => {
if (event.type === "tool-finish" && event.state === "error") {
analytics.track("agent_tool_failed", {
tool: event.tool,
code: event.code,
});
}
if (event.type === "run-finish") {
analytics.track("agent_run", {
reason: event.reason,
steps: event.steps,
ms: Math.round(event.ms),
});
}
});
Options
onAgentRun(listener, options?):
raw?boolean
Receive tool inputs and outputs (and a parked call's prompt) as they are, without the page's redaction. For the app's own trusted code only: anything that sends events off the page should keep the default. Default false.
booleanThe events
A run is a sequence, in this order:
The run starts
run-start. Every event carries the conversation and run ids.
Each model step
step-start and step-finish, with the model and the token counts the server reported.
That step's tool calls
tool-start, then tool-park when it waits for the person, tool-yield when the cursor got out of their way,
and tool-finish.
The run ends
run-finish, with how the run ended.
The full list, with every field, is on onAgentRun.
Notes
Redacted by default
Tool inputs, results and a parked call’s prompt pass through the page’s redactor and the tool’s sensitive fields
before your listener sees them.
A listener that throws
Never breaks a run.