---
title: "Reference: MastraMCPClient (Deprecated) | Tools & MCP"
description: API Reference for MastraMCPClient - A client implementation for the Model Context Protocol.
packages:
  - "@mastra/core"
  - "@mastra/mcp"
---

# 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`](./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

<br />
<PropertiesTable
  content={[
    {
      name: "name",
      type: "string",
      description: "The name identifier for this client instance.",
    },
    {
      name: "version",
      type: "string",
      isOptional: true,
      defaultValue: "1.0.0",
      description: "The version of the client.",
    },
    {
      name: "server",
      type: "MastraMCPServerDefinition",
      description:
        "Configuration parameters for either a stdio server connection or an SSE server connection. Can include log handler and server logs configuration.",
    },
    {
      name: "capabilities",
      type: "ClientCapabilities",
      isOptional: true,
      defaultValue: "{}",
      description: "Optional capabilities configuration for the client.",
    },
    {
      name: "timeout",
      type: "number",
      isOptional: true,
      defaultValue: 60000,
      description:
        "The timeout duration, in milliseconds, for client tool calls.",
    },
  ]}
/>

### 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.

<br />
<PropertiesTable
  content={[
    {
      name: "command",
      type: "string",
      isOptional: true,
      description: "For Stdio servers: The command to execute.",
    },
    {
      name: "args",
      type: "string[]",
      isOptional: true,
      description: "For Stdio servers: Arguments to pass to the command.",
    },
    {
      name: "env",
      type: "Record<string, string>",
      isOptional: true,
      description:
        "For Stdio servers: Environment variables to set for the command.",
    },
    {
      name: "url",
      type: "URL",
      isOptional: true,
      description:
        "For HTTP servers (Streamable HTTP or SSE): The URL of the server.",
    },
    {
      name: "requestInit",
      type: "RequestInit",
      isOptional: true,
      description: "For HTTP servers: Request configuration for the fetch API.",
    },
    {
      name: "eventSourceInit",
      type: "EventSourceInit",
      isOptional: true,
      description:
        "For SSE fallback: Custom fetch configuration for SSE connections. Required when using custom headers with SSE.",
    },
    {
      name: "logger",
      type: "LogHandler",
      isOptional: true,
      description: "Optional additional handler for logging.",
    },
    {
      name: "timeout",
      type: "number",
      isOptional: true,
      description: "Server-specific timeout in milliseconds.",
    },
    {
      name: "capabilities",
      type: "ClientCapabilities",
      isOptional: true,
      description: "Server-specific capabilities configuration.",
    },
    {
      name: "enableServerLogs",
      type: "boolean",
      isOptional: true,
      defaultValue: "true",
      description: "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`.

<br />
<PropertiesTable
  content={[
    {
      name: "level",
      type: "LoggingLevel",
      description: "Log level (debug, info, warn, error)",
    },
    {
      name: "message",
      type: "string",
      description: "Log message content",
    },
    {
      name: "timestamp",
      type: "Date",
      description: "When the log was generated",
    },
    {
      name: "serverName",
      type: "string",
      description: "Name of the server that generated the log",
    },
    {
      name: "details",
      type: "Record<string, any>",
      isOptional: true,
      description: "Optional additional log details",
    },
  ]}
/>

## Methods

### connect()

Establishes a connection with the MCP server.

```typescript
async connect(): Promise<void>
```

### disconnect()

Closes the connection with the MCP server.

```typescript
async disconnect(): Promise<void>
```

### resources()

Retrieves the list of available resources from the server.

```typescript
async resources(): Promise<ListResourcesResult>
```

### tools()

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

```typescript
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

```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](./mcp-client)
- For more details about the Model Context Protocol, see the [@modelcontextprotocol/sdk documentation](https://github.com/modelcontextprotocol/typescript-sdk).
