@mastra/mcp 1.0.0-beta.7 → 1.0.0-beta.9

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,376 @@
1
+ > Learn about the Model Context Protocol (MCP), how to use third-party tools via MCPClient, connect to registries, and share your own tools using MCPServer.
2
+
3
+ # MCP Overview
4
+
5
+ Mastra supports the [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction), 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.
6
+
7
+ 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.
8
+
9
+ Mastra currently supports two MCP classes:
10
+
11
+ 1. **`MCPClient`**: Connects to one or many MCP servers to access their tools, resources, prompts, and handle elicitation requests.
12
+ 2. **`MCPServer`**: Exposes Mastra tools, agents, workflows, prompts, and resources to MCP compatible clients.
13
+
14
+ ## Getting started
15
+
16
+ To use MCP, install the required dependency:
17
+
18
+ ```bash
19
+ npm install @mastra/mcp@beta
20
+ ```
21
+
22
+ ## Configuring `MCPClient`
23
+
24
+ The `MCPClient` connects Mastra primitives to external MCP servers, which can be local packages (invoked using `npx`) or remote HTTP(S) endpoints. Each server must be configured with either a `command` or a `url`, depending on how it's hosted.
25
+
26
+ ```typescript title="src/mastra/mcp/test-mcp-client.ts"
27
+ import { MCPClient } from "@mastra/mcp";
28
+
29
+ export const testMcpClient = new MCPClient({
30
+ id: "test-mcp-client",
31
+ servers: {
32
+ wikipedia: {
33
+ command: "npx",
34
+ args: ["-y", "wikipedia-mcp"],
35
+ },
36
+ weather: {
37
+ url: new URL(
38
+ `https://server.smithery.ai/@smithery-ai/national-weather-service/mcp?api_key=${process.env.SMITHERY_API_KEY}`,
39
+ ),
40
+ },
41
+ },
42
+ });
43
+ ```
44
+
45
+ > **Note:**
46
+
47
+ Visit [MCPClient](https://mastra.ai/reference/v1/tools/mcp-client) for a full list of configuration options.
48
+
49
+ ## Using `MCPClient` with an agent
50
+
51
+ To use tools from an MCP server in an agent, import your `MCPClient` and call `.listTools()` in the `tools` parameter. This loads from the defined MCP servers, making them available to the agent.
52
+
53
+ ```typescript {3,15} title="src/mastra/agents/test-agent.ts"
54
+ import { Agent } from "@mastra/core/agent";
55
+
56
+ import { testMcpClient } from "../mcp/test-mcp-client";
57
+
58
+ export const testAgent = new Agent({
59
+ id: "test-agent",
60
+ name: "Test Agent",
61
+ description: "You are a helpful AI assistant",
62
+ instructions: `
63
+ You are a helpful assistant that has access to the following MCP Servers.
64
+ - Wikipedia MCP Server
65
+ - US National Weather Service
66
+
67
+ Answer questions using the information you find using the MCP Servers.`,
68
+ model: "openai/gpt-5.1",
69
+ tools: await testMcpClient.listTools(),
70
+ });
71
+ ```
72
+
73
+ > **Note:**
74
+
75
+ Visit [Agent Class](https://mastra.ai/reference/v1/agents/agent) for a full list of configuration options.
76
+
77
+ ## Configuring `MCPServer`
78
+
79
+ To expose agents, tools, and workflows from your Mastra application to external systems over HTTP(S) use the `MCPServer` class. This makes them accessible to any system or agent that supports the protocol.
80
+
81
+ ```typescript title="src/mastra/mcp/test-mcp-server.ts"
82
+ import { MCPServer } from "@mastra/mcp";
83
+
84
+ import { testAgent } from "../agents/test-agent";
85
+ import { testWorkflow } from "../workflows/test-workflow";
86
+ import { testTool } from "../tools/test-tool";
87
+
88
+ export const testMcpServer = new MCPServer({
89
+ id: "test-mcp-server", // Required: unique identifier for the server
90
+ name: "Test MCP Server",
91
+ version: "1.0.0",
92
+ agents: { testAgent },
93
+ tools: { testTool },
94
+ workflows: { testWorkflow },
95
+ });
96
+ ```
97
+
98
+ > **Note:**
99
+
100
+ Visit [MCPServer](https://mastra.ai/reference/v1/tools/mcp-server) for a full list of configuration options.
101
+
102
+ ### Serverless deployments
103
+
104
+ `MCPServer` can be deployed in serverless environments (Cloudflare Workers, Vercel Edge Functions, AWS Lambda, etc.) by enabling the `serverless: true` option in `startHTTP()`. This runs the server in stateless mode, where each request is handled independently without session management.
105
+
106
+ **Note:** Some MCP features require persistent connections and won't work in serverless mode, including elicitation, resource subscriptions, and update notifications. See the [serverless section](https://mastra.ai/reference/v1/tools/mcp-server#starthttp) in the API reference for full details and limitations.
107
+
108
+ ## Registering an `MCPServer`
109
+
110
+ To make an MCP server available to other systems or agents that support the protocol, register it in the main `Mastra` instance using `mcpServers`.
111
+
112
+ ```typescript title="src/mastra/index.ts"
113
+ import { Mastra } from "@mastra/core";
114
+
115
+ import { testMcpServer } from "./mcp/test-mcp-server";
116
+
117
+ export const mastra = new Mastra({
118
+ mcpServers: {
119
+ testMcpServer, // Registry key: 'testMcpServer'
120
+ },
121
+ });
122
+
123
+ // Both retrieval methods work:
124
+ mastra.getMCPServer('testMcpServer'); // By registry key
125
+ mastra.getMCPServerById('test-mcp-server'); // By intrinsic ID
126
+ ```
127
+
128
+ ## Static and dynamic tools
129
+
130
+ `MCPClient` offers two approaches to retrieving tools from connected servers, suitable for different application architectures:
131
+
132
+ | Feature | Static Configuration (`await mcp.listTools()`) | Dynamic Configuration (`await mcp.listToolsets()`) |
133
+ | :---------------- | :-------------------------------------------- | :--------------------------------------------------- |
134
+ | **Use Case** | Single-user, static config (e.g., CLI tool) | Multi-user, dynamic config (e.g., SaaS app) |
135
+ | **Configuration** | Fixed at agent initialization | Per-request, dynamic |
136
+ | **Credentials** | Shared across all uses | Can vary per user/request |
137
+ | **Agent Setup** | Tools added in `Agent` constructor | Tools passed in `.generate()` or `.stream()` options |
138
+
139
+ ### Static tools
140
+
141
+ Use the `.listTools()` method to fetch tools from all configured MCP servers. This is suitable when configuration (such as API keys) is static and consistent across users or requests. Call it once and pass the result to the `tools` property when defining your agent.
142
+
143
+ > **Note:**
144
+
145
+ Visit [listTools()](https://mastra.ai/reference/v1/tools/mcp-client#listtools) for more information.
146
+
147
+ ```typescript {7} title="src/mastra/agents/test-agent.ts"
148
+ import { Agent } from "@mastra/core/agent";
149
+
150
+ import { testMcpClient } from "../mcp/test-mcp-client";
151
+
152
+ export const testAgent = new Agent({
153
+ // ...
154
+ tools: await testMcpClient.listTools(),
155
+ });
156
+ ```
157
+
158
+ ### Dynamic tools
159
+
160
+ Use the `.listToolsets()` method when tool configuration may vary by request or user, such as in a multi-tenant system where each user provides their own API key. This method returns toolsets that can be passed to the `toolsets` option in the agent's `.generate()` or `.stream()` calls.
161
+
162
+ ```typescript {5-16,21}
163
+ import { MCPClient } from "@mastra/mcp";
164
+ import { mastra } from "./mastra";
165
+
166
+ async function handleRequest(userPrompt: string, userApiKey: string) {
167
+ const userMcp = new MCPClient({
168
+ servers: {
169
+ weather: {
170
+ url: new URL("http://localhost:8080/mcp"),
171
+ requestInit: {
172
+ headers: {
173
+ Authorization: `Bearer ${userApiKey}`,
174
+ },
175
+ },
176
+ },
177
+ },
178
+ });
179
+
180
+ const agent = mastra.getAgent("testAgent");
181
+
182
+ const response = await agent.generate(userPrompt, {
183
+ toolsets: await userMcp.listToolsets(),
184
+ });
185
+
186
+ await userMcp.disconnect();
187
+
188
+ return Response.json({
189
+ data: response.text,
190
+ });
191
+ }
192
+ ```
193
+
194
+ > **Note:**
195
+
196
+ Visit [listToolsets()](https://mastra.ai/reference/v1/tools/mcp-client#listtoolsets) for more information.
197
+
198
+ ## Connecting to an MCP registry
199
+
200
+ MCP servers can be discovered through registries. Here's how to connect to some popular ones using `MCPClient`:
201
+
202
+ **klavis:**
203
+
204
+ [Klavis AI](https://klavis.ai) provides hosted, enterprise-authenticated, high-quality MCP servers.
205
+
206
+ ```typescript
207
+ import { MCPClient } from "@mastra/mcp";
208
+
209
+ const mcp = new MCPClient({
210
+ servers: {
211
+ salesforce: {
212
+ url: new URL("https://salesforce-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}"),
213
+ },
214
+ hubspot: {
215
+ url: new URL("https://hubspot-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}"),
216
+ },
217
+ },
218
+ });
219
+ ```
220
+
221
+ Klavis AI offers enterprise-grade authentication and security for production deployments.
222
+
223
+ For more details on how to integrate Mastra with Klavis, check out their [documentation](https://docs.klavis.ai/documentation/ai-platform-integration/mastra).
224
+
225
+
226
+ **mcp-run:**
227
+
228
+ [mcp.run](https://www.mcp.run/) provides pre-authenticated, managed MCP servers. Tools are grouped into Profiles, each with a unique, signed URL.
229
+
230
+ ```typescript
231
+ import { MCPClient } from "@mastra/mcp";
232
+
233
+ const mcp = new MCPClient({
234
+ servers: {
235
+ marketing: { // Example profile name
236
+ url: new URL(process.env.MCP_RUN_SSE_URL!), // Get URL from mcp.run profile
237
+ },
238
+ },
239
+ });
240
+ ```
241
+
242
+ > **Important:** Treat the mcp.run SSE URL like a password. Store it securely, for example, in an environment variable.
243
+ > ```bash title=".env"
244
+ > MCP_RUN_SSE_URL=https://www.mcp.run/api/mcp/sse?nonce=...
245
+ > ```
246
+
247
+
248
+ **composio:**
249
+
250
+ [Composio.dev](https://composio.dev) offers a registry of [SSE-based MCP servers](https://mcp.composio.dev). You can use the SSE URL generated for tools like Cursor directly.
251
+
252
+ ```typescript
253
+ import { MCPClient } from "@mastra/mcp";
254
+
255
+ const mcp = new MCPClient({
256
+ servers: {
257
+ googleSheets: {
258
+ url: new URL("https://mcp.composio.dev/googlesheets/[private-url-path]"),
259
+ },
260
+ gmail: {
261
+ url: new URL("https://mcp.composio.dev/gmail/[private-url-path]"),
262
+ },
263
+ },
264
+ });
265
+ ```
266
+
267
+ Authentication with services like Google Sheets often happens interactively through the agent conversation.
268
+
269
+ *Note: Composio URLs are typically tied to a single user account, making them best suited for personal automation rather than multi-tenant applications.*
270
+
271
+
272
+ **smithery:**
273
+
274
+ [Smithery.ai](https://smithery.ai) provides a registry accessible via their CLI.
275
+
276
+ ```typescript
277
+ // Unix/Mac
278
+ import { MCPClient } from "@mastra/mcp";
279
+
280
+ const mcp = new MCPClient({
281
+ servers: {
282
+ sequentialThinking: {
283
+ command: "npx",
284
+ args: [
285
+ "-y",
286
+ "@smithery/cli@latest",
287
+ "run",
288
+ "@smithery-ai/server-sequential-thinking",
289
+ "--config",
290
+ "{}",
291
+ ],
292
+ },
293
+ },
294
+ });
295
+ ```
296
+
297
+ ```typescript
298
+ // Windows
299
+ import { MCPClient } from "@mastra/mcp";
300
+
301
+ const mcp = new MCPClient({
302
+ servers: {
303
+ sequentialThinking: {
304
+ command: "npx",
305
+ args: [
306
+ "-y",
307
+ "@smithery/cli@latest",
308
+ "run",
309
+ "@smithery-ai/server-sequential-thinking",
310
+ "--config",
311
+ "{}",
312
+ ],
313
+ },
314
+ },
315
+ });
316
+ ```
317
+
318
+
319
+ **ampersand:**
320
+
321
+ [Ampersand](https://withampersand.com?utm_source=mastra-docs) offers an [MCP Server](https://docs.withampersand.com/mcp) that allows you to connect your agent to 150+ integrations with SaaS products like Salesforce, Hubspot, and Zendesk.
322
+
323
+ ```typescript
324
+ // MCPClient with Ampersand MCP Server using SSE
325
+ export const mcp = new MCPClient({
326
+ servers: {
327
+ "@amp-labs/mcp-server": {
328
+ url: `https://mcp.withampersand.com/v1/sse?${new URLSearchParams({
329
+ apiKey: process.env.AMPERSAND_API_KEY,
330
+ project: process.env.AMPERSAND_PROJECT_ID,
331
+ integrationName: process.env.AMPERSAND_INTEGRATION_NAME,
332
+ groupRef: process.env.AMPERSAND_GROUP_REF,
333
+ })}`,
334
+ },
335
+ },
336
+ });
337
+ ```
338
+
339
+ ```typescript
340
+ // If you prefer to run the MCP server locally:
341
+ import { MCPClient } from "@mastra/mcp";
342
+
343
+ // MCPClient with Ampersand MCP Server using stdio transport
344
+ export const mcp = new MCPClient({
345
+ servers: {
346
+ "@amp-labs/mcp-server": {
347
+ command: "npx",
348
+ args: [
349
+ "-y",
350
+ "@amp-labs/mcp-server@latest",
351
+ "--transport",
352
+ "stdio",
353
+ "--project",
354
+ process.env.AMPERSAND_PROJECT_ID,
355
+ "--integrationName",
356
+ process.env.AMPERSAND_INTEGRATION_NAME,
357
+ "--groupRef",
358
+ process.env.AMPERSAND_GROUP_REF, // optional
359
+ ],
360
+ env: {
361
+ AMPERSAND_API_KEY: process.env.AMPERSAND_API_KEY,
362
+ },
363
+ },
364
+ },
365
+ });
366
+ ```
367
+
368
+ As an alternative to MCP, Ampersand's AI SDK also has an adapter for Mastra, so you can [directly import Ampersand tools](https://docs.withampersand.com/ai-sdk#use-with-mastra) for your agent to access.
369
+
370
+
371
+
372
+ ## Related
373
+
374
+ - [Using Tools](https://mastra.ai/docs/v1/agents/using-tools)
375
+ - [MCPClient](https://mastra.ai/reference/v1/tools/mcp-client)
376
+ - [MCPServer](https://mastra.ai/reference/v1/tools/mcp-server)
package/dist/index.cjs CHANGED
@@ -1821,14 +1821,20 @@ To fix this you have three different options:
1821
1821
  }
1822
1822
  };
1823
1823
 
1824
- // ../../node_modules/.pnpm/hono@4.10.6/node_modules/hono/dist/utils/stream.js
1824
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/stream.js
1825
1825
  var StreamingApi = class {
1826
1826
  writer;
1827
1827
  encoder;
1828
1828
  writable;
1829
1829
  abortSubscribers = [];
1830
1830
  responseReadable;
1831
+ /**
1832
+ * Whether the stream has been aborted.
1833
+ */
1831
1834
  aborted = false;
1835
+ /**
1836
+ * Whether the stream has been closed normally.
1837
+ */
1832
1838
  closed = false;
1833
1839
  constructor(writable, _readable) {
1834
1840
  this.writable = writable;
@@ -1880,6 +1886,10 @@ var StreamingApi = class {
1880
1886
  onAbort(listener) {
1881
1887
  this.abortSubscribers.push(listener);
1882
1888
  }
1889
+ /**
1890
+ * Abort the stream.
1891
+ * You can call this method when stream is aborted by external event.
1892
+ */
1883
1893
  abort() {
1884
1894
  if (!this.aborted) {
1885
1895
  this.aborted = true;
@@ -1888,7 +1898,7 @@ var StreamingApi = class {
1888
1898
  }
1889
1899
  };
1890
1900
 
1891
- // ../../node_modules/.pnpm/hono@4.10.6/node_modules/hono/dist/helper/streaming/utils.js
1901
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/helper/streaming/utils.js
1892
1902
  var isOldBunVersion = () => {
1893
1903
  const version = typeof Bun !== "undefined" ? Bun.version : void 0;
1894
1904
  if (version === void 0) {
@@ -1899,7 +1909,7 @@ var isOldBunVersion = () => {
1899
1909
  return result;
1900
1910
  };
1901
1911
 
1902
- // ../../node_modules/.pnpm/hono@4.10.6/node_modules/hono/dist/utils/html.js
1912
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/utils/html.js
1903
1913
  var HtmlEscapedCallbackPhase = {
1904
1914
  Stringify: 1};
1905
1915
  var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) => {
@@ -1930,7 +1940,7 @@ var resolveCallback = async (str, phase, preserveCallbacks, context, buffer) =>
1930
1940
  }
1931
1941
  };
1932
1942
 
1933
- // ../../node_modules/.pnpm/hono@4.10.6/node_modules/hono/dist/helper/streaming/sse.js
1943
+ // ../../node_modules/.pnpm/hono@4.11.3/node_modules/hono/dist/helper/streaming/sse.js
1934
1944
  var SSEStreamingApi = class extends StreamingApi {
1935
1945
  constructor(writable, readable) {
1936
1946
  super(writable, readable);