invokeRoute()
The invokeRoute() function runs a server route in-process as the calling user and returns what the route would have answered over HTTP. It expects a request context that Mastra server auth already authenticated, then applies the same checks as the route's HTTP endpoint on every adapter: your auth provider's authorize, authorizeUser, and rules, schema validation, RBAC permission, and fine-grained authorization (FGA).
Use it to expose a route through another channel, such as an MCP tool, without proxying through the HTTP server and without the two drifting apart.
Usage exampleDirect link to Usage example
import { Mastra } from '@mastra/core/mastra'
import { RequestContext } from '@mastra/core/request-context'
import { createTool } from '@mastra/core/tools'
import { GET_METRIC_AGGREGATE } from '@mastra/server/handlers/observability'
import { invokeRoute } from '@mastra/server/server-adapter'
import { z } from 'zod'
export const agentRunCount = createTool({
id: 'agentRunCount',
description: 'Counts agent runs',
inputSchema: z.object({}),
execute: async (_input, { mastra, requestContext = new RequestContext() }) => {
if (!(mastra instanceof Mastra)) throw new Error('agentRunCount must run inside Mastra')
const { status, body } = await invokeRoute(GET_METRIC_AGGREGATE, {
mastra,
requestContext,
body: { name: ['mastra_agent_duration_ms'], aggregation: 'count' },
})
if (status !== 200) throw new Error(`Metric aggregate failed with status ${status}`)
return body
},
})
ImportDirect link to Import
import { invokeRoute } from '@mastra/server/server-adapter'
SignatureDirect link to Signature
function invokeRoute(route: ServerRoute, options: InvokeRouteOptions): Promise<InvokeRouteResult>
ParametersDirect link to Parameters
route:
@mastra/server/handlers/*. Must have responseType: 'json'.options.mastra:
options.requestContext:
options.pathParams?:
pathParamSchema.options.query?:
queryParamSchema. Use an array for a repeated key.options.body?:
bodySchema.options.abortSignal?:
ReturnsDirect link to Returns
status:
200, 400, 401, or 403.body:
Failed checks and errors thrown by the handler are returned as a status and body, not thrown.
BehaviorDirect link to Behavior
- Authentication isn't re-run. When server or Studio auth is configured, the request context must already carry the user Mastra server auth resolved. Otherwise
invokeRoute()returns401without running the handler. Requests reaching an MCP tool through a Mastra server adapter carry this context. - Authorization hooks see the HTTP path.
authorize()andrulesreceive the route's path under the server'sapiPrefix(/apiby default), with path parameters filled in, and the route's method.authorize()gets no adapter-specific request context. - Only JSON routes are supported.
invokeRoute()throws for routes with any otherresponseType, such as streaming or MCP transport routes. - HTTP-only handler parameters aren't supplied. The handler receives the parsed parameters,
mastra,requestContext, andabortSignal, but notrequest,registeredTools,taskStore, orroutePrefix. Routes that read those aren't suitable.
Differences from dispatchRoute()Direct link to differences-from-dispatchroute
dispatchRoute() runs the same checks for any route, including streaming routes, and differs in these ways:
invokeRoute()always needs an authenticated user when auth is configured.dispatchRoute()lets a caller without a user reach paths your auth config declares public.invokeRoute()builds the path forauthorize()andrulesfrom the server'sapiPrefix.dispatchRoute()uses the prefix of the server adapter that serves the route.invokeRoute()lets a body field override a path parameter with the same name, as the HTTP adapters do.dispatchRoute()lets the path parameter win.invokeRoute()returns{ status, body }.dispatchRoute()returns the handler's raw result, or a status and error body when a check fails.