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: StdioServerParameters | SSEClientParameters;
capabilities?: ClientCapabilities;
version?: string;
timeout?: number;
})
Parameters
name:
version?:
server:
capabilities?:
timeout?:
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"],
},
});
// 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,
});
},
},
},
});
// 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 MCPConfiguration documentation
- For more details about the Model Context Protocol, see the @modelcontextprotocol/sdk documentation .