telemetry

package
v0.59.0 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2025 License: Apache-2.0 Imports: 29 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// MCP Tool attributes - Tool execution specific
	AttrMCPToolName     = "mcp.tool.name"           // Tool identifier (e.g., "internet_search")
	AttrMCPToolCategory = "mcp.tool.category"       // Tool category (e.g., "search_discovery")
	AttrMCPToolSuccess  = "mcp.tool.result.success" // Execution success (boolean)
	AttrMCPToolError    = "mcp.tool.result.error"   // Error message if failed (string)

	// MCP Session attributes - Session tracking and correlation
	AttrMCPSessionID         = "mcp.session.id"          // Unique session identifier
	AttrMCPSessionTimeout    = "mcp.session.timeout"     // Session timeout in seconds
	AttrMCPSessionDuration   = "mcp.session.duration"    // Session duration in seconds (on termination)
	AttrMCPSessionToolCount  = "mcp.session.tool_count"  // Number of tools executed in session
	AttrMCPSessionErrorCount = "mcp.session.error_count" // Number of failed tool executions
	AttrMCPTransport         = "mcp.transport"           // Transport type (stdio/http/sse)

	// LLM/GenAI attributes - LLM invocation tracking
	AttrLLMSystem        = "llm.system"              // LLM provider (e.g., "anthropic", "openai")
	AttrLLMModel         = "llm.model"               // Model identifier (e.g., "claude-sonnet-4-5")
	AttrLLMRequestType   = "llm.request.type"        // Request type (e.g., "chat", "completion")
	AttrLLMInputTokens   = "llm.usage.input_tokens"  // Input tokens consumed
	AttrLLMOutputTokens  = "llm.usage.output_tokens" // Output tokens generated
	AttrLLMCachedTokens  = "llm.usage.cached_tokens" // Cached tokens used
	AttrLLMTotalTokens   = "llm.usage.total_tokens"  // Total tokens (input + output)
	AttrLLMCostEstimated = "llm.cost.estimated"      // Estimated cost in USD
	AttrLLMTemperature   = "llm.temperature"         // Temperature setting
	AttrLLMMaxTokens     = "llm.max_tokens"          // Max tokens limit
	AttrLLMFinishReason  = "llm.finish_reason"       // Completion reason (e.g., "stop", "length")

	// Cache attributes - Cache operation tracking
	AttrCacheHit       = "cache.hit"       // Cache hit (boolean)
	AttrCacheKey       = "cache.key"       // Cache key (sanitised)
	AttrCacheOperation = "cache.operation" // Cache operation (get/set/delete)

	// Security attributes - Security framework tracking
	AttrSecurityRuleMatched = "security.rule.matched" // Rule name that matched
	AttrSecurityAction      = "security.action"       // Security action (allow/block/warn)
	AttrSecurityContentSize = "security.content.size" // Size of content scanned
)
View Source
const (
	SpanNameSession       = "mcp.session"      // Session span (parent for all tool calls)
	SpanNameToolExecute   = "mcp.tool.execute" // Tool execution span
	SpanNameHTTPClient    = "http.client"      // HTTP client request span
	SpanNameSecurityCheck = "security.check"   // Security framework check span
	SpanNameCacheOp       = "cache"            // Cache operation span
	SpanNameLLMExecute    = "llm.execute"      // LLM invocation span
)

Span names for consistent span naming across the application

Variables

This section is empty.

Functions

func CategoriseToolError

func CategoriseToolError(err error) string

CategoriseToolError maps errors to metric-friendly categories

func ContextWithSessionID

func ContextWithSessionID(ctx context.Context, sessionID string) context.Context

ContextWithSessionID adds a session ID to the context

func EndSessionSpan

func EndSessionSpan(span trace.Span, toolCount int, errorCount int, duration int64)

EndSessionSpan clears global session data The session span was already ended in StartSessionSpan

func EndToolSpan

func EndToolSpan(span trace.Span, err error)

EndToolSpan ends a tool execution span with success or error

func GenerateSessionID

func GenerateSessionID() string

GenerateSessionID generates a new unique session ID

func GetMeter

func GetMeter() metric.Meter

GetMeter returns the global meter instance

func GetTextMapPropagator

func GetTextMapPropagator() propagation.TextMapPropagator

GetTextMapPropagator returns the global text map propagator for extracting/injecting trace context

func GetTracer

func GetTracer() trace.Tracer

GetTracer returns the global tracer instance Returns a noop tracer if not initialised

func InitMetrics

func InitMetrics(logger *logrus.Logger) (func() error, error)

InitMetrics initialises the OpenTelemetry meter provider Should be called after InitTracer in main.go Returns a shutdown function and an error if initialisation fails

func InitTracer

func InitTracer(logger *logrus.Logger) (func() error, error)

InitTracer initialises the OpenTelemetry tracer based on environment variables Returns a shutdown function and an error if initialisation fails. The application can continue with a noop tracer even if initialisation fails.

func IsEnabled

func IsEnabled() bool

IsEnabled returns true if tracing is enabled

func IsMetricsEnabled

func IsMetricsEnabled() bool

IsMetricsEnabled returns true if metrics collection is enabled

func IsToolTracingDisabled

func IsToolTracingDisabled(toolName string) bool

IsToolTracingDisabled returns true if tracing is disabled for the specified tool via the MCP_TRACING_DISABLED_TOOLS environment variable

func RecordCacheOperation

func RecordCacheOperation(ctx context.Context, toolName string, operation string, hit bool)

RecordCacheOperation records a cache operation metric

func RecordSecurityCheck

func RecordSecurityCheck(ctx context.Context, action string, sourceType string, durationMs float64)

RecordSecurityCheck records a security framework check metric

func RecordSecurityRuleTrigger

func RecordSecurityRuleTrigger(ctx context.Context, ruleName string, action string)

RecordSecurityRuleTrigger records a security rule trigger

func RecordSessionEnd

func RecordSessionEnd(ctx context.Context, transport string, durationSeconds float64, toolCount int64)

RecordSessionEnd decrements active sessions and records duration and tool count

func RecordSessionStart

func RecordSessionStart(ctx context.Context, transport string)

RecordSessionStart increments active sessions counter

func RecordToolCall

func RecordToolCall(ctx context.Context, toolName string, transport string, success bool, durationMs float64)

RecordToolCall records a tool invocation metric

func RecordToolError

func RecordToolError(ctx context.Context, toolName string, errorType string)

RecordToolError records a categorised tool error

func SanitiseArguments

func SanitiseArguments(args map[string]any, toolName string) string

SanitiseArguments sanitises tool arguments by removing sensitive values Returns a JSON string of the sanitised arguments, or an error message if serialisation fails toolName is optional - if provided, enables tool-specific redaction rules

func SanitiseCacheKey

func SanitiseCacheKey(key string) string

SanitiseCacheKey sanitises cache keys to avoid leaking sensitive information

func SanitiseURL

func SanitiseURL(rawURL string) string

SanitiseURL removes sensitive query parameters and credentials from URLs

func SessionIDFromContext

func SessionIDFromContext(ctx context.Context) string

SessionIDFromContext retrieves the session ID from the context

func StartSessionSpan

func StartSessionSpan(ctx context.Context, sessionID string, transport string) (context.Context, trace.Span)

StartSessionSpan creates a session span that acts as parent for all tool spans The span is ended immediately to ensure it exports before child tool spans Returns a noop span since the real span is already ended

func StartToolSpan

func StartToolSpan(ctx context.Context, toolName string, args map[string]any) (context.Context, trace.Span)

StartToolSpan creates a new span for tool execution If a session span context exists, tool spans will be children of the session span Returns the span and a modified context. The caller MUST call span.End() when done.

func TruncateString

func TruncateString(s string, maxLen int) string

TruncateString truncates a string to a maximum length with ellipsis

func WrapHTTPClient

func WrapHTTPClient(client *http.Client) *http.Client

WrapHTTPClient wraps an existing http.Client's transport with OTEL instrumentation Modifies the client in-place and returns it for convenience

func WrapHTTPTransport

func WrapHTTPTransport(transport http.RoundTripper) http.RoundTripper

WrapHTTPTransport wraps an existing http.Transport with OTEL instrumentation This preserves any existing configuration (proxy, timeouts, etc.) whilst adding tracing

Types

This section is empty.

Jump to

Keyboard shortcuts

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