defineObservability
The server's telemetry layer: one object the chat handler records model steps with and the relay forwards the page's spans through.
defineObservability() builds the server’s telemetry layer, once, in its own module. Give it to the chat handler as
its observability option and every model step becomes a chat span; mount its relay at /api/telemetry and the
page’s runs and tool calls join the same trace. With no options, the standard OTEL_* environment (or a provider your
app registered) decides where spans go, so most apps write it once and never touch it again.
Import
import { defineObservability } from "@webmcp-agents/telemetry/server";
import type {
Observability,
ObservabilityConfig,
} from "@webmcp-agents/telemetry/server";
Example
The layer, and the chat route that uses it. The highlighted lines are the ones the layer adds.
import { defineObservability } from "@webmcp-agents/telemetry/server";
// One layer for the server: the chat handler exports each model
// step, the relay forwards the page's spans. Where spans go is the
// standard OTEL_* environment (or nothing: then it is off).
export const observability = defineObservability({
serviceName: "field-store",
});
import { createChatHandler } from "@webmcp-agents/chat/server";
import { observability } from "../src/lib/observability";
import { agents } from "../src/agents";
const handler = createChatHandler({ agents, observability });
export const GET = handler;
export const POST = handler;import { createChatHandler } from "@webmcp-agents/chat/server";
import { agents } from "@/agents";
import { observability } from "@/lib/observability";
const handler = createChatHandler({ agents, observability });
export const GET = handler;
export const POST = handler;import { createFileRoute } from "@tanstack/react-router";
import { createChatHandler } from "@webmcp-agents/chat/server";
import { agents } from "@/agents";
import { observability } from "@/lib/observability";
const handler = createChatHandler({ agents, observability });
export const Route = createFileRoute("/api/chat")({
server: {
handlers: {
GET: ({ request }) => handler(request),
POST: ({ request }) => handler(request),
},
},
});import type { APIRoute } from "astro";
import { getSecret } from "astro:env/server";
import { createChatHandler } from "@webmcp-agents/chat/server";
import { agents } from "@/agents";
import { observability } from "@/lib/observability";
export const prerender = false;
const handler = createChatHandler({
agents,
observability,
env: {
ANTHROPIC_API_KEY: getSecret("ANTHROPIC_API_KEY"),
WEB_AGENTS_MODEL: getSecret("WEB_AGENTS_MODEL"),
},
});
export const GET: APIRoute = ({ request }) => handler(request);
export const POST: APIRoute = ({ request }) => handler(request);Nothing loads until the first request: the three OpenTelemetry packages are imported then, on the server only.
Options
Every option is optional. Open a row for its description and default.
serviceName?string
`service.name` of every span. Default `OTEL_SERVICE_NAME`, else `"web-agents"`.
stringresourceAttributes?Record<string, string>
Resource attributes (release, region), merged over `OTEL_RESOURCE_ATTRIBUTES`; an option wins over the env.
Record<string, string>exporters?readonly (OtlpTarget | SpanExporter)[]
Where spans go: OTLP targets (`otlp()`) and/or any OpenTelemetry `SpanExporter` instance, as is. Default: the app's registered tracer provider, else one OTLP target from `OTEL_EXPORTER_OTLP_*`, else off.
readonly (OtlpTarget | SpanExporter)[]spanProcessors?readonly SpanProcessor[]
Any OpenTelemetry `SpanProcessor` (a vendor's own, or yours), as is. They run first, before `metadataMapping`, redaction and `spanFilter`. A processor that exports by itself sends what the AI SDK set, which this package redacted when the span was created; what the processor adds is its own to handle.
readonly SpanProcessor[]tracerProvider?TracerProviderOption
A provider to use as is (its pipeline is the app's), `"global"` to require the app's registered one (off, with one error, when there is none), or `"own"` never to use it. Default: the registered one when there is one.
TracerProviderOptionrelayThrough?"exporter" | "provider"
Where the relay sends the browser's spans when the server's go through an app's provider (a `tracerProvider`, or the registered one). `"exporter"`: straight to the OTLP target (`exporters`, else `OTEL_EXPORTER_OTLP_*`) with the browser's own span ids, so a run and its tool calls need no reordering on the server and line up with the server's step spans. `"provider"`: re-created through the app's provider (new span ids, a child that comes a batch before its parent waits for it up to 30 s), for an app whose provider must see every span. With no OTLP target to send to, it is `"provider"`. With a provider this package builds, spans always go through it. Default `"exporter"`.
"exporter" | "provider"appIntegrations?"dedupe" | "keep"
What to do with the app's own `@ai-sdk/otel` integrations (`registerTelemetry(new OpenTelemetry())`) on a sampled request whose spans go to the same provider as the app's (the registered one): `"dedupe"` leaves them out of that call, logged once, so each model step is one `chat` span, not two; `"keep"` passes them along (both record). Other integrations, and every one when the request is not sampled or the layer builds its own provider, are always kept, never recording content. An `@ai-sdk/otel` integration the app gave a tracer of another provider is left out as well: pass `"keep"` then. Default `"dedupe"`.
"dedupe" | "keep"sampling?Sampling
Which requests are exported. Default `OTEL_TRACES_SAMPLER` (+ `_ARG`), else `{ type: "always" }`.
Samplingconventions?"genai" | "legacy" | "both"
Attribute style of the model spans: `"genai"` (`gen_ai.*`, default), `"legacy"` (`ai.*`, what LangWatch, PostHog and Braintrust read), or `"both"`, each from its own tracer.
"genai" | "legacy" | "both"recordInputs?boolean
Record prompts and tool definitions on model spans, redacted. The handler's own `telemetry.recordInputs` wins. Default false.
booleanrecordOutputs?boolean
Record the model's output on model spans, redacted. The handler's own `telemetry.recordOutputs` wins. Default false.
booleanredact?false | RedactOptions | Redactor
Redaction of everything exported (server spans and relayed browser spans). Default: the process's redactor (`configureRedaction`, `createChatHandler({ redact })`), read at each use. `false` only for local debugging.
false | RedactOptions | RedactormetadataMapping?Record<string, string>
Copy one of the span's attributes to the name a backend groups by. Runs before redaction.
Record<string, string>spanFilter?(span: ReadableSpanLike) => boolean
Keep (true) or drop (false) a span; a throw drops it. With a provider this package builds it runs last, on the redacted span; through an app's provider it runs when the span starts (name and attributes only).
(span: ReadableSpanLike) => booleanbatchSize?number
Spans per export batch. Default 512.
numberdebug?boolean
Also print each exported span to the console, redacted. Default `WEB_AGENTS_OTEL_DEBUG === "true"`.
booleanenv?Record<string, string | undefined>
Where the `OTEL_*` variables are read. Default `process.env`.
Record<string, string | undefined>Four of them have a page of their own: relayThrough,
appIntegrations, sampling and
metadataMapping. recordInputs, recordOutputs and redact are on
Privacy and redaction.
Returns
An Observability, which is what the chat handler takes as observability (ChatObservability: telemetry,
withContext, flush, exportTimeoutMs), plus:
enabled: false when the configuration resolves to off, or once setting it up failed.relay(options?): the/api/telemetryhandler.shutdown(): sends what is buffered and shuts down a provider this package built; an app’s own provider is only flushed.
flush() and shutdown() never reject.
Your backend
The shared lib/observability.ts above is all it needs: where spans go comes from the environment.
spanProcessors takes OpenInference’s span processor around a protobuf exporter, and resourceAttributes names the
project (openinference.project.name). The file is on its installation page.
spanProcessors takes BraintrustSpanProcessor with its parent (project_name:<name>, project_id:<id> or
experiment_id:<id>); without the package, the environment is enough.
Helicone is the chat handler’s model, not an option of this layer: the layer, if you use one, is set up like for any
other backend.
Written out, exporters takes one otlp() target with protocol: "http/protobuf" and the x-instana-key header, and
resourceAttributes sets an identity (faas.id, host.id or device.id) and INSTANA_PLUGIN: "genai".
spanProcessors takes LangfuseSpanProcessor, which reads its keys and LANGFUSE_BASE_URL from the environment.
exporters takes LangWatchExporter, and conventions: "legacy" sends the AI SDK’s ai.* spans that LangWatch’s AI
SDK integration is built on.
With its package, exporters takes PostHogTraceExporter (projectToken, host); without it, the environment is
enough.
No exporter: Sentry’s provider is found and used once Sentry.init has enableOpenTelemetrySetup: true.
No options: the provider registerOTel from @vercel/otel registers is found and used.
resourceAttributes files the traces: wandb.entity and wandb.project.
Notes
Decided once, never global
Where spans go is decided on the first request, first match wins (Where spans go). The layer never registers anything globally and never shuts down a provider it did not build.
When something fails
A missing package, bad env, both endpoint forms on a target, an unknown protocol, a throwing or hanging exporter, an unreachable backend: each is logged once (redacted), turns off only what it affects, and never changes a chat request’s answer or timing.
Options in detail
Giving exporters builds a private provider. spanProcessors run first, before metadataMapping, redaction and
spanFilter. tracerProvider: "global" is off, with one error, when the app registered none. spanFilter runs
last on a provider this package builds; through an app’s provider, when the span starts (name and attributes
only). The handler’s own telemetry.recordInputs and recordOutputs win over the layer’s. To drop your own
custom spans, filter on webmcp.custom.
Through an app's provider
This package cannot own the app’s pipeline, so it redacts every attribute it sets before the span exists. What the app’s own processors add is theirs to handle.
The span tree
When the request carries the page’s traceparent with its sampled flag set (the page records its run span), the
AI SDK’s own invoke_agent and step wrapper spans are left out, so each chat span is a direct child of the
browser’s run span. Without it, or with the flag unset (a page without observeAgents, a run without consent or
sampled out by the page, a 0.4.0 page), the AI SDK’s tree is exported as is, in a trace of its own. The flag
decides only the parent: whether the step is exported is the server’s sampling.
The app's own AI SDK integrations
Integrations the app registered with registerTelemetry are passed along with this package’s for each call
(ai@7 replaces registered ones with per-call ones otherwise), never recording content: they cannot redact. The
one exception is the app’s own @ai-sdk/otel integration when it would record the same steps into the same
provider (appIntegrations).
Serverless
The handler hands flush() to the host’s waitUntil when it finds one (Vercel, Workers); a Vercel app keeps one
layer per function instance
(createVercelTelemetryRoute).
One layer per server
Define it once, in its own module, and import it from the chat route and the relay route. Both then share one provider, one sampler and one redactor.
conventions: the model spans’ attribute style
"genai" (the default) emits the OpenTelemetry GenAI conventions, gen_ai.*. "legacy" emits the AI SDK’s older
ai.* spans, which some tools were built on. "both" emits each set from its own tracer, so model steps appear
twice: use it only to compare.