> ## 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.
> Packages and server binaries are not published yet: build from source, as the quick start shows. Check the status note on the introduction page before you suggest `cargo add`, `npm install` or `pip install`.
> Only one process may write to a store folder at a time. For many apps, send traces to one `magpie-server`.

# Mapping, cost and masking

> How magpie-server maps OpenTelemetry GenAI spans to Magpie spans, how it computes cost from a price file, and how it masks private data before it is stored.

## Mapping from an OpenTelemetry span to a Magpie span

`src/genai.rs`, `MAPPING_VERSION = 2` (2: usage and cost; spans stored with mapping 1 have no cached or reasoning tokens, no time to first token and no cost). It follows the OpenTelemetry GenAI semantic conventions, `open-telemetry/semantic-conventions-genai` release v0.1.0 (2026-11-21). These are still marked "Development", so the mapping has its own version, and every stored span has `magpie.mapping: 2` in its attributes. It also reads older GenAI names and a few clear names of the Vercel AI SDK and OpenInference. The first name found wins.

| Magpie field | taken from |
| - | - |
| `traceId`, `spanId`, `parentSpanId` | the OTLP ids, as lowercase hex. An all-zero parent is no parent. |
| `startedAt`, `endedAt` | the OTLP times, ns -> ms (rounded down). End time 0: still running (`endedAt` null). |
| `name` | the span name |
| `kind` | `gen_ai.operation.name`: `chat`, `generate_content`, `text_completion`, `realtime_inference` -> `model_generation`; `execute_tool` -> `tool_call`; `invoke_agent` -> `agent_run`; other operations as they are (`embeddings`, `retrieval`, `invoke_workflow`, ...). Without it: the first word of the span name if it is one of those operations; else OpenInference `openinference.span.kind` (`LLM`, `TOOL`, `AGENT`, `EMBEDDING`, else lowercase); else Vercel `ai.operationId` (`*.doGenerate`, `*.doStream` -> `model_generation`, `*.doEmbed` -> `embeddings`, `ai.toolCall` -> `tool_call`, else the id); else the OTel span kind (`internal`, `server`, `client`, `producer`, `consumer`). |
| `model` | `gen_ai.response.model`, `gen_ai.request.model`, `llm.model_name`, `ai.response.model`, `ai.model.id` |
| `inputTokens` | only for `model_generation` and `embeddings` spans: `gen_ai.usage.input_tokens`, `gen_ai.usage.prompt_tokens`, `llm.token_count.prompt`, `ai.usage.inputTokens`, `ai.usage.promptTokens`, `ai.usage.tokens` |
| `outputTokens` | same rule: `gen_ai.usage.output_tokens`, `gen_ai.usage.completion_tokens`, `llm.token_count.completion`, `ai.usage.outputTokens`, `ai.usage.completionTokens` |
| `cacheReadTokens` | same rule: `gen_ai.usage.cache_read.input_tokens` (semconv 1.40 and later), `gen_ai.usage.cache_read_input_tokens` (OpenLLMetry), `llm.token_count.prompt_details.cache_read` (OpenInference), `ai.usage.inputTokenDetails.cacheReadTokens`, `ai.usage.cachedInputTokens` (Vercel AI SDK) |
| `cacheWriteTokens` | same rule: `gen_ai.usage.cache_write.input_tokens` (GenAI conventions v0.1.0), `gen_ai.usage.cache_creation.input_tokens` (semconv 1.40 and 1.41), `gen_ai.usage.cache_creation_input_tokens` (OpenLLMetry), `llm.token_count.prompt_details.cache_write`, `ai.usage.inputTokenDetails.cacheWriteTokens` |
| `reasoningTokens` | same rule: `gen_ai.usage.reasoning.output_tokens` (semconv 1.41 and later), `gen_ai.usage.reasoning_tokens` (OpenLLMetry), `llm.token_count.completion_details.reasoning`, `ai.usage.outputTokenDetails.reasoningTokens`, `ai.usage.reasoningTokens` |
| `timeToFirstTokenMs` | same rule: `gen_ai.response.time_to_first_chunk` (seconds, semconv 1.41 and later) x 1000; `ai.response.msToFirstChunk`, `ai.stream.msToFirstChunk` (ms) on the span or on its `ai.stream.firstChunk` event. Rounded to whole ms. |
| `cost`, `inputCost`, `outputCost` | same rule, US dollars: `gen_ai.usage.cost` or `llm.cost.total`; `llm.cost.prompt`; `llm.cost.completion`. The GenAI conventions have no cost attribute. With no cost: `--prices` (see [Cost](https://docs.magpiedb.com/reference/mapping-cost-masking.md#cost)). A value that is not a number from 0 to 1.8e10 stays in the attributes. |
| `input` | `gen_ai.system_instructions` + `gen_ai.input.messages`; else `gen_ai.tool.call.arguments`, `gen_ai.retrieval.query.text`, `gen_ai.prompt`, `ai.prompt.messages`, `ai.prompt`, `ai.toolCall.args`, `ai.toolCall.input`, `input.value`; else OpenLLMetry `gen_ai.prompt.N.*`; else span events: `gen_ai.client.inference.operation.details`, `gen_ai.content.prompt`, `gen_ai.{system,user,assistant,tool}.message` |
| `output` | `gen_ai.output.messages`; else `gen_ai.tool.call.result`, `gen_ai.completion`, `ai.response.text`, `ai.response.object`, `ai.toolCall.result`, `ai.toolCall.output`, `ai.response.toolCalls`, `output.value`; else `gen_ai.completion.N.*`; else events `gen_ai.client.inference.operation.details`, `gen_ai.content.completion`, `gen_ai.choice` |
| `userId` | span `user.id`, `enduser.id`, `ai.telemetry.metadata.userId`; else the same on the resource |
| `sessionId` | span `session.id`, `gen_ai.conversation.id`, `ai.telemetry.metadata.sessionId`; else the same on the resource |
| `service` | resource `service.name` |
| `environment` | resource `deployment.environment.name`, `deployment.environment` |
| `status`, `error` | status `ERROR` -> `error`, with the status message, else the first exception event (`exception.type: exception.message`), else `error.type`. Status unset with an exception event: `error` is set (the span counts as failed). Status `OK`: no error. |
| `attributes` | every span attribute not used above, with its OTel key; resource attributes not used above under `resource`; `otel.scope.name`, `otel.scope.version`; `magpie.mapping`. `gen_ai.operation.name` and `gen_ai.request.model` (when the response model is used) stay. |
| `events` | every span event: `{"name", "time" (ms), "attributes"}` |

`input` and `output` are readable text, not JSON. A message becomes `role: text`, one line each; other objects become `key: value` lines. Why: it is easier to read, and real line breaks keep every word a word. (The core also indexes a word after a JSON escape like `\nRefund` as `refund`, so JSON text is found too.)

Why tokens come from model calls only: an `invoke_agent` span reports the sum of the model calls under it (the conventions say so). Counting both would count the same tokens twice in trace totals and sums. The agent's own numbers stay in its attributes. The same holds for cached and reasoning tokens, the cost and the time to first token.

Cached and reasoning tokens are parts, not extra tokens. In Magpie, `inputTokens` is every input token (the cached ones too) and `outputTokens` is every output token (the reasoning ones too), so `totalTokens = inputTokens + outputTokens` counts each token once. The GenAI conventions say the same: `gen_ai.usage.input_tokens` "SHOULD include cached tokens", and the cache and reasoning counts "SHOULD be included in" the two totals. The providers differ: OpenAI's `input_tokens` has the cached tokens in it, Anthropic's `input_tokens` does not (the total is `input_tokens + cache_read_input_tokens + cache_creation_input_tokens`), and Google's `candidatesTokenCount` is next to its `thoughtsTokenCount`, not around it. An instrumentation that follows the conventions adds them up before it sends. For one that does not, the server has one rule: a part that is larger than its whole shows that the parts were left out, so they are added to the count, and the count as it came stays in the attributes (`magpie.usage.input_tokens_reported`, `magpie.usage.output_tokens_reported`). When the parts are smaller than the count, the server cannot know, and takes the numbers as they are.

## Cost

A span has `cost` (the total, US dollars), and its two parts `inputCost` and `outputCost`. The store keeps them as whole nano-dollars; sums are `costNanos`, `inputCostNanos`, `outputCostNanos`.

* A cost that comes with the span is kept (see the mapping table). When only parts come, `cost` is their sum.
* With `--prices <file>`, a model call that comes with tokens and no cost gets a cost computed from the file: `inputCost`, `outputCost`, `cost`, and `costComputed: true`.
* A model that is not in the file gets no cost. The server never guesses a price. A span with no tokens gets no cost either.
* The cost is computed once, when the span is written, and stored with it. A new price file (the server reads it when it starts) changes the cost of new spans only: old spans keep the cost of their day.

The file: US dollars per one million tokens, as the price pages of the providers give them, by the exact `model` of the spans (the response model, when the span has one). At most 6 decimals. `cacheRead` and `cacheWrite` are the prices of input tokens read from and written to the provider's cache; left out, each is the `input` price. These numbers are made up:

```json theme={null}
{"perMillionTokens": {
  "made-up-large": {"input": 3, "output": 15, "cacheRead": 0.3, "cacheWrite": 3.75},
  "made-up-small": {"input": 0.25, "output": 1.25}
}}
```

`inputCost` = (input tokens - cache read - cache write) x `input` + cache read x `cacheRead` + cache write x `cacheWrite`. `outputCost` = output tokens x `output` (reasoning tokens are output tokens). The math is in whole numbers (pico-dollars per token); each part is rounded to whole nano-dollars, half up. Example with `made-up-large`: 1,000 input tokens of which 600 from the cache and 100 written to it, 200 output tokens: `inputCost` = (300 x 3 + 600 x 0.3 + 100 x 3.75) / 1,000,000 = 0.001455 dollars, `outputCost` = 200 x 15 / 1,000,000 = 0.003, `cost` = 0.004455.

No price list comes with Magpie: prices change, and they differ by contract and by region. Take them from the price page of each provider (for example [https://platform.claude.com/docs/en/about-claude/pricing](https://platform.claude.com/docs/en/about-claude/pricing), [https://developers.openai.com/api/docs/pricing](https://developers.openai.com/api/docs/pricing), [https://aistudio.google.com/docs/pricing](https://aistudio.google.com/docs/pricing)), under the model names your spans have. One price per model: a model with price steps (a higher price above a prompt size, batch prices, a 1-hour cache) needs the price you pay most, or a cost sent with the span.

## Masking

With `--mask <file>` the server replaces private data in every span and every score BEFORE it is stored. The write log, the index, the trace summaries, the previews and the exports then hold the masked text only: no search finds the original and no read returns it. It is off by default: without the flag nothing is masked and a write does no extra work.

```json theme={null}
{
  "rules": [
    {"builtin": "email"},
    {"builtin": "secret"},
    {"builtin": "credit_card", "replace": "<card>"},
    {"name": "order", "pattern": "ORD-[0-9]{8}"}
  ],
  "dropAttributes": ["customer.address"]
}
```

* **A rule** is `builtin` or `pattern` (a regex in the syntax of the Rust `regex` crate: no look-around, no back-references). `name` is its name in the counts; a rule with a pattern needs one, a built-in rule has the name of the built-in by default. No two rules have one name. `replace` is the text that goes in the place of each match, as it is (no `$1`), and it must not be empty. The default is the name in upper case in square brackets: `[EMAIL]`, `[ORDER]`.
* **`dropAttributes`** removes attribute values whole, whatever they hold. A dot is a path step, as in an attribute filter: `customer.address` takes the flat key `customer.address`, the nested `{"customer": {"address": ..}}`, and every key below it (`customer.address.street`).
* **A wrong policy stops the start**: a rule with no such built-in, a regex that does not compile, a pattern that matches the empty text, an unknown field. The server (also with `--tenants-dir`), `import` and `mask-test` then end with an error that names the rule. A write never fails because of the policy.
* **One policy for all tenants** in this version. A policy per tenant is planned, not built.
* **New writes only.** The server reads the file when it starts. A new policy does not change what is stored: for old data use the deletes (`POST /v1/traces/delete`, `POST /v1/purge`).

**The built-in rules.** None is on until the policy names it. They are narrow on purpose: a rule that masks too much makes traces useless. They do NOT find names of people: a regex cannot do that.

| `builtin` | what it finds | what it does not find |
| - | - | - |
| `email` | ASCII addresses: `bob.smith+tag@mail.example.co.uk` | An address with letters outside ASCII before the `@`, or with no dot after it (`bob@localhost`). A file name like `logo@2x.png` has the shape of an address and IS masked. |
| `credit_card` | 13 to 19 digits that start with 2 to 6 and pass the Luhn check: in one run, as four groups of four, or as 4-6-4 or 4-6-5, with spaces or with dashes | Other groupings, a mix of spaces and dashes, a number that starts with 0, 1, 7, 8 or 9, a number that is a part of a longer number, of an id (a UUID) or of a fraction. A number that only looks like a card and passes the check by chance (1 in 10 does) IS masked. |
| `ipv4` | four numbers of 0 to 255 with dots: `10.0.0.1` | IPv6. A version number of four parts (`1.2.3.4`) has the shape of an address and IS masked; `1.2.3.4567` and `1.2.3.4.5` are not. |
| `phone` | `+` and 8 to 15 digits, with at most two of space, dot, dash and brackets between two digits: `+1 (415) 555-2671` | A number with no `+`. This rule is narrow: national formats differ too much for one regex. Add a pattern for the formats of your users. |
| `secret` | Keys that say what they are: `sk-...` (OpenAI and others; 20 characters or more with a digit), Stripe `sk_live_` and `rk_live_`, AWS access key ids (`AKIA`, `ASIA`), GitHub tokens (`ghp_`, `gho_`, `ghu_`, `ghs_`, `ghr_`, `github_pat_`), Slack tokens (`xox?-`), Google API keys (`AIza`), JWTs, `Bearer <token>` (16 characters or more with a digit; the word `Bearer` goes too), PEM private key blocks | A secret with no such shape: a password, an AWS secret access key, a key of a provider that is not in the list. Add a pattern for those. |

**What is masked:** `input`, `output`, `error`, every string value in `attributes` and in `events` (at every depth, also in lists), and the `label` and the `comment` of a score. With OTLP: the prompt and the answer, tool arguments and results, the exception message, and every attribute value that is text.

**What is NOT masked:** the ids (trace, span, parent span, session, user), the span `name`, `kind`, `model`, `service`, `environment`, `tags`, attribute keys, numbers and booleans, and of a score its `name`, `source`, `authorId` and `evalId`. Do not put private data there: a user id should be an id, not an email address. (To remove a whole attribute, name it in `dropAttributes`.)

**How overlaps are settled.** All rules look at the text as it was sent. They do not look at text another rule has changed. Where two matches overlap: the one that starts first wins; then the longer one; then the rule that is first in the file.

**Limits.**

* Text that holds JSON is masked as text: it is not parsed. A value that is written with a JSON escape inside it is not found: `bob\u0040example.com` stays. An escape before a value (`\n` before an address) is fine, and stays as it is.
* A match is replaced whole. Two equal values give the same replacement, and two different values too: the masked text does not say which values were equal.
* Queries are not masked: a search for an address, or a delete by a filter with one, is in the server's memory (and a delete by filter is in the write log until its commit, a moment later).
* What a rule does not match is stored. Test your policy with real shapes of your data before you rely on it.
* The cost in time: not measured yet.

**Counts.** `GET /v1/mask` (read right) says how many matches each rule replaced since the store opened, and how many attribute values were dropped. It never holds a value. Nothing that was masked is logged or kept.

```json theme={null}
{"droppedAttributes": 1, "enabled": true, "rules": [{"name": "email", "masked": 4}, {"name": "secret", "masked": 3}]}
```

With tenants the counts are of the tenant's store, and a store that was closed (idle, or `--max-open-tenants`) starts at 0 again. A server with no policy answers `{"droppedAttributes": 0, "enabled": false, "rules": []}`.

**Try a policy first.** `mask-test` reads a text from the standard input, prints it masked, and prints the counts on stderr. It stores nothing.

```sh theme={null}
printf 'Card 4111 1111 1111 1111, mail bob@example.com\n' | magpie-server mask-test --mask mask.json
# stdout: Card <card>, mail [EMAIL]
# stderr: {"rules":[{"name":"email","masked":1},{"name":"secret","masked":0},{"name":"credit_card","masked":1},{"name":"order","masked":0}],"droppedAttributes":0}
```

Tested in `tests/mask.rs` (the real server binary: OTLP in, then every search and every read; `import --mask`; `mask-test`; wrong policies) and in the core (`crates/core/src/mask.rs`, `crates/core/tests/mask.rs`: no file of the store folder holds a masked value, also before the first commit and after a stop before the commit).


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