MastraServer
MastraServer 抽象类是所有服务器适配器的基类。扩展此类可以为 Hono 或 Express 以外的框架创建适配器。
🌐 The MastraServer abstract class is the base for all server adapters. Extend this class to create adapters for frameworks other than Hono or Express.
导入Direct link to 导入
🌐 Import
import { MastraServer } from '@mastra/server/server-adapter';
类型参数Direct link to 类型参数
🌐 Type parameters
MastraServer<TApp, TRequest, TResponse>
| 参数 | 描述 |
|---|---|
TApp | 框架应用类型(例如,Hono,Application) |
TRequest | 框架请求类型 |
TResponse | 框架响应/上下文类型 |
构造函数Direct link to 构造函数
🌐 Constructor
constructor(options: MastraServerOptions<TApp>)
选项Direct link to 选项
🌐 Options
app:
mastra:
prefix?:
openapiPath?:
bodyLimitOptions?:
streamOptions?:
customRouteAuthConfig?:
tools?:
taskStore?:
mcpOptions?:
抽象方法Direct link to 抽象方法
🌐 Abstract methods
这些方法必须由适配器实现:
🌐 These methods must be implemented by adapters:
registerContextMiddleware()Direct link to registerContextMiddleware()
将Mastra上下文附加到每个请求中。
🌐 Attach Mastra context to every request.
abstract registerContextMiddleware(): void
要附加的上下文:
mastra- Mastra 实例requestContext- 请求范围上下文tools- 可用工具abortSignal- 请求取消信号
registerAuthMiddleware()Direct link to registerAuthMiddleware()
注册身份验证和授权中间件。
🌐 Register authentication and authorization middleware.
abstract registerAuthMiddleware(): void
registerRoute()Direct link to registerRoute()
在框架中注册一个路由。
🌐 Register a single route with the framework.
abstract registerRoute(
app: TApp,
route: ServerRoute,
options: { prefix?: string }
): Promise<void>
getParams()Direct link to getParams()
从请求中提取参数。
🌐 Extract parameters from the request.
abstract getParams(
route: ServerRoute,
request: TRequest
): Promise<{
urlParams: Record<string, string>;
queryParams: Record<string, string>;
body: unknown;
}>
sendResponse()Direct link to sendResponse()
根据路线类型发送响应。
🌐 Send response based on route type.
abstract sendResponse(
route: ServerRoute,
response: TResponse,
result: unknown
): Promise<unknown>
stream()Direct link to stream()
处理流式响应。
🌐 Handle streaming responses.
abstract stream(
route: ServerRoute,
response: TResponse,
result: unknown
): Promise<unknown>
实例方法Direct link to 实例方法
🌐 Instance methods
init()Direct link to init()
通过注册所有中间件和路由来初始化服务器。
🌐 Initialize the server by registering all middleware and routes.
async init(): Promise<void>
按顺序调用:
🌐 Calls in order:
registerContextMiddleware()registerAuthMiddleware()registerRoutes()
registerRoutes()Direct link to registerRoutes()
注册所有Mastra路线。
🌐 Register all Mastra routes.
async registerRoutes(): Promise<void>
getApp()Direct link to getApp()
获取框架应用实例。
🌐 Get the framework app instance.
getApp<T = TApp>(): T
parsePathParams()Direct link to parsePathParams()
使用路由的 Zod 模式验证路径参数。
🌐 Validate path parameters with the route's Zod schema.
async parsePathParams(
route: ServerRoute,
params: Record<string, string>
): Promise<Record<string, unknown>>
parseQueryParams()Direct link to parseQueryParams()
使用路由的 Zod 模式验证查询参数。
🌐 Validate query parameters with the route's Zod schema.
async parseQueryParams(
route: ServerRoute,
params: Record<string, string>
): Promise<Record<string, unknown>>
parseBody()Direct link to parseBody()
使用路由的 Zod 模式验证请求体。
🌐 Validate request body with the route's Zod schema.
async parseBody(
route: ServerRoute,
body: unknown
): Promise<unknown>
registerOpenAPIRoute()Direct link to registerOpenAPIRoute()
注册一个提供 OpenAPI 规范的端点。
🌐 Register an endpoint that serves the OpenAPI specification.
async registerOpenAPIRoute(
app: TApp,
config: OpenAPIConfig,
options: { prefix?: string }
): Promise<void>
受保护的方法Direct link to 受保护的方法
🌐 Protected methods
mergeRequestContext()Direct link to mergeRequestContext()
合并来自多个来源的请求上下文(查询参数和请求体)。
🌐 Merge request context from multiple sources (query params and body).
protected mergeRequestContext(options: {
paramsRequestContext?: Record<string, any>;
bodyRequestContext?: Record<string, any>;
}): RequestContext
类型Direct link to 类型
🌐 Types
BodyLimitOptionsDirect link to BodyLimitOptions
interface BodyLimitOptions {
maxSize: number;
onError: (error: unknown) => unknown;
}
StreamOptionsDirect link to StreamOptions
interface StreamOptions {
redact?: boolean;
}
MCP选项Direct link to MCP选项
🌐 MCPOptions
interface MCPOptions {
serverless?: boolean;
sessionIdGenerator?: () => string;
}
| 属性 | 描述 |
|---|---|
serverless | 当 true 时,以无状态模式运行 MCP,不管理会话。适用于无服务器环境,如 Cloudflare Workers 或 Vercel Edge。 |
sessionIdGenerator | 用于生成会话 ID 的自定义函数。 |
示例Direct link to 示例
🌐 Example
import { MastraServer, ServerRoute } from '@mastra/server/server-adapter';
import type { Mastra } from '@mastra/core';
export class MyServer extends MastraServer<MyApp, MyRequest, MyResponse> {
registerContextMiddleware(): void {
this.app.use('*', (req, res, next) => {
res.locals.mastra = this.mastra;
next();
});
}
registerAuthMiddleware(): void {
const auth = this.mastra.getServer()?.auth;
if (!auth) return;
// Implement auth
}
async registerRoute(app, route, { prefix }) {
// Implement route registration
}
async getParams(route, request) {
return {
urlParams: request.params,
queryParams: request.query,
body: request.body,
};
}
async sendResponse(route, response, result) {
return response.json(result);
}
async stream(route, response, result) {
// Implement streaming
}
}
相关Direct link to 相关
🌐 Related
- 服务器适配器 - 使用适配器
- 自定义适配器 - 创建自定义适配器
- createRoute() - 创建自定义路由