mettr

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Dec 3, 2026 License: MIT Imports: 22 Imported by: 0 modules, 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

mettr for Go

Live analytics for websites and SaaS products: who is on your site right now, what they do, where they came from and what broke, with no delay. This module sends a Go app's side of it to mettr: your product's own events, crawlers' visits (search engines and AI crawlers seldom run the browser script), 404s, panics, response times and subscriptions, and serves the browser script from your own domain.

go get github.com/mettrhq/mettr-go

Go 1.23 or later, the standard library only.

Settings

mettr.New reads the environment; Options win.

variable what
METTR_SECRET_KEY the site's secret key (mettr, the site's settings, Tracking); keep it on the server
METTR_PUBLIC_KEY the site's public key, for the script tag and the proxy
METTR_ENABLED true or false; by default on once a key is set
METTR_PROXY_PATH the first-party path, _live by default; empty serves the script from mettr
METTR_ENDPOINT where mettr runs, https://mettr.app

net/http, chi, gorilla/mux

client := mettr.New(mettr.Options{})
defer client.Close()

mux := http.NewServeMux()
mux.HandleFunc("GET /posts/{id}", showPost)

http.ListenAndServe(":8080", client.Middleware(mux))

The route comes from ServeMux's pattern; with chi, pass Route: func(r *http.Request) string { return chi.RouteContext(r.Context()).RoutePattern() } and use the middleware inside the router (r.Use(client.Middleware)). Behind a proxy of your own, set TrustForwarded: true.

Gin

import "github.com/mettrhq/mettr-go/mettrgin"

router.Use(gin.Recovery(), mettrgin.Middleware(client))

Echo

import "github.com/mettrhq/mettr-go/mettrecho"

e.Use(mettrecho.Middleware(client))

In the page

template.HTML(client.ScriptTag())

The tag loads the script from /_live/script.js and sends its events to /_live/events, which the middleware serves: ad blockers mostly leave first-party requests alone, and the events carry the visitor's address and user as your server saw them. Only what a browser may send passes.

Your own events

func signup(w http.ResponseWriter, r *http.Request) {
    mettr.SetUser(r.Context(), user.ID)          // the request's events carry it
    client.Event(r.Context(), "signup", mettr.Props{"plan": "pro"})
    client.Revenue(r.Context(), "order", 49.5, "EUR", nil)
}

Props are flat: up to 30, each a string, number, boolean or nil. Events wait a second to go together; a program that ends calls client.Close(). client.Exception(ctx, err) sends an error you handled, by its type.

Subscriptions

For MRR when your billing is your own (anything but Stripe, Paddle or Polar, which mettr reads itself), send each subscription whenever it changes, and every one once for the history:

client.Subscription(mettr.Subscription{
    ID: "sub_1", Status: "active", Amount: 19, Currency: "USD",
    Interval: "month", UserID: "42", Plan: "Pro",
})

Your MCP server

If your app runs an MCP server, mettr shows how AI assistants use it: calls, tools, clients, failures and time. Wrap the server's handler outside its auth, so a 401 that sends a client to sign in counts too:

server := mcp.NewStreamableHTTPHandler(getServer, nil)   // any MCP server's http.Handler
mux.Handle("/mcp", client.Mcp(requireAuth(server), mettr.McpOptions{
    User:   func(r *http.Request) string { return userID(r) },   // or mettr.SetUser inside
    Errors: false,                                              // true keeps failed calls' messages
}))

// Gin, Echo: mount it the same way
router.Any("/mcp", gin.WrapH(client.Mcp(server, mettr.McpOptions{})))

Each handshake, tool call, resource read and prompt becomes an mcp.* event with the client (Claude, ChatGPT, Cursor...), how it ended and how long it took. Only the tool's, resource's or prompt's name is sent, never the arguments or the result, and nothing of the assistant's address or user agent. A failed call's message is sent only with Errors: true (it may quote the user), cut to 200 characters; the session id only as a hash. The middleware and the Gin and Echo adapters send no crawl, 404 or timing for its requests. Read with Pro: see MCP analytics.

History and deploys

client.Import(rows)     // each with TS and SourceID: a second run adds nothing
client.Annotation("Deployed v2.4", "https://github.com/acme/app/releases/v2.4", time.Now())

What is sent on its own

  • A crawler's request: its page and status, as a crawl (mettr names the crawler and checks it against its owner's network).
  • A person's 404, as an error.
  • A panic, by its type only, never its message; then it panics on.
  • One request in twenty's response time, by route.
  • Nothing for /up (Ignore), for staff, or while mettr is off.

Sending never panics into your app: a failed batch answers false and is told to OnError, without its events.

License

MIT

Documentation

Overview

Package mettr sends a Go app's side of mettr's live analytics: the product's own events, crawlers' visits (search engines and AI crawlers seldom run the browser script), 404s, panics, response times and subscriptions, and serves the browser script from your own domain.

client := mettr.New(mettr.Options{})
defer client.Close()
http.ListenAndServe(":8080", client.Middleware(mux))

Index

Constants

View Source
const (
	PathEvents        = "/api/v1/events"
	PathImport        = "/api/v1/import"
	PathSubscriptions = "/api/v1/subscriptions"
	PathAnnotations   = "/api/v1/annotations"
	PathScript        = "/script.js"
)

The API's paths.

View Source
const (
	Batch              = 100
	ImportBatch        = 1000
	SubscriptionsBatch = 100
	MaxProps           = 30
	MaxPropLength      = 500
)

The ingest's limits.

View Source
const (
	ProxyPath          = "_live"
	ProxyMaxBytes      = 65536
	ProxyMaxEvents     = 20
	ScriptCacheSeconds = 3600
	ScriptRetrySeconds = 60
)

The first-party proxy.

View Source
const (
	McpErrorLength         = 200
	McpMetaClientInfo      = "io.modelcontextprotocol/clientInfo"
	McpMetaProtocolVersion = "io.modelcontextprotocol/protocolVersion"
	McpSessionHeader       = "Mcp-Session-Id"
)

The MCP calls' limits, _meta keys and session header.

View Source
const DefaultEndpoint = "https://mettr.app"

DefaultEndpoint is where mettr runs.

View Source
const McpMaxAnswer = 1 << 20

McpMaxAnswer is how much of an answer is read for its outcome; the rest still goes to the client.

View Source
const McpSessions = 10_000

McpSessions is how many older clients' sessions are remembered at once.

View Source
const ResponseTimeSample = 0.05

ResponseTimeSample is the share of requests whose response time is sent.

View Source
const TimeoutSeconds = 3

TimeoutSeconds is how long a batch waits for mettr.

View Source
const Version = "0.2.0"

Version is the package's version, sent in the User-Agent.

Variables

View Source
var (
	ProxyTypes  = []string{"pageview", "event", "engagement", "vital", "presence"}
	ProxyFields = []string{"type", "name", "url", "referrer", "props", "automated"}
)

ProxyTypes and ProxyFields are what a browser may send through the proxy.

View Source
var (
	McpProps    = []string{"tool", "resource", "prompt", "client", "client_version", "protocol", "outcome", "status", "duration_ms", "error_code", "error", "session"}
	McpOutcomes = []string{"ok", "tool_error", "error", "sign_in", "forbidden", "throttled", "failed"}
)

McpProps and McpOutcomes are what an MCP call's event says.

View Source
var Cloudflare = []string{
	"173.245.48.0/20", "103.21.244.0/22", "103.22.200.0/22", "103.31.4.0/22", "141.101.64.0/18",
	"108.162.192.0/18", "190.93.240.0/20", "188.114.96.0/20", "197.234.240.0/22", "198.41.128.0/17",
	"162.158.0.0/15", "104.16.0.0/13", "104.24.0.0/14", "172.64.0.0/13", "131.0.72.0/22",
	"2400:cb00::/32", "2606:4700::/32", "2803:f800::/32", "2405:b500::/32", "2405:8100::/32",
	"2a06:98c0::/29", "2c0f:f248::/32",
}

Cloudflare is Cloudflare's addresses, from cloudflare.com/ips (October 2026).

View Source
var CrawlerPattern = regexp.MustCompile("(?i)bot|crawl|spider|slurp|facebookexternalhit|facebookcatalog|embedly|iframely|whatsapp|perplexity|chatgpt|claude|anthropic|cohere|diffbot|bytespider|meta-external|uptime|pingdom|statuscake|site24x7|checkly|screaming frog")

CrawlerPattern matches the user agents sent as crawler visits.

View Source
var McpMethods = map[string]string{
	"initialize":      "mcp.connect",
	"server/discover": "mcp.connect",
	"tools/call":      "mcp.tool",
	"resources/read":  "mcp.resource",
	"prompts/get":     "mcp.prompt",
}

McpMethods are the calls to the customer's own MCP server that are sent (Client.Mcp), each as its event.

View Source
var SubscriptionIntervals = []string{"day", "week", "month", "year"}

SubscriptionIntervals are the billing intervals mettr takes.

View Source
var SubscriptionStatuses = []string{"active", "trialing", "past_due", "paused", "canceled"}

SubscriptionStatuses are the statuses mettr takes; active and past_due pay.

Functions

func ForwardedFor

func ForwardedFor(header string) string

ForwardedFor is the first address of X-Forwarded-For: the client, as the proxies saw it; empty when there is none.

func SetRoute

func SetRoute(ctx context.Context, route string)

SetRoute names the matched route's pattern, for the response time sample (the gin and echo adapters do).

func SetUser

func SetUser(ctx context.Context, userID string)

SetUser ties the request's events to the signed-in user, from a handler or an auth middleware inside mettr's: mettr.SetUser(r.Context(), "42").

func VisitorIP

func VisitorIP(relay, connecting string) string

VisitorIP is the visitor's address, not the edge node relaying the request.

Behind Cloudflare, the address the request came from (the relay) is a Cloudflare node: every visitor would be placed where the node is, and would become a new visitor whenever Cloudflare routed them through another. CF-Connecting-IP names the address Cloudflare took the request from, and counts only when the request came from Cloudflare: one sent to the server directly could name any address.

Types

type Client

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

Client collects events and sends them in batches, so a request never waits on mettr. Sending never panics into the app: a failed batch answers false and is told to OnError, without its events. Close sends what is left.

func New

func New(options Options) *Client

New makes a client.

func (*Client) Annotation

func (c *Client) Annotation(title, link string, at time.Time) bool

Annotation notes a change under the traffic chart, from a deploy script or CI.

func (*Client) Begin

func (c *Client) Begin(r *http.Request) (*http.Request, func(status int, failure any))

Begin starts tracking a request: the context the handler should get (SetUser, SetRoute and the client's event methods read it), and the function that ends it with the status written. A framework adapter calls it; net/http apps use Middleware.

func (*Client) Close

func (c *Client) Close()

Close sends what is left: defer it where the app ends.

func (*Client) Crawl

func (c *Client) Crawl(status int, visitor Visitor)

Crawl sends a crawler's request: the page and its status. mettr names the crawler.

func (*Client) Enabled

func (c *Client) Enabled() bool

Enabled says whether anything is sent.

func (*Client) Error

func (c *Client) Error(ctx context.Context, name string, props Props)

Error sends an error: a 404, anything that broke.

func (*Client) Event

func (c *Client) Event(ctx context.Context, name string, props Props)

Event sends a custom event, with the visitor of the request in ctx: client.Event(r.Context(), "signup", mettr.Props{"plan": "pro"}).

func (*Client) Exception

func (c *Client) Exception(ctx context.Context, failure any)

Exception sends an error or a panic's value as an error event: its type only, never the message (it may hold what the app's users typed). One that says its HTTP status is under 500 is the request's fault, and is not sent.

func (*Client) Finished

func (c *Client) Finished(status int, took time.Duration, route string, visitor Visitor)

Finished is what a middleware calls once the response is known: a crawler's request becomes a crawl, a 404 an error, and a sample of requests sends its response time. mettr's own proxy path sends none.

func (*Client) Flush

func (c *Client) Flush() bool

Flush sends what has been collected, now.

func (*Client) Ignores

func (c *Client) Ignores(raw string) bool

Ignores says whether a URL or path is one mettr sends nothing for.

func (*Client) Import

func (c *Client) Import(events []Event) bool

Import sends history (POST /api/v1/import), in batches of 1,000: each event with its TS and SourceID, so a second run adds nothing.

func (*Client) IsCrawler

func (c *Client) IsCrawler(userAgent string) bool

IsCrawler says whether a user agent is a crawler's, as the middleware reads it.

func (*Client) IsProxy

func (c *Client) IsProxy(raw string) bool

IsProxy says whether a URL is under the proxy path.

func (*Client) Mcp added in v0.2.0

func (c *Client) Mcp(next http.Handler, options McpOptions) http.Handler

Mcp wraps your own MCP server's handler, outside its auth, so the 401 that sends a client to sign in is counted too:

mux.Handle("/mcp", client.Mcp(server, mettr.McpOptions{}))

Each call an AI assistant makes (the handshake, a tool, a resource, a prompt) is sent as an mcp.* event with the client, how the call ended and how long it took. What a call was about is sent (the tool's, resource's or prompt's name), never what it carried or what came back. Nothing of the client's address or user agent is sent: they are the assistant's servers', not the person's. Lists and pings are not sent. Middleware (and the gin and echo adapters) send no crawl, 404 or timing for its requests.

func (*Client) Middleware

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

Middleware wraps an http.Handler (a ServeMux, chi, gorilla/mux, echo through echo.WrapMiddleware): serves the first-party proxy, and sends a crawler's visit as a crawl, a 404 as an error, a panic by its type (then panics on) and a sample of response times.

func (*Client) ProxyEvents

func (c *Client) ProxyEvents(raw []byte, visitor Visitor) (int, map[string]any)

ProxyEvents answers POST {proxy}/events: the browser script's events, through your own domain. They go on with the secret key, carrying what only your server knows: the visitor's address and browser as they reached you, and the signed-in user. So only what a browser may say passes: the types and fields of the public key, never a time, a user, an address or revenue.

func (*Client) ProxyPath

func (c *Client) ProxyPath() string

ProxyPath is the first-party path, "" when the script comes from mettr.

func (*Client) ProxyScript

func (c *Client) ProxyScript() (int, http.Header, string)

ProxyScript answers GET {proxy}/script.js: mettr's browser script from your own domain, fetched once an hour and kept in memory. While mettr cannot be reached the page gets an empty script, tried again in a minute.

func (*Client) Record

func (c *Client) Record(event Event, visitor Visitor)

Record adds an event with what the request knows of the visitor. Nothing is added while mettr is off, for staff, or on a path mettr ignores.

func (*Client) Revenue

func (c *Client) Revenue(ctx context.Context, name string, amount float64, currency string, props Props)

Revenue sends a payment: an amount in the currency's main unit, negative for a refund.

func (*Client) ScriptTag

func (c *Client) ScriptTag() string

ScriptTag is the tag for the page's <head>: the script with the site's public key, through the proxy path when there is one; empty while mettr is off.

func (*Client) Send

func (c *Client) Send(events []Event) bool

Send sends events now, in batches of 100, as mettr's ingest API takes them.

func (*Client) ServeProxy

func (c *Client) ServeProxy(w http.ResponseWriter, r *http.Request) bool

ServeProxy answers the first-party proxy's two paths, and says whether the request was one of them.

func (*Client) Subscription

func (c *Client) Subscription(s Subscription)

Subscription sends a subscription of the app's own billing, as it is now, for MRR when mettr does not read the billing itself (not Stripe, Paddle or Polar). Send it whenever it changes, and every one once for the history.

func (*Client) VisitorFromRequest

func (c *Client) VisitorFromRequest(r *http.Request) Visitor

VisitorFromRequest is the visitor as a request shows them: its URL, the address (behind Cloudflare its visitor's), browser and signed-in user.

type Event

type Event struct {
	Type      string   `json:"type"`
	Name      string   `json:"name,omitempty"`
	URL       string   `json:"url,omitempty"`
	Referrer  string   `json:"referrer,omitempty"`
	TS        string   `json:"ts,omitempty"`
	UserID    string   `json:"user_id,omitempty"`
	IP        string   `json:"ip,omitempty"`
	UserAgent string   `json:"user_agent,omitempty"`
	Props     Props    `json:"props,omitempty"`
	Revenue   *Revenue `json:"revenue,omitempty"`
	Automated *bool    `json:"automated,omitempty"`
	// SourceID is the source's own id, for history (Import).
	SourceID string `json:"source_id,omitempty"`
	// OwnURL keeps URL as the event's own, even empty, rather than the
	// request's.
	OwnURL bool `json:"-"`
}

Event is an event as mettr's ingest API takes it (POST /api/v1/events).

type McpOptions added in v0.2.0

type McpOptions struct {
	// User is the signed-in user's id, read once the server has answered;
	// else SetUser's, else the client's Options.User.
	User func(*http.Request) string
	// Errors sends a failed call's message (it may quote the user), cut to
	// McpErrorLength characters.
	Errors bool
}

McpOptions are the settings of Client.Mcp.

type Options

type Options struct {
	SecretKey string
	PublicKey string
	Endpoint  string
	// Enabled: by default on when METTR_ENABLED says so, or else once a key is set.
	Enabled *bool
	// ProxyPath is the first-party path, "_live" by default; a pointer to ""
	// serves the script from mettr directly.
	ProxyPath *string
	// Timeout for each call to mettr, 3 s by default.
	Timeout time.Duration
	// FlushInterval is how long events wait to go together, 1 s by default;
	// a negative one sends only on Flush.
	FlushInterval time.Duration
	// ResponseTimeSample is the share of requests whose response time is
	// sent, 0.05 by default; a negative one sends none.
	ResponseTimeSample float64
	CrawlerPattern     *regexp.Regexp
	// Ignore lists paths that send nothing at all (a * matches anything),
	// ["/up"] by default.
	Ignore []string
	Track  Track
	// HTTPClient sends to mettr; by default one that never follows a redirect.
	HTTPClient *http.Client
	// OnError is told of a batch mettr refused or could not take (never its events).
	OnError func(error)
	// Random is the source of the response time sample (tests).
	Random func() float64

	// User reads the signed-in user's id from a request, after the handler
	// ran; SetUser from a handler wins.
	User func(*http.Request) string
	// Staff says whether a request is staff's: nothing of theirs is sent.
	Staff func(*http.Request) bool
	// TrustForwarded takes X-Forwarded-For's first address as the relay (an
	// app behind its own proxy).
	TrustForwarded bool
	// Route reads the matched route's pattern (chi's RoutePattern); by
	// default net/http's Request.Pattern.
	Route func(*http.Request) string
}

Options are the client's settings. Empty fields come from the environment (METTR_SECRET_KEY, METTR_PUBLIC_KEY, METTR_ENDPOINT, METTR_ENABLED, METTR_PROXY_PATH), then the defaults.

type Props

type Props map[string]any

Props are flat: up to 30, each a string, number, boolean or nil.

type Revenue

type Revenue struct {
	Amount   float64 `json:"amount"`
	Currency string  `json:"currency"`
}

Revenue is a payment's amount, in the currency's main unit.

type Subscription

type Subscription struct {
	ID string
	// Status: active or past_due (both pay), trialing, paused, canceled.
	Status string
	// Amount is what it bills each cycle before tax, in the main unit (19.00).
	Amount   float64
	Currency string
	// Interval: day, week, month (the default) or year; every IntervalCount.
	Interval      string
	IntervalCount int
	UserID        string
	Plan          string
	StartedAt     time.Time
	// CanceledAt is when it stopped paying.
	CanceledAt time.Time
	// ChangedAt is when it became as sent; now if zero.
	ChangedAt time.Time
}

Subscription is one of the app's own billing, as it is now.

type Track

type Track struct {
	NoNotFound   bool
	NoExceptions bool
	NoCrawlers   bool
}

Track says what the middleware sends on its own; all on by default.

type Visitor

type Visitor struct {
	URL       string
	IP        string
	UserAgent string
	UserID    string
	// Staff (the site's own people) send nothing.
	Staff bool
}

Visitor is what the current request knows of the visitor. mettr uses the address for the place and the visitor hash, and keeps nothing of it.

func VisitorFrom

func VisitorFrom(ctx context.Context) Visitor

VisitorFrom is the visitor of the request being served in ctx, or none.

Jump to

Keyboard shortcuts

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