@mastra/mcp 1.0.0-beta.9 → 1.0.1-alpha.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.
Files changed (35) hide show
  1. package/CHANGELOG.md +368 -0
  2. package/README.md +9 -605
  3. package/dist/__fixtures__/tools.d.ts +8 -5
  4. package/dist/__fixtures__/tools.d.ts.map +1 -1
  5. package/dist/client/index.d.ts +1 -0
  6. package/dist/client/index.d.ts.map +1 -1
  7. package/dist/client/oauth-provider.d.ts +230 -0
  8. package/dist/client/oauth-provider.d.ts.map +1 -0
  9. package/dist/docs/SKILL.md +16 -22
  10. package/dist/docs/assets/SOURCE_MAP.json +59 -0
  11. package/dist/docs/{tools-mcp/01-mcp-overview.md → references/docs-mcp-overview.md} +150 -156
  12. package/dist/docs/references/docs-mcp-publishing-mcp-server.md +95 -0
  13. package/dist/docs/references/reference-tools-mcp-client.md +962 -0
  14. package/dist/docs/references/reference-tools-mcp-server.md +1275 -0
  15. package/dist/index.cjs +465 -10
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.ts +1 -0
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +405 -11
  20. package/dist/index.js.map +1 -1
  21. package/dist/server/index.d.ts +1 -0
  22. package/dist/server/index.d.ts.map +1 -1
  23. package/dist/server/oauth-middleware.d.ts +142 -0
  24. package/dist/server/oauth-middleware.d.ts.map +1 -0
  25. package/dist/server/server.d.ts.map +1 -1
  26. package/dist/shared/index.d.ts +2 -0
  27. package/dist/shared/index.d.ts.map +1 -0
  28. package/dist/shared/oauth-types.d.ts +137 -0
  29. package/dist/shared/oauth-types.d.ts.map +1 -0
  30. package/package.json +8 -9
  31. package/dist/docs/README.md +0 -33
  32. package/dist/docs/SOURCE_MAP.json +0 -6
  33. package/dist/docs/mcp/01-overview.md +0 -362
  34. package/dist/docs/mcp/02-publishing-mcp-server.md +0 -111
  35. package/dist/docs/tools/01-reference.md +0 -2005
package/README.md CHANGED
@@ -1,618 +1,22 @@
1
1
  # @mastra/mcp
2
2
 
3
- Model Context Protocol (MCP) client implementation for Mastra, providing seamless integration with MCP-compatible AI models and tools.
3
+ Mastra supports the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/docs/getting-started/intro), an open standard for connecting AI agents to external tools and resources. It serves as a universal plugin system, enabling agents to call tools regardless of language or hosting environment.
4
+
5
+ Mastra can also be used to author MCP servers, exposing agents, tools, and other structured resources via the MCP interface. These can then be accessed by any system or agent that supports the protocol.
4
6
 
5
7
  ## Installation
6
8
 
9
+ To use MCP, install the required dependency:
10
+
7
11
  ```bash
8
12
  npm install @mastra/mcp@latest
9
13
  ```
10
14
 
11
15
  ## Overview
12
16
 
13
- The `@mastra/mcp` package provides a client implementation for the Model Context Protocol (MCP), enabling Mastra to communicate with MCP-compatible AI models and tools. It wraps the official `@modelcontextprotocol/sdk` and provides Mastra-specific functionality.
14
-
15
- The client automatically detects the transport type based on your server configuration:
16
-
17
- - If you provide a `command`, it uses the Stdio transport.
18
- - If you provide a `url`, it first attempts to use the Streamable HTTP transport (protocol version 2025-03-26) and falls back to the legacy SSE transport (protocol version 2024-11-05) if the initial connection fails.
19
-
20
- ## Usage
21
-
22
- ```typescript
23
- import { MCPClient } from '@mastra/mcp';
24
-
25
- // Create a client with a Stdio server
26
- const stdioClient = new MCPClient({
27
- servers: {
28
- myStdioClient: {
29
- command: 'your-mcp-server-command',
30
- args: ['--your', 'args'],
31
- env: { API_KEY: 'your-api-key' }, // optional environment variables
32
- capabilities: {}, // optional ClientCapabilities
33
- timeout: 60000, // optional timeout for tool calls in milliseconds
34
- },
35
- },
36
- });
37
-
38
- // Create a client with an HTTP server (tries Streamable HTTP, falls back to SSE)
39
- const httpClient = new MCPClient({
40
- servers: {
41
- myHttpClient: {
42
- url: new URL('https://your-mcp-server.com/mcp'), // Use the base URL for Streamable HTTP
43
- requestInit: {
44
- // Optional fetch request configuration
45
- headers: { Authorization: 'Bearer your-token' },
46
- },
47
- // eventSourceInit is only needed for custom headers with the legacy SSE fallback
48
- eventSourceInit: {
49
- /* ... */
50
- },
51
- },
52
- },
53
- });
54
-
55
- // Or create a client with SSE server
56
- const sseClient = new MCPClient({
57
- servers: {
58
- mySseClient: {
59
- url: new URL('https://your-mcp-server.com/sse'),
60
- requestInit: {
61
- headers: { Authorization: 'Bearer your-token' },
62
- },
63
- eventSourceInit: {
64
- fetch(input: Request | URL | string, init?: RequestInit) {
65
- const headers = new Headers(init?.headers || {});
66
- headers.set('Authorization', 'Bearer your-token');
67
- return fetch(input, {
68
- ...init,
69
- headers,
70
- });
71
- },
72
- },
73
- timeout: 60000, // optional timeout for tool calls in milliseconds
74
- },
75
- },
76
- });
77
-
78
- // Connect to the MCP server (using one of the clients above)
79
- await httpClient.connect();
80
-
81
- // List available resources
82
- const resources = await httpClient.resources();
83
-
84
- // Get available tools
85
- const tools = await httpClient.tools();
86
-
87
- // Disconnect when done
88
- await httpClient.disconnect();
89
- ```
90
-
91
- ## Managing Multiple MCP Servers
92
-
93
- For applications that need to interact with multiple MCP servers, the `MCPClient` class provides a convenient way to manage multiple server connections and their tools. It also uses the automatic transport detection based on the `server` configuration:
94
-
95
- ```typescript
96
- import { MCPClient } from '@mastra/mcp';
97
-
98
- const mcp = new MCPClient({
99
- servers: {
100
- // Stdio-based server
101
- stockPrice: {
102
- command: 'npx',
103
- args: ['tsx', 'stock-price.ts'],
104
- env: {
105
- API_KEY: 'your-api-key',
106
- },
107
- },
108
- // HTTP-based server (tries Streamable HTTP, falls back to SSE)
109
- weather: {
110
- url: new URL('http://localhost:8080/mcp'), // Use the base URL for Streamable HTTP
111
- requestInit: {
112
- // Optional fetch request configuration
113
- headers: { 'X-Api-Key': 'weather-key' },
114
- },
115
- },
116
- },
117
- });
118
-
119
- // Get all tools from all configured servers namespaced with the server name
120
- const tools = await mcp.listTools();
121
-
122
- // Get tools grouped into a toolset object per-server
123
- const toolsets = await mcp.listToolsets();
124
- ```
125
-
126
- ## Logging
127
-
128
- The MCP client provides per-server logging capabilities, allowing you to monitor interactions with each MCP server separately:
129
-
130
- ```typescript
131
- import { MCPClient, LogMessage, LoggingLevel } from '@mastra/mcp';
132
-
133
- // Define a custom log handler
134
- const weatherLogger = (logMessage: LogMessage) => {
135
- console.log(`[${logMessage.level}] ${logMessage.serverName}: ${logMessage.message}`);
136
-
137
- // Log data contains valuable information
138
- console.log('Details:', logMessage.details);
139
- console.log('Timestamp:', logMessage.timestamp);
140
- };
141
-
142
- // Initialize MCP configuration with server-specific loggers
143
- const mcp = new MCPClient({
144
- servers: {
145
- weatherService: {
146
- command: 'npx',
147
- args: ['tsx', 'weather-mcp.ts'],
148
- // Attach the logger to this specific server
149
- logger: weatherLogger, // Use 'logger' key
150
- },
151
-
152
- stockPriceService: {
153
- command: 'npx',
154
- args: ['tsx', 'stock-mcp.ts'],
155
- // Different logger for this service
156
- logger: logMessage => {
157
- // Use 'logger' key
158
- // Just log errors and critical events for this service
159
- if (['error', 'critical', 'alert', 'emergency'].includes(logMessage.level)) {
160
- console.error(`Stock service ${logMessage.level}: ${logMessage.message}`);
161
- }
162
- },
163
- },
164
- },
165
- });
166
- ```
167
-
168
- ### Log Message Structure
169
-
170
- Each log message contains the following information:
171
-
172
- ```typescript
173
- interface LogMessage {
174
- level: LoggingLevel; // MCP SDK standard log levels
175
- message: string;
176
- timestamp: Date;
177
- serverName: string;
178
- details?: Record<string, any>;
179
- }
180
- ```
181
-
182
- The `LoggingLevel` type is directly imported from the MCP SDK, ensuring compatibility with all standard MCP log levels: `'debug' | 'info' | 'notice' | 'warning' | 'error' | 'critical' | 'alert' | 'emergency'`.
183
-
184
- ### Creating Reusable Loggers
185
-
186
- You can create reusable logger factories for common patterns:
187
-
188
- ```typescript
189
- import fs from 'node:fs';
190
-
191
- // File logger factory with color coded output for different severity levels
192
- const createFileLogger = (filePath: string) => {
193
- return (logMessage: LogMessage) => {
194
- // Format the message based on level
195
- const prefix =
196
- logMessage.level === 'emergency' ? '!!! EMERGENCY !!! ' : logMessage.level === 'alert' ? '! ALERT ! ' : '';
197
-
198
- // Write to file with timestamp, level, etc.
199
- fs.appendFileSync(
200
- filePath,
201
- `[${logMessage.timestamp.toISOString()}] [${logMessage.level.toUpperCase()}] ${prefix}${logMessage.message}\n`,
202
- );
203
- };
204
- };
205
-
206
- // Use the factory in configuration
207
- const mcp = new MCPClient({
208
- servers: {
209
- weatherService: {
210
- command: 'npx',
211
- args: ['tsx', 'weather-mcp.ts'],
212
- logger: createFileLogger('./logs/weather.log'), // Use 'logger' key
213
- },
214
- },
215
- });
216
- ```
217
-
218
- See the `examples/server-logging.ts` file for comprehensive examples of various logging strategies.
219
-
220
- ### Tools vs Toolsets
221
-
222
- The MCPClient class provides two ways to access MCP tools:
223
-
224
- #### Tools (`listTools()`)
225
-
226
- Use this when:
227
-
228
- - You have a single MCP connection
229
- - The tools are used by a single user/context (CLI tools, automation scripts, etc)
230
- - Tool configuration (API keys, credentials) remains constant
231
- - You want to initialize an Agent with a fixed set of tools
232
-
233
- ```typescript
234
- import { Agent } from '@mastra/core/agent';
235
- import { openai } from '@ai-sdk/openai';
236
-
237
- const agent = new Agent({
238
- id: 'cli-assistant',
239
- name: 'CLI Assistant',
240
- instructions: 'You help users with CLI tasks',
241
- model: openai('gpt-4'),
242
- tools: await mcp.listTools(), // Tools are fixed at agent creation
243
- });
244
- ```
245
-
246
- #### Toolsets (`listToolsets()`)
247
-
248
- Use this when:
249
-
250
- - You need per-request tool configuration
251
- - Tools need different credentials per user
252
- - Running in a multi-user environment (web app, API, etc)
253
- - Tool configuration needs to change dynamically
254
-
255
- ```typescript
256
- import { MCPClient } from '@mastra/mcp';
257
- import { Agent } from '@mastra/core/agent';
258
- import { openai } from '@ai-sdk/openai';
259
-
260
- // Configure MCP servers with user-specific settings before getting toolsets
261
- const mcp = new MCPClient({
262
- servers: {
263
- stockPrice: {
264
- command: 'npx',
265
- args: ['tsx', 'weather-mcp.ts'],
266
- env: {
267
- // These would be different per user
268
- API_KEY: 'user-1-api-key',
269
- },
270
- },
271
- weather: {
272
- url: new URL('http://localhost:8080/mcp'), // Use the base URL for Streamable HTTP
273
- requestInit: {
274
- headers: {
275
- // These would be different per user
276
- Authorization: 'Bearer user-1-token',
277
- },
278
- },
279
- // eventSourceInit is only needed for custom headers with the legacy SSE fallback
280
- eventSourceInit: {
281
- /* ... */
282
- },
283
- },
284
- },
285
- });
286
-
287
- // Get the current toolsets configured for this user
288
- const toolsets = await mcp.listToolsets();
289
-
290
- // Use the agent with user-specific tool configurations
291
- const response = await agent.generate('What is the weather in London?', {
292
- toolsets,
293
- });
294
-
295
- console.log(response.text);
296
- ```
297
-
298
- The `MCPClient` class automatically:
299
-
300
- - Manages connections to multiple MCP servers
301
- - Namespaces tools to prevent naming conflicts
302
- - Handles connection lifecycle and cleanup
303
- - Provides both flat and grouped access to tools
304
-
305
- ## Accessing MCP Resources
306
-
307
- MCP servers can expose resources - data or content that can be retrieved and used in your application. The `MCPClient` class provides methods to access these resources across multiple servers:
308
-
309
- ```typescript
310
- import { MCPClient } from '@mastra/mcp';
311
-
312
- const mcp = new MCPClient({
313
- servers: {
314
- weather: {
315
- url: new URL('http://localhost:8080/mcp'),
316
- },
317
- dataService: {
318
- command: 'npx',
319
- args: ['tsx', 'data-service.ts'],
320
- },
321
- },
322
- });
323
-
324
- // Get resources from all connected MCP servers
325
- const resources = await mcp.resources.get();
326
-
327
- // Resources are grouped by server name
328
- console.log(Object.keys(resources)); // ['weather', 'dataService']
329
-
330
- // Each server entry contains an array of resources
331
- if (resources.weather) {
332
- // Access resources from the weather server
333
- const weatherResources = resources.weather;
334
-
335
- // Each resource has uri, name, description, and mimeType
336
- weatherResources.forEach(resource => {
337
- console.log(`${resource.uri}: ${resource.name} (${resource.mimeType})`);
338
- });
339
-
340
- // Find a specific resource by URI
341
- const forecast = weatherResources.find(r => r.uri === 'weather://forecast');
342
- if (forecast) {
343
- console.log(`Found forecast resource: ${forecast.description}`);
344
- }
345
- }
346
- ```
347
-
348
- The `getResources()` method handles errors gracefully - if a server fails or doesn't support resources, it will be omitted from the results without causing the entire operation to fail.
349
-
350
- ## Prompts
351
-
352
- MCP servers can also expose prompts, which represent structured message templates or conversational context for agents.
353
-
354
- ### Listing Prompts
355
-
356
- ```typescript
357
- const prompts = await mcp.prompts.list();
358
- console.log(prompts.weather); // [ { name: 'current', ... }, ... ]
359
- ```
360
-
361
- ### Getting a Prompt and Messages
362
-
363
- ```typescript
364
- const { prompt, messages } = await mcp.prompts.get({ serverName: 'weather', name: 'current' });
365
- console.log(prompt); // { name: 'current', version: 'v1', ... }
366
- console.log(messages); // [ { role: 'assistant', content: { type: 'text', text: '...' } }, ... ]
367
- ```
368
-
369
- ### Handling Prompt List Change Notifications
370
-
371
- ```typescript
372
- mcp.prompts.onListChanged({
373
- serverName: 'weather',
374
- handler: () => {
375
- // Refresh prompt list or update UI
376
- },
377
- });
378
- ```
379
-
380
- Prompt notifications are delivered via SSE or compatible transports. Register handlers before expecting notifications.
381
-
382
- ## Authentication
383
-
384
- ### OAuth Token Refresh with AuthProvider
385
-
386
- For HTTP-based MCP servers that require OAuth authentication with automatic token refresh, you can use the `authProvider` option:
387
-
388
- ```typescript
389
- const httpClient = new MCPClient({
390
- 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
408
- },
409
- },
410
- },
411
- });
412
- ```
413
-
414
- The `authProvider` is automatically passed to both Streamable HTTP and SSE transports.
415
-
416
- ### Custom Fetch for Dynamic Authentication
417
-
418
- 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.
419
-
420
- When `fetch` is provided, `requestInit`, `eventSourceInit`, and `authProvider` become optional, as you can handle these concerns within your custom fetch function.
421
-
422
- ```typescript
423
- const mcpClient = new MCPClient({
424
- servers: {
425
- apiServer: {
426
- url: new URL('https://api.example.com/mcp'),
427
- fetch: async (url, init) => {
428
- // Refresh token on each request
429
- const token = await getAuthToken(); // Your token refresh logic
430
-
431
- return fetch(url, {
432
- ...init,
433
- headers: {
434
- ...init?.headers,
435
- Authorization: `Bearer ${token}`,
436
- },
437
- });
438
- },
439
- },
440
- },
441
- });
442
- ```
443
-
444
- 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.
445
-
446
- ### SSE Authentication and Headers (Legacy Fallback)
447
-
448
- 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:
449
-
450
- **Option 1: Using custom `fetch` (Recommended)**
451
-
452
- The simplest approach is to provide a custom `fetch` function, which will automatically be used for both POST requests and SSE connections:
453
-
454
- ```typescript
455
- const sseClient = new MCPClient({
456
- servers: {
457
- authenticatedSseClient: {
458
- url: new URL('https://your-mcp-server.com/sse'),
459
- fetch: async (url, init) => {
460
- const headers = new Headers(init?.headers || {});
461
- headers.set('Authorization', 'Bearer your-token');
462
- return fetch(url, {
463
- ...init,
464
- headers,
465
- });
466
- },
467
- },
468
- },
469
- });
470
- ```
471
-
472
- **Option 2: Using `requestInit` and `eventSourceInit`**
473
-
474
- 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.
475
-
476
- The `eventSourceInit` configuration allows you to customize the underlying fetch request used for the SSE connection, ensuring your authentication headers are properly included.
477
-
478
- To properly include authentication headers or other custom headers in SSE connections when using the legacy fallback, you need to use both `requestInit` and `eventSourceInit`:
479
-
480
- ```typescript
481
- const sseClient = new MCPClient({
482
- servers: {
483
- authenticatedSseClient: {
484
- url: new URL('https://your-mcp-server.com/sse'), // Note the typical /sse path for legacy servers
485
- // requestInit alone isn't enough for SSE connections
486
- requestInit: {
487
- headers: { Authorization: 'Bearer your-token' },
488
- },
489
- // eventSourceInit is required to include headers in the SSE connection
490
- eventSourceInit: {
491
- fetch(input: Request | URL | string, init?: RequestInit) {
492
- const headers = new Headers(init?.headers || {});
493
- headers.set('Authorization', 'Bearer your-token');
494
- return fetch(input, {
495
- ...init,
496
- headers,
497
- });
498
- },
499
- },
500
- },
501
- },
502
- });
503
- ```
504
-
505
- This configuration ensures that:
506
-
507
- 1. The authentication headers are properly included in the SSE connection request
508
- 2. The connection can be established with the required credentials
509
- 3. Subsequent messages can be received through the authenticated connection
510
-
511
- ```typescript
512
- const sseClient = new MastraMCPClient({
513
- name: 'authenticated-sse-client',
514
- server: {
515
- url: new URL('https://your-mcp-server.com/sse'), // Note the typical /sse path for legacy servers
516
- // requestInit alone isn't enough for SSE connections
517
- requestInit: {
518
- headers: { Authorization: 'Bearer your-token' },
519
- },
520
- // eventSourceInit is required to include headers in the SSE connection
521
- eventSourceInit: {
522
- fetch(input: Request | URL | string, init?: RequestInit) {
523
- const headers = new Headers(init?.headers || {});
524
- headers.set('Authorization', 'Bearer your-token');
525
- return fetch(input, {
526
- ...init,
527
- headers,
528
- });
529
- },
530
- },
531
- },
532
- });
533
- ```
534
-
535
- ## Configuration (`MastraMCPServerDefinition`)
536
-
537
- The `server` parameter for both `MastraMCPClient` and `MCPConfiguration` uses the `MastraMCPServerDefinition` type. The client automatically detects the transport type based on the provided parameters:
538
-
539
- - If `command` is provided, it uses the Stdio transport.
540
- - 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.
541
-
542
- Here are the available options within `MastraMCPServerDefinition`:
543
-
544
- - **`command`**: (Optional, string) For Stdio servers: The command to execute.
545
- - **`args`**: (Optional, string[]) For Stdio servers: Arguments to pass to the command.
546
- - **`env`**: (Optional, Record<string, string>) For Stdio servers: Environment variables to set for the command.
547
- - **`url`**: (Optional, URL) For HTTP servers (Streamable HTTP or SSE): The URL of the server.
548
- - **`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.
549
- - **`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.
550
- - **`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.
551
- - **`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.
552
- - **`logger`**: (Optional, LogHandler) Optional additional handler for logging.
553
- - **`timeout`**: (Optional, number) Server-specific timeout in milliseconds, overriding the global client/configuration timeout.
554
- - **`capabilities`**: (Optional, ClientCapabilities) Server-specific capabilities configuration.
555
- - **`enableServerLogs`**: (Optional, boolean, default: `true`) Whether to enable logging for this server.
556
-
557
- ## Features
558
-
559
- - Standard MCP client implementation
560
- - Automatic tool conversion to Mastra format
561
- - Resource discovery and management
562
- - Multiple transport layers with automatic detection:
563
- - Stdio-based for local servers (`command`)
564
- - HTTP-based for remote servers (`url`): Tries Streamable HTTP first, falls back to legacy SSE.
565
- - OAuth authentication with automatic token refresh (`authProvider`)
566
- - Manual authentication headers for static tokens (`requestInit`, `eventSourceInit`)
567
- - Per-server logging capability using all standard MCP log levels
568
- - Automatic error handling and logging
569
- - Tool execution with context
570
-
571
- ## Methods
572
-
573
- ### `connect()`
574
-
575
- Establishes connection with the MCP server.
576
-
577
- ### `disconnect()`
578
-
579
- Closes the connection with the MCP server.
580
-
581
- ### `resources()`
582
-
583
- Lists available resources from the MCP server.
584
-
585
- ### `tools()`
586
-
587
- Retrieves and converts MCP tools to Mastra-compatible format.
588
-
589
- ## Tool Conversion
590
-
591
- The package automatically converts MCP tools to Mastra's format:
592
-
593
- ```typescript
594
- const tools = await client.tools();
595
- // Returns: { [toolName: string]: MastraTool }
596
-
597
- // Each tool includes:
598
- // - Converted JSON schema
599
- // - Mastra-compatible execution wrapper
600
- // - Error handling
601
- // - Automatic context passing
602
- ```
603
-
604
- ## Error Handling
605
-
606
- The client includes comprehensive error handling:
607
-
608
- - Connection errors
609
- - Tool execution errors
610
- - Resource listing errors
611
- - Schema conversion errors
17
+ Mastra currently supports two MCP classes:
612
18
 
613
- ## Related Links
19
+ - `MCPClient`: Connects to one or many MCP servers to access their tools, resources, prompts, and handle elicitation requests.
20
+ - `MCPServer`: Exposes Mastra tools, agents, workflows, prompts, and resources to MCP-compatible clients.
614
21
 
615
- - [Model Context Protocol Specification](https://modelcontextprotocol.io/specification)
616
- - [@modelcontextprotocol/sdk Documentation](https://github.com/modelcontextprotocol/typescript-sdk)
617
- - [Mastra Docs: Using MCP With Mastra](/docs/agents/mcp-guide)
618
- - [Mastra Docs: MastraMCPClient Reference](/reference/tools/client)
22
+ Read the [official MCP documentation](https://mastra.ai/docs/mcp/overview) to learn more.
@@ -1,9 +1,12 @@
1
- import { z } from 'zod';
2
- export declare const weatherTool: import("@mastra/core/tools").Tool<z.ZodObject<{
3
- location: z.ZodString;
4
- }, "strip", z.ZodTypeAny, {
1
+ export declare const weatherTool: import("@mastra/core/tools").Tool<{
5
2
  location: string;
6
3
  }, {
4
+ temperature: number;
5
+ feelsLike: number;
6
+ humidity: number;
7
+ windSpeed: number;
8
+ windGust: number;
9
+ conditions: string;
7
10
  location: string;
8
- }>, undefined, any, any, import("@mastra/core/tools").ToolExecutionContext<any, any>, "get-weather">;
11
+ }, unknown, unknown, import("@mastra/core/tools").ToolExecutionContext<unknown, unknown, unknown>, "get-weather", unknown>;
9
12
  //# sourceMappingURL=tools.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../src/__fixtures__/tools.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAqBxB,eAAO,MAAM,WAAW;;;;;;oGAUtB,CAAC"}
1
+ {"version":3,"file":"tools.d.ts","sourceRoot":"","sources":["../../src/__fixtures__/tools.ts"],"names":[],"mappings":"AAsBA,eAAO,MAAM,WAAW;;;;;;;;;;0HAUtB,CAAC"}
@@ -1,4 +1,5 @@
1
1
  export type { LoggingLevel, LogMessage, LogHandler, MastraMCPServerDefinition, ElicitationHandler, ProgressHandler, InternalMastraMCPClientOptions, } from './types.js';
2
2
  export * from './client.js';
3
3
  export * from './configuration.js';
4
+ export * from './oauth-provider.js';
4
5
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACR,YAAY,EACZ,UAAU,EACV,UAAU,EACV,yBAAyB,EACzB,kBAAkB,EAClB,eAAe,EACf,8BAA8B,GACjC,MAAM,SAAS,CAAC;AACjB,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,CAAC"}
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/client/index.ts"],"names":[],"mappings":"AAAA,YAAY,EACR,YAAY,EACZ,UAAU,EACV,UAAU,EACV,yBAAyB,EACzB,kBAAkB,EAClB,eAAe,EACf,8BAA8B,GACjC,MAAM,SAAS,CAAC;AACjB,cAAc,UAAU,CAAC;AACzB,cAAc,iBAAiB,CAAC;AAChC,cAAc,kBAAkB,CAAC"}