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
- Variables
- func ForwardedFor(header string) string
- func SetRoute(ctx context.Context, route string)
- func SetUser(ctx context.Context, userID string)
- func VisitorIP(relay, connecting string) string
- type Client
- func (c *Client) Annotation(title, link string, at time.Time) bool
- func (c *Client) Begin(r *http.Request) (*http.Request, func(status int, failure any))
- func (c *Client) Close()
- func (c *Client) Crawl(status int, visitor Visitor)
- func (c *Client) Enabled() bool
- func (c *Client) Error(ctx context.Context, name string, props Props)
- func (c *Client) Event(ctx context.Context, name string, props Props)
- func (c *Client) Exception(ctx context.Context, failure any)
- func (c *Client) Finished(status int, took time.Duration, route string, visitor Visitor)
- func (c *Client) Flush() bool
- func (c *Client) Ignores(raw string) bool
- func (c *Client) Import(events []Event) bool
- func (c *Client) IsCrawler(userAgent string) bool
- func (c *Client) IsProxy(raw string) bool
- func (c *Client) Mcp(next http.Handler, options McpOptions) http.Handler
- func (c *Client) Middleware(next http.Handler) http.Handler
- func (c *Client) ProxyEvents(raw []byte, visitor Visitor) (int, map[string]any)
- func (c *Client) ProxyPath() string
- func (c *Client) ProxyScript() (int, http.Header, string)
- func (c *Client) Record(event Event, visitor Visitor)
- func (c *Client) Revenue(ctx context.Context, name string, amount float64, currency string, props Props)
- func (c *Client) ScriptTag() string
- func (c *Client) Send(events []Event) bool
- func (c *Client) ServeProxy(w http.ResponseWriter, r *http.Request) bool
- func (c *Client) Subscription(s Subscription)
- func (c *Client) VisitorFromRequest(r *http.Request) Visitor
- type Event
- type McpOptions
- type Options
- type Props
- type Revenue
- type Subscription
- type Track
- type Visitor
Constants ¶
const ( PathEvents = "/api/v1/events" PathImport = "/api/v1/import" PathSubscriptions = "/api/v1/subscriptions" PathAnnotations = "/api/v1/annotations" PathScript = "/script.js" )
The API's paths.
const ( Batch = 100 ImportBatch = 1000 SubscriptionsBatch = 100 MaxProps = 30 MaxPropLength = 500 )
The ingest's limits.
const ( ProxyPath = "_live" ProxyMaxBytes = 65536 ProxyMaxEvents = 20 ScriptCacheSeconds = 3600 ScriptRetrySeconds = 60 )
The first-party proxy.
const ( McpErrorLength = 200 McpMetaClientInfo = "io.modelcontextprotocol/clientInfo" McpMetaProtocolVersion = "io.modelcontextprotocol/protocolVersion" McpSessionHeader = "Mcp-Session-Id" )
The MCP calls' limits, _meta keys and session header.
const DefaultEndpoint = "https://mettr.app"
DefaultEndpoint is where mettr runs.
const McpMaxAnswer = 1 << 20
McpMaxAnswer is how much of an answer is read for its outcome; the rest still goes to the client.
const McpSessions = 10_000
McpSessions is how many older clients' sessions are remembered at once.
const ResponseTimeSample = 0.05
ResponseTimeSample is the share of requests whose response time is sent.
const TimeoutSeconds = 3
TimeoutSeconds is how long a batch waits for mettr.
const Version = "0.2.0"
Version is the package's version, sent in the User-Agent.
Variables ¶
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.
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.
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).
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.
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.
var SubscriptionIntervals = []string{"day", "week", "month", "year"}
SubscriptionIntervals are the billing intervals mettr takes.
var SubscriptionStatuses = []string{"active", "trialing", "past_due", "paused", "canceled"}
SubscriptionStatuses are the statuses mettr takes; active and past_due pay.
Functions ¶
func ForwardedFor ¶
ForwardedFor is the first address of X-Forwarded-For: the client, as the proxies saw it; empty when there is none.
func SetRoute ¶
SetRoute names the matched route's pattern, for the response time sample (the gin and echo adapters do).
func SetUser ¶
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 ¶
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 (*Client) Annotation ¶
Annotation notes a change under the traffic chart, from a deploy script or CI.
func (*Client) Begin ¶
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 ¶
Crawl sends a crawler's request: the page and its status. mettr names the crawler.
func (*Client) Event ¶
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 ¶
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 ¶
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) Import ¶
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 ¶
IsCrawler says whether a user agent is a crawler's, as the middleware reads it.
func (*Client) Mcp ¶ added in v0.2.0
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 ¶
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 ¶
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) ProxyScript ¶
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 ¶
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 ¶
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) ServeProxy ¶
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.
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 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 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 ¶
VisitorFrom is the visitor of the request being served in ctx, or none.