@mastra/mcp-docs-server 1.3.12 → 1.3.13-alpha.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.docs/docs/agents/resumable-streams.md +140 -0
- package/.docs/docs/agents/tools.md +3 -2
- package/.docs/docs/auth/overview.md +1 -0
- package/.docs/docs/auth/simple-auth.md +8 -8
- package/.docs/docs/channels.md +34 -1
- package/.docs/docs/connections/mcp.md +73 -7
- package/.docs/docs/deployment/mastra-server.md +10 -2
- package/.docs/docs/deployment/workers.md +3 -1
- package/.docs/docs/guides/authentication-identity.md +4 -0
- package/.docs/docs/harness/background-tasks.md +2 -1
- package/.docs/docs/harness/durable-agents.md +106 -8
- package/.docs/docs/harness/goals.md +1 -1
- package/.docs/docs/harness/schedules.md +2 -0
- package/.docs/docs/knowledge/agents-and-tools.md +122 -0
- package/.docs/docs/knowledge/load-your-content.md +86 -0
- package/.docs/docs/knowledge/overview.md +106 -0
- package/.docs/docs/knowledge/patterns.md +167 -0
- package/.docs/docs/knowledge/pinned-context.md +177 -0
- package/.docs/docs/knowledge/scopes-and-access.md +202 -0
- package/.docs/docs/knowledge/search.md +63 -0
- package/.docs/docs/mastra-platform/connect.md +231 -0
- package/.docs/docs/mastra-platform/overview.md +1 -1
- package/.docs/docs/memory/observational-memory.md +23 -23
- package/.docs/docs/memory/overview.md +19 -7
- package/.docs/docs/memory/semantic-recall.md +26 -1
- package/.docs/docs/observability/integrations/exporters/mastra-storage.md +41 -0
- package/.docs/docs/observability/tracing/overview.md +0 -2
- package/.docs/docs/sandbox/skills.md +32 -3
- package/.docs/docs/server/custom-adapters.md +44 -11
- package/.docs/docs/server/middleware.md +1 -1
- package/.docs/docs/server/request-context.md +6 -6
- package/.docs/docs/server/server-adapters.md +12 -12
- package/.docs/docs/signals/sending-signals.md +3 -1
- package/.docs/docs/studio/knowledge.md +45 -24
- package/.docs/docs/studio/overview.md +3 -1
- package/.docs/docs/workflows/overview.md +12 -0
- package/.docs/docs/workflows/suspend-and-resume.md +1 -1
- package/.docs/integrations/agentic-ui/ai-sdk-ui.md +46 -0
- package/.docs/integrations/auth/clerk.md +46 -7
- package/.docs/integrations/auth/neon.md +217 -0
- package/.docs/integrations/auth/supabase.md +46 -7
- package/.docs/integrations/auth/workos.md +54 -15
- package/.docs/integrations/channels/discord.md +84 -6
- package/.docs/integrations/channels/github.md +63 -24
- package/.docs/integrations/channels/slack.md +89 -8
- package/.docs/integrations/channels/teams.md +79 -5
- package/.docs/integrations/channels/telegram.md +47 -6
- package/.docs/integrations/crm/attio.md +42 -0
- package/.docs/integrations/crm/clay.md +42 -0
- package/.docs/integrations/crm/hubspot.md +41 -0
- package/.docs/integrations/databases/neon.md +37 -1
- package/.docs/integrations/databases/postgresql.md +46 -0
- package/.docs/integrations/deploy/render.md +59 -18
- package/.docs/integrations/deploy/temporal.md +74 -0
- package/.docs/integrations/documents/google-docs.md +41 -0
- package/.docs/integrations/documents/google-sheet.md +41 -0
- package/.docs/integrations/documents/microsoft-excel.md +43 -0
- package/.docs/integrations/documents/microsoft-powerpoint.md +41 -0
- package/.docs/integrations/documents/microsoft-word.md +41 -0
- package/.docs/integrations/documents/notion.md +41 -0
- package/.docs/integrations/documents/one-drive.md +41 -0
- package/.docs/integrations/documents/sharepoint-online.md +41 -0
- package/.docs/integrations/email-calendar/google-calendar.md +41 -0
- package/.docs/integrations/email-calendar/google-mail.md +41 -0
- package/.docs/integrations/email-calendar/outlook.md +41 -0
- package/.docs/integrations/file-storage/amazon-s3.md +1 -1
- package/.docs/integrations/file-storage/google-drive.md +54 -15
- package/.docs/integrations/observability/arize.md +1 -1
- package/.docs/integrations/observability/posthog.md +50 -11
- package/.docs/integrations/other/canva.md +42 -0
- package/.docs/integrations/other/fireflies.md +41 -0
- package/.docs/integrations/other/incident-io.md +41 -0
- package/.docs/integrations/other/resend.md +43 -0
- package/.docs/integrations/other/robinhood.md +44 -0
- package/.docs/integrations/other/sanity.md +42 -0
- package/.docs/integrations/other/snowflake.md +41 -0
- package/.docs/integrations/project-management/jira.md +41 -0
- package/.docs/integrations/project-management/linear.md +41 -0
- package/.docs/integrations/sandboxes/e2b.md +1 -1
- package/.docs/integrations/voice/openai.md +40 -0
- package/.docs/integrations.md +40 -1
- package/.docs/models/environment-variables.md +1 -1
- package/.docs/models/gateways/azure-openai.md +61 -2
- package/.docs/models/gateways/custom-gateways.md +2 -0
- package/.docs/models/gateways/merge-gateway.md +3 -1
- package/.docs/models/gateways/netlify.md +13 -7
- package/.docs/models/gateways/openrouter.md +13 -12
- package/.docs/models/gateways/requesty.md +221 -0
- package/.docs/models/gateways/vercel.md +423 -419
- package/.docs/models/gateways.md +7 -1
- package/.docs/models/index.md +46 -3
- package/.docs/models/providers/aiand.md +1 -1
- package/.docs/models/providers/aihubmix.md +2 -0
- package/.docs/models/providers/amazon-bedrock.md +4 -0
- package/.docs/models/providers/anthropic.md +2 -1
- package/.docs/models/providers/azure.md +4 -0
- package/.docs/models/providers/baseten.md +2 -1
- package/.docs/models/providers/chutes.md +6 -4
- package/.docs/models/providers/cloudflare-ai-gateway.md +2 -0
- package/.docs/models/providers/cloudflare-workers-ai.md +0 -13
- package/.docs/models/providers/cohere.md +2 -0
- package/.docs/models/providers/crossmodel.md +5 -1
- package/.docs/models/providers/deepinfra.md +2 -1
- package/.docs/models/providers/edenai.md +12 -13
- package/.docs/models/providers/empiriolabs.md +3 -3
- package/.docs/models/providers/fireworks-ai.md +30 -28
- package/.docs/models/providers/google-vertex.md +2 -0
- package/.docs/models/providers/google.md +4 -3
- package/.docs/models/providers/hyper.md +8 -14
- package/.docs/models/providers/inceptron.md +3 -3
- package/.docs/models/providers/kilo.md +36 -40
- package/.docs/models/providers/llmgateway-providers.md +448 -423
- package/.docs/models/providers/llmgateway.md +10 -6
- package/.docs/models/providers/meta.md +5 -4
- package/.docs/models/providers/modular.md +6 -6
- package/.docs/models/providers/morph.md +2 -1
- package/.docs/models/providers/nano-gpt.md +55 -62
- package/.docs/models/providers/novita-ai.md +4 -2
- package/.docs/models/providers/ollama-cloud.md +2 -1
- package/.docs/models/providers/ollama.md +2 -0
- package/.docs/models/providers/opencode-go.md +3 -1
- package/.docs/models/providers/opencode.md +11 -5
- package/.docs/models/providers/ovhcloud.md +1 -2
- package/.docs/models/providers/prime.md +4 -4
- package/.docs/models/providers/qvac.md +2 -0
- package/.docs/models/providers/tencent-token-plan.md +2 -1
- package/.docs/models/providers/tencent-tokenhub.md +2 -1
- package/.docs/models/providers/tinfoil.md +4 -3
- package/.docs/models/providers/togetherai.md +2 -1
- package/.docs/models/providers/wandb.md +6 -5
- package/.docs/models/providers.md +0 -1
- package/.docs/reference/agent-controller/agent-controller-class.md +4 -2
- package/.docs/reference/agent-controller/session.md +1 -1
- package/.docs/reference/agents/agent.md +3 -1
- package/.docs/reference/agents/channels.md +117 -1
- package/.docs/reference/agents/durable-agent.md +42 -29
- package/.docs/reference/agents/generate.md +1 -1
- package/.docs/reference/agents/getLLM.md +1 -1
- package/.docs/reference/agents/getMetadata.md +1 -1
- package/.docs/reference/agents/getModel.md +4 -2
- package/.docs/reference/agents/getSkill.md +1 -1
- package/.docs/reference/agents/listScorers.md +1 -1
- package/.docs/reference/agents/listTools.md +1 -1
- package/.docs/reference/ai-sdk/chat-route.md +33 -2
- package/.docs/reference/auth/better-auth.md +2 -2
- package/.docs/reference/auth/neon.md +24 -15
- package/.docs/reference/build-with-ai.md +12 -2
- package/.docs/reference/channels/slack-provider.md +1 -1
- package/.docs/reference/cli/mastra.md +10 -1
- package/.docs/reference/client-js/agents.md +4 -4
- package/.docs/reference/client-js/observability.md +90 -3
- package/.docs/reference/code-sdk/mount-agent-controller.md +5 -1
- package/.docs/reference/connect/channels.md +55 -1
- package/.docs/reference/connect/credential.md +2 -1
- package/.docs/reference/connect/providers.md +5 -3
- package/.docs/reference/connect/tools.md +34 -3
- package/.docs/reference/core/addDynamicWorkflow.md +1 -1
- package/.docs/reference/core/addGateway.md +1 -1
- package/.docs/reference/core/getAgent.md +4 -2
- package/.docs/reference/core/getEditor.md +1 -1
- package/.docs/reference/core/getGateway.md +1 -1
- package/.docs/reference/core/getGatewayById.md +14 -1
- package/.docs/reference/core/getMemory.md +2 -2
- package/.docs/reference/core/getStorage.md +1 -1
- package/.docs/reference/core/listMemory.md +3 -3
- package/.docs/reference/core/listScorers.md +2 -2
- package/.docs/reference/core/listVectors.md +1 -1
- package/.docs/reference/core/mastra-class.md +1 -1
- package/.docs/reference/evals/completeness.md +0 -1
- package/.docs/reference/evals/content-similarity.md +1 -3
- package/.docs/reference/evals/create-scorer.md +8 -4
- package/.docs/reference/evals/faithfulness.md +1 -1
- package/.docs/reference/evals/hallucination.md +2 -2
- package/.docs/reference/evals/noise-sensitivity.md +8 -1
- package/.docs/reference/evals/scorer-utils.md +1 -1
- package/.docs/reference/file-based-agents/tools.md +3 -3
- package/.docs/reference/index.md +8 -0
- package/.docs/reference/knowledge/knowledge-class.md +296 -0
- package/.docs/reference/knowledge/knowledge-memory-scopes.md +78 -0
- package/.docs/reference/knowledge/knowledge-tools.md +299 -0
- package/.docs/reference/knowledge/limits.md +44 -0
- package/.docs/reference/knowledge/scope-declarations.md +275 -0
- package/.docs/reference/knowledge/tool-instructions.md +56 -0
- package/.docs/reference/logging/pino-logger.md +1 -1
- package/.docs/reference/memory/memory-class.md +1 -1
- package/.docs/reference/memory/observational-memory.md +9 -7
- package/.docs/reference/observability/feedback.md +3 -1
- package/.docs/reference/observability/tracing/advanced-queries.md +47 -58
- package/.docs/reference/observability/tracing/configuration.md +3 -0
- package/.docs/reference/observability/tracing/exporters/mastra-platform-exporter.md +33 -0
- package/.docs/reference/observability/tracing/exporters/mastra-storage-exporter.md +30 -0
- package/.docs/reference/observability/tracing/interfaces.md +2 -0
- package/.docs/reference/processors/batch-parts-processor.md +0 -2
- package/.docs/reference/processors/message-history-processor.md +1 -1
- package/.docs/reference/processors/moderation-processor.md +1 -1
- package/.docs/reference/processors/processor-interface.md +1 -1
- package/.docs/reference/processors/semantic-recall-processor.md +8 -4
- package/.docs/reference/processors/skill-search-processor.md +3 -0
- package/.docs/reference/processors/skills-processor.md +84 -0
- package/.docs/reference/processors/stream-error-retry-processor.md +1 -1
- package/.docs/reference/processors/token-limiter-processor.md +1 -1
- package/.docs/reference/processors/tool-search-processor.md +1 -1
- package/.docs/reference/pubsub/lease-provider.md +4 -2
- package/.docs/reference/pubsub/redis-streams.md +3 -1
- package/.docs/reference/rag/graph-rag.md +2 -2
- package/.docs/reference/rag/rerank.md +1 -1
- package/.docs/reference/rag/rerankWithScorer.md +1 -1
- package/.docs/reference/schedules/overview.md +3 -3
- package/.docs/reference/server/invoke-route.md +86 -0
- package/.docs/reference/server/koa-adapter.md +1 -1
- package/.docs/reference/server/routes.md +63 -0
- package/.docs/reference/streaming/ChunkType.md +3 -1
- package/.docs/reference/streaming/agents/MastraModelOutput.md +13 -12
- package/.docs/reference/streaming/agents/stream.md +1 -1
- package/.docs/reference/streaming/workflows/resumeStream.md +1 -1
- package/.docs/reference/tools/mcp-client.md +30 -7
- package/.docs/reference/tools/mcp-server.md +6 -2
- package/.docs/reference/tools/vector-query-tool.md +3 -3
- package/.docs/reference/workers/overview.md +2 -2
- package/.docs/reference/workflows/run-methods/resume.md +1 -1
- package/.docs/reference/workflows/run-methods/start.md +1 -1
- package/.docs/reference/workflows/run-methods/timeTravel.md +1 -1
- package/.docs/reference/workflows/run.md +1 -1
- package/.docs/reference/workflows/workflow.md +2 -0
- package/.docs/reference/workspace/factory-sandbox.md +24 -8
- package/.docs/reference/workspace/platform-sandbox.md +22 -7
- package/.docs/reference/workspace/sandbox.md +1 -1
- package/.docs/reference/workspace/workspace-class.md +5 -5
- package/dist/index.js +1 -1
- package/dist/{src-BDrEqwuY.js → src-CwUXyWAK.js} +3 -3
- package/dist/src-CwUXyWAK.js.map +1 -0
- package/dist/stdio.js +1 -1
- package/dist/tools/embedded-docs.d.ts.map +1 -1
- package/package.json +4 -5
- package/.docs/docs/mastra-platform/connect/channels.md +0 -165
- package/.docs/docs/mastra-platform/connect/overview.md +0 -102
- package/.docs/docs/mastra-platform/connect/providers.md +0 -66
- package/.docs/docs/mastra-platform/connect/tools.md +0 -151
- package/.docs/models/providers/requesty.md +0 -261
- package/dist/src-BDrEqwuY.js.map +0 -1
|
@@ -76,10 +76,35 @@ Mastra also gives the agent three tools:
|
|
|
76
76
|
| -------------- | ----------------------------------------------------------------------------------------- |
|
|
77
77
|
| `skill` | Loads a skill's `SKILL.md` instructions and lists its reference, script, and asset files. |
|
|
78
78
|
| `skill_read` | Reads all or part of any file under the selected skill directory. |
|
|
79
|
-
| `skill_search` | Searches skill instructions and reference files.
|
|
79
|
+
| `skill_search` | Searches skill names, descriptions, instructions, and reference files. |
|
|
80
80
|
|
|
81
81
|
Loading is stateless. The instructions remain in the conversation as a tool result, and the agent can call `skill` again if they leave the context after compaction.
|
|
82
82
|
|
|
83
|
+
### Turn off the skills list
|
|
84
|
+
|
|
85
|
+
With many skills, listing all of them in the system message costs tokens on every request. Add `SkillsProcessor` with `injectCatalog: false` to replace the list with a short instruction to find skills with `skill_search` and load them with `skill`:
|
|
86
|
+
|
|
87
|
+
```typescript
|
|
88
|
+
import { Agent } from '@mastra/core/agent'
|
|
89
|
+
import { SkillsProcessor } from '@mastra/core/processors'
|
|
90
|
+
import { workspace } from '../workspaces'
|
|
91
|
+
|
|
92
|
+
export const supportAgent = new Agent({
|
|
93
|
+
id: 'support-agent',
|
|
94
|
+
name: 'Support Agent',
|
|
95
|
+
instructions: 'You help customers with support requests.',
|
|
96
|
+
model: 'openai/gpt-6.1-sol',
|
|
97
|
+
workspace,
|
|
98
|
+
inputProcessors: [new SkillsProcessor({ injectCatalog: false })],
|
|
99
|
+
})
|
|
100
|
+
```
|
|
101
|
+
|
|
102
|
+
The agent keeps the `skill`, `skill_read`, and `skill_search` tools for both filesystem-backed and [agent skills](https://mastra.ai/docs/skills). `skill_search` works without any search setup: it matches query words against skill names, descriptions, and content. For larger collections, configure [BM25 or vector search](#search-skill-content) on the workspace to improve ranking. Agent skills are always indexed.
|
|
103
|
+
|
|
104
|
+
Keep the default list when you have a few dozen skills: the agent sees every option at once, and the list is a stable prefix that providers can cache. Turn it off when you have around a hundred skills or more, or when the size of the system message matters. The search instruction stays the same size however many skills you add.
|
|
105
|
+
|
|
106
|
+
[`SkillSearchProcessor`](https://mastra.ai/reference/processors/skill-search-processor) also hides the list, but replaces the standard tools with its own `search_skills` and `load_skill` tools and only covers workspace skills. Configure one or the other, not both: together, the agent gets both sets of tools. See the [`SkillsProcessor`](https://mastra.ai/reference/processors/skills-processor) reference for all options.
|
|
107
|
+
|
|
83
108
|
## Configure skill paths
|
|
84
109
|
|
|
85
110
|
The `skills` array accepts several path forms:
|
|
@@ -114,9 +139,13 @@ Direct [agent skills](https://mastra.ai/docs/skills) are resolved before filesys
|
|
|
114
139
|
|
|
115
140
|
## Search skill content
|
|
116
141
|
|
|
117
|
-
When [BM25 or vector search](https://mastra.ai/docs/sandbox/search) is configured alongside skills, Mastra automatically indexes each skill's `SKILL.md` instructions and reference files. Scripts and assets aren't indexed.
|
|
142
|
+
When [BM25 or vector search](https://mastra.ai/docs/sandbox/search) is configured alongside skills, Mastra automatically indexes each skill's name, description, `SKILL.md` instructions, and reference files. Scripts and assets aren't indexed.
|
|
143
|
+
|
|
144
|
+
Without BM25 or vector search, `skill_search` falls back to case-insensitive text matching across the name, description, instructions, and references. Results are ranked by how many query words they contain, and words found in a skill's name or description count more. This keeps skill search available without a separate search configuration, while indexed search provides ranking and semantic retrieval for larger collections.
|
|
145
|
+
|
|
146
|
+
A result from a reference file includes the file path, such as `references/style-guide.md`, so the agent can pass it to `skill_read`.
|
|
118
147
|
|
|
119
|
-
|
|
148
|
+
When the agent asks for a skill name that doesn't exist, `skill` and `skill_read` list every available skill if there are 20 or fewer. With more skills, they suggest up to five close matches and point the agent to `skill_search`, so a mistyped name doesn't add the whole skill list to the conversation.
|
|
120
149
|
|
|
121
150
|
## Dynamic skill paths
|
|
122
151
|
|
|
@@ -262,24 +262,38 @@ async sendResponse(
|
|
|
262
262
|
|
|
263
263
|
Handle streaming responses for agent generation. When an agent generates a response, it produces a stream of chunks that should be sent to the client as they become available. This method reads from the stream and optionally applies redaction to hide sensitive data before writing chunks to the response in the appropriate format (SSE or newline-delimited JSON).
|
|
264
264
|
|
|
265
|
+
Cancel the stream when the client disconnects. For agents with resumable streams, such as durable agents, the cancel is the only signal that the client left. Without it, the run isn't kept for replay and the server keeps reading a stream nobody receives. The client can also leave before your route handler returns, so a `close` listener added afterward never fires.
|
|
266
|
+
|
|
267
|
+
If your framework writes to a Node.js `ServerResponse`, use the helpers from `@mastra/server/server-adapter`:
|
|
268
|
+
|
|
269
|
+
- `cancelReaderOnResponseClose(reader, res)` cancels the reader when the response closes, or right away if it's already closed. Call `dispose()` before ending the response so a normal end doesn't cancel.
|
|
270
|
+
- `writeWithBackpressure(res, chunk)` waits for the client to catch up when the socket buffer is full, so a slow client doesn't make the server buffer the whole stream.
|
|
271
|
+
|
|
265
272
|
```typescript
|
|
273
|
+
import type { ServerResponse } from 'node:http';
|
|
274
|
+
import { cancelReaderOnResponseClose, writeWithBackpressure } from '@mastra/server/server-adapter';
|
|
275
|
+
|
|
266
276
|
async stream(
|
|
267
277
|
route: ServerRoute,
|
|
268
|
-
|
|
278
|
+
res: ServerResponse,
|
|
269
279
|
result: unknown
|
|
270
280
|
): Promise<unknown> {
|
|
271
281
|
const isSSE = route.streamFormat === 'sse';
|
|
272
282
|
|
|
273
283
|
// Set streaming headers based on format
|
|
274
|
-
|
|
275
|
-
|
|
284
|
+
res.setHeader('Content-Type', isSSE ? 'text/event-stream' : 'text/plain');
|
|
285
|
+
res.setHeader('Transfer-Encoding', 'chunked');
|
|
276
286
|
|
|
277
287
|
const reader = result.fullStream.getReader();
|
|
288
|
+
const readerCancel = cancelReaderOnResponseClose(reader, res);
|
|
278
289
|
|
|
279
290
|
try {
|
|
280
291
|
while (true) {
|
|
281
292
|
const { done, value } = await reader.read();
|
|
282
|
-
|
|
293
|
+
|
|
294
|
+
if (done) {
|
|
295
|
+
break;
|
|
296
|
+
}
|
|
283
297
|
|
|
284
298
|
// Apply redaction if enabled
|
|
285
299
|
const chunk = this.streamOptions.redact
|
|
@@ -288,24 +302,25 @@ async stream(
|
|
|
288
302
|
|
|
289
303
|
// Format based on stream format
|
|
290
304
|
if (isSSE) {
|
|
291
|
-
|
|
305
|
+
await writeWithBackpressure(res, `data: ${JSON.stringify(chunk)}\n\n`);
|
|
292
306
|
} else {
|
|
293
|
-
|
|
307
|
+
await writeWithBackpressure(res, JSON.stringify(chunk) + '\x1E');
|
|
294
308
|
}
|
|
295
309
|
}
|
|
296
310
|
|
|
297
311
|
// Send completion marker (SSE uses data: [DONE], other formats use record separator)
|
|
298
312
|
if (isSSE) {
|
|
299
|
-
|
|
313
|
+
await writeWithBackpressure(res, 'data: [DONE]\n\n');
|
|
300
314
|
}
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
throw error;
|
|
315
|
+
} finally {
|
|
316
|
+
readerCancel.dispose();
|
|
317
|
+
res.end();
|
|
305
318
|
}
|
|
306
319
|
}
|
|
307
320
|
```
|
|
308
321
|
|
|
322
|
+
If your framework returns a fetch `Response` instead, wrap the stream in a `ReadableStream` that reads one chunk per `pull()` and cancels the reader in its `cancel()`. Also cancel the reader when the request's `abortSignal` aborts: some runtimes never read or cancel the body of a request that closed while the route handler ran.
|
|
323
|
+
|
|
309
324
|
## Helper methods
|
|
310
325
|
|
|
311
326
|
The base class provides helper methods you can use in your implementation. These handle common tasks like parameter validation and route registration, so you don't need to reimplement them:
|
|
@@ -334,6 +349,10 @@ constructor(options: {
|
|
|
334
349
|
bodyLimitOptions?: BodyLimitOptions;
|
|
335
350
|
streamOptions?: StreamOptions;
|
|
336
351
|
customRouteAuthConfig?: Map<string, boolean>;
|
|
352
|
+
tools?: ToolsInput;
|
|
353
|
+
taskStore?: InMemoryTaskStore;
|
|
354
|
+
customApiRoutes?: ApiRoute[];
|
|
355
|
+
mcpOptions?: MCPOptions;
|
|
337
356
|
}) {
|
|
338
357
|
super(options);
|
|
339
358
|
}
|
|
@@ -464,6 +483,20 @@ createRouteAdapterTestSuite({
|
|
|
464
483
|
})
|
|
465
484
|
```
|
|
466
485
|
|
|
486
|
+
Run the stream disconnect suite to check that your adapter cancels a route's stream when the client disconnects and waits for a slow client. `startServer` serves the route over real HTTP and returns its URL. When the suite passes `beforeContext`, run it as async middleware before your context middleware:
|
|
487
|
+
|
|
488
|
+
```typescript
|
|
489
|
+
import { createStreamDisconnectTestSuite } from '@mastra/server-adapters-test-suite'
|
|
490
|
+
import { startMyFrameworkServer } from './adapter-test-helpers'
|
|
491
|
+
|
|
492
|
+
createStreamDisconnectTestSuite({
|
|
493
|
+
startServer: async (route, { beforeContext } = {}) => {
|
|
494
|
+
const { url, close } = await startMyFrameworkServer(route, { beforeContext })
|
|
495
|
+
return { url, close }
|
|
496
|
+
},
|
|
497
|
+
})
|
|
498
|
+
```
|
|
499
|
+
|
|
467
500
|
The package also provides root exports for Model Context Protocol (MCP), multipart request, HTTP logging, and body limit tests. See the [package README](https://github.com/mastra-ai/mastra/tree/main/server-adapters/server-adapters-test-suite) for the supported peer dependency versions.
|
|
468
501
|
|
|
469
502
|
> **Tip:** The existing [@mastra/hono](https://github.com/mastra-ai/mastra/blob/main/server-adapters/hono/src/index.ts) and [@mastra/express](https://github.com/mastra-ai/mastra/blob/main/server-adapters/express/src/index.ts) implementations are good references when building your custom adapter. They show how to handle framework-specific patterns for context storage and middleware registration, plus response handling.
|
|
@@ -283,7 +283,7 @@ This is useful when you want to restrict operations to a specific thread that yo
|
|
|
283
283
|
}
|
|
284
284
|
```
|
|
285
285
|
|
|
286
|
-
|
|
286
|
+
## Related
|
|
287
287
|
|
|
288
288
|
- [Request Context](https://mastra.ai/docs/server/request-context)
|
|
289
289
|
- [Reserved Keys](https://mastra.ai/docs/server/request-context)
|
|
@@ -290,12 +290,12 @@ requestContext.set(MASTRA_RESOURCE_ID_KEY, user.id)
|
|
|
290
290
|
requestContext.set(MASTRA_THREAD_ID_KEY, threadId)
|
|
291
291
|
```
|
|
292
292
|
|
|
293
|
-
| Key | Purpose
|
|
294
|
-
| --------------------------- |
|
|
295
|
-
| `MASTRA_RESOURCE_ID_KEY` | Forces all memory operations to use this resource ID. The server validates that accessed threads belong to this resource and returns 403 if not.
|
|
296
|
-
| `MASTRA_THREAD_ID_KEY` | Forces thread operations to use this thread ID, overriding client-provided values
|
|
297
|
-
| `MASTRA_SCOPES_KEY` | Sets the [scopes](https://mastra.ai/docs/memory/overview) the agent run acts as, as an array of `<type>:<value>` strings. Combined with the agent's `scopes` and
|
|
298
|
-
| `MASTRA_MESSAGE_AUTHOR_KEY` | Names who sent a user message as `{ id, name?, avatarUrl? }`. Agent-controller sessions persist it at `content.metadata.signal.author` and mirror it to `providerMetadata.mastra.author` for compatibility, so a thread shared by several people can show who wrote what.
|
|
293
|
+
| Key | Purpose |
|
|
294
|
+
| --------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
295
|
+
| `MASTRA_RESOURCE_ID_KEY` | Forces all memory operations to use this resource ID. The server validates that accessed threads belong to this resource and returns 403 if not. |
|
|
296
|
+
| `MASTRA_THREAD_ID_KEY` | Forces thread operations to use this thread ID, overriding client-provided values |
|
|
297
|
+
| `MASTRA_SCOPES_KEY` | Sets the [scopes](https://mastra.ai/docs/memory/overview) the agent run acts as, as an array of `<type>:<value>` strings. Combined with per-call `scopes`; the agent's `scopes` list adds to them, and a `scopes` function replaces them. A `resource:` or `thread:` scope that conflicts with another resource or thread value returns a 400 error. |
|
|
298
|
+
| `MASTRA_MESSAGE_AUTHOR_KEY` | Names who sent a user message as `{ id, name?, avatarUrl? }`. Agent-controller sessions persist it at `content.metadata.signal.author` and mirror it to `providerMetadata.mastra.author` for compatibility, so a thread shared by several people can show who wrote what. |
|
|
299
299
|
|
|
300
300
|
Server ownership checks read only `MASTRA_RESOURCE_ID_KEY` and `MASTRA_THREAD_ID_KEY`. If your middleware sets identity through `MASTRA_SCOPES_KEY` and you want those checks, set `MASTRA_RESOURCE_ID_KEY` too:
|
|
301
301
|
|
|
@@ -594,12 +594,13 @@ When using server adapters, configuration comes from two places: the Mastra `ser
|
|
|
594
594
|
|
|
595
595
|
The adapter reads these settings from `mastra.getServer()`:
|
|
596
596
|
|
|
597
|
-
| Option | Description
|
|
598
|
-
| --------------- |
|
|
599
|
-
| `auth` | Authentication config, used by `registerAuthMiddleware()`.
|
|
600
|
-
| `
|
|
601
|
-
| `
|
|
602
|
-
| `
|
|
597
|
+
| Option | Description |
|
|
598
|
+
| --------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
599
|
+
| `auth` | Authentication config, used by `registerAuthMiddleware()`. |
|
|
600
|
+
| `apiRoutes` | Custom [`registerApiRoute()`](https://mastra.ai/reference/server/register-api-route) routes, registered by `registerCustomApiRoutes()` and added to the OpenAPI spec when `openapiPath` is set. The adapter constructor `customApiRoutes` option overrides this list. |
|
|
601
|
+
| `bodySizeLimit` | Default body size limit in bytes. Can be overridden per-adapter via `bodyLimitOptions`. |
|
|
602
|
+
| `onError` | Custom error handler called when an unhandled error occurs in a route handler. See [server.onError](https://mastra.ai/reference/configuration). |
|
|
603
|
+
| `middleware` | User [middleware](https://mastra.ai/docs/server/middleware), registered by `registerUserMiddleware()`. Hono-based adapters run it; Elysia, Express, Fastify, Koa, and NestJS log a warning because Hono handlers can't run there. |
|
|
603
604
|
|
|
604
605
|
### Adapter constructor only
|
|
605
606
|
|
|
@@ -618,12 +619,11 @@ These options are passed directly to the adapter constructor and aren't read fro
|
|
|
618
619
|
|
|
619
620
|
These `server` config options are only used by `mastra build` and have no effect when using adapters directly:
|
|
620
621
|
|
|
621
|
-
| Option | Used by
|
|
622
|
-
| -------------- |
|
|
623
|
-
| `port`, `host` | `mastra dev`, `mastra build`
|
|
624
|
-
| `cors` | `mastra build` adds CORS middleware
|
|
625
|
-
| `timeout` | `mastra build`
|
|
626
|
-
| `apiRoutes` | `registerApiRoute()` for `mastra build` |
|
|
622
|
+
| Option | Used by |
|
|
623
|
+
| -------------- | ----------------------------------- |
|
|
624
|
+
| `port`, `host` | `mastra dev`, `mastra build` |
|
|
625
|
+
| `cors` | `mastra build` adds CORS middleware |
|
|
626
|
+
| `timeout` | `mastra build` |
|
|
627
627
|
|
|
628
628
|
When using adapters, configure these features directly with your framework. For example, add CORS middleware using Hono's or Express's built-in CORS packages, and set the port when calling your framework's listen function.
|
|
629
629
|
|
|
@@ -119,7 +119,9 @@ if (action === 'persist') {
|
|
|
119
119
|
|
|
120
120
|
Only idle threads persist here. An active thread still delivers to the running run, so `persisted` is set only when the action is `persist`.
|
|
121
121
|
|
|
122
|
-
|
|
122
|
+
Message and signal sends return an `accepted` promise. It resolves when Mastra decides what to do, not when a run finishes. `sendNotificationSignal()` includes `accepted` only when its delivery policy emits a signal, so check `decision` first. `sendStateSignal()` omits it when it skips an unchanged snapshot.
|
|
123
|
+
|
|
124
|
+
The `accepted` promise resolves with one of these actions:
|
|
123
125
|
|
|
124
126
|
- `wake`: this process started a run for the input.
|
|
125
127
|
- `deliver`: the input was sent to a run, or another process accepted responsibility for starting one.
|
|
@@ -4,43 +4,59 @@
|
|
|
4
4
|
|
|
5
5
|
# Knowledge
|
|
6
6
|
|
|
7
|
-
Studio
|
|
7
|
+
Studio's Knowledge page shows what your agents know: every scope and page, how they link, and who wrote what. Use it to check content you loaded and to watch agents' edits as they happen. It's read-only.
|
|
8
8
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
The routes that feed it are **off by default**. Until you enable them, the Knowledge page in Studio shows an explainer saying Knowledge browsing isn't enabled.
|
|
9
|
+
> **Alpha:** Knowledge is in alpha. Its API may change between releases.
|
|
12
10
|
|
|
13
11
|
## Enable the routes
|
|
14
12
|
|
|
15
|
-
Register the Knowledge routes
|
|
13
|
+
The Knowledge routes are **off by default**. Until you enable them, Studio's Knowledge page says browsing isn't enabled. Register the Knowledge instance on `Mastra` and add the routes:
|
|
16
14
|
|
|
17
15
|
```typescript
|
|
18
|
-
import { Mastra } from '@mastra/core'
|
|
16
|
+
import { Mastra } from '@mastra/core/mastra'
|
|
19
17
|
import { KNOWLEDGE_ROUTES } from '@mastra/server/server-adapter'
|
|
18
|
+
import { knowledge } from './knowledge'
|
|
19
|
+
import { supportAgent } from './agents/support-agent'
|
|
20
20
|
|
|
21
21
|
export const mastra = new Mastra({
|
|
22
|
+
agents: { supportAgent },
|
|
23
|
+
knowledge: { company: knowledge },
|
|
22
24
|
server: { apiRoutes: [...KNOWLEDGE_ROUTES] },
|
|
23
25
|
})
|
|
24
26
|
```
|
|
25
27
|
|
|
26
|
-
|
|
28
|
+
The routes mount under your server's API prefix, `/api/knowledge` by default, and need `@mastra/core` 1.81.0 or later. With 1.81.0, Studio counts links only among the pages it has loaded. [Server routes](https://mastra.ai/reference/server/routes) lists each route, its parameters and its errors.
|
|
29
|
+
|
|
30
|
+
## What you see
|
|
31
|
+
|
|
32
|
+
- **Tree**: every scope and the pages inside it, nested the way your agents organized them.
|
|
33
|
+
- **Graph**: the same pages and how they connect. Lines show each page's parent, the pages its notes mention, the links written in its body, and which scopes grant access to which. A legend names each kind of line. Select a page in either view to open it.
|
|
34
|
+
- **Page**: the body, version and who last updated it, its notes with their authors, its child pages, the notes on other pages that mention it, and who it's pinned for.
|
|
35
|
+
- **Activity**: each page's history of creates, edits, moves, merges, notes and pins, with the author and time of each.
|
|
36
|
+
- **Search**: over page names, descriptions, bodies and note text.
|
|
37
|
+
|
|
38
|
+
On narrow screens the tree and graph share one panel, with a toggle between them that keeps the selected page.
|
|
39
|
+
|
|
40
|
+
When an agent writes, the tree, graph and open page update as it happens, without a reload. Studio follows writes made through the Knowledge instance registered with Mastra. Writes from another process or another instance on the same storage show up after a reload.
|
|
27
41
|
|
|
28
|
-
|
|
29
|
-
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------ |
|
|
30
|
-
| `GET /knowledge` | The Knowledge instances you can read |
|
|
31
|
-
| `GET /knowledge/:knowledgeKey/tree` | The root scopes, or the child scopes and pages under `parentId` |
|
|
32
|
-
| `GET /knowledge/:knowledgeKey/pages/:pageId` | One page with its ancestors, notes, pin and referenced pages |
|
|
33
|
-
| `GET /knowledge/:knowledgeKey/graph` | A bounded graph of pages with parent and mention edges |
|
|
34
|
-
| `GET /knowledge/:knowledgeKey/search` | Pages and notes matching a query |
|
|
35
|
-
| `GET /knowledge/:knowledgeKey/activity` | Recent changes, optionally for one scope or page |
|
|
36
|
-
| `GET /knowledge/:knowledgeKey/events` | A Server-Sent Events stream of the writes the caller can read, which Studio follows to show changes as they happen |
|
|
42
|
+

|
|
37
43
|
|
|
38
|
-
|
|
44
|
+
Hover over or select a page in the graph to draw its links: solid green lines for the pages it links to, dashed orange lines for the pages that link to it.
|
|
45
|
+
|
|
46
|
+

|
|
47
|
+
|
|
48
|
+
Focus a page to see only it, its parent and its child pages.
|
|
49
|
+
|
|
50
|
+

|
|
51
|
+
|
|
52
|
+
In an agent's chat, Knowledge tool calls show the pages they read or wrote, and pinned pages show what the run received. Both link to the page in this view.
|
|
53
|
+
|
|
54
|
+
## Control who sees what
|
|
39
55
|
|
|
40
56
|
What the routes return depends on whether your app configures auth (`server.auth` or `studio.auth`):
|
|
41
57
|
|
|
42
|
-
- **No auth:** the routes read as the instance owner and return every scope, page and note.
|
|
43
|
-
- **Auth:** the routes return only what the signed-in
|
|
58
|
+
- **No auth:** the routes read as the instance owner and return every scope, page and note to anyone who can reach the server. Use this only for a local or test project, and add auth before you deploy.
|
|
59
|
+
- **Auth:** the routes return only what the signed-in user can read. In `authorize`, set the request context key `MASTRA_KNOWLEDGE_PRINCIPALS_KEY` to the user's Knowledge scopes. Knowledge applies the same access rules agents use. In the alpha, these rules aren't an [isolation boundary](https://mastra.ai/docs/knowledge/scopes-and-access), so don't store content that must never reach another user.
|
|
44
60
|
|
|
45
61
|
```typescript
|
|
46
62
|
import { Mastra } from '@mastra/core/mastra'
|
|
@@ -69,13 +85,18 @@ export const mastra = new Mastra({
|
|
|
69
85
|
})
|
|
70
86
|
```
|
|
71
87
|
|
|
88
|
+
If you set a different prefix, change the `/api/knowledge` check in `authorize` to match. Otherwise the key isn't set and the routes return `403`.
|
|
89
|
+
|
|
72
90
|
An `authorize` function replaces the server's rules and role checks for every route, so keep your app's existing decision for the other paths, as above. Returning `true` for everything would let any signed-in user call any route.
|
|
73
91
|
|
|
74
|
-
Set the value to
|
|
92
|
+
Set the value to an array of scopes, or `'all'` for someone who should see the whole instance. An empty array reads nothing. See [Knowledge access and errors](https://mastra.ai/reference/server/routes) for what other values return. If you configure `studio.auth`, Studio requests use it instead of `server.auth`, so set the key in that `authorize`.
|
|
75
93
|
|
|
76
|
-
|
|
94
|
+
### Deployment notes
|
|
77
95
|
|
|
78
|
-
- **No auth configured:** the routes are open to anyone who can reach the server and read the whole instance. Enable them only where Studio itself is private.
|
|
79
96
|
- **No RBAC provider:** the `knowledge:read` check is skipped, so any authenticated user with a principal mapping can read the pages those principals cover, in every instance.
|
|
80
|
-
- **With an FGA provider:** Knowledge
|
|
81
|
-
- **NestJS:** the NestJS adapter doesn't serve the Knowledge routes yet.
|
|
97
|
+
- **With an FGA provider:** each Knowledge instance is checked separately with `knowledge:read`. A user sees only the instances you grant. See [Knowledge access and errors](https://mastra.ai/reference/server/routes).
|
|
98
|
+
- **NestJS:** the NestJS adapter doesn't serve the Knowledge routes yet.
|
|
99
|
+
|
|
100
|
+
## Build your own view
|
|
101
|
+
|
|
102
|
+
To show Knowledge changes in your own app, subscribe with [`knowledge.onChange()`](https://mastra.ai/reference/knowledge/knowledge-class). Events carry IDs, not content. Read the page again under the user's scopes before you show it to them. A `page` `delete` event can't be read again, so remove the page from your view. A `page` `merge` event's `pageId` is the target, so also remove the merged-away page in `sourceId`. A `scope` event is sent for a new scope only, not for its child scopes or template pages, so list the scope again to find them.
|
|
@@ -63,6 +63,8 @@ CSV exports contain plain cell text, including link labels rather than URLs. Foo
|
|
|
63
63
|
|
|
64
64
|
You can also attach [scorers](#scorers) to measure and compare response quality over time.
|
|
65
65
|
|
|
66
|
+
To ask about part of a response, select the text in the message and choose **Add to chat**, or press Tab to reach it from the keyboard. Each passage you add gets a numbered comment bubble in the chat, and the message box counts them, for example **2 annotations**. Select a bubble to write a comment on that passage or remove it, or open the count to find a passage in the chat. When you send, the agent receives a numbered list of the passages, each quoted with its comment, ahead of what you type. You can also send the annotations without typing anything. A selection that spans two messages doesn't offer **Add to chat**.
|
|
67
|
+
|
|
66
68
|
You can send a follow-up message in the same thread during an agent response stream. Studio shows the message as pending until the stream confirms it, then continues the response below that follow-up. Other Studio tabs that have the same thread open can observe the active stream.
|
|
67
69
|
|
|
68
70
|
Use [Editor](https://mastra.ai/docs/studio/editor) to let non-technical team members iterate on agents and version every change, plus run experiments without redeploying.
|
|
@@ -73,7 +75,7 @@ Use [Agent Builder](https://agent-builder.mastra.ai) to create and manage fully
|
|
|
73
75
|
|
|
74
76
|
Open an agent's **Models** panel to view its primary model and fallback models in priority order. For static model lists, you can reorder models, enable or disable fallbacks, and change the provider or model. The panel stays synchronized when Studio refetches the agent.
|
|
75
77
|
|
|
76
|
-
|
|
78
|
+
When the agent sets `editor: { model: true }`, these edits are saved through [Editor](https://mastra.ai/docs/studio/editor). This requires a configured `MastraEditor` and agent storage; without either, saving fails with HTTP 500. Otherwise they change the running server's in-memory agent and are lost when the server restarts. Persistent editing for other agents is tracked in [GitHub issue #27089](https://github.com/mastra-ai/mastra/issues/27089).
|
|
77
79
|
|
|
78
80
|
Function-valued model lists can vary by request context, so Studio displays them as read-only. Change a dynamic model list in code instead.
|
|
79
81
|
|
|
@@ -502,6 +502,18 @@ To exclude a workflow from automatic boot-time restarts triggered by `Mastra.res
|
|
|
502
502
|
|
|
503
503
|
While a run executes, Mastra holds a storage lease on it and renews it in the background. `restart()` refuses to take over a run whose lease hasn't expired: it throws a `WORKFLOW_RESTART_RUN_OWNED` error and the sweep skips the run. The lease is advisory and doesn't fence writes. If a process stops renewing its lease but keeps executing a step, for example because its event loop is blocked for longer than the lease TTL, recovery can run that step a second time. The boot-time sweep, `mastra.restartAllActiveWorkflowRuns()`, rechecks a skipped run once its lease could have expired, so a run whose process crashed is still recovered. `workflow.restartAllActiveWorkflowRuns()` skips the run without a recheck, so call it after the lease expires if you need to recover that run. Storage adapters without run-ownership support keep the previous behavior and restart every active run.
|
|
504
504
|
|
|
505
|
+
A restarted run runs the interrupted step again, even if that step finished before the process stopped but its result wasn't saved. On the evented engine, a step also runs again when its event is redelivered to a worker. Make steps with side effects idempotent, so a repeated step has no additional effect.
|
|
506
|
+
|
|
507
|
+
A step's `execute` function receives `runId` and `workflowId`. Combine them with the `id` you gave the step in `createStep()`, plus a name for each side effect when the step performs more than one, to build an idempotency key.
|
|
508
|
+
|
|
509
|
+
Some steps need part of the key to come from their input:
|
|
510
|
+
|
|
511
|
+
- A nested workflow can receive a new `runId` when it's recovered or redelivered. Pass the parent's `runId` into the nested workflow's input and use it in place of the nested `runId`.
|
|
512
|
+
- `foreach` runs the same step once per item. Add an ID from the step's input that identifies the item.
|
|
513
|
+
- A loop runs the same step on every iteration. Return an iteration number from the step and read it from the input on the next iteration. A repeated or resumed iteration receives the same input, so the number doesn't change.
|
|
514
|
+
|
|
515
|
+
For tools that agents call, see [make tools safe to repeat](https://mastra.ai/docs/harness/durable-agents).
|
|
516
|
+
|
|
505
517
|
### Restarting an active workflow run with `restart()`
|
|
506
518
|
|
|
507
519
|
Use `restart()` to restart an active workflow run from the last active step. This will resume execution from the last active step, and the workflow will continue from there.
|
|
@@ -188,7 +188,7 @@ if (result.status === 'suspended') {
|
|
|
188
188
|
|
|
189
189
|
### Example output
|
|
190
190
|
|
|
191
|
-
The `suspended` array contains the
|
|
191
|
+
The `suspended` array contains one path for each suspended step in the run. Each path is an array of step IDs that leads from the top-level workflow to the suspended step, passing through any nested workflows. Pass a path to the `step` parameter of `resume()` to target and resume that execution path. With the default engine, a nested workflow contributes only one path at a time, even if several of its parallel steps suspended. After resuming, check the returned `suspended` array for remaining paths. Treat each path as opaque and pass it back unchanged: depending on the engine, it can include repeated IDs or numeric `.foreach()` indexes. A path to a suspended `.foreach()` step targets every suspended iteration, so pass [`forEachIndex`](https://mastra.ai/reference/workflows/run-methods/resume) to resume one iteration at a time. For a step suspended inside a nested workflow, `result.suspended[0]` is:
|
|
192
192
|
|
|
193
193
|
```typescript
|
|
194
194
|
['nested-workflow', 'step-1']
|
|
@@ -243,6 +243,52 @@ export default function Chat() {
|
|
|
243
243
|
|
|
244
244
|
Use [`prepareSendMessagesRequest`](https://ai-sdk.dev/docs/reference/ai-sdk-ui/use-chat#transport.default-chat-transport.prepare-send-messages-request) to customize the request sent to the chat route, for example to pass additional configuration to the agent.
|
|
245
245
|
|
|
246
|
+
### Resume a chat stream after a disconnect
|
|
247
|
+
|
|
248
|
+
Enable resumable streams on the Mastra route:
|
|
249
|
+
|
|
250
|
+
```typescript
|
|
251
|
+
import { Mastra } from '@mastra/core'
|
|
252
|
+
import { chatRoute } from '@mastra/ai-sdk'
|
|
253
|
+
|
|
254
|
+
export const mastra = new Mastra({
|
|
255
|
+
server: {
|
|
256
|
+
apiRoutes: [
|
|
257
|
+
chatRoute({
|
|
258
|
+
path: '/chat',
|
|
259
|
+
agent: 'weatherAgent',
|
|
260
|
+
resumable: true,
|
|
261
|
+
}),
|
|
262
|
+
],
|
|
263
|
+
},
|
|
264
|
+
})
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
Pass a stable chat ID and `resume: true` to `useChat()`. AI SDK UI reconnects through `GET /chat/:chatId/stream` when the component mounts again while the generation is still active.
|
|
268
|
+
|
|
269
|
+
```tsx
|
|
270
|
+
import { useChat } from '@ai-sdk/react'
|
|
271
|
+
import { DefaultChatTransport } from 'ai'
|
|
272
|
+
|
|
273
|
+
export function Chat({ chatId }: { chatId: string }) {
|
|
274
|
+
const { messages, sendMessage, status } = useChat({
|
|
275
|
+
id: chatId,
|
|
276
|
+
resume: true,
|
|
277
|
+
transport: new DefaultChatTransport({
|
|
278
|
+
api: 'http://localhost:4111/chat',
|
|
279
|
+
}),
|
|
280
|
+
})
|
|
281
|
+
|
|
282
|
+
// ...render messages and call sendMessage()
|
|
283
|
+
}
|
|
284
|
+
```
|
|
285
|
+
|
|
286
|
+
Keep `chatId` in a URL, browser storage, or application state so a refresh reuses the same value. Resumption only applies to an active run. Completed or unavailable runs return `204`, so load completed chat history from memory separately.
|
|
287
|
+
|
|
288
|
+
Resumable mode lets generation continue after the POST connection closes, which means `useChat().stop()` doesn't cancel the agent run. Active-run discovery is process-local, so the reconnect request must reach the same running Mastra server process.
|
|
289
|
+
|
|
290
|
+
If the chat uses a resource ID, authentication middleware must set `MASTRA_RESOURCE_ID_KEY` in the request context. Don't send the resource ID only as `memory.resource` in the POST body because the reconnecting GET request has no body.
|
|
291
|
+
|
|
246
292
|
### Client tools with `useChat()`
|
|
247
293
|
|
|
248
294
|
A tool without an `execute` function runs on the client. When the model calls it, the agent's run ends at that step and the stream finishes with a `tool-{toolKey}` part in the `input-available` state. To let the agent continue, run the tool in the browser, add its result with `addToolOutput()`, and send the conversation back. `sendAutomaticallyWhen` sends the next request once every tool call in the last assistant message has a result:
|
|
@@ -4,9 +4,48 @@
|
|
|
4
4
|
|
|
5
5
|
# Clerk
|
|
6
6
|
|
|
7
|
+
Use Clerk with Mastra in two ways:
|
|
8
|
+
|
|
9
|
+
- **Agent tools** let an agent manage Clerk users, organizations, and sessions through [Mastra Connect](https://mastra.ai/docs/mastra-platform/connect).
|
|
10
|
+
- **[Server authentication](#server-authentication)** verifies requests to your Mastra server with Clerk, using the `@mastra/auth-clerk` package.
|
|
11
|
+
|
|
12
|
+
## Connect
|
|
13
|
+
|
|
14
|
+
Before you start, complete the [Connect setup](https://mastra.ai/docs/mastra-platform/connect) to install `@mastra/connect` and configure your platform project.
|
|
15
|
+
|
|
16
|
+
### Agent tools
|
|
17
|
+
|
|
18
|
+
Give agents tools to manage users, organizations, memberships, invitations, roles, and sessions in Clerk.
|
|
19
|
+
|
|
20
|
+
Connect an account with the `clerk` provider ID. Run this command from the directory that contains your `.env` file:
|
|
21
|
+
|
|
22
|
+
```bash
|
|
23
|
+
mastra connect add clerk
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
Then pass [`tools()`](https://mastra.ai/reference/connect/tools) to the agent and select the provider:
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { Agent } from '@mastra/core/agent'
|
|
30
|
+
import { tools } from '@mastra/connect'
|
|
31
|
+
|
|
32
|
+
export const clerkAgent = new Agent({
|
|
33
|
+
id: 'clerk-agent',
|
|
34
|
+
name: 'Clerk agent',
|
|
35
|
+
instructions:
|
|
36
|
+
'You help people manage users, organizations, memberships, invitations, roles, and sessions in Clerk.',
|
|
37
|
+
model: '__GATEWAY_OPENAI_MODEL_LUNA__',
|
|
38
|
+
tools: tools({ providers: ['clerk'] }),
|
|
39
|
+
})
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
The agent gets 42 Clerk tools, with keys such as `clerk_assign_organization_role_permission`. See [Clerk tools](https://mastra.ai/reference/connect/providers) for the full list, and the [`tools()` parameters](https://mastra.ai/reference/connect/tools) to restrict tools or require approval before a call runs.
|
|
43
|
+
|
|
44
|
+
## Server authentication
|
|
45
|
+
|
|
7
46
|
The `@mastra/auth-clerk` package provides authentication for Mastra using Clerk. It verifies incoming requests using Clerk's authentication system and integrates with the Mastra server using the `auth` option.
|
|
8
47
|
|
|
9
|
-
|
|
48
|
+
### Prerequisites
|
|
10
49
|
|
|
11
50
|
This example uses Clerk authentication. Make sure to add your Clerk credentials to your `.env` file and ensure your Clerk project is properly configured.
|
|
12
51
|
|
|
@@ -18,7 +57,7 @@ CLERK_JWKS_URI=https://your-clerk-domain.clerk.accounts.dev/.well-known/jwks.jso
|
|
|
18
57
|
|
|
19
58
|
> **Note:** You can find these keys in your Clerk Dashboard under "API Keys".
|
|
20
59
|
|
|
21
|
-
|
|
60
|
+
### Installation
|
|
22
61
|
|
|
23
62
|
Before you can use the `MastraAuthClerk` class you have to install the `@mastra/auth-clerk` package.
|
|
24
63
|
|
|
@@ -46,7 +85,7 @@ yarn add @mastra/auth-clerk@latest
|
|
|
46
85
|
bun add @mastra/auth-clerk@latest
|
|
47
86
|
```
|
|
48
87
|
|
|
49
|
-
|
|
88
|
+
### Usage example
|
|
50
89
|
|
|
51
90
|
```typescript
|
|
52
91
|
import { Mastra } from '@mastra/core'
|
|
@@ -67,11 +106,11 @@ export const mastra = new Mastra({
|
|
|
67
106
|
>
|
|
68
107
|
> Visit [MastraAuthClerk](https://mastra.ai/reference/auth/clerk) for all available configuration options.
|
|
69
108
|
|
|
70
|
-
|
|
109
|
+
### Client-side setup
|
|
71
110
|
|
|
72
111
|
When using Clerk auth, you'll need to retrieve the access token from Clerk on the client side and pass it to your Mastra requests.
|
|
73
112
|
|
|
74
|
-
|
|
113
|
+
#### Retrieving the access token
|
|
75
114
|
|
|
76
115
|
Use the Clerk React hooks to authenticate users and retrieve their access token:
|
|
77
116
|
|
|
@@ -92,7 +131,7 @@ export const useClerkAuth = () => {
|
|
|
92
131
|
|
|
93
132
|
Refer to the [Clerk documentation](https://clerk.com/docs) for more information.
|
|
94
133
|
|
|
95
|
-
|
|
134
|
+
### Configuring `MastraClient`
|
|
96
135
|
|
|
97
136
|
When `auth` is enabled, all requests made with `MastraClient` must include a valid Clerk access token in the `Authorization` header:
|
|
98
137
|
|
|
@@ -111,7 +150,7 @@ export const mastraClient = new MastraClient({
|
|
|
111
150
|
>
|
|
112
151
|
> Visit [Mastra Client SDK](https://mastra.ai/docs/server/mastra-client) for more configuration options.
|
|
113
152
|
|
|
114
|
-
|
|
153
|
+
#### Making authenticated requests
|
|
115
154
|
|
|
116
155
|
Once `MastraClient` is configured with the Clerk access token, you can send authenticated requests:
|
|
117
156
|
|