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

# Write spans

> Write spans from your app with write or upsert, commit them, compute their cost and mask private data.

```js Node.js theme={null}
const now = Date.now() // times are Unix milliseconds
await store.write([
  { traceId: 't1', spanId: 's1', kind: 'agent_run', startedAt: now, userId: 'user-7', input: 'please refund my order' },
  { traceId: 't1', spanId: 's2', parentSpanId: 's1', kind: 'tool_call', name: 'lookup_order', startedAt: now, error: 'timeout' },
])
await store.commit() // or wait for the commit timer (500 ms)
```

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

now = int(time.time() * 1000)  # times are Unix milliseconds
store.write([
    {"traceId": "t1", "spanId": "s1", "kind": "agent_run", "startedAt": now, "userId": "user-7", "input": "please refund my order"},
    {"traceId": "t1", "spanId": "s2", "parentSpanId": "s1", "kind": "tool_call", "name": "lookup_order", "startedAt": now, "error": "timeout"},
])
store.commit()  # or wait for the commit timer (500 ms)
```

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

let now = 1_764_547_200_000; // times are Unix milliseconds
let mut run = Span::new("t1", "s1", "agent_run", now);
run.user_id = Some("user-7".into());
run.input = "please refund my order".into();
let mut tool = Span::new("t1", "s2", "tool_call", now);
tool.parent_span_id = Some("s1".into());
tool.name = "lookup_order".into();
tool.error = Some("timeout".into());
store.write(vec![run, tool])?;
store.commit()?; // or wait for the commit timer (500 ms)
```

A span is one step of an agent run: the run itself, a model call, a tool call. Every span needs `traceId`, `spanId`, `kind` and `startedAt`. The example uses an open `store` ([open a store](https://docs.magpiedb.com/libraries/overview.md#open-a-store)).

## Write a span when it starts and when it ends

```js Node.js theme={null}
const call = { traceId: 't2', spanId: 'm1', kind: 'model_generation', model: 'gpt-4o', startedAt: Date.now() }
await store.upsert([call]) // the span starts
await store.upsert([{ ...call, endedAt: Date.now(), inputTokens: 120, outputTokens: 40 }]) // it ends: this version replaces the first
```

```python Python theme={null}
call = {"traceId": "t2", "spanId": "m1", "kind": "model_generation", "model": "gpt-4o", "startedAt": now}
store.upsert([call])  # the span starts
store.upsert([{**call, "endedAt": now + 2000, "inputTokens": 120, "outputTokens": 40}])  # it ends: this version replaces the first
```

```rust Rust theme={null}
let mut call = Span::new("t2", "m1", "model_generation", now);
call.model = Some("gpt-4o".into());
store.upsert(vec![call.clone()])?; // the span starts
call.ended_at = Some(now + 2_000);
call.input_tokens = 120;
call.output_tokens = 40;
store.upsert(vec![call])?; // it ends: this version replaces the first
```

| Call | Use it for | A span with the same `traceId` and `spanId` is stored |
| - | - | - |
| `write` | Spans written once, when they are complete. The fast path. | Again: the store has two copies. |
| `upsert` | A span written when it starts and again when it ends, and writes that may be retried. | Replaced. |

Both return the number of spans. A batch with one invalid span is refused whole.

## When a span can be found

A span is in the write log when `write` returns. Queries find it after the next commit: call `commit()`, or wait for the timer (`commitInterval`, 500 ms by default). `commit()` returns the operation stamp of the commit. What a write survives depends on the option `durability` ([options](https://docs.magpiedb.com/libraries/overview.md#set-options)).

## Span fields

Node.js and Python use these camelCase names. Rust uses the same names in snake\_case (`trace_id`), and `Span::new(trace_id, span_id, kind, started_at)` sets the four that every span needs.

| Field | Type | What it is |
| - | - | - |
| `traceId`, `spanId` | string | Required. The ids of the trace and of the span. |
| `parentSpanId` | string | Not set: the root span of the trace. |
| `kind` | string | Required. `agent_run`, `model_generation`, `tool_call`, ... Exact match in filters. |
| `startedAt` | integer | Required. Unix milliseconds. |
| `endedAt` | integer | Not set: still running. Write the span again with `upsert` when it ends. |
| `name`, `model`, `userId`, `sessionId`, `service`, `environment` | string | Exact match in filters. |
| `tags` | list of strings | |
| `input`, `output` | string | The text that full-text search reads. |
| `status` | `'unset'`, `'ok'`, `'error'` | |
| `error` | string | The error message. A span failed when `status` is `'error'` or `error` is set. |
| `inputTokens`, `outputTokens` | integer | Every input token and every output token. |
| `cacheReadTokens`, `cacheWriteTokens` | integer | Input tokens read from and written to the provider's cache: a part of `inputTokens`. |
| `reasoningTokens` | integer | Output tokens the model used to reason: a part of `outputTokens`. |
| `timeToFirstTokenMs` | integer | Milliseconds from `startedAt` to the first piece of the answer. |
| `cost` | number | US dollars, the total. Stored as whole nano-dollars, so values round to 9 decimals. |
| `inputCost`, `outputCost` | number | Parts of `cost`. When `cost` is not given, it is their sum. |
| `costComputed` | boolean | The store computed the cost from a price table. |
| `attributes` | JSON object | Each leaf value can be filtered by exact match. |
| `events` | JSON array | Stored, not indexed. |

Never add a part to its whole: that is the rule of the OpenTelemetry GenAI conventions and of OpenAI's numbers. Anthropic reports input tokens without the cached ones: add `input_tokens`, `cache_read_input_tokens` and `cache_creation_input_tokens`. Google reports output tokens without the thinking tokens: add them. A span with a part above its whole is refused.

An answer leaves out the usage fields that are 0 or not set. Read them with a default: `span.cacheReadTokens ?? 0` in Node.js, `span.get("cacheReadTokens", 0)` in Python.

## Compute cost from a price table

```js Node.js theme={null}
const store = await Store.open('./traces', {
  prices: { perMillionTokens: { 'my-model': { input: 3, output: 15, cacheRead: 0.3, cacheWrite: 3.75 } } },
})
```

```python Python theme={null}
store = Store.open("./traces", prices={"perMillionTokens": {"my-model": {"input": 3, "output": 15, "cacheRead": 0.3, "cacheWrite": 3.75}}})
```

```rust Rust theme={null}
// needs serde_json in your Cargo.toml
let prices: magpiedb::Prices = serde_json::from_str(
    r#"{"perMillionTokens": {"my-model": {"input": 3, "output": 15, "cacheRead": 0.3, "cacheWrite": 3.75}}}"#,
)?;
let store = Store::open("traces", Options { prices: Some(prices), ..Default::default() })?;
```

With this table, a `my-model` span with 1,000,000 input tokens and 1,000 output tokens gets `cost` 3.015 and `costComputed: true`.

* Prices are US dollars per one million tokens, by the exact model name, with at most 6 decimals. `cacheRead` and `cacheWrite` default to the `input` price.
* `write` and `upsert` compute the cost of a span that has a model of the table, tokens, and no cost: `inputCost`, `outputCost` and `cost`, their sum.
* The cost is computed once, when the span is written. A new table changes new spans only.
* A span that comes with a `cost`, or a part of it, keeps it. A model that is not in the table gets no cost, and so does a span with no tokens.
* No price list comes with the package: take the numbers from the price page of your provider. The table is the same as the file of `magpie-server --prices`.

## Mask private data

```js Node.js theme={null}
const store = await Store.open('./traces', {
  mask: {
    rules: [{ builtin: 'email' }, { builtin: 'secret' }, { name: 'order', pattern: 'ORD-[0-9]{8}', replace: '[ORDER]' }],
    dropAttributes: ['user.address'],
  },
})
console.log(await store.maskCounts()) // { rules: [{ name: 'email', masked: 0 }, ...], droppedAttributes: 0 }
```

```python Python theme={null}
store = Store.open("./traces", mask={
    "rules": [{"builtin": "email"}, {"builtin": "secret"}, {"name": "order", "pattern": "ORD-[0-9]{8}", "replace": "[ORDER]"}],
    "dropAttributes": ["user.address"],
})
print(store.mask_counts())  # {'rules': [{'name': 'email', 'masked': 0}, ...], 'droppedAttributes': 0}
```

```rust Rust theme={null}
use magpiedb::{MaskPolicy, MaskRule};

let mask = MaskPolicy {
    rules: vec![
        MaskRule::builtin("email"),
        MaskRule::builtin("secret"),
        MaskRule { replace: Some("[ORDER]".into()), ..MaskRule::pattern("order", "ORD-[0-9]{8}") },
    ],
    drop_attributes: vec!["user.address".into()],
};
let store = Store::open("traces", Options { mask: Some(mask), ..Default::default() })?;
println!("{:?}", store.mask_counts());
```

`write`, `upsert` and `writeScores` replace every match before the write goes into the write log. No file of the store holds the original text, no search finds it, and no read returns it. Masking is off by default.

| | |
| - | - |
| Built-in rules | `email`, `credit_card` (with a Luhn check), `ipv4`, `phone` (only `+` and 8 to 15 digits), `secret` (key shapes such as `sk-`, AWS access key ids, GitHub and Slack tokens, JWTs, `Bearer <token>`, PEM private keys). Each is off until you name it. No rule finds names of people. |
| Your own rule | `pattern` is a regex of the Rust `regex` crate. `replace` defaults to the rule's name in upper case in square brackets (`[EMAIL]`). |
| Masked | `input`, `output`, `error`, every string value in `attributes` and `events`, and the `label` and `comment` of a score. |
| Not masked | Ids (trace, span, parent, session, user), `name`, `kind`, `model`, `service`, `environment`, `tags`, attribute keys, numbers. |
| `dropAttributes` | Removes attribute values whole, by path. A dot is a path step; a path names everything below it. |
| Two rules match | All rules look at the text as it was sent. The match that starts first wins, then the longer one, then the first rule. |
| Errors | A wrong rule makes `open` fail. It never makes a write fail. A new policy changes new writes only. |
| Limits | Text that holds JSON is masked as text: a value with a JSON escape inside it (`bob@example.com`) is not found. What no rule matches is stored. |
| Counts | `maskCounts()` (Python and Rust: `mask_counts()`) counts the matches per rule since the store opened. It never gives a value. With no policy: `null`, `None`. |

The same policy is the file of `magpie-server --mask`. What each built-in rule does not find: [masking reference](https://docs.magpiedb.com/reference/mapping-cost-masking.md).

> [accordion] A span written twice with write
>
> `write` does not look for an older version, so a span id written twice is stored twice. Lists of rows (search, `traceSpans`, the export) give every copy; copies with one start come in no promised order.
>
> Where an answer takes one copy, it takes the least by a fixed copy order, not the one that came first. The order: the span's fields (root or not, `kind`, `name`, `model`, `userId`, `sessionId`, `service`, `environment`, error, `endedAt`, the token counts, the costs, the time to first token, whether it has an input and an output; not set comes first), then the first 200 characters of `input` and of `output`, then its line of the export. This holds for the summary of a trace, for `getSpan` (of the copies with the latest start) and for `getTrace` (copies with one start). A preview of more than 200 characters comes from the copy whose text starts with the 200 characters that the summary keeps.
>
> To replace a span, use `upsert`.

> [card] [Query from your app](https://docs.magpiedb.com/libraries/query.md)
>
> Search text, find traces, add up tokens and cost.

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

> [card] [Errors and input rules](https://docs.magpiedb.com/libraries/errors.md)
>
> Unknown fields, depth, numbers, a full disk.


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