Skip to Content
DocsTools & MCPMCP Overview

MCP Overview

Model Context Protocol (MCP) is an open standard designed to let AI models discover and interact with external tools and resources. Think of it as a universal plugin system for AI agents, allowing them to use tools regardless of the language they were written in or where they are hosted.

Mastra uses MCP to connect agents to external tool servers.

Use third-party tools with an MCP Client

Mastra provides the MCPClient class to manage connections to one or more MCP servers and access their tools.

Installation

If you haven’t already, install the Mastra MCP package:

npm install @mastra/mcp@latest

Registering the MCPServer

Register your MCP server with Mastra to enable logging and access to configured tools and integrations:

src/mastra/index.ts
import { Mastra } from "@mastra/core"; import { myMcpServer } from "./mcpServers"; export const mastra = new Mastra({ mcpServers: { myMcpServer }, });

Configuring MCPClient

You configure MCPClient with a map of servers you want to connect to. It supports connections via subprocess (Stdio) or HTTP (Streamable HTTP with SSE fallback).

import { MCPClient } from "@mastra/mcp"; const mcp = new MCPClient({ servers: { // Stdio example sequential: { command: "npx", args: ["-y", "@modelcontextprotocol/server-sequential-thinking"], }, // HTTP example weather: { url: new URL("http://localhost:8080/mcp"), requestInit: { headers: { Authorization: "Bearer your-token", }, }, }, }, });

For detailed configuration options, see the MCPClient reference documentation.

Static vs Dynamic Tool Configurations

MCPClient offers two approaches to retrieving tools from connected servers, suitable for different application architectures:

FeatureStatic Configuration (await mcp.getTools())Dynamic Configuration (await mcp.getToolsets())
Use CaseSingle-user, static config (e.g., CLI tool)Multi-user, dynamic config (e.g., SaaS app)
ConfigurationFixed at agent initializationPer-request, dynamic
CredentialsShared across all usesCan vary per user/request
Agent SetupTools added in Agent constructorTools passed in generate() or stream() options
  • Static Configuration (getTools()): Fetches all tools from all configured servers. Best when the tool configuration (like API keys) is static and shared across all users or requests. You typically call this once and pass the result to the tools property when defining your Agent. Reference: getTools()

    import { Agent } from "@mastra/core/agent"; // ... mcp client setup const agent = new Agent({ // ... other agent config tools: await mcp.getTools(), });
  • Dynamic Configuration (getToolsets()): Designed for scenarios where configuration might change per request or per user (e.g., different API keys for different tenants in a multi-user application). You pass the result of getToolsets() to the toolsets option in the agent’s generate() or stream() method. Reference: getToolsets()

    import { Agent } from "@mastra/core/agent"; // ... agent setup without tools initially async function handleRequest(userPrompt: string, userApiKey: string) { const userMcp = new MCPClient({ /* config with userApiKey */ }); const toolsets = await userMcp.getToolsets(); const response = await agent.stream(userPrompt, { toolsets, // Pass dynamic toolsets }); // ... handle response await userMcp.disconnect(); }

Connecting to an MCP registry

MCP servers can be discovered through registries. Here’s how to connect to some popular ones using MCPClient:

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.

.env
MCP_RUN_SSE_URL=https://www.mcp.run/api/mcp/sse?nonce=...

Share your tools with an MCP server

If you have created your own Mastra tools, you can expose them to any MCP-compatible client using Mastra’s MCPServer class.

Similarly, Mastra Agent and Workflow instances can also be exposed as tools via MCPServer. This allows other MCP clients to interact with your agents by “asking” them questions or run your workflows. Each agent provided in the MCPServer configuration will be converted into a tool named ask_<agentKey>, using the agent’s description property. Each workflow will be converted into a tool named run_<workflowKey>, using its inputSchema and description.

This allows others to use your tools, agents, and workflows without needing direct access to your codebase.

Using MCPServer

You initialize MCPServer with a name, version, and the Mastra tools, agents, and/or workflows you want to share.

import { MCPServer } from "@mastra/mcp"; import { Agent } from "@mastra/core/agent"; import { openai } from "@ai-sdk/openai"; import { weatherTool } from "./tools"; // Your Mastra tool import { weatherAgent } from "./agents"; // Your Mastra Agent import { dataWorkflow } from "./workflows"; // Your Mastra Workflow const server = new MCPServer({ name: "My Custom Server", version: "1.0.0", tools: { weatherTool }, // Provide your tool(s) here agents: { weatherAgent }, // Provide your agent(s) here workflows: { dataWorkflow }, // Provide your workflow(s) here }); // Start the server (e.g., using stdio for a CLI tool) // await server.startStdio(); // Or integrate with an HTTP server using startSSE() // See MCPServer reference for details

For an agent to be exposed as a tool, it must have a non-empty description string. Similarly, for a workflow to be exposed, its description must also be a non-empty string. If the description is missing or empty for either, MCPServer will throw an error during initialization. Workflows will use their inputSchema for the tool’s input.

For detailed usage and examples, see the MCPServer reference documentation.