Skip to main content

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 example
Direct link to Usage example

src/mastra/tools/metric-aggregate.ts
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
},
})

Import
Direct link to Import

import { invokeRoute } from '@mastra/server/server-adapter'

Signature
Direct link to Signature

function invokeRoute(route: ServerRoute, options: InvokeRouteOptions): Promise<InvokeRouteResult>

Parameters
Direct link to Parameters

route:

ServerRoute
The route to run, such as one created with `createRoute()` or exported from @mastra/server/handlers/*. Must have responseType: 'json'.

options.mastra:

Mastra
The Mastra instance the route runs against.

options.requestContext:

RequestContext
The caller's request context, already authenticated by Mastra server auth. Its user, permissions, and auth mode decide what the caller may do.

options.pathParams?:

Record<string, string>
Path parameters, validated against the route's pathParamSchema.

options.query?:

Record<string, string | string[]>
Query parameters, validated against the route's queryParamSchema. Use an array for a repeated key.

options.body?:

unknown
Request body, validated against the route's bodySchema.

options.abortSignal?:

AbortSignal
Cancels the route handler.

Returns
Direct link to Returns

status:

number
The HTTP status the route would have answered with, such as 200, 400, 401, or 403.

body:

unknown
The route's response body, or an error body when a check fails or the handler throws.

Failed checks and errors thrown by the handler are returned as a status and body, not thrown.

Behavior
Direct 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() returns 401 without running the handler. Requests reaching an MCP tool through a Mastra server adapter carry this context.
  • Authorization hooks see the HTTP path. authorize() and rules receive the route's path under the server's apiPrefix (/api by 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 other responseType, such as streaming or MCP transport routes.
  • HTTP-only handler parameters aren't supplied. The handler receives the parsed parameters, mastra, requestContext, and abortSignal, but not request, registeredTools, taskStore, or routePrefix. Routes that read those aren't suitable.