@mastra/mcp 2.5.0 → 2.6.0-alpha.1

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.
Files changed (40) hide show
  1. package/dist/cli/generate-D0K0N5WQ.js +218 -0
  2. package/dist/cli/generate-D0K0N5WQ.js.map +1 -0
  3. package/dist/cli/generate.d.ts +18 -0
  4. package/dist/cli/generate.d.ts.map +1 -0
  5. package/dist/cli/index.d.ts +3 -0
  6. package/dist/cli/index.d.ts.map +1 -0
  7. package/dist/cli/index.js +32 -0
  8. package/dist/cli/index.js.map +1 -0
  9. package/dist/cli/json-schema-dialect-CdIOPBiC.js +132 -0
  10. package/dist/cli/json-schema-dialect-CdIOPBiC.js.map +1 -0
  11. package/dist/cli/typegen-B5dH_z0t.js +363 -0
  12. package/dist/cli/typegen-B5dH_z0t.js.map +1 -0
  13. package/dist/cli/typegen.d.ts +14 -0
  14. package/dist/cli/typegen.d.ts.map +1 -0
  15. package/dist/client/client.d.ts +2 -1
  16. package/dist/client/client.d.ts.map +1 -1
  17. package/dist/client/configuration.d.ts +30 -10
  18. package/dist/client/configuration.d.ts.map +1 -1
  19. package/dist/client/index.d.ts +1 -1
  20. package/dist/client/index.d.ts.map +1 -1
  21. package/dist/client/types.d.ts +38 -1
  22. package/dist/client/types.d.ts.map +1 -1
  23. package/dist/docs/SKILL.md +2 -3
  24. package/dist/docs/assets/SOURCE_MAP.json +1 -1
  25. package/dist/docs/references/docs-connections-mcp.md +159 -50
  26. package/dist/docs/references/docs-connections-overview.md +1 -1
  27. package/dist/docs/references/docs-guides-mcp-authentication-authorization.md +2 -2
  28. package/dist/docs/references/reference-migrations-mcp-v2.md +1 -1
  29. package/dist/docs/references/reference-tools-mcp-client.md +207 -16
  30. package/dist/docs/references/reference-tools-mcp-server.md +9 -7
  31. package/dist/index.cjs +270 -257
  32. package/dist/index.cjs.map +1 -1
  33. package/dist/index.js +269 -255
  34. package/dist/index.js.map +1 -1
  35. package/dist/server/server.d.ts +13 -1
  36. package/dist/server/server.d.ts.map +1 -1
  37. package/dist/shared/json-schema-dialect.d.ts +34 -0
  38. package/dist/shared/json-schema-dialect.d.ts.map +1 -1
  39. package/package.json +25 -20
  40. package/dist/docs/references/docs-guides-mcp-events.md +0 -306
@@ -1,8 +1,43 @@
1
1
  import type { IOType } from 'node:child_process';
2
2
  import type { RequestContext } from '@mastra/core/di';
3
- import type { StreamableHTTPClientTransportOptions, ClientCapabilities, ElicitRequestParams, ElicitResult, LoggingLevel, ProgressNotification, ToolAnnotations, jsonSchemaValidator } from '@modelcontextprotocol/client';
3
+ import type { Tool } from '@mastra/core/tools';
4
+ import type { CallToolResult, StreamableHTTPClientTransportOptions, ClientCapabilities, ElicitRequestParams, ElicitResult, LoggingLevel, ProgressNotification, ToolAnnotations, jsonSchemaValidator } from '@modelcontextprotocol/client';
4
5
  import type { MCPTraceContext } from '../shared/trace-context.js';
5
6
  import type { EventsWebhookSetup } from './events/types.js';
7
+ /** Published tool input and structured-output snapshot for each configured server. */
8
+ export type MCPServerMap = Record<string, {
9
+ tools: Record<string, {
10
+ input: unknown;
11
+ output: unknown;
12
+ }>;
13
+ }>;
14
+ /**
15
+ * Constraint for a supplied server snapshot. Mapping over the given keys lets concrete
16
+ * generated interfaces satisfy it without declaring an index signature.
17
+ */
18
+ export type MCPClientServers<TServers> = {
19
+ [Server in keyof TServers]: MCPServerMap[string];
20
+ };
21
+ type MCPClientTool<Input, Output> = Omit<Tool<Input, Output | CallToolResult, any, any>, 'execute'> & {
22
+ execute?: (input: Input, context?: Parameters<NonNullable<Tool<Input, Output | CallToolResult, any, any>['execute']>>[1]) => ReturnType<NonNullable<Tool<Input, Output | CallToolResult, any, any>['execute']>>;
23
+ };
24
+ /** Flat discovery remains partial because servers and tools may be unavailable. */
25
+ export type MCPClientTools<TServers extends MCPClientServers<TServers>> = string extends keyof TServers ? Record<string, Tool<any, any, any, any>> : Partial<{
26
+ [Entry in {
27
+ [Server in keyof TServers & string]: {
28
+ [Name in keyof TServers[Server]['tools'] & string]: {
29
+ key: `${Server}_${Name}`;
30
+ tool: MCPClientTool<TServers[Server]['tools'][Name]['input'], TServers[Server]['tools'][Name]['output']>;
31
+ };
32
+ }[keyof TServers[Server]['tools'] & string];
33
+ }[keyof TServers & string] as Entry['key']]: Entry['tool'];
34
+ }>;
35
+ /** Grouped discovery preserves raw tool names and potentially absent servers. */
36
+ export type MCPClientToolsets<TServers extends MCPClientServers<TServers>> = string extends keyof TServers ? Record<string, Record<string, Tool<any, any, any, any>>> : Partial<{
37
+ [Server in keyof TServers]: Partial<{
38
+ [Name in keyof TServers[Server]['tools'] & string]: MCPClientTool<TServers[Server]['tools'][Name]['input'], TServers[Server]['tools'][Name]['output']>;
39
+ }>;
40
+ }>;
6
41
  export type { FetchLike } from '@modelcontextprotocol/client';
7
42
  export type { ToolAnnotations } from '@modelcontextprotocol/client';
8
43
  export type { LoggingLevel } from '@modelcontextprotocol/client';
@@ -483,6 +518,8 @@ export type InternalMastraMCPClientOptions = {
483
518
  clientInfo?: MCPClientInfo;
484
519
  /** Optional timeout in milliseconds */
485
520
  timeout?: number;
521
+ /** Install process exit and signal hooks (default: true). */
522
+ registerProcessHooks?: boolean;
486
523
  /** Webhook settings and receiver shared by the owning `MCPClient`'s servers. */
487
524
  webhook?: EventsWebhookSetup;
488
525
  };
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/client/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,EAAE,MAAM,oBAAoB,CAAC;AACjD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EACV,oCAAoC,EACpC,kBAAkB,EAClB,mBAAmB,EACnB,YAAY,EACZ,YAAY,EACZ,oBAAoB,EACpB,eAAe,EACf,mBAAmB,EACpB,MAAM,8BAA8B,CAAC;AACtC,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,yBAAyB,CA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AuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,6DAA6D;IAC7D,oBAAoB,CAAC,EAAE,OAAO,CAAC;IAC/B,gFAAgF;IAChF,OAAO,CAAC,EAAE,kBAAkB,CAAC;CAC9B,CAAC;AAEF;;;;;;;;;;GAUG;AACH,MAAM,MAAM,6BAA6B,GAAG;IAC1C,kFAAkF;IAClF,IAAI,EAAE,MAAM,CAAC;IACb,uEAAuE;IACvE,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,sEAAsE;IACtE,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,+EAA+E;IAC/E,WAAW,EAAE,OAAO,CAAC;IACrB,oFAAoF;IACpF,YAAY,CAAC,EAAE,OAAO,CAAC;IACvB,iFAAiF;IACjF,WAAW,CAAC,EAAE,eAAe,CAAC;IAC9B,wEAAwE;IACxE,KAAK,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAChC;;;;;;OAMG;IACH,MAAM,EAAE;QACN,gDAAgD;QAChD,IAAI,EAAE,MAAM,CAAC;QACb,wDAAwD;QACxD,OAAO,CAAC,EAAE,MAAM,CAAC;QACjB,iEAAiE;QACjE,YAAY,CAAC,EAAE,MAAM,CAAC;KACvB,CAAC;CACH,CAAC;AAEF;;;;GAIG;AACH,MAAM,MAAM,0BAA0B,GAAG,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,6BAA6B,CAAC,CAAC,CAAC"}
@@ -3,7 +3,7 @@ name: mastra-mcp
3
3
  description: Documentation for @mastra/mcp. Use when working with @mastra/mcp APIs, configuration, or implementation.
4
4
  metadata:
5
5
  package: "@mastra/mcp"
6
- version: "2.5.0"
6
+ version: "2.6.0-alpha.1"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -17,10 +17,9 @@ Read the individual reference documents for detailed explanations and code examp
17
17
  ### Docs
18
18
 
19
19
  - [Fine-Grained Authorization (FGA)](references/docs-auth-fga.md) - Configure Mastra Fine-Grained Authorization for resource-level permissions that map routes to actions and scope stored resources for enterprise users.
20
- - [MCP](references/docs-connections-mcp.md) - Connect Mastra agents to remote MCP servers, expose Mastra tools through MCPServer, manage approvals, and build interactive MCP Apps for Studio.
20
+ - [MCP](references/docs-connections-mcp.md) - Connect Mastra agents to remote MCP servers, expose Mastra tools through MCPServer, manage approvals, subscribe to MCP events, and build interactive MCP Apps for Studio.
21
21
  - [Connections](references/docs-connections-overview.md) - Connect Mastra to remote agents, coding agents, SDK runtimes, MCP servers, and external tools by choosing the protocol that fits your application.
22
22
  - [MCP authentication and authorization](references/docs-guides-mcp-authentication-authorization.md) - Choose credentials for MCP connections, protect a Mastra MCP server, and separate delegated access from tool and data permissions.
23
- - [MCP events](references/docs-guides-mcp-events.md) - Publish events from a Mastra MCP server, subscribe to them with MCPClient, resume from a cursor, and start agent or workflow runs per occurrence.
24
23
 
25
24
  ### Reference
26
25
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "2.5.0",
2
+ "version": "2.6.0-alpha.1",
3
3
  "package": "@mastra/mcp",
4
4
  "exports": {},
5
5
  "modules": {}
@@ -81,11 +81,83 @@ export const assistant = new Agent({
81
81
  Use the available MCP tools to answer questions.
82
82
  Include the source of any information you retrieve.
83
83
  `,
84
- model: 'openai/gpt-5.6-sol',
84
+ model: 'openai/gpt-6.1-sol',
85
85
  tools: await mcpClient.listTools(),
86
86
  })
87
87
  ```
88
88
 
89
+ ### Generate types for direct tool calls
90
+
91
+ For stable server configurations, generate types from published tool schemas instead of redeclaring tool arguments and results. This optional workflow leaves dynamic discovery unchanged.
92
+
93
+ Export a client with an output path and pass the generated `MCPServers` interface to its constructor:
94
+
95
+ ```typescript
96
+ import { MCPClient } from '@mastra/mcp'
97
+ import type { MCPServers } from './mcp-types.generated'
98
+
99
+ export const mcp = new MCPClient<MCPServers>({
100
+ id: 'weather-client',
101
+ servers: { weather: { url: new URL(process.env.WEATHER_MCP_URL!) } },
102
+ typegen: { outFile: 'src/mcp/mcp-types.generated.ts' },
103
+ })
104
+ ```
105
+
106
+ Set `WEATHER_MCP_URL` and configure any required authentication before running the command from your project root:
107
+
108
+ **npm**:
109
+
110
+ ```bash
111
+ npx @mastra/mcp generate ./src/mcp/client.ts
112
+ ```
113
+
114
+ **pnpm**:
115
+
116
+ ```bash
117
+ pnpm dlx @mastra/mcp generate ./src/mcp/client.ts
118
+ ```
119
+
120
+ **Yarn**:
121
+
122
+ ```bash
123
+ yarn dlx @mastra/mcp generate ./src/mcp/client.ts
124
+ ```
125
+
126
+ **Bun**:
127
+
128
+ ```bash
129
+ bun x @mastra/mcp generate ./src/mcp/client.ts
130
+ ```
131
+
132
+ The generated file can be absent on the first run because its import is type-only. Generation loads TypeScript modules without typechecking and lists schemas without executing tools. Run your project's typecheck afterward.
133
+
134
+ Call a discovered tool using its generated arguments. The following assumes the server publishes `get_weather` with a string `location` and numeric `temperature`:
135
+
136
+ ```typescript
137
+ import { mcp } from './client'
138
+
139
+ try {
140
+ const tools = await mcp.listTools()
141
+ const weather = tools.weather_get_weather
142
+ if (weather?.execute) {
143
+ const result = await weather.execute({ location: 'Paris' })
144
+ if (result && 'temperature' in result && typeof result.temperature === 'number') {
145
+ console.log(result.temperature)
146
+ }
147
+ }
148
+ } finally {
149
+ await mcp.disconnect()
150
+ }
151
+ ```
152
+
153
+ Tools can be absent, and execution can return a protocol envelope, validation error, or `undefined` alongside structured output. Narrow the result before using it. Missing output schemas produce `unknown`.
154
+
155
+ Pass multiple explicit client files to generate several outputs. Export clients directly as named or default exports, use different output paths, and give independent clients distinct IDs when their server configurations match. Input and output paths resolve from the command's working directory. Repeated exports of the same client are processed once.
156
+
157
+ Discovery failures leave existing files unchanged, as does a schema problem generation can't work around, such as a reference cycle, excessive depth, or an unresolved local reference. File replacement is atomic per file, not across the whole set. Regenerate when server schemas change, using equivalent permissions. Before generation, provide credentials and load any environment files yourself. Importing a client executes its module and transitive imports, so choose files without application startup side effects. Interactive authentication isn't part of the command.
158
+
159
+ See [type generation reference](https://mastra.ai/reference/tools/mcp-client) for export selection, instance caching, schema limitations, and failure handling.
160
+
89
161
  ### Static and runtime tools
90
162
 
91
163
  Choose how to load tools based on whether the server configuration changes between requests:
@@ -154,9 +226,9 @@ Treat tool annotations from servers you don't control as untrusted hints. Visit
154
226
 
155
227
  MCP servers run code and return content on your agent's behalf, so configure them with the same care as any other external dependency:
156
228
 
157
- - **Stdio subprocess environment**: subprocesses inherit only the MCP SDK's curated environment whitelist (for example `PATH` and `HOME` on POSIX), not the full parent environment. Set `inheritDefaultEnv: false` on a server to pass only the variables you list in `env`.
158
- - **Outbound host restriction**: Set `allowedHosts` when HTTP server URLs come from untrusted configuration to restrict the hosts that the client can contact. The default fetch path also blocks redirect hops before sending them. A custom `fetch` is validated against its final response URL only after the request, so it must enforce its own redirect policy when outbound contact must be prevented.
159
- - **Tool response trust**: tool results are untrusted model input. Use [input and output processors](https://mastra.ai/docs/agents/processors) to inspect or sanitize content before it reaches the model, and `requireToolApproval` to gate sensitive tools.
229
+ - **Stdio subprocess environment**: subprocesses inherit only the MCP SDK's curated environment whitelist (for example `PATH` and `HOME` on POSIX), not the full parent environment. Set `inheritDefaultEnv: false` on a server to pass only the variables listed in `env`.
230
+ - **Outbound host restriction**: set `allowedHosts` when HTTP server URLs come from untrusted configuration, to restrict the hosts the client can contact. The default fetch path blocks redirect hops before sending them; a custom `fetch` is validated against its final response URL only after the request, so it must enforce its own redirect policy when outbound contact must be prevented.
231
+ - **Tool response trust**: tool results are untrusted model input. Use [input and output processors](https://mastra.ai/docs/agents/processors) to sanitize content before it reaches the model, and `requireToolApproval` for sensitive tools.
160
232
 
161
233
  Visit the [MCPClient security reference](https://mastra.ai/reference/tools/mcp-client) for enforcement details of each option.
162
234
 
@@ -271,32 +343,24 @@ import { MCPServer } from '@mastra/mcp'
271
343
  import { createTool } from '@mastra/core/tools'
272
344
  import { z } from 'zod'
273
345
 
274
- export const calculatorTool = createTool({
346
+ const calculatorTool = createTool({
275
347
  id: 'calculatorWithUI',
276
348
  description: 'Calculate the sum of two numbers',
277
- inputSchema: z.object({
278
- num1: z.number(),
279
- num2: z.number(),
280
- }),
281
- mcp: {
282
- _meta: { ui: { resourceUri: 'ui://calculator/main' } },
283
- },
349
+ inputSchema: z.object({ num1: z.number(), num2: z.number() }),
350
+ mcp: { _meta: { ui: { resourceUri: 'ui://calculator/main' } } },
284
351
  execute: async ({ num1, num2 }) => ({
285
352
  content: [{ type: 'text', text: 'The result is displayed in the calculator app.' }],
286
353
  structuredContent: { result: num1 + num2 },
287
354
  }),
288
355
  })
289
356
 
290
- export const calculatorMcpServer = new MCPServer({
357
+ const calculatorMcpServer = new MCPServer({
291
358
  id: 'calculator-app-server',
292
359
  name: 'Calculator App Server',
293
360
  version: '1.0.0',
294
361
  tools: { calculatorTool },
295
362
  appResources: {
296
- 'ui://calculator/main': {
297
- name: 'Calculator',
298
- htmlPath: './src/mastra/mcp/calculator.html',
299
- },
363
+ 'ui://calculator/main': { name: 'Calculator', htmlPath: './src/mastra/mcp/calculator.html' },
300
364
  },
301
365
  })
302
366
  ```
@@ -330,11 +394,6 @@ Use the `App` class from `@modelcontextprotocol/ext-apps` inside the HTML resour
330
394
  arguments: toolInput,
331
395
  })
332
396
  document.querySelector('#result').textContent = JSON.stringify(result)
333
-
334
- await app.sendMessage({
335
- role: 'user',
336
- content: [{ type: 'text', text: 'Explain the recalculated result.' }],
337
- })
338
397
  })
339
398
 
340
399
  await app.connect()
@@ -352,37 +411,11 @@ The guest-side APIs serve different parts of the interaction:
352
411
  | `app.sendMessage()` | Add a user message to chat and start a new model turn |
353
412
  | `app.connect()` | Connect to the host after registering event handlers |
354
413
 
355
- The interaction follows this sequence:
356
-
357
- 1. The agent calls the tool.
358
- 2. The tool returns model-facing `content` and UI-facing `structuredContent`.
359
- 3. Studio renders the associated app resource.
360
- 4. The app receives tool input and can call server tools or send chat messages.
361
-
362
414
  Visit the external [`App` API reference](https://apps.extensions.modelcontextprotocol.io/api/classes/app.App.html) for all guest-side methods and lifecycle hooks.
363
415
 
364
416
  ### Register MCP Apps
365
417
 
366
- For a local app, pass the tool to an agent and register its MCP server on `Mastra`:
367
-
368
- ```typescript
369
- import { Agent } from '@mastra/core/agent'
370
- import { Mastra } from '@mastra/core/mastra'
371
- import { calculatorMcpServer, calculatorTool } from './mcp/calculator'
372
-
373
- const calculatorAgent = new Agent({
374
- id: 'calculator-agent',
375
- name: 'Calculator Agent',
376
- instructions: 'Use the calculator tool for arithmetic.',
377
- model: 'openai/gpt-5-mini',
378
- tools: { calculatorTool },
379
- })
380
-
381
- export const mastra = new Mastra({
382
- agents: { calculatorAgent },
383
- mcpServers: { calculatorMcpServer },
384
- })
385
- ```
418
+ Register the server on `Mastra` the same way as any other server in [Expose a Mastra MCP server](#expose-a-mastra-mcp-server), and pass its tool to the agent that should render the app.
386
419
 
387
420
  For an external MCP server that implements MCP Apps, load its tools with `MCPClient.listTools()` and register its proxy so Studio can resolve the remote app resources:
388
421
 
@@ -398,7 +431,7 @@ const agent = new Agent({
398
431
  id: 'remote-app-agent',
399
432
  name: 'Remote App Agent',
400
433
  instructions: 'Use the available remote tools.',
401
- model: 'openai/gpt-5-mini',
434
+ model: 'openai/gpt-6-luna',
402
435
  tools,
403
436
  })
404
437
 
@@ -416,6 +449,82 @@ Mastra Studio uses [`@mcp-ui/client`](https://www.npmjs.com/package/@mcp-ui/clie
416
449
 
417
450
  App iframes allow scripts, forms, and popups. They can't access the parent page's DOM, cookies, or storage. The host controls all communication with the guest app.
418
451
 
452
+ ## MCP events
453
+
454
+ MCP events let a client react when something happens on a server, such as a ticket being opened or a build finishing, instead of calling a tool on a schedule to check. A server declares event types, a client subscribes with arguments, and the server delivers each matching occurrence over the same stdio or Streamable HTTP transport as its tools.
455
+
456
+ > **Warning:** MCP events implement [SEP-3415](https://github.com/modelcontextprotocol/modelcontextprotocol/pull/3415), a draft MCP extension. The wire format and the Mastra API are experimental and may change in any release.
457
+
458
+ - **Subscription:** one client request for one event type with arguments, such as `{ project: 'web' }`. The server delivers only matching occurrences.
459
+ - **Occurrence:** one delivered event with an `eventId`, `name`, `timestamp`, and `data`. Delivery is at least once, and the client drops duplicates by `eventId` within a `dedupWindow` of recent ids. Handlers should still tolerate a repeat.
460
+ - **Cursor:** an opaque position in the event sequence. Save it to resume from a later subscription. Replay covers only history the source retains. An `emit()` source buffers in one process, so a restart or another instance serving the subscription can miss occurrences, and durable replay needs a `poll` source backed by shared storage.
461
+
462
+ ### Publish events
463
+
464
+ Declare each type with `defineEvent()` in the `events` option of `MCPServer`, then publish occurrences with `server.events.emit()`:
465
+
466
+ ```typescript
467
+ import { createTool } from '@mastra/core/tools'
468
+ import { MCPServer, defineEvent } from '@mastra/mcp'
469
+ import { z } from 'zod'
470
+
471
+ const ticket = z.object({ id: z.string(), project: z.string(), title: z.string() })
472
+
473
+ const server: MCPServer = new MCPServer({
474
+ id: 'tickets',
475
+ name: 'Tickets',
476
+ version: '1.0.0',
477
+ tools: {
478
+ openTicket: createTool({
479
+ id: 'openTicket',
480
+ description: 'Opens a support ticket',
481
+ inputSchema: ticket,
482
+ execute: async input => server.events.emit('ticket.created', input),
483
+ }),
484
+ },
485
+ events: {
486
+ 'ticket.created': defineEvent({
487
+ description: 'A support ticket was opened',
488
+ inputSchema: z.object({ project: z.string() }),
489
+ payloadSchema: ticket,
490
+ match: (args, data) => data.project === args.project,
491
+ }),
492
+ },
493
+ })
494
+ ```
495
+
496
+ The examples serve this server over HTTP at `http://localhost:4111/mcp` with [`startHTTP()`](https://mastra.ai/reference/tools/mcp-server).
497
+
498
+ `match` decides which subscriptions receive an occurrence. It filters on arguments the client chooses, so it doesn't control who can subscribe; add `authorize` to restrict callers, since it runs on every poll and every subscription open and rejects the request when it returns `false`. An event type takes its occurrences from either `server.events.emit()`, which serves push and poll from an in-process buffer, or a `poll` function that reads an external system and supports poll only.
499
+
500
+ ### Subscribe to events
501
+
502
+ List the types a server offers with `mcp.events.list()`, then subscribe with `mcp.events.subscribe()`. The returned subscription is an async iterable of occurrences:
503
+
504
+ ```typescript
505
+ import { MCPClient } from '@mastra/mcp'
506
+
507
+ const mcp = new MCPClient({ servers: { tickets: { url: new URL('http://localhost:4111/mcp') } } })
508
+
509
+ const eventTypes = await mcp.events.list('tickets')
510
+ const subscription = await mcp.events.subscribe('tickets', 'ticket.created', { project: 'web' })
511
+
512
+ for await (const event of subscription) {
513
+ console.log(event.eventId, event.data)
514
+ if (subscription.cursor) await saveCursor('tickets:web', subscription.cursor)
515
+ }
516
+ ```
517
+
518
+ `subscribe()` resolves once the server accepts the subscription. A new subscription starts from now, so pass `options.cursor` to resume from a saved position. The client picks the first mode the event offers, in the order `webhook` when the client has `webhook` settings, then `push`, then `poll`, and reopens dropped streams on its own.
519
+
520
+ ### Start runs from events
521
+
522
+ Subscribe in a loop that starts one agent run or workflow run per occurrence. The occurrence comes from the server, so pass `event.data` as data rather than as instructions, and save `subscription.cursor` after handling each one. Because the loop handles one occurrence at a time and a slow run delays the next, when order doesn't matter you can start runs without awaiting them and save the cursor only after every earlier run has finished, since a crash otherwise loses the occurrences whose runs were still going.
523
+
524
+ Under push or webhook delivery the client buffers occurrences the loop hasn't read, and a loop that falls more than `maxBufferedEvents` behind loses the oldest ones and reports `MCP_EVENTS_BUFFER_OVERFLOW`. To deliver occurrences to agent threads as notifications instead of writing your own loop, use [`MCPEventsSignalProvider`](https://mastra.ai/reference/tools/mcp-client).
525
+
526
+ When the server is remote and your application already serves HTTP, use webhook delivery instead: enable `webhook` in `eventsOptions` on the server and `webhook` on the client, and each occurrence arrives as a POST to your endpoint. For delivery modes, error codes, buffers, retries, and the `poll` source example, visit the [`MCPServer` events reference](https://mastra.ai/reference/tools/mcp-server) and the [`MCPClient` events reference](https://mastra.ai/reference/tools/mcp-client). The [MCP events example](https://github.com/mastra-ai/mastra/tree/main/examples/mcp-events) runs the agent flow end to end against a local stdio server.
527
+
419
528
  ## Next steps
420
529
 
421
530
  - [Use tools with agents](https://mastra.ai/docs/agents/tools)
@@ -64,7 +64,7 @@ const agent = new OpenAISDKAgent({
64
64
  description: 'Answers project questions',
65
65
  sdkOptions: {
66
66
  name: 'Project assistant',
67
- model: 'gpt-5',
67
+ model: 'gpt-5.6',
68
68
  },
69
69
  })
70
70
 
@@ -2,7 +2,7 @@
2
2
 
3
3
  > Discover all available pages from the documentation index: https://mastra.ai/llms.txt
4
4
 
5
- # MCP authentication
5
+ # MCP authentication and authorization
6
6
 
7
7
  You either connect your Mastra application to someone else's protected MCP server, or you expose your own tools and data to a third-party client. Each direction needs different credentials and different checks.
8
8
 
@@ -125,7 +125,7 @@ An MCP access token is for the MCP server. The specification prohibits passing t
125
125
 
126
126
  Keep access tokens, refresh tokens, and service credentials outside model-visible instructions, tool arguments, and tool results. Return only the data needed for the task. The [authentication and identity guide](https://mastra.ai/docs/guides/authentication-identity) explains this model boundary.
127
127
 
128
- ## Verify before production
128
+ ## Production checklist
129
129
 
130
130
  - [ ] **Validate tokens:** Configure validation for your issuer, including audience and expiry checks, and confirm an unvalidated token is rejected.
131
131
  - [ ] **Challenge missing tokens:** Confirm every protected server path returns `401` without a bearer token.
@@ -204,7 +204,7 @@ await server.startHTTP({
204
204
 
205
205
  ### Server `protocolVersion` option
206
206
 
207
- Servers accepted `protocolVersion` (`'2025-11-25'`, `'2026-07-28'` or `'auto'`). Only `2026-07-28` is served now, exposed as the `MCP_PROTOCOL_VERSION` constant. Remove the option; a client that doesn't offer `2026-07-28` fails with an explicit negotiation error instead of a downgrade.
207
+ Servers accepted `protocolVersion` (`'2025-11-25'`, `'2026-07-28'` or `'auto'`). Only `2026-07-28` is served now, exposed as the `MCP_PROTOCOL_VERSION` constant. Remove the option; a client that doesn't offer `2026-07-28` fails with an explicit negotiation error instead of a downgrade. To keep serving clients that still open with `initialize` over HTTP, set `legacy: 'stateless'` on the server. Each of their requests is then answered without a session.
208
208
 
209
209
  ```diff
210
210
  const server = new MCPServer({