serviceutil

package
v0.0.0 Latest Latest
Warning

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

Go to latest
Published: Oct 5, 2026 License: Apache-2.0 Imports: 0 Imported by: 0

Documentation

Overview

Package serviceutil provides authentication utilities for MCP services.

Package serviceutil provides shared utilities for MCP services. This package centralizes common helper functions to avoid duplication across service implementations.

Package serviceutil provides HTTP utilities for MCP services.

Package serviceutil provides OpenTelemetry utilities for MCP services.

Package serviceutil provides HTTP routing utilities for MCP services.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrMethodNotAllowed = errors.New("method not allowed")
	ErrInvalidPath      = errors.New("invalid path")
	ErrInvalidAction    = errors.New("invalid action")
)

Predefined errors for routing validation.

Functions

func AudienceMatches

func AudienceMatches(audClaim any, expected string) bool

AudienceMatches validates if the JWT audience claim matches the expected value. It handles both string and string slice audience claims as per JWT specifications.

func BoolEnv

func BoolEnv(key string) (bool, bool)

BoolEnv parses a boolean environment variable. It returns the parsed boolean value and true if parsing succeeded. Returns false, false if the variable is not set or parsing failed.

func CaptureTraceContext

func CaptureTraceContext(ctx context.Context) map[string]string

CaptureTraceContext serializes the active trace context for async handoffs.

func ConfigureOTelDiagnostics

func ConfigureOTelDiagnostics()

ConfigureOTelDiagnostics routes OpenTelemetry SDK internal errors, such as failed OTLP exports, to the service log and a Prometheus counter, so a silently unreachable collector is visible. It is safe to call repeatedly.

func ConfigureTracePropagation

func ConfigureTracePropagation()

ConfigureTracePropagation enables W3C trace context and baggage propagation.

func ContextWithTraceContext

func ContextWithTraceContext(ctx context.Context, headers map[string]string) context.Context

ContextWithTraceContext extracts serialized trace context into ctx.

func DiscoverOIDCJWKSURL

func DiscoverOIDCJWKSURL(ctx context.Context, issuer string) (string, error)

DiscoverOIDCJWKSURL resolves an issuer's OIDC discovery document and returns its jwks_uri. The caller can use an explicitly configured URL instead when a provider does not publish standard discovery metadata.

func DiscoverOIDCJWKSURLWithRetry

func DiscoverOIDCJWKSURLWithRetry(ctx context.Context, issuer string, attempts int, initialBackoff time.Duration) (string, error)

DiscoverOIDCJWKSURLWithRetry retries transient discovery failures with exponential backoff, so a service starting while its identity provider is briefly unreachable does not crash-loop on the first attempt.

func EnvDuration

func EnvDuration(key string, fallback time.Duration) time.Duration

EnvDuration parses a duration environment variable, falling back when unset or invalid.

func EnvInt

func EnvInt(key string, fallback int) int

EnvInt parses an integer environment variable, falling back when unset or invalid.

func EnvOr

func EnvOr(key, fallback string) string

EnvOr returns the value of an environment variable or a fallback if not set. If the environment variable is set to a non-empty value, it returns that value. Otherwise, it returns the provided fallback value.

func ExtractBearer

func ExtractBearer(auth string) string

ExtractBearer extracts the JWT token from an Authorization header. It expects the format "Bearer <token>" and returns the token part. Returns empty string if the format is invalid.

func ExtractKafkaHeaders

func ExtractKafkaHeaders(ctx context.Context, headers []kafka.Header) context.Context

ExtractKafkaHeaders extracts trace context from Kafka headers into ctx.

func ExtractNamespacedResourceDelete

func ExtractNamespacedResourceDelete(r *http.Request, prefix string) (namespace, name string, err error)

ExtractNamespacedResourceDelete validates DELETE /{prefix}{namespace}/{name} (two path segments after prefix).

func ExtractToken

func ExtractToken(headerName, value string) string

ExtractToken extracts a token from a header value, handling Bearer prefix. If the headerName is "authorization", it only extracts Bearer tokens. Otherwise, it returns the raw value or the Bearer-extracted token if present.

func FormatTokenHeaderValue

func FormatTokenHeaderValue(headerName, token string) string

FormatTokenHeaderValue formats a token for a specific header. If the header is "authorization", it returns "Bearer <token>". Otherwise, it returns the token as-is.

func InitTracer

func InitTracer(serviceName string) (func(context.Context) error, error)

InitTracer initializes OpenTelemetry tracing from OTEL_* environment variables.

func InjectKafkaHeaders

func InjectKafkaHeaders(ctx context.Context, headers []kafka.Header) []kafka.Header

InjectKafkaHeaders appends the active trace context to Kafka headers.

func IsActionEnabled

func IsActionEnabled(action string) bool

IsActionEnabled returns true for "enable" and "unrevoke" actions, false for "disable" and "revoke".

func IsProbePath

func IsProbePath(r *http.Request) bool

IsProbePath reports whether the request is a health, readiness, or metrics probe. Probes are excluded from tracing so they do not drown failure traces.

func LogRequests

func LogRequests(next http.Handler) http.Handler

LogRequests logs HTTP method, path, status, and duration for each request.

func LogfCtx

func LogfCtx(ctx context.Context, format string, args ...any)

LogfCtx logs like log.Printf and appends trace_id/span_id when ctx carries a span.

func NormalizePublicAPIPath

func NormalizePublicAPIPath(path string) string

NormalizePublicAPIPath strips the public API version prefix so handlers can match on /runtime/... paths whether the request arrived as /api/v1/runtime/* or legacy /api/runtime/*.

func OTLPTraceOptions

func OTLPTraceOptions(endpoint string) []otlptracehttp.Option

OTLPTraceOptions configures OTLP HTTP exporter options. It sets up the endpoint URL and configures secure/insecure connections based on whether the endpoint uses HTTPS or HTTP.

func RecordSpanFailure

func RecordSpanFailure(ctx context.Context, operation, reason string, status int, err error)

RecordSpanFailure marks the active span as failed so error spans are searchable. operation and reason must be bounded, non-secret identifiers (never tokens, headers, or MCP tool arguments). status is the HTTP status returned to the caller, or 0 when unknown. A nil err is allowed.

func SpanIDFromContext

func SpanIDFromContext(ctx context.Context) string

SpanIDFromContext returns the active span ID, or an empty string when the context does not carry a valid span.

func StartMetricsServer

func StartMetricsServer(port string) (func(context.Context) error, <-chan error)

StartMetricsServer starts a Prometheus metrics server with /metrics and /health.

func TraceIDFromContext

func TraceIDFromContext(ctx context.Context) string

TraceIDFromContext returns the active span trace ID, or an empty string when the context does not carry a valid trace.

func TraceLogSuffix

func TraceLogSuffix(ctx context.Context) string

TraceLogSuffix returns " trace_id=<id> span_id=<id>" for the active span, or an empty string when there is none. Append it to log lines so logs can be joined to traces by ID (for example Loki to Tempo in Grafana).

func TraceableRequest

func TraceableRequest(r *http.Request) bool

TraceableRequest is an otelhttp filter that skips probe requests.

func WriteJSON

func WriteJSON(w http.ResponseWriter, status int, payload any)

WriteJSON writes a JSON response with the specified status code. It sets appropriate Content-Type headers and handles JSON marshaling errors. It first marshals the payload to check for encoding errors before writing headers.

Types

type RequestMetrics

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

RequestMetrics records request throughput, errors, and latency for service HTTP handlers using bounded service, operation, status, and server labels.

func DefaultRequestMetrics

func DefaultRequestMetrics() *RequestMetrics

func NewRequestMetrics

func NewRequestMetrics(registerer prometheus.Registerer) *RequestMetrics

func (*RequestMetrics) Middleware

func (m *RequestMetrics) Middleware(service string, next http.Handler) http.Handler

Middleware records requests by ServeMux's matched route pattern. Unmatched paths share one label value so arbitrary URLs never become metric labels.

func (*RequestMetrics) Record

func (m *RequestMetrics) Record(service, operation string, status int, server string, duration time.Duration)

type RouteParams

type RouteParams struct {
	Namespace string
	Name      string
	Action    string
}

RouteParams extracts path parameters from HTTP request paths. It provides a structured way to handle path-based routing without manual string manipulation.

func ExtractGrantActionParams

func ExtractGrantActionParams(r *http.Request, prefix string) (RouteParams, error)

Expected path format: /api/runtime/grants/{namespace}/{name}/{action} where action is either "disable" or "enable".

func ExtractSessionActionParams

func ExtractSessionActionParams(r *http.Request, prefix string) (RouteParams, error)

ExtractSessionActionParams extracts parameters from session toggle paths. Expected path format: /api/runtime/sessions/{namespace}/{name}/{action} where action is either "revoke" or "unrevoke".

Jump to

Keyboard shortcuts

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