tracing

package
v0.4.5 Latest Latest
Warning

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

Go to latest
Published: Jul 23, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package tracing provides OpenTelemetry OTLP trace export for the MCP Gateway. This file defines custom and non-semconv attribute keys for gen_ai and MCP spans. The semconv-derived GenAI attribute keys (GenAIToolName, GenAIOperationName, etc.) are defined in semconv.go, which is the single file that imports go.opentelemetry.io/otel/semconv/v1.41.0.

Package tracing provides OpenTelemetry OTLP trace export for the MCP Gateway. This file provides HTTP handler wrapping helpers.

Package tracing provides OpenTelemetry OTLP trace export for the MCP Gateway.

When an OTLP endpoint is configured (via config or OTEL_EXPORTER_OTLP_ENDPOINT), this package initializes a real tracer provider that exports spans over HTTP. When no endpoint is configured, a noop tracer provider is used, adding zero overhead.

Usage:

tp, err := tracing.InitProvider(ctx, cfg.Gateway.Tracing)
if err != nil {
    return err
}
defer tp.Shutdown(ctx)

Once initialized, obtain a tracer with:

tracer := otel.Tracer("github.com/github/gh-aw-mcpg")

Package tracing provides OpenTelemetry OTLP trace export for the MCP Gateway. This file is the single source of truth for go.opentelemetry.io/otel/semconv/v1.41.0 imports in the tracing package. All callers inside and outside this package should reference these re-exports so that upgrading semconv only requires editing this file.

Package tracing provides OpenTelemetry OTLP trace export for the MCP Gateway. This file provides span error recording helpers and span start constructors.

Index

Constants

View Source
const (
	// MCPMethod is the JSON-RPC method name (e.g. "tools/call").
	MCPMethod = attribute.Key("mcp.method")

	// MCPResponseStatus is the conceptual HTTP status of the proxied MCP response.
	// Used on internal MCP spans (e.g. mcp.tool_call) instead of the HTTP-specific
	// semconv.HTTPResponseStatusCodeKey, which is semantically reserved for HTTP spans.
	MCPResponseStatus = attribute.Key("mcp.response.status")

	// RateLimitHit indicates a rate limit was triggered.
	RateLimitHit = attribute.Key("rate_limit.hit")

	// GatewayTag is the routing mode tag (unified/routed).
	GatewayTag = attribute.Key("gateway.tag")
)

MCP-specific attribute keys (no gen_ai equivalent in the spec).

View Source
const (
	// HTTPRequestMethodKey is the HTTP request method.
	HTTPRequestMethodKey = semconv.HTTPRequestMethodKey
	// HTTPRouteKey is the matched HTTP route template.
	HTTPRouteKey = semconv.HTTPRouteKey
	// HTTPResponseStatusCodeKey is the HTTP response status code.
	HTTPResponseStatusCodeKey = semconv.HTTPResponseStatusCodeKey
	// URLPathKey is the full URL path.
	URLPathKey = semconv.URLPathKey
	// ServerAddressKey is the server domain name or IP address.
	ServerAddressKey = semconv.ServerAddressKey
)

HTTP and URL semantic convention attribute keys.

View Source
const (
	// GenAIToolName is the name of the tool utilized by the agent.
	GenAIToolName = semconv.GenAIToolNameKey
	// GenAIOperationName is the name of the operation being performed.
	GenAIOperationName = semconv.GenAIOperationNameKey
	// GenAIConversationID is the unique identifier for a conversation (session).
	GenAIConversationID = semconv.GenAIConversationIDKey
	// GenAIAgentName is the human-readable name of the GenAI agent.
	GenAIAgentName = semconv.GenAIAgentNameKey
	// GenAIAgentID is the unique identifier of the GenAI agent (server ID).
	GenAIAgentID = semconv.GenAIAgentIDKey
)

GenAI semantic convention attribute keys (semconv/v1.41.0). gen_ai.system was removed from the spec; see GenAISystem in genai_attrs.go.

View Source
const (
	// ErrorTypeKey is the attribute key for error.type.
	ErrorTypeKey = semconv.ErrorTypeKey
)

Error semantic convention keys.

View Source
const GenAISystem = attribute.Key("gen_ai.system")

GenAISystem identifies the GenAI system family for MCP spans. gen_ai.system was removed from semconv/v1.41.0; the key string is preserved for wire compatibility with observability backends that still expect it.

View Source
const SchemaURL = semconv.SchemaURL

SchemaURL is the semconv schema URL for this semantic conventions version.

Variables

This section is empty.

Functions

func ErrorType added in v0.4.0

func ErrorType(err error) attribute.KeyValue

ErrorType returns the error.type attribute KeyValue for err. It wraps semconv.ErrorType so callers outside this package can use it without importing the semconv package directly.

func GetCachedOrGlobal added in v0.2.26

func GetCachedOrGlobal(cached trace.Tracer) trace.Tracer

GetCachedOrGlobal returns cached if non-nil, otherwise falls back to the global tracer.

func ParentContext added in v0.2.14

func ParentContext(ctx context.Context, cfg *config.TracingConfig) context.Context

ParentContext returns a context carrying the W3C remote parent span context from the configured traceId and spanId (spec §4.1.3.6). Exported for use at startup to build the root span's parent context.

func RecordSpanError added in v0.3.21

func RecordSpanError(span oteltrace.Span, err error, msg string)

RecordSpanError records err on span with a stack trace and sets the span status to Error. Use this instead of calling RecordError + SetStatus individually to ensure consistent behavior (stack traces enabled, status always set) across all error paths.

func RecordSpanErrorOnAll added in v0.3.21

func RecordSpanErrorOnAll(err error, msg string, spans ...oteltrace.Span)

RecordSpanErrorOnAll records err on all provided spans with a stack trace and sets their status to Error. Useful when both a parent and child span must reflect the same failure.

func RecordSpanErrorSafe added in v0.4.0

func RecordSpanErrorSafe(span oteltrace.Span, internalErr error, publicMsg string)

RecordSpanErrorSafe records a scrubbed error on span for security-sensitive paths. internalErr is the actual error (logged and returned to the caller via normal channels); publicMsg is the message recorded on the span and set as the status description. This prevents internal error details from leaking to trace backends, which may be operated by third parties.

func ServiceName added in v0.4.0

func ServiceName(val string) attribute.KeyValue

ServiceName returns the service.name attribute KeyValue for val.

func ServiceVersion added in v0.4.0

func ServiceVersion(val string) attribute.KeyValue

ServiceVersion returns the service.version attribute KeyValue for val.

func StartBackendExecuteSpan added in v0.3.21

func StartBackendExecuteSpan(ctx context.Context, tracer oteltrace.Tracer, serverID, toolName string) (context.Context, oteltrace.Span)

StartBackendExecuteSpan starts the backend execution child span for the unified server. It is a client-kind span that covers the actual RPC to the backend MCP server.

func StartDIFCPipelineSpan added in v0.3.21

func StartDIFCPipelineSpan(ctx context.Context, tracer oteltrace.Tracer, toolName, urlPath string) (context.Context, oteltrace.Span)

StartDIFCPipelineSpan starts the DIFC pipeline OTEL span for the proxy handler. It covers all phases of the DIFC pipeline for a single proxied request.

func StartProxyForwardSpan added in v0.3.21

func StartProxyForwardSpan(ctx context.Context, tracer oteltrace.Tracer, toolName, urlPath, serverAddress string) (context.Context, oteltrace.Span)

StartProxyForwardSpan starts the backend forward child span for the proxy handler. It is a client-kind span that covers the HTTP request forwarded to the upstream API.

func StartToolCallSpan added in v0.3.21

func StartToolCallSpan(ctx context.Context, tracer oteltrace.Tracer, serverID, toolName string) (context.Context, oteltrace.Span)

StartToolCallSpan starts the outer tool-call OTEL span with standard gen_ai attributes. It covers the full tool call lifecycle (all DIFC pipeline phases) in unified server mode.

func Tracer

func Tracer() trace.Tracer

Tracer returns the global MCP gateway tracer. This is a convenience wrapper around otel.Tracer for packages that don't hold a reference to the Provider.

func WrapHTTPHandler

func WrapHTTPHandler(next http.Handler, spanName string, extraAttrs ...attribute.KeyValue) http.Handler

WrapHTTPHandler wraps an http.Handler with an OpenTelemetry server span. A span named spanName is created for every request, with http.request.method and http.route set automatically. Extra attrs are merged in.

Incoming W3C traceparent/tracestate headers are extracted so that an agent-originated trace is continued; if no such headers are present a fresh root span (and new trace ID) is created automatically.

This is a low-level helper used by both the MCP gateway middleware and the GitHub API proxy. Callers that need session-level attributes (e.g. session.id) should add them as extra attrs or extend the context themselves.

Types

type CachedTracer added in v0.3.14

type CachedTracer struct {
	Tracer trace.Tracer
}

CachedTracer holds an optional pre-initialized tracer and falls back to the global tracer when the cached tracer is nil.

func (CachedTracer) GetTracer added in v0.3.14

func (ct CachedTracer) GetTracer() trace.Tracer

GetTracer returns the cached tracer when set, otherwise the global tracer.

type Provider

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

Provider wraps an OpenTelemetry TracerProvider and provides a Shutdown method.

func InitProvider

func InitProvider(ctx context.Context, cfg *config.TracingConfig) (*Provider, error)

InitProvider initializes the global OpenTelemetry tracer provider. When no endpoint is configured, a noop provider is installed (zero overhead). When one or more endpoints are configured, an OTLP/HTTP exporter is created for each endpoint and the SDK tracer provider is registered as the global provider. Multiple endpoints (from GH_AW_OTLP_ENDPOINTS) are supported via a fan-out exporter so that every backend receives complete gateway traces.

In both cases a W3C TraceContext propagator is registered globally so that incoming traceparent/tracestate headers are honoured by all HTTP middleware.

The returned Provider must be shut down on application exit to flush buffered spans.

func (*Provider) IsEnabled added in v0.3.26

func (p *Provider) IsEnabled() bool

IsEnabled reports whether the provider has a real SDK (non-noop) exporter active.

func (*Provider) Resource added in v0.3.26

func (p *Provider) Resource() *resource.Resource

Resource returns the OTel resource associated with this provider, or nil if the provider is a noop (no OTLP endpoint configured).

func (*Provider) Shutdown

func (p *Provider) Shutdown(ctx context.Context) error

Shutdown flushes and shuts down the tracer provider. For noop providers this is a no-op. Must be called on application exit.

func (*Provider) Tracer

func (p *Provider) Tracer() trace.Tracer

Tracer returns the tracer for the MCP gateway instrumentation scope.

Jump to

Keyboard shortcuts

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