Documentation
¶
Overview ¶
Package usagemetrics provides internal usage metrics for tracking usage and adoption.
Index ¶
- Constants
- func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
- func IsBuiltinCatalogServer(name string) bool
- func NormalizeClientName(name string) string
- func SetCatalogLookup(lookup func(name string) bool)
- func ShouldEnableMetrics(configDisabled bool) bool
- type Client
- type Collector
- type CollectorOption
- type MetricRecord
- type Middleware
- type MiddlewareParams
- type Profile
- type ProfileProvider
Constants ¶
const ( ValueOther = "other" ValueNone = "none" ValueCustom = "custom" ValueOn = "on" ValueOff = "off" ValueBuiltin = "builtin" ServerKindContainer = "container" ServerKindRemote = "remote" RegistrySourceCustomRemote = "custom_remote" RegistrySourceCustomAPI = "custom_api" RegistrySourceCustomLocal = "custom_local" RegistrySourcePackageUVX = "package_uvx" RegistrySourcePackageNPX = "package_npx" RegistrySourcePackageGo = "package_go" RuntimeKubernetes = "kubernetes" AuthModeOIDC = "oidc" AuthModeLocal = "local" AuthModeEmbedded = "embedded" FeatureOptimizer = "optimizer" FeatureCodeMode = "code_mode" FeatureCompositeTools = "composite_tools" FeatureOutgoingAuth = "outgoing_auth" )
Allowed profile values.
const (
// ClientUnknown is reported when a tool call cannot be tied to a client.
ClientUnknown = "unknown"
)
const ( // EnvVarAnonymousID overrides the anonymous ID sent with usage metrics. The // operator sets it on the workloads it deploys to its own instance ID, so // reports from one cluster share an ID instead of a fixed placeholder. EnvVarAnonymousID = "TOOLHIVE_ANONYMOUS_ID" )
const (
// EnvVarUsageMetricsEnabled is the environment variable to disable usage metrics
EnvVarUsageMetricsEnabled = "TOOLHIVE_USAGE_METRICS_ENABLED"
)
const (
// MiddlewareType is the type identifier for usage metrics middleware
MiddlewareType = "usagemetrics"
)
Variables ¶
This section is empty.
Functions ¶
func CreateMiddleware ¶
func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
CreateMiddleware is the factory function for creating usage metrics middleware
func IsBuiltinCatalogServer ¶ added in v0.66.0
IsBuiltinCatalogServer reports whether name is an entry of the built-in registry. Without a registered lookup it returns false, so a name is never reported unless it has been checked against the catalog.
func NormalizeClientName ¶ added in v0.66.0
NormalizeClientName maps an MCP clientInfo.name to one of a fixed set of client values, "other" for unrecognized names, or "unknown" for an empty name. The raw name is never reported.
func SetCatalogLookup ¶ added in v0.66.0
SetCatalogLookup registers the function that tells whether a server name is an entry of the registry embedded in the binary. Only binaries that embed the registry (thv) register one; the lookup lives outside this package so that binaries without it, such as thv-proxyrunner, do not pull the catalog in.
func ShouldEnableMetrics ¶
ShouldEnableMetrics returns true if metrics collection should be enabled Checks: CI detection > Config disable > Environment variable > Default (true) If either config or env var explicitly disables metrics, they stay disabled
Types ¶
type Client ¶
type Client struct {
// contains filtered or unexported fields
}
Client sends usage metrics to the API
func (*Client) SendMetrics ¶
func (c *Client) SendMetrics(instanceID string, record MetricRecord) error
SendMetrics sends the metrics record to the API
type Collector ¶
type Collector struct {
// contains filtered or unexported fields
}
Collector manages tool call counting and reporting
func NewCollector ¶
func NewCollector(opts ...CollectorOption) (*Collector, error)
NewCollector creates a new metrics collector
func (*Collector) Flush ¶
Flush sends the current metrics to the API Checks for midnight boundary crossing and handles daily reset
func (*Collector) GetCurrentCount ¶
GetCurrentCount returns the current count (for testing/debugging)
func (*Collector) IncrementToolCall ¶
func (c *Collector) IncrementToolCall()
IncrementToolCall records a tool call from an unidentified client.
func (*Collector) IncrementToolCallFrom ¶ added in v0.66.0
IncrementToolCallFrom records a tool call made by the given client. The client name is normalized, so callers may pass the raw clientInfo name.
type CollectorOption ¶ added in v0.66.0
type CollectorOption func(*Collector)
CollectorOption configures a Collector.
func WithComponent ¶ added in v0.66.0
func WithComponent(component string) CollectorOption
WithComponent sets the component reported in the User-Agent (for example "vmcp"). By default the component is "local" or "operator", depending on whether the process runs in Kubernetes.
func WithEndpoint ¶ added in v0.66.0
func WithEndpoint(endpoint string) CollectorOption
WithEndpoint sets the URL reports are sent to, instead of the Stacklok update service. Tests use it to point the collector at a local server.
func WithProfile ¶ added in v0.66.0
func WithProfile(profile func() Profile) CollectorOption
WithProfile sets the function that describes the server being reported on. It is called on every flush, so it must be cheap and safe for concurrent use.
type MetricRecord ¶
type MetricRecord struct {
Count int64 `json:"count"`
Timestamp string `json:"timestamp"` // ISO 8601 format in UTC (e.g., "2025-01-01T23:50:00Z")
// CallsByClient splits Count by the MCP client that made the calls. Keys are
// always one of the normalized client values (see NormalizeClientName), so the
// map holds at most a fixed, small number of entries.
CallsByClient map[string]int64 `json:"calls_by_client,omitempty"`
Profile
}
MetricRecord is the payload sent to the metrics API
type Middleware ¶
type Middleware struct {
// contains filtered or unexported fields
}
Middleware implements the types.Middleware interface
func NewMiddleware ¶ added in v0.66.0
func NewMiddleware(collector *Collector) *Middleware
NewMiddleware returns usage metrics middleware that reports to the given collector. It must run after the MCP parsing middleware. A nil collector yields a pass-through middleware.
func (*Middleware) Handler ¶
func (m *Middleware) Handler() types.MiddlewareFunction
Handler returns the middleware function
type MiddlewareParams ¶
type MiddlewareParams struct {
}
MiddlewareParams represents the parameters for usage metrics middleware
type Profile ¶ added in v0.66.0
type Profile struct {
// Transport is the MCP transport: stdio, sse, streamable-http or other.
Transport string `json:"transport,omitempty"`
// ServerKind is container or remote.
ServerKind string `json:"server_kind,omitempty"`
// RegistrySource is where the server definition came from: a registry
// (builtin, custom_remote, custom_api, custom_local), a package that thv
// built into an image (package_uvx, package_npx, package_go), or none of
// these (a plain image or URL).
RegistrySource string `json:"registry_source,omitempty"`
// CatalogServer is the built-in registry entry name, or "custom".
CatalogServer string `json:"catalog_server,omitempty"`
// Runtime is docker, podman, colima, kubernetes, none or other.
Runtime string `json:"runtime,omitempty"`
// AuthMode is the incoming authentication: none, oidc, local, embedded or other.
AuthMode string `json:"auth_mode,omitempty"`
// Authz is on or off.
Authz string `json:"authz,omitempty"`
// BackendCount is the number of backends behind a vMCP server.
BackendCount *int `json:"backend_count,omitempty"`
// ToolCount is the number of backend tools a vMCP server aggregates, after
// conflict resolution and per-backend filters. It excludes composite and
// optimizer tools and is not filtered per user, so it measures the size of
// the deployment rather than what one client sees. Aggregation results are
// cached per caller, so it is the count from the most recent aggregation.
ToolCount *int `json:"tool_count,omitempty"`
// Features lists the vMCP features in use, drawn from optimizer, code_mode,
// composite_tools and outgoing_auth.
Features []string `json:"features,omitempty"`
}
Profile describes the server a collector reports for. Every string field holds one of a fixed set of values (enforced by normalize), so no field can carry user-defined names, URLs or other free-form data. The one exception, CatalogServer, is restricted to entry names of the registry embedded in the ToolHive binary.
type ProfileProvider ¶ added in v0.66.0
type ProfileProvider interface {
UsageMetricsProfile() Profile
}
ProfileProvider is implemented by runner configurations that can describe the server they run. The usage metrics middleware checks for it at creation time.