metrics

package
v1.1.2 Latest Latest
Warning

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

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 12 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.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func ListenAndServe

func ListenAndServe(addr string, logger *slog.Logger) (*http.Server, error)

ListenAndServe starts the metrics endpoint from a bind address alone, with no token and no extra allowed hosts. It is a thin wrapper around ListenAndServeConfig kept for callers that have no need for authentication (a loopback-only bind); ListenAndServeConfig refuses to start on a non-loopback bind without a token exactly the same way either entry point is called.

func ListenAndServeConfig added in v1.1.1

func ListenAndServeConfig(cfg Config, logger *slog.Logger) (*http.Server, error)

ListenAndServeConfig starts the metrics endpoint per cfg. A non-loopback bind (cfg.Bind's host is not loopback) without cfg.Token refuses to start, exactly like pkg/dashboard: otherwise the JSON snapshot — server names, tool names and token counts — would be served to anyone who can reach the bound interface. Every request's Host header is validated the same way the dashboard's is, to close the DNS-rebinding path from a malicious page in a local browser (issue #316).

func SetResponseCacheProvider added in v1.1.1

func SetResponseCacheProvider(f func() ResponseCacheMetric)

SetResponseCacheProvider registers the function Snapshot uses to populate ResponseCache. Front ends (`server run --stdio`, `serve`) call this once at startup with a closure over their own *mcp.ResponseCache. Passing nil clears it, so ResponseCache is omitted from the snapshot again.

func SetResponseGovernorProvider added in v1.1.1

func SetResponseGovernorProvider(f func() mcp.GovernorStats)

SetResponseGovernorProvider registers the function Snapshot uses to populate ResponseGovernor (issue #319). Front ends call it once at startup with their *mcp.Governor's Stats. Passing nil clears it.

Types

type Config added in v1.1.1

type Config struct {
	Bind  string
	Token string

	// AllowedHosts lists extra Host header values (--metrics-allowed-hosts)
	// accepted in addition to the bind host, localhost, 127.0.0.1 and ::1.
	AllowedHosts []string

	// Usage, when set, supplies the "usage" section (today / week-to-date
	// from the usage store, see UsageSummary). A nil func, or one that
	// returns nil (e.g. the store could not be read), omits the section.
	Usage func() *UsageSummary
}

Config holds the metrics endpoint's bind address and, since issue #316, its optional bearer token and extra allowed Host header values. It mirrors pkg/dashboard.Config; the two packages stay independent of each other but share the same DNS-rebinding and unauthenticated-access defenses via pkg/httpsec.

type MetricsSnapshot

type MetricsSnapshot struct {
	ResponseCache *ResponseCacheMetric `json:"response_cache,omitempty"`
	// ResponseGovernor is the response token governor's accounting (issue
	// #319): tokens before/after per tool, truncations, spill store size.
	// Omitted while the governor is off.
	ResponseGovernor *mcp.GovernorStats `json:"response_governor,omitempty"`
	// Telemetry mirrors the counters OpenTelemetry records (issue #317):
	// requests, errors, redactions, injection detections, cache hits/misses,
	// policy decisions, rate-limit waits and in-flight requests. Populated
	// unconditionally (see pkg/mcp.TelemetrySnapshot), independent of
	// whether an OTLP exporter is configured, so /metrics keeps working the
	// same whether or not telemetry is enabled.
	Telemetry mcp.TelemetryCounters `json:"telemetry"`
}

MetricsSnapshot is this process's live counters. It is what /metrics serves (plus the usage store's windows, see UsageSummary) and what every front end appends to the usage store (pkg/usage.Record), so it must stay payload-free: only numbers, server/tool names and flags.

It used to carry by_tool/by_server/total_spend/top_5_expensive_tools from reporter.GlobalCostTracker, which nothing in the live pipeline feeds; those were always empty and are gone. Per-server/per-tool token figures now come from the usage store (UsageSummary), built from the response governor's per-tool accounting below.

func Snapshot

func Snapshot() MetricsSnapshot

Snapshot returns this process's live counters.

type ResponseCacheMetric added in v1.1.1

type ResponseCacheMetric struct {
	Enabled   bool   `json:"enabled"`
	Hits      uint64 `json:"hits"`
	Misses    uint64 `json:"misses"`
	Evictions uint64 `json:"evictions"`
	Bytes     int64  `json:"bytes"`
	Entries   int    `json:"entries"`
}

ResponseCacheMetric is the response cache's (issue #299) counters as exposed on the /metrics endpoint. It deliberately mirrors responsecache.Stats field-for-field instead of importing pkg/mcp, so this package stays a leaf dependency.

type UsageServer added in v1.1.1

type UsageServer struct {
	Server         string `json:"server"`
	Tools          int    `json:"tools"`
	Calls          int64  `json:"calls"`
	OriginalTokens int64  `json:"original_tokens"`
	ReturnedTokens int64  `json:"returned_tokens"`
	SavedTokens    int64  `json:"saved_tokens"`
}

UsageServer is one upstream server's tool results in a window.

type UsageSummary added in v1.1.1

type UsageSummary struct {
	// Estimator names the token-counting heuristic of every *_tokens
	// field ("chars/4"), the same one `leanproxy-mcp report` uses.
	Estimator string `json:"estimator"`
	// Today starts at 00:00 UTC of the current day.
	Today UsageWindow `json:"today"`
	// Week starts at 00:00 UTC of the current ISO week's Monday.
	Week UsageWindow `json:"week"`
}

UsageSummary is the usage store's (pkg/usage) view of the tokens every front end on this machine recorded, over two windows: today and week-to-date. It is computed by pkg/usage (which imports this package, so the types live here) and served by /metrics under "usage" and by the dashboard. Every number is measured by the proxy and counted with Estimator; nothing here is modeled or priced.

type UsageTool added in v1.1.1

type UsageTool struct {
	// Server is the upstream server; empty for a tool the governor did
	// not attribute to a server (and for its "other" overflow bucket).
	Server         string `json:"server"`
	Tool           string `json:"tool"`
	Calls          int64  `json:"calls"`
	OriginalTokens int64  `json:"original_tokens"`
	ReturnedTokens int64  `json:"returned_tokens"`
	SavedTokens    int64  `json:"saved_tokens"`
}

UsageTool is one tool's results in a window.

func (UsageTool) AvgTokensPerCall added in v1.1.1

func (t UsageTool) AvgTokensPerCall() float64

AvgTokensPerCall is OriginalTokens / Calls (0 without calls).

type UsageWindow added in v1.1.1

type UsageWindow struct {
	Since    time.Time `json:"since"`
	Sessions int       `json:"sessions"`

	// OriginalTokens, SavedTokens and SavedPercent are `report`'s
	// total_original_tokens / total_saved_tokens / total_saved_percent for
	// this window: schema savings plus the response governor's.
	OriginalTokens int64   `json:"original_tokens"`
	SavedTokens    int64   `json:"saved_tokens"`
	SavedPercent   float64 `json:"saved_percent"`

	// DiscoveryCalls and DiscoveryTokens are the search_tools / list_tools
	// / list_servers cost (not a saving; not in SavedTokens).
	DiscoveryCalls  int64 `json:"discovery_calls"`
	DiscoveryTokens int64 `json:"discovery_tokens"`

	// ToolCalls is the number of tool results the response governor saw.
	ToolCalls int64 `json:"tool_calls"`

	// TopServer and TopTool are the largest entries of ByServer and ByTool
	// (by response size, OriginalTokens); empty when there are none.
	TopServer string `json:"top_server,omitempty"`
	TopTool   string `json:"top_tool,omitempty"`

	// ByServer and ByTool break tool results down by upstream server and
	// tool, largest response size first. They come from the response
	// governor's per-tool accounting, so they stay empty unless
	// `response.enabled: true` (the same data as `report --by tool|server`).
	ByServer []UsageServer `json:"by_server"`
	ByTool   []UsageTool   `json:"by_tool"`
}

UsageWindow is the tokens recorded between Since and now, summed over every session (front-end process) that recorded something in it. A session that started before Since only contributes what it accumulated after Since (its latest record minus its last record before Since), so today and week-to-date are genuinely different windows.

func (UsageWindow) ServerTools added in v1.1.1

func (w UsageWindow) ServerTools(server string) []UsageTool

ServerTools returns the window's tools of server, largest first.

func (*UsageWindow) SetTools added in v1.1.1

func (w *UsageWindow) SetTools(tools []UsageTool)

SetTools sets ByTool from tools and derives ByServer, TopServer and TopTool from it, all sorted by OriginalTokens descending (then name, so the output is deterministic).

Jump to

Keyboard shortcuts

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