@mastra/mcp-docs-server 1.3.12 → 1.3.13-alpha.2
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/agents/resumable-streams.md +140 -0
- package/.docs/docs/agents/tools.md +2 -2
- package/.docs/docs/auth/overview.md +1 -0
- package/.docs/docs/auth/simple-auth.md +8 -8
- package/.docs/docs/channels.md +34 -1
- package/.docs/docs/connections/mcp.md +66 -1
- package/.docs/docs/guides/authentication-identity.md +4 -0
- package/.docs/docs/harness/background-tasks.md +2 -1
- package/.docs/docs/harness/durable-agents.md +6 -6
- package/.docs/docs/harness/goals.md +1 -1
- package/.docs/docs/harness/schedules.md +2 -0
- package/.docs/docs/knowledge/agents-and-tools.md +122 -0
- package/.docs/docs/knowledge/load-your-content.md +86 -0
- package/.docs/docs/knowledge/overview.md +106 -0
- package/.docs/docs/knowledge/patterns.md +167 -0
- package/.docs/docs/knowledge/pinned-context.md +177 -0
- package/.docs/docs/knowledge/scopes-and-access.md +202 -0
- package/.docs/docs/knowledge/search.md +63 -0
- package/.docs/docs/mastra-platform/connect.md +231 -0
- package/.docs/docs/mastra-platform/overview.md +1 -1
- package/.docs/docs/memory/observational-memory.md +23 -23
- package/.docs/docs/memory/overview.md +19 -7
- package/.docs/docs/observability/tracing/overview.md +0 -2
- package/.docs/docs/server/custom-adapters.md +4 -0
- package/.docs/docs/server/request-context.md +6 -6
- package/.docs/docs/server/server-adapters.md +12 -12
- package/.docs/docs/signals/sending-signals.md +3 -1
- package/.docs/docs/studio/knowledge.md +45 -24
- package/.docs/docs/studio/overview.md +3 -1
- package/.docs/integrations/auth/clerk.md +46 -7
- package/.docs/integrations/auth/neon.md +217 -0
- package/.docs/integrations/auth/supabase.md +46 -7
- package/.docs/integrations/auth/workos.md +54 -15
- package/.docs/integrations/channels/discord.md +84 -6
- package/.docs/integrations/channels/github.md +63 -24
- package/.docs/integrations/channels/slack.md +89 -8
- package/.docs/integrations/channels/teams.md +79 -5
- package/.docs/integrations/channels/telegram.md +47 -6
- package/.docs/integrations/crm/attio.md +42 -0
- package/.docs/integrations/crm/clay.md +42 -0
- package/.docs/integrations/crm/hubspot.md +41 -0
- package/.docs/integrations/databases/neon.md +37 -1
- package/.docs/integrations/databases/postgresql.md +46 -0
- package/.docs/integrations/deploy/render.md +59 -18
- package/.docs/integrations/documents/google-docs.md +41 -0
- package/.docs/integrations/documents/google-sheet.md +41 -0
- package/.docs/integrations/documents/microsoft-excel.md +43 -0
- package/.docs/integrations/documents/microsoft-powerpoint.md +41 -0
- package/.docs/integrations/documents/microsoft-word.md +41 -0
- package/.docs/integrations/documents/notion.md +41 -0
- package/.docs/integrations/documents/one-drive.md +41 -0
- package/.docs/integrations/documents/sharepoint-online.md +41 -0
- package/.docs/integrations/email-calendar/google-calendar.md +41 -0
- package/.docs/integrations/email-calendar/google-mail.md +41 -0
- package/.docs/integrations/email-calendar/outlook.md +41 -0
- package/.docs/integrations/file-storage/amazon-s3.md +1 -1
- package/.docs/integrations/file-storage/google-drive.md +54 -15
- package/.docs/integrations/observability/posthog.md +50 -11
- package/.docs/integrations/other/canva.md +42 -0
- package/.docs/integrations/other/fireflies.md +41 -0
- package/.docs/integrations/other/incident-io.md +41 -0
- package/.docs/integrations/other/resend.md +43 -0
- package/.docs/integrations/other/robinhood.md +44 -0
- package/.docs/integrations/other/sanity.md +42 -0
- package/.docs/integrations/other/snowflake.md +41 -0
- package/.docs/integrations/project-management/jira.md +41 -0
- package/.docs/integrations/project-management/linear.md +41 -0
- package/.docs/integrations/voice/openai.md +40 -0
- package/.docs/integrations.md +40 -1
- package/.docs/models/gateways/custom-gateways.md +2 -0
- package/.docs/models/gateways/netlify.md +8 -3
- package/.docs/models/gateways/openrouter.md +7 -8
- package/.docs/models/gateways/vercel.md +418 -418
- package/.docs/models/index.md +46 -2
- package/.docs/models/providers/aiand.md +1 -1
- package/.docs/models/providers/baseten.md +2 -1
- package/.docs/models/providers/chutes.md +2 -1
- package/.docs/models/providers/edenai.md +5 -9
- package/.docs/models/providers/empiriolabs.md +3 -3
- package/.docs/models/providers/hyper.md +7 -13
- package/.docs/models/providers/inceptron.md +3 -3
- package/.docs/models/providers/kilo.md +20 -25
- package/.docs/models/providers/llmgateway-providers.md +22 -10
- package/.docs/models/providers/llmgateway.md +5 -5
- package/.docs/models/providers/modular.md +6 -6
- package/.docs/models/providers/nano-gpt.md +18 -21
- package/.docs/models/providers/opencode-go.md +3 -1
- package/.docs/models/providers/opencode.md +3 -2
- package/.docs/models/providers/ovhcloud.md +1 -2
- package/.docs/models/providers/prime.md +1 -1
- package/.docs/models/providers/tencent-token-plan.md +2 -1
- package/.docs/models/providers/tencent-tokenhub.md +2 -1
- package/.docs/models/providers/tinfoil.md +2 -2
- package/.docs/models/providers/togetherai.md +2 -1
- package/.docs/models/providers/wandb.md +5 -4
- package/.docs/reference/agents/agent.md +3 -1
- package/.docs/reference/agents/channels.md +38 -1
- package/.docs/reference/agents/durable-agent.md +37 -26
- package/.docs/reference/agents/generate.md +1 -1
- package/.docs/reference/agents/getLLM.md +1 -1
- package/.docs/reference/agents/getMetadata.md +1 -1
- package/.docs/reference/agents/getModel.md +4 -2
- package/.docs/reference/agents/getSkill.md +1 -1
- package/.docs/reference/agents/listScorers.md +1 -1
- package/.docs/reference/agents/listTools.md +1 -1
- package/.docs/reference/auth/better-auth.md +2 -2
- package/.docs/reference/auth/neon.md +24 -15
- package/.docs/reference/channels/slack-provider.md +1 -1
- package/.docs/reference/cli/mastra.md +10 -1
- package/.docs/reference/client-js/agents.md +4 -4
- package/.docs/reference/client-js/observability.md +90 -3
- package/.docs/reference/connect/channels.md +55 -1
- package/.docs/reference/connect/providers.md +5 -3
- package/.docs/reference/connect/tools.md +34 -3
- package/.docs/reference/core/addDynamicWorkflow.md +1 -1
- package/.docs/reference/core/addGateway.md +1 -1
- package/.docs/reference/core/getAgent.md +4 -2
- package/.docs/reference/core/getEditor.md +1 -1
- package/.docs/reference/core/getGateway.md +1 -1
- package/.docs/reference/core/getGatewayById.md +14 -1
- package/.docs/reference/core/getMemory.md +2 -2
- package/.docs/reference/core/getStorage.md +1 -1
- package/.docs/reference/core/listMemory.md +3 -3
- package/.docs/reference/core/listScorers.md +2 -2
- package/.docs/reference/core/listVectors.md +1 -1
- package/.docs/reference/evals/completeness.md +0 -1
- package/.docs/reference/evals/content-similarity.md +1 -3
- package/.docs/reference/evals/create-scorer.md +5 -3
- package/.docs/reference/evals/faithfulness.md +1 -1
- package/.docs/reference/evals/hallucination.md +2 -2
- package/.docs/reference/evals/noise-sensitivity.md +8 -1
- package/.docs/reference/evals/scorer-utils.md +1 -1
- package/.docs/reference/index.md +7 -0
- package/.docs/reference/knowledge/knowledge-class.md +296 -0
- package/.docs/reference/knowledge/knowledge-memory-scopes.md +78 -0
- package/.docs/reference/knowledge/knowledge-tools.md +299 -0
- package/.docs/reference/knowledge/limits.md +44 -0
- package/.docs/reference/knowledge/scope-declarations.md +275 -0
- package/.docs/reference/knowledge/tool-instructions.md +56 -0
- package/.docs/reference/logging/pino-logger.md +1 -1
- package/.docs/reference/memory/observational-memory.md +9 -7
- package/.docs/reference/observability/feedback.md +3 -1
- package/.docs/reference/observability/tracing/advanced-queries.md +47 -58
- package/.docs/reference/processors/batch-parts-processor.md +0 -2
- package/.docs/reference/processors/message-history-processor.md +1 -1
- package/.docs/reference/processors/moderation-processor.md +1 -1
- package/.docs/reference/processors/semantic-recall-processor.md +1 -1
- package/.docs/reference/processors/stream-error-retry-processor.md +1 -1
- package/.docs/reference/processors/token-limiter-processor.md +1 -1
- package/.docs/reference/processors/tool-search-processor.md +1 -1
- package/.docs/reference/pubsub/redis-streams.md +2 -0
- package/.docs/reference/schedules/overview.md +3 -3
- package/.docs/reference/server/invoke-route.md +86 -0
- package/.docs/reference/server/koa-adapter.md +1 -1
- package/.docs/reference/server/routes.md +63 -0
- package/.docs/reference/streaming/ChunkType.md +3 -1
- package/.docs/reference/streaming/agents/MastraModelOutput.md +6 -4
- package/.docs/reference/streaming/agents/stream.md +1 -1
- package/.docs/reference/streaming/workflows/resumeStream.md +1 -1
- package/.docs/reference/tools/mcp-client.md +4 -0
- package/.docs/reference/tools/mcp-server.md +6 -2
- package/.docs/reference/tools/vector-query-tool.md +3 -3
- package/.docs/reference/workflows/run-methods/start.md +1 -1
- package/.docs/reference/workflows/run-methods/timeTravel.md +1 -1
- package/.docs/reference/workflows/workflow.md +2 -0
- package/.docs/reference/workspace/sandbox.md +1 -1
- package/dist/index.js +1 -1
- package/dist/{src-BDrEqwuY.js → src-CwUXyWAK.js} +3 -3
- package/dist/src-CwUXyWAK.js.map +1 -0
- package/dist/stdio.js +1 -1
- package/dist/tools/embedded-docs.d.ts.map +1 -1
- package/package.json +4 -4
- package/.docs/docs/mastra-platform/connect/channels.md +0 -165
- package/.docs/docs/mastra-platform/connect/overview.md +0 -102
- package/.docs/docs/mastra-platform/connect/providers.md +0 -66
- package/.docs/docs/mastra-platform/connect/tools.md +0 -151
- package/dist/src-BDrEqwuY.js.map +0 -1
|
@@ -51,7 +51,7 @@ The `channels` property accepts a `ChannelConfig` object with the following fiel
|
|
|
51
51
|
|
|
52
52
|
**threadContext** (`{ maxMessages?: number; addSystemMessage?: boolean }`): How the agent picks up context about the current thread. maxMessages sets how many platform messages are saved to memory on first mention: the thread's first message plus up to maxMessages - 1 recent messages, with an omitted-count marker between them when needed (set to 0 to disable; only applies to non-DM threads). addSystemMessage: false skips the built-in system message that tells the agent which channel/platform a request came from. (Default: `{ maxMessages: 10, addSystemMessage: true }`)
|
|
53
53
|
|
|
54
|
-
**chatOptions** (`Omit<ChatConfig, 'adapters' | 'state' | 'userName'>`): Additional options passed directly to the Chat SDK. Use for advanced configuration such as dedupeTtlMs, fallbackStreamingPlaceholderText, lockScope, and messageHistory.
|
|
54
|
+
**chatOptions** (`Omit<ChatConfig, 'adapters' | 'state' | 'userName'>`): Additional options passed directly to the Chat SDK. Use for advanced configuration such as dedupeTtlMs, fallbackStreamingPlaceholderText, lockScope, and messageHistory. logger defaults to the Mastra logger. Set it to use a different logger or a Chat SDK log level.
|
|
55
55
|
|
|
56
56
|
**resolveResourceId** (`(ctx: ResolveResourceIdContext) => string | Promise<string>`): Decide which resourceId owns resource-level memory for a channel thread, separately from who sent the message. Runs only when a new thread is created; reused threads keep their stored owner and never call the hook. Return ctx.defaultResourceId (${platform}:${message.author.userId}) to keep the built-in behavior.
|
|
57
57
|
|
|
@@ -480,6 +480,43 @@ type InlineLinkEntry =
|
|
|
480
480
|
| { match: string; mimeType: string } // Domain + forced mime type (skips HEAD)
|
|
481
481
|
```
|
|
482
482
|
|
|
483
|
+
## `toChatLogger()`
|
|
484
|
+
|
|
485
|
+
Adapts a Mastra logger to the Chat SDK `Logger` interface. Pass the result to an adapter's `logger` option so its logs go to the same logger as the rest of your app. See [Logging](https://mastra.ai/docs/channels) for when to use it.
|
|
486
|
+
|
|
487
|
+
```typescript
|
|
488
|
+
import { toChatLogger } from '@mastra/core/channels'
|
|
489
|
+
import { createDiscordAdapter } from '@chat-adapter/discord'
|
|
490
|
+
import { PinoLogger } from '@mastra/loggers'
|
|
491
|
+
|
|
492
|
+
const logger = new PinoLogger({ name: 'app', level: 'info' })
|
|
493
|
+
|
|
494
|
+
const discord = createDiscordAdapter({
|
|
495
|
+
logger: toChatLogger(logger, { component: 'discord', minLevel: 'warn' }),
|
|
496
|
+
})
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
**logger** (`IMastraLogger`): The Mastra logger that receives the records.
|
|
500
|
+
|
|
501
|
+
**options** (`ToChatLoggerOptions`): Options for the bridge.
|
|
502
|
+
|
|
503
|
+
**options.minLevel** (`'debug' | 'info' | 'warn' | 'error' | 'silent'`): Lowest level to forward. 'silent' forwards nothing. With the default, the Mastra logger's own level decides what gets written.
|
|
504
|
+
|
|
505
|
+
**options.component** (`string`): Written as the component field on each record. child(prefix) extends it, so chat-sdk becomes chat-sdk:discord.
|
|
506
|
+
|
|
507
|
+
Returns: a Chat SDK `Logger`.
|
|
508
|
+
|
|
509
|
+
Extra log arguments become fields on the record:
|
|
510
|
+
|
|
511
|
+
| Arguments | Fields |
|
|
512
|
+
| -------------------- | -------------------------------- |
|
|
513
|
+
| None | `component` |
|
|
514
|
+
| One `Error` | `error`, `component` |
|
|
515
|
+
| One non-array object | The object's fields, `component` |
|
|
516
|
+
| Anything else | `args`, `component` |
|
|
517
|
+
|
|
518
|
+
An `Error` passed directly or under an object's `error` key is normalized so it keeps its message and stack when serialized.
|
|
519
|
+
|
|
483
520
|
## Related
|
|
484
521
|
|
|
485
522
|
- [Channels overview](https://mastra.ai/docs/channels): Concepts, quickstart, and platform setup
|
|
@@ -41,28 +41,9 @@ const text = await output.text
|
|
|
41
41
|
cleanup()
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
-
###
|
|
44
|
+
### Plain Agent stream configuration
|
|
45
45
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
```typescript
|
|
49
|
-
import { Mastra } from '@mastra/core'
|
|
50
|
-
import { Agent } from '@mastra/core/agent'
|
|
51
|
-
|
|
52
|
-
const myAgent = new Agent({
|
|
53
|
-
id: 'my-agent',
|
|
54
|
-
name: 'My Agent',
|
|
55
|
-
instructions: 'You are a helpful assistant',
|
|
56
|
-
model: 'openai/gpt-6.1-sol',
|
|
57
|
-
durable: true, // or: { maxSteps: 10, cleanupTimeoutMs: 60_000 }
|
|
58
|
-
})
|
|
59
|
-
|
|
60
|
-
export const mastra = new Mastra({
|
|
61
|
-
agents: { myAgent },
|
|
62
|
-
})
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
`mastra.getAgent('myAgent')` returns the wrapped `DurableAgent`. Standalone agents (constructed but never registered on a `Mastra` instance) don't become durable. The wrapping is applied at registration.
|
|
46
|
+
The `durable` option on a plain `Agent` controls resumable streams only. It never wraps the agent or enables checkpoints. Use `createDurableAgent({ agent })` explicitly for durable execution, and pass execution options such as `maxSteps` and `shouldPersistSnapshot` to that factory.
|
|
66
47
|
|
|
67
48
|
## `createDurableAgent(options)`
|
|
68
49
|
|
|
@@ -86,7 +67,7 @@ Returns: `DurableAgent`
|
|
|
86
67
|
|
|
87
68
|
**cache** (`MastraServerCache | false`): Cache for stored stream events, which enables resumable streams. If omitted, the agent inherits the cache from the Mastra instance, or uses an InMemoryServerCache. Set to false to disable caching, which makes streams non-resumable.
|
|
88
69
|
|
|
89
|
-
**pubsub** (`PubSub`): PubSub instance for streaming events. (Default: `EventEmitterPubSub`)
|
|
70
|
+
**pubsub** (`PubSub`): PubSub instance for streaming events. Takes precedence over mastra.pubsub. When omitted, a registered agent publishes on mastra.pubsub and an unregistered agent uses an in-process EventEmitterPubSub. (Default: `mastra.pubsub, or EventEmitterPubSub when unregistered`)
|
|
90
71
|
|
|
91
72
|
**maxSteps** (`number`): Maximum number of steps for the agentic loop.
|
|
92
73
|
|
|
@@ -112,7 +93,7 @@ Returns: `EventedAgent` (a subclass of `DurableAgent`)
|
|
|
112
93
|
|
|
113
94
|
**cache** (`MastraServerCache | false`): Cache for stored stream events, which enables resumable streams. If omitted, the agent inherits the cache from the Mastra instance, or uses an InMemoryServerCache. Set to false to disable caching.
|
|
114
95
|
|
|
115
|
-
**pubsub** (`PubSub`): PubSub instance for streaming events. (Default: `EventEmitterPubSub`)
|
|
96
|
+
**pubsub** (`PubSub`): PubSub instance for streaming events. Once the agent is registered, evented run frames use mastra.pubsub instead, because evented steps publish there. (Default: `mastra.pubsub, or EventEmitterPubSub when unregistered`)
|
|
116
97
|
|
|
117
98
|
**maxSteps** (`number`): Maximum number of steps for the agentic loop.
|
|
118
99
|
|
|
@@ -132,7 +113,7 @@ The `DurableAgent` class accepts the same options as `createDurableAgent`, plus
|
|
|
132
113
|
|
|
133
114
|
**cache** (`MastraServerCache | false`): Cache for stored stream events. If omitted, inherits from the Mastra instance or uses an InMemoryServerCache. Set to false to disable caching.
|
|
134
115
|
|
|
135
|
-
**pubsub** (`PubSub`): PubSub instance for streaming events. (Default: `EventEmitterPubSub`)
|
|
116
|
+
**pubsub** (`PubSub`): PubSub instance for streaming events. Takes precedence over mastra.pubsub. When omitted, a registered agent publishes on mastra.pubsub and an unregistered agent uses an in-process EventEmitterPubSub. (Default: `mastra.pubsub, or EventEmitterPubSub when unregistered`)
|
|
136
117
|
|
|
137
118
|
**maxSteps** (`number`): Maximum number of steps for the agentic loop.
|
|
138
119
|
|
|
@@ -195,11 +176,41 @@ const { output } = await durableAgent.observe(runId, {
|
|
|
195
176
|
await output.text
|
|
196
177
|
```
|
|
197
178
|
|
|
198
|
-
The `offset` option is an inclusive, zero-based PubSub event index. It counts every cached event published to the run topic, including lifecycle events, rather than counting chunks.
|
|
179
|
+
The `offset` option is an inclusive, zero-based PubSub event index. It counts every cached event published to the run topic, including lifecycle events, rather than counting chunks. A chunk read from the run log carries the index of its event as `chunk.index`, on `stream()`, `observe()`, and the HTTP `/stream` and `/observe` endpoints. To resume after a dropped connection, pass `index + 1` of the last chunk that has an index, or omit `offset` if nothing arrived. Lifecycle events take an index but produce no chunk, so indexes have gaps and a chunk count isn't a valid offset.
|
|
180
|
+
|
|
181
|
+
Some chunks carry no `index`. The client builds `object` chunks itself rather than reading them from the log. An `abort` chunk is sent beside the `finish` of the same run-log entry, and only the `finish` carries the index, so a client that reconnects between the two gets the `abort` again.
|
|
182
|
+
|
|
183
|
+
A run that used a structuring model publishes its `object-result` to the run log, so that chunk carries an `index` and replays like any other. A core `observe()` caller holding the schema can also rebuild structured output from replayed text, but gets `object-result` only when it replays the text that produced it. HTTP `/observe` replays the log and doesn't rebuild it. To rebuild it after a reconnect, observe without an `offset` and skip chunks whose `index` you already processed. That replay also rebuilds `object` chunks you already received, and they have no `index` to skip by. Each `object` chunk is a snapshot of the object so far, so keep the latest one. Indexes come from the replay cache, so a chunk whose cache write failed, or any chunk when caching is off, has no `index`, so no offset can resume at it. Omitting `offset` replays whatever the transport itself retains, such as a Redis stream, and can repeat chunks you already received. The paragraphs below cover offsets past the end and transports without numeric offsets.
|
|
184
|
+
|
|
185
|
+
`index` is additive and `offset` keeps its meaning, so code that already passes a log position, or replays from `0`, needs no change. Code that passed a count of chunks received should switch to the last `index + 1`.
|
|
186
|
+
|
|
187
|
+
The following example records the resume offset while streaming and passes it to `observe()` after a reconnect:
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
let offset: number | undefined
|
|
191
|
+
const { output } = await durableAgent.stream(messages, { runId })
|
|
192
|
+
for await (const chunk of output.fullStream) {
|
|
193
|
+
if (chunk.index === undefined) continue
|
|
194
|
+
offset = chunk.index + 1
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// After a dropped connection:
|
|
198
|
+
const { output: resumed } = await durableAgent.observe(runId, { offset })
|
|
199
|
+
```
|
|
199
200
|
|
|
200
201
|
A non-zero offset can skip earlier events. Aggregated values are built only from chunks delivered to that observer. If the offset skips earlier text deltas, `output.text` is partial and structured output may be incomplete or fail validation or parsing.
|
|
201
202
|
|
|
202
|
-
When the PubSub transport supports numeric offsets,
|
|
203
|
+
When the PubSub transport supports numeric offsets, the observer receives numbered events only when the published index reaches the requested offset. An offset beyond the highest retained index replays nothing and also skips live events with lower indexes.
|
|
204
|
+
|
|
205
|
+
An event without an `index`, such as one whose cache write failed, is delivered as it arrives whatever the offset.
|
|
206
|
+
|
|
207
|
+
If the retained log expires or is cleared and numbering restarts at `0` while an observer is attached, that observer resyncs to the new log and receives its events, including ones below the requested offset. Detection is best effort. If the cache can't be read at that moment, or the new log has numbered past the observer's position before its first event arrives, the observer can miss the restart and skip those events instead. An observer that reconnects after the restart with an offset from the old log can't tell the logs apart and skips the new log's events below that offset, so omit `offset` to replay the new log.
|
|
208
|
+
|
|
209
|
+
On a transport without numeric offset support, such as `RedisStreamsPubSub` with caching off, `observe()` with any offset, including `0`, starts with new live events and doesn't replay retained events. This is the same in core and over HTTP `/observe`. Omit `offset` to replay them. (HTTP `/observe` on a plain `Agent` replays the retained events instead, which can repeat events already received.)
|
|
210
|
+
|
|
211
|
+
Indexed replay is limited to events still available in the configured cache. The cache has nothing to replay when caching is disabled, `shouldCache` excludes the run topic, or retained events have been cleared. Omitting `offset` then replays only what the transport itself retains, if anything.
|
|
212
|
+
|
|
213
|
+
A failed cache write loses only that event from the cache. It has no `index`, and the events written before and after it still replay when the cache numbers and appends an event in one step. The in-memory and Valkey caches always do. `RedisServerCache` does while Redis scripting works, and switches to two steps when the client has no `eval` or Redis Cluster rejects the script with `CROSSSLOT`. A custom cache that keeps the default `listPushIndexed()` also takes two steps. A two-step cache can leave a gap that makes offset replay skip later events, so replay such a log without an `offset` and skip indexes already processed. Cache replay can't recover an event the cache never stored. A transport that retains it, such as `RedisStreamsPubSub`, can still deliver it without an `index`.
|
|
203
214
|
|
|
204
215
|
An evented agent (`createEventedAgent()`) on a cross-process PubSub, such as Redis Streams, numbers its events only when every process shares the server cache. Configure a shared cache such as `RedisServerCache` on the `Mastra` instance. With the default in-memory server cache, events aren't numbered, so an offset can't skip them: the observer can receive events from before the offset again, and Mastra logs a warning.
|
|
205
216
|
|
|
@@ -128,7 +128,7 @@ const result = await agent.generate('message for agent')
|
|
|
128
128
|
|
|
129
129
|
**options.output** (`Zod schema | JsonSchema7`): \*\*Deprecated.\*\* Use structuredOutput without a model to achieve the same thing. Defines the expected structure of the output. Can be a JSON Schema object or a Zod schema.
|
|
130
130
|
|
|
131
|
-
**options.scopes** (`string[]`): Scopes the run acts as, written as \<type>:\<value> (for example org:acme, resource:user-123, thread:conversation-123). Memory reads its resource and thread from resource: and thread: scopes. Other scopes are passed to tools and processors. Combined with the agent's scopes
|
|
131
|
+
**options.scopes** (`string[]`): Scopes the run acts as, written as \<type>:\<value> (for example org:acme, resource:user-123, thread:conversation-123). Memory reads its resource and thread from resource: and thread: scopes. Other scopes are passed to tools and processors. Combined with defaultOptions.scopes and the mastra__scopes request context key, then passed through the agent's scopes option: a list adds to them, a function replaces them. Throws if a resource: or thread: scope conflicts with another resource or thread value.
|
|
132
132
|
|
|
133
133
|
**options.memory** (`object`): Memory configuration for conversation persistence and retrieval.
|
|
134
134
|
|
|
@@ -28,7 +28,7 @@ await agent.getLLM({
|
|
|
28
28
|
|
|
29
29
|
## Returns
|
|
30
30
|
|
|
31
|
-
**llm** (`MastraLLMV1 | Promise<MastraLLMV1>`): The language model instance configured for the agent, either as a direct instance or a promise that resolves to the LLM.
|
|
31
|
+
**llm** (`MastraLLMV1 | MastraLLMVNext | Promise<MastraLLMV1 | MastraLLMVNext>`): The language model instance configured for the agent, either as a direct instance or a promise that resolves to the LLM.
|
|
32
32
|
|
|
33
33
|
## Extended usage example
|
|
34
34
|
|
|
@@ -20,7 +20,7 @@ await agent.getMetadata()
|
|
|
20
20
|
|
|
21
21
|
## Returns
|
|
22
22
|
|
|
23
|
-
**metadata** (`Record<string, unknown> | Promise<Record<string, unknown
|
|
23
|
+
**metadata** (`Record<string, unknown> | undefined | Promise<Record<string, unknown> | undefined>`): The metadata configured for the agent, or undefined if no metadata was configured. Returns either directly or as a promise that resolves to the metadata when defined as a function.
|
|
24
24
|
|
|
25
25
|
## Extended usage example
|
|
26
26
|
|
|
@@ -14,13 +14,15 @@ await agent.getModel()
|
|
|
14
14
|
|
|
15
15
|
## Parameters
|
|
16
16
|
|
|
17
|
-
**options** (`{ requestContext?: RequestContext }`): Optional configuration object containing request context. (Default: `{}`)
|
|
17
|
+
**options** (`{ requestContext?: RequestContext; modelConfig?: DynamicArgument<MastraModelConfig | ModelWithRetries[]> | ModelFallbacks }`): Optional configuration object containing request context and an optional model override. (Default: `{}`)
|
|
18
18
|
|
|
19
19
|
**options.requestContext** (`RequestContext`): Request Context for dependency injection and contextual information.
|
|
20
20
|
|
|
21
|
+
**options.modelConfig** (`DynamicArgument<MastraModelConfig | ModelWithRetries[]> | ModelFallbacks`): Model configuration to resolve instead of the agent model. Can also be a function that receives the request context.
|
|
22
|
+
|
|
21
23
|
## Returns
|
|
22
24
|
|
|
23
|
-
**model** (`
|
|
25
|
+
**model** (`Promise<MastraLanguageModel | MastraLegacyLanguageModel>`): A promise that resolves to the language model configured for the agent. Always await the result.
|
|
24
26
|
|
|
25
27
|
## Extended usage example
|
|
26
28
|
|
|
@@ -54,7 +54,7 @@ interface Skill {
|
|
|
54
54
|
}
|
|
55
55
|
```
|
|
56
56
|
|
|
57
|
-
`source` describes where Mastra discovered the skill. Skills from a path with a `node_modules` segment are `external`, skills under `.mastra/skills` are `managed`, and all other skills, including those created with [`createSkill()`](https://mastra.ai/reference/agents/createSkill), are `local`.
|
|
57
|
+
`source` describes where Mastra discovered the skill. Skills from a path with a `node_modules` segment are `external`, skills from a path under `.mastra/skills` are `managed`, and all other skills, including those created with [`createSkill()`](https://mastra.ai/reference/agents/createSkill), are `local`.
|
|
58
58
|
|
|
59
59
|
## Merging behavior
|
|
60
60
|
|
|
@@ -20,7 +20,7 @@ await agent.listScorers()
|
|
|
20
20
|
|
|
21
21
|
## Returns
|
|
22
22
|
|
|
23
|
-
**scorers** (`
|
|
23
|
+
**scorers** (`Promise<MastraScorers>`): A promise that resolves to the scoring configuration configured for the agent.
|
|
24
24
|
|
|
25
25
|
## Extended usage example
|
|
26
26
|
|
|
@@ -20,7 +20,7 @@ await agent.listTools()
|
|
|
20
20
|
|
|
21
21
|
## Returns
|
|
22
22
|
|
|
23
|
-
**tools** (`
|
|
23
|
+
**tools** (`Promise<TTools>`): A promise that resolves to the tools configured for the agent.
|
|
24
24
|
|
|
25
25
|
## Extended usage example
|
|
26
26
|
|
|
@@ -71,8 +71,8 @@ The `Session` and `User` types are exported by the Better Auth package.
|
|
|
71
71
|
|
|
72
72
|
- `public` and `protected` accept exact paths, wildcard patterns (like `/api/*`), and path params (like `/users/:id`).
|
|
73
73
|
- For method-specific rules, use tuples like `["/api/agents", ["GET", "POST"]]`.
|
|
74
|
-
- If a route matches both `public` and `protected`, `public` wins and no auth is required.
|
|
75
|
-
- If neither matches,
|
|
74
|
+
- If a route matches both `public` and `protected`, `public` wins and no auth is required, unless the route is marked `requiresAuth: true`. Those routes still authenticate.
|
|
75
|
+
- If neither matches, a route requires auth when it's under `/api/*` (the built-in default `protected` pattern) or is a custom route registered with `registerApiRoute()` that isn't marked `requiresAuth: false`, and other paths don't require auth.
|
|
76
76
|
|
|
77
77
|
## Related
|
|
78
78
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
# `MastraAuthNeon` and `MastraRBACNeon`
|
|
6
6
|
|
|
7
|
-
[`MastraAuthNeon`](https://github.com/mastra-ai/mastra/tree/main/auth/neon) connects Mastra authentication to [Neon Auth](https://neon.com/docs/guides/neon-auth). It
|
|
7
|
+
[`MastraAuthNeon`](https://github.com/mastra-ai/mastra/tree/main/auth/neon) connects Mastra authentication to [Neon Auth](https://neon.com/docs/guides/neon-auth). It verifies Neon Auth JWTs sent as bearer tokens with Neon Auth's JWKS endpoint and validates Neon Auth session cookies through its session API. The provider also supports email-and-password sign-in, sign-up, and session management.
|
|
8
8
|
|
|
9
9
|
`MastraRBACNeon` maps Neon Auth organization roles to Mastra permissions. Register it separately when your application uses Neon Auth organization memberships for role-based access control.
|
|
10
10
|
|
|
@@ -34,7 +34,9 @@ export const mastra = new Mastra({
|
|
|
34
34
|
})
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
-
Set `NEON_AUTH_BASE_URL` to
|
|
37
|
+
Set `NEON_AUTH_BASE_URL` to the Neon Auth URL shown in the Neon Console, for example `https://ep-example-123456.neonauth.us-east-2.aws.neon.tech/neondb/auth`. You can also pass `baseUrl` directly to both constructors.
|
|
38
|
+
|
|
39
|
+
Visit the [Neon integration guide](https://mastra.ai/integrations/auth/neon) for setup steps.
|
|
38
40
|
|
|
39
41
|
## `MastraAuthNeon`
|
|
40
42
|
|
|
@@ -42,13 +44,13 @@ Set `NEON_AUTH_BASE_URL` to your Neon Auth service URL. You can also pass `baseU
|
|
|
42
44
|
|
|
43
45
|
The `MastraAuthNeon` constructor accepts an optional `MastraAuthNeonOptions` object.
|
|
44
46
|
|
|
45
|
-
**baseUrl** (`string`): Neon Auth
|
|
47
|
+
**baseUrl** (`string`): Neon Auth URL, including the database path (for example /neondb/auth). Falls back to the NEON_AUTH_BASE_URL environment variable. Trailing slashes are removed. The JWT issuer and audience must equal the origin of this URL.
|
|
46
48
|
|
|
47
|
-
**jwksUrl** (`string`): JWKS endpoint used to verify bearer tokens. Falls back to NEON_AUTH_JWKS_URL, then \<baseUrl
|
|
49
|
+
**jwksUrl** (`string`): JWKS endpoint used to verify bearer tokens. Falls back to NEON_AUTH_JWKS_URL, then \<baseUrl>/.well-known/jwks.json.
|
|
48
50
|
|
|
49
|
-
**sessionCookieName** (`string`): Name of the Neon Auth session cookie. Defaults to
|
|
51
|
+
**sessionCookieName** (`string`): Name of the Neon Auth session cookie. Defaults to \_\_Secure-neon-auth.session_token.
|
|
50
52
|
|
|
51
|
-
**signUpEnabled** (`boolean`): Whether credentials-based sign-up is enabled. Defaults to true.
|
|
53
|
+
**signUpEnabled** (`boolean`): Whether credentials-based sign-up is enabled. When false, signUp() throws and no Neon Auth account is created. Defaults to true.
|
|
52
54
|
|
|
53
55
|
**name** (`string`): Provider name. Defaults to neon.
|
|
54
56
|
|
|
@@ -74,7 +76,9 @@ The `MastraAuthNeon` constructor accepts an optional `MastraAuthNeonOptions` obj
|
|
|
74
76
|
await auth.authenticateToken(token, request)
|
|
75
77
|
```
|
|
76
78
|
|
|
77
|
-
Verifies
|
|
79
|
+
Verifies a JWT-shaped token against the configured JWKS endpoint, checking its signature, issuer, audience, and expiry. Otherwise, validates the Neon Auth session cookie from the request through the session API. If JWT verification fails, the session cookie is still accepted, so an expired bearer token doesn't sign out a client that also sends cookies. When the request has no session cookie, a non-JWT token is treated as the session cookie value. Returns the authenticated `NeonAuthUser`, or `null` when validation fails.
|
|
80
|
+
|
|
81
|
+
`NeonAuthUser` contains the top-level `id`, `email`, and `name`, the Neon Auth `user` object, and either the `session` (cookie authentication) or the verified `jwt` claims (bearer authentication).
|
|
78
82
|
|
|
79
83
|
#### `authorizeUser()`
|
|
80
84
|
|
|
@@ -92,7 +96,7 @@ Runs the configured custom authorization function when one is provided. Otherwis
|
|
|
92
96
|
const result = await auth.signIn(email, password, request)
|
|
93
97
|
```
|
|
94
98
|
|
|
95
|
-
Authenticates email-and-password credentials through Neon Auth. Returns the authenticated user,
|
|
99
|
+
Authenticates email-and-password credentials through Neon Auth. Returns the authenticated user, a Neon Auth JWT as `token`, and the Neon Auth session cookies. Neon Auth must trust the origin of the incoming request.
|
|
96
100
|
|
|
97
101
|
#### `signUp()`
|
|
98
102
|
|
|
@@ -100,7 +104,7 @@ Authenticates email-and-password credentials through Neon Auth. Returns the auth
|
|
|
100
104
|
const result = await auth.signUp(email, password, name, request)
|
|
101
105
|
```
|
|
102
106
|
|
|
103
|
-
Creates a Neon Auth account using email-and-password credentials. `name` is optional
|
|
107
|
+
Creates a Neon Auth account using email-and-password credentials. `name` is optional. When omitted, the provider derives a display name from the email address. Returns the same result as `signIn()`.
|
|
104
108
|
|
|
105
109
|
#### `isSignUpEnabled()`
|
|
106
110
|
|
|
@@ -139,10 +143,13 @@ Validates the session through Neon Auth. Neon Auth refreshes sessions automatica
|
|
|
139
143
|
#### `destroySession()`
|
|
140
144
|
|
|
141
145
|
```typescript
|
|
142
|
-
|
|
146
|
+
const sessionId = auth.getSessionIdFromRequest(request)
|
|
147
|
+
if (sessionId) await auth.destroySession(sessionId)
|
|
143
148
|
```
|
|
144
149
|
|
|
145
|
-
|
|
150
|
+
Pass the signed session cookie value from `getSessionIdFromRequest()`, not the `id` returned by `validateSession()`. `destroySession()` attempts to revoke that session through the Neon Auth sign-out endpoint. A network error or non-2xx response can leave the session active, and the method doesn't throw for these failures. When Mastra sends the header from `getClearSessionHeaders()`, it clears the matching cookie on the Mastra host, not a cookie on a separate Neon Auth host. A separate Neon Auth session can remain active after Studio sign-out.
|
|
151
|
+
|
|
152
|
+
Revoking a session doesn't invalidate an already-issued JWT. Bearer tokens that pass JWT verification can still authenticate because verification doesn't check the Neon Auth session. JWT verification doesn't require an expiration claim, so a token without one may remain usable after sign-out.
|
|
146
153
|
|
|
147
154
|
## `MastraRBACNeon`
|
|
148
155
|
|
|
@@ -152,11 +159,11 @@ The `MastraRBACNeon` constructor accepts a `MastraRBACNeonOptions` object.
|
|
|
152
159
|
|
|
153
160
|
**roleMapping** (`RoleMapping`): Maps Neon Auth role names to Mastra permission patterns. Use \_default to define permissions for unmapped roles.
|
|
154
161
|
|
|
155
|
-
**baseUrl** (`string`): Neon Auth
|
|
162
|
+
**baseUrl** (`string`): Neon Auth URL. Falls back to the NEON_AUTH_BASE_URL environment variable. Trailing slashes are removed.
|
|
156
163
|
|
|
157
|
-
**organizationId** (`string`):
|
|
164
|
+
**organizationId** (`string`): Organization whose membership role is used. Defaults to the active organization of the session.
|
|
158
165
|
|
|
159
|
-
**getUserRoles** (`(user: NeonAuthUser) => Promise<string[]> | string[]`): Custom function
|
|
166
|
+
**getUserRoles** (`(user: NeonAuthUser) => Promise<string[]> | string[]`): Custom function that returns role names for a user. Use it to assign roles to bearer JWT requests, which carry no organization roles.
|
|
160
167
|
|
|
161
168
|
**cache** (`{ ttlMs?: number; maxSize?: number }`): Role lookup cache configuration. The defaults are 60,000 ms and 1,000 entries.
|
|
162
169
|
|
|
@@ -168,7 +175,9 @@ The `MastraRBACNeon` constructor accepts a `MastraRBACNeonOptions` object.
|
|
|
168
175
|
const roles = await rbac.getRoles(user)
|
|
169
176
|
```
|
|
170
177
|
|
|
171
|
-
Returns roles from the configured `getUserRoles` function, the user's
|
|
178
|
+
Returns roles from the configured `getUserRoles` function when provided. Otherwise, when `organizationId` is set or the session has an active organization, returns the user's role in that organization, read from Neon Auth with the user's session cookie. Non-members get no roles. Without an organization, returns the user's Neon Auth role, such as `user` or `admin`.
|
|
179
|
+
|
|
180
|
+
Bearer JWT requests have no session, so they get no roles unless `getUserRoles` is provided. The JWT `role` claim (`authenticated`) is never used as a Mastra role.
|
|
172
181
|
|
|
173
182
|
#### `hasRole()`
|
|
174
183
|
|
|
@@ -63,7 +63,7 @@ await slack.configure({
|
|
|
63
63
|
|
|
64
64
|
**toolApprovers** (`'requester' | 'anyone'`): Who can approve or deny tool calls. By default, only the user whose message triggered the call can respond when their identity was recorded; without a recorded requester, another channel member may respond. Set 'anyone' to allow another member of the shared Slack channel to approve or deny even when a requester was recorded. This bypasses only the requester check; the action still requires a pending approval in the same thread. (Default: `'requester'`)
|
|
65
65
|
|
|
66
|
-
**typingStatus** (`boolean | TypingStatusFn`): Show a typing indicator while the agent works. Set false to disable, or pass a function to return custom status text per stream chunk (return
|
|
66
|
+
**typingStatus** (`boolean | TypingStatusFn`): Show a typing indicator while the agent works. Set false to disable, or pass a function to return custom status text per stream chunk (return false, null, or undefined to leave the current status unchanged for that chunk). (Default: `true`)
|
|
67
67
|
|
|
68
68
|
**waitUntil** (`WaitUntilFn`): Returns a waitUntil for the current Slack webhook request. Required on serverless runtimes where Hono can't bridge the platform's ExecutionContext (Vercel, AWS Lambda). Without it, the invocation freezes after the 200 ack and kills the run mid-flight. Pass the bare waitUntil(promise) from your platform SDK (for example, @vercel/functions). Cloudflare Workers and Netlify users typically don't need this.
|
|
69
69
|
|
|
@@ -877,6 +877,8 @@ Manages authentication for Mastra platform. Credentials are stored in `~/.mastra
|
|
|
877
877
|
|
|
878
878
|
Opens a browser for login and stores the credentials locally.
|
|
879
879
|
|
|
880
|
+
When browser sign-in is needed and there's no interactive terminal (in CI, when input or output is piped, or in an agent's shell), the command first prints how to authenticate headless shells, then still waits for browser sign-in. On the same machine, you can run `mastra auth login` once in your own terminal so later commands reuse the saved session. In CI or on another machine, set `MASTRA_API_TOKEN` and `MASTRA_ORG_ID` instead. Create the token from a signed-in terminal with [`mastra auth tokens create`](#mastra-auth-tokens-create) or in the dashboard. If the browser sign-in wait times out, the command exits with status 1. If `MASTRA_API_TOKEN` is already set in a non-interactive shell, the command skips browser sign-in: it verifies the token and checks that an organization is selected (from `MASTRA_ORG_ID` or saved credentials), then exits with status 0. If either check fails, it exits with status 1 and names what's missing.
|
|
881
|
+
|
|
880
882
|
### `mastra auth logout`
|
|
881
883
|
|
|
882
884
|
Removes stored credentials. If `MASTRA_API_TOKEN` is still set in the environment, the CLI warns that it will continue to be used.
|
|
@@ -943,7 +945,7 @@ Connects a provider to the project. When the organization already has connection
|
|
|
943
945
|
|
|
944
946
|
OAuth providers open the provider's consent screen in your browser and print its URL if you need to open it manually. API key and Basic auth providers prompt for credentials in the terminal and verify them before completing the connection. Providers with other auth types open a hosted connect page. The command waits until the connection becomes active before exiting.
|
|
945
947
|
|
|
946
|
-
Credential prompts require an interactive terminal, even with `--yes`. Run the command outside CI or connect through the platform UI.
|
|
948
|
+
Credential prompts require an interactive terminal, even with `--yes`. Run the command outside CI or connect through the platform UI. Each provider's [integration page](https://mastra.ai/docs/mastra-platform/connect) lists its API key and permission requirements.
|
|
947
949
|
|
|
948
950
|
Once a new connection is active, the command offers to set a display name so you can tell connections to the same provider apart. It lists the provider's existing connections, suggests a name that doesn't collide with them, and asks for confirmation if the chosen name duplicates another connection's name. Leave the field blank to skip naming. Setting a display name requires the organization admin role; if naming fails, the connection remains active.
|
|
949
951
|
|
|
@@ -1266,6 +1268,13 @@ Errors are written to `stderr` as JSON and return a non-zero exit code:
|
|
|
1266
1268
|
}
|
|
1267
1269
|
```
|
|
1268
1270
|
|
|
1271
|
+
The exit code reflects whether the request succeeded, not the contents of the response:
|
|
1272
|
+
|
|
1273
|
+
- `0`: The server returned a successful response. This includes empty results and payloads that report existing state, such as a tool result saying a record already exists. A tool that returns an object with an `error` field still exits `0`, so check the `data` payload when the tool reports its own failures.
|
|
1274
|
+
- `1`: The request failed. This includes an unreachable server, invalid JSON input, a missing resource, or a tool that throws an error.
|
|
1275
|
+
|
|
1276
|
+
If the command reading the output exits early, as with `| head`, the exit code still reflects whether the request succeeded.
|
|
1277
|
+
|
|
1269
1278
|
### Target resolution
|
|
1270
1279
|
|
|
1271
1280
|
For runtime commands, the command resolves the target server in this order:
|
|
@@ -914,9 +914,9 @@ const agent = await mastraClient.createStoredAgent({
|
|
|
914
914
|
})
|
|
915
915
|
```
|
|
916
916
|
|
|
917
|
-
####
|
|
917
|
+
#### Resumable streams for stored agents
|
|
918
918
|
|
|
919
|
-
Set `durable` to
|
|
919
|
+
Set `durable` to configure [resumable streams](https://mastra.ai/docs/agents/resumable-streams) on the hydrated plain agent. Pass `true` to enable streams, `false` to disable them, or an object to tune stream cleanup:
|
|
920
920
|
|
|
921
921
|
```typescript
|
|
922
922
|
const agent = await mastraClient.createStoredAgent({
|
|
@@ -927,11 +927,11 @@ const agent = await mastraClient.createStoredAgent({
|
|
|
927
927
|
provider: 'openai',
|
|
928
928
|
name: 'gpt-5.4',
|
|
929
929
|
},
|
|
930
|
-
durable: {
|
|
930
|
+
durable: { cleanupTimeoutMs: 0 },
|
|
931
931
|
})
|
|
932
932
|
```
|
|
933
933
|
|
|
934
|
-
Only serializable options are accepted
|
|
934
|
+
Only serializable options are accepted, with cache and pubsub inherited from the server's `Mastra` instance. Existing stored agents with `durable: true` also use this field for resumable streams only. To retain durable execution and checkpoint recovery, register a code agent wrapped with `createDurableAgent({ agent })`.
|
|
935
935
|
|
|
936
936
|
### `getStoredAgent()`
|
|
937
937
|
|
|
@@ -115,7 +115,7 @@ if (capabilities.spanAggregate) {
|
|
|
115
115
|
|
|
116
116
|
The request and response structure follows `aggregateTraces()`, with direct span predicates and span dimensions such as `spanType`, `name`, and `parentEntityName`. Token and cost measures belong to the span that recorded the usage and aren't added to parent spans. Check `capabilities.spanAggregate` before calling, and `capabilities.spanAggregateModelDimensions` before grouping or counting distinct values by `model` or `provider`. With an older adapter, those requests return `501`.
|
|
117
117
|
|
|
118
|
-
Both `aggregateTraces()` and `aggregateSpans()` accept `timeToFirstToken.*` and `timeToFirstChunk
|
|
118
|
+
Both `aggregateTraces()` and `aggregateSpans()` accept time to first token (TTFT) and time to first chunk (TTFC) measures, `timeToFirstToken.*` and `timeToFirstChunk.*`, when `capabilities.aggregateTimeToFirstMeasures` is `true`. Spans and traces without a recorded value are skipped, never counted as 0. See [Time to first chunk (TTFC)](https://mastra.ai/reference/observability/tracing/advanced-queries) and [Time to first token (TTFT)](https://mastra.ai/reference/observability/tracing/advanced-queries).
|
|
119
119
|
|
|
120
120
|
See [Aggregate spans](https://mastra.ai/reference/observability/tracing/advanced-queries) for selection, dimensions, per-span usage, and how to list the spans behind a group.
|
|
121
121
|
|
|
@@ -403,13 +403,52 @@ const scores = await mastraClient.listScoresBySpan({
|
|
|
403
403
|
})
|
|
404
404
|
```
|
|
405
405
|
|
|
406
|
+
## Get a score by ID
|
|
407
|
+
|
|
408
|
+
Use `getScore()` to retrieve one observability score:
|
|
409
|
+
|
|
410
|
+
```typescript
|
|
411
|
+
const { score } = await mastraClient.getScore('score-id-123')
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
The response is `{ score: record | null }`. A missing score returns HTTP 200 with `{ score: null }`. The return type is `GetScoreResponse`, exported from `@mastra/client-js`.
|
|
415
|
+
|
|
416
|
+
## Creating scores
|
|
417
|
+
|
|
418
|
+
Create a score for a trace, optionally identifying a span within it:
|
|
419
|
+
|
|
420
|
+
```typescript
|
|
421
|
+
const response = await mastraClient.createScore({
|
|
422
|
+
score: {
|
|
423
|
+
traceId: 'trace-123',
|
|
424
|
+
spanId: 'span-456',
|
|
425
|
+
scorerId: 'accuracy',
|
|
426
|
+
score: 0.95,
|
|
427
|
+
},
|
|
428
|
+
})
|
|
429
|
+
```
|
|
430
|
+
|
|
431
|
+
`createScore()` requires a nonblank `score.traceId`, with an optional `spanId`. The client generates a missing `scoreId` and ISO `timestamp` once per call and preserves them across retries. Supply these fields to reuse an existing identity. See [signal write options](#signal-write-options) for context resolution and retry behavior.
|
|
432
|
+
|
|
406
433
|
## Feedback
|
|
407
434
|
|
|
408
|
-
Feedback methods create, list, and query human-in-the-loop signals such as ratings, thumbs, comments, and corrections through the
|
|
435
|
+
Feedback methods create, list, and query human-in-the-loop signals such as ratings, thumbs, comments, and corrections through the configured API server. Create methods support OSS and Platform. Full replacement uses Platform's PUT endpoint. See the [feedback guide](https://mastra.ai/docs/observability/feedback) for examples and the [feedback reference](https://mastra.ai/reference/observability/feedback) for full schemas.
|
|
436
|
+
|
|
437
|
+
### Get feedback by ID
|
|
438
|
+
|
|
439
|
+
Use `getFeedback()` to retrieve one feedback record:
|
|
440
|
+
|
|
441
|
+
```typescript
|
|
442
|
+
const { feedback } = await mastraClient.getFeedback('feedback-id-123')
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
The response is `{ feedback: record | null }`. A missing record returns HTTP 200 with `{ feedback: null }`. The return type is `GetFeedbackResponse`, exported from `@mastra/client-js`.
|
|
446
|
+
|
|
447
|
+
Both getters accept an unencoded ID and encode it as a URL path segment. They use the client's configured API prefix, credentials, and headers. Record timestamps are ISO strings in the JSON response.
|
|
409
448
|
|
|
410
449
|
### Creating feedback
|
|
411
450
|
|
|
412
|
-
Create a feedback record
|
|
451
|
+
Create a feedback record for a trace, optionally identifying a span within it:
|
|
413
452
|
|
|
414
453
|
```typescript
|
|
415
454
|
const response = await mastraClient.createFeedback({
|
|
@@ -424,6 +463,54 @@ const response = await mastraClient.createFeedback({
|
|
|
424
463
|
})
|
|
425
464
|
```
|
|
426
465
|
|
|
466
|
+
`createFeedback()` requires a nonblank `feedback.traceId`, with an optional `spanId`. The client generates a missing `feedbackId` and ISO `timestamp` once per call and preserves them across retries. Set `feedbackUserId` to identify the feedback author. `userId` identifies the span's user. An authenticated OSS user takes precedence over a submitted feedback author.
|
|
467
|
+
|
|
468
|
+
### Signal write options
|
|
469
|
+
|
|
470
|
+
Both create methods accept an optional top-level `contextMode` alongside the `feedback` or `score` wrapper:
|
|
471
|
+
|
|
472
|
+
- `"provided"` uses the record's flattened context fields without looking up spans. Missing context fields aren't enriched.
|
|
473
|
+
- `"resolve"` derives context from the stored root and optional target span. Root tags are inherited. Record metadata overrides matching stored metadata keys. A missing root returns `TRACE_NOT_FOUND`. A missing target returns `SPAN_NOT_FOUND`.
|
|
474
|
+
|
|
475
|
+
Omitting `contextMode` uses the server's default: `"provided"` on OSS and `"resolve"` on Platform. The client preserves omission. Select a mode explicitly when the same behavior is required on both servers. On OSS, each configured trusted scope field overrides caller input. In provided mode, other context fields remain caller-supplied. For example, a trusted organization ID overrides `organizationId` but doesn't clear `resourceId` when no trusted resource scope is configured.
|
|
476
|
+
|
|
477
|
+
```typescript
|
|
478
|
+
const result = await mastraClient.createFeedback({
|
|
479
|
+
contextMode: 'resolve',
|
|
480
|
+
feedback: {
|
|
481
|
+
traceId: 'trace-123',
|
|
482
|
+
feedbackUserId: 'reviewer-1',
|
|
483
|
+
feedbackType: 'thumbs',
|
|
484
|
+
value: 1,
|
|
485
|
+
},
|
|
486
|
+
})
|
|
487
|
+
```
|
|
488
|
+
|
|
489
|
+
Use `retries` and `anchorRetryTimeoutMs` in the optional second argument to control retries. Network and server errors use the client's transport retry settings. Only 404s with `TRACE_NOT_FOUND` or `SPAN_NOT_FOUND` receive anchor retries, for at most 30 seconds after the first such response. Set `anchorRetryTimeoutMs` to a shorter window or `0` to disable them. Other 404s and authentication or validation errors are terminal.
|
|
490
|
+
|
|
491
|
+
Create responses contain `success` and optional `data` with the generated or supplied `feedbackId`/`scoreId`, `traceId`, nullable `spanId`, and normalized UTC `timestamp`. The client also accepts success-only responses. Platform success confirms publication. The record may not be immediately visible to reads. Direct OSS HTTP callers can omit the ID and timestamp to have the server generate them.
|
|
492
|
+
|
|
493
|
+
Explicit modes require server support. Older servers may ignore `contextMode`. Deploy Platform's supplied-context support before sending `"provided"` there.
|
|
494
|
+
|
|
495
|
+
### Replacing feedback on Platform
|
|
496
|
+
|
|
497
|
+
`replaceFeedback()` sends a full replacement to `PUT /api/observability/feedback/:feedbackId`. Include the original `feedbackId`, `traceId`, and normalized `timestamp`, along with all feedback fields to retain. This method targets Platform. OSS server doesn't implement this replacement endpoint.
|
|
498
|
+
|
|
499
|
+
```typescript
|
|
500
|
+
await mastraClient.replaceFeedback({
|
|
501
|
+
feedback: {
|
|
502
|
+
feedbackId: 'feedback-1',
|
|
503
|
+
traceId: 'trace-123',
|
|
504
|
+
timestamp: '2026-01-01T00:00:00.123Z',
|
|
505
|
+
feedbackType: 'thumbs',
|
|
506
|
+
value: -1,
|
|
507
|
+
feedbackUserId: 'reviewer-1',
|
|
508
|
+
},
|
|
509
|
+
})
|
|
510
|
+
```
|
|
511
|
+
|
|
512
|
+
Use the normalized timestamp from the create response's `data` when available. A changed timestamp identifies a different Platform record. 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 automatic retries.
|
|
513
|
+
|
|
427
514
|
### Deleting feedback and scores
|
|
428
515
|
|
|
429
516
|
Delete feedback or score records by id. Deletion is idempotent, so missing ids are ignored. Each request accepts at most 1,000 `feedbackIds` or 1,000 `scoreIds`. Optional `organizationId` and `resourceId` fields restrict each deletion to records with matching scope fields:
|