Guide for using Model Context Protocol (MCP) to connect AI agents with external tools and resources in Mastra applications.
Insight
Mastra supports MCP as an open standard for connecting AI agents to external tools and resources. Two main classes are available: MCPClient connects to external MCP servers to access their tools, resources, prompts, and handle elicitation requests; MCPServer exposes Mastra tools, agents, workflows, prompts, and resources to MCP-compatible clients. MCPClient supports both local packages invoked via npx and remote HTTP(S) endpoints. Each server configuration requires either a ‘command’ or ‘url’ property. MCPClient offers two approaches for retrieving tools: listTools() for static configurations suitable for single-user CLI tools with shared credentials, and listToolsets() for dynamic per-request configurations supporting multi-tenant SaaS applications where credentials vary by user. MCPServer can expose agents, tools, and workflows over HTTP(S) and must be registered in the Mastra instance using mcpServers. Tool approval can be configured with requireToolApproval on server definitions for human-in-the-loop validation. MCP servers can be discovered through registries including Klavis AI (enterprise-authenticated), mcp.run (pre-authenticated managed servers), Composio.dev (SSE-based), Smithery.ai (CLI-accessible), Apify (largest marketplace with thousands of Actors), and Ampersand (150+ SaaS integrations). MCP Apps enables interactive HTML UIs via sandboxed iframes in Studio.
Hành động
Install the @mastra/mcp@latest package using npm, pnpm, yarn, or bun. For MCPClient, configure servers with either command (for npx-based local packages) or url (for remote endpoints). Load tools using listTools() in agent constructor for static config, or listToolsets() for dynamic per-request loading. Integrate with agents by passing tools to the tools parameter. For MCPServer, import MCPServer and register it in the Mastra instance using mcpServers option. Configure requireToolApproval for human approval before tool execution. Connect to MCP registries by configuring their specific URLs or commands. Treat mcp.run SSE URLs as secrets and store in environment variables. For Apify, obtain API token from Apify Console and configure Authorization header.
Kết quả
MCPClient enables agents to call tools from external MCP servers regardless of language or hosting environment. MCPServer exposes Mastra primitives to any MCP-compatible client. Static listTools() provides fixed tools at agent initialization with shared credentials; dynamic listToolsets() returns toolsets for per-request passing via agent.generate() or agent.stream() options. Human approval integration via requireToolApproval enables human-in-the-loop validation before tool execution.
Điều kiện áp dụng
Requires @mastra/mcp@latest package. MCPClient.listToolsets() is for multi-tenant/dynamic scenarios. Composio URLs are tied to single user accounts, suitable for personal automation. Ampersand offers both MCP and direct AI SDK adapter options.
Nội dung gốc (Original)
MCP overview
Mastra supports the Model Context Protocol (MCP), 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.
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.
Mastra currently supports two MCP classes:
MCPClient: Connects to one or many MCP servers to access their tools, resources, prompts, and handle elicitation requests.
MCPServer: Exposes Mastra tools, agents, workflows, prompts, and resources to MCP-compatible clients.
Get started
To use MCP, install the required dependency:
npm:
npm install @mastra/mcp@latest
pnpm:
pnpm add @mastra/mcp@latest
Yarn:
yarn add @mastra/mcp@latest
Bun:
bun add @mastra/mcp@latest
Configuring MCPClient
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.
Info: Visit MCPClient for a full list of configuration options.
Authentication: For connecting to OAuth-protected MCP servers, see the OAuth Authentication section.
Using MCPClient with an agent
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.
import { Agent } from '@mastra/core/agent'import { testMcpClient } from '../mcp/test-mcp-client'export const testAgent = new Agent({ id: 'test-agent', name: 'Test Agent', description: 'You are a helpful AI assistant', instructions: ` You are a helpful assistant that has access to the following MCP Servers. - Wikipedia MCP Server - US National Weather Service Answer questions using the information you find using the MCP Servers.`, model: 'openai/gpt-5.4', tools: await testMcpClient.listTools(),})
Info: Visit Agent Class for a full list of configuration options.
Tool approval
You can require human approval before MCP tools are executed by setting requireToolApproval on a server definition. This integrates with the existing human-in-the-loop approval flow.
export const mcp = new MCPClient({ servers: { github: { url: new URL('http://localhost:3000/mcp'), requireToolApproval: true, }, },})
You can also pass a function to decide dynamically per-call. See the MCPClient reference for the full API.
Configuring MCPServer
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.
import { MCPServer } from '@mastra/mcp'import { testAgent } from '../agents/test-agent'import { testWorkflow } from '../workflows/test-workflow'import { testTool } from '../tools/test-tool'export const testMcpServer = new MCPServer({ id: 'test-mcp-server', name: 'Test Server', version: '1.0.0', agents: { testAgent }, tools: { testTool }, workflows: { testWorkflow },})
Info: Visit MCPServer for a full list of configuration options.
Authentication: To protect your MCP server with OAuth, see the OAuth Protection section.
Registering an MCPServer
To make an MCP server available to other systems or agents that support the protocol, register it in the main Mastra instance using mcpServers.
import { Mastra } from '@mastra/core/mastra'import { testMcpServer } from './mcp/test-mcp-server'export const mastra = new Mastra({ mcpServers: { testMcpServer },})
Static and dynamic tools
MCPClient offers two approaches to retrieving tools from connected servers, suitable for different application architectures:
Feature
Static Configuration (await mcp.listTools())
Dynamic Configuration (await mcp.listToolsets())
Use Case
Single-user, static config (e.g., CLI tool)
Multi-user, dynamic config (e.g., SaaS app)
Configuration
Fixed at agent initialization
Per-request, dynamic
Credentials
Shared across all uses
Can vary per user/request
Agent Setup
Tools added in Agent constructor
Tools passed in .generate() or .stream() options
Static tools
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.
import { Agent } from '@mastra/core/agent'import { testMcpClient } from '../mcp/test-mcp-client'export const testAgent = new Agent({ id: 'test-agent', tools: await testMcpClient.listTools(),})
Dynamic tools
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.
MCP servers can be discovered through registries. Here’s how to connect to some popular ones using MCPClient:
Klavis AI:
Klavis AI provides hosted, enterprise-authenticated, high-quality MCP servers.
import { MCPClient } from '@mastra/mcp'const mcp = new MCPClient({ servers: { salesforce: { url: new URL( 'https://salesforce-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}', ), }, hubspot: { url: new URL('https://hubspot-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}'), }, },})
Klavis AI offers enterprise-grade authentication and security for production deployments.
For more details on how to integrate Mastra with Klavis, check out their documentation.
mcp.run:
mcp.run provides pre-authenticated, managed MCP servers. Tools are grouped into Profiles, each with a unique, signed URL.
import { MCPClient } from '@mastra/mcp'const mcp = new MCPClient({ servers: { marketing: { // Example profile name url: new URL(process.env.MCP_RUN_SSE_URL!), // Get URL from mcp.run profile }, },})
Important: Treat the mcp.run SSE URL like a password. Store it securely, for example, in an environment variable.
import { MCPClient } from '@mastra/mcp'const mcp = new MCPClient({ servers: { googleSheets: { url: new URL('https://mcp.composio.dev/googlesheets/[private-url-path]'), }, gmail: { url: new URL('https://mcp.composio.dev/gmail/[private-url-path]'), }, },})
Authentication with services like Google Sheets often happens interactively through the agent conversation.
Note: Composio URLs are typically tied to a single user account, making them best suited for personal automation rather than multi-tenant applications.
Smithery.ai:
Smithery.ai provides a registry accessible via their CLI.
Apify is the largest marketplace of tools for AI, with thousands of ready-made Actors to extract real-time data from any website, track competitors, generate leads, analyze sentiment, or orchestrate your apps. Connect your agent through the Apify MCP Server.
import { MCPClient } from '@mastra/mcp'export const mcp = new MCPClient({ servers: { apify: { url: new URL('https://mcp.apify.com'), requestInit: { headers: { Authorization: `Bearer ${process.env.APIFY_TOKEN}`, }, }, }, },})
Get your API token from the Apify Console and store it as APIFY_TOKEN in your environment.
Ampersand offers an MCP Server that allows you to connect your agent to 150+ integrations with SaaS products like Salesforce, Hubspot, and Zendesk.
// MCPClient with Ampersand MCP Server using SSEexport const mcp = new MCPClient({ servers: { '@amp-labs/mcp-server': { url: `https://mcp.withampersand.com/v1/sse?${new URLSearchParams({ apiKey: process.env.AMPERSAND_API_KEY, project: process.env.AMPERSAND_PROJECT_ID, integrationName: process.env.AMPERSAND_INTEGRATION_NAME, groupRef: process.env.AMPERSAND_GROUP_REF, })}`, }, },})
// If you prefer to run the MCP server locally:import { MCPClient } from '@mastra/mcp'// MCPClient with Ampersand MCP Server using stdio transportexport const mcp = new MCPClient({ servers: { '@amp-labs/mcp-server': { command: 'npx', args: [ '-y', '@amp-labs/mcp-server@latest', '--transport', 'stdio', '--project', process.env.AMPERSAND_PROJECT_ID, '--integrationName', process.env.AMPERSAND_INTEGRATION_NAME, '--groupRef', process.env.AMPERSAND_GROUP_REF, // optional ], env: { AMPERSAND_API_KEY: process.env.AMPERSAND_API_KEY, }, }, },})
As an alternative to MCP, Ampersand’s AI SDK also has an adapter for Mastra, so you can directly import Ampersand tools for your agent to access.
MCP Apps
MCP servers can serve interactive HTML UIs via the MCP Apps extension. Tools with associated ui:// resources render sandboxed iframes in Studio — both on tool detail pages and inline in agent chat. The app iframe can call server tools and inject messages into the conversation.
Note: Visit MCP Apps for setup instructions and the app bridge API.