跳至主要內容

發布 MCP server

本範例將引導你使用 stdio transport 設定基本的 Mastra MCPServer、進行建置,並準備發布至 NPM。

安裝相依套件
「安裝相依套件」的直接連結

安裝必要套件:

npm install @mastra/mcp @mastra/core tsup

設定 MCP server
「設定 MCP server」的直接連結

  1. 為 stdio server 建立檔案,例如 src/mastra/stdio.ts

  2. 將下列程式碼加入檔案。請記得匯入你實際使用的 Mastra tools,並為 server 指定適當名稱。

    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,加入指向已建置 server 檔案的 bin 項目,以及用來同時建置 ESM 與 CJS 輸出的 script。

    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 artifact 前加上 shebang(#!/usr/bin/env node),使其可直接執行,而 bin 項目則指向此檔案。

  4. 執行建置指令:

    npm run build:mcp

    這會將 server 程式碼編譯成 ESM 與 CJS 格式,並讓 ESM 輸出檔可供執行。在類 Unix 系統上,chmod +x 步驟會讓檔案可直接執行。Windows 使用者可能需要使用 WSL,或直接透過 Node.js 處理執行作業。

發布至 NPM
「發布至 NPM」的直接連結

若要讓其他人(或你自己)可透過 npx 使用你的 MCP server,或將其作為相依套件使用,可以將它發布至 NPM。

  1. 確認你擁有 NPM 帳號且已登入(npm login)。

  2. 確認 package.json 中的套件名稱不重複且可供使用。

  3. 建置完成後,從專案根目錄執行發布指令:

    npm publish --access public

    如需發布套件的詳細資訊,請參閱 NPM 文件

使用已發布的 MCP server
「使用已發布的 MCP server」的直接連結

發布後,你可以在 MCPClient 中指定用來執行套件的指令,以使用 MCP server。你也可以使用 Claude desktop、Cursor 或 Windsurf 等其他 MCP client。

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

注意:若發布時未使用組織 scope,args 可能是 ["-y", "your-package-name@latest"]