Integrating the Countly AI SDK with Mastra

Mastra already traces every agent run, model generation, tool call, and workflow step it executes. The Countly AI SDK plugs into that tracing as an exporter, so every generation your Mastra agents make reaches your Countly Server with its tokens, cost, latency, tool calls, and errors.

This article walks you through registering the exporter, attributing each run to the right person, and handling the few places where Mastra behaves differently from the other frameworks the SDK supports.

Prerequisites

Before you start, make sure you have the following:

  • Your app key and Server URL: both come from the Countly app you want to send AI data to. See Getting Started with SDKs if you do not have them yet.
  • Node.js 20.19 or later (or 22.12 or later on the 22.x line). The packages are ESM-only, so if you bundle to CommonJS, your bundler must inline them.
  • @mastra/core 1.26.0 or later and @mastra/observability 1.11.0 or later, both below 2.0.
  • Your Countly device ID strategy: the ID your web or mobile Countly SDK already uses for each person. See Passing the Device ID below.

Check your Mastra versions before you upgrade to 0.0.6

Version 0.0.6 raised the Mastra floor from 1.0.0 because cache-token capture depends on a usage shape that @mastra/observability only emits from 1.11.0. With auto-install-peers=true, an older pair installs without complaint and then reports zero cache tokens. Every prompt-cached call is then mispriced, and nothing raises an error.

If you cannot move to the supported Mastra versions, pin @countly/ai-sdk-mastra@0.0.5 instead of running 0.0.6 below its floor. You then keep that version's known cost error: it bills cached tokens at the full input rate.

Setting Up the Integration

Installing the Adapter

Install the Mastra adapter. The shared core package, @countly/ai-sdk-core, is installed automatically.

npm install @countly/ai-sdk-mastra

Then confirm that the Mastra packages your project resolves meet the floor above:

npm ls @mastra/core @mastra/observability

Registering the Exporter

Create a CountlyMastraExporter and add it to the exporters list of an Observability instance, then pass that instance to Mastra through its observability field:

import { Mastra } from "@mastra/core/mastra";
import { Observability } from "@mastra/observability";
import { CountlyMastraExporter } from "@countly/ai-sdk-mastra";

const exporter = new CountlyMastraExporter({
  appKey: "YOUR_APP_KEY",
  url: "https://your-countly-server.com",
  requestContextDeviceIdKey: "countlyDeviceId",
});

const mastra = new Mastra({
  observability: new Observability({
    configs: {
      default: {
        serviceName: "my-ai-app",
        exporters: [exporter],
      },
    },
  }),
});

The exporter must sit inside new Observability({...})

If you pass the exporter directly as exporters on the Mastra constructor, no spans reach it and no data arrives in Countly. There is no error to warn you.

Keep a reference to the exporter, as above. You need it to flush and shut down, and to collect feedback.

Passing the Device ID

The Mastra adapter reads the device ID from Mastra's request context, not from a getDeviceId function. Set it on a RequestContext in your request handler, then pass the context to the agent or workflow:

import { RequestContext } from "@mastra/core/request-context";

app.post("/chat", async (req, res) => {
  const ctx = new RequestContext();
  // The same ID the client-side Countly SDK reports for this person
  ctx.set("countlyDeviceId", req.header("x-countly-device-id"));
  await mastra.getAgent("intent").stream(messages, { requestContext: ctx });
});

Mastra copies the context onto every span it creates during the run, including agent runs, model generations, and tool calls, and the exporter reads the ID from there. You can rename the key with requestContextDeviceIdKey, or set it to null to fall back to getDeviceId() or deviceId.

The ID must be the one your web or mobile Countly SDK already reports for that person. Any other value, including your own user ID when the client SDK does not use it, creates a profile with no sessions, and every user-based AI metric then reads zero. For the full rule and a five-minute check, see Attributing AI Activity to the Right User.

Captured Data

Once the exporter is registered, it sends the following events. Which of them leave your application depends on the observabilityLevel setting.

Event One Event per Sent at Level
[CLY]_llm_interaction model_generation span 0 and above
[CLY]_llm_tool_used function_call or mcp_tool_call tool call, or registered workflow step 1 and above
[CLY]_llm_tool_usage_parameter Tool argument, or key of a workflow step's inputData 2

Feedback events are covered in Collecting Feedback below.

Each generation is its own row. A Mastra trace is not a turn: one turn can span several traces, and one trace can contain several generations with different models. Each model_generation span therefore becomes exactly one interaction row, with its own model, provider, usage, cost, finish_reason, and latency_total, so every call is priced at its own model's rate.

Turn context is copied onto every row: run_id, generation_index (0-based, in start order), run_latency_total (the root span's end-to-end duration), workflow_name, agent_name, thread_id, the device ID, and trace_id. A trace that contained no generation, such as a workflow root, a rag_* pipeline, or a memory operation, emits no interaction row. Its tool rows are still sent, attached to the run.

The exporter also captures the following:

  • Token usage: cache read, cache write, and reasoning tokens are reported as subsets of the input and output totals, so the cache premium is billed exactly once. Audio and image tokens are included where Mastra reports them.
  • Tool calls: each with its own latency and its real outcome, attached to the generation that requested it.
  • Errors: a failed generation is reported as an error. A failed tool or workflow step is reported on its own tool row, not as a model failure.

Handling Mastra-Specific Behavior

Grouping a Turn Into a Single Run

Every row of a turn shares one run_id. The exporter takes the first of these that is available:

  1. The value returned by your getPromptId() function.
  2. The request context value under your requestContextPromptIdKey.
  3. Mastra's own run ID.
  4. The trace's root span ID.

Mastra runs a workflow and the agents it calls as separate traces, so without one of the first two options, a single workflow turn appears in Countly as several runs. To group them, choose a key, set your own ID for the turn under it, and do so before you start the agent or workflow:

const exporter = new CountlyMastraExporter({
  appKey: "YOUR_APP_KEY",
  url: "https://your-countly-server.com",
  requestContextPromptIdKey: "countlyPromptId", // opt in to your own turn ID
});

// In your request handler, before the run starts
const ctx = new RequestContext();
ctx.set("countlyDeviceId", req.header("x-countly-device-id"));
ctx.set("countlyPromptId", currentMessageId); // your own ID for this turn
await mastra.getAgent("intent").stream(messages, { requestContext: ctx });

Mastra clones the request context when it creates each span, so a value you set inside a workflow step is only visible on that step's own span and cannot group the turn.

Capturing Workflow Steps

If you orchestrate agents with Mastra workflows (createWorkflow and createStep), the steps only reach the exporter when the workflow is registered on the Mastra instance and run through that instance. A workflow you import and run on its own, with myWorkflow.createRun(), has no observability attached: only the agent runs it calls are traced, and its routing and handoff decisions are invisible.

const mastra = new Mastra({
  agents: { intentAgent, pluginsAgent },
  workflows: { myWorkflow }, // register the workflow
  observability: new Observability({ /* exporter config as above */ }),
});

// Run it through the instance so its spans are exported
const run = await mastra.getWorkflow("myWorkflow").createRun();
await run.stream({ inputData, requestContext: ctx });

Once the workflow is registered, each leaf step becomes a tool row:

  • Tool name: the step's ID, with hyphens replaced by underscores (e.g., potential-handoff becomes potential_handoff), so it aggregates with tool rows of the same name.
  • Parameters: each key of the step's inputData, such as handoff_to or confidence, becomes a named parameter you can break down in Countly.
  • Parent: a step is orchestration, not a tool the model chose, so its row is attached to the run, not to a generation. It is labeled with the root workflow's name.

Steps that only wrap a nested workflow, such as .then(nestedWorkflow), are skipped, so only real decision steps become rows. Register only the top-level workflow you run: its nested workflows are traced automatically as part of the run.

Reporting the API Endpoint Yourself

Out of the box, every Mastra row reports api_host_type: "unknown" and omits api_host. Mastra declares an attribute for the endpoint but never fills it in, and the SDK does not guess. As a result, the breakdown by host type in Countly stays empty for Mastra traffic, and you cannot separate gateway, vendor-direct, and Azure calls. Here, "unknown" means that Mastra did not report the endpoint, not that the call went somewhere unusual.

You built the model, so you know its endpoint, and Mastra has a supported place to report it: spanOutputProcessors, which sits next to exporters in the same Observability config. Processors run before a span is exported, so an attribute written there reaches the exporter, which records it in the same api_host_type and api_host fields.

import { Observability } from "@mastra/observability";
import { SpanType } from "@mastra/core/observability";
import { CountlyMastraExporter } from "@countly/ai-sdk-mastra";

// resolveHost returns the base URL your models are pointed at,
// or undefined if you cannot say (see the rules below)
function hostStamper(resolveHost) {
  return {
    name: "countly-host-stamper",
    process(span) {
      if (!span || span.type !== SpanType.MODEL_GENERATION) return span;
      const attributes = span.attributes ?? {};
      if (attributes.serverAddress) return span; // never override an observed value
      const host = resolveHost();
      if (!host) return span;
      span.attributes = {
        ...attributes,
        serverAddress: host,
      };
      return span;
    },
    async shutdown() {},
  };
}

new Observability({
  configs: {
    default: {
      serviceName: "my-app",
      exporters: [new CountlyMastraExporter({ appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" })],
      spanOutputProcessors: [hostStamper(() => process.env.LLM_BASE_URL)],
    },
  },
});

Three rules keep this a measurement rather than a guess:

  • Stamp only model_generation spans. An endpoint belongs to a model call. Stamping an agent run or a tool call would attach it to rows that never contacted it.
  • Never overwrite. If a span already carries serverAddress, that is an observed value, so leave it. The day Mastra starts filling the attribute, your processor quietly becomes a no-op instead of competing with it.
  • Say nothing when you cannot say. A resolver that always returns a string stamps every row, including calls that went elsewhere, such as a fallback provider or a flag that routes around your gateway. Returning undefined keeps the honest "unknown".

Only the hostname is stored. The scheme, port, path, and query are dropped, so https://gw.example.com/openai is recorded as gw.example.com, and a credential in a path or query cannot leak into an event.

Configuring the Exporter

The exporter accepts the same configuration object as every other adapter, plus the request context keys that only Mastra uses.

Field Default Description
appKey Required Your Countly app key
url Required Your Countly Server URL
requestContextDeviceIdKey "countlyDeviceId" Request context key that holds the device ID. null disables it.
requestContextThreadIdKey "threadId" Request context key that holds the conversation ID. Falls back to Mastra's own thread ID. null disables it.
requestContextWorkflowNameKey "workflowName" Request context key that holds the workflow name. Falls back to the root workflow's name. null disables it.
requestContextPromptIdKey None Request context key that holds your own ID for the turn, which becomes run_id. Opt-in.
getPromptId None The same, as a function. Takes precedence over requestContextPromptIdKey.
observabilityLevel 0 0 sends metrics only, 1 adds tool calls, and 2 adds text previews and tool parameters
tags [] Labels for cost attribution and filtering
environment "production" Environment label
costModel None Custom pricing overrides
flushInterval 10000 Buffer flush interval, in milliseconds
maxBatchSize 20 Maximum number of buffered events before an automatic flush
paramValueLength 1024 Cap on the serialized length of a tool argument's value
debug false Log transport errors and dropped or unrecognized spans
disabled false Turn off all tracking

Collecting Feedback

Mastra's own feedback signals need no extra code. The exporter turns every scorer result and every recordedSpan.addFeedback() call into a [CLY]_llm_interaction_feedback event, linked to the run that produced it.

For feedback from your own UI, such as a thumbs up on an answer, capture each generation's IDs with the onPrompt callback, which fires once per exported generation. Then record the rating with createFeedbackTracker, which this package re-exports:

import { CountlyMastraExporter, createFeedbackTracker } from "@countly/ai-sdk-mastra";

const countly = { appKey: "YOUR_APP_KEY", url: "https://your-countly-server.com" };

let lastPrompt;
const exporter = new CountlyMastraExporter({
  ...countly,
  requestContextDeviceIdKey: "countlyDeviceId",
  onPrompt: (info) => { lastPrompt = info; }, // fires once per exported generation
});
// Wire the exporter into new Observability({...}) as shown above

const feedback = createFeedbackTracker(countly, { sdk_adapter: "mastra" });

// Later, when the person rates the answer, rate the whole turn:
feedback.track({
  prompt_id: lastPrompt.prompt_id, // equal to run_id
  rating: "thumbs_up", // or "thumbs_down", or any custom string
  deviceId: req.header("x-countly-device-id"), // the same device ID as the interaction
});

// Or rate one generation of a multi-generation turn:
feedback.track({
  prompt_id: lastPrompt.event_id, // that row's own ID
  run_id: lastPrompt.run_id,
  rating: "thumbs_down",
});

In a real application, store the ID next to the rendered message, or return it to your client, and read it back when the person rates the answer. If you already set your own turn ID through requestContextPromptIdKey, you can pass that ID as prompt_id directly. For ratings, scores, categories, and comments, see Collecting User Feedback on AI Responses.

Flushing Before Your Process Exits

The exporter buffers events and sends them every 10 seconds or every 20 events, whichever comes first. The two methods to send buffered events behave differently while a turn is still running:

await exporter.flush();    // send buffered events; turns still running are not sent
await exporter.shutdown(); // send everything, including unfinished turns, then stop

flush() never sends a turn that has not finished, because Mastra calls it in the middle of requests. Reporting a live turn would record a premature success with zero latency, then a duplicate row when the turn ends. shutdown() sends whatever is left and marks each unfinished turn status: "incomplete", so a process that exits mid-turn loses nothing and misreports nothing.

In a script, cron job, or serverless function, call shutdown() before the process exits. If you collect feedback from your UI, call feedback.shutdown() as well.

Verifying the Integration

  1. Add debug: true to the exporter configuration. It then logs transport errors and dropped or unrecognized spans.
  2. Add an onPrompt callback that logs its argument. It fires once for every generation the exporter records, so a silent callback means no generation reached the exporter.
  3. Run one agent call with the device ID set on the request context, and note that ID.
  4. Wait up to 10 seconds for the batch to be sent, or call exporter.flush().
  5. In Countly, open User ProfilesProfiles and search for that exact device ID. The profile should already exist, have sessions, and show the new AI activity.

If onPrompt never fires, check that the exporter sits inside new Observability({...}), and that a workflow is registered on the Mastra instance and run through getWorkflow. If the profile exists but has zero sessions, the device ID does not match the one your client SDK reports. For a general checklist, see How to Validate Your Countly SDK Integration.

FAQ and Troubleshooting

Why Did My Row Counts Change After Upgrading to 0.0.6?

Two changes pull in opposite directions. Interaction rows rise, because a turn that used to emit one row now emits one per generation: roughly double for a single-agent turn, and more for a multi-agent or multi-model turn. Size your ingest accordingly.

Prompt counts drop, because traces that never contained a generation no longer emit a placeholder row. On observed traffic, that was 200 of 601 rows. Those rows had no model and zero tokens, so they inflated prompt counts and understated cost per prompt.

Why Do Some of My Rows Have No Token Counts?

The trace did not report usage for that generation. Instead of recording zero, the exporter omits the token fields and sets usage_state to "not_reported", so a missing count is never mistaken for a free call. If every row is affected, check that your Mastra versions meet the floor in Prerequisites.

Why Do I See a Failed Tool but a Successful Generation?

The model call itself succeeded. The exporter reports errors where they happened: a failed generation on its interaction row, and a failed tool or workflow step on its own tool row. To see tool failures, set observabilityLevel to 1 or higher, so tool rows are sent.

How Do I Group Rows by Conversation?

Every row carries a thread_id. The exporter reads it from the threadId request context key, or from Mastra's own thread ID when that key is not set. To use your own conversation ID, set it on the request context before the run, or point requestContextThreadIdKey at the key you already use.

Related Resources

Was this page helpful?
Reach out to us for any other questions.
Helpful?

Looking For More Help?