メインコンテンツへ移動

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-responsemcp-httpmcp-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 の説明

tags?:

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-exceptionHTTPException を使用できます。

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サーバー内部エラー