跳至主要內容

發佈 MCP 伺服器

本範例會引導你使用 stdio 傳輸方式設定基本的 Mastra MCPServer、進行建置,並準備將其發佈至 NPM。

安裝依賴套件
安裝依賴套件 的直接連結

安裝所需套件:

npm install @mastra/mcp @mastra/core tsup

設定 MCP 伺服器
設定 MCP 伺服器 的直接連結

  1. 為你的 stdio 伺服器建立檔案,例如 src/mastra/stdio.ts

  2. 將以下程式碼加入檔案。請記得匯入你實際使用的 Mastra Tool,並為伺服器設定合適的名稱。

    src/mastra/stdio.ts
    #!/usr/bin/env node
    import { MCPServer } from '@mastra/mcp'
    import { weatherTool } from './tools'

    const server = new MCPServer({
    name: 'my-mcp-server',
    version: '1.0.0',
    tools: { weatherTool },
    })

    server.startStdio().catch(error => {
    console.error('Error running MCP server:', error)
    process.exit(1)
    })
  3. 更新你的 package.json,加入指向已建置伺服器檔案的 bin 項目,以及以 ESM 和 CJS 兩種格式建置伺服器的指令碼。

    package.json
    {
    "bin": "dist/stdio.mjs",
    "scripts": {
    "build:mcp": "tsup src/mastra/stdio.ts --format esm,cjs --no-splitting --dts && echo '#!/usr/bin/env node' | cat - dist/stdio.mjs > temp && mv temp dist/stdio.mjs && chmod +x dist/stdio.mjs"
    }
    }

    建置命令會同時產生 ESM(.mjs)及 CJS(.cjs)輸出,以提供最大的兼容性。系統會在 ESM 成品前加上 shebang(#!/usr/bin/env node),讓它可以直接執行,而 bin 項目則指向此檔案。

  4. 執行建置命令:

    npm run build:mcp

    這會將伺服器程式碼編譯成 ESM 及 CJS 格式,並讓 ESM 輸出檔案可以執行。在類 Unix 系統上,chmod +x 步驟會讓檔案可以直接執行。Windows 用戶可能需要使用 WSL,或直接透過 Node.js 執行。

發佈至 NPM
發佈至 NPM 的直接連結

如要讓其他人(或你自己)透過 npx 或作為依賴套件使用你的 MCP 伺服器,可以將它發佈至 NPM。

  1. 確保你擁有 NPM 帳戶並已登入(npm login)。

  2. 確保 package.json 中的套件名稱是獨一無二且尚未被使用。

  3. 建置完成後,在項目根目錄執行發佈命令:

    npm publish --access public

    如需更多發佈套件的詳情,請參閱 NPM 文件

使用已發佈的 MCP 伺服器
使用已發佈的 MCP 伺服器 的直接連結

發佈後,你可以指定執行套件的命令,讓 MCPClient 使用你的 MCP 伺服器。你亦可以使用任何其他 MCP Client,例如 Claude desktop、Cursor 或 Windsurf。

import { MCPClient } from '@mastra/mcp'

const mcp = new MCPClient({
servers: {
// Give this MCP server instance a name
yourServerName: {
command: 'npx',
args: ['-y', '@your-org-name/your-package-name@latest'], // Replace with your package name
},
},
})

// You can then get tools or toolsets from this configuration to use in your agent
const tools = await mcp.listTools()
const toolsets = await mcp.listToolsets()

注意:如果發佈時沒有使用組織範圍,args 可能是 ["-y", "your-package-name@latest"]