Server Adapter
Server Adapter を使用すると、mastra build が生成する Hono サーバーの代わりに、独自の HTTP サーバーで Mastra を実行できます。カスタムミドルウェアの順序、認証、ログ記録、デプロイ設定など、サーバーのセットアップをより細かく制御できます。Agent や Workflow の実行方法を変更することなく、Mastra を任意の Node.js アプリケーションに統合できます。
Server Adapter は渡された mastra インスタンスを使用し、ファイルベースの検出は実行しません。そのインスタンスにコードで Agent を登録してください。ファイルベースの Agent を使用するには、mastra dev または mastra build で Mastra を別のサーバーとして実行します。
Server Adapter を使用する場面Server Adapter を使用する場面への直接リンク
- 既存のアプリケーションに Mastra のエンドポイントを自動的に追加したい場合
- カスタム設定のためにサーバーインスタンスへ直接アクセスする必要がある場合
mastra buildが作成する Hono サーバーではなく、別のサーバーフレームワークをチームで使用したい場合
サーバーにカスタム要件がないデプロイでは、代わりに mastra build を使用してください。サーバーのセットアップとミドルウェアの登録を行い、プロジェクト設定に基づいてデプロイ設定も適用します。詳しくは、サーバー設定を参照してください。
Server Adapter で Studio を使用する場合は、mastra studio を使用して Studio UI だけを起動してください。
利用可能な Adapter利用可能な Adapterへの直接リンク
Mastra は現在、次の公式 Server Adapter を提供しています。
独自の Adapter も構築できます。詳しくは、カスタム Adapterを参照してください。
インストールインストールへの直接リンク
使用するフレームワークの Adapter をインストールします。
- Express
- Hono
- Fastify
- Koa
- NestJS
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/express@latest
pnpm add @mastra/express@latest
yarn add @mastra/express@latest
bun add @mastra/express@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/hono@latest
pnpm add @mastra/hono@latest
yarn add @mastra/hono@latest
bun add @mastra/hono@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/fastify@latest
pnpm add @mastra/fastify@latest
yarn add @mastra/fastify@latest
bun add @mastra/fastify@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/koa@latest
pnpm add @mastra/koa@latest
yarn add @mastra/koa@latest
bun add @mastra/koa@latest
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/nestjs@latest
pnpm add @mastra/nestjs@latest
yarn add @mastra/nestjs@latest
bun add @mastra/nestjs@latest
設定設定への直接リンク
通常どおりアプリを初期化してから、MastraServer を作成し、app とメインの mastra インスタンス(src/mastra/index.ts から取得)を渡します。init() を呼び出すと、Mastra のミドルウェアと利用可能なすべてのエンドポイントが自動的に登録されます。init() の前後どちらでも、通常どおり独自のルートを追加でき、それらは Mastra のエンドポイントと並行して動作します。
- Express
- Hono
- Fastify
- Koa
- NestJS
import express from 'express'
import { MastraServer } from '@mastra/express'
import { mastra } from './mastra'
const app = express()
app.use(express.json())
const server = new MastraServer({ app, mastra })
await server.init()
app.listen(4111, () => {
console.log('Server running on port 4111')
})
すべての設定オプションについては、Express Adapter のドキュメントを参照してください。
import { Hono } from 'hono'
import { serve } from '@hono/node-server'
import { HonoBindings, HonoVariables, MastraServer } from '@mastra/hono'
import { mastra } from './mastra'
const app = new Hono<{ Bindings: HonoBindings; Variables: HonoVariables }>()
const server = new MastraServer({ app, mastra })
await server.init()
serve({ fetch: app.fetch, port: 4111 }, () => {
console.log('Server running on port 4111')
})
すべての設定オプションについては、Hono Adapter のドキュメントを参照してください。
import Fastify from 'fastify'
import { MastraServer } from '@mastra/fastify'
import { mastra } from './mastra'
const app = Fastify()
const server = new MastraServer({ app, mastra })
await server.init()
app.get('/health', async request => {
const mastraInstance = request.mastra
const agents = Object.keys(mastraInstance.listAgents())
return { status: 'ok', agents }
})
const port = 4111
app.listen({ port }, () => {
console.log(`Server running on http://localhost:${port}`)
console.log(`Try: curl http://localhost:${port}/api/agents`)
})
すべての設定オプションについては、Fastify Adapter のドキュメントを参照してください。
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()) // Required for body parsing
const server = new MastraServer({ app, mastra })
await server.init()
app.use(async (ctx, next) => {
if (ctx.path === '/health' && ctx.method === 'GET') {
const mastraInstance = ctx.state.mastra
const agents = Object.keys(mastraInstance.listAgents())
ctx.body = { status: 'ok', agents }
return
}
await next()
})
const port = 4111
app.listen(port, () => {
console.log(`Server running on http://localhost:${port}`)
console.log(`Try: curl http://localhost:${port}/api/agents`)
})
すべての設定オプションについては、Koa Adapter のドキュメントを参照してください。
import { Module } from '@nestjs/common'
import { MastraModule } from '@mastra/nestjs'
import { mastra } from './mastra'
@Module({
imports: [
MastraModule.register({
mastra,
}),
],
})
export class AppModule {}
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
async function bootstrap() {
const app = await NestFactory.create(AppModule)
await app.listen(3000)
}
bootstrap()
すべての設定オプションについては、NestJS Adapter のドキュメントを参照してください。
初期化フロー初期化フローへの直接リンク
init() を呼び出すと、次の3つのステップが順番に実行されます。このフローを理解しておくと、特定の位置に独自のミドルウェアを挿入する場合に役立ちます。
registerContextMiddleware(): Mastra インスタンス、Request Context、Tool、AbortSignal をすべてのリクエストに付加します。これにより、後続のすべてのミドルウェアとルートハンドラーで Mastra を使用できます。registerAuthMiddleware(): 初期化中に Adapter の認証フックを実行します。公式 Adapter は、Mastra が組み込みルートとregisterApiRoute()のルートを登録する際にインラインで認証を適用します。そのため、生のフレームワークルートで Mastra の認証が必要な場合は、Adapter がエクスポートするcreateAuthMiddleware()ヘルパーを使用してください。registerRoutes(): Agent、Workflow、その他の機能に対応する Mastra API ルートをすべて登録します。MCP サーバーが設定されている場合は、MCP ルートも登録します。
手動での初期化手動での初期化への直接リンク
ミドルウェアの順序をカスタマイズするには、init() の代わりに各メソッドを個別に呼び出します。Mastra のコンテキストが設定される前に実行するミドルウェアが必要な場合や、初期化ステップの間にロジックを挿入する必要がある場合に便利です。
const server = new MastraServer({ app, mastra });
// Your middleware first
app.use(loggingMiddleware);
server.registerContextMiddleware();
// Middleware that needs Mastra context
app.use(customMiddleware);
await server.registerRoutes();
// Routes after Mastra
app.get('/health', ...);
Mastra のコンテキストが利用可能になる前に実行するミドルウェアが必要な場合や、コンテキストと認証のステップの間にミドルウェアを挿入する必要がある場合は、手動で初期化してください。
カスタムルートの追加カスタムルートの追加への直接リンク
Mastra のルートと並行して、独自のルートをアプリに追加できます。
init()の前に追加したルートでは、Mastra のコンテキストを利用できません。init()の後に追加したルートでは、Mastra のコンテキスト(Mastra インスタンス、Request Context、認証済みユーザーなど)へアクセスできます。- Mastra が管理する認証と
requiresAuthなどのルートメタデータを使用する場合は、registerApiRoute()を推奨します。 - フレームワークのアプリにルートを直接マウントする場合、そのルートで Mastra の認証が必要なら、Adapter がエクスポートする
createAuthMiddleware()ヘルパーを使用してください。
詳しくは、Express と Hono の「カスタムルートの追加」を参照してください。Express、Hono
ルートのプレフィックスルートのプレフィックスへの直接リンク
デフォルトでは、Mastra のルートは /api/agents、/api/workflows などに登録されます。これを変更するには prefix オプションを使用します。API のバージョニングや、独自の /api ルートを持つ既存アプリとの統合に便利です。
const server = new MastraServer({
app,
mastra,
prefix: '/api/v2',
})
このプレフィックスを設定すると、Mastra のルートは /api/v2/agents、/api/v2/workflows などになります。アプリに直接追加したカスタムルートは、このプレフィックスの影響を受けません。
OpenAPI 仕様OpenAPI 仕様への直接リンク
Mastra は、登録済みのすべてのルートに対する OpenAPI 仕様を生成できます。ドキュメント、クライアント生成、API Tool との統合に便利です。openapiPath オプションを設定して有効にします。
const server = new MastraServer({
app,
mastra,
openapiPath: '/openapi.json',
})
仕様は各ルートに定義された Zod スキーマから生成され、指定したパスで提供されます。Mastra のすべてのルートに加え、createRoute() で作成したカスタムルートも含まれます。
ストリームデータの秘匿化ストリームデータの秘匿化への直接リンク
Agent のレスポンスを HTTP 経由でストリーミングする際、HTTP ストリーミングレイヤーはクライアントへ送信する前に、ストリームのチャンクから機密情報を秘匿します。これにより、次の情報が誤って公開されるのを防ぎます。
- システムプロンプトと Agent の指示
- Tool の定義とそのパラメーター
- リクエスト本文内の API キーやその他の認証情報
- 内部設定データ
この秘匿化は HTTP 境界で行われるため、onStepFinish などの内部コールバックでは、デバッグや可観測性のために引き続き完全なリクエストデータへアクセスできます。
デフォルトでは秘匿化が有効です。この動作は streamOptions で設定します。ストリームレスポンス内の完全なリクエストデータへアクセスする必要がある内部サービスやデバッグ用途に限り、redact: false を設定してください。
const server = new MastraServer({
app,
mastra,
streamOptions: {
redact: true, // Default
},
})
すべての設定オプションについては、MastraServer を参照してください。
ルート単位での認証の上書きルート単位での認証の上書きへの直接リンク
Mastra インスタンスに認証が設定されている場合、デフォルトではすべてのルートで認証が必要です。ただし、公開するヘルスチェックエンドポイントや Webhook 受信エンドポイント、より厳格な制御が必要な管理ルートなど、例外が必要になることがあります。
特定のルートの認証動作を上書きするには、customRouteAuthConfig を使用します。キーは METHOD:PATH 形式で、メソッドには GET、POST、PUT、DELETE、ALL を指定できます。パスでは、複数のルートに一致させるためにワイルドカード(*)を使用できます。値を false に設定するとルートが公開され、true に設定すると認証が必須になります。
const server = new MastraServer({
app,
mastra,
customRouteAuthConfig: new Map([
// Public health check
['GET:/api/health', false],
// Public API spec
['GET:/api/openapi.json', false],
// Public webhook endpoints
['POST:/api/webhooks/*', false],
// Require auth even if globally disabled
['POST:/api/admin/reset', true],
// Protect all methods on internal routes
['ALL:/api/internal/*', true],
]),
})
すべての設定オプションについては、MastraServer を参照してください。
アプリへのアクセスアプリへのアクセスへの直接リンク
Adapter の作成後も、基盤となるフレームワークのアプリへアクセスする必要がある場合があります。プラットフォームの serve 関数へ渡す場合や、別のモジュールからルートを追加する場合に便利です。
// Via the MastraServer instance
const app = server.getApp()
// Via the Mastra instance (available after adapter construction)
const app = mastra.getServerApp()
どちらのメソッドも同じアプリインスタンスを返します。スコープ内で利用できるものに応じて、使いやすい方を使用してください。
サーバー設定と Adapter オプションの違いサーバー設定と Adapter オプションの違いへの直接リンク
Server Adapter を使用する場合、設定は2か所から取得されます。Mastra の server 設定(Mastra コンストラクターに渡すもの)と、Adapter のコンストラクターオプションです。各オプションの取得元を理解しておくと、設定が反映されない場合の混乱を避けられます。
Adapter が使用する設定Adapter が使用する設定への直接リンク
Adapter は mastra.getServer() から次の設定を読み取ります。
| オプション | 説明 |
|---|---|
auth | registerAuthMiddleware() で使用する認証設定。 |
bodySizeLimit | バイト単位のデフォルトの本文サイズ制限。Adapter ごとに bodyLimitOptions で上書きできます。 |
onError | ルートハンドラーで未処理のエラーが発生したときに呼び出されるカスタムエラーハンドラー。server.onError を参照してください。 |
Adapter のコンストラクター専用Adapter のコンストラクター専用への直接リンク
次のオプションは Adapter のコンストラクターへ直接渡され、Mastra の設定からは読み取られません。
| オプション | 説明 |
|---|---|
prefix | ルートパスのプレフィックス |
openapiPath | OpenAPI 仕様のエンドポイント |
bodyLimitOptions | カスタムエラーハンドラーを伴う本文サイズ制限 |
streamOptions | ストリームの秘匿化設定 |
customRouteAuthConfig | ルート単位での認証の上書き |
mcpOptions | MCP トランスポートオプション(ステートレス環境向けの serverless: true など) |
Adapter が使用しない設定Adapter が使用しない設定への直接リンク
次の server 設定オプションは mastra build だけが使用し、Adapter を直接使用する場合は効果がありません。
| オプション | 使用箇所 |
|---|---|
port, host | mastra dev、mastra build |
cors | mastra build が CORS ミドルウェアを追加 |
timeout | mastra build |
apiRoutes | registerApiRoute()(mastra build 向け) |
middleware | mastra build のミドルウェア設定 |
Adapter を使用する場合、これらの機能はフレームワークで直接設定してください。たとえば、Hono または Express の組み込み CORS パッケージを使用して CORS ミドルウェアを追加し、フレームワークの listen 関数を呼び出す際にポートを設定します。
MCP のサポートMCP のサポートへの直接リンク
Mastra インスタンスに MCP サーバーが設定されている場合、Server Adapter は registerRoutes() の実行時に MCP(Model Context Protocol)ルートを登録します。MCP を使用すると、外部の Tool やサービスが Mastra サーバーへ接続し、Agent とやり取りできます。
Adapter は HTTP と SSE(Server-Sent Events)の両方のトランスポートに対応するルートを登録し、異なるクライアント接続パターンを利用できるようにします。
Serverless モードServerless モードへの直接リンク
Cloudflare Workers や Vercel Edge などの Serverless 環境では、mcpOptions でステートレスモードを有効にします。
Mastra Deployer(標準の mastra dev / mastra build のパス)を使用する場合は、サーバー設定で mcpOptions を設定します。
const mastra = new Mastra({
server: {
mcpOptions: {
serverless: true,
},
},
})
Server Adapter を手動で作成する場合は、mcpOptions を直接渡します。
const server = new MastraServer({
app,
mastra,
mcpOptions: {
serverless: true,
},
})
serverless: true の場合、MCP HTTP リクエストはセッション管理なしで実行されるため、ステートレスな実行環境と互換性があります。
設定の詳細と MCP サーバーのセットアップ方法については、MCP を参照してください。
関連項目関連項目への直接リンク
- Hono Adapter - Hono 固有のセットアップ
- Express Adapter - Express 固有のセットアップ
- NestJS Adapter - NestJS 固有のセットアップ
- カスタム Adapter - その他のフレームワーク向けの Adapter の構築
- サーバー設定 - 代わりに
mastra buildを使用する方法 - 認証 - サーバーの認証設定
- MastraServer リファレンス - API リファレンスの全内容
- createRoute() リファレンス - 型安全なカスタムルートの作成