Skip to main content

MCP 概览

🌐 MCP Overview

Mastra 支持 模型上下文协议 (MCP),这是一种用于将 AI 代理连接到外部工具和资源的开放标准。它作为一个通用插件系统,使代理能够调用工具,而不受语言或托管环境的限制。

🌐 Mastra supports the Model Context Protocol (MCP), an open standard for connecting AI agents to external tools and resources. It serves as a universal plugin system, enabling agents to call tools regardless of language or hosting environment.

Mastra 也可以用来创建 MCP 服务器,通过 MCP 接口公开代理、工具和其他结构化资源。然后,任何支持该协议的系统或代理都可以访问这些资源。

🌐 Mastra can also be used to author MCP servers, exposing agents, tools, and other structured resources via the MCP interface. These can then be accessed by any system or agent that supports the protocol.

Mastra 当前支持两种 MCP 类别:

🌐 Mastra currently supports two MCP classes:

  1. MCPClient:连接到一个或多个 MCP 服务器以访问它们的工具、资源、提示,并处理引导请求。
  2. MCPServer:向与MCP兼容的客户端公开Mastra工具、代理、工作流程、提示和资源。

入门
Direct link to 入门

🌐 Getting started

要使用 MCP,请安装所需的依赖:

🌐 To use MCP, install the required dependency:

npm install @mastra/mcp@latest

配置 MCPClient
Direct link to configuring-mcpclient

🌐 Configuring MCPClient

MCPClient 将 Mastra 原语连接到外部 MCP 服务器,这些服务器可以是本地包(使用 npx 调用)或远程 HTTP(S) 端点。每个服务器都必须根据其托管方式配置 commandurl

🌐 The MCPClient connects Mastra primitives to external MCP servers, which can be local packages (invoked using npx) or remote HTTP(S) endpoints. Each server must be configured with either a command or a url, depending on how it's hosted.

src/mastra/mcp/test-mcp-client.ts
import { MCPClient } from "@mastra/mcp";

export const testMcpClient = new MCPClient({
id: "test-mcp-client",
servers: {
wikipedia: {
command: "npx",
args: ["-y", "wikipedia-mcp"],
},
weather: {
url: new URL(
`https://server.smithery.ai/@smithery-ai/national-weather-service/mcp?api_key=${process.env.SMITHERY_API_KEY}`,
),
},
},
});
info

访问 MCPClient 查看完整的配置选项列表。

🌐 Visit MCPClient for a full list of configuration options.

验证

有关连接到受 OAuth 保护的 MCP 服务器,请参阅 OAuth 身份验证 部分。

🌐 For connecting to OAuth-protected MCP servers, see the OAuth Authentication section.

MCPClient 与代理一起使用
Direct link to using-mcpclient-with-an-agent

🌐 Using MCPClient with an agent

要在代理中使用来自 MCP 服务器的工具,请导入你的 MCPClient 并在 tools 参数中调用 .listTools()。这会从已定义的 MCP 服务器加载,使它们可供代理使用。

🌐 To use tools from an MCP server in an agent, import your MCPClient and call .listTools() in the tools parameter. This loads from the defined MCP servers, making them available to the agent.

src/mastra/agents/test-agent.ts
import { Agent } from "@mastra/core/agent";
import { testMcpClient } from "../mcp/test-mcp-client";

export const testAgent = new Agent({
id: "test-agent",
name: "Test Agent",
description: "You are a helpful AI assistant",
instructions: `
You are a helpful assistant that has access to the following MCP Servers.
- Wikipedia MCP Server
- US National Weather Service

Answer questions using the information you find using the MCP Servers.`,
model: "openai/gpt-5.1",
tools: await testMcpClient.listTools(),
});
info

请访问 Agent Class 查看完整的配置选项列表。

🌐 Visit Agent Class for a full list of configuration options.

配置 MCPServer
Direct link to configuring-mcpserver

🌐 Configuring MCPServer

要将 Mastra 应用中的代理、工具和工作流通过 HTTP(S) 暴露给外部系统,请使用 MCPServer 类。这使得任何支持该协议的系统或代理都可以访问它们。

🌐 To expose agents, tools, and workflows from your Mastra application to external systems over HTTP(S) use the MCPServer class. This makes them accessible to any system or agent that supports the protocol.

src/mastra/mcp/test-mcp-server.ts
import { MCPServer } from "@mastra/mcp";

import { testAgent } from "../agents/test-agent";
import { testWorkflow } from "../workflows/test-workflow";
import { testTool } from "../tools/test-tool";

export const testMcpServer = new MCPServer({
id: "test-mcp-server",
name: "Test Server",
version: "1.0.0",
agents: { testAgent },
tools: { testTool },
workflows: { testWorkflow },
});
info

访问 MCPServer 查看完整的配置选项列表。

🌐 Visit MCPServer for a full list of configuration options.

验证

要使用 OAuth 保护你的 MCP 服务器,请参阅 OAuth 保护 部分。

🌐 To protect your MCP server with OAuth, see the OAuth Protection section.

注册 MCPServer
Direct link to registering-an-mcpserver

🌐 Registering an MCPServer

要使 MCP 服务器对其他支持该协议的系统或代理可用,请使用 mcpServers 在主 Mastra 实例中注册它。

🌐 To make an MCP server available to other systems or agents that support the protocol, register it in the main Mastra instance using mcpServers.

src/mastra/index.ts
import { Mastra } from "@mastra/core/mastra";

import { testMcpServer } from "./mcp/test-mcp-server";

export const mastra = new Mastra({
mcpServers: { testMcpServer },
});

静态工具和动态工具
Direct link to 静态工具和动态工具

🌐 Static and dynamic tools

MCPClient 提供两种从连接的服务器获取工具的方法,适用于不同的应用架构:

功能静态配置 (await mcp.listTools())动态配置 (await mcp.listToolsets())
使用场景单用户,静态配置(例如 CLI 工具)多用户,动态配置(例如 SaaS 应用)
配置方式在代理初始化时固定每次请求动态设置
凭证所有使用共享可根据用户/请求变化
代理设置工具在 Agent 构造函数中添加工具通过 .generate().stream() 选项传入

静态工具
Direct link to 静态工具

🌐 Static tools

使用 .listTools() 方法从所有配置的 MCP 服务器获取工具。当配置(例如 API 密钥)在用户或请求之间是静态且一致时,这种方法非常适用。调用一次后,将结果传递给定义代理时的 tools 属性。

🌐 Use the .listTools() method to fetch tools from all configured MCP servers. This is suitable when configuration (such as API keys) is static and consistent across users or requests. Call it once and pass the result to the tools property when defining your agent.

info

访问 listTools() 以获取更多信息。

🌐 Visit listTools() for more information.

src/mastra/agents/test-agent.ts
import { Agent } from "@mastra/core/agent";

import { testMcpClient } from "../mcp/test-mcp-client";

export const testAgent = new Agent({
id: "test-agent",
tools: await testMcpClient.listTools(),
});

动态工具
Direct link to 动态工具

🌐 Dynamic tools

当工具配置可能因请求或用户而异时(例如在每个用户提供自己 API 密钥的多租户系统中),请使用 .listToolsets() 方法。此方法返回的工具集可传递给代理的 .generate().stream() 调用中的 toolsets 选项。

🌐 Use the .listToolsets() method when tool configuration may vary by request or user, such as in a multi-tenant system where each user provides their own API key. This method returns toolsets that can be passed to the toolsets option in the agent's .generate() or .stream() calls.

import { MCPClient } from "@mastra/mcp";
import { mastra } from "./mastra";

async function handleRequest(userPrompt: string, userApiKey: string) {
const userMcp = new MCPClient({
servers: {
weather: {
url: new URL("http://localhost:8080/mcp"),
requestInit: {
headers: {
Authorization: `Bearer ${userApiKey}`,
},
},
},
},
});

const agent = mastra.getAgent("testAgent");

const response = await agent.generate(userPrompt, {
toolsets: await userMcp.listToolsets(),
});

await userMcp.disconnect();

return Response.json({
data: response.text,
});
}
info

访问 listToolsets() 获取更多信息。

🌐 Visit listToolsets() for more information.

正在连接到MCP注册表
Direct link to 正在连接到MCP注册表

🌐 Connecting to an MCP registry

可以通过注册表发现 MCP 服务器。以下是如何使用 MCPClient 连接到一些流行的服务器的方法:

🌐 MCP servers can be discovered through registries. Here's how to connect to some popular ones using MCPClient:

Klavis AI 提供托管的、企业认证的、高质量 MCP 服务器。

import { MCPClient } from "@mastra/mcp";

const mcp = new MCPClient({
servers: {
salesforce: {
url: new URL("https://salesforce-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}"),
},
hubspot: {
url: new URL("https://hubspot-mcp-server.klavis.ai/mcp/?instance_id={private-instance-id}"),
},
},
});

Klavis AI 为生产部署提供企业级身份验证和安全性。

有关如何将 Mastra 与 Klavis 集成的更多详细信息,请查看他们的文档

🌐 Related