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

# Go SDK reference

> Every option of agentrail-go, 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-go`. To install it, start with [Install the Go SDK](https://agentrail.co/docs/guides/journeys-go.md). It needs Go 1.26 or later.

## Options

`agentrail.New` and `agentrail.NewProcessors` take the same `Options`. An invalid option returns a `*ConfigurationError`. The SDK never reads environment variables itself, so check yours before calling them.

| Field | Required | What it does |
| - | - | - |
| `Collector.Endpoint` | Yes | The collector's address, ending in `/ingest/otlp`. |
| `Collector.Secret` | Yes | Your server source's secret. |
| `HashKey` | Yes | Your workspace's hash key. Identities and operation references 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 instance'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 | `func(*http.Request) bool`. A request it returns `true` for is not recorded. See [Leave out your own servers](https://agentrail.co/docs/guides/journeys-own-servers.md). |
| `IncomingLocation` | No | `func(*http.Request) (IPLocation, error)`. An approximate location for each request. See [Add an approximate location](https://agentrail.co/docs/guides/journeys-go.md#add-an-approximate-location). |
| `Logs.IncludeFields` | No | The log fields whose values may be sent, in order. None by default. |
| `Logs.ExcludeUncorrelated` | No | `true` leaves out logs written outside a recorded request. `false` by default. |
| `Queue` | No | Delivery limits. See [Delivery and shutdown](#delivery-and-shutdown). |
| `Propagator` | No | Your existing propagator, used for work outside recorded requests. |
| `OnError` | No | `func(context.Context, CaptureError)`. Told of every capture problem. Writes to standard error by default. |

## Recording requests

`New` creates its own tracer and logger providers. It registers nothing globally and patches nothing in your process: you choose what is recorded.

* **`Middleware`** records each request it wraps, with the `ServeMux` route pattern when there is one. It keeps streaming responses and the optional `ResponseWriter` interfaces working. It records only what runs inside it, so installed after your authentication middleware, authentication itself is not recorded. If you already trace incoming requests with `otelhttp`, replace that for this part of your application, or each request is recorded twice.
* **`Transport`** records outgoing calls. Pass your `*http.Transport`, or `nil` for a shared standard one, and install other client middleware outside it. OpenTelemetry instrumentation inside a request must use the same provider. To combine it with other libraries, use [an existing OpenTelemetry setup](#an-existing-opentelemetry-setup).

## 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, before it signs.

Only the exact origins in `OutboundOrigins` receive your trace context, and each redirect is checked again at its destination, whatever the `Host` header says. Baggage, trace state and Sentry trace headers never leave a recorded request. The SDK's own calls to the collector are not recorded. If this middleware also runs on a server that receives Agentrail's own traffic, leave those routes out with `IgnoreIncomingRequest`.

## Identity and milestones

`Identify` returns an error for an invalid kind or id. Called outside a recorded request, it reports `identity_outside_request` and records nothing. The first identity in a request stands: repeating it does nothing, and a different one is recorded as its own step and the first is kept. Goroutines that carry the request's context share its identity; other requests never do. A span that ended before `Identify` stays without one.

A milestone's name and kind are 1 to 256 characters. An invalid one reports `invalid_milestone`, and your code keeps running. `WithMilestone` returns your error unchanged and raises your panic again. A milestone outside a recorded request starts a step of its own.

## Logs

The `slog` handler passes every record to your own handler unchanged, with its groups, filtering and errors. Use the `…Context` logger calls, so a log is tied to the span it was written in.

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`, such as `"message"`. Grouped keys use dots, such as `order.status`. Only listed fields with plain values are sent, as a JSON object of at most 4,096 characters. Values from a `LogValuer` are never sent. Never list fields that hold credentials, identities or customer content.

## MCP

The `mcp` package wraps the handlers you register with the official MCP Go SDK: `Tool`, `ToolHandler`, `Resource` and `Prompt`. Each call is recorded with its registered name, method, the client's name and version, the protocol version and whether it failed. Your result, error and panic come back unchanged, and a tool result with `IsError` marks the step as failed. Pass a stable registered name, never the resource address a caller asked for.

Behind `Middleware`, each call nests under its request. Outside a request, it starts a step of its own. It is tested with MCP Go SDK 1.8.0 on protocol 2026-07-28 over stateless Streamable HTTP, 2025-11-25, and 2024-11-05 over SSE. What a client says about itself is never a verified identity.

## An existing OpenTelemetry setup

If your service builds its own tracer provider, add Agentrail's parts while you construct it:

```go theme={null}
processors, err := agentrail.NewProcessors(ctx, options)
if err != nil {
	return err
}
provider := sdktrace.NewTracerProvider(
	sdktrace.WithSampler(processors.Sampler(yourSampler)),
	sdktrace.WithSpanProcessor(yourProcessor),
	sdktrace.WithSpanProcessor(processors.SpanProcessor),
)
capture, err := processors.Bind(provider)
if err != nil {
	return err
}
// Add processors.LogProcessor to your LoggerProvider, and register
// processors.Propagator wherever you register a propagator.
```

* `Bind` is called once, for the provider you pass. Nothing finds or replaces a global provider.
* 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. A span processor alone cannot keep spans a sampler already dropped.
* Your other processors and exporters receive what they did before.
* `capture.Shutdown` never shuts down your provider.

Signatures are checked by `Middleware` and `Transport`, which see the method and path. A propagator alone cannot check them.

This release is tested with OpenTelemetry Go 1.47.0, its log exporter 0.23.0, and the MCP Go SDK 1.8.0.

## Delivery and shutdown

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

| `Queue` field | Default | What it limits |
| - | - | - |
| `MaxRecords` | 2048 | Records held per signal, the batch being sent included |
| `BatchSize` | 128 | Records sent in one call, at most 10,000 |
| `ScheduledDelay` | 1 s | Time between scheduled sends |
| `ExportTimeout` | 5 s | Time for one send, retries included |
| `FlushTimeout` | 10 s | Time `Flush` may take |
| `ShutdownTimeout` | 10 s | Time `Shutdown` may take |

Values must be positive, `BatchSize` cannot be more than `MaxRecords`, and the flush and shutdown times must cover `ExportTimeout`. 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.

* Stop accepting requests, wait for your handlers, then call `capture.Shutdown(ctx)`. It sends what is queued once, and is safe to call twice.
* `capture.Flush(ctx)` waits until every record accepted so far has been tried. It does not mean every record arrived.
* `capture.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` as a `CaptureError` 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. |
| `location_failed` | `IncomingLocation` returned an error or an invalid location. |
| `identity_outside_request` | `Identify` was called outside a recorded request. |
| `invalid_milestone` | A milestone's name, kind or surface was invalid. |
| `invalid_performance` | Workflow or plugin evidence was invalid and was left out. |

`OnError` runs synchronously, so return quickly. It receives a context that is never recorded: log with that context, so your log of the problem is not captured again. A panic in it is contained and written to standard error.

## What is sent

* Each request's method, route pattern, status, timing and user agent, the hash of its verified identity, and only Agentrail's own `h` markers from its address.
* Supporting operations carry only their place in the trace and their timing.
* The service name and instance, the SDK's name and version, and the hash key's id, never the key.

Your service names, route patterns, 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.