Mastra Observability 如何運作,以及如何監測 Mastra 智能體
Mastra Observability: How It Works and the Best Way to Monitor Mastra Agents
指南建議保留 Mastra 內建 Observability,並加入 OpenTelemetry exporter,將相同 spans 傳至 Agnost AI,以按用戶及 session 監測完整對話。
The best way to monitor a Mastra agent in production is to keep Mastra’s built-in observability and add an OpenTelemetry exporter that sends the same spans to Agnost AI, which detects failures across whole conversations, alerts on them, and turns recurring ones into pull requests with tested fixes. Mastra Studio stays the place to inspect single runs during development; Agnost shows each conversation’s spans and tool calls itself and adds the production view across users and sessions. Agnost AI is one of the providers documented in Mastra’s OpenTelemetry exporter docs.
Disclosure: We make Agnost AI. Facts about Mastra and other tools come from their own docs, checked on November 21, 2026.
How does observability work in Mastra? Observability is built into the framework. You register an Observability instance from @mastra/observability on your Mastra instance, and Mastra records each agent run, model call, tool call, and workflow step as a span in a trace. Exporters in that config decide where the spans go: Mastra Studio, Mastra’s hosted platform, a provider such as Langfuse or Arize, or any OpenTelemetry backend through @mastra/otel-exporter. Logs written inside a traced context carry the trace and span IDs, and Studio derives duration, token, and cost metrics from the ended spans.
That gives you execution history. It does not tell you whether the user got what they asked for. An agent can generate a useful intermediate answer while a later tool fails, and a workflow can finish while the user-facing action remains incomplete. Useful Mastra observability connects agent execution, workflow steps, and the product conversation. Use Mastra’s exporter layer for execution traces, attach stable identity at the call boundary, and define outcomes from the system that actually performs the work.
Agnost AI receives Mastra traces through OtelExporter and also has a separate conversation SDK. The Mastra integration guide describes both. Start with the exporter if your application already uses Mastra Observability; add a request wrapper only when it supplies a missing application boundary. This guide was checked against @mastra/core 1.82, @mastra/observability 1.23, and @mastra/otel-exporter 1.5 in November 2026.
Mastra observability tools you can use
| Tool | How it connects to Mastra | Best for |
|---|---|---|
| Agnost AI |
OtelExporter with the custom provider; listed in Mastra’s OpenTelemetry docs |
Production monitoring of whole conversations: failures, frustration, plain-language rules, Slack or email alerts, and fix pull requests |
| Mastra Studio | MastraStorageExporter |
Inspecting single runs, with duration, token, and cost metrics, during development |
| Mastra platform | MastraPlatformExporter |
Mastra’s hosted view of the same traces |
| Langfuse |
LangfuseExporter from @mastra/langfuse
|
Open-source tracing, prompt management, and evals |
| Arize Phoenix / AX |
ArizeExporter from @mastra/arize
|
Tracing and evaluation, self-hosted (Phoenix) or managed (AX) |
| Datadog, Sentry, New Relic, SigNoz, Dash0, Laminar, Traceloop, MLflow |
OtelExporter providers |
Keeping agent traces in an APM or tracing backend you already run |
Exporters are not exclusive. Mastra sends every span to every exporter in the active config, so you can keep Studio for development and add Agnost for production.
Best tool for monitoring Mastra agents in production
Use Mastra’s own observability for execution traces, and Agnost AI for production monitoring of conversations. Mastra Studio and Mastra’s hosted platform are enough when you are developing or debugging: they show each agent run, tool call, and workflow step, with duration, token, and cost metrics. They do not group runs into user conversations or tell you which conversations failed. Agnost AI adds that layer:
- Groups traffic by user and session and judges whole conversations, not single traces.
- Detects failures, user frustration, intents (auto-generated and custom), tool-call errors, loops, and silent wrong answers.
- Runs plain-language rules, such as “do not tell the user an export is ready until the job reports done,” judged pass or fail by an LLM on each assistant message, with no sampling.
- Sends alerts to Slack or email, and Auto Improve opens a pull request with a fix tested against past runs for your team to review.
Judging runs in batches once a conversation has been idle for 15 minutes, so it is a review layer, not real-time paging.
Agnost shows the traces too. Agnost ingests the OpenTelemetry traces itself: each conversation opens to its messages, spans and errors, and each tool call shows success or failure, latency, and its arguments and results when content capture is on. You do not need a separate tracing tool to use Agnost. Mastra Studio stays useful for local and development debugging. Teams that want offline datasets, experiments or CI gates add LangSmith, Braintrust or Langfuse for that.
Recommended setup. Install the OpenTelemetry exporter and add an Agnost exporter next to the ones you already have:
npm install @mastra/observability @mastra/otel-exporter \
@opentelemetry/exporter-trace-otlp-proto
import { OtelExporter } from '@mastra/otel-exporter';
const agnostExporter = new OtelExporter({
provider: {
custom: {
endpoint: 'https://otel.agnost.ai/v1/traces',
protocol: 'http/protobuf',
headers: { 'X-Agnost-Org-ID': process.env.AGNOST_ORG_ID! },
},
},
});
// In your Observability config: exporters: [ ...yourExistingExporters, agnostExporter ]
Pass userId and conversationId in tracingOptions.metadata on each call (shown below) so Agnost can group runs, then write your first rules and alerts. The full setup, including a config from scratch, sampling, and flushing, is below.
Worked example: the workflow returns before the export exists
An illustrative Mastra assistant creates a dashboard export. The workflow submits an export job and immediately tells the user the file is ready, but the export service still reports pending.
| Boundary | Evidence | Interpretation |
|---|---|---|
| Agent request | User asked for a downloadable file | The goal requires a usable artifact |
| Workflow submission | Service returned a job ID | Work was accepted, not completed |
| Status lookup | Job is pending or failed | The artifact is not ready |
| Public answer | “Your export is ready” | Completion claim exceeds the evidence |
The issue may be the workflow’s completion contract rather than model quality. Record the job ID as an approved reference and keep job acceptance separate from artifact readiness. If work continues in another process, propagate request context and instrument that worker; the web server’s trace will not observe it automatically.
A better product response to a pending job is an accurate pending state with a continuation mechanism your application supports. Verify the eventual file or external status before recording success. This is proposed handling for the example, not a claim that the sample adapter implements job polling.
Use Agnost to follow the user request, tool submission, and subsequent evidence. If the status lookup was never recorded, mark the outcome unknown instead of deriving it from the assistant’s wording.

Metrics that answer useful Mastra questions
Use these definitions to design your measurement plan. Calculate them from the required application or tracing evidence; they are not all precomputed dashboard metrics.
| Metric | Definition | Interpretation |
|---|---|---|
| Workflow execution failures | Failed workflow attempts / started attempts | Keep job submission and job completion distinct. |
| Confirmed action completion | Externally confirmed actions / eligible action requests | Pending work remains in its own state. |
| Time to usable result | Artifact-ready time minus initial request time | Includes queue time outside agent generation. |
Mastra OpenTelemetry: route traces to Agnost
Mastra exports OpenTelemetry through @mastra/otel-exporter. The exporter needs a transport package that matches its protocol; for Agnost that is HTTP/protobuf:
Example scope: the code below is an integration adapter for an existing application. Configure its framework, model, credentials, and output contract as described; the demo screenshots were not generated by running these snippets.
npm install @mastra/observability @mastra/otel-exporter \
@opentelemetry/exporter-trace-otlp-proto
If you already have Mastra Observability, append an Agnost exporter to the existing exporters array. Mastra sends every span to every exporter in the list, so Studio, Langfuse, or another destination keeps working:
import { OtelExporter } from '@mastra/otel-exporter';
const orgId = process.env.AGNOST_ORG_ID;
if (!orgId) throw new Error('AGNOST_ORG_ID is required');
export const agnostExporter = new OtelExporter({
provider: {
custom: {
endpoint: 'https://otel.agnost.ai/v1/traces',
protocol: 'http/protobuf',
headers: { 'X-Agnost-Org-ID': orgId },
},
},
});
// Inside your existing Observability config:
// exporters: [ ...yourExistingExporters, agnostExporter ]
If you have no observability config yet, register one on the Mastra instance:
import { Mastra } from '@mastra/core';
import { Observability } from '@mastra/observability';
export const mastra = new Mastra({
agents: { supportAgent },
observability: new Observability({
configs: {
default: {
serviceName: 'support-app',
exporters: [agnostExporter],
},
},
}),
});
Creating an exporter object without registering it in the active config sends nothing. If you also use Mastra Studio, keep MastraStorageExporter in the list; Studio’s dashboards read from it, and adding an external exporter does not replace it.
Three settings on the same config matter in production:
-
Sampling.
sampling: { type: 'always' }keeps every trace;{ type: 'ratio', probability: 0.1 }keeps 10%. Sampled-out requests return an undefinedtraceIdand never reach any exporter, including Agnost. -
Redaction.
SensitiveDataFilterinspanOutputProcessorsredacts passwords, tokens, and keys before export. Mastra enables it in the default config; keep it when you write your own. -
Flushing. In serverless runtimes, call
await mastra.observability.flush()before the function returns or buffered spans can be lost.
Mastra’s OtelExporter reference lists the transport package for each protocol, and the observability overview covers configs, exporters, and flushing. Keep package versions compatible with your existing Mastra release rather than upgrading the whole application to copy a snippet.
Mastra logging and metrics
Mastra treats traces as the primary signal and builds the others on top of them. Log calls made inside a traced context are tagged with the current trace and span IDs, so you can jump from a log line to the agent run that produced it. Duration, token counts, and cost estimates are extracted from ended spans without extra code, and Studio’s aggregate dashboards are built from those values.
OtelExporter exports logs too by default: if the matching OTLP log exporter package is installed, it sends them to the trace endpoint with /v1/traces replaced by /v1/logs. Agnost stores traces only. Its collector accepts OTLP logs and metrics but does not keep them, so send logs to your existing log backend and set signals: { traces: true, logs: false } on the Agnost exporter if you want to avoid exporting them twice.
In Agnost, metrics come from the received spans and conversations: tool call volume, recorded success, and P90 duration in Tools, plus errors, intents, and rule violations across conversations. Business metrics such as confirmed action completion still need your application’s own outcome events, as in the metrics table above.
Attach user and conversation context
For your existing agent, pass the application identity with the request:
await agent.generate(prompt, {
tracingOptions: {
metadata: {
userId: authenticatedUserId,
conversationId: applicationConversationId,
agentVersion: 'support-v1',
},
},
});Here agent, prompt, and the identity values come from your application. Reuse the conversation ID for follow-up turns. Derive the user ID from authenticated server context, not an untrusted client claim. Agnost reads the reserved keys userId, conversationId, and threadId from tracingOptions.metadata for user and conversation grouping. Other metadata travels with the span but should not be assumed to become a built-in analytics dimension. Inside a tool or workflow step, tracingContext.currentSpan?.update({ metadata }) adds metadata to the current span.
Inspect a real received event to confirm grouping. Trace parentage and product identity solve different problems: a span can have the correct parent while still lacking the user or conversation needed for product review.
Decide whether you also need a conversation wrapper
The npm package agnostai can wrap the public agent.generate() call using agnost.begin(...) and interaction.end(result.text). That records the input and final response you choose to expose. It does not replace deeper framework tracing.
Use a wrapper when you need a clearly defined public interaction or an approved, sanitized representation that differs from internal messages. Avoid adding it merely to make more records appear. If the wrapper and exported root span describe the same request, choose one for request counts and use the other for detail.
For streaming, end the public interaction at an explicit terminal state rather than when a stream object is created. For background workflows, define where a user’s job starts and what event proves completion.
Diagnose a workflow from the failing boundary backward
Consider an assistant that reads a support request, looks up an account, proposes a change, and calls an external service. Investigate the earliest point where the evidence diverges from the intended behavior.
| Symptom | Evidence to inspect |
|---|---|
| Correct proposal, no actual change | External operation result and any approval state |
| Wrong account used | Lookup input and account scope |
| Slow final answer | Dependent workflow steps and tool latency |
| Repeated actions | Attempt IDs and external action identifiers |
| Fragmented conversation | Metadata propagation across calls |
A successful generation only establishes that generation returned. If the change requires approval or asynchronous processing, preserve that pending state. Do not mark the user request resolved because a workflow step emitted confident text.
Store compact evidence such as operation status and resource reference. Avoid exporting full account records when a small allowlist is sufficient. Content capture can expand as you add tools, even if your original agent handled only harmless text.
Measure the boundaries separately
Keep three measurements distinct: public request duration, individual step duration, and completion of the external action. Parallel steps overlap, and queue time may occur outside agent generation. The user’s wait can include both.
For cost, verify which provider usage fields are actually present in exported spans. Missing usage should remain unknown. If an exporter or application reports both aggregate and child usage, avoid summing both levels.
In Agnost Users, inspect the full interaction. In Events, examine the received execution evidence. Configured intents can organize demand by user goal; they do not establish that the associated workflow succeeded.
Troubleshooting the integration
No traces arrive. Check that the exporter is registered in the active configuration, the endpoint includes /v1/traces, the protocol matches HTTP/protobuf, and the organization header is populated.
Some steps are missing. Check instrumentation coverage and whether execution moved to another process. An asynchronous job needs propagated context; a trace exporter in the web process cannot observe an uninstrumented worker.
A conversation appears several times. Inspect whether IDs change between turns or whether request and execution records are being treated as separate customers.
Production differs from local development. Check the config’s sampling strategy, the environment that selects the active config, and flushing. A short-lived runtime can terminate before buffered spans are exported unless you call await mastra.observability.flush().
Use Agnost’s Mastra setup for configuration. For stream lifecycle concerns, read Vercel AI SDK monitoring.
Browse all agent observability guides by framework.
Frequently asked questions
What's the best way to monitor a Mastra agent?
Keep Mastra's built-in observability for execution traces and add an OpenTelemetry exporter that sends the same spans to a tool that judges whole conversations. With Agnost AI, add an OtelExporter pointed at https://otel.agnost.ai/v1/traces with your X-Agnost-Org-ID header to the exporters array. Agnost groups runs by user and session, detects failures, frustration, intents, tool-call errors, and loops, judges plain-language rules on every conversation, alerts in Slack or email, and can open a pull request with a fix tested against past runs. Mastra Studio alone is enough for inspecting single runs and duration, token, and cost metrics during development.
How does observability work in Mastra, and what tools can I use?
You pass an Observability instance from @mastra/observability to new Mastra({ observability }). Mastra then records every agent run, model call, tool call, and workflow step as a span. The exporters you list in the config decide where those spans go: MastraStorageExporter for Mastra Studio, MastraPlatformExporter for Mastra's hosted platform, provider exporters such as Langfuse or Arize, or OtelExporter for any OpenTelemetry backend. For production monitoring of whole conversations, Agnost AI receives Mastra spans through OtelExporter and adds failure detection, plain-language rules, alerts, and fix pull requests.
What is @mastra/observability?
It is Mastra's observability package. It exports the Observability class you register on your Mastra instance, the built-in storage and platform exporters, and span output processors such as SensitiveDataFilter, which redacts passwords, tokens, and keys before spans are exported. Each named config holds a serviceName, a list of exporters, optional span output processors, and an optional sampling strategy.
Does Mastra support OpenTelemetry?
Yes. Install @mastra/otel-exporter plus the OTLP transport package for your protocol, such as @opentelemetry/exporter-trace-otlp-proto for HTTP/protobuf, and add an OtelExporter to the exporters array. Spans follow the OpenTelemetry GenAI semantic conventions. Mastra also has an experimental @mastra/otel-bridge for applications that already run their own OpenTelemetry SDK.
Do I need to rewrite my Mastra agents?
No. The exporter belongs in the observability configuration and identity belongs at invocation. Custom spans are additional instrumentation for application behavior the framework cannot know.
Does a trace show whether the user accepted the result?
Only if the application records that evidence. Use an explicit acceptance, confirmed operation, or reviewed outcome rather than inferring satisfaction from a completed trace.
Originally published on agnost.ai.
來源:DEV Community · dev.to