Skip to content

datarobot_genai.drmcpbase.datarobot_otel_metrics

datarobot_otel_metrics

Bootstrap an OTel SDK MeterProvider so metrics actually export.

Sibling to datarobot_otel.py (which does the same for traces). genai wires OTel traces + logs but no metrics provider, so SLI counters/histograms emitted via opentelemetry.metrics.get_meter(...) go to the default no-op provider and never leave the process. Call :func:bootstrap_metrics_provider once at startup to point the global MeterProvider at an OTLP/HTTP collector.

Follows the same safety contract as the trace bootstrap: a no-op when no endpoint is configured, idempotent, and never raises.

bootstrap_metrics_provider

bootstrap_metrics_provider(endpoint: str | None = None, *, headers: dict[str, str] | None = None, export_interval_ms: int | None = None, resource_attributes: dict[str, Any] | None = None) -> bool

Install a global OTLP/HTTP MeterProvider; return whether it installed.

When endpoint is not passed, the exporter resolves it the standard OTLP way: OTEL_EXPORTER_OTLP_METRICS_ENDPOINT if set, otherwise the shared OTEL_EXPORTER_OTLP_ENDPOINT collector base URL (the same one traces and logs use) with /v1/metrics appended. Headers likewise come from OTEL_EXPORTER_OTLP_HEADERS unless passed explicitly, so a process that already configured OTel for traces needs nothing extra for metrics.

Returns False (silently) when no endpoint is configured (the local-dev / CI shape), when already installed in this process, or when setup raises.

resource_attributes are merged over the default service.name so a host process (e.g. the MCP server) can stamp metrics with the same resource identity it uses for traces and logs.

Source code in datarobot_genai/drmcpbase/datarobot_otel_metrics.py
def bootstrap_metrics_provider(
    endpoint: str | None = None,
    *,
    headers: dict[str, str] | None = None,
    export_interval_ms: int | None = None,
    resource_attributes: dict[str, Any] | None = None,
) -> bool:
    """Install a global OTLP/HTTP ``MeterProvider``; return whether it installed.

    When ``endpoint`` is not passed, the exporter resolves it the standard OTLP
    way: ``OTEL_EXPORTER_OTLP_METRICS_ENDPOINT`` if set, otherwise the shared
    ``OTEL_EXPORTER_OTLP_ENDPOINT`` collector *base* URL (the same one traces
    and logs use) with ``/v1/metrics`` appended. Headers likewise come from
    ``OTEL_EXPORTER_OTLP_HEADERS`` unless passed explicitly, so a process that
    already configured OTel for traces needs nothing extra for metrics.

    Returns ``False`` (silently) when no endpoint is configured (the local-dev /
    CI shape), when already installed in this process, or when setup raises.

    ``resource_attributes`` are merged over the default ``service.name`` so a
    host process (e.g. the MCP server) can stamp metrics with the same resource
    identity it uses for traces and logs.
    """
    if _STATE["installed"]:
        return False

    if not (
        endpoint
        or os.environ.get("OTEL_EXPORTER_OTLP_METRICS_ENDPOINT")
        or os.environ.get("OTEL_EXPORTER_OTLP_ENDPOINT")
    ):
        # Without this guard the exporter would fall back to its built-in
        # localhost default and every unconfigured process would try to export.
        logger.info(
            "Skipping OTel MeterProvider bootstrap: no OTEL_EXPORTER_OTLP_"
            "(METRICS_)ENDPOINT set and no endpoint passed."
        )
        return False

    try:
        exporter_kwargs: dict[str, Any] = {}
        if endpoint:
            exporter_kwargs["endpoint"] = endpoint
        if headers:
            exporter_kwargs["headers"] = headers
        exporter = OTLPMetricExporter(**exporter_kwargs)
        reader = PeriodicExportingMetricReader(
            exporter,
            export_interval_millis=export_interval_ms or _DEFAULT_EXPORT_INTERVAL_MS,
        )
        resource = Resource.create(
            {"service.name": _resolve_service_name(), **(resource_attributes or {})}
        )
        metrics.set_meter_provider(MeterProvider(metric_readers=[reader], resource=resource))
    except Exception:
        # Never let telemetry setup take down the caller.
        logger.exception("Failed to bootstrap OTel MeterProvider")
        return False

    _STATE["installed"] = True
    logger.info(
        "OTel MeterProvider installed → %s",
        endpoint or "endpoint resolved from OTEL_EXPORTER_OTLP_* env",
    )
    return True