> Discover all available pages from the documentation index: https://mastra.zisheng.pro/ja/llms.txt # Koa アダプター `@mastra/koa` パッケージは、Mastra を [Koa](https://koajs.com) で実行するためのサーバーアダプターを提供します。アダプターの一般的な概念(コンストラクターオプション、初期化フローなど)については、[サーバーアダプター](https://mastra.zisheng.pro/ja/docs/server/server-adapters)を参照してください。 ## インストール Koa アダプターと Koa フレームワークをインストールします。 **npm**: ```bash npm install @mastra/koa@latest koa koa-bodyparser ``` **pnpm**: ```bash pnpm add @mastra/koa@latest koa koa-bodyparser ``` **Yarn**: ```bash yarn add @mastra/koa@latest koa koa-bodyparser ``` **Bun**: ```bash bun add @mastra/koa@latest koa koa-bodyparser ``` ## 使用例 ```typescript import Koa from 'koa' import bodyParser from 'koa-bodyparser' import { MastraServer } from '@mastra/koa' import { mastra } from './mastra' const app = new Koa() app.use(bodyParser()) const server = new MastraServer({ app, mastra }) await server.init() app.listen(3000, () => { console.log('Server running on http://localhost:3000') }) ``` ## コンストラクターのパラメーター **app** (`Koa`): Koa アプリのインスタンス **mastra** (`Mastra`): Mastra のインスタンス **prefix** (`string`): ルートパスのプレフィックス(例:/api/v2) (Default: `''`) **openapiPath** (`string`): OpenAPI 仕様を配信するパス(例:/openapi.json) (Default: `''`) **bodyLimitOptions** (`BodyLimitOptions`): リクエストボディのサイズ制限 **streamOptions** (`StreamOptions`): ストリームの秘匿化設定。true(デフォルト)の場合、クライアントに送信する前にストリームチャンクから機密データ(システムプロンプト、Tool 定義、API キー)を秘匿します。 (Default: `{ redact: true }`) **customRouteAuthConfig** (`Map`): ルートごとの認証オーバーライド。キーは METHOD:PATH(例:GET:/api/health)です。値が false の場合はルートを公開し、true の場合は認証を必須にします。 **tools** (`ToolsInput`): サーバーで利用可能な Tool **taskStore** (`InMemoryTaskStore`): A2A(Agent-to-Agent)操作用のタスクストア **mcpOptions** (`MCPOptions`): MCP トランスポートのオプション。Cloudflare Workers や Vercel Edge などのステートレス環境では serverless: true を設定します。 ## エラー処理 Koa アダプターは、Koa の標準的なエラー処理パターンに従い、ルートハンドラーからのエラーを Koa のミドルウェアチェーンへ伝播します。そのため、通常の Koa エラー処理ミドルウェアを使用できます。 ```typescript const app = new Koa() app.use(bodyParser()) // Your error middleware catches errors from Mastra route handlers app.use(async (ctx, next) => { try { await next() } catch (err) { ctx.status = err.status || 500 ctx.body = { error: err.message } // Log, report to Sentry, etc. } }) const server = new MastraServer({ app, mastra }) await server.init() ``` [`server.onError`](https://mastra.zisheng.pro/ja/reference/configuration) フックもサポートされています。設定すると、エラーがミドルウェアに伝播する前に呼び出され、そのレスポンスが直接使用されます。 ```typescript const mastra = new Mastra({ server: { onError: (err, c) => { console.error('Unhandled error:', err) return c.json({ error: err.message }, 500) }, }, }) ``` `init()` を使用すると、安全策としてグローバルなエラー処理ミドルウェアも登録されます。このミドルウェアに到達したエラーは、Koa の標準規約に従い `ctx.app.emit('error', err, ctx)` を介して発行されます。 ## 生のルートの保護 Mastra が管理する認証や `requiresAuth` などのルートメタデータが必要な場合は、[`registerApiRoute()`](https://mastra.zisheng.pro/ja/reference/server/register-api-route) を推奨します。アプリに直接マウントする生の Koa ルートでは、`createAuthMiddleware()` を使用します。 ```typescript import Koa from 'koa' import { createAuthMiddleware, MastraServer } from '@mastra/koa' import { mastra } from './mastra' const app = new Koa() const server = new MastraServer({ app, mastra }) await server.init() app.use(createAuthMiddleware({ mastra })) app.use(async ctx => { if (ctx.path !== '/custom/protected') return const user = ctx.state.requestContext.get('user') ctx.body = { user } }) ``` ## 手動初期化 ミドルウェアの順序をカスタマイズするには、`init()` の代わりに各メソッドを個別に呼び出します。詳しくは、[手動初期化](https://mastra.zisheng.pro/ja/docs/server/server-adapters)を参照してください。 ## 例 - [Koa アダプター](https://github.com/mastra-ai/mastra/tree/main/examples/server-koa-adapter):Koa サーバーの基本的なセットアップ ## 関連項目 - [サーバーアダプター](https://mastra.zisheng.pro/ja/docs/server/server-adapters):アダプターに共通する概念 - [MastraServer リファレンス](https://mastra.zisheng.pro/ja/reference/server/mastra-server):完全な API リファレンス - [createRoute() リファレンス](https://mastra.zisheng.pro/ja/reference/server/create-route):型安全なカスタムルートの作成