> ## Documentation Index
> Fetch the complete documentation index at: https://docs.waniwani.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Instrumentation

> Where each funnel event belongs in a flow, and how to auto-instrument it with the instrument-tracking skill.

> [!NOTE]
>
> **Platform feature.** Requires `WANIWANI_API_KEY`. Works whether your MCP server is self-hosted or on Managed Hosting. [About the Platform](https://docs.waniwani.ai/sdk/platform/overview.md).

Instrumentation is the mapping between your flow's nodes and the Waniwani event taxonomy: which node emits which event, with which metadata. Get the mapping right and the dashboard shows a funnel that explains where users drop off and which conversations turn into revenue. This page gives you the placement rules, and a skill that applies them to your codebase automatically.

## The taxonomy

The event set is closed and typed. Model every funnel stage with one of these; there is no custom event name.

| Stage | Event | Emit via | Notes |
| - | - | - | - |
| Landing | `page.viewed` | chat widget, automatic | Attributed to an anonymous `visitorId`. |
| Activity | `tool.called` | `withWaniwani(server)`, automatic | One per tool invocation, with timing and status. |
| Identity | `user.identified` | `waniwani?.identify(userId, properties?)` | Attach a stable external id as soon as one is known. |
| Qualification | `lead_qualified` | `waniwani?.track.leadQualified({ ... })` | The person met your qualification bar. |
| Step | `price_shown` | `waniwani?.track.priceShown({ amount, currency })` | You showed one price. |
| Step | `prices_compared` | `waniwani?.track.pricesCompared({ options })` | You showed two or more options side by side. |
| Step | `option_selected` | `waniwani?.track.optionSelected({ id, amount, currency })` | The user picked one of those options. |
| Conversion | `converted` | `waniwani?.track.converted({ amount, currency })` | The user became paying, possibly later and off-platform. |

Inside a flow node, `waniwani` comes from the handler context and already carries the session identity. Full type shapes are in the [Event schema](https://docs.waniwani.ai/sdk/reference/event-schema.md).

## Placing `lead_qualified`

`lead_qualified` is your code declaring that the conversation produced a concrete handoff toward your business. A lead is qualified whenever the user:

* is redirected to your pricing page or to your own website (the moment right before `openExternal(...)` or the redirect widget is the natural emit point),
* books a call or a meeting,
* is sent an email (a quote recap, a follow-up, a booking confirmation),
* or meets an explicit qualification bar you defined (finished the qualifying questions, requested a demo, matched your target profile).

Three rules:

1. **It fires at the handoff, not at flow entry.** Starting a flow is activity (`tool.called` covers it). The event belongs where the handoff happens: the node that pushes the lead to your CRM, or the widget callback that redirects the user to your site.
2. **It fires once per flow run.**
3. **Fill every property you can.** The properties are the join keys the dashboard uses to dedupe leads and connect them to your system.

| Property | What to pass |
| - | - |
| `externalId` | Your own lead id, for example the record id your CRM or lead API returns. The strongest dedup key, so place the event after that push exists. |
| `email` | The lead's email, from whichever state field holds it. |
| `name` | The lead's name, if collected. |

```ts theme={null}
.addNode({
  id: "push_lead",
  label: "Push to CRM",
  run: async ({ state, waniwani }) => {
    const lead = await crm.createLead({
      email: state.email,
      role: state.role,
      useCase: state.useCase,
    });
    waniwani?.track.leadQualified({
      externalId: lead.id,
      email: state.email,
    });
    return { leadId: lead.id };
  },
})
```

> [!NOTE]
>
> Sharing an email, a phone number, or a first and last name mid-conversation is `identify(userId, { ... })`, not a qualified lead. `identify` attaches identity; `lead_qualified` declares the handoff happened. Most flows emit both, at different nodes.

## Placement rules for the rest

* **`identify` as early as possible.** The first node where an email or user id is in state calls `waniwani?.identify(state.email)`. This is what lets an off-platform `converted` find its way back to the session.
* **Price events go where the numbers are.** The node that computes a single price emits `priceShown`; the node that presents multiple plans emits `pricesCompared`; the node that runs after the user picked (the selection is now in state) emits `optionSelected`.
* **`converted` only on real conversion.** A confirmed booking or completed purchase inside the flow. If the sale closes later on your own site, emit it from your backend with the same `externalUserId` you identified during the flow, or with the `waniwani.sessionId` you stored on the lead. See [Sessions](https://docs.waniwani.ai/sdk/tracking/sessions.md).
* **Emit from node handlers, never from `validate` callbacks.** Validation can run several times per answer and would duplicate events.
* **Always guard with `waniwani?.`.** The scoped client is `undefined` when the server is not wrapped with `withWaniwani(server)`, and tracking throws without an API key. Optional chaining keeps keyless runs working.
* **Never pass `sessionId` manually inside a flow.** The scoped client carries it.

## A fully instrumented flow

```
START
  -> welcome            (interrupt: email)            identify(state.email)
  -> qualify            (interrupt: role, team size)
  -> push_lead          (action, CRM returns id)      lead_qualified { externalId, email }
  -> compute_quote      (action)                      price_shown { amount, currency }
  -> show_plans         (widget: 3 plans)             prices_compared { options }
  -> confirm_plan       (action)                      option_selected { id, amount, currency }
  -> book               (action)                      converted { amount, currency }
  -> END
```

Not every flow has every stage. A lead-gen flow can end at `lead_qualified`; a support flow may only ever `identify`. Forcing events onto nodes that do not represent that stage corrupts the funnel.

## Auto-instrument with the skill

The `instrument-tracking` agent skill applies everything on this page to your codebase: it inventories your flows, maps every node to the taxonomy, inserts guarded tracking calls with metadata read from your flow state, wraps the server with `withWaniwani` if needed, and runs your typecheck.

```bash npx theme={null}
npx skills add Waniwani-AI/sdk -s instrument-tracking
```

```bash bunx theme={null}
bunx skills add Waniwani-AI/sdk -s instrument-tracking
```

Then ask your agent, in natural language:

* *"Instrument tracking across my flows"*
* *"Track qualified leads in my demo flow"*
* *"Add conversion tracking to the booking flow"*

The skill also runs well as a subagent at the end of a scaffolding session, so a freshly generated flow ships instrumented from its first deploy. It reports the final node-to-event mapping as a table, so you can review every placement before committing.

## Audit an existing app

The `audit-tracking` skill is the read-only counterpart. It fetches the latest event definitions from these docs, inventories every tracking call across the server, flows, widgets, and chat embed, verifies that only events from the taxonomy are sent, and reports missing funnel events with a suggested payload for each. Run it before instrumenting, or as a periodic health check on an already instrumented app.

```bash npx theme={null}
npx skills add Waniwani-AI/sdk -s audit-tracking
```

```bash bunx theme={null}
bunx skills add Waniwani-AI/sdk -s audit-tracking
```

Then ask your agent, in natural language:

* *"Audit the tracking in this MCP"*
* *"Are we sending any events that aren't defined?"*
* *"Which funnel events are we missing?"*

## Checklist

* Exactly one `leadQualified` per flow run, placed at the qualification bar, with `externalId` when your CRM returns one.
* `identify` runs at the earliest node where a stable id exists.
* Every tracking call is guarded with `waniwani?.` and none passes `sessionId`.
* `withWaniwani(server)` wraps the server.
* Off-platform conversions send `converted` from your backend with the identified `externalUserId`.

## Next

> [card] [Event schema](https://docs.waniwani.ai/sdk/reference/event-schema.md)

> [card] [Identify](https://docs.waniwani.ai/sdk/tracking/identify.md)

> [card] [Sessions](https://docs.waniwani.ai/sdk/tracking/sessions.md)

> [card] [Agent skills](https://docs.waniwani.ai/sdk/guides/skills.md)


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.