@mastra/mcp-docs-server 1.3.13-alpha.8 → 1.3.13
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/auth/custom-auth-provider.md +66 -0
- package/.docs/docs/auth/jwt.md +1 -1
- package/.docs/docs/connections/mcp.md +11 -71
- package/.docs/docs/evals/overview.md +4 -0
- package/.docs/docs/harness/durable-agents.md +36 -0
- package/.docs/docs/harness/schedules.md +1 -1
- package/.docs/docs/memory/multi-user-threads.md +57 -127
- package/.docs/docs/memory/observational-memory.md +196 -756
- package/.docs/docs/memory/overview.md +4 -0
- package/.docs/docs/memory/semantic-recall.md +2 -0
- package/.docs/docs/observability/feedback.md +5 -7
- package/.docs/docs/sandbox/overview.md +2 -0
- package/.docs/docs/sandbox/search.md +25 -0
- package/.docs/docs/server/mcp.md +315 -0
- package/.docs/docs/server/request-context.md +35 -0
- package/.docs/docs/studio/deployment.md +0 -1
- package/.docs/docs/studio/overview.md +4 -4
- package/.docs/docs/workflows/scheduled-workflows.md +26 -5
- package/.docs/integrations/deploy/temporal.md +74 -0
- package/.docs/integrations/sandboxes/docker.md +39 -0
- package/.docs/integrations/sandboxes/e2b.md +1 -1
- package/.docs/integrations/voice/openai.md +2 -2
- package/.docs/models/environment-variables.md +1 -1
- package/.docs/models/gateways/azure-openai.md +61 -2
- package/.docs/models/gateways/custom-gateways.md +74 -44
- package/.docs/models/gateways/requesty.md +221 -0
- package/.docs/models/gateways.md +7 -1
- package/.docs/models/index.md +0 -1
- package/.docs/models/providers/aihubmix.md +2 -0
- package/.docs/models/providers/amazon-bedrock.md +4 -0
- package/.docs/models/providers/azure.md +4 -0
- package/.docs/models/providers/cloudflare-ai-gateway.md +2 -0
- package/.docs/models/providers/cohere.md +2 -0
- package/.docs/models/providers/google-vertex.md +2 -0
- package/.docs/models/providers/ollama.md +2 -0
- package/.docs/models/providers/qvac.md +2 -0
- package/.docs/models/providers.md +0 -1
- package/.docs/reference/agents/generate.md +1 -1
- package/.docs/reference/agents/generateLegacy.md +7 -23
- package/.docs/reference/auth/jwt.md +26 -2
- package/.docs/reference/cli/mastra.md +74 -6
- package/.docs/reference/client-js/observability.md +13 -5
- package/.docs/reference/configuration.md +64 -0
- package/.docs/reference/connect/tools.md +59 -0
- package/.docs/reference/editor/mastra-editor.md +1 -1
- package/.docs/reference/index.md +1 -0
- package/.docs/reference/memory/observational-memory.md +350 -151
- package/.docs/reference/observability/feedback.md +57 -14
- package/.docs/reference/observability/tracing/advanced-queries.md +3 -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/observability/tracing/spans.md +7 -1
- package/.docs/reference/processors/processor-interface.md +23 -0
- package/.docs/reference/processors/semantic-recall-processor.md +2 -0
- package/.docs/reference/rag/chunk.md +1 -1
- package/.docs/reference/rag/graph-rag-guide.md +3 -1
- package/.docs/reference/rag/graph-rag.md +1 -1
- package/.docs/reference/rag/rerank.md +1 -1
- package/.docs/reference/rag/rerankWithScorer.md +1 -1
- package/.docs/reference/schedules/overview.md +25 -5
- package/.docs/reference/server/dispatch-route.md +124 -0
- package/.docs/reference/server/elysia-adapter.md +1 -1
- package/.docs/reference/server/express-adapter.md +17 -11
- package/.docs/reference/server/fastify-adapter.md +1 -1
- package/.docs/reference/server/hono-adapter.md +1 -1
- package/.docs/reference/server/invoke-route.md +10 -0
- package/.docs/reference/server/koa-adapter.md +1 -1
- package/.docs/reference/server/nestjs-adapter.md +1 -1
- package/.docs/reference/streaming/agents/stream.md +1 -1
- package/.docs/reference/tools/mcp-client.md +11 -1
- package/.docs/reference/workspace/factory-sandbox.md +20 -1
- package/.docs/reference/workspace/platform-sandbox.md +1 -1
- package/package.json +5 -5
- package/.docs/models/providers/requesty.md +0 -261
|
@@ -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
|
|
@@ -138,6 +138,72 @@ async authorizeUser(user: TUser, request: MastraAuthRequest): Promise<boolean> |
|
|
|
138
138
|
|
|
139
139
|
**Returns**: `true` to allow access, `false` to deny (returns 403 Forbidden).
|
|
140
140
|
|
|
141
|
+
## Optional methods
|
|
142
|
+
|
|
143
|
+
### `toMastraUser()`
|
|
144
|
+
|
|
145
|
+
Normalize your provider-specific user object to the stable `MastraUser` shape that dynamic configuration callbacks (such as dynamic `instructions`, `model`, or `tools`) receive as the optional `user` argument.
|
|
146
|
+
|
|
147
|
+
```typescript
|
|
148
|
+
toMastraUser(user: TUser): MastraUser
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
| Parameter | Type | Description |
|
|
152
|
+
| --------- | ------- | ----------------------------------------------- |
|
|
153
|
+
| `user` | `TUser` | The user object returned by `authenticateToken` |
|
|
154
|
+
|
|
155
|
+
**Returns**: A `MastraUser` object: `{ id: string, name?: string, email?: string, avatarUrl?: string, role?: string }`.
|
|
156
|
+
|
|
157
|
+
The default implementation picks `id` from `id`, `sub`, or `userId`, `avatarUrl` from `avatarUrl` or `picture`, and passes `name`, `email`, and `role` through when present. Override it when your user type stores these fields elsewhere:
|
|
158
|
+
|
|
159
|
+
```typescript
|
|
160
|
+
import type { MastraUser } from '@mastra/core/auth'
|
|
161
|
+
|
|
162
|
+
export class MyAuthProvider extends MastraAuthProvider<MyUser> {
|
|
163
|
+
async authenticateToken(token: string) {
|
|
164
|
+
/* ... */
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
toMastraUser(user: MyUser): MastraUser {
|
|
168
|
+
return {
|
|
169
|
+
id: user.accountId,
|
|
170
|
+
name: user.profile.displayName,
|
|
171
|
+
role: user.permissions.primaryRole,
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
If no `id` can be derived from the user object, the normalized user is omitted and callbacks receive `user: undefined`. The raw user object remains available on the request context.
|
|
178
|
+
|
|
179
|
+
## Optional methods for MCP OAuth
|
|
180
|
+
|
|
181
|
+
The [built-in MCP server](https://mastra.ai/docs/server/mcp) uses two optional methods for OAuth discovery and audience checks.
|
|
182
|
+
|
|
183
|
+
`getOAuthMetadata()` returns the authorization servers, and optionally scopes, that MCP clients should use. `server.mcp.oauth.authorizationServers` and `server.mcp.oauth.scopesSupported` take precedence.
|
|
184
|
+
|
|
185
|
+
```typescript
|
|
186
|
+
getOAuthMetadata(): { authorizationServers?: string[]; scopesSupported?: string[] } | undefined
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
`verifyAudience()` runs on `/api/mcp` when `server.mcp.oauth.resource` is set. It receives the value `authenticateToken()` returned and the `resource` URL, and returns whether the token was issued for it. Returning `false` rejects the request with a `401`. Without this method the audience isn't checked, and Mastra logs a warning.
|
|
190
|
+
|
|
191
|
+
```typescript
|
|
192
|
+
verifyAudience(user: TUser, audience: string): boolean | Promise<boolean>
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
For a JWT provider whose `authenticateToken()` returns the verified payload:
|
|
196
|
+
|
|
197
|
+
```typescript
|
|
198
|
+
getOAuthMetadata() {
|
|
199
|
+
return { authorizationServers: ['https://auth.example.com/'] }
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
verifyAudience(user: JwtPayload, audience: string) {
|
|
203
|
+
return Array.isArray(user.aud) ? user.aud.includes(audience) : user.aud === audience
|
|
204
|
+
}
|
|
205
|
+
```
|
|
206
|
+
|
|
141
207
|
## Configuration options
|
|
142
208
|
|
|
143
209
|
The `MastraAuthProviderOptions` interface supports these options:
|
package/.docs/docs/auth/jwt.md
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
# JSON Web Token
|
|
6
6
|
|
|
7
|
-
The `MastraJwtAuth` class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests based on a shared secret and integrates with the Mastra server using the `auth` option.
|
|
7
|
+
The `MastraJwtAuth` class provides a lightweight authentication mechanism for Mastra using JSON Web Tokens (JWTs). It verifies incoming requests based on a shared secret and integrates with the Mastra server using the `auth` option. To verify tokens signed by an identity provider, use the `jwksUri` and `issuer` options described in the [reference](https://mastra.ai/reference/auth/jwt).
|
|
8
8
|
|
|
9
9
|
## Installation
|
|
10
10
|
|
|
@@ -162,12 +162,13 @@ See [type generation reference](https://mastra.ai/reference/tools/mcp-client) fo
|
|
|
162
162
|
|
|
163
163
|
Choose how to load tools based on whether the server configuration changes between requests:
|
|
164
164
|
|
|
165
|
-
| | Static tools
|
|
166
|
-
| ----------- |
|
|
167
|
-
| Method | `await mcpClient.listTools()`
|
|
168
|
-
| Use case | Shared, fixed configuration
|
|
169
|
-
| Credentials | Shared by all requests
|
|
170
|
-
| Agent API | `tools` in the `Agent` constructor
|
|
165
|
+
| | Static tools | Runtime toolsets |
|
|
166
|
+
| ----------- | ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
|
|
167
|
+
| Method | `await mcpClient.listTools()` | `await mcpClient.listToolsets()` |
|
|
168
|
+
| Use case | Shared, fixed configuration | Per-user or per-request configuration |
|
|
169
|
+
| Credentials | Shared by all requests | Can vary between requests |
|
|
170
|
+
| Agent API | `tools` in the `Agent` constructor | `toolsets` in `generate()` or `stream()` |
|
|
171
|
+
| Tool names | Prefixed with the server name, such as `weather_get_weather` | Raw tool names. Same-named tools from different servers collide. See [`listToolsets()`](https://mastra.ai/reference/tools/mcp-client). |
|
|
171
172
|
|
|
172
173
|
The preceding agent example uses static tools. For runtime credentials, create a client for the request and pass its toolsets when calling the agent:
|
|
173
174
|
|
|
@@ -199,6 +200,8 @@ export async function handleRequest(prompt: string, apiKey: string) {
|
|
|
199
200
|
|
|
200
201
|
Visit [`listTools()`](https://mastra.ai/reference/tools/mcp-client) and [`listToolsets()`](https://mastra.ai/reference/tools/mcp-client) for their full APIs.
|
|
201
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
|
+
|
|
202
205
|
### Tool approval
|
|
203
206
|
|
|
204
207
|
Set `requireToolApproval` on a server to require approval for all its tools:
|
|
@@ -286,6 +289,8 @@ A tool that needs something from the user before it can finish calls `context.su
|
|
|
286
289
|
|
|
287
290
|
Visit the [`MCPServer` reference](https://mastra.ai/reference/tools/mcp-server) for prompts, resources, transports, and other server options.
|
|
288
291
|
|
|
292
|
+
To expose every agent, workflow, and tool on your Mastra app without defining a server, use the [built-in MCP server](https://mastra.ai/docs/server/mcp) at `/api/mcp`.
|
|
293
|
+
|
|
289
294
|
### Publish a stdio server package
|
|
290
295
|
|
|
291
296
|
Package a server that uses the standard input/output (stdio) transport when you want clients to run it locally through a command such as `npx`. Create a separate executable entry point that starts the server:
|
|
@@ -443,71 +448,6 @@ export const mastra = new Mastra({
|
|
|
443
448
|
|
|
444
449
|
Tools loaded through `listTools()` include a `serverId` in `_meta.ui`, allowing Studio to resolve each app resource without scanning every server. Visit [`toMCPServerProxies()`](https://mastra.ai/reference/tools/mcp-client) for proxy configuration details.
|
|
445
450
|
|
|
446
|
-
### Use prebuilt Mastra apps
|
|
447
|
-
|
|
448
|
-
The `@mastra/mcp-apps-components` package includes prebuilt MCP Apps. Each one is a self-contained HTML page that you register as an app resource, next to the tools it talks to.
|
|
449
|
-
|
|
450
|
-
**npm**:
|
|
451
|
-
|
|
452
|
-
```bash
|
|
453
|
-
npm install @mastra/mcp-apps-components
|
|
454
|
-
```
|
|
455
|
-
|
|
456
|
-
**pnpm**:
|
|
457
|
-
|
|
458
|
-
```bash
|
|
459
|
-
pnpm add @mastra/mcp-apps-components
|
|
460
|
-
```
|
|
461
|
-
|
|
462
|
-
**Yarn**:
|
|
463
|
-
|
|
464
|
-
```bash
|
|
465
|
-
yarn add @mastra/mcp-apps-components
|
|
466
|
-
```
|
|
467
|
-
|
|
468
|
-
**Bun**:
|
|
469
|
-
|
|
470
|
-
```bash
|
|
471
|
-
bun add @mastra/mcp-apps-components
|
|
472
|
-
```
|
|
473
|
-
|
|
474
|
-
`greetingApp` greets someone by name. The host sends it the arguments of the tool that opened it, and the app reads `name`. It then calls the `getGreeting` tool on the same server for its data and shows the `greeting` from the result. Mark `getGreeting` as app-only with `visibility: ['app']`, so the model doesn't see it:
|
|
475
|
-
|
|
476
|
-
```typescript
|
|
477
|
-
import { createTool } from '@mastra/core/tools'
|
|
478
|
-
import { MCPServer } from '@mastra/mcp'
|
|
479
|
-
import { greetingApp } from '@mastra/mcp-apps-components'
|
|
480
|
-
import { z } from 'zod'
|
|
481
|
-
|
|
482
|
-
const uri = 'ui://mastra/greeting'
|
|
483
|
-
|
|
484
|
-
export const greetingServer = new MCPServer({
|
|
485
|
-
id: 'greeting-server',
|
|
486
|
-
name: 'Greeting Server',
|
|
487
|
-
version: '1.0.0',
|
|
488
|
-
appResources: { [uri]: greetingApp },
|
|
489
|
-
tools: {
|
|
490
|
-
showGreeting: createTool({
|
|
491
|
-
id: 'showGreeting',
|
|
492
|
-
description: 'Shows a greeting card for someone',
|
|
493
|
-
inputSchema: z.object({ name: z.string() }),
|
|
494
|
-
mcp: { _meta: { ui: { resourceUri: uri } } },
|
|
495
|
-
execute: async ({ name }) => ({ name }),
|
|
496
|
-
}),
|
|
497
|
-
getGreeting: createTool({
|
|
498
|
-
id: 'getGreeting',
|
|
499
|
-
description: 'Returns the greeting for a name',
|
|
500
|
-
inputSchema: z.object({ name: z.string() }),
|
|
501
|
-
outputSchema: z.object({ greeting: z.string() }),
|
|
502
|
-
mcp: { _meta: { ui: { resourceUri: uri, visibility: ['app'] } } },
|
|
503
|
-
execute: async ({ name }) => ({ greeting: `Hello, ${name}!` }),
|
|
504
|
-
}),
|
|
505
|
-
},
|
|
506
|
-
})
|
|
507
|
-
```
|
|
508
|
-
|
|
509
|
-
`getGreeting` runs on your server, so it can call any API with your server's credentials. The app's iframe has no network access of its own.
|
|
510
|
-
|
|
511
451
|
### Sandbox security
|
|
512
452
|
|
|
513
453
|
Mastra Studio uses [`@mcp-ui/client`](https://www.npmjs.com/package/@mcp-ui/client) to load app HTML through a sandbox proxy and communicate over JSON-RPC with `postMessage`.
|
|
@@ -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
|
|
@@ -413,6 +413,42 @@ Recovery can start the same tool call before the previous execution detects owne
|
|
|
413
413
|
|
|
414
414
|
Every replica can start with `recovery.durableAgents: 'auto'`. Replicas that boot together race to recover the same orphaned runs, but only one claim succeeds per run and the other replicas skip it. This requires a claim that every replica shares: a workflows store that supports run fencing, or a PubSub backend whose lease every replica shares. Without either, gate recovery behind your own leader election or run it from a single replica.
|
|
415
415
|
|
|
416
|
+
## Database load
|
|
417
|
+
|
|
418
|
+
Mastra doesn't publish a benchmarked hardware reference for durable agents, so size your database from your own workload. This section covers what drives the load and what to watch.
|
|
419
|
+
|
|
420
|
+
Each checkpoint upserts the run's full snapshot as JSONB in `mastra_workflow_snapshot`, with one row for the agent workflow and one for its nested execution workflow. The snapshot holds the conversation and every tool result so far, so it grows during a run, and the total bytes a run writes grow faster than its step count. Write load depends on:
|
|
421
|
+
|
|
422
|
+
- **Checkpoint frequency**: A `createDurableAgent()` agent with `recovery.durableAgents` set to `'off'` (the default) writes few checkpoints. With `'auto'`, it writes a `running` checkpoint at every step. A `createEventedAgent()` agent always writes at every step. See [snapshot persistence](#snapshot-persistence).
|
|
423
|
+
- **Steps per run and payload size**: Every byte a tool returns is written again in each later checkpoint of the run.
|
|
424
|
+
- **Concurrent runs**: Load grows with the number of runs in progress.
|
|
425
|
+
|
|
426
|
+
To reduce writes and keep crash recovery:
|
|
427
|
+
|
|
428
|
+
- Give the agent a fixed memory instance, so checkpoints store references to saved messages instead of full copies.
|
|
429
|
+
- Return small tool results, such as IDs or URLs, instead of large documents.
|
|
430
|
+
- Split long tasks into shorter runs.
|
|
431
|
+
|
|
432
|
+
Each `PostgresStore` opens up to `max` connections, 20 by default, per process. A `pool`, `writePool`, or separate `readPool` you pass in uses its own limit. Add up the limits of every pool that connects to the server, across all replicas and processes, and keep the total below the server's `max_connections` with room for other clients. If you put a transaction-mode pooler such as PgBouncer in front, budget its server-side connections the same way. See [PostgreSQL](https://mastra.ai/integrations/databases/postgresql).
|
|
433
|
+
|
|
434
|
+
Every checkpoint upsert leaves a dead row version, and Mastra deletes a finished run's rows, so `mastra_workflow_snapshot` collects dead rows fast. Suspended runs keep their rows. If deletion fails, Mastra logs a `Failed to delete workflow snapshot rows` warning and the rows stay until you delete or [prune](https://mastra.ai/reference/storage/retention) them. The exception is a `createEventedAgent()` agent on a shared pub/sub transport with storage-backed fencing: it logs `durable execution delivery failed` and retries the delete with the event. Pruning removes snapshots by inactivity, including suspended runs and running runs whose step hasn't written a checkpoint recently. Set `workflowSnapshot.maxAge` longer than your longest expected suspension and your longest step, or leave snapshot pruning off if you can't bound them. Make autovacuum more aggressive for this table. Replace `public` with your `schemaName` if you set one:
|
|
435
|
+
|
|
436
|
+
```sql
|
|
437
|
+
ALTER TABLE public.mastra_workflow_snapshot SET (
|
|
438
|
+
autovacuum_vacuum_scale_factor = 0.01,
|
|
439
|
+
toast.autovacuum_vacuum_scale_factor = 0.01
|
|
440
|
+
);
|
|
441
|
+
```
|
|
442
|
+
|
|
443
|
+
To decide whether to add capacity or tune the workload, watch:
|
|
444
|
+
|
|
445
|
+
- `n_dead_tup` and `last_autovacuum` for `mastra_workflow_snapshot` in `pg_stat_user_tables`, and for its TOAST table in `pg_stat_all_tables`, where large snapshots are stored
|
|
446
|
+
- The snapshot upsert's share of `total_exec_time` and `wal_bytes` in `pg_stat_statements`. This requires `pg_stat_statements` in `shared_preload_libraries` (a server restart) and `CREATE EXTENSION pg_stat_statements`
|
|
447
|
+
- WAL bytes per second (`pg_stat_wal`)
|
|
448
|
+
- Active connections compared with the pool `max`
|
|
449
|
+
|
|
450
|
+
If the snapshot upsert dominates writes, reduce checkpoint size or frequency first. If many unrelated queries are slow, add capacity.
|
|
451
|
+
|
|
416
452
|
## Make tools safe to repeat
|
|
417
453
|
|
|
418
454
|
A durable or evented agent can run the same tool call more than once. A tool call is one request from the model to run a tool. A repeat happens in these situations:
|
|
@@ -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
|
|
|
@@ -4,60 +4,50 @@
|
|
|
4
4
|
|
|
5
5
|
# Multi-user threads
|
|
6
6
|
|
|
7
|
-
A single Mastra thread can be shared by
|
|
7
|
+
A single Mastra thread can be shared by several users. Send each user's message with [`sendMessage()`](https://mastra.ai/docs/signals/sending-signals) and put the speaker in the message's `attributes`. Mastra renders the message as a `<user>` tag carrying those attributes, so the agent can tell the participants apart, now and when the message is loaded from history later.
|
|
8
8
|
|
|
9
9
|
## When to use multi-user threads
|
|
10
10
|
|
|
11
|
-
Use multi-user threads when several people
|
|
11
|
+
Use multi-user threads when several people work on the same subject through one agent:
|
|
12
12
|
|
|
13
|
-
- Collaborative documents with editors, reviewers
|
|
13
|
+
- Collaborative documents with editors, reviewers and approvers
|
|
14
14
|
- Group chats where one assistant serves many participants
|
|
15
|
-
-
|
|
15
|
+
- Reviews where different roles have different authority
|
|
16
16
|
|
|
17
17
|
## Share one `resourceId` across all participants
|
|
18
18
|
|
|
19
|
-
A thread belongs to exactly one `resourceId`, so
|
|
19
|
+
A thread belongs to exactly one `resourceId`, so everyone on a shared thread needs to pass the same value. Instead of a user ID (the default for single-user apps), key `resourceId` on the conversation itself, for example `doc_${docId}` for a shared document or `room_${roomId}` for a group chat. With everyone pointing at the same `resourceId` and `threadId`, they read and write the same history.
|
|
20
20
|
|
|
21
|
-
##
|
|
21
|
+
## Send each message with the speaker's identity
|
|
22
22
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
Build the tag with a small helper. The example below is one way to do it, copy it into your project and adapt it to your shape of user data:
|
|
23
|
+
Pass the message as an object with `contents` and `attributes`. Each attribute becomes an XML attribute on the `<user>` tag the model reads:
|
|
26
24
|
|
|
27
25
|
```typescript
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
}
|
|
26
|
+
agent.sendMessage(
|
|
27
|
+
{
|
|
28
|
+
contents: 'Please make the cover page teal.',
|
|
29
|
+
attributes: { name: 'Alice', role: 'editor' },
|
|
30
|
+
},
|
|
31
|
+
{ resourceId: 'doc_42', threadId: 'doc_42' },
|
|
32
|
+
)
|
|
33
|
+
```
|
|
33
34
|
|
|
34
|
-
|
|
35
|
-
return value
|
|
36
|
-
.replace(/&/g, '&')
|
|
37
|
-
.replace(/"/g, '"')
|
|
38
|
-
.replace(/</g, '<')
|
|
39
|
-
.replace(/>/g, '>')
|
|
40
|
-
}
|
|
35
|
+
The model receives:
|
|
41
36
|
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
const name = escapeAttr(speaker.name)
|
|
45
|
-
const role = escapeAttr(speaker.role)
|
|
46
|
-
return {
|
|
47
|
-
role: 'user' as const,
|
|
48
|
-
content: `<turn author_id="${id}" author_name="${name}" functional_role="${role}">
|
|
49
|
-
${text}
|
|
50
|
-
</turn>`,
|
|
51
|
-
}
|
|
52
|
-
}
|
|
37
|
+
```xml
|
|
38
|
+
<user name="Alice" role="editor">Please make the cover page teal.</user>
|
|
53
39
|
```
|
|
54
40
|
|
|
55
|
-
|
|
41
|
+
Mastra escapes attribute values for you. Attribute names must be valid XML names, such as `name`, `role` or `user_id`. Any other name fails with `Invalid signal XML attribute name` when the message is rendered for the model. The attributes are stored with the message, so when history loads on a later turn, the model still sees who said what.
|
|
42
|
+
|
|
43
|
+
## Tell the agent how to read the tag
|
|
44
|
+
|
|
45
|
+
Describe the `<user>` tag and its attributes in the agent's instructions. The agent needs `memory` so its messages are stored on the thread:
|
|
56
46
|
|
|
57
47
|
```typescript
|
|
58
48
|
import { Agent } from '@mastra/core/agent'
|
|
59
|
-
import { Memory } from '@mastra/memory'
|
|
60
49
|
import { LibSQLStore } from '@mastra/libsql'
|
|
50
|
+
import { Memory } from '@mastra/memory'
|
|
61
51
|
|
|
62
52
|
const memory = new Memory({
|
|
63
53
|
storage: new LibSQLStore({ id: 'collab-storage', url: 'file:./collab.db' }),
|
|
@@ -72,139 +62,79 @@ export const collabAgent = new Agent({
|
|
|
72
62
|
model: 'openai/gpt-6-luna',
|
|
73
63
|
memory,
|
|
74
64
|
instructions: `
|
|
75
|
-
You are a collaborative document assistant.
|
|
65
|
+
You are a collaborative document assistant. Several people talk to you in the same thread.
|
|
76
66
|
|
|
77
|
-
|
|
67
|
+
Each user message arrives in a <user> tag whose attributes say who sent it:
|
|
78
68
|
|
|
79
|
-
<
|
|
80
|
-
...message text...
|
|
81
|
-
</turn>
|
|
69
|
+
<user name="Alice" role="editor">...message text...</user>
|
|
82
70
|
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
2. Respect functional_role: editors propose changes, reviewers approve.
|
|
86
|
-
3. When attributing past statements, read author_name from the surrounding <turn> tag.
|
|
87
|
-
4. Do not echo the <turn> tags back at users.
|
|
71
|
+
Address people by name. Editors propose changes and reviewers approve them.
|
|
72
|
+
When you refer to something said earlier, name the person who said it.
|
|
88
73
|
`.trim(),
|
|
89
74
|
})
|
|
90
75
|
```
|
|
91
76
|
|
|
92
|
-
|
|
77
|
+
Send every participant's message to the same thread. When the thread is idle, `sendMessage()` starts a run and `accepted` resolves with its output:
|
|
93
78
|
|
|
94
79
|
```typescript
|
|
95
|
-
import {
|
|
80
|
+
import { collabAgent } from './agents/collab'
|
|
96
81
|
|
|
97
|
-
const
|
|
98
|
-
const docThreadId = 'doc_42'
|
|
82
|
+
const doc = { resourceId: 'doc_42', threadId: 'doc_42' }
|
|
99
83
|
|
|
100
|
-
|
|
101
|
-
const
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
}
|
|
84
|
+
async function send(speaker: { name: string; role: string }, text: string) {
|
|
85
|
+
const { accepted } = collabAgent.sendMessage({ contents: text, attributes: speaker }, doc)
|
|
86
|
+
const result = await accepted
|
|
87
|
+
if (result.action === 'wake') {
|
|
88
|
+
return (await result.output.getFullOutput()).text
|
|
89
|
+
}
|
|
90
|
+
}
|
|
106
91
|
|
|
107
|
-
await
|
|
108
|
-
|
|
109
|
-
})
|
|
92
|
+
await send({ name: 'Alice', role: 'editor' }, 'Please make the cover page teal.')
|
|
93
|
+
await send({ name: 'Bob', role: 'reviewer' }, 'I want QA sign-off before we publish.')
|
|
94
|
+
await send({ name: 'Alice', role: 'editor' }, 'Who asked for QA sign-off?')
|
|
95
|
+
// The agent answers that Bob asked for it.
|
|
110
96
|
```
|
|
111
97
|
|
|
112
|
-
|
|
98
|
+
When a message arrives while the agent is still answering someone else, Mastra delivers it into the running turn instead of starting a new one, and `accepted` resolves with `action: 'deliver'`. In a live app, render replies from the [thread stream](https://mastra.ai/docs/signals/thread-streams) rather than from each `sendMessage()` call. That way every participant sees the same conversation.
|
|
113
99
|
|
|
114
100
|
## Combining with memory layers
|
|
115
101
|
|
|
116
|
-
|
|
102
|
+
Pick the memory layer by how long the conversation needs to remember each participant:
|
|
117
103
|
|
|
118
|
-
- **Short conversations
|
|
119
|
-
- **Long-running threads**
|
|
120
|
-
- **Need a structured participants list, or your storage adapter doesn't support OM** (OM requires LibSQL, PG, or MongoDB): use [working memory](#with-working-memory).
|
|
121
|
-
|
|
122
|
-
We recommend using either observational memory or working memory because they cover overlapping needs. Running both adds latency and token cost without much benefit.
|
|
104
|
+
- **Short conversations**, or when you need a verbatim record of who said what: use [message history alone](#message-history-alone).
|
|
105
|
+
- **Long-running threads** that outgrow the context window: use [Observational Memory](#with-observational-memory).
|
|
123
106
|
|
|
124
107
|
### Message history alone
|
|
125
108
|
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
```typescript
|
|
129
|
-
import { Memory } from '@mastra/memory'
|
|
130
|
-
import { LibSQLStore } from '@mastra/libsql'
|
|
131
|
-
|
|
132
|
-
const memory = new Memory({
|
|
133
|
-
storage: new LibSQLStore({ id: 'collab-storage', url: 'file:./collab.db' }),
|
|
134
|
-
options: {
|
|
135
|
-
lastMessages: 20,
|
|
136
|
-
},
|
|
137
|
-
})
|
|
138
|
-
```
|
|
139
|
-
|
|
140
|
-
The model reads identity from the `<turn>` tag on the current message and from prior tagged messages brought back through `lastMessages`.
|
|
141
|
-
|
|
142
|
-
### With Observational Memory (recommended)
|
|
109
|
+
`lastMessages` brings earlier messages back into context with their `<user>` attributes, so attribution survives across turns. The agent example above uses this setup.
|
|
143
110
|
|
|
144
|
-
|
|
111
|
+
### With Observational Memory
|
|
145
112
|
|
|
146
|
-
|
|
113
|
+
[Observational Memory](https://mastra.ai/docs/memory/observational-memory) (OM) keeps a long shared thread inside the context window by replacing older messages with observations. Enable it on the same `Memory`:
|
|
147
114
|
|
|
148
115
|
```typescript
|
|
149
|
-
import { Memory } from '@mastra/memory'
|
|
150
116
|
import { LibSQLStore } from '@mastra/libsql'
|
|
151
|
-
|
|
152
|
-
const memory = new Memory({
|
|
153
|
-
storage: new LibSQLStore({ id: 'collab-storage', url: 'file:./collab.db' }),
|
|
154
|
-
options: {
|
|
155
|
-
lastMessages: 20,
|
|
156
|
-
observationalMemory: true,
|
|
157
|
-
},
|
|
158
|
-
})
|
|
159
|
-
```
|
|
160
|
-
|
|
161
|
-
OM requires a storage adapter that supports it: `@mastra/libsql`, `@mastra/pg`, `@mastra/mongodb`, `@mastra/mysql`, `@mastra/convex`, or `@mastra/oracledb`.
|
|
162
|
-
|
|
163
|
-
> **Note:** If you switch the Observer to a less capable model and see facts attributed to a generic `User` instead of individual participants, use [`observation.instruction`](https://mastra.ai/reference/memory/observational-memory) to explain how to interpret the `<turn>` tag.
|
|
164
|
-
|
|
165
|
-
### With working memory
|
|
166
|
-
|
|
167
|
-
Use working memory when OM isn't an option, for example, when your storage adapter doesn't support OM, or when you need a structured, deterministic participants list the agent can read and write on every turn.
|
|
168
|
-
|
|
169
|
-
The default [working memory](https://mastra.ai/docs/memory/working-memory) template assumes one user per thread ("First Name", "Last Name", etc.). For multi-user threads, provide a template with a participants list:
|
|
170
|
-
|
|
171
|
-
```typescript
|
|
172
117
|
import { Memory } from '@mastra/memory'
|
|
173
|
-
import { LibSQLStore } from '@mastra/libsql'
|
|
174
118
|
|
|
175
119
|
const memory = new Memory({
|
|
176
120
|
storage: new LibSQLStore({ id: 'collab-storage', url: 'file:./collab.db' }),
|
|
177
121
|
options: {
|
|
178
|
-
|
|
179
|
-
workingMemory: {
|
|
180
|
-
enabled: true,
|
|
181
|
-
scope: 'thread',
|
|
182
|
-
template: `# Document Collaboration State
|
|
183
|
-
|
|
184
|
-
## Participants
|
|
185
|
-
<!-- One entry per known collaborator. Use author_id as the stable key. -->
|
|
186
|
-
<!-- - **<author_name>** (<author_id>, <functional_role>): <their position> -->
|
|
187
|
-
|
|
188
|
-
## Open Questions
|
|
189
|
-
|
|
190
|
-
## Decisions
|
|
191
|
-
`,
|
|
192
|
-
},
|
|
122
|
+
observationalMemory: true,
|
|
193
123
|
},
|
|
194
124
|
})
|
|
195
125
|
```
|
|
196
126
|
|
|
197
|
-
|
|
127
|
+
OM replaces `lastMessages` history loading, so leave `lastMessages` out when OM is on.
|
|
198
128
|
|
|
199
|
-
|
|
129
|
+
The Observer keeps the speaker's attributes, so observations say who said what. A message sent with `attributes: { name: 'Alice', role: 'editor' }` is labeled `User (name="Alice" role="editor")`. Messages sent without attributes are labeled plain `User`.
|
|
200
130
|
|
|
201
131
|
## Security
|
|
202
132
|
|
|
203
|
-
Set the
|
|
133
|
+
Set the attributes on your server from the authenticated user, never from the request body. If a client can choose its own `name`, one user can impersonate another. Use [request context](https://mastra.ai/docs/server/request-context) to read the verified user from your auth layer and build the `attributes` before calling `sendMessage()`.
|
|
204
134
|
|
|
205
135
|
## Related
|
|
206
136
|
|
|
207
|
-
- [
|
|
208
|
-
- [
|
|
209
|
-
- [
|
|
137
|
+
- [Sending signals](https://mastra.ai/docs/signals/sending-signals)
|
|
138
|
+
- [Agent `sendMessage()` reference](https://mastra.ai/reference/agents/agent)
|
|
139
|
+
- [Observational Memory](https://mastra.ai/docs/memory/observational-memory)
|
|
210
140
|
- [`Memory` reference](https://mastra.ai/reference/memory/memory-class)
|