@mastra/mcp-docs-server 1.3.14-alpha.5 → 1.3.14-alpha.7
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.docs/docs/harness/background-tasks.md +53 -0
- package/.docs/docs/harness/durable-agents.md +2 -0
- package/.docs/docs/observability/integrations/exporters/mastra-storage.md +28 -9
- package/.docs/docs/observability/tracing/overview.md +1 -0
- package/.docs/docs/sandbox/overview.md +2 -0
- package/.docs/docs/server/mcp.md +55 -1
- package/.docs/docs/workflows/error-handling.md +34 -2
- package/.docs/integrations/observability/opentelemetry.md +207 -205
- package/.docs/reference/agents/durable-agent.md +2 -2
- package/.docs/reference/auth/google.md +1 -1
- package/.docs/reference/client-js/mastra-client.md +1 -1
- package/.docs/reference/client-js/observability.md +1 -1
- package/.docs/reference/configuration.md +6 -0
- package/.docs/reference/observability/feedback.md +13 -0
- package/.docs/reference/observability/tracing/advanced-queries.md +31 -0
- package/.docs/reference/observability/tracing/exporters/braintrust.md +7 -2
- package/.docs/reference/observability/tracing/exporters/langsmith.md +0 -1
- package/.docs/reference/observability/tracing/exporters/mastra-storage-exporter.md +5 -2
- package/.docs/reference/observability/tracing/exporters/sentry.md +2 -2
- package/.docs/reference/rag/metadata-filters.md +1 -1
- package/.docs/reference/server/builtin-mcp-tools.md +2 -2
- package/.docs/reference/tools/mcp-server.md +23 -0
- package/.docs/reference/workflows/step.md +1 -1
- package/package.json +3 -3
|
@@ -483,6 +483,59 @@ const { tasks, total } = await mastra.backgroundTaskManager?.listTasks({
|
|
|
483
483
|
|
|
484
484
|
These read from storage rather than the pubsub stream, so they're suitable for paginated lists and detail views.
|
|
485
485
|
|
|
486
|
+
## Execution ownership and recovery
|
|
487
|
+
|
|
488
|
+
Every Mastra process with background tasks enabled runs its own manager. You can run several processes or replicas against the same storage backend. The managers coordinate through an execution lease stored on each task record. A lease is a time-limited claim on a task that its owner must keep renewing. When the owner stops renewing it, another manager can take the task over.
|
|
489
|
+
|
|
490
|
+
### Deployment requirements
|
|
491
|
+
|
|
492
|
+
- Every manager must use the same storage backend, and its `updateTask` must apply the write conditions atomically. Mastra's storage adapters do. In-memory storage is only shared within one process.
|
|
493
|
+
- `leaseExpiresAt` is a timestamp written with the owner's clock and compared against the clock of the manager that reads it. Keep server clocks synchronized, for example with Network Time Protocol (NTP), to well under `leaseDurationMs`. If a reader's clock runs ahead by more than the lease, it can recover a task whose owner is still alive. If it runs behind, recovery is delayed. The startup scan recovers a task as soon as its lease has expired by the reader's clock. Follow-up scans wait about one second past the expiry to absorb small differences.
|
|
494
|
+
- A longer [`leaseDurationMs`](https://mastra.ai/reference/configuration) delays recovery after a crash. A shorter one adds storage writes and makes it more likely that a stalled owner loses its lease while still running. The default is 30 seconds and the minimum is 3000 ms.
|
|
495
|
+
|
|
496
|
+
### Lease guarantees and repeated tool calls
|
|
497
|
+
|
|
498
|
+
The lease guarantees that at most one manager can commit a task's state at a time. The tool itself can still run more than once when:
|
|
499
|
+
|
|
500
|
+
- The owner stalls, for example because its event loop is blocked or it can't reach storage, for longer than the lease. Another manager recovers the task while the first execution is still running.
|
|
501
|
+
- The owner crashes after the tool has acted on an external system but before the result is saved. The recovered task runs the tool again.
|
|
502
|
+
- A durable agent restarts the task with `restart()` while the previous execution is still running.
|
|
503
|
+
|
|
504
|
+
Make tools that change external systems safe to repeat, for example by passing the tool call ID as an idempotency key. See [make tools safe to repeat](https://mastra.ai/docs/harness/durable-agents).
|
|
505
|
+
|
|
506
|
+
A resume interrupted by shutdown is the one exception to the single-committer guarantee. It restores the previous `suspended` state with a write that checks only that the task is `running`, and that write can overwrite a manager that took the task over in the meantime.
|
|
507
|
+
|
|
508
|
+
### Claim and renew a lease
|
|
509
|
+
|
|
510
|
+
Each manager gets a random owner ID when it's created. A restarted process gets a new ID and counts as a new owner.
|
|
511
|
+
|
|
512
|
+
Before a manager runs a task, it claims the task with a conditional write. The write sets the status to `running`, records the manager's `ownerId`, and sets `leaseExpiresAt` to the current time plus `leaseDurationMs`. It only applies if the task still has the status, owner, and lease that the manager last read. When two managers race for the same task, one claim succeeds and the other manager skips the task without running it.
|
|
513
|
+
|
|
514
|
+
While the task runs, the owner renews the lease every `leaseDurationMs / 3`, with a minimum of one second. Each renewal is conditional on the task still being `running` under the same owner. The task's final writes, such as `completed`, `failed`, `timed_out`, or `suspended`, carry the same condition, so a manager that lost the task can't overwrite the result of the manager that replaced it.
|
|
515
|
+
|
|
516
|
+
The owner stops renewing when the task completes, fails, or suspends. On shutdown, the manager releases the leases it still holds, so other managers can recover those tasks without waiting for the lease to expire. A lease that isn't released, for example because the process crashed, expires on its own.
|
|
517
|
+
|
|
518
|
+
### Recover a task from a dead owner
|
|
519
|
+
|
|
520
|
+
A manager treats a `running` task as abandoned only after its lease expires.
|
|
521
|
+
|
|
522
|
+
When `recoverStaleTasksOnStart` is `true`, the default, each manager that runs tasks scans for abandoned tasks on startup. If the scan finds a lease that hasn't expired yet, the manager scans again shortly after that lease expires, and repeats until no live lease is left. A task that a manager starts after that and then abandons waits for the next startup scan. For each task the scan recovers:
|
|
523
|
+
|
|
524
|
+
- If the task has `maxRetries` above `0`, it returns to `pending` and is dispatched again.
|
|
525
|
+
- Otherwise, it fails with `Worker process terminated before task completed`.
|
|
526
|
+
|
|
527
|
+
The recovery write is conditional on the owner and lease that the scan read, so only one manager recovers each task.
|
|
528
|
+
|
|
529
|
+
If the pubsub redelivers the unacknowledged dispatch of an abandoned task, the redelivery claims the task once its lease expires and runs it again, even when `maxRetries` is `0`.
|
|
530
|
+
|
|
531
|
+
The manager that runs the recovered task needs an executor for it. See the known limitations under [non-agent owners](#non-agent-owners).
|
|
532
|
+
|
|
533
|
+
`manager.restart(taskId)` is an explicit takeover. It claims a `running` task even while another manager holds a live lease. Durable agents use it when a redelivered step finds the task for its tool call. The task's results then reach the new stream. A restart on the manager that already runs the task doesn't stop the earlier execution. Both executions share an owner ID, and the earlier one can commit first.
|
|
534
|
+
|
|
535
|
+
### Stop work after losing a lease
|
|
536
|
+
|
|
537
|
+
When a lease renewal fails because the task is now owned by another manager or was cancelled, the previous owner aborts the `abortSignal` passed to the tool. After a takeover, `abortSignal.reason` is an error with the message `Background task execution ownership was taken over by another worker`. The abort is best effort. If the manager can't read the task at that point, it doesn't retry the abort. The previous owner normally notices at its next renewal. A stalled event loop or slow storage can delay that renewal. A tool that ignores `abortSignal` keeps running until it returns, but its result is rejected.
|
|
538
|
+
|
|
486
539
|
## Non-agent owners
|
|
487
540
|
|
|
488
541
|
Code other than agents can run tasks through the manager. For example, an MCP server can run long tool calls as background tasks. The task's `agentId` is its owner key, and agent streams, `untilIdle`, and the end-of-step wait only see tasks whose `agentId` matches the agent. Use a namespaced owner key such as `mcp-server:<serverId>` so it can't collide with a real agent ID. Mastra doesn't enforce this.
|
|
@@ -249,6 +249,8 @@ await durableAgent.stream('Research topic', {
|
|
|
249
249
|
|
|
250
250
|
Visit [Background tasks](https://mastra.ai/docs/harness/background-tasks) for the full background task guide, including configuration, subagents, and suspend/resume.
|
|
251
251
|
|
|
252
|
+
Background tasks have their own execution lease, stored on each task record, separate from the run claims described in [run ownership](#run-ownership). Replicas that share storage can run and recover each other's background tasks. Recovery and step redelivery can still run a background tool call more than once. See [Execution ownership and recovery](https://mastra.ai/docs/harness/background-tasks).
|
|
253
|
+
|
|
252
254
|
## Cleanup
|
|
253
255
|
|
|
254
256
|
Every `stream()` and `observe()` call returns a `cleanup` function that tears the run down: it unsubscribes from PubSub, removes the run from the internal registry, and deletes the run's cached events so nobody can replay it afterward.
|
|
@@ -130,12 +130,14 @@ MastraStorageExporter automatically selects the optimal tracing strategy based o
|
|
|
130
130
|
|
|
131
131
|
### Available Strategies
|
|
132
132
|
|
|
133
|
-
| Strategy | Description | Use Case
|
|
134
|
-
| ---------------------- | ------------------------------------------------------------------------------------- |
|
|
135
|
-
| **realtime** | Process each event immediately |
|
|
136
|
-
| **batch-with-updates** | Buffer events and batch write with full lifecycle support | Low volume Production
|
|
137
|
-
| **insert-only** | Only process completed spans, ignore updates | High volume Production
|
|
138
|
-
| **event-sourced** | Write one row when a span starts and another when it ends, then collapse them on read | High volume Production, in-progress traces
|
|
133
|
+
| Strategy | Description | Use Case |
|
|
134
|
+
| ---------------------- | ------------------------------------------------------------------------------------- | ---------------------------------------------- |
|
|
135
|
+
| **realtime** | Process each event immediately | Single-process local development and debugging |
|
|
136
|
+
| **batch-with-updates** | Buffer events and batch write with full lifecycle support | Low volume Production |
|
|
137
|
+
| **insert-only** | Only process completed spans, ignore updates | High volume Production |
|
|
138
|
+
| **event-sourced** | Write one row when a span starts and another when it ends, then collapse them on read | High volume Production, in-progress traces |
|
|
139
|
+
|
|
140
|
+
> **Note:** `realtime` assumes one process owns a span from start to end, so it isn't supported with durable execution (durable agents, and Inngest, Temporal, or evented workflows). When any of these is registered, the exporter logs one warning and runs `batch-with-updates`.
|
|
139
141
|
|
|
140
142
|
### Strategy Configuration
|
|
141
143
|
|
|
@@ -185,7 +187,7 @@ The following storage providers **don't support** the observability domain. If y
|
|
|
185
187
|
|
|
186
188
|
### Strategy Benefits
|
|
187
189
|
|
|
188
|
-
- **realtime**: Immediate visibility, best for debugging
|
|
190
|
+
- **realtime**: Immediate visibility, best for debugging in a single process
|
|
189
191
|
- **batch-with-updates**: 10-100x throughput improvement, full span lifecycle
|
|
190
192
|
- **insert-only**: Additional 70% reduction in database operations, perfect for analytics
|
|
191
193
|
- **event-sourced**: Append-only like insert-only, but in-progress traces stay visible in Studio while a run executes
|
|
@@ -227,6 +229,23 @@ The MastraStorageExporter includes reliable error handling for production use:
|
|
|
227
229
|
- **Persistent Failures**: Drop batch after 4 failed attempts
|
|
228
230
|
- **Buffer Overflow**: Prevent memory issues during storage outages
|
|
229
231
|
|
|
232
|
+
### Spans ended by another process
|
|
233
|
+
|
|
234
|
+
With durable execution, a worker can end a span before the process that started it stores the span. With `batch-with-updates`, the worker's exporter holds that end and retries it with `maxRetries` and `retryDelayMs`. Other flushes don't send it before its retry time. With `realtime`, the exporter doesn't retry and drops the end right away. An update that doesn't apply is dropped right away, because a retried update could overwrite a newer one. Only an end is retried, since it carries the span's full state.
|
|
235
|
+
|
|
236
|
+
This retry needs a store with conditional span updates: libSQL, PostgreSQL, or the in-memory store. On other stores, the exporter holds the end until its retries run out, then drops it with `retry-exhausted`.
|
|
237
|
+
|
|
238
|
+
The retries must last longer than the other process takes to store the span:
|
|
239
|
+
|
|
240
|
+
- **Worker**: The defaults retry for about 7.5 seconds (500ms, 1s, 2s, 4s).
|
|
241
|
+
- **Process that started the span**: It stores the span within its `maxBatchWaitMs` (5 seconds by default), plus write time and any retries of its own.
|
|
242
|
+
|
|
243
|
+
If you raise `maxBatchWaitMs` on that process, or lower `maxRetries` or `retryDelayMs` on the worker, change the other settings to keep this margin. When the retries run out, the exporter drops the end with `span-not-updatable` and the span stays open in Studio.
|
|
244
|
+
|
|
245
|
+
At `shutdown()`, the exporter tries each held end one last time. It reports an end that still doesn't apply as `span-not-updatable`, and an end whose write fails as `retry-exhausted`.
|
|
246
|
+
|
|
247
|
+
A serverless worker can freeze right after a run's flush. The retry timer may then never fire, so the end isn't stored and no drop event is emitted.
|
|
248
|
+
|
|
230
249
|
## Dropped observability events
|
|
231
250
|
|
|
232
251
|
`DefaultExporter` emits structured drop events when it can't persist observability data. Register an exporter or bridge with `onDroppedEvent` to forward these drops to alerting or monitoring.
|
|
@@ -235,7 +254,7 @@ Events are dropped for these reasons:
|
|
|
235
254
|
|
|
236
255
|
- `unsupported-storage`: The storage provider doesn't implement the signal type.
|
|
237
256
|
- `retry-exhausted`: The exporter retried a batch up to `maxRetries` times and then dropped it.
|
|
238
|
-
- `span-not-updatable`: Under `realtime` or `batch-with-updates`, a span update or end reached storage but didn't apply, because the span was never stored or had already ended. Ended spans don't change.
|
|
257
|
+
- `span-not-updatable`: Under `realtime` or `batch-with-updates`, a span update or end reached storage but didn't apply, because the span was never stored or had already ended. Ended spans don't change. With `batch-with-updates`, an end for a span another process started is dropped only after its [retries](#spans-ended-by-another-process) run out.
|
|
239
258
|
|
|
240
259
|
The following example demonstrates forwarding drop details to a monitoring endpoint:
|
|
241
260
|
|
|
@@ -269,7 +288,7 @@ class DropAlertExporter extends BaseExporter {
|
|
|
269
288
|
// Zero config - recommended for most users
|
|
270
289
|
new MastraStorageExporter()
|
|
271
290
|
|
|
272
|
-
//
|
|
291
|
+
// Single-process development override
|
|
273
292
|
new MastraStorageExporter({
|
|
274
293
|
strategy: 'realtime', // Immediate visibility for debugging
|
|
275
294
|
})
|
|
@@ -987,6 +987,7 @@ Mastra automatically creates spans for:
|
|
|
987
987
|
|
|
988
988
|
- **Agent runs**: Complete execution with instructions and tools
|
|
989
989
|
- **Signal-triggered runs**: The `AGENT_RUN` span records a starting signal's `id`, `type`, `tagName`, and `attributes` under `attributes.signal`
|
|
990
|
+
- **Run setup**: `agent:load-thread` covers the memory thread lookup and creation, and `agent:prepare-tools` covers tool resolution before the first model call. The `agent:prepare-tools` output reports `toolCount`. Any tool source that takes 100 ms or longer is listed with its duration in `slowSourcesMs`.
|
|
990
991
|
- **LLM calls**: Model interactions with tokens and parameters
|
|
991
992
|
- **Tool executions**: Function calls with inputs and outputs
|
|
992
993
|
- **Memory operations**: Thread and semantic recall
|
|
@@ -285,6 +285,8 @@ Each callback receives the process `pid` and, when available, the `toolCallId`,
|
|
|
285
285
|
|
|
286
286
|
By default, background processes inherit the agent's abort signal and stop when the agent disconnects. Set `abortSignal` to a custom signal, or use `null` or `false` when the process should continue after the request ends.
|
|
287
287
|
|
|
288
|
+
The `timeout` input of `execute_command` also applies to background commands: the process is stopped after that many seconds. A `timeout` of `0` sets no timer in `LocalSandbox`. When `timeout` is omitted, the sandbox provider decides. `LocalSandbox` sets no timer for background commands, while `E2BSandbox` uses the `timeout` option it was created with, which defaults to 300 seconds. That option is in milliseconds, unlike the `execute_command` `timeout`, so a 60-second default needs `new E2BSandbox({ timeout: 60000 })`. The tool description tells agents to omit `timeout` for dev servers and other commands meant to keep running.
|
|
289
|
+
|
|
288
290
|
For the full `SandboxProcessManager` API, including programmatic process spawning, output, and standard input, see the [`SandboxProcessManager` reference](https://mastra.ai/reference/workspace/process-manager).
|
|
289
291
|
|
|
290
292
|
## Lifecycle and persistence
|
package/.docs/docs/server/mcp.md
CHANGED
|
@@ -218,9 +218,63 @@ In read-only mode, the query and aggregate tools stay available because their ro
|
|
|
218
218
|
> })
|
|
219
219
|
> ```
|
|
220
220
|
|
|
221
|
+
### MCP Apps
|
|
222
|
+
|
|
223
|
+
Clients that render [MCP Apps](https://modelcontextprotocol.io/extensions/apps/overview), such as the Claude app, can show tool results as interactive views. Install `@mastra/mcp-apps-components` next to `@mastra/server` to turn them on:
|
|
224
|
+
|
|
225
|
+
**npm**:
|
|
226
|
+
|
|
227
|
+
```bash
|
|
228
|
+
npm install @mastra/mcp-apps-components
|
|
229
|
+
```
|
|
230
|
+
|
|
231
|
+
**pnpm**:
|
|
232
|
+
|
|
233
|
+
```bash
|
|
234
|
+
pnpm add @mastra/mcp-apps-components
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
**Yarn**:
|
|
238
|
+
|
|
239
|
+
```bash
|
|
240
|
+
yarn add @mastra/mcp-apps-components
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
**Bun**:
|
|
244
|
+
|
|
245
|
+
```bash
|
|
246
|
+
bun add @mastra/mcp-apps-components
|
|
247
|
+
```
|
|
248
|
+
|
|
249
|
+
With it installed, `get_trace` opens the trace in Studio's trace timeline. Select a span to see its input, output, and attributes. The view loads the rest of a long trace and each span through `get_trace` and `get_span`, so it shows only what the caller's permissions allow.
|
|
250
|
+
|
|
251
|
+
`query_traces` and `list_traces` open Studio's observability explorer on the results. The time range, sort, and filters the model asked for stay applied, and you can clear the model's filters to see every trace. From there you can filter, change the time range, page through traces, and open a trace on its timeline. If the observability store supports span and thread queries, the explorer also has Spans and Threads tabs. Every query goes back through the same MCP tools, with the caller's permissions.
|
|
252
|
+
|
|
253
|
+
`list_logs` opens the explorer on its Logs tab, with the level, entity, and time range the model asked for applied. Select a log to see its details, or open the trace it belongs to. With the `observability_analytics` toolset enabled, `analyze_metrics` opens the Metrics tab: Studio's metrics dashboard of token usage, latency, and run counts. Select a breakdown row to see its traces or logs. The explorer shows the Logs and Metrics tabs only when the store keeps logs or metrics and the caller can use the tools that read them.
|
|
254
|
+
|
|
255
|
+
The apps work with the conversation, where the client supports it:
|
|
256
|
+
|
|
257
|
+
- The app tells the model what's on screen: the open trace and span, the explorer's tab and filters, or the open log. Ask about "this trace" and the model knows which one you mean.
|
|
258
|
+
- **Ask about this** buttons on a trace, span, or log send a message about it to the conversation.
|
|
259
|
+
- **Fullscreen** opens the app full screen.
|
|
260
|
+
- **Open in Studio** opens the same view in Studio. With `mastra dev` this is the local Studio. Otherwise, set `studioUrl` to your Studio's URL to show the button.
|
|
261
|
+
- When an app shows a result, the model gets a short text summary of the rows, such as each trace's name, status, and duration, instead of the full JSON. The app still gets the full result. Clients without MCP Apps get the full JSON as before.
|
|
262
|
+
|
|
263
|
+
Apps are served only to clients that declare MCP Apps support. Other clients, such as Claude Code in a terminal, get the same tools and JSON results as without the package. Set `apps: false` to turn them off:
|
|
264
|
+
|
|
265
|
+
```typescript
|
|
266
|
+
import { Mastra } from '@mastra/core'
|
|
267
|
+
|
|
268
|
+
export const mastra = new Mastra({
|
|
269
|
+
server: {
|
|
270
|
+
mcp: { apps: false },
|
|
271
|
+
},
|
|
272
|
+
})
|
|
273
|
+
```
|
|
274
|
+
|
|
221
275
|
### Agents creating agents
|
|
222
276
|
|
|
223
|
-
`create_stored_agent` lets an MCP client create agents that other clients can then call. It needs `stored-agents:write`. A created agent is owned by the caller and is private by default. Without a caller identity, such as when `server.auth` isn't configured, the agent has no owner and is public, even with `visibility: 'private'`. A private agent is hidden from other users in `list_agents` and `list_stored_agents
|
|
277
|
+
`create_stored_agent` lets an MCP client create agents that other clients can then call. It needs `stored-agents:write`. A created agent is owned by the caller and is private by default. Without a caller identity, such as when `server.auth` isn't configured, the agent has no owner and is public, even with `visibility: 'private'`. A private agent is hidden from other users in `list_agents` and `list_stored_agents`. Calling it as anyone other than an admin or a user granted that agent by id answers as if it doesn't exist, the same as over HTTP. Set `visibility: 'public'` to let every user call it. Only the owner, admins, and users granted that agent by id can edit it either way. An agent with no owner can be edited by any user with `stored-agents:write`. See [stored agent visibility](https://mastra.ai/docs/studio/editor). When the agent builder restricts models, the MCP tools accept only allowed models for the agent's model (the `provider` and `name` it runs, in each conditional variant), for any model named in `defaultOptions` (such as `structuredOutput.model`), for each enabled entry of the fallback `modelList`, for the memory models (the Observational Memory observer and reflector models and the title model), and for the `model` of every input and output processor step, at any depth of the processor graph. They also reject anything that would run on a default model the policy can't check: `observationalMemory: true`, an Observational Memory config without a `model`, memory left out on create (which the agent builder fills with Observational Memory on its default model), or a processor that needs a model, such as `moderation`, without one. Set an allowed `model` instead. A stored `model` takes only `provider`, `name`, and model settings such as `temperature`. Other keys, such as `modelId` or `providerId`, are rejected. If the agent builder's policy can't be loaded, the tools return an error instead of saving unchecked. `list_available_models` returns the allowed models. The HTTP route doesn't apply this check, so a user who can call `POST /stored/agents` directly can still save any model. Embedding models (`memory.embedder`) aren't on the builder's model list and aren't checked. Tool allowlists aren't checked when an agent is saved, so a created agent can use any tool the server has. Its tools run with the permissions of the user who calls it.
|
|
224
278
|
|
|
225
279
|
Observational Memory starts observing only after a thread reaches its token threshold, 30,000 tokens by default. For a short demo, set a lower `observation.messageTokens` so the agent learns from a few messages. Observational Memory processes messages in the background, so right after `call_agent`, call `get_observations` with `waitForPending: true` to wait (up to 30 seconds) for it to finish before reading.
|
|
226
280
|
|
|
@@ -92,7 +92,7 @@ const orderWorkflow = createWorkflow({
|
|
|
92
92
|
|
|
93
93
|
The `onFinish` callback receives:
|
|
94
94
|
|
|
95
|
-
- `status` - The workflow status
|
|
95
|
+
- `status` - The workflow status, typed as `WorkflowRunStatus`: `'running'`, `'success'`, `'failed'`, `'tripwire'`, `'suspended'`, `'waiting'`, `'pending'`, `'canceled'`, `'bailed'`, `'paused'`, or `'skipped'`
|
|
96
96
|
- `result` - The workflow output (on success)
|
|
97
97
|
- `error` - Error details (on failure)
|
|
98
98
|
- `steps` - Individual step results
|
|
@@ -100,7 +100,7 @@ The `onFinish` callback receives:
|
|
|
100
100
|
- `runId` - The unique identifier for this workflow run
|
|
101
101
|
- `workflowId` - The workflow's identifier
|
|
102
102
|
- `resourceId` - Optional resource identifier (if provided when creating the run)
|
|
103
|
-
- `getInitData
|
|
103
|
+
- `getInitData()` - Function that returns the initial input data
|
|
104
104
|
- `mastra` - The Mastra instance (if workflow is registered with Mastra)
|
|
105
105
|
- `requestContext` - Request-scoped context data
|
|
106
106
|
- `logger` - The workflow's logger instance
|
|
@@ -231,6 +231,38 @@ const step1 = createStep({
|
|
|
231
231
|
})
|
|
232
232
|
```
|
|
233
233
|
|
|
234
|
+
## Skipping retries with `MastraNonRetryableError`
|
|
235
|
+
|
|
236
|
+
Some failures are permanent, for example invalid input or a resource that doesn't exist. Retrying them only delays the failure. Throw `MastraNonRetryableError` from a step to fail it immediately, without using the remaining attempts from `retries` or `retryConfig`:
|
|
237
|
+
|
|
238
|
+
```typescript
|
|
239
|
+
import { createStep } from '@mastra/core/workflows'
|
|
240
|
+
import { MastraNonRetryableError } from '@mastra/core/error'
|
|
241
|
+
import { z } from 'zod'
|
|
242
|
+
|
|
243
|
+
const step1 = createStep({
|
|
244
|
+
id: 'step-1',
|
|
245
|
+
inputSchema: z.object({ templateId: z.string() }),
|
|
246
|
+
outputSchema: z.object({ value: z.string() }),
|
|
247
|
+
execute: async ({ inputData }) => {
|
|
248
|
+
const response = await fetch(`https://example.com/templates/${inputData.templateId}`)
|
|
249
|
+
|
|
250
|
+
if (response.status === 404) {
|
|
251
|
+
throw new MastraNonRetryableError(`Template ${inputData.templateId} not found`)
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
if (!response.ok) {
|
|
255
|
+
throw new Error(`Request failed with status ${response.status}`)
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
return { value: await response.text() }
|
|
259
|
+
},
|
|
260
|
+
retries: 3,
|
|
261
|
+
})
|
|
262
|
+
```
|
|
263
|
+
|
|
264
|
+
In this example, a `404` response fails the step on the first attempt. Other failed responses throw a regular `Error`. The step retries up to three times.
|
|
265
|
+
|
|
234
266
|
## Conditional branching
|
|
235
267
|
|
|
236
268
|
You can create alternative workflow paths based on the success or failure of previous steps using conditional logic:
|
|
@@ -8,13 +8,13 @@ Mastra supports OpenTelemetry (OTEL) through an exporter for sending traces and
|
|
|
8
8
|
|
|
9
9
|
## Exporter
|
|
10
10
|
|
|
11
|
-
The OpenTelemetry exporter sends your traces and logs using standardized [OpenTelemetry Semantic Conventions for GenAI](https://opentelemetry.io/docs/specs/semconv/gen-ai/). This ensures broad compatibility with platforms like
|
|
11
|
+
The OpenTelemetry exporter sends your traces and logs using standardized [OpenTelemetry Semantic Conventions for GenAI](https://opentelemetry.io/docs/specs/semconv/gen-ai/). This ensures broad compatibility with platforms like Agnost AI, Dash0, Datadog, Laminar, Latitude, MLflow, New Relic, Sazabi, Sentry, SigNoz, telemetry.dev, Traceloop, and more.
|
|
12
12
|
|
|
13
13
|
### Installation
|
|
14
14
|
|
|
15
15
|
Each provider requires specific protocol packages. Install the base exporter plus the protocol package for your provider:
|
|
16
16
|
|
|
17
|
-
#### For HTTP/Protobuf providers (
|
|
17
|
+
#### For HTTP/Protobuf providers (Agnost AI, Laminar, Latitude, MLflow, New Relic, Sentry, SigNoz, telemetry.dev)
|
|
18
18
|
|
|
19
19
|
**npm**:
|
|
20
20
|
|
|
@@ -66,7 +66,7 @@ yarn add @mastra/otel-exporter@latest @opentelemetry/exporter-trace-otlp-grpc @g
|
|
|
66
66
|
bun add @mastra/otel-exporter@latest @opentelemetry/exporter-trace-otlp-grpc @grpc/grpc-js
|
|
67
67
|
```
|
|
68
68
|
|
|
69
|
-
#### For HTTP/JSON providers (
|
|
69
|
+
#### For HTTP/JSON providers (Sazabi, Traceloop)
|
|
70
70
|
|
|
71
71
|
**npm**:
|
|
72
72
|
|
|
@@ -99,129 +99,13 @@ All providers support zero-config setup via environment variables. Set the appro
|
|
|
99
99
|
| Provider | Environment Variables |
|
|
100
100
|
| --------- | ------------------------------------------------------------------------------------------- |
|
|
101
101
|
| Dash0 | `DASH0_API_KEY` (required), `DASH0_ENDPOINT` (required), `DASH0_DATASET` (optional) |
|
|
102
|
-
|
|
|
102
|
+
| Laminar | `LMNR_PROJECT_API_KEY` (required), `LAMINAR_ENDPOINT` (optional) |
|
|
103
103
|
| New Relic | `NEW_RELIC_LICENSE_KEY` (required), `NEW_RELIC_ENDPOINT` (optional) |
|
|
104
|
+
| SigNoz | `SIGNOZ_API_KEY` (required), `SIGNOZ_REGION` (optional), `SIGNOZ_ENDPOINT` (optional) |
|
|
104
105
|
| Traceloop | `TRACELOOP_API_KEY` (required), `TRACELOOP_DESTINATION_ID`, `TRACELOOP_ENDPOINT` (optional) |
|
|
105
|
-
| Laminar | `LMNR_PROJECT_API_KEY` (required), `LAMINAR_ENDPOINT` (optional) |
|
|
106
106
|
|
|
107
107
|
### Provider configurations
|
|
108
108
|
|
|
109
|
-
#### Sentry
|
|
110
|
-
|
|
111
|
-
[Sentry](https://sentry.io/) accepts OpenTelemetry traces and logs through its OTLP endpoints. In Sentry, open [**Project Settings** > **Client Keys (DSN)**](https://sentry.io/settings/projects/) and copy the OTLP traces endpoint and authentication header. Add both values to your environment:
|
|
112
|
-
|
|
113
|
-
```bash
|
|
114
|
-
SENTRY_OTLP_ENDPOINT=https://o000000.ingest.sentry.io/api/0000000/integration/otlp/v1/traces
|
|
115
|
-
SENTRY_OTLP_AUTH_HEADER="sentry sentry_key=..."
|
|
116
|
-
```
|
|
117
|
-
|
|
118
|
-
Use the `custom` provider with HTTP/Protobuf:
|
|
119
|
-
|
|
120
|
-
```typescript
|
|
121
|
-
new OtelExporter({
|
|
122
|
-
provider: {
|
|
123
|
-
custom: {
|
|
124
|
-
endpoint: process.env.SENTRY_OTLP_ENDPOINT!,
|
|
125
|
-
protocol: 'http/protobuf',
|
|
126
|
-
headers: {
|
|
127
|
-
'x-sentry-auth': process.env.SENTRY_OTLP_AUTH_HEADER!,
|
|
128
|
-
},
|
|
129
|
-
},
|
|
130
|
-
},
|
|
131
|
-
})
|
|
132
|
-
```
|
|
133
|
-
|
|
134
|
-
See [Sentry's OTLP documentation](https://docs.sentry.io/concepts/otlp/) for endpoint setup, supported signals, and current ingestion limits.
|
|
135
|
-
|
|
136
|
-
Choose an exporter based on your setup:
|
|
137
|
-
|
|
138
|
-
- `OtelExporter`: Sends vendor-neutral traces and logs over OTLP. Use it with an existing OpenTelemetry pipeline or when you want backend portability.
|
|
139
|
-
- [`SentryExporter`](https://mastra.ai/integrations/observability/sentry): Uses the Sentry SDK to map Mastra span types to Sentry operations, add AI monitoring attributes, and capture span errors as Sentry issues.
|
|
140
|
-
|
|
141
|
-
#### MLflow
|
|
142
|
-
|
|
143
|
-
[MLflow](https://mlflow.org/docs/latest/genai/tracing/integrations/listing/mastra) supports native Mastra tracing through its OTLP endpoint at `/v1/traces`. Use the `custom` provider with HTTP/Protobuf and include the experiment header so traces are routed to the correct MLflow experiment:
|
|
144
|
-
|
|
145
|
-
```typescript
|
|
146
|
-
new OtelExporter({
|
|
147
|
-
provider: {
|
|
148
|
-
custom: {
|
|
149
|
-
endpoint: `${process.env.MLFLOW_TRACKING_URI}/v1/traces`,
|
|
150
|
-
protocol: 'http/protobuf',
|
|
151
|
-
headers: {
|
|
152
|
-
'x-mlflow-experiment-id': process.env.MLFLOW_EXPERIMENT_ID,
|
|
153
|
-
},
|
|
154
|
-
},
|
|
155
|
-
},
|
|
156
|
-
})
|
|
157
|
-
```
|
|
158
|
-
|
|
159
|
-
#### Latitude
|
|
160
|
-
|
|
161
|
-
[Latitude](https://latitude.so) is an open-source LLM observability and evaluation platform that ingests OTLP traces. Use the `custom` provider with HTTP/Protobuf, pointing at Latitude's ingestion endpoint and authenticating with your API key and project slug:
|
|
162
|
-
|
|
163
|
-
```typescript
|
|
164
|
-
new OtelExporter({
|
|
165
|
-
provider: {
|
|
166
|
-
custom: {
|
|
167
|
-
endpoint: 'https://ingest.latitude.so/v1/traces',
|
|
168
|
-
protocol: 'http/protobuf',
|
|
169
|
-
headers: {
|
|
170
|
-
Authorization: `Bearer ${process.env.LATITUDE_API_KEY}`,
|
|
171
|
-
'X-Latitude-Project': process.env.LATITUDE_PROJECT,
|
|
172
|
-
},
|
|
173
|
-
},
|
|
174
|
-
},
|
|
175
|
-
})
|
|
176
|
-
```
|
|
177
|
-
|
|
178
|
-
Sign up at [console.latitude.so](https://console.latitude.so/login), or self-host and point the endpoint at your own ingestion host.
|
|
179
|
-
|
|
180
|
-
#### telemetry.dev
|
|
181
|
-
|
|
182
|
-
[telemetry.dev](https://telemetry.dev) ingests OTLP/HTTP protobuf traces and normalizes OpenTelemetry GenAI semantic conventions into model, provider, token, latency, and cost fields. Use the `custom` provider with your project API key:
|
|
183
|
-
|
|
184
|
-
```bash
|
|
185
|
-
TELEMETRY_DEV_API_KEY=td_live_...
|
|
186
|
-
```
|
|
187
|
-
|
|
188
|
-
```typescript
|
|
189
|
-
new OtelExporter({
|
|
190
|
-
provider: {
|
|
191
|
-
custom: {
|
|
192
|
-
endpoint: 'https://ingest.telemetry.dev/v1/traces',
|
|
193
|
-
protocol: 'http/protobuf',
|
|
194
|
-
headers: {
|
|
195
|
-
Authorization: `Bearer ${process.env.TELEMETRY_DEV_API_KEY}`,
|
|
196
|
-
},
|
|
197
|
-
},
|
|
198
|
-
},
|
|
199
|
-
})
|
|
200
|
-
```
|
|
201
|
-
|
|
202
|
-
#### Sazabi
|
|
203
|
-
|
|
204
|
-
[Sazabi](https://sazabi.com) is an AI-native observability platform that ingests OTLP traces. In Sazabi, add a Mastra log source and copy its intake URL. The URL carries your project key, so no auth header is needed:
|
|
205
|
-
|
|
206
|
-
```bash
|
|
207
|
-
SAZABI_INTAKE_URL=https://...
|
|
208
|
-
```
|
|
209
|
-
|
|
210
|
-
Use the `custom` provider with HTTP/JSON:
|
|
211
|
-
|
|
212
|
-
```typescript
|
|
213
|
-
new OtelExporter({
|
|
214
|
-
provider: {
|
|
215
|
-
custom: {
|
|
216
|
-
endpoint: process.env.SAZABI_INTAKE_URL!,
|
|
217
|
-
protocol: 'http/json',
|
|
218
|
-
},
|
|
219
|
-
},
|
|
220
|
-
})
|
|
221
|
-
```
|
|
222
|
-
|
|
223
|
-
See [Sazabi's Mastra guide](https://docs.sazabi.com/catalogs/log-sources/send-to-an-endpoint/mastra) for the full setup.
|
|
224
|
-
|
|
225
109
|
#### Agnost AI
|
|
226
110
|
|
|
227
111
|
[Agnost AI](https://agnost.ai) ingests OTLP/HTTP protobuf traces and groups them into conversations and users for production agent monitoring. Use the `custom` provider with your organization ID:
|
|
@@ -316,23 +200,78 @@ export const mastra = new Mastra({
|
|
|
316
200
|
|
|
317
201
|
> **Note:** Get your Dash0 endpoint from your dashboard. It should be in the format `ingress.{region}.aws.dash0.com:4317`.
|
|
318
202
|
|
|
319
|
-
####
|
|
203
|
+
#### Datadog
|
|
204
|
+
|
|
205
|
+
[Datadog](https://www.datadoghq.com/) APM provides application performance monitoring with distributed tracing. To send traces to Datadog via OTLP, you need the Datadog Agent running with OTLP ingestion enabled.
|
|
320
206
|
|
|
321
|
-
[
|
|
207
|
+
Datadog uses gRPC for OTLP ingestion, which requires explicit imports and [bundler configuration](https://mastra.ai/reference/configuration) to work correctly:
|
|
208
|
+
|
|
209
|
+
```typescript
|
|
210
|
+
// Explicitly import gRPC dependencies for the bundler
|
|
211
|
+
import '@grpc/grpc-js'
|
|
212
|
+
import '@opentelemetry/exporter-trace-otlp-grpc'
|
|
213
|
+
import { Mastra } from '@mastra/core'
|
|
214
|
+
import { Observability } from '@mastra/observability'
|
|
215
|
+
import { OtelExporter, type ExportProtocol } from '@mastra/otel-exporter'
|
|
216
|
+
|
|
217
|
+
export const mastra = new Mastra({
|
|
218
|
+
// Add grpc-js to externals so it's handled at runtime
|
|
219
|
+
bundler: {
|
|
220
|
+
externals: ['@grpc/grpc-js'],
|
|
221
|
+
},
|
|
222
|
+
observability: new Observability({
|
|
223
|
+
configs: {
|
|
224
|
+
default: {
|
|
225
|
+
serviceName: 'my-service',
|
|
226
|
+
exporters: [
|
|
227
|
+
new OtelExporter({
|
|
228
|
+
provider: {
|
|
229
|
+
custom: {
|
|
230
|
+
endpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4317',
|
|
231
|
+
protocol: (process.env.OTEL_EXPORTER_OTLP_PROTOCOL || 'grpc') as ExportProtocol,
|
|
232
|
+
headers: {},
|
|
233
|
+
},
|
|
234
|
+
},
|
|
235
|
+
}),
|
|
236
|
+
],
|
|
237
|
+
},
|
|
238
|
+
},
|
|
239
|
+
}),
|
|
240
|
+
})
|
|
241
|
+
```
|
|
242
|
+
|
|
243
|
+
> **Note:** The Datadog Agent must be configured with OTLP ingestion enabled. Add the following to your `datadog.yaml`:
|
|
244
|
+
>
|
|
245
|
+
> ```yaml
|
|
246
|
+
> otlp_config:
|
|
247
|
+
> receiver:
|
|
248
|
+
> protocols:
|
|
249
|
+
> grpc:
|
|
250
|
+
> endpoint: 0.0.0.0:4317
|
|
251
|
+
> ```
|
|
252
|
+
>
|
|
253
|
+
> The default OTLP endpoint is `http://localhost:4317` when running the Datadog Agent locally.
|
|
254
|
+
|
|
255
|
+
> **Warning:** The explicit imports of `@grpc/grpc-js` and `@opentelemetry/exporter-trace-otlp-grpc` at the top of the file, along with the [`bundler.externals`](https://mastra.ai/reference/configuration) configuration, are required for the gRPC transport to work correctly. Without these, you may encounter connection issues.
|
|
256
|
+
|
|
257
|
+
> **Datadog-Native Exporter:** For Datadog-specific features like automatic span type mapping, LLM span categorization, and simplified setup without gRPC configuration, consider using the dedicated [`@mastra/datadog`](https://mastra.ai/integrations/observability/datadog) exporter instead. It provides optimized integration with Datadog's APM platform.
|
|
258
|
+
|
|
259
|
+
#### Laminar
|
|
260
|
+
|
|
261
|
+
[Laminar](https://laminar.sh/) provides specialized LLM observability and analytics.
|
|
322
262
|
|
|
323
263
|
##### Zero-Config Setup
|
|
324
264
|
|
|
325
265
|
```bash
|
|
326
266
|
# Required
|
|
327
|
-
|
|
267
|
+
LMNR_PROJECT_API_KEY=your-api-key
|
|
328
268
|
|
|
329
269
|
# Optional
|
|
330
|
-
|
|
331
|
-
SIGNOZ_ENDPOINT=https://my-signoz.example.com # For self-hosted
|
|
270
|
+
LAMINAR_ENDPOINT=https://api.lmnr.ai/v1/traces
|
|
332
271
|
```
|
|
333
272
|
|
|
334
273
|
```typescript
|
|
335
|
-
new OtelExporter({ provider: {
|
|
274
|
+
new OtelExporter({ provider: { laminar: {} } })
|
|
336
275
|
```
|
|
337
276
|
|
|
338
277
|
##### Explicit Configuration
|
|
@@ -340,10 +279,49 @@ new OtelExporter({ provider: { signoz: {} } })
|
|
|
340
279
|
```typescript
|
|
341
280
|
new OtelExporter({
|
|
342
281
|
provider: {
|
|
343
|
-
|
|
344
|
-
apiKey: process.env.
|
|
345
|
-
|
|
346
|
-
|
|
282
|
+
laminar: {
|
|
283
|
+
apiKey: process.env.LMNR_PROJECT_API_KEY,
|
|
284
|
+
},
|
|
285
|
+
},
|
|
286
|
+
})
|
|
287
|
+
```
|
|
288
|
+
|
|
289
|
+
> **Laminar-Native Exporter:** For Laminar-specific features like native span paths, metadata, and tags rendering in the Laminar dashboard, consider using the dedicated [`@mastra/laminar`](https://mastra.ai/integrations/observability/laminar) exporter instead. It provides optimized integration with Laminar's platform.
|
|
290
|
+
|
|
291
|
+
#### Latitude
|
|
292
|
+
|
|
293
|
+
[Latitude](https://latitude.so) is an open-source LLM observability and evaluation platform that ingests OTLP traces. Use the `custom` provider with HTTP/Protobuf, pointing at Latitude's ingestion endpoint and authenticating with your API key and project slug:
|
|
294
|
+
|
|
295
|
+
```typescript
|
|
296
|
+
new OtelExporter({
|
|
297
|
+
provider: {
|
|
298
|
+
custom: {
|
|
299
|
+
endpoint: 'https://ingest.latitude.so/v1/traces',
|
|
300
|
+
protocol: 'http/protobuf',
|
|
301
|
+
headers: {
|
|
302
|
+
Authorization: `Bearer ${process.env.LATITUDE_API_KEY}`,
|
|
303
|
+
'X-Latitude-Project': process.env.LATITUDE_PROJECT,
|
|
304
|
+
},
|
|
305
|
+
},
|
|
306
|
+
},
|
|
307
|
+
})
|
|
308
|
+
```
|
|
309
|
+
|
|
310
|
+
Sign up at [console.latitude.so](https://console.latitude.so/login), or self-host and point the endpoint at your own ingestion host.
|
|
311
|
+
|
|
312
|
+
#### MLflow
|
|
313
|
+
|
|
314
|
+
[MLflow](https://mlflow.org/docs/latest/genai/tracing/integrations/listing/mastra) supports native Mastra tracing through its OTLP endpoint at `/v1/traces`. Use the `custom` provider with HTTP/Protobuf and include the experiment header so traces are routed to the correct MLflow experiment:
|
|
315
|
+
|
|
316
|
+
```typescript
|
|
317
|
+
new OtelExporter({
|
|
318
|
+
provider: {
|
|
319
|
+
custom: {
|
|
320
|
+
endpoint: `${process.env.MLFLOW_TRACKING_URI}/v1/traces`,
|
|
321
|
+
protocol: 'http/protobuf',
|
|
322
|
+
headers: {
|
|
323
|
+
'x-mlflow-experiment-id': process.env.MLFLOW_EXPERIMENT_ID,
|
|
324
|
+
},
|
|
347
325
|
},
|
|
348
326
|
},
|
|
349
327
|
})
|
|
@@ -380,54 +358,78 @@ new OtelExporter({
|
|
|
380
358
|
})
|
|
381
359
|
```
|
|
382
360
|
|
|
383
|
-
####
|
|
384
|
-
|
|
385
|
-
[Traceloop](https://www.traceloop.com/) specializes in LLM observability with automatic prompt tracking.
|
|
361
|
+
#### Sazabi
|
|
386
362
|
|
|
387
|
-
|
|
363
|
+
[Sazabi](https://sazabi.com) is an AI-native observability platform that ingests OTLP traces. In Sazabi, add a Mastra log source and copy its intake URL. The URL carries your project key, so no auth header is needed:
|
|
388
364
|
|
|
389
365
|
```bash
|
|
390
|
-
|
|
391
|
-
TRACELOOP_API_KEY=your-api-key
|
|
392
|
-
|
|
393
|
-
# Optional
|
|
394
|
-
TRACELOOP_DESTINATION_ID=my-destination
|
|
395
|
-
TRACELOOP_ENDPOINT=https://custom.traceloop.com
|
|
366
|
+
SAZABI_INTAKE_URL=https://...
|
|
396
367
|
```
|
|
397
368
|
|
|
369
|
+
Use the `custom` provider with HTTP/JSON:
|
|
370
|
+
|
|
398
371
|
```typescript
|
|
399
|
-
new OtelExporter({
|
|
372
|
+
new OtelExporter({
|
|
373
|
+
provider: {
|
|
374
|
+
custom: {
|
|
375
|
+
endpoint: process.env.SAZABI_INTAKE_URL!,
|
|
376
|
+
protocol: 'http/json',
|
|
377
|
+
},
|
|
378
|
+
},
|
|
379
|
+
})
|
|
400
380
|
```
|
|
401
381
|
|
|
402
|
-
|
|
382
|
+
See [Sazabi's Mastra guide](https://docs.sazabi.com/catalogs/log-sources/send-to-an-endpoint/mastra) for the full setup.
|
|
383
|
+
|
|
384
|
+
#### Sentry
|
|
385
|
+
|
|
386
|
+
[Sentry](https://sentry.io/) accepts OpenTelemetry traces and logs through its OTLP endpoints. In Sentry, open [**Project Settings** > **Client Keys (DSN)**](https://sentry.io/settings/projects/) and copy the OTLP traces endpoint and authentication header. Add both values to your environment:
|
|
387
|
+
|
|
388
|
+
```bash
|
|
389
|
+
SENTRY_OTLP_ENDPOINT=https://o000000.ingest.sentry.io/api/0000000/integration/otlp/v1/traces
|
|
390
|
+
SENTRY_OTLP_AUTH_HEADER="sentry sentry_key=..."
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
Use the `custom` provider with HTTP/Protobuf:
|
|
403
394
|
|
|
404
395
|
```typescript
|
|
405
396
|
new OtelExporter({
|
|
406
397
|
provider: {
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
398
|
+
custom: {
|
|
399
|
+
endpoint: process.env.SENTRY_OTLP_ENDPOINT!,
|
|
400
|
+
protocol: 'http/protobuf',
|
|
401
|
+
headers: {
|
|
402
|
+
'x-sentry-auth': process.env.SENTRY_OTLP_AUTH_HEADER!,
|
|
403
|
+
},
|
|
410
404
|
},
|
|
411
405
|
},
|
|
412
406
|
})
|
|
413
407
|
```
|
|
414
408
|
|
|
415
|
-
|
|
409
|
+
See [Sentry's OTLP documentation](https://docs.sentry.io/concepts/otlp/) for endpoint setup, supported signals, and current ingestion limits.
|
|
416
410
|
|
|
417
|
-
|
|
411
|
+
Choose an exporter based on your setup:
|
|
412
|
+
|
|
413
|
+
- `OtelExporter`: Sends vendor-neutral traces and logs over OTLP. Use it with an existing OpenTelemetry pipeline or when you want backend portability.
|
|
414
|
+
- [`SentryExporter`](https://mastra.ai/integrations/observability/sentry): Uses the Sentry SDK to map Mastra span types to Sentry operations, add AI monitoring attributes, and capture span errors as Sentry issues.
|
|
415
|
+
|
|
416
|
+
#### SigNoz
|
|
417
|
+
|
|
418
|
+
[SigNoz](https://signoz.io/) is an open-source APM alternative with built-in Tracing support.
|
|
418
419
|
|
|
419
420
|
##### Zero-Config Setup
|
|
420
421
|
|
|
421
422
|
```bash
|
|
422
423
|
# Required
|
|
423
|
-
|
|
424
|
+
SIGNOZ_API_KEY=your-api-key
|
|
424
425
|
|
|
425
426
|
# Optional
|
|
426
|
-
|
|
427
|
+
SIGNOZ_REGION=us # 'us' | 'eu' | 'in'
|
|
428
|
+
SIGNOZ_ENDPOINT=https://my-signoz.example.com # For self-hosted
|
|
427
429
|
```
|
|
428
430
|
|
|
429
431
|
```typescript
|
|
430
|
-
new OtelExporter({ provider: {
|
|
432
|
+
new OtelExporter({ provider: { signoz: {} } })
|
|
431
433
|
```
|
|
432
434
|
|
|
433
435
|
##### Explicit Configuration
|
|
@@ -435,70 +437,68 @@ new OtelExporter({ provider: { laminar: {} } })
|
|
|
435
437
|
```typescript
|
|
436
438
|
new OtelExporter({
|
|
437
439
|
provider: {
|
|
438
|
-
|
|
439
|
-
apiKey: process.env.
|
|
440
|
+
signoz: {
|
|
441
|
+
apiKey: process.env.SIGNOZ_API_KEY,
|
|
442
|
+
region: 'us', // 'us' | 'eu' | 'in'
|
|
443
|
+
// endpoint: 'https://my-signoz.example.com', // For self-hosted
|
|
440
444
|
},
|
|
441
445
|
},
|
|
442
446
|
})
|
|
443
447
|
```
|
|
444
448
|
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
#### Datadog
|
|
449
|
+
#### telemetry.dev
|
|
448
450
|
|
|
449
|
-
[
|
|
451
|
+
[telemetry.dev](https://telemetry.dev) ingests OTLP/HTTP protobuf traces and normalizes OpenTelemetry GenAI semantic conventions into model, provider, token, latency, and cost fields. Use the `custom` provider with your project API key:
|
|
450
452
|
|
|
451
|
-
|
|
453
|
+
```bash
|
|
454
|
+
TELEMETRY_DEV_API_KEY=td_live_...
|
|
455
|
+
```
|
|
452
456
|
|
|
453
457
|
```typescript
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
export const mastra = new Mastra({
|
|
462
|
-
// Add grpc-js to externals so it's handled at runtime
|
|
463
|
-
bundler: {
|
|
464
|
-
externals: ['@grpc/grpc-js'],
|
|
465
|
-
},
|
|
466
|
-
observability: new Observability({
|
|
467
|
-
configs: {
|
|
468
|
-
default: {
|
|
469
|
-
serviceName: 'my-service',
|
|
470
|
-
exporters: [
|
|
471
|
-
new OtelExporter({
|
|
472
|
-
provider: {
|
|
473
|
-
custom: {
|
|
474
|
-
endpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || 'http://localhost:4317',
|
|
475
|
-
protocol: (process.env.OTEL_EXPORTER_OTLP_PROTOCOL || 'grpc') as ExportProtocol,
|
|
476
|
-
headers: {},
|
|
477
|
-
},
|
|
478
|
-
},
|
|
479
|
-
}),
|
|
480
|
-
],
|
|
458
|
+
new OtelExporter({
|
|
459
|
+
provider: {
|
|
460
|
+
custom: {
|
|
461
|
+
endpoint: 'https://ingest.telemetry.dev/v1/traces',
|
|
462
|
+
protocol: 'http/protobuf',
|
|
463
|
+
headers: {
|
|
464
|
+
Authorization: `Bearer ${process.env.TELEMETRY_DEV_API_KEY}`,
|
|
481
465
|
},
|
|
482
466
|
},
|
|
483
|
-
}
|
|
467
|
+
},
|
|
484
468
|
})
|
|
485
469
|
```
|
|
486
470
|
|
|
487
|
-
|
|
488
|
-
>
|
|
489
|
-
> ```yaml
|
|
490
|
-
> otlp_config:
|
|
491
|
-
> receiver:
|
|
492
|
-
> protocols:
|
|
493
|
-
> grpc:
|
|
494
|
-
> endpoint: 0.0.0.0:4317
|
|
495
|
-
> ```
|
|
496
|
-
>
|
|
497
|
-
> The default OTLP endpoint is `http://localhost:4317` when running the Datadog Agent locally.
|
|
471
|
+
#### Traceloop
|
|
498
472
|
|
|
499
|
-
|
|
473
|
+
[Traceloop](https://www.traceloop.com/) specializes in LLM observability with automatic prompt tracking.
|
|
500
474
|
|
|
501
|
-
|
|
475
|
+
##### Zero-Config Setup
|
|
476
|
+
|
|
477
|
+
```bash
|
|
478
|
+
# Required
|
|
479
|
+
TRACELOOP_API_KEY=your-api-key
|
|
480
|
+
|
|
481
|
+
# Optional
|
|
482
|
+
TRACELOOP_DESTINATION_ID=my-destination
|
|
483
|
+
TRACELOOP_ENDPOINT=https://custom.traceloop.com
|
|
484
|
+
```
|
|
485
|
+
|
|
486
|
+
```typescript
|
|
487
|
+
new OtelExporter({ provider: { traceloop: {} } })
|
|
488
|
+
```
|
|
489
|
+
|
|
490
|
+
##### Explicit Configuration
|
|
491
|
+
|
|
492
|
+
```typescript
|
|
493
|
+
new OtelExporter({
|
|
494
|
+
provider: {
|
|
495
|
+
traceloop: {
|
|
496
|
+
apiKey: process.env.TRACELOOP_API_KEY,
|
|
497
|
+
destinationId: 'my-destination', // Optional
|
|
498
|
+
},
|
|
499
|
+
},
|
|
500
|
+
})
|
|
501
|
+
```
|
|
502
502
|
|
|
503
503
|
#### Custom/Generic OTEL Endpoints
|
|
504
504
|
|
|
@@ -595,7 +595,7 @@ If the matching log exporter package isn't installed, log export is silently dis
|
|
|
595
595
|
new OtelExporter({
|
|
596
596
|
// Provider configuration (required)
|
|
597
597
|
provider: {
|
|
598
|
-
// Use one of: dash0,
|
|
598
|
+
// Use one of: dash0, laminar, newrelic, signoz, traceloop, custom
|
|
599
599
|
},
|
|
600
600
|
|
|
601
601
|
// Per-signal toggles. Both default to true.
|
|
@@ -615,7 +615,9 @@ new OtelExporter({
|
|
|
615
615
|
|
|
616
616
|
### `OpenTelemetry` semantic conventions
|
|
617
617
|
|
|
618
|
-
The exporter follows [OpenTelemetry Semantic Conventions for GenAI v1.
|
|
618
|
+
The exporter follows [OpenTelemetry Semantic Conventions for GenAI v1.41.0](https://github.com/open-telemetry/semantic-conventions/tree/v1.41.0/docs/gen-ai). Traces and logs exported over OTLP declare this version with the schema URL `https://opentelemetry.io/schemas/1.41.0`, so backends that read attributes by version read them correctly. Traces sent through a custom `exporter` declare no version, because that exporter can change the attributes.
|
|
619
|
+
|
|
620
|
+
The conventions cover the following span names and attributes:
|
|
619
621
|
|
|
620
622
|
#### Span Naming
|
|
621
623
|
|
|
@@ -647,10 +649,10 @@ Choose the right protocol package based on your provider:
|
|
|
647
649
|
| --------- | ------------- | ------------------------------------------ |
|
|
648
650
|
| Dash0 | gRPC | `@opentelemetry/exporter-trace-otlp-grpc` |
|
|
649
651
|
| Datadog | gRPC | `@opentelemetry/exporter-trace-otlp-grpc` |
|
|
650
|
-
|
|
|
652
|
+
| Laminar | HTTP/Protobuf | `@opentelemetry/exporter-trace-otlp-proto` |
|
|
651
653
|
| New Relic | HTTP/Protobuf | `@opentelemetry/exporter-trace-otlp-proto` |
|
|
654
|
+
| SigNoz | HTTP/Protobuf | `@opentelemetry/exporter-trace-otlp-proto` |
|
|
652
655
|
| Traceloop | HTTP/JSON | `@opentelemetry/exporter-trace-otlp-http` |
|
|
653
|
-
| Laminar | HTTP/Protobuf | `@opentelemetry/exporter-trace-otlp-proto` |
|
|
654
656
|
| Custom | Varies | Depends on your collector |
|
|
655
657
|
|
|
656
658
|
> **Warning:** Make sure to install the correct protocol package for your provider. The exporter will provide a helpful error message if the wrong package is installed.
|
|
@@ -679,7 +681,7 @@ Install the suggested package for your provider.
|
|
|
679
681
|
|
|
680
682
|
- [Tracing Overview](https://mastra.ai/docs/observability/tracing/overview)
|
|
681
683
|
- [OpenTelemetry Bridge](#bridge)
|
|
682
|
-
- [OpenTelemetry Semantic Conventions for GenAI v1.
|
|
684
|
+
- [OpenTelemetry Semantic Conventions for GenAI v1.41.0](https://github.com/open-telemetry/semantic-conventions/tree/v1.41.0/docs/gen-ai)
|
|
683
685
|
- [OTEL Exporter Reference](https://mastra.ai/reference/observability/tracing/exporters/otel)
|
|
684
686
|
|
|
685
687
|
## Bridge
|
|
@@ -851,7 +853,7 @@ Mastra's `flush()` and `shutdown()` ask the registered OTEL providers to flush,
|
|
|
851
853
|
|
|
852
854
|
### Semantic conventions
|
|
853
855
|
|
|
854
|
-
The `OtelBridge` exports Mastra spans using [OpenTelemetry Semantic Conventions for GenAI v1.
|
|
856
|
+
The `OtelBridge` exports Mastra spans using [OpenTelemetry Semantic Conventions for GenAI v1.41.0](https://github.com/open-telemetry/semantic-conventions/tree/v1.41.0/docs/gen-ai). This includes standardized span names (`chat {model}`, `execute_tool {tool_name}`, etc.) and attributes (`gen_ai.usage.input_tokens`, `gen_ai.request.model`, etc.).
|
|
855
857
|
|
|
856
858
|
For details on span naming and attributes, see the [OpenTelemetry Exporter semantic conventions](#opentelemetry-semantic-conventions).
|
|
857
859
|
|
|
@@ -284,7 +284,7 @@ Returns: `boolean`. `true` when this process aborted the run locally or can see
|
|
|
284
284
|
|
|
285
285
|
#### `abortThreadStream({ threadId, resourceId?, expectedRunId? })`
|
|
286
286
|
|
|
287
|
-
Aborts the active run on a memory thread with the same abort request as `abortRunStream()`.
|
|
287
|
+
Aborts the active run on a memory thread with the same abort request as `abortRunStream()`. When this process runs the thread's active run, the abort applies here. When this process has observed the run through `subscribeToThread()`, the abort request is published to the process executing the run, and nothing stops in this process. When the process never saw the run, it looks the run up in the background through the thread's lease and asks the process executing it to stop, publishing the request over the shared PubSub. That lookup runs asynchronously. The method returns before the lookup finishes. The server route [`POST /agents/:agentId/threads/abort`](https://mastra.ai/reference/server/routes) awaits the lookup when the abort wasn't resolved in this process, which is how it reports whether a run on another process was asked to stop.
|
|
288
288
|
|
|
289
289
|
Pass `expectedRunId` when the request must only stop a specific run. If another queued run becomes active before the request is handled, the method returns `false` without aborting the successor. Omit `expectedRunId` to abort whichever run is active when the request is handled.
|
|
290
290
|
|
|
@@ -296,7 +296,7 @@ const aborted = durableAgent.abortThreadStream({
|
|
|
296
296
|
})
|
|
297
297
|
```
|
|
298
298
|
|
|
299
|
-
Returns: `boolean`. `
|
|
299
|
+
Returns: `boolean`. `true` when this process aborted the run, or when the abort request was published to the process executing it. A published request doesn't confirm that the other process stopped the run. `false` is this process's own result: it had no run of the thread's to stop, the active run didn't match `expectedRunId`, or `localOnly: true` kept the abort local and left a run owned by another process alone. An `expectedRunId` mismatch and `localOnly: true` leave the run running by design. Otherwise `false` doesn't rule out a forwarded abort: the background lookup still publishes an abort request to the process holding the lease when it finishes, or finds nothing to publish. A failed lookup or publish is logged as a warning through the Mastra logger. Use the thread-abort route above when you need the forwarded outcome reported.
|
|
300
300
|
|
|
301
301
|
### Recovery
|
|
302
302
|
|
|
@@ -137,7 +137,7 @@ The `GoogleUser` type extends the base `EEUser` interface with Google-specific f
|
|
|
137
137
|
|
|
138
138
|
**hostedDomain** (`string`): Google Workspace hosted domain from the verified hd claim.
|
|
139
139
|
|
|
140
|
-
**expiresAt** (`Date`): Verified ID token expiration time, when available.
|
|
140
|
+
**expiresAt** (`Date`): Verified ID token expiration time for bearer ID-token users, or the session expiration time for SSO cookie users, when available.
|
|
141
141
|
|
|
142
142
|
**emailVerified** (`boolean`): Whether Google reports the email address as verified.
|
|
143
143
|
|
|
@@ -43,7 +43,7 @@ You can also pass `requestContext` as a `Record<string, any>`.
|
|
|
43
43
|
|
|
44
44
|
**baseUrl** (`string`): The base URL for the Mastra API. All requests will be sent relative to this URL.
|
|
45
45
|
|
|
46
|
-
**retries** (`number`): The number of times a request will be retried on failure before throwing an error. Retries apply to read requests (GET, HEAD, OPTIONS) by default, and to the observability queries that read server state even though they are sent as POST (aggregateTraces, aggregateSpans, queryTraceThreads, querySpans). Write requests (POST, PUT, PATCH, DELETE) are sent once unless you set
|
|
46
|
+
**retries** (`number`): The number of times a request will be retried on failure before throwing an error. Retries apply to read requests (GET, HEAD, OPTIONS) by default, and to the observability queries that read server state even though they are sent as POST (aggregateTraces, aggregateSpans, queryTraceThreads, querySpans). Write requests (POST, PUT, PATCH, DELETE) are sent once unless you set retries here, so a server error can't repeat a state-changing request. Methods that accept request options, such as createFeedback() and replaceFeedback(), can also set retries per call, and that count takes precedence over this one. This count covers transport retries only: createScore(), createFeedback(), and replaceFeedback() also retry missing-trace and missing-span responses for up to 30 seconds unless you pass anchorRetryTimeoutMs: 0, as described in the observability reference under Signal write options. (Default: `3 for read requests, 0 for write requests`)
|
|
47
47
|
|
|
48
48
|
**backoffMs** (`number`): The initial delay in milliseconds before retrying a failed request. This value is doubled with each retry (exponential backoff). (Default: `300`)
|
|
49
49
|
|
|
@@ -515,7 +515,7 @@ await mastraClient.replaceFeedback({
|
|
|
515
515
|
})
|
|
516
516
|
```
|
|
517
517
|
|
|
518
|
-
Use the normalized timestamp from the create response's `data` when available. OSS rejects changes to the original trace or timestamp with `409`. Platform uses the timestamp as part of record identity, so preserve it there too. The client preserves the replacement body across retries, but each accepted PUT retry is a new replacement and can supersede another edit. Pass `{ retries: 0, anchorRetryTimeoutMs: 0 }` as the second argument to disable
|
|
518
|
+
Use the normalized timestamp from the create response's `data` when available. OSS rejects changes to the original trace or timestamp with `409`. Platform uses the timestamp as part of record identity, so preserve it there too. The client preserves the replacement body across retries, but each accepted PUT retry is a new replacement and can supersede another edit. PUT requests get no transport retries by default, but a client configured with `retries` applies that count here too, and anchor retries stay on unless you turn them off. Pass `{ retries: 0, anchorRetryTimeoutMs: 0 }` as the second argument to disable both transport and anchor retries. `retries: 0` is only redundant when the client has no `retries` configured.
|
|
519
519
|
|
|
520
520
|
### Deleting feedback and scores
|
|
521
521
|
|
|
@@ -99,6 +99,10 @@ export const mastra = new Mastra({
|
|
|
99
99
|
|
|
100
100
|
**cleanup.cleanupIntervalMs** (`number`): How often the cleanup process runs, in milliseconds. Default: 1 minute.
|
|
101
101
|
|
|
102
|
+
**recoverStaleTasksOnStart** (`boolean`): Whether the manager recovers abandoned running and pending tasks on startup. A running task is only recovered once its owner's execution lease has expired, so this is safe when several managers share storage. When enabled, the manager scans again once the earliest live lease it found expires, and checks every leaseDurationMs for pinToWorker tasks whose worker stopped renewing their lease. See Execution ownership and recovery. (Default: `true`)
|
|
103
|
+
|
|
104
|
+
**leaseDurationMs** (`number`): Duration of the execution lease a manager holds on each task it runs, in milliseconds. The owner renews the lease every leaseDurationMs / 3. While the lease is live, no other manager recovers the task. Once it expires, the owner is treated as dead. Must be at least 3000; the manager throws at construction for lower values. (Default: `30000`)
|
|
105
|
+
|
|
102
106
|
**waitTimeoutMs** (`number`): How long the agentic loop waits for a background task to complete before moving on. If a task has not finished within this time, the loop proceeds without setting isContinued. Default: undefined (do not wait). Can be overridden per-agent or per-tool.
|
|
103
107
|
|
|
104
108
|
**untilIdleMaxIdleMs** (`number`): Default idle timeout, in milliseconds, for agent.stream(..., { untilIdle: true }) calls that do not set maxIdleMs. The stream closes when background tasks are still running but no event has arrived for this long. Set it above your longest expected background task so its completion still triggers a continuation turn. A per-call untilIdle: { maxIdleMs } takes precedence. Default: 5 minutes. (Default: `300000`)
|
|
@@ -735,6 +739,8 @@ Configures the [built-in MCP server](https://mastra.ai/docs/server/mcp) that exp
|
|
|
735
739
|
| `enumLimit` | `number` | `25` | Up to this many visible agents or workflows are listed as an enum on the id argument, and up to this many tools get an individual `tool_<id>` tool. |
|
|
736
740
|
| `featured` | `{ agents?: string[]; workflows?: string[] }` | `undefined` | Agents and workflows that also get a dedicated `agent_<id>` or `workflow_<id>` tool. |
|
|
737
741
|
| `readOnly` | `boolean` | `false` | Only serve tools whose backing route is a read operation. Clients can also request this with `?readonly=1` or the `X-MCP-Readonly` header. |
|
|
742
|
+
| `apps` | `boolean` | `true` | Serve [MCP Apps](https://mastra.ai/docs/server/mcp), such as the trace viewer and the observability explorer (traces, logs, and metrics), to clients that render them. Needs `@mastra/mcp-apps-components` installed. |
|
|
743
|
+
| `studioUrl` | `string \| false` | `undefined` | Studio's base URL, used by the MCP Apps' **Open in Studio** button. Defaults to the local Studio when using `mastra dev`. Set `false` to hide the button. |
|
|
738
744
|
| `include` | `{ agents?: string[]; workflows?: string[]; tools?: string[] }` | `undefined` | When set for a primitive type, only these are exposed. Each entry matches a primitive's `id` or its registration key. |
|
|
739
745
|
| `exclude` | `{ agents?: string[]; workflows?: string[]; tools?: string[] }` | `undefined` | Never exposed. Each entry matches a primitive's `id` or its registration key. Takes precedence over `include`. |
|
|
740
746
|
| `serverInfo` | `{ name?: string; version?: string; title?: string; instructions?: string }` | `undefined` | Server identity reported to MCP clients. |
|
|
@@ -154,6 +154,18 @@ await mastraClient.deleteScores({
|
|
|
154
154
|
})
|
|
155
155
|
```
|
|
156
156
|
|
|
157
|
+
## Get feedback
|
|
158
|
+
|
|
159
|
+
### `getFeedback(feedbackId)`
|
|
160
|
+
|
|
161
|
+
Returns one feedback record by ID. The response's `feedback` field is `null` when no record matches.
|
|
162
|
+
|
|
163
|
+
```typescript
|
|
164
|
+
const { feedback } = await mastraClient.getFeedback('feedback-1')
|
|
165
|
+
```
|
|
166
|
+
|
|
167
|
+
Observability storage exposes the same lookup as `await storage.getFeedbackById(feedbackId)`, which resolves to the `FeedbackRecord` or `null`. `PostgresStoreVNext`, `ClickhouseStoreVNext`, and the DuckDB and in-memory observability stores support it. Other stores, including the legacy `PostgresStore` and `ClickhouseStore` and LibSQL, throw `OBSERVABILITY_STORAGE_GET_FEEDBACK_BY_ID_NOT_IMPLEMENTED`, and the client request fails instead of returning `null`.
|
|
168
|
+
|
|
157
169
|
## List feedback
|
|
158
170
|
|
|
159
171
|
### `listFeedback(args?)`
|
|
@@ -462,6 +474,7 @@ These routes belong to a Mastra runtime and use its configured observability sto
|
|
|
462
474
|
| Method | Path | Purpose | Permission |
|
|
463
475
|
| -------- | ------------------------------------------------------- | ---------------------------------- | ---------------------- |
|
|
464
476
|
| `GET` | `/api/observability/feedback` | List feedback records | `observability:read` |
|
|
477
|
+
| `GET` | `/api/observability/feedback/:feedbackId` | Get one feedback record | `observability:read` |
|
|
465
478
|
| `POST` | `/api/observability/feedback` | Create a feedback record | `observability:write` |
|
|
466
479
|
| `PUT` | `/api/observability/feedback/:feedbackId` | Replace a complete feedback record | `observability:write` |
|
|
467
480
|
| `DELETE` | `/api/observability/feedback` | Delete feedback records by id | `observability:delete` |
|
|
@@ -639,6 +639,37 @@ Cursor pagination is deterministic, but it isn't a database snapshot. Traces or
|
|
|
639
639
|
|
|
640
640
|
PostgreSQL and ClickHouse stop trace queries after 15 seconds by default and return `504` when the database timeout is exceeded. Set `observability.traceQueryTimeoutMs` on `PostgresStoreVNext`, or `observability.traceQuery.timeoutMs` on `ClickhouseStoreVNext`, to an integer from 1 through 300,000 milliseconds to change the timeout. DuckDB doesn't currently provide query-scoped timeout or cancellation through its driver wrapper, so this `504` guarantee doesn't apply to DuckDB.
|
|
641
641
|
|
|
642
|
+
PostgreSQL enforces the timeout with `statement_timeout`, which can't stop a query while PostgreSQL compiles it with [JIT](https://www.postgresql.org/docs/current/jit.html). On small or low-resource databases, JIT compilation for a complex trace query can run well past the timeout and hold a pooled connection until it finishes, so later requests can fail while waiting for a connection. If trace queries run longer than `traceQueryTimeoutMs`, turn off JIT for the observability connections and compare:
|
|
643
|
+
|
|
644
|
+
```typescript
|
|
645
|
+
import { Pool } from 'pg'
|
|
646
|
+
import { PostgresStoreVNext } from '@mastra/pg'
|
|
647
|
+
|
|
648
|
+
const observabilityPool = new Pool({
|
|
649
|
+
connectionString: process.env.OBSERVABILITY_DATABASE_URL,
|
|
650
|
+
options: '-c jit=off',
|
|
651
|
+
})
|
|
652
|
+
|
|
653
|
+
// The store only handles errors on pools it creates, so handle them here.
|
|
654
|
+
// The pool listener covers idle clients. The client listener covers checked-out ones.
|
|
655
|
+
observabilityPool.on('error', err => {
|
|
656
|
+
console.error('Observability pool error', err)
|
|
657
|
+
})
|
|
658
|
+
observabilityPool.on('connect', client => {
|
|
659
|
+
client.on('error', err => {
|
|
660
|
+
console.error('Observability client error', err)
|
|
661
|
+
})
|
|
662
|
+
})
|
|
663
|
+
|
|
664
|
+
const storage = new PostgresStoreVNext({
|
|
665
|
+
id: 'pg-storage',
|
|
666
|
+
connectionString: process.env.DATABASE_URL,
|
|
667
|
+
observability: { pool: observabilityPool },
|
|
668
|
+
})
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
You can also turn off JIT for the whole database with `ALTER DATABASE <name> SET jit = off`, or raise `jit_above_cost` so only more expensive queries use it.
|
|
672
|
+
|
|
642
673
|
| Status | Meaning |
|
|
643
674
|
| ------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
644
675
|
| `400` | Malformed JSON or malformed cursor. |
|
|
@@ -15,7 +15,7 @@ new BraintrustExporter(config: BraintrustExporterConfig)
|
|
|
15
15
|
## `BraintrustExporterConfig`
|
|
16
16
|
|
|
17
17
|
```typescript
|
|
18
|
-
interface BraintrustExporterConfig extends
|
|
18
|
+
interface BraintrustExporterConfig extends TrackingExporterConfig {
|
|
19
19
|
apiKey?: string
|
|
20
20
|
endpoint?: string
|
|
21
21
|
projectName?: string
|
|
@@ -25,10 +25,15 @@ interface BraintrustExporterConfig extends BaseExporterConfig {
|
|
|
25
25
|
}
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
Extends `
|
|
28
|
+
Extends `TrackingExporterConfig`, which builds on `BaseExporterConfig` and includes:
|
|
29
29
|
|
|
30
30
|
- `logger?: IMastraLogger` - Logger instance
|
|
31
31
|
- `logLevel?: LogLevel | 'debug' | 'info' | 'warn' | 'error'` - Log level (default: INFO)
|
|
32
|
+
- `earlyQueueMaxAttempts?: number` - Attempts to process a queued event before dropping it (default: 5)
|
|
33
|
+
- `earlyQueueTTLMs?: number` - Maximum age in milliseconds of a queued event (default: 30000). The age is checked when the queue is replayed. An older event is dropped at the next replay or trace cleanup.
|
|
34
|
+
- `traceCleanupDelayMs?: number` - Milliseconds to keep trace data after all its spans end, so late data can still be processed (default: 30000)
|
|
35
|
+
- `maxPendingCleanupTraces?: number` - Soft cap on finished traces awaiting cleanup; the oldest are cleaned first when exceeded (default: 100)
|
|
36
|
+
- `maxTotalTraces?: number` - Hard cap on tracked traces, including active ones; the oldest are aborted when exceeded (default: 500)
|
|
32
37
|
|
|
33
38
|
## Methods
|
|
34
39
|
|
|
@@ -80,7 +80,6 @@ const exporter = new LangSmithExporter({
|
|
|
80
80
|
| Span Type | LangSmith Type |
|
|
81
81
|
| -------------------- | -------------- |
|
|
82
82
|
| `MODEL_GENERATION` | `llm` |
|
|
83
|
-
| `MODEL_CHUNK` | `llm` |
|
|
84
83
|
| `TOOL_CALL` | `tool` |
|
|
85
84
|
| `MCP_TOOL_CALL` | `tool` |
|
|
86
85
|
| `PROVIDER_TOOL_CALL` | `tool` |
|
|
@@ -85,7 +85,7 @@ type TracingStorageStrategy = 'realtime' | 'batch-with-updates' | 'insert-only'
|
|
|
85
85
|
|
|
86
86
|
### Strategy Behaviors
|
|
87
87
|
|
|
88
|
-
- **realtime**: Immediately persists each event to storage
|
|
88
|
+
- **realtime**: Immediately persists each event to storage. Use it only in single-process local development. It isn't supported with durable execution: when a durable agent or an Inngest, Temporal, or evented workflow is registered, the exporter logs one warning and runs `batch-with-updates`.
|
|
89
89
|
- **batch-with-updates**: Batches creates and updates separately, applies in order
|
|
90
90
|
- **insert-only**: Only processes SPAN_ENDED events, ignores updates
|
|
91
91
|
|
|
@@ -175,10 +175,13 @@ Failed flushes are retried with exponential backoff:
|
|
|
175
175
|
For `batch-with-updates` strategy:
|
|
176
176
|
|
|
177
177
|
- Tracks which spans have been created
|
|
178
|
-
-
|
|
178
|
+
- Holds updates/ends for spans this exporter started until their create is written
|
|
179
|
+
- Sends updates/ends for spans another process started straight to storage, and retries an end up to `maxRetries` times if it doesn't apply
|
|
179
180
|
- Logs warnings for out-of-order events
|
|
180
181
|
- Maintains sequence numbers for ordered updates
|
|
181
182
|
|
|
183
|
+
The default retries last about 7.5 seconds. Keep them longer than the `maxBatchWaitMs` of the process that started the span, or the end is dropped with `span-not-updatable`. `realtime` doesn't retry these ends and drops them right away. This retry needs a store with conditional span updates: libSQL, PostgreSQL, or the in-memory store. For the full behavior, see [Spans ended by another process](https://mastra.ai/docs/observability/integrations/exporters/mastra-storage).
|
|
184
|
+
|
|
182
185
|
## Usage
|
|
183
186
|
|
|
184
187
|
```typescript
|
|
@@ -175,8 +175,8 @@ The exporter sets these standard OpenTelemetry attributes:
|
|
|
175
175
|
- `gen_ai.tool.name`: Tool identifier
|
|
176
176
|
- `gen_ai.tool.type`: `function`
|
|
177
177
|
- `gen_ai.tool.call.id`: Tool call ID
|
|
178
|
-
- `gen_ai.tool.
|
|
179
|
-
- `gen_ai.tool.
|
|
178
|
+
- `gen_ai.tool.call.arguments`: Tool input
|
|
179
|
+
- `gen_ai.tool.call.result`: Tool output
|
|
180
180
|
- `tool.success`: Success flag
|
|
181
181
|
|
|
182
182
|
**AGENT_RUN spans:**
|
|
@@ -40,7 +40,7 @@ const results = await store.query({
|
|
|
40
40
|
|
|
41
41
|
### Logical Operators
|
|
42
42
|
|
|
43
|
-
`$and`Logical AND{ $and: \[{ price: { $gt: 100 } }, { stock: { $gt: 0 } }] }Supported by: All except Vectorize, Couchbase`$or`Logical OR{ $or: \[{ status: "active" }, { priority: "high" }] }Supported by: All except Vectorize, Couchbase`$not`Logical NOT{ price: { $not: { $lt: 100 } } }Supported by: Astra, Qdrant, Upstash, PgVector, libSQL, MongoDB, OracleDB`$nor`Logical NOR{ $nor: \[{ status: "deleted" }, { archived: true }] }Supported by:
|
|
43
|
+
`$and`Logical AND{ $and: \[{ price: { $gt: 100 } }, { stock: { $gt: 0 } }] }Supported by: All except Vectorize, Couchbase`$or`Logical OR{ $or: \[{ status: "active" }, { priority: "high" }] }Supported by: All except Vectorize, Couchbase`$not`Logical NOT{ price: { $not: { $lt: 100 } } }Supported by: Astra, Qdrant, Upstash, PgVector, libSQL, MongoDB, OracleDB`$nor`Logical NOR{ $nor: \[{ status: "deleted" }, { archived: true }] }Supported by: Upstash, PgVector, libSQL, MongoDB, OracleDB
|
|
44
44
|
|
|
45
45
|
### Element Operators
|
|
46
46
|
|
|
@@ -80,9 +80,9 @@ A `tool_<id>` entry uses the tool's own `mcp.annotations` when the tool defines
|
|
|
80
80
|
|
|
81
81
|
| Tool | Arguments | Route | Permission |
|
|
82
82
|
| ------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------- | -------------------- |
|
|
83
|
-
| `query_traces` | `timeRange*`, `where`, `
|
|
83
|
+
| `query_traces` | `timeRange*`, `where`, `rootSource`, `group`, `orderBy`, `page` | `POST /observability/traces/query` | `observability:read` |
|
|
84
84
|
| `aggregate_traces` | `timeRange*`, `measures*`, `where`, `groupBy`, `interval`, `having`, `orderBy`, `limit` | `POST /observability/traces/aggregate` | `observability:read` |
|
|
85
|
-
| `query_spans` | `timeRange*`, `where`, `
|
|
85
|
+
| `query_spans` | `timeRange*`, `where`, `orderBy`, `page` | `POST /observability/spans/query` | `observability:read` |
|
|
86
86
|
| `aggregate_spans` | `timeRange*`, `measures*`, `where`, `groupBy`, `interval`, `having`, `orderBy`, `limit` | `POST /observability/spans/aggregate` | `observability:read` |
|
|
87
87
|
| `query_threads` | `timeRange*`, `where`, `orderBy`, `page` | `POST /observability/threads/query` | `observability:read` |
|
|
88
88
|
| `get_trace_query_fields` | `timeRange*`, `predicateScope*`, `search`, `limit` | `POST /observability/traces/query/fields` | `observability:read` |
|
|
@@ -121,6 +121,8 @@ The constructor accepts an `MCPServerConfig` object with the following propertie
|
|
|
121
121
|
|
|
122
122
|
**appResources** (`AppResources`): A map of ui:// URIs to app resource configurations. Each entry defines an interactive HTML UI served via the MCP Apps extension (SEP-1865). See the MCP Apps section for details.
|
|
123
123
|
|
|
124
|
+
**appsRequireClientSupport** (`boolean`): Serve MCP Apps only to clients that declare MCP Apps support. Other clients see the server as if it had no apps. See Serving apps only to supporting clients. (Default: `false`)
|
|
125
|
+
|
|
124
126
|
## Tool results
|
|
125
127
|
|
|
126
128
|
By default, a tool's output is sent to the MCP client as a single text block. A string is sent as-is and any other value as JSON. A tool with an `outputSchema` also returns the value as `structuredContent`.
|
|
@@ -1491,6 +1493,27 @@ const server = new MCPServer({
|
|
|
1491
1493
|
|
|
1492
1494
|
Link a tool to its app resource by setting `mcp._meta.ui.resourceUri` in `createTool()` to the matching `ui://` URI. The server normalizes this metadata for older hosts when listing tools, and returns the same link on successful tool call results. Visit [MCP Apps](https://mastra.ai/docs/connections/mcp) for the full app bridge API and usage patterns.
|
|
1493
1495
|
|
|
1496
|
+
### Serving apps only to supporting clients
|
|
1497
|
+
|
|
1498
|
+
By default, every client sees the app resources, the app links on tools, and tools marked `visibility: ['app']`. Set `appsRequireClientSupport: true` to serve them only to clients that declare the `io.modelcontextprotocol/ui` extension:
|
|
1499
|
+
|
|
1500
|
+
```typescript
|
|
1501
|
+
const server = new MCPServer({
|
|
1502
|
+
id: 'app-server',
|
|
1503
|
+
name: 'App Server',
|
|
1504
|
+
version: '1.0.0',
|
|
1505
|
+
tools: { calculatorTool },
|
|
1506
|
+
appResources: {
|
|
1507
|
+
'ui://calculator/main': { name: 'Interactive Calculator', html: '<html>...</html>' },
|
|
1508
|
+
},
|
|
1509
|
+
appsRequireClientSupport: true,
|
|
1510
|
+
})
|
|
1511
|
+
```
|
|
1512
|
+
|
|
1513
|
+
A client that doesn't declare the extension sees the server as if it had no apps. The server hides its `ui://` resources, app links on tools and tool results, app-only tools, and the MCP Apps capability from that client.
|
|
1514
|
+
|
|
1515
|
+
The declaration is read on every request. Clients on the 2026-07-28 protocol send it with each request. Clients on older protocol versions declare it once, at `initialize`. Over stateless HTTP, the server answers that `initialize` with an `Mcp-Session-Id`, and the client sends it back on every later request. That id only marks the client as one that renders apps: the server keeps no record of it, and it grants no access. Clients that don't declare the extension get no session id, and their stateless traffic stays the same.
|
|
1516
|
+
|
|
1494
1517
|
## Events (experimental)
|
|
1495
1518
|
|
|
1496
1519
|
> **Warning:** Events implement [SEP-3415](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/3415), a draft MCP extension. The wire format and this API may change in any release.
|
|
@@ -230,7 +230,7 @@ A classifier without constructor-configured questions can't be used as a workflo
|
|
|
230
230
|
|
|
231
231
|
**execute.getInitData** (`() => any`): Function to access the initial input data of the workflow in any step
|
|
232
232
|
|
|
233
|
-
**execute.suspend** (`(suspendPayload: any, suspendOptions?: { resumeLabel?: string }) => Promise<void>`): Function to pause workflow execution
|
|
233
|
+
**execute.suspend** (`(suspendPayload: any, suspendOptions?: { resumeLabel?: string | string[] }) => Promise<void>`): Function to pause workflow execution
|
|
234
234
|
|
|
235
235
|
**execute.state** (`z.infer<TState>`): The current workflow state. Contains shared values that persist across all steps and suspend/resume cycles. The structure is defined by the step's stateSchema. Reading it in a run stored with storageVersion: 2 throws; use await getState() instead.
|
|
236
236
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/mcp-docs-server",
|
|
3
|
-
"version": "1.3.14-alpha.
|
|
3
|
+
"version": "1.3.14-alpha.7",
|
|
4
4
|
"description": "MCP server for accessing Mastra.ai documentation, changelogs, and news.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -26,8 +26,8 @@
|
|
|
26
26
|
"@mastra/mcp-legacy": "npm:@mastra/mcp@^1.18.0",
|
|
27
27
|
"local-pkg": "^1.2.1",
|
|
28
28
|
"zod": "^4.6.7",
|
|
29
|
-
"@mastra/core": "1.84.0-alpha.
|
|
30
|
-
"@mastra/mcp": "^2.10.0-alpha.
|
|
29
|
+
"@mastra/core": "1.84.0-alpha.7",
|
|
30
|
+
"@mastra/mcp": "^2.10.0-alpha.1"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@hono/node-server": "^2.1.3",
|