> ## 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 Go SDK

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

`agentrail-go` adds your Go servers to a journey. It records the requests your server answers and the calls it makes while answering them, the identity your application verified, the milestones you name, your `slog` logs and your MCP tool calls. It needs Go 1.26 or later.

The same features are in the [Python SDK](https://agentrail.co/docs/guides/journeys-python.md). The [Node SDK](https://agentrail.co/docs/guides/journeys-node.md) has them too, except the approximate location and workflow tracking.

## 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 and operation references 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}
go get github.com/agentrail-co/agentrail-go@latest
```

Create the capture once at startup, wrap your handler, and wrap the HTTP clients whose calls belong to the journey:

```go theme={null}
capture, err := agentrail.New(ctx, agentrail.Options{
	Collector: agentrail.CollectorOptions{
		Endpoint: "https://<collector>/ingest/otlp",
		Secret:   os.Getenv("AGENTRAIL_SECRET"),
	},
	HashKey:         os.Getenv("AGENTRAIL_HASH_KEY"),
	ServiceName:     "orders-api",
	OutboundOrigins: []string{"https://inventory.example.com"},
	OnError: func(ctx context.Context, issue agentrail.CaptureError) {
		slog.ErrorContext(ctx, "agentrail", "code", issue.Code)
	},
})
if err != nil {
	return err
}

server := &http.Server{Addr: ":8080", Handler: capture.Middleware(mux)}
inventory := &http.Client{Transport: capture.Transport(nil)}
```

`New` returns an error when an option is wrong. It never reads environment variables itself, so check yours are set before calling it.

* **`Middleware`** records each request it wraps. Install it once. If you already trace incoming requests with `otelhttp`, replace that for this scope, or each request is recorded twice.
* **`Transport`** records outgoing calls. Only the exact origins in `OutboundOrigins` receive your trace context.
* **`OnError`** is told of anything that could not be captured or delivered. None of it replaces your application's response.

`New` registers no global provider. If your application already has an OpenTelemetry provider, use `NewProcessors` and `Bind`, as the [module's README](https://github.com/agentrail-co/agentrail-go#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.

## Name who is calling

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

```go theme={null}
err := capture.Identify(r.Context(), agentrail.VerifiedIdentity{
	Kind:         agentrail.PrincipalAgentRegistration,
	ID:           agent.ID,
	ActingUserID: agent.UserID,
})
```

The kind is `PrincipalUser`, `PrincipalAgentRegistration`, `PrincipalAgentInstance`, `PrincipalOAuthClient` or `PrincipalAPIKey`. 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:

```go theme={null}
err := capture.WithMilestone(ctx, "checkout.confirm",
	agentrail.MilestoneContext{Surface: agentrail.SurfaceCustom, Kind: "checkout.confirm"},
	func(ctx context.Context) error { return confirmOrder(ctx) })
```

`Milestone` records an instant step, and `StartMilestone` returns a function to end one yourself. Use a stable operation name, without arguments or ids. Your error is returned as it was, and a panic is raised again. To report workflow attempts and plugin calls on a milestone, see [Plugin workflow tracking](https://agentrail.co/docs/guides/plugin-performance.md#instrument-your-servers).

## Send your logs

The `slog` handler passes every record on to your own handler unchanged:

```go theme={null}
import agentrailslog "github.com/agentrail-co/agentrail-go/slog"

logger := slog.New(agentrailslog.NewHandler(capture, existingHandler))
logger.ErrorContext(r.Context(), "payment declined", "event.name", "checkout.failed")
```

Use the `…Context` calls, so a log is tied to its request. 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 the handlers you register with the official MCP Go SDK:

```go theme={null}
import capturemcp "github.com/agentrail-co/agentrail-go/mcp"

sdk.AddTool(server, &sdk.Tool{Name: "confirm_order"},
	capturemcp.Tool(capture, "confirm_order", confirmOrder))
```

`capturemcp.ToolHandler`, `capturemcp.Resource` and `capturemcp.Prompt` wrap the others. This targets MCP Go SDK 1.8.0. Arguments, results, prompt text and resource addresses are not recorded.

## Add an approximate location

To record where a request came from, set `IncomingLocation`. It runs for each request and returns the country, region and city from your platform's trusted headers or a local database:

```go theme={null}
options.IncomingLocation = func(r *http.Request) (agentrail.IPLocation, error) {
	return lookUpLocation(r)
}
```

`Country` is a two-letter code, and `Source` is `LocationCloudflare`, `LocationVercel`, `LocationDBIP` or `LocationConfigured`. Return `agentrail.IPLocation{}` when there is none. Make no network call in it. Without it, no location is recorded.

## Shut down cleanly

Stop accepting requests, wait for your handlers, then call `capture.Shutdown(ctx)`, so what is queued is sent. Records wait in a bounded queue in memory, with nothing kept on disk. `capture.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 [Go SDK reference](https://agentrail.co/docs/guides/journeys-go-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.