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

# Sessions and scores

> Write scores on traces, spans and sessions, read them, add them up, and list sessions from Node.js, Python or Rust.

```js Node.js theme={null}
const at = Date.now()
await store.writeScores([
  { traceId: 't1', name: 'quality', value: 0.8, source: 'llm-judge', at },         // on a trace
  { traceId: 't1', spanId: 's2', name: 'tool-ok', value: 0, type: 'boolean', at }, // on a span
  { sessionId: 'chat-1', name: 'resolved', value: 1, type: 'boolean', at },        // on a session
  { traceId: 't1', name: 'tone', label: 'polite', at },                            // a category
])
await store.commit()
const scores = await store.getScores('t1')                // on the trace and on its spans
const onSession = await store.getSessionScores('chat-1')  // on the session itself
```

```python Python theme={null}
import time

at = int(time.time() * 1000)
store.write_scores([
    {"traceId": "t1", "name": "quality", "value": 0.8, "source": "llm-judge", "at": at},          # on a trace
    {"traceId": "t1", "spanId": "s2", "name": "tool-ok", "value": 0, "type": "boolean", "at": at},  # on a span
    {"sessionId": "chat-1", "name": "resolved", "value": 1, "type": "boolean", "at": at},         # on a session
    {"traceId": "t1", "name": "tone", "label": "polite", "at": at},                               # a category
])
store.commit()
scores = store.get_scores("t1")                   # on the trace and on its spans
on_session = store.get_session_scores("chat-1")   # on the session itself
```

```rust Rust theme={null}
use magpiedb::{Score, ScoreType};

let at = 1_764_547_300_000;
store.write_scores(vec![
    Score { source: Some("llm-judge".into()), ..Score::new("t1", "quality", 0.8, at) }, // on a trace
    Score { span_id: Some("s2".into()), score_type: Some(ScoreType::Boolean), ..Score::new("t1", "tool-ok", 0.0, at) }, // on a span
    Score { score_type: Some(ScoreType::Boolean), ..Score::on_session("chat-1", "resolved", 1.0, at) }, // on a session
    Score { label: Some("polite".into()), ..Score::new("t1", "tone", f64::NAN, at) }, // a category: NaN is no value
])?;
store.commit()?;
let scores = store.get_scores("t1")?;                  // on the trace and on its spans
let on_session = store.get_session_scores("chat-1")?;  // on the session itself
```

A score is a number, a yes or no, or a label: from a person, an LLM judge or a test. It can come long after its trace. The examples use an open `store` ([open a store](https://docs.magpiedb.com/libraries/overview.md#open-a-store)).

## Score fields

Rust uses the same names in snake\_case; `type` is `score_type`.

| Field | What it is |
| - | - |
| `traceId`, `spanId`, `sessionId` | The target: a trace (`traceId`), a span (`traceId` and `spanId`), or a session (`sessionId` and no `traceId`). |
| `name` | Required. `quality`, `hallucination`, ... |
| `value` | A finite number. A score with a `label` and no value is a category, stored with the value 0. |
| `label` | The result of a category: `pass`, `polite`, ... |
| `type` | `'number'` (also when left out), `'boolean'` (the value is 0 or 1), `'category'` (it has a label). |
| `source` | The kind of giver: `'human'`, `'llm-judge'`, `'code'`. |
| `authorId` | Who gave it: a user id, or the name of a judge. |
| `evalId` | The eval that made it: an evaluator and its version, a score config, or one run of an experiment. |
| `comment` | A comment, or the reason a judge gave. |
| `at` | Required. The time of the score, in Unix milliseconds. |

* A score replaces the stored score with the same target, `name`, `source`, `authorId` and `evalId`. So two people, or two runs of an eval, keep one score each.
* A score with no target or two, a boolean that is not 0 or 1, or a category with no label is an error, and its batch is refused whole.
* Scores on a session are not in `getScores` of its traces, and not in `anyScore`. They go with `deleteSession`, and when a delete or a drop removes the last trace of the session. `deleteTrace` leaves them.

To find traces by their scores, use `anyScore` in [`findTraces`](https://docs.magpiedb.com/libraries/query#find-traces).

## Add up scores

```js Node.js theme={null}
// the average quality per day
const perDay = await store.aggregateScores({ score: { name: 'quality' }, groupBy: { time: { bucketMs: 86400000 } } })
// one row per day: { key, count, avg, labels }; key is the start of the day
```

```python Python theme={null}
# the average quality per day
per_day = store.aggregate_scores({"score": {"name": "quality"}, "groupBy": {"time": {"bucketMs": 86_400_000}}})
# one row per day: {key, count, avg, labels}; key is the start of the day
```

```rust Rust theme={null}
use magpiedb::{ScoreAggregateQuery, ScoreFilter, ScoreGroupBy};

// the average quality per day
let per_day = store.aggregate_scores(&ScoreAggregateQuery {
    score: ScoreFilter { name: "quality".into(), ..Default::default() },
    group_by: ScoreGroupBy::Time { bucket_ms: 86_400_000 },
    ..Default::default()
})?;
```

| Field | What it does |
| - | - |
| `score` | Which scores: `name` (required), `min`, `max`, `label`, `source`, `authorId`, `evalId`, and `from`, `to` on the score's own time `at`. |
| `traces` | Only the scores of the traces that meet this trace filter (the filter of `findTraces`). |
| `groupBy` | `'all'` (default), `{ time: { bucketMs } }`, `{ traceField: 'model' }` (also `userId`, `sessionId`, `name`, `tag`, `environment`, `service`), `{ rootAttribute: 'prompt.version' }`. |
| `thenBy` | A second key with a time bucket in `groupBy`: one series per value. |
| `percentiles` | `[50, 95]`: exact, by nearest rank. |
| `sort`, `limit` | `{ by: 'count' }` or `{ by: 'avg' }`, with `order`; the first `limit` rows (with `thenBy`: series). |

Each row has `key`, `count` (every score of the group), `avg` and `labels` (the count per label). `avg` is the average of the numbers and booleans; of a boolean, it is the share of true. It is `null` for a group of categories.

The trace side is read when the query runs, so a group follows the trace as it is now. A score with no trace in the store has the key `null`. To compare two experiments, run the query once per group: for example with `traces: { root: { attributes: { experiment: 'A' } } }`, then with `'B'`. More examples: [sessions and scores](https://docs.magpiedb.com/queries/sessions-scores.md).

## List sessions

```js Node.js theme={null}
const { count, sessions, nextCursor } = await store.findSessions({ filter: { userId: 'user-7' }, limit: 20 })
const one = await store.getSession('chat-1') // { session, traces }, or null
```

```python Python theme={null}
page = store.find_sessions({"filter": {"userId": "user-7"}, "limit": 20})
one = store.get_session("chat-1")  # {"session": ..., "traces": [...]}, or None
```

```rust Rust theme={null}
use magpiedb::{SessionFilter, SessionQuery};

let page = store.find_sessions(&SessionQuery {
    filter: SessionFilter { user_id: Some("user-7".into()), ..Default::default() },
    limit: 20,
    ..Default::default()
})?;
let one = store.get_session("chat-1")?; // Some(SessionTraces), or None
```

A session is a conversation: the traces with one `sessionId`. A trace's session is the `sessionId` of its root span, or else of its earliest span that has one.

* `findSessions` gives the newest first, with sums over the traces: `traceCount`, `spanCount`, `errorCount`, tokens and `costNanos`. It pages by `cursor`, as the other lists do.
* A row also has `userId` (of the earliest trace that has one), `firstTraceId` and `firstInput`, `lastTraceId` and `lastOutput` (the first 200 characters).
* The filter takes `userId`, `from` and `to`: the start of the session.
* `getSession` gives every trace of the session, oldest first. For a very large session, page `findTraces` with `filter.sessionId`.

> [card] [Read and export](https://docs.magpiedb.com/libraries/read-export.md)
>
> Read whole traces, export to JSON Lines.

> [card] [Delete and maintain](https://docs.magpiedb.com/libraries/delete-maintenance.md)
>
> Delete users, drop old spans, free disk space.


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