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

# Set up Magpie with a coding agent

> Steps that a coding agent follows in your project: build magpie-server, start it, add the OpenTelemetry setup for your app, send a test trace and check that it arrived.

Copy this prompt into Claude Code, Codex, Cursor or another coding agent. The agent asks you before it installs a tool or changes a file.

Read [https://docs.magpiedb.com/agent-setup.md](https://docs.magpiedb.com/agent-setup.md) and follow it to add Magpie tracing to this project.

You are a coding agent. The user asked you to add Magpie tracing to this project. Magpie is a trace store for AI agents. `magpie-server` takes OpenTelemetry traces (OTLP) and answers JSON queries over HTTP. It also serves a read-only web viewer. Do the steps below in order.

## Rules

* Ask the user before you install anything (Rust, a package, a tool) and before you create or change a file. Show the command or the change first, then wait for a yes.
* Ask the user before you run their app. A run can call a paid model.
* Do not print, copy or store a secret: API keys, tokens, passwords, the values in `.env` files, Magpie keys (`mgp_...`). Do not write a secret into a file or a command line.
* If a step fails, stop. Tell the user the step, the command and the error text. Do not try a way that this page does not show.
* Use only the commands, flags, routes and JSON shapes on this page and on [docs.magpiedb.com](https://docs.magpiedb.com/index.md). If a page does not show a flag or a field, it does not exist.
* Magpie is not on crates.io, npm or PyPI yet, and there is no release to download yet. Do not run `cargo add magpiedb`, `npm install magpiedb` or `pip install magpiedb`. Build the server from source (step 3).

## The places

| what | default |
| - | - |
| the Magpie source | `~/src/magpie` |
| the store: one folder that holds all trace data | `~/magpie-traces` |
| OTLP/HTTP and the query API | `http://127.0.0.1:4318` |
| OTLP/gRPC | `127.0.0.1:4317` |
| the viewer | `http://127.0.0.1:4318/` |

Ask the user if they want other folders. Your shell can lose variables between two commands, so the commands below use full paths.

## Step 1: Check the tools

```sh theme={null}
cargo --version
git --version
curl --version
```

Each command must print a version. Magpie needs stable Rust. If `cargo` is not found, stop and ask the user to install Rust from [rustup.rs](https://rustup.rs). Do not install it yourself.

## Step 2: Check if a Magpie server runs already

```sh theme={null}
curl -s localhost:4318/v1/storage
```

* An answer like `{"diskBytes":59692,"mode":"local","spans":0,"traces":0}`: a Magpie server runs on this machine. Tell the user, and go to step 5.
* No answer (`curl` exits with code 7): nothing listens on port 4318. Go to step 3.
* Any other answer, or `401`: another program or a server with API keys has the port. Stop and ask the user.

## Step 3: Get and build magpie-server

Ask the user first. This step puts the source in `~/src/magpie` and builds it. The first build takes some minutes. If `~/src/magpie` exists already, ask the user if you can use it as it is.

```sh theme={null}
git clone https://github.com/intojhanurag/magpie ~/src/magpie
cd ~/src/magpie && cargo build --release -p magpie-server
~/src/magpie/target/release/magpie-server --help | head -1
```

The last command must print:

```text theme={null}
usage: magpie-server --dir <store directory> | --tenants-dir <directory>
```

## Step 4: Start the server

The server must keep running after this step. The best way: ask the user to open a new terminal, run this command there, and keep that terminal open.

```sh theme={null}
~/src/magpie/target/release/magpie-server --dir ~/magpie-traces
```

If the user wants you to start it, run it in the background with its output in a log file:

```sh theme={null}
nohup ~/src/magpie/target/release/magpie-server --dir ~/magpie-traces > ~/magpie-traces.log 2>&1 &
```

The server makes the store folder. It prints one line that starts with `magpie-server: store` and ends with `Viewer: http://127.0.0.1:4318/`. Then check it:

```sh theme={null}
curl -s localhost:4318/healthz
```

The answer must be `ok`. By default the server listens on `127.0.0.1` only and has no API keys. Ctrl-C stops it; the data stays in the store folder.

If the server stops at once, read its line:

| the server prints | what it means | do this |
| - | - | - |
| `cannot listen on 127.0.0.1:4318 / 127.0.0.1:4317: Address already in use` | another program has a port | Stop and ask the user. The flags `--http-addr` and `--grpc-addr` pick other ports; then use those ports in every later step. |
| `cannot open store ...: another writer has this store open (one store = one writer process)` | a Magpie server runs on this store already | Use that server (go to step 5), or ask the user to stop it. |

## Step 5: Send a test trace

This test trace has two steps: a model call, and a tool call that failed. Send it with `curl` (no file is made):

```sh theme={null}
curl -s localhost:4318/v1/traces -H 'content-type: application/json' -d @- <<'EOF'
{"resourceSpans": [{
  "resource": {"attributes": [{"key": "service.name", "value": {"stringValue": "support-bot"}}]},
  "scopeSpans": [{"spans": [
    {"traceId": "5b8efff798038103d269b633813fc60c", "spanId": "eee19b7ec3c1b174",
     "name": "chat gpt-4o", "startTimeUnixNano": "1764500000000000000", "endTimeUnixNano": "1764500002000000000",
     "attributes": [
       {"key": "gen_ai.operation.name", "value": {"stringValue": "chat"}},
       {"key": "gen_ai.request.model", "value": {"stringValue": "gpt-4o"}},
       {"key": "gen_ai.usage.input_tokens", "value": {"intValue": "120"}},
       {"key": "gen_ai.usage.output_tokens", "value": {"intValue": "40"}},
       {"key": "user.id", "value": {"stringValue": "user-7"}},
       {"key": "gen_ai.prompt", "value": {"stringValue": "What is your refund policy?"}},
       {"key": "gen_ai.completion", "value": {"stringValue": "You can get a refund within 30 days."}}]},
    {"traceId": "5b8efff798038103d269b633813fc60c", "spanId": "eee19b7ec3c1b175", "parentSpanId": "eee19b7ec3c1b174",
     "name": "execute_tool lookup_order", "startTimeUnixNano": "1764500000500000000", "endTimeUnixNano": "1764500001000000000",
     "status": {"code": 2, "message": "order service timeout"},
     "attributes": [
       {"key": "gen_ai.operation.name", "value": {"stringValue": "execute_tool"}},
       {"key": "gen_ai.tool.call.arguments", "value": {"stringValue": "{\"order\": 4411}"}}]}
  ]}]}]}
EOF
sleep 2   # a span can be found after the next commit
```

The answer must be `{}`: every span is stored.

## Step 6: Check that the test trace arrived

Ask for traces with a tool call that failed:

```sh theme={null}
curl -s localhost:4318/v1/traces/find -d '{"anySpan": [{"kind": "tool_call", "hasError": true}], "limit": 10}'
```

On a new store the answer is:

```json theme={null}
{"count":1,"traces":[{"traceId":"5b8efff798038103d269b633813fc60c","rootSpanId":"eee19b7ec3c1b174","startedAt":1764500000000,"endedAt":1764500002000,"name":"chat gpt-4o","userId":"user-7","sessionId":null,"spanCount":2,"errorCount":1,"inputTokens":120,"outputTokens":40,"costNanos":0}],"nextCursor":null}
```

The trace `5b8efff798038103d269b633813fc60c` must be in the list. A store that had data before can show more traces. If `count` is `0`, wait 2 seconds and ask again. If it is still `0`, stop and report.

## Step 7: Find the language and the framework of the app

Read the files of the project; do not change them. Look at the dependencies in `package.json`, `pyproject.toml`, `requirements*.txt` and the lock files. Pick a row:

| the project has | setup in step 8 | tested with Magpie |
| - | - | - |
| `ai` (the Vercel AI SDK), JavaScript or TypeScript | [Vercel AI SDK](#vercel-ai-sdk) | yes, with `ai` 7.0.188 |
| `langchain` or `langgraph`, Python | [LangChain and LangGraph](#langchain-and-langgraph-python) | yes |
| `openai-agents`, Python | [OpenAI Agents SDK](#openai-agents-sdk-python) | **not tested** |
| `@mastra/core` | [Mastra](#mastra) | **not tested** |
| an OpenTelemetry SDK that is set up already, any language | [only environment variables](#an-app-with-an-opentelemetry-sdk) | yes for the JavaScript and Python exporters; other languages **not tested** |
| Python, none of the above | [spans by hand in Python](#python-with-no-framework) | yes |
| none of these | none | |

If no row fits, stop. Tell the user that this page has no setup for the app, and give them the link [docs.magpiedb.com/guides/opentelemetry](https://docs.magpiedb.com/guides/opentelemetry.md). If more than one row fits, ask the user which one to use.

Then tell the user: what you found, the setup you want to use, if it is tested, the packages it adds and the files it changes. Wait for a yes.

## Step 8: Add the setup

* Install the packages with the package manager that the project uses (`npm`, `pnpm`, `yarn`, `uv`, `poetry`, `pip`).
* Put the setup code where the app starts, before its first model call.
* A short script must send its spans before it ends: each setup below says how.
* The setups are from the docs of each project (links). Copy them as they are.

### An app with an OpenTelemetry SDK

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

Set them in the shell that runs the app, or where the project keeps its settings (ask the user which). Magpie reads the GenAI attribute names of OpenTelemetry (`gen_ai.*`), so the spans of the model calls must have them.

### Vercel AI SDK

From [ai-sdk.dev/docs/ai-sdk-core/telemetry](https://ai-sdk.dev/docs/ai-sdk-core/telemetry). Tested with `ai` 7.0.188, `@ai-sdk/otel` 1.0.188 and `@opentelemetry/sdk-node` 0.302.0. AI SDK 5 used `experimental_telemetry: { isEnabled: true }` on each call instead ([v5 docs](https://ai-sdk.dev/v5/docs/ai-sdk-core/telemetry)); that way was not tested here. In Next.js, the AI SDK docs use `@vercel/otel` in `instrumentation.ts`.

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

Call `await sdk.shutdown()` before a short script ends, or its spans are not sent. For this, keep the `NodeSDK` in a variable `sdk`.

### LangChain and LangGraph (Python)

Through the OpenTelemetry mode of LangSmith ([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. Tested with `langsmith` 0.14.17, `langchain` 1.4.10 and `langchain-core` 1.7.7.

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

Call `provider.force_flush()` before a short script ends.

### OpenAI Agents SDK (Python)

**Not tested.** Tell the user. Through the OpenInference instrumentation ([its README](https://github.com/Arize-ai/openinference/tree/main/python/instrumentation/openinference-instrumentation-openai-agents)).

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

### Mastra

**Not tested.** Tell the user. Through `@mastra/otel-exporter` ([mastra.ai/docs/observability/tracing/exporters/otel](https://mastra.ai/docs/observability/tracing/exporters/otel), "Custom or generic OTEL endpoints").

```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' } } }),
    ] } },
  }),
})
```

### Python with no framework

The app makes its own spans with the OpenTelemetry SDK: an agent span with a model call inside. This example is a whole script. Use it as the pattern: show the user where the spans go in their code before you change it.

```python theme={null}
# pip install opentelemetry-sdk opentelemetry-exporter-otlp-proto-http
# OTEL_EXPORTER_OTLP_ENDPOINT=http://127.0.0.1:4318 python agent.py
import json
from opentelemetry.sdk.resources import Resource
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(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
```

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

## Step 9: Run the app once and find its trace

Ask the user to run the app with one short task, or ask if you can run it. Then wait 2 seconds and list the newest traces:

```sh theme={null}
sleep 2
curl -s localhost:4318/v1/traces/find -d '{"limit": 5, "previewChars": 60}'
```

The newest trace comes first. Its `inputPreview` holds the first characters of the app's prompt. To find it by a word of the prompt, put the word in place of `parcel`:

```sh theme={null}
curl -s localhost:4318/v1/traces/find -d '{"anySpan": [{"text": {"words": "parcel"}}], "previewChars": 60}'
```

If the app's trace is not there:

* The process of the app did not get `OTEL_EXPORTER_OTLP_ENDPOINT`. Set it in the same shell or settings that start the app.
* A short script ended before its spans were sent. Add the shutdown or flush call of its setup.
* The protocol and the port do not agree: `http/protobuf` goes to port 4318, `grpc` to port 4317.

If it is still not there, stop and report what you see.

## Step 10: Tell the user

Give the user this report, with the real values:

```text theme={null}
Magpie setup
- Server: running, store ~/magpie-traces, viewer http://127.0.0.1:4318/
- Test trace: found
- App setup: <framework>, tested or not tested
- App trace: found or not found
- Files changed: <list>
- Packages added: <list>
```

Also tell the user:

* Open `http://127.0.0.1:4318/` in a browser to see the traces. Click a trace to see its steps; a failed step is red.

* To start the server again: `~/src/magpie/target/release/magpie-server --dir ~/magpie-traces`.

* The test trace of step 5 stays in the store. To delete it (ask first):

  ```sh theme={null}
  curl -s localhost:4318/v1/traces/delete -H 'content-type: application/json' -d '{"traceIds": ["5b8efff798038103d269b633813fc60c"]}'
  ```

* The store keeps the prompts and answers of the app as text. To replace private data before it is stored, see [masking](https://docs.magpiedb.com/operations/masking.md).

* Before other machines send to this server, read [operations](https://docs.magpiedb.com/operations/overview.md): API keys and TLS.

* To let an agent query these traces later (for example, to find why a run failed), install the Magpie skill: `npx skills add intojhanurag/magpie` ([AI tools](https://docs.magpiedb.com/ai-tools.md)).


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