@mastra/mcp 1.0.0 → 1.0.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.
@@ -0,0 +1,962 @@
1
+ # MCPClient
2
+
3
+ The `MCPClient` class provides a way to manage multiple MCP server connections and their tools in a Mastra application. It handles connection lifecycle, tool namespacing, and provides access to tools across all configured servers.
4
+
5
+ ## Constructor
6
+
7
+ Creates a new instance of the MCPClient class.
8
+
9
+ ```typescript
10
+ constructor({
11
+ id?: string;
12
+ servers: Record<string, MastraMCPServerDefinition>;
13
+ timeout?: number;
14
+ }: MCPClientOptions)
15
+ ```
16
+
17
+ ### MCPClientOptions
18
+
19
+ **id?:** (`string`): Optional unique identifier for the configuration instance. Use this to prevent memory leaks when creating multiple instances with identical configurations.
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.
22
+
23
+ **timeout?:** (`number`): Global timeout value in milliseconds for all servers unless overridden in individual server configs. (Default: `60000`)
24
+
25
+ ### MastraMCPServerDefinition
26
+
27
+ Each server in the `servers` map is configured using the `MastraMCPServerDefinition` type. The transport type is detected based on the provided parameters:
28
+
29
+ - If `command` is provided, it uses the Stdio transport.
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
+
32
+ **command?:** (`string`): For Stdio servers: The command to execute.
33
+
34
+ **args?:** (`string[]`): For Stdio servers: Arguments to pass to the command.
35
+
36
+ **env?:** (`Record<string, string>`): For Stdio servers: Environment variables to set for the command.
37
+
38
+ **url?:** (`URL`): For HTTP servers (Streamable HTTP or SSE): The URL of the server.
39
+
40
+ **requestInit?:** (`RequestInit`): For HTTP servers: Request configuration for the fetch API.
41
+
42
+ **eventSourceInit?:** (`EventSourceInit`): For SSE fallback: Custom fetch configuration for SSE connections. Required when using custom headers with SSE.
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.
45
+
46
+ **logger?:** (`LogHandler`): Optional additional handler for logging.
47
+
48
+ **timeout?:** (`number`): Server-specific timeout in milliseconds.
49
+
50
+ **capabilities?:** (`ClientCapabilities`): Server-specific capabilities configuration.
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.
53
+
54
+ **enableServerLogs?:** (`boolean`): Whether to enable logging for this server. (Default: `true`)
55
+
56
+ ## Methods
57
+
58
+ ### listTools()
59
+
60
+ Retrieves all tools from all configured servers, with tool names namespaced by their server name (in the format `serverName_toolName`) to prevent conflicts. Intended to be passed onto an Agent definition.
61
+
62
+ ```ts
63
+ new Agent({ id: "agent", tools: await mcp.listTools() });
64
+ ```
65
+
66
+ ### listToolsets()
67
+
68
+ Returns an object mapping namespaced tool names (in the format `serverName.toolName`) to their tool implementations. Intended to be passed dynamically into the generate or stream method.
69
+
70
+ ```typescript
71
+ const res = await agent.stream(prompt, {
72
+ toolsets: await mcp.listToolsets(),
73
+ });
74
+ ```
75
+
76
+ ### disconnect()
77
+
78
+ Disconnects from all MCP servers and cleans up resources.
79
+
80
+ ```typescript
81
+ async disconnect(): Promise<void>
82
+ ```
83
+
84
+ ### `resources` Property
85
+
86
+ The `MCPClient` instance has a `resources` property that provides access to resource-related operations.
87
+
88
+ ```typescript
89
+ const mcpClient = new MCPClient({
90
+ /* ...servers configuration... */
91
+ });
92
+
93
+ // Access resource methods via mcpClient.resources
94
+ const allResourcesByServer = await mcpClient.resources.list();
95
+ const templatesByServer = await mcpClient.resources.templates();
96
+ // ... and so on for other resource methods.
97
+ ```
98
+
99
+ #### `resources.list()`
100
+
101
+ Retrieves all available resources from all connected MCP servers, grouped by server name.
102
+
103
+ ```typescript
104
+ async list(): Promise<Record<string, Resource[]>>
105
+ ```
106
+
107
+ Example:
108
+
109
+ ```typescript
110
+ const resourcesByServer = await mcpClient.resources.list();
111
+ for (const serverName in resourcesByServer) {
112
+ console.log(`Resources from ${serverName}:`, resourcesByServer[serverName]);
113
+ }
114
+ ```
115
+
116
+ #### `resources.templates()`
117
+
118
+ Retrieves all available resource templates from all connected MCP servers, grouped by server name.
119
+
120
+ ```typescript
121
+ async templates(): Promise<Record<string, ResourceTemplate[]>>
122
+ ```
123
+
124
+ Example:
125
+
126
+ ```typescript
127
+ const templatesByServer = await mcpClient.resources.templates();
128
+ for (const serverName in templatesByServer) {
129
+ console.log(`Templates from ${serverName}:`, templatesByServer[serverName]);
130
+ }
131
+ ```
132
+
133
+ #### `resources.read(serverName: string, uri: string)`
134
+
135
+ Reads the content of a specific resource from a named server.
136
+
137
+ ```typescript
138
+ async read(serverName: string, uri: string): Promise<ReadResourceResult>
139
+ ```
140
+
141
+ - `serverName`: The identifier of the server (key used in the `servers` constructor option).
142
+ - `uri`: The URI of the resource to read.
143
+
144
+ Example:
145
+
146
+ ```typescript
147
+ const content = await mcpClient.resources.read(
148
+ "myWeatherServer",
149
+ "weather://current",
150
+ );
151
+ console.log("Current weather:", content.contents[0].text);
152
+ ```
153
+
154
+ #### `resources.subscribe(serverName: string, uri: string)`
155
+
156
+ Subscribes to updates for a specific resource on a named server.
157
+
158
+ ```typescript
159
+ async subscribe(serverName: string, uri: string): Promise<object>
160
+ ```
161
+
162
+ Example:
163
+
164
+ ```typescript
165
+ await mcpClient.resources.subscribe("myWeatherServer", "weather://current");
166
+ ```
167
+
168
+ #### `resources.unsubscribe(serverName: string, uri: string)`
169
+
170
+ Unsubscribes from updates for a specific resource on a named server.
171
+
172
+ ```typescript
173
+ async unsubscribe(serverName: string, uri: string): Promise<object>
174
+ ```
175
+
176
+ Example:
177
+
178
+ ```typescript
179
+ await mcpClient.resources.unsubscribe("myWeatherServer", "weather://current");
180
+ ```
181
+
182
+ #### `resources.onUpdated(serverName: string, handler: (params: { uri: string }) => void)`
183
+
184
+ Sets a notification handler that will be called when a subscribed resource on a specific server is updated.
185
+
186
+ ```typescript
187
+ async onUpdated(serverName: string, handler: (params: { uri: string }) => void): Promise<void>
188
+ ```
189
+
190
+ Example:
191
+
192
+ ```typescript
193
+ mcpClient.resources.onUpdated("myWeatherServer", (params) => {
194
+ console.log(`Resource updated on myWeatherServer: ${params.uri}`);
195
+ // You might want to re-fetch the resource content here
196
+ // await mcpClient.resources.read("myWeatherServer", params.uri);
197
+ });
198
+ ```
199
+
200
+ #### `resources.onListChanged(serverName: string, handler: () => void)`
201
+
202
+ Sets a notification handler that will be called when the overall list of available resources changes on a specific server.
203
+
204
+ ```typescript
205
+ async onListChanged(serverName: string, handler: () => void): Promise<void>
206
+ ```
207
+
208
+ Example:
209
+
210
+ ```typescript
211
+ mcpClient.resources.onListChanged("myWeatherServer", () => {
212
+ console.log("Resource list changed on myWeatherServer.");
213
+ // You should re-fetch the list of resources
214
+ // await mcpClient.resources.list();
215
+ });
216
+ ```
217
+
218
+ ### `elicitation` Property
219
+
220
+ The `MCPClient` instance has an `elicitation` property that provides access to elicitation-related operations. Elicitation allows MCP servers to request structured information from users.
221
+
222
+ ```typescript
223
+ const mcpClient = new MCPClient({
224
+ /* ...servers configuration... */
225
+ });
226
+
227
+ // Set up elicitation handler
228
+ mcpClient.elicitation.onRequest("serverName", async (request) => {
229
+ // Handle elicitation request from server
230
+ console.log("Server requests:", request.message);
231
+ console.log("Schema:", request.requestedSchema);
232
+
233
+ // Return user response
234
+ return {
235
+ action: "accept",
236
+ content: { name: "John Doe", email: "john@example.com" },
237
+ };
238
+ });
239
+ ```
240
+
241
+ #### `elicitation.onRequest(serverName: string, handler: ElicitationHandler)`
242
+
243
+ Sets up a handler function that will be called when any connected MCP server sends an elicitation request. The handler receives the request and must return a response.
244
+
245
+ **ElicitationHandler Function:**
246
+
247
+ The handler function receives a request object with:
248
+
249
+ - `message`: A human-readable message describing what information is needed
250
+ - `requestedSchema`: A JSON schema defining the structure of the expected response
251
+
252
+ The handler must return an `ElicitResult` with:
253
+
254
+ - `action`: One of `'accept'`, `'decline'`, or `'cancel'`
255
+ - `content`: The user's data (only when action is `'accept'`)
256
+
257
+ **Example:**
258
+
259
+ ```typescript
260
+ mcpClient.elicitation.onRequest("serverName", async (request) => {
261
+ console.log(`Server requests: ${request.message}`);
262
+
263
+ // Example: Simple user input collection
264
+ if (request.requestedSchema.properties.name) {
265
+ // Simulate user accepting and providing data
266
+ return {
267
+ action: "accept",
268
+ content: {
269
+ name: "Alice Smith",
270
+ email: "alice@example.com",
271
+ },
272
+ };
273
+ }
274
+
275
+ // Simulate user declining the request
276
+ return { action: "decline" };
277
+ });
278
+ ```
279
+
280
+ **Complete Interactive Example:**
281
+
282
+ ```typescript
283
+ import { MCPClient } from "@mastra/mcp";
284
+ import { createInterface } from "readline";
285
+
286
+ const readline = createInterface({
287
+ input: process.stdin,
288
+ output: process.stdout,
289
+ });
290
+
291
+ function askQuestion(question: string): Promise<string> {
292
+ return new Promise((resolve) => {
293
+ readline.question(question, (answer) => resolve(answer.trim()));
294
+ });
295
+ }
296
+
297
+ const mcpClient = new MCPClient({
298
+ servers: {
299
+ interactiveServer: {
300
+ url: new URL("http://localhost:3000/mcp"),
301
+ },
302
+ },
303
+ });
304
+
305
+ // Set up interactive elicitation handler
306
+ await mcpClient.elicitation.onRequest("interactiveServer", async (request) => {
307
+ console.log(`\n📋 Server Request: ${request.message}`);
308
+ console.log("Required information:");
309
+
310
+ const schema = request.requestedSchema;
311
+ const properties = schema.properties || {};
312
+ const required = schema.required || [];
313
+ const content: Record<string, any> = {};
314
+
315
+ // Collect input for each field
316
+ for (const [fieldName, fieldSchema] of Object.entries(properties)) {
317
+ const field = fieldSchema as any;
318
+ const isRequired = required.includes(fieldName);
319
+
320
+ let prompt = `${field.title || fieldName}`;
321
+ if (field.description) prompt += ` (${field.description})`;
322
+ if (isRequired) prompt += " *required*";
323
+ prompt += ": ";
324
+
325
+ const answer = await askQuestion(prompt);
326
+
327
+ // Handle cancellation
328
+ if (answer.toLowerCase() === "cancel") {
329
+ return { action: "cancel" };
330
+ }
331
+
332
+ // Validate required fields
333
+ if (answer === "" && isRequired) {
334
+ console.log(`❌ ${fieldName} is required`);
335
+ return { action: "decline" };
336
+ }
337
+
338
+ if (answer !== "") {
339
+ content[fieldName] = answer;
340
+ }
341
+ }
342
+
343
+ // Confirm submission
344
+ console.log("\n📝 You provided:");
345
+ console.log(JSON.stringify(content, null, 2));
346
+
347
+ const confirm = await askQuestion(
348
+ "\nSubmit this information? (yes/no/cancel): ",
349
+ );
350
+
351
+ if (confirm.toLowerCase() === "yes" || confirm.toLowerCase() === "y") {
352
+ return { action: "accept", content };
353
+ } else if (confirm.toLowerCase() === "cancel") {
354
+ return { action: "cancel" };
355
+ } else {
356
+ return { action: "decline" };
357
+ }
358
+ });
359
+ ```
360
+
361
+ ### `prompts` Property
362
+
363
+ The `MCPClient` instance has a `prompts` property that provides access to prompt-related operations.
364
+
365
+ ```typescript
366
+ const mcpClient = new MCPClient({
367
+ /* ...servers configuration... */
368
+ });
369
+
370
+ // Access prompt methods via mcpClient.prompts
371
+ const allPromptsByServer = await mcpClient.prompts.list();
372
+ const { prompt, messages } = await mcpClient.prompts.get({
373
+ serverName: "myWeatherServer",
374
+ name: "current",
375
+ });
376
+ ```
377
+
378
+ #### `prompts.list()`
379
+
380
+ Retrieves all available prompts from all connected MCP servers, grouped by server name.
381
+
382
+ ```typescript
383
+ async list(): Promise<Record<string, Prompt[]>>
384
+ ```
385
+
386
+ Example:
387
+
388
+ ```typescript
389
+ const promptsByServer = await mcpClient.prompts.list();
390
+ for (const serverName in promptsByServer) {
391
+ console.log(`Prompts from ${serverName}:`, promptsByServer[serverName]);
392
+ }
393
+ ```
394
+
395
+ #### `prompts.get({ serverName, name, args?, version? })`
396
+
397
+ Retrieves a specific prompt and its messages from a server.
398
+
399
+ ```typescript
400
+ async get({
401
+ serverName,
402
+ name,
403
+ args?,
404
+ version?,
405
+ }: {
406
+ serverName: string;
407
+ name: string;
408
+ args?: Record<string, any>;
409
+ version?: string;
410
+ }): Promise<{ prompt: Prompt; messages: PromptMessage[] }>
411
+ ```
412
+
413
+ Example:
414
+
415
+ ```typescript
416
+ const { prompt, messages } = await mcpClient.prompts.get({
417
+ serverName: "myWeatherServer",
418
+ name: "current",
419
+ args: { location: "London" },
420
+ });
421
+ console.log(prompt);
422
+ console.log(messages);
423
+ ```
424
+
425
+ #### `prompts.onListChanged(serverName: string, handler: () => void)`
426
+
427
+ Sets a notification handler that will be called when the list of available prompts changes on a specific server.
428
+
429
+ ```typescript
430
+ async onListChanged(serverName: string, handler: () => void): Promise<void>
431
+ ```
432
+
433
+ Example:
434
+
435
+ ```typescript
436
+ mcpClient.prompts.onListChanged("myWeatherServer", () => {
437
+ console.log("Prompt list changed on myWeatherServer.");
438
+ // You should re-fetch the list of prompts
439
+ // await mcpClient.prompts.list();
440
+ });
441
+ ```
442
+
443
+ ### `progress` Property
444
+
445
+ The `MCPClient` instance has a `progress` property for subscribing to progress notifications emitted by MCP servers while tools execute.
446
+
447
+ ```typescript
448
+ const mcpClient = new MCPClient({
449
+ servers: {
450
+ myServer: {
451
+ url: new URL('http://localhost:4111/api/mcp/myServer/mcp'),
452
+ // Enabled by default; set to false to disable
453
+ enableProgressTracking: true,
454
+ },
455
+ },
456
+ });
457
+
458
+ // Subscribe to progress updates for a specific server
459
+ await mcpClient.progress.onUpdate('myServer', (params) => {
460
+ console.log('📊 Progress:', params.progress, '/', params.total);
461
+ if (params.message) console.log('Message:', params.message);
462
+ if (params.progressToken) console.log('Token:', params.progressToken);
463
+ });
464
+ ```
465
+
466
+ #### `progress.onUpdate(serverName: string, handler)`
467
+
468
+ Registers a handler function to receive progress updates from the specified server.
469
+
470
+ ```typescript
471
+ async onUpdate(
472
+ serverName: string,
473
+ handler: (params: {
474
+ progressToken: string;
475
+ progress: number;
476
+ total?: number;
477
+ message?: string;
478
+ }) => void,
479
+ ): Promise<void>
480
+ ```
481
+
482
+ Notes:
483
+
484
+ - When `enableProgressTracking` is true (default), tool calls include a `progressToken` so you can correlate updates to a specific run.
485
+ - If you pass a `runId` when executing a tool, it will be used as the `progressToken`.
486
+
487
+ To disable progress tracking for a server:
488
+
489
+ ```typescript
490
+ const mcpClient = new MCPClient({
491
+ servers: {
492
+ myServer: {
493
+ url: new URL('http://localhost:4111/api/mcp/myServer/mcp'),
494
+ enableProgressTracking: false,
495
+ },
496
+ },
497
+ });
498
+ ```
499
+
500
+ ## Elicitation
501
+
502
+ Elicitation is a feature that allows MCP servers to request structured information from users. When a server needs additional data, it can send an elicitation request that the client handles by prompting the user. A common example is during a tool call.
503
+
504
+ ### How Elicitation Works
505
+
506
+ 1. **Server Request**: An MCP server tool calls `server.elicitation.sendRequest()` with a message and schema
507
+ 2. **Client Handler**: Your elicitation handler function is called with the request
508
+ 3. **User Interaction**: Your handler collects user input (via UI, CLI, etc.)
509
+ 4. **Response**: Your handler returns the user's response (accept/decline/cancel)
510
+ 5. **Tool Continuation**: The server tool receives the response and continues execution
511
+
512
+ ### Setting Up Elicitation
513
+
514
+ You must set up an elicitation handler before tools that use elicitation are called:
515
+
516
+ ```typescript
517
+ import { MCPClient } from "@mastra/mcp";
518
+
519
+ const mcpClient = new MCPClient({
520
+ servers: {
521
+ interactiveServer: {
522
+ url: new URL("http://localhost:3000/mcp"),
523
+ },
524
+ },
525
+ });
526
+
527
+ // Set up elicitation handler
528
+ mcpClient.elicitation.onRequest("interactiveServer", async (request) => {
529
+ // Handle the server's request for user input
530
+ console.log(`Server needs: ${request.message}`);
531
+
532
+ // Your logic to collect user input
533
+ const userData = await collectUserInput(request.requestedSchema);
534
+
535
+ return {
536
+ action: "accept",
537
+ content: userData,
538
+ };
539
+ });
540
+ ```
541
+
542
+ ### Response Types
543
+
544
+ Your elicitation handler must return one of three response types:
545
+
546
+ - **Accept**: User provided data and confirmed submission
547
+
548
+ ```typescript
549
+ return {
550
+ action: "accept",
551
+ content: { name: "John Doe", email: "john@example.com" },
552
+ };
553
+ ```
554
+
555
+ - **Decline**: User explicitly declined to provide the information
556
+
557
+ ```typescript
558
+ return { action: "decline" };
559
+ ```
560
+
561
+ - **Cancel**: User dismissed or cancelled the request
562
+
563
+ ```typescript
564
+ return { action: "cancel" };
565
+ ```
566
+
567
+ ### Schema-Based Input Collection
568
+
569
+ The `requestedSchema` provides structure for the data the server needs:
570
+
571
+ ```typescript
572
+ await mcpClient.elicitation.onRequest("interactiveServer", async (request) => {
573
+ const { properties, required = [] } = request.requestedSchema;
574
+ const content: Record<string, any> = {};
575
+
576
+ for (const [fieldName, fieldSchema] of Object.entries(properties || {})) {
577
+ const field = fieldSchema as any;
578
+ const isRequired = required.includes(fieldName);
579
+
580
+ // Collect input based on field type and requirements
581
+ const value = await promptUser({
582
+ name: fieldName,
583
+ title: field.title,
584
+ description: field.description,
585
+ type: field.type,
586
+ required: isRequired,
587
+ format: field.format,
588
+ enum: field.enum,
589
+ });
590
+
591
+ if (value !== null) {
592
+ content[fieldName] = value;
593
+ }
594
+ }
595
+
596
+ return { action: "accept", content };
597
+ });
598
+ ```
599
+
600
+ ### Best Practices
601
+
602
+ - **Always handle elicitation**: Set up your handler before calling tools that might use elicitation
603
+ - **Validate input**: Check that required fields are provided
604
+ - **Respect user choice**: Handle decline and cancel responses gracefully
605
+ - **Clear UI**: Make it obvious what information is being requested and why
606
+ - **Security**: Never auto-accept requests for sensitive information
607
+
608
+ ## OAuth Authentication
609
+
610
+ For connecting to MCP servers that require OAuth authentication per the [MCP Auth Specification](https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization), use the `MCPOAuthClientProvider`:
611
+
612
+ ```typescript
613
+ import { MCPClient, MCPOAuthClientProvider } from "@mastra/mcp";
614
+
615
+ // Create an OAuth provider
616
+ const oauthProvider = new MCPOAuthClientProvider({
617
+ redirectUrl: "http://localhost:3000/oauth/callback",
618
+ clientMetadata: {
619
+ redirect_uris: ["http://localhost:3000/oauth/callback"],
620
+ client_name: "My MCP Client",
621
+ grant_types: ["authorization_code", "refresh_token"],
622
+ response_types: ["code"],
623
+ },
624
+ onRedirectToAuthorization: (url) => {
625
+ // Handle authorization redirect (open browser, redirect response, etc.)
626
+ console.log(`Please visit: ${url}`);
627
+ },
628
+ });
629
+
630
+ // Use the provider with MCPClient
631
+ const client = new MCPClient({
632
+ servers: {
633
+ protectedServer: {
634
+ url: new URL("https://mcp.example.com/mcp"),
635
+ authProvider: oauthProvider,
636
+ },
637
+ },
638
+ });
639
+ ```
640
+
641
+ ### Quick Token Provider
642
+
643
+ For testing or when you already have a valid access token:
644
+
645
+ ```typescript
646
+ import { MCPClient, createSimpleTokenProvider } from "@mastra/mcp";
647
+
648
+ const provider = createSimpleTokenProvider("your-access-token", {
649
+ redirectUrl: "http://localhost:3000/callback",
650
+ clientMetadata: {
651
+ redirect_uris: ["http://localhost:3000/callback"],
652
+ client_name: "Test Client",
653
+ },
654
+ });
655
+
656
+ const client = new MCPClient({
657
+ servers: {
658
+ testServer: {
659
+ url: new URL("https://mcp.example.com/mcp"),
660
+ authProvider: provider,
661
+ },
662
+ },
663
+ });
664
+ ```
665
+
666
+ ### Custom Token Storage
667
+
668
+ For persistent token storage across sessions, implement the `OAuthStorage` interface:
669
+
670
+ ```typescript
671
+ import { MCPOAuthClientProvider, OAuthStorage } from "@mastra/mcp";
672
+
673
+ class DatabaseOAuthStorage implements OAuthStorage {
674
+ constructor(private db: Database, private userId: string) {}
675
+
676
+ async set(key: string, value: string): Promise<void> {
677
+ await this.db.query(
678
+ "INSERT INTO oauth_tokens (user_id, key, value) VALUES (?, ?, ?) ON CONFLICT DO UPDATE SET value = ?",
679
+ [this.userId, key, value, value]
680
+ );
681
+ }
682
+
683
+ async get(key: string): Promise<string | undefined> {
684
+ const result = await this.db.query(
685
+ "SELECT value FROM oauth_tokens WHERE user_id = ? AND key = ?",
686
+ [this.userId, key]
687
+ );
688
+ return result?.[0]?.value;
689
+ }
690
+
691
+ async delete(key: string): Promise<void> {
692
+ await this.db.query(
693
+ "DELETE FROM oauth_tokens WHERE user_id = ? AND key = ?",
694
+ [this.userId, key]
695
+ );
696
+ }
697
+ }
698
+
699
+ const provider = new MCPOAuthClientProvider({
700
+ redirectUrl: "http://localhost:3000/callback",
701
+ clientMetadata: { /* ... */ },
702
+ storage: new DatabaseOAuthStorage(db, "user-123"),
703
+ });
704
+ ```
705
+
706
+ ## Examples
707
+
708
+ ### Static Tool Configuration
709
+
710
+ For tools where you have a single connection to the MCP server for you entire app, use `listTools()` and pass the tools to your agent:
711
+
712
+ ```typescript
713
+ import { MCPClient } from "@mastra/mcp";
714
+ import { Agent } from "@mastra/core/agent";
715
+
716
+ const mcp = new MCPClient({
717
+ servers: {
718
+ stockPrice: {
719
+ command: "npx",
720
+ args: ["tsx", "stock-price.ts"],
721
+ env: {
722
+ API_KEY: "your-api-key",
723
+ },
724
+ log: (logMessage) => {
725
+ console.log(`[${logMessage.level}] ${logMessage.message}`);
726
+ },
727
+ },
728
+ weather: {
729
+ url: new URL("http://localhost:8080/sse"),
730
+ },
731
+ },
732
+ timeout: 30000, // Global 30s timeout
733
+ });
734
+
735
+ // Create an agent with access to all tools
736
+ const agent = new Agent({
737
+ id: "multi-tool-agent",
738
+ name: "Multi-tool Agent",
739
+ instructions: "You have access to multiple tool servers.",
740
+ model: "openai/gpt-5.1",
741
+ tools: await mcp.listTools(),
742
+ });
743
+
744
+ // Example of using resource methods
745
+ async function checkWeatherResource() {
746
+ try {
747
+ const weatherResources = await mcp.resources.list();
748
+ if (weatherResources.weather && weatherResources.weather.length > 0) {
749
+ const currentWeatherURI = weatherResources.weather[0].uri;
750
+ const weatherData = await mcp.resources.read(
751
+ "weather",
752
+ currentWeatherURI,
753
+ );
754
+ console.log("Weather data:", weatherData.contents[0].text);
755
+ }
756
+ } catch (error) {
757
+ console.error("Error fetching weather resource:", error);
758
+ }
759
+ }
760
+ checkWeatherResource();
761
+
762
+ // Example of using prompt methods
763
+ async function checkWeatherPrompt() {
764
+ try {
765
+ const weatherPrompts = await mcp.prompts.list();
766
+ if (weatherPrompts.weather && weatherPrompts.weather.length > 0) {
767
+ const currentWeatherPrompt = weatherPrompts.weather.find(
768
+ (p) => p.name === "current",
769
+ );
770
+ if (currentWeatherPrompt) {
771
+ console.log("Weather prompt:", currentWeatherPrompt);
772
+ } else {
773
+ console.log("Current weather prompt not found");
774
+ }
775
+ }
776
+ } catch (error) {
777
+ console.error("Error fetching weather prompt:", error);
778
+ }
779
+ }
780
+ checkWeatherPrompt();
781
+ ```
782
+
783
+ ### Dynamic toolsets
784
+
785
+ When you need a new MCP connection for each user, use `listToolsets()` and add the tools when calling stream or generate:
786
+
787
+ ```typescript
788
+ import { Agent } from "@mastra/core/agent";
789
+ import { MCPClient } from "@mastra/mcp";
790
+
791
+ // Create the agent first, without any tools
792
+ const agent = new Agent({
793
+ id: "multi-tool-agent",
794
+ name: "Multi-tool Agent",
795
+ instructions: "You help users check stocks and weather.",
796
+ model: "openai/gpt-5.1",
797
+ });
798
+
799
+ // Later, configure MCP with user-specific settings
800
+ const mcp = new MCPClient({
801
+ servers: {
802
+ stockPrice: {
803
+ command: "npx",
804
+ args: ["tsx", "stock-price.ts"],
805
+ env: {
806
+ API_KEY: "user-123-api-key",
807
+ },
808
+ timeout: 20000, // Server-specific timeout
809
+ },
810
+ weather: {
811
+ url: new URL("http://localhost:8080/sse"),
812
+ requestInit: {
813
+ headers: {
814
+ Authorization: `Bearer user-123-token`,
815
+ },
816
+ },
817
+ },
818
+ },
819
+ });
820
+
821
+ // Pass all toolsets to stream() or generate()
822
+ const response = await agent.stream(
823
+ "How is AAPL doing and what is the weather?",
824
+ {
825
+ toolsets: await mcp.listToolsets(),
826
+ },
827
+ );
828
+ ```
829
+
830
+ ## Instance Management
831
+
832
+ The `MCPClient` class includes built-in memory leak prevention for managing multiple instances:
833
+
834
+ 1. Creating multiple instances with identical configurations without an `id` will throw an error to prevent memory leaks
835
+ 2. If you need multiple instances with identical configurations, provide a unique `id` for each instance
836
+ 3. Call `await configuration.disconnect()` before recreating an instance with the same configuration
837
+ 4. If you only need one instance, consider moving the configuration to a higher scope to avoid recreation
838
+
839
+ For example, if you try to create multiple instances with the same configuration without an `id`:
840
+
841
+ ```typescript
842
+ // First instance - OK
843
+ const mcp1 = new MCPClient({
844
+ servers: {
845
+ /* ... */
846
+ },
847
+ });
848
+
849
+ // Second instance with same config - Will throw an error
850
+ const mcp2 = new MCPClient({
851
+ servers: {
852
+ /* ... */
853
+ },
854
+ });
855
+
856
+ // To fix, either:
857
+ // 1. Add unique IDs
858
+ const mcp3 = new MCPClient({
859
+ id: "instance-1",
860
+ servers: {
861
+ /* ... */
862
+ },
863
+ });
864
+
865
+ // 2. Or disconnect before recreating
866
+ await mcp1.disconnect();
867
+ const mcp4 = new MCPClient({
868
+ servers: {
869
+ /* ... */
870
+ },
871
+ });
872
+ ```
873
+
874
+ ## Server Lifecycle
875
+
876
+ MCPClient handles server connections gracefully:
877
+
878
+ 1. Automatic connection management for multiple servers
879
+ 2. Graceful server shutdown to prevent error messages during development
880
+ 3. Proper cleanup of resources when disconnecting
881
+
882
+ ## Using Custom Fetch for Dynamic Authentication
883
+
884
+ 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.
885
+
886
+ When `fetch` is provided, `requestInit`, `eventSourceInit`, and `authProvider` become optional, as you can handle these concerns within your custom fetch function.
887
+
888
+ ```typescript
889
+ const mcpClient = new MCPClient({
890
+ servers: {
891
+ apiServer: {
892
+ url: new URL("https://api.example.com/mcp"),
893
+ fetch: async (url, init) => {
894
+ // Refresh token on each request
895
+ const token = await getAuthToken(); // Your token refresh logic
896
+
897
+ return fetch(url, {
898
+ ...init,
899
+ headers: {
900
+ ...init?.headers,
901
+ Authorization: `Bearer ${token}`,
902
+ },
903
+ });
904
+ },
905
+ },
906
+ },
907
+ });
908
+ ```
909
+
910
+ ## Using SSE Request Headers
911
+
912
+ When using the legacy SSE MCP transport, you must configure both `requestInit` and `eventSourceInit` due to a bug in the MCP SDK. Alternatively, you can use a custom `fetch` function which will be automatically used for both POST requests and SSE connections:
913
+
914
+ ```ts
915
+ // Option 1: Using requestInit and eventSourceInit (required for SSE)
916
+ const sseClient = new MCPClient({
917
+ servers: {
918
+ exampleServer: {
919
+ url: new URL("https://your-mcp-server.com/sse"),
920
+ // Note: requestInit alone isn't enough for SSE
921
+ requestInit: {
922
+ headers: {
923
+ Authorization: "Bearer your-token",
924
+ },
925
+ },
926
+ // This is also required for SSE connections with custom headers
927
+ eventSourceInit: {
928
+ fetch(input: Request | URL | string, init?: RequestInit) {
929
+ const headers = new Headers(init?.headers || {});
930
+ headers.set("Authorization", "Bearer your-token");
931
+ return fetch(input, {
932
+ ...init,
933
+ headers,
934
+ });
935
+ },
936
+ },
937
+ },
938
+ },
939
+ });
940
+
941
+ // Option 2: Using custom fetch (simpler, works for both Streamable HTTP and SSE)
942
+ const sseClientWithFetch = new MCPClient({
943
+ servers: {
944
+ exampleServer: {
945
+ url: new URL("https://your-mcp-server.com/sse"),
946
+ fetch: async (url, init) => {
947
+ const headers = new Headers(init?.headers || {});
948
+ headers.set("Authorization", "Bearer your-token");
949
+ return fetch(url, {
950
+ ...init,
951
+ headers,
952
+ });
953
+ },
954
+ },
955
+ },
956
+ });
957
+ ```
958
+
959
+ ## Related Information
960
+
961
+ - For creating MCP servers, see the [MCPServer documentation](https://mastra.ai/reference/tools/mcp-server).
962
+ - For more about the Model Context Protocol, see the [@modelcontextprotocol/sdk documentation](https://github.com/modelcontextprotocol/typescript-sdk).