> For the complete documentation index, see [llms.txt](https://docs.mediarithmics.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.mediarithmics.io/setup-and-monitor/extend-the-platform/build-an-activity-analyzer.md).

# Build an activity analyzer

Write and deploy the plugin that transforms each activity before it is stored.

## Your goal

Implement an activity analyzer plugin: one endpoint that receives an activity and returns the activity you want stored.

## Expected outcome

A deployed plugin version your users can attach to a channel, reformatting or enriching every real-time activity on it.

## Before you start

* Read [Activity analyzers](/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/activity-analyzers.md) for what an analyzer does, where it sits in the pipeline, and what it may and may not change.
* Read [Plugin architecture](/setup-and-monitor/extend-the-platform/plugin-architecture.md) for the plugin, version, worker, and instance model.
* Check whether an [event rule](/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/event-rules.md) already covers your case - a rule needs no code.

Create the plugin with type `ACTIVITY_ANALYZER`, following the procedure in [Build a custom feed plugin](/setup-and-monitor/extend-the-platform/build-a-custom-feed-plugin.md#create-and-deploy).

{% hint style="info" %}
The standard group ID for an activity analyzer is `{domain}.{organisation}.activity-analyzer` - for example `com.mediarithmics.activity-analyzer`.
{% endhint %}

## The one endpoint to implement

```
POST myworker/v1/activity_analysis
```

Called any time an activity is processed by the platform. The analyzer receives an activity and responds with a new activity.

| Request field          | Type   | Description                                                                           |
| ---------------------- | ------ | ------------------------------------------------------------------------------------- |
| `activity_analyzer_id` | String | The ID of the analyzer instance to use. **Used to retrieve the instance properties.** |
| `datamart_id`          | String | The ID of the datamart.                                                               |
| `activity`             | Object | The UserActivity object to analyse.                                                   |

{% tabs %}
{% tab title="Success" %}
In most cases, respond with the modified activity object to store:

```json
{
    "status": "ok",
    "data": {
        // New UserActivity object
    }
}
```

{% endtab %}

{% tab title="Error" %}
On an unexpected error:

```json
{
  "status": "error",
  "error": "Your error message"
}
```

{% endtab %}
{% endtabs %}

{% hint style="warning" %}
The analyzer **cannot modify the identifiers** passed in the incoming activity. Everything else in the activity is yours to change - including removing events, which is a real risk: an analyzer that drops unrecognised events will drop `$set_user_choice` events too.
{% endhint %}

## Read your instance

The same version is attached to several channels, and each attachment is a separate [instance](/setup-and-monitor/extend-the-platform/plugin-architecture.md#instances) with its own properties. Use `activity_analyzer_id` from the request to fetch them:

```
GET https://api.mediarithmics.com/v1/activity_analyzers/:id
GET https://api.mediarithmics.com/v1/activity_analyzers/:id/properties
```

The first returns the instance - name, organisation, plugin ID, group ID, artifact ID. The second returns its properties, each with a technical name, value, type, origin, and whether it is writable.

Cache the properties rather than fetching them per activity: this endpoint is called for **every** activity on the channel.

## Design guidance

| Concern            | Guidance                                                                                                                                                                                                                                                                          |
| ------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Latency**        | The analyzer sits in the ingestion path. An external lookup per activity puts that provider's latency between your users and their stored data - cache aggressively.                                                                                                              |
| **External calls** | Any host you call must be declared as an external service **and enabled** by mediarithmics. See [Build a custom feed plugin](/setup-and-monitor/extend-the-platform/build-a-custom-feed-plugin.md#create-and-deploy).                                                             |
| **Rate limits**    | If you call a partner API, configure a [throttling](/setup-and-monitor/extend-the-platform/plugin-architecture.md#controlling-how-hard-a-plugin-is-called) on the version.                                                                                                        |
| **Bulk imports**   | Analyzers **do not run** on bulk activity imports. If a transformation is mandatory for correctness, imported activities must already be formatted correctly. See [Import activities](/setup-and-monitor/collect-and-manage-your-data/import-data-in-batch/import-activities.md). |
| **Edge**           | Properties that must be usable in Edge segment queries must be stored **exactly as pushed** - they cannot pass through your analyzer. See [Edge](/setup-and-monitor/plan-and-integrate/set-up-advanced-features/edge.md).                                                         |

## Watch it in production

Everything written through the Plugin SDK's `Logger` class is available as logs, in a stream dedicated to the plugin's organisation.

{% stepper %}
{% step %}

### Get access

Ask your account manager for access to your organisation's plugin logs if you do not already have it. Streams are named `{Organisation ID} {Organisation name}`.
{% endstep %}

{% step %}

### Add context to every log line

Systematically include context - feed ID, site ID, app ID - so you can filter down to a **specific instance** of your plugin. Without it, logs from every instance are interleaved.
{% endstep %}

{% step %}

### Use the right level

Levels are **Error**, **Log**, **Info**, and **Debug**.

Use **Debug** for log-intensive work such as tracing data and functions. Debug logs are **not saved by default**, and your account manager can enable them temporarily - which lets you leave tracing in the code without generating useless volume.
{% endstep %}

{% step %}

### Keep the volume down

{% hint style="danger" %}
Aim not to generate too many logs. If you do, mediarithmics will **stop your stream from logging** in order to protect the other streams.
{% endhint %}

A good practice: generate statistics every few seconds rather than a line per item - the number of items processed and their status, instead of a message per activity.
{% endstep %}
{% endstepper %}

Alongside logs, watch the `ACTIVITY_ANALYZER` and `DOCUMENT_STORE` steps in [ingestion monitoring](/setup-and-monitor/operate-and-monitor/monitor-data-ingestion.md): a gap between them is your analyzer dropping activities.

## Verify

* A test activity returns transformed as expected, with identifiers untouched.
* Two instances on two channels behave according to their own properties.
* The `ACTIVITY_ANALYZER` and `DOCUMENT_STORE` counts are consistent.
* Logs can be filtered down to one instance.
* An error in your code returns the error shape rather than timing out.

## Related pages

<table data-view="cards" data-search="false"><thead><tr><th></th><th></th><th data-hidden data-card-target data-type="content-ref"></th></tr></thead><tbody><tr><td><strong>Activity analyzers</strong></td><td>What an analyzer is, and where it runs.</td><td><a href="/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/activity-analyzers.md">Activity analyzers</a></td></tr><tr><td><strong>Plugin architecture</strong></td><td>Instances, properties, throttlings.</td><td><a href="/setup-and-monitor/extend-the-platform/plugin-architecture.md">Plugin architecture</a></td></tr><tr><td><strong>Event rules</strong></td><td>The no-code alternative.</td><td><a href="/setup-and-monitor/collect-and-manage-your-data/collect-data-in-real-time/event-rules.md">Event rules</a></td></tr></tbody></table>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.mediarithmics.io/setup-and-monitor/extend-the-platform/build-an-activity-analyzer.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
