@mastra/mcp 1.0.0-beta.1 → 1.0.0-beta.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.
Files changed (51) hide show
  1. package/CHANGELOG.md +292 -0
  2. package/README.md +250 -24
  3. package/dist/__fixtures__/tools.d.ts +8 -5
  4. package/dist/__fixtures__/tools.d.ts.map +1 -1
  5. package/dist/client/{elicitationActions.d.ts → actions/elicitation.d.ts} +2 -2
  6. package/dist/client/actions/elicitation.d.ts.map +1 -0
  7. package/dist/client/actions/progress.d.ts +23 -0
  8. package/dist/client/actions/progress.d.ts.map +1 -0
  9. package/dist/client/{promptActions.d.ts → actions/prompt.d.ts} +2 -2
  10. package/dist/client/actions/prompt.d.ts.map +1 -0
  11. package/dist/client/{resourceActions.d.ts → actions/resource.d.ts} +2 -2
  12. package/dist/client/actions/resource.d.ts.map +1 -0
  13. package/dist/client/client.d.ts +79 -132
  14. package/dist/client/client.d.ts.map +1 -1
  15. package/dist/client/configuration.d.ts +23 -1
  16. package/dist/client/configuration.d.ts.map +1 -1
  17. package/dist/client/index.d.ts +3 -1
  18. package/dist/client/index.d.ts.map +1 -1
  19. package/dist/client/oauth-provider.d.ts +230 -0
  20. package/dist/client/oauth-provider.d.ts.map +1 -0
  21. package/dist/client/types.d.ts +237 -0
  22. package/dist/client/types.d.ts.map +1 -0
  23. package/dist/docs/README.md +33 -0
  24. package/dist/docs/SKILL.md +46 -0
  25. package/dist/docs/SOURCE_MAP.json +59 -0
  26. package/dist/docs/mcp/01-overview.md +372 -0
  27. package/dist/docs/mcp/02-publishing-mcp-server.md +111 -0
  28. package/dist/docs/tools/01-reference.md +2306 -0
  29. package/dist/docs/tools-mcp/01-mcp-overview.md +384 -0
  30. package/dist/index.cjs +844 -107
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +767 -92
  35. package/dist/index.js.map +1 -1
  36. package/dist/server/index.d.ts +1 -0
  37. package/dist/server/index.d.ts.map +1 -1
  38. package/dist/server/oauth-middleware.d.ts +142 -0
  39. package/dist/server/oauth-middleware.d.ts.map +1 -0
  40. package/dist/server/server.d.ts +20 -4
  41. package/dist/server/server.d.ts.map +1 -1
  42. package/dist/server/types.d.ts +11 -4
  43. package/dist/server/types.d.ts.map +1 -1
  44. package/dist/shared/index.d.ts +2 -0
  45. package/dist/shared/index.d.ts.map +1 -0
  46. package/dist/shared/oauth-types.d.ts +137 -0
  47. package/dist/shared/oauth-types.d.ts.map +1 -0
  48. package/package.json +17 -14
  49. package/dist/client/elicitationActions.d.ts.map +0 -1
  50. package/dist/client/promptActions.d.ts.map +0 -1
  51. package/dist/client/resourceActions.d.ts.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,297 @@
1
1
  # @mastra/mcp
2
2
 
3
+ ## 1.0.0-beta.10
4
+
5
+ ### Major Changes
6
+
7
+ - Refactor workflow and tool types to remove Zod-specific constraints ([#11814](https://github.com/mastra-ai/mastra/pull/11814))
8
+
9
+ Removed Zod-specific type constraints across all workflow implementations and tool types, replacing them with generic types. This ensures type consistency across default, evented, and inngest workflows while preparing for Zod v4 migration.
10
+
11
+ **Workflow Changes:**
12
+ - Removed `z.ZodObject<any>` and `z.ZodType<any>` constraints from all workflow generic types
13
+ - Updated method signatures to use `TInput` and `TState` directly instead of `z.infer<TInput>` and `z.infer<TState>`
14
+ - Aligned conditional types across all workflow implementations using `TInput extends unknown` pattern
15
+ - Fixed `TSteps` generic to properly use `TEngineType` instead of `any`
16
+
17
+ **Tool Changes:**
18
+ - Removed Zod schema constraints from `ToolExecutionContext` and related interfaces
19
+ - Simplified type parameters from `TSuspendSchema extends ZodLikeSchema` to `TSuspend` and `TResume`
20
+ - Updated tool execution context types to use generic types
21
+
22
+ **Type Utilities:**
23
+ - Refactored type helpers to work with generic schemas instead of Zod-specific types
24
+ - Updated type extraction utilities for better compatibility
25
+
26
+ This change maintains backward compatibility while improving type consistency and preparing for Zod v4 support across all affected packages.
27
+
28
+ ### Minor Changes
29
+
30
+ - Expose tool `mcp.annotations` and `mcp._meta` in MCPServer listTools response ([#11841](https://github.com/mastra-ai/mastra/pull/11841))
31
+
32
+ MCP clients (including OpenAI Apps SDK) now receive tool behavior hints and custom metadata when listing tools. This enables clients to display user-friendly tool titles, show permission indicators, and access arbitrary metadata without additional configuration.
33
+
34
+ ```typescript
35
+ // Tools with mcp properties are automatically exposed via MCP
36
+ const server = new MCPServer({
37
+ name: 'My Server',
38
+ version: '1.0.0',
39
+ tools: { myTool }, // mcp.annotations and mcp._meta flow through to clients
40
+ });
41
+ ```
42
+
43
+ - Add OAuth 2.1 support for MCP client and server ([#11939](https://github.com/mastra-ai/mastra/pull/11939))
44
+
45
+ Client-side OAuth:
46
+ - MCPOAuthClientProvider: Ready-to-use OAuth provider implementation for connecting to OAuth-protected MCP servers
47
+ - Supports dynamic client registration (RFC 7591), PKCE, and token refresh
48
+ - OAuthStorage interface with InMemoryOAuthStorage for token persistence
49
+ - createSimpleTokenProvider helper for testing with pre-configured tokens
50
+
51
+ Server-side OAuth middleware:
52
+ - createOAuthMiddleware - Middleware for protecting MCP server endpoints with OAuth
53
+ - Serves Protected Resource Metadata at /.well-known/oauth-protected-resource (RFC 9728)
54
+ - createStaticTokenValidator for simple token validation in development
55
+ - createIntrospectionValidator for production token introspection (RFC 7662)
56
+
57
+ Shared utilities:
58
+ - Re-exports OAuth types from the MCP SDK
59
+ - MCPServerOAuthConfig and TokenValidationResult types
60
+ - Helper functions for WWW-Authenticate headers and Protected Resource Metadata generation
61
+
62
+ ### Patch Changes
63
+
64
+ - Updated dependencies [[`ebae12a`](https://github.com/mastra-ai/mastra/commit/ebae12a2dd0212e75478981053b148a2c246962d), [`c61a0a5`](https://github.com/mastra-ai/mastra/commit/c61a0a5de4904c88fd8b3718bc26d1be1c2ec6e7), [`69136e7`](https://github.com/mastra-ai/mastra/commit/69136e748e32f57297728a4e0f9a75988462f1a7), [`449aed2`](https://github.com/mastra-ai/mastra/commit/449aed2ba9d507b75bf93d427646ea94f734dfd1), [`eb648a2`](https://github.com/mastra-ai/mastra/commit/eb648a2cc1728f7678768dd70cd77619b448dab9), [`0131105`](https://github.com/mastra-ai/mastra/commit/0131105532e83bdcbb73352fc7d0879eebf140dc), [`9d5059e`](https://github.com/mastra-ai/mastra/commit/9d5059eae810829935fb08e81a9bb7ecd5b144a7), [`ef756c6`](https://github.com/mastra-ai/mastra/commit/ef756c65f82d16531c43f49a27290a416611e526), [`b00ccd3`](https://github.com/mastra-ai/mastra/commit/b00ccd325ebd5d9e37e34dd0a105caae67eb568f), [`3bdfa75`](https://github.com/mastra-ai/mastra/commit/3bdfa7507a91db66f176ba8221aa28dd546e464a), [`e770de9`](https://github.com/mastra-ai/mastra/commit/e770de941a287a49b1964d44db5a5763d19890a6), [`52e2716`](https://github.com/mastra-ai/mastra/commit/52e2716b42df6eff443de72360ae83e86ec23993), [`27b4040`](https://github.com/mastra-ai/mastra/commit/27b4040bfa1a95d92546f420a02a626b1419a1d6), [`610a70b`](https://github.com/mastra-ai/mastra/commit/610a70bdad282079f0c630e0d7bb284578f20151), [`8dc7f55`](https://github.com/mastra-ai/mastra/commit/8dc7f55900395771da851dc7d78d53ae84fe34ec), [`8379099`](https://github.com/mastra-ai/mastra/commit/8379099fc467af6bef54dd7f80c9bd75bf8bbddf), [`8c0ec25`](https://github.com/mastra-ai/mastra/commit/8c0ec25646c8a7df253ed1e5ff4863a0d3f1316c), [`ff4d9a6`](https://github.com/mastra-ai/mastra/commit/ff4d9a6704fc87b31a380a76ed22736fdedbba5a), [`69821ef`](https://github.com/mastra-ai/mastra/commit/69821ef806482e2c44e2197ac0b050c3fe3a5285), [`1ed5716`](https://github.com/mastra-ai/mastra/commit/1ed5716830867b3774c4a1b43cc0d82935f32b96), [`4186bdd`](https://github.com/mastra-ai/mastra/commit/4186bdd00731305726fa06adba0b076a1d50b49f), [`7aaf973`](https://github.com/mastra-ai/mastra/commit/7aaf973f83fbbe9521f1f9e7a4fd99b8de464617)]:
65
+ - @mastra/core@1.0.0-beta.22
66
+
67
+ ## 1.0.0-beta.9
68
+
69
+ ### Patch Changes
70
+
71
+ - dependencies updates: ([#10114](https://github.com/mastra-ai/mastra/pull/10114))
72
+ - Updated dependency [`uuid@^13.0.0` ↗︎](https://www.npmjs.com/package/uuid/v/13.0.0) (from `^11.1.0`, in `dependencies`)
73
+ - Updated dependencies [[`08766f1`](https://github.com/mastra-ai/mastra/commit/08766f15e13ac0692fde2a8bd366c2e16e4321df), [`ae8baf7`](https://github.com/mastra-ai/mastra/commit/ae8baf7d8adcb0ff9dac11880400452bc49b33ff), [`cfabdd4`](https://github.com/mastra-ai/mastra/commit/cfabdd4aae7a726b706942d6836eeca110fb6267), [`a0e437f`](https://github.com/mastra-ai/mastra/commit/a0e437fac561b28ee719e0302d72b2f9b4c138f0), [`bec5efd`](https://github.com/mastra-ai/mastra/commit/bec5efde96653ccae6604e68c696d1bc6c1a0bf5), [`9eedf7d`](https://github.com/mastra-ai/mastra/commit/9eedf7de1d6e0022a2f4e5e9e6fe1ec468f9b43c)]:
74
+ - @mastra/core@1.0.0-beta.21
75
+
76
+ ## 1.0.0-beta.8
77
+
78
+ ### Patch Changes
79
+
80
+ - dependencies updates: ([#10194](https://github.com/mastra-ai/mastra/pull/10194))
81
+ - Updated dependency [`exit-hook@^5.0.1` ↗︎](https://www.npmjs.com/package/exit-hook/v/5.0.1) (from `^4.0.0`, in `dependencies`)
82
+
83
+ - Add embedded documentation support for Mastra packages ([#11472](https://github.com/mastra-ai/mastra/pull/11472))
84
+
85
+ Mastra packages now include embedded documentation in the published npm package under `dist/docs/`. This enables coding agents and AI assistants to understand and use the framework by reading documentation directly from `node_modules`.
86
+
87
+ Each package includes:
88
+ - **SKILL.md** - Entry point explaining the package's purpose and capabilities
89
+ - **SOURCE_MAP.json** - Machine-readable index mapping exports to types and implementation files
90
+ - **Topic folders** - Conceptual documentation organized by feature area
91
+
92
+ Documentation is driven by the `packages` frontmatter field in MDX files, which maps docs to their corresponding packages. CI validation ensures all docs include this field.
93
+
94
+ - Updated dependencies [[`d2d3e22`](https://github.com/mastra-ai/mastra/commit/d2d3e22a419ee243f8812a84e3453dd44365ecb0), [`bc72b52`](https://github.com/mastra-ai/mastra/commit/bc72b529ee4478fe89ecd85a8be47ce0127b82a0), [`05b8bee`](https://github.com/mastra-ai/mastra/commit/05b8bee9e50e6c2a4a2bf210eca25ee212ca24fa), [`c042bd0`](https://github.com/mastra-ai/mastra/commit/c042bd0b743e0e86199d0cb83344ca7690e34a9c), [`940a2b2`](https://github.com/mastra-ai/mastra/commit/940a2b27480626ed7e74f55806dcd2181c1dd0c2), [`e0941c3`](https://github.com/mastra-ai/mastra/commit/e0941c3d7fc75695d5d258e7008fd5d6e650800c), [`0c0580a`](https://github.com/mastra-ai/mastra/commit/0c0580a42f697cd2a7d5973f25bfe7da9055038a), [`28f5f89`](https://github.com/mastra-ai/mastra/commit/28f5f89705f2409921e3c45178796c0e0d0bbb64), [`e601b27`](https://github.com/mastra-ai/mastra/commit/e601b272c70f3a5ecca610373aa6223012704892), [`3d3366f`](https://github.com/mastra-ai/mastra/commit/3d3366f31683e7137d126a3a57174a222c5801fb), [`5a4953f`](https://github.com/mastra-ai/mastra/commit/5a4953f7d25bb15ca31ed16038092a39cb3f98b3), [`eb9e522`](https://github.com/mastra-ai/mastra/commit/eb9e522ce3070a405e5b949b7bf5609ca51d7fe2), [`20e6f19`](https://github.com/mastra-ai/mastra/commit/20e6f1971d51d3ff6dd7accad8aaaae826d540ed), [`4f0b3c6`](https://github.com/mastra-ai/mastra/commit/4f0b3c66f196c06448487f680ccbb614d281e2f7), [`74c4f22`](https://github.com/mastra-ai/mastra/commit/74c4f22ed4c71e72598eacc346ba95cdbc00294f), [`81b6a8f`](https://github.com/mastra-ai/mastra/commit/81b6a8ff79f49a7549d15d66624ac1a0b8f5f971), [`e4d366a`](https://github.com/mastra-ai/mastra/commit/e4d366aeb500371dd4210d6aa8361a4c21d87034), [`a4f010b`](https://github.com/mastra-ai/mastra/commit/a4f010b22e4355a5fdee70a1fe0f6e4a692cc29e), [`73b0bb3`](https://github.com/mastra-ai/mastra/commit/73b0bb394dba7c9482eb467a97ab283dbc0ef4db), [`5627a8c`](https://github.com/mastra-ai/mastra/commit/5627a8c6dc11fe3711b3fa7a6ffd6eb34100a306), [`3ff45d1`](https://github.com/mastra-ai/mastra/commit/3ff45d10e0c80c5335a957ab563da72feb623520), [`251df45`](https://github.com/mastra-ai/mastra/commit/251df4531407dfa46d805feb40ff3fb49769f455), [`f894d14`](https://github.com/mastra-ai/mastra/commit/f894d148946629af7b1f452d65a9cf864cec3765), [`c2b9547`](https://github.com/mastra-ai/mastra/commit/c2b9547bf435f56339f23625a743b2147ab1c7a6), [`580b592`](https://github.com/mastra-ai/mastra/commit/580b5927afc82fe460dfdf9a38a902511b6b7e7f), [`58e3931`](https://github.com/mastra-ai/mastra/commit/58e3931af9baa5921688566210f00fb0c10479fa), [`08bb631`](https://github.com/mastra-ai/mastra/commit/08bb631ae2b14684b2678e3549d0b399a6f0561e), [`4fba91b`](https://github.com/mastra-ai/mastra/commit/4fba91bec7c95911dc28e369437596b152b04cd0), [`12b0cc4`](https://github.com/mastra-ai/mastra/commit/12b0cc4077d886b1a552637dedb70a7ade93528c)]:
95
+ - @mastra/core@1.0.0-beta.20
96
+
97
+ ## 1.0.0-beta.7
98
+
99
+ ### Patch Changes
100
+
101
+ - Add support for `instructions` field in MCPServer ([#11421](https://github.com/mastra-ai/mastra/pull/11421))
102
+
103
+ Implements the official MCP specification's `instructions` field, which allows MCP servers to provide system-wide prompts that are automatically sent to clients during initialization. This eliminates the need for per-project configuration files (like AGENTS.md) by centralizing the system prompt in the server definition.
104
+
105
+ **What's New:**
106
+ - Added `instructions` optional field to `MCPServerConfig` type
107
+ - Instructions are passed to the underlying MCP SDK Server during initialization
108
+ - Instructions are sent to clients in the `InitializeResult` response
109
+ - Fully compatible with all MCP clients (Cursor, Windsurf, Claude Desktop, etc.)
110
+
111
+ **Example Usage:**
112
+
113
+ ```typescript
114
+ const server = new MCPServer({
115
+ name: 'GitHub MCP Server',
116
+ version: '1.0.0',
117
+ instructions:
118
+ 'Use the available tools to help users manage GitHub repositories, issues, and pull requests. Always search before creating to avoid duplicates.',
119
+ tools: { searchIssues, createIssue, listPRs },
120
+ });
121
+ ```
122
+
123
+ - Updated dependencies [[`3d93a15`](https://github.com/mastra-ai/mastra/commit/3d93a15796b158c617461c8b98bede476ebb43e2), [`efe406a`](https://github.com/mastra-ai/mastra/commit/efe406a1353c24993280ebc2ed61dd9f65b84b26), [`119e5c6`](https://github.com/mastra-ai/mastra/commit/119e5c65008f3e5cfca954eefc2eb85e3bf40da4), [`74e504a`](https://github.com/mastra-ai/mastra/commit/74e504a3b584eafd2f198001c6a113bbec589fd3), [`e33fdbd`](https://github.com/mastra-ai/mastra/commit/e33fdbd07b33920d81e823122331b0c0bee0bb59), [`929f69c`](https://github.com/mastra-ai/mastra/commit/929f69c3436fa20dd0f0e2f7ebe8270bd82a1529), [`8a73529`](https://github.com/mastra-ai/mastra/commit/8a73529ca01187f604b1f3019d0a725ac63ae55f)]:
124
+ - @mastra/core@1.0.0-beta.16
125
+
126
+ ## 1.0.0-beta.6
127
+
128
+ ### Patch Changes
129
+
130
+ - Add "Not connected" error detection to MCP auto-reconnection ([#10994](https://github.com/mastra-ai/mastra/pull/10994))
131
+
132
+ Enhanced the MCPClient auto-reconnection feature to also detect and handle "Not connected" protocol errors. When the MCP SDK's transport layer throws this error (typically when the connection is in a disconnected state), the client will now automatically reconnect and retry the operation.
133
+
134
+ - Updated dependencies [[`72df8ae`](https://github.com/mastra-ai/mastra/commit/72df8ae595584cdd7747d5c39ffaca45e4507227), [`9198899`](https://github.com/mastra-ai/mastra/commit/91988995c427b185c33714b7f3be955367911324), [`653e65a`](https://github.com/mastra-ai/mastra/commit/653e65ae1f9502c2958a32f47a5a2df11e612a92), [`c6fd6fe`](https://github.com/mastra-ai/mastra/commit/c6fd6fedd09e9cf8004b03a80925f5e94826ad7e), [`0bed332`](https://github.com/mastra-ai/mastra/commit/0bed332843f627202c6520eaf671771313cd20f3)]:
135
+ - @mastra/core@1.0.0-beta.9
136
+
137
+ ## 1.0.0-beta.5
138
+
139
+ ### Minor Changes
140
+
141
+ - Add support for RequestOptions in elicitation requests to allow custom timeouts and request cancellation. ([#10849](https://github.com/mastra-ai/mastra/pull/10849))
142
+
143
+ You can now pass RequestOptions when sending elicitation requests:
144
+
145
+ ```typescript
146
+ // Within a tool's execute function
147
+ const result = await options.mcp.elicitation.sendRequest(
148
+ {
149
+ message: 'Please provide your email',
150
+ requestedSchema: {
151
+ type: 'object',
152
+ properties: { email: { type: 'string' } },
153
+ },
154
+ },
155
+ { timeout: 120000 }, // Custom 2-minute timeout
156
+ );
157
+ ```
158
+
159
+ The RequestOptions parameter supports:
160
+ - `timeout`: Custom timeout in milliseconds (default: 60000ms)
161
+ - `signal`: AbortSignal for request cancellation
162
+
163
+ Fixes #10834
164
+
165
+ ### Patch Changes
166
+
167
+ - Fix HTTP SSE fallback to only trigger for 400/404/405 per MCP spec ([#10803](https://github.com/mastra-ai/mastra/pull/10803))
168
+
169
+ With @modelcontextprotocol/sdk 1.24.0+, SSE fallback now only occurs for HTTP status codes 400, 404, and 405. Other errors (like 401 Unauthorized) are re-thrown for proper handling.
170
+
171
+ Older SDK versions maintain the existing behavior (always fallback to SSE).
172
+
173
+ - Add injectable fetch into mcp client integration. Follows from modelcontextprotocol/sdk implementation of Streamable HTTP and SSE transports. ([#10780](https://github.com/mastra-ai/mastra/pull/10780))
174
+
175
+ - Updated dependencies [[`3076c67`](https://github.com/mastra-ai/mastra/commit/3076c6778b18988ae7d5c4c5c466366974b2d63f), [`85d7ee1`](https://github.com/mastra-ai/mastra/commit/85d7ee18ff4e14d625a8a30ec6656bb49804989b), [`c6c1092`](https://github.com/mastra-ai/mastra/commit/c6c1092f8fbf76109303f69e000e96fd1960c4ce), [`81dc110`](https://github.com/mastra-ai/mastra/commit/81dc11008d147cf5bdc8996ead1aa61dbdebb6fc), [`7aedb74`](https://github.com/mastra-ai/mastra/commit/7aedb74883adf66af38e270e4068fd42e7a37036), [`8f02d80`](https://github.com/mastra-ai/mastra/commit/8f02d800777397e4b45d7f1ad041988a8b0c6630), [`d7aad50`](https://github.com/mastra-ai/mastra/commit/d7aad501ce61646b76b4b511e558ac4eea9884d0), [`ce0a73a`](https://github.com/mastra-ai/mastra/commit/ce0a73abeaa75b10ca38f9e40a255a645d50ebfb), [`a02e542`](https://github.com/mastra-ai/mastra/commit/a02e542d23179bad250b044b17ff023caa61739f), [`a372c64`](https://github.com/mastra-ai/mastra/commit/a372c640ad1fd12e8f0613cebdc682fc156b4d95), [`8846867`](https://github.com/mastra-ai/mastra/commit/8846867ffa9a3746767618e314bebac08eb77d87), [`42a42cf`](https://github.com/mastra-ai/mastra/commit/42a42cf3132b9786feecbb8c13c583dce5b0e198), [`ae08bf0`](https://github.com/mastra-ai/mastra/commit/ae08bf0ebc6a4e4da992b711c4a389c32ba84cf4), [`21735a7`](https://github.com/mastra-ai/mastra/commit/21735a7ef306963554a69a89b44f06c3bcd85141), [`1d877b8`](https://github.com/mastra-ai/mastra/commit/1d877b8d7b536a251c1a7a18db7ddcf4f68d6f8b)]:
176
+ - @mastra/core@1.0.0-beta.7
177
+
178
+ ## 1.0.0-beta.4
179
+
180
+ ### Patch Changes
181
+
182
+ - Fix MCPClient automatic reconnection when session becomes invalid ([#10660](https://github.com/mastra-ai/mastra/pull/10660))
183
+
184
+ When an MCP server restarts, the session ID becomes invalid causing "Bad Request: No valid session ID provided" errors. The MCPClient now automatically detects session-related errors, reconnects to the server, and retries the tool call.
185
+
186
+ This fix addresses issue #7675 where MCPClient would fail to reconnect after an MCP server went offline and came back online.
187
+
188
+ - Populate RequestContext from options.extra for workflows and agents ([#10655](https://github.com/mastra-ai/mastra/pull/10655))
189
+
190
+ Workflows and agents exposed as MCP tools now receive all keys from `options.extra` directly on the RequestContext. This allows workflows and agents to access authentication information (authInfo, sessionId, requestId, etc.) via `requestContext.get('key')` when exposed via MCPServer.
191
+
192
+ - Fix timeout parameter position in listTools call ([#10609](https://github.com/mastra-ai/mastra/pull/10609))
193
+
194
+ The MCP SDK's `listTools` signature is `listTools(params?, options?)`. Timeout was incorrectly passed as params (1st arg) instead of options (2nd arg), causing timeouts to not be applied to requests.
195
+
196
+ - Unified MastraServer API with MCP transport routes ([#10644](https://github.com/mastra-ai/mastra/pull/10644))
197
+
198
+ **Breaking Changes:**
199
+ - Renamed `HonoServerAdapter` to `MastraServer` in `@mastra/hono`
200
+ - Renamed `ExpressServerAdapter` to `MastraServer` in `@mastra/express`
201
+ - Configuration now passed to constructor instead of separate method calls
202
+ - Renamed base class from `ServerAdapter` to `MastraServerBase` in `@mastra/server`
203
+
204
+ **New Features:**
205
+ - Added MCP transport routes (HTTP and SSE) to server adapters
206
+ - MCP endpoints available at `/api/mcp/:serverId/mcp` (HTTP) and `/api/mcp/:serverId/sse` (SSE)
207
+ - Added `express.json()` middleware compatibility for MCP routes
208
+ - Moved authentication helpers from deployer to `@mastra/server/auth`
209
+
210
+ **Testing:**
211
+ - Added shared MCP route and transport test suites in `@internal/server-adapter-test-utils`
212
+ - Added comprehensive MCP endpoint tests for both Hono and Express adapters
213
+ - Added GitHub Actions workflow for server adapter CI testing
214
+
215
+ - Add MCP Roots capability support (fixes #8660) ([#10646](https://github.com/mastra-ai/mastra/pull/10646))
216
+
217
+ This adds support for the MCP Roots capability, allowing clients to expose filesystem roots to MCP servers like `@modelcontextprotocol/server-filesystem`.
218
+
219
+ **New Features:**
220
+ - Added `roots` option to server configuration for specifying allowed directories
221
+ - Client automatically advertises `roots` capability when roots are configured
222
+ - Client handles `roots/list` requests from servers per MCP spec
223
+ - Added `client.roots` getter to access configured roots
224
+ - Added `client.setRoots()` to dynamically update roots
225
+ - Added `client.sendRootsListChanged()` to notify servers of root changes
226
+
227
+ **Usage:**
228
+
229
+ ```typescript
230
+ const client = new MCPClient({
231
+ servers: {
232
+ filesystem: {
233
+ command: 'npx',
234
+ args: ['-y', '@modelcontextprotocol/server-filesystem', '/tmp'],
235
+ roots: [
236
+ { uri: 'file:///tmp', name: 'Temp Directory' },
237
+ { uri: 'file:///home/user/projects', name: 'Projects' },
238
+ ],
239
+ },
240
+ },
241
+ });
242
+ ```
243
+
244
+ Before this fix, the filesystem server would log:
245
+
246
+ > "Client does not support MCP Roots, using allowed directories set from server args"
247
+
248
+ After this fix, the server properly receives roots from the client:
249
+
250
+ > "Updated allowed directories from MCP roots: 2 valid directories"
251
+
252
+ - Add MCP progress notification support and refactor client structure ([#10637](https://github.com/mastra-ai/mastra/pull/10637))
253
+ - Added progress notification support for MCP tool execution. Enable with `enableProgressTracking: true` in server config and use `client.progress.onUpdate(handler)` to receive progress updates during long-running tool operations.
254
+ - Added `ProgressClientActions` class for handling progress notifications
255
+ - Refactored client action classes into `actions/` directory (elicitation, prompt, resource, progress)
256
+ - Extracted all type definitions to a dedicated `types.ts` file for better code organization
257
+
258
+ - Updated dependencies [[`ac0d2f4`](https://github.com/mastra-ai/mastra/commit/ac0d2f4ff8831f72c1c66c2be809706d17f65789), [`1a0d3fc`](https://github.com/mastra-ai/mastra/commit/1a0d3fc811482c9c376cdf79ee615c23bae9b2d6), [`85a628b`](https://github.com/mastra-ai/mastra/commit/85a628b1224a8f64cd82ea7f033774bf22df7a7e), [`c237233`](https://github.com/mastra-ai/mastra/commit/c23723399ccedf7f5744b3f40997b79246bfbe64), [`15f9e21`](https://github.com/mastra-ai/mastra/commit/15f9e216177201ea6e3f6d0bfb063fcc0953444f), [`ff94dea`](https://github.com/mastra-ai/mastra/commit/ff94dea935f4e34545c63bcb6c29804732698809), [`5b2ff46`](https://github.com/mastra-ai/mastra/commit/5b2ff4651df70c146523a7fca773f8eb0a2272f8), [`db41688`](https://github.com/mastra-ai/mastra/commit/db4168806d007417e2e60b4f68656dca4e5f40c9), [`5ca599d`](https://github.com/mastra-ai/mastra/commit/5ca599d0bb59a1595f19f58473fcd67cc71cef58), [`bff1145`](https://github.com/mastra-ai/mastra/commit/bff114556b3cbadad9b2768488708f8ad0e91475), [`5c8ca24`](https://github.com/mastra-ai/mastra/commit/5c8ca247094e0cc2cdbd7137822fb47241f86e77), [`e191844`](https://github.com/mastra-ai/mastra/commit/e1918444ca3f80e82feef1dad506cd4ec6e2875f), [`22553f1`](https://github.com/mastra-ai/mastra/commit/22553f11c63ee5e966a9c034a349822249584691), [`7237163`](https://github.com/mastra-ai/mastra/commit/72371635dbf96a87df4b073cc48fc655afbdce3d), [`2500740`](https://github.com/mastra-ai/mastra/commit/2500740ea23da067d6e50ec71c625ab3ce275e64), [`873ecbb`](https://github.com/mastra-ai/mastra/commit/873ecbb517586aa17d2f1e99283755b3ebb2863f), [`4f9bbe5`](https://github.com/mastra-ai/mastra/commit/4f9bbe5968f42c86f4930b8193de3c3c17e5bd36), [`02e51fe`](https://github.com/mastra-ai/mastra/commit/02e51feddb3d4155cfbcc42624fd0d0970d032c0), [`8f3fa3a`](https://github.com/mastra-ai/mastra/commit/8f3fa3a652bb77da092f913ec51ae46e3a7e27dc), [`cd29ad2`](https://github.com/mastra-ai/mastra/commit/cd29ad23a255534e8191f249593849ed29160886), [`bdf4d8c`](https://github.com/mastra-ai/mastra/commit/bdf4d8cdc656d8a2c21d81834bfa3bfa70f56c16), [`854e3da`](https://github.com/mastra-ai/mastra/commit/854e3dad5daac17a91a20986399d3a51f54bf68b), [`ce18d38`](https://github.com/mastra-ai/mastra/commit/ce18d38678c65870350d123955014a8432075fd9), [`cccf9c8`](https://github.com/mastra-ai/mastra/commit/cccf9c8b2d2dfc1a5e63919395b83d78c89682a0), [`61a5705`](https://github.com/mastra-ai/mastra/commit/61a570551278b6743e64243b3ce7d73de915ca8a), [`db70a48`](https://github.com/mastra-ai/mastra/commit/db70a48aeeeeb8e5f92007e8ede52c364ce15287), [`f0fdc14`](https://github.com/mastra-ai/mastra/commit/f0fdc14ee233d619266b3d2bbdeea7d25cfc6d13), [`db18bc9`](https://github.com/mastra-ai/mastra/commit/db18bc9c3825e2c1a0ad9a183cc9935f6691bfa1), [`9b37b56`](https://github.com/mastra-ai/mastra/commit/9b37b565e1f2a76c24f728945cc740c2b09be9da), [`41a23c3`](https://github.com/mastra-ai/mastra/commit/41a23c32f9877d71810f37e24930515df2ff7a0f), [`5d171ad`](https://github.com/mastra-ai/mastra/commit/5d171ad9ef340387276b77c2bb3e83e83332d729), [`f03ae60`](https://github.com/mastra-ai/mastra/commit/f03ae60500fe350c9d828621006cdafe1975fdd8), [`d1e74a0`](https://github.com/mastra-ai/mastra/commit/d1e74a0a293866dece31022047f5dbab65a304d0), [`39e7869`](https://github.com/mastra-ai/mastra/commit/39e7869bc7d0ee391077ce291474d8a84eedccff), [`5761926`](https://github.com/mastra-ai/mastra/commit/57619260c4a2cdd598763abbacd90de594c6bc76), [`c900fdd`](https://github.com/mastra-ai/mastra/commit/c900fdd504c41348efdffb205cfe80d48c38fa33), [`604a79f`](https://github.com/mastra-ai/mastra/commit/604a79fecf276e26a54a3fe01bb94e65315d2e0e), [`887f0b4`](https://github.com/mastra-ai/mastra/commit/887f0b4746cdbd7cb7d6b17ac9f82aeb58037ea5), [`2562143`](https://github.com/mastra-ai/mastra/commit/256214336b4faa78646c9c1776612393790d8784), [`ef11a61`](https://github.com/mastra-ai/mastra/commit/ef11a61920fa0ed08a5b7ceedd192875af119749)]:
259
+ - @mastra/core@1.0.0-beta.6
260
+
261
+ ## 1.0.0-beta.3
262
+
263
+ ### Patch Changes
264
+
265
+ - Fix MCPClient resource leak causing MaxListenersExceededWarning ([#10501](https://github.com/mastra-ai/mastra/pull/10501))
266
+
267
+ Fixes an issue where `InternalMastraMCPClient` registered event listeners to the `process` object for graceful shutdown but failed to remove them upon disconnection. This caused a memory leak after multiple connect/disconnect cycles, triggering the warning:
268
+
269
+ ```
270
+ MaxListenersExceededWarning: Possible EventEmitter memory leak detected. 11 SIGTERM listeners added to [process].
271
+ ```
272
+
273
+ The fix stores references to the exit hook unsubscribe function and SIGTERM handler, then properly cleans them up in `disconnect()`.
274
+
275
+ Additionally, users can now disable session management by passing `sessionIdGenerator: undefined` in `startHTTP()` options. This enables stateless MCP server deployments, which is useful for serverless environments.
276
+
277
+ Fixes #10499, #8526
278
+
279
+ - Fix MCP client to return structuredContent directly when tools define an outputSchema, ensuring output validation works correctly instead of failing with "expected X, received undefined" errors. ([#10442](https://github.com/mastra-ai/mastra/pull/10442))
280
+
281
+ - Updated dependencies [[`21a15de`](https://github.com/mastra-ai/mastra/commit/21a15de369fe82aac26bb642ed7be73505475e8b), [`feb7ee4`](https://github.com/mastra-ai/mastra/commit/feb7ee4d09a75edb46c6669a3beaceec78811747), [`b0e2ea5`](https://github.com/mastra-ai/mastra/commit/b0e2ea5b52c40fae438b9e2f7baee6f0f89c5442), [`c456e01`](https://github.com/mastra-ai/mastra/commit/c456e0149e3c176afcefdbd9bb1d2c5917723725), [`ab035c2`](https://github.com/mastra-ai/mastra/commit/ab035c2ef6d8cc7bb25f06f1a38508bd9e6f126b), [`1a46a56`](https://github.com/mastra-ai/mastra/commit/1a46a566f45a3fcbadc1cf36bf86d351f264bfa3), [`3cf540b`](https://github.com/mastra-ai/mastra/commit/3cf540b9fbfea8f4fc8d3a2319a4e6c0b0cbfd52), [`1c6ce51`](https://github.com/mastra-ai/mastra/commit/1c6ce51f875915ab57fd36873623013699a2a65d), [`898a972`](https://github.com/mastra-ai/mastra/commit/898a9727d286c2510d6b702dfd367e6aaf5c6b0f), [`a97003a`](https://github.com/mastra-ai/mastra/commit/a97003aa1cf2f4022a41912324a1e77263b326b8), [`ccc141e`](https://github.com/mastra-ai/mastra/commit/ccc141ed27da0abc3a3fc28e9e5128152e8e37f4), [`fe3b897`](https://github.com/mastra-ai/mastra/commit/fe3b897c2ccbcd2b10e81b099438c7337feddf89), [`00123ba`](https://github.com/mastra-ai/mastra/commit/00123ba96dc9e5cd0b110420ebdba56d8f237b25), [`29c4309`](https://github.com/mastra-ai/mastra/commit/29c4309f818b24304c041bcb4a8f19b5f13f6b62), [`16785ce`](https://github.com/mastra-ai/mastra/commit/16785ced928f6f22638f4488cf8a125d99211799), [`de8239b`](https://github.com/mastra-ai/mastra/commit/de8239bdcb1d8c0cfa06da21f1569912a66bbc8a), [`b5e6cd7`](https://github.com/mastra-ai/mastra/commit/b5e6cd77fc8c8e64e0494c1d06cee3d84e795d1e), [`3759cb0`](https://github.com/mastra-ai/mastra/commit/3759cb064935b5f74c65ac2f52a1145f7352899d), [`651e772`](https://github.com/mastra-ai/mastra/commit/651e772eb1475fb13e126d3fcc01751297a88214), [`b61b93f`](https://github.com/mastra-ai/mastra/commit/b61b93f9e058b11dd2eec169853175d31dbdd567), [`bae33d9`](https://github.com/mastra-ai/mastra/commit/bae33d91a63fbb64d1e80519e1fc1acaed1e9013), [`c0b731f`](https://github.com/mastra-ai/mastra/commit/c0b731fb27d712dc8582e846df5c0332a6a0c5ba), [`43ca8f2`](https://github.com/mastra-ai/mastra/commit/43ca8f2c7334851cc7b4d3d2f037d8784bfbdd5f), [`2ca67cc`](https://github.com/mastra-ai/mastra/commit/2ca67cc3bb1f6a617353fdcab197d9efebe60d6f), [`9e67002`](https://github.com/mastra-ai/mastra/commit/9e67002b52c9be19936c420a489dbee9c5fd6a78), [`35edc49`](https://github.com/mastra-ai/mastra/commit/35edc49ac0556db609189641d6341e76771b81fc)]:
282
+ - @mastra/core@1.0.0-beta.5
283
+
284
+ ## 1.0.0-beta.2
285
+
286
+ ### Patch Changes
287
+
288
+ - Add timeout configuration to mcp server config ([#9950](https://github.com/mastra-ai/mastra/pull/9950))
289
+
290
+ - Remove unused dependencies ([#10019](https://github.com/mastra-ai/mastra/pull/10019))
291
+
292
+ - Updated dependencies [[`2319326`](https://github.com/mastra-ai/mastra/commit/2319326f8c64e503a09bbcf14be2dd65405445e0), [`d629361`](https://github.com/mastra-ai/mastra/commit/d629361a60f6565b5bfb11976fdaf7308af858e2), [`08c31c1`](https://github.com/mastra-ai/mastra/commit/08c31c188ebccd598acaf55e888b6397d01f7eae), [`fd3d338`](https://github.com/mastra-ai/mastra/commit/fd3d338a2c362174ed5b383f1f011ad9fb0302aa), [`c30400a`](https://github.com/mastra-ai/mastra/commit/c30400a49b994b1b97256fe785eb6c906fc2b232), [`69e0a87`](https://github.com/mastra-ai/mastra/commit/69e0a878896a2da9494945d86e056a5f8f05b851), [`01f8878`](https://github.com/mastra-ai/mastra/commit/01f88783de25e4de048c1c8aace43e26373c6ea5), [`4c77209`](https://github.com/mastra-ai/mastra/commit/4c77209e6c11678808b365d545845918c40045c8), [`d827d08`](https://github.com/mastra-ai/mastra/commit/d827d0808ffe1f3553a84e975806cc989b9735dd), [`23c10a1`](https://github.com/mastra-ai/mastra/commit/23c10a1efdd9a693c405511ab2dc8a1236603162), [`676ccc7`](https://github.com/mastra-ai/mastra/commit/676ccc7fe92468d2d45d39c31a87825c89fd1ea0), [`c10398d`](https://github.com/mastra-ai/mastra/commit/c10398d5b88f1d4af556f4267ff06f1d11e89179), [`00c2387`](https://github.com/mastra-ai/mastra/commit/00c2387f5f04a365316f851e58666ac43f8c4edf), [`ad6250d`](https://github.com/mastra-ai/mastra/commit/ad6250dbdaad927e29f74a27b83f6c468b50a705), [`3a73998`](https://github.com/mastra-ai/mastra/commit/3a73998fa4ebeb7f3dc9301afe78095fc63e7999), [`e16d553`](https://github.com/mastra-ai/mastra/commit/e16d55338403c7553531cc568125c63d53653dff), [`4d59f58`](https://github.com/mastra-ai/mastra/commit/4d59f58de2d90d6e2810a19d4518e38ddddb9038), [`e1bb9c9`](https://github.com/mastra-ai/mastra/commit/e1bb9c94b4eb68b019ae275981be3feb769b5365), [`351a11f`](https://github.com/mastra-ai/mastra/commit/351a11fcaf2ed1008977fa9b9a489fc422e51cd4)]:
293
+ - @mastra/core@1.0.0-beta.3
294
+
3
295
  ## 1.0.0-beta.1
4
296
 
5
297
  ### Patch Changes
package/README.md CHANGED
@@ -381,41 +381,264 @@ Prompt notifications are delivered via SSE or compatible transports. Register ha
381
381
 
382
382
  ## Authentication
383
383
 
384
+ ### OAuth 2.0 Authentication (MCP Auth Spec)
385
+
386
+ Mastra provides full support for the [MCP OAuth specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization), including:
387
+
388
+ - **Server-side**: Protected Resource Metadata (RFC 9728), token validation middleware
389
+ - **Client-side**: OAuth client provider implementation with PKCE, token storage, and automatic refresh
390
+
391
+ #### Client-Side: Connecting to OAuth-Protected MCP Servers
392
+
393
+ Use `MCPOAuthClientProvider` to connect to MCP servers that require OAuth authentication:
394
+
395
+ ```typescript
396
+ import { MCPClient, MCPOAuthClientProvider } from '@mastra/mcp';
397
+
398
+ // Create an OAuth provider for your client
399
+ const oauthProvider = new MCPOAuthClientProvider({
400
+ redirectUrl: 'http://localhost:3000/oauth/callback',
401
+ clientMetadata: {
402
+ redirect_uris: ['http://localhost:3000/oauth/callback'],
403
+ client_name: 'My MCP Client',
404
+ grant_types: ['authorization_code', 'refresh_token'],
405
+ response_types: ['code'],
406
+ },
407
+ // Handle authorization redirects (for CLI apps, open browser; for web apps, redirect response)
408
+ onRedirectToAuthorization: url => {
409
+ console.log(`Please visit: ${url}`);
410
+ // Or: window.location.href = url.toString();
411
+ },
412
+ });
413
+
414
+ // Create client with OAuth provider
415
+ const client = new MCPClient({
416
+ servers: {
417
+ protectedServer: {
418
+ url: new URL('https://mcp.example.com/mcp'),
419
+ authProvider: oauthProvider,
420
+ },
421
+ },
422
+ });
423
+
424
+ await client.connect();
425
+ ```
426
+
427
+ For testing or when you already have a valid token, use `createSimpleTokenProvider`:
428
+
429
+ ```typescript
430
+ import { MCPClient, createSimpleTokenProvider } from '@mastra/mcp';
431
+
432
+ const provider = createSimpleTokenProvider('your-access-token', {
433
+ redirectUrl: 'http://localhost:3000/callback',
434
+ clientMetadata: {
435
+ redirect_uris: ['http://localhost:3000/callback'],
436
+ client_name: 'Test Client',
437
+ },
438
+ });
439
+
440
+ const client = new MCPClient({
441
+ servers: {
442
+ testServer: {
443
+ url: new URL('https://mcp.example.com/mcp'),
444
+ authProvider: provider,
445
+ },
446
+ },
447
+ });
448
+ ```
449
+
450
+ #### Server-Side: Protecting Your MCP Server with OAuth
451
+
452
+ Use `createOAuthMiddleware` to protect your MCP server endpoints:
453
+
454
+ ```typescript
455
+ import http from 'node:http';
456
+ import { MCPServer, createOAuthMiddleware, createStaticTokenValidator } from '@mastra/mcp';
457
+
458
+ // Create your MCP server
459
+ const mcpServer = new MCPServer({
460
+ id: 'protected-mcp-server',
461
+ name: 'Protected MCP Server',
462
+ version: '1.0.0',
463
+ tools: {
464
+ /* your tools */
465
+ },
466
+ });
467
+
468
+ // Create OAuth middleware
469
+ const oauthMiddleware = createOAuthMiddleware({
470
+ oauth: {
471
+ resource: 'https://mcp.example.com/mcp',
472
+ authorizationServers: ['https://auth.example.com'],
473
+ scopesSupported: ['mcp:read', 'mcp:write'],
474
+ resourceName: 'My Protected MCP Server',
475
+ // For production, use proper token validation (JWT, introspection, etc.)
476
+ validateToken: createStaticTokenValidator(['allowed-token-1', 'allowed-token-2']),
477
+ },
478
+ mcpPath: '/mcp',
479
+ });
480
+
481
+ // Create HTTP server with OAuth protection
482
+ const httpServer = http.createServer(async (req, res) => {
483
+ const url = new URL(req.url || '', 'https://mcp.example.com');
484
+
485
+ // Apply OAuth middleware first
486
+ const result = await oauthMiddleware(req, res, url);
487
+ if (!result.proceed) return; // Middleware handled the response (401, metadata, etc.)
488
+
489
+ // Token is valid, proceed to MCP handler
490
+ await mcpServer.startHTTP({ url, httpPath: '/mcp', req, res });
491
+ });
492
+
493
+ httpServer.listen(3000);
494
+ ```
495
+
496
+ The middleware automatically:
497
+
498
+ - Serves Protected Resource Metadata at `/.well-known/oauth-protected-resource`
499
+ - Returns `401 Unauthorized` with proper `WWW-Authenticate` headers when authentication is required
500
+ - Validates bearer tokens using your provided validator
501
+
502
+ #### Token Validation Options
503
+
504
+ For production use, implement proper token validation:
505
+
506
+ ```typescript
507
+ import { createOAuthMiddleware, createIntrospectionValidator } from '@mastra/mcp';
508
+
509
+ // Option 1: Token introspection (RFC 7662)
510
+ const middleware = createOAuthMiddleware({
511
+ oauth: {
512
+ resource: 'https://mcp.example.com/mcp',
513
+ authorizationServers: ['https://auth.example.com'],
514
+ validateToken: createIntrospectionValidator('https://auth.example.com/oauth/introspect', {
515
+ clientId: 'mcp-server',
516
+ clientSecret: 'secret',
517
+ }),
518
+ },
519
+ });
520
+
521
+ // Option 2: Custom validation (JWT, database lookup, etc.)
522
+ const middlewareCustom = createOAuthMiddleware({
523
+ oauth: {
524
+ resource: 'https://mcp.example.com/mcp',
525
+ authorizationServers: ['https://auth.example.com'],
526
+ validateToken: async (token, resource) => {
527
+ // Your custom validation logic
528
+ const decoded = await verifyJWT(token);
529
+ if (!decoded) {
530
+ return { valid: false, error: 'invalid_token', errorDescription: 'Token verification failed' };
531
+ }
532
+ return {
533
+ valid: true,
534
+ scopes: decoded.scope?.split(' ') || [],
535
+ subject: decoded.sub,
536
+ expiresAt: decoded.exp,
537
+ };
538
+ },
539
+ },
540
+ });
541
+ ```
542
+
543
+ #### Custom OAuth Storage
544
+
545
+ For persistent token storage across sessions, implement the `OAuthStorage` interface:
546
+
547
+ ```typescript
548
+ import { MCPOAuthClientProvider, OAuthStorage } from '@mastra/mcp';
549
+
550
+ // Example: Redis-based storage
551
+ class RedisOAuthStorage implements OAuthStorage {
552
+ constructor(
553
+ private redis: RedisClient,
554
+ private prefix: string,
555
+ ) {}
556
+
557
+ async set(key: string, value: string): Promise<void> {
558
+ await this.redis.set(`${this.prefix}:${key}`, value);
559
+ }
560
+
561
+ async get(key: string): Promise<string | undefined> {
562
+ return (await this.redis.get(`${this.prefix}:${key}`)) ?? undefined;
563
+ }
564
+
565
+ async delete(key: string): Promise<void> {
566
+ await this.redis.del(`${this.prefix}:${key}`);
567
+ }
568
+ }
569
+
570
+ const provider = new MCPOAuthClientProvider({
571
+ redirectUrl: 'http://localhost:3000/callback',
572
+ clientMetadata: {
573
+ /* ... */
574
+ },
575
+ storage: new RedisOAuthStorage(redisClient, 'oauth:user123'),
576
+ });
577
+ ```
578
+
384
579
  ### OAuth Token Refresh with AuthProvider
385
580
 
386
- For HTTP-based MCP servers that require OAuth authentication with automatic token refresh, you can use the `authProvider` option:
581
+ For simpler OAuth scenarios where you just need token refresh, you can pass an `authProvider` directly:
582
+
583
+ ### Custom Fetch for Dynamic Authentication
584
+
585
+ For HTTP servers, you can provide a custom `fetch` function to handle dynamic authentication, request interception, or other custom behavior. This is particularly useful when you need to refresh tokens on each request or customize request behavior.
586
+
587
+ When `fetch` is provided, `requestInit`, `eventSourceInit`, and `authProvider` become optional, as you can handle these concerns within your custom fetch function.
387
588
 
388
589
  ```typescript
389
- const httpClient = new MCPClient({
590
+ const mcpClient = new MCPClient({
390
591
  servers: {
391
- myOAuthClient: {
392
- url: new URL('https://your-mcp-server.com/mcp'),
393
- authProvider: {
394
- tokens: async () => {
395
- // Your token refresh logic here
396
- const refreshedToken = await refreshAccessToken();
397
- return {
398
- token: refreshedToken,
399
- type: 'Bearer',
400
- };
401
- },
402
- // Additional OAuth provider methods as needed
403
- redirectUrl: 'https://your-app.com/oauth/callback',
404
- clientMetadata: {
405
- /* ... */
406
- },
407
- // ... other OAuth provider properties
592
+ apiServer: {
593
+ url: new URL('https://api.example.com/mcp'),
594
+ fetch: async (url, init) => {
595
+ // Refresh token on each request
596
+ const token = await getAuthToken(); // Your token refresh logic
597
+
598
+ return fetch(url, {
599
+ ...init,
600
+ headers: {
601
+ ...init?.headers,
602
+ Authorization: `Bearer ${token}`,
603
+ },
604
+ });
408
605
  },
409
606
  },
410
607
  },
411
608
  });
412
609
  ```
413
610
 
414
- The `authProvider` is automatically passed to both Streamable HTTP and SSE transports.
611
+ The custom `fetch` function is automatically used for both Streamable HTTP and SSE transports, making it a simpler alternative to configuring `requestInit` and `eventSourceInit` separately.
415
612
 
416
613
  ### SSE Authentication and Headers (Legacy Fallback)
417
614
 
418
- When the client falls back to using the legacy SSE (Server-Sent Events) transport and you need to include authentication or custom headers, you need to configure headers in a specific way. The standard `requestInit` headers won't work alone because SSE connections using the browser's `EventSource` API don't support custom headers directly.
615
+ When the client falls back to using the legacy SSE (Server-Sent Events) transport and you need to include authentication or custom headers, you have two options:
616
+
617
+ **Option 1: Using custom `fetch` (Recommended)**
618
+
619
+ The simplest approach is to provide a custom `fetch` function, which will automatically be used for both POST requests and SSE connections:
620
+
621
+ ```typescript
622
+ const sseClient = new MCPClient({
623
+ servers: {
624
+ authenticatedSseClient: {
625
+ url: new URL('https://your-mcp-server.com/sse'),
626
+ fetch: async (url, init) => {
627
+ const headers = new Headers(init?.headers || {});
628
+ headers.set('Authorization', 'Bearer your-token');
629
+ return fetch(url, {
630
+ ...init,
631
+ headers,
632
+ });
633
+ },
634
+ },
635
+ },
636
+ });
637
+ ```
638
+
639
+ **Option 2: Using `requestInit` and `eventSourceInit`**
640
+
641
+ Alternatively, you can use both `requestInit` and `eventSourceInit`. The standard `requestInit` headers won't work alone because SSE connections using the browser's `EventSource` API don't support custom headers directly.
419
642
 
420
643
  The `eventSourceInit` configuration allows you to customize the underlying fetch request used for the SSE connection, ensuring your authentication headers are properly included.
421
644
 
@@ -489,9 +712,10 @@ Here are the available options within `MastraMCPServerDefinition`:
489
712
  - **`args`**: (Optional, string[]) For Stdio servers: Arguments to pass to the command.
490
713
  - **`env`**: (Optional, Record<string, string>) For Stdio servers: Environment variables to set for the command.
491
714
  - **`url`**: (Optional, URL) For HTTP servers (Streamable HTTP or SSE): The URL of the server.
492
- - **`requestInit`**: (Optional, RequestInit) For HTTP servers: Request configuration for the fetch API. Used for the initial Streamable HTTP connection attempt and subsequent POST requests. Also used for the initial SSE connection attempt.
493
- - **`eventSourceInit`**: (Optional, EventSourceInit) **Only** for the legacy SSE fallback: Custom fetch configuration for SSE connections. Required when using custom headers with SSE.
494
- - **`authProvider`**: (Optional, OAuthClientProvider) For HTTP servers: OAuth authentication provider for automatic token refresh. Automatically passed to both Streamable HTTP and SSE transports.
715
+ - **`fetch`**: (Optional, FetchLike) For HTTP servers: Custom fetch implementation used for all network requests. When provided, this function will be used for all HTTP requests, allowing you to add dynamic authentication headers (e.g., refreshing bearer tokens), customize request behavior per-request, or intercept and modify requests/responses. When `fetch` is provided, `requestInit`, `eventSourceInit`, and `authProvider` become optional, as you can handle these concerns within your custom fetch function.
716
+ - **`requestInit`**: (Optional, RequestInit) For HTTP servers: Request configuration for the fetch API. Used for the initial Streamable HTTP connection attempt and subsequent POST requests. Also used for the initial SSE connection attempt. Optional when `fetch` is provided.
717
+ - **`eventSourceInit`**: (Optional, EventSourceInit) **Only** for the legacy SSE fallback: Custom fetch configuration for SSE connections. Required when using custom headers with SSE. Optional when `fetch` is provided.
718
+ - **`authProvider`**: (Optional, OAuthClientProvider) For HTTP servers: OAuth authentication provider for automatic token refresh. Automatically passed to both Streamable HTTP and SSE transports. Optional when `fetch` is provided.
495
719
  - **`logger`**: (Optional, LogHandler) Optional additional handler for logging.
496
720
  - **`timeout`**: (Optional, number) Server-specific timeout in milliseconds, overriding the global client/configuration timeout.
497
721
  - **`capabilities`**: (Optional, ClientCapabilities) Server-specific capabilities configuration.
@@ -556,6 +780,8 @@ The client includes comprehensive error handling:
556
780
  ## Related Links
557
781
 
558
782
  - [Model Context Protocol Specification](https://modelcontextprotocol.io/specification)
783
+ - [MCP Authorization Specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization)
784
+ - [RFC 9728 - OAuth 2.0 Protected Resource Metadata](https://www.rfc-editor.org/rfc/rfc9728.html)
559
785
  - [@modelcontextprotocol/sdk Documentation](https://github.com/modelcontextprotocol/typescript-sdk)
560
786
  - [Mastra Docs: Using MCP With Mastra](/docs/agents/mcp-guide)
561
787
  - [Mastra Docs: MastraMCPClient Reference](/reference/tools/client)