跳到主要内容
非官方简体中文翻译,内容版权归 Mastra 所有,遵循 Apache-2.0 许可。

Elysia adapter

The @mastra/elysia package provides a server adapter for running Mastra with Elysia.

note

For general adapter concepts, constructor options, and initialization flow, see Server Adapters.

Installation
Installation的直接链接

Install the Elysia adapter and Elysia framework:

npm install @mastra/elysia@latest elysia

Usage example
Usage example的直接链接

server.ts
import { Elysia } from 'elysia'
import { MastraServer } from '@mastra/elysia'
import { mastra } from './mastra'

const app = new Elysia()
const server = new MastraServer({ app, mastra })

await server.init()

app.listen(3000)

console.log('Server running on http://localhost:3000')

init() doesn't start Mastra's background workers. To run scheduled workflows, agent schedules, or event listeners, call await mastra.startWorkers() after the server starts listening. See Start background workers.

Constructor parameters
Constructor parameters的直接链接

app:

Elysia
Elysia app instance

mastra:

Mastra
Mastra instance

prefix?:

string
= '/api'
Route path prefix (e.g., /api/v2)

openapiPath?:

string
= ''
Path to serve OpenAPI spec (e.g., /openapi.json)

bodyLimitOptions?:

BodyLimitOptions
Request body size limits

streamOptions?:

StreamOptions
= { redact: true }
Stream redaction config. When true (default), redacts sensitive data from stream chunks before sending to clients.

customRouteAuthConfig?:

Map<string, boolean>
Per-route auth overrides. Keys are METHOD:PATH (e.g., GET:/api/health). Value false makes route public, true requires auth.

tools?:

ToolsInput
Available tools for the server

taskStore?:

InMemoryTaskStore
Task store for A2A (Agent-to-Agent) operations

mcpOptions?:

MCPOptions
MCP transport options, such as setRequestAuth to control what tools see as context.mcp.extra.authInfo.

Adding custom routes
Adding custom routes的直接链接

Add routes directly to the Elysia app:

server.ts
import { Elysia } from 'elysia'
import { MastraServer } from '@mastra/elysia'
import { mastra } from './mastra'

const app = new Elysia()
const server = new MastraServer({ app, mastra })

// Before init - runs before Mastra middleware
app.get('/early-health', () => ({ status: 'ok' }))

await server.init()

// After init - has access to Mastra context
app.get('/custom', ({ mastra }) => {
return { agents: Object.keys(mastra.listAgents()) }
})
提示

Routes added before init() run without Mastra context. Add routes after init() to access the Mastra instance and request context.

When you want Mastra-managed auth and route metadata such as requiresAuth, prefer registerApiRoute(). For raw Elysia routes mounted directly on app, use createAuthMiddleware():

server.ts
import { Elysia } from 'elysia'
import { createAuthMiddleware, MastraServer } from '@mastra/elysia'
import { mastra } from './mastra'

const app = new Elysia()
const server = new MastraServer({ app, mastra })

await server.init()

app.get('/custom/protected', async ctx => {
const authResponse = await createAuthMiddleware({ mastra })(ctx)
if (authResponse) return authResponse

const user = ctx.requestContext.get('user')
return { user }
})

app.get('/custom/public', async ctx => {
const authResponse = await createAuthMiddleware({ mastra, requiresAuth: false })(ctx)
if (authResponse) return authResponse

return { ok: true }
})

When the auth provider refreshes an expired session, createAuthMiddleware() forwards the refreshed session headers (such as Set-Cookie) to the response, including error responses. MastraServer registers the applyAuthRefreshHeaders hook during init(), so routes added after init() get these headers alongside any cookies your route sets.

If you use createAuthMiddleware() without MastraServer, register the hook yourself before defining routes:

server.ts
import { Elysia } from 'elysia'
import { applyAuthRefreshHeaders, createAuthMiddleware } from '@mastra/elysia'
import { mastra } from './mastra'

const app = new Elysia()
.onAfterHandle({ as: 'global' }, applyAuthRefreshHeaders)
.onError({ as: 'global' }, applyAuthRefreshHeaders)

app.get('/custom/protected', () => ({ ok: true }), {
beforeHandle: createAuthMiddleware({ mastra }),
})

Accessing context
Accessing context的直接链接

In Elysia handlers registered after init(), access Mastra context from the handler context:

server.ts
app.get('/custom', ({ mastra, requestContext, abortSignal }) => {
const agent = mastra.getAgent('myAgent')
const user = requestContext.get('user')

return { agent: agent.name, user, aborted: abortSignal.aborted }
})

Available context keys:

KeyDescription
mastraMastra instance
requestContextRequest context map
abortSignalRequest cancellation signal
registeredToolsAvailable tools
taskStoreTask store for A2A operations
customRouteAuthConfigPer-route auth overrides
userAuthenticated user in requestContext when auth is configured

OpenAPI helpers
OpenAPI helpers的直接链接

Use getMastraOpenAPIDoc() when you need to pass Mastra's generated OpenAPI document to Elysia tooling such as @elysiajs/openapi:

server.ts
import { openapi } from '@elysiajs/openapi'
import { Elysia } from 'elysia'
import { getMastraOpenAPIDoc, MastraServer } from '@mastra/elysia'
import { mastra } from './mastra'

const app = new Elysia()
const server = new MastraServer({ app, mastra })

await server.init()

app.use(
openapi({
documentation: getMastraOpenAPIDoc(server),
}),
)

Call clearMastraOpenAPICache(server) if you need to regenerate the cached document for the same server instance.

MCP support
MCP support的直接链接

The Elysia adapter serves each registered MCP server over Streamable HTTP at /api/mcp/:serverId/mcp.

Manual initialization
Manual initialization的直接链接

For custom middleware ordering, call each method separately instead of init(). See manual initialization for details.