@mastra/mcp 0.4.1-alpha.2 → 0.4.1-alpha.4
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/.turbo/turbo-build.log +7 -7
- package/CHANGELOG.md +15 -0
- package/README.md +144 -92
- package/dist/_tsup-dts-rollup.d.cts +100 -40
- package/dist/_tsup-dts-rollup.d.ts +100 -40
- package/dist/index.cjs +200 -66
- package/dist/index.d.cts +2 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +197 -67
- package/package.json +4 -3
- package/src/client.test.ts +121 -33
- package/src/client.ts +172 -56
- package/src/configuration.test.ts +21 -36
- package/src/configuration.ts +107 -26
- package/src/index.ts +2 -1
- package/src/server-logging.test.ts +4 -4
- package/src/server.test.ts +2 -2
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,23 +1,23 @@
|
|
|
1
1
|
|
|
2
|
-
> @mastra/mcp@0.4.1-alpha.
|
|
2
|
+
> @mastra/mcp@0.4.1-alpha.4 build /home/runner/work/mastra/mastra/packages/mcp
|
|
3
3
|
> tsup src/index.ts --format esm,cjs --experimental-dts --clean --treeshake=smallest --splitting
|
|
4
4
|
|
|
5
5
|
[34mCLI[39m Building entry: src/index.ts
|
|
6
6
|
[34mCLI[39m Using tsconfig: tsconfig.json
|
|
7
7
|
[34mCLI[39m tsup v8.4.0
|
|
8
8
|
[34mTSC[39m Build start
|
|
9
|
-
[32mTSC[39m ⚡️ Build success in
|
|
9
|
+
[32mTSC[39m ⚡️ Build success in 15854ms
|
|
10
10
|
[34mDTS[39m Build start
|
|
11
11
|
[34mCLI[39m Target: es2022
|
|
12
12
|
Analysis will use the bundled TypeScript version 5.8.2
|
|
13
13
|
[36mWriting package typings: /home/runner/work/mastra/mastra/packages/mcp/dist/_tsup-dts-rollup.d.ts[39m
|
|
14
14
|
Analysis will use the bundled TypeScript version 5.8.2
|
|
15
15
|
[36mWriting package typings: /home/runner/work/mastra/mastra/packages/mcp/dist/_tsup-dts-rollup.d.cts[39m
|
|
16
|
-
[32mDTS[39m ⚡️ Build success in
|
|
16
|
+
[32mDTS[39m ⚡️ Build success in 14760ms
|
|
17
17
|
[34mCLI[39m Cleaning output folder
|
|
18
18
|
[34mESM[39m Build start
|
|
19
19
|
[34mCJS[39m Build start
|
|
20
|
-
[
|
|
21
|
-
[
|
|
22
|
-
[
|
|
23
|
-
[
|
|
20
|
+
[32mESM[39m [1mdist/index.js [22m[32m204.37 KB[39m
|
|
21
|
+
[32mESM[39m ⚡️ Build success in 4901ms
|
|
22
|
+
[32mCJS[39m [1mdist/index.cjs [22m[32m205.23 KB[39m
|
|
23
|
+
[32mCJS[39m ⚡️ Build success in 4903ms
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,20 @@
|
|
|
1
1
|
# @mastra/mcp
|
|
2
2
|
|
|
3
|
+
## 0.4.1-alpha.4
|
|
4
|
+
|
|
5
|
+
### Patch Changes
|
|
6
|
+
|
|
7
|
+
- 2526527: We are deprecating the MastraMCPClient class in favour of using MCPClient (formerly MCPConfiguration). MCPClient can handle 1+ MCP servers, whereas MastraMCPClient can only handle a single MCP server. Rather than having two different interfaces to use when using a single MCP vs multiple, we opted to nudge people towards using the interface that is more flexible.
|
|
8
|
+
- a2ccb71: improved mcp config cache
|
|
9
|
+
|
|
10
|
+
## 0.4.1-alpha.3
|
|
11
|
+
|
|
12
|
+
### Patch Changes
|
|
13
|
+
|
|
14
|
+
- ba1f4f3: Added Streamable HTTP MCP support to MCPConfiguration and MastraMCPClient
|
|
15
|
+
- Updated dependencies [6262bd5]
|
|
16
|
+
- @mastra/core@0.9.1-alpha.3
|
|
17
|
+
|
|
3
18
|
## 0.4.1-alpha.2
|
|
4
19
|
|
|
5
20
|
### Patch Changes
|
package/README.md
CHANGED
|
@@ -5,73 +5,97 @@ Model Context Protocol (MCP) client implementation for Mastra, providing seamles
|
|
|
5
5
|
## Installation
|
|
6
6
|
|
|
7
7
|
```bash
|
|
8
|
-
npm install @mastra/mcp
|
|
8
|
+
npm install @mastra/mcp@latest
|
|
9
9
|
```
|
|
10
10
|
|
|
11
11
|
## Overview
|
|
12
12
|
|
|
13
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
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
|
+
|
|
15
20
|
## Usage
|
|
16
21
|
|
|
17
22
|
```typescript
|
|
18
|
-
import {
|
|
23
|
+
import { MCPClient } from '@mastra/mcp';
|
|
19
24
|
|
|
20
|
-
// Create a client with
|
|
21
|
-
const stdioClient = new
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
+
},
|
|
27
35
|
},
|
|
28
|
-
capabilities: {}, // optional ClientCapabilities
|
|
29
36
|
});
|
|
30
37
|
|
|
31
|
-
//
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
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
|
+
},
|
|
39
51
|
},
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
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' },
|
|
48
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
|
|
49
74
|
},
|
|
50
75
|
},
|
|
51
|
-
timeout: 60000, // optional timeout for tool calls in milliseconds
|
|
52
76
|
});
|
|
53
77
|
|
|
54
|
-
// Connect to the MCP server
|
|
55
|
-
await
|
|
78
|
+
// Connect to the MCP server (using one of the clients above)
|
|
79
|
+
await httpClient.connect();
|
|
56
80
|
|
|
57
81
|
// List available resources
|
|
58
|
-
const resources = await
|
|
82
|
+
const resources = await httpClient.resources();
|
|
59
83
|
|
|
60
84
|
// Get available tools
|
|
61
|
-
const tools = await
|
|
85
|
+
const tools = await httpClient.tools();
|
|
62
86
|
|
|
63
87
|
// Disconnect when done
|
|
64
|
-
await
|
|
88
|
+
await httpClient.disconnect();
|
|
65
89
|
```
|
|
66
90
|
|
|
67
91
|
## Managing Multiple MCP Servers
|
|
68
92
|
|
|
69
|
-
For applications that need to interact with multiple MCP servers, the `
|
|
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:
|
|
70
94
|
|
|
71
95
|
```typescript
|
|
72
|
-
import {
|
|
96
|
+
import { MCPClient } from '@mastra/mcp';
|
|
73
97
|
|
|
74
|
-
const mcp = new
|
|
98
|
+
const mcp = new MCPClient({
|
|
75
99
|
servers: {
|
|
76
100
|
// Stdio-based server
|
|
77
101
|
stockPrice: {
|
|
@@ -81,9 +105,13 @@ const mcp = new MCPConfiguration({
|
|
|
81
105
|
API_KEY: 'your-api-key',
|
|
82
106
|
},
|
|
83
107
|
},
|
|
84
|
-
//
|
|
108
|
+
// HTTP-based server (tries Streamable HTTP, falls back to SSE)
|
|
85
109
|
weather: {
|
|
86
|
-
url: new URL('http://localhost:8080/
|
|
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
|
+
},
|
|
87
115
|
},
|
|
88
116
|
},
|
|
89
117
|
});
|
|
@@ -100,7 +128,7 @@ const toolsets = await mcp.getToolsets();
|
|
|
100
128
|
The MCP client provides per-server logging capabilities, allowing you to monitor interactions with each MCP server separately:
|
|
101
129
|
|
|
102
130
|
```typescript
|
|
103
|
-
import {
|
|
131
|
+
import { MCPClient, LogMessage, LoggingLevel } from '@mastra/mcp';
|
|
104
132
|
|
|
105
133
|
// Define a custom log handler
|
|
106
134
|
const weatherLogger = (logMessage: LogMessage) => {
|
|
@@ -112,20 +140,21 @@ const weatherLogger = (logMessage: LogMessage) => {
|
|
|
112
140
|
};
|
|
113
141
|
|
|
114
142
|
// Initialize MCP configuration with server-specific loggers
|
|
115
|
-
const mcp = new
|
|
143
|
+
const mcp = new MCPClient({
|
|
116
144
|
servers: {
|
|
117
145
|
weatherService: {
|
|
118
146
|
command: 'npx',
|
|
119
147
|
args: ['tsx', 'weather-mcp.ts'],
|
|
120
148
|
// Attach the logger to this specific server
|
|
121
|
-
|
|
149
|
+
logger: weatherLogger, // Use 'logger' key
|
|
122
150
|
},
|
|
123
151
|
|
|
124
152
|
stockPriceService: {
|
|
125
153
|
command: 'npx',
|
|
126
154
|
args: ['tsx', 'stock-mcp.ts'],
|
|
127
155
|
// Different logger for this service
|
|
128
|
-
|
|
156
|
+
logger: logMessage => {
|
|
157
|
+
// Use 'logger' key
|
|
129
158
|
// Just log errors and critical events for this service
|
|
130
159
|
if (['error', 'critical', 'alert', 'emergency'].includes(logMessage.level)) {
|
|
131
160
|
console.error(`Stock service ${logMessage.level}: ${logMessage.message}`);
|
|
@@ -157,9 +186,11 @@ The `LoggingLevel` type is directly imported from the MCP SDK, ensuring compatib
|
|
|
157
186
|
You can create reusable logger factories for common patterns:
|
|
158
187
|
|
|
159
188
|
```typescript
|
|
189
|
+
import fs from 'node:fs';
|
|
190
|
+
|
|
160
191
|
// File logger factory with color coded output for different severity levels
|
|
161
|
-
const createFileLogger = filePath => {
|
|
162
|
-
return logMessage => {
|
|
192
|
+
const createFileLogger = (filePath: string) => {
|
|
193
|
+
return (logMessage: LogMessage) => {
|
|
163
194
|
// Format the message based on level
|
|
164
195
|
const prefix =
|
|
165
196
|
logMessage.level === 'emergency' ? '!!! EMERGENCY !!! ' : logMessage.level === 'alert' ? '! ALERT ! ' : '';
|
|
@@ -173,12 +204,12 @@ const createFileLogger = filePath => {
|
|
|
173
204
|
};
|
|
174
205
|
|
|
175
206
|
// Use the factory in configuration
|
|
176
|
-
const mcp = new
|
|
207
|
+
const mcp = new MCPClient({
|
|
177
208
|
servers: {
|
|
178
209
|
weatherService: {
|
|
179
210
|
command: 'npx',
|
|
180
211
|
args: ['tsx', 'weather-mcp.ts'],
|
|
181
|
-
|
|
212
|
+
logger: createFileLogger('./logs/weather.log'), // Use 'logger' key
|
|
182
213
|
},
|
|
183
214
|
},
|
|
184
215
|
});
|
|
@@ -188,7 +219,7 @@ See the `examples/server-logging.ts` file for comprehensive examples of various
|
|
|
188
219
|
|
|
189
220
|
### Tools vs Toolsets
|
|
190
221
|
|
|
191
|
-
The
|
|
222
|
+
The MCPClient class provides two ways to access MCP tools:
|
|
192
223
|
|
|
193
224
|
#### Tools (`getTools()`)
|
|
194
225
|
|
|
@@ -200,6 +231,9 @@ Use this when:
|
|
|
200
231
|
- You want to initialize an Agent with a fixed set of tools
|
|
201
232
|
|
|
202
233
|
```typescript
|
|
234
|
+
import { Agent } from '@mastra/core/agent';
|
|
235
|
+
import { openai } from '@ai-sdk/openai';
|
|
236
|
+
|
|
203
237
|
const agent = new Agent({
|
|
204
238
|
name: 'CLI Assistant',
|
|
205
239
|
instructions: 'You help users with CLI tasks',
|
|
@@ -218,12 +252,12 @@ Use this when:
|
|
|
218
252
|
- Tool configuration needs to change dynamically
|
|
219
253
|
|
|
220
254
|
```typescript
|
|
221
|
-
import {
|
|
255
|
+
import { MCPClient } from '@mastra/mcp';
|
|
222
256
|
import { Agent } from '@mastra/core/agent';
|
|
223
257
|
import { openai } from '@ai-sdk/openai';
|
|
224
258
|
|
|
225
259
|
// Configure MCP servers with user-specific settings before getting toolsets
|
|
226
|
-
const mcp = new
|
|
260
|
+
const mcp = new MCPClient({
|
|
227
261
|
servers: {
|
|
228
262
|
stockPrice: {
|
|
229
263
|
command: 'npx',
|
|
@@ -234,22 +268,16 @@ const mcp = new MCPConfiguration({
|
|
|
234
268
|
},
|
|
235
269
|
},
|
|
236
270
|
weather: {
|
|
237
|
-
url: new URL('http://localhost:8080/
|
|
271
|
+
url: new URL('http://localhost:8080/mcp'), // Use the base URL for Streamable HTTP
|
|
238
272
|
requestInit: {
|
|
239
273
|
headers: {
|
|
240
274
|
// These would be different per user
|
|
241
275
|
Authorization: 'Bearer user-1-token',
|
|
242
276
|
},
|
|
243
277
|
},
|
|
278
|
+
// eventSourceInit is only needed for custom headers with the legacy SSE fallback
|
|
244
279
|
eventSourceInit: {
|
|
245
|
-
|
|
246
|
-
const headers = new Headers(init?.headers || {});
|
|
247
|
-
headers.set('Authorization', 'Bearer user-1-token');
|
|
248
|
-
return fetch(input, {
|
|
249
|
-
...init,
|
|
250
|
-
headers,
|
|
251
|
-
});
|
|
252
|
-
},
|
|
280
|
+
/* ... */
|
|
253
281
|
},
|
|
254
282
|
},
|
|
255
283
|
},
|
|
@@ -266,26 +294,57 @@ const response = await agent.generate('What is the weather in London?', {
|
|
|
266
294
|
console.log(response.text);
|
|
267
295
|
```
|
|
268
296
|
|
|
269
|
-
The `
|
|
297
|
+
The `MCPClient` class automatically:
|
|
270
298
|
|
|
271
299
|
- Manages connections to multiple MCP servers
|
|
272
300
|
- Namespaces tools to prevent naming conflicts
|
|
273
301
|
- Handles connection lifecycle and cleanup
|
|
274
302
|
- Provides both flat and grouped access to tools
|
|
275
303
|
|
|
276
|
-
## SSE Authentication and Headers
|
|
304
|
+
## SSE Authentication and Headers (Legacy Fallback)
|
|
277
305
|
|
|
278
|
-
When using SSE (Server-Sent Events)
|
|
306
|
+
When the client falls back to using the legacy SSE (Server-Sent Events) transport and you need to include authentication or custom headers, you need to configure headers in a specific way. The standard `requestInit` headers won't work alone because SSE connections using the browser's `EventSource` API don't support custom headers directly.
|
|
279
307
|
|
|
280
308
|
The `eventSourceInit` configuration allows you to customize the underlying fetch request used for the SSE connection, ensuring your authentication headers are properly included.
|
|
281
309
|
|
|
282
|
-
To properly include authentication headers or other custom headers in SSE connections, you need to use both `requestInit` and `eventSourceInit`:
|
|
310
|
+
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`:
|
|
311
|
+
|
|
312
|
+
```typescript
|
|
313
|
+
const sseClient = new MCPClient({
|
|
314
|
+
servers: {
|
|
315
|
+
authenticatedSseClient: {
|
|
316
|
+
url: new URL('https://your-mcp-server.com/sse'), // Note the typical /sse path for legacy servers
|
|
317
|
+
// requestInit alone isn't enough for SSE connections
|
|
318
|
+
requestInit: {
|
|
319
|
+
headers: { Authorization: 'Bearer your-token' },
|
|
320
|
+
},
|
|
321
|
+
// eventSourceInit is required to include headers in the SSE connection
|
|
322
|
+
eventSourceInit: {
|
|
323
|
+
fetch(input: Request | URL | string, init?: RequestInit) {
|
|
324
|
+
const headers = new Headers(init?.headers || {});
|
|
325
|
+
headers.set('Authorization', 'Bearer your-token');
|
|
326
|
+
return fetch(input, {
|
|
327
|
+
...init,
|
|
328
|
+
headers,
|
|
329
|
+
});
|
|
330
|
+
},
|
|
331
|
+
},
|
|
332
|
+
},
|
|
333
|
+
},
|
|
334
|
+
});
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
This configuration ensures that:
|
|
338
|
+
|
|
339
|
+
1. The authentication headers are properly included in the SSE connection request
|
|
340
|
+
2. The connection can be established with the required credentials
|
|
341
|
+
3. Subsequent messages can be received through the authenticated connection
|
|
283
342
|
|
|
284
343
|
```typescript
|
|
285
344
|
const sseClient = new MastraMCPClient({
|
|
286
345
|
name: 'authenticated-sse-client',
|
|
287
346
|
server: {
|
|
288
|
-
url: new URL('https://your-mcp-server.com/sse'),
|
|
347
|
+
url: new URL('https://your-mcp-server.com/sse'), // Note the typical /sse path for legacy servers
|
|
289
348
|
// requestInit alone isn't enough for SSE connections
|
|
290
349
|
requestInit: {
|
|
291
350
|
headers: { Authorization: 'Bearer your-token' },
|
|
@@ -305,44 +364,34 @@ const sseClient = new MastraMCPClient({
|
|
|
305
364
|
});
|
|
306
365
|
```
|
|
307
366
|
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
1. The authentication headers are properly included in the SSE connection request
|
|
311
|
-
2. The connection can be established with the required credentials
|
|
312
|
-
3. Subsequent messages can be received through the authenticated connection
|
|
313
|
-
|
|
314
|
-
## Configuration
|
|
315
|
-
|
|
316
|
-
### Required Parameters
|
|
317
|
-
|
|
318
|
-
- `name`: Name of the MCP client instance
|
|
319
|
-
- `server`: Either a StdioServerParameters or SSEClientParameters object:
|
|
320
|
-
|
|
321
|
-
#### StdioServerParameters
|
|
322
|
-
|
|
323
|
-
- `command`: Command to start the MCP server
|
|
324
|
-
- `args`: Array of command arguments
|
|
367
|
+
## Configuration (`MastraMCPServerDefinition`)
|
|
325
368
|
|
|
326
|
-
|
|
369
|
+
The `server` parameter for both `MastraMCPClient` and `MCPConfiguration` uses the `MastraMCPServerDefinition` type. The client automatically detects the transport type based on the provided parameters:
|
|
327
370
|
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
- `eventSourceInit`: Optional EventSource configuration
|
|
371
|
+
- If `command` is provided, it uses the Stdio transport.
|
|
372
|
+
- 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.
|
|
331
373
|
|
|
332
|
-
|
|
374
|
+
Here are the available options within `MastraMCPServerDefinition`:
|
|
333
375
|
|
|
334
|
-
-
|
|
335
|
-
-
|
|
336
|
-
-
|
|
376
|
+
- **`command`**: (Optional, string) For Stdio servers: The command to execute.
|
|
377
|
+
- **`args`**: (Optional, string[]) For Stdio servers: Arguments to pass to the command.
|
|
378
|
+
- **`env`**: (Optional, Record<string, string>) For Stdio servers: Environment variables to set for the command.
|
|
379
|
+
- **`url`**: (Optional, URL) For HTTP servers (Streamable HTTP or SSE): The URL of the server.
|
|
380
|
+
- **`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.
|
|
381
|
+
- **`eventSourceInit`**: (Optional, EventSourceInit) **Only** for the legacy SSE fallback: Custom fetch configuration for SSE connections. Required when using custom headers with SSE.
|
|
382
|
+
- **`logger`**: (Optional, LogHandler) Optional additional handler for logging.
|
|
383
|
+
- **`timeout`**: (Optional, number) Server-specific timeout in milliseconds, overriding the global client/configuration timeout.
|
|
384
|
+
- **`capabilities`**: (Optional, ClientCapabilities) Server-specific capabilities configuration.
|
|
385
|
+
- **`enableServerLogs`**: (Optional, boolean, default: `true`) Whether to enable logging for this server.
|
|
337
386
|
|
|
338
387
|
## Features
|
|
339
388
|
|
|
340
389
|
- Standard MCP client implementation
|
|
341
390
|
- Automatic tool conversion to Mastra format
|
|
342
391
|
- Resource discovery and management
|
|
343
|
-
- Multiple transport layers:
|
|
344
|
-
- Stdio-based for local servers
|
|
345
|
-
-
|
|
392
|
+
- Multiple transport layers with automatic detection:
|
|
393
|
+
- Stdio-based for local servers (`command`)
|
|
394
|
+
- HTTP-based for remote servers (`url`): Tries Streamable HTTP first, falls back to legacy SSE.
|
|
346
395
|
- Per-server logging capability using all standard MCP log levels
|
|
347
396
|
- Automatic error handling and logging
|
|
348
397
|
- Tool execution with context
|
|
@@ -391,5 +440,8 @@ The client includes comprehensive error handling:
|
|
|
391
440
|
|
|
392
441
|
## Related Links
|
|
393
442
|
|
|
394
|
-
- [Model Context Protocol Specification](https://
|
|
395
|
-
- [@modelcontextprotocol/sdk Documentation](https://github.com/modelcontextprotocol/sdk)
|
|
443
|
+
- [Model Context Protocol Specification](https://modelcontextprotocol.io/specification)
|
|
444
|
+
- [@modelcontextprotocol/sdk Documentation](https://github.com/modelcontextprotocol/typescript-sdk)
|
|
445
|
+
- [Mastra Docs: Using MCP With Mastra](/docs/agents/mcp-guide)
|
|
446
|
+
- [Mastra Docs: MCPConfiguration Reference](/reference/tools/mcp-configuration)
|
|
447
|
+
- [Mastra Docs: MastraMCPClient Reference](/reference/tools/client)
|
|
@@ -5,13 +5,20 @@ import type { Protocol } from '@modelcontextprotocol/sdk/shared/protocol.js';
|
|
|
5
5
|
import { Server } from '@modelcontextprotocol/sdk/server/index.js';
|
|
6
6
|
import type { SSEClientTransportOptions } from '@modelcontextprotocol/sdk/client/sse.js';
|
|
7
7
|
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
|
|
8
|
-
import type { StdioServerParameters } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
9
8
|
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
|
|
9
|
+
import type { StreamableHTTPClientTransportOptions } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
10
10
|
import { Tool } from '@mastra/core/tools';
|
|
11
11
|
import { ToolExecutionContext } from '@mastra/core';
|
|
12
12
|
import type { ToolsInput } from '@mastra/core/agent';
|
|
13
13
|
import { z } from 'zod';
|
|
14
14
|
|
|
15
|
+
declare type BaseServerOptions = {
|
|
16
|
+
logger?: LogHandler;
|
|
17
|
+
timeout?: number;
|
|
18
|
+
capabilities?: ClientCapabilities;
|
|
19
|
+
enableServerLogs?: boolean;
|
|
20
|
+
};
|
|
21
|
+
|
|
15
22
|
declare type ConvertedTool = {
|
|
16
23
|
name: string;
|
|
17
24
|
description?: string;
|
|
@@ -22,39 +29,26 @@ declare type ConvertedTool = {
|
|
|
22
29
|
|
|
23
30
|
export declare function createLogger(server?: Server): Logger;
|
|
24
31
|
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
export { LoggingLevel as LoggingLevel_alias_1 }
|
|
36
|
-
|
|
37
|
-
declare type LogHandler = (logMessage: LogMessage) => void;
|
|
38
|
-
export { LogHandler }
|
|
39
|
-
export { LogHandler as LogHandler_alias_1 }
|
|
40
|
-
|
|
41
|
-
declare interface LogMessage {
|
|
42
|
-
level: LoggingLevel;
|
|
43
|
-
message: string;
|
|
44
|
-
timestamp: Date;
|
|
45
|
-
serverName: string;
|
|
46
|
-
details?: Record<string, any>;
|
|
47
|
-
}
|
|
48
|
-
export { LogMessage }
|
|
49
|
-
export { LogMessage as LogMessage_alias_1 }
|
|
32
|
+
declare type HttpServerDefinition = BaseServerOptions & {
|
|
33
|
+
url: URL;
|
|
34
|
+
command?: never;
|
|
35
|
+
args?: never;
|
|
36
|
+
env?: never;
|
|
37
|
+
requestInit?: StreamableHTTPClientTransportOptions['requestInit'];
|
|
38
|
+
eventSourceInit?: SSEClientTransportOptions['eventSourceInit'];
|
|
39
|
+
reconnectionOptions?: StreamableHTTPClientTransportOptions['reconnectionOptions'];
|
|
40
|
+
sessionId?: StreamableHTTPClientTransportOptions['sessionId'];
|
|
41
|
+
};
|
|
50
42
|
|
|
51
|
-
declare class
|
|
43
|
+
export declare class InternalMastraMCPClient extends MastraBase {
|
|
52
44
|
name: string;
|
|
53
|
-
private transport;
|
|
54
45
|
private client;
|
|
55
46
|
private readonly timeout;
|
|
56
47
|
private logHandler?;
|
|
57
48
|
private enableServerLogs?;
|
|
49
|
+
private static hasWarned;
|
|
50
|
+
private serverConfig;
|
|
51
|
+
private transport?;
|
|
58
52
|
constructor({ name, version, server, capabilities, timeout, }: {
|
|
59
53
|
name: string;
|
|
60
54
|
server: MastraMCPServerDefinition;
|
|
@@ -70,41 +64,100 @@ declare class MastraMCPClient extends MastraBase {
|
|
|
70
64
|
*/
|
|
71
65
|
private log;
|
|
72
66
|
private setupLogging;
|
|
67
|
+
private connectStdio;
|
|
68
|
+
private connectHttp;
|
|
73
69
|
private isConnected;
|
|
74
70
|
connect(): Promise<void>;
|
|
71
|
+
/**
|
|
72
|
+
* Get the current session ID if using the Streamable HTTP transport.
|
|
73
|
+
* Returns undefined if not connected or not using Streamable HTTP.
|
|
74
|
+
*/
|
|
75
|
+
get sessionId(): string | undefined;
|
|
75
76
|
disconnect(): Promise<void>;
|
|
76
77
|
resources(): Promise<ReturnType<Protocol<any, any, any>['request']>>;
|
|
77
78
|
tools(): Promise<Record<string, any>>;
|
|
78
79
|
}
|
|
80
|
+
|
|
81
|
+
export declare interface Logger {
|
|
82
|
+
info: (message: string, data?: any) => Promise<void>;
|
|
83
|
+
warning: (message: string, data?: any) => Promise<void>;
|
|
84
|
+
error: (message: string, error?: any) => Promise<void>;
|
|
85
|
+
debug: (message: string, data?: any) => Promise<void>;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export declare const logger: Logger;
|
|
89
|
+
|
|
90
|
+
export { LoggingLevel }
|
|
91
|
+
export { LoggingLevel as LoggingLevel_alias_1 }
|
|
92
|
+
|
|
93
|
+
declare type LogHandler = (logMessage: LogMessage) => void;
|
|
94
|
+
export { LogHandler }
|
|
95
|
+
export { LogHandler as LogHandler_alias_1 }
|
|
96
|
+
|
|
97
|
+
declare interface LogMessage {
|
|
98
|
+
level: LoggingLevel;
|
|
99
|
+
message: string;
|
|
100
|
+
timestamp: Date;
|
|
101
|
+
serverName: string;
|
|
102
|
+
details?: Record<string, any>;
|
|
103
|
+
}
|
|
104
|
+
export { LogMessage }
|
|
105
|
+
export { LogMessage as LogMessage_alias_1 }
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* @deprecated MastraMCPClient is deprecated and will be removed in a future release. Please use MCPClient instead.
|
|
109
|
+
*/
|
|
110
|
+
declare const MastraMCPClient: typeof InternalMastraMCPClient;
|
|
79
111
|
export { MastraMCPClient }
|
|
80
112
|
export { MastraMCPClient as MastraMCPClient_alias_1 }
|
|
81
113
|
|
|
82
|
-
declare type MastraMCPServerDefinition =
|
|
83
|
-
logger?: LogHandler;
|
|
84
|
-
timeout?: number;
|
|
85
|
-
capabilities?: ClientCapabilities;
|
|
86
|
-
enableServerLogs?: boolean;
|
|
87
|
-
};
|
|
114
|
+
declare type MastraMCPServerDefinition = StdioServerDefinition | HttpServerDefinition;
|
|
88
115
|
export { MastraMCPServerDefinition }
|
|
89
116
|
export { MastraMCPServerDefinition as MastraMCPServerDefinition_alias_1 }
|
|
90
117
|
|
|
91
|
-
declare class
|
|
118
|
+
declare class MCPClient extends MastraBase {
|
|
92
119
|
private serverConfigs;
|
|
93
120
|
private id;
|
|
94
121
|
private defaultTimeout;
|
|
95
|
-
|
|
122
|
+
private mcpClientsById;
|
|
123
|
+
private disconnectPromise;
|
|
124
|
+
constructor(args: MCPClientOptions);
|
|
96
125
|
private addToInstanceCache;
|
|
97
126
|
private makeId;
|
|
98
127
|
disconnect(): Promise<void>;
|
|
99
128
|
getTools(): Promise<Record<string, any>>;
|
|
100
129
|
getToolsets(): Promise<Record<string, Record<string, any>>>;
|
|
101
|
-
|
|
130
|
+
/**
|
|
131
|
+
* Get the current session IDs for all connected MCP clients using the Streamable HTTP transport.
|
|
132
|
+
* Returns an object mapping server names to their session IDs.
|
|
133
|
+
*/
|
|
134
|
+
get sessionIds(): Record<string, string>;
|
|
102
135
|
private getConnectedClient;
|
|
103
136
|
private eachClientTools;
|
|
104
137
|
}
|
|
138
|
+
export { MCPClient }
|
|
139
|
+
export { MCPClient as MCPClient_alias_1 }
|
|
140
|
+
|
|
141
|
+
declare interface MCPClientOptions {
|
|
142
|
+
id?: string;
|
|
143
|
+
servers: Record<string, MastraMCPServerDefinition>;
|
|
144
|
+
timeout?: number;
|
|
145
|
+
}
|
|
146
|
+
export { MCPClientOptions }
|
|
147
|
+
export { MCPClientOptions as MCPClientOptions_alias_1 }
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* @deprecated MCPConfiguration is deprecated and will be removed in a future release. Use MCPClient instead.
|
|
151
|
+
*/
|
|
152
|
+
declare class MCPConfiguration extends MCPClient {
|
|
153
|
+
constructor(args: MCPClientOptions);
|
|
154
|
+
}
|
|
105
155
|
export { MCPConfiguration }
|
|
106
156
|
export { MCPConfiguration as MCPConfiguration_alias_1 }
|
|
107
157
|
|
|
158
|
+
/**
|
|
159
|
+
* @deprecated MCPConfigurationOptions is deprecated and will be removed in a future release. Use MCPClientOptions instead.
|
|
160
|
+
*/
|
|
108
161
|
declare interface MCPConfigurationOptions {
|
|
109
162
|
id?: string;
|
|
110
163
|
servers: Record<string, MastraMCPServerDefinition>;
|
|
@@ -228,9 +281,16 @@ export declare const server_alias_1: Server<{
|
|
|
228
281
|
} | undefined;
|
|
229
282
|
}>;
|
|
230
283
|
|
|
231
|
-
declare type
|
|
232
|
-
|
|
233
|
-
|
|
284
|
+
declare type StdioServerDefinition = BaseServerOptions & {
|
|
285
|
+
command: string;
|
|
286
|
+
args?: string[];
|
|
287
|
+
env?: Record<string, string>;
|
|
288
|
+
url?: never;
|
|
289
|
+
requestInit?: never;
|
|
290
|
+
eventSourceInit?: never;
|
|
291
|
+
reconnectionOptions?: never;
|
|
292
|
+
sessionId?: never;
|
|
293
|
+
};
|
|
234
294
|
|
|
235
295
|
export declare const weatherTool: Tool<z.ZodObject<{
|
|
236
296
|
location: z.ZodString;
|