createRoute()
createRoute() 関数は、Zod バリデーションを備えた型安全なルートを作成します。サーバーアダプターに openapiPath が設定されている場合、指定された Zod スキーマから OpenAPI スキーマエントリを生成します。
インポートインポートへの直接リンク
import { createRoute } from '@mastra/server/server-adapter'
シグネチャシグネチャへの直接リンク
function createRoute<TPath, TQuery, TBody, TResponse, TResponseType>(
config: RouteConfig<TPath, TQuery, TBody, TResponse, TResponseType>,
): ServerRoute
パラメーターパラメーターへの直接リンク
method:
'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'
HTTP メソッド
path:
string
省略可能なパラメーターを含むルートパス(例:
/api/items/:id)responseType:
'json' | 'stream'
レスポンス形式。内部ルートでは追加の型(
datastream-response、mcp-http、mcp-sse)を使用できます。handler:
ServerRouteHandler
ルートハンドラー関数
pathParamSchema?:
ZodSchema
URL パスパラメーターを検証します
queryParamSchema?:
ZodSchema
クエリ文字列パラメーターを検証します
bodySchema?:
ZodSchema
リクエストボディを検証します
responseSchema?:
ZodSchema
OpenAPI 用にレスポンスの構造を記述します
streamFormat?:
'sse' | 'stream'
ストリーム形式(responseType が 'stream' の場合)
maxBodySize?:
number
デフォルトのボディサイズ上限をバイト単位で上書きします
summary?:
string
OpenAPI の概要
description?:
string
OpenAPI の説明
deprecated?:
boolean
ルートを非推奨としてマークします
onValidationError?:
(error: ZodError, context: 'query' | 'body' | 'path') => { status: number; body: unknown } | undefined
このルート用のカスタムバリデーションエラーハンドラー。サーバーレベルの
onValidationError フックを上書きします。レスポンスをカスタマイズするには { status, body } を返し、デフォルトを使用するには undefined を返します。ハンドラーのパラメーターハンドラーのパラメーターへの直接リンク
ハンドラーは、検証済みのパラメーターとランタイムコンテキストを受け取ります。
handler: async params => {
// From schemas (typed from Zod)
params.id // From pathParamSchema
params.filter // From queryParamSchema
params.name // From bodySchema
// Runtime context (always available)
params.mastra // Mastra instance
params.requestContext // Request-scoped context
params.tools // Available tools
params.abortSignal // Request cancellation signal
params.taskStore // A2A task storage
}
戻り値戻り値への直接リンク
アダプターに登録できる ServerRoute オブジェクトを返します。
例例への直接リンク
パスパラメーターを使用する GET ルートパスパラメーターを使用する GET ルートへの直接リンク
import { createRoute } from '@mastra/server/server-adapter'
import { z } from 'zod'
const getAgent = createRoute({
method: 'GET',
path: '/api/agents/:agentId',
responseType: 'json',
pathParamSchema: z.object({
agentId: z.string(),
}),
responseSchema: z.object({
name: z.string(),
description: z.string().optional(),
}),
summary: 'Get agent by ID',
tags: ['Agents'],
handler: async ({ agentId, mastra }) => {
return mastra.getAgent(agentId)
},
})
ボディを使用する POST ルートボディを使用する POST ルートへの直接リンク
const createItem = createRoute({
method: 'POST',
path: '/api/items',
responseType: 'json',
bodySchema: z.object({
name: z.string(),
value: z.number(),
}),
responseSchema: z.object({
id: z.string(),
name: z.string(),
value: z.number(),
}),
handler: async ({ name, value, mastra }) => {
// name and value are typed from bodySchema
return { id: 'new-id', name, value }
},
})
型変換を伴うクエリパラメーター型変換を伴うクエリパラメーターへの直接リンク
const listItems = createRoute({
method: 'GET',
path: '/api/items',
responseType: 'json',
queryParamSchema: z.object({
page: z.coerce.number().default(0),
limit: z.coerce.number().default(50),
enabled: z.coerce.boolean().optional(),
}),
handler: async ({ page, limit, enabled, mastra }) => {
// page, limit, enabled are typed and coerced
return { items: [], page, limit }
},
})
Streaming ルートStreaming ルートへの直接リンク
const streamAgent = createRoute({
method: 'POST',
path: '/api/agents/:agentId/stream',
responseType: 'stream',
streamFormat: 'sse',
pathParamSchema: z.object({
agentId: z.string(),
}),
bodySchema: z.object({
messages: z.array(z.any()),
}),
handler: async ({ agentId, messages, mastra, abortSignal }) => {
const agent = mastra.getAgent(agentId)
return agent.stream(messages, { abortSignal })
},
})
カスタムのボディサイズ上限カスタムのボディサイズ上限への直接リンク
const uploadRoute = createRoute({
method: 'POST',
path: '/api/upload',
responseType: 'json',
maxBodySize: 50 * 1024 * 1024, // 50MB
bodySchema: z.object({
file: z.string(),
}),
handler: async ({ file }) => {
return { uploaded: true }
},
})
スキーマパターンスキーマパターンへの直接リンク
拡張性のための Passthrough拡張性のための Passthroughへの直接リンク
const bodySchema = z
.object({
required: z.string(),
})
.passthrough() // Allow unknown fields
日付の型変換日付の型変換への直接リンク
const querySchema = z.object({
fromDate: z.coerce.date().optional(),
toDate: z.coerce.date().optional(),
})
Union 型Union 型への直接リンク
const bodySchema = z.object({
messages: z.union([z.array(z.any()), z.string()]),
})
エラー処理エラー処理への直接リンク
ハンドラーから特定の HTTP ステータスコードを返すには、status プロパティを持つエラーをスローします。Hono を使用している場合は、hono/http-exception の HTTPException を使用できます。
import { createRoute } from '@mastra/server/server-adapter'
import { HTTPException } from 'hono/http-exception'
const getAgent = createRoute({
method: 'GET',
path: '/api/agents/:agentId',
responseType: 'json',
pathParamSchema: z.object({ agentId: z.string() }),
handler: async ({ agentId, mastra }) => {
const agent = mastra.getAgent(agentId)
if (!agent) {
throw new HTTPException(404, { message: `Agent '${agentId}' not found` })
}
return agent
},
})
Express またはフレームワークに依存しないコードでは、status プロパティを持つエラーをスローします。
class HttpError extends Error {
constructor(
public status: number,
message: string,
) {
super(message)
}
}
// In handler:
throw new HttpError(404, `Agent '${agentId}' not found`)
一般的なステータスコードは次のとおりです。
| コード | 意味 |
|---|---|
| 400 | 不正なリクエスト |
| 401 | 認証が必要 |
| 403 | アクセス禁止 |
| 404 | 見つかりません |
| 500 | サーバー内部エラー |
関連項目関連項目への直接リンク
- Server ルート: Mastra のデフォルトルート
- MastraServer: Server アダプタークラス
- Server アダプター: アダプターの使用方法