MCP サーバーの公開
この例では、stdio transport を使用する基本的な Mastra MCPServer をセットアップしてビルドし、NPM への公開準備を行います。
依存関係のインストール依存関係のインストールへの直接リンク
必要なパッケージをインストールします。
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/mcp @mastra/core tsup
pnpm add @mastra/mcp @mastra/core tsup
yarn add @mastra/mcp @mastra/core tsup
bun add @mastra/mcp @mastra/core tsup
MCP サーバーのセットアップMCP サーバーのセットアップへの直接リンク
stdio サーバー用のファイル(例:
src/mastra/stdio.ts)を作成します。次のコードをファイルに追加します。実際に使用する Mastra Tool を import し、サーバーに適切な名前を付けてください。
src/mastra/stdio.ts#!/usr/bin/env nodeimport { 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)})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エントリはこのファイルを指します。ビルドコマンドを実行します。
- npm
- pnpm
- Yarn
- Bun
npm run build:mcppnpm run build:mcpyarn build:mcpbun run build:mcpサーバーのコードが ESM と CJS の両形式にコンパイルされ、ESM 出力ファイルが実行可能になります。Unix 系システムでは、
chmod +xによってファイルを直接実行できるようになります。Windows ユーザーは WSL を使用するか、Node.js から直接実行する必要があります。
NPM への公開NPM への公開への直接リンク
他のユーザー(または自分)が npx や依存関係として MCP サーバーを利用できるよう、NPM に公開できます。
NPM アカウントを所有し、ログイン済み(
npm login)であることを確認します。package.jsonのパッケージ名が一意で、利用可能であることを確認します。ビルド後、プロジェクトルートから公開コマンドを実行します。
npm publish --access publicパッケージの公開について詳しくは、NPM ドキュメントを参照してください。
公開した MCP サーバーの使用公開した MCP サーバーの使用への直接リンク
公開後は、パッケージを実行するコマンドを指定することで、MCPClient から MCP サーバーを使用できます。Claude Desktop、Cursor、Windsurf など、ほかの MCP クライアントも利用できます。
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"] になることがあります。