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

# Install the Node SDK

> agentrail-node adds your Node servers to a journey: HTTP and fetch traces, verified identity, milestones, logs and MCP calls.

`agentrail-node` adds your servers to a journey. It records the requests your server answers and the HTTP and `fetch` calls it makes while answering them, the identity your application verified, the milestones you name, your structured logs and your MCP tool calls. It needs Node 22 or later.

The [Go SDK](https://agentrail.co/docs/guides/journeys-go.md) and the [Python SDK](https://agentrail.co/docs/guides/journeys-python.md) have the same features, and can also add an approximate location to each request and report [workflow attempts](https://agentrail.co/docs/guides/plugin-performance.md).

## Create a server source

An Admin creates the source once. One source can serve every service that shares it.

**1. Open Set up**

Open **Journeys**, select **Set up** and choose **Your servers**. If you are in **Settings · Journeys**, select **Add source**, then **Your servers**.

**2. Name the source**

Enter a **Name**, such as "API servers", and select **Create source**.

**3. Save the secret and hash key**

Agentrail shows the **Secret** and the **Hash key** once, with the **Collector endpoint** and the install commands. Copy them before you select **I have saved them**. If you lose one, revoke the source and create another.

Keep both in your platform's secrets, never in your code or a page:

* `AGENTRAIL_SECRET` lets your servers send this source's events.
* `AGENTRAIL_HASH_KEY` is your workspace's key. Identities are hashed with it before anything leaves your server. Give the edge and every server the same one.

The examples below write the collector's address as `<collector>`. The **Collector endpoint** Agentrail shows has yours in it.

## Install it

```sh theme={null}
npm install agentrail-node
```

Create `instrumentation.ts`, and load it before your application's HTTP modules:

```ts theme={null}
// instrumentation.ts
import { init } from 'agentrail-node';

const secret = process.env.AGENTRAIL_SECRET;
const hashKey = process.env.AGENTRAIL_HASH_KEY;
if (!secret || !hashKey) throw new Error('Agentrail is not configured');

export const agentrail = await init({
  collector: { endpoint: 'https://<collector>/ingest/otlp', secret },
  hashKey,
  serviceName: 'orders-api',
  outboundOrigins: ['https://inventory.example.com'],
  onError(error) {
    console.error(error);
  },
});
```

```sh theme={null}
node --import ./instrumentation.js app.js
```

* **`serviceName`** names this service on each step.
* **`outboundOrigins`** lists the exact origins allowed to receive your trace context. The default is none.
* **`onError`** is told of anything that could not be captured or delivered. The default is the console. None of it replaces your application's response.

If your application already has an OpenTelemetry provider, `init` refuses to start. Use `createProcessors` instead, as [An existing OpenTelemetry setup](https://agentrail.co/docs/guides/journeys-node-reference.md#an-existing-opentelemetry-setup) describes.

## Join the edge to your servers

With [`agentrail-edge`](https://agentrail.co/docs/guides/journeys-edge) in front of your site, each request reaches your server with a signed trace, so the edge's step and your server's step join as a proof. Give both the same workspace hash key. Your server continues that trace only if the signature is valid, and only for 60 seconds, so keep your clocks synchronized. Direct calls start a trace of their own.

If your edge rewrites a request's path or query, do it in `prepareOriginRequest` on the edge's adapter, so the rewrite happens before signing.

## Name who is calling

After your application has authenticated a request, tell Agentrail who it was:

```ts theme={null}
agentrail.identify({
  kind: 'agent_registration',
  id: authenticatedAgent.id,
  actingUserId: authenticatedAgent.userId,
});
```

The kind is `user`, `agent_registration`, `agent_instance`, `oauth_client` or `api_key`. Ids are hashed before they leave your server. Nothing a caller merely says about itself becomes a verified identity.

## Mark a milestone

A milestone is a step you name, such as a confirmed order:

```ts theme={null}
const result = await agentrail.milestone(
  'checkout.confirm',
  { surface: 'custom', kind: 'checkout.confirm' },
  async () => confirmOrder(),
);
```

Use a stable operation name, without arguments or ids. The result of your callback is returned as it was, and an error it throws is thrown again.

## Send your logs

The Pino hook leaves your logger's own output unchanged:

```ts theme={null}
import pinoLogger from 'pino';
import { pino } from 'agentrail-node/pino';

const logger = pinoLogger({ hooks: pino(agentrail) });
```

By default, a log sends its severity, error type, event name, a stable id and the span it belongs to. Message text is sent only for the fields you list in `logs.includeFields`, so never list anything that holds credentials or customer content. A log is never proof that two steps belong together.

## Record MCP calls

Wrap your MCP server's callbacks to record each call as a step:

```ts theme={null}
import { mcp } from 'agentrail-node/mcp';

const capture = mcp({ client: agentrail });
server.registerTool('checkout', {}, capture.tool('checkout', checkout));
```

`capture.resource` and `capture.prompt` wrap resources and prompts the same way. This targets `@modelcontextprotocol/server` 2.3.1. Arguments, results, prompt text and resource addresses are not recorded.

## Shut down cleanly

Call `await agentrail.shutdown()` when your application stops, so what is queued is sent. Records wait in a bounded queue in memory, with nothing kept on disk. `agentrail.diagnostics()` reports what was accepted, sent, dropped and still waiting.

Every option, the error codes and how to use an existing OpenTelemetry setup are in the [Node SDK reference](https://agentrail.co/docs/guides/journeys-node-reference.md).

Next, [leave out your own servers](https://agentrail.co/docs/guides/journeys-own-servers.md), and see [what Agentrail records](https://agentrail.co/docs/guides/journeys-data.md#your-servers).


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