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

# Send traces with OpenTelemetry

> Send traces to magpie-server from any app, SDK or Collector that speaks OTLP, and see how a span is stored.

`magpie-server` takes traces over OTLP, the protocol of OpenTelemetry. So any app, in any language, with any framework that sends OpenTelemetry spans can send them to Magpie. You do not need a Magpie package in your app.

Start a server first ([quickstart](https://docs.magpiedb.com/quickstart.md)).

## The endpoints

| protocol | address | content |
| - | - | - |
| OTLP/HTTP | `http://127.0.0.1:4318/v1/traces` | protobuf (`application/x-protobuf`) or JSON (`application/json`), plain or gzip |
| OTLP/gRPC | `127.0.0.1:4317` | protobuf, plain or gzip |

These are the standard OTLP ports. Change them with `--http-addr` and `--grpc-addr`.

## Point your app at Magpie

Most OpenTelemetry SDKs read these environment variables. No code change is needed:

```sh theme={null}
# OTLP/HTTP with protobuf (the default of most SDKs) or JSON
export OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
# or OTLP/gRPC
export OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4317 OTEL_EXPORTER_OTLP_PROTOCOL=grpc
```

With API keys and TLS on the server ([operations](https://docs.magpiedb.com/operations/overview.md)), add the key and the CA that signed the server's certificate (`%20` is a space):

```sh theme={null}
export OTEL_EXPORTER_OTLP_ENDPOINT=https://magpie-host:4318
export OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer%20mgp_..."
export OTEL_EXPORTER_OTLP_CERTIFICATE=ca.pem
```

The OpenTelemetry JS exporters (protobuf, JSON and gRPC) are tested this way, with a key and TLS (`crates/server/e2e/` in the repo).

## An example: an app in Python

This app makes one agent run by hand: an agent span with a model call inside. A real app gets such spans from its framework or from an instrumentation library.

```sh theme={null}
uv venv --quiet .otel && uv pip install --quiet --python .otel/bin/python opentelemetry-sdk opentelemetry-exporter-otlp-proto-http opentelemetry-exporter-otlp-proto-grpc
cat > agent.py <<'EOF'
import json, sys
from opentelemetry import trace
from opentelemetry.sdk.resources import Resource
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

if sys.argv[1:] == ["grpc"]:
    from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
else:
    from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

provider = TracerProvider(resource=Resource.create({"service.name": "support-bot", "deployment.environment.name": "prod"}))
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter()))  # reads OTEL_EXPORTER_OTLP_ENDPOINT
tracer = provider.get_tracer("my-agent")

with tracer.start_as_current_span("invoke_agent support") as agent:
    agent.set_attribute("gen_ai.operation.name", "invoke_agent")
    agent.set_attribute("user.id", "user-7")
    agent.set_attribute("session.id", "chat-42")
    with tracer.start_as_current_span("chat gpt-4o") as llm:
        llm.set_attribute("gen_ai.operation.name", "chat")
        llm.set_attribute("gen_ai.request.model", "gpt-4o")
        llm.set_attribute("gen_ai.usage.input_tokens", 120)
        llm.set_attribute("gen_ai.usage.output_tokens", 40)
        llm.set_attribute("gen_ai.input.messages", json.dumps(
            [{"role": "user", "parts": [{"type": "text", "content": "Where is my parcel?"}]}]))
        llm.set_attribute("gen_ai.output.messages", json.dumps(
            [{"role": "assistant", "parts": [{"type": "text", "content": "It arrives on Monday."}]}]))

provider.shutdown()  # sends the spans that wait in the batch
EOF
OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 .otel/bin/python agent.py        # OTLP/HTTP, protobuf
OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4317 .otel/bin/python agent.py grpc   # OTLP/gRPC
sleep 2   # new spans are searchable after the next commit
```

Two runs went in: one over HTTP, one over gRPC. Find them by a word of the prompt (`jq` only makes the answer short):

```sh theme={null}
curl -s localhost:4318/v1/traces/find -d '{"anySpan": [{"text": {"words": "parcel"}}], "previewChars": 60}' \
  | jq -c '.count, (.traces[] | {name, userId, sessionId, spanCount, inputTokens, outputTokens, inputPreview, outputPreview})'
```

```json theme={null}
2
{"name":"invoke_agent support","userId":"user-7","sessionId":"chat-42","spanCount":2,"inputTokens":120,"outputTokens":40,"inputPreview":"user: Where is my parcel?","outputPreview":"assistant: It arrives on Monday."}
{"name":"invoke_agent support","userId":"user-7","sessionId":"chat-42","spanCount":2,"inputTokens":120,"outputTokens":40,"inputPreview":"user: Where is my parcel?","outputPreview":"assistant: It arrives on Monday."}
```

Call `provider.shutdown()` (or `force_flush()`) before a short script ends. Else the last batch is not sent.

## From an agent framework

Each framework below sends OpenTelemetry spans; Magpie reads their GenAI attribute names ([Mapping](https://docs.magpiedb.com/reference/mapping-cost-masking.md#mapping-from-an-opentelemetry-span-to-a-magpie-span)). The setups are from each project's own docs (links). Two were run against Magpie on 2026-12-03 with the framework's own fake model (no API key, no call to a provider), in a scratch folder: the Vercel AI SDK and LangChain. The OpenAI Agents SDK and Mastra setups were **not tested**. With API keys, add the header to each exporter (`authorization: Bearer mgp_...`), or set `OTEL_EXPORTER_OTLP_HEADERS="authorization=Bearer%20mgp_..."`.

### OpenAI Agents SDK (Python)

Through the OpenInference instrumentation ([its README](https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-openai-agents); the SDK's own tracing page lists such processors: [openai.github.io/openai-agents-python/tracing](https://openai.github.io/openai-agents-python/tracing/)). It writes OpenInference attributes (`openinference.span.kind`, `input.value`, `output.value`, `llm.model_name`). Not tested.

```python theme={null}
# pip install openai-agents openinference-instrumentation-openai-agents opentelemetry-sdk opentelemetry-exporter-otlp
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from openinference.instrumentation.openai_agents import OpenAIAgentsInstrumentor

provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter("http://127.0.0.1:4318/v1/traces")))
OpenAIAgentsInstrumentor().instrument(tracer_provider=provider)
# ... then run your agents as usual
```

### Vercel AI SDK

The setup is from [ai-sdk.dev/docs/ai-sdk-core/telemetry](https://ai-sdk.dev/docs/ai-sdk-core/telemetry). The current SDK sends its spans to the global OpenTelemetry tracer when you call `registerTelemetry(new OpenTelemetry())` (`@ai-sdk/otel`); it writes the GenAI names (`gen_ai.input.messages`, `gen_ai.usage.input_tokens`, ...). AI SDK 5 used `experimental_telemetry: { isEnabled: true }` on each call instead ([v5 docs](https://ai-sdk.dev/v5/docs/ai-sdk-core/telemetry)) and the `ai.*` names, which Magpie reads too. The AI SDK docs show no exporter; the Node SDK below is the standard OpenTelemetry one (in Next.js: `@vercel/otel` in `instrumentation.ts`). Tested with this code as it is and the SDK's `MockLanguageModelV4` (`ai` 7.0.188, `@ai-sdk/otel` 1.0.188, `@opentelemetry/sdk-node` 0.302.0): a `generateText` run is found by a word of its prompt. It has three spans: `invoke_agent` (kind `agent_run`), `chat` (kind `model_generation`, with the model, the tokens, counted once, and the prompt and answer as text) and `step 1`. Call `await sdk.shutdown()` before a short script ends, or its spans are not sent.

```js theme={null}
// npm install ai @ai-sdk/otel @opentelemetry/sdk-node @opentelemetry/exporter-trace-otlp-proto
// OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 node app.mjs
import { NodeSDK } from '@opentelemetry/sdk-node'
import { OTLPTraceExporter } from '@opentelemetry/exporter-trace-otlp-proto'
import { registerTelemetry } from 'ai'
import { OpenTelemetry } from '@ai-sdk/otel'

new NodeSDK({ traceExporter: new OTLPTraceExporter() }).start()   // reads OTEL_EXPORTER_OTLP_ENDPOINT
registerTelemetry(new OpenTelemetry())
// ... then generateText / streamText as usual
```

### LangChain and LangGraph (Python)

Through LangSmith's OpenTelemetry mode ([docs.langchain.com/langsmith/trace-with-opentelemetry](https://docs.langchain.com/langsmith/trace-with-opentelemetry), section "Configure alternate OTLP endpoints"). `LANGSMITH_OTEL_ONLY=true` sends to your endpoint only, not to LangSmith. Another way is the OpenInference instrumentation `openinference-instrumentation-langchain` ([README](https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-langchain)), set up like the OpenAI Agents one above. Tested with the LangSmith way, this code as it is and LangChain's `FakeListChatModel` in a prompt-and-model chain (`langsmith` 0.14.17, `langchain` 1.4.10, `langchain-core` 1.7.7): the run is found by a word of its prompt, with the chain's input and output as text. Limits seen: the prompt-template step is stored with the kind `model_generation` (no tokens), the input of the model call is LangChain's serialized message list as `key: value` lines, and the fake model has no model name (a real one sends `ls_model_name`; not checked). Call `provider.force_flush()` before a short script ends.

```python theme={null}
# pip install "langsmith[otel]" langchain
# LANGSMITH_OTEL_ENABLED=true LANGSMITH_TRACING=true LANGSMITH_OTEL_ONLY=true python app.py
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter

provider = TracerProvider()
provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint="http://127.0.0.1:4318/v1/traces")))
trace.set_tracer_provider(provider)
# ... then run your chains and graphs as usual
```

### Mastra

Through `@mastra/otel-exporter` ([mastra.ai/docs/observability/tracing/exporters/otel](https://mastra.ai/docs/observability/tracing/exporters/otel), "Custom or generic OTEL endpoints"). It follows the GenAI conventions (semconv 1.41: `gen_ai.input.messages`, `gen_ai.output.messages`, `gen_ai.usage.*`). Not tested.

```ts theme={null}
// npm install @mastra/observability @mastra/otel-exporter @opentelemetry/exporter-trace-otlp-proto
import { Mastra } from '@mastra/core'
import { Observability } from '@mastra/observability'
import { OtelExporter } from '@mastra/otel-exporter'

export const mastra = new Mastra({
  // ... your agents
  observability: new Observability({
    configs: { default: { serviceName: 'my-agent', exporters: [
      new OtelExporter({ provider: { custom: { endpoint: 'http://127.0.0.1:4318/v1/traces', protocol: 'http/protobuf' } } }),
    ] } },
  }),
})
```

## From an OpenTelemetry Collector

Add Magpie as one more exporter. Not tested here (no Collector binary was run); it speaks the same protocol as the SDKs above.

```yaml theme={null}
exporters:
  otlphttp/magpie:
    endpoint: https://magpie-host:4318    # the exporter adds /v1/traces
    headers: { authorization: "Bearer ${env:MAGPIE_KEY}" }
    tls: { ca_file: ca.pem }              # not needed for a certificate of a public CA
service:
  pipelines:
    traces:
      exporters: [otlphttp/magpie]
```

For gRPC, use the exporter `otlp` with `endpoint: magpie-host:4317`.

## What Magpie keeps

Each OpenTelemetry span becomes one Magpie span. Magpie reads the [GenAI semantic conventions](https://github.com/open-telemetry/semantic-conventions-genai) (release v0.1.0), older GenAI names, and some names of OpenInference and the Vercel AI SDK. The first name it finds wins.

| Magpie field | comes from (the main names) |
| - | - |
| `traceId`, `spanId`, `parentSpanId` | the OTLP ids, as lower-case hex |
| `startedAt`, `endedAt` | the OTLP times, in ms. A span with no end time is still running. |
| `name` | the span name |
| `kind` | `gen_ai.operation.name`: `chat` and other model calls are `model_generation`, `execute_tool` is `tool_call`, `invoke_agent` is `agent_run`. Other names stay as they are. Without it: OpenInference, Vercel, then the OTel span kind. |
| `model` | `gen_ai.response.model`, else `gen_ai.request.model` |
| `inputTokens`, `outputTokens` | `gen_ai.usage.input_tokens`, `gen_ai.usage.output_tokens`, on model calls and embeddings only |
| `input`, `output` | `gen_ai.input.messages` (with `gen_ai.system_instructions`) and `gen_ai.output.messages`; else tool arguments and results, `gen_ai.prompt`, `gen_ai.completion`, OpenInference `input.value` and `output.value`, and span events |
| `userId`, `sessionId` | `user.id`, `session.id` (also `gen_ai.conversation.id`), on the span or on the resource |
| `service`, `environment` | resource `service.name`, `deployment.environment.name` |
| `status`, `error` | status ERROR with its message; else the first exception event |
| `attributes` | every other span attribute; the other resource attributes under `resource` |
| `events` | every span event |

The full table (cached and reasoning tokens, time to first token, cost, every name that is read): [the server reference, "Mapping"](https://docs.magpiedb.com/reference/mapping-cost-masking.md#mapping-from-an-opentelemetry-span-to-a-magpie-span).

Some rules to know:

* **Text is made readable.** A message list becomes one `role: text` line per message (you saw `user: Where is my parcel?` above). Other JSON objects become `key: value` lines.
* **Tokens come from model calls only.** An agent span reports the sum of the model calls under it. Magpie does not count those tokens twice. The agent's own numbers stay in its attributes.
* **Cost.** The GenAI conventions have no cost attribute. Magpie reads `gen_ai.usage.cost` and OpenInference `llm.cost.*`. Or give the server a price table (`--prices`), and it computes the cost of each model call: [the server reference, "Cost"](https://docs.magpiedb.com/reference/mapping-cost-masking.md#cost).
* **A retry does not make a copy.** Spans are written with `upsert`: a span with the same trace id and span id replaces the one before.
* **A bad span is refused alone.** A span with bad ids, no start time, an end before its start, or (in OTLP/JSON) a value that is wrong for its field is refused. The answer is `200` with `partialSuccess`, and the other spans are stored. The message names the span by its number and the field. It does not give the value.
* **A text cut inside an emoji is kept.** The half character is stored as U+FFFD (`�`), as the protobuf exporters send it, and `partialSuccess` says how many there were. `"NaN"` and `"Infinity"` in a JSON `doubleValue` are kept as those values. The rules per value: [the server reference, "Send traces to it"](https://docs.magpiedb.com/reference/server.md#send-traces-to-it).
* **Every stored span has `magpie.mapping: 2`** in its attributes: the version of the mapping. The GenAI conventions are still in development. When they change, the mapping gets a new version. Spans that are stored keep the old one.

**Not stored:** span links, `traceState`, flags, dropped counts, scope attributes, schema URLs. `tags` are never set from OTLP: OpenTelemetry has no standard name for them.

## What the server answers

| answer | meaning | does the SDK send it again? |
| - | - | - |
| `200` (gRPC `OK`) | stored; with `partialSuccess`, some spans were refused, or some characters were replaced (`rejectedSpans` `0`) | no |
| `400` | the body cannot be read | no |
| `401`, `403` | no key, a wrong key, or no `write` right | no |
| `413` | the request is too large (body, spans, lists) | no |
| `415` | the content type or encoding is not known | no |
| `429` (gRPC `UNAVAILABLE`) | too many writes at once | yes |
| `503` (gRPC `UNAVAILABLE`) | the store cannot write now (for example, the disk is full) | yes |

The largest request is 64 MiB by default (`--max-body-bytes 67108864`, the default that the OTLP spec recommends). That takes an SDK's full batch with the default settings: 512 spans of 50 KB each, about 26 MB, over HTTP and gRPC (`crates/server/tests/sdk_batch.rs` in the repo). For larger batches, raise `--max-body-bytes`, or send fewer spans per export (`OTEL_BSP_MAX_EXPORT_BATCH_SIZE`). A `413` is not sent again: the batch is lost.

All errors and their limits: [operations, "What an error means"](https://docs.magpiedb.com/operations/errors-memory.md#what-an-error-means).

## Import old traces

Traces from before, in files (OTLP/JSON of the Collector's `file` exporter, LangSmith runs, or a Magpie export), go in with `magpie-server import`: [operations, "Import"](https://docs.magpiedb.com/operations/backup-import.md#import).


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