@microsoft/opentelemetry package

Classes

A365Configuration

Resolved A365 configuration.

Merges values from three sources (lowest to highest precedence):

  1. Defaults
  2. Programmatic options (A365Options)
  3. Environment variables (see A365_ENV_VARS)
A365SpanProcessor

Copies relevant baggage entries to span attributes on span start.

This is the "automatic" counterpart to the manual scope API — it ensures every span in the pipeline gets agent identity attributes from baggage without explicitly creating scopes.

Agent365Exporter

Agent365 span exporter.

Implements SpanExporter from @opentelemetry/sdk-trace-base. Partitions spans by (tenantId, agentId), builds OTLP-like JSON payloads, and POSTs them to the Agent365 observability service with Bearer auth.

AgenticTokenCache

Cache for agentic authentication tokens used by observability services.

Example

// Use the default singleton:
import { AgenticTokenCacheInstance } from '@microsoft/opentelemetry';

// Or create an instance with custom scopes:
const cache = new AgenticTokenCache({ authScopes: ['api://my-scope/.default'] });
ApplyGuardrailScope

Provides OpenTelemetry tracing scope for security guardrail evaluation operations.

Describes a security guardian evaluation. Multiple guardian spans MAY exist under a single operation span if multiple guardians are chained.

Guardian spans SHOULD be children of the operation span they are protecting (e.g., inference or execute_tool spans).

BaggageBuilder

Fluent builder for setting OpenTelemetry baggage values.

Example

const scope = new BaggageBuilder()
  .tenantId("tenant-123")
  .agentId("agent-456")
  .build();

scope.run(() => {
  // Baggage is active in this context
});
BaggageBuilderUtils

Utilities to populate BaggageBuilder from a TurnContext.

BaggageMiddleware

Middleware that propagates OpenTelemetry baggage context derived from TurnContext. Async replies (ContinueConversation) are passed through without baggage setup.

BaggageScope

Context manager for baggage scope.

Manages the lifecycle of baggage values, setting them in the OTel context and restoring the previous context when the scope ends.

ExecuteToolScope

Provides OpenTelemetry tracing scope for AI tool execution operations.

GenAIMainAgentLogRecordProcessor

Copies any microsoft.gen_ai.main_agent.* attributes from the current span onto every emitted log record.

GenAIMainAgentSpanProcessor

Propagates microsoft.gen_ai.main_agent.* attributes onto spans.

  • onStart: copies main-agent attributes from the parent span (or falls back to the parent's gen_ai.agent.* / gen_ai.conversation.id attributes) onto the new span.
  • onEnd: when the span is itself an invoke_agent operation and has not already been enriched, copies its own gen_ai.agent.* / gen_ai.conversation.id attributes onto microsoft.gen_ai.main_agent.* so the top-level agent identifies itself as the main agent.
InferenceScope

Provides OpenTelemetry tracing scope for generative AI inference operations.

InvokeAgentScope

Provides OpenTelemetry tracing scope for AI agent invocation operations.

ObservabilityHostingManager

Manager for configuring hosting-layer observability middleware.

Example

const manager = new ObservabilityHostingManager();
manager.configure(adapter, { enableOutputLogging: true });
OpenTelemetryConstants

OpenTelemetry constants for A365 observability.

Provides the well-known span operation names, attribute keys, metric names, environment-variable names, and feature-flag switches used when emitting A365 telemetry. Attribute keys follow OTel gen-ai semantic conventions plus Microsoft-specific extensions under the microsoft.* namespace.

Adapted from microsoft/Agent365-nodejs agents-a365-observability/src/tracing/constants.ts

OpenTelemetryScope

Base class for OpenTelemetry tracing scopes.

Subclasses: InvokeAgentScope, ExecuteToolScope, InferenceScope, OutputScope.

OutputLoggingMiddleware

Middleware that creates OutputScope spans for outgoing messages. Links to a parent span when A365_PARENT_SPAN_KEY is set in turnState.

Privacy note: Outgoing message content is captured verbatim as span attributes and exported to the configured telemetry backend.

OutputScope

Provides OpenTelemetry tracing scope for output message tracing.

ScopeUtils

Unified utilities to populate scope tags from a TurnContext.

Interfaces

A365Options

A365 observability configuration options.

These are the public-facing options passed via the a365 scope of MicrosoftOpenTelemetryOptions.

A365Request

Represents a request with telemetry context.

A365SpanDetails

Span configuration details for scope creation.

ActivityLike

Minimal activity shape required by hosting observability utilities.

Agent365DurableDeliveryOptions
Agent365ExporterOptions

Options controlling the behavior of the Agent365 span exporter.

AgentDetails

Details about an AI agent.

AgentIdentity

Represents the identity of an agent and its acting user.

In agentic user scenarios, agenticUserId identifies the specific user in the current interaction so the token resolver can generate a user-scoped token. In S2S scenarios, agenticUserId will be undefined.

AgenticTokenCacheOptions

Options for constructing an AgenticTokenCache instance.

AuthorizationLike

Minimal authorization shape required by AgenticTokenCache.

Mirrors the Authorization interface from @microsoft/agents-hosting so the cache can be used without a direct dependency on that package.

AzureMonitorOpenTelemetryOptions

Azure Monitor scoped options.

These options control Azure Monitor-specific behavior. Global options (resource, sampling, instrumentations, processors) are defined at the top level in MicrosoftOpenTelemetryOptions.

BrowserSdkLoaderOptions

Application Insights Web Instrumentation Configuration interface

CallerDetails

Caller details for scope creation. Supports human callers, agent callers, or both (A2A with a human in the chain).

Channel

Represents a channel for an invocation.

ChatMessage

An input message sent to a model (OTEL gen-ai semantic conventions).

GuardrailDetails

Details of a guardrail evaluation for security operations tracing.

GuardrailFinding

Represents a single security finding detected during guardian evaluation. Multiple findings may be emitted for a single guardrail span.

HostingAdapterLike

Minimal adapter contract for registering hosting middleware.

InferenceDetails

Details for an inference call.

InferenceResponse

Details for recording the response from an inference call.

InputMessages

A structured wrapper around the list of input messages.

InstrumentationOptions

OpenTelemetry Instrumentations Configuration interface

InvokeAgentScopeDetails

Details for invoking agent scope.

LangChainInstrumentationConfig

Configuration for LangChain instrumentation.

MicrosoftOpenTelemetryOptions

Microsoft OpenTelemetry Options

Top-level configuration for the Microsoft OpenTelemetry distribution. Global options (resource, sampling, instrumentations, processors) live here. Backend-specific options are scoped under their respective keys.

MiddlewareLike

Middleware interface compatible with agents-hosting adapters.

ObservabilityHostingOptions

Configuration options for the hosting observability layer.

OpenAIAgentsInstrumentationConfig

Configuration for OpenAI Agents SDK instrumentation.

OutputMessage

An output message produced by a model (OTEL gen-ai semantic conventions). finish_reason defaults to "stop" per OTel spec when not provided.

OutputMessages

A structured wrapper around the list of output messages.

OutputResponse

Represents a response containing output messages from an agent.

ParentSpanRef

Manual parent span reference for cross-async-boundary tracing.

ReasoningPart

Model reasoning / chain-of-thought content.

ServiceEndpoint

Represents an endpoint for agent invocation.

TextPart

Plain text content.

TokenResolverContext

Provides contextual information to the contextual token resolver delegate.

identity provides first-class access to agent identity fields (agent ID, agentic user ID). tenantId and identity together identify the cache key.

ToolCallDetails

Details of a tool call made by an agent.

ToolCallRequestPart

A tool call requested by the model.

ToolCallResponsePart

Result of a tool call.

TurnContextLike

Minimal turn context shape required by hosting observability utilities.

UserDetails

Details about the human user caller.

Type Aliases

ClusterCategory

Cluster categories for A365 service endpoint resolution. Mirrors the ClusterCategory enum from Agent365-nodejs.

ContextualTokenResolver

Async delegate used by the exporter to obtain an auth token using rich context. Provides additional fields (e.g. TokenResolverContext.identity) beyond what TokenResolver offers. Must be fast and non-blocking (use internal caching elsewhere). Return null/undefined to skip the export for that agent/tenant group.

HeadersCarrier

Carrier type for HTTP headers.

InputMessagesParam

Accepted input for recordInputMessages. Supports a single string, an array of strings (backward compat), or the structured wrapper.

MessagePart

Union of all message part types per OTEL gen-ai semantic conventions.

OutputMessagesParam

Accepted input for recordOutputMessages. Supports a single string, an array of strings (backward compat), or the structured wrapper.

ParentContext

Parent context — either an OTel Context or a manual ParentSpanRef.

ResponseMessagesParam

Accepted input for OutputResponse.messages.

SendActivitiesHandler

Handler for intercepting outgoing activities.

TokenResolver

A function that resolves an authentication token for the given agent and tenant. Return null if a token cannot be provided.

Enums

FinishReason

Reason a model stopped generating per OTEL gen-ai semantic conventions.

GuardrailDecisionType

The decision made by a security guardian during guardrail evaluation.

InferenceOperationType

Represents different operation types for model inference.

InvocationRole

Represents different roles that can invoke an agent.

MessageRole

Role of a message participant per OTEL gen-ai semantic conventions.

Modality

Media modality for blob, file, and URI parts.

Functions

configureA365Hosting(HostingAdapterLike, ObservabilityHostingOptions)

Configure A365 hosting middleware in a single call.

Defaults to enabling both baggage propagation and output logging.

createContextWithParentSpanRef(Context, ParentSpanRef)

Creates a new Context with an explicit parent span reference. This allows child spans to be correctly parented even when async context is broken.

extractContextFromHeaders(HeadersCarrier, Context)

Extracts trace context from incoming HTTP headers using the globally registered W3C propagator.

getCallerBaggagePairs(TurnContextLike)

Extracts caller-related OpenTelemetry baggage pairs from the TurnContext.

getChannelBaggagePairs(TurnContextLike)

Extracts channel baggage pairs from the TurnContext.

getConversationIdAndItemLinkPairs(TurnContextLike)

Extracts conversation ID and item link baggage pairs.

getExportToken(Context)

Retrieve the per-request export token from a given OTel Context (or the active one).

getTargetAgentBaggagePairs(TurnContextLike, string)

Extracts agent/recipient-related OpenTelemetry baggage pairs from the TurnContext.

getTenantIdPair(TurnContextLike)

Extracts the tenant ID baggage key-value pair.

injectContextToHeaders(Record<string, string>, Context)

Injects the current trace context (traceparent/tracestate headers) into the provided headers object using the globally registered W3C propagator.

isParentSpanRef(unknown)

Type guard to distinguish a ParentSpanRef from an OTel Context.

resolveEmbodiedAgentIds(TurnContextLike, string)

Resolves the agent instance ID and blueprint ID for embodied (agentic) agents. For non-embodied agents, both fields are undefined.

runWithExportToken<T>(string, () => T)

Run a function within a Context that carries the per-request export token. This keeps the token only in OTel Context (ALS), never in any registry.

The token can be updated later via updateExportToken() before the trace is flushed — useful when the callback is long-running and the original token may expire before export.

runWithExtractedTraceContext<T>(HeadersCarrier, () => T)

Extracts trace context from incoming HTTP headers and runs the callback within that context.

runWithParentSpanRef<T>(ParentSpanRef, () => T)

Runs a callback within a context that has an explicit parent span reference.

shutdownMicrosoftOpenTelemetry()

Shutdown Microsoft OpenTelemetry distribution.

updateExportToken(string)

Update the export token in the active OTel Context. Call this to refresh the token before ending the root span when the original token may have expired during a long-running request.

Must be called within the same async context created by runWithExportToken.

useMicrosoftOpenTelemetry(MicrosoftOpenTelemetryOptions)

Initialize Microsoft OpenTelemetry.

This is the primary entry point. It sets up OpenTelemetry providers and instrumentations, then attaches the configured exporters:

  • Azure Monitor (when options.azureMonitor is provided or the APPLICATIONINSIGHTS_CONNECTION_STRING env var is set; explicitly disable with options.azureMonitor.enabled = false)
  • OTLP HTTP (when OTEL_EXPORTER_OTLP_ENDPOINT is set)
  • A365 (when the resolved A365 config has enabled=true; the ENABLE_A365_OBSERVABILITY_EXPORTER env var is only considered when options.a365 is provided)

Variables

A365_AUTH_TOKEN_KEY

TurnState key for the auth token. Set this in turnState so middleware can resolve the agent blueprint ID from token claims (used for embodied/agentic requests).

A365_PARENT_SPAN_KEY

TurnState key for the parent span reference. Set this in turnState to link OutputScope spans as children of an InvokeAgentScope.

AgenticTokenCacheInstance

Default singleton instance of AgenticTokenCache using the default configuration.

DEFAULT_FINISH_REASON

Default finish reason applied when none is provided (per OTel spec).

GEN_AI_MAIN_AGENT_ATTRIBUTE_PREFIX

Common prefix shared by all main-agent attribute keys.

GEN_AI_MAIN_AGENT_CONVERSATION_ID_KEY

Attribute key for the main agent's conversation identifier.

GEN_AI_MAIN_AGENT_ID_KEY

Attribute key for the main agent's identifier.

GEN_AI_MAIN_AGENT_NAME_KEY

Attribute key for the main agent's display name.

GEN_AI_MAIN_AGENT_VERSION_KEY

Attribute key for the main agent's version.

GENERIC_ATTRIBUTES

Generic / common tracing attributes applied to all spans.

GuardrailRiskSeverity

Well-known severity levels for security risks detected by guardrails.

GuardrailTargetType

Well-known values for the type of content or action a guardrail is applied to. Custom strings are also accepted.

INVOKE_AGENT_ATTRIBUTES

Invoke Agent-specific attributes. These are only applied to spans whose operation is invoke_agent.

MICROSOFT_OPENTELEMETRY_VERSION

Microsoft OpenTelemetry distribution version.

Function Details

configureA365Hosting(HostingAdapterLike, ObservabilityHostingOptions)

Configure A365 hosting middleware in a single call.

Defaults to enabling both baggage propagation and output logging.

function configureA365Hosting(adapter: HostingAdapterLike, options?: ObservabilityHostingOptions): ObservabilityHostingManager

Parameters

Returns

createContextWithParentSpanRef(Context, ParentSpanRef)

Creates a new Context with an explicit parent span reference. This allows child spans to be correctly parented even when async context is broken.

function createContextWithParentSpanRef(base: Context, parent: ParentSpanRef): Context

Parameters

base

Context

parent
ParentSpanRef

Returns

Context

extractContextFromHeaders(HeadersCarrier, Context)

Extracts trace context from incoming HTTP headers using the globally registered W3C propagator.

function extractContextFromHeaders(headers: HeadersCarrier, baseCtx?: Context): Context

Parameters

headers
HeadersCarrier
baseCtx

Context

Returns

Context

getCallerBaggagePairs(TurnContextLike)

Extracts caller-related OpenTelemetry baggage pairs from the TurnContext.

function getCallerBaggagePairs(turnContext: TurnContextLike): [string, string][]

Parameters

turnContext
TurnContextLike

Returns

[string, string][]

getChannelBaggagePairs(TurnContextLike)

Extracts channel baggage pairs from the TurnContext.

function getChannelBaggagePairs(turnContext: TurnContextLike): [string, string][]

Parameters

turnContext
TurnContextLike

Returns

[string, string][]

getConversationIdAndItemLinkPairs(TurnContextLike)

Extracts conversation ID and item link baggage pairs.

function getConversationIdAndItemLinkPairs(turnContext: TurnContextLike): [string, string][]

Parameters

turnContext
TurnContextLike

Returns

[string, string][]

getExportToken(Context)

Retrieve the per-request export token from a given OTel Context (or the active one).

function getExportToken(ctx?: Context): string | undefined

Parameters

ctx

Context

Returns

string | undefined

getTargetAgentBaggagePairs(TurnContextLike, string)

Extracts agent/recipient-related OpenTelemetry baggage pairs from the TurnContext.

function getTargetAgentBaggagePairs(turnContext: TurnContextLike, authToken?: string): [string, string][]

Parameters

turnContext
TurnContextLike
authToken

string

Returns

[string, string][]

getTenantIdPair(TurnContextLike)

Extracts the tenant ID baggage key-value pair.

function getTenantIdPair(turnContext: TurnContextLike): [string, string][]

Parameters

turnContext
TurnContextLike

Returns

[string, string][]

injectContextToHeaders(Record<string, string>, Context)

Injects the current trace context (traceparent/tracestate headers) into the provided headers object using the globally registered W3C propagator.

function injectContextToHeaders(headers: Record<string, string>, ctx?: Context): Record<string, string>

Parameters

headers

Record<string, string>

ctx

Context

Returns

Record<string, string>

isParentSpanRef(unknown)

Type guard to distinguish a ParentSpanRef from an OTel Context.

function isParentSpanRef(value: unknown): value is ParentSpanRef

Parameters

value

unknown

Returns

value is ParentSpanRef

resolveEmbodiedAgentIds(TurnContextLike, string)

Resolves the agent instance ID and blueprint ID for embodied (agentic) agents. For non-embodied agents, both fields are undefined.

function resolveEmbodiedAgentIds(turnContext: TurnContextLike, authToken: string): { agentBlueprintId: string | undefined, agentId: string | undefined }

Parameters

turnContext
TurnContextLike

Activity context

authToken

string

Auth token for resolving blueprint ID from token claims.

Returns

{ agentBlueprintId: string | undefined, agentId: string | undefined }

runWithExportToken<T>(string, () => T)

Run a function within a Context that carries the per-request export token. This keeps the token only in OTel Context (ALS), never in any registry.

The token can be updated later via updateExportToken() before the trace is flushed — useful when the callback is long-running and the original token may expire before export.

function runWithExportToken<T>(token: string, fn: () => T): T

Parameters

token

string

fn

() => T

Returns

T

runWithExtractedTraceContext<T>(HeadersCarrier, () => T)

Extracts trace context from incoming HTTP headers and runs the callback within that context.

function runWithExtractedTraceContext<T>(headers: HeadersCarrier, callback: () => T): T

Parameters

headers
HeadersCarrier
callback

() => T

Returns

T

runWithParentSpanRef<T>(ParentSpanRef, () => T)

Runs a callback within a context that has an explicit parent span reference.

function runWithParentSpanRef<T>(parent: ParentSpanRef, callback: () => T): T

Parameters

parent
ParentSpanRef
callback

() => T

Returns

T

shutdownMicrosoftOpenTelemetry()

Shutdown Microsoft OpenTelemetry distribution.

function shutdownMicrosoftOpenTelemetry(): Promise<void>

Returns

Promise<void>

updateExportToken(string)

Update the export token in the active OTel Context. Call this to refresh the token before ending the root span when the original token may have expired during a long-running request.

Must be called within the same async context created by runWithExportToken.

function updateExportToken(token: string): boolean

Parameters

token

string

The fresh token to use for export.

Returns

boolean

true if the token was updated successfully, false if no token holder was found.

useMicrosoftOpenTelemetry(MicrosoftOpenTelemetryOptions)

Initialize Microsoft OpenTelemetry.

This is the primary entry point. It sets up OpenTelemetry providers and instrumentations, then attaches the configured exporters:

  • Azure Monitor (when options.azureMonitor is provided or the APPLICATIONINSIGHTS_CONNECTION_STRING env var is set; explicitly disable with options.azureMonitor.enabled = false)
  • OTLP HTTP (when OTEL_EXPORTER_OTLP_ENDPOINT is set)
  • A365 (when the resolved A365 config has enabled=true; the ENABLE_A365_OBSERVABILITY_EXPORTER env var is only considered when options.a365 is provided)
function useMicrosoftOpenTelemetry(options?: MicrosoftOpenTelemetryOptions)

Parameters

options
MicrosoftOpenTelemetryOptions

Microsoft OpenTelemetry configuration options

Variable Details

A365_AUTH_TOKEN_KEY

TurnState key for the auth token. Set this in turnState so middleware can resolve the agent blueprint ID from token claims (used for embodied/agentic requests).

A365_AUTH_TOKEN_KEY: "A365AuthToken"

Type

"A365AuthToken"

A365_PARENT_SPAN_KEY

TurnState key for the parent span reference. Set this in turnState to link OutputScope spans as children of an InvokeAgentScope.

A365_PARENT_SPAN_KEY: "A365ParentSpanId"

Type

"A365ParentSpanId"

AgenticTokenCacheInstance

Default singleton instance of AgenticTokenCache using the default configuration.

AgenticTokenCacheInstance: AgenticTokenCache

Type

DEFAULT_FINISH_REASON

Default finish reason applied when none is provided (per OTel spec).

DEFAULT_FINISH_REASON: "stop"

Type

"stop"

GEN_AI_MAIN_AGENT_ATTRIBUTE_PREFIX

Common prefix shared by all main-agent attribute keys.

GEN_AI_MAIN_AGENT_ATTRIBUTE_PREFIX: "microsoft.gen_ai.main_agent."

Type

"microsoft.gen_ai.main_agent."

GEN_AI_MAIN_AGENT_CONVERSATION_ID_KEY

Attribute key for the main agent's conversation identifier.

GEN_AI_MAIN_AGENT_CONVERSATION_ID_KEY: "microsoft.gen_ai.main_agent.conversation_id"

Type

"microsoft.gen_ai.main_agent.conversation_id"

GEN_AI_MAIN_AGENT_ID_KEY

Attribute key for the main agent's identifier.

GEN_AI_MAIN_AGENT_ID_KEY: "microsoft.gen_ai.main_agent.id"

Type

"microsoft.gen_ai.main_agent.id"

GEN_AI_MAIN_AGENT_NAME_KEY

Attribute key for the main agent's display name.

GEN_AI_MAIN_AGENT_NAME_KEY: "microsoft.gen_ai.main_agent.name"

Type

"microsoft.gen_ai.main_agent.name"

GEN_AI_MAIN_AGENT_VERSION_KEY

Attribute key for the main agent's version.

GEN_AI_MAIN_AGENT_VERSION_KEY: "microsoft.gen_ai.main_agent.version"

Type

"microsoft.gen_ai.main_agent.version"

GENERIC_ATTRIBUTES

Generic / common tracing attributes applied to all spans.

GENERIC_ATTRIBUTES: readonly string[]

Type

readonly string[]

GuardrailRiskSeverity

Well-known severity levels for security risks detected by guardrails.

GuardrailRiskSeverity: { Critical: "critical", High: "high", Low: "low", Medium: "medium", None: "none" }

Type

{ Critical: "critical", High: "high", Low: "low", Medium: "medium", None: "none" }

GuardrailTargetType

Well-known values for the type of content or action a guardrail is applied to. Custom strings are also accepted.

GuardrailTargetType: { KnowledgeQuery: "knowledge_query", KnowledgeResult: "knowledge_result", LlmInput: "llm_input", LlmOutput: "llm_output", MemoryRetrieve: "memory_retrieve", MemoryStore: "memory_store", Message: "message", ToolCall: "tool_call", ToolDefinition: "tool_definition" }

Type

{ KnowledgeQuery: "knowledge_query", KnowledgeResult: "knowledge_result", LlmInput: "llm_input", LlmOutput: "llm_output", MemoryRetrieve: "memory_retrieve", MemoryStore: "memory_store", Message: "message", ToolCall: "tool_call", ToolDefinition: "tool_definition" }

INVOKE_AGENT_ATTRIBUTES

Invoke Agent-specific attributes. These are only applied to spans whose operation is invoke_agent.

INVOKE_AGENT_ATTRIBUTES: readonly string[]

Type

readonly string[]

MICROSOFT_OPENTELEMETRY_VERSION

Microsoft OpenTelemetry distribution version.

MICROSOFT_OPENTELEMETRY_VERSION: "1.4.0"

Type

"1.4.0"