@mastra/mcp-docs-server 1.3.13-alpha.11 → 1.3.13-alpha.14
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/connections/mcp.md +2 -0
- package/.docs/docs/evals/overview.md +4 -0
- package/.docs/docs/harness/schedules.md +1 -1
- package/.docs/docs/sandbox/overview.md +2 -0
- package/.docs/docs/sandbox/search.md +25 -0
- package/.docs/docs/workflows/scheduled-workflows.md +26 -5
- 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/connect/tools.md +59 -0
- package/.docs/reference/editor/mastra-editor.md +1 -1
- package/.docs/reference/observability/feedback.md +14 -0
- 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/otel.md +1 -1
- package/.docs/reference/observability/tracing/interfaces.md +2 -2
- 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
|
|
@@ -200,6 +200,8 @@ export async function handleRequest(prompt: string, apiKey: string) {
|
|
|
200
200
|
|
|
201
201
|
Visit [`listTools()`](https://mastra.ai/reference/tools/mcp-client) and [`listToolsets()`](https://mastra.ai/reference/tools/mcp-client) for their full APIs.
|
|
202
202
|
|
|
203
|
+
This example finishes within one request. When agent work must continue after the request ends or survive a process restart, use [durable agents](https://mastra.ai/docs/harness/durable-agents) or [background tasks](https://mastra.ai/docs/harness/background-tasks) instead of building your own task tracking. Call-time `toolsets` can't move to another process, so with a durable agent, load per-request MCP tools in the agent's `tools` function from [request context](https://mastra.ai/docs/server/request-context).
|
|
204
|
+
|
|
203
205
|
### Tool approval
|
|
204
206
|
|
|
205
207
|
Set `requireToolApproval` on a server to require approval for all its tools:
|
|
@@ -10,6 +10,8 @@ Scorers are automated tests that evaluate Agents outputs using model-graded, rul
|
|
|
10
10
|
|
|
11
11
|
Scorers can run in the cloud to capture real-time results. Scorers can also be part of your CI/CD pipeline for testing and monitoring agents over time.
|
|
12
12
|
|
|
13
|
+
Scorers measure a single output. To improve an agent over time, combine them with [datasets](https://mastra.ai/docs/evals/datasets), which store versioned test cases, and [experiments](https://mastra.ai/docs/evals/experiments), which run an agent or workflow against a dataset, optionally score each result, and keep the results for comparison. [Build an eval loop](https://mastra.ai/docs/guides/build-an-eval-loop) walks through using them together.
|
|
14
|
+
|
|
13
15
|
> **📹 Watch:** Watch [Mastra evals overview](https://www.youtube.com/watch?v=12WN6u2DrBk) for an introduction to evals and how to reason about agent quality.
|
|
14
16
|
|
|
15
17
|
## Types of scorers
|
|
@@ -220,6 +222,8 @@ Once registered, you can score traces interactively within Studio under the **Ob
|
|
|
220
222
|
|
|
221
223
|
## Next steps
|
|
222
224
|
|
|
225
|
+
- Follow [Build an eval loop](https://mastra.ai/docs/guides/build-an-eval-loop) to compare agent changes with datasets, scorers, and experiments
|
|
226
|
+
- Store test cases in [datasets](https://mastra.ai/docs/evals/datasets) and run them with [experiments](https://mastra.ai/docs/evals/experiments)
|
|
223
227
|
- Use [Quick Checks](https://mastra.ai/docs/evals/quick-checks) for fast, deterministic assertions on text and tool usage
|
|
224
228
|
- Add [gates and verdicts](https://mastra.ai/docs/evals/gates-and-verdicts) to enforce hard requirements and quality thresholds
|
|
225
229
|
- Test [multi-turn conversations](https://mastra.ai/docs/evals/multi-turn) where behavior emerges across sequential turns
|
|
@@ -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
|
|
|
@@ -112,6 +112,8 @@ export const startServerTool = createTool({
|
|
|
112
112
|
|
|
113
113
|
[`LocalSandbox`](https://mastra.ai/reference/workspace/local-sandbox) executes commands on the same machine as your Mastra application. By default, commands run directly on the host with the permissions of the application process.
|
|
114
114
|
|
|
115
|
+
`workingDirectory` only sets where commands run. Mastra doesn't copy your project into it. To give an agent its own checkout, run `git clone` or `git worktree add` into a directory outside the source repository.
|
|
116
|
+
|
|
115
117
|
```typescript
|
|
116
118
|
const sandbox = new LocalSandbox({
|
|
117
119
|
workingDirectory: './workspace',
|
|
@@ -215,6 +215,31 @@ await workspace.index('/docs/api.md', apiDocContent, {
|
|
|
215
215
|
|
|
216
216
|
Manual indexing works well for database records and API responses, or when you need to preprocess, chunk, or annotate content yourself.
|
|
217
217
|
|
|
218
|
+
### Index application content
|
|
219
|
+
|
|
220
|
+
A workspace needs a `filesystem`, `sandbox`, or `skills` provider even when your application reads content and passes it to `workspace.index()`. Without one, the `Workspace` constructor throws `Workspace requires at least a filesystem, sandbox, or skills`.
|
|
221
|
+
|
|
222
|
+
Configuring a filesystem doesn't mean the agent should use it. By default, an agent with this workspace also gets file tools such as `mastra_workspace_read_file` and `mastra_workspace_write_file`. To expose only search, disable all workspace tools and re-enable the search tool:
|
|
223
|
+
|
|
224
|
+
```typescript
|
|
225
|
+
import { LocalFilesystem, Workspace, WORKSPACE_TOOLS } from '@mastra/core/workspace'
|
|
226
|
+
|
|
227
|
+
const workspace = new Workspace({
|
|
228
|
+
filesystem: new LocalFilesystem({ basePath: './workspace' }),
|
|
229
|
+
bm25: true,
|
|
230
|
+
tools: {
|
|
231
|
+
enabled: false,
|
|
232
|
+
[WORKSPACE_TOOLS.SEARCH.SEARCH]: { enabled: true },
|
|
233
|
+
},
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
for (const document of documents) {
|
|
237
|
+
await workspace.index(document.id, document.content)
|
|
238
|
+
}
|
|
239
|
+
```
|
|
240
|
+
|
|
241
|
+
Your application keeps calling `workspace.index()` directly. The tool settings only control what the agent can call.
|
|
242
|
+
|
|
218
243
|
### Keep files and the index in sync
|
|
219
244
|
|
|
220
245
|
Filesystem and index mutations are independent. Writing, editing, or deleting a file doesn't update its indexed content, and `workspace.index()` doesn't read or change a file.
|
|
@@ -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
|
|
|
@@ -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`
|
|
@@ -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
|
|
|
@@ -441,6 +441,20 @@ await mastra.observability.replaceFeedback?.({
|
|
|
441
441
|
|
|
442
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
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
|
+
|
|
444
458
|
## HTTP routes
|
|
445
459
|
|
|
446
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.
|
|
@@ -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`
|
|
@@ -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 */
|
|
@@ -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.14",
|
|
4
4
|
"description": "MCP server for accessing Mastra.ai documentation, changelogs, and news.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "dist/index.js",
|
|
@@ -26,8 +26,8 @@
|
|
|
26
26
|
"@mastra/mcp-legacy": "npm:@mastra/mcp@^1.18.0",
|
|
27
27
|
"local-pkg": "^1.2.1",
|
|
28
28
|
"zod": "^4.6.7",
|
|
29
|
-
"@mastra/core": "1.83.0-alpha.
|
|
30
|
-
"@mastra/mcp": "^2.9.0-alpha.
|
|
29
|
+
"@mastra/core": "1.83.0-alpha.10",
|
|
30
|
+
"@mastra/mcp": "^2.9.0-alpha.4"
|
|
31
31
|
},
|
|
32
32
|
"devDependencies": {
|
|
33
33
|
"@hono/node-server": "^2.1.3",
|