MCP 概覽
Mastra 支援 Model Context Protocol (MCP),這是一套用於將 AI Agent 連接至外部 Tool 及資源的開放標準。
使用 MCPClient 連接至 MCP 伺服器。使用 MCPServer 將 Mastra Agent、Tool、Workflow、prompt 及資源公開予其他兼容 MCP 的系統。
連接至 MCP 伺服器連接至 MCP 伺服器 的直接連結
安裝 MCP 套件:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/mcp@latest
pnpm add @mastra/mcp@latest
yarn add @mastra/mcp@latest
bun add @mastra/mcp@latest
使用本機命令或遠端 URL 設定每個伺服器:
import { MCPClient } from '@mastra/mcp'
export const mcpClient = new MCPClient({
id: 'my-mcp-client',
servers: {
wikipedia: {
command: 'npx',
args: ['-y', 'wikipedia-mcp'],
},
weather: {
url: new URL('https://weather.example.com/mcp'),
requestInit: {
headers: {
Authorization: `Bearer ${process.env.WEATHER_API_KEY}`,
},
},
},
},
})
如伺服器受 OAuth 保護,請使用 authenticate() 完成以瀏覽器進行的授權流程。設定詳情請參閱 OAuth 身份驗證。
將已設定伺服器的 Tool 傳遞給 Agent:
import { Agent } from '@mastra/core/agent'
import { mcpClient } from '../mcp/client'
export const assistant = new Agent({
id: 'assistant',
name: 'Assistant',
instructions: `
Use the available MCP tools to answer questions.
Include the source of any information you retrieve.
`,
model: 'openai/gpt-5.6-sol',
tools: await mcpClient.listTools(),
})
靜態及執行階段 Tool靜態及執行階段 Tool 的直接連結
根據伺服器設定會否因應每個請求而改變,選擇載入 Tool 的方式:
| 靜態 Tool | 執行階段 Toolset | |
|---|---|---|
| 方法 | await mcpClient.listTools() | await mcpClient.listToolsets() |
| 使用情境 | 共用的固定設定 | 按用戶或按請求設定 |
| 憑證 | 所有請求共用 | 可因應請求而異 |
| Agent API | tools(位於 Agent constructor) | toolsets(位於 generate() 或 stream()) |
以上 Agent 範例使用靜態 Tool。如需使用執行階段憑證,請為該請求建立 client,並在調用 Agent 時傳入其 Toolset:
import { MCPClient } from '@mastra/mcp'
import { mastra } from './mastra'
export async function handleRequest(prompt: string, apiKey: string) {
const userMcpClient = new MCPClient({
servers: {
weather: {
url: new URL('https://weather.example.com/mcp'),
requestInit: {
headers: { Authorization: `Bearer ${apiKey}` },
},
},
},
})
const agent = mastra.getAgent('assistant')
const response = await agent.generate(prompt, {
toolsets: await userMcpClient.listToolsets(),
})
await userMcpClient.disconnect()
return response.text
}
如需完整 API,請參閱 listTools() 及 listToolsets()。
Tool 審批Tool 審批 的直接連結
在伺服器上設定 requireToolApproval,要求其所有 Tool 均須經過審批:
const mcpClient = new MCPClient({
servers: {
github: {
url: new URL('https://github.example.com/mcp'),
requireToolApproval: true,
},
},
})
你亦可提供一個函數,根據 Tool 名稱、引數或 annotation 作出決定:
requireToolApproval: ({ toolName }) => toolName.startsWith('delete_')
對於來自你無法控制的伺服器的 Tool annotation,應視為不可信的提示。callback context 及安全指引請參閱 Tool 審批。
安全性安全性 的直接連結
MCP 伺服器會代表你的 Agent 執行程式碼並傳回內容,因此設定時應如同處理任何其他外部依賴套件一樣謹慎:
- Stdio 子程序環境:子程序只會繼承 MCP SDK 經篩選的環境變數白名單(例如 POSIX 上的
PATH及HOME),而不會繼承完整的父程序環境。在伺服器上設定inheritDefaultEnv: false,即可只傳遞你在env中列出的變數。 - 限制對外連線的主機:當 HTTP 伺服器 URL 來自不可信的設定時,設定
allowedHosts以限制 client 可連接的主機。在預設 fetch 路徑中,此設定亦會在傳送請求前封鎖重新導向至其他主機;自訂fetch則會在請求執行後驗證最終回應 URL,因此如需防止對外連線,它本身必須強制執行重新導向政策。 - Tool 回應的可信度:Tool 結果是不可信的模型輸入。請使用輸入及輸出 processor 在內容送達模型前檢查或清理內容,並使用
requireToolApproval為敏感 Tool 設置審批關卡。
每個選項的執行詳情請參閱 MCPClient 安全性參考。
MCP registryMCP registry 的直接連結
Registry 提供託管或已封裝的 MCP 伺服器。以上 client 設定可配合 registry endpoint 及命令使用。
| Registry | 連線方式 | 備註 |
|---|---|---|
| Klavis AI | 託管 HTTP | 企業身份驗證及受管理伺服器 |
| mcp.run | 已簽署的 SSE URL | 將 profile URL 視為秘密資料 |
| Composio | 託管 SSE URL | URL 通常綁定至單一用戶帳戶 |
| Smithery | CLI 或託管 URL | 透過 npx 執行本機套件 |
| Apify | 託管 HTTP | 使用 Apify API token 進行身份驗證 |
| Ampersand | SSE 或 stdio | 連接至已設定的 SaaS 整合服務 |
將已簽署的 URL、API 金鑰及 token 儲存在環境變數中。按照 registry 的文件,取得每個伺服器的 endpoint、命令及憑證。
公開 Mastra MCP 伺服器公開 Mastra MCP 伺服器 的直接連結
建立 MCPServer,向外部 MCP client 公開 Mastra primitive:
import { MCPServer } from '@mastra/mcp'
import { assistant } from '../agents/assistant'
import { weatherTool } from '../tools/weather'
import { weatherWorkflow } from '../workflows/weather'
export const mcpServer = new MCPServer({
id: 'my-mcp-server',
name: 'My MCP Server',
version: '1.0.0',
agents: { assistant },
tools: { weatherTool },
workflows: { weatherWorkflow },
})
在主要的 Mastra instance 上註冊伺服器:
import { Mastra } from '@mastra/core/mastra'
import { mcpServer } from './mcp/server'
export const mastra = new Mastra({
mcpServers: { mcpServer },
})
使用 OAuth middleware 保護 HTTP MCP 伺服器。設定指引請參閱 OAuth 保護。
如需了解 prompt、資源、transport 及其他伺服器選項,請參閱 MCPServer 參考。
建立 MCP Apps建立 MCP Apps 的直接連結
MCP Apps extension 讓 MCP Tool 可透過 ui:// 資源提供互動式 HTML 介面。Mastra Studio 會在 Tool 頁面及 Agent 對話中,以 sandbox iframe 顯示這些 app。
當 Tool 結果適合以互動方式呈現時(例如表單、計算機、顏色選擇器或數據視覺化),便可使用 MCP App。
定義 app 資源定義 app 資源 的直接連結
在 content 中傳回供模型使用的簡短摘要,並將 UI 數據放入 structuredContent。將 _meta.ui.resourceUri 設為同一個 ui:// URI(即 appResources 所使用的 URI),從而把 Tool 連結至其 app:
import { MCPServer } from '@mastra/mcp'
import { createTool } from '@mastra/core/tools'
import { z } from 'zod'
export const calculatorTool = createTool({
id: 'calculatorWithUI',
description: 'Calculate the sum of two numbers',
inputSchema: z.object({
num1: z.number(),
num2: z.number(),
}),
execute: async ({ num1, num2 }) => ({
content: [{ type: 'text', text: 'The result is displayed in the calculator app.' }],
structuredContent: { result: num1 + num2 },
}),
})
calculatorTool._meta = {
ui: { resourceUri: 'ui://calculator/main' },
}
export const calculatorMcpServer = new MCPServer({
id: 'calculator-app-server',
name: 'Calculator App Server',
version: '1.0.0',
tools: { calculatorTool },
appResources: {
'ui://calculator/main': {
name: 'Calculator',
htmlPath: './src/mastra/mcp/calculator.html',
},
},
})
模型會看到 content,而 app 則會收到 structuredContent。如需了解 inline HTML、文件路徑、metadata 及內容安全政策選項,請參閱 appResources。
將 app 連接至 Studio將 app 連接至 Studio 的直接連結
在 HTML 資源內使用 App class(來自 @modelcontextprotocol/ext-apps)。請先註冊 event handler,然後才調用 connect():
<!doctype html>
<html>
<body>
<p id="result">Waiting for input</p>
<button id="recalculate">Recalculate</button>
<script type="module">
import { App } from 'https://cdn.jsdelivr.net/npm/@modelcontextprotocol/ext-apps/+esm'
const app = new App({ name: 'Calculator', version: '1.0.0' })
let toolInput
app.ontoolinput = params => {
toolInput = params.arguments
}
document.querySelector('#recalculate').addEventListener('click', async () => {
const result = await app.callServerTool({
name: 'calculatorWithUI',
arguments: toolInput,
})
document.querySelector('#result').textContent = JSON.stringify(result)
await app.sendMessage({
role: 'user',
content: [{ type: 'text', text: 'Explain the recalculated result.' }],
})
})
await app.connect()
</script>
</body>
</html>
Guest 端 API 分別負責互動中的不同部分:
| API | 用途 |
|---|---|
app.ontoolinput | 接收來自 host Tool 調用的引數 |
app.callServerTool() | 從 iframe 內調用 MCP Tool |
app.sendMessage() | 在對話中加入用戶訊息,並開始新的模型 turn |
app.connect() | 註冊 event handler 後連接至 host |
互動流程如下:
- Agent 調用 Tool。
- Tool 傳回面向模型的
content及面向 UI 的structuredContent。 - Studio 顯示相關的 app 資源。
- App 接收 Tool 輸入,並可調用伺服器 Tool 或傳送對話訊息。
如需所有 Guest 端方法及 lifecycle hook,請參閱外部 App API 參考。
註冊 MCP Apps註冊 MCP Apps 的直接連結
如為本機 app,請將 Tool 傳遞給 Agent,並在 Mastra 上註冊其 MCP 伺服器:
import { Agent } from '@mastra/core/agent'
import { Mastra } from '@mastra/core/mastra'
import { calculatorMcpServer, calculatorTool } from './mcp/calculator'
const calculatorAgent = new Agent({
id: 'calculator-agent',
name: 'Calculator Agent',
instructions: 'Use the calculator tool for arithmetic.',
model: 'openai/gpt-5-mini',
tools: { calculatorTool },
})
export const mastra = new Mastra({
agents: { calculatorAgent },
mcpServers: { calculatorMcpServer },
})
如外部 MCP 伺服器實作了 MCP Apps,請使用 MCPClient.listTools() 載入其 Tool,並註冊其 proxy,讓 Studio 可以解析遠端 app 資源:
import { Agent } from '@mastra/core/agent'
import { Mastra } from '@mastra/core/mastra'
import { mcpClient } from './mcp/client'
const tools = await mcpClient.listTools()
const mcpServers = mcpClient.toMCPServerProxies()
const agent = new Agent({
id: 'remote-app-agent',
name: 'Remote App Agent',
instructions: 'Use the available remote tools.',
model: 'openai/gpt-5-mini',
tools,
})
export const mastra = new Mastra({
agents: { agent },
mcpServers,
})
透過 listTools() 載入的 Tool 會包含 serverId(位於 _meta.ui 中),讓 Studio 無需掃描每個伺服器,亦可解析各個 app 資源。proxy 設定詳情請參閱 toMCPServerProxies()。
Sandbox 安全性Sandbox 安全性 的直接連結
Mastra Studio 使用 @mcp-ui/client,透過 sandbox proxy 載入 app HTML,並以 JSON-RPC 配合 postMessage 通訊。
App iframe 允許 script、表單及彈出式視窗。它們無法存取父頁面的 DOM、cookie 或儲存空間。Host 控制與 Guest app 之間的所有通訊。