Documentation
¶
Overview ¶
Package coldread shows which AI agents use your Go website or API, CLI and MCP server. Three parts:
- NewTracker: net/http middleware for websites and APIs, the Go counterpart of @coldread/track (secret key, COLDREAD_KEY).
- NewMCP: an MCP server's tool calls, the counterpart of @coldread/cli/mcp, fed by the crmcp (official SDK) and crmcpgo (mcp-go) helpers (public key).
- New: a CLI's runs, the counterpart of @coldread/cli (public key), below.
The CLI half sends the same events as @coldread/cli, with the same opt-outs, the same spool and the same COLDREAD_VERIFY lines.
cr := coldread.New(coldread.Options{Key: "cr_pub_...", Tool: "acme", Version: "1.2.0", OptOut: "ACME_NO_TELEMETRY"})
cr.Track("deploy preview", "--prod") // once the command is parsed
// ... run it ...
cr.Exit(code) // instead of os.Exit: sends, then exits
Helpers for cobra (coldread.apappas.dev/go/crcobra) and urfave/cli (coldread.apappas.dev/go/crurfave) do the Track and the Exit for you; the standard flag package is TrackFlags.
It never breaks your CLI: nothing panics, and nothing here returns an error. It barely slows it: the connection opens in the background at startup, and at exit the send waits ExitWait (300ms) at most; what isn't sent by then goes with the next run.
Sent per run: your tool's name and version, the command path you pass, flag names (never values), exit code, duration, which agent ran it (by the names of the variables that said so, never their values), whether it ran in CI or at a person's terminal, a salted hash of the agent's session id, and os, arch and Go version. Never arguments, paths, hostnames, usernames, env values, a device id or anything typed. Coldread never stores the IP.
Killed (SIGTERM, SIGHUP, SIGQUIT: what agents' timeouts send), a run is recorded only when the CLI asks: catching a signal in Go turns its default exit off, so Coldread never does it unasked, and by default a killed run is simply not recorded. CaptureSignals (no handler of its own): saved to the spool as 128+n and raised again at once. OwnSignals (the CLI handles the signal itself): its handler runs as ever and the run reads 128+n when it ends. Ctrl-C (SIGINT) sends nothing; SIGKILL can't be seen. A refused command line is ParseError (exit 2); a panic is Recover (exit 2). Help and version runs aren't sent.
Off with DO_NOT_TRACK=1, COLDREAD_DISABLED=1 or your own OptOut, and in test binaries (unless COLDREAD_VERIFY=1 to an endpoint that isn't production). COLDREAD_DEBUG=1 prints each event to stderr and sends nothing. COLDREAD_VERIFY=1 sends for real, waits, and prints what came back on stderr: "coldread verify: accepted", or why not.
Index ¶
- Constants
- Variables
- func ClientIP(r *http.Request) string
- func CodexSession(meta map[string]any) string
- type Agent
- type Client
- func (c *Client) Agent() *Agent
- func (c *Client) Enabled() bool
- func (c *Client) Exit(code int)
- func (c *Client) Finish(exit int)
- func (c *Client) Headers(userAgent string) http.Header
- func (c *Client) ParseError(command string, flags ...string)
- func (c *Client) Recover()
- func (c *Client) Track(command string, flags ...string)
- func (c *Client) TrackFlags(command string, fs *flag.FlagSet)
- type ClientInfo
- type MCP
- type MCPOptions
- type Options
- type RequestFacts
- type ToolCall
- type Tracker
- type TrackerOptions
- type TrackerStats
Constants ¶
const ( VerifyPrefix = "[coldread] verify: " VerifyAccepted = "[coldread] verify: accepted" )
The prefix of every COLDREAD_VERIFY line, and the line that means the event arrived. The same as @coldread/cli's.
const ClientInfoMeta = "io.modelcontextprotocol/clientInfo"
ClientInfoMeta is the _meta key a client names itself under on each request (the stateless MCP spec).
const CodexClientName = "codex-mcp-client"
CodexClientName is the client name Codex's MCP client gives itself. A call with Codex's turn metadata and no client named is Codex's (stateless HTTP carries no initialize).
const CodexTurnMeta = "x-codex-turn-metadata"
CodexTurnMeta is the _meta key Codex sends its turn under: session_id, thread_id, turn_id and more. Codex passes MCP servers no environment, so this is its session.
const ConnectedLine = "[coldread] connected: first requests accepted"
ConnectedLine is the line an install is verified by. Said once per process, on stderr, the first time Coldread confirms it accepted records.
const DefaultEndpoint = "https://coldread.apappas.dev/api/ingest"
DefaultEndpoint is where events go unless Options.Endpoint or COLDREAD_ENDPOINT says otherwise.
const ExitWait = 300 * time.Millisecond
ExitWait is the longest Finish and Exit wait for the event to be sent. Past it, the event waits in the spool for the next run.
const Version = "0.3.1"
Version is this SDK's version.
Variables ¶
var SentHeaders = []string{"user-agent", "accept", "accept-language", "sec-fetch-dest", "sec-ch-ua", "sec-ch-ua-platform", "sec-ch-ua-mobile", "signature", "signature-input", "signature-agent", "ai-agent"}
SentHeaders are the only request headers sent: who's asking (user-agent, and accept-language, which real browsers always send), whether it's a page load (accept, sec-fetch-dest), the browser's own client hints (sec-ch-ua*: a cloud browser dressed as a laptop gives itself away), Web Bot Auth signatures, and ai-agent, which CLIs a coding agent drives stamp on their API calls.
Functions ¶
func ClientIP ¶ added in v0.2.0
ClientIP is the visitor's address as Middleware reads it by default: Vercel's x-real-ip on Vercel, X-Forwarded-For only when COLDREAD_TRUST_PROXY says proxies of yours add to it, else the connection's own address. Headers are anyone's to send: a visitor can put Google's address in cf-connecting-ip and pass as Googlebot, so none is read unless something you run sets it.
func CodexSession ¶ added in v0.3.0
CodexSession is Codex's session id from a request's _meta, or "".
Types ¶
type Agent ¶
type Agent struct {
// Name is ours, normalized: "claude-code", "codex", "cursor". "unknown"
// when something says an agent runs this without naming one (AGENT=1).
Name string
// Raw is the identity string as given (AI_AGENT, AGENT), or "" when a
// marker variable named the agent.
Raw string
Version string
// Host is where the agent runs: terminal, desktop, vscode, sdk, remote.
Host string
// Evidence is "declared" (the agent's own marker) or "inferred" (guessed
// from a parent process; Options.InferParent).
Evidence string
// Confidence is "high", "medium" or "low".
Confidence string
// Signals are the names of the variables that matched, never their values.
Signals []string
}
Agent is the AI coding agent running this process, as detected.
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client reports one run of your CLI. The zero value and nil do nothing.
func (*Client) Agent ¶
Agent is the AI coding agent running this process, or nil. Yours to use too, e.g. to skip a prompt no agent can answer. Detected even when reporting is off.
func (*Client) Enabled ¶
Enabled is false when opted out (DO_NOT_TRACK, COLDREAD_DISABLED, OptOut), in a test binary, or without a valid public key.
func (*Client) Exit ¶
Exit is Finish, then os.Exit(code). Use it wherever your CLI calls os.Exit, since os.Exit skips everything else.
func (*Client) Finish ¶
Finish sends the run with its exit code, waiting ExitWait at most. Only the first call counts, and only after Track. Use it when main returns on its own; Exit when it calls os.Exit.
func (*Client) Headers ¶
Headers are for your CLI's own API calls, so your server (and Coldread's track SDK there) sees the agent: "User-Agent: <ua> AIAgent/<name>" and a structured AI-Agent header. Just the user-agent when no agent is running or the user opted out. userAgent "" means "<tool>/<version>".
func (*Client) ParseError ¶ added in v0.3.0
ParseError records a command line the parser refused (an unknown command or flag, a missing or bad argument, a value that didn't validate): the command that was tried (sanitised; the root when nothing usable), sent when the run ends (Exit, Finish) with the code the CLI exits with, or 2 if it exits 0. No command given: the one already tracked, else the root.
func (*Client) Recover ¶ added in v0.3.0
func (c *Client) Recover()
Recover, deferred at the top of main (`defer cr.Recover()`), records a run that panics with Go's own exit code for it, 2, then panics again, so the CLI ends exactly as it would have. crcobra and crurfave do it for you.
func (*Client) Track ¶
Track names the command once it's parsed: the path ("deploy preview"), never argv, and flag names ("--prod"); values after = are stripped. The root command itself is "" (or the tool's name): it's sent as the tool's name, so a bare `acme` reads "acme". The last call before Finish wins.
A command is up to 4 plain words; the path ends at the first part that isn't one (a path, a URL, a value, something like a key). Flags are `--long-name` or `-x`; anything else is dropped. COLDREAD_DEBUG=1 says what was dropped.
type ClientInfo ¶ added in v0.2.0
type ClientInfo struct{ Name, Version string }
ClientInfo is the MCP client that called, as it named itself.
type MCP ¶ added in v0.2.0
type MCP struct {
// contains filtered or unexported fields
}
MCP reports an MCP server's tool calls. The zero value and nil do nothing.
func NewMCP ¶ added in v0.2.0
func NewMCP(opts MCPOptions) *MCP
NewMCP starts reporting an MCP server's tool calls. One per process, shared by every server it creates (a server per session is fine).
func (*MCP) Agent ¶ added in v0.2.0
Agent is the AI agent this server's environment names, or nil (always nil with Remote).
func (*MCP) Close ¶ added in v0.2.0
func (m *MCP) Close()
Close is Flush, waiting 2 seconds at most. Call it when the server stops (defer it in main): stdio servers stop when the client closes stdin.
func (*MCP) Enabled ¶ added in v0.2.0
Enabled is false when opted out (DO_NOT_TRACK, COLDREAD_DISABLED, OptOut), in a test binary, or without a valid public key.
type MCPOptions ¶ added in v0.2.0
type MCPOptions struct {
// Key is your site's public key (cr_pub_...). It ships in your code;
// that's fine. A secret key (cr_sec_...) is never sent.
Key string
// Tool is your server's name, as you want to see it ("acme-mcp").
Tool string
// Version is your server's version.
Version string
// OptOut names an environment variable your users set to opt out
// (set = opted out). DO_NOT_TRACK and COLDREAD_DISABLED always work.
OptOut string
// OptOutFunc returns true to opt out. A panic counts as opting out.
OptOutFunc func() bool
// Endpoint defaults to COLDREAD_ENDPOINT, then DefaultEndpoint.
Endpoint string
// Remote is for a server reached over HTTP: the agent's markers aren't
// in this process's environment, so they aren't read. Leave it false
// for stdio servers, which the agent starts.
Remote bool
// InferParent also looks at parent processes for agents that set no
// marker. Off by default: it runs ps on macOS. Labeled "inferred".
InferParent bool
// FlushInterval is the longest an event waits before its batch is
// sent. Default 2s.
FlushInterval time.Duration
// FlushOnSignal, for a stdio server with no signal handling of its
// own: its client's SIGINT or SIGTERM sends the spool first (100 ms at
// most), then the signal is raised again. Off by default: catching a
// signal turns its default exit off, and the events are on disk
// already.
FlushOnSignal bool
}
MCPOptions configure an MCP. Key and Tool are required.
type Options ¶
type Options struct {
// Key is your site's public key (cr_pub_...). It ships in your binary;
// that's fine. A secret key (cr_sec_...) is never sent.
Key string
// Tool is your tool's name, as you want to see it ("acme").
Tool string
// Version is your tool's version.
Version string
// OptOut names an environment variable your users set to opt out
// (set = opted out). DO_NOT_TRACK and COLDREAD_DISABLED always work.
OptOut string
// OptOutFunc returns true to opt out. A panic counts as opting out.
OptOutFunc func() bool
// Endpoint defaults to COLDREAD_ENDPOINT, then DefaultEndpoint.
Endpoint string
// InferParent also looks at parent processes for agents that set no
// marker (Copilot CLI, Aider, Windsurf). Off by default: it runs ps on
// macOS. Labeled "inferred".
InferParent bool
// Notice replaces the one-time notice shown on stderr at a person's
// terminal. NoNotice turns it off.
Notice string
NoNotice bool
// CaptureSignals records runs killed by SIGTERM, SIGHUP or SIGQUIT, for
// a CLI with no handler of its own: the run is saved to the spool as
// 128+n and the signal raised again at once, so the CLI dies of it as
// before. Off by default (Go can't tell whether anyone else listens for
// a signal, and catching one turns its default exit off): killed runs
// are then not recorded. A CLI that also handles the signal would get
// the raised one as a second signal: use OwnSignals there.
CaptureSignals bool
// OwnSignals records killed runs for a CLI that handles SIGTERM, SIGHUP
// and SIGQUIT itself (signal.Notify, signal.NotifyContext: a server, a
// watcher), and only then. Its handler runs as ever and ends the run
// (Finish, Exit); the run reads 128+n. Coldread never raises the signal
// again: set on a CLI without a handler, SIGTERM would no longer end it
// (only SIGKILL would). Finish waits 2 ms for a signal not yet read.
OwnSignals bool
// Expected: exit codes that are a normal result, not a failure, by
// command path: {"detect": {1}} for a scanner that exits 1 when it
// finds something. The root command is "" (or the tool's name). Codes
// 1-255. Sent once (again only when it changes) and kept as the site's
// expected outcomes, so those runs never count as dead ends. Only what
// your tool documents.
Expected map[string][]int
}
Options configure a Client. Key and Tool are required.
type RequestFacts ¶ added in v0.2.0
type RequestFacts struct {
Method string
// URL is a path or a full URL; only the path is sent.
URL string
Header http.Header
// IP is the visitor's address. Coldread uses it to check that a bot
// claiming to be, say, OpenAI's comes from OpenAI's published ranges,
// then discards it.
IP string
// Host is the host the visitor asked for (signatures cover it).
Host string
// Status is the response's status code; 0 when it isn't known.
Status int
// Time defaults to now.
Time time.Time
}
RequestFacts is one request, for Track: what Middleware reads from an *http.Request, for servers that aren't net/http (fasthttp, Fiber).
type ToolCall ¶ added in v0.2.0
type ToolCall struct {
// Name is the tool's name.
Name string
// Failed: the call returned an error or a result with isError.
Failed bool
// Start defaults to now minus Duration.
Start time.Time
Duration time.Duration
Client ClientInfo
// SessionID is the transport's session (Streamable HTTP), if any. It
// is hashed before it leaves the process.
SessionID string
// AgentSession is a session the agent named on the call itself
// (Codex's _meta turn metadata: CodexSession). Hashed too; it wins over
// SessionID.
AgentSession string
// HTTP: the call came over HTTP (Streamable HTTP, SSE), not stdio. The
// agent's markers in this process's environment are then the
// operator's, not the caller's, so they aren't read for it (Remote
// does the same for every call). crmcp and crmcpgo set it.
HTTP bool
// UserAgent is the HTTP request's User-Agent, if any. A client the
// registry knows by it (Codex's codex_cli_rs/0.142.5) names a call that
// names no client, and gives its version to one that has none.
UserAgent string
}
ToolCall is one tools/call, for Record.
type Tracker ¶ added in v0.2.0
type Tracker struct {
// contains filtered or unexported fields
}
Tracker sends a server's requests to Coldread. The zero value and nil do nothing. One per process is plenty.
func NewTracker ¶ added in v0.2.0
func NewTracker(opts TrackerOptions) *Tracker
NewTracker starts a Tracker. Without a usable secret key, opted out (DO_NOT_TRACK, COLDREAD_DISABLED) or in a test binary sending to Coldread's own endpoint, it says why once on stderr and sends nothing.
func (*Tracker) Close ¶ added in v0.2.0
func (t *Tracker) Close()
Close sends what's queued, waiting the send timeout plus a second at most, and stops the sender. Requests tracked after it are dropped. Call it on shutdown, after http.Server.Shutdown.
func (*Tracker) Enabled ¶ added in v0.2.0
Enabled is false when nothing will ever be sent: no key, a public key, opted out, or a test run.
func (*Tracker) Flush ¶ added in v0.2.0
Flush sends everything queued now, people's counts included, waiting until it's sent or ctx is done. Never returns an error.
func (*Tracker) Middleware ¶ added in v0.2.0
Middleware reports every request next serves, with its response's status, once the handler writes its header (or returns). It never touches the response. Works with anything net/http: http.ServeMux, chi's r.Use, and gin, echo or gorilla by wrapping the router where the server is made.
func (*Tracker) Stats ¶ added in v0.2.0
func (t *Tracker) Stats() TrackerStats
Stats says how many requests were sent and dropped so far.
func (*Tracker) Track ¶ added in v0.2.0
func (t *Tracker) Track(f RequestFacts)
Track queues one request. It returns at once and never panics. Middleware calls it for you; call it yourself on servers that aren't net/http.
type TrackerOptions ¶ added in v0.2.0
type TrackerOptions struct {
// Key is your site's secret key (cr_sec_...). Defaults to COLDREAD_KEY.
Key string
// Endpoint defaults to COLDREAD_ENDPOINT, then DefaultEndpoint.
Endpoint string
// FlushInterval is the longest a request waits before its batch is
// sent. Default 2s.
FlushInterval time.Duration
// BatchSize is records per batch, at most 500. Default 100.
BatchSize int
// MaxQueue is records waiting to be sent; past it, new ones are
// dropped. Default 1000.
MaxQueue int
// Timeout abandons a batch that takes longer. Default 3s.
Timeout time.Duration
// People is "count" (the default: people's page views go as counts,
// never their IP or headers) or "full" (every request is sent whole).
People string
// TrustProxy is how many proxies you control sit in front of the app,
// each adding the address it saw to X-Forwarded-For (nginx, a load
// balancer, Cloudflare in front of your server). The visitor is the
// entry that many from the end. 0 reads COLDREAD_TRUST_PROXY; unset or
// negative, no header is trusted and the address is the connection's:
// a visitor can write any header, Google's address included.
TrustProxy int
// IP returns the visitor's address when your host puts it somewhere
// else (e.g. Fly's fly-client-ip).
IP func(*http.Request) string
}
TrackerOptions configure a Tracker. All optional.
type TrackerStats ¶ added in v0.2.0
type TrackerStats struct{ Sent, Dropped int }
TrackerStats count requests (a count is as many requests as it counts), not records.