---
title: onAgentRun
description: "Count runs, failed tool calls and tokens in your own analytics with onAgentRun: no telemetry package, no OpenTelemetry, redacted by default."
sidebar:
  label: "onAgentRun"
related:
  - /observability/observe-agents
  - /reference/chat/on-agent-run
---

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.

:::note[Experimental]
`onAgentRun` is new in 0.5.0, and its event fields may still change in a minor release.
:::

## Example

Call it once, when the page starts. It returns a function that stops listening.

```ts title="agent-analytics.ts"
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?)`:

<AutoTypeTable path="../../packages/chat/src/session/run-events.ts" name="OnAgentRunOptions" />

## The events

A run is a sequence, in this order:

1. **The run starts**

    `run-start`. Every event carries the conversation and run ids.

2. **Each model step**

    `step-start` and `step-finish`, with the model and the token counts the server reported.

3. **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`.

4. **The run ends**

    `run-finish`, with how the run ended.

The full list, with every field, is on [`onAgentRun`](/docs/reference/chat/on-agent-run#the-events).

## 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.

:::warning[`raw: true` is for your own trusted code]
`onAgentRun(listener, { raw: true })` gives the values as they are. Never use it for anything that sends them off the
page.
:::

## Next

**[Custom events](/docs/observability/custom-events)**

Your own events and spans in the same trace, from the page and the server.

**[Reference: onAgentRun](/docs/reference/chat/on-agent-run)**

Every event and its fields.
