Skip to Content
ReferenceToolsMastraMCPClient

MastraMCPClient

The MastraMCPClient class provides a client implementation for interacting with Model Context Protocol (MCP) servers. It handles connection management, resource discovery, and tool execution through the MCP protocol.

Constructor

Creates a new instance of the MastraMCPClient.

constructor({ name, version = '1.0.0', server, capabilities = {}, timeout = 60000, }: { name: string; server: MastraMCPServerDefinition; capabilities?: ClientCapabilities; version?: string; timeout?: number; })

Parameters


name:

string
The name identifier for this client instance.

version?:

string
= 1.0.0
The version of the client.

server:

MastraMCPServerDefinition
Configuration parameters for either a stdio server connection or an SSE server connection. Can include log handler and server logs configuration.

capabilities?:

ClientCapabilities
= {}
Optional capabilities configuration for the client.

timeout?:

number
= 60000
The timeout duration, in milliseconds, for client tool calls.

MastraMCPServerDefinition

MCP servers can be configured as either stdio-based or SSE-based servers. The configuration includes both server-specific settings and common options:


command?:

string
For stdio servers: The command to execute.

args?:

string[]
For stdio servers: Arguments to pass to the command.

env?:

Record<string, string>
For stdio servers: Environment variables to set for the command.

url?:

URL
For SSE servers: The URL of the server.

requestInit?:

RequestInit
For SSE servers: Request configuration for the fetch API.

eventSourceInit?:

EventSourceInit
For SSE servers: Custom fetch configuration for SSE connections. Required when using custom headers.

logger?:

LogHandler
Optional additional handler for logging.

timeout?:

number
Server-specific timeout in milliseconds.

capabilities?:

ClientCapabilities
Server-specific capabilities configuration.

enableServerLogs?:

boolean
= true
Whether to enable logging for this server.

LogHandler

The LogHandler function takes a LogMessage object as its parameter and returns void. The LogMessage object has the following properties. The LoggingLevel type is a string enum with values: debug, info, warn, and error.


level:

LoggingLevel
Log level (debug, info, warn, error)

message:

string
Log message content

timestamp:

Date
When the log was generated

serverName:

string
Name of the server that generated the log

details?:

Record<string, any>
Optional additional log details

Methods

connect()

Establishes a connection with the MCP server.

async connect(): Promise<void>

disconnect()

Closes the connection with the MCP server.

async disconnect(): Promise<void>

resources()

Retrieves the list of available resources from the server.

async resources(): Promise<ListResourcesResult>

tools()

Fetches and initializes available tools from the server, converting them into Mastra-compatible tool formats.

async tools(): Promise<Record<string, Tool>>

Returns an object mapping tool names to their corresponding Mastra tool implementations.

Examples

Using with Mastra Agent

Example with Stdio Server

import { Agent } from "@mastra/core/agent"; import { MastraMCPClient } from "@mastra/mcp"; import { openai } from "@ai-sdk/openai"; // Initialize the MCP client using mcp/fetch as an example https://hub.docker.com/r/mcp/fetch // Visit https://github.com/docker/mcp-servers for other reference docker mcp servers const fetchClient = new MastraMCPClient({ name: "fetch", server: { command: "docker", args: ["run", "-i", "--rm", "mcp/fetch"], logger: (logMessage) => { console.log(`[${logMessage.level}] ${logMessage.message}`); }, }, }); // Create a Mastra Agent const agent = new Agent({ name: "Fetch agent", instructions: "You are able to fetch data from URLs on demand and discuss the response data with the user.", model: openai("gpt-4o-mini"), }); try { // Connect to the MCP server await fetchClient.connect(); // Gracefully handle process exits so the docker subprocess is cleaned up process.on("exit", () => { fetchClient.disconnect(); }); // Get available tools const tools = await fetchClient.tools(); // Use the agent with the MCP tools const response = await agent.generate( "Tell me about mastra.ai/docs. Tell me generally what this page is and the content it includes.", { toolsets: { fetch: tools, }, }, ); console.log("\n\n" + response.text); } catch (error) { console.error("Error:", error); } finally { // Always disconnect when done await fetchClient.disconnect(); }

Example with SSE Server

// Initialize the MCP client using an SSE server const sseClient = new MastraMCPClient({ name: "sse-client", server: { url: new URL("https://your-mcp-server.com/sse"), // Optional fetch request configuration - Note: requestInit alone isn't enough for SSE requestInit: { headers: { Authorization: "Bearer your-token", }, }, // Required for SSE connections with custom headers eventSourceInit: { fetch(input: Request | URL | string, init?: RequestInit) { const headers = new Headers(init?.headers || {}); headers.set('Authorization', 'Bearer your-token'); return fetch(input, { ...init, headers, }); }, }, // Optional additional logging configuration logger: (logMessage) => { console.log(`[${logMessage.level}] ${logMessage.serverName}: ${logMessage.message}`); }, // Disable server logs enableServerLogs: false }, }); // The rest of the usage is identical to the stdio example

Important Note About SSE Authentication

When using SSE connections with authentication or custom headers, you need to configure both requestInit and eventSourceInit. This is because SSE connections use the browser’s EventSource API, which doesn’t support custom headers directly.

The eventSourceInit configuration allows you to customize the underlying fetch request used for the SSE connection, ensuring your authentication headers are properly included. Without eventSourceInit, authentication headers specified in requestInit won’t be included in the connection request, leading to 401 Unauthorized errors.