agentstats

package module
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: MIT Imports: 16 Imported by: ? 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

agentstats-go

Analytics for Go MCP servers. The core package has no dependencies; adapters per library:

go get agentstats.io/go
// github.com/modelcontextprotocol/go-sdk
server := mcp.NewServer(&mcp.Implementation{Name: "my-server", Version: "1.0.0"}, nil)
tracker := gosdk.Instrument(server, agentstats.Options{}) // receiving middleware
defer tracker.Shutdown(context.Background())

// github.com/mark3labs/mcp-go: drop-in for server.NewMCPServer
s, tracker := mcpgo.NewServer("my-server", "1.0.0", agentstats.Options{})
// already using hooks? mcpgo.AddTo(yourHooks, agentstats.New(agentstats.Options{ServerName: "my-server"}))

agentstats.Options{FeedbackTool: true} adds a send_feedback tool the SDK answers itself, so agents and users can report problems (with mcp-go and your own hooks, also call mcpgo.AddFeedbackTool(s, tracker)).

Handles both the initialize handshake and the 2026-07-28 server/discover + per-request _meta client info. Measured overhead: ~0.4 µs on an 80 µs in-memory call (go test -bench .).

go test ./...

Documentation

Overview

Package agentstats is the core of the AgentStats MCP analytics SDK for Go.

Use an adapter for your MCP library:

agentstats.io/go/gosdk  (github.com/modelcontextprotocol/go-sdk)
agentstats.io/go/mcpgo  (github.com/mark3labs/mcp-go)

Recording an event is a timestamp and an append under a short mutex. A background goroutine ships batches; on failure events are dropped, never retried inline. Tool arguments and results are never sent. See https://github.com/getagentstats/spec/blob/main/PROTOCOL.md.

Index

Constants

View Source
const (
	FeedbackToolTitle       = "Send feedback"
	FeedbackToolDescription = "" /* 364-byte string literal not displayed */
	FeedbackReply           = "Thanks: your feedback was sent to the developers of this server."
	FeedbackEmptyReply      = "Nothing was sent: `content` is empty."
)

FeedbackToolTitle, FeedbackToolDescription, FeedbackInputSchema and FeedbackReply define the send_feedback tool exactly as the spec does, for adapters to list and answer it.

View Source
const FeedbackToolName = "send_feedback"

FeedbackToolName is the tool Options.FeedbackTool adds (PROTOCOL.md, "Feedback").

View Source
const Version = "0.1.0"

Variables

View Source
var ContentMethods = map[string]bool{"tools/call": true, "resources/read": true, "prompts/get": true}

ContentMethods are the requests whose result is content handed to the model, so its size is its context cost.

View Source
var Tracked = map[string]bool{
	"tools/call": true, "tools/list": true, "initialize": true, "server/discover": true,
	"resources/read": true, "resources/list": true, "prompts/get": true, "prompts/list": true,
}

Tracked lists the methods worth recording.

Functions

func FeedbackInputSchema

func FeedbackInputSchema() map[string]any

FeedbackInputSchema returns the send_feedback input schema (a fresh map each call).

func LocalSessionID

func LocalSessionID() string

LocalSessionID returns a random id for transports without sessions (stdio).

func ToolsSignature

func ToolsSignature(n int, each func(i int) (name string, descLen int)) string

ToolsSignature is the cheap change-detection key for a tool list.

Types

type Auth

type Auth struct {
	Method string   `json:"method"`
	Client *string  `json:"client"`
	Scopes []string `json:"scopes"`
}

Auth is what's kept of a validated OAuth access token (https://github.com/getagentstats/spec/blob/main/PROTOCOL.md "Sign-in").

func AuthSummary

func AuthSummary(clientID string, scopes []string) *Auth

AuthSummary keeps the client app, by its Client ID Metadata Document URL (https, with a path, no credentials or query), else "registered" (Dynamic Client Registration ids are random per installation), and the granted scopes: de-duplicated, sorted, at most 20 of at most 80 chars.

type Call

type Call struct {
	Method, Tool, SessionID string
	Started                 time.Time
	IsError                 bool
	// ErrorKind is "tool" for an isError result, "protocol" for a JSON-RPC error (with ErrorCode).
	ErrorKind    string
	ErrorCode    *int64
	ErrorMessage string
	Err          error // the error the handler returned, if any
	// ResultChars is the characters of text a successful tools/call, resources/read or prompts/get
	// result handed the model; nil when the adapter didn't measure it.
	ResultChars *int
	// Client identity, when the adapter knows it. Otherwise it is looked up by session.
	ClientName, ClientVersion string
	// Auth is the request's sign-in summary (AuthSummary), if it carried a validated token.
	Auth *Auth
}

Call describes one observed request/response pair.

type CatalogTool

type CatalogTool struct {
	Name        string `json:"name"`
	Description string `json:"description,omitempty"`
	InputSchema any    `json:"inputSchema,omitempty"`
}

CatalogTool is the subset of a tool definition sent for lint and never-called reports.

type ErrorInfo

type ErrorInfo struct {
	Tool    string // empty unless tools/call
	Method  string
	Message string // the error, or the first text content of an isError result
	Err     error  // the Go error the handler returned, or nil for isError results
}

ErrorInfo is a failed request, as passed to Options.ErrorText.

type Event

type Event struct {
	Ts            int64   `json:"ts"`
	Method        string  `json:"method"`
	Tool          *string `json:"tool"`
	DurationMs    float64 `json:"durationMs"`
	IsError       bool    `json:"isError"`
	ErrorKind     *string `json:"errorKind,omitempty"`
	ErrorCode     *int64  `json:"errorCode,omitempty"`
	ErrorMessage  *string `json:"errorMessage"`
	ResultChars   *int    `json:"resultChars,omitempty"`
	ClientName    *string `json:"clientName"`
	ClientVersion *string `json:"clientVersion"`
	SessionID     *string `json:"sessionId"`
	Auth          *Auth   `json:"auth,omitempty"`
}

Event is one observed MCP request/response pair.

type Feedback

type Feedback struct {
	Ts            int64   `json:"ts"`
	SessionID     *string `json:"sessionId"`
	ClientName    *string `json:"clientName"`
	ClientVersion *string `json:"clientVersion"`
	Source        string  `json:"source"`
	Tool          *string `json:"tool"`
	Content       string  `json:"content"`
}

Feedback is one send_feedback call, as sent with a batch.

type Options

type Options struct {
	APIKey     string // AGENTSTATS_MCP_KEY
	ServerName string // defaults to the serverInfo name the server reports
	// SampleRate is the fraction of tools/call requests recorded. 0 means 1.
	SampleRate float64
	// DisableErrorText stops error messages being sent.
	DisableErrorText bool
	// ErrorText decides what is sent of each failed request's message: return the text to
	// keep, or "" for none. It runs as the response is sent, so keep it cheap; a panic keeps nothing.
	ErrorText func(ErrorInfo) string
	// DisableCatalog stops the tool list being sent.
	DisableCatalog bool
	// FeedbackTool adds a send_feedback tool to the server's tools, answered by the SDK (it never reaches
	// your handlers), so agents can report a tool that failed them and users can pass something on.
	// What they write is sent to AgentStats (Feedback, under the server). Off by default.
	FeedbackTool  bool
	FlushInterval time.Duration // default 2s
	MaxBatch      int           // default 250
	MaxBuffer     int           // default 10000
	Debug         bool          // AGENTSTATS_DEBUG=1
	HTTPClient    *http.Client
	// AuthInfo returns the OAuth client id and granted scopes of the request's validated access
	// token, for transports that put them in the context (mcp-go's WithHTTPContextFunc, your own
	// middleware). The gosdk adapter reads the go-sdk's TokenInfo without it. Only the client app
	// and scopes are sent (see AuthSummary), never the token or the user.
	AuthInfo func(ctx context.Context) (clientID string, scopes []string, ok bool)
	// contains filtered or unexported fields
}

Options configure a Tracker. Zero values fall back to environment variables and defaults.

type Tracker

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

Tracker buffers events and ships them in the background. Safe for concurrent use.

func New

func New(opts Options) *Tracker

New creates a Tracker. Without an API key it returns a disabled tracker whose methods are no-ops.

func (*Tracker) AuthFrom

func (t *Tracker) AuthFrom(ctx context.Context) (a *Auth)

AuthFrom applies Options.AuthInfo to a request context. A panic keeps nothing.

func (*Tracker) Dropped

func (t *Tracker) Dropped() int64

Dropped returns how many events have been dropped since the last successful send.

func (*Tracker) Enabled

func (t *Tracker) Enabled() bool

Enabled reports whether events are being recorded.

func (*Tracker) FeedbackEnabled

func (t *Tracker) FeedbackEnabled() bool

FeedbackEnabled says whether adapters should add send_feedback.

func (*Tracker) Flush

func (t *Tracker) Flush(ctx context.Context) error

Flush sends buffered events now. Call it before a serverless handler returns.

func (*Tracker) Record

func (t *Tracker) Record(c Call)

Record buffers one event. It never blocks on I/O.

func (*Tracker) RecordFeedback

func (t *Tracker) RecordFeedback(args map[string]any, sessionID, clientName, clientVersion string) bool

RecordFeedback queues what a send_feedback call said (args are its arguments). It returns false when there's nothing to keep (empty content), so the adapter answers with FeedbackEmptyReply.

func (*Tracker) Sample

func (t *Tracker) Sample() bool

Sample reports whether a tools/call should be recorded under the sample rate.

func (*Tracker) SetClient

func (t *Tracker) SetClient(sessionID, name, version string)

SetClient remembers the client behind a session, from its initialize request.

func (*Tracker) SetInstructions

func (t *Tracker) SetInstructions(instructions string)

SetInstructions records the server's instructions.

func (*Tracker) SetServerInfo

func (t *Tracker) SetServerInfo(name, version, instructions string)

SetServerInfo records the server's name, version and instructions from its initialize result.

func (*Tracker) SetTools

func (t *Tracker) SetTools(build func() []CatalogTool, sig string)

SetTools records a complete tools/list result; it is sent once whenever it changes.

func (*Tracker) Shutdown

func (t *Tracker) Shutdown(ctx context.Context) error

Shutdown stops the background goroutine and sends what is left.

Directories

Path Synopsis
Package api tracks which routes AI agents call on your API, and counts every other call.
Package api tracks which routes AI agents call on your API, and counts every other call.
cli
Package cli is AgentStats analytics for command-line tools written in Go: which commands coding agents, people and CI run, and where they fail.
Package cli is AgentStats analytics for command-line tools written in Go: which commands coding agents, people and CI run, and where they fail.
cobracli
Package cobracli records cobra commands with AgentStats: one call in place of root.Execute().
Package cobracli records cobra commands with AgentStats: one call in place of root.Execute().
Package gosdk adds AgentStats analytics to servers built with github.com/modelcontextprotocol/go-sdk.
Package gosdk adds AgentStats analytics to servers built with github.com/modelcontextprotocol/go-sdk.
internal
ingest
Package ingest says where the SDK sends events.
Package ingest says where the SDK sends events.
Package mcpgo adds AgentStats analytics to servers built with github.com/mark3labs/mcp-go.
Package mcpgo adds AgentStats analytics to servers built with github.com/mark3labs/mcp-go.

Jump to

Keyboard shortcuts

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