Skip to main content

MastraMCP客户端(已弃用)

🌐 MastraMCPClient (Deprecated)

MastraMCPClient 类提供了一个客户端实现,用于与模型上下文协议(MCP)服务器交互。它通过 MCP 协议处理连接管理、资源发现和工具执行。

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

不推荐使用通知
Direct link to 不推荐使用通知

🌐 Deprecation notice

MastraMCPClient 正在被弃用,转而推荐使用 MCPClient。与其为管理单个 MCP 服务器和多个 MCP 服务器提供两个不同的接口,我们选择建议即使在使用单个 MCP 服务器时,也使用用于管理多个服务器的接口。

构造函数
Direct link to 构造函数

🌐 Constructor

创建一个新的 MastraMCPClient 实例。

🌐 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;
})

参数
Direct link to 参数

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

MastraMCP服务器定义
Direct link to MastraMCP服务器定义

🌐 MastraMCPServerDefinition

可以使用此定义配置 MCP 服务器。客户端会根据提供的参数自动检测传输类型:

🌐 MCP servers can be configured using this definition. The client automatically detects the transport type based on the provided parameters:

  • 如果提供 command,它将使用 Stdio 传输。
  • 如果提供了 url,它会先尝试使用可流式 HTTP 传输,如果初始连接失败,则回退到传统的 SSE 传输。

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 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
= true
Whether to enable logging for this server.

LogHandler
Direct link to LogHandler

LogHandler 函数以 LogMessage 对象作为其参数,并返回 void。LogMessage 对象具有以下属性。LoggingLevel 类型是一个字符串枚举,包含以下值:debuginfowarnerror

🌐 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

方法
Direct link to 方法

🌐 Methods

connect()
Direct link to connect()

与 MCP 服务器建立连接。

🌐 Establishes a connection with the MCP server.

async connect(): Promise<void>

disconnect()
Direct link to disconnect()

关闭与 MCP 服务器的连接。

🌐 Closes the connection with the MCP server.

async disconnect(): Promise<void>

resources()
Direct link to resources()

从服务器获取可用资源的列表。

🌐 Retrieves the list of available resources from the server.

async resources(): Promise<ListResourcesResult>

tools()
Direct link to tools()

从服务器获取并初始化可用工具,将其转换为与Mastra兼容的工具格式。

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

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

返回一个对象,将工具名称映射到其对应的Mastra工具实现。

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

示例
Direct link to 示例

🌐 Examples

与 Mastra 代理一起使用
Direct link to 与 Mastra 代理一起使用

🌐 Using with Mastra Agent

带有标准输入输出服务器的示例
Direct link to 带有标准输入输出服务器的示例

🌐 Example with Stdio Server

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();
}

带 SSE 服务器的示例
Direct link to 带 SSE 服务器的示例

🌐 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

关于 SSE 认证的重要说明
Direct link to 关于 SSE 认证的重要说明

🌐 Important Note About SSE Authentication

在使用带有身份验证或自定义头的 SSE 连接时,你需要同时配置 requestIniteventSourceInit。这是因为 SSE 连接使用浏览器的 EventSource API,而该 API 不直接支持自定义头。

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

eventSourceInit 配置允许你自定义用于 SSE 连接的底层 fetch 请求,确保你的身份验证头被正确包含。 如果没有 eventSourceInit,在 requestInit 中指定的身份验证头将不会包含在连接请求中,从而导致 401 未经授权错误。

🌐 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