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

# Read and export

> Read a whole trace, page through a very large one, and export spans and scores to JSON Lines from Node.js, Python or Rust.

```js Node.js theme={null}
const spans = await store.getTrace('t1')                             // every span, with its text
const page = await store.traceSpans({ traceId: 't1', limit: 1000 })  // { count, spans, nextCursor }, no text
const step = await store.getSpan({ traceId: 't1', spanId: 's2' })    // one span with its text, or null
```

```python Python theme={null}
spans = store.get_trace("t1")                              # every span, with its text
page = store.trace_spans({"traceId": "t1", "limit": 1000})  # {count, spans, nextCursor}, no text
step = store.get_span({"traceId": "t1", "spanId": "s2"})    # one span with its text, or None
```

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

let spans = store.get_trace("t1")?; // every span, with its text
let page = store.trace_spans(&TraceSpansQuery { trace_id: "t1".into(), limit: 1000, ..Default::default() })?; // no text
let step = store.get_span("t1", "s2")?; // one span with its text, or None
```

The examples use an open `store` ([open a store](https://docs.magpiedb.com/libraries/overview.md#open-a-store)).

| Call | Gives | Use it for |
| - | - | - |
| `getTrace(traceId)` | Every span of the trace with every field, by `startedAt`, then `spanId`. | A normal trace. |
| `traceSpans({ traceId, limit, cursor })` | One page of the spans without their text, in the same order, and the `count` of all spans. | A trace too large for `getTrace`: draw the tree and the timeline. |
| `getSpan({ traceId, spanId })` | One span with every field. It reads one stored span, not the trace. | The text of one step. |

`getTrace` of a trace with 100,000 spans is hundreds of MB. A `traceSpans` row has `spanId`, `parentSpanId`, `name`, `kind`, `model`, `startedAt`, `endedAt`, `hasError`, `inputTokens`, `outputTokens`, `cost`, and the usage fields that the span has. Each page reads the time of every span of the trace once, so for a whole trace use a large `limit`.

## Export spans to JSON Lines

```js Node.js theme={null}
import fs from 'node:fs'
import { Readable } from 'node:stream'
import { pipeline } from 'node:stream/promises'

await pipeline(Readable.from(store.export({ filter: { from: 1764547200000 } })), fs.createWriteStream('spans.ndjson'))
```

```python Python theme={null}
with open("spans.ndjson", "w") as f:
    for chunk in store.export({"filter": {"from": 1764547200000}}):
        f.write(chunk)
```

```rust Rust theme={null}
use std::io::Write;
use magpiedb::ExportQuery;

let mut file = std::fs::File::create("spans.ndjson")?;
for chunk in store.export(&ExportQuery { filter: Filter { from: Some(1_764_547_200_000), ..Default::default() } })? {
    file.write_all(chunk?.as_bytes())?;
}
```

`export` gives every span that matches the filter, oldest first. With no filter, it gives every span of the store.

* Each chunk is a string of whole lines, at most a few MB. A line is one span as JSON, in the shape that `write` takes.
* The next chunk is made when the loop asks for it, so memory stays small for a store of any size.
* A line has no line break inside, also not U+2028, U+2029 or U+0085 (they are written as escapes). `readline` in Node.js and `str.splitlines` in Python read one span per line.
* The export reads the commit of the moment it starts: later writes and deletes are not in it. It keeps the files of that commit open until the loop ends. Leave the loop (`break`) to give it up; in Python, `.close()` on the iterator also does.
* A bad query: Node.js rejects it when the loop starts, Python raises at the call, Rust returns the error from `export`.

## Load an export into another store

```js Node.js theme={null}
for await (const chunk of store.export()) {
  await target.write(chunk.split('\n').filter(Boolean).map((line) => JSON.parse(line)))
}
await target.commit()
```

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

for chunk in store.export():
    target.write([json.loads(line) for line in chunk.splitlines()])
target.commit()
```

```rust Rust theme={null}
// needs serde_json in your Cargo.toml
for chunk in store.export(&ExportQuery::default())? {
    let spans: Vec<Span> = chunk?.lines().map(serde_json::from_str).collect::<Result<_, _>>()?;
    target.write(spans)?;
}
target.commit()?;
```

`target` is a second store, open for writing in another folder.

## Export scores

`exportScores({ from, to })` (Python and Rust: `export_scores`) works the same way for scores. `from` and `to` are a time range on the score's time `at`. The lines come in no promised order, in the shape that `writeScores` takes.

Backups and imports with the server: [backup and import](https://docs.magpiedb.com/operations/backup-import.md).

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

> [card] [Backup and import](https://docs.magpiedb.com/operations/backup-import.md)
>
> Copy a store, move data between stores.


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