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