telemetry

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2026 License: Apache-2.0 Imports: 15 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package telemetry traces and logs MCP requests.

TraceReceiving starts one server span per request. Span names and parenting follow the MCP semantic conventions; the span carries a subset of their attributes. Install it with Server.AddReceivingMiddleware. Incoming notifications get the same span and parent handling.

The caller owns the OpenTelemetry setup. TraceReceiving takes a TracerProvider and never reads the global provider or propagator. The package configures no exporter, resource, or sampler.

The span continues a trace that the client sends in params._meta, not in transport headers: one HTTP request can carry several MCP messages, and stdio has no headers. The default propagator reads W3C traceparent and tracestate; WithPropagator replaces it, for example with a composite propagator that also reads baggage. A parent from _meta replaces the ambient span, such as an HTTP server span, which becomes a link. Without either, each request starts a new trace. Spans from outbound calls made with the request context nest under the request span.

The ambient span is whatever the handler context carries. Stateless streamable HTTP gives each request its own context. A stateful session keeps the context of the HTTP request that created it, so every later request on the session sees that request's span as ambient.

A gated write runs twice. Protocol 2026-07-28 clients resend the call, so it produces two tools/call spans: one that asks and one that acts. For older clients the SDK shim runs both passes inside one request, which gets one span.

TraceSending installs with AddSendingMiddleware on a client or server. It starts a client span under the supplied context and injects that span into a copy of params._meta. It preserves the concrete SDK request type and unrelated metadata, replacing configured propagation fields. Nil params get metadata-only params. Notification spans end on send completion, without waiting for peer handling. The middleware leaves its input unchanged; SDK code outside middleware may still add protocol metadata.

Log works in both directions, including notifications. Return emit=false from WithLevelFunc to skip a record. Each record has the method or span name as its message, a level, and an outcome: ok, input_required, declined, canceled, tool_error, or error. It does not repeat what the span holds, such as the request attributes, duration, and error. Pass TraceReceiving first and Log second in one AddReceivingMiddleware call, or register logging first and tracing last in separate calls. For sending, use TraceSending in the same position. An OpenTelemetry bridge then sets the record's trace and span IDs. Params and results are logged only through WithPayload, because they can hold secrets.

The MCP semantic conventions are in development and live in the OpenTelemetry GenAI semantic conventions repository. Attribute names may change.

Configuration and callbacks

Both tracing constructors panic with ErrNilTracerProvider for a nil provider and ErrNilPropagator for WithPropagator(nil). Log panics with ErrNilLogger for a nil logger. WithPayload(nil) and WithLevelFunc(nil) panic with ErrNilPayloadFunc and ErrNilLevelFunc respectively.

Outcome.DefaultLevel returns Error for call errors, Warn for tool errors, and Info otherwise, including declined and canceled confirmations. LevelFunc receives the method, outcome, and call or retained tool error. Returning emit=false skips both logging and PayloadFunc. Otherwise the logger's Enabled check runs before payload work. Tool errors received from a peer have no retained Go error, so their cause can be nil.

PayloadFunc receives nil params for a request without params and a plain nil result when the call failed. Payloads are off by default; the caller selects and redacts fields. The result returned to the SDK is not changed.

Errors and SDK details

JSON-RPC errors set error.type and rpc.response.status_code to the code. Other call errors use semconv.ErrorType. IsError tool results use tool_error; their retained Go error, when present, becomes an exception event. All mark the span failed.

MCP keys are declared locally because semconv v1.42.0 moved them to the GenAI conventions repository. These spans omit jsonrpc.request.id, mcp.protocol.version, and network attributes.

Receiving params may be typed nil; normalize them before calling GetMeta. Sending copies only the top-level request, params, and metadata map. Nested arguments and content remain shared and must not be mutated by injection. A typed-nil params pointer becomes a fresh value of its concrete type.

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNilTracerProvider reports a tracing constructor without a provider.
	ErrNilTracerProvider = errors.New("nil tracer provider")
	// ErrNilPropagator reports a nil propagator passed to WithPropagator.
	ErrNilPropagator = errors.New("nil propagator")
	// ErrNilLogger reports a Log call without a logger.
	ErrNilLogger = errors.New("nil logger")
	// ErrNilLevelFunc reports a nil func passed to WithLevelFunc.
	ErrNilLevelFunc = errors.New("nil level func")
	// ErrNilPayloadFunc reports a nil func passed to WithPayload.
	ErrNilPayloadFunc = errors.New("nil payload func")
)

Functions

func Log

func Log(l *slog.Logger, opts ...LogOption) mcp.Middleware

Log logs requests and notifications in either middleware direction.

func TraceReceiving

func TraceReceiving(tp trace.TracerProvider, opts ...Option) mcp.Middleware

TraceReceiving traces incoming messages using the parent in params._meta.

func TraceSending

func TraceSending(tp trace.TracerProvider, opts ...Option) mcp.Middleware

TraceSending traces outgoing messages and injects their span context.

Types

type LevelFunc

type LevelFunc func(
	method string, outcome Outcome, err error,
) (level slog.Level, emit bool)

LevelFunc selects severity and whether to emit the record.

type LogOption

type LogOption func(*logConfig)

LogOption configures Log.

func WithLevelFunc

func WithLevelFunc(f LevelFunc) LogOption

WithLevelFunc overrides severity and emission; nil panics.

func WithPayload

func WithPayload(f PayloadFunc) LogOption

WithPayload adds caller-selected attributes; nil panics.

type Option

type Option func(*config)

Option configures TraceReceiving and TraceSending.

func WithPropagator

func WithPropagator(p propagation.TextMapPropagator) Option

WithPropagator selects propagation through params._meta.

type Outcome

type Outcome string

Outcome describes how an MCP request completed.

const (
	OutcomeOK            Outcome = "ok"
	OutcomeInputRequired Outcome = "input_required"
	OutcomeDeclined      Outcome = "declined"
	OutcomeCanceled      Outcome = "canceled"
	OutcomeToolError     Outcome = "tool_error"
	OutcomeError         Outcome = "error"
)

Request outcomes logged under the outcome key.

func (Outcome) DefaultLevel

func (o Outcome) DefaultLevel() slog.Level

DefaultLevel maps call errors to Error, tool errors to Warn, others to Info.

type PayloadFunc

type PayloadFunc func(method string, p mcp.Params, res mcp.Result) []slog.Attr

PayloadFunc selects request and result attributes to log.

Jump to

Keyboard shortcuts

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