> Discover all available pages from the documentation index: https://mastra.zisheng.pro/zh-HK/llms.txt # MCP 概覽 Mastra 支援 [Model Context Protocol (MCP)](https://modelcontextprotocol.io/introduction),這是一套用於將 AI Agent 連接至外部 Tool 及資源的開放標準。 使用 [`MCPClient`](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-client) 連接至 MCP 伺服器。使用 [`MCPServer`](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-server) 將 Mastra Agent、Tool、Workflow、prompt 及資源公開予其他兼容 MCP 的系統。 ## 連接至 MCP 伺服器 安裝 MCP 套件: **npm**: ```bash npm install @mastra/mcp@latest ``` **pnpm**: ```bash pnpm add @mastra/mcp@latest ``` **Yarn**: ```bash yarn add @mastra/mcp@latest ``` **Bun**: ```bash bun add @mastra/mcp@latest ``` 使用本機命令或遠端 URL 設定每個伺服器: ```typescript 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 身份驗證](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-client)。 將已設定伺服器的 Tool 傳遞給 Agent: ```typescript 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 | 執行階段 Toolset | | --------- | ------------------------------- | ---------------------------------------- | | 方法 | `await mcpClient.listTools()` | `await mcpClient.listToolsets()` | | 使用情境 | 共用的固定設定 | 按用戶或按請求設定 | | 憑證 | 所有請求共用 | 可因應請求而異 | | Agent API | `tools`(位於 `Agent` constructor) | `toolsets`(位於 `generate()` 或 `stream()`) | 以上 Agent 範例使用靜態 Tool。如需使用執行階段憑證,請為該請求建立 client,並在調用 Agent 時傳入其 Toolset: ```typescript 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()`](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-client) 及 [`listToolsets()`](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-client)。 ### Tool 審批 在伺服器上設定 `requireToolApproval`,要求其所有 Tool 均須經過審批: ```typescript const mcpClient = new MCPClient({ servers: { github: { url: new URL('https://github.example.com/mcp'), requireToolApproval: true, }, }, }) ``` 你亦可提供一個函數,根據 Tool 名稱、引數或 annotation 作出決定: ```typescript requireToolApproval: ({ toolName }) => toolName.startsWith('delete_') ``` 對於來自你無法控制的伺服器的 Tool annotation,應視為不可信的提示。callback context 及安全指引請參閱 [Tool 審批](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-client)。 ### 安全性 MCP 伺服器會代表你的 Agent 執行程式碼並傳回內容,因此設定時應如同處理任何其他外部依賴套件一樣謹慎: - **Stdio 子程序環境**:子程序只會繼承 MCP SDK 經篩選的環境變數白名單(例如 POSIX 上的 `PATH` 及 `HOME`),而不會繼承完整的父程序環境。在伺服器上設定 `inheritDefaultEnv: false`,即可只傳遞你在 `env` 中列出的變數。 - **限制對外連線的主機**:當 HTTP 伺服器 URL 來自不可信的設定時,設定 `allowedHosts` 以限制 client 可連接的主機。在預設 fetch 路徑中,此設定亦會在傳送請求前封鎖重新導向至其他主機;自訂 `fetch` 則會在請求執行後驗證最終回應 URL,因此如需防止對外連線,它本身必須強制執行重新導向政策。 - **Tool 回應的可信度**:Tool 結果是不可信的模型輸入。請使用[輸入及輸出 processor](https://mastra.zisheng.pro/zh-HK/docs/agents/processors) 在內容送達模型前檢查或清理內容,並使用 `requireToolApproval` 為敏感 Tool 設置審批關卡。 每個選項的執行詳情請參閱 [MCPClient 安全性參考](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-client)。 ### MCP registry Registry 提供託管或已封裝的 MCP 伺服器。以上 client 設定可配合 registry endpoint 及命令使用。 | Registry | 連線方式 | 備註 | | ----------------------------------------------- | ------------ | ------------------------- | | [Klavis AI](https://klavis.ai) | 託管 HTTP | 企業身份驗證及受管理伺服器 | | [mcp.run](https://www.mcp.run/) | 已簽署的 SSE URL | 將 profile URL 視為秘密資料 | | [Composio](https://mcp.composio.dev) | 託管 SSE URL | URL 通常綁定至單一用戶帳戶 | | [Smithery](https://smithery.ai) | CLI 或託管 URL | 透過 `npx` 執行本機套件 | | [Apify](https://mcp.apify.com) | 託管 HTTP | 使用 Apify API token 進行身份驗證 | | [Ampersand](https://docs.withampersand.com/mcp) | SSE 或 stdio | 連接至已設定的 SaaS 整合服務 | 將已簽署的 URL、API 金鑰及 token 儲存在環境變數中。按照 registry 的文件,取得每個伺服器的 endpoint、命令及憑證。 ## 公開 Mastra MCP 伺服器 建立 `MCPServer`,向外部 MCP client 公開 Mastra primitive: ```typescript 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 上註冊伺服器: ```typescript import { Mastra } from '@mastra/core/mastra' import { mcpServer } from './mcp/server' export const mastra = new Mastra({ mcpServers: { mcpServer }, }) ``` > **身份驗證:** 使用 OAuth middleware 保護 HTTP MCP 伺服器。設定指引請參閱 [OAuth 保護](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-server)。 如需了解 prompt、資源、transport 及其他伺服器選項,請參閱 [`MCPServer` 參考](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-server)。 ## 建立 MCP Apps [MCP Apps extension](https://github.com/modelcontextprotocol/ext-apps) 讓 MCP Tool 可透過 `ui://` 資源提供互動式 HTML 介面。Mastra Studio 會在 Tool 頁面及 Agent 對話中,以 sandbox iframe 顯示這些 app。 當 Tool 結果適合以互動方式呈現時(例如表單、計算機、顏色選擇器或數據視覺化),便可使用 MCP App。 ### 定義 app 資源 在 `content` 中傳回供模型使用的簡短摘要,並將 UI 數據放入 `structuredContent`。將 `_meta.ui.resourceUri` 設為同一個 `ui://` URI(即 `appResources` 所使用的 URI),從而把 Tool 連結至其 app: ```typescript 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`](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-server)。 ### 將 app 連接至 Studio 在 HTML 資源內使用 `App` class(來自 `@modelcontextprotocol/ext-apps`)。請先註冊 event handler,然後才調用 `connect()`: ```html
Waiting for input
``` Guest 端 API 分別負責互動中的不同部分: | API | 用途 | | ---------------------- | -------------------------- | | `app.ontoolinput` | 接收來自 host Tool 調用的引數 | | `app.callServerTool()` | 從 iframe 內調用 MCP Tool | | `app.sendMessage()` | 在對話中加入用戶訊息,並開始新的模型 turn | | `app.connect()` | 註冊 event handler 後連接至 host | 互動流程如下: 1. Agent 調用 Tool。 2. Tool 傳回面向模型的 `content` 及面向 UI 的 `structuredContent`。 3. Studio 顯示相關的 app 資源。 4. App 接收 Tool 輸入,並可調用伺服器 Tool 或傳送對話訊息。 如需所有 Guest 端方法及 lifecycle hook,請參閱外部 [`App` API 參考](https://apps.extensions.modelcontextprotocol.io/api/classes/app.App.html)。 ### 註冊 MCP Apps 如為本機 app,請將 Tool 傳遞給 Agent,並在 `Mastra` 上註冊其 MCP 伺服器: ```typescript 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 資源: ```typescript 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()`](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-client)。 ### Sandbox 安全性 Mastra Studio 使用 [`@mcp-ui/client`](https://www.npmjs.com/package/@mcp-ui/client),透過 sandbox proxy 載入 app HTML,並以 JSON-RPC 配合 `postMessage` 通訊。 App iframe 允許 script、表單及彈出式視窗。它們無法存取父頁面的 DOM、cookie 或儲存空間。Host 控制與 Guest app 之間的所有通訊。 ## 下一步 - [配合 Agent 使用 Tool](https://mastra.zisheng.pro/zh-HK/docs/agents/using-tools) - [`MCPClient` 參考](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-client) - [`MCPServer` 參考](https://mastra.zisheng.pro/zh-HK/reference/tools/mcp-server) - [MCP Apps extension 規格](https://github.com/modelcontextprotocol/ext-apps)