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

> ## Agent Instructions
> Magpie is a trace store for AI agents, used as a library (crate `magpiedb`, npm `magpiedb`, PyPI `magpiedb`) or as `magpie-server`, which takes OpenTelemetry (OTLP over HTTP on 127.0.0.1:4318 and gRPC on 127.0.0.1:4317 by default).
> Use only the commands, flags, routes and JSON shapes that these pages show. Do not guess a flag or a query field: if a page does not show it, say that the docs do not show it.
> Install the library with `cargo add magpiedb`, `npm install magpiedb` or `pip install magpiedb`. Get the server from the GitHub Releases download or the Docker image `ghcr.io/intojhanurag/magpie-server`, as the quick start shows.
> Only one process may write to a store folder at a time. For many apps, send traces to one `magpie-server`.
> `magpie-server doctor` checks a running server. An AI agent can query the traces over MCP at `/mcp` on the HTTP port (page guides/mcp).

# Aggregate spans

> POST /v1/aggregate: the count, exact sums and percentiles of spans per group: by field, attribute or time bucket, top N and time series.

`POST /v1/aggregate` counts the spans that match a filter, and sums their numbers, per group. Right: `read`.

```sh Request theme={null}
curl -s localhost:4318/v1/aggregate -d '{"groupBy": {"field": "userId"}, "metrics": ["costNanos"], "sort": {"by": {"sum": 0}}, "limit": 1}'
```

```json 200 theme={null}
{"rows":[{"count":5,"key":"u1","sums":[1500000]}]}
```

## Body

**filter** `object` (default: \{})

A [span filter](https://docs.magpiedb.com/reference/api/filters.md#span-filter). Left out: every span.

**groupBy** `string | object` (default: all)

The key of a group.

**values**

| Value | One group per |
| - | - |
| `"all"` | nothing: one group for all matching spans |
| `{"field": f}` | value of `f`: `traceId`, `kind`, `model`, `userId`, `sessionId`, `name` or `tag` |
| `{"attribute": "user.plan"}` | value at the attribute path |
| `{"time": {"bucketMs": 3600000}}` | time bucket of `startedAt` |

* `tag`: a span with two tags is in both groups, so the counts and sums of the groups add up to more than the spans. A tag given twice on one span counts once.
* `attribute`: the path is read as in the `attributes` filter (`user.plan` is `{"user": {"plan": ..}}` or the flat key `user.plan`). The key keeps its type: `"1"`, `1` and `true` are three groups, and `1.0` is `1`. A span with a list at the path is in the group of each value.
* `time`: buckets start at the Unix epoch, so a bucket of a day is a UTC day. Only buckets with a span come back: a chart fills the others with zero.
* A span with no value for the key (no tag; for an attribute: no such path, `null` or an object) is in the group with the key `null`.

**thenBy** `object`

A second key, for a time series per value. `groupBy` must be a time bucket, and `thenBy` a field or an attribute: else `400`. Each row is one bucket and one value: `key` is the bucket, `key2` the value. Rows come by bucket (oldest first), and inside a bucket in the order of the series.

**metrics** `string[]` (default: \[])

The exact sums to compute per group. `sums` in each row has the same order.

**values**

| Metric | Sum of |
| - | - |
| `inputTokens` | every input token, the cached ones too |
| `outputTokens` | every output token, the reasoning ones too |
| `totalTokens` | input plus output tokens |
| `costNanos` | cost, nano-dollars |
| `durationMs` | durations; spans that have not ended count 0 |
| `errorCount` | failed spans |
| `cacheReadTokens` | input tokens read from the provider's cache |
| `cacheWriteTokens` | input tokens written to the provider's cache |
| `reasoningTokens` | output tokens used to reason |
| `inputCostNanos` | the part of the cost for input tokens |
| `outputCostNanos` | the part of the cost for output tokens |
| `timeToFirstTokenMs` | times to first token; spans with none count 0 (a percentile is more useful) |

**percentiles** `object[]` (default: \[])

Percentiles per group: `[{"p": 95}, {"p": 99.9, "approx": true}, {"p": 95, "of": "costNanos"}]`.

**properties**

**p** `number` *required*

From 0 to 100, at most 4 decimals.

**of** `string` (default: durationMs)

The value: any metric but `errorCount`.

**approx** `boolean` (default: false)

`false`: exact, by the nearest-rank rule. `true`: from a sketch, at most 1% off, with small memory for any span count.

Spans with no value do not count: for the duration, spans that have not ended; for a cost, spans with no such cost; for the time to first token, spans with none. A group where no span has a value gets `null`.

**sort** `object`

Rows by one value instead of by key: `{"by": "count" | {"sum": i} | {"percentile": i}, "order": "desc" | "asc"}`. `i` is an index into the row's `sums` or `percentiles`. `order` defaults to `"desc"`. Ties by key; `null` values last. Left out: rows by key.

**limit** `integer`

Keep this many rows, after the sort (top N). Left out: every row.

With `thenBy`, `sort` and `limit` choose whole series, not rows. A series is one value of `thenBy` over all buckets. The server puts the series in order by their count, sum or percentile over all matching spans, keeps the first `limit`, and returns every bucket of each. The 10 users with the highest cost, each with all its days: `{"groupBy": {"time": {"bucketMs": 86400000}}, "thenBy": {"field": "userId"}, "metrics": ["costNanos"], "sort": {"by": {"sum": 0}}, "limit": 10}`.

## Answer

**rows** `object[]`

One row per group. Rows by key: `null`, then text, then `true` and `false`, then numbers.

**row**

**key** `string | number | boolean | null`

The value (`"gpt-4o"`; for an attribute also a number or a boolean), the bucket start in ms (`1764000000000`), or `null` (`"all"`, or spans with no value).

**key2** `string | number | boolean | null`

The value of `thenBy`. Only with `thenBy`.

**count** `integer`

Spans in the group.

**sums** `integer[]`

One sum per metric, in the order of `metrics`.

**percentiles** `(integer | null)[]`

One value per percentile, in the order asked (ms for a duration). Only when the query asks for percentiles.

> [accordion] What a sum costs
>
> * With no percentiles, a filter on `kind`, `model` and time only (also as a tree of `and`, `or`, `not`) reads saved sums: one row per hour, kind and model. It reads spans only for the parts of the time range that are not whole hours.
> * The groups that the saved sums can give: `"all"`, kind, model, buckets of whole hours, and buckets of whole hours with `thenBy` kind or model.
> * Every other query visits every matching span: another field, a tag, an attribute, a bucket that is not whole hours, any percentile.
> * A group by attribute also reads, in each part of the store, the list of spans of every value of the path. A path with very many values is slow.

> [card] [Add up numbers](https://docs.magpiedb.com/queries/sums.md)
>
> A guide with real sums, series and percentiles.

> [card] [Sums of scores](https://docs.magpiedb.com/reference/api/scores-aggregate.md)
>
> Averages and label counts of eval scores.


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