Model Context Protocol (MCP)
Relevant source files
The following files were used as context for generating this wiki page:The Model Context Protocol (MCP) is a standardized communication system that enables AI models and agents to interact with external tools, resources, and prompts. Within the Mastra ecosystem, the @mastra/mcp package provides a client implementation that allows Mastra agents to seamlessly consume tools from any MCP-compatible server. This decouples tool implementation from the agent, allowing for modular, scalable, and reusable AI capabilities.
MCP facilitates a client-server architecture where one or more MCP servers expose structured resources (like tools) that can be discovered and utilized by MCP clients, such as a Mastra Agent. This allows for building specialized, independent services that can be consumed by various AI applications. A practical example is the @mastra/mcp-docs-server, which provides AI assistants with access to the Mastra.ai knowledge base.
Sources: packages/mcp/README.md, DEVELOPMENT.md:15, README.md:41-43, packages/mcp-docs-server/README.md:3-8, templates/template-docs-chatbot/README.md:5-9
Architecture
The MCP implementation in Mastra follows a client-server model. A Mastra application acts as the MCP client, connecting to one or more MCP servers to access tools and other resources.
This diagram illustrates the basic architectural separation:
This modular architecture allows the MCP server to be deployed and scaled independently, and consumed by multiple clients or different frontend applications.
Sources: templates/template-docs-chatbot/README.md:5-9, 106-113
Components
| Component | Description | Example Implementation |
|---|---|---|
| MCP Client | The @mastra/mcp package provides the MCPClient class, which connects to MCP servers, manages the connection lifecycle, and retrieves tools and resources. | A Mastra agent using the MCPClient to get tools. Source: packages/mcp-docs-server/README.md:65-79 |
| MCP Server | A standalone server that exposes tools, prompts, or resources over HTTP/SSE or Stdio. | The @mastra/mcp-docs-server or the server in the template-docs-chatbot. Source: templates/template-docs-chatbot/README.md:6, packages/mcp-docs-server/README.md:3-8 |
| Tools | Functions exposed by the MCP server that an agent can execute. | The mastraDocs or mastraExamples tools from the docs server. Source: packages/mcp-docs-server/README.md:83-95 |
| Resources | Data or content exposed by the server, such as documentation or data files. | The MCP server can expose resources with a URI, name, description, and MIME type. Source: packages/mcp/README.md:214-239 |
| Prompts | Structured message templates or conversational context that can be retrieved from a server. | A server can expose prompts like weather/current. Source: packages/mcp/README.md:241-263 |
MCP Client (@mastra/mcp)
The core of the client-side implementation is the MCPClient class in the @mastra/mcp package. It wraps the official @modelcontextprotocol/sdk and is responsible for managing connections to one or more MCP servers.
Sources: packages/mcp/README.md:9-12
Configuration
The MCPClient is instantiated with a configuration object that defines the servers to connect to. It can manage multiple servers simultaneously.
import { MCPClient } from '@mastra/mcp';
const mcp = new MCPClient({
servers: {
// Stdio-based server
stockPrice: {
command: 'npx',
args: ['tsx', 'stock-price.ts'],
env: { API_KEY: 'your-api-key' },
},
// HTTP-based server
weather: {
url: new URL('http://localhost:8080/mcp'),
requestInit: {
headers: { 'X-Api-Key': 'weather-key' },
},
},
},
});
Source: packages/mcp/README.md:61-82
The MastraMCPServerDefinition type outlines all possible configuration options for a server.
| Parameter | Type | Transport | Description |
|---|---|---|---|
command | string | Stdio | The command to execute for a Stdio-based server. |
args | string[] | Stdio | Arguments for the command. |
env | Record<string, string> | Stdio | Environment variables for the command. |
url | URL | HTTP | The URL for an HTTP-based server. |
fetch | FetchLike | HTTP | A custom fetch implementation for dynamic authentication or request interception. |
requestInit | RequestInit | HTTP | Configuration for the fetch API, used for initial connection and POST requests. |
eventSourceInit | EventSourceInit | HTTP (SSE) | Custom fetch configuration specifically for legacy SSE connections. |
authProvider | OAuthClientProvider | HTTP | An OAuth provider for automatic token refresh. |
logger | LogHandler | Both | A handler for per-server logging. |
timeout | number | Both | Server-specific timeout in milliseconds. |
enableServerLogs | boolean | Both | Whether to enable logging for this server (default: true). |
Source: packages/mcp/README.md:368-390
Transports
The client automatically detects which transport to use based on the server configuration.
This diagram shows the transport detection logic:
Client Usage Flow
A typical interaction involves creating a client, connecting, listing resources, and then disconnecting.
Source: packages/mcp/README.md:47-58
Tools vs. Toolsets
The MCPClient offers two methods for accessing tools, catering to different use cases.
| Method | listTools() | listToolsets() |
|---|---|---|
| Description | Returns a flat object of all tools from all configured servers, namespaced to prevent conflicts. | Returns tools grouped into a toolset object for each server. |
| Use Case | Single-user contexts (CLI, scripts) where tool configuration is fixed. Good for initializing an Agent with a static set of tools. | Multi-user environments (web apps, APIs) where tool configuration (e.g., credentials) must be dynamic and per-request. |
| Example | const tools = await mcp.listTools(); | const toolsets = await mcp.listToolsets(); |
Source: packages/mcp/README.md:162-212
MCP Server
An MCP server is a service that exposes tools and resources. The template-docs-chatbot provides a clear example of a standalone MCP server. It is an HTTP/SSE server that exposes a docsTool for querying function documentation.
Key files for a server implementation:
src/server.ts: The main server entry point, where tools are registered.src/tools/: Directory containing tool definitions.src/data/: Location for any data the tools might use, likefunctions.json.
Sources: templates/template-docs-chatbot/apps/mcp-server/README.md:3-9, 53-57
Integration with IDEs and Agents
MCP servers can be integrated into various development environments and Mastra agents to provide contextual tools.
| Environment | Configuration Method |
|---|---|
| Cursor | Create or update .cursor/mcp.json with the server command. |
| Windsurf | Create or update ~/.codeium/windsurf/mcp_config.json. |
| Claude Code | Use the claude mcp add command. |
| Mastra Agent | Instantiate MCPClient within the agent's tools definition. |
Source: packages/mcp-docs-server/README.md:12-81
Future Exploration: MCP Registry
An exploration in the repository, mcp-registry-client, proposes a potential future direction for MCP with the introduction of a RegistryClient. This would allow for programmatic discovery, configuration, and management of MCP servers from a central registry, simplifying the process of finding and using public or private tool servers.
The proposal includes:
- A
RegistryClientto connect to a registry endpoint (e.g.,https://example-tools.com/.well-known/mcp.json). - The ability to list and search for servers.
- A
ServerDefinitionclass for introspection and validation of server configurations.
This would enable more dynamic and user-friendly configuration workflows, such as building UIs for server setup or even providing IDE-level autocompletion for available servers.
Source: explorations/mcp-registry-client/README.md:6-43, 53-78
Summary
The Model Context Protocol (MCP) is a key architectural component in the Mastra framework for enabling AI agents to use external tools in a decoupled and standardized way. The @mastra/mcp package provides a robust client for connecting to any MCP-compliant server, handling multiple transport layers, and managing tool lifecycles. By separating tool logic into independent MCP servers, developers can build modular, reusable, and scalable AI systems.
Sources: README.md:41-43, DEVELOPMENT.md:15, packages/mcp/README.md