MCPConfiguration
The MCPConfiguration
class provides a way to manage multiple MCP server connections and their tools in a Mastra application. It handles connection lifecycle, tool namespacing, and provides convenient access to tools across all configured servers.
Constructor
Creates a new instance of the MCPConfiguration class.
constructor({
id?: string;
servers: Record<string, MastraMCPServerDefinition>
}: {
servers: {
[serverName: string]: {
// For stdio-based servers
command?: string;
args?: string[];
env?: Record<string, string>;
// For SSE-based servers
url?: URL;
requestInit?: RequestInit;
}
}
})
Parameters
id:
servers:
Methods
getTools()
Retrieves all tools from all configured servers, with tool names namespaced by their server name (in the format serverName_toolName
) to prevent conflicts.
Intended to be passed onto an Agent definition.
new Agent({ tools: await mcp.getTools() });
getToolsets()
Returns an object mapping namespaced tool names (in the format serverName.toolName
) to their tool implementations.
Intended to be passed dynamically into the generate or stream method.
const res = await agent.stream(prompt, {
toolsets: await mcp.getToolsets(),
});
Examples
Basic Usage
import { MCPConfiguration } from "@mastra/mcp";
import { Agent } from "@mastra/core/agent";
import { openai } from "@ai-sdk/openai";
const mcp = new MCPConfiguration({
servers: {
stockPrice: {
command: "npx",
args: ["tsx", "stock-price.ts"],
env: {
API_KEY: "your-api-key",
},
},
weather: {
url: new URL("http://localhost:8080/sse"),
},
},
});
// Create an agent with access to all tools
const agent = new Agent({
name: "Multi-tool Agent",
instructions: "You have access to multiple tool servers.",
model: openai("gpt-4"),
tools: await mcp.getTools(),
});
Using Toolsets in generate() or stream()
import { Agent } from "@mastra/core/agent";
import { MCPConfiguration } from "@mastra/mcp";
import { openai } from "@ai-sdk/openai";
// Create the agent first, without any tools
const agent = new Agent({
name: "Multi-tool Agent",
instructions: "You help users check stocks and weather.",
model: openai("gpt-4"),
});
// Later, configure MCP with user-specific settings
const mcp = new MCPConfiguration({
servers: {
stockPrice: {
command: "npx",
args: ["tsx", "stock-price.ts"],
env: {
API_KEY: "user-123-api-key",
},
},
weather: {
url: new URL("http://localhost:8080/sse"),
requestInit: {
headers: {
Authorization: `Bearer user-123-token`,
},
},
},
},
});
// Pass all toolsets to stream() or generate()
const response = await agent.stream(
"How is AAPL doing and what is the weather?",
{
toolsets: await mcp.getToolsets(),
},
);
Resource Management
The MCPConfiguration
class includes built-in memory leak prevention for managing multiple instances:
- Creating multiple instances with identical configurations without an
id
will throw an error to prevent memory leaks - If you need multiple instances with identical configurations, provide a unique
id
for each instance - Call
await configuration.disconnect()
before recreating an instance with the same configuration - If you only need one instance, consider moving the configuration to a higher scope to avoid recreation
For example, if you try to create multiple instances with the same configuration without an id
:
// First instance - OK
const mcp1 = new MCPConfiguration({
servers: {
/* ... */
},
});
// Second instance with same config - Will throw an error
const mcp2 = new MCPConfiguration({
servers: {
/* ... */
},
});
// To fix, either:
// 1. Add unique IDs
const mcp3 = new MCPConfiguration({
id: "instance-1",
servers: {
/* ... */
},
});
// 2. Or disconnect before recreating
await mcp1.disconnect();
const mcp4 = new MCPConfiguration({
servers: {
/* ... */
},
});
Server Lifecycle
MCPConfiguration handles server connections gracefully:
- Automatic connection management for multiple servers
- Graceful server shutdown to prevent error messages during development
- Proper cleanup of resources when disconnecting
Related Information
- For details about individual MCP client configuration, see the MastraMCPClient documentation
- For more about the Model Context Protocol, see the @modelcontextprotocol/sdk documentation