Documentation
¶
Overview ¶
Package telemetry provides OpenTelemetry instrumentation for ToolHive MCP server proxies.
Package telemetry provides OpenTelemetry instrumentation for ToolHive MCP server proxies.
Package telemetry provides OpenTelemetry instrumentation for ToolHive MCP server proxies.
+groupName=toolhive.stacklok.dev +versionName=telemetry
Index ¶
- Constants
- Variables
- func ConvertMapToAttributes(attrs map[string]string) []attribute.KeyValue
- func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
- func InjectMetaTraceContext(ctx context.Context, meta map[string]interface{})
- func NewHTTPMiddleware(config Config, tracerProvider trace.TracerProvider, ...) types.MiddlewareFunction
- func ParseCustomAttributes(input string) (map[string]string, error)
- func ResolveServiceName(config *Config, serverName string)
- type Config
- type FactoryMiddleware
- type FactoryMiddlewareParams
- type HTTPMiddleware
- type MetaCarrier
- type Provider
- func (p *Provider) MeterProvider() metric.MeterProvider
- func (p *Provider) Middleware(serverName, transport string) types.MiddlewareFunction
- func (p *Provider) PrometheusHandler() http.Handler
- func (p *Provider) Shutdown(ctx context.Context) error
- func (p *Provider) TracerProvider() trace.TracerProvider
Constants ¶
const DefaultServiceNamePrefix = "thv-"
DefaultServiceNamePrefix is prepended to the workload name when deriving the OTel service name automatically (e.g. "thv-fetch", "thv-github").
const (
MiddlewareType = "telemetry"
)
Factory middleware type constant
Variables ¶
var MCPHistogramBuckets = []float64{0.01, 0.02, 0.05, 0.1, 0.2, 0.5, 1, 2, 5, 10, 30, 60, 120, 300}
MCPHistogramBuckets are the bucket boundaries defined by the MCP OTEL semantic conventions for MCP server histograms (e.g. mcp.server.operation.duration). See https://github.com/open-telemetry/semantic-conventions/blob/main/docs/gen-ai/mcp.md
Functions ¶
func ConvertMapToAttributes ¶ added in v0.4.1
ConvertMapToAttributes converts a map[string]string to OpenTelemetry attributes
func CreateMiddleware ¶ added in v0.2.8
func CreateMiddleware(config *types.MiddlewareConfig, runner types.MiddlewareRunner) error
CreateMiddleware factory function for telemetry middleware
func InjectMetaTraceContext ¶ added in v0.9.4
InjectMetaTraceContext injects the current trace context from ctx directly into the given meta map using W3C Trace Context format (traceparent, tracestate).
This function operates directly on the meta map contents. Use this when you already have the _meta map and want to inject trace context fields into it.
func NewHTTPMiddleware ¶
func NewHTTPMiddleware( config Config, tracerProvider trace.TracerProvider, meterProvider metric.MeterProvider, serverName, transport string, ) types.MiddlewareFunction
NewHTTPMiddleware creates a new HTTP middleware for OpenTelemetry instrumentation. serverName is the name of the MCP server (e.g., "github", "fetch") transport is the backend transport type ("stdio", "sse", or "streamable-http").
func ParseCustomAttributes ¶ added in v0.4.1
ParseCustomAttributes parses a comma-separated list of key=value pairs into a map. Example input: "server_type=production,region=us-east-1,team=platform" Returns a map[string]string that can be converted to resource attributes.
func ResolveServiceName ¶ added in v0.9.4
ResolveServiceName sets the telemetry service name on the config if it has not been explicitly provided. When empty, it derives the name from the workload/server name with the "thv-" prefix (e.g. "thv-fetch").
Types ¶
type Config ¶
type Config struct {
// Endpoint is the OTLP endpoint URL
// +optional
Endpoint string `json:"endpoint,omitempty" yaml:"endpoint,omitempty"`
// ServiceName is the service name for telemetry.
// When omitted, defaults to the server name (e.g., VirtualMCPServer name).
// +optional
ServiceName string `json:"serviceName,omitempty" yaml:"serviceName,omitempty"`
// ServiceVersion is the service version for telemetry.
// When omitted, defaults to the ToolHive version.
// +optional
ServiceVersion string `json:"serviceVersion,omitempty" yaml:"serviceVersion,omitempty"`
// TracingEnabled controls whether distributed tracing is enabled.
// When false, no tracer provider is created even if an endpoint is configured.
// +kubebuilder:default=false
// +optional
TracingEnabled bool `json:"tracingEnabled" yaml:"tracingEnabled"`
// MetricsEnabled controls whether OTLP metrics are enabled.
// When false, OTLP metrics are not sent even if an endpoint is configured.
// This is independent of EnablePrometheusMetricsPath.
// +kubebuilder:default=false
// +optional
MetricsEnabled bool `json:"metricsEnabled" yaml:"metricsEnabled"`
// SamplingRate is the trace sampling rate (0.0-1.0) as a string.
// Only used when TracingEnabled is true.
// Example: "0.05" for 5% sampling.
// +kubebuilder:default="0.05"
// +optional
SamplingRate string `json:"samplingRate,omitempty" yaml:"samplingRate,omitempty"`
// Headers contains authentication headers for the OTLP endpoint.
// +optional
Headers map[string]string `json:"headers,omitempty" yaml:"headers,omitempty"`
// Insecure indicates whether to use HTTP instead of HTTPS for the OTLP endpoint.
// +kubebuilder:default=false
// +optional
Insecure bool `json:"insecure,omitempty" yaml:"insecure,omitempty"`
// EnablePrometheusMetricsPath controls whether to expose Prometheus-style /metrics endpoint.
// The metrics are served on the main transport port at /metrics.
// This is separate from OTLP metrics which are sent to the Endpoint.
// +kubebuilder:default=false
// +optional
EnablePrometheusMetricsPath bool `json:"enablePrometheusMetricsPath,omitempty" yaml:"enablePrometheusMetricsPath,omitempty"`
// EnvironmentVariables is a list of environment variable names that should be
// included in telemetry spans as attributes. Only variables in this list will
// be read from the host machine and included in spans for observability.
// Example: ["NODE_ENV", "DEPLOYMENT_ENV", "SERVICE_VERSION"]
// +optional
EnvironmentVariables []string `json:"environmentVariables,omitempty" yaml:"environmentVariables,omitempty"`
// CustomAttributes contains custom resource attributes to be added to all telemetry signals.
// These are parsed from CLI flags (--otel-custom-attributes) or environment variables
// (OTEL_RESOURCE_ATTRIBUTES) as key=value pairs.
// +optional
CustomAttributes map[string]string `json:"customAttributes,omitempty" yaml:"customAttributes,omitempty"`
// UseLegacyAttributes controls whether legacy (pre-MCP OTEL semconv) attribute names
// are emitted alongside the new standard attribute names. When true, spans include both
// old and new attribute names for backward compatibility with existing dashboards.
// Currently defaults to true; this will change to false in a future release.
// +kubebuilder:default=true
// +optional
UseLegacyAttributes bool `json:"useLegacyAttributes" yaml:"useLegacyAttributes"`
}
Config holds the configuration for OpenTelemetry instrumentation. +kubebuilder:object:generate=true +gendoc
func DefaultConfig ¶
func DefaultConfig() Config
DefaultConfig returns a default telemetry configuration.
func MaybeMakeConfig ¶ added in v0.6.12
func MaybeMakeConfig( otelEndpoint string, otelEnablePrometheusMetricsPath bool, otelTracingEnabled bool, otelMetricsEnabled bool, otelServiceName string, otelSamplingRate float64, otelHeaders []string, otelInsecure bool, otelEnvironmentVariables []string, otelUseLegacyAttributes bool, ) *Config
MaybeMakeConfig creates a new telemetry configuration from the given values. It may return nil if no telemetry is configured.
func (*Config) DeepCopy ¶ added in v0.6.17
DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new Config.
func (*Config) DeepCopyInto ¶ added in v0.6.17
DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.
func (*Config) GetSamplingRateFloat ¶ added in v0.6.17
GetSamplingRateFloat parses the SamplingRate string and returns it as float64. Returns 0.0 if the string is empty or cannot be parsed.
func (Config) GoString ¶ added in v0.9.4
GoString returns the same redacted representation as String(). This prevents credential leakage via the %#v format verb, which calls GoString() instead of String().
func (*Config) SetSamplingRateFromFloat ¶ added in v0.6.17
SetSamplingRateFromFloat sets the SamplingRate from a float64 value.
type FactoryMiddleware ¶ added in v0.2.8
type FactoryMiddleware struct {
// contains filtered or unexported fields
}
FactoryMiddleware wraps telemetry middleware functionality for factory pattern
func (*FactoryMiddleware) Close ¶ added in v0.2.8
func (m *FactoryMiddleware) Close() error
Close cleans up any resources used by the middleware.
func (*FactoryMiddleware) Handler ¶ added in v0.2.8
func (m *FactoryMiddleware) Handler() types.MiddlewareFunction
Handler returns the middleware function used by the proxy.
func (*FactoryMiddleware) PrometheusHandler ¶ added in v0.2.8
func (m *FactoryMiddleware) PrometheusHandler() http.Handler
PrometheusHandler returns the Prometheus metrics handler.
type FactoryMiddlewareParams ¶ added in v0.2.8
type FactoryMiddlewareParams struct {
Config *Config `json:"config"`
ServerName string `json:"server_name"`
Transport string `json:"transport"`
}
FactoryMiddlewareParams represents the parameters for telemetry middleware
type HTTPMiddleware ¶
type HTTPMiddleware struct {
// contains filtered or unexported fields
}
HTTPMiddleware provides OpenTelemetry instrumentation for HTTP requests.
func (*HTTPMiddleware) Handler ¶
func (m *HTTPMiddleware) Handler(next http.Handler) http.Handler
Handler implements the middleware function that wraps HTTP handlers. This middleware should be placed after the MCP parsing middleware in the chain to leverage the parsed MCP data. Note: Panic recovery is handled by the dedicated recovery middleware.
type MetaCarrier ¶ added in v0.9.4
type MetaCarrier struct {
// contains filtered or unexported fields
}
MetaCarrier implements propagation.TextMapCarrier for MCP _meta fields. This enables W3C Trace Context propagation through MCP request params._meta, as recommended by the MCP OpenTelemetry specification.
The carrier wraps a map[string]interface{} (the _meta field from MCP params) and allows the OpenTelemetry propagator to inject/extract traceparent and tracestate headers into/from the map.
func NewMetaCarrier ¶ added in v0.9.4
func NewMetaCarrier(meta map[string]interface{}) *MetaCarrier
NewMetaCarrier creates a new MetaCarrier wrapping the given meta map. If meta is nil, a new empty map is created.
func (*MetaCarrier) Get ¶ added in v0.9.4
func (c *MetaCarrier) Get(key string) string
Get returns the value associated with the passed key.
func (*MetaCarrier) Keys ¶ added in v0.9.4
func (c *MetaCarrier) Keys() []string
Keys lists the keys stored in this carrier.
func (*MetaCarrier) Meta ¶ added in v0.9.4
func (c *MetaCarrier) Meta() map[string]interface{}
Meta returns the underlying meta map. Use this after injection to retrieve the enriched map containing trace context fields.
func (*MetaCarrier) Set ¶ added in v0.9.4
func (c *MetaCarrier) Set(key string, value string)
Set stores the key-value pair.
type Provider ¶
type Provider struct {
// contains filtered or unexported fields
}
Provider encapsulates OpenTelemetry providers and configuration.
func NewProvider ¶
NewProvider creates a new OpenTelemetry provider with the given configuration.
func (*Provider) MeterProvider ¶
func (p *Provider) MeterProvider() metric.MeterProvider
MeterProvider returns the configured meter provider.
func (*Provider) Middleware ¶
func (p *Provider) Middleware(serverName, transport string) types.MiddlewareFunction
Middleware returns an HTTP middleware that instruments requests with OpenTelemetry. serverName is the name of the MCP server (e.g., "github", "fetch") transport is the backend transport type ("stdio", "sse", or "streamable-http").
func (*Provider) PrometheusHandler ¶
PrometheusHandler returns the Prometheus metrics handler if configured. Returns nil if no metrics port is configured.
func (*Provider) TracerProvider ¶
func (p *Provider) TracerProvider() trace.TracerProvider
TracerProvider returns the configured tracer provider.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package providers contains telemetry provider implementations and builder logic
|
Package providers contains telemetry provider implementations and builder logic |
|
otlp
Package otlp provides OpenTelemetry Protocol (OTLP) provider implementations
|
Package otlp provides OpenTelemetry Protocol (OTLP) provider implementations |
|
prometheus
Package prometheus provides Prometheus metric exporter implementation
|
Package prometheus provides Prometheus metric exporter implementation |