agentrail

package module
v0.5.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 37 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Agentrail for Go

Go Reference CI Go version Licence

agentrail-go adds your Go servers to the journeys Agentrail follows: the requests your server answers, the calls it makes, the identity your application verified, the milestones you name, your slog logs and your MCP traffic. It is built on OpenTelemetry, registers no globals, runs beside Sentry, Datadog and your own OpenTelemetry with nothing in them to change, and never sends raw identities, or bodies, arguments and results, unless you turn on MCP payload capture (Options.MCP.CapturePayloads, with a required Redact hook).

Requirements

  • Go 1.26 or later
  • A server source in Agentrail: open Journeys, select Set up and choose Your servers. Agentrail shows its Secret and Hash key once. Keep both on the server, for example as AGENTRAIL_SECRET and AGENTRAIL_HASH_KEY.

Install

go get github.com/agentrail-co/agentrail-go@latest

Quick start

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"},
})
if err != nil {
	return err // an option is wrong
}

// Record incoming requests, and the outgoing calls made with this client.
server := &http.Server{Addr: ":8080", Handler: capture.Middleware(mux)}
inventory := &http.Client{Transport: capture.Transport(nil)}

// In a handler, once your application has authenticated the caller:
err = capture.Identify(r.Context(), agentrail.VerifiedIdentity{
	Kind: agentrail.PrincipalUser, ID: user.ID,
})

// Name the steps that matter. Your error and panic come back unchanged.
err = capture.WithMilestone(r.Context(), "checkout.confirm",
	agentrail.MilestoneContext{Surface: agentrail.SurfaceCustom, Kind: "checkout.confirm"},
	func(ctx context.Context) error { return confirmOrder(ctx, inventory) })

// On shutdown: stop taking requests first, then send what is queued.
_ = server.Shutdown(shutdownCtx)
_ = capture.Shutdown(shutdownCtx)

For an MCP server, wrap its handler (or, for stdio, its transport) and its tools:

mcpHandler := sdk.NewStreamableHTTPHandler(getServer, nil)
mux.Handle("/mcp", capturemcp.Handler(capture, mcpHandler))
// stdio: server.Connect(ctx, capturemcp.Transport(capture, &sdk.StdioTransport{}), nil)
sdk.AddTool(server, tool, capturemcp.Tool(capture, "confirm_order", confirmOrder))

Under capturemcp.Handler, each MCP span also says how the HTTP request that carried its message was made, which is how Agentrail tells one agent product from another: the method, the URL (its query cut to Agentrail's marker), the status, the user agent, the header names (never a value; lower-cased and sorted, as Go keeps neither their case nor their order), Accept, Accept-Encoding and the JSON-RPC id. A message over stdio carries none of these.

When a customer's CLI uses agentrail-cli-sdk, its requests say which command an agent ran, in which run and session. The middleware records that on the request's span, the session only as a keyed hash, so the agent's CLI runs join its journey. There is nothing to configure.

New never reads environment variables, so check yours are set before calling it. Only the exact origins in OutboundOrigins receive Agentrail's trace context. Complete programs: HTTP server, MCP server, beside OpenTelemetry.

Beside Sentry, Datadog and OpenTelemetry

A server that already runs Sentry, Datadog or its own OpenTelemetry uses the same setup and changes nothing in theirs. Agentrail keeps its own tracer and logger, registers no OpenTelemetry global, and keeps its current span in a place of its own in the request's context. The other tracer's spans stay where they were, its trace headers still reach the services you call, and Agentrail records the same spans with or without it. Put the other tracer's middleware and client transport outside Agentrail's:

server := &http.Server{Addr: ":8080", Handler: otelhttp.NewHandler(capture.Middleware(mux), "orders-api")}
inventory := &http.Client{Transport: otelhttp.NewTransport(capture.Transport(nil))}

Sentry's sentryhttp handler and sentryhttpclient round tripper, and Datadog's httptrace.WrapHandler and httptrace.WrapRoundTripper, go in the same places. Transport takes a concrete *http.Transport (or nil), so Agentrail's headers are set next to the network.

On calls to any origin outside OutboundOrigins, the other tracer's headers (traceparent, tracestate, baggage, sentry-trace, x-datadog-*) go out as it set them, and Agentrail's own never do. On a call to an allowed origin, Agentrail's signed traceparent replaces the other tracer's and its tracestate is dropped; its other headers go through unchanged. One limit follows for a tracer that propagates by traceparent alone, as OpenTelemetry does by default: its trace for that one hop continues under Agentrail's trace ID. Sentry (sentry-trace) and Datadog (x-datadog-*) keep their own trace there, as their headers go through.

Agentrail records only its own spans. Spans your code or its libraries start inside a request go to your tracer, not to Agentrail, and trace.SpanFromContext in a handler returns your tracer's span, never Agentrail's.

Upgrading from 0.4

0.5.0 has one setup, New, for every server. Removed: NewProcessors, the Processors type (SpanProcessor, LogProcessor, Propagator, Bind, Sampler), Options.Propagator and ErrUnbound. Replace them with New and keep your provider as it was. Your own spans and OpenTelemetry log records are no longer copied to Agentrail, and calls made while answering a request now keep your trace headers.

Documentation

Topic Guide
Set up, identity, milestones, logs, MCP, location Install the Go SDK
Every option, Sentry, Datadog and OpenTelemetry, delivery and error codes Go SDK reference
Leaving out health checks and your own services Leave out your own servers
Workflow attempts and plugin calls Plugin workflow tracking
What is sent, and what never is What Agentrail records
Package API pkg.go.dev

The same SDK for other languages: Node and Python. Before 1.0, a minor version may change the API.

Contributing

Bugs and questions: GitHub issues. Building, testing and releasing: CONTRIBUTING.md.

Licence

Apache-2.0.

Documentation

Overview

Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.

Package agentrail records privacy-filtered backend evidence for Agentrail. It uses explicit request contexts and never installs global OTel providers.

Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.

Copyright 2026 Agentrail. Licensed under the Apache License, Version 2.0.

Index

Constants

View Source
const Version = "0.5.1"

Variables

View Source
var ErrClosed = errors.New("Agentrail capture is shut down")

Functions

This section is empty.

Types

type AuthorizedOperation

type AuthorizedOperation struct {
	NamespaceID, InstanceRef string
	Role                     WorkflowRole
}

AuthorizedOperation names a business attempt the application has already authorized. InstanceRef is hashed locally and never exported.

type CaptureError

type CaptureError struct {
	Code, Signal string
	Count        int
}

CaptureError describes loss or refused context without including customer data.

func (CaptureError) Error

func (e CaptureError) Error() string

type Client

type Client struct {
	// contains filtered or unexported fields
}

func New

func New(ctx context.Context, input Options) (*Client, error)

New starts capture with tracer and logger providers of its own. It registers no OpenTelemetry global and replaces nothing the application set up, so it runs beside Sentry, Datadog or the application's own OpenTelemetry, before or after them.

func (*Client) Diagnostics

func (c *Client) Diagnostics() Diagnostics

func (*Client) Flush

func (c *Client) Flush(ctx context.Context) error

Flush waits for delivery attempts, not guaranteed delivery. Inspect Diagnostics and OnError for records lost to refusal, timeout or queue overflow.

func (*Client) Identify

func (c *Client) Identify(ctx context.Context, id VerifiedIdentity) error

Identify asserts identity the application has already authenticated. Headers, generic OTel user attributes and self-reported MCP metadata are never trusted.

func (*Client) Log

func (c *Client) Log(ctx context.Context, input StructuredLog)

Log records structured fields only. Message text requires Logs.IncludeFields.

func (*Client) Middleware

func (c *Client) Middleware(next http.Handler) http.Handler

Middleware records each request it admits. Install it once. Other tracing middleware, such as otelhttp, Sentry's or Datadog's, can wrap it: their span stays current in the request's context, and ours is never its parent nor its child.

func (*Client) Milestone

func (c *Client) Milestone(ctx context.Context, name string, d MilestoneContext)

func (*Client) Shutdown

func (c *Client) Shutdown(ctx context.Context) error

func (*Client) StartMilestone

func (c *Client) StartMilestone(ctx context.Context, name string, d MilestoneContext) (context.Context, func(error))

StartMilestone starts a scoped operation. Call the returned end function once with the application error. Use WithMilestone to preserve panics automatically.

func (*Client) Transport

func (c *Client) Transport(base *http.Transport) http.RoundTripper

Transport instruments a network transport. Inside a managed request, a call keeps the application's trace headers, such as those otelhttp, Sentry or Datadog set in a transport installed outside this one, and loses Agentrail's own. A call to an exact allowed origin gets our signed traceparent and handoff in place of the application's traceparent and tracestate. A concrete *http.Transport keeps that adjacent to the network: a nested tracing RoundTripper could otherwise overwrite the signed traceparent after signing. A nil base uses a private standard network transport. Client redirects pass through this wrapper again, so each actual destination is admitted independently.

func (*Client) WithMilestone

func (c *Client) WithMilestone(ctx context.Context, name string, d MilestoneContext, run func(context.Context) error) (err error)

WithMilestone returns the application's original error and rethrows panics.

type CollectorOptions

type CollectorOptions struct {
	Endpoint string
	Secret   string
}

type ConfigurationError

type ConfigurationError struct{ Problem string }

func (*ConfigurationError) Error

func (e *ConfigurationError) Error() string

type Diagnostics

type Diagnostics struct {
	Spans delivery.Stats
	Logs  delivery.Stats
}

type IPLocation

type IPLocation struct {
	Country, Region, City string
	Source                LocationSource
}

IPLocation describes a network exit, not a person's verified location. Country is an uppercase two-letter code. Empty place fields mean unknown. Values are copied at request admission; raw addresses are never included.

type LocationSource

type LocationSource string

LocationSource identifies the trusted provider of an approximate IP location.

const (
	LocationDBIP       LocationSource = "dbip"
	LocationCloudflare LocationSource = "cloudflare"
	LocationVercel     LocationSource = "vercel"
	LocationConfigured LocationSource = "source"
)

type LogsOptions

type LogsOptions struct {
	IncludeFields       []string
	ExcludeUncorrelated bool
}

type MCPContext

type MCPContext struct{ Method, Client, ClientVersion, Protocol, Name string }

MCPContext describes an MCP call. Name is the tool, resource or prompt's registered name, never a value from its arguments.

type MCPOptions added in v0.3.0

type MCPOptions struct {
	// CapturePayloads sends each request's params and its result as JSON text.
	// Off by default: without it no argument, result or resource content is sent.
	// It requires Redact.
	CapturePayloads bool
	// Redact, required with CapturePayloads, runs on every payload before it
	// is queued, on the goroutine that wrote the response. Return the payload to send, which must stay valid JSON,
	// or false to send none. It receives copies it may change. A panic, or JSON
	// that is not valid, drops the payload and is reported to OnError; the MCP
	// call is never affected.
	Redact func(MCPPayload) (MCPPayload, bool)
}

MCPOptions configures capture by the mcp package's transport wrappers.

type MCPPayload added in v0.3.0

type MCPPayload struct {
	Method, Name      string
	Request, Response json.RawMessage
}

MCPPayload is one MCP message the server received and its answer, as the MCP SDK encoded them. Request is the request's params; Response is the result, or the JSON-RPC error object. Name is the tool or prompt name, or the resource URI, where the method has one.

type MilestoneContext

type MilestoneContext struct {
	Surface Surface
	Kind    string
	MCP     *MCPContext
	// Performance is explicit evidence supplied after application authorization;
	// it is never inferred from tool inputs or results, and applies only to this
	// milestone's own span.
	Performance *PerformanceContext
}

type Options

type Options struct {
	Collector                               CollectorOptions
	HashKey, ServiceName, ServiceInstanceID string
	OutboundOrigins                         []string
	IgnoreIncomingRequest                   func(*http.Request) bool
	// IncomingLocation uses trusted platform metadata or a preloaded local database.
	// Return a zero value for unknown locations. Errors are reported without failing the request.
	IncomingLocation func(*http.Request) (IPLocation, error)
	Logs             LogsOptions
	Queue            QueueOptions
	MCP              MCPOptions
	OnError          func(context.Context, CaptureError)
	// contains filtered or unexported fields
}

Options configures backend capture. Secrets are supplied by the application; this package never reads environment variables implicitly.

type PerformanceContext

type PerformanceContext struct {
	Environment PerformanceEnvironment
	Operation   *AuthorizedOperation
	EventName   string
	Plugin      *PluginInvocation
}

PerformanceContext is explicit workflow or plugin evidence for one milestone. Supply an Operation with an EventName, a Plugin, or both; or a Plugin alone, without an EventName, for activity that earns no workflow-outcome credit.

type PerformanceEnvironment

type PerformanceEnvironment string

PerformanceEnvironment separates production evidence from test evidence.

const (
	EnvironmentProduction PerformanceEnvironment = "production"
	EnvironmentTest       PerformanceEnvironment = "test"
)

type PluginInvocation

type PluginInvocation struct{ BindingID, InvocationID string }

PluginInvocation names an authenticated plugin deployment and an opaque invocation ID, never tool arguments or a customer identifier.

type PrincipalKind

type PrincipalKind string
const (
	PrincipalAgentRegistration PrincipalKind = "agent_registration"
	PrincipalUser              PrincipalKind = "user"
	PrincipalAPIKey            PrincipalKind = "api_key"
	PrincipalAgentInstance     PrincipalKind = "agent_instance"
	PrincipalOAuthClient       PrincipalKind = "oauth_client"
)

type QueueOptions

type QueueOptions struct {
	MaxRecords, BatchSize                                        int
	ScheduledDelay, ExportTimeout, FlushTimeout, ShutdownTimeout time.Duration
}

type StructuredLog

type StructuredLog struct {
	SeverityNumber                     int
	SeverityText, ErrorType, EventName string
	Fields                             map[string]any
	Timestamp, ObservedTimestamp       time.Time
}

type Surface

type Surface string
const (
	SurfaceHTTP     Surface = "http"
	SurfaceMCP      Surface = "mcp"
	SurfaceAuth     Surface = "auth"
	SurfaceCustom   Surface = "custom"
	SurfaceA2A      Surface = "a2a"
	SurfaceGenAI    Surface = "genai"
	SurfacePayment  Surface = "payment"
	SurfaceEdge     Surface = "edge"
	SurfaceFirewall Surface = "firewall"
	SurfaceBrowser  Surface = "browser"
)

type VerifiedIdentity

type VerifiedIdentity struct {
	Kind             PrincipalKind
	ID, ActingUserID string
}

type WorkflowRole

type WorkflowRole string

WorkflowRole is where a milestone sits in one business attempt.

const (
	RoleStart    WorkflowRole = "start"
	RoleProgress WorkflowRole = "progress"
	RoleTerminal WorkflowRole = "terminal"
)

Directories

Path Synopsis
examples
http command
mcp command
integration
capture command
Command capture produces synthetic OTLP bytes through the public Go SDK.
Command capture produces synthetic OTLP bytes through the public Go SDK.
internal
delivery
Package delivery provides bounded, best-effort asynchronous batch delivery.
Package delivery provides bounded, best-effort asynchronous batch delivery.
handoff
Package handoff implements the authenticated Agentrail trace handoff protocol.
Package handoff implements the authenticated Agentrail trace handoff protocol.
mcpspan
Package mcpspan connects the MCP adapter to the client's private span recording.
Package mcpspan connects the MCP adapter to the client's private span recording.
Package mcp records MCP traffic of official MCP Go SDK servers as Agentrail evidence.
Package mcp records MCP traffic of official MCP Go SDK servers as Agentrail evidence.
Package slog adds opt-in Agentrail capture to an application's log/slog handler.
Package slog adds opt-in Agentrail capture to an application's log/slog handler.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL
⌂ 换网址