@mastra/mcp 1.0.0-beta.0 → 1.0.0-beta.10

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 (51) hide show
  1. package/CHANGELOG.md +303 -0
  2. package/README.md +250 -24
  3. package/dist/__fixtures__/tools.d.ts +8 -5
  4. package/dist/__fixtures__/tools.d.ts.map +1 -1
  5. package/dist/client/{elicitationActions.d.ts → actions/elicitation.d.ts} +2 -2
  6. package/dist/client/actions/elicitation.d.ts.map +1 -0
  7. package/dist/client/actions/progress.d.ts +23 -0
  8. package/dist/client/actions/progress.d.ts.map +1 -0
  9. package/dist/client/{promptActions.d.ts → actions/prompt.d.ts} +2 -2
  10. package/dist/client/actions/prompt.d.ts.map +1 -0
  11. package/dist/client/{resourceActions.d.ts → actions/resource.d.ts} +2 -2
  12. package/dist/client/actions/resource.d.ts.map +1 -0
  13. package/dist/client/client.d.ts +79 -132
  14. package/dist/client/client.d.ts.map +1 -1
  15. package/dist/client/configuration.d.ts +23 -1
  16. package/dist/client/configuration.d.ts.map +1 -1
  17. package/dist/client/index.d.ts +3 -1
  18. package/dist/client/index.d.ts.map +1 -1
  19. package/dist/client/oauth-provider.d.ts +230 -0
  20. package/dist/client/oauth-provider.d.ts.map +1 -0
  21. package/dist/client/types.d.ts +237 -0
  22. package/dist/client/types.d.ts.map +1 -0
  23. package/dist/docs/README.md +33 -0
  24. package/dist/docs/SKILL.md +46 -0
  25. package/dist/docs/SOURCE_MAP.json +59 -0
  26. package/dist/docs/mcp/01-overview.md +372 -0
  27. package/dist/docs/mcp/02-publishing-mcp-server.md +111 -0
  28. package/dist/docs/tools/01-reference.md +2306 -0
  29. package/dist/docs/tools-mcp/01-mcp-overview.md +384 -0
  30. package/dist/index.cjs +851 -107
  31. package/dist/index.cjs.map +1 -1
  32. package/dist/index.d.ts +1 -0
  33. package/dist/index.d.ts.map +1 -1
  34. package/dist/index.js +774 -92
  35. package/dist/index.js.map +1 -1
  36. package/dist/server/index.d.ts +1 -0
  37. package/dist/server/index.d.ts.map +1 -1
  38. package/dist/server/oauth-middleware.d.ts +142 -0
  39. package/dist/server/oauth-middleware.d.ts.map +1 -0
  40. package/dist/server/server.d.ts +20 -4
  41. package/dist/server/server.d.ts.map +1 -1
  42. package/dist/server/types.d.ts +11 -4
  43. package/dist/server/types.d.ts.map +1 -1
  44. package/dist/shared/index.d.ts +2 -0
  45. package/dist/shared/index.d.ts.map +1 -0
  46. package/dist/shared/oauth-types.d.ts +137 -0
  47. package/dist/shared/oauth-types.d.ts.map +1 -0
  48. package/package.json +17 -14
  49. package/dist/client/elicitationActions.d.ts.map +0 -1
  50. package/dist/client/promptActions.d.ts.map +0 -1
  51. package/dist/client/resourceActions.d.ts.map +0 -1
@@ -0,0 +1,372 @@
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
+ > **Note:** Authentication
50
+
51
+ For connecting to OAuth-protected MCP servers, see the [OAuth Authentication](https://mastra.ai/reference/v1/tools/mcp-client#oauth-authentication) section.
52
+
53
+ ## Using `MCPClient` with an agent
54
+
55
+ 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.
56
+
57
+ ```typescript {3,15} title="src/mastra/agents/test-agent.ts"
58
+ import { Agent } from "@mastra/core/agent";
59
+
60
+ import { testMcpClient } from "../mcp/test-mcp-client";
61
+
62
+ export const testAgent = new Agent({
63
+ id: "test-agent",
64
+ name: "Test Agent",
65
+ description: "You are a helpful AI assistant",
66
+ instructions: `
67
+ You are a helpful assistant that has access to the following MCP Servers.
68
+ - Wikipedia MCP Server
69
+ - US National Weather Service
70
+
71
+ Answer questions using the information you find using the MCP Servers.`,
72
+ model: "openai/gpt-5.1",
73
+ tools: await testMcpClient.listTools(),
74
+ });
75
+ ```
76
+
77
+ > **Note:**
78
+
79
+ Visit [Agent Class](https://mastra.ai/reference/v1/agents/agent) for a full list of configuration options.
80
+
81
+ ## Configuring `MCPServer`
82
+
83
+ 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.
84
+
85
+ ```typescript title="src/mastra/mcp/test-mcp-server.ts"
86
+ import { MCPServer } from "@mastra/mcp";
87
+
88
+ import { testAgent } from "../agents/test-agent";
89
+ import { testWorkflow } from "../workflows/test-workflow";
90
+ import { testTool } from "../tools/test-tool";
91
+
92
+ export const testMcpServer = new MCPServer({
93
+ id: "test-mcp-server",
94
+ name: "Test Server",
95
+ version: "1.0.0",
96
+ agents: { testAgent },
97
+ tools: { testTool },
98
+ workflows: { testWorkflow },
99
+ });
100
+ ```
101
+
102
+ > **Note:**
103
+
104
+ Visit [MCPServer](https://mastra.ai/reference/v1/tools/mcp-server) for a full list of configuration options.
105
+
106
+ > **Note:** Authentication
107
+
108
+ To protect your MCP server with OAuth, see the [OAuth Protection](https://mastra.ai/reference/v1/tools/mcp-server#oauth-protection) section.
109
+
110
+ ## Registering an `MCPServer`
111
+
112
+ To make an MCP server available to other systems or agents that support the protocol, register it in the main `Mastra` instance using `mcpServers`.
113
+
114
+ ```typescript title="src/mastra/index.ts"
115
+ import { Mastra } from "@mastra/core/mastra";
116
+
117
+ import { testMcpServer } from "./mcp/test-mcp-server";
118
+
119
+ export const mastra = new Mastra({
120
+ mcpServers: { testMcpServer },
121
+ });
122
+ ```
123
+
124
+ ## Static and dynamic tools
125
+
126
+ `MCPClient` offers two approaches to retrieving tools from connected servers, suitable for different application architectures:
127
+
128
+ | Feature | Static Configuration (`await mcp.listTools()`) | Dynamic Configuration (`await mcp.listToolsets()`) |
129
+ | :---------------- | :--------------------------------------------- | :--------------------------------------------------- |
130
+ | **Use Case** | Single-user, static config (e.g., CLI tool) | Multi-user, dynamic config (e.g., SaaS app) |
131
+ | **Configuration** | Fixed at agent initialization | Per-request, dynamic |
132
+ | **Credentials** | Shared across all uses | Can vary per user/request |
133
+ | **Agent Setup** | Tools added in `Agent` constructor | Tools passed in `.generate()` or `.stream()` options |
134
+
135
+ ### Static tools
136
+
137
+ 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.
138
+
139
+ > **Note:**
140
+
141
+ Visit [listTools()](https://mastra.ai/reference/v1/tools/mcp-client#listtools) for more information.
142
+
143
+ ```typescript {6} title="src/mastra/agents/test-agent.ts"
144
+ import { Agent } from "@mastra/core/agent";
145
+
146
+ import { testMcpClient } from "../mcp/test-mcp-client";
147
+
148
+ export const testAgent = new Agent({
149
+ id: "test-agent",
150
+ tools: await testMcpClient.listTools(),
151
+ });
152
+ ```
153
+
154
+ ### Dynamic tools
155
+
156
+ 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.
157
+
158
+ ```typescript {5-16,21}
159
+ import { MCPClient } from "@mastra/mcp";
160
+ import { mastra } from "./mastra";
161
+
162
+ async function handleRequest(userPrompt: string, userApiKey: string) {
163
+ const userMcp = new MCPClient({
164
+ servers: {
165
+ weather: {
166
+ url: new URL("http://localhost:8080/mcp"),
167
+ requestInit: {
168
+ headers: {
169
+ Authorization: `Bearer ${userApiKey}`,
170
+ },
171
+ },
172
+ },
173
+ },
174
+ });
175
+
176
+ const agent = mastra.getAgent("testAgent");
177
+
178
+ const response = await agent.generate(userPrompt, {
179
+ toolsets: await userMcp.listToolsets(),
180
+ });
181
+
182
+ await userMcp.disconnect();
183
+
184
+ return Response.json({
185
+ data: response.text,
186
+ });
187
+ }
188
+ ```
189
+
190
+ > **Note:**
191
+
192
+ Visit [listToolsets()](https://mastra.ai/reference/v1/tools/mcp-client#listtoolsets) for more information.
193
+
194
+ ## Connecting to an MCP registry
195
+
196
+ MCP servers can be discovered through registries. Here's how to connect to some popular ones using `MCPClient`:
197
+
198
+ **klavis:**
199
+
200
+ [Klavis AI](https://klavis.ai) provides hosted, enterprise-authenticated, high-quality MCP servers.
201
+
202
+ ```typescript
203
+ import { MCPClient } from "@mastra/mcp";
204
+
205
+ const mcp = new MCPClient({
206
+ servers: {
207
+ salesforce: {
208
+ url: new URL("https://salesforce-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}"),
209
+ },
210
+ hubspot: {
211
+ url: new URL("https://hubspot-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}"),
212
+ },
213
+ },
214
+ });
215
+ ```
216
+
217
+ Klavis AI offers enterprise-grade authentication and security for production deployments.
218
+
219
+ For more details on how to integrate Mastra with Klavis, check out their [documentation](https://docs.klavis.ai/documentation/ai-platform-integration/mastra).
220
+
221
+
222
+ **mcp-run:**
223
+
224
+ [mcp.run](https://www.mcp.run/) provides pre-authenticated, managed MCP servers. Tools are grouped into Profiles, each with a unique, signed URL.
225
+
226
+ ```typescript
227
+ import { MCPClient } from "@mastra/mcp";
228
+
229
+ const mcp = new MCPClient({
230
+ servers: {
231
+ marketing: { // Example profile name
232
+ url: new URL(process.env.MCP_RUN_SSE_URL!), // Get URL from mcp.run profile
233
+ },
234
+ },
235
+ });
236
+ ```
237
+
238
+ > **Important:** Treat the mcp.run SSE URL like a password. Store it securely, for example, in an environment variable.
239
+ > ```bash title=".env"
240
+ > MCP_RUN_SSE_URL=https://www.mcp.run/api/mcp/sse?nonce=...
241
+ > ```
242
+
243
+
244
+ **composio:**
245
+
246
+ [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.
247
+
248
+ ```typescript
249
+ import { MCPClient } from "@mastra/mcp";
250
+
251
+ const mcp = new MCPClient({
252
+ servers: {
253
+ googleSheets: {
254
+ url: new URL("https://mcp.composio.dev/googlesheets/[private-url-path]"),
255
+ },
256
+ gmail: {
257
+ url: new URL("https://mcp.composio.dev/gmail/[private-url-path]"),
258
+ },
259
+ },
260
+ });
261
+ ```
262
+
263
+ Authentication with services like Google Sheets often happens interactively through the agent conversation.
264
+
265
+ *Note: Composio URLs are typically tied to a single user account, making them best suited for personal automation rather than multi-tenant applications.*
266
+
267
+
268
+ **smithery:**
269
+
270
+ [Smithery.ai](https://smithery.ai) provides a registry accessible via their CLI.
271
+
272
+ ```typescript
273
+ // Unix/Mac
274
+ import { MCPClient } from "@mastra/mcp";
275
+
276
+ const mcp = new MCPClient({
277
+ servers: {
278
+ sequentialThinking: {
279
+ command: "npx",
280
+ args: [
281
+ "-y",
282
+ "@smithery/cli@latest",
283
+ "run",
284
+ "@smithery-ai/server-sequential-thinking",
285
+ "--config",
286
+ "{}",
287
+ ],
288
+ },
289
+ },
290
+ });
291
+ ```
292
+
293
+ ```typescript
294
+ // Windows
295
+ import { MCPClient } from "@mastra/mcp";
296
+
297
+ const mcp = new MCPClient({
298
+ servers: {
299
+ sequentialThinking: {
300
+ command: "npx",
301
+ args: [
302
+ "-y",
303
+ "@smithery/cli@latest",
304
+ "run",
305
+ "@smithery-ai/server-sequential-thinking",
306
+ "--config",
307
+ "{}",
308
+ ],
309
+ },
310
+ },
311
+ });
312
+ ```
313
+
314
+
315
+ **ampersand:**
316
+
317
+ [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.
318
+
319
+ ```typescript
320
+ // MCPClient with Ampersand MCP Server using SSE
321
+ export const mcp = new MCPClient({
322
+ servers: {
323
+ "@amp-labs/mcp-server": {
324
+ url: `https://mcp.withampersand.com/v1/sse?${new URLSearchParams({
325
+ apiKey: process.env.AMPERSAND_API_KEY,
326
+ project: process.env.AMPERSAND_PROJECT_ID,
327
+ integrationName: process.env.AMPERSAND_INTEGRATION_NAME,
328
+ groupRef: process.env.AMPERSAND_GROUP_REF,
329
+ })}`,
330
+ },
331
+ },
332
+ });
333
+ ```
334
+
335
+ ```typescript
336
+ // If you prefer to run the MCP server locally:
337
+ import { MCPClient } from "@mastra/mcp";
338
+
339
+ // MCPClient with Ampersand MCP Server using stdio transport
340
+ export const mcp = new MCPClient({
341
+ servers: {
342
+ "@amp-labs/mcp-server": {
343
+ command: "npx",
344
+ args: [
345
+ "-y",
346
+ "@amp-labs/mcp-server@latest",
347
+ "--transport",
348
+ "stdio",
349
+ "--project",
350
+ process.env.AMPERSAND_PROJECT_ID,
351
+ "--integrationName",
352
+ process.env.AMPERSAND_INTEGRATION_NAME,
353
+ "--groupRef",
354
+ process.env.AMPERSAND_GROUP_REF, // optional
355
+ ],
356
+ env: {
357
+ AMPERSAND_API_KEY: process.env.AMPERSAND_API_KEY,
358
+ },
359
+ },
360
+ },
361
+ });
362
+ ```
363
+
364
+ 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.
365
+
366
+
367
+
368
+ ## Related
369
+
370
+ - [Using Tools](https://mastra.ai/docs/v1/agents/using-tools)
371
+ - [MCPClient](https://mastra.ai/reference/v1/tools/mcp-client)
372
+ - [MCPServer](https://mastra.ai/reference/v1/tools/mcp-server)
@@ -0,0 +1,111 @@
1
+ > Guide to setting up and building a Mastra MCP server using the stdio transport, and publishing it to NPM.
2
+
3
+ # Publishing an MCP Server
4
+
5
+ This example guides you through setting up a basic Mastra MCPServer using the stdio transport, building it, and preparing it for publishing to NPM.
6
+
7
+ ## Install dependencies
8
+
9
+ Install the necessary packages:
10
+
11
+ ```bash
12
+ pnpm add @mastra/mcp @mastra/core tsup
13
+ ```
14
+
15
+ ## Setting up an MCP Server
16
+
17
+ ### Step
18
+
19
+ Create a file for your stdio server, for example, `/src/mastra/stdio.ts`.
20
+
21
+ ### Step
22
+
23
+ Add the following code to the file. Remember to import your actual Mastra tools and name the server appropriately.
24
+
25
+ ```typescript title="src/mastra/stdio.ts"
26
+ #!/usr/bin/env node
27
+ import { MCPServer } from "@mastra/mcp";
28
+ import { weatherTool } from "./tools";
29
+
30
+ const server = new MCPServer({
31
+ name: "my-mcp-server",
32
+ version: "1.0.0",
33
+ tools: { weatherTool },
34
+ });
35
+
36
+ server.startStdio().catch((error) => {
37
+ console.error("Error running MCP server:", error);
38
+ process.exit(1);
39
+ });
40
+ ```
41
+
42
+ ### Step
43
+
44
+ Update your `package.json` to include the `bin` entry pointing to your built server file and a script to build the server with both ESM and CJS outputs.
45
+
46
+ ```json title="package.json"
47
+ {
48
+ "bin": "dist/stdio.mjs",
49
+ "scripts": {
50
+ "build:mcp": "tsup src/mastra/stdio.ts --format esm,cjs --no-splitting --dts && echo '#!/usr/bin/env node' | cat - dist/stdio.mjs > temp && mv temp dist/stdio.mjs && chmod +x dist/stdio.mjs"
51
+ }
52
+ }
53
+ ```
54
+
55
+ The build command generates both ESM (`.mjs`) and CJS (`.cjs`) outputs for maximum compatibility. The shebang (`#!/usr/bin/env node`) is prepended to the ESM artifact to make it directly executable, and the `bin` entry points to this file.
56
+
57
+ ### Step
58
+
59
+ Run the build command:
60
+
61
+ ```bash
62
+ pnpm run build:mcp
63
+ ```
64
+
65
+ This will compile your server code into both ESM and CJS formats and make the ESM output file executable. On Unix-like systems, the `chmod +x` step makes the file directly executable. Windows users may need to use WSL or handle execution through Node.js directly.
66
+
67
+ ## Publishing to NPM
68
+
69
+ To make your MCP server available for others (or yourself) to use via `npx` or as a dependency, you can publish it to NPM.
70
+
71
+ ### Step
72
+
73
+ Ensure you have an NPM account and are logged in (`npm login`).
74
+
75
+ ### Step
76
+
77
+ Make sure your package name in `package.json` is unique and available.
78
+
79
+ ### Step
80
+
81
+ Run the publish command from your project root after building:
82
+
83
+ ```bash
84
+ npm publish --access public
85
+ ```
86
+
87
+ For more details on publishing packages, refer to the [NPM documentation](https://docs.npmjs.com/creating-and-publishing-scoped-public-packages).
88
+
89
+ ## Using a published MCP Server
90
+
91
+ Once published, your MCP server can be used by an `MCPClient` by specifying the command to run your package. You can also use any other MCP client like Claude desktop, Cursor, or Windsurf.
92
+
93
+ ```typescript
94
+ import { MCPClient } from "@mastra/mcp";
95
+
96
+ const mcp = new MCPClient({
97
+ servers: {
98
+ // Give this MCP server instance a name
99
+ yourServerName: {
100
+ command: "npx",
101
+ args: ["-y", "@your-org-name/your-package-name@latest"], // Replace with your package name
102
+ },
103
+ },
104
+ });
105
+
106
+ // You can then get tools or toolsets from this configuration to use in your agent
107
+ const tools = await mcp.listTools();
108
+ const toolsets = await mcp.listToolsets();
109
+ ```
110
+
111
+ Note: If you published without an organization scope, the `args` might just be `["-y", "your-package-name@latest"]`.