@mastra/mcp 1.0.3 → 1.1.0

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/CHANGELOG.md CHANGED
@@ -1,5 +1,71 @@
1
1
  # @mastra/mcp
2
2
 
3
+ ## 1.1.0
4
+
5
+ ### Minor Changes
6
+
7
+ - Added requestContext support to the custom fetch option in MCP client HTTP server definitions. The fetch function now receives the current request context as an optional third argument, enabling users to forward authentication cookies, bearer tokens, and other request-scoped data from the incoming request to remote MCP servers during tool execution. ([#13773](https://github.com/mastra-ai/mastra/pull/13773))
8
+
9
+ **Example usage:**
10
+
11
+ ```typescript
12
+ const mcp = new MCPClient({
13
+ servers: {
14
+ myServer: {
15
+ url: new URL('https://api.example.com/mcp'),
16
+ fetch: async (url, init, requestContext) => {
17
+ const headers = new Headers(init?.headers);
18
+ const cookie = requestContext?.get('cookie');
19
+ if (cookie) {
20
+ headers.set('cookie', cookie);
21
+ }
22
+ return fetch(url, { ...init, headers });
23
+ },
24
+ },
25
+ },
26
+ });
27
+ ```
28
+
29
+ This change is fully backward-compatible — existing fetch functions with `(url, init)` signatures continue to work unchanged. Closes #13769.
30
+
31
+ ### Patch Changes
32
+
33
+ - Updated dependencies [[`41e48c1`](https://github.com/mastra-ai/mastra/commit/41e48c198eee846478e60c02ec432c19d322a517), [`82469d3`](https://github.com/mastra-ai/mastra/commit/82469d3135d5a49dd8dc8feec0ff398b4e0225a0), [`33e2fd5`](https://github.com/mastra-ai/mastra/commit/33e2fd5088f83666df17401e2da68c943dbc0448), [`7ef6e2c`](https://github.com/mastra-ai/mastra/commit/7ef6e2c61be5a42e26f55d15b5902866fc76634f), [`b12d2a5`](https://github.com/mastra-ai/mastra/commit/b12d2a59a48be0477cabae66eb6cf0fc94a7d40d), [`fa37d39`](https://github.com/mastra-ai/mastra/commit/fa37d39910421feaf8847716292e3d65dd4f30c2), [`b12d2a5`](https://github.com/mastra-ai/mastra/commit/b12d2a59a48be0477cabae66eb6cf0fc94a7d40d), [`71c38bf`](https://github.com/mastra-ai/mastra/commit/71c38bf905905148ecd0e75c07c1f9825d299b76), [`f993c38`](https://github.com/mastra-ai/mastra/commit/f993c3848c97479b813231be872443bedeced6ab), [`f51849a`](https://github.com/mastra-ai/mastra/commit/f51849a568935122b5100b7ee69704e6d680cf7b), [`9bf3a0d`](https://github.com/mastra-ai/mastra/commit/9bf3a0dac602787925f1762f1f0387d7b4a59620), [`cafa045`](https://github.com/mastra-ai/mastra/commit/cafa0453c9de141ad50c09a13894622dffdd9978), [`1fd9ddb`](https://github.com/mastra-ai/mastra/commit/1fd9ddbb3fe83b281b12bd2e27e426ae86288266), [`6135ef4`](https://github.com/mastra-ai/mastra/commit/6135ef4f5288652bf45f616ec590607e4c95f443), [`d9d228c`](https://github.com/mastra-ai/mastra/commit/d9d228c0c6ae82ae6ce3b540a3a56b2b1c2b8d98), [`5576507`](https://github.com/mastra-ai/mastra/commit/55765071e360fb97e443aa0a91ccf7e1cd8d92aa), [`79d69c9`](https://github.com/mastra-ai/mastra/commit/79d69c9d5f842ff1c31352fb6026f04c1f6190f3), [`94f44b8`](https://github.com/mastra-ai/mastra/commit/94f44b827ce57b179e50f4916a84c0fa6e7f3b8c), [`13187db`](https://github.com/mastra-ai/mastra/commit/13187dbac880174232dedc5a501ff6c5d0fe59bc), [`2ae5311`](https://github.com/mastra-ai/mastra/commit/2ae531185fff66a80fa165c0999e3d801900e89d), [`6135ef4`](https://github.com/mastra-ai/mastra/commit/6135ef4f5288652bf45f616ec590607e4c95f443)]:
34
+ - @mastra/core@1.10.0
35
+
36
+ ## 1.1.0-alpha.0
37
+
38
+ ### Minor Changes
39
+
40
+ - Added requestContext support to the custom fetch option in MCP client HTTP server definitions. The fetch function now receives the current request context as an optional third argument, enabling users to forward authentication cookies, bearer tokens, and other request-scoped data from the incoming request to remote MCP servers during tool execution. ([#13773](https://github.com/mastra-ai/mastra/pull/13773))
41
+
42
+ **Example usage:**
43
+
44
+ ```typescript
45
+ const mcp = new MCPClient({
46
+ servers: {
47
+ myServer: {
48
+ url: new URL('https://api.example.com/mcp'),
49
+ fetch: async (url, init, requestContext) => {
50
+ const headers = new Headers(init?.headers);
51
+ const cookie = requestContext?.get('cookie');
52
+ if (cookie) {
53
+ headers.set('cookie', cookie);
54
+ }
55
+ return fetch(url, { ...init, headers });
56
+ },
57
+ },
58
+ },
59
+ });
60
+ ```
61
+
62
+ This change is fully backward-compatible — existing fetch functions with `(url, init)` signatures continue to work unchanged. Closes #13769.
63
+
64
+ ### Patch Changes
65
+
66
+ - Updated dependencies [[`41e48c1`](https://github.com/mastra-ai/mastra/commit/41e48c198eee846478e60c02ec432c19d322a517), [`82469d3`](https://github.com/mastra-ai/mastra/commit/82469d3135d5a49dd8dc8feec0ff398b4e0225a0), [`33e2fd5`](https://github.com/mastra-ai/mastra/commit/33e2fd5088f83666df17401e2da68c943dbc0448), [`7ef6e2c`](https://github.com/mastra-ai/mastra/commit/7ef6e2c61be5a42e26f55d15b5902866fc76634f), [`b12d2a5`](https://github.com/mastra-ai/mastra/commit/b12d2a59a48be0477cabae66eb6cf0fc94a7d40d), [`fa37d39`](https://github.com/mastra-ai/mastra/commit/fa37d39910421feaf8847716292e3d65dd4f30c2), [`b12d2a5`](https://github.com/mastra-ai/mastra/commit/b12d2a59a48be0477cabae66eb6cf0fc94a7d40d), [`71c38bf`](https://github.com/mastra-ai/mastra/commit/71c38bf905905148ecd0e75c07c1f9825d299b76), [`f993c38`](https://github.com/mastra-ai/mastra/commit/f993c3848c97479b813231be872443bedeced6ab), [`f51849a`](https://github.com/mastra-ai/mastra/commit/f51849a568935122b5100b7ee69704e6d680cf7b), [`9bf3a0d`](https://github.com/mastra-ai/mastra/commit/9bf3a0dac602787925f1762f1f0387d7b4a59620), [`cafa045`](https://github.com/mastra-ai/mastra/commit/cafa0453c9de141ad50c09a13894622dffdd9978), [`1fd9ddb`](https://github.com/mastra-ai/mastra/commit/1fd9ddbb3fe83b281b12bd2e27e426ae86288266), [`6135ef4`](https://github.com/mastra-ai/mastra/commit/6135ef4f5288652bf45f616ec590607e4c95f443), [`d9d228c`](https://github.com/mastra-ai/mastra/commit/d9d228c0c6ae82ae6ce3b540a3a56b2b1c2b8d98), [`5576507`](https://github.com/mastra-ai/mastra/commit/55765071e360fb97e443aa0a91ccf7e1cd8d92aa), [`79d69c9`](https://github.com/mastra-ai/mastra/commit/79d69c9d5f842ff1c31352fb6026f04c1f6190f3), [`94f44b8`](https://github.com/mastra-ai/mastra/commit/94f44b827ce57b179e50f4916a84c0fa6e7f3b8c), [`13187db`](https://github.com/mastra-ai/mastra/commit/13187dbac880174232dedc5a501ff6c5d0fe59bc), [`2ae5311`](https://github.com/mastra-ai/mastra/commit/2ae531185fff66a80fa165c0999e3d801900e89d), [`6135ef4`](https://github.com/mastra-ai/mastra/commit/6135ef4f5288652bf45f616ec590607e4c95f443)]:
67
+ - @mastra/core@1.10.0-alpha.0
68
+
3
69
  ## 1.0.3
4
70
 
5
71
  ### Patch Changes
@@ -8,7 +8,7 @@ import { ProgressClientActions } from './actions/progress.js';
8
8
  import { PromptClientActions } from './actions/prompt.js';
9
9
  import { ResourceClientActions } from './actions/resource.js';
10
10
  import type { ElicitationHandler, ProgressHandler, InternalMastraMCPClientOptions, Root } from './types.js';
11
- export type { LoggingLevel, LogMessage, LogHandler, ElicitationHandler, ProgressHandler, MastraMCPServerDefinition, InternalMastraMCPClientOptions, Root, } from './types.js';
11
+ export type { LoggingLevel, LogMessage, LogHandler, ElicitationHandler, ProgressHandler, MastraFetchLike, MastraMCPServerDefinition, InternalMastraMCPClientOptions, Root, } from './types.js';
12
12
  /**
13
13
  * Internal MCP client implementation for connecting to a single MCP server.
14
14
  *
@@ -26,7 +26,7 @@ export declare class InternalMastraMCPClient extends MastraBase {
26
26
  private enableProgressTracking?;
27
27
  private serverConfig;
28
28
  private transport?;
29
- private currentOperationContext;
29
+ private operationContextStore;
30
30
  private exitHookUnsubscribe?;
31
31
  private sigTermHandler?;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AAI,OAAO,CAAC,iBAAiB,CAAC;IAO/C;;;;;OAKG;IACG,SAAS,CAAC,EACd,IAAI,EACJ,IAAI,EACJ,OAAO,GACR,EAAE;QACD,IAAI,EAAE,MAAM,CAAC;QACb,IAAI,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,GAAG,CAAC,CAAC;QAC3B,OAAO,CAAC,EAAE,MAAM,CAAC;KAClB,GAAG,OAAO,CAAC,eAAe,CAAC;IAS5B;;;OAGG;IACH,uCAAuC,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,IAAI;IAOlE,qCAAqC,CACnC,OAAO,EAAE,CAAC,MAAM,EAAE,CAAC,CAAC,KAAK,CAAC,OAAO,iCAAiC,CAAC,CAAC,QAAQ,CAAC,KAAK,IAAI,GACrF,IAAI;IAOP,yCAAyC,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,IAAI;IAOpE,4BAA4B,CAAC,OAAO,EAAE,kBAAkB,GAAG,IAAI;IAQ/D,8BAA8B,CAAC,OAAO,EAAE,eAAe,GAAG,IAAI;YAOhD,kBAAkB;IA0ChC;;;;OAIG;IACH,OAAO,CAAC,gBAAgB;YAqBV,mBAAmB;IA+C3B,KAAK,IAAI,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,IAAI,CAAC,GAAG,EAAE,GAAG,EAAE,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC;CAsHjE"}
@@ -1,8 +1,37 @@
1
1
  import type { RequestContext } from '@mastra/core/di';
2
2
  import type { SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';
3
3
  import type { StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
4
- import type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
4
+ export type { FetchLike } from '@modelcontextprotocol/sdk/shared/transport.js';
5
5
  import type { ClientCapabilities, ElicitRequest, ElicitResult, LoggingLevel, ProgressNotification } from '@modelcontextprotocol/sdk/types.js';
6
+ /**
7
+ * Extended fetch function type that receives the current request context as a third argument.
8
+ *
9
+ * This allows custom fetch implementations to access request-scoped data (e.g., authentication
10
+ * cookies, bearer tokens) from the incoming request and forward them to the MCP server.
11
+ *
12
+ * The `requestContext` parameter is `null` when no context is available (e.g., during
13
+ * initial connection or when a tool is called without a request context).
14
+ *
15
+ * @example
16
+ * ```typescript
17
+ * const mcp = new MCPClient({
18
+ * servers: {
19
+ * myServer: {
20
+ * url: new URL('https://api.example.com/mcp'),
21
+ * fetch: (url, init, requestContext) => {
22
+ * const headers = new Headers(init?.headers);
23
+ * const cookie = requestContext?.get('cookie');
24
+ * if (cookie) {
25
+ * headers.set('cookie', cookie);
26
+ * }
27
+ * return fetch(url, { ...init, headers });
28
+ * },
29
+ * },
30
+ * },
31
+ * });
32
+ * ```
33
+ */
34
+ export type MastraFetchLike = (url: string | URL, init?: RequestInit, requestContext?: RequestContext | null) => Promise<Response>;
6
35
  export type { LoggingLevel } from '@modelcontextprotocol/sdk/types.js';
7
36
  /**
8
37
  * Log message structure for MCP client logging.
@@ -137,9 +166,14 @@ export type HttpServerDefinition = BaseServerOptions & {
137
166
  *
138
167
  * When provided, this function will be used for all HTTP requests, allowing you to:
139
168
  * - Add dynamic authentication headers (e.g., refreshing bearer tokens)
169
+ * - Forward request-scoped data (cookies, tokens) from the incoming request to the MCP server
140
170
  * - Customize request behavior per-request
141
171
  * - Intercept and modify requests/responses
142
172
  *
173
+ * The third `requestContext` parameter provides access to request-scoped data set by middleware
174
+ * or passed during agent/tool execution. It is `null` when no context is available (e.g.,
175
+ * during the initial connection handshake).
176
+ *
143
177
  * When `fetch` is provided, `requestInit`, `eventSourceInit`, and `authProvider` become optional,
144
178
  * as you can handle these concerns within your custom fetch function.
145
179
  *
@@ -147,20 +181,19 @@ export type HttpServerDefinition = BaseServerOptions & {
147
181
  * ```typescript
148
182
  * {
149
183
  * url: new URL('https://api.example.com/mcp'),
150
- * fetch: async (url, init) => {
151
- * const token = await getAuthToken(); // Your token refresh logic
152
- * return fetch(url, {
153
- * ...init,
154
- * headers: {
155
- * ...init?.headers,
156
- * Authorization: `Bearer ${token}`,
157
- * },
158
- * });
184
+ * fetch: async (url, init, requestContext) => {
185
+ * const headers = new Headers(init?.headers);
186
+ * // Forward auth cookie from the incoming request
187
+ * const cookie = requestContext?.get('cookie');
188
+ * if (cookie) {
189
+ * headers.set('cookie', cookie);
190
+ * }
191
+ * return fetch(url, { ...init, headers });
159
192
  * },
160
193
  * }
161
194
  * ```
162
195
  */
163
- fetch?: FetchLike;
196
+ fetch?: MastraFetchLike;
164
197
  /** Optional request configuration for HTTP requests (optional when `fetch` is provided) */
165
198
  requestInit?: StreamableHTTPClientTransportOptions['requestInit'];
166
199
  /** Optional configuration for SSE fallback (required when using custom headers with SSE, optional when `fetch` is provided) */
@@ -1 +1 @@
1
- {"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/client/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,iBAAiB,CAAC;AACtD,OAAO,KAAK,EAAE,yBAAyB,EAAE,MAAM,yCAAyC,CAAC;AACzF,OAAO,KAAK,EAAE,oCAAoC,EAAE,MAAM,oDAAoD,CAAC;AAC/G,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,+CAA+C,CAAC;AAC/E,OAAO,KAAK,EACV,kBAAkB,EAClB,aAAa,EACb,YAAY,EACZ,YAAY,EACZ,oBAAoB,EACrB,MAAM,oCAAoC,CAAC;AAG5C,YAAY,EAAE,YAAY,EAAE,MAAM,oCAAoC,CAAC;AAEvE;;GAEG;AACH,MAAM,WAAW,UAAU;IACzB,wDAAwD;IACxD,KAAK,EAAE,YAAY,CAAC;IACpB,0BAA0B;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,yCAAyC;IACzC,SAAS,EAAE,IAAI,CAAC;IAChB,oDAAoD;IACpD,UAAU,EAAE,MAAM,CAAC;IACnB,kCAAkC;IAClC,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,E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8BAA8B;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,uCAAuC;IACvC,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB,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: "1.0.3"
6
+ version: "1.1.0"
7
7
  ---
8
8
 
9
9
  ## When to use
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": "1.0.3",
2
+ "version": "1.1.0",
3
3
  "package": "@mastra/mcp",
4
4
  "exports": {
5
5
  "UnauthorizedError": {
@@ -16,11 +16,11 @@ constructor({
16
16
 
17
17
  ### MCPClientOptions
18
18
 
19
- **id?:** (`string`): Optional unique identifier for the configuration instance. Use this to prevent memory leaks when creating multiple instances with identical configurations.
19
+ **id** (`string`): Optional unique identifier for the configuration instance. Use this to prevent memory leaks when creating multiple instances with identical configurations.
20
20
 
21
- **servers:** (`Record<string, MastraMCPServerDefinition>`): A map of server configurations, where each key is a unique server identifier and the value is the server configuration.
21
+ **servers** (`Record<string, MastraMCPServerDefinition>`): A map of server configurations, where each key is a unique server identifier and the value is the server configuration.
22
22
 
23
- **timeout?:** (`number`): Global timeout value in milliseconds for all servers unless overridden in individual server configs. (Default: `60000`)
23
+ **timeout** (`number`): Global timeout value in milliseconds for all servers unless overridden in individual server configs. (Default: `60000`)
24
24
 
25
25
  ### MastraMCPServerDefinition
26
26
 
@@ -29,29 +29,29 @@ Each server in the `servers` map is configured using the `MastraMCPServerDefinit
29
29
  - If `command` is provided, it uses the Stdio transport.
30
30
  - If `url` is provided, it first attempts to use the Streamable HTTP transport and falls back to the legacy SSE transport if the initial connection fails.
31
31
 
32
- **command?:** (`string`): For Stdio servers: The command to execute.
32
+ **command** (`string`): For Stdio servers: The command to execute.
33
33
 
34
- **args?:** (`string[]`): For Stdio servers: Arguments to pass to the command.
34
+ **args** (`string[]`): For Stdio servers: Arguments to pass to the command.
35
35
 
36
- **env?:** (`Record<string, string>`): For Stdio servers: Environment variables to set for the command.
36
+ **env** (`Record<string, string>`): For Stdio servers: Environment variables to set for the command.
37
37
 
38
- **url?:** (`URL`): For HTTP servers (Streamable HTTP or SSE): The URL of the server.
38
+ **url** (`URL`): For HTTP servers (Streamable HTTP or SSE): The URL of the server.
39
39
 
40
- **requestInit?:** (`RequestInit`): For HTTP servers: Request configuration for the fetch API.
40
+ **requestInit** (`RequestInit`): For HTTP servers: Request configuration for the fetch API.
41
41
 
42
- **eventSourceInit?:** (`EventSourceInit`): For SSE fallback: Custom fetch configuration for SSE connections. Required when using custom headers with SSE.
42
+ **eventSourceInit** (`EventSourceInit`): For SSE fallback: Custom fetch configuration for SSE connections. Required when using custom headers with SSE.
43
43
 
44
- **fetch?:** (`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.
44
+ **fetch** (`MastraFetchLike`): For HTTP servers: Custom fetch implementation used for all network requests. Receives an optional third \`requestContext\` parameter containing request-scoped data (e.g., authentication cookies, bearer tokens) from the incoming request. When provided, this function will be used for all HTTP requests, allowing you to add dynamic authentication headers, forward request-scoped credentials to the MCP server, 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.
45
45
 
46
- **logger?:** (`LogHandler`): Optional additional handler for logging.
46
+ **logger** (`LogHandler`): Optional additional handler for logging.
47
47
 
48
- **timeout?:** (`number`): Server-specific timeout in milliseconds.
48
+ **timeout** (`number`): Server-specific timeout in milliseconds.
49
49
 
50
- **capabilities?:** (`ClientCapabilities`): Server-specific capabilities configuration.
50
+ **capabilities** (`ClientCapabilities`): Server-specific capabilities configuration.
51
51
 
52
- **authProvider?:** (`OAuthClientProvider`): For HTTP servers: OAuth authentication provider for automatic token refresh and OAuth flow management. Use MCPOAuthClientProvider for a ready-to-use implementation.
52
+ **authProvider** (`OAuthClientProvider`): For HTTP servers: OAuth authentication provider for automatic token refresh and OAuth flow management. Use MCPOAuthClientProvider for a ready-to-use implementation.
53
53
 
54
- **enableServerLogs?:** (`boolean`): Whether to enable logging for this server. (Default: `true`)
54
+ **enableServerLogs** (`boolean`): Whether to enable logging for this server. (Default: `true`)
55
55
 
56
56
  ## Methods
57
57
 
@@ -873,7 +873,9 @@ MCPClient handles server connections gracefully:
873
873
 
874
874
  ## Using Custom Fetch for Dynamic Authentication
875
875
 
876
- 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.
876
+ 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 forward user credentials from the incoming request to the MCP server.
877
+
878
+ The custom `fetch` function receives an optional third `requestContext` parameter, which provides access to request-scoped data (e.g., authentication cookies, bearer tokens) set by middleware or passed during agent/tool execution. The `requestContext` is `null` during the initial connection handshake.
877
879
 
878
880
  When `fetch` is provided, `requestInit`, `eventSourceInit`, and `authProvider` become optional, as you can handle these concerns within your custom fetch function.
879
881
 
@@ -882,21 +884,30 @@ const mcpClient = new MCPClient({
882
884
  servers: {
883
885
  apiServer: {
884
886
  url: new URL('https://api.example.com/mcp'),
885
- fetch: async (url, init) => {
886
- // Refresh token on each request
887
- const token = await getAuthToken() // Your token refresh logic
888
-
889
- return fetch(url, {
890
- ...init,
891
- headers: {
892
- ...init?.headers,
893
- Authorization: `Bearer ${token}`,
894
- },
895
- })
887
+ fetch: async (url, init, requestContext) => {
888
+ const headers = new Headers(init?.headers)
889
+ // Forward auth cookie from the incoming request
890
+ const cookie = requestContext?.get('cookie')
891
+ if (cookie) {
892
+ headers.set('cookie', cookie)
893
+ }
894
+ return fetch(url, { ...init, headers })
896
895
  },
897
896
  },
898
897
  },
899
898
  })
899
+
900
+ // Use with an agent — requestContext is automatically forwarded
901
+ const agent = new Agent({
902
+ name: 'My Agent',
903
+ instructions: 'You are a helpful assistant.',
904
+ model: openai('gpt-4o'),
905
+ tools: await mcpClient.listTools(),
906
+ })
907
+
908
+ await agent.generate('Hello!', {
909
+ requestContext: myRequestContext, // forwarded to the custom fetch
910
+ })
900
911
  ```
901
912
 
902
913
  ## Using SSE Request Headers
@@ -51,37 +51,37 @@ const server = new MCPServer({
51
51
 
52
52
  The constructor accepts an `MCPServerConfig` object with the following properties:
53
53
 
54
- **id:** (`string`): Unique identifier for the server. This ID is preserved when the server is registered with Mastra and can be used to retrieve the server via getMCPServerById().
54
+ **id** (`string`): Unique identifier for the server. This ID is preserved when the server is registered with Mastra and can be used to retrieve the server via getMCPServerById().
55
55
 
56
- **name:** (`string`): A descriptive name for your server (e.g., 'My Weather and Agent Server').
56
+ **name** (`string`): A descriptive name for your server (e.g., 'My Weather and Agent Server').
57
57
 
58
- **version:** (`string`): The semantic version of your server (e.g., '1.0.0').
58
+ **version** (`string`): The semantic version of your server (e.g., '1.0.0').
59
59
 
60
- **tools:** (`ToolsInput`): An object where keys are tool names and values are Mastra tool definitions (created with \`createTool\` or Vercel AI SDK). These tools will be directly exposed.
60
+ **tools** (`ToolsInput`): An object where keys are tool names and values are Mastra tool definitions (created with \`createTool\` or Vercel AI SDK). These tools will be directly exposed.
61
61
 
62
- **agents?:** (`Record<string, Agent>`): An object where keys are agent identifiers and values are Mastra Agent instances. Each agent will be automatically converted into a tool named \`ask\_\<agentIdentifier>\`. The agent \*\*must\*\* have a non-empty \`description\` string property defined in its constructor configuration. This description will be used in the tool's description. If an agent's description is missing or empty, an error will be thrown during MCPServer initialization.
62
+ **agents** (`Record<string, Agent>`): An object where keys are agent identifiers and values are Mastra Agent instances. Each agent will be automatically converted into a tool named \`ask\_\<agentIdentifier>\`. The agent \*\*must\*\* have a non-empty \`description\` string property defined in its constructor configuration. This description will be used in the tool's description. If an agent's description is missing or empty, an error will be thrown during MCPServer initialization.
63
63
 
64
- **workflows?:** (`Record<string, Workflow>`): An object where keys are workflow identifiers and values are Mastra Workflow instances. Each workflow is converted into a tool named \`run\_\<workflowKey>\`. The workflow's \`inputSchema\` becomes the tool's input schema. The workflow \*\*must\*\* have a non-empty \`description\` string property, which is used for the tool's description. If a workflow's description is missing or empty, an error will be thrown. The tool executes the workflow by calling \`workflow\.createRun()\` followed by \`run.start({ inputData: \<tool\_input> })\`. If a tool name derived from an agent or workflow (e.g., \`ask\_myAgent\` or \`run\_myWorkflow\`) collides with an explicitly defined tool name or another derived name, the explicitly defined tool takes precedence, and a warning is logged. Agents/workflows leading to subsequent collisions are skipped.
64
+ **workflows** (`Record<string, Workflow>`): An object where keys are workflow identifiers and values are Mastra Workflow instances. Each workflow is converted into a tool named \`run\_\<workflowKey>\`. The workflow's \`inputSchema\` becomes the tool's input schema. The workflow \*\*must\*\* have a non-empty \`description\` string property, which is used for the tool's description. If a workflow's description is missing or empty, an error will be thrown. The tool executes the workflow by calling \`workflow\.createRun()\` followed by \`run.start({ inputData: \<tool\_input> })\`. If a tool name derived from an agent or workflow (e.g., \`ask\_myAgent\` or \`run\_myWorkflow\`) collides with an explicitly defined tool name or another derived name, the explicitly defined tool takes precedence, and a warning is logged. Agents/workflows leading to subsequent collisions are skipped.
65
65
 
66
- **description?:** (`string`): Optional description of what the MCP server does.
66
+ **description** (`string`): Optional description of what the MCP server does.
67
67
 
68
- **instructions?:** (`string`): Optional instructions describing how to use the server and its features.
68
+ **instructions** (`string`): Optional instructions describing how to use the server and its features.
69
69
 
70
- **repository?:** (`Repository`): Optional repository information for the server's source code.
70
+ **repository** (`Repository`): Optional repository information for the server's source code.
71
71
 
72
- **releaseDate?:** (`string`): Optional release date of this server version (ISO 8601 string). Defaults to the time of instantiation if not provided.
72
+ **releaseDate** (`string`): Optional release date of this server version (ISO 8601 string). Defaults to the time of instantiation if not provided.
73
73
 
74
- **isLatest?:** (`boolean`): Optional flag indicating if this is the latest version. Defaults to true if not provided.
74
+ **isLatest** (`boolean`): Optional flag indicating if this is the latest version. Defaults to true if not provided.
75
75
 
76
- **packageCanonical?:** (`'npm' | 'docker' | 'pypi' | 'crates' | string`): Optional canonical packaging format if the server is distributed as a package (e.g., 'npm', 'docker').
76
+ **packageCanonical** (`'npm' | 'docker' | 'pypi' | 'crates' | string`): Optional canonical packaging format if the server is distributed as a package (e.g., 'npm', 'docker').
77
77
 
78
- **packages?:** (`PackageInfo[]`): Optional list of installable packages for this server.
78
+ **packages** (`PackageInfo[]`): Optional list of installable packages for this server.
79
79
 
80
- **remotes?:** (`RemoteInfo[]`): Optional list of remote access points for this server.
80
+ **remotes** (`RemoteInfo[]`): Optional list of remote access points for this server.
81
81
 
82
- **resources?:** (`MCPServerResources`): An object defining how the server should handle MCP resources. See Resource Handling section for details.
82
+ **resources** (`MCPServerResources`): An object defining how the server should handle MCP resources. See Resource Handling section for details.
83
83
 
84
- **prompts?:** (`MCPServerPrompts`): An object defining how the server should handle MCP prompts. See Prompt Handling section for details.
84
+ **prompts** (`MCPServerPrompts`): An object defining how the server should handle MCP prompts. See Prompt Handling section for details.
85
85
 
86
86
  ## Exposing Agents as Tools
87
87
 
@@ -228,15 +228,15 @@ httpServer.listen(PORT, () => {
228
228
 
229
229
  Here are the details for the values needed by the `startSSE` method:
230
230
 
231
- **url:** (`URL`): The web address the user is requesting.
231
+ **url** (`URL`): The web address the user is requesting.
232
232
 
233
- **ssePath:** (`string`): The specific part of the URL where clients will connect for SSE (e.g., '/sse').
233
+ **ssePath** (`string`): The specific part of the URL where clients will connect for SSE (e.g., '/sse').
234
234
 
235
- **messagePath:** (`string`): The specific part of the URL where clients will send messages (e.g., '/message').
235
+ **messagePath** (`string`): The specific part of the URL where clients will send messages (e.g., '/message').
236
236
 
237
- **req:** (`any`): The incoming request object from your web server.
237
+ **req** (`any`): The incoming request object from your web server.
238
238
 
239
- **res:** (`any`): The response object from your web server, used to send data back.
239
+ **res** (`any`): The response object from your web server, used to send data back.
240
240
 
241
241
  ### startHonoSSE()
242
242
 
@@ -280,15 +280,15 @@ httpServer.listen(PORT, () => {
280
280
 
281
281
  Here are the details for the values needed by the `startHonoSSE` method:
282
282
 
283
- **url:** (`URL`): The web address the user is requesting.
283
+ **url** (`URL`): The web address the user is requesting.
284
284
 
285
- **ssePath:** (`string`): The specific part of the URL where clients will connect for SSE (e.g., '/hono-sse').
285
+ **ssePath** (`string`): The specific part of the URL where clients will connect for SSE (e.g., '/hono-sse').
286
286
 
287
- **messagePath:** (`string`): The specific part of the URL where clients will send messages (e.g., '/message').
287
+ **messagePath** (`string`): The specific part of the URL where clients will send messages (e.g., '/message').
288
288
 
289
- **req:** (`any`): The incoming request object from your web server.
289
+ **req** (`any`): The incoming request object from your web server.
290
290
 
291
- **res:** (`any`): The response object from your web server, used to send data back.
291
+ **res** (`any`): The response object from your web server, used to send data back.
292
292
 
293
293
  ### startHTTP()
294
294
 
@@ -402,27 +402,27 @@ serve(async req => {
402
402
 
403
403
  Here are the details for the values needed by the `startHTTP` method:
404
404
 
405
- **url:** (`URL`): The web address the user is requesting.
405
+ **url** (`URL`): The web address the user is requesting.
406
406
 
407
- **httpPath:** (`string`): The specific part of the URL where the MCP server will handle HTTP requests (e.g., '/mcp').
407
+ **httpPath** (`string`): The specific part of the URL where the MCP server will handle HTTP requests (e.g., '/mcp').
408
408
 
409
- **req:** (`http.IncomingMessage`): The incoming request object from your web server.
409
+ **req** (`http.IncomingMessage`): The incoming request object from your web server.
410
410
 
411
- **res:** (`http.ServerResponse`): The response object from your web server, used to send data back.
411
+ **res** (`http.ServerResponse`): The response object from your web server, used to send data back.
412
412
 
413
- **options:** (`StreamableHTTPServerTransportOptions`): Optional configuration for the HTTP transport. See the options table below for more details.
413
+ **options** (`StreamableHTTPServerTransportOptions`): Optional configuration for the HTTP transport. See the options table below for more details.
414
414
 
415
415
  The `StreamableHTTPServerTransportOptions` object allows you to customize the behavior of the HTTP transport. Here are the available options:
416
416
 
417
- **serverless:** (`boolean`): If \`true\`, runs in stateless mode without session management. Each request is handled independently with a fresh server instance. Essential for serverless environments (Cloudflare Workers, Supabase Edge Functions, Vercel Edge, etc.) where sessions cannot persist between invocations. Defaults to \`false\`.
417
+ **serverless** (`boolean`): If \`true\`, runs in stateless mode without session management. Each request is handled independently with a fresh server instance. Essential for serverless environments (Cloudflare Workers, Supabase Edge Functions, Vercel Edge, etc.) where sessions cannot persist between invocations. Defaults to \`false\`.
418
418
 
419
- **sessionIdGenerator:** (`(() => string) | undefined`): A function that generates a unique session ID. This should be a cryptographically secure, globally unique string. Return \`undefined\` to disable session management.
419
+ **sessionIdGenerator** (`(() => string) | undefined`): A function that generates a unique session ID. This should be a cryptographically secure, globally unique string. Return \`undefined\` to disable session management.
420
420
 
421
- **onsessioninitialized:** (`(sessionId: string) => void`): A callback that is invoked when a new session is initialized. This is useful for tracking active MCP sessions.
421
+ **onsessioninitialized** (`(sessionId: string) => void`): A callback that is invoked when a new session is initialized. This is useful for tracking active MCP sessions.
422
422
 
423
- **enableJsonResponse:** (`boolean`): If \`true\`, the server will return plain JSON responses instead of using Server-Sent Events (SSE) for streaming. Defaults to \`false\`.
423
+ **enableJsonResponse** (`boolean`): If \`true\`, the server will return plain JSON responses instead of using Server-Sent Events (SSE) for streaming. Defaults to \`false\`.
424
424
 
425
- **eventStore:** (`EventStore`): An event store for message resumability. Providing this enables clients to reconnect and resume message streams.
425
+ **eventStore** (`EventStore`): An event store for message resumability. Providing this enables clients to reconnect and resume message streams.
426
426
 
427
427
  ### close()
428
428
 
@@ -516,11 +516,11 @@ async executeTool(
516
516
  ): Promise<any>
517
517
  ```
518
518
 
519
- **toolId:** (`string`): The ID/name of the tool to execute.
519
+ **toolId** (`string`): The ID/name of the tool to execute.
520
520
 
521
- **args:** (`any`): The arguments to pass to the tool's execute function.
521
+ **args** (`any`): The arguments to pass to the tool's execute function.
522
522
 
523
- **executionContext?:** (`object`): Optional context for the tool execution, like messages or a toolCallId.
523
+ **executionContext** (`object`): Optional context for the tool execution, like messages or a toolCallId.
524
524
 
525
525
  ## Resource Handling
526
526
 
@@ -1073,17 +1073,17 @@ const customMiddleware = createOAuthMiddleware({
1073
1073
 
1074
1074
  ### OAuth Middleware Options
1075
1075
 
1076
- **oauth.resource:** (`string`): The canonical URL of your MCP server. This is returned in Protected Resource Metadata.
1076
+ **oauth.resource** (`string`): The canonical URL of your MCP server. This is returned in Protected Resource Metadata.
1077
1077
 
1078
- **oauth.authorizationServers:** (`string[]`): URLs of authorization servers that can issue tokens for this resource.
1078
+ **oauth.authorizationServers** (`string[]`): URLs of authorization servers that can issue tokens for this resource.
1079
1079
 
1080
- **oauth.scopesSupported?:** (`string[]`): Scopes supported by this MCP server. (Default: `['mcp:read', 'mcp:write']`)
1080
+ **oauth.scopesSupported** (`string[]`): Scopes supported by this MCP server. (Default: `['mcp:read', 'mcp:write']`)
1081
1081
 
1082
- **oauth.resourceName?:** (`string`): Human-readable name for this resource server.
1082
+ **oauth.resourceName** (`string`): Human-readable name for this resource server.
1083
1083
 
1084
- **oauth.validateToken?:** (`(token: string, resource: string) => Promise<TokenValidationResult>`): Function to validate access tokens. If not provided, tokens are accepted without validation (NOT recommended for production).
1084
+ **oauth.validateToken** (`(token: string, resource: string) => Promise<TokenValidationResult>`): Function to validate access tokens. If not provided, tokens are accepted without validation (NOT recommended for production).
1085
1085
 
1086
- **mcpPath?:** (`string`): Path where the MCP endpoint is served. Only requests to this path require authentication. (Default: `'/mcp'`)
1086
+ **mcpPath** (`string`): Path where the MCP endpoint is served. Only requests to this path require authentication. (Default: `'/mcp'`)
1087
1087
 
1088
1088
  ## Authentication Context
1089
1089