# MastraMCPClient (Deprecated) 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. ## Deprecation notice `MastraMCPClient` is being deprecated in favour of [`MCPClient`](https://mastra.ai/reference/tools/mcp-client). Rather than having two different interfaces for managing a single MCP server vs multiple MCP servers, we opted to recommend using the interface to manage multiple even when using a single MCP server. ## Constructor Creates a new instance of the MastraMCPClient. ```typescript 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`): The version of the client. (Default: `1.0.0`) **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. (Default: `{}`) **timeout?:** (`number`): The timeout duration, in milliseconds, for client tool calls. (Default: `60000`) ### MastraMCPServerDefinition MCP servers can be configured using this definition. The client automatically detects the transport type based on the provided parameters: - If `command` is provided, it uses the Stdio transport. - If `url` is provided, it first attempts to use the Streamable HTTP transport and falls back to the legacy SSE transport if the initial connection fails. **command?:** (`string`): For Stdio servers: The command to execute. **args?:** (`string[]`): For Stdio servers: Arguments to pass to the command. **env?:** (`Record`): For Stdio servers: Environment variables to set for the command. **url?:** (`URL`): For HTTP servers (Streamable HTTP or SSE): The URL of the server. **requestInit?:** (`RequestInit`): For HTTP servers: Request configuration for the fetch API. **eventSourceInit?:** (`EventSourceInit`): For SSE fallback: Custom fetch configuration for SSE connections. Required when using custom headers with SSE. **logger?:** (`LogHandler`): Optional additional handler for logging. **timeout?:** (`number`): Server-specific timeout in milliseconds. **capabilities?:** (`ClientCapabilities`): Server-specific capabilities configuration. **enableServerLogs?:** (`boolean`): Whether to enable logging for this server. (Default: `true`) ### 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`): Optional additional log details ## Methods ### connect() Establishes a connection with the MCP server. ```typescript async connect(): Promise ``` ### disconnect() Closes the connection with the MCP server. ```typescript async disconnect(): Promise ``` ### resources() Retrieves the list of available resources from the server. ```typescript async resources(): Promise ``` ### tools() Fetches and initializes available tools from the server, converting them into Mastra-compatible tool formats. ```typescript async tools(): Promise> ``` Returns an object mapping tool names to their corresponding Mastra tool implementations. ## Examples ### Using with Mastra Agent #### Example with Stdio Server ```typescript import { Agent } from "@mastra/core/agent"; import { MastraMCPClient } from "@mastra/mcp"; // 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-5.1", }); 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 ```typescript // 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. ## Related Information - For managing multiple MCP servers in your application, see the [MCPClient documentation](https://mastra.ai/reference/tools/mcp-client) - For more details about the Model Context Protocol, see the [@modelcontextprotocol/sdk documentation](https://github.com/modelcontextprotocol/typescript-sdk).