Skip to main content

createRoute()

createRoute() 函数使用 Zod 验证创建类型安全的路由。当服务器适配器上配置了 openapiPath 时,它会根据提供的 Zod 模式生成 OpenAPI 架构条目。

🌐 The createRoute() function creates type-safe routes with Zod validation. When an openapiPath is configured on the server adapter, it generates OpenAPI schema entries from the supplied Zod schemas.

导入
Direct link to 导入

🌐 Import

import { createRoute } from '@mastra/server/server-adapter';

签名
Direct link to 签名

🌐 Signature

function createRoute<TPath, TQuery, TBody, TResponse, TResponseType>(
config: RouteConfig<TPath, TQuery, TBody, TResponse, TResponseType>
): ServerRoute

参数
Direct link to 参数

🌐 Parameters

method:

'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'ALL'
HTTP method

path:

string
Route path with optional params (e.g., `/api/items/:id`)

responseType:

'json' | 'stream'
Response format. Internal routes may use additional types (`datastream-response`, `mcp-http`, `mcp-sse`).

handler:

ServerRouteHandler
Route handler function

pathParamSchema?:

ZodSchema
Validates URL path parameters

queryParamSchema?:

ZodSchema
Validates query string parameters

bodySchema?:

ZodSchema
Validates request body

responseSchema?:

ZodSchema
Documents response shape for OpenAPI

streamFormat?:

'sse' | 'stream'
Stream format (when responseType is 'stream')

maxBodySize?:

number
Override default body size limit in bytes

summary?:

string
OpenAPI summary

description?:

string
OpenAPI description

tags?:

string[]
OpenAPI tags

deprecated?:

boolean
Mark route as deprecated

处理程序参数
Direct link to 处理程序参数

🌐 Handler parameters

处理程序接收经过验证的参数以及运行时上下文:

🌐 The handler receives validated parameters plus runtime context:

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
}

返回值
Direct link to 返回值

🌐 Return value

返回一个可以注册到适配器的 ServerRoute 对象。

🌐 Returns a ServerRoute object that can be registered with an adapter.

示例
Direct link to 示例

🌐 Examples

带路径参数的 GET 路由
Direct link to 带路径参数的 GET 路由

🌐 GET route with path params

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 路由
Direct link to 带请求体的 POST 路由

🌐 POST route with body

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 };
},
});

带强制类型转换的查询参数
Direct link to 带强制类型转换的查询参数

🌐 Query params with coercion

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 };
},
});

流路线
Direct link to 流路线

🌐 Streaming route

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 });
},
});

自定义主体尺寸限制
Direct link to 自定义主体尺寸限制

🌐 Custom body size limit

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 };
},
});

模式模式
Direct link to 模式模式

🌐 Schema patterns

用于可扩展性的直通
Direct link to 用于可扩展性的直通

🌐 Passthrough for extensibility

const bodySchema = z.object({
required: z.string(),
}).passthrough(); // Allow unknown fields

日期强制转换
Direct link to 日期强制转换

🌐 Date coercion

const querySchema = z.object({
fromDate: z.coerce.date().optional(),
toDate: z.coerce.date().optional(),
});

联合类型
Direct link to 联合类型

🌐 Union types

const bodySchema = z.object({
messages: z.union([
z.array(z.any()),
z.string(),
]),
});

错误处理
Direct link to 错误处理

🌐 Error handling

抛出带有 status 属性的错误,以便从处理程序返回特定的 HTTP 状态码。如果使用 Hono,你可以从 hono/http-exception 使用 HTTPException

🌐 Throw an error with a status property to return specific HTTP status codes from handlers. If using Hono, you can use HTTPException from hono/http-exception:

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 属性的错误:

🌐 For Express or framework-agnostic code, throw an error with a status property:

class HttpError extends Error {
constructor(public status: number, message: string) {
super(message);
}
}

// In handler:
throw new HttpError(404, `Agent '${agentId}' not found`);

常见状态码:

🌐 Common status codes:

代码含义
400错误的请求
401未授权
403禁止访问
404未找到
500服务器内部错误

🌐 Related