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

# Query from your app

> Search text, count spans, find traces, add up tokens and cost, and page through results in Node.js, Python or Rust.

```js Node.js theme={null}
// spans with both words, newest first
const rows = await store.search({ filter: { text: { words: 'refund order' } }, limit: 10 })
// spans that failed with "timeout" in the error message
const failed = await store.count({ errorText: { words: 'timeout' } })
// traces with a failed tool call
const { count, traces } = await store.findTraces({ anySpan: [{ kind: 'tool_call', hasError: true }], limit: 10 })
// tokens per model
const perModel = await store.aggregate({ groupBy: { field: 'model' }, metrics: ['inputTokens', 'outputTokens'] })
```

```python Python theme={null}
# spans with both words, newest first
rows = store.search({"filter": {"text": {"words": "refund order"}}, "limit": 10})
# spans that failed with "timeout" in the error message
failed = store.count({"errorText": {"words": "timeout"}})
# traces with a failed tool call
found = store.find_traces({"anySpan": [{"kind": "tool_call", "hasError": True}], "limit": 10})
# tokens per model
per_model = store.aggregate({"groupBy": {"field": "model"}, "metrics": ["inputTokens", "outputTokens"]})
```

```rust Rust theme={null}
use magpiedb::{Filter, GroupBy, Metric, Sort, StrField, Text, TraceQuery};

// spans with both words, newest first
let rows = store.search(&Filter { text: Some(Text::words("refund order")), ..Default::default() }, Sort::Newest, 10)?;
// spans that failed with "timeout" in the error message
let failed = store.count(&Filter { error_text: Some(Text::words("timeout")), ..Default::default() })?;
// traces with a failed tool call
let found = store.find_traces(&TraceQuery {
    any_span: vec![Filter { kind: Some("tool_call".into()), has_error: Some(true), ..Default::default() }],
    limit: 10,
    ..Default::default()
})?;
// tokens per model
let per_model = store.aggregate(&Filter::default(), GroupBy::Field(StrField::Model), &[Metric::InputTokens, Metric::OutputTokens])?;
```

The library takes the same queries as the server. Every field of each query: [text search](https://docs.magpiedb.com/queries/text-search.md), [filters](https://docs.magpiedb.com/queries/filters.md), [whole traces](https://docs.magpiedb.com/queries/traces.md), [sums](https://docs.magpiedb.com/queries/sums.md). The examples use an open `store` ([open a store](https://docs.magpiedb.com/libraries/overview.md#open-a-store)).

## Pick the call

| Task | Node.js | Python | Rust | Returns |
| - | - | - | - | - |
| Find spans | `search(q)` | `search(q)` | `search(&filter, sort, limit)` | rows: `traceId`, `spanId`, `startedAt` |
| Find spans, one page | `searchPage(q)` | `search_page(q)` | `search_query(&q)` | `{ spans, nextCursor }` |
| Count spans | `count(filter)` | `count(filter=None)` | `count(&filter)` | a number |
| Find traces | `findTraces(q)` | `find_traces(q)` | `find_traces(&q)` | `{ count, traces, nextCursor }` |
| Add up | `aggregate(q)` | `aggregate(q)` | `aggregate(&filter, group_by, &metrics)`, `aggregate_query(&q)` | rows: `key`, `key2`, `count`, `sums`, `percentiles` |

Sessions and scores have their own calls: [sessions and scores](https://docs.magpiedb.com/libraries/sessions-scores.md). The route of the server for each call: [the same queries in the library](https://docs.magpiedb.com/queries/library.md).

## Search text

| Shape | Finds |
| - | - |
| `{ words: 'refund policy' }` | Every word, in any order. |
| `{ phrase: 'refund policy' }` | The words next to each other, in this order. |
| `{ contains: 'fund pol' }` | The string as you type it for `LIKE '%...%'`, also inside words: `und` finds `refund`. |
| `{ prefix: 'refund pol' }` | Whole words, and the last one may go on: `refund` finds `refunded`. |

Put a shape in `text` to look in `input` and `output`, or in `errorText` to look in the error message. Attribute values have no text search: `attributes` is an exact match of a whole value. What a word is, and the limits of `contains` and `prefix`: [text search](https://docs.magpiedb.com/queries/text-search.md).

## Find traces

```js Node.js theme={null}
// traces that failed or cost a dollar or more, and have no tool call
const found = await store.findTraces({
  filter: { or: [{ hasError: true }, { costNanos: { min: 1e9 } }], not: { anySpan: [{ kind: 'tool_call' }] } },
  limit: 20,
})
```

```python Python theme={null}
# traces that failed or cost a dollar or more, and have no tool call
found = store.find_traces({
    "filter": {"or": [{"hasError": True}, {"costNanos": {"min": 10**9}}], "not": {"anySpan": [{"kind": "tool_call"}]}},
    "limit": 20,
})
```

```rust Rust theme={null}
use magpiedb::{NumRange, TraceFilter};

// traces that failed or cost a dollar or more, and have no tool call
let found = store.find_traces(&TraceQuery {
    filter: TraceFilter {
        or: Some(vec![
            TraceFilter { has_error: Some(true), ..Default::default() },
            TraceFilter { cost_nanos: Some(NumRange { min: Some(1_000_000_000), max: None }), ..Default::default() },
        ]),
        not: Some(Box::new(TraceFilter {
            any_span: vec![Filter { kind: Some("tool_call".into()), ..Default::default() }],
            ..Default::default()
        })),
        ..Default::default()
    },
    limit: 20,
    ..Default::default()
})?;
```

`count` is the number of all matching traces; `traces` holds one page of summaries. Every field of a trace filter (`root`, `anySpan`, `anyScore`, ranges of totals, `and`, `or`, `not`): [whole traces](https://docs.magpiedb.com/queries/traces.md) and [filters](https://docs.magpiedb.com/queries/filters.md).

## Add up tokens and cost

```js Node.js theme={null}
// the 10 users with the highest cost, with the p95 duration of their spans
const top = await store.aggregate({
  groupBy: { field: 'userId' }, metrics: ['costNanos'], percentiles: [{ p: 95 }], sort: { by: { sum: 0 } }, limit: 10,
})
```

```python Python theme={null}
# the 10 users with the highest cost, with the p95 duration of their spans
top = store.aggregate({
    "groupBy": {"field": "userId"}, "metrics": ["costNanos"], "percentiles": [{"p": 95}], "sort": {"by": {"sum": 0}}, "limit": 10,
})
```

```rust Rust theme={null}
use magpiedb::{AggregateQuery, GroupSort, GroupSortBy, Order, Percentile};

// the 10 users with the highest cost, with the p95 duration of their spans
let top = store.aggregate_query(&AggregateQuery {
    group_by: GroupBy::Field(StrField::UserId),
    metrics: vec![Metric::CostNanos],
    percentiles: vec![Percentile { p: 95.0, approx: false, of: None }],
    sort: Some(GroupSort { by: GroupSortBy::Sum(0), order: Order::Desc }),
    limit: Some(10),
    ..Default::default()
})?;
```

Each row has `key` (the group), `count`, and `sums`: one exact integer per metric, in the order of `metrics`. It has `percentiles` only when the query asks for some; a group where no span has a value gets `null`. Time buckets, a second key (`thenBy`), every metric and percentile: [sums](https://docs.magpiedb.com/queries/sums.md).

## Page through results

```js Node.js theme={null}
let cursor = null
do {
  const page = await store.searchPage({ filter: { text: { words: 'refund' } }, limit: 100, cursor })
  for (const row of page.spans) console.log(row.traceId, row.spanId)
  cursor = page.nextCursor
} while (cursor)
```

```python Python theme={null}
cursor = None
while True:
    page = store.search_page({"filter": {"text": {"words": "refund"}}, "limit": 100, "cursor": cursor})
    for row in page["spans"]:
        print(row["traceId"], row["spanId"])
    cursor = page["nextCursor"]
    if cursor is None:
        break
```

```rust Rust theme={null}
use magpiedb::SearchQuery;

let mut q = SearchQuery { filter: Filter { text: Some(Text::words("refund")), ..Default::default() }, limit: 100, ..Default::default() };
loop {
    let page = store.search_query(&q)?;
    for row in &page.spans {
        println!("{} {}", row.trace_id, row.span_id);
    }
    match page.next_cursor {
        Some(c) => q.cursor = Some(c),
        None => break,
    }
}
```

`findTraces`, `findSessions` and `traceSpans` page the same way.

* `nextCursor` is `null` (`None`) on the last page. Ties: `spanId`, then `traceId` (spans); `traceId` (traces); `sessionId` (sessions).
* A cursor is a position in the sort order, not a saved result. Each page is read as of its own call and costs about as much as page 1.
* A row whose sort key does not change comes exactly once, in order, also while writes go on. A new row that sorts before the position does not come; one that sorts after it comes on a later page.
* A trace whose start moves during the walk (an earlier span arrives) can come twice or not at all.
* A cursor given with another `sort`, or to another list, is an error. So is a string that is not a cursor.

## Show previews of the text

With `previewChars: 80` (Rust: `preview_chars: Some(80)`), each row also has `inputPreview` and `outputPreview`: the first 80 characters of the text.

* A search row: of the span. It reads the stored span.
* A trace row: of the root span. A root with no input gives the input of the earliest span that has one (start, then span id). A root with no output gives the output of the span that ended last among those that have one (ties: earlier start, then smaller span id).
* The summary of a trace keeps the first 200 characters of both texts, so up to 200 the list reads no stored span. With more, it reads the stored span of each longer text.

## Defaults

| Field | Default |
| - | - |
| `limit` of `search`, `findTraces`, `findSessions`, `traceSpans` | 50. `0` on `findTraces`, `findSessions` and `traceSpans`: only the count. |
| `limit` of `aggregate` | every row |
| `groupBy` | `'all'`: one group |
| `sort` | `'newest'`; or `'oldest'` |

> [!WARNING]
>
> In Rust, `..Default::default()` gives `limit: 0` in `SearchQuery`, `TraceQuery` and `SessionQuery`: no rows. Set `limit`, for example to `magpiedb::DEFAULT_LIMIT` (50).

> [card] [Sessions and scores](https://docs.magpiedb.com/libraries/sessions-scores.md)
>
> Score traces, sum scores, list sessions.

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

> [card] [All query types](https://docs.magpiedb.com/queries/overview.md)
>
> Every query shape, with examples.


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