> ## Documentation Index
> Fetch the complete documentation index at: https://agentrail.co/docs/llms.txt
> Use this file to discover all available pages before exploring further.

# Node SDK reference

> Every option of agentrail-node, how to add it to an existing OpenTelemetry setup, how delivery works, and what each capture error means.

This page is the reference for `agentrail-node`. To install it, start with [Install the Node SDK](https://agentrail.co/docs/guides/journeys-node.md). It needs Node 22 or later.

## Options

`init` and `createProcessors` take the same options. Invalid options throw a `ConfigurationError`, so check your environment before calling them.

| Option | Required | What it does |
| - | - | - |
| `collector.endpoint` | Yes | The collector's address, ending in `/ingest/otlp`, over `http` or `https`, with no credentials, query or fragment. |
| `collector.secret` | Yes | Your server source's secret. |
| `hashKey` | Yes | Your workspace's hash key. Identities are hashed with it before they leave your server. |
| `serviceName` | Yes | A stable name for this service, such as `orders-api`. At most 4,096 characters. |
| `serviceInstanceId` | No | This process's id. A random id by default. |
| `outboundOrigins` | No | The exact origins, such as `https://inventory.example.com`, that receive your trace context. None by default. |
| `ignoreIncomingRequest` | No | `(request) => boolean`. A request it returns `true` for is not recorded. See [Leave out your own servers](https://agentrail.co/docs/guides/journeys-own-servers.md). |
| `logs.includeFields` | No | The log fields whose values may be sent, in order. None by default. |
| `logs.uncorrelated` | No | `false` leaves out logs written outside a recorded request. `true` by default. |
| `queue` | No | Delivery limits. See [Delivery and shutdown](#delivery-and-shutdown). |
| `onError` | No | `(error) => void`. Told of every capture problem. Writes to the console by default. |
| `propagator` | No | Only with `createProcessors`: your existing propagator. See [An existing OpenTelemetry setup](#an-existing-opentelemetry-setup). |

## How `init` starts

`init` installs one tracer provider, one logger provider, an async context manager and the instrumentation for `http` and `fetch`. Load it before your application's HTTP modules, with `node --import`, so the requests your application makes are recorded too.

Calling `init` again with the same options object returns the same client, and calling it with different options throws. It refuses to replace an OpenTelemetry provider, context manager or propagator that is already installed. If another library already set one up in your process, use [`createProcessors`](#an-existing-opentelemetry-setup) instead. After `shutdown`, the installation cannot be started again.

## Requests from the edge

With [`agentrail-edge`](https://agentrail.co/docs/guides/journeys-edge) in front of your service, the edge signs each request it forwards. A request with a valid signature continues the edge's trace, so your server's steps join the visit the edge recorded. A direct call, or one whose signature fails, starts a trace of its own, and a trace context the caller sent is kept only as a link.

The signature covers the method, the exact path and query, and the time it was made, and is accepted for 60 seconds. So:

* give the edge and every service the same workspace hash key;
* keep your servers' clocks synchronized;
* rewrite a path or query on the edge in `prepareOriginRequest`, before it signs.

Only the exact origins in `outboundOrigins` receive your trace context, and the address a call actually connects to decides, not a `Host` header. Baggage and trace state never leave a recorded request. The SDK's own calls to the collector are not recorded.

## Logs

The Pino hook works with Pino 9 and 10. It records in the caller's async context and leaves your logger's own output unchanged. Pass an existing hook as its second argument to keep it.

By default, a log sends its severity, error type, event name, a stable id and the span it was written in. Message text and other fields are sent only when you list them in `logs.includeFields`: `['msg']` for Pino, `['message']` for an OpenTelemetry log body. `agentrail.log()` picks the fields from its `fields` value.

Only listed top-level fields with text, number, boolean or null values are sent, in the order you listed them, as a JSON object of at most 4,096 characters. A long value is shortened to fit, and a field that cannot fit is left out. Never list fields that hold credentials, identities or customer content.

## MCP

The MCP adapter targets `@modelcontextprotocol/server` 2.3.1 and wraps the callbacks you register, without changing the server's own handlers or transports. Each call is recorded with its registered name, method, the client's name and version, the protocol version and whether it failed. A result with `isError` marks the step as failed and is returned unchanged.

Behind HTTP capture, each call nests under its request and shares its verified identity. Outside a request, it starts a step of its own. The protocol version 2026-07-28 and the official client's 2025-11-25 HTTP exchange are tested. A stateless server may not know the client's name after a 2025-11-25 initialize request. What a client says about itself is never a verified identity.

## An existing OpenTelemetry setup

If your process already sets up OpenTelemetry, create the processors **before** you construct your provider. A provider that is already running cannot recover the spans its sampler dropped.

```ts theme={null}
import { createProcessors } from 'agentrail-node';
import {
  TracerProvider,
  ParentBasedSampler,
  TraceIdRatioBasedSampler,
} from '@opentelemetry/sdk-trace';
import { LoggerProvider } from '@opentelemetry/sdk-logs';
import { HttpInstrumentation } from '@opentelemetry/instrumentation-http';
import { UndiciInstrumentation } from '@opentelemetry/instrumentation-undici';

const capture = createProcessors({ ...options, propagator: yourPropagator });

const provider = new TracerProvider({
  sampler: capture.sampler(
    new ParentBasedSampler({ root: new TraceIdRatioBasedSampler(0.1) }),
  ),
  spanProcessors: [yourProcessor, capture.spanProcessor],
});
const logProvider = new LoggerProvider({
  processors: [yourLogProcessor, capture.logProcessor],
});

// Register provider, logProvider, an async context manager and
// capture.propagator in your startup, then the two instrumentations:
const http = new HttpInstrumentation(capture.httpOptions);
const fetch = new UndiciInstrumentation(capture.undiciOptions);
http.setTracerProvider(provider);
fetch.setTracerProvider(provider);

export const agentrail = capture.client;
```

* Pass your existing propagator as `propagator`, and register the **returned** `capture.propagator`, not yours. It hands work outside recorded requests to yours, and stops a late injection from adding headers to a recorded call.
* Install only one HTTP and one Undici instrumentation, with these options. Keep the propagator and the HTTP options together: they are how a signature is checked against the method and path.
* `createProcessors` registers nothing globally, and never changes what your other processors and exporters receive.
* The sampler keeps the spans of a recorded request your sampler would drop, as record-only, without changing your sampled flag. An exporter that sends only sampled spans behaves as before. Without it, a dropped entry is reported as `entry_not_recording`.
* `agentrail.shutdown()` never shuts down your provider.

**Sentry.** Construct the single provider you own with this sampler wrapped around `SentrySampler`, keep `SentrySpanProcessor` and its context manager, pass `new SentryPropagator()` as `propagator`, and register the returned `capture.propagator` globally. Even at a 100% sample rate, Sentry drops HEAD and OPTIONS requests, which only the sampler wrapper keeps.

**Recording after your framework admits a request.** If your framework authenticates or parses a request before your handler runs, you can record from that point: use the HTTP options and propagator in the admitted part of your application, and turn off automatic incoming instrumentation, so each request has one entry. What happens before that point is not recorded.

This release is built on OpenTelemetry API 1.9.1, SDK 2.10.0, logs, exporters and HTTP instrumentation 0.221.0, and Undici instrumentation 0.31.0. Check that your own OpenTelemetry packages are compatible when you combine them.

## Delivery and shutdown

Records wait in a bounded queue in memory, one for spans and one for logs. Nothing is written to disk.

| `queue` option | Default | What it limits |
| - | - | - |
| `maxRecords` | 2048 | Records held per signal, the batch being sent included |
| `batchSize` | 128 | Records sent in one call |
| `scheduledDelayMs` | 1000 | Time between scheduled sends |
| `exportTimeoutMs` | 5000 | Time for one send, retries included |
| `flushTimeoutMs` | 10000 | Time `flush()` may take |
| `shutdownTimeoutMs` | 10000 | Time `shutdown()` may take |

Limits must be positive whole numbers, `batchSize` cannot be more than `maxRecords`, and the flush and shutdown times cannot be shorter than `exportTimeoutMs`. One batch is sent at a time. A send the collector can retry is retried within its time; a refusal, or a batch still failing, is dropped and reported.

* `await agentrail.flush()` waits until every record accepted so far has been tried. It does not mean every record arrived.
* `await agentrail.shutdown()` stops recording and sends what is queued, once. Call it after your server stops taking requests.
* `agentrail.diagnostics()` reports the records accepted, sent, dropped and still waiting, for spans and for logs.

## Capture errors

A capture problem never changes your application's response. Each goes to `onError` with a `code`, a `signal` (`traces`, `logs` or `context`) and a `count` of records, and never holds customer data.

| Code | What happened |
| - | - |
| `queue_full` | The queue was full, and records were dropped. |
| `export_failed` | The collector refused a batch, or its retries ran out. |
| `deadline` | A send, `flush` or `shutdown` ran out of time. |
| `closed` | A record arrived after `shutdown`. |
| `handoff_refused` | A signed request from the edge did not verify, so a new trace started. |
| `entry_not_recording` | A sampler dropped a request that should have been recorded. |
| `identity_outside_request` | `identify` was called outside a recorded request. |

Reporting runs outside capture, even when it goes through the same Pino or OpenTelemetry logger, so it can never fill the queue it reports on. If your `onError` throws, both errors go to the console and delivery carries on.

## What is sent

* Each request's method, route, status and user agent, the hash of its verified identity, and only Agentrail's own `h` markers from its address. An address longer than 4,096 characters is left out, and the step is kept.
* Supporting operations carry only their place in the trace and their timing: their names are replaced, and exception details and status messages are dropped.
* The service name and instance, the SDK's name and version, and the hash key's id, never the key.

Your service names, routes, milestone names, user agents and the log fields you list are yours to choose, so keep them free of personal data. For every source, see [What Agentrail records](https://agentrail.co/docs/guides/journeys-data.md).


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