Koa adapter
The @mastra/koa package provides a server adapter for running Mastra with Koa. For general adapter concepts (constructor options, initialization flow, etc.), see Server Adapters.
InstallationInstallation的直接链接
Install the Koa adapter and Koa framework:
- npm
- pnpm
- Yarn
- Bun
npm install @mastra/koa@latest koa koa-bodyparser
pnpm add @mastra/koa@latest koa koa-bodyparser
yarn add @mastra/koa@latest koa koa-bodyparser
bun add @mastra/koa@latest koa koa-bodyparser
Usage exampleUsage example的直接链接
import Koa from 'koa'
import bodyParser from 'koa-bodyparser'
import { MastraServer } from '@mastra/koa'
import { mastra } from './mastra'
const app = new Koa()
app.use(bodyParser())
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 parametersConstructor parameters的直接链接
app:
mastra:
prefix?:
/api/v2)openapiPath?:
/openapi.json)bodyLimitOptions?:
streamOptions?:
customRouteAuthConfig?:
METHOD:PATH (e.g., GET:/api/health). Value false makes route public, true requires auth.tools?:
taskStore?:
mcpOptions?:
setRequestAuth to control what tools see as context.mcp.extra.authInfo.Error handlingError handling的直接链接
The Koa adapter propagates errors from route handlers up through Koa's middleware chain, following Koa's standard error handling pattern. You can use regular Koa error-handling middleware:
const app = new Koa()
app.use(bodyParser())
// Your error middleware catches errors from Mastra route handlers
app.use(async (ctx, next) => {
try {
await next()
} catch (err) {
ctx.status = err.status || 500
ctx.body = { error: err.message }
// Log, report to Sentry, etc.
}
})
const server = new MastraServer({ app, mastra })
await server.init()
The server.onError hook is also supported. When configured, it's called before the error propagates to middleware, and its response is used directly:
const mastra = new Mastra({
server: {
onError: (err, c) => {
console.error('Unhandled error:', err)
return c.json({ error: err.message }, 500)
},
},
})
When init() is used, a global error-handling middleware is also registered as a safety net. Errors that reach this middleware are emitted via ctx.app.emit('error', err, ctx) following the standard Koa convention.
Protecting raw routesProtecting raw routes的直接链接
When you want Mastra-managed auth and route metadata such as requiresAuth, prefer registerApiRoute(). For raw Koa routes mounted directly on the app, use createAuthMiddleware():
import Koa from 'koa'
import { createAuthMiddleware, MastraServer } from '@mastra/koa'
import { mastra } from './mastra'
const app = new Koa()
const server = new MastraServer({ app, mastra })
await server.init()
app.use(createAuthMiddleware({ mastra }))
app.use(async ctx => {
if (ctx.path !== '/custom/protected') return
const user = ctx.state.requestContext.get('user')
ctx.body = { user }
})
Manual initializationManual initialization的直接链接
For custom middleware ordering, call each method separately instead of init(). See manual initialization for details.
ExamplesExamples的直接链接
- Koa Adapter: Basic Koa server setup
RelatedRelated的直接链接
- Server Adapters: Shared adapter concepts
- MastraServer Reference: Full API reference
- createRoute() Reference: Creating type-safe custom routes