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 ¶
- Variables
- func AudienceMatches(audClaim any, expected string) bool
- func BoolEnv(key string) (bool, bool)
- func CaptureTraceContext(ctx context.Context) map[string]string
- func ConfigureOTelDiagnostics()
- func ConfigureTracePropagation()
- func ContextWithTraceContext(ctx context.Context, headers map[string]string) context.Context
- func DiscoverOIDCJWKSURL(ctx context.Context, issuer string) (string, error)
- func DiscoverOIDCJWKSURLWithRetry(ctx context.Context, issuer string, attempts int, initialBackoff time.Duration) (string, error)
- func EnvDuration(key string, fallback time.Duration) time.Duration
- func EnvInt(key string, fallback int) int
- func EnvOr(key, fallback string) string
- func ExtractBearer(auth string) string
- func ExtractKafkaHeaders(ctx context.Context, headers []kafka.Header) context.Context
- func ExtractNamespacedResourceDelete(r *http.Request, prefix string) (namespace, name string, err error)
- func ExtractToken(headerName, value string) string
- func FormatTokenHeaderValue(headerName, token string) string
- func InitTracer(serviceName string) (func(context.Context) error, error)
- func InjectKafkaHeaders(ctx context.Context, headers []kafka.Header) []kafka.Header
- func IsActionEnabled(action string) bool
- func IsProbePath(r *http.Request) bool
- func LogRequests(next http.Handler) http.Handler
- func LogfCtx(ctx context.Context, format string, args ...any)
- func NormalizePublicAPIPath(path string) string
- func OTLPTraceOptions(endpoint string) []otlptracehttp.Option
- func RecordSpanFailure(ctx context.Context, operation, reason string, status int, err error)
- func SpanIDFromContext(ctx context.Context) string
- func StartMetricsServer(port string) (func(context.Context) error, <-chan error)
- func TraceIDFromContext(ctx context.Context) string
- func TraceLogSuffix(ctx context.Context) string
- func TraceableRequest(r *http.Request) bool
- func WriteJSON(w http.ResponseWriter, status int, payload any)
- type RequestMetrics
- type RouteParams
Constants ¶
This section is empty.
Variables ¶
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 ¶
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 ¶
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 ¶
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 ¶
ContextWithTraceContext extracts serialized trace context into ctx.
func DiscoverOIDCJWKSURL ¶
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 ¶
EnvDuration parses a duration environment variable, falling back when unset or invalid.
func EnvOr ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
InitTracer initializes OpenTelemetry tracing from OTEL_* environment variables.
func InjectKafkaHeaders ¶
InjectKafkaHeaders appends the active trace context to Kafka headers.
func IsActionEnabled ¶
IsActionEnabled returns true for "enable" and "unrevoke" actions, false for "disable" and "revoke".
func IsProbePath ¶
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 ¶
LogRequests logs HTTP method, path, status, and duration for each request.
func NormalizePublicAPIPath ¶
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 ¶
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 ¶
SpanIDFromContext returns the active span ID, or an empty string when the context does not carry a valid span.
func StartMetricsServer ¶
StartMetricsServer starts a Prometheus metrics server with /metrics and /health.
func TraceIDFromContext ¶
TraceIDFromContext returns the active span trace ID, or an empty string when the context does not carry a valid trace.
func TraceLogSuffix ¶
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 ¶
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 ¶
Middleware records requests by ServeMux's matched route pattern. Unmatched paths share one label value so arbitrary URLs never become metric labels.
type RouteParams ¶
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".