@mastra/mcp-docs-server 1.3.13-alpha.0 → 1.3.13-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.docs/docs/agents/resumable-streams.md +140 -0
- package/.docs/docs/agents/tools.md +2 -2
- package/.docs/docs/auth/overview.md +1 -0
- package/.docs/docs/channels.md +34 -1
- package/.docs/docs/connections/mcp.md +27 -61
- package/.docs/docs/harness/background-tasks.md +2 -1
- package/.docs/docs/harness/durable-agents.md +6 -6
- package/.docs/docs/harness/schedules.md +2 -0
- package/.docs/docs/mastra-platform/connect.md +231 -0
- package/.docs/docs/mastra-platform/overview.md +1 -1
- package/.docs/docs/observability/tracing/overview.md +0 -2
- package/.docs/docs/signals/sending-signals.md +3 -1
- package/.docs/integrations/auth/clerk.md +46 -7
- package/.docs/integrations/auth/neon.md +217 -0
- package/.docs/integrations/auth/supabase.md +46 -7
- package/.docs/integrations/auth/workos.md +54 -15
- package/.docs/integrations/channels/discord.md +84 -6
- package/.docs/integrations/channels/github.md +63 -24
- package/.docs/integrations/channels/slack.md +89 -8
- package/.docs/integrations/channels/teams.md +79 -5
- package/.docs/integrations/channels/telegram.md +47 -6
- package/.docs/integrations/crm/attio.md +42 -0
- package/.docs/integrations/crm/clay.md +42 -0
- package/.docs/integrations/crm/hubspot.md +41 -0
- package/.docs/integrations/databases/neon.md +37 -1
- package/.docs/integrations/databases/postgresql.md +46 -0
- package/.docs/integrations/deploy/render.md +59 -18
- package/.docs/integrations/documents/google-docs.md +41 -0
- package/.docs/integrations/documents/google-sheet.md +41 -0
- package/.docs/integrations/documents/microsoft-excel.md +43 -0
- package/.docs/integrations/documents/microsoft-powerpoint.md +41 -0
- package/.docs/integrations/documents/microsoft-word.md +41 -0
- package/.docs/integrations/documents/notion.md +41 -0
- package/.docs/integrations/documents/one-drive.md +41 -0
- package/.docs/integrations/documents/sharepoint-online.md +41 -0
- package/.docs/integrations/email-calendar/google-calendar.md +41 -0
- package/.docs/integrations/email-calendar/google-mail.md +41 -0
- package/.docs/integrations/email-calendar/outlook.md +41 -0
- package/.docs/integrations/file-storage/amazon-s3.md +1 -1
- package/.docs/integrations/file-storage/google-drive.md +54 -15
- package/.docs/integrations/observability/posthog.md +50 -11
- package/.docs/integrations/other/canva.md +42 -0
- package/.docs/integrations/other/fireflies.md +41 -0
- package/.docs/integrations/other/incident-io.md +41 -0
- package/.docs/integrations/other/resend.md +43 -0
- package/.docs/integrations/other/robinhood.md +44 -0
- package/.docs/integrations/other/sanity.md +42 -0
- package/.docs/integrations/other/snowflake.md +41 -0
- package/.docs/integrations/project-management/jira.md +41 -0
- package/.docs/integrations/project-management/linear.md +41 -0
- package/.docs/integrations/voice/openai.md +40 -0
- package/.docs/integrations.md +40 -1
- package/.docs/models/gateways/custom-gateways.md +2 -0
- package/.docs/models/gateways/netlify.md +7 -6
- package/.docs/models/gateways/openrouter.md +9 -11
- package/.docs/models/gateways/vercel.md +419 -420
- package/.docs/models/index.md +46 -2
- package/.docs/models/providers/aiand.md +1 -1
- package/.docs/models/providers/chutes.md +2 -1
- package/.docs/models/providers/edenai.md +10 -14
- package/.docs/models/providers/empiriolabs.md +3 -3
- package/.docs/models/providers/fireworks-ai.md +30 -28
- package/.docs/models/providers/hyper.md +7 -13
- package/.docs/models/providers/inceptron.md +2 -2
- package/.docs/models/providers/kilo.md +25 -26
- package/.docs/models/providers/llmgateway-providers.md +16 -10
- package/.docs/models/providers/llmgateway.md +4 -4
- package/.docs/models/providers/morph.md +2 -1
- package/.docs/models/providers/nano-gpt.md +24 -21
- package/.docs/models/providers/novita-ai.md +4 -2
- package/.docs/models/providers/ollama-cloud.md +2 -1
- package/.docs/models/providers/opencode-go.md +3 -1
- package/.docs/models/providers/opencode.md +3 -2
- package/.docs/models/providers/prime.md +3 -3
- package/.docs/models/providers/tencent-token-plan.md +2 -1
- package/.docs/models/providers/tencent-tokenhub.md +2 -1
- package/.docs/models/providers/tinfoil.md +2 -1
- package/.docs/models/providers/wandb.md +3 -3
- package/.docs/reference/agents/agent.md +2 -0
- package/.docs/reference/agents/channels.md +38 -1
- package/.docs/reference/agents/durable-agent.md +37 -26
- package/.docs/reference/auth/neon.md +24 -15
- package/.docs/reference/cli/mastra.md +10 -1
- package/.docs/reference/client-js/agents.md +4 -4
- package/.docs/reference/client-js/observability.md +23 -1
- package/.docs/reference/connect/channels.md +55 -1
- package/.docs/reference/connect/providers.md +5 -3
- package/.docs/reference/connect/tools.md +29 -2
- package/.docs/reference/core/getGatewayById.md +14 -1
- package/.docs/reference/observability/tracing/advanced-queries.md +47 -58
- package/.docs/reference/pubsub/redis-streams.md +2 -0
- package/.docs/reference/streaming/agents/MastraModelOutput.md +6 -4
- package/.docs/reference/tools/mcp-server.md +6 -2
- package/.docs/reference/workflows/workflow.md +1 -1
- package/package.json +4 -4
- package/.docs/docs/mastra-platform/connect/channels.md +0 -165
- package/.docs/docs/mastra-platform/connect/overview.md +0 -102
- package/.docs/docs/mastra-platform/connect/providers.md +0 -66
- package/.docs/docs/mastra-platform/connect/tools.md +0 -151
|
@@ -51,7 +51,7 @@ The `channels` property accepts a `ChannelConfig` object with the following fiel
|
|
|
51
51
|
|
|
52
52
|
**threadContext** (`{ maxMessages?: number; addSystemMessage?: boolean }`): How the agent picks up context about the current thread. maxMessages sets how many platform messages are saved to memory on first mention: the thread's first message plus up to maxMessages - 1 recent messages, with an omitted-count marker between them when needed (set to 0 to disable; only applies to non-DM threads). addSystemMessage: false skips the built-in system message that tells the agent which channel/platform a request came from. (Default: `{ maxMessages: 10, addSystemMessage: true }`)
|
|
53
53
|
|
|
54
|
-
**chatOptions** (`Omit<ChatConfig, 'adapters' | 'state' | 'userName'>`): Additional options passed directly to the Chat SDK. Use for advanced configuration such as dedupeTtlMs, fallbackStreamingPlaceholderText, lockScope, and messageHistory.
|
|
54
|
+
**chatOptions** (`Omit<ChatConfig, 'adapters' | 'state' | 'userName'>`): Additional options passed directly to the Chat SDK. Use for advanced configuration such as dedupeTtlMs, fallbackStreamingPlaceholderText, lockScope, and messageHistory. logger defaults to the Mastra logger. Set it to use a different logger or a Chat SDK log level.
|
|
55
55
|
|
|
56
56
|
**resolveResourceId** (`(ctx: ResolveResourceIdContext) => string | Promise<string>`): Decide which resourceId owns resource-level memory for a channel thread, separately from who sent the message. Runs only when a new thread is created; reused threads keep their stored owner and never call the hook. Return ctx.defaultResourceId (${platform}:${message.author.userId}) to keep the built-in behavior.
|
|
57
57
|
|
|
@@ -480,6 +480,43 @@ type InlineLinkEntry =
|
|
|
480
480
|
| { match: string; mimeType: string } // Domain + forced mime type (skips HEAD)
|
|
481
481
|
```
|
|
482
482
|
|
|
483
|
+
## `toChatLogger()`
|
|
484
|
+
|
|
485
|
+
Adapts a Mastra logger to the Chat SDK `Logger` interface. Pass the result to an adapter's `logger` option so its logs go to the same logger as the rest of your app. See [Logging](https://mastra.ai/docs/channels) for when to use it.
|
|
486
|
+
|
|
487
|
+
```typescript
|
|
488
|
+
import { toChatLogger } from '@mastra/core/channels'
|
|
489
|
+
import { createDiscordAdapter } from '@chat-adapter/discord'
|
|
490
|
+
import { PinoLogger } from '@mastra/loggers'
|
|
491
|
+
|
|
492
|
+
const logger = new PinoLogger({ name: 'app', level: 'info' })
|
|
493
|
+
|
|
494
|
+
const discord = createDiscordAdapter({
|
|
495
|
+
logger: toChatLogger(logger, { component: 'discord', minLevel: 'warn' }),
|
|
496
|
+
})
|
|
497
|
+
```
|
|
498
|
+
|
|
499
|
+
**logger** (`IMastraLogger`): The Mastra logger that receives the records.
|
|
500
|
+
|
|
501
|
+
**options** (`ToChatLoggerOptions`): Options for the bridge.
|
|
502
|
+
|
|
503
|
+
**options.minLevel** (`'debug' | 'info' | 'warn' | 'error' | 'silent'`): Lowest level to forward. 'silent' forwards nothing. With the default, the Mastra logger's own level decides what gets written.
|
|
504
|
+
|
|
505
|
+
**options.component** (`string`): Written as the component field on each record. child(prefix) extends it, so chat-sdk becomes chat-sdk:discord.
|
|
506
|
+
|
|
507
|
+
Returns: a Chat SDK `Logger`.
|
|
508
|
+
|
|
509
|
+
Extra log arguments become fields on the record:
|
|
510
|
+
|
|
511
|
+
| Arguments | Fields |
|
|
512
|
+
| -------------------- | -------------------------------- |
|
|
513
|
+
| None | `component` |
|
|
514
|
+
| One `Error` | `error`, `component` |
|
|
515
|
+
| One non-array object | The object's fields, `component` |
|
|
516
|
+
| Anything else | `args`, `component` |
|
|
517
|
+
|
|
518
|
+
An `Error` passed directly or under an object's `error` key is normalized so it keeps its message and stack when serialized.
|
|
519
|
+
|
|
483
520
|
## Related
|
|
484
521
|
|
|
485
522
|
- [Channels overview](https://mastra.ai/docs/channels): Concepts, quickstart, and platform setup
|
|
@@ -41,28 +41,9 @@ const text = await output.text
|
|
|
41
41
|
cleanup()
|
|
42
42
|
```
|
|
43
43
|
|
|
44
|
-
###
|
|
44
|
+
### Plain Agent stream configuration
|
|
45
45
|
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
```typescript
|
|
49
|
-
import { Mastra } from '@mastra/core'
|
|
50
|
-
import { Agent } from '@mastra/core/agent'
|
|
51
|
-
|
|
52
|
-
const myAgent = new Agent({
|
|
53
|
-
id: 'my-agent',
|
|
54
|
-
name: 'My Agent',
|
|
55
|
-
instructions: 'You are a helpful assistant',
|
|
56
|
-
model: 'openai/gpt-6.1-sol',
|
|
57
|
-
durable: true, // or: { maxSteps: 10, cleanupTimeoutMs: 60_000 }
|
|
58
|
-
})
|
|
59
|
-
|
|
60
|
-
export const mastra = new Mastra({
|
|
61
|
-
agents: { myAgent },
|
|
62
|
-
})
|
|
63
|
-
```
|
|
64
|
-
|
|
65
|
-
`mastra.getAgent('myAgent')` returns the wrapped `DurableAgent`. Standalone agents (constructed but never registered on a `Mastra` instance) don't become durable. The wrapping is applied at registration.
|
|
46
|
+
The `durable` option on a plain `Agent` controls resumable streams only. It never wraps the agent or enables checkpoints. Use `createDurableAgent({ agent })` explicitly for durable execution, and pass execution options such as `maxSteps` and `shouldPersistSnapshot` to that factory.
|
|
66
47
|
|
|
67
48
|
## `createDurableAgent(options)`
|
|
68
49
|
|
|
@@ -86,7 +67,7 @@ Returns: `DurableAgent`
|
|
|
86
67
|
|
|
87
68
|
**cache** (`MastraServerCache | false`): Cache for stored stream events, which enables resumable streams. If omitted, the agent inherits the cache from the Mastra instance, or uses an InMemoryServerCache. Set to false to disable caching, which makes streams non-resumable.
|
|
88
69
|
|
|
89
|
-
**pubsub** (`PubSub`): PubSub instance for streaming events. (Default: `EventEmitterPubSub`)
|
|
70
|
+
**pubsub** (`PubSub`): PubSub instance for streaming events. Takes precedence over mastra.pubsub. When omitted, a registered agent publishes on mastra.pubsub and an unregistered agent uses an in-process EventEmitterPubSub. (Default: `mastra.pubsub, or EventEmitterPubSub when unregistered`)
|
|
90
71
|
|
|
91
72
|
**maxSteps** (`number`): Maximum number of steps for the agentic loop.
|
|
92
73
|
|
|
@@ -112,7 +93,7 @@ Returns: `EventedAgent` (a subclass of `DurableAgent`)
|
|
|
112
93
|
|
|
113
94
|
**cache** (`MastraServerCache | false`): Cache for stored stream events, which enables resumable streams. If omitted, the agent inherits the cache from the Mastra instance, or uses an InMemoryServerCache. Set to false to disable caching.
|
|
114
95
|
|
|
115
|
-
**pubsub** (`PubSub`): PubSub instance for streaming events. (Default: `EventEmitterPubSub`)
|
|
96
|
+
**pubsub** (`PubSub`): PubSub instance for streaming events. Once the agent is registered, evented run frames use mastra.pubsub instead, because evented steps publish there. (Default: `mastra.pubsub, or EventEmitterPubSub when unregistered`)
|
|
116
97
|
|
|
117
98
|
**maxSteps** (`number`): Maximum number of steps for the agentic loop.
|
|
118
99
|
|
|
@@ -132,7 +113,7 @@ The `DurableAgent` class accepts the same options as `createDurableAgent`, plus
|
|
|
132
113
|
|
|
133
114
|
**cache** (`MastraServerCache | false`): Cache for stored stream events. If omitted, inherits from the Mastra instance or uses an InMemoryServerCache. Set to false to disable caching.
|
|
134
115
|
|
|
135
|
-
**pubsub** (`PubSub`): PubSub instance for streaming events. (Default: `EventEmitterPubSub`)
|
|
116
|
+
**pubsub** (`PubSub`): PubSub instance for streaming events. Takes precedence over mastra.pubsub. When omitted, a registered agent publishes on mastra.pubsub and an unregistered agent uses an in-process EventEmitterPubSub. (Default: `mastra.pubsub, or EventEmitterPubSub when unregistered`)
|
|
136
117
|
|
|
137
118
|
**maxSteps** (`number`): Maximum number of steps for the agentic loop.
|
|
138
119
|
|
|
@@ -195,11 +176,41 @@ const { output } = await durableAgent.observe(runId, {
|
|
|
195
176
|
await output.text
|
|
196
177
|
```
|
|
197
178
|
|
|
198
|
-
The `offset` option is an inclusive, zero-based PubSub event index. It counts every cached event published to the run topic, including lifecycle events, rather than counting chunks.
|
|
179
|
+
The `offset` option is an inclusive, zero-based PubSub event index. It counts every cached event published to the run topic, including lifecycle events, rather than counting chunks. A chunk read from the run log carries the index of its event as `chunk.index`, on `stream()`, `observe()`, and the HTTP `/stream` and `/observe` endpoints. To resume after a dropped connection, pass `index + 1` of the last chunk that has an index, or omit `offset` if nothing arrived. Lifecycle events take an index but produce no chunk, so indexes have gaps and a chunk count isn't a valid offset.
|
|
180
|
+
|
|
181
|
+
Some chunks carry no `index`. The client builds `object` chunks itself rather than reading them from the log. An `abort` chunk is sent beside the `finish` of the same run-log entry, and only the `finish` carries the index, so a client that reconnects between the two gets the `abort` again.
|
|
182
|
+
|
|
183
|
+
A run that used a structuring model publishes its `object-result` to the run log, so that chunk carries an `index` and replays like any other. A core `observe()` caller holding the schema can also rebuild structured output from replayed text, but gets `object-result` only when it replays the text that produced it. HTTP `/observe` replays the log and doesn't rebuild it. To rebuild it after a reconnect, observe without an `offset` and skip chunks whose `index` you already processed. That replay also rebuilds `object` chunks you already received, and they have no `index` to skip by. Each `object` chunk is a snapshot of the object so far, so keep the latest one. Indexes come from the replay cache, so a chunk whose cache write failed, or any chunk when caching is off, has no `index`, so no offset can resume at it. Omitting `offset` replays whatever the transport itself retains, such as a Redis stream, and can repeat chunks you already received. The paragraphs below cover offsets past the end and transports without numeric offsets.
|
|
184
|
+
|
|
185
|
+
`index` is additive and `offset` keeps its meaning, so code that already passes a log position, or replays from `0`, needs no change. Code that passed a count of chunks received should switch to the last `index + 1`.
|
|
186
|
+
|
|
187
|
+
The following example records the resume offset while streaming and passes it to `observe()` after a reconnect:
|
|
188
|
+
|
|
189
|
+
```typescript
|
|
190
|
+
let offset: number | undefined
|
|
191
|
+
const { output } = await durableAgent.stream(messages, { runId })
|
|
192
|
+
for await (const chunk of output.fullStream) {
|
|
193
|
+
if (chunk.index === undefined) continue
|
|
194
|
+
offset = chunk.index + 1
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// After a dropped connection:
|
|
198
|
+
const { output: resumed } = await durableAgent.observe(runId, { offset })
|
|
199
|
+
```
|
|
199
200
|
|
|
200
201
|
A non-zero offset can skip earlier events. Aggregated values are built only from chunks delivered to that observer. If the offset skips earlier text deltas, `output.text` is partial and structured output may be incomplete or fail validation or parsing.
|
|
201
202
|
|
|
202
|
-
When the PubSub transport supports numeric offsets,
|
|
203
|
+
When the PubSub transport supports numeric offsets, the observer receives numbered events only when the published index reaches the requested offset. An offset beyond the highest retained index replays nothing and also skips live events with lower indexes.
|
|
204
|
+
|
|
205
|
+
An event without an `index`, such as one whose cache write failed, is delivered as it arrives whatever the offset.
|
|
206
|
+
|
|
207
|
+
If the retained log expires or is cleared and numbering restarts at `0` while an observer is attached, that observer resyncs to the new log and receives its events, including ones below the requested offset. Detection is best effort. If the cache can't be read at that moment, or the new log has numbered past the observer's position before its first event arrives, the observer can miss the restart and skip those events instead. An observer that reconnects after the restart with an offset from the old log can't tell the logs apart and skips the new log's events below that offset, so omit `offset` to replay the new log.
|
|
208
|
+
|
|
209
|
+
On a transport without numeric offset support, such as `RedisStreamsPubSub` with caching off, `observe()` with any offset, including `0`, starts with new live events and doesn't replay retained events. This is the same in core and over HTTP `/observe`. Omit `offset` to replay them. (HTTP `/observe` on a plain `Agent` replays the retained events instead, which can repeat events already received.)
|
|
210
|
+
|
|
211
|
+
Indexed replay is limited to events still available in the configured cache. The cache has nothing to replay when caching is disabled, `shouldCache` excludes the run topic, or retained events have been cleared. Omitting `offset` then replays only what the transport itself retains, if anything.
|
|
212
|
+
|
|
213
|
+
A failed cache write loses only that event from the cache. It has no `index`, and the events written before and after it still replay when the cache numbers and appends an event in one step. The in-memory and Valkey caches always do. `RedisServerCache` does while Redis scripting works, and switches to two steps when the client has no `eval` or Redis Cluster rejects the script with `CROSSSLOT`. A custom cache that keeps the default `listPushIndexed()` also takes two steps. A two-step cache can leave a gap that makes offset replay skip later events, so replay such a log without an `offset` and skip indexes already processed. Cache replay can't recover an event the cache never stored. A transport that retains it, such as `RedisStreamsPubSub`, can still deliver it without an `index`.
|
|
203
214
|
|
|
204
215
|
An evented agent (`createEventedAgent()`) on a cross-process PubSub, such as Redis Streams, numbers its events only when every process shares the server cache. Configure a shared cache such as `RedisServerCache` on the `Mastra` instance. With the default in-memory server cache, events aren't numbered, so an offset can't skip them: the observer can receive events from before the offset again, and Mastra logs a warning.
|
|
205
216
|
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
|
|
5
5
|
# `MastraAuthNeon` and `MastraRBACNeon`
|
|
6
6
|
|
|
7
|
-
[`MastraAuthNeon`](https://github.com/mastra-ai/mastra/tree/main/auth/neon) connects Mastra authentication to [Neon Auth](https://neon.com/docs/guides/neon-auth). It
|
|
7
|
+
[`MastraAuthNeon`](https://github.com/mastra-ai/mastra/tree/main/auth/neon) connects Mastra authentication to [Neon Auth](https://neon.com/docs/guides/neon-auth). It verifies Neon Auth JWTs sent as bearer tokens with Neon Auth's JWKS endpoint and validates Neon Auth session cookies through its session API. The provider also supports email-and-password sign-in, sign-up, and session management.
|
|
8
8
|
|
|
9
9
|
`MastraRBACNeon` maps Neon Auth organization roles to Mastra permissions. Register it separately when your application uses Neon Auth organization memberships for role-based access control.
|
|
10
10
|
|
|
@@ -34,7 +34,9 @@ export const mastra = new Mastra({
|
|
|
34
34
|
})
|
|
35
35
|
```
|
|
36
36
|
|
|
37
|
-
Set `NEON_AUTH_BASE_URL` to
|
|
37
|
+
Set `NEON_AUTH_BASE_URL` to the Neon Auth URL shown in the Neon Console, for example `https://ep-example-123456.neonauth.us-east-2.aws.neon.tech/neondb/auth`. You can also pass `baseUrl` directly to both constructors.
|
|
38
|
+
|
|
39
|
+
Visit the [Neon integration guide](https://mastra.ai/integrations/auth/neon) for setup steps.
|
|
38
40
|
|
|
39
41
|
## `MastraAuthNeon`
|
|
40
42
|
|
|
@@ -42,13 +44,13 @@ Set `NEON_AUTH_BASE_URL` to your Neon Auth service URL. You can also pass `baseU
|
|
|
42
44
|
|
|
43
45
|
The `MastraAuthNeon` constructor accepts an optional `MastraAuthNeonOptions` object.
|
|
44
46
|
|
|
45
|
-
**baseUrl** (`string`): Neon Auth
|
|
47
|
+
**baseUrl** (`string`): Neon Auth URL, including the database path (for example /neondb/auth). Falls back to the NEON_AUTH_BASE_URL environment variable. Trailing slashes are removed. The JWT issuer and audience must equal the origin of this URL.
|
|
46
48
|
|
|
47
|
-
**jwksUrl** (`string`): JWKS endpoint used to verify bearer tokens. Falls back to NEON_AUTH_JWKS_URL, then \<baseUrl
|
|
49
|
+
**jwksUrl** (`string`): JWKS endpoint used to verify bearer tokens. Falls back to NEON_AUTH_JWKS_URL, then \<baseUrl>/.well-known/jwks.json.
|
|
48
50
|
|
|
49
|
-
**sessionCookieName** (`string`): Name of the Neon Auth session cookie. Defaults to
|
|
51
|
+
**sessionCookieName** (`string`): Name of the Neon Auth session cookie. Defaults to \_\_Secure-neon-auth.session_token.
|
|
50
52
|
|
|
51
|
-
**signUpEnabled** (`boolean`): Whether credentials-based sign-up is enabled. Defaults to true.
|
|
53
|
+
**signUpEnabled** (`boolean`): Whether credentials-based sign-up is enabled. When false, signUp() throws and no Neon Auth account is created. Defaults to true.
|
|
52
54
|
|
|
53
55
|
**name** (`string`): Provider name. Defaults to neon.
|
|
54
56
|
|
|
@@ -74,7 +76,9 @@ The `MastraAuthNeon` constructor accepts an optional `MastraAuthNeonOptions` obj
|
|
|
74
76
|
await auth.authenticateToken(token, request)
|
|
75
77
|
```
|
|
76
78
|
|
|
77
|
-
Verifies
|
|
79
|
+
Verifies a JWT-shaped token against the configured JWKS endpoint, checking its signature, issuer, audience, and expiry. Otherwise, validates the Neon Auth session cookie from the request through the session API. If JWT verification fails, the session cookie is still accepted, so an expired bearer token doesn't sign out a client that also sends cookies. When the request has no session cookie, a non-JWT token is treated as the session cookie value. Returns the authenticated `NeonAuthUser`, or `null` when validation fails.
|
|
80
|
+
|
|
81
|
+
`NeonAuthUser` contains the top-level `id`, `email`, and `name`, the Neon Auth `user` object, and either the `session` (cookie authentication) or the verified `jwt` claims (bearer authentication).
|
|
78
82
|
|
|
79
83
|
#### `authorizeUser()`
|
|
80
84
|
|
|
@@ -92,7 +96,7 @@ Runs the configured custom authorization function when one is provided. Otherwis
|
|
|
92
96
|
const result = await auth.signIn(email, password, request)
|
|
93
97
|
```
|
|
94
98
|
|
|
95
|
-
Authenticates email-and-password credentials through Neon Auth. Returns the authenticated user,
|
|
99
|
+
Authenticates email-and-password credentials through Neon Auth. Returns the authenticated user, a Neon Auth JWT as `token`, and the Neon Auth session cookies. Neon Auth must trust the origin of the incoming request.
|
|
96
100
|
|
|
97
101
|
#### `signUp()`
|
|
98
102
|
|
|
@@ -100,7 +104,7 @@ Authenticates email-and-password credentials through Neon Auth. Returns the auth
|
|
|
100
104
|
const result = await auth.signUp(email, password, name, request)
|
|
101
105
|
```
|
|
102
106
|
|
|
103
|
-
Creates a Neon Auth account using email-and-password credentials. `name` is optional
|
|
107
|
+
Creates a Neon Auth account using email-and-password credentials. `name` is optional. When omitted, the provider derives a display name from the email address. Returns the same result as `signIn()`.
|
|
104
108
|
|
|
105
109
|
#### `isSignUpEnabled()`
|
|
106
110
|
|
|
@@ -139,10 +143,13 @@ Validates the session through Neon Auth. Neon Auth refreshes sessions automatica
|
|
|
139
143
|
#### `destroySession()`
|
|
140
144
|
|
|
141
145
|
```typescript
|
|
142
|
-
|
|
146
|
+
const sessionId = auth.getSessionIdFromRequest(request)
|
|
147
|
+
if (sessionId) await auth.destroySession(sessionId)
|
|
143
148
|
```
|
|
144
149
|
|
|
145
|
-
|
|
150
|
+
Pass the signed session cookie value from `getSessionIdFromRequest()`, not the `id` returned by `validateSession()`. `destroySession()` attempts to revoke that session through the Neon Auth sign-out endpoint. A network error or non-2xx response can leave the session active, and the method doesn't throw for these failures. When Mastra sends the header from `getClearSessionHeaders()`, it clears the matching cookie on the Mastra host, not a cookie on a separate Neon Auth host. A separate Neon Auth session can remain active after Studio sign-out.
|
|
151
|
+
|
|
152
|
+
Revoking a session doesn't invalidate an already-issued JWT. Bearer tokens that pass JWT verification can still authenticate because verification doesn't check the Neon Auth session. JWT verification doesn't require an expiration claim, so a token without one may remain usable after sign-out.
|
|
146
153
|
|
|
147
154
|
## `MastraRBACNeon`
|
|
148
155
|
|
|
@@ -152,11 +159,11 @@ The `MastraRBACNeon` constructor accepts a `MastraRBACNeonOptions` object.
|
|
|
152
159
|
|
|
153
160
|
**roleMapping** (`RoleMapping`): Maps Neon Auth role names to Mastra permission patterns. Use \_default to define permissions for unmapped roles.
|
|
154
161
|
|
|
155
|
-
**baseUrl** (`string`): Neon Auth
|
|
162
|
+
**baseUrl** (`string`): Neon Auth URL. Falls back to the NEON_AUTH_BASE_URL environment variable. Trailing slashes are removed.
|
|
156
163
|
|
|
157
|
-
**organizationId** (`string`):
|
|
164
|
+
**organizationId** (`string`): Organization whose membership role is used. Defaults to the active organization of the session.
|
|
158
165
|
|
|
159
|
-
**getUserRoles** (`(user: NeonAuthUser) => Promise<string[]> | string[]`): Custom function
|
|
166
|
+
**getUserRoles** (`(user: NeonAuthUser) => Promise<string[]> | string[]`): Custom function that returns role names for a user. Use it to assign roles to bearer JWT requests, which carry no organization roles.
|
|
160
167
|
|
|
161
168
|
**cache** (`{ ttlMs?: number; maxSize?: number }`): Role lookup cache configuration. The defaults are 60,000 ms and 1,000 entries.
|
|
162
169
|
|
|
@@ -168,7 +175,9 @@ The `MastraRBACNeon` constructor accepts a `MastraRBACNeonOptions` object.
|
|
|
168
175
|
const roles = await rbac.getRoles(user)
|
|
169
176
|
```
|
|
170
177
|
|
|
171
|
-
Returns roles from the configured `getUserRoles` function, the user's
|
|
178
|
+
Returns roles from the configured `getUserRoles` function when provided. Otherwise, when `organizationId` is set or the session has an active organization, returns the user's role in that organization, read from Neon Auth with the user's session cookie. Non-members get no roles. Without an organization, returns the user's Neon Auth role, such as `user` or `admin`.
|
|
179
|
+
|
|
180
|
+
Bearer JWT requests have no session, so they get no roles unless `getUserRoles` is provided. The JWT `role` claim (`authenticated`) is never used as a Mastra role.
|
|
172
181
|
|
|
173
182
|
#### `hasRole()`
|
|
174
183
|
|
|
@@ -877,6 +877,8 @@ Manages authentication for Mastra platform. Credentials are stored in `~/.mastra
|
|
|
877
877
|
|
|
878
878
|
Opens a browser for login and stores the credentials locally.
|
|
879
879
|
|
|
880
|
+
When browser sign-in is needed and there's no interactive terminal (in CI, when input or output is piped, or in an agent's shell), the command first prints how to authenticate headless shells, then still waits for browser sign-in. On the same machine, you can run `mastra auth login` once in your own terminal so later commands reuse the saved session. In CI or on another machine, set `MASTRA_API_TOKEN` and `MASTRA_ORG_ID` instead. Create the token from a signed-in terminal with [`mastra auth tokens create`](#mastra-auth-tokens-create) or in the dashboard. If the browser sign-in wait times out, the command exits with status 1. If `MASTRA_API_TOKEN` is already set in a non-interactive shell, the command skips browser sign-in: it verifies the token and checks that an organization is selected (from `MASTRA_ORG_ID` or saved credentials), then exits with status 0. If either check fails, it exits with status 1 and names what's missing.
|
|
881
|
+
|
|
880
882
|
### `mastra auth logout`
|
|
881
883
|
|
|
882
884
|
Removes stored credentials. If `MASTRA_API_TOKEN` is still set in the environment, the CLI warns that it will continue to be used.
|
|
@@ -943,7 +945,7 @@ Connects a provider to the project. When the organization already has connection
|
|
|
943
945
|
|
|
944
946
|
OAuth providers open the provider's consent screen in your browser and print its URL if you need to open it manually. API key and Basic auth providers prompt for credentials in the terminal and verify them before completing the connection. Providers with other auth types open a hosted connect page. The command waits until the connection becomes active before exiting.
|
|
945
947
|
|
|
946
|
-
Credential prompts require an interactive terminal, even with `--yes`. Run the command outside CI or connect through the platform UI.
|
|
948
|
+
Credential prompts require an interactive terminal, even with `--yes`. Run the command outside CI or connect through the platform UI. Each provider's [integration page](https://mastra.ai/docs/mastra-platform/connect) lists its API key and permission requirements.
|
|
947
949
|
|
|
948
950
|
Once a new connection is active, the command offers to set a display name so you can tell connections to the same provider apart. It lists the provider's existing connections, suggests a name that doesn't collide with them, and asks for confirmation if the chosen name duplicates another connection's name. Leave the field blank to skip naming. Setting a display name requires the organization admin role; if naming fails, the connection remains active.
|
|
949
951
|
|
|
@@ -1266,6 +1268,13 @@ Errors are written to `stderr` as JSON and return a non-zero exit code:
|
|
|
1266
1268
|
}
|
|
1267
1269
|
```
|
|
1268
1270
|
|
|
1271
|
+
The exit code reflects whether the request succeeded, not the contents of the response:
|
|
1272
|
+
|
|
1273
|
+
- `0`: The server returned a successful response. This includes empty results and payloads that report existing state, such as a tool result saying a record already exists. A tool that returns an object with an `error` field still exits `0`, so check the `data` payload when the tool reports its own failures.
|
|
1274
|
+
- `1`: The request failed. This includes an unreachable server, invalid JSON input, a missing resource, or a tool that throws an error.
|
|
1275
|
+
|
|
1276
|
+
If the command reading the output exits early, as with `| head`, the exit code still reflects whether the request succeeded.
|
|
1277
|
+
|
|
1269
1278
|
### Target resolution
|
|
1270
1279
|
|
|
1271
1280
|
For runtime commands, the command resolves the target server in this order:
|
|
@@ -914,9 +914,9 @@ const agent = await mastraClient.createStoredAgent({
|
|
|
914
914
|
})
|
|
915
915
|
```
|
|
916
916
|
|
|
917
|
-
####
|
|
917
|
+
#### Resumable streams for stored agents
|
|
918
918
|
|
|
919
|
-
Set `durable` to
|
|
919
|
+
Set `durable` to configure [resumable streams](https://mastra.ai/docs/agents/resumable-streams) on the hydrated plain agent. Pass `true` to enable streams, `false` to disable them, or an object to tune stream cleanup:
|
|
920
920
|
|
|
921
921
|
```typescript
|
|
922
922
|
const agent = await mastraClient.createStoredAgent({
|
|
@@ -927,11 +927,11 @@ const agent = await mastraClient.createStoredAgent({
|
|
|
927
927
|
provider: 'openai',
|
|
928
928
|
name: 'gpt-5.4',
|
|
929
929
|
},
|
|
930
|
-
durable: {
|
|
930
|
+
durable: { cleanupTimeoutMs: 0 },
|
|
931
931
|
})
|
|
932
932
|
```
|
|
933
933
|
|
|
934
|
-
Only serializable options are accepted
|
|
934
|
+
Only serializable options are accepted, with cache and pubsub inherited from the server's `Mastra` instance. Existing stored agents with `durable: true` also use this field for resumable streams only. To retain durable execution and checkpoint recovery, register a code agent wrapped with `createDurableAgent({ agent })`.
|
|
935
935
|
|
|
936
936
|
### `getStoredAgent()`
|
|
937
937
|
|
|
@@ -115,7 +115,7 @@ if (capabilities.spanAggregate) {
|
|
|
115
115
|
|
|
116
116
|
The request and response structure follows `aggregateTraces()`, with direct span predicates and span dimensions such as `spanType`, `name`, and `parentEntityName`. Token and cost measures belong to the span that recorded the usage and aren't added to parent spans. Check `capabilities.spanAggregate` before calling, and `capabilities.spanAggregateModelDimensions` before grouping or counting distinct values by `model` or `provider`. With an older adapter, those requests return `501`.
|
|
117
117
|
|
|
118
|
-
Both `aggregateTraces()` and `aggregateSpans()` accept `timeToFirstToken.*` and `timeToFirstChunk
|
|
118
|
+
Both `aggregateTraces()` and `aggregateSpans()` accept time to first token (TTFT) and time to first chunk (TTFC) measures, `timeToFirstToken.*` and `timeToFirstChunk.*`, when `capabilities.aggregateTimeToFirstMeasures` is `true`. Spans and traces without a recorded value are skipped, never counted as 0. See [Time to first chunk (TTFC)](https://mastra.ai/reference/observability/tracing/advanced-queries) and [Time to first token (TTFT)](https://mastra.ai/reference/observability/tracing/advanced-queries).
|
|
119
119
|
|
|
120
120
|
See [Aggregate spans](https://mastra.ai/reference/observability/tracing/advanced-queries) for selection, dimensions, per-span usage, and how to list the spans behind a group.
|
|
121
121
|
|
|
@@ -403,6 +403,16 @@ const scores = await mastraClient.listScoresBySpan({
|
|
|
403
403
|
})
|
|
404
404
|
```
|
|
405
405
|
|
|
406
|
+
## Get a score by ID
|
|
407
|
+
|
|
408
|
+
Use `getScore()` to retrieve one observability score:
|
|
409
|
+
|
|
410
|
+
```typescript
|
|
411
|
+
const { score } = await mastraClient.getScore('score-id-123')
|
|
412
|
+
```
|
|
413
|
+
|
|
414
|
+
The response is `{ score: record | null }`. A missing score returns HTTP 200 with `{ score: null }`. The return type is `GetScoreResponse`, exported from `@mastra/client-js`.
|
|
415
|
+
|
|
406
416
|
## Creating scores
|
|
407
417
|
|
|
408
418
|
Create a score for a trace, optionally identifying a span within it:
|
|
@@ -424,6 +434,18 @@ const response = await mastraClient.createScore({
|
|
|
424
434
|
|
|
425
435
|
Feedback methods create, list, and query human-in-the-loop signals such as ratings, thumbs, comments, and corrections through the configured API server. Create methods support OSS and Platform. Full replacement uses Platform's PUT endpoint. See the [feedback guide](https://mastra.ai/docs/observability/feedback) for examples and the [feedback reference](https://mastra.ai/reference/observability/feedback) for full schemas.
|
|
426
436
|
|
|
437
|
+
### Get feedback by ID
|
|
438
|
+
|
|
439
|
+
Use `getFeedback()` to retrieve one feedback record:
|
|
440
|
+
|
|
441
|
+
```typescript
|
|
442
|
+
const { feedback } = await mastraClient.getFeedback('feedback-id-123')
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
The response is `{ feedback: record | null }`. A missing record returns HTTP 200 with `{ feedback: null }`. The return type is `GetFeedbackResponse`, exported from `@mastra/client-js`.
|
|
446
|
+
|
|
447
|
+
Both getters accept an unencoded ID and encode it as a URL path segment. They use the client's configured API prefix, credentials, and headers. Record timestamps are ISO strings in the JSON response.
|
|
448
|
+
|
|
427
449
|
### Creating feedback
|
|
428
450
|
|
|
429
451
|
Create a feedback record for a trace, optionally identifying a span within it:
|
|
@@ -18,7 +18,7 @@ export const mastra = new Mastra({
|
|
|
18
18
|
|
|
19
19
|
Returns: `Promise<ChannelsResolver>`. See [The resolver](#the-resolver).
|
|
20
20
|
|
|
21
|
-
|
|
21
|
+
Each provider's integration page covers its channel setup: [Slack](https://mastra.ai/integrations/channels/slack), [Telegram](https://mastra.ai/integrations/channels/telegram), [Discord](https://mastra.ai/integrations/channels/discord), and [Microsoft Teams](https://mastra.ai/integrations/channels/teams). Their implementations come from `@mastra/slack`, `@mastra/telegram`, `@mastra/discord`, and `@mastra/teams`, loaded on demand. Use those packages directly to configure a channel outside the platform connection flow.
|
|
22
22
|
|
|
23
23
|
The Teams provider encrypts stored bot secrets with `MASTRA_ENCRYPTION_KEY` when set. When it isn't, the key is derived from the platform access token and a warning is logged while a Teams connection is active. Rotating the platform access token makes stored bot credentials unreadable (disconnect and reconnect to re-provision). Projects without a Teams connection are unaffected.
|
|
24
24
|
|
|
@@ -62,6 +62,60 @@ Providers without an active connection don't appear in the resolved map. Their r
|
|
|
62
62
|
|
|
63
63
|
Failure handling matches [`tools()`](https://mastra.ai/reference/connect/tools): configuration errors (missing project ID, bad `ttlMs`, an unknown or malformed provider ID, both spellings of the Slack key) reject at call time, while per-provider problems (provider construction failure, `needs_reauth`, credential sync failure) are downgraded to warn-and-skip. Several active connections for one provider aren't a skip: the resolver warns and uses the first, and `providers.<id>.connectionId` pins the choice. The initial resolution rejects if its platform fetch fails. A failed background refresh warns and preserves the cached snapshot, while an explicit `refresh()` rejects on fetch failure.
|
|
64
64
|
|
|
65
|
+
## Combine with self-managed channels
|
|
66
|
+
|
|
67
|
+
`channels()` replaces the whole `channels` option, and there is no built-in helper to merge it with providers you construct yourself. To use Connect for some channels and manage another yourself, wrap both in one resolver. The wrapper must stay callable and expose a `getRoutes()` that returns every provider's routes, because Mastra mounts channel routes once at construction:
|
|
68
|
+
|
|
69
|
+
```typescript
|
|
70
|
+
import { Mastra } from '@mastra/core'
|
|
71
|
+
import { channels } from '@mastra/connect'
|
|
72
|
+
import { TelegramProvider } from '@mastra/telegram'
|
|
73
|
+
import { assistant } from './agents/assistant'
|
|
74
|
+
|
|
75
|
+
const connectChannels = await channels({ providers: ['slack', 'discord'] })
|
|
76
|
+
const telegram = new TelegramProvider()
|
|
77
|
+
|
|
78
|
+
export const mastra = new Mastra({
|
|
79
|
+
agents: { assistant },
|
|
80
|
+
channels: Object.assign(async () => ({ ...(await connectChannels()), telegram }), {
|
|
81
|
+
getRoutes: () => [...connectChannels.getRoutes(), ...telegram.getRoutes()],
|
|
82
|
+
}),
|
|
83
|
+
})
|
|
84
|
+
```
|
|
85
|
+
|
|
86
|
+
Exclude the self-managed channel from the Connect selection, as the array form does here. Mastra doesn't detect two providers that register the same route, so a channel enabled in both places mounts conflicting webhooks. Create the self-managed provider once, outside the wrapper: Mastra attaches each distinct provider instance only once. Configure its credentials as described in the [Telegram provider reference](https://mastra.ai/reference/channels/telegram-provider).
|
|
87
|
+
|
|
88
|
+
## Vary tools by channel
|
|
89
|
+
|
|
90
|
+
Channel messages put a [`ChannelContext`](https://mastra.ai/integrations/channels/slack) on the [request context](https://mastra.ai/docs/server/request-context) under the `channel` key. It includes the platform, whether the conversation is a direct message (`isDM`), channel and thread IDs, and the sender's user ID and name. An agent's `tools` function can read it to filter the record that [`tools()`](https://mastra.ai/reference/connect/tools) resolves:
|
|
91
|
+
|
|
92
|
+
```typescript
|
|
93
|
+
import { Agent } from '@mastra/core/agent'
|
|
94
|
+
import type { ChannelContext } from '@mastra/core/channels'
|
|
95
|
+
import { tools } from '@mastra/connect'
|
|
96
|
+
|
|
97
|
+
const connectTools = tools({ providers: ['linear'] })
|
|
98
|
+
const readTools = new Set(['linear_list_issues'])
|
|
99
|
+
|
|
100
|
+
export const assistant = new Agent({
|
|
101
|
+
id: 'assistant',
|
|
102
|
+
name: 'assistant',
|
|
103
|
+
instructions: 'You help the team track work in Linear from Slack and Discord.',
|
|
104
|
+
model: 'openai/gpt-6-luna',
|
|
105
|
+
tools: async ctx => {
|
|
106
|
+
const channel = ctx.requestContext?.get('channel') as ChannelContext | undefined
|
|
107
|
+
const all = await connectTools(ctx)
|
|
108
|
+
|
|
109
|
+
if (channel?.isDM && ctx.requestContext?.get('role') === 'operator') {
|
|
110
|
+
return all
|
|
111
|
+
}
|
|
112
|
+
return Object.fromEntries(Object.entries(all).filter(([key]) => readTools.has(key)))
|
|
113
|
+
},
|
|
114
|
+
})
|
|
115
|
+
```
|
|
116
|
+
|
|
117
|
+
Here, only direct messages from users your application identifies as operators get the full Linear toolset. Other requests get only `linear_list_issues`. Set `role` in trusted server-side code after you verify the sender's identity and permissions. Don't grant write access based on conversation type alone. To filter by options instead of post-processing, see [per-request options](https://mastra.ai/reference/connect/tools).
|
|
118
|
+
|
|
65
119
|
## Discord permissions
|
|
66
120
|
|
|
67
121
|
The Discord bot-invite URL requests the `bot` and `applications.commands` scopes with these permissions:
|
|
@@ -8,7 +8,7 @@ This page documents generated toolsets for 28 providers (1076 tools in this vers
|
|
|
8
8
|
|
|
9
9
|
Tool keys are stable identifiers of the form `<provider>_<action>` and are the values accepted by `allowTools` and `disallowTools`. Toolsets are versioned with the package: the exact list depends on the installed `@mastra/connect` version, and this page reflects the version it was generated from.
|
|
10
10
|
|
|
11
|
-
MCP providers (Attio, Canva, Clay, Neon, Render, Robinhood, and Sanity) serve their tools from their hosted MCP servers at runtime and aren't listed here. See [MCP providers](https://mastra.ai/
|
|
11
|
+
MCP providers ([Attio](https://mastra.ai/integrations/crm/attio), [Canva](https://mastra.ai/integrations/other/canva), [Clay](https://mastra.ai/integrations/crm/clay), [Neon](https://mastra.ai/integrations/databases/neon), [Render](https://mastra.ai/integrations/deploy/render), [Robinhood](https://mastra.ai/integrations/other/robinhood), and [Sanity](https://mastra.ai/integrations/other/sanity)) serve their tools from their hosted MCP servers at runtime and aren't listed here. See [MCP providers](https://mastra.ai/reference/connect/tools) for how `tools()` discovers them.
|
|
12
12
|
|
|
13
13
|
| Provider | Provider ID | Tools |
|
|
14
14
|
| ----------------------------------------------------------------------------------------------------------------------- | ---------------------- | ----- |
|
|
@@ -30,9 +30,9 @@ MCP providers (Attio, Canva, Clay, Neon, Render, Robinhood, and Sanity) serve th
|
|
|
30
30
|
|  [Microsoft Teams](#microsoft-teams) | `microsoft-teams` | 25 |
|
|
31
31
|
|  [Microsoft Word](#microsoft-word) | `microsoft-word` | 18 |
|
|
32
32
|
|  [Notion](#notion) | `notion` | 44 |
|
|
33
|
-
| [OneDrive](#onedrive)
|
|
33
|
+
|  [OneDrive](#onedrive) | `one-drive` | 20 |
|
|
34
34
|
|  [OpenAI](#openai) | `openai` | 26 |
|
|
35
|
-
|  [Microsoft Outlook](#microsoft-outlook) | `outlook` | 30 |
|
|
36
36
|
|  [PostHog](#posthog) | `posthog` | 67 |
|
|
37
37
|
|  [Resend](#resend) | `resend` | 80 |
|
|
38
38
|
|  [SharePoint Online](#sharepoint-online) | `sharepoint-online` | 53 |
|
|
@@ -1010,6 +1010,8 @@ Provider ID: `posthog` · 67 tools
|
|
|
1010
1010
|
|
|
1011
1011
|
Provider ID: `resend` · 80 tools
|
|
1012
1012
|
|
|
1013
|
+
> **Note:** Connect Resend with an API key that has **Full access** permission. A **Sending access** key fails to connect because Mastra checks a new key by listing your domains, which sending access keys can't do.
|
|
1014
|
+
|
|
1013
1015
|
| Tool | Description |
|
|
1014
1016
|
| ---------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
1015
1017
|
| `resend_add_contact_to_segment` | Add a contact to a segment in Resend. |
|
|
@@ -21,7 +21,7 @@ export const opsAgent = new Agent({
|
|
|
21
21
|
|
|
22
22
|
Returns: `ToolsResolver`, a resolver producing a flat tool record keyed by tool key (for example `linear_create_issue`). See [The resolver](#the-resolver).
|
|
23
23
|
|
|
24
|
-
See [Connect](https://mastra.ai/docs/mastra-platform/connect
|
|
24
|
+
See [Connect](https://mastra.ai/docs/mastra-platform/connect) to get started.
|
|
25
25
|
|
|
26
26
|
## Parameters
|
|
27
27
|
|
|
@@ -108,7 +108,34 @@ The resolver also exposes methods for manual control:
|
|
|
108
108
|
|
|
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
|
-
- `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 [
|
|
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
|
+
|
|
113
|
+
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
|
+
```typescript
|
|
116
|
+
import { Agent } from '@mastra/core/agent'
|
|
117
|
+
import { tools } from '@mastra/connect'
|
|
118
|
+
|
|
119
|
+
const connectTools = tools({ providers: ['linear'] })
|
|
120
|
+
const viewerTools = new Set(['linear_list_issues'])
|
|
121
|
+
|
|
122
|
+
export const opsAgent = new Agent({
|
|
123
|
+
id: 'ops',
|
|
124
|
+
name: 'ops',
|
|
125
|
+
instructions: 'You help the team track work in Linear.',
|
|
126
|
+
model: 'openai/gpt-6-luna',
|
|
127
|
+
tools: async ctx => {
|
|
128
|
+
const all = await connectTools(ctx)
|
|
129
|
+
|
|
130
|
+
if (ctx.requestContext?.get('role') === 'admin') {
|
|
131
|
+
return all
|
|
132
|
+
}
|
|
133
|
+
return Object.fromEntries(Object.entries(all).filter(([key]) => viewerTools.has(key)))
|
|
134
|
+
},
|
|
135
|
+
})
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
Only the `admin` role gets every tool. Any other or missing role gets the viewer subset. Set `role` in trusted server-side code based on the authenticated user. [Vary tools by channel](https://mastra.ai/reference/connect/channels) applies the same pattern to channel messages.
|
|
112
139
|
|
|
113
140
|
Error handling depends on the cause:
|
|
114
141
|
|
|
@@ -34,7 +34,20 @@ console.log(gateway.name) // 'My Custom Gateway'
|
|
|
34
34
|
|
|
35
35
|
## Returns
|
|
36
36
|
|
|
37
|
-
**gateway** (`
|
|
37
|
+
**gateway** (`MastraModelGatewayInterface`): The gateway instance
|
|
38
|
+
|
|
39
|
+
## Throws
|
|
40
|
+
|
|
41
|
+
Throws a `MastraError` with ID `MASTRA_GET_GATEWAY_BY_ID_NOT_FOUND` if no registered gateway has the specified ID. Wrap the call in `try`/`catch` when the gateway might not be registered:
|
|
42
|
+
|
|
43
|
+
```typescript
|
|
44
|
+
let gateway
|
|
45
|
+
try {
|
|
46
|
+
gateway = mastra.getGatewayById('my-custom-gateway')
|
|
47
|
+
} catch {
|
|
48
|
+
// Gateway is not registered
|
|
49
|
+
}
|
|
50
|
+
```
|
|
38
51
|
|
|
39
52
|
## Related
|
|
40
53
|
|