Skip to main content

Koa Adapter

The @mastra/koa package provides a server adapter for running Mastra with Koa.

info

For general adapter concepts (constructor options, initialization flow, etc.), see Server Adapters.

Installation
Direct link to Installation

Install the Koa adapter and Koa framework:

npm install @mastra/koa@latest koa koa-bodyparser

Usage example
Direct link to Usage example

server.ts
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')
})

Constructor parameters
Direct link to Constructor parameters

app:

Koa
Koa app instance

mastra:

Mastra
Mastra instance

prefix?:

string
= ''
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 (system prompts, tool definitions, API keys) 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. Set `serverless: true` for stateless environments like Cloudflare Workers or Vercel Edge.

Error handling
Direct link to Error handling

The Koa adapter propagates errors from route handlers up through Koa's middleware chain, following Koa's standard error handling pattern. This means you can use regular Koa error-handling middleware:

server.ts
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 is called before the error propagates to middleware, and its response is used directly:

src/mastra/index.ts
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.

Manual initialization
Direct link to Manual initialization

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

Examples
Direct link to Examples