@mastra/mcp-docs-server 1.3.13-alpha.10 → 1.3.13-alpha.12
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/code-mode.md +4 -0
- package/.docs/docs/agents/tools.md +10 -2
- package/.docs/docs/harness/schedules.md +1 -1
- package/.docs/docs/observability/feedback.md +5 -7
- package/.docs/docs/workflows/scheduled-workflows.md +26 -5
- package/.docs/integrations/sandboxes/docker.md +39 -0
- package/.docs/reference/agents/generate.md +1 -1
- package/.docs/reference/agents/generateLegacy.md +7 -23
- package/.docs/reference/cli/mastra.md +74 -6
- package/.docs/reference/client-js/observability.md +13 -5
- package/.docs/reference/connect/tools.md +59 -0
- package/.docs/reference/editor/mastra-editor.md +1 -1
- package/.docs/reference/observability/feedback.md +57 -14
- package/.docs/reference/observability/tracing/advanced-queries.md +2 -1
- package/.docs/reference/observability/tracing/exporters/langfuse.md +24 -1
- package/.docs/reference/observability/tracing/exporters/mastra-platform-exporter.md +19 -16
- package/.docs/reference/observability/tracing/exporters/otel.md +1 -1
- package/.docs/reference/observability/tracing/interfaces.md +2 -2
- package/.docs/reference/processors/processor-interface.md +23 -0
- package/.docs/reference/schedules/overview.md +25 -5
- package/.docs/reference/server/express-adapter.md +16 -10
- package/.docs/reference/streaming/agents/stream.md +1 -1
- package/package.json +3 -3
|
@@ -132,6 +132,10 @@ const agent = new Agent({
|
|
|
132
132
|
|
|
133
133
|
The generated code for `sales_code` can't call an inventory tool, and the reverse holds too. Use this for least-privilege scoping and to keep each tool's prompt surface small.
|
|
134
134
|
|
|
135
|
+
## Connected tools
|
|
136
|
+
|
|
137
|
+
To orchestrate the tools of providers connected in Mastra Platform, use [`tools().codeMode()`](https://mastra.ai/reference/connect/tools) from `@mastra/connect`. It builds the code tool and instructions from the current connections on each request, and keeps tools that need approval as direct agent tools.
|
|
138
|
+
|
|
135
139
|
## Remote sandboxes
|
|
136
140
|
|
|
137
141
|
By default, code mode uses a transport that writes the program to the host filesystem and runs `node` against it. That works for `LocalSandbox`, which shares the host, but not for remote sandboxes that run in their own micro-VM (such as [E2B](https://mastra.ai/integrations/sandboxes/e2b)), where the host paths don't exist.
|
|
@@ -380,6 +380,7 @@ Use `hooks` to run custom logic before and after every tool call an agent makes.
|
|
|
380
380
|
|
|
381
381
|
```typescript
|
|
382
382
|
import { Agent } from '@mastra/core/agent'
|
|
383
|
+
import { db } from '../db' // your application database client
|
|
383
384
|
|
|
384
385
|
export const supportAgent = new Agent({
|
|
385
386
|
id: 'support-agent',
|
|
@@ -390,13 +391,20 @@ export const supportAgent = new Agent({
|
|
|
390
391
|
beforeToolCall: ({ toolName, input }) => {
|
|
391
392
|
console.log(`Running ${toolName}`, input)
|
|
392
393
|
},
|
|
393
|
-
afterToolCall: ({ toolName, output, error }) => {
|
|
394
|
-
|
|
394
|
+
afterToolCall: async ({ toolName, input, output, error }) => {
|
|
395
|
+
await db.auditLog.insert({
|
|
396
|
+
toolName,
|
|
397
|
+
input,
|
|
398
|
+
output,
|
|
399
|
+
error: error ? String(error) : undefined,
|
|
400
|
+
})
|
|
395
401
|
},
|
|
396
402
|
},
|
|
397
403
|
})
|
|
398
404
|
```
|
|
399
405
|
|
|
406
|
+
`afterToolCall` must return `void` (or `Promise<void>`). Await your storage call, but don't return its result. If the storage call throws, the tool call fails with that error, so catch it inside the hook if audit logging should be best-effort. `afterToolCall` doesn't run for calls skipped by `beforeToolCall` or for declined [pre-execution approvals](https://mastra.ai/docs/agents/human-in-the-loop), so record those decisions where you handle them.
|
|
407
|
+
|
|
400
408
|
`beforeToolCall` runs before the tool executes and receives the tool name, input, and execution context. Return `{ proceed: false, output }` to skip the tool call entirely, the agent receives `output` as the tool result:
|
|
401
409
|
|
|
402
410
|
```typescript
|
|
@@ -42,7 +42,7 @@ await mastra.schedules.create({
|
|
|
42
42
|
})
|
|
43
43
|
```
|
|
44
44
|
|
|
45
|
-
Mastra starts
|
|
45
|
+
Schedules fire only in a process where Mastra's background [workers](https://mastra.ai/docs/deployment/workers) are running. The server that `mastra dev` and `mastra build` generate starts them for you. With a [server adapter](https://mastra.ai/docs/server/server-adapters) or your own script, call `mastra.startWorkers()` yourself, otherwise schedules are saved but never fire. See [Start background workers](https://mastra.ai/docs/server/server-adapters).
|
|
46
46
|
|
|
47
47
|
## Cadence
|
|
48
48
|
|
|
@@ -16,7 +16,7 @@ Unlike metrics and scores, feedback is usually supplied by a person or review wo
|
|
|
16
16
|
|
|
17
17
|
## Add feedback
|
|
18
18
|
|
|
19
|
-
Use `mastra.observability.addFeedback()`
|
|
19
|
+
Use `mastra.observability.addFeedback()` to annotate a trace or span from app code. The helper is optional on the observability entrypoint, so check that the active observability implementation supports it. See the [client SDK observability reference](https://mastra.ai/reference/client-js/observability) for all client methods.
|
|
20
20
|
|
|
21
21
|
```typescript
|
|
22
22
|
if (!mastra.observability.addFeedback) {
|
|
@@ -35,9 +35,9 @@ await mastra.observability.addFeedback({
|
|
|
35
35
|
})
|
|
36
36
|
```
|
|
37
37
|
|
|
38
|
-
|
|
38
|
+
Feedback goes to each configured exporter that supports it. Each exporter handles its own destination independently. A trace missing from local storage doesn't prevent feedback from reaching Platform or another exporter.
|
|
39
39
|
|
|
40
|
-
|
|
40
|
+
[`MastraStorageExporter`](https://mastra.ai/docs/observability/integrations/exporters/mastra-storage) looks up the trace or span in your configured storage before saving feedback. If the target remains unavailable after retries, it logs a warning and skips the local write. Call `mastra.observability.flush()` or `shutdown()` before your process exits to finish pending delivery.
|
|
41
41
|
|
|
42
42
|
## Find the trace for a message
|
|
43
43
|
|
|
@@ -185,11 +185,9 @@ The local runtime exposes the list route at `/api/observability/feedback` and an
|
|
|
185
185
|
|
|
186
186
|
## Export feedback to Mastra Platform
|
|
187
187
|
|
|
188
|
-
[`MastraPlatformExporter`](https://mastra.ai/reference/observability/tracing/exporters/mastra-platform-exporter)
|
|
188
|
+
[`MastraPlatformExporter`](https://mastra.ai/reference/observability/tracing/exporters/mastra-platform-exporter) sends feedback to Mastra Platform, which looks up the target trace or span when needed. Local trace storage isn't required. Add `MastraStorageExporter` only if you also want a local copy.
|
|
189
189
|
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
See [Observability on Mastra Platform](https://mastra.ai/docs/mastra-platform/observability) for the combined exporter configuration.
|
|
190
|
+
Studio sends feedback to the backend serving its trace reads. For HTTP creates handled by your OSS server, the server saves feedback locally and notifies configured exporters. Because exporter delivery is asynchronous, a successful HTTP response doesn't guarantee that the record is already visible at a remote destination. Direct storage writes bypass exporters.
|
|
193
191
|
|
|
194
192
|
## Export feedback to external platforms
|
|
195
193
|
|
|
@@ -74,13 +74,29 @@ const dailyReport = createWorkflow({
|
|
|
74
74
|
|
|
75
75
|
Fields:
|
|
76
76
|
|
|
77
|
-
- `cron
|
|
77
|
+
- `cron`: a 5-, 6-, or 7-part cron expression. Validated at workflow construction time. Provide exactly one of `cron` or `runAt`.
|
|
78
|
+
- `runAt` (optional): fire once at this time (epoch milliseconds or `Date`) instead of on a cron. After it fires, the schedule moves to `completed` and later deploys don't re-arm it unless you change `runAt`. A `runAt` that has already passed when the schedule is first registered is recorded as `completed` without firing.
|
|
79
|
+
- `endAt` (optional): only with `cron`. Stop firing after this time. The schedule moves to `completed` once its next occurrence would fall after `endAt`.
|
|
78
80
|
- `timezone` (optional): IANA timezone, for example `America/New_York`. Defaults to the host's local timezone. Set this explicitly in production so fire times don't depend on server locale.
|
|
79
81
|
- `inputData` (optional): payload passed as the workflow's input on every fire.
|
|
80
82
|
- `initialState` (optional): initial state for the run.
|
|
81
83
|
- `requestContext` (optional): request context attached to the run.
|
|
82
84
|
- `metadata` (optional): arbitrary metadata persisted alongside the schedule row.
|
|
83
85
|
|
|
86
|
+
To run a workflow once at a fixed time, use `runAt`:
|
|
87
|
+
|
|
88
|
+
```typescript
|
|
89
|
+
const launchAnnouncement = createWorkflow({
|
|
90
|
+
id: 'launch-announcement',
|
|
91
|
+
schedule: {
|
|
92
|
+
// Set this to a stable future ISO timestamp in your deployment environment.
|
|
93
|
+
runAt: new Date(process.env.LAUNCH_ANNOUNCEMENT_AT!),
|
|
94
|
+
inputData: { userId: 'system' },
|
|
95
|
+
},
|
|
96
|
+
// ...
|
|
97
|
+
})
|
|
98
|
+
```
|
|
99
|
+
|
|
84
100
|
## Multiple schedules
|
|
85
101
|
|
|
86
102
|
Pass an array to fire the same workflow on multiple cadences. Each entry needs a unique stable `id`:
|
|
@@ -147,8 +163,9 @@ In Studio, open the schedule detail page and select **Pause** or **Resume** in t
|
|
|
147
163
|
|
|
148
164
|
A few rules to know:
|
|
149
165
|
|
|
150
|
-
- Pause is durable. The status is written to the schedules table and survives process restarts and redeploys. The declarative-config upsert never overwrites a user-set status, even when you change `cron`, `timezone`, or other fields.
|
|
151
|
-
-
|
|
166
|
+
- Pause is durable. The status is written to the schedules table and survives process restarts and redeploys. The declarative-config upsert never overwrites a user-set status, even when you change `cron`, `timezone`, `runAt`, `endAt`, or other fields.
|
|
167
|
+
- Resuming a cron schedule recomputes `nextFireAt` from now. A schedule paused for a week doesn't fire seven backlogged runs. It fires on the next regular cron tick.
|
|
168
|
+
- Resuming a one-off keeps its configured `runAt`. If that time passed while the schedule was paused, it fires on the next scheduler tick.
|
|
152
169
|
- Unpause with `resumeSchedule` or the **Resume** button in Studio. Editing the workflow's `schedule` config doesn't unpause a paused row.
|
|
153
170
|
- Pause and resume are idempotent. Calling pause on an already-paused schedule is a no-op.
|
|
154
171
|
- This operational override controls existing schedules. Author declarative schedules in code. Declarative schedules are created, deleted, and edited in code via the `schedule` field on `createWorkflow`. To create schedules imperatively at runtime instead, use the unified [`mastra.schedules`](https://mastra.ai/docs/harness/schedules) service with a `workflowId`.
|
|
@@ -159,9 +176,13 @@ The underlying HTTP routes are `POST /api/schedules/:scheduleId/pause` and `POST
|
|
|
159
176
|
|
|
160
177
|
When you change the `schedule` config and redeploy, Mastra diffs the existing schedule row against the new config:
|
|
161
178
|
|
|
162
|
-
- If `cron` or `
|
|
179
|
+
- If `cron`, `timezone`, or `endAt` changes on a recurring schedule, `nextFireAt` is recomputed. A cadence with no future occurrence completes the schedule. A recomputed cadence that can still fire reactivates a completed schedule.
|
|
180
|
+
- If `runAt` changes on a one-off schedule, `nextFireAt` is updated to that time. A future `runAt` reactivates a completed one-off. A past `runAt` leaves it completed.
|
|
181
|
+
- If an active one-off's unchanged `runAt` passed while the app was offline, it remains due and fires on the next scheduler tick. A one-off first registered with a past `runAt` is instead created as `completed` and doesn't fire.
|
|
163
182
|
- If only `inputData`, `initialState`, or `metadata` changed, the row is patched in place and the next fire time is preserved.
|
|
164
|
-
- User-set status (for example, paused via `client.pauseSchedule`) and fire history are never overwritten, unless
|
|
183
|
+
- User-set status (for example, paused via `client.pauseSchedule`) and fire history are never overwritten, unless a timing change above requires a status update.
|
|
184
|
+
|
|
185
|
+
The `completed` status means the schedule has no automatic fires remaining: its one-off fire was claimed, its recurring cadence was exhausted, or its configured timing was already exhausted during registration or reconciliation. It doesn't confirm that the workflow run completed successfully.
|
|
165
186
|
|
|
166
187
|
Removing a schedule entry from a workflow's `schedule` array deletes its row on the next boot.
|
|
167
188
|
|
|
@@ -118,6 +118,45 @@ Markers tell a session what the image already ran: `.mastra-sandbox/repos/<repo>
|
|
|
118
118
|
|
|
119
119
|
If any entry's access or head can't be resolved, the whole resolution rejects and the sandbox falls back to its default template.
|
|
120
120
|
|
|
121
|
+
## Docker Cloud Sandboxes
|
|
122
|
+
|
|
123
|
+
`DockerSandboxesSandbox` runs commands in a Docker Cloud Sandboxes microVM instead of a local container. Supply an authenticated `@docker/sandboxes` client to access Docker Cloud Sandboxes.
|
|
124
|
+
|
|
125
|
+
```typescript
|
|
126
|
+
import { Sandboxes, pat } from '@docker/sandboxes'
|
|
127
|
+
import { Workspace } from '@mastra/core/workspace'
|
|
128
|
+
import { DockerSandboxesSandbox } from '@mastra/docker'
|
|
129
|
+
|
|
130
|
+
const client = new Sandboxes({
|
|
131
|
+
auth: pat({
|
|
132
|
+
username: process.env.DOCKER_USERNAME!,
|
|
133
|
+
personalAccessToken: process.env.DOCKER_PAT!,
|
|
134
|
+
}),
|
|
135
|
+
})
|
|
136
|
+
const workspace = new Workspace({
|
|
137
|
+
sandbox: new DockerSandboxesSandbox({
|
|
138
|
+
id: sessionId,
|
|
139
|
+
image: 'ubuntu:24.04',
|
|
140
|
+
environment: { NODE_ENV: 'production' },
|
|
141
|
+
client,
|
|
142
|
+
}),
|
|
143
|
+
})
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
The `id` is used as the remote sandbox display name for reconnection lookup, so a new instance with the same `id` reconnects to an existing microVM and restarts it if it was stopped. Each instance uses a separate creation idempotency key. Pass `sandboxId` to reconnect directly to a known remote sandbox.
|
|
147
|
+
|
|
148
|
+
Commands run through `sh -lc`, so command strings can use pipes, redirects and `&&`. Separate `args` are shell-quoted. `executeCommand` supports `timeout`, `abortSignal`, streaming `onStdout`/`onStderr` callbacks and `maxRetainedBytes` (default 1 MiB per stream). Calling `destroy()` deletes the remote sandbox.
|
|
149
|
+
|
|
150
|
+
**image** (`string`): Image used to create the cloud sandbox.
|
|
151
|
+
|
|
152
|
+
**id** (`string`): Stable logical identifier used as the remote display name for reconnection lookup. (Default: `Auto-generated`)
|
|
153
|
+
|
|
154
|
+
**sandboxId** (`string`): Remote sandbox name to reconnect to directly.
|
|
155
|
+
|
|
156
|
+
**environment** (`Record<string, string>`): Environment variables set on a newly created cloud sandbox.
|
|
157
|
+
|
|
158
|
+
**client** (`Sandboxes`): Authenticated Docker Cloud Sandboxes client. Supply one to access Docker Cloud Sandboxes; caller-owned clients are not closed on destroy().
|
|
159
|
+
|
|
121
160
|
## Constructor parameters
|
|
122
161
|
|
|
123
162
|
**id** (`string`): Unique identifier for this sandbox instance. Used for label-based reconnection. (Default: `Auto-generated`)
|
|
@@ -178,7 +178,7 @@ const result = await agent.generate('message for agent')
|
|
|
178
178
|
|
|
179
179
|
**options.clientTools** (`ToolsInput`): Client-side tools available during execution.
|
|
180
180
|
|
|
181
|
-
**options.hooks** (`ToolHooks`): Per-execution hooks that run before and after tool calls.
|
|
181
|
+
**options.hooks** (`ToolHooks`): Per-execution hooks that run before and after tool calls, for example to log or save audit records. afterToolCall: (context) => void | Promise\<void> receives toolName, input, and output or error. beforeToolCall can return { proceed: false, output } to skip the tool call. Overrides matching agent-level hooks for this execution. See Run logic around tool calls.
|
|
182
182
|
|
|
183
183
|
**options.savePerStep** (`boolean`): Save messages incrementally after each generation step completes (default: false). Disabled internally when observational memory is enabled.
|
|
184
184
|
|
|
@@ -30,23 +30,11 @@ Scorer judges with legacy model adapters call `generateLegacy()`. They don't rec
|
|
|
30
30
|
|
|
31
31
|
**options.context** (`CoreMessage[]`): Additional context messages to provide to the agent.
|
|
32
32
|
|
|
33
|
-
**options.structuredOutput** (`StructuredOutputOptions<S extends ZodTypeAny = ZodTypeAny>`): Enables structured output generation with better developer experience. Automatically creates and uses a StructuredOutputProcessor internally.
|
|
34
|
-
|
|
35
|
-
**options.structuredOutput.schema** (`z.ZodSchema<S>`): Zod schema to validate the output against.
|
|
36
|
-
|
|
37
|
-
**options.structuredOutput.model** (`MastraLanguageModel`): Model to use for the internal structuring agent.
|
|
38
|
-
|
|
39
|
-
**options.structuredOutput.errorStrategy** (`'strict' | 'warn' | 'fallback'`): Strategy when parsing or validation fails. Defaults to 'strict'.
|
|
40
|
-
|
|
41
|
-
**options.structuredOutput.fallbackValue** (`<S extends ZodTypeAny>`): Fallback value when errorStrategy is 'fallback'.
|
|
42
|
-
|
|
43
|
-
**options.structuredOutput.instructions** (`string`): Custom instructions for the structuring agent.
|
|
44
|
-
|
|
45
33
|
**options.outputProcessors** (`Processor[]`): Overrides the output processors set on the agent. Output processors that can modify or validate messages from the agent before they are returned to the user. Must implement either (or both) of the processOutputResult and processOutputStream functions.
|
|
46
34
|
|
|
47
35
|
**options.inputProcessors** (`Processor[]`): Overrides the input processors set on the agent. Input processors that can modify or validate messages before they are processed by the agent. Must implement the processInput function.
|
|
48
36
|
|
|
49
|
-
**options.experimental_output** (`Zod schema | JsonSchema7`):
|
|
37
|
+
**options.experimental_output** (`Zod schema | JsonSchema7`): Enables structured output generation alongside text generation and tool calls. The model will generate responses that conform to the provided schema.
|
|
50
38
|
|
|
51
39
|
**options.instructions** (`string`): Custom instructions that override the agent's default instructions for this specific generation. Useful for dynamically modifying agent behavior without creating a new agent instance.
|
|
52
40
|
|
|
@@ -120,7 +108,7 @@ Scorer judges with legacy model adapters call `generateLegacy()`. They don't rec
|
|
|
120
108
|
|
|
121
109
|
**text** (`string`): The generated text response. Present when output is 'text' (no schema provided).
|
|
122
110
|
|
|
123
|
-
**object** (`object`): The generated structured response
|
|
111
|
+
**object** (`object`): The generated structured response when a schema is provided via output or experimental_output. With experimental_output, it may be undefined when generation finishes with a reason other than stop.
|
|
124
112
|
|
|
125
113
|
**toolCalls** (`Array<ToolCall>`): The tool calls made during the generation process. Present in both text and object modes.
|
|
126
114
|
|
|
@@ -191,15 +179,11 @@ await agent.generateLegacy(
|
|
|
191
179
|
reasoningEffort: 'high',
|
|
192
180
|
},
|
|
193
181
|
},
|
|
194
|
-
// Structured output
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
}),
|
|
200
|
-
model: 'openai/gpt-6.1-sol',
|
|
201
|
-
errorStrategy: 'warn',
|
|
202
|
-
},
|
|
182
|
+
// Structured output alongside tool calls
|
|
183
|
+
experimental_output: z.object({
|
|
184
|
+
sentiment: z.enum(['positive', 'negative', 'neutral']),
|
|
185
|
+
confidence: z.number(),
|
|
186
|
+
}),
|
|
203
187
|
// Output processors for response validation
|
|
204
188
|
outputProcessors: [
|
|
205
189
|
new ModerationProcessor({ model: 'openai/gpt-6-luna' }),
|
|
@@ -1880,26 +1880,94 @@ curl -sS "https://observability.mastra.ai/api/observability/traces/<trace-id>/sp
|
|
|
1880
1880
|
|
|
1881
1881
|
#### `mastra api score create`
|
|
1882
1882
|
|
|
1883
|
-
Creates
|
|
1883
|
+
Creates a score for a trace. Wrap the record in `score` with a required `traceId` and an optional `spanId`. The CLI generates an ID and timestamp when omitted and preserves them across retries. Pass `--schema` to inspect the request fields.
|
|
1884
1884
|
|
|
1885
1885
|
```bash
|
|
1886
|
-
mastra api score create
|
|
1886
|
+
mastra api score create '{"score":{"traceId":"trace_123","scorerId":"quality","score":0.95}}'
|
|
1887
1887
|
```
|
|
1888
1888
|
|
|
1889
|
+
Score and feedback creates accept an optional top-level `contextMode`. Use `"resolve"` to look up context from a stored trace or span, or `"provided"` to write the fields you supply without a lookup. When you omit `contextMode`, OSS uses `provided` and Platform uses `resolve`, regardless of any context fields you supply.
|
|
1890
|
+
|
|
1891
|
+
Successful writes on Platform mean the record is accepted for storage and may not be readable immediately. Output preserves the server's success response and any returned ID and timestamp. Older servers may return only `success`.
|
|
1892
|
+
|
|
1889
1893
|
#### `mastra api score list`
|
|
1890
1894
|
|
|
1891
|
-
Lists
|
|
1895
|
+
Lists scores with optional filters and pagination.
|
|
1892
1896
|
|
|
1893
1897
|
```bash
|
|
1894
|
-
mastra api score list
|
|
1898
|
+
mastra api score list '{"traceId":"trace_123","page":0,"perPage":50}'
|
|
1895
1899
|
```
|
|
1896
1900
|
|
|
1897
1901
|
#### `mastra api score get`
|
|
1898
1902
|
|
|
1899
|
-
Gets
|
|
1903
|
+
Gets a score by ID. Missing scores return `{"data":{"score":null}}`.
|
|
1904
|
+
|
|
1905
|
+
```bash
|
|
1906
|
+
mastra api score get score_123
|
|
1907
|
+
```
|
|
1908
|
+
|
|
1909
|
+
#### `mastra api feedback create`
|
|
1910
|
+
|
|
1911
|
+
Creates feedback for a trace or span. Wrap the record in `feedback`. Feedback requires `traceId`, with IDs and timestamps generated when omitted.
|
|
1912
|
+
|
|
1913
|
+
```bash
|
|
1914
|
+
mastra api feedback create '{"contextMode":"resolve","feedback":{"traceId":"trace_123","feedbackType":"comment","feedbackSource":"user","value":"actionable","feedbackUserId":"reviewer_123"}}'
|
|
1915
|
+
```
|
|
1916
|
+
|
|
1917
|
+
`feedbackUserId` identifies the feedback author. `userId` describes the trace or span context and is separate from the author.
|
|
1918
|
+
|
|
1919
|
+
#### `mastra api feedback list`
|
|
1920
|
+
|
|
1921
|
+
Lists feedback with optional filters and pagination.
|
|
1922
|
+
|
|
1923
|
+
```bash
|
|
1924
|
+
mastra api feedback list '{"traceId":"trace_123","reviewStatus":"needs-review","page":0,"perPage":50}'
|
|
1925
|
+
```
|
|
1926
|
+
|
|
1927
|
+
#### `mastra api feedback get`
|
|
1928
|
+
|
|
1929
|
+
Gets feedback by ID. Missing feedback returns `{"data":{"feedback":null}}`.
|
|
1930
|
+
|
|
1931
|
+
```bash
|
|
1932
|
+
mastra api feedback get feedback_123
|
|
1933
|
+
```
|
|
1934
|
+
|
|
1935
|
+
#### `mastra api feedback replace`
|
|
1936
|
+
|
|
1937
|
+
Replaces the full feedback record. Send the original `feedbackId`, `traceId`, and `timestamp`, along with the complete replacement. Copy the timestamp from the create response or a subsequent read. The ID in the argument must match the body. Scores don't support replacement.
|
|
1938
|
+
|
|
1939
|
+
```bash
|
|
1940
|
+
mastra api feedback replace feedback_123 '{"feedback":{"feedbackId":"feedback_123","traceId":"trace_123","timestamp":"2026-11-11T10:00:00.123Z","feedbackType":"comment","feedbackSource":"user","value":"corrected"}}'
|
|
1941
|
+
```
|
|
1942
|
+
|
|
1943
|
+
Creates and replacements retry missing trace/span responses and transient failures within the command timeout, for at most six attempts or 30 seconds. Each accepted replacement retry counts as a new replacement. Older servers without PUT support return an error.
|
|
1944
|
+
|
|
1945
|
+
#### `mastra api feedback review-status`
|
|
1946
|
+
|
|
1947
|
+
Changes only the review status to `needs-review` or `reviewed`. No timestamp is required. Missing feedback returns an error, including records still waiting to be stored on Platform.
|
|
1948
|
+
|
|
1949
|
+
```bash
|
|
1950
|
+
mastra api feedback review-status feedback_123 '{"reviewStatus":"reviewed"}'
|
|
1951
|
+
```
|
|
1952
|
+
|
|
1953
|
+
#### Score and feedback analytics
|
|
1954
|
+
|
|
1955
|
+
Both command groups expose `aggregate`, `breakdown`, `timeseries`, and `percentiles` for numeric values. Select scores by `scorerId` and feedback by `feedbackType`. Use `--schema` on an operation to inspect its filters and options.
|
|
1956
|
+
|
|
1957
|
+
```bash
|
|
1958
|
+
mastra api score aggregate '{"scorerId":"quality","aggregation":"avg"}'
|
|
1959
|
+
mastra api score breakdown '{"scorerId":"quality","aggregation":"avg","groupBy":["entityName"]}'
|
|
1960
|
+
mastra api feedback timeseries '{"feedbackType":"rating","aggregation":"avg","interval":"1d"}'
|
|
1961
|
+
mastra api feedback percentiles '{"feedbackType":"rating","percentiles":[0.5,0.95],"interval":"1d"}'
|
|
1962
|
+
```
|
|
1963
|
+
|
|
1964
|
+
#### Score and feedback deletion
|
|
1965
|
+
|
|
1966
|
+
Deletes records by ID. Platform returns `accepted: true` when cleanup is queued. OSS returns `success` after deletion.
|
|
1900
1967
|
|
|
1901
1968
|
```bash
|
|
1902
|
-
mastra api score
|
|
1969
|
+
mastra api score delete '{"scoreIds":["score_123"]}'
|
|
1970
|
+
mastra api feedback delete '{"feedbackIds":["feedback_123"]}'
|
|
1903
1971
|
```
|
|
1904
1972
|
|
|
1905
1973
|
#### `mastra api dataset list`
|
|
@@ -371,11 +371,17 @@ const result = await mastraClient.deleteTraces({
|
|
|
371
371
|
traceIds: ['trace-1', 'trace-2'],
|
|
372
372
|
})
|
|
373
373
|
|
|
374
|
-
|
|
374
|
+
if ('accepted' in result) {
|
|
375
|
+
console.log('Deletion requested')
|
|
376
|
+
} else {
|
|
377
|
+
console.log(result.success)
|
|
378
|
+
}
|
|
375
379
|
```
|
|
376
380
|
|
|
377
381
|
Each request accepts up to 1,000 trace IDs and no tenant scope fields. Signals that aren't linked to a trace are preserved. Traces created by experiments are deleted like any other trace.
|
|
378
382
|
|
|
383
|
+
The client supports two response shapes: OSS returns `{ success: true }` after its delete operation, while a Platform backend that supports queued batch deletion returns `202 { accepted: true }` after accepting cleanup. Acceptance doesn't mean records have disappeared from reads, so check the response before reporting deletion as complete. Using these client methods with Platform requires a deployment that supports the batch deletion endpoints.
|
|
384
|
+
|
|
379
385
|
## Scoring traces
|
|
380
386
|
|
|
381
387
|
Score specific traces using registered scorers for evaluation:
|
|
@@ -432,7 +438,7 @@ const response = await mastraClient.createScore({
|
|
|
432
438
|
|
|
433
439
|
## Feedback
|
|
434
440
|
|
|
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
|
|
441
|
+
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 is supported by Platform and OSS servers with feedback replacement support. 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
442
|
|
|
437
443
|
### Get feedback by ID
|
|
438
444
|
|
|
@@ -492,9 +498,9 @@ Create responses contain `success` and optional `data` with the generated or sup
|
|
|
492
498
|
|
|
493
499
|
Explicit modes require server support. Older servers may ignore `contextMode`. Deploy Platform's supplied-context support before sending `"provided"` there.
|
|
494
500
|
|
|
495
|
-
### Replacing feedback
|
|
501
|
+
### Replacing feedback
|
|
496
502
|
|
|
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.
|
|
503
|
+
`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. Platform and OSS servers with feedback replacement support accept this method. OSS returns `501` when its storage adapter doesn't support replacement. For OSS, check `capabilities.feedbackReplacement` before offering edits. A missing capability means unavailable.
|
|
498
504
|
|
|
499
505
|
```typescript
|
|
500
506
|
await mastraClient.replaceFeedback({
|
|
@@ -509,7 +515,7 @@ await mastraClient.replaceFeedback({
|
|
|
509
515
|
})
|
|
510
516
|
```
|
|
511
517
|
|
|
512
|
-
Use the normalized timestamp from the create response's `data` when available.
|
|
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 automatic retries.
|
|
513
519
|
|
|
514
520
|
### Deleting feedback and scores
|
|
515
521
|
|
|
@@ -529,6 +535,8 @@ await mastraClient.deleteScores({
|
|
|
529
535
|
})
|
|
530
536
|
```
|
|
531
537
|
|
|
538
|
+
Both methods return `{ success: boolean }` from OSS or `{ accepted: true }` from a Platform backend that supports queued batch deletion. See [Deleting traces](#deleting-traces) for response handling. Accepted records can remain readable until cleanup runs. Platform uses authenticated organization/project scope, which request-body scope fields can't override.
|
|
539
|
+
|
|
532
540
|
### Listing feedback
|
|
533
541
|
|
|
534
542
|
Retrieve paginated feedback records with optional filters:
|
|
@@ -109,6 +109,7 @@ The resolver also exposes methods for manual control:
|
|
|
109
109
|
- `refresh()` fetches from the platform immediately, then updates the cache and returns the tool record. Rejects if the platform fetch fails.
|
|
110
110
|
- `disconnect()` clears the cached snapshots and closes the MCP transports of the state behind this resolver. Resolvers created with identical options share that state, so this disconnects them too. A later resolution rebuilds the state, and already-returned MCP tools reconnect on their next call.
|
|
111
111
|
- `with(extra)` returns a new resolver that merges extra tools into every resolution, giving extras priority on key collision. It accepts a static tool record or a function (sync or async) and calls chain. For the same merge using a spread of the resolver's result in a `tools` callback, see [Add tools to an agent](https://mastra.ai/docs/mastra-platform/connect).
|
|
112
|
+
- `codeMode(options)` exposes the tools through [Code Mode](#code-mode).
|
|
112
113
|
|
|
113
114
|
To filter on something other than tool keys, or on data that options can't express, post-process the resolved record in the agent's `tools` function. Create the resolver once, outside the function, so its cache is shared:
|
|
114
115
|
|
|
@@ -144,6 +145,64 @@ Error handling depends on the cause:
|
|
|
144
145
|
- If a background refresh fails while a snapshot is cached, the resolver keeps serving the cached toolsets and warns. It rejects only when nothing was ever cached.
|
|
145
146
|
- A problem with one provider, such as a connection that needs reauthorization, logs a warning and skips that provider. The other providers' tools still load.
|
|
146
147
|
|
|
148
|
+
## Code Mode
|
|
149
|
+
|
|
150
|
+
`codeMode()` gives the agent the connected tools through [Code Mode](https://mastra.ai/docs/agents/code-mode): the agent writes one TypeScript program that calls the tools as `external_*` functions, instead of calling each tool in its own step. Use it when tasks fan out across many calls or providers, such as listing items in one provider and looking each one up in another.
|
|
151
|
+
|
|
152
|
+
```typescript
|
|
153
|
+
import { Agent } from '@mastra/core/agent'
|
|
154
|
+
import { LocalSandbox } from '@mastra/core/workspace'
|
|
155
|
+
import { tools } from '@mastra/connect'
|
|
156
|
+
|
|
157
|
+
const code = tools({ providers: ['linear', 'slack'] }).codeMode({ sandbox: new LocalSandbox() })
|
|
158
|
+
|
|
159
|
+
export const opsAgent = new Agent({
|
|
160
|
+
id: 'ops',
|
|
161
|
+
name: 'ops',
|
|
162
|
+
instructions: async ctx => ['You help the team track work.', await code.instructions(ctx)],
|
|
163
|
+
model: 'openai/gpt-6-luna',
|
|
164
|
+
tools: code.tools,
|
|
165
|
+
})
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
> **Warning:** `LocalSandbox` runs the model-written program as a host `node` process with host privileges. Connected tools return third-party data, such as issue text, that can influence the code the model writes. Use `LocalSandbox` only for trusted or local development. See [how Code Mode works](https://mastra.ai/docs/agents/code-mode) for isolated alternatives.
|
|
169
|
+
|
|
170
|
+
`codeMode()` returns two functions, `tools` and `instructions`. Pass both to the agent. Like the resolver, they resolve the current connections on every request. The functions the program can call change as providers are connected or disconnected. Within one request both use the same resolution, and the instructions never declare a function the program can't call.
|
|
171
|
+
|
|
172
|
+
The method accepts every [`createCodeMode()` option](https://mastra.ai/reference/tools/create-code-mode) except `tools` (`sandbox`, `timeout`, `id`), plus `transport` for a [remote sandbox](https://mastra.ai/docs/agents/code-mode) or [in-process isolation](https://mastra.ai/docs/agents/code-mode), and `toolSearch` for [tool search](#tool-search). Every resolver provides it, including the callback form and resolvers returned by `with()`. Extra tools from `with()` join the program's functions.
|
|
173
|
+
|
|
174
|
+
Some tools stay direct agent tools instead of program functions, because they pause the agent run and a call from inside a program can't:
|
|
175
|
+
|
|
176
|
+
- Tools that need approval through `requireApproval`. The agent still waits for the user to approve each call.
|
|
177
|
+
- The `request_connection` tool, so the connect prompt can still pause the run until the user connects.
|
|
178
|
+
|
|
179
|
+
For [MCP providers](#mcp-providers), a `requireApproval` list keeps **all** of that provider's tools direct, including the ones the list doesn't name. Mastra discovers MCP tools at request time and checks the list on each call, so Code Mode has no way to know in advance which calls need approval and keeps every tool from that provider out of the program. Generated HTTP tools work differently, because only the tools that match the list stay direct.
|
|
180
|
+
|
|
181
|
+
```typescript
|
|
182
|
+
// Every neon-mcp tool stays direct, not just neon-mcp_run_sql
|
|
183
|
+
const ops = tools({
|
|
184
|
+
providers: { 'neon-mcp': { requireApproval: ['neon-mcp_run_sql'] } },
|
|
185
|
+
}).codeMode({ sandbox })
|
|
186
|
+
```
|
|
187
|
+
|
|
188
|
+
To let a program call that provider's other tools, remove the gated tools with `disallowTools` instead of gating them. To keep them gated, accept that the agent calls the provider's tools one at a time.
|
|
189
|
+
|
|
190
|
+
When there is nothing to orchestrate, for example when the project has no connections yet, `tools` returns only the direct tools and `instructions` returns an empty string.
|
|
191
|
+
|
|
192
|
+
### Tool search
|
|
193
|
+
|
|
194
|
+
Declaring every function in the instructions uses context on every request: about 4,000 tokens for Linear alone and over 20,000 for Linear, GitHub, and Stripe together. With tool search, the instructions list only the function names, and the agent gets a `search_functions` tool that returns the TypeScript declarations for the functions it needs. The agent searches by what it wants to do or by exact names from the list, then writes the program. The program can still call every function. Only the declarations move behind the search.
|
|
195
|
+
|
|
196
|
+
Tool search turns on by itself when declaring every function would take more than about 10,000 tokens. Set `toolSearch` to choose:
|
|
197
|
+
|
|
198
|
+
```typescript
|
|
199
|
+
// Always list names only and search for declarations
|
|
200
|
+
const searching = tools().codeMode({ sandbox: new LocalSandbox(), toolSearch: true })
|
|
201
|
+
|
|
202
|
+
// Always declare every function up front
|
|
203
|
+
const declared = tools().codeMode({ sandbox: new LocalSandbox(), toolSearch: false })
|
|
204
|
+
```
|
|
205
|
+
|
|
147
206
|
## Choosing providers
|
|
148
207
|
|
|
149
208
|
The `providers` array form is an allowlist: only listed providers are returned. Without the option, every connected provider with a supported toolset is included. A listed provider with no connection in the project yet is skipped and included automatically once a connection is attached. In the record form, `false` excludes a provider and never errors, even for IDs that match nothing.
|
|
@@ -38,7 +38,7 @@ export const mastra = new Mastra({
|
|
|
38
38
|
|
|
39
39
|
**builder** (`AgentBuilderOptions`): Agent Builder configuration. See the AgentBuilderOptions reference. Omit or set enabled: false to disable the Builder.
|
|
40
40
|
|
|
41
|
-
**source** (`'code' | 'db'`): Where agent overrides are stored. With 'db', overrides live in the configured storage backend and Studio shows the save and publish flow. With 'code', overrides live as per-agent JSON files
|
|
41
|
+
**source** (`'code' | 'db'`): Where agent overrides are stored. With 'db', overrides live in the configured storage backend and Studio shows the save and publish flow. With 'code', overrides live as per-agent JSON files at codePath (routed through a local FilesystemStore) and Studio shows filesystem actions. When source is 'code' and a source-control provider is configured, agent overrides are persisted through source-control operations instead of the local filesystem, and the provider controls the repository path. A provider passed as sourceControlProvider uses its own pathPrefix; the provider created from environment variables uses MASTRA_SOURCE_STORAGE_PATH_PREFIX when it is set, and codePath otherwise. The environment provider is created only when MASTRA_SOURCE_PROVIDER is github, an endpoint is set (MASTRA_SOURCE_PROVIDER_ENDPOINT, MASTRA_SHARED_API_URL, or MASTRA_CLOUD_API_ENDPOINT), and a token is set (MASTRA_PLATFORM_ACCESS_TOKEN or MASTRA_CLOUD_ACCESS_TOKEN). Each list is checked in order and the first defined variable wins, so an empty higher-priority variable disables the provider instead of falling back. The endpoint is a Mastra platform API that brokers the GitHub operations, so the provider never calls the GitHub API directly. Without a provider, overrides stay in the local files at codePath. See Editor storage options for the difference. (Default: `'db'`)
|
|
42
42
|
|
|
43
43
|
**codePath** (`string`): Directory used by the 'code' source for per-agent JSON files. Ignored when source is not 'code'. (Default: `'./mastra/editor'`)
|
|
44
44
|
|
|
@@ -33,7 +33,7 @@ await mastra.observability.addFeedback({
|
|
|
33
33
|
|
|
34
34
|
### `addFeedback(args)`
|
|
35
35
|
|
|
36
|
-
|
|
36
|
+
Sends feedback about a trace or span to configured exporters.
|
|
37
37
|
|
|
38
38
|
```typescript
|
|
39
39
|
await mastra.observability.addFeedback?.({
|
|
@@ -56,7 +56,9 @@ await mastra.observability.addFeedback?.({
|
|
|
56
56
|
|
|
57
57
|
**feedback** (`FeedbackInput`): Feedback payload to add.
|
|
58
58
|
|
|
59
|
-
Without `correlationContext`,
|
|
59
|
+
Without `correlationContext`, each exporter handles the target trace or span at its own destination. `MastraStorageExporter` resolves it from local storage. A failed local lookup doesn't block other exporters. `MastraPlatformExporter` doesn't require local storage. Use `flush()` or `shutdown()` to drain pending deliveries.
|
|
60
|
+
|
|
61
|
+
Local lookup requires the target span's parent chain through its root so feedback inherits the correct root tags. If any ancestor remains missing after retries, the storage exporter logs a warning and skips the local write. Other exporters still receive the feedback.
|
|
60
62
|
|
|
61
63
|
### `createFeedback(args)`
|
|
62
64
|
|
|
@@ -138,7 +140,7 @@ await mastraClient.deleteFeedback({
|
|
|
138
140
|
|
|
139
141
|
**resourceId** (`string`): Restricts the delete to records with this resource id.
|
|
140
142
|
|
|
141
|
-
|
|
143
|
+
The OSS HTTP route returns `{ success: boolean }`. `mastraClient.deleteFeedback()` returns `Promise<{ success: boolean } | { accepted: true }>` to also support Platform backends with queued batch deletion. An accepted response means cleanup is queued, and records can remain readable until cleanup runs. See [client deletion response handling](https://mastra.ai/reference/client-js/observability). The storage domain method returns `Promise<void>`. Requests with more than 1,000 ids return `400`, and a server running `@mastra/core` older than `1.66.0` returns `501`. ClickHouse vNext, PostgreSQL vNext, DuckDB, and the in-memory store implement deletion. Every other adapter, including LibSQL and MongoDB, throws `OBSERVABILITY_STORAGE_DELETE_FEEDBACK_NOT_IMPLEMENTED`.
|
|
142
144
|
|
|
143
145
|
On ClickHouse, deletion uses lightweight deletes on the main feedback events table to remove rows from reads, including OLAP queries, without guaranteeing immediate physical removal, so open-source deployments must configure an [observability retention period](https://mastra.ai/reference/storage/retention) to physically purge them. Each request is marked applied once its delete succeeds; if the delete fails, the request stays unapplied, doesn't block `updateFeedbackReviewStatus()` on the still-visible feedback, and you retry by calling `deleteFeedback()` again. `updateFeedbackReviewStatus()` also retries the delete and throws a not-found error if the retry succeeds, or saves the new status and throws the delete's error if it fails again. Open-source deployments have no background reconciler. ClickHouse applies a TTL to deletion requests only when all five signals have finite retention. See [ClickHouse native TTL](https://mastra.ai/reference/storage/retention). Delete APIs leave the separate delta cursor table untouched. Its rows contain identifiers rather than feedback payloads and expire within two days.
|
|
144
146
|
|
|
@@ -413,21 +415,62 @@ Use `FeedbackFilter` in `listFeedback()` and OLAP query `filters`.
|
|
|
413
415
|
|
|
414
416
|
**tags** (`string[]`): Filter by tags. Matching records must have all specified tags.
|
|
415
417
|
|
|
418
|
+
## Replace feedback
|
|
419
|
+
|
|
420
|
+
`PUT /api/observability/feedback/:feedbackId` accepts a full `{ feedback: { ... } }` replacement. Keep the original `feedbackId`, `traceId`, and `timestamp`, and include every field you want to retain. Omitted optional fields are cleared. The URL and body IDs must match. See [the client example](https://mastra.ai/reference/client-js/observability).
|
|
421
|
+
|
|
422
|
+
OSS writes to its configured storage before returning success and notifies supporting exporters independently. `contextMode` has the same meaning as on create. In `"resolve"` mode, the local trace or span must exist. A missing feedback record is created from the full replacement. Changing an existing record's trace or timestamp returns `409`.
|
|
423
|
+
|
|
424
|
+
In-memory, PostgreSQL vNext, DuckDB, and ClickHouse vNext storage support replacement. Check `capabilities.feedbackReplacement` on the server. Unsupported versions return `501`. Sequential retries of the original HTTP create don't undo a replacement. Direct storage `createFeedback()` calls retain upsert behavior. Pass `onConflict: 'ignore'` to keep an existing record.
|
|
425
|
+
|
|
426
|
+
ClickHouse support uses the existing schema without a migration. Concurrent writes from separate processes can race, so it doesn't guarantee ordering between overlapping creates and replacements. Serialize edits to the same feedback record when using this adapter.
|
|
427
|
+
|
|
428
|
+
To send a replacement to configured exporters without depending on local storage, use the observability entrypoint:
|
|
429
|
+
|
|
430
|
+
```typescript
|
|
431
|
+
await mastra.observability.replaceFeedback?.({
|
|
432
|
+
traceId: 'trace-123',
|
|
433
|
+
feedback: {
|
|
434
|
+
feedbackId: 'feedback-1',
|
|
435
|
+
timestamp: new Date('2026-11-11T12:00:00.123Z'),
|
|
436
|
+
feedbackType: 'thumbs',
|
|
437
|
+
value: -1,
|
|
438
|
+
},
|
|
439
|
+
})
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
Each exporter handles its destination independently. `MastraStorageExporter` resolves local span context when needed, and `MastraPlatformExporter` sends a PUT to Platform. Exporters without a replacement handler skip the event. `flush()` and `shutdown()` wait for pending deliveries.
|
|
443
|
+
|
|
444
|
+
## Updating review status
|
|
445
|
+
|
|
446
|
+
To change review status at configured exporter destinations, pass the feedback ID and either `"reviewed"` or `"needs-review"`:
|
|
447
|
+
|
|
448
|
+
```typescript
|
|
449
|
+
await mastra.observability.updateFeedbackReviewStatus?.({
|
|
450
|
+
feedbackId: 'feedback-123',
|
|
451
|
+
reviewStatus: 'reviewed',
|
|
452
|
+
})
|
|
453
|
+
await mastra.observability.flush()
|
|
454
|
+
```
|
|
455
|
+
|
|
456
|
+
Review updates go to each exporter that supports them, even when the feedback isn't stored locally. Call `flush()` or `shutdown()` to wait for pending deliveries.
|
|
457
|
+
|
|
416
458
|
## HTTP routes
|
|
417
459
|
|
|
418
460
|
These routes belong to a Mastra runtime and use its configured observability storage. They're separate from the [unversioned Mastra Platform Feedback API](https://mastra.ai/docs/mastra-platform/api), which doesn't provide a feedback creation route.
|
|
419
461
|
|
|
420
|
-
| Method | Path | Purpose
|
|
421
|
-
| -------- | ------------------------------------------------------- |
|
|
422
|
-
| `GET` | `/api/observability/feedback` | List feedback records
|
|
423
|
-
| `POST` | `/api/observability/feedback` | Create a feedback record
|
|
424
|
-
| `
|
|
425
|
-
| `DELETE` | `/api/observability/
|
|
426
|
-
| `
|
|
427
|
-
| `
|
|
428
|
-
| `POST` | `/api/observability/feedback/
|
|
429
|
-
| `POST` | `/api/observability/feedback/
|
|
430
|
-
| `POST` | `/api/observability/feedback/
|
|
462
|
+
| Method | Path | Purpose | Permission |
|
|
463
|
+
| -------- | ------------------------------------------------------- | ---------------------------------- | ---------------------- |
|
|
464
|
+
| `GET` | `/api/observability/feedback` | List feedback records | `observability:read` |
|
|
465
|
+
| `POST` | `/api/observability/feedback` | Create a feedback record | `observability:write` |
|
|
466
|
+
| `PUT` | `/api/observability/feedback/:feedbackId` | Replace a complete feedback record | `observability:write` |
|
|
467
|
+
| `DELETE` | `/api/observability/feedback` | Delete feedback records by id | `observability:delete` |
|
|
468
|
+
| `DELETE` | `/api/observability/scores` | Delete score records by id | `observability:delete` |
|
|
469
|
+
| `PATCH` | `/api/observability/feedback/:feedbackId/review-status` | Update review status | `observability:write` |
|
|
470
|
+
| `POST` | `/api/observability/feedback/aggregate` | Return one aggregate value | `observability:read` |
|
|
471
|
+
| `POST` | `/api/observability/feedback/breakdown` | Group feedback by dimensions | `observability:read` |
|
|
472
|
+
| `POST` | `/api/observability/feedback/timeseries` | Bucket feedback by interval | `observability:read` |
|
|
473
|
+
| `POST` | `/api/observability/feedback/percentiles` | Return percentile series | `observability:read` |
|
|
431
474
|
|
|
432
475
|
### List query parameters
|
|
433
476
|
|
|
@@ -35,6 +35,7 @@ The configured observability store must support each API. Call `getObservability
|
|
|
35
35
|
| -------------------------------- | -------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
36
36
|
| `traceQuery` | `trace-query` | `queryTraces()` |
|
|
37
37
|
| `spanQuery` | `span-query` | `querySpans()` |
|
|
38
|
+
| `spanQueryDurationSort` | `span-query-duration-sort` | `orderBy` on `durationMs` in `querySpans()` |
|
|
38
39
|
| `spanQueryContextFields` | `span-query-context-fields` | Additional identity, context, and parent/root entity predicates in span queries and aggregates |
|
|
39
40
|
| `spanQueryModelFields` | `span-query-model-fields` | `model` and `provider` predicates in span queries and aggregates |
|
|
40
41
|
| `traceAggregate` | `trace-aggregate` | `aggregateTraces()` |
|
|
@@ -672,7 +673,7 @@ const result = await mastraClient.querySpans({
|
|
|
672
673
|
console.log(result.spans)
|
|
673
674
|
```
|
|
674
675
|
|
|
675
|
-
Pages default to 100 rows and allow at most 1,000. The response is `{ spans, page: { next } }`, without a total count. Ordering accepts exactly one of `startedAt`, `endedAt`, `timeToFirstChunkMs`, or `timeToFirstTokenMs`, ascending or descending, and defaults to descending start time. Spans without a value for the `timeToFirstChunkMs` or `timeToFirstTokenMs` sort field sort last in both directions.
|
|
676
|
+
Pages default to 100 rows and allow at most 1,000. The response is `{ spans, page: { next } }`, without a total count. Ordering accepts exactly one of `startedAt`, `endedAt`, `durationMs`, `timeToFirstChunkMs`, or `timeToFirstTokenMs`, ascending or descending, and defaults to descending start time. Spans without a value for the `timeToFirstChunkMs` or `timeToFirstTokenMs` sort field sort last in both directions.
|
|
676
677
|
|
|
677
678
|
| Fields | Operators |
|
|
678
679
|
| -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------- |
|
|
@@ -9,7 +9,7 @@ Sends Tracing data to Langfuse for observability.
|
|
|
9
9
|
## Constructor
|
|
10
10
|
|
|
11
11
|
```typescript
|
|
12
|
-
new LangfuseExporter(config
|
|
12
|
+
new LangfuseExporter(config?: LangfuseExporterConfig)
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
## `LangfuseExporterConfig`
|
|
@@ -25,6 +25,7 @@ interface LangfuseExporterConfig extends BaseExporterConfig {
|
|
|
25
25
|
flushInterval?: number
|
|
26
26
|
environment?: string
|
|
27
27
|
release?: string
|
|
28
|
+
resourceAttributes?: DetectedResourceAttributes
|
|
28
29
|
}
|
|
29
30
|
```
|
|
30
31
|
|
|
@@ -33,6 +34,28 @@ Extends `BaseExporterConfig`, which includes:
|
|
|
33
34
|
- `logger?: IMastraLogger` - Logger instance
|
|
34
35
|
- `logLevel?: LogLevel | 'debug' | 'info' | 'warn' | 'error'` - Log level (default: INFO)
|
|
35
36
|
|
|
37
|
+
**publicKey** (`string`): Langfuse API key. Falls back to LANGFUSE_PUBLIC_KEY env var.
|
|
38
|
+
|
|
39
|
+
**secretKey** (`string`): Langfuse secret key. Falls back to LANGFUSE_SECRET_KEY env var.
|
|
40
|
+
|
|
41
|
+
**baseUrl** (`string`): Langfuse host URL. Falls back to LANGFUSE_BASE_URL env var. Default: https\://cloud.langfuse.com
|
|
42
|
+
|
|
43
|
+
**additionalHeaders** (`Record<string, string>`): Additional headers sent with requests to Langfuse.
|
|
44
|
+
|
|
45
|
+
**realtime** (`boolean`): Enable realtime mode - exports spans immediately instead of batching
|
|
46
|
+
|
|
47
|
+
**flushAt** (`number`): Maximum number of spans per OTEL export batch. Forwarded to the underlying LangfuseSpanProcessor.
|
|
48
|
+
|
|
49
|
+
**flushInterval** (`number`): Maximum time in seconds before pending spans are exported. Forwarded to the underlying LangfuseSpanProcessor.
|
|
50
|
+
|
|
51
|
+
**environment** (`string`): Environment tag for traces (e.g. production, staging). Shows in Langfuse UI for filtering.
|
|
52
|
+
|
|
53
|
+
**release** (`string`): Release tag for traces (e.g. git commit hash). Used for version tracking.
|
|
54
|
+
|
|
55
|
+
**resourceAttributes** (`DetectedResourceAttributes`): OpenTelemetry resource attributes, such as service.version. Values here override the defaults.
|
|
56
|
+
|
|
57
|
+
**logLevel** (`'debug' | 'info' | 'warn' | 'error'`): Level for the logger the exporter creates when no logger is passed (default: 'info'). It has no effect on a supplied logger. When the exporter is registered with Mastra, Mastra replaces this logger with the application logger.
|
|
58
|
+
|
|
36
59
|
## Properties
|
|
37
60
|
|
|
38
61
|
### `client`
|
|
@@ -37,7 +37,7 @@ interface MastraPlatformExporterConfig extends BaseExporterConfig {
|
|
|
37
37
|
uploadTimeoutMs?: number // Default: 30000
|
|
38
38
|
}
|
|
39
39
|
|
|
40
|
-
/** Maximum retry attempts. Default: 3 */
|
|
40
|
+
/** Maximum retry attempts for collector batches. Default: 3 */
|
|
41
41
|
maxRetries?: number
|
|
42
42
|
|
|
43
43
|
/** Mastra Observability access token (from env or config) */
|
|
@@ -142,11 +142,9 @@ Every `MetricEvent` passed to this handler is buffered and exported to the metri
|
|
|
142
142
|
async onScoreEvent(event: ScoreEvent): Promise<void>
|
|
143
143
|
```
|
|
144
144
|
|
|
145
|
-
|
|
145
|
+
Schedules a score for export using the [feedback and score delivery](#feedback-and-score-delivery) behavior. Events are ignored when the exporter is disabled or shutdown has started. If Platform needs to look up the trace, a missing trace ID causes the record to be dropped.
|
|
146
146
|
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
**Returns:** `Promise<void>` after the score event has been accepted for buffering.
|
|
147
|
+
**Returns:** `Promise<void>` when the event has been scheduled or ignored. Call `flush()` to wait for pending deliveries, because this return value doesn't confirm delivery.
|
|
150
148
|
|
|
151
149
|
### `onFeedbackEvent`
|
|
152
150
|
|
|
@@ -154,11 +152,9 @@ Every `ScoreEvent` passed to this handler is buffered and exported to the scores
|
|
|
154
152
|
async onFeedbackEvent(event: FeedbackEvent): Promise<void>
|
|
155
153
|
```
|
|
156
154
|
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
Every `FeedbackEvent` passed to this handler is buffered and exported to the feedback endpoint derived from the configured base endpoint. No feedback-type filtering inside `MastraPlatformExporter` is performed. All feedback events received here are forwarded unless the exporter is disabled.
|
|
155
|
+
Schedules feedback for export using the [feedback and score delivery](#feedback-and-score-delivery) behavior. Events are ignored when the exporter is disabled or shutdown has started. If Platform needs to look up the trace, a missing trace ID causes the record to be dropped.
|
|
160
156
|
|
|
161
|
-
**Returns:** `Promise<void>`
|
|
157
|
+
**Returns:** `Promise<void>` when the event has been scheduled or ignored. Call `flush()` to wait for pending deliveries, because this return value doesn't confirm delivery.
|
|
162
158
|
|
|
163
159
|
### flush
|
|
164
160
|
|
|
@@ -187,12 +183,18 @@ If no access token is provided via config or environment variable, the exporter:
|
|
|
187
183
|
|
|
188
184
|
### Batching
|
|
189
185
|
|
|
190
|
-
The exporter batches
|
|
186
|
+
The exporter batches traces, logs, and metrics, along with feedback and scores that already include their trace details:
|
|
191
187
|
|
|
192
188
|
- Flushes when total buffered event count reaches `maxBatchSize`
|
|
193
189
|
- Flushes when `maxBatchWaitMs` elapsed since the first buffered signal in the batch
|
|
194
190
|
- Flushes on `shutdown()`
|
|
195
191
|
|
|
192
|
+
### Feedback and score delivery
|
|
193
|
+
|
|
194
|
+
Feedback and scores received by the exporter can reference a trace stored in Platform using its trace ID and an optional span ID. If the record needs details from that trace, the exporter sends it immediately instead of waiting for a batch.
|
|
195
|
+
|
|
196
|
+
Call `flush()` before ending a short-lived process, or `shutdown()` when stopping the exporter, to wait for pending deliveries and retries. These methods finish when records have been accepted or dropped after a failure. Accepted feedback and scores may take time to appear in Platform.
|
|
197
|
+
|
|
196
198
|
### Byte batching
|
|
197
199
|
|
|
198
200
|
Set `byteBatching` to flush by serialized byte size and control concurrent uploads:
|
|
@@ -212,7 +214,7 @@ const exporter = new MastraPlatformExporter({
|
|
|
212
214
|
Without `byteBatching`, the exporter keeps its existing count-based batching behavior.
|
|
213
215
|
|
|
214
216
|
- `maxBatchBytes` triggers an upload when a batch reaches 8 MiB by default. Larger records are sent intact, without truncation or size-based drops.
|
|
215
|
-
- `maxConcurrentUploads` controls concurrent
|
|
217
|
+
- `maxConcurrentUploads` controls concurrent collector batch uploads. The default is two.
|
|
216
218
|
- `uploadTimeoutMs` sets the upload deadline, including retries. The default is 30 seconds.
|
|
217
219
|
|
|
218
220
|
Record-count and timer-based flush triggers still apply. Queued records are retained when uploads fall behind, so queue memory can grow.
|
|
@@ -221,7 +223,7 @@ Inspect the current queue with `exporter.getByteBatchingStats()`.
|
|
|
221
223
|
|
|
222
224
|
### Error handling
|
|
223
225
|
|
|
224
|
-
- Uses exponential backoff retry with `maxRetries` attempts
|
|
226
|
+
- Uses exponential backoff retry for collector batches with `maxRetries` attempts
|
|
225
227
|
- Drops batches after all retries fail
|
|
226
228
|
- Logs errors but continues processing new events
|
|
227
229
|
|
|
@@ -232,14 +234,14 @@ Errors raised by `MastraPlatformExporter` use the `MASTRA_PLATFORM_EXPORTER_*` `
|
|
|
232
234
|
When an organization has exhausted its observability quota, the Mastra platform rejects publish requests with `402 Payment Required` plus the `x-mastra-observability: disabled` header. When the exporter sees a `402` (or the header) on any publish route, it:
|
|
233
235
|
|
|
234
236
|
- Drops the rejected batch without retrying it
|
|
235
|
-
- Pauses
|
|
237
|
+
- Pauses collector batches for traces, logs, metrics, scores, and feedback, dropping buffered and incoming batch records
|
|
236
238
|
- Logs a warning that telemetry is paused
|
|
237
239
|
- Probes the platform periodically with an empty batch, using the interval from the `x-mastra-observability-retry-after` header (seconds), or every 5 minutes if the header is absent
|
|
238
240
|
- Resumes exporting automatically and logs a warning once the platform stops rejecting with `402`
|
|
239
241
|
|
|
240
242
|
The probe timer doesn't keep the Node.js process alive, so short-lived and serverless processes exit normally while paused.
|
|
241
243
|
|
|
242
|
-
Every request
|
|
244
|
+
Every collector request (batch uploads and the traces recovery probe) includes the `x-mastra-observability-capabilities: quota-pause-v1` header. This tells the platform that the client understands the quota-pause contract, so it can safely respond with `402` instead of silently dropping telemetry for older clients that would retry it.
|
|
243
245
|
|
|
244
246
|
### Endpoint routing
|
|
245
247
|
|
|
@@ -248,10 +250,11 @@ Every request the exporter sends (batch uploads for all five signal types, plus
|
|
|
248
250
|
- With `projectId` or `MASTRA_PROJECT_ID`, derived routes use `/projects/:projectId/ai/{signal}/publish`
|
|
249
251
|
- Explicit full publish URLs are used as-is, even when `projectId` is configured
|
|
250
252
|
|
|
251
|
-
###
|
|
253
|
+
### Event processing
|
|
252
254
|
|
|
253
255
|
- `exportTracingEvent()` only exports `SPAN_ENDED` tracing events
|
|
254
|
-
- `onLogEvent()
|
|
256
|
+
- `onLogEvent()` and `onMetricEvent()` buffer events
|
|
257
|
+
- `onScoreEvent()` and `onFeedbackEvent()` deliver records as described in [Feedback and score delivery](#feedback-and-score-delivery)
|
|
255
258
|
- All supported signal batches are uploaded to their matching publish endpoints during `flush()` and `shutdown()`
|
|
256
259
|
|
|
257
260
|
## Span wire format
|
|
@@ -36,7 +36,7 @@ interface OtelExporterConfig {
|
|
|
36
36
|
|
|
37
37
|
**batchSize** (`number`): Number of spans/logs per batch (default: 512)
|
|
38
38
|
|
|
39
|
-
**logLevel** (`'debug' | 'info' | 'warn' | 'error'`):
|
|
39
|
+
**logLevel** (`'debug' | 'info' | 'warn' | 'error'`): Level for the logger the exporter creates when no logger is passed (default: 'info'). It has no effect on a supplied logger. When the exporter is registered with Mastra, Mastra replaces this logger with the application logger. Setting debug also writes exporter diagnostics directly to the console and installs a global OpenTelemetry diagnostic logger, whichever logger is in use.
|
|
40
40
|
|
|
41
41
|
**metadataMapping** (`Record<string, string>`): Maps metadata keys to top-level span attribute names, for example { userId: "user.id" }. Disabled by default. Namespaced metadata is retained. See Metadata mapping below for value conversion and precedence.
|
|
42
42
|
|
|
@@ -1006,11 +1006,11 @@ interface ModelStepResult {
|
|
|
1006
1006
|
|
|
1007
1007
|
### `InterruptedSpanOutput`
|
|
1008
1008
|
|
|
1009
|
-
Output recorded on `AGENT_RUN`, `MODEL_GENERATION` and `MODEL_STEP` spans when the run stops before the span's own result exists: a durable run suspended, or the
|
|
1009
|
+
Output recorded on `AGENT_RUN`, `MODEL_GENERATION` and `MODEL_STEP` spans when the run stops before the span's own result exists: a durable run suspended, the caller aborted, or the process running a durable run stopped and the run was recovered elsewhere. `MODEL_INFERENCE` spans never carry it.
|
|
1010
1010
|
|
|
1011
1011
|
```typescript
|
|
1012
1012
|
interface InterruptedSpanOutput {
|
|
1013
|
-
status: 'suspended' | 'aborted'
|
|
1013
|
+
status: 'suspended' | 'aborted' | 'interrupted'
|
|
1014
1014
|
/** Why the run stopped */
|
|
1015
1015
|
reason?: string
|
|
1016
1016
|
/** Tool that suspended the run */
|
|
@@ -652,6 +652,29 @@ processOutputStream?(args: ProcessOutputStreamArgs): Promise<ChunkType | null |
|
|
|
652
652
|
|
|
653
653
|
Dropping a chunk only affects that single chunk. The stream continues and the next chunk is still processed. To stop the stream entirely, call `abort()`.
|
|
654
654
|
|
|
655
|
+
#### Emitting a second chunk
|
|
656
|
+
|
|
657
|
+
`processOutputStream` returns one chunk, but a processor sometimes needs to emit two for one input, such as text it held back followed by the chunk that released it. Return the first chunk and set the second on `state` under `REPROCESS_PART_KEY`. Mastra emits the stashed chunk right after the returned one.
|
|
658
|
+
|
|
659
|
+
The stashed chunk goes through the output processors again, including the one that stashed it, so that processor must pass it through unchanged on the second pass:
|
|
660
|
+
|
|
661
|
+
```typescript
|
|
662
|
+
import { REPROCESS_PART_KEY } from '@mastra/core/processors'
|
|
663
|
+
import type { ChunkType } from '@mastra/core/stream'
|
|
664
|
+
import type { ProcessOutputStreamArgs, Processor } from '@mastra/core/processors'
|
|
665
|
+
|
|
666
|
+
export class SignOff implements Processor<'sign-off'> {
|
|
667
|
+
readonly id = 'sign-off'
|
|
668
|
+
|
|
669
|
+
async processOutputStream({ part, state }: ProcessOutputStreamArgs): Promise<ChunkType> {
|
|
670
|
+
if (part.type !== 'text-end' || state.signed) return part
|
|
671
|
+
state.signed = true
|
|
672
|
+
state[REPROCESS_PART_KEY] = part
|
|
673
|
+
return { ...part, type: 'text-delta', payload: { id: part.payload.id, text: '\n\nCheers!' } }
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
```
|
|
677
|
+
|
|
655
678
|
***
|
|
656
679
|
|
|
657
680
|
### `processOutputResult`
|
|
@@ -50,6 +50,15 @@ const schedule = await mastra.schedules.create({
|
|
|
50
50
|
|
|
51
51
|
Schedules require a storage adapter that implements the schedules domain. Supported adapters include `@mastra/libsql`, `@mastra/pg`, `@mastra/mysql`, `@mastra/mongodb`, `@mastra/convex`, and `@mastra/spanner`.
|
|
52
52
|
|
|
53
|
+
To run once at a fixed time, pass `runAt` instead of `cron`:
|
|
54
|
+
|
|
55
|
+
```typescript
|
|
56
|
+
await mastra.schedules.create({
|
|
57
|
+
workflowId: 'send-report',
|
|
58
|
+
runAt: new Date(Date.now() + 60 * 60 * 1000), // One hour from now
|
|
59
|
+
})
|
|
60
|
+
```
|
|
61
|
+
|
|
53
62
|
## Methods
|
|
54
63
|
|
|
55
64
|
### Create schedules
|
|
@@ -72,7 +81,11 @@ const schedule = await mastra.schedules.create({
|
|
|
72
81
|
|
|
73
82
|
**agentId** (`string`): ID of the agent to run on each schedule fire.
|
|
74
83
|
|
|
75
|
-
**cron** (`string`): Cron expression for
|
|
84
|
+
**cron** (`string`): Cron expression for a recurring schedule. Accepts 5-, 6-, or 7-part cron expressions and Croner nicknames. Provide exactly one of cron or runAt.
|
|
85
|
+
|
|
86
|
+
**runAt** (`number | Date`): Fire the schedule once at this time (epoch milliseconds or Date). After it fires, the schedule moves to completed. Must be in the future.
|
|
87
|
+
|
|
88
|
+
**endAt** (`number | Date`): Only with cron. Stop firing after this time; the schedule moves to completed once its next occurrence would fall after endAt. Must be in the future.
|
|
76
89
|
|
|
77
90
|
**prompt** (`string`): Prompt sent to the agent on each schedule fire.
|
|
78
91
|
|
|
@@ -106,7 +119,11 @@ const schedule = await mastra.schedules.create({
|
|
|
106
119
|
|
|
107
120
|
**workflowId** (`string`): ID of the workflow to start on each schedule fire.
|
|
108
121
|
|
|
109
|
-
**cron** (`string`): Cron expression for
|
|
122
|
+
**cron** (`string`): Cron expression for a recurring schedule. Accepts 5-, 6-, or 7-part cron expressions and Croner nicknames. Provide exactly one of cron or runAt.
|
|
123
|
+
|
|
124
|
+
**runAt** (`number | Date`): Fire the schedule once at this time (epoch milliseconds or Date). After it fires, the schedule moves to completed. Must be in the future.
|
|
125
|
+
|
|
126
|
+
**endAt** (`number | Date`): Only with cron. Stop firing after this time; the schedule moves to completed once its next occurrence would fall after endAt. Must be in the future.
|
|
110
127
|
|
|
111
128
|
**timezone** (`string`): IANA timezone used to resolve cron fire times.
|
|
112
129
|
|
|
@@ -176,7 +193,7 @@ Workflow schedule patches can update `cron`, `timezone`, `inputData`, `initialSt
|
|
|
176
193
|
|
|
177
194
|
#### `pause(id)`
|
|
178
195
|
|
|
179
|
-
Pauses a schedule. Pausing is durable and idempotent.
|
|
196
|
+
Pauses a schedule. Pausing is durable and idempotent. Pausing a `completed` schedule throws a `409` error.
|
|
180
197
|
|
|
181
198
|
```typescript
|
|
182
199
|
const paused = await mastra.schedules.pause('pinger')
|
|
@@ -184,7 +201,7 @@ const paused = await mastra.schedules.pause('pinger')
|
|
|
184
201
|
|
|
185
202
|
#### `resume(id)`
|
|
186
203
|
|
|
187
|
-
Resumes a paused schedule and recomputes the next fire time from the current time. A paused schedule whose cron has no future occurrence is completed instead of resumed.
|
|
204
|
+
Resumes a paused schedule and recomputes the next fire time from the current time. One-off schedules keep their `runAt`; if it passed while the schedule was paused, the schedule fires on the next scheduler tick. A paused schedule whose cron has no future occurrence is completed instead of resumed. Resuming a `completed` schedule throws a `409` error; update its timing instead to reactivate it.
|
|
188
205
|
|
|
189
206
|
```typescript
|
|
190
207
|
const active = await mastra.schedules.resume('pinger')
|
|
@@ -214,4 +231,7 @@ await mastra.schedules.delete('pinger')
|
|
|
214
231
|
- Threaded agent schedules require `resourceId` when `threadId` is set.
|
|
215
232
|
- On agent schedules, `signalType`, `ifActive`, `ifIdle`, and `resourceId` require `threadId`. Workflow schedules accept `resourceId` without a thread.
|
|
216
233
|
- Workflow schedules don't accept agent-only patch fields such as `prompt`, `signalType`, or `ifIdle`.
|
|
217
|
-
- `run()` publishes a manual fire immediately and doesn't change the stored cron cadence.
|
|
234
|
+
- `run()` publishes a manual fire immediately and doesn't change the stored cron cadence.
|
|
235
|
+
- Schedules have three statuses: `active`, `paused`, and `completed`. A schedule becomes `completed` when it has no remaining automatic fires: after a one-off fires, when a bounded or exhausted cron has no future occurrence, or when declarative registration finds its timing has already passed. `update()` and `resume()` also mark exhausted cron schedules as completed. `run()` doesn't complete a one-off schedule.
|
|
236
|
+
- Updating `runAt` on a one-off, or `endAt` on a cron schedule (`null` removes the bound), reactivates a `completed` schedule only if the resulting timing can still fire. A cron schedule with no occurrence before its new `endAt` remains completed.
|
|
237
|
+
- `list()` hides `completed` schedules unless you pass `status: 'completed'`.
|
|
@@ -126,7 +126,10 @@ const server = new MastraServer({ app, mastra })
|
|
|
126
126
|
await server.init()
|
|
127
127
|
|
|
128
128
|
app.get('/custom/protected', createAuthMiddleware({ mastra }), (req, res) => {
|
|
129
|
-
const user = res.locals.requestContext
|
|
129
|
+
const user = res.locals.requestContext?.get('mastra__user')
|
|
130
|
+
if (!user) {
|
|
131
|
+
return res.status(401).json({ error: 'Unauthorized' })
|
|
132
|
+
}
|
|
130
133
|
res.json({ user })
|
|
131
134
|
})
|
|
132
135
|
|
|
@@ -135,6 +138,8 @@ app.get('/custom/public', createAuthMiddleware({ mastra, requiresAuth: false }),
|
|
|
135
138
|
})
|
|
136
139
|
```
|
|
137
140
|
|
|
141
|
+
`createAuthMiddleware()` calls the next handler without authenticating when the Mastra server has no `auth` config, or when the route matches a public pattern. Public patterns include the built-in defaults (`/api` and `/api/auth/*`) and any `auth.public` patterns you configure. In those cases `mastra__user` isn't set, so protected handlers should reject requests without it, as the example above does.
|
|
142
|
+
|
|
138
143
|
## Accessing context
|
|
139
144
|
|
|
140
145
|
In Express middleware and routes, access Mastra context via `res.locals`:
|
|
@@ -152,15 +157,16 @@ app.get('/custom', (req, res) => {
|
|
|
152
157
|
|
|
153
158
|
Available properties on `res.locals`:
|
|
154
159
|
|
|
155
|
-
| Key | Description
|
|
156
|
-
| ----------------------- |
|
|
157
|
-
| `mastra` | Mastra instance
|
|
158
|
-
| `requestContext` | Request context map
|
|
159
|
-
| `abortSignal` | Request cancellation signal
|
|
160
|
-
| `registeredTools` | Tools registered with the adapter
|
|
161
|
-
| `taskStore` | Task store for A2A operations
|
|
162
|
-
| `customRouteAuthConfig` | Per-route auth overrides
|
|
163
|
-
|
|
160
|
+
| Key | Description |
|
|
161
|
+
| ----------------------- | --------------------------------- |
|
|
162
|
+
| `mastra` | Mastra instance |
|
|
163
|
+
| `requestContext` | Request context map |
|
|
164
|
+
| `abortSignal` | Request cancellation signal |
|
|
165
|
+
| `registeredTools` | Tools registered with the adapter |
|
|
166
|
+
| `taskStore` | Task store for A2A operations |
|
|
167
|
+
| `customRouteAuthConfig` | Per-route auth overrides |
|
|
168
|
+
|
|
169
|
+
When auth is configured, read the authenticated user with `res.locals.requestContext.get('mastra__user')`. Clients can't set the reserved `mastra__user` key through the `requestContext` query parameter or body. On raw Express routes, the value is only populated after [`createAuthMiddleware()`](#adding-custom-routes) runs, so apply it before trusting the user. Don't rely on the legacy `user` key for authorization. A client can supply it on routes without auth middleware.
|
|
164
170
|
|
|
165
171
|
## Adding middleware
|
|
166
172
|
|
|
@@ -172,7 +172,7 @@ const stream = await agent.stream('message for agent')
|
|
|
172
172
|
|
|
173
173
|
**options.clientTools** (`ToolsInput`): Tools that are executed on the 'client' side of the request. These tools do not have execute functions in the definition.
|
|
174
174
|
|
|
175
|
-
**options.hooks** (`ToolHooks`): Per-execution hooks that run before and after tool calls.
|
|
175
|
+
**options.hooks** (`ToolHooks`): Per-execution hooks that run before and after tool calls, for example to log or save audit records. afterToolCall: (context) => void | Promise\<void> receives toolName, input, and output or error. beforeToolCall can return { proceed: false, output } to skip the tool call. Overrides matching agent-level hooks for this execution. See Run logic around tool calls.
|
|
176
176
|
|
|
177
177
|
**options.savePerStep** (`boolean`): Save messages incrementally after each stream step completes (default: false).
|
|
178
178
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mastra/mcp-docs-server",
|
|
3
|
-
"version": "1.3.13-alpha.
|
|
3
|
+
"version": "1.3.13-alpha.12",
|
|
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/
|
|
30
|
-
"@mastra/
|
|
29
|
+
"@mastra/mcp": "^2.9.0-alpha.3",
|
|
30
|
+
"@mastra/core": "1.83.0-alpha.9"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@hono/node-server": "^2.1.3",
|