@mastra/server 1.84.0-alpha.2 → 1.84.0-alpha.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{agent-builder-DYu--54x.js → agent-builder-D9rubwk0.js} +2 -2
- package/dist/{agent-builder-DYu--54x.js.map → agent-builder-D9rubwk0.js.map} +1 -1
- package/dist/{agent-builder-CMAT5xu8.cjs → agent-builder-DHqHFO5d.cjs} +2 -2
- package/dist/{agent-builder-CMAT5xu8.cjs.map → agent-builder-DHqHFO5d.cjs.map} +1 -1
- package/dist/{api-schema-manifest-DyOyIk-C.cjs → api-schema-manifest-AltoM-cn.cjs} +2 -2
- package/dist/{api-schema-manifest-DyOyIk-C.cjs.map → api-schema-manifest-AltoM-cn.cjs.map} +1 -1
- package/dist/{api-schema-manifest-MtnJy994.js → api-schema-manifest-D1A2zfm3.js} +2 -2
- package/dist/{api-schema-manifest-MtnJy994.js.map → api-schema-manifest-D1A2zfm3.js.map} +1 -1
- package/dist/{catalogue-oK_QSBRh.cjs → catalogue-BW2a1gu4.cjs} +3 -3
- package/dist/{catalogue-oK_QSBRh.cjs.map → catalogue-BW2a1gu4.cjs.map} +1 -1
- package/dist/{catalogue-BdR5h6fv.js → catalogue-DPLsw3zE.js} +3 -3
- package/dist/{catalogue-BdR5h6fv.js.map → catalogue-DPLsw3zE.js.map} +1 -1
- package/dist/{dist-4o3EGZcG.js → dist-CMgUx8hS.js} +102 -22
- package/dist/{dist-4o3EGZcG.js.map → dist-CMgUx8hS.js.map} +1 -1
- package/dist/{dist-p7VXVmE_.cjs → dist-D2zyg15_.cjs} +102 -22
- package/dist/{dist-p7VXVmE_.cjs.map → dist-D2zyg15_.cjs.map} +1 -1
- package/dist/dist-HNpJc8bT.js +1 -0
- package/dist/{dist-DXhZqfZZ.cjs → dist-ToffHjwd.cjs} +1 -1
- package/dist/docs/SKILL.md +1 -1
- package/dist/docs/assets/SOURCE_MAP.json +1 -1
- package/dist/{probe-image-size-DmttstPc.cjs → probe-image-size--ACsCqf-.cjs} +2 -2
- package/dist/{probe-image-size-DmttstPc.cjs.map → probe-image-size--ACsCqf-.cjs.map} +1 -1
- package/dist/{probe-image-size-IIGl_zRY.js → probe-image-size-CxVMV0gk.js} +2 -2
- package/dist/{probe-image-size-IIGl_zRY.js.map → probe-image-size-CxVMV0gk.js.map} +1 -1
- package/dist/{routes-DAnFdADa.js → routes-CH5SQLu2.js} +3 -3
- package/dist/{routes-DAnFdADa.js.map → routes-CH5SQLu2.js.map} +1 -1
- package/dist/{routes-6lsEmZwB.cjs → routes-bWCQflz5.cjs} +3 -3
- package/dist/{routes-6lsEmZwB.cjs.map → routes-bWCQflz5.cjs.map} +1 -1
- package/dist/server/handlers/agent-builder.cjs +1 -1
- package/dist/server/handlers/agent-builder.js +1 -1
- package/dist/server/handlers/system.cjs +1 -1
- package/dist/server/handlers/system.js +1 -1
- package/dist/server/handlers.cjs +1 -1
- package/dist/server/handlers.js +1 -1
- package/dist/server/server-adapter/index.cjs +2 -2
- package/dist/server/server-adapter/index.js +2 -2
- package/dist/{server-adapter-Dgy-iIqA.js → server-adapter-B3kR1OJs.js} +2 -2
- package/dist/{server-adapter-Dgy-iIqA.js.map → server-adapter-B3kR1OJs.js.map} +1 -1
- package/dist/{server-adapter-CbxRgDBh.cjs → server-adapter-SLljXCyr.cjs} +2 -2
- package/dist/{server-adapter-CbxRgDBh.cjs.map → server-adapter-SLljXCyr.cjs.map} +1 -1
- package/package.json +5 -5
- package/dist/dist-CecsVJCw.js +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server-adapter-Dgy-iIqA.js","names":["isProtectedFGARoute","MASTRA_RESOURCE_ID_KEY"],"sources":["../src/server/mcp/oauth.ts","../src/server/server-adapter/routes/fga-manifest.ts","../src/server/server-adapter/mcp-auth.ts","../src/server/server-adapter/mcp-disconnect.ts","../src/server/server-adapter/redact.ts","../src/server/server-adapter/serialize.ts","../src/server/server-adapter/stream-disconnect.ts","../src/server/server-adapter/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport type { IMastraAuthProvider } from '@mastra/core/server';\nimport type { ServerRoute } from '../server-adapter/routes';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { isBuiltinMCPEnabled, resolveBuiltinMCPPath } from './config';\n\n/** RFC 9728 well-known path for OAuth protected-resource metadata. */\nexport const OAUTH_PROTECTED_RESOURCE_PATH = '/.well-known/oauth-protected-resource';\n\nconst warnedAudience = new WeakSet<Mastra>();\nconst resourceValidity = new WeakMap<Mastra, boolean>();\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/** `server.auth` when it is a provider instance (only providers carry the OAuth hooks). */\nfunction getAuthProvider(mastra: Mastra): IMastraAuthProvider | undefined {\n const auth = mastra.getServer()?.auth;\n return auth && typeof (auth as IMastraAuthProvider).authenticateToken === 'function'\n ? (auth as IMastraAuthProvider)\n : undefined;\n}\n\nfunction getOAuthConfig(mastra: Mastra) {\n return mastra.getServer()?.mcp?.oauth ?? {};\n}\n\n/** RFC 9728 resource identifier: absolute https URL (http only for loopback hosts) without a fragment. */\nfunction isValidResourceUrl(resource: string): boolean {\n let url: URL;\n try {\n url = new URL(resource);\n } catch {\n return false;\n }\n if (resource.includes('#')) return false;\n return url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname));\n}\n\n/** Whether `server.mcp.oauth.resource` is unset or valid. Logs one error per instance when it isn't. */\nfunction hasValidResource(mastra: Mastra): boolean {\n const { resource } = getOAuthConfig(mastra);\n if (resource === undefined) return true;\n let valid = resourceValidity.get(mastra);\n if (valid === undefined) {\n valid = isValidResourceUrl(resource);\n resourceValidity.set(mastra, valid);\n if (!valid) {\n mastra\n .getLogger()\n ?.error(\n `server.mcp.oauth.resource \"${resource}\" is not an absolute https URL without a fragment ` +\n '(http is only allowed for localhost). OAuth discovery for the built-in MCP server is disabled. ' +\n 'Token audience checks still use this value, so MCP requests are rejected unless the token audience matches it exactly.',\n );\n }\n }\n return valid;\n}\n\nfunction isBuiltinMCPAuthenticated(mastra: Mastra): boolean {\n return Boolean(mastra.getServer()?.auth) && isBuiltinMCPEnabled(mastra);\n}\n\n/**\n * Whether OAuth discovery applies: the built-in MCP endpoint is on, requires auth, and any configured\n * `server.mcp.oauth.resource` is valid. Gates the well-known routes and the `resource_metadata` challenge.\n */\nexport function isMCPOAuthDiscoveryEnabled(mastra: Mastra): boolean {\n return isBuiltinMCPAuthenticated(mastra) && hasValidResource(mastra);\n}\n\n/**\n * Whether the built-in MCP endpoint checks token audience: `server.mcp.oauth.resource` is set. An invalid value\n * only turns discovery off; the audience is still checked against it, so a config typo fails closed.\n */\nexport function isMCPAudienceEnforced(mastra: Mastra): boolean {\n return isBuiltinMCPAuthenticated(mastra) && getOAuthConfig(mastra).resource !== undefined;\n}\n\n/** Canonical URL of the MCP endpoint: `server.mcp.oauth.resource`, else derived from the request. */\nexport function resolveMCPResource(mastra: Mastra, prefix: string, requestUrl: string): string {\n return getOAuthConfig(mastra).resource ?? `${new URL(requestUrl).origin}${prefix}${resolveBuiltinMCPPath(mastra)}`;\n}\n\n/** Absolute URL of the path-suffixed metadata document advertised in `WWW-Authenticate`. */\nexport function mcpResourceMetadataUrl(mastra: Mastra, prefix: string, requestUrl: string): string {\n const origin = new URL(getOAuthConfig(mastra).resource ?? requestUrl).origin;\n return `${origin}${OAUTH_PROTECTED_RESOURCE_PATH}${prefix}${resolveBuiltinMCPPath(mastra)}`;\n}\n\n/** RFC 9728 metadata for the built-in MCP endpoint. Unset optional fields are omitted. */\nexport function resolveMCPResourceMetadata(mastra: Mastra, prefix: string, requestUrl: string) {\n const config = getOAuthConfig(mastra);\n const hints = getAuthProvider(mastra)?.getOAuthMetadata?.();\n const authorizationServers = config.authorizationServers ?? hints?.authorizationServers;\n const scopesSupported = config.scopesSupported ?? hints?.scopesSupported;\n // Built here rather than with @mastra/mcp's helpers: @mastra/mcp is an optional peer, and discovery must work\n // (and 401s must not fail) without it.\n return {\n resource: resolveMCPResource(mastra, prefix, requestUrl),\n ...(authorizationServers?.length ? { authorization_servers: authorizationServers } : {}),\n ...(scopesSupported?.length ? { scopes_supported: scopesSupported } : {}),\n bearer_methods_supported: ['header'],\n };\n}\n\n/**\n * `WWW-Authenticate` value for a 401 from the built-in MCP endpoint (RFC 6750 §3 auth-params, quoted and escaped).\n * `resource_metadata` is only included while discovery is enabled.\n */\nexport function mcpWWWAuthenticate(\n mastra: Mastra,\n prefix: string,\n requestUrl: string,\n error?: { error: string; error_description?: string },\n): string {\n const params = {\n ...(isMCPOAuthDiscoveryEnabled(mastra)\n ? { resource_metadata: mcpResourceMetadataUrl(mastra, prefix, requestUrl) }\n : {}),\n ...error,\n };\n const quoted = Object.entries(params)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => `${key}=\"${value!.replace(/[\\\\\"]/g, '\\\\$&')}\"`);\n return `Bearer ${quoted.join(', ')}`;\n}\n\ntype CompositeProvider = IMastraAuthProvider & {\n getProviders?: () => readonly IMastraAuthProvider[];\n getAuthenticatedProvider?: (user: unknown) => IMastraAuthProvider | undefined;\n};\n\n/** The innermost provider that authenticated `user`, looking through `CompositeAuth`. Undefined when unknown. */\nfunction authenticatingLeaf(provider: IMastraAuthProvider, user: unknown): IMastraAuthProvider | undefined {\n const composite = provider as CompositeProvider;\n if (typeof composite.getAuthenticatedProvider !== 'function') return provider;\n const inner = composite.getAuthenticatedProvider(user);\n return inner && authenticatingLeaf(inner, user);\n}\n\n/**\n * When `server.mcp.oauth.resource` is set, the token's audience must include it. A provider that can't check the\n * audience is accepted, unless `requireAudience` is on: then the request is rejected.\n */\nexport async function checkMCPAudience(mastra: Mastra, user: unknown): Promise<boolean> {\n const { resource, requireAudience } = getOAuthConfig(mastra);\n if (resource === undefined) return true;\n const provider = getAuthProvider(mastra);\n if (requireAudience) {\n const leaf = provider && authenticatingLeaf(provider, user);\n if (typeof leaf?.verifyAudience !== 'function') return false;\n }\n if (typeof provider?.verifyAudience !== 'function') return true;\n return provider.verifyAudience(user, resource);\n}\n\nfunction leafProviders(provider: IMastraAuthProvider): IMastraAuthProvider[] {\n const inner = (provider as CompositeProvider).getProviders?.();\n return inner ? inner.flatMap(leafProviders) : [provider];\n}\n\n/** Warns once when `server.mcp.oauth.resource` is set but some provider cannot check token audience. */\nexport function warnOnUnenforcedMCPAudience(mastra: Mastra): void {\n if (warnedAudience.has(mastra) || getOAuthConfig(mastra).resource === undefined) return;\n warnedAudience.add(mastra);\n const auth = mastra.getServer()?.auth;\n if (!auth) return;\n const provider = getAuthProvider(mastra);\n const unenforced = provider\n ? leafProviders(provider)\n .filter(p => typeof p.verifyAudience !== 'function')\n .map(p => p.name || 'server.auth')\n : ['server.auth'];\n if (!unenforced.length) return;\n const consequence = getOAuthConfig(mastra).requireAudience\n ? 'requireAudience is on, so MCP requests authenticated by them are rejected.'\n : 'MCP requests authenticated by them are accepted for any audience. Set server.mcp.oauth.requireAudience to reject them.';\n mastra\n .getLogger()\n ?.warn(\n `server.mcp.oauth.resource is set, but ${unenforced.join(', ')} cannot check the token audience: ${consequence}`,\n );\n}\n\n/**\n * Public routes serving the metadata at `/.well-known/oauth-protected-resource` and its path-suffixed\n * form for the MCP endpoint. Mounted at the server root (outside the API prefix), not in SERVER_ROUTES.\n */\nexport function createMCPOAuthMetadataRoutes(mastra: Mastra, prefix: string): ServerRoute[] {\n const paths = [\n OAUTH_PROTECTED_RESOURCE_PATH,\n `${OAUTH_PROTECTED_RESOURCE_PATH}${prefix}${resolveBuiltinMCPPath(mastra)}`,\n ];\n return paths.map(path =>\n createRoute({\n method: 'GET',\n path,\n // A Response so the metadata can carry `Cache-Control: no-store` (its `resource` may echo the Host header).\n responseType: 'datastream-response',\n summary: 'OAuth protected-resource metadata',\n description: 'RFC 9728 metadata for the built-in MCP endpoint',\n tags: ['MCP'],\n requiresAuth: false,\n handler: async ({ mastra, request }) =>\n Response.json(resolveMCPResourceMetadata(mastra, prefix, request?.url ?? `http://localhost${path}`), {\n headers: { 'Cache-Control': 'no-store' },\n }),\n }),\n );\n}\n","import type { FGARouteConfig, MastraFGAPermissionInput } from '@mastra/core/auth/ee';\n\nimport { MASTRA_RESOURCE_ID_KEY } from '../../constants';\nimport { getEffectivePermission } from './permissions';\nimport type { ServerRoute } from './index';\n\nfunction isProtectedFGARoute(route: Pick<ServerRoute, 'requiresAuth'>): boolean {\n return route.requiresAuth !== false;\n}\n\nfunction getToolRoutePermission(path: string): MastraFGAPermissionInput {\n return path.includes('/execute') ? 'tools:execute' : 'tools:read';\n}\n\nfunction getAgentToolResourceId(agentId: string, toolId: string): string {\n return `${agentId}:${toolId}`;\n}\n\nfunction getMCPToolResourceId(serverId: string, toolId: string): string {\n return JSON.stringify([serverId, toolId]);\n}\n\nconst STORED_ROUTE_FGA: Record<string, { resourceType: string; idParams: string[] }> = {\n agents: { resourceType: 'stored-agents', idParams: ['storedAgentId', 'agentId'] },\n 'mcp-clients': { resourceType: 'stored-mcp-clients', idParams: ['storedMCPClientId', 'mcpClientId'] },\n 'prompt-blocks': { resourceType: 'stored-prompt-blocks', idParams: ['storedPromptBlockId', 'promptBlockId'] },\n scorers: { resourceType: 'stored-scorers', idParams: ['storedScorerId', 'scorerId'] },\n skills: { resourceType: 'stored-skills', idParams: ['storedSkillId'] },\n workspaces: { resourceType: 'stored-workspaces', idParams: ['storedWorkspaceId'] },\n};\n\nfunction getStoredResourceRouteFGAConfig(path: string, permission: MastraFGAPermissionInput): FGARouteConfig | null {\n const match = path.match(/^\\/stored\\/([^/]+)/);\n if (!match?.[1]) {\n return null;\n }\n\n const config = STORED_ROUTE_FGA[match[1]];\n if (!config) {\n return null;\n }\n\n return {\n resourceType: config.resourceType,\n resourceId: (params, { requestContext }) => {\n for (const idParam of config.idParams) {\n const id = params[idParam];\n if (typeof id === 'string' && id) {\n return id;\n }\n }\n\n const scopedResourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY);\n return typeof scopedResourceId === 'string' && scopedResourceId ? scopedResourceId : config.resourceType;\n },\n permission,\n };\n}\n\nexport function getBuiltInRouteFGAConfig(route: ServerRoute): FGARouteConfig | null {\n if (!isProtectedFGARoute(route) || !route.path || !route.method) {\n return null;\n }\n\n const permission = getEffectivePermission(route) as MastraFGAPermissionInput | null;\n if (!permission) {\n return null;\n }\n\n const path = route.path;\n const storedRouteConfig = getStoredResourceRouteFGAConfig(path, permission);\n if (storedRouteConfig) {\n return storedRouteConfig;\n }\n\n if (path.startsWith('/agents/:agentId/tools/:toolId')) {\n return {\n resourceType: 'tool',\n resourceId: ({ agentId, toolId }) => getAgentToolResourceId(String(agentId), String(toolId)),\n permission: getToolRoutePermission(path),\n };\n }\n\n if (path.startsWith('/agents/:agentId')) {\n return { resourceType: 'agent', resourceIdParam: 'agentId', permission };\n }\n\n if (path.startsWith('/workflows/:workflowId')) {\n return { resourceType: 'workflow', resourceIdParam: 'workflowId', permission };\n }\n\n if (path.startsWith('/tools/:toolId')) {\n return { resourceType: 'tool', resourceIdParam: 'toolId', permission };\n }\n\n if (path.startsWith('/mcp/:serverId/tools/:toolId')) {\n return {\n resourceType: 'tool',\n resourceId: ({ serverId, toolId }) => getMCPToolResourceId(String(serverId), String(toolId)),\n permission: getToolRoutePermission(path),\n };\n }\n\n if (path.startsWith('/mcp/:serverId')) {\n return { resourceType: 'mcp', resourceIdParam: 'serverId', permission };\n }\n\n if (path.startsWith('/knowledge/:knowledgeKey')) {\n return { resourceType: 'knowledge', resourceIdParam: 'knowledgeKey', permission };\n }\n\n if (path.startsWith('/memory/threads/:threadId') || path.startsWith('/memory/network/threads/:threadId')) {\n return { resourceType: 'thread', resourceIdParam: 'threadId', permission };\n }\n\n if (path === '/memory/threads' || path === '/memory/network/threads') {\n return {\n resourceType: 'thread',\n resourceId: ({ threadId, resourceId }) => {\n if (typeof threadId === 'string') return threadId;\n return typeof resourceId === 'string' ? resourceId : undefined;\n },\n permission,\n };\n }\n\n if (path === '/memory/save-messages' || path === '/memory/network/save-messages') {\n return {\n resourceType: 'thread',\n resourceId: ({ messages }) => {\n if (!Array.isArray(messages)) return undefined;\n const threadId = messages.find(\n message => message && typeof message === 'object' && 'threadId' in message,\n )?.threadId;\n return typeof threadId === 'string' ? threadId : undefined;\n },\n permission,\n };\n }\n\n // Same identity the handler checks: the caller's context resource wins over a requested resourceId.\n if (path === '/memory/working-memory') {\n return {\n resourceType: 'resource',\n resourceId: ({ resourceId }, { requestContext }) => {\n const contextResourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY);\n if (typeof contextResourceId === 'string' && contextResourceId) return contextResourceId;\n return typeof resourceId === 'string' ? resourceId : undefined;\n },\n permission,\n };\n }\n\n if (path === '/v1/responses') {\n return { resourceType: 'agent', resourceIdParam: 'agent_id', permission };\n }\n\n if (path.startsWith('/v1/responses/:responseId')) {\n return { resourceType: 'response', resourceIdParam: 'responseId', permission };\n }\n\n if (path === '/v1/conversations') {\n return { resourceType: 'agent', resourceIdParam: 'agent_id', permission };\n }\n\n if (path.startsWith('/v1/conversations/:conversationId')) {\n return { resourceType: 'conversation', resourceIdParam: 'conversationId', permission };\n }\n\n return null;\n}\n","import type { IncomingMessage } from 'node:http';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport { MASTRA_AUTH_TOKEN_KEY, MASTRA_USER_KEY, RESERVED_REQUEST_CONTEXT_KEYS } from '../constants';\n\n/**\n * Key under which `applyMcpRequestAuth` attaches the trusted request context to\n * `req.auth`. `@mastra/mcp` reads the same registered symbol and copies the\n * values into the request context its tools receive. A symbol cannot come out\n * of a token or JSON payload, so only server code can supply it.\n */\nexport const MCP_TRUSTED_REQUEST_CONTEXT = Symbol.for('mastra.mcp.trustedRequestContext');\n\n/**\n * Shape the MCP SDK expects on `req.auth`.\n */\nexport interface McpAuthInfo {\n token: string;\n clientId: string;\n scopes: string[];\n extra?: Record<string, unknown>;\n}\n\n/**\n * Hook that sets `req.auth` before the MCP transport reads it.\n *\n * Receives the Node request handed to the MCP transport plus the Mastra\n * request context, which carries whatever server auth or your own middleware\n * resolved for this request. Setting `req.auth` is the caller's job; leaving it\n * unset is an explicit opt-out of the default bridge.\n *\n * The hook only owns `authInfo`. Whenever `req.auth` ends up set, the reserved\n * request context values (user, permissions, roles, resource, organization)\n * are still attached to it, so tools' `requestContext` reflects Mastra server\n * auth even if the hook's `authInfo` names a different principal.\n */\nexport type SetMcpRequestAuth = (req: IncomingMessage, requestContext: RequestContext) => void | Promise<void>;\n\nfunction normalizeScopes(value: unknown): string[] {\n if (Array.isArray(value)) return value.filter((s): s is string => typeof s === 'string');\n if (typeof value === 'string') return value.split(/[\\s,]+/).filter(Boolean);\n return [];\n}\n\nfunction resolveClientId(user: Record<string, unknown>): string {\n for (const key of ['id', 'sub', 'userId', 'email']) {\n const value = user[key];\n if (typeof value === 'string' && value) return value;\n }\n return '';\n}\n\n/**\n * Build the default `AuthInfo` from the Mastra request context.\n *\n * Returns `undefined` when the request carries no identity at all, so servers\n * without auth keep behaving exactly as before.\n */\nexport function buildMcpAuthInfoFromRequestContext(requestContext: RequestContext): McpAuthInfo | undefined {\n const user = requestContext.get(MASTRA_USER_KEY);\n const token = requestContext.get(MASTRA_AUTH_TOKEN_KEY);\n const hasUser = !!user && typeof user === 'object';\n const hasToken = typeof token === 'string' && token.length > 0;\n\n if (!hasUser && !hasToken) return undefined;\n\n const userRecord = (hasUser ? user : {}) as Record<string, unknown>;\n\n return {\n token: hasToken ? token : '',\n clientId: resolveClientId(userRecord),\n scopes: normalizeScopes(userRecord.scopes ?? userRecord.scope ?? userRecord.permissions),\n ...(hasUser ? { extra: { user: userRecord } } : {}),\n };\n}\n\n/**\n * Populate `req.auth` on the Node request that is about to be handed to an MCP\n * transport.\n *\n * Resolution order:\n * 1. An already-set `req.auth` keeps its identity.\n * 2. A configured `setRequestAuth` hook runs and fully owns the result.\n * 3. Otherwise the principal resolved by Mastra server auth is bridged from the\n * request context using the default mapping.\n *\n * Whichever way `req.auth` is set, the trusted request context is attached to\n * it so MCP tools see the same principal as Mastra routes.\n */\nexport async function applyMcpRequestAuth({\n req,\n requestContext,\n setRequestAuth,\n}: {\n req: IncomingMessage;\n requestContext?: RequestContext;\n setRequestAuth?: SetMcpRequestAuth;\n}): Promise<void> {\n const request = req as IncomingMessage & { auth?: unknown };\n if (!requestContext) return;\n\n if (!request.auth) {\n if (setRequestAuth) {\n await setRequestAuth(req, requestContext);\n } else {\n const authInfo = buildMcpAuthInfoFromRequestContext(requestContext);\n if (authInfo) request.auth = authInfo;\n }\n }\n\n if (request.auth && typeof request.auth === 'object') {\n attachTrustedRequestContext(request.auth, requestContext);\n }\n}\n\n/**\n * Hands MCP tools the values Mastra server auth resolved for this request\n * (user, permissions, roles, resource id, tenant, auth mode), so a tool called\n * over MCP is authorized the same way as the matching HTTP route. The token is\n * left out; it is already on `authInfo`.\n */\nfunction attachTrustedRequestContext(auth: object, requestContext: RequestContext): void {\n const trusted: Record<string, unknown> = {};\n for (const key of RESERVED_REQUEST_CONTEXT_KEYS) {\n if (key === MASTRA_AUTH_TOKEN_KEY || !requestContext.has(key)) continue;\n trusted[key] = requestContext.get(key);\n }\n Object.defineProperty(auth, MCP_TRUSTED_REQUEST_CONTEXT, { value: trusted, configurable: true });\n}\n","/**\n * Forwards a fetch `Request` abort to the simulated Node response used by fetch-based\n * adapters (Hono, Elysia, Next) to drive the MCP Node transport.\n *\n * `fetch-to-node`'s `toReqRes` ignores `Request.signal`, and the MCP Node transport only\n * aborts an in-flight request when `res` emits `close`. Without this, a client that\n * disconnects before any response bytes are sent leaves the tool call running to completion.\n *\n * Call it after `startHTTP` has been invoked so the transport's `close` listener is attached.\n */\nexport function propagateRequestAbort(\n signal: AbortSignal | undefined,\n res: {\n emit: (event: string) => boolean | void;\n once: (event: string, listener: () => void) => unknown;\n writableFinished?: boolean;\n },\n): void {\n if (!signal) return;\n\n const onAbort = () => {\n if (res.writableFinished) return;\n try {\n res.emit('close');\n } catch {\n // Already torn down - nothing left to abort.\n }\n };\n\n if (signal.aborted) {\n onAbort();\n return;\n }\n\n signal.addEventListener('abort', onAbort, { once: true });\n res.once('finish', () => signal.removeEventListener('abort', onAbort));\n}\n","import type { ChunkType } from '@mastra/core/stream';\n\n/**\n * Redacts request data from a v2 format payload.\n * Removes `metadata.request` and `output.steps[].request` from the payload.\n */\nfunction redactV2Payload(payload: Record<string, unknown>): Record<string, unknown> {\n const redactedPayload = { ...payload };\n\n // Remove metadata.request\n if (redactedPayload.metadata && typeof redactedPayload.metadata === 'object') {\n const { request, ...metadataRest } = redactedPayload.metadata as Record<string, unknown>;\n redactedPayload.metadata = metadataRest;\n }\n\n // Remove request from output.steps[]\n if (redactedPayload.output && typeof redactedPayload.output === 'object') {\n const output = { ...(redactedPayload.output as Record<string, unknown>) };\n if (Array.isArray(output.steps)) {\n output.steps = output.steps.map((step: Record<string, unknown>) => {\n if (step && typeof step === 'object') {\n const { request, ...stepRest } = step;\n return stepRest;\n }\n return step;\n });\n }\n redactedPayload.output = output;\n }\n\n return redactedPayload;\n}\n\n/**\n * Redacts sensitive data from stream chunks before they are sent to clients.\n *\n * This function strips out request bodies that may contain sensitive information\n * such as system prompts, tool definitions, API keys, and other configuration data.\n *\n * Handles both v1 (legacy) and v2 stream formats:\n *\n * v1 format (fields at root level):\n * - `step-start.request` - Contains the full LLM request body\n * - `step-finish.request` - Contains the request body\n * - `finish.request` - Contains the request body (if present)\n *\n * v2 format (fields nested in payload):\n * - `step-start.payload.request` - Contains the full LLM request body\n * - `step-finish.payload.metadata.request` - Contains the request metadata\n * - `step-finish.payload.output.steps[].request` - Contains request data for each step\n * - `finish.payload.metadata.request` - Contains the request metadata\n * - `finish.payload.output.steps[].request` - Contains request data for each step\n *\n * @param chunk - The stream chunk to redact\n * @returns A new chunk with sensitive data removed, or the original chunk if no redaction needed\n */\nexport function redactStreamChunk<OUTPUT = undefined>(chunk: ChunkType<OUTPUT>): ChunkType<OUTPUT> {\n if (!chunk || typeof chunk !== 'object') {\n return chunk;\n }\n\n const typedChunk = chunk as Record<string, unknown>;\n\n switch (chunk.type) {\n case 'step-start': {\n // Check if this is v2 format (has payload) or v1 format (request at root)\n if ('payload' in typedChunk && typedChunk.payload && typeof typedChunk.payload === 'object') {\n // v2 format: Remove request from payload\n const { payload, ...rest } = typedChunk;\n const { request, ...payloadRest } = payload as Record<string, unknown>;\n return {\n ...rest,\n type: 'step-start',\n payload: {\n ...payloadRest,\n // Keep an empty request object to maintain structure but remove body\n request: {},\n },\n } as ChunkType<OUTPUT>;\n } else if ('request' in typedChunk) {\n // v1 format: Remove request at root level\n const { request, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'step-start',\n // Keep an empty request object to maintain structure\n request: {},\n } as unknown as ChunkType<OUTPUT>;\n }\n return chunk;\n }\n\n case 'step-finish': {\n // Check if this is v2 format (has payload) or v1 format (request at root)\n if ('payload' in typedChunk && typedChunk.payload && typeof typedChunk.payload === 'object') {\n // v2 format: Remove request from metadata and output.steps[].request\n const { payload, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'step-finish',\n payload: redactV2Payload(payload as Record<string, unknown>),\n } as ChunkType<OUTPUT>;\n } else if ('request' in typedChunk) {\n // v1 format: Remove request at root level\n const { request, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'step-finish',\n } as unknown as ChunkType<OUTPUT>;\n }\n return chunk;\n }\n\n case 'finish': {\n // Check if this is v2 format (has payload) or v1 format (request at root)\n if ('payload' in typedChunk && typedChunk.payload && typeof typedChunk.payload === 'object') {\n // v2 format: Remove request from metadata and output.steps[].request\n const { payload, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'finish',\n payload: redactV2Payload(payload as Record<string, unknown>),\n } as ChunkType<OUTPUT>;\n } else if ('request' in typedChunk) {\n // v1 format: Remove request at root level\n const { request, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'finish',\n } as unknown as ChunkType<OUTPUT>;\n }\n return chunk;\n }\n\n default:\n // Other chunk types don't contain sensitive request data\n return chunk;\n }\n}\n","import { safeStringify } from '@mastra/core/utils';\n\nexport type SerializedStreamChunk = { ok: true; json: string } | { ok: false; error: Error };\n\n/**\n * Serializes a stream chunk to JSON for wire transport.\n *\n * Stream chunks can contain values that plain `JSON.stringify` throws on\n * (e.g. BigInt produced by zod coercions/transforms in structuredOutput\n * schemas, or circular references) — `safeStringify` handles those. A single\n * bad chunk must never kill the whole stream — Studio relies on later chunks\n * (`workflow-step-result`, `workflow-finish`) to render run state.\n *\n * Returns `{ ok: false, error }` if the chunk cannot be serialized at all\n * (e.g. a throwing getter/toJSON) — callers should log the error, skip the\n * chunk, and keep streaming.\n */\nexport function serializeStreamChunk(chunk: unknown): SerializedStreamChunk {\n try {\n return { ok: true, json: safeStringify(withPlainPayloadError(chunk)) };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * `JSON.stringify(new Error('x'))` keeps only own enumerable fields, so an Error subclass that sets `name`\n * arrives as `{ name }` and clients show `[object Object]`. Send the message too; never the stack. An\n * error whose class curates its JSON (`toJSON`, e.g. MastraError) keeps that shape, so fields it leaves\n * out stay out.\n */\nfunction withPlainPayloadError(chunk: unknown): unknown {\n if (!chunk || typeof chunk !== 'object' || !('payload' in chunk)) return chunk;\n const { payload } = chunk;\n if (!payload || typeof payload !== 'object' || !('error' in payload)) return chunk;\n const { error } = payload;\n if (!(error instanceof Error)) return withoutStack(chunk, payload, error);\n const plain: Record<string, unknown> = { ...(curatedJson(error) ?? error), message: error.message };\n delete plain.stack;\n if (!plain.name && error.name !== 'Error') plain.name = error.name;\n return { ...chunk, payload: { ...payload, error: plain } };\n}\n\n/** An error that is already a plain object (a replayed one) is kept as is, minus its stack. */\nfunction withoutStack(chunk: object, payload: object, error: unknown): unknown {\n if (!error || typeof error !== 'object' || Array.isArray(error) || !('stack' in error)) return chunk;\n const { stack: _stack, ...rest } = error as Record<string, unknown>;\n return { ...chunk, payload: { ...payload, error: rest } };\n}\n\nfunction curatedJson(error: Error): Record<string, unknown> | undefined {\n const toJSON = (error as { toJSON?: unknown }).toJSON;\n if (typeof toJSON !== 'function') return undefined;\n try {\n const json: unknown = toJSON.call(error);\n return json && typeof json === 'object' ? (json as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n","interface NodeResponseLike {\n on(event: 'close' | 'drain', listener: () => void): unknown;\n off(event: 'close' | 'drain', listener: () => void): unknown;\n write(chunk: any): boolean;\n destroyed?: boolean;\n}\n\n/**\n * Cancels `reader` once when the Node response closes, so a disconnected client stops the upstream stream.\n *\n * Cancels right away when the response is already destroyed: if the client dropped while the route handler\n * was still running, `close` fired before this listener existed. Call `dispose()` before ending the response\n * so the close that follows a normal end does not cancel.\n */\nexport function cancelReaderOnResponseClose(\n reader: ReadableStreamDefaultReader<unknown>,\n res: NodeResponseLike,\n): { cancel: (reason: string) => void; dispose: () => void } {\n let canceled = false;\n const cancel = (reason: string) => {\n if (canceled) {\n return;\n }\n\n canceled = true;\n void reader.cancel(reason).catch(() => {});\n };\n const onClose = () => cancel('request aborted');\n res.on('close', onClose);\n\n if (res.destroyed) {\n onClose();\n }\n\n return { cancel, dispose: () => res.off('close', onClose) };\n}\n\n// Writes waiting for `drain`, per response. Each response gets one `drain` and one `close` listener for its whole life\n// instead of one pair per wait: the `compression` middleware forwards `res.on('drain')` to its zlib stream but not\n// `res.off`, so a listener removed after every wait would still pile up there.\nconst pendingWrites = new WeakMap<NodeResponseLike, Array<() => void>>();\n\nfunction getPendingWrites(res: NodeResponseLike): Array<() => void> {\n const existing = pendingWrites.get(res);\n\n if (existing) {\n return existing;\n }\n\n const queue: Array<() => void> = [];\n const release = () => {\n for (const resolve of queue.splice(0)) resolve();\n };\n res.on('drain', release);\n res.on('close', release);\n pendingWrites.set(res, queue);\n return queue;\n}\n\n/**\n * Writes `chunk` and, when the socket buffer is full, waits for `drain` so a slow client pauses reads from the\n * upstream stream instead of growing the buffer. Resolves on `close` too, so a dropped client never stalls the caller.\n */\nexport async function writeWithBackpressure(res: NodeResponseLike, chunk: unknown): Promise<void> {\n if (res.write(chunk) !== false || res.destroyed) {\n return;\n }\n\n await new Promise<void>(resolve => getPendingWrites(res).push(resolve));\n}\n","import { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport { hasPermission } from '@mastra/core/auth/ee';\nimport type { FGARouteConfig, FGARouteInfo, IFGAProvider, MastraFGAPermissionInput } from '@mastra/core/auth/ee';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { MastraServerBase } from '@mastra/core/server';\nimport type {\n ApiRoute,\n HttpLoggingConfig,\n MastraAuthConfig,\n ValidationErrorContext,\n ValidationErrorResponse,\n} from '@mastra/core/server';\nimport type { ExecutionContext } from 'hono';\nimport { Hono } from 'hono';\nimport type { ZodError } from 'zod/v4';\nimport { z } from 'zod/v4';\n\nimport type { InMemoryTaskStore } from '../a2a/store';\nimport { CustomRouteMatcher } from '../auth/custom-route-matcher';\nimport {\n authorizeAuthenticatedUser,\n coreAuthMiddleware,\n findMatchingCustomRoute,\n canAccessPublicly,\n isCustomRoutePublic,\n isProtectedCustomRoute,\n pathMatchesPattern,\n} from '../auth/helpers';\nimport {\n MASTRA_AUTH_MODE_KEY,\n MASTRA_AUTH_TOKEN_KEY,\n MASTRA_CLIENT_TYPE_HEADER,\n MASTRA_IS_STUDIO_KEY,\n MASTRA_USER_KEY,\n MASTRA_USER_PERMISSIONS_KEY,\n isReservedRequestContextKey,\n isStudioClientTypeHeader,\n} from '../constants';\nimport type { MastraAuthMode } from '../constants';\nimport { formatZodError, isZodError } from '../handlers/error';\nimport { HTTPException } from '../http-exception';\nexport { isZodError, type ZodErrorLike } from '../handlers/error';\nimport {\n checkMCPAudience,\n createMCPOAuthMetadataRoutes,\n isMCPAudienceEnforced,\n isMCPOAuthDiscoveryEnabled,\n mcpWWWAuthenticate,\n warnOnUnenforcedMCPAudience,\n} from '../mcp/oauth';\nimport { resolveServerRoute } from '../mcp/route';\nimport { normalizeRoutePath } from '../utils';\nimport type { SetMcpRequestAuth } from './mcp-auth';\nimport { generateOpenAPIDocument, convertCustomRoutesToOpenAPIPaths } from './openapi-utils';\nimport type { ServerContext, ServerRoute } from './routes';\nimport { OPT_IN_ROUTES, SERVER_ROUTES, getEffectivePermission } from './routes';\nimport { getBuiltInRouteFGAConfig } from './routes/fga-manifest';\n\nexport * from './routes';\nexport { applyMcpRequestAuth, buildMcpAuthInfoFromRequestContext } from './mcp-auth';\nexport type { McpAuthInfo, SetMcpRequestAuth } from './mcp-auth';\nexport { propagateRequestAbort } from './mcp-disconnect';\nexport { BUILTIN_MCP_HTTP_ROUTE, resolveServerRoute } from '../mcp/route';\nexport {\n checkMCPAudience,\n createMCPOAuthMetadataRoutes,\n isMCPAudienceEnforced,\n isMCPOAuthDiscoveryEnabled,\n mcpWWWAuthenticate,\n} from '../mcp/oauth';\nexport { convertCustomRoutesToOpenAPIPaths } from './openapi-utils';\nexport { redactStreamChunk } from './redact';\nexport { serializeStreamChunk, type SerializedStreamChunk } from './serialize';\nexport { cancelReaderOnResponseClose, writeWithBackpressure } from './stream-disconnect';\nexport {\n MASTRA_AUTH_MODE_KEY,\n MASTRA_CLIENT_TYPE_HEADER,\n MASTRA_IS_STUDIO_KEY,\n MASTRA_KNOWLEDGE_PRINCIPALS_KEY,\n MASTRA_STUDIO_CLIENT_TYPE,\n RESERVED_REQUEST_CONTEXT_KEYS,\n isReservedRequestContextKey,\n isStudioClientTypeHeader,\n} from '../constants';\nexport type { MastraAuthMode } from '../constants';\n\nexport { WorkflowRegistry, normalizeRoutePath } from '../utils';\nexport { HTTPException };\n\nexport function getCustomHTTPExceptionResponse(error: unknown): Response | undefined {\n if (!(error instanceof HTTPException) || !error.res) {\n return undefined;\n }\n\n return error.getResponse();\n}\n\n/**\n * Response for an HTTPException thrown from a `registerApiRoute` handler, or undefined for\n * any other error (which callers keep behind a generic 500). Duck-typed so an HTTPException\n * from `hono/http-exception`, possibly a separate Hono install, is recognised too.\n */\nexport function getCustomRouteHTTPExceptionResponse(error: unknown): Response | undefined {\n if (!(error instanceof Error)) return undefined;\n const httpError = error as Error & { status?: unknown; res?: unknown; getResponse?: unknown };\n const status = httpError.status;\n if (\n typeof httpError.getResponse !== 'function' ||\n typeof status !== 'number' ||\n !Number.isInteger(status) ||\n status < 400 ||\n status > 599\n ) {\n return undefined;\n }\n if (httpError.res) return (httpError.getResponse as () => Response).call(httpError);\n return Response.json({ error: httpError.message }, { status });\n}\n\nexport interface HTTPErrorResponseBody {\n error: string;\n cause?: { failingItems: unknown[] } | { field: string; errors: Array<{ path: string; message: string }> };\n}\n\n/**\n * Only allowlisted causes are exposed to clients; any other cause stays server-side:\n * - `cause.failingItems` (dataset schema-update rejections)\n * - `cause.field` + `cause.errors` (schema validation failures), reduced to each error's path and message\n */\nfunction getSafeErrorCause(error: unknown): HTTPErrorResponseBody['cause'] {\n try {\n const raw = error instanceof Error ? error.cause : undefined;\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n if (Array.isArray((raw as any).failingItems)) {\n return { failingItems: (raw as any).failingItems };\n }\n const { field, errors } = raw as { field?: unknown; errors?: unknown };\n if (typeof field === 'string' && Array.isArray(errors)) {\n return {\n field,\n errors: errors.flatMap(e =>\n e && typeof e.path === 'string' && typeof e.message === 'string'\n ? [{ path: e.path, message: e.message }]\n : [],\n ),\n };\n }\n } catch {\n // property access threw (e.g. a getter) — omit cause\n }\n return undefined;\n}\n\n/**\n * Maps a handler error to the status and JSON body every adapter sends:\n * `error.status` (HTTPException) first, then `error.details.status` (MastraError), else 500.\n */\nexport function getHTTPErrorResponse(error: unknown): { status: number; body: HTTPErrorResponseBody } {\n const message = error instanceof Error ? error.message : 'Unknown error';\n\n if (error && typeof error === 'object') {\n if ('status' in error) {\n const cause = getSafeErrorCause(error);\n return { status: (error as any).status, body: { error: message, ...(cause ? { cause } : {}) } };\n }\n if ('details' in error && error.details && typeof error.details === 'object' && 'status' in error.details) {\n return { status: (error.details as any).status, body: { error: message } };\n }\n }\n\n return { status: 500, body: { error: message } };\n}\n\n/**\n * Hono/adapter context key set by the framework-public middleware.\n *\n * When true, the current request targets a route the framework has declared\n * public (via `createPublicRoute()` / `requiresAuth: false`). Adapter authors\n * MUST short-circuit any user-registered middleware for such requests so that\n * users cannot accidentally (or intentionally) 401 routes the framework needs\n * to keep reachable (e.g. Studio sign-in endpoints).\n */\nexport const MASTRA_FRAMEWORK_PUBLIC_KEY = '__mastraFrameworkPublic';\n\n/**\n * A pre-computed matcher that returns true if a given (path, method) targets a\n * route the framework has declared public via `requiresAuth: false`.\n *\n * Built once at server-adapter registration time from `SERVER_ROUTES` and the\n * `customRouteAuthConfig` map. Called by each adapter's context middleware to\n * stash a boolean on the per-request context under `MASTRA_FRAMEWORK_PUBLIC_KEY`.\n */\nexport type FrameworkPublicMatcher = (path: string, method: string) => boolean;\n\nexport interface OpenAPIConfig {\n title?: string;\n version?: string;\n description?: string;\n path?: string;\n}\n\nexport interface BodyLimitOptions {\n maxSize: number;\n onError: (error: unknown) => unknown;\n}\n\nexport interface StreamOptions {\n /**\n * When true (default), redacts sensitive data from stream chunks\n * (system prompts, tool definitions, API keys) before sending to clients.\n *\n * Set to false to include full request data in stream chunks (useful for\n * debugging or internal services that need access to this data).\n *\n * @default true\n */\n redact?: boolean;\n}\n\nconst AGENT_CHANNEL_WEBHOOK_PATH = /^\\/api\\/agents\\/([^/]+)\\/channels\\/([^/]+)\\/webhook\\/?$/;\n\n/**\n * MCP transport options for configuring MCP HTTP and SSE transports.\n */\nexport interface MCPOptions {\n /**\n * When true, runs in stateless mode without session management.\n * Ideal for serverless environments (Cloudflare Workers, Vercel Edge, etc.)\n * where you can't maintain persistent connections across requests.\n *\n * @default false\n */\n serverless?: boolean;\n /**\n * Custom session ID generator function.\n */\n sessionIdGenerator?: () => string;\n /**\n * Sets `req.auth` before the MCP transport reads it, which is what surfaces as\n * `extra.authInfo` inside tool and agent execution.\n *\n * When omitted, the principal resolved by `server.auth` is bridged\n * automatically. Provide this hook when your own middleware performs the\n * verification and you want full control over the resulting `AuthInfo`.\n *\n * The hook only controls `authInfo`. Tools still receive the user,\n * permissions, roles and other reserved values Mastra server auth resolved\n * in their `requestContext`, even when the hook's `authInfo` names a\n * different principal.\n */\n setRequestAuth?: SetMcpRequestAuth;\n}\n\n/**\n * Query parameter values parsed from HTTP requests.\n * Supports both single values and arrays (for repeated query params like ?tag=a&tag=b).\n */\nexport type QueryParamValue = string | string[];\n\n/**\n * Parsed request parameters returned by getParams().\n */\nexport interface ParsedRequestParams {\n urlParams: Record<string, string>;\n queryParams: Record<string, QueryParamValue>;\n body: unknown;\n /**\n * Error that occurred while parsing the request body.\n * When set, the server should return a 400 Bad Request response.\n */\n bodyParseError?: {\n message: string;\n };\n}\n\nfunction isAbortSignalError(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false;\n\n const { code, name } = error as { code?: string; name?: string };\n return name === 'AbortError' || code === 'ABORT_ERR';\n}\n\nfunction isExpectedResponseCloseError(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false;\n\n const { code } = error as { code?: string };\n return (\n code === 'ECONNRESET' ||\n code === 'EPIPE' ||\n code === 'ERR_STREAM_DESTROYED' ||\n code === 'ERR_STREAM_WRITE_AFTER_END' ||\n code === 'ERR_STREAM_PREMATURE_CLOSE'\n );\n}\n\n/**\n * Returns `response` with a pass-through body that holds the re-dispatched\n * custom route `request` until that body is fully read, errors or is cancelled.\n *\n * `new Request(url, { signal })` gives the request its own signal and forwards\n * the outer abort to it through a listener that only weakly references the\n * request's controller (nodejs/undici#4068). Once a custom route returns a\n * streaming Response, nothing else holds that inner Request, so a GC can drop\n * it and a client disconnect never reaches `c.req.raw.signal` (#29154).\n *\n * The reference lives on the body because the body is reachable exactly while\n * an adapter is still sending the response. Anything reachable from the outer\n * signal (a WeakMap keyed by it, or an abort listener on it) would leak instead:\n * undici's request finalizer holds the outer signal strongly while the inner\n * controller is alive, so signal -> request -> controller -> signal is never\n * collected when the signal never aborts, as after a normal Express response.\n * An abort ends or cancels the body, which releases the request too.\n */\nfunction retainRequestWhileBodyIsOpen(response: Response, request: Request): Response {\n const source = response.body;\n if (!source) return response;\n\n const reader = source.getReader();\n const retained: { request?: Request } = { request };\n const release = () => {\n retained.request = undefined;\n };\n const body = new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n release();\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n release();\n controller.error(error);\n }\n },\n cancel(reason) {\n release();\n return reader.cancel(reason);\n },\n },\n // Read from the route's body only when the adapter asks for a chunk.\n { highWaterMark: 0 },\n );\n return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });\n}\n\nfunction isResponseClosed(response: { writableEnded?: boolean; destroyed?: boolean }): boolean {\n return Boolean(response.writableEnded || response.destroyed);\n}\n\nfunction isProtectedFGARoute(route: Pick<ServerRoute, 'requiresAuth'>): boolean {\n return route.requiresAuth !== false;\n}\n\nfunction formatRoute(route: Pick<ServerRoute, 'method' | 'path'>): string {\n return `${route.method} ${route.path}`;\n}\n\n/** A schema-aware custom route created by `createRoute()`. */\ntype SchemaCustomApiRoute = Extract<ApiRoute, { readonly _mastraSchemaRoute: true }>;\n/** A Hono-style custom route created by `registerApiRoute()`. */\ntype HonoCustomApiRoute = Exclude<ApiRoute, SchemaCustomApiRoute>;\n\nfunction isSchemaApiRoute(route: ApiRoute): route is SchemaCustomApiRoute {\n return '_mastraSchemaRoute' in route && route._mastraSchemaRoute === true;\n}\n\nexport function getFGAProvider(mastra: any, requestContext?: RequestContext): IFGAProvider | undefined {\n // If we have request context, check auth mode to determine which FGA provider to use\n if (requestContext) {\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY);\n if (authMode === 'studio') {\n const studioFga = mastra?.getStudio?.()?.fga;\n if (studioFga) return studioFga as IFGAProvider;\n }\n }\n // Fall back to server FGA\n return mastra?.getServer?.()?.fga as IFGAProvider | undefined;\n}\n\nfunction getFGARouteInfo(route: ServerRoute): FGARouteInfo {\n return {\n path: route.path,\n method: route.method,\n requiresAuth: route.requiresAuth,\n requiresPermission: route.requiresPermission,\n fga: route.fga,\n };\n}\n\nfunction getRoutePermissions(route: ServerRoute): MastraFGAPermissionInput[] {\n return [getEffectivePermission(route), route.fga?.permission]\n .flatMap(value => (Array.isArray(value) ? value : [value]))\n .filter((permission): permission is MastraFGAPermissionInput => Boolean(permission));\n}\n\nasync function resolveRouteFGAConfig(\n fgaProvider: IFGAProvider,\n route: ServerRoute,\n requestContext: RequestContext,\n params: Record<string, unknown>,\n): Promise<FGARouteConfig | null | undefined> {\n if (route.fga) {\n return route.fga;\n }\n\n const resolvedConfig = await fgaProvider.resolveRouteFGA?.({\n route: getFGARouteInfo(route),\n params,\n requestContext,\n });\n if (resolvedConfig) {\n return resolvedConfig;\n }\n\n return getBuiltInRouteFGAConfig(route);\n}\n\nfunction getSchemaTypeName(schema: z.ZodTypeAny): string | undefined {\n const schemaDef = (schema as any)?._def ?? (schema as any)?.def;\n return schemaDef?.typeName ?? schemaDef?.type;\n}\n\nfunction unwrapOptionalNullable(schema: z.ZodTypeAny): z.ZodTypeAny {\n let inner = schema;\n let typeName = getSchemaTypeName(inner);\n\n while (\n typeName === 'ZodOptional' ||\n typeName === 'ZodNullable' ||\n typeName === 'optional' ||\n typeName === 'nullable'\n ) {\n const innerDef = (inner as any)?._def ?? (inner as any)?.def;\n if (!innerDef?.innerType) {\n return inner;\n }\n inner = innerDef.innerType;\n typeName = getSchemaTypeName(inner);\n }\n\n return inner;\n}\n\nfunction parseComplexQueryParams(\n queryParamSchema: z.ZodTypeAny,\n params: Record<string, unknown>,\n): Record<string, unknown> {\n if (!(queryParamSchema instanceof z.ZodObject)) {\n return params;\n }\n\n const parsedParams: Record<string, unknown> = { ...params };\n const shape = queryParamSchema.shape as Record<string, z.ZodTypeAny>;\n\n for (const [key, fieldSchema] of Object.entries(shape)) {\n const rawValue = parsedParams[key];\n if (typeof rawValue !== 'string') {\n continue;\n }\n\n const unwrappedField = unwrapOptionalNullable(fieldSchema);\n const typeName = getSchemaTypeName(unwrappedField);\n const isComplex =\n typeName === 'ZodObject' ||\n typeName === 'ZodArray' ||\n typeName === 'ZodRecord' ||\n typeName === 'object' ||\n typeName === 'array' ||\n typeName === 'record';\n\n if (!isComplex) {\n continue;\n }\n\n try {\n parsedParams[key] = JSON.parse(rawValue);\n } catch {\n // Keep original string; schema validation will surface a clear error.\n }\n }\n\n return parsedParams;\n}\n\n/**\n * Property names that must never be written onto objects built from untrusted\n * input: assigning them can mutate the object's prototype chain.\n */\nconst UNSAFE_OBJECT_KEYS = new Set(['__proto__', 'prototype', 'constructor']);\n\n/**\n * Returns whether `key` is safe to use as a property name when building an\n * object from untrusted input (query strings, form fields, etc.).\n */\nexport function isSafeObjectKey(key: string): boolean {\n return !UNSAFE_OBJECT_KEYS.has(key);\n}\n\n/**\n * Normalizes query parameters from various HTTP framework formats to a consistent structure.\n * Handles both single string values and arrays (for repeated query params like ?tag=a&tag=b).\n * Reconstructs bracket-notation keys (e.g., `orderBy[field]=createdAt`) into JSON strings\n * so that z.preprocess JSON.parse can handle them.\n * Filters out non-string values that some frameworks may include.\n *\n * @param rawQuery - Raw query parameters from the HTTP framework (may contain strings, arrays, or nested objects)\n * @returns Normalized query parameters as Record<string, string | string[]>\n */\nexport function normalizeQueryParams(rawQuery: Record<string, unknown>): Record<string, QueryParamValue> {\n const queryParams: Record<string, QueryParamValue> = {};\n // Collect bracket-notation keys: e.g., \"orderBy[field]\" → parent \"orderBy\", child \"field\"\n const bracketGroups: Record<string, Record<string, string>> = {};\n\n for (const [key, value] of Object.entries(rawQuery)) {\n const bracketMatch = key.match(/^([^[]+)\\[([^\\]]+)\\]$/);\n if (bracketMatch) {\n const parent = bracketMatch[1]!;\n const child = bracketMatch[2]!;\n const strValue = Array.isArray(value)\n ? value.filter((v): v is string => typeof v === 'string')[0]\n : typeof value === 'string'\n ? value\n : undefined;\n if (strValue !== undefined && isSafeObjectKey(parent) && isSafeObjectKey(child)) {\n if (!Object.hasOwn(bracketGroups, parent)) {\n bracketGroups[parent] = {};\n }\n bracketGroups[parent]![child] = strValue;\n }\n } else if (typeof value === 'string') {\n if (isSafeObjectKey(key)) {\n queryParams[key] = value;\n }\n } else if (Array.isArray(value)) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n // Filter to only string values (some frameworks include nested objects)\n const stringValues = value.filter((v): v is string => typeof v === 'string');\n // Convert single-value arrays back to strings for compatibility\n queryParams[key] = stringValues.length === 1 ? stringValues[0]! : stringValues;\n }\n }\n\n // Merge bracket groups as JSON strings (only if the parent key wasn't already set directly)\n for (const [parent, children] of Object.entries(bracketGroups)) {\n if (!Object.hasOwn(queryParams, parent)) {\n queryParams[parent] = JSON.stringify(children);\n }\n }\n\n return queryParams;\n}\n\n/**\n * Abstract base class for server adapters that handle HTTP requests.\n *\n * This class extends `MastraServerBase` to inherit app storage functionality\n * and provides the framework for registering routes, middleware, and handling requests.\n *\n * Framework-specific adapters in @mastra/hono and @mastra/express extend this class\n * (both named `MastraServer` in their respective packages) and implement the abstract\n * methods for their specific framework.\n *\n * @template TApp - The type of the server app (e.g., Hono, Express Application)\n * @template TRequest - The type of the request object\n * @template TResponse - The type of the response object\n */\nexport abstract class MastraServer<TApp, TRequest, TResponse> extends MastraServerBase<TApp> {\n /** Request bodies cannot set agent scopes: handlers strip `scopes`, and `mastra__scopes` is a reserved key. */\n readonly reservesAgentScopes = true;\n\n protected mastra: Mastra;\n protected bodyLimitOptions?: BodyLimitOptions;\n protected tools?: ToolsInput;\n protected prefix?: string;\n protected openapiPath?: string;\n protected taskStore?: InMemoryTaskStore;\n protected customRouteAuthConfig?: Map<string, boolean>;\n protected streamOptions: StreamOptions;\n protected httpLoggingConfig?: HttpLoggingConfig;\n protected customApiRoutes?: ApiRoute[];\n protected mcpOptions?: MCPOptions;\n /** This adapter's `registerDispatchAdapter` handle, recorded on each request it serves. */\n private readonly dispatchAdapter: DispatchAdapterHandle;\n private customRouteHandler:\n | ((\n request: Request,\n env?: { requestContext?: RequestContext },\n executionCtx?: ExecutionContext,\n ) => Promise<Response>)\n | null = null;\n /** Mirrors the custom-route app's router so auth can ask which route a request runs. */\n private customRouteMatcher: CustomRouteMatcher<{\n method: string;\n path: string;\n handlerCount: number;\n route: HonoCustomApiRoute;\n }> | null = null;\n\n /**\n * Whether custom (non-schema) API routes were registered. Adapters use this\n * at request time to decide if they need to preserve a pristine copy of the\n * request body for the custom-route bridge.\n */\n protected get hasCustomRouteHandler(): boolean {\n return this.customRouteHandler !== null;\n }\n\n constructor({\n app,\n mastra,\n bodyLimitOptions,\n tools,\n prefix = '/api',\n openapiPath = '',\n taskStore,\n customRouteAuthConfig,\n streamOptions,\n customApiRoutes,\n mcpOptions,\n }: {\n app: TApp;\n mastra: Mastra;\n bodyLimitOptions?: BodyLimitOptions;\n tools?: ToolsInput;\n prefix?: string;\n openapiPath?: string;\n taskStore?: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n streamOptions?: StreamOptions;\n customApiRoutes?: ApiRoute[];\n /**\n * MCP transport options applied to all MCP HTTP and SSE routes.\n * Individual routes can override these via MCPHttpTransportResult.mcpOptions.\n */\n mcpOptions?: MCPOptions;\n }) {\n super({ app, name: 'MastraServer' });\n this.mastra = mastra;\n this.bodyLimitOptions = bodyLimitOptions;\n this.tools = tools;\n this.prefix = normalizeRoutePath(prefix);\n this.dispatchAdapter = registerDispatchAdapter(mastra, {\n prefix: this.prefix,\n getCustomRouteAuthConfig: () => this.customRouteAuthConfig,\n getCustomApiRoutes: () => this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [],\n checkRouteRBAC: (route, requestContext) => this.checkRouteRBAC(route, requestContext),\n });\n this.openapiPath = openapiPath;\n this.taskStore = taskStore;\n this.customRouteAuthConfig = customRouteAuthConfig;\n this.streamOptions = { redact: true, ...streamOptions };\n this.customApiRoutes = customApiRoutes;\n this.mcpOptions = mcpOptions;\n\n // Parse HTTP logging configuration\n const serverConfig = mastra.getServer();\n this.httpLoggingConfig = this.parseLoggingConfig(serverConfig?.build?.apiReqLogs);\n\n // Automatically register this adapter with Mastra so getServerApp() works\n mastra.setMastraServer(this);\n }\n\n /**\n * Parses the apiReqLogs configuration into a normalized HttpLoggingConfig.\n * @param config - The raw config value from server.build.apiReqLogs\n * @returns Normalized HttpLoggingConfig or undefined if disabled\n */\n private parseLoggingConfig(config?: boolean | HttpLoggingConfig): HttpLoggingConfig | undefined {\n if (config === true) {\n // Default configuration when enabled with just `true`\n return {\n enabled: true,\n level: 'info',\n redactHeaders: ['authorization', 'cookie'],\n };\n }\n if (typeof config === 'object' && config.enabled) {\n // Merge user config with defaults\n return {\n enabled: true,\n level: config.level || 'info',\n excludePaths: config.excludePaths,\n includeHeaders: config.includeHeaders,\n includeQueryParams: config.includeQueryParams,\n redactHeaders: [...new Set([...['authorization', 'cookie'], ...(config.redactHeaders || [])])],\n };\n }\n return undefined;\n }\n\n /**\n * Determines if a request to the given path should be logged.\n * @param path - The request path to check\n * @returns true if the request should be logged, false otherwise\n */\n protected shouldLogRequest(path: string): boolean {\n if (!this.httpLoggingConfig?.enabled) {\n return false;\n }\n\n // Uses segment-aware matching so '/health' excludes '/health' and '/health/deep' but not '/healthcheck'\n const excludePaths = this.httpLoggingConfig.excludePaths || [];\n return !excludePaths.some((excluded: string) => path === excluded || path.startsWith(excluded + '/'));\n }\n\n /** Warn when a request looks like an agent channel webhook whose route was never registered. */\n protected warnIfUnregisteredChannelWebhook(path: string, method: string, status: number): void {\n if (status !== 404 || method.toUpperCase() !== 'POST') return;\n\n const match = AGENT_CHANNEL_WEBHOOK_PATH.exec(path);\n if (!match) return;\n\n const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes;\n if (findMatchingCustomRoute(path, method.toUpperCase(), routes)) return;\n\n const agentId = match[1]!;\n const platform = match[2]!;\n const platformLabel = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i.test(platform)\n ? platform\n .split(/[-_]/)\n .map(segment => segment.charAt(0).toUpperCase() + segment.slice(1))\n .join(' ')\n : 'channel';\n this.mastra\n .getLogger()\n ?.warn(\n `Received a ${platformLabel} webhook, but this agent doesn't have a ${platformLabel} adapter. Add one to the agent's channels.adapters configuration and restart the server.`,\n { agentId, platform },\n );\n }\n\n protected mergeRequestContext({\n paramsRequestContext,\n bodyRequestContext,\n }: {\n paramsRequestContext?: Record<string, any>;\n bodyRequestContext?: Record<string, any>;\n }): RequestContext {\n const requestContext = new RequestContext();\n bindDispatchAdapter(requestContext, this.dispatchAdapter);\n if (bodyRequestContext) {\n for (const [key, value] of Object.entries(bodyRequestContext)) {\n if (isReservedRequestContextKey(key)) continue;\n requestContext.set(key, value);\n }\n }\n if (paramsRequestContext) {\n for (const [key, value] of Object.entries(paramsRequestContext)) {\n if (isReservedRequestContextKey(key)) continue;\n requestContext.set(key, value);\n }\n }\n return requestContext;\n }\n\n protected applyRequestMetadataToContext({\n requestContext,\n getHeader,\n }: {\n requestContext: RequestContext;\n getHeader: (name: string) => string | undefined;\n }): void {\n if (isStudioClientTypeHeader(getHeader(MASTRA_CLIENT_TYPE_HEADER))) {\n requestContext.set(MASTRA_IS_STUDIO_KEY, true);\n }\n }\n\n /**\n * Determines which auth configuration to use for the current request.\n *\n * Request routing logic:\n * 1. If `x-mastra-client-type: studio` header is present AND `studio.auth` is configured:\n * → Use studio auth (for internal team members accessing Studio UI)\n * 2. If studio header is present but `studio.auth` is NOT configured:\n * → No auth required (Studio development mode)\n * 3. Otherwise:\n * → Use server auth (for external customers calling API)\n *\n * Security note: The header is only for routing - auth validation happens\n * via session cookies/tokens. If someone spoofs the studio header but doesn't\n * have a valid studio session, they'll get a 401 (not fall back to server auth).\n */\n protected getEffectiveAuthConfig(\n getHeader: (name: string) => string | undefined,\n ): { authConfig: unknown; authMode: MastraAuthMode } | null {\n return resolveEffectiveAuthConfig(this.mastra, getHeader);\n }\n\n /**\n * Gets the effective RBAC provider for the current request based on auth mode.\n *\n * @deprecated Never consulted by route permission checks, so overriding it has no effect.\n * Override `checkRoutePermission` to change how a route's permission is decided.\n */\n protected getEffectiveRBACProvider(requestContext: RequestContext) {\n return getEffectiveRBACProvider(this.mastra, requestContext);\n }\n\n /**\n * Gets the effective FGA provider for the current request based on auth mode.\n */\n protected getEffectiveFGAProvider(requestContext: RequestContext) {\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY) as MastraAuthMode | undefined;\n\n if (authMode === 'studio') {\n return this.mastra.getStudio?.()?.fga ?? this.mastra.getServer()?.fga;\n }\n\n return this.mastra.getServer()?.fga;\n }\n\n /**\n * Check if the current request should be authenticated/authorized.\n * Returns null if auth passes, or an error response if it fails.\n *\n * This is a thin wrapper around coreAuthMiddleware that:\n * 1. Routes to the correct auth provider (studio vs server) based on request headers\n * 2. Handles route-level requiresAuth opt-out (not available in global middleware)\n * 3. Delegates all other auth logic to coreAuthMiddleware\n * 4. Translates the AuthResult into the {status, error} format adapters expect\n *\n * Security: When `x-mastra-client-type: studio` header is present and studio auth\n * is configured, we ONLY use studio auth. If authentication fails, we return 401\n * and redirect to login - we do NOT fall back to server auth. This prevents\n * external users from spoofing the studio header to access Studio UI.\n */\n protected async checkRouteAuth(\n route: ServerRoute,\n context: {\n path: string;\n method: string;\n getHeader: (name: string) => string | undefined;\n getQuery: (name: string) => string | undefined;\n requestContext: RequestContext;\n /** Raw Request object for cookie-based auth providers */\n request?: Request;\n /** Build framework-specific context for authorize() callback */\n buildAuthorizeContext?: () => unknown;\n /** Overrides the server's custom route auth map for this check. */\n customRouteAuthConfig?: Map<string, boolean>;\n },\n ): Promise<{ status: number; error: string; headers?: Record<string, string> } | null> {\n if (route.authTransport === 'bearer') {\n return this.checkBearerRouteAuth(route, context);\n }\n\n // Determine which auth config to use based on request type\n const effectiveAuth = this.getEffectiveAuthConfig(context.getHeader);\n\n // No auth config means no auth required\n if (!effectiveAuth) {\n return null;\n }\n\n const { authConfig, authMode } = effectiveAuth;\n\n // Store auth mode in request context for downstream RBAC/FGA provider selection\n context.requestContext.set(MASTRA_AUTH_MODE_KEY, authMode);\n\n // Check route-level requiresAuth flag first (explicit per-route setting)\n // This opt-out is route-specific and not available in the global middleware\n if (route.requiresAuth === false) {\n return null;\n }\n\n // Extract token from headers/query\n const authHeader = context.getHeader('authorization');\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token) {\n token = context.getQuery('apiKey') || null;\n }\n\n const fallbackHeaders = new Headers();\n for (const headerName of ['authorization', 'cookie']) {\n const headerValue = context.getHeader(headerName);\n if (headerValue) {\n fallbackHeaders.set(headerName, headerValue);\n }\n }\n\n // Delegate to coreAuthMiddleware for all auth logic\n const result = await coreAuthMiddleware({\n path: context.path,\n method: context.method,\n getHeader: context.getHeader,\n mastra: this.mastra,\n authConfig: authConfig as any,\n customRouteAuthConfig: context.customRouteAuthConfig ?? this.customRouteAuthConfig,\n requestContext: context.requestContext,\n rawRequest:\n context.request ??\n new Request(`http://localhost${context.path}`, { method: context.method, headers: fallbackHeaders }),\n token,\n buildAuthorizeContext: context.buildAuthorizeContext ?? (() => null),\n requiresAuth: route.requiresAuth,\n });\n\n if (result.action === 'next') {\n // Pass through any refresh headers (e.g. Set-Cookie from transparent session refresh)\n if (result.headers) {\n return { status: 200, error: '', headers: result.headers };\n }\n return null;\n }\n\n // Translate AuthResult error to the {status, error} format adapters expect\n const errorBody = result.body as { error?: string } | undefined;\n return { status: result.status, error: errorBody?.error ?? 'Access denied', headers: result.headers };\n }\n\n /**\n * Auth for routes with `authTransport: 'bearer'` (the built-in MCP server): only the\n * `Authorization` header counts, always against `server.auth`. Studio client-type routing,\n * cookies, and the `apiKey` query parameter are ignored, so a browser session can't be used.\n *\n * 401s carry `WWW-Authenticate` pointing at the OAuth protected-resource metadata, and when\n * `server.mcp.oauth.resource` is set the token audience must include it.\n */\n private async checkBearerRouteAuth(\n route: ServerRoute,\n context: Parameters<MastraServer<TApp, TRequest, TResponse>['checkRouteAuth']>[1],\n ): ReturnType<MastraServer<TApp, TRequest, TResponse>['checkRouteAuth']> {\n context.requestContext.set(MASTRA_IS_STUDIO_KEY, false);\n const authorization = context.getHeader('authorization');\n const getHeader = (name: string) => {\n const lower = name.toLowerCase();\n return lower === 'cookie' || lower === MASTRA_CLIENT_TYPE_HEADER ? undefined : context.getHeader(name);\n };\n const result = await this.checkRouteAuth(\n { ...route, authTransport: undefined },\n {\n ...context,\n getHeader,\n getQuery: name => (name === 'apiKey' ? undefined : context.getQuery(name)),\n request: new Request(context.request?.url ?? `http://localhost${context.path}`, {\n method: context.method,\n headers: authorization ? { authorization } : {},\n }),\n },\n );\n\n const discovery = isMCPOAuthDiscoveryEnabled(this.mastra);\n if (!discovery && !isMCPAudienceEnforced(this.mastra)) return result;\n\n const requestUrl = context.request?.url ?? `http://localhost${context.path}`;\n const prefix = this.prefix ?? '';\n if (result?.status === 401) {\n if (!discovery) return result;\n // RFC 6750 §3: no error code when the request carried no credentials.\n const error = authorization?.trim() ? { error: 'invalid_token' } : undefined;\n const challenge = mcpWWWAuthenticate(this.mastra, prefix, requestUrl, error);\n return { ...result, headers: { ...result.headers, 'WWW-Authenticate': challenge } };\n }\n\n const user = context.requestContext.get(MASTRA_USER_KEY);\n if (user !== undefined && !(await checkMCPAudience(this.mastra, user))) {\n const challenge = mcpWWWAuthenticate(this.mastra, prefix, requestUrl, {\n error: 'invalid_token',\n error_description: 'The token audience does not include this MCP server',\n });\n return {\n status: 401,\n error: 'Invalid token audience',\n headers: { ...result?.headers, 'WWW-Authenticate': challenge },\n };\n }\n return result;\n }\n\n /**\n * Check if the user has the required permission for a route.\n *\n * Uses convention-based permission derivation:\n * 1. If route has explicit `requiresPermission`, use that\n * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)\n * 3. Routes with `requiresAuth: false` skip permission checks\n *\n * When the route specifies an array of permissions, the user needs ANY ONE\n * of them (logical OR).\n *\n * @param route - The route being accessed\n * @param userPermissions - The user's permissions from the request context\n * @returns Error response if permission denied, null if allowed\n */\n /**\n * Check if the user has the required permission for a route.\n *\n * Uses convention-based permission derivation:\n * 1. If route has explicit `requiresPermission`, use that\n * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)\n * 3. Routes with `requiresAuth: false` skip permission checks\n *\n * Permission checks use the RBAC provider that corresponds to the auth mode\n * (studio vs server) that was used for authentication.\n *\n * @param route - The route being accessed\n * @param userPermissions - The user's permissions from the request context\n * @param hasPermissionFn - Function to check if user permissions match required permission\n * @param requestContext - Request context to determine which RBAC provider to use\n * @returns Error response if permission denied, null if allowed\n */\n protected checkRoutePermission(\n route: ServerRoute,\n userPermissions: string[] | undefined,\n hasPermissionFn: (userPerms: string[], required: string) => boolean,\n requestContext: RequestContext,\n ): { status: number; error: string; message: string } | null {\n return getRoutePermissionError(this.mastra, route, userPermissions, hasPermissionFn, requestContext);\n }\n\n /**\n * RBAC check for a route this adapter serves. Skipped when no auth is configured;\n * otherwise decided by `checkRoutePermission`, so a subclass override of it still applies.\n */\n protected checkRouteRBAC(route: ServerRoute, requestContext: RequestContext): RouteAuthorizationError | null {\n if (!this.mastra.getStudio?.()?.auth && !this.mastra.getServer()?.auth) {\n return null;\n }\n const userPermissions = requestContext.get(MASTRA_USER_PERMISSIONS_KEY) as string[] | undefined;\n return this.checkRoutePermission(route, userPermissions, hasPermission, requestContext);\n }\n\n /** RBAC (`checkRouteRBAC`) then FGA on the parsed params, after authentication and validation. */\n protected async authorizeRoute(\n route: ServerRoute,\n params: Record<string, unknown>,\n requestContext: RequestContext,\n ): Promise<RouteAuthorizationError | null> {\n return (\n this.checkRouteRBAC(route, requestContext) ?? (await checkRouteFGA(this.mastra, route, requestContext, params))\n );\n }\n\n /**\n * Build a matcher that answers \"is this (path, method) a framework-public\n * route?\" — i.e. registered with `requiresAuth: false`.\n *\n * Adapters call this once at registration time and use the returned function\n * inside their context middleware to stash a boolean on the per-request\n * context under `MASTRA_FRAMEWORK_PUBLIC_KEY`. That boolean is then read by\n * per-user-middleware wrappers to short-circuit user middleware for\n * framework-public routes, guaranteeing that user middleware cannot 401\n * routes the framework declared public (e.g. Studio sign-in endpoints).\n *\n * The matcher considers:\n * - Built-in `SERVER_ROUTES` entries with `requiresAuth === false`\n * (paths joined with the adapter's configured `prefix`).\n * - Custom user API routes registered with `requiresAuth: false` via the\n * `customRouteAuthConfig` map.\n */\n getFrameworkPublicMatcher(): FrameworkPublicMatcher {\n const prefix = this.prefix ?? '';\n\n const publicRoutes = SERVER_ROUTES.filter(r => r.requiresAuth === false).map(r => ({\n method: r.method.toUpperCase(),\n pattern: `${prefix}${r.path}`,\n }));\n\n if (isMCPOAuthDiscoveryEnabled(this.mastra)) {\n for (const route of createMCPOAuthMetadataRoutes(this.mastra, prefix)) {\n publicRoutes.push({ method: route.method.toUpperCase(), pattern: route.path });\n }\n }\n\n return (path: string, method: string): boolean => {\n const upperMethod = method.toUpperCase();\n\n for (const r of publicRoutes) {\n if ((r.method === upperMethod || r.method === 'ALL') && pathMatchesPattern(path, r.pattern)) {\n return true;\n }\n }\n\n // Read `customRouteAuthConfig` at request time, not at matcher build\n // time: adapters constructed without an explicit map only populate it\n // later, in registerCustomApiRoutes(), after the context middleware has\n // already built this matcher.\n return isCustomRoutePublic(path, upperMethod, this.customRouteAuthConfig);\n };\n }\n\n abstract stream(route: ServerRoute, response: TResponse, result: unknown): Promise<unknown>;\n abstract getParams(route: ServerRoute, request: TRequest): Promise<ParsedRequestParams>;\n abstract sendResponse(route: ServerRoute, response: TResponse, result: unknown): Promise<unknown>;\n abstract registerRoute(app: TApp, route: ServerRoute, { prefix }: { prefix?: string }): Promise<void>;\n abstract registerContextMiddleware(): void;\n abstract registerAuthMiddleware(): void;\n abstract registerHttpLoggingMiddleware(): void;\n\n async init() {\n this.registerContextMiddleware();\n this.registerAuthMiddleware();\n this.validateAuthResourceScoping();\n this.registerUserMiddleware();\n this.registerHttpLoggingMiddleware();\n await this.validateEELicense();\n await this.validateAgentBuilderLicense();\n await this.validateFGAPolicyCoverage();\n await this.registerCustomApiRoutes();\n await this.registerRoutes();\n }\n\n /**\n * Validate that EE features have a valid license in production.\n * Throws if RBAC or FGA is configured without a valid license outside dev/test environments.\n */\n async validateEELicense(): Promise<void> {\n const serverConfig = this.mastra.getServer();\n const studioConfig = this.mastra.getStudio?.();\n // Check both server and studio configs for EE features\n const configuredFeatures = [\n serverConfig?.rbac || studioConfig?.rbac ? 'RBAC' : null,\n serverConfig?.fga || studioConfig?.fga ? 'FGA' : null,\n ].filter((feature): feature is string => feature !== null);\n\n if (configuredFeatures.length === 0) return;\n\n try {\n const { isEEEnabled } = await import('@mastra/core/auth/ee');\n if (!isEEEnabled()) {\n const featureList = configuredFeatures.join(' and ');\n throw new Error(\n `[mastra/auth-ee] ${featureList} ${configuredFeatures.length === 1 ? 'is' : 'are'} configured but no valid EE license was found.\\n` +\n `${featureList} ${configuredFeatures.length === 1 ? 'requires' : 'require'} a Mastra Enterprise License for production use.\\n` +\n 'Set the MASTRA_EE_LICENSE environment variable with your license key.\\n' +\n 'Learn more: https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE',\n );\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('[mastra/auth-ee]')) {\n throw err;\n }\n // @mastra/core/auth/ee module not available; EE authorization cannot function.\n throw new Error(\n `[mastra/auth-ee] ${configuredFeatures.join(' and ')} ${configuredFeatures.length === 1 ? 'is' : 'are'} configured but the EE module (@mastra/core/auth/ee) could not be loaded.\\n` +\n 'Ensure @mastra/core is updated to a version that includes EE support.',\n );\n }\n }\n\n /**\n * Validate that an Agent Builder configuration has a valid EE license.\n * Throws if the editor is configured with builder support but no valid EE license is available.\n */\n async validateAgentBuilderLicense(): Promise<void> {\n const editor = this.mastra.getEditor();\n if (!editor?.hasEnabledBuilderConfig?.()) return;\n\n try {\n const { isEEEnabled } = await import('@mastra/core/auth/ee');\n if (!isEEEnabled()) {\n throw new Error(\n '[mastra/auth-ee] Agent Builder is configured but no valid EE license was found.\\n' +\n 'Agent Builder requires a Mastra Enterprise License for production use.\\n' +\n 'Set the MASTRA_EE_LICENSE environment variable with your license key.\\n' +\n 'Learn more: https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE',\n );\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('[mastra/auth-ee]')) {\n throw err;\n }\n // @mastra/core/auth/ee module not available — Agent Builder cannot function\n throw new Error(\n '[mastra/auth-ee] Agent Builder is configured but the EE module (@mastra/core/auth/ee) could not be loaded.\\n' +\n 'Ensure @mastra/core is updated to a version that includes EE support.',\n );\n }\n }\n\n /**\n * Warn when `server.auth` is configured without `mapUserToResourceId`.\n *\n * Without it, MASTRA_RESOURCE_ID_KEY is never set in the request context, so\n * built-in routes fall back to the client-supplied resource ID (for example\n * `memory.resource`) and ownership checks run against a caller-chosen value.\n */\n validateAuthResourceScoping(): void {\n const auth = this.mastra.getServer()?.auth as { mapUserToResourceId?: unknown } | undefined;\n if (!auth || typeof auth.mapUserToResourceId === 'function') return;\n\n this.mastra\n .getLogger()\n ?.warn(\n '[mastra/auth] server.auth is configured without mapUserToResourceId. ' +\n 'Memory, thread and workflow ownership checks will trust the resource ID supplied by the client ' +\n \"(e.g. memory.resource in the request body), so an authenticated user can read or write another user's threads. \" +\n 'Configure server.auth.mapUserToResourceId to derive the resource ID from the authenticated user.',\n );\n }\n\n /**\n * Validate route-level FGA policy coverage when an FGA provider opts into\n * startup checks.\n */\n async validateFGAPolicyCoverage(): Promise<void> {\n const serverConfig = this.mastra.getServer();\n const studioConfig = this.mastra.getStudio?.();\n // Check both server and studio FGA providers\n const fgaProvider = serverConfig?.fga ?? studioConfig?.fga;\n if (!fgaProvider) return;\n\n const customRoutes = (this.customApiRoutes ?? serverConfig?.apiRoutes ?? []).filter(\n route => !route._mastraInternal,\n );\n const routes = [...SERVER_ROUTES, ...customRoutes] as ServerRoute[];\n\n if (fgaProvider.validatePermissions) {\n const permissions = [...new Set(routes.flatMap(route => getRoutePermissions(route)))];\n await fgaProvider.validatePermissions(permissions);\n }\n\n const auditMode = fgaProvider.auditProtectedRoutes ?? (fgaProvider.requireForProtectedRoutes ? 'warn' : false);\n if (!auditMode || fgaProvider.resolveRouteFGA) return;\n\n const missingRoutes = routes.filter(\n route => isProtectedFGARoute(route) && !route.fga && !getBuiltInRouteFGAConfig(route),\n );\n\n if (missingRoutes.length === 0) return;\n\n const routeList = missingRoutes.map(route => formatRoute(route as ServerRoute));\n const message =\n `[mastra/auth-ee] FGA is configured but ${missingRoutes.length} protected route` +\n `${missingRoutes.length === 1 ? ' is' : 's are'} missing FGA metadata: ${routeList.join(', ')}`;\n\n if (auditMode === 'error') {\n throw new Error(message);\n }\n\n this.mastra.getLogger()?.warn(message, {\n routes: routeList,\n count: missingRoutes.length,\n });\n }\n\n /**\n * Register user-provided middleware from the Mastra config (`server.middleware`)\n * and from `mastra.setServerMiddleware()`. Called by init() between\n * registerAuthMiddleware() and registerHttpLoggingMiddleware().\n *\n * Mastra middleware handlers use Hono's `(c, next)` signature, so only\n * Hono-based adapters can run them. Those adapters override this method and\n * MUST wrap each handler with `skipIfFrameworkPublic` (exported by\n * `@mastra/hono`) so user middleware cannot block framework-public routes.\n * The default implementation warns when middleware is configured so the\n * config is not silently ignored on adapters that cannot honor it.\n */\n registerUserMiddleware(): void {\n const instanceMiddleware = this.mastra.getServerMiddleware?.() ?? [];\n const configMiddleware = this.mastra.getServer()?.middleware;\n const hasConfigMiddleware = Array.isArray(configMiddleware) ? configMiddleware.length > 0 : !!configMiddleware;\n if (instanceMiddleware.length === 0 && !hasConfigMiddleware) return;\n\n this.mastra\n .getLogger()\n ?.warn(\n 'Mastra server middleware (`server.middleware` or `setServerMiddleware()`) is configured, but this server adapter cannot run Hono middleware handlers. The configured middleware will not run — register middleware through your server framework instead.',\n );\n }\n\n /**\n * Override in adapters to register custom API routes defined via registerApiRoute().\n * Called by init() between registerAuthMiddleware() and registerRoutes().\n */\n async registerCustomApiRoutes(): Promise<void> {\n // Default no-op. Adapters override this to register custom routes\n // using their framework-specific middleware.\n }\n\n /** Ensures every custom route has an auth entry without overriding supplied values. */\n private initializeCustomRouteAuthConfig(routes: ApiRoute[]): void {\n this.customRouteAuthConfig ??= new Map();\n for (const route of routes) {\n const routeKey = `${route.method}:${route.path}`;\n if (!this.customRouteAuthConfig.has(routeKey)) {\n this.customRouteAuthConfig.set(routeKey, route.requiresAuth !== false);\n }\n }\n }\n\n /**\n * Registers schema-aware custom routes through the adapter's native route pipeline.\n * Returns the remaining Hono-style routes for the custom-route bridge.\n */\n protected async registerSchemaApiRoutes(): Promise<HonoCustomApiRoute[]> {\n const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [];\n this.validateCustomRoutePaths(routes);\n this.initializeCustomRouteAuthConfig(routes);\n\n const schemaRoutes = routes.filter(isSchemaApiRoute);\n for (const route of schemaRoutes) {\n // Opt-in built-in routes are first-party: Studio and the client SDK call them under the API prefix,\n // so they mount there like any built-in route. Other custom routes mount at the root.\n // Matched by identity: a cloned route object lands back at the root.\n const prefix = (OPT_IN_ROUTES as readonly unknown[]).includes(route) ? this.prefix : '';\n await this.registerRoute(this.app, route as unknown as ServerRoute, { prefix });\n }\n\n return routes.filter((route): route is HonoCustomApiRoute => !isSchemaApiRoute(route));\n }\n\n /**\n * Validates that no custom route path collides with the built-in route prefix.\n * Throws if any route path starts with the server's `apiPrefix`.\n */\n protected validateCustomRoutePaths(routes: ApiRoute[]): void {\n const prefix = this.prefix ?? '';\n if (!prefix) return;\n for (const route of routes) {\n if (route._mastraInternal) continue;\n if (route.path.startsWith(`${prefix}/`) || route.path === prefix) {\n throw new Error(\n `Custom API route \"${route.path}\" must not start with \"${prefix}\" — ` +\n `that path is reserved for built-in Mastra routes. ` +\n `Choose a different path (e.g. \"${route.path.replace(prefix, '/custom')}\").`,\n );\n }\n }\n }\n\n /**\n * Creates an internal Hono sub-app with all custom API routes registered.\n * Stores the handler on this instance for use by handleCustomRouteRequest().\n * Returns true if custom routes were found and registered.\n */\n protected async buildCustomRouteHandler(routes: HonoCustomApiRoute[]): Promise<boolean> {\n if (routes.length === 0) return false;\n\n const NOT_FOUND_HEADER = 'x-mastra-custom-route-not-found';\n const mastra = this.mastra;\n\n const app = new Hono<{\n Bindings: { requestContext?: RequestContext };\n Variables: { mastra: Mastra; requestContext: RequestContext };\n }>();\n\n // Internal context middleware — sets variables that custom route handlers expect\n app.use('*', async (c, next) => {\n c.set('mastra', mastra);\n c.set('requestContext', c.env?.requestContext ?? new RequestContext());\n await next();\n });\n\n // Propagate the server's onError handler so errors from custom route handlers\n // are caught here (not swallowed by Hono's default plain-text 500).\n const serverOnError = this.mastra.getServer()?.onError;\n app.onError((err, c) => {\n if (serverOnError) {\n return serverOnError(err, c as unknown as Parameters<typeof serverOnError>[1]);\n }\n const httpExceptionResponse = getCustomRouteHTTPExceptionResponse(err);\n if (httpExceptionResponse) return httpExceptionResponse;\n // Log before responding — otherwise the error is invisible on the server\n // and the client only ever sees an opaque 500.\n this.mastra.getLogger()?.error(`Custom route handler failed: ${c.req.method} ${c.req.path}`, {\n method: c.req.method,\n path: c.req.path,\n error: err instanceof Error ? (err.stack ?? err.message) : String(err),\n });\n return c.json({ error: 'Internal Server Error' }, 500);\n });\n\n // Register each custom route\n const matcherEntries: Array<{ method: string; path: string; handlerCount: number; route: HonoCustomApiRoute }> = [];\n for (const route of routes) {\n const handler =\n 'handler' in route && route.handler\n ? route.handler\n : 'createHandler' in route\n ? await route.createHandler({ mastra })\n : undefined;\n if (!handler) continue;\n\n const middlewares: any[] = [];\n if (route.middleware) {\n middlewares.push(...(Array.isArray(route.middleware) ? route.middleware : [route.middleware]));\n }\n\n const allHandlers = [...middlewares, handler];\n matcherEntries.push({ method: route.method, path: route.path, handlerCount: allHandlers.length, route });\n if (route.method === 'ALL') {\n app.all(route.path, allHandlers[0]!, ...allHandlers.slice(1));\n } else {\n app.on(route.method, route.path, allHandlers[0]!, ...allHandlers.slice(1));\n }\n }\n\n // Mark unmatched requests so the adapter bridge can fall through to next()\n app.notFound(() => new Response(null, { status: 404, headers: { [NOT_FOUND_HEADER]: 'true' } }));\n\n // Forward the platform execution context (e.g. Cloudflare Workers' `waitUntil`)\n // into the internal app so custom route handlers can keep background work\n // alive after the response is sent. Without this third arg, serverless\n // runtimes freeze the invocation on return and kill any in-flight work.\n this.customRouteHandler = async (request, env, executionCtx) => app.fetch(request, env, executionCtx);\n this.customRouteMatcher = new CustomRouteMatcher(matcherEntries);\n return true;\n }\n\n /**\n * Returns the custom route the custom-route app will run for `url` (the same URL\n * passed to `handleCustomRouteRequest`), with its decoded path params, or\n * undefined if none will.\n */\n protected matchCustomRoute(\n url: string,\n method: string,\n ): { route: HonoCustomApiRoute; params: Record<string, string> } | undefined {\n if (!this.customRouteMatcher) return undefined;\n try {\n const match = this.customRouteMatcher.matchUrl(url, method);\n return match ? { route: match.entry.route, params: match.params } : undefined;\n } catch {\n // The custom-route app can't parse or route this request either.\n return undefined;\n }\n }\n\n /**\n * Works out what auth applies to a request before it's forwarded to the\n * custom-route app. The route that decides is the one the app will dispatch\n * `dispatchUrl` to, not the route the outer framework matched, because the two\n * routers can disagree on precedence, case, trailing slashes and encoding.\n *\n * `requestPath` is the path passed to `checkRouteAuth`. When the dispatched route\n * requires auth, the returned `customRouteAuthConfig` marks that path protected so\n * the auth middleware can't skip auth on it. `fallbackRoute` is used when the app\n * won't dispatch the request (it 404s and nothing runs); pass the framework's own\n * route when there is one so its auth still applies.\n */\n protected resolveCustomRouteAuth(\n dispatchUrl: string,\n method: string,\n requestPath: string,\n fallbackRoute?: HonoCustomApiRoute,\n ): {\n match?: { route: HonoCustomApiRoute; params: Record<string, string> };\n requiresAuth: boolean;\n serverRoute: ServerRoute;\n customRouteAuthConfig?: Map<string, boolean>;\n } {\n const match = this.matchCustomRoute(dispatchUrl, method);\n const route = match?.route ?? fallbackRoute;\n\n const requiresAuth = route\n ? (this.customRouteAuthConfig?.get(`${route.method}:${route.path}`) ?? route.requiresAuth !== false)\n : isProtectedCustomRoute(requestPath, method, this.customRouteAuthConfig);\n\n const serverRoute: ServerRoute = {\n method: (route?.method ?? method) as any,\n path: route?.path ?? requestPath,\n responseType: 'json',\n handler: async () => {},\n // An explicit requiresAuth: true keeps its meaning; otherwise the auth middleware\n // decides from the path, which the map below forces to protected.\n requiresAuth: requiresAuth ? (route?.requiresAuth === true ? true : undefined) : false,\n requiresPermission: route?.requiresPermission,\n fga: route?.fga,\n };\n\n let customRouteAuthConfig: Map<string, boolean> | undefined;\n if (requiresAuth) {\n customRouteAuthConfig = new Map(this.customRouteAuthConfig ?? []);\n customRouteAuthConfig.set(`${method.toUpperCase()}:${requestPath}`, true);\n }\n\n return { match, requiresAuth, serverRoute, customRouteAuthConfig };\n }\n\n /**\n * Forwards a request to the internal custom route handler.\n * Returns the Response if a custom route matched, or null to fall through.\n */\n protected async handleCustomRouteRequest(\n url: string,\n method: string,\n headers: Record<string, string | string[] | undefined>,\n body: unknown,\n requestContext?: RequestContext,\n signal?: AbortSignal,\n executionCtx?: ExecutionContext,\n ): Promise<Response | null> {\n if (!this.customRouteHandler) return null;\n\n const fetchHeaders = new Headers();\n for (const [key, value] of Object.entries(headers)) {\n if (typeof value === 'string') fetchHeaders.set(key, value);\n else if (Array.isArray(value))\n value.forEach(v => {\n fetchHeaders.append(key, v);\n });\n }\n\n const init: RequestInit = { method, headers: fetchHeaders, signal };\n if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && body !== undefined) {\n if (body instanceof ArrayBuffer || body instanceof Uint8Array || body instanceof ReadableStream) {\n init.body = body as any;\n if (body instanceof ReadableStream) {\n (init as any).duplex = 'half';\n }\n } else {\n const contentType = (typeof headers['content-type'] === 'string' ? headers['content-type'] : '') || '';\n if (contentType.includes('application/json')) {\n init.body = JSON.stringify(body);\n } else if (typeof body === 'string') {\n init.body = body;\n }\n }\n }\n\n const request = new globalThis.Request(url, init);\n const response = await this.customRouteHandler(request, { requestContext }, executionCtx);\n\n if (response.headers.get('x-mastra-custom-route-not-found') === 'true') return null;\n return signal ? retainRequestWhileBodyIsOpen(response, request) : response;\n }\n\n /**\n * Pipes a custom route Response to a Node.js ServerResponse (http.ServerResponse).\n * Works with Koa (ctx.res), Express (res), and Fastify (reply.raw).\n */\n protected async writeCustomRouteResponse(\n response: Response,\n nodeRes: {\n writeHead(status: number, headers: Record<string, string | string[]>): void;\n write(chunk: unknown): void;\n end(data?: string): void;\n writableEnded?: boolean;\n destroyed?: boolean;\n } & NodeJS.WritableStream,\n signal?: AbortSignal,\n ): Promise<void> {\n const headers: Record<string, string | string[]> = {};\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() !== 'set-cookie') {\n headers[key] = value;\n }\n });\n const setCookies = response.headers.getSetCookie?.();\n if (setCookies && setCookies.length > 0) {\n headers['set-cookie'] = setCookies;\n }\n if (isResponseClosed(nodeRes)) {\n await response.body?.cancel();\n return;\n }\n nodeRes.writeHead(response.status, headers);\n\n if (response.body) {\n let responseBodyError: unknown;\n let responseBodyErrorAfterResponseClosed = false;\n try {\n const responseStream = Readable.fromWeb(response.body as any);\n // This listener must run before pipeline's cleanup so source errors are\n // not mistaken for client disconnects after pipeline destroys nodeRes.\n responseStream.once('error', error => {\n responseBodyError = error;\n responseBodyErrorAfterResponseClosed = isResponseClosed(nodeRes);\n });\n if (signal) {\n await pipeline(responseStream, nodeRes, { signal });\n } else {\n await pipeline(responseStream, nodeRes);\n }\n } catch (error) {\n const expectedSignalAbort =\n signal?.aborted && isAbortSignalError(error) && (!responseBodyError || responseBodyErrorAfterResponseClosed);\n const expectedResponseClose =\n (!responseBodyError || responseBodyErrorAfterResponseClosed) &&\n isResponseClosed(nodeRes) &&\n isExpectedResponseCloseError(error);\n // Request cancellation is expected unless the response body already reported its own error.\n if (!expectedSignalAbort && !expectedResponseClose) {\n throw error;\n }\n }\n } else {\n const text = await response.text();\n if (!isResponseClosed(nodeRes)) {\n nodeRes.end(text);\n }\n }\n }\n\n /**\n * Builds the OpenAPI spec object with servers field and custom route paths.\n */\n private buildOpenAPISpec(config: { title: string; version: string; description: string }, prefix?: string): any {\n const openApiSpec = generateOpenAPIDocument(SERVER_ROUTES, config);\n\n if (prefix) {\n openApiSpec.servers = [{ url: prefix }];\n }\n\n // Custom routes are served at root (/), not under the API prefix — add per-path servers override.\n const allCustomRoutes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes;\n if (allCustomRoutes && allCustomRoutes.length > 0) {\n const componentSchemas = openApiSpec.components?.schemas ?? Object.create(null);\n // Opt-in built-in routes are mounted under the API prefix (see registerSchemaApiRoutes), so they keep the\n // top-level server; every other custom route is served at the root.\n const isPrefixed = (route: ApiRoute) => (OPT_IN_ROUTES as readonly unknown[]).includes(route);\n const customPaths = convertCustomRoutesToOpenAPIPaths(\n allCustomRoutes.filter(route => !isPrefixed(route)),\n componentSchemas,\n );\n const prefixedPaths = convertCustomRoutesToOpenAPIPaths(allCustomRoutes.filter(isPrefixed), componentSchemas);\n if (Object.keys(componentSchemas).length > 0) {\n openApiSpec.components = { ...openApiSpec.components, schemas: componentSchemas };\n }\n if (prefix) {\n for (const pathKey of Object.keys(customPaths)) {\n if (!customPaths[pathKey].servers) {\n customPaths[pathKey].servers = [{ url: '/' }];\n }\n }\n }\n Object.assign(customPaths, prefixedPaths);\n openApiSpec.paths = { ...openApiSpec.paths, ...customPaths };\n }\n\n return openApiSpec;\n }\n\n async registerOpenAPIRoute(app: TApp, config: OpenAPIConfig = {}, { prefix }: { prefix?: string }): Promise<void> {\n const {\n title = 'Mastra API',\n version = '1.0.0',\n description = 'Mastra Server API',\n path = '/openapi.json',\n } = config;\n\n const openApiSpec = this.buildOpenAPISpec({ title, version, description }, prefix);\n\n const openApiRoute: ServerRoute = {\n method: 'GET',\n path,\n responseType: 'json',\n handler: async () => openApiSpec,\n };\n\n await this.registerRoute(app, openApiRoute, { prefix });\n }\n\n async registerRoutes(): Promise<void> {\n // Register routes sequentially to maintain order - important for routers where\n // more specific routes (e.g., /versions/compare) must be registered before\n // parameterized routes (e.g., /versions/:versionId)\n for (const route of SERVER_ROUTES) {\n await this.registerRoute(this.app, resolveServerRoute(route, this.mastra, SERVER_ROUTES), {\n prefix: this.prefix,\n });\n }\n\n // OAuth discovery for the built-in MCP endpoint lives at the server root, outside the API prefix.\n if (isMCPAudienceEnforced(this.mastra)) warnOnUnenforcedMCPAudience(this.mastra);\n if (isMCPOAuthDiscoveryEnabled(this.mastra)) {\n for (const route of createMCPOAuthMetadataRoutes(this.mastra, this.prefix ?? '')) {\n await this.registerRoute(this.app, route, { prefix: '' });\n }\n }\n\n if (this.openapiPath) {\n const specConfig = {\n title: 'Mastra API',\n version: '1.0.0',\n description: 'Mastra Server API',\n };\n\n await this.registerOpenAPIRoute(this.app, { ...specConfig, path: this.openapiPath }, { prefix: this.prefix });\n }\n }\n\n async parsePathParams(route: ServerRoute, params: Record<string, string>): Promise<Record<string, any>> {\n return parseRoutePathParams(route, params);\n }\n\n async parseQueryParams(route: ServerRoute, params: Record<string, QueryParamValue>): Promise<Record<string, any>> {\n return parseRouteQueryParams(route, params);\n }\n\n async parseBody(route: ServerRoute, body: unknown): Promise<unknown> {\n return parseRouteBody(route, body);\n }\n\n protected resolveValidationError(\n route: ServerRoute,\n error: ZodError,\n context: ValidationErrorContext,\n ): ValidationErrorResponse {\n return resolveRouteValidationError(this.mastra, route, error, context);\n }\n}\n\n/**\n * The RBAC provider for the auth mode the request was authenticated with\n * (studio vs server).\n */\nexport function getEffectiveRBACProvider(mastra: Mastra, requestContext: RequestContext) {\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY) as MastraAuthMode | undefined;\n\n if (authMode === 'studio') {\n return mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac;\n }\n\n return mastra.getServer()?.rbac;\n}\n\n/**\n * Check if the user has the required permission for a route.\n *\n * Uses convention-based permission derivation:\n * 1. If route has explicit `requiresPermission`, use that\n * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)\n * 3. Routes with `requiresAuth: false` skip permission checks\n *\n * When the route specifies an array of permissions, the user needs ANY ONE\n * of them (logical OR). Without an RBAC provider, authenticated users get full access.\n *\n * @returns Error response if permission denied, null if allowed\n */\nexport function getRoutePermissionError(\n mastra: Mastra,\n route: ServerRoute,\n userPermissions: string[] | undefined,\n hasPermissionFn: (userPerms: string[], required: string) => boolean,\n requestContext: RequestContext,\n): { status: number; error: string; message: string } | null {\n if (!getEffectiveRBACProvider(mastra, requestContext)) {\n return null;\n }\n\n const requiredPermission = getEffectivePermission(route);\n if (!requiredPermission) {\n return null;\n }\n\n const permissions = Array.isArray(requiredPermission) ? requiredPermission : [requiredPermission];\n const hasAny = userPermissions && permissions.some(perm => hasPermissionFn(userPermissions, perm));\n\n if (!hasAny) {\n return {\n status: 403,\n error: 'Forbidden',\n message: `Missing required permission: ${permissions.join(' or ')}`,\n };\n }\n\n return null;\n}\n\nexport async function parseRoutePathParams(\n route: ServerRoute,\n params: Record<string, unknown>,\n): Promise<Record<string, any>> {\n const pathParamSchema = route.pathParamSchema;\n if (!pathParamSchema) {\n return params;\n }\n\n return pathParamSchema.parseAsync(params) as Promise<Record<string, any>>;\n}\n\nexport async function parseRouteQueryParams(\n route: ServerRoute,\n params: Record<string, unknown>,\n): Promise<Record<string, any>> {\n const queryParamSchema = route.queryParamSchema;\n if (!queryParamSchema) {\n return params;\n }\n\n const normalizedParams = parseComplexQueryParams(queryParamSchema as z.ZodTypeAny, params);\n return queryParamSchema.parseAsync(normalizedParams) as Promise<Record<string, any>>;\n}\n\nexport async function parseRouteBody(route: ServerRoute, body: unknown): Promise<unknown> {\n const bodySchema = route.bodySchema;\n if (!bodySchema) {\n return body;\n }\n\n if (body === undefined) {\n const omitted = await bodySchema.safeParseAsync(undefined);\n if (omitted.success) return omitted.data;\n // Preserve bodyless object requests with optional/defaulted fields, but keep\n // the original missing-input error if the compatibility fallback also fails.\n const schemaType = getSchemaTypeName(unwrapOptionalNullable(bodySchema));\n if (schemaType === 'object' || schemaType === 'ZodObject') {\n const emptyObject = await bodySchema.safeParseAsync({});\n if (emptyObject.success) return emptyObject.data;\n }\n throw omitted.error;\n }\n\n return bodySchema.parseAsync(body);\n}\n\nconst VALIDATION_CONTEXT_LABELS: Record<ValidationErrorContext, string> = {\n query: 'query parameters',\n body: 'request body',\n path: 'path parameters',\n};\n\nexport function resolveRouteValidationError(\n mastra: Mastra,\n route: ServerRoute,\n error: ZodError,\n context: ValidationErrorContext,\n): ValidationErrorResponse {\n const hook = route.onValidationError ?? mastra.getServer()?.onValidationError;\n\n if (hook) {\n try {\n const result = hook(error, context);\n if (result) {\n return result;\n }\n } catch (hookError) {\n mastra.getLogger()?.error('Error in custom onValidationError hook', {\n error: hookError instanceof Error ? { message: hookError.message, stack: hookError.stack } : hookError,\n });\n }\n }\n\n return {\n status: 400,\n body: formatZodError(error, VALIDATION_CONTEXT_LABELS[context]),\n };\n}\n\ntype RouteAuthorizationError = { status: number; error: string; message: string };\n\n/**\n * Check the route's RBAC permission (explicit `requiresPermission` or derived from\n * path/method) against the permissions `checkRouteAuth` stored in the request context.\n * Skipped when no auth or no RBAC provider is configured, matching what adapters enforce.\n * Uses the studio RBAC provider for studio-authenticated requests.\n * Returns null if allowed, or a 403 error object if denied.\n */\nexport function checkRouteRBAC(\n mastra: Mastra,\n route: ServerRoute,\n requestContext: RequestContext,\n): RouteAuthorizationError | null {\n if (!mastra.getStudio?.()?.auth && !mastra.getServer()?.auth) {\n return null;\n }\n\n const userPermissions = requestContext.get(MASTRA_USER_PERMISSIONS_KEY) as string[] | undefined;\n return getRoutePermissionError(mastra, route, userPermissions, hasPermission, requestContext);\n}\n\n/**\n * Run the route authorization adapters enforce after authentication and schema\n * validation: RBAC (`checkRouteRBAC`) then FGA (`checkRouteFGA`) on the parsed params.\n * Returns null if allowed, or a 403 error object if denied.\n */\nexport async function authorizeRoute(\n mastra: Mastra,\n route: ServerRoute,\n params: Record<string, unknown>,\n requestContext: RequestContext,\n): Promise<RouteAuthorizationError | null> {\n return checkRouteRBAC(mastra, route, requestContext) ?? (await checkRouteFGA(mastra, route, requestContext, params));\n}\n\nexport interface DispatchRouteInput {\n pathParams?: Record<string, unknown>;\n query?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport type DispatchRouteResult = { ok: true; result: unknown } | { ok: false; status: number; body: unknown };\n\n/** What `dispatchRoute` needs to know about an adapter serving a Mastra instance's routes over HTTP. */\nexport interface DispatchAdapterInfo {\n /** The prefix built-in routes are served under, as request paths reach server auth (e.g. `/api`). */\n prefix?: string;\n getCustomRouteAuthConfig?: () => Map<string, boolean> | undefined;\n getCustomApiRoutes?: () => ApiRoute[];\n /** The adapter's own RBAC check, so its overrides also apply in-process. */\n checkRouteRBAC?: (route: ServerRoute, requestContext: RequestContext) => RouteAuthorizationError | null;\n}\n\n/**\n * Opaque handle naming one registered adapter. An adapter binds it to each request context it\n * creates (`bindDispatchAdapter`) so routes dispatched with that context get its policy.\n */\nexport type DispatchAdapterHandle = Readonly<Record<string, never>>;\n\nconst dispatchAdapters = new WeakMap<Mastra, Map<DispatchAdapterHandle, DispatchAdapterInfo>>();\n\n// Kept beside the request context rather than in it, so agent and tool code never see the handle\n// and no client input can set it.\nconst servingAdapters = new WeakMap<RequestContext, DispatchAdapterHandle>();\n\n/**\n * Record that `handle`'s adapter is serving the request `requestContext` belongs to. Adapters\n * built on `MastraServer` do this for every request; other adapters must call it.\n */\nexport function bindDispatchAdapter(requestContext: RequestContext, handle: DispatchAdapterHandle): void {\n servingAdapters.set(requestContext, handle);\n}\n\n/**\n * Tell `dispatchRoute` where an adapter serves a Mastra instance's routes. Adapters built on\n * `MastraServer` register themselves; adapters that are not must call this, and bind the returned\n * handle to each request context they create with `bindDispatchAdapter`.\n */\nexport function registerDispatchAdapter(mastra: Mastra, info: DispatchAdapterInfo): DispatchAdapterHandle {\n const adapters = dispatchAdapters.get(mastra) ?? new Map<DispatchAdapterHandle, DispatchAdapterInfo>();\n const handle: DispatchAdapterHandle = Object.freeze({});\n adapters.set(handle, info);\n dispatchAdapters.set(mastra, adapters);\n return handle;\n}\n\n/**\n * The adapter whose HTTP paths and checks a dispatched route gets. Among the adapters serving\n * `routePrefix` (all of them when it is not given), that is the one serving the current request\n * (`bindDispatchAdapter`), else the only one. `prefix` is undefined when it cannot be\n * told: several candidates and none serving this request, a `routePrefix` no registered adapter\n * serves (a custom route's own `routePrefix` is empty, for one), or nothing to go on. Guessing\n * between adapters could skip one's stricter checks, so it is never done.\n */\nfunction resolveDispatchAdapter(\n mastra: Mastra,\n routePrefix: string | undefined,\n requestContext: RequestContext,\n): { prefix: string | undefined; adapter?: DispatchAdapterInfo } {\n const adapters = [...(dispatchAdapters.get(mastra) ?? new Map<DispatchAdapterHandle, DispatchAdapterInfo>())];\n if (routePrefix !== undefined && adapters.length === 0) {\n return { prefix: normalizeRoutePath(routePrefix) };\n }\n const candidates =\n routePrefix === undefined\n ? adapters\n : adapters.filter(([, adapter]) => normalizeRoutePath(adapter.prefix ?? '') === normalizeRoutePath(routePrefix));\n const serving = servingAdapters.get(requestContext);\n const match =\n candidates.find(([handle]) => handle === serving) ?? (candidates.length === 1 ? candidates[0] : undefined);\n if (!match) {\n return { prefix: undefined };\n }\n const [, adapter] = match;\n return { prefix: normalizeRoutePath(adapter.prefix ?? ''), adapter };\n}\n\n/** Studio auth for Studio requests when `studio.auth` is configured, otherwise `server.auth`. */\nfunction resolveEffectiveAuthConfig(\n mastra: Mastra,\n getHeader: (name: string) => string | undefined,\n): { authConfig: unknown; authMode: MastraAuthMode } | null {\n const isStudioRequest = isStudioClientTypeHeader(getHeader(MASTRA_CLIENT_TYPE_HEADER));\n const studioAuth = mastra.getStudio?.()?.auth;\n const serverAuth = mastra.getServer()?.auth;\n\n // Dual auth is opt-in: if studio.auth is configured, Studio requests use it exclusively\n if (isStudioRequest && studioAuth) {\n return { authConfig: studioAuth, authMode: 'studio' };\n }\n\n // Otherwise (non-studio request, OR studio request without studio.auth configured),\n // fall back to server.auth for backward compatibility\n if (serverAuth) {\n return { authConfig: serverAuth, authMode: 'server' };\n }\n\n // No auth configured\n return null;\n}\n\nconst ROUTE_PATH_PARAM = /\\/:([A-Za-z0-9_]+)(\\?)?/g;\n\n/**\n * A URL can only carry a path param as a non-empty segment, and `.` / `..` segments are\n * resolved away before routing. Anything else names a path no HTTP request to this route\n * has, so it is rejected instead of being authorized as some other path.\n */\nfunction findInvalidPathParams(\n path: string,\n pathParams: Record<string, unknown>,\n): Array<{ field: string; message: string }> {\n const issues: Array<{ field: string; message: string }> = [];\n for (const [, name, optional] of path.matchAll(ROUTE_PATH_PARAM)) {\n const value = pathParams[name!];\n if (value === undefined && optional) continue;\n if (typeof value !== 'string' || value === '') {\n issues.push({ field: name!, message: 'Path parameter must be a non-empty string' });\n } else if (value === '.' || value === '..') {\n issues.push({ field: name!, message: 'Path parameter cannot be \".\" or \"..\"' });\n }\n }\n return issues;\n}\n\n/** Fill `:param` / `:param?` segments of a route path the way a client would put them in a URL. */\nfunction fillRoutePath(path: string, pathParams: Record<string, unknown>): string {\n return path.replace(ROUTE_PATH_PARAM, (_segment, name: string) => {\n const value = pathParams[name];\n return value === undefined ? '' : `/${encodeURIComponent(String(value))}`;\n });\n}\n\n/** Where the in-process pipeline deliberately differs between `dispatchRoute` and `invokeRoute`. */\ninterface RoutePipelinePolicy {\n /**\n * Skip auth for paths server auth declares public (and for the dev playground). When false,\n * every route that requires auth needs an authenticated user.\n */\n honorPublicPaths: boolean;\n /** Path params override same-named query/body fields, instead of the adapters' path < query < body. */\n pathParamsWin: boolean;\n /**\n * The path server auth's hooks are asked about. `adapter`: under the prefix of the adapter\n * serving the routes (custom routes unprefixed, with their auth config), refusing path params\n * no URL could carry and refusing to run when that prefix is not known. `apiPrefix`: always\n * under `server.apiPrefix`, each `:param` replaced in place.\n */\n authPath: 'adapter' | 'apiPrefix';\n /** Order inputs are validated in, which decides the error reported when several are invalid. */\n validationOrder: 'query-body-path' | 'path-query-body';\n /** A schema failing with something other than a ZodError: answer 400, or let it throw. */\n nonZodParseError: 'respond' | 'throw';\n /** Answer with the `Response` an HTTPException carries, instead of the standard error body. */\n customErrorResponses: boolean;\n /** Handlers only see the server context the caller passed, never same-named request fields. */\n reserveServerContext: boolean;\n}\n\nconst DISPATCH_ROUTE_POLICY: RoutePipelinePolicy = {\n honorPublicPaths: true,\n pathParamsWin: true,\n authPath: 'adapter',\n validationOrder: 'query-body-path',\n nonZodParseError: 'respond',\n customErrorResponses: true,\n reserveServerContext: true,\n};\n\n/** `invokeRoute`'s contract as it shipped; changing any of these changes a public API. */\nconst INVOKE_ROUTE_POLICY: RoutePipelinePolicy = {\n honorPublicPaths: false,\n pathParamsWin: false,\n authPath: 'apiPrefix',\n validationOrder: 'path-query-body',\n nonZodParseError: 'throw',\n customErrorResponses: false,\n reserveServerContext: false,\n};\n\n/**\n * The path-scoped half of `checkRouteAuth` for a route run in-process: `requiresAuth: false`,\n * protected/public path handling, then `authorizeUser` / `authorize` / `rules` / the RBAC\n * default rules, all evaluated against the route's own request path and method.\n * Uses the user Mastra server auth already put in the request context; never re-authenticates.\n */\nasync function checkDispatchedRouteAuth(\n route: ServerRoute,\n pathParams: Record<string, unknown>,\n context: ServerContext,\n policy: RoutePipelinePolicy,\n): Promise<{ status: number; body: Record<string, unknown> } | null> {\n if (route.requiresAuth === false) {\n return null;\n }\n\n const { mastra, requestContext } = context;\n const outerHeaders = context.request?.headers;\n const getHeader = (name: string) => outerHeaders?.get(name) ?? undefined;\n const studioAuth = mastra.getStudio?.()?.auth;\n const serverAuth = mastra.getServer()?.auth;\n\n // Only the user Mastra server auth resolved counts; the legacy `user` key can be\n // written by code outside it (such as an MCP server's own auth mapper).\n const user = requestContext.get(MASTRA_USER_KEY);\n if (!policy.honorPublicPaths && (studioAuth || serverAuth) && !user) {\n return { status: 401, body: { error: 'Authentication required' } };\n }\n\n // Use the auth config the caller was authenticated with (recorded by checkRouteAuth);\n // only fall back to the request's client-type header when no mode was recorded.\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY) as MastraAuthMode | undefined;\n const recordedAuth = authMode === 'studio' ? studioAuth : authMode === 'server' ? serverAuth : undefined;\n const authConfig = (recordedAuth ?? resolveEffectiveAuthConfig(mastra, getHeader)?.authConfig) as\n | MastraAuthConfig\n | undefined;\n if (!authConfig) {\n return null;\n }\n\n // Server auth's authorization hooks see the route's own HTTP path, not the\n // path of whatever request (such as an MCP call) is running it.\n const method = route.method;\n let path: string | undefined;\n let customRouteAuthConfig: Map<string, boolean> | undefined;\n if (policy.authPath === 'adapter') {\n const { prefix, adapter } = resolveDispatchAdapter(mastra, context.routePrefix, requestContext);\n customRouteAuthConfig = adapter?.getCustomRouteAuthConfig?.();\n const customRoutes = adapter?.getCustomApiRoutes?.() ?? mastra.getServer()?.apiRoutes ?? [];\n // Opt-in built-in routes are listed as custom routes but served under the prefix.\n const isUnprefixed =\n customRoutes.includes(route as unknown as ApiRoute) && !(OPT_IN_ROUTES as readonly unknown[]).includes(route);\n if (isUnprefixed || prefix !== undefined) {\n path = `${isUnprefixed ? '' : prefix}${fillRoutePath(route.path, pathParams)}` || '/';\n }\n } else {\n const apiPrefix = normalizeRoutePath(mastra.getServer()?.apiPrefix ?? '/api');\n path = `${apiPrefix}${route.path.replace(/:(\\w+)/g, (_, name: string) =>\n encodeURIComponent(String(pathParams[name] ?? '')),\n )}`;\n }\n\n // Unlike an HTTP request, a path outside the protected patterns is not let through: the\n // path here is rebuilt, and a wrong prefix must not turn auth off. Only paths declared\n // public skip auth, plus the dev playground when no auth provider is configured.\n if (policy.honorPublicPaths && path !== undefined) {\n const isDevPlayground =\n typeof authConfig.authenticateToken !== 'function' &&\n process.env.MASTRA_DEV === 'true' &&\n getHeader('x-mastra-dev-playground') === 'true';\n const isPublic =\n !route.requiresAuth &&\n (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig));\n if (isDevPlayground || isPublic) {\n return null;\n }\n }\n\n if (!user) {\n return { status: 401, body: { error: 'Invalid or expired token' } };\n }\n\n if (path === undefined) {\n throw new Error(\n `dispatchRoute cannot tell which path ${method} ${route.path} is served under, so it cannot apply server auth to it. ` +\n 'Set `routePrefix` in the context to the prefix the server adapter serves its built-in routes under (such as \"/api\").',\n );\n }\n\n // Hooks get the caller's own headers when the request is forwarded, otherwise the token it authenticated with.\n const token = requestContext.get(MASTRA_AUTH_TOKEN_KEY);\n const headers =\n outerHeaders ?? (typeof token === 'string' && token ? { authorization: `Bearer ${token}` } : undefined);\n\n return authorizeAuthenticatedUser({\n path,\n method,\n user,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest: new Request(`http://localhost${path}`, { method, headers }),\n buildAuthorizeContext: () => null,\n });\n}\n\n/** The one in-process pipeline behind `dispatchRoute` and `invokeRoute`: path-scoped auth → validate → RBAC → FGA → handler. */\nasync function runRoutePipeline(\n route: ServerRoute,\n input: DispatchRouteInput,\n context: ServerContext,\n policy: RoutePipelinePolicy,\n): Promise<DispatchRouteResult> {\n const { mastra, requestContext } = context;\n\n if (policy.authPath === 'adapter') {\n const issues = findInvalidPathParams(route.path, input.pathParams ?? {});\n if (issues.length > 0) {\n return { ok: false, status: 400, body: { error: 'Invalid path parameters', issues } };\n }\n }\n\n const pathAuthError = await checkDispatchedRouteAuth(route, input.pathParams ?? {}, context, policy);\n if (pathAuthError) {\n return { ok: false, ...pathAuthError };\n }\n\n const validate = async <T>(\n kind: ValidationErrorContext,\n label: string,\n parse: () => Promise<T>,\n ): Promise<{ value: T } | { error: DispatchRouteResult }> => {\n try {\n return { value: await parse() };\n } catch (error) {\n if (isZodError(error)) {\n const { status, body } = resolveRouteValidationError(mastra, route, error, kind);\n return { error: { ok: false, status, body } };\n }\n if (policy.nonZodParseError === 'throw') {\n throw error;\n }\n return {\n error: {\n ok: false,\n status: 400,\n body: {\n error: `Invalid ${label}`,\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n },\n },\n };\n }\n };\n\n const parsed: { query?: Record<string, any>; body?: unknown; path?: Record<string, any> } = { body: input.body };\n const steps = {\n query: async () => {\n const result = await validate('query', 'query parameters', () => parseRouteQueryParams(route, input.query ?? {}));\n if ('error' in result) return result.error;\n parsed.query = result.value;\n },\n body: async () => {\n if (input.body === undefined && !route.bodySchema) return;\n const result = await validate('body', 'request body', () => parseRouteBody(route, input.body));\n if ('error' in result) return result.error;\n parsed.body = result.value;\n },\n path: async () => {\n const result = await validate('path', 'path parameters', () =>\n parseRoutePathParams(route, input.pathParams ?? {}),\n );\n if ('error' in result) return result.error;\n parsed.path = result.value;\n },\n };\n const order =\n policy.validationOrder === 'path-query-body'\n ? ([steps.path, steps.query, steps.body] as const)\n : ([steps.query, steps.body, steps.path] as const);\n for (const step of order) {\n const validationError = await step();\n if (validationError) return validationError;\n }\n const { body } = parsed;\n\n const params = {\n ...(policy.pathParamsWin ? {} : parsed.path),\n ...parsed.query,\n ...(typeof body === 'object' ? body : {}),\n ...(policy.pathParamsWin ? parsed.path : {}),\n };\n\n // With an adapter serving the routes, its own RBAC check runs so subclass overrides apply here too.\n const adapter =\n policy.authPath === 'adapter'\n ? resolveDispatchAdapter(mastra, context.routePrefix, requestContext).adapter\n : undefined;\n const authError = adapter?.checkRouteRBAC\n ? (adapter.checkRouteRBAC(route, requestContext) ?? (await checkRouteFGA(mastra, route, requestContext, params)))\n : await authorizeRoute(mastra, route, params, requestContext);\n if (authError) {\n return { ok: false, status: authError.status, body: { error: authError.error, message: authError.message } };\n }\n\n try {\n // HTTP adapters always set every server-context field, so request fields never stand in for them.\n const serverContext: ServerContext = policy.reserveServerContext\n ? {\n registeredTools: undefined,\n taskStore: undefined,\n routePrefix: undefined,\n request: undefined,\n ...context,\n }\n : context;\n return { ok: true, result: await route.handler({ ...params, ...serverContext }) };\n } catch (error) {\n const customResponse = policy.customErrorResponses ? getCustomHTTPExceptionResponse(error) : undefined;\n if (customResponse) {\n const text = await customResponse.text();\n let responseBody: unknown = text;\n try {\n responseBody = JSON.parse(text);\n } catch {\n // non-JSON custom response body stays as text\n }\n return { ok: false, status: customResponse.status, body: responseBody };\n }\n const { status, body: errorBody } = getHTTPErrorResponse(error);\n return { ok: false, status, body: errorBody };\n }\n}\n\n/**\n * Invoke a route in-process, enforcing what an adapter enforces for an HTTP request to it,\n * and never allowing more than that request would:\n *\n * 1. Path params must be what a URL can carry: a non-empty string for every `:param` (optional\n * `:param?` may be left out), and never `.` or `..`. Anything else is a 400.\n * 2. Path-scoped authorization from `checkRouteAuth`, evaluated against the route's own\n * path (the serving adapter's prefix + filled path params) and method: `requiresAuth: false`,\n * public paths, and `authorizeUser` / `authorize` / `rules` / the RBAC default rules.\n * Authentication is not repeated: the user (`MASTRA_USER_KEY`), permissions, and auth mode\n * must already be in `context.requestContext` from the caller's authenticated request, and\n * the auth config used is the one recorded there (`studio.auth` or `server.auth`), falling\n * back to the request's client-type header only when none was recorded. `authorizeUser`\n * receives the same `{ raw, headers, header() }` shape as over HTTP, wrapping a synthetic\n * `Request` for the route's path/method with the caller's headers (no body).\n * 3. Schema validation: query, then body, then path params.\n * 4. RBAC (the serving adapter's `checkRoutePermission`), then FGA (`checkRouteFGA`) on the\n * parsed params.\n * 5. `route.handler` with the parsed params and `context`.\n *\n * The adapter's paths and checks apply: the adapter serving the request `requestContext` came\n * from, else the only adapter serving the Mastra instance (or `context.routePrefix`, when set).\n * With none registered, `routePrefix` is required. When the adapter cannot be told (several\n * serve the prefix and none served this request), or `routePrefix` is one no registered adapter\n * serves, a caller without a user gets 401 and the call otherwise throws rather than guess.\n *\n * It is stricter than HTTP in three ways. With auth configured, a route needs a user unless\n * its path is declared public; a path merely outside the `protected` patterns is not let\n * through. Path params win over same-named query or body fields, so authorization and the\n * handler act on the resource named in the path. And request fields never stand in for\n * server context (`request`, `routePrefix`, `registeredTools`, `taskStore`) left out of `context`.\n *\n * Failures resolve to the status and JSON body an adapter would send; successful calls\n * return the raw handler result (streams are not converted).\n *\n * `invokeRoute` runs the same pipeline for JSON routes with a stricter contract: it never\n * skips auth for public paths and answers with `{ status, body }`.\n */\nexport async function dispatchRoute(\n route: ServerRoute,\n input: DispatchRouteInput,\n context: ServerContext,\n): Promise<DispatchRouteResult> {\n return runRoutePipeline(route, input, context, DISPATCH_ROUTE_POLICY);\n}\n\nexport interface InvokeRouteOptions {\n mastra: Mastra;\n /**\n * The caller's request context, already authenticated by Mastra (an HTTP route,\n * or an MCP request bridged by `applyMcpRequestAuth`). Its user, permissions and\n * auth mode decide what the caller may do.\n */\n requestContext: RequestContext;\n pathParams?: Record<string, string>;\n query?: Record<string, QueryParamValue>;\n body?: unknown;\n abortSignal?: AbortSignal;\n}\n\n/** What the route would have answered over HTTP. */\nexport interface InvokeRouteResult {\n status: number;\n body: unknown;\n}\n\n/**\n * Runs a server route in-process as the caller, with the checks its HTTP\n * endpoint applies on every adapter: authentication, auth's `authorizeUser`,\n * `authorize` and `rules` (against the route's path under `apiPrefix`), input\n * validation, RBAC permission and FGA. Lets code outside an HTTP request (such\n * as an MCP tool) reuse a route without proxying through the HTTP server.\n *\n * Authentication is not re-run: when server or studio auth is configured, the\n * request context must already carry the user Mastra server auth resolved\n * (`MASTRA_USER_KEY`), otherwise the call is refused with 401.\n *\n * Only JSON routes are supported; other response types throw. The handler gets\n * the parsed params, `mastra`, `requestContext` and `abortSignal`, but not the\n * HTTP-only `request`, `registeredTools`, `taskStore` or `routePrefix`, so\n * routes that read those are not suitable.\n *\n * Shares its pipeline with `dispatchRoute`, which follows the HTTP request more\n * closely (public paths, the adapter's prefix, custom error responses), passes a\n * full `ServerContext` and returns raw handler results.\n */\nexport async function invokeRoute(route: ServerRoute, options: InvokeRouteOptions): Promise<InvokeRouteResult> {\n if (route.responseType !== 'json') {\n throw new Error(\n `invokeRoute only runs JSON routes; ${route.method} ${route.path} answers with '${route.responseType}'`,\n );\n }\n\n const result = await runRoutePipeline(\n route,\n { pathParams: options.pathParams, query: options.query, body: options.body },\n {\n mastra: options.mastra,\n requestContext: options.requestContext,\n abortSignal: options.abortSignal ?? new AbortController().signal,\n },\n INVOKE_ROUTE_POLICY,\n );\n return result.ok ? { status: 200, body: result.result } : { status: result.status, body: result.body };\n}\n\n/**\n * Check FGA authorization for an HTTP route.\n * Returns null if authorized or FGA not configured, or an error object if denied.\n */\nexport async function checkRouteFGA(\n mastra: any,\n route: ServerRoute,\n requestContext: RequestContext,\n params: Record<string, unknown>,\n): Promise<{ status: number; error: string; message: string } | null> {\n // Use request context to determine which FGA provider to use (studio vs server)\n const fgaProvider = getFGAProvider(mastra, requestContext);\n if (!fgaProvider) return null;\n\n const fgaConfig = await resolveRouteFGAConfig(fgaProvider, route, requestContext, params);\n if (!fgaConfig) {\n if (fgaProvider.requireForProtectedRoutes && isProtectedFGARoute(route)) {\n return {\n status: 403,\n error: 'Forbidden',\n message: 'FGA authorization denied: route FGA metadata is required',\n };\n }\n return null;\n }\n\n const user = requestContext?.get('user');\n if (!user) {\n return {\n status: 403,\n error: 'Forbidden',\n message: 'FGA authorization denied: authenticated user is required',\n };\n }\n\n const resourceId =\n typeof fgaConfig.resourceId === 'function'\n ? fgaConfig.resourceId(params, { requestContext })\n : fgaConfig.resourceId || (fgaConfig.resourceIdParam ? (params[fgaConfig.resourceIdParam] as string) : undefined);\n if (!fgaConfig.resourceType || !resourceId) {\n return {\n status: 403,\n error: 'Forbidden',\n message: 'FGA authorization denied: route FGA metadata is incomplete',\n };\n }\n const effectivePermission = route.path ? getEffectivePermission(route) : null;\n const permission =\n fgaConfig.permission ||\n effectivePermission ||\n `${getFGAResourcePermissionSlug(fgaConfig.resourceType)}:${deriveFGAAction(route.method)}`;\n\n const authorized = await fgaProvider.check(user, {\n resource: { type: fgaConfig.resourceType, id: resourceId },\n permission,\n context: { resourceId, requestContext },\n });\n\n if (!authorized) {\n return {\n status: 403,\n error: 'Forbidden',\n message: `FGA authorization denied: cannot ${permission} on ${fgaConfig.resourceType}:${resourceId}`,\n };\n }\n\n return null;\n}\n\nfunction deriveFGAAction(method: string): string {\n switch (method.toUpperCase()) {\n case 'GET':\n return 'read';\n case 'DELETE':\n return 'delete';\n case 'POST':\n case 'PUT':\n case 'PATCH':\n return 'write';\n default:\n return 'read';\n }\n}\n\nfunction getFGAResourcePermissionSlug(resourceType: string): string {\n const resourcePermissionSlugs: Record<string, string> = {\n agent: 'agents',\n workflow: 'workflows',\n tool: 'tools',\n thread: 'memory',\n };\n\n return resourcePermissionSlugs[resourceType] ?? resourceType;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAOA,MAAa,gCAAgC;AAE7C,MAAM,iCAAiB,IAAI,QAAgB;AAC3C,MAAM,mCAAmB,IAAI,QAAyB;AACtD,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;;AAGlE,SAAS,gBAAgB,QAAiD;CACxE,MAAM,OAAO,OAAO,UAAU,CAAC,EAAE;CACjC,OAAO,QAAQ,OAAQ,KAA6B,sBAAsB,aACrE,OACD,KAAA;AACN;AAEA,SAAS,eAAe,QAAgB;CACtC,OAAO,OAAO,UAAU,CAAC,EAAE,KAAK,SAAS,CAAC;AAC5C;;AAGA,SAAS,mBAAmB,UAA2B;CACrD,IAAI;CACJ,IAAI;EACF,MAAM,IAAI,IAAI,QAAQ;CACxB,QAAQ;EACN,OAAO;CACT;CACA,IAAI,SAAS,SAAS,GAAG,GAAG,OAAO;CACnC,OAAO,IAAI,aAAa,YAAa,IAAI,aAAa,WAAW,eAAe,IAAI,IAAI,QAAQ;AAClG;;AAGA,SAAS,iBAAiB,QAAyB;CACjD,MAAM,EAAE,aAAa,eAAe,MAAM;CAC1C,IAAI,aAAa,KAAA,GAAW,OAAO;CACnC,IAAI,QAAQ,iBAAiB,IAAI,MAAM;CACvC,IAAI,UAAU,KAAA,GAAW;EACvB,QAAQ,mBAAmB,QAAQ;EACnC,iBAAiB,IAAI,QAAQ,KAAK;EAClC,IAAI,CAAC,OACH,OACG,UAAU,CAAC,EACV,MACA,8BAA8B,SAAS,wQAGzC;CAEN;CACA,OAAO;AACT;AAEA,SAAS,0BAA0B,QAAyB;CAC1D,OAAO,QAAQ,OAAO,UAAU,CAAC,EAAE,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EACL,QAAQ;EACR,OAAO;EACP,SAAS,oCAAoC,WAAW,MAAM,UAAU,aAAa,GAAG;CAC1F;CAGF,OAAO;AACT;AAEA,SAAS,gBAAgB,QAAwB;CAC/C,QAAQ,OAAO,YAAY,GAA3B;EACE,KAAK,OACH,OAAO;EACT,KAAK,UACH,OAAO;EACT,KAAK;EACL,KAAK;EACL,KAAK,SACH,OAAO;EACT,SACE,OAAO;CACX;AACF;AAEA,SAAS,6BAA6B,cAA8B;CAQlE,OAAO;EANL,OAAO;EACP,UAAU;EACV,MAAM;EACN,QAAQ;CAGmB,EAAE,iBAAiB;AAClD"}
|
|
1
|
+
{"version":3,"file":"server-adapter-B3kR1OJs.js","names":["isProtectedFGARoute","MASTRA_RESOURCE_ID_KEY"],"sources":["../src/server/mcp/oauth.ts","../src/server/server-adapter/routes/fga-manifest.ts","../src/server/server-adapter/mcp-auth.ts","../src/server/server-adapter/mcp-disconnect.ts","../src/server/server-adapter/redact.ts","../src/server/server-adapter/serialize.ts","../src/server/server-adapter/stream-disconnect.ts","../src/server/server-adapter/index.ts"],"sourcesContent":["import type { Mastra } from '@mastra/core/mastra';\nimport type { IMastraAuthProvider } from '@mastra/core/server';\nimport type { ServerRoute } from '../server-adapter/routes';\nimport { createRoute } from '../server-adapter/routes/route-builder';\nimport { isBuiltinMCPEnabled, resolveBuiltinMCPPath } from './config';\n\n/** RFC 9728 well-known path for OAuth protected-resource metadata. */\nexport const OAUTH_PROTECTED_RESOURCE_PATH = '/.well-known/oauth-protected-resource';\n\nconst warnedAudience = new WeakSet<Mastra>();\nconst resourceValidity = new WeakMap<Mastra, boolean>();\nconst LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);\n\n/** `server.auth` when it is a provider instance (only providers carry the OAuth hooks). */\nfunction getAuthProvider(mastra: Mastra): IMastraAuthProvider | undefined {\n const auth = mastra.getServer()?.auth;\n return auth && typeof (auth as IMastraAuthProvider).authenticateToken === 'function'\n ? (auth as IMastraAuthProvider)\n : undefined;\n}\n\nfunction getOAuthConfig(mastra: Mastra) {\n return mastra.getServer()?.mcp?.oauth ?? {};\n}\n\n/** RFC 9728 resource identifier: absolute https URL (http only for loopback hosts) without a fragment. */\nfunction isValidResourceUrl(resource: string): boolean {\n let url: URL;\n try {\n url = new URL(resource);\n } catch {\n return false;\n }\n if (resource.includes('#')) return false;\n return url.protocol === 'https:' || (url.protocol === 'http:' && LOOPBACK_HOSTS.has(url.hostname));\n}\n\n/** Whether `server.mcp.oauth.resource` is unset or valid. Logs one error per instance when it isn't. */\nfunction hasValidResource(mastra: Mastra): boolean {\n const { resource } = getOAuthConfig(mastra);\n if (resource === undefined) return true;\n let valid = resourceValidity.get(mastra);\n if (valid === undefined) {\n valid = isValidResourceUrl(resource);\n resourceValidity.set(mastra, valid);\n if (!valid) {\n mastra\n .getLogger()\n ?.error(\n `server.mcp.oauth.resource \"${resource}\" is not an absolute https URL without a fragment ` +\n '(http is only allowed for localhost). OAuth discovery for the built-in MCP server is disabled. ' +\n 'Token audience checks still use this value, so MCP requests are rejected unless the token audience matches it exactly.',\n );\n }\n }\n return valid;\n}\n\nfunction isBuiltinMCPAuthenticated(mastra: Mastra): boolean {\n return Boolean(mastra.getServer()?.auth) && isBuiltinMCPEnabled(mastra);\n}\n\n/**\n * Whether OAuth discovery applies: the built-in MCP endpoint is on, requires auth, and any configured\n * `server.mcp.oauth.resource` is valid. Gates the well-known routes and the `resource_metadata` challenge.\n */\nexport function isMCPOAuthDiscoveryEnabled(mastra: Mastra): boolean {\n return isBuiltinMCPAuthenticated(mastra) && hasValidResource(mastra);\n}\n\n/**\n * Whether the built-in MCP endpoint checks token audience: `server.mcp.oauth.resource` is set. An invalid value\n * only turns discovery off; the audience is still checked against it, so a config typo fails closed.\n */\nexport function isMCPAudienceEnforced(mastra: Mastra): boolean {\n return isBuiltinMCPAuthenticated(mastra) && getOAuthConfig(mastra).resource !== undefined;\n}\n\n/** Canonical URL of the MCP endpoint: `server.mcp.oauth.resource`, else derived from the request. */\nexport function resolveMCPResource(mastra: Mastra, prefix: string, requestUrl: string): string {\n return getOAuthConfig(mastra).resource ?? `${new URL(requestUrl).origin}${prefix}${resolveBuiltinMCPPath(mastra)}`;\n}\n\n/** Absolute URL of the path-suffixed metadata document advertised in `WWW-Authenticate`. */\nexport function mcpResourceMetadataUrl(mastra: Mastra, prefix: string, requestUrl: string): string {\n const origin = new URL(getOAuthConfig(mastra).resource ?? requestUrl).origin;\n return `${origin}${OAUTH_PROTECTED_RESOURCE_PATH}${prefix}${resolveBuiltinMCPPath(mastra)}`;\n}\n\n/** RFC 9728 metadata for the built-in MCP endpoint. Unset optional fields are omitted. */\nexport function resolveMCPResourceMetadata(mastra: Mastra, prefix: string, requestUrl: string) {\n const config = getOAuthConfig(mastra);\n const hints = getAuthProvider(mastra)?.getOAuthMetadata?.();\n const authorizationServers = config.authorizationServers ?? hints?.authorizationServers;\n const scopesSupported = config.scopesSupported ?? hints?.scopesSupported;\n // Built here rather than with @mastra/mcp's helpers: @mastra/mcp is an optional peer, and discovery must work\n // (and 401s must not fail) without it.\n return {\n resource: resolveMCPResource(mastra, prefix, requestUrl),\n ...(authorizationServers?.length ? { authorization_servers: authorizationServers } : {}),\n ...(scopesSupported?.length ? { scopes_supported: scopesSupported } : {}),\n bearer_methods_supported: ['header'],\n };\n}\n\n/**\n * `WWW-Authenticate` value for a 401 from the built-in MCP endpoint (RFC 6750 §3 auth-params, quoted and escaped).\n * `resource_metadata` is only included while discovery is enabled.\n */\nexport function mcpWWWAuthenticate(\n mastra: Mastra,\n prefix: string,\n requestUrl: string,\n error?: { error: string; error_description?: string },\n): string {\n const params = {\n ...(isMCPOAuthDiscoveryEnabled(mastra)\n ? { resource_metadata: mcpResourceMetadataUrl(mastra, prefix, requestUrl) }\n : {}),\n ...error,\n };\n const quoted = Object.entries(params)\n .filter(([, value]) => value !== undefined)\n .map(([key, value]) => `${key}=\"${value!.replace(/[\\\\\"]/g, '\\\\$&')}\"`);\n return `Bearer ${quoted.join(', ')}`;\n}\n\ntype CompositeProvider = IMastraAuthProvider & {\n getProviders?: () => readonly IMastraAuthProvider[];\n getAuthenticatedProvider?: (user: unknown) => IMastraAuthProvider | undefined;\n};\n\n/** The innermost provider that authenticated `user`, looking through `CompositeAuth`. Undefined when unknown. */\nfunction authenticatingLeaf(provider: IMastraAuthProvider, user: unknown): IMastraAuthProvider | undefined {\n const composite = provider as CompositeProvider;\n if (typeof composite.getAuthenticatedProvider !== 'function') return provider;\n const inner = composite.getAuthenticatedProvider(user);\n return inner && authenticatingLeaf(inner, user);\n}\n\n/**\n * When `server.mcp.oauth.resource` is set, the token's audience must include it. A provider that can't check the\n * audience is accepted, unless `requireAudience` is on: then the request is rejected.\n */\nexport async function checkMCPAudience(mastra: Mastra, user: unknown): Promise<boolean> {\n const { resource, requireAudience } = getOAuthConfig(mastra);\n if (resource === undefined) return true;\n const provider = getAuthProvider(mastra);\n if (requireAudience) {\n const leaf = provider && authenticatingLeaf(provider, user);\n if (typeof leaf?.verifyAudience !== 'function') return false;\n }\n if (typeof provider?.verifyAudience !== 'function') return true;\n return provider.verifyAudience(user, resource);\n}\n\nfunction leafProviders(provider: IMastraAuthProvider): IMastraAuthProvider[] {\n const inner = (provider as CompositeProvider).getProviders?.();\n return inner ? inner.flatMap(leafProviders) : [provider];\n}\n\n/** Warns once when `server.mcp.oauth.resource` is set but some provider cannot check token audience. */\nexport function warnOnUnenforcedMCPAudience(mastra: Mastra): void {\n if (warnedAudience.has(mastra) || getOAuthConfig(mastra).resource === undefined) return;\n warnedAudience.add(mastra);\n const auth = mastra.getServer()?.auth;\n if (!auth) return;\n const provider = getAuthProvider(mastra);\n const unenforced = provider\n ? leafProviders(provider)\n .filter(p => typeof p.verifyAudience !== 'function')\n .map(p => p.name || 'server.auth')\n : ['server.auth'];\n if (!unenforced.length) return;\n const consequence = getOAuthConfig(mastra).requireAudience\n ? 'requireAudience is on, so MCP requests authenticated by them are rejected.'\n : 'MCP requests authenticated by them are accepted for any audience. Set server.mcp.oauth.requireAudience to reject them.';\n mastra\n .getLogger()\n ?.warn(\n `server.mcp.oauth.resource is set, but ${unenforced.join(', ')} cannot check the token audience: ${consequence}`,\n );\n}\n\n/**\n * Public routes serving the metadata at `/.well-known/oauth-protected-resource` and its path-suffixed\n * form for the MCP endpoint. Mounted at the server root (outside the API prefix), not in SERVER_ROUTES.\n */\nexport function createMCPOAuthMetadataRoutes(mastra: Mastra, prefix: string): ServerRoute[] {\n const paths = [\n OAUTH_PROTECTED_RESOURCE_PATH,\n `${OAUTH_PROTECTED_RESOURCE_PATH}${prefix}${resolveBuiltinMCPPath(mastra)}`,\n ];\n return paths.map(path =>\n createRoute({\n method: 'GET',\n path,\n // A Response so the metadata can carry `Cache-Control: no-store` (its `resource` may echo the Host header).\n responseType: 'datastream-response',\n summary: 'OAuth protected-resource metadata',\n description: 'RFC 9728 metadata for the built-in MCP endpoint',\n tags: ['MCP'],\n requiresAuth: false,\n handler: async ({ mastra, request }) =>\n Response.json(resolveMCPResourceMetadata(mastra, prefix, request?.url ?? `http://localhost${path}`), {\n headers: { 'Cache-Control': 'no-store' },\n }),\n }),\n );\n}\n","import type { FGARouteConfig, MastraFGAPermissionInput } from '@mastra/core/auth/ee';\n\nimport { MASTRA_RESOURCE_ID_KEY } from '../../constants';\nimport { getEffectivePermission } from './permissions';\nimport type { ServerRoute } from './index';\n\nfunction isProtectedFGARoute(route: Pick<ServerRoute, 'requiresAuth'>): boolean {\n return route.requiresAuth !== false;\n}\n\nfunction getToolRoutePermission(path: string): MastraFGAPermissionInput {\n return path.includes('/execute') ? 'tools:execute' : 'tools:read';\n}\n\nfunction getAgentToolResourceId(agentId: string, toolId: string): string {\n return `${agentId}:${toolId}`;\n}\n\nfunction getMCPToolResourceId(serverId: string, toolId: string): string {\n return JSON.stringify([serverId, toolId]);\n}\n\nconst STORED_ROUTE_FGA: Record<string, { resourceType: string; idParams: string[] }> = {\n agents: { resourceType: 'stored-agents', idParams: ['storedAgentId', 'agentId'] },\n 'mcp-clients': { resourceType: 'stored-mcp-clients', idParams: ['storedMCPClientId', 'mcpClientId'] },\n 'prompt-blocks': { resourceType: 'stored-prompt-blocks', idParams: ['storedPromptBlockId', 'promptBlockId'] },\n scorers: { resourceType: 'stored-scorers', idParams: ['storedScorerId', 'scorerId'] },\n skills: { resourceType: 'stored-skills', idParams: ['storedSkillId'] },\n workspaces: { resourceType: 'stored-workspaces', idParams: ['storedWorkspaceId'] },\n};\n\nfunction getStoredResourceRouteFGAConfig(path: string, permission: MastraFGAPermissionInput): FGARouteConfig | null {\n const match = path.match(/^\\/stored\\/([^/]+)/);\n if (!match?.[1]) {\n return null;\n }\n\n const config = STORED_ROUTE_FGA[match[1]];\n if (!config) {\n return null;\n }\n\n return {\n resourceType: config.resourceType,\n resourceId: (params, { requestContext }) => {\n for (const idParam of config.idParams) {\n const id = params[idParam];\n if (typeof id === 'string' && id) {\n return id;\n }\n }\n\n const scopedResourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY);\n return typeof scopedResourceId === 'string' && scopedResourceId ? scopedResourceId : config.resourceType;\n },\n permission,\n };\n}\n\nexport function getBuiltInRouteFGAConfig(route: ServerRoute): FGARouteConfig | null {\n if (!isProtectedFGARoute(route) || !route.path || !route.method) {\n return null;\n }\n\n const permission = getEffectivePermission(route) as MastraFGAPermissionInput | null;\n if (!permission) {\n return null;\n }\n\n const path = route.path;\n const storedRouteConfig = getStoredResourceRouteFGAConfig(path, permission);\n if (storedRouteConfig) {\n return storedRouteConfig;\n }\n\n if (path.startsWith('/agents/:agentId/tools/:toolId')) {\n return {\n resourceType: 'tool',\n resourceId: ({ agentId, toolId }) => getAgentToolResourceId(String(agentId), String(toolId)),\n permission: getToolRoutePermission(path),\n };\n }\n\n if (path.startsWith('/agents/:agentId')) {\n return { resourceType: 'agent', resourceIdParam: 'agentId', permission };\n }\n\n if (path.startsWith('/workflows/:workflowId')) {\n return { resourceType: 'workflow', resourceIdParam: 'workflowId', permission };\n }\n\n if (path.startsWith('/tools/:toolId')) {\n return { resourceType: 'tool', resourceIdParam: 'toolId', permission };\n }\n\n if (path.startsWith('/mcp/:serverId/tools/:toolId')) {\n return {\n resourceType: 'tool',\n resourceId: ({ serverId, toolId }) => getMCPToolResourceId(String(serverId), String(toolId)),\n permission: getToolRoutePermission(path),\n };\n }\n\n if (path.startsWith('/mcp/:serverId')) {\n return { resourceType: 'mcp', resourceIdParam: 'serverId', permission };\n }\n\n if (path.startsWith('/knowledge/:knowledgeKey')) {\n return { resourceType: 'knowledge', resourceIdParam: 'knowledgeKey', permission };\n }\n\n if (path.startsWith('/memory/threads/:threadId') || path.startsWith('/memory/network/threads/:threadId')) {\n return { resourceType: 'thread', resourceIdParam: 'threadId', permission };\n }\n\n if (path === '/memory/threads' || path === '/memory/network/threads') {\n return {\n resourceType: 'thread',\n resourceId: ({ threadId, resourceId }) => {\n if (typeof threadId === 'string') return threadId;\n return typeof resourceId === 'string' ? resourceId : undefined;\n },\n permission,\n };\n }\n\n if (path === '/memory/save-messages' || path === '/memory/network/save-messages') {\n return {\n resourceType: 'thread',\n resourceId: ({ messages }) => {\n if (!Array.isArray(messages)) return undefined;\n const threadId = messages.find(\n message => message && typeof message === 'object' && 'threadId' in message,\n )?.threadId;\n return typeof threadId === 'string' ? threadId : undefined;\n },\n permission,\n };\n }\n\n // Same identity the handler checks: the caller's context resource wins over a requested resourceId.\n if (path === '/memory/working-memory') {\n return {\n resourceType: 'resource',\n resourceId: ({ resourceId }, { requestContext }) => {\n const contextResourceId = requestContext?.get(MASTRA_RESOURCE_ID_KEY);\n if (typeof contextResourceId === 'string' && contextResourceId) return contextResourceId;\n return typeof resourceId === 'string' ? resourceId : undefined;\n },\n permission,\n };\n }\n\n if (path === '/v1/responses') {\n return { resourceType: 'agent', resourceIdParam: 'agent_id', permission };\n }\n\n if (path.startsWith('/v1/responses/:responseId')) {\n return { resourceType: 'response', resourceIdParam: 'responseId', permission };\n }\n\n if (path === '/v1/conversations') {\n return { resourceType: 'agent', resourceIdParam: 'agent_id', permission };\n }\n\n if (path.startsWith('/v1/conversations/:conversationId')) {\n return { resourceType: 'conversation', resourceIdParam: 'conversationId', permission };\n }\n\n return null;\n}\n","import type { IncomingMessage } from 'node:http';\nimport type { RequestContext } from '@mastra/core/request-context';\n\nimport { MASTRA_AUTH_TOKEN_KEY, MASTRA_USER_KEY, RESERVED_REQUEST_CONTEXT_KEYS } from '../constants';\n\n/**\n * Key under which `applyMcpRequestAuth` attaches the trusted request context to\n * `req.auth`. `@mastra/mcp` reads the same registered symbol and copies the\n * values into the request context its tools receive. A symbol cannot come out\n * of a token or JSON payload, so only server code can supply it.\n */\nexport const MCP_TRUSTED_REQUEST_CONTEXT = Symbol.for('mastra.mcp.trustedRequestContext');\n\n/**\n * Shape the MCP SDK expects on `req.auth`.\n */\nexport interface McpAuthInfo {\n token: string;\n clientId: string;\n scopes: string[];\n extra?: Record<string, unknown>;\n}\n\n/**\n * Hook that sets `req.auth` before the MCP transport reads it.\n *\n * Receives the Node request handed to the MCP transport plus the Mastra\n * request context, which carries whatever server auth or your own middleware\n * resolved for this request. Setting `req.auth` is the caller's job; leaving it\n * unset is an explicit opt-out of the default bridge.\n *\n * The hook only owns `authInfo`. Whenever `req.auth` ends up set, the reserved\n * request context values (user, permissions, roles, resource, organization)\n * are still attached to it, so tools' `requestContext` reflects Mastra server\n * auth even if the hook's `authInfo` names a different principal.\n */\nexport type SetMcpRequestAuth = (req: IncomingMessage, requestContext: RequestContext) => void | Promise<void>;\n\nfunction normalizeScopes(value: unknown): string[] {\n if (Array.isArray(value)) return value.filter((s): s is string => typeof s === 'string');\n if (typeof value === 'string') return value.split(/[\\s,]+/).filter(Boolean);\n return [];\n}\n\nfunction resolveClientId(user: Record<string, unknown>): string {\n for (const key of ['id', 'sub', 'userId', 'email']) {\n const value = user[key];\n if (typeof value === 'string' && value) return value;\n }\n return '';\n}\n\n/**\n * Build the default `AuthInfo` from the Mastra request context.\n *\n * Returns `undefined` when the request carries no identity at all, so servers\n * without auth keep behaving exactly as before.\n */\nexport function buildMcpAuthInfoFromRequestContext(requestContext: RequestContext): McpAuthInfo | undefined {\n const user = requestContext.get(MASTRA_USER_KEY);\n const token = requestContext.get(MASTRA_AUTH_TOKEN_KEY);\n const hasUser = !!user && typeof user === 'object';\n const hasToken = typeof token === 'string' && token.length > 0;\n\n if (!hasUser && !hasToken) return undefined;\n\n const userRecord = (hasUser ? user : {}) as Record<string, unknown>;\n\n return {\n token: hasToken ? token : '',\n clientId: resolveClientId(userRecord),\n scopes: normalizeScopes(userRecord.scopes ?? userRecord.scope ?? userRecord.permissions),\n ...(hasUser ? { extra: { user: userRecord } } : {}),\n };\n}\n\n/**\n * Populate `req.auth` on the Node request that is about to be handed to an MCP\n * transport.\n *\n * Resolution order:\n * 1. An already-set `req.auth` keeps its identity.\n * 2. A configured `setRequestAuth` hook runs and fully owns the result.\n * 3. Otherwise the principal resolved by Mastra server auth is bridged from the\n * request context using the default mapping.\n *\n * Whichever way `req.auth` is set, the trusted request context is attached to\n * it so MCP tools see the same principal as Mastra routes.\n */\nexport async function applyMcpRequestAuth({\n req,\n requestContext,\n setRequestAuth,\n}: {\n req: IncomingMessage;\n requestContext?: RequestContext;\n setRequestAuth?: SetMcpRequestAuth;\n}): Promise<void> {\n const request = req as IncomingMessage & { auth?: unknown };\n if (!requestContext) return;\n\n if (!request.auth) {\n if (setRequestAuth) {\n await setRequestAuth(req, requestContext);\n } else {\n const authInfo = buildMcpAuthInfoFromRequestContext(requestContext);\n if (authInfo) request.auth = authInfo;\n }\n }\n\n if (request.auth && typeof request.auth === 'object') {\n attachTrustedRequestContext(request.auth, requestContext);\n }\n}\n\n/**\n * Hands MCP tools the values Mastra server auth resolved for this request\n * (user, permissions, roles, resource id, tenant, auth mode), so a tool called\n * over MCP is authorized the same way as the matching HTTP route. The token is\n * left out; it is already on `authInfo`.\n */\nfunction attachTrustedRequestContext(auth: object, requestContext: RequestContext): void {\n const trusted: Record<string, unknown> = {};\n for (const key of RESERVED_REQUEST_CONTEXT_KEYS) {\n if (key === MASTRA_AUTH_TOKEN_KEY || !requestContext.has(key)) continue;\n trusted[key] = requestContext.get(key);\n }\n Object.defineProperty(auth, MCP_TRUSTED_REQUEST_CONTEXT, { value: trusted, configurable: true });\n}\n","/**\n * Forwards a fetch `Request` abort to the simulated Node response used by fetch-based\n * adapters (Hono, Elysia, Next) to drive the MCP Node transport.\n *\n * `fetch-to-node`'s `toReqRes` ignores `Request.signal`, and the MCP Node transport only\n * aborts an in-flight request when `res` emits `close`. Without this, a client that\n * disconnects before any response bytes are sent leaves the tool call running to completion.\n *\n * Call it after `startHTTP` has been invoked so the transport's `close` listener is attached.\n */\nexport function propagateRequestAbort(\n signal: AbortSignal | undefined,\n res: {\n emit: (event: string) => boolean | void;\n once: (event: string, listener: () => void) => unknown;\n writableFinished?: boolean;\n },\n): void {\n if (!signal) return;\n\n const onAbort = () => {\n if (res.writableFinished) return;\n try {\n res.emit('close');\n } catch {\n // Already torn down - nothing left to abort.\n }\n };\n\n if (signal.aborted) {\n onAbort();\n return;\n }\n\n signal.addEventListener('abort', onAbort, { once: true });\n res.once('finish', () => signal.removeEventListener('abort', onAbort));\n}\n","import type { ChunkType } from '@mastra/core/stream';\n\n/**\n * Redacts request data from a v2 format payload.\n * Removes `metadata.request` and `output.steps[].request` from the payload.\n */\nfunction redactV2Payload(payload: Record<string, unknown>): Record<string, unknown> {\n const redactedPayload = { ...payload };\n\n // Remove metadata.request\n if (redactedPayload.metadata && typeof redactedPayload.metadata === 'object') {\n const { request, ...metadataRest } = redactedPayload.metadata as Record<string, unknown>;\n redactedPayload.metadata = metadataRest;\n }\n\n // Remove request from output.steps[]\n if (redactedPayload.output && typeof redactedPayload.output === 'object') {\n const output = { ...(redactedPayload.output as Record<string, unknown>) };\n if (Array.isArray(output.steps)) {\n output.steps = output.steps.map((step: Record<string, unknown>) => {\n if (step && typeof step === 'object') {\n const { request, ...stepRest } = step;\n return stepRest;\n }\n return step;\n });\n }\n redactedPayload.output = output;\n }\n\n return redactedPayload;\n}\n\n/**\n * Redacts sensitive data from stream chunks before they are sent to clients.\n *\n * This function strips out request bodies that may contain sensitive information\n * such as system prompts, tool definitions, API keys, and other configuration data.\n *\n * Handles both v1 (legacy) and v2 stream formats:\n *\n * v1 format (fields at root level):\n * - `step-start.request` - Contains the full LLM request body\n * - `step-finish.request` - Contains the request body\n * - `finish.request` - Contains the request body (if present)\n *\n * v2 format (fields nested in payload):\n * - `step-start.payload.request` - Contains the full LLM request body\n * - `step-finish.payload.metadata.request` - Contains the request metadata\n * - `step-finish.payload.output.steps[].request` - Contains request data for each step\n * - `finish.payload.metadata.request` - Contains the request metadata\n * - `finish.payload.output.steps[].request` - Contains request data for each step\n *\n * @param chunk - The stream chunk to redact\n * @returns A new chunk with sensitive data removed, or the original chunk if no redaction needed\n */\nexport function redactStreamChunk<OUTPUT = undefined>(chunk: ChunkType<OUTPUT>): ChunkType<OUTPUT> {\n if (!chunk || typeof chunk !== 'object') {\n return chunk;\n }\n\n const typedChunk = chunk as Record<string, unknown>;\n\n switch (chunk.type) {\n case 'step-start': {\n // Check if this is v2 format (has payload) or v1 format (request at root)\n if ('payload' in typedChunk && typedChunk.payload && typeof typedChunk.payload === 'object') {\n // v2 format: Remove request from payload\n const { payload, ...rest } = typedChunk;\n const { request, ...payloadRest } = payload as Record<string, unknown>;\n return {\n ...rest,\n type: 'step-start',\n payload: {\n ...payloadRest,\n // Keep an empty request object to maintain structure but remove body\n request: {},\n },\n } as ChunkType<OUTPUT>;\n } else if ('request' in typedChunk) {\n // v1 format: Remove request at root level\n const { request, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'step-start',\n // Keep an empty request object to maintain structure\n request: {},\n } as unknown as ChunkType<OUTPUT>;\n }\n return chunk;\n }\n\n case 'step-finish': {\n // Check if this is v2 format (has payload) or v1 format (request at root)\n if ('payload' in typedChunk && typedChunk.payload && typeof typedChunk.payload === 'object') {\n // v2 format: Remove request from metadata and output.steps[].request\n const { payload, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'step-finish',\n payload: redactV2Payload(payload as Record<string, unknown>),\n } as ChunkType<OUTPUT>;\n } else if ('request' in typedChunk) {\n // v1 format: Remove request at root level\n const { request, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'step-finish',\n } as unknown as ChunkType<OUTPUT>;\n }\n return chunk;\n }\n\n case 'finish': {\n // Check if this is v2 format (has payload) or v1 format (request at root)\n if ('payload' in typedChunk && typedChunk.payload && typeof typedChunk.payload === 'object') {\n // v2 format: Remove request from metadata and output.steps[].request\n const { payload, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'finish',\n payload: redactV2Payload(payload as Record<string, unknown>),\n } as ChunkType<OUTPUT>;\n } else if ('request' in typedChunk) {\n // v1 format: Remove request at root level\n const { request, ...rest } = typedChunk;\n return {\n ...rest,\n type: 'finish',\n } as unknown as ChunkType<OUTPUT>;\n }\n return chunk;\n }\n\n default:\n // Other chunk types don't contain sensitive request data\n return chunk;\n }\n}\n","import { safeStringify } from '@mastra/core/utils';\n\nexport type SerializedStreamChunk = { ok: true; json: string } | { ok: false; error: Error };\n\n/**\n * Serializes a stream chunk to JSON for wire transport.\n *\n * Stream chunks can contain values that plain `JSON.stringify` throws on\n * (e.g. BigInt produced by zod coercions/transforms in structuredOutput\n * schemas, or circular references) — `safeStringify` handles those. A single\n * bad chunk must never kill the whole stream — Studio relies on later chunks\n * (`workflow-step-result`, `workflow-finish`) to render run state.\n *\n * Returns `{ ok: false, error }` if the chunk cannot be serialized at all\n * (e.g. a throwing getter/toJSON) — callers should log the error, skip the\n * chunk, and keep streaming.\n */\nexport function serializeStreamChunk(chunk: unknown): SerializedStreamChunk {\n try {\n return { ok: true, json: safeStringify(withPlainPayloadError(chunk)) };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * `JSON.stringify(new Error('x'))` keeps only own enumerable fields, so an Error subclass that sets `name`\n * arrives as `{ name }` and clients show `[object Object]`. Send the message too; never the stack. An\n * error whose class curates its JSON (`toJSON`, e.g. MastraError) keeps that shape, so fields it leaves\n * out stay out.\n */\nfunction withPlainPayloadError(chunk: unknown): unknown {\n if (!chunk || typeof chunk !== 'object' || !('payload' in chunk)) return chunk;\n const { payload } = chunk;\n if (!payload || typeof payload !== 'object' || !('error' in payload)) return chunk;\n const { error } = payload;\n if (!(error instanceof Error)) return withoutStack(chunk, payload, error);\n const plain: Record<string, unknown> = { ...(curatedJson(error) ?? error), message: error.message };\n delete plain.stack;\n if (!plain.name && error.name !== 'Error') plain.name = error.name;\n return { ...chunk, payload: { ...payload, error: plain } };\n}\n\n/** An error that is already a plain object (a replayed one) is kept as is, minus its stack. */\nfunction withoutStack(chunk: object, payload: object, error: unknown): unknown {\n if (!error || typeof error !== 'object' || Array.isArray(error) || !('stack' in error)) return chunk;\n const { stack: _stack, ...rest } = error as Record<string, unknown>;\n return { ...chunk, payload: { ...payload, error: rest } };\n}\n\nfunction curatedJson(error: Error): Record<string, unknown> | undefined {\n const toJSON = (error as { toJSON?: unknown }).toJSON;\n if (typeof toJSON !== 'function') return undefined;\n try {\n const json: unknown = toJSON.call(error);\n return json && typeof json === 'object' ? (json as Record<string, unknown>) : undefined;\n } catch {\n return undefined;\n }\n}\n","interface NodeResponseLike {\n on(event: 'close' | 'drain', listener: () => void): unknown;\n off(event: 'close' | 'drain', listener: () => void): unknown;\n write(chunk: any): boolean;\n destroyed?: boolean;\n}\n\n/**\n * Cancels `reader` once when the Node response closes, so a disconnected client stops the upstream stream.\n *\n * Cancels right away when the response is already destroyed: if the client dropped while the route handler\n * was still running, `close` fired before this listener existed. Call `dispose()` before ending the response\n * so the close that follows a normal end does not cancel.\n */\nexport function cancelReaderOnResponseClose(\n reader: ReadableStreamDefaultReader<unknown>,\n res: NodeResponseLike,\n): { cancel: (reason: string) => void; dispose: () => void } {\n let canceled = false;\n const cancel = (reason: string) => {\n if (canceled) {\n return;\n }\n\n canceled = true;\n void reader.cancel(reason).catch(() => {});\n };\n const onClose = () => cancel('request aborted');\n res.on('close', onClose);\n\n if (res.destroyed) {\n onClose();\n }\n\n return { cancel, dispose: () => res.off('close', onClose) };\n}\n\n// Writes waiting for `drain`, per response. Each response gets one `drain` and one `close` listener for its whole life\n// instead of one pair per wait: the `compression` middleware forwards `res.on('drain')` to its zlib stream but not\n// `res.off`, so a listener removed after every wait would still pile up there.\nconst pendingWrites = new WeakMap<NodeResponseLike, Array<() => void>>();\n\nfunction getPendingWrites(res: NodeResponseLike): Array<() => void> {\n const existing = pendingWrites.get(res);\n\n if (existing) {\n return existing;\n }\n\n const queue: Array<() => void> = [];\n const release = () => {\n for (const resolve of queue.splice(0)) resolve();\n };\n res.on('drain', release);\n res.on('close', release);\n pendingWrites.set(res, queue);\n return queue;\n}\n\n/**\n * Writes `chunk` and, when the socket buffer is full, waits for `drain` so a slow client pauses reads from the\n * upstream stream instead of growing the buffer. Resolves on `close` too, so a dropped client never stalls the caller.\n */\nexport async function writeWithBackpressure(res: NodeResponseLike, chunk: unknown): Promise<void> {\n if (res.write(chunk) !== false || res.destroyed) {\n return;\n }\n\n await new Promise<void>(resolve => getPendingWrites(res).push(resolve));\n}\n","import { Readable } from 'node:stream';\nimport { pipeline } from 'node:stream/promises';\nimport type { ToolsInput } from '@mastra/core/agent';\nimport { hasPermission } from '@mastra/core/auth/ee';\nimport type { FGARouteConfig, FGARouteInfo, IFGAProvider, MastraFGAPermissionInput } from '@mastra/core/auth/ee';\nimport type { Mastra } from '@mastra/core/mastra';\nimport { RequestContext } from '@mastra/core/request-context';\nimport { MastraServerBase } from '@mastra/core/server';\nimport type {\n ApiRoute,\n HttpLoggingConfig,\n MastraAuthConfig,\n ValidationErrorContext,\n ValidationErrorResponse,\n} from '@mastra/core/server';\nimport type { ExecutionContext } from 'hono';\nimport { Hono } from 'hono';\nimport type { ZodError } from 'zod/v4';\nimport { z } from 'zod/v4';\n\nimport type { InMemoryTaskStore } from '../a2a/store';\nimport { CustomRouteMatcher } from '../auth/custom-route-matcher';\nimport {\n authorizeAuthenticatedUser,\n coreAuthMiddleware,\n findMatchingCustomRoute,\n canAccessPublicly,\n isCustomRoutePublic,\n isProtectedCustomRoute,\n pathMatchesPattern,\n} from '../auth/helpers';\nimport {\n MASTRA_AUTH_MODE_KEY,\n MASTRA_AUTH_TOKEN_KEY,\n MASTRA_CLIENT_TYPE_HEADER,\n MASTRA_IS_STUDIO_KEY,\n MASTRA_USER_KEY,\n MASTRA_USER_PERMISSIONS_KEY,\n isReservedRequestContextKey,\n isStudioClientTypeHeader,\n} from '../constants';\nimport type { MastraAuthMode } from '../constants';\nimport { formatZodError, isZodError } from '../handlers/error';\nimport { HTTPException } from '../http-exception';\nexport { isZodError, type ZodErrorLike } from '../handlers/error';\nimport {\n checkMCPAudience,\n createMCPOAuthMetadataRoutes,\n isMCPAudienceEnforced,\n isMCPOAuthDiscoveryEnabled,\n mcpWWWAuthenticate,\n warnOnUnenforcedMCPAudience,\n} from '../mcp/oauth';\nimport { resolveServerRoute } from '../mcp/route';\nimport { normalizeRoutePath } from '../utils';\nimport type { SetMcpRequestAuth } from './mcp-auth';\nimport { generateOpenAPIDocument, convertCustomRoutesToOpenAPIPaths } from './openapi-utils';\nimport type { ServerContext, ServerRoute } from './routes';\nimport { OPT_IN_ROUTES, SERVER_ROUTES, getEffectivePermission } from './routes';\nimport { getBuiltInRouteFGAConfig } from './routes/fga-manifest';\n\nexport * from './routes';\nexport { applyMcpRequestAuth, buildMcpAuthInfoFromRequestContext } from './mcp-auth';\nexport type { McpAuthInfo, SetMcpRequestAuth } from './mcp-auth';\nexport { propagateRequestAbort } from './mcp-disconnect';\nexport { BUILTIN_MCP_HTTP_ROUTE, resolveServerRoute } from '../mcp/route';\nexport {\n checkMCPAudience,\n createMCPOAuthMetadataRoutes,\n isMCPAudienceEnforced,\n isMCPOAuthDiscoveryEnabled,\n mcpWWWAuthenticate,\n} from '../mcp/oauth';\nexport { convertCustomRoutesToOpenAPIPaths } from './openapi-utils';\nexport { redactStreamChunk } from './redact';\nexport { serializeStreamChunk, type SerializedStreamChunk } from './serialize';\nexport { cancelReaderOnResponseClose, writeWithBackpressure } from './stream-disconnect';\nexport {\n MASTRA_AUTH_MODE_KEY,\n MASTRA_CLIENT_TYPE_HEADER,\n MASTRA_IS_STUDIO_KEY,\n MASTRA_KNOWLEDGE_PRINCIPALS_KEY,\n MASTRA_STUDIO_CLIENT_TYPE,\n RESERVED_REQUEST_CONTEXT_KEYS,\n isReservedRequestContextKey,\n isStudioClientTypeHeader,\n} from '../constants';\nexport type { MastraAuthMode } from '../constants';\n\nexport { WorkflowRegistry, normalizeRoutePath } from '../utils';\nexport { HTTPException };\n\nexport function getCustomHTTPExceptionResponse(error: unknown): Response | undefined {\n if (!(error instanceof HTTPException) || !error.res) {\n return undefined;\n }\n\n return error.getResponse();\n}\n\n/**\n * Response for an HTTPException thrown from a `registerApiRoute` handler, or undefined for\n * any other error (which callers keep behind a generic 500). Duck-typed so an HTTPException\n * from `hono/http-exception`, possibly a separate Hono install, is recognised too.\n */\nexport function getCustomRouteHTTPExceptionResponse(error: unknown): Response | undefined {\n if (!(error instanceof Error)) return undefined;\n const httpError = error as Error & { status?: unknown; res?: unknown; getResponse?: unknown };\n const status = httpError.status;\n if (\n typeof httpError.getResponse !== 'function' ||\n typeof status !== 'number' ||\n !Number.isInteger(status) ||\n status < 400 ||\n status > 599\n ) {\n return undefined;\n }\n if (httpError.res) return (httpError.getResponse as () => Response).call(httpError);\n return Response.json({ error: httpError.message }, { status });\n}\n\nexport interface HTTPErrorResponseBody {\n error: string;\n cause?: { failingItems: unknown[] } | { field: string; errors: Array<{ path: string; message: string }> };\n}\n\n/**\n * Only allowlisted causes are exposed to clients; any other cause stays server-side:\n * - `cause.failingItems` (dataset schema-update rejections)\n * - `cause.field` + `cause.errors` (schema validation failures), reduced to each error's path and message\n */\nfunction getSafeErrorCause(error: unknown): HTTPErrorResponseBody['cause'] {\n try {\n const raw = error instanceof Error ? error.cause : undefined;\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n if (Array.isArray((raw as any).failingItems)) {\n return { failingItems: (raw as any).failingItems };\n }\n const { field, errors } = raw as { field?: unknown; errors?: unknown };\n if (typeof field === 'string' && Array.isArray(errors)) {\n return {\n field,\n errors: errors.flatMap(e =>\n e && typeof e.path === 'string' && typeof e.message === 'string'\n ? [{ path: e.path, message: e.message }]\n : [],\n ),\n };\n }\n } catch {\n // property access threw (e.g. a getter) — omit cause\n }\n return undefined;\n}\n\n/**\n * Maps a handler error to the status and JSON body every adapter sends:\n * `error.status` (HTTPException) first, then `error.details.status` (MastraError), else 500.\n */\nexport function getHTTPErrorResponse(error: unknown): { status: number; body: HTTPErrorResponseBody } {\n const message = error instanceof Error ? error.message : 'Unknown error';\n\n if (error && typeof error === 'object') {\n if ('status' in error) {\n const cause = getSafeErrorCause(error);\n return { status: (error as any).status, body: { error: message, ...(cause ? { cause } : {}) } };\n }\n if ('details' in error && error.details && typeof error.details === 'object' && 'status' in error.details) {\n return { status: (error.details as any).status, body: { error: message } };\n }\n }\n\n return { status: 500, body: { error: message } };\n}\n\n/**\n * Hono/adapter context key set by the framework-public middleware.\n *\n * When true, the current request targets a route the framework has declared\n * public (via `createPublicRoute()` / `requiresAuth: false`). Adapter authors\n * MUST short-circuit any user-registered middleware for such requests so that\n * users cannot accidentally (or intentionally) 401 routes the framework needs\n * to keep reachable (e.g. Studio sign-in endpoints).\n */\nexport const MASTRA_FRAMEWORK_PUBLIC_KEY = '__mastraFrameworkPublic';\n\n/**\n * A pre-computed matcher that returns true if a given (path, method) targets a\n * route the framework has declared public via `requiresAuth: false`.\n *\n * Built once at server-adapter registration time from `SERVER_ROUTES` and the\n * `customRouteAuthConfig` map. Called by each adapter's context middleware to\n * stash a boolean on the per-request context under `MASTRA_FRAMEWORK_PUBLIC_KEY`.\n */\nexport type FrameworkPublicMatcher = (path: string, method: string) => boolean;\n\nexport interface OpenAPIConfig {\n title?: string;\n version?: string;\n description?: string;\n path?: string;\n}\n\nexport interface BodyLimitOptions {\n maxSize: number;\n onError: (error: unknown) => unknown;\n}\n\nexport interface StreamOptions {\n /**\n * When true (default), redacts sensitive data from stream chunks\n * (system prompts, tool definitions, API keys) before sending to clients.\n *\n * Set to false to include full request data in stream chunks (useful for\n * debugging or internal services that need access to this data).\n *\n * @default true\n */\n redact?: boolean;\n}\n\nconst AGENT_CHANNEL_WEBHOOK_PATH = /^\\/api\\/agents\\/([^/]+)\\/channels\\/([^/]+)\\/webhook\\/?$/;\n\n/**\n * MCP transport options for configuring MCP HTTP and SSE transports.\n */\nexport interface MCPOptions {\n /**\n * When true, runs in stateless mode without session management.\n * Ideal for serverless environments (Cloudflare Workers, Vercel Edge, etc.)\n * where you can't maintain persistent connections across requests.\n *\n * @default false\n */\n serverless?: boolean;\n /**\n * Custom session ID generator function.\n */\n sessionIdGenerator?: () => string;\n /**\n * Sets `req.auth` before the MCP transport reads it, which is what surfaces as\n * `extra.authInfo` inside tool and agent execution.\n *\n * When omitted, the principal resolved by `server.auth` is bridged\n * automatically. Provide this hook when your own middleware performs the\n * verification and you want full control over the resulting `AuthInfo`.\n *\n * The hook only controls `authInfo`. Tools still receive the user,\n * permissions, roles and other reserved values Mastra server auth resolved\n * in their `requestContext`, even when the hook's `authInfo` names a\n * different principal.\n */\n setRequestAuth?: SetMcpRequestAuth;\n}\n\n/**\n * Query parameter values parsed from HTTP requests.\n * Supports both single values and arrays (for repeated query params like ?tag=a&tag=b).\n */\nexport type QueryParamValue = string | string[];\n\n/**\n * Parsed request parameters returned by getParams().\n */\nexport interface ParsedRequestParams {\n urlParams: Record<string, string>;\n queryParams: Record<string, QueryParamValue>;\n body: unknown;\n /**\n * Error that occurred while parsing the request body.\n * When set, the server should return a 400 Bad Request response.\n */\n bodyParseError?: {\n message: string;\n };\n}\n\nfunction isAbortSignalError(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false;\n\n const { code, name } = error as { code?: string; name?: string };\n return name === 'AbortError' || code === 'ABORT_ERR';\n}\n\nfunction isExpectedResponseCloseError(error: unknown): boolean {\n if (!error || typeof error !== 'object') return false;\n\n const { code } = error as { code?: string };\n return (\n code === 'ECONNRESET' ||\n code === 'EPIPE' ||\n code === 'ERR_STREAM_DESTROYED' ||\n code === 'ERR_STREAM_WRITE_AFTER_END' ||\n code === 'ERR_STREAM_PREMATURE_CLOSE'\n );\n}\n\n/**\n * Returns `response` with a pass-through body that holds the re-dispatched\n * custom route `request` until that body is fully read, errors or is cancelled.\n *\n * `new Request(url, { signal })` gives the request its own signal and forwards\n * the outer abort to it through a listener that only weakly references the\n * request's controller (nodejs/undici#4068). Once a custom route returns a\n * streaming Response, nothing else holds that inner Request, so a GC can drop\n * it and a client disconnect never reaches `c.req.raw.signal` (#29154).\n *\n * The reference lives on the body because the body is reachable exactly while\n * an adapter is still sending the response. Anything reachable from the outer\n * signal (a WeakMap keyed by it, or an abort listener on it) would leak instead:\n * undici's request finalizer holds the outer signal strongly while the inner\n * controller is alive, so signal -> request -> controller -> signal is never\n * collected when the signal never aborts, as after a normal Express response.\n * An abort ends or cancels the body, which releases the request too.\n */\nfunction retainRequestWhileBodyIsOpen(response: Response, request: Request): Response {\n const source = response.body;\n if (!source) return response;\n\n const reader = source.getReader();\n const retained: { request?: Request } = { request };\n const release = () => {\n retained.request = undefined;\n };\n const body = new ReadableStream<Uint8Array>(\n {\n async pull(controller) {\n try {\n const { done, value } = await reader.read();\n if (done) {\n release();\n controller.close();\n } else {\n controller.enqueue(value);\n }\n } catch (error) {\n release();\n controller.error(error);\n }\n },\n cancel(reason) {\n release();\n return reader.cancel(reason);\n },\n },\n // Read from the route's body only when the adapter asks for a chunk.\n { highWaterMark: 0 },\n );\n return new Response(body, { status: response.status, statusText: response.statusText, headers: response.headers });\n}\n\nfunction isResponseClosed(response: { writableEnded?: boolean; destroyed?: boolean }): boolean {\n return Boolean(response.writableEnded || response.destroyed);\n}\n\nfunction isProtectedFGARoute(route: Pick<ServerRoute, 'requiresAuth'>): boolean {\n return route.requiresAuth !== false;\n}\n\nfunction formatRoute(route: Pick<ServerRoute, 'method' | 'path'>): string {\n return `${route.method} ${route.path}`;\n}\n\n/** A schema-aware custom route created by `createRoute()`. */\ntype SchemaCustomApiRoute = Extract<ApiRoute, { readonly _mastraSchemaRoute: true }>;\n/** A Hono-style custom route created by `registerApiRoute()`. */\ntype HonoCustomApiRoute = Exclude<ApiRoute, SchemaCustomApiRoute>;\n\nfunction isSchemaApiRoute(route: ApiRoute): route is SchemaCustomApiRoute {\n return '_mastraSchemaRoute' in route && route._mastraSchemaRoute === true;\n}\n\nexport function getFGAProvider(mastra: any, requestContext?: RequestContext): IFGAProvider | undefined {\n // If we have request context, check auth mode to determine which FGA provider to use\n if (requestContext) {\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY);\n if (authMode === 'studio') {\n const studioFga = mastra?.getStudio?.()?.fga;\n if (studioFga) return studioFga as IFGAProvider;\n }\n }\n // Fall back to server FGA\n return mastra?.getServer?.()?.fga as IFGAProvider | undefined;\n}\n\nfunction getFGARouteInfo(route: ServerRoute): FGARouteInfo {\n return {\n path: route.path,\n method: route.method,\n requiresAuth: route.requiresAuth,\n requiresPermission: route.requiresPermission,\n fga: route.fga,\n };\n}\n\nfunction getRoutePermissions(route: ServerRoute): MastraFGAPermissionInput[] {\n return [getEffectivePermission(route), route.fga?.permission]\n .flatMap(value => (Array.isArray(value) ? value : [value]))\n .filter((permission): permission is MastraFGAPermissionInput => Boolean(permission));\n}\n\nasync function resolveRouteFGAConfig(\n fgaProvider: IFGAProvider,\n route: ServerRoute,\n requestContext: RequestContext,\n params: Record<string, unknown>,\n): Promise<FGARouteConfig | null | undefined> {\n if (route.fga) {\n return route.fga;\n }\n\n const resolvedConfig = await fgaProvider.resolveRouteFGA?.({\n route: getFGARouteInfo(route),\n params,\n requestContext,\n });\n if (resolvedConfig) {\n return resolvedConfig;\n }\n\n return getBuiltInRouteFGAConfig(route);\n}\n\nfunction getSchemaTypeName(schema: z.ZodTypeAny): string | undefined {\n const schemaDef = (schema as any)?._def ?? (schema as any)?.def;\n return schemaDef?.typeName ?? schemaDef?.type;\n}\n\nfunction unwrapOptionalNullable(schema: z.ZodTypeAny): z.ZodTypeAny {\n let inner = schema;\n let typeName = getSchemaTypeName(inner);\n\n while (\n typeName === 'ZodOptional' ||\n typeName === 'ZodNullable' ||\n typeName === 'optional' ||\n typeName === 'nullable'\n ) {\n const innerDef = (inner as any)?._def ?? (inner as any)?.def;\n if (!innerDef?.innerType) {\n return inner;\n }\n inner = innerDef.innerType;\n typeName = getSchemaTypeName(inner);\n }\n\n return inner;\n}\n\nfunction parseComplexQueryParams(\n queryParamSchema: z.ZodTypeAny,\n params: Record<string, unknown>,\n): Record<string, unknown> {\n if (!(queryParamSchema instanceof z.ZodObject)) {\n return params;\n }\n\n const parsedParams: Record<string, unknown> = { ...params };\n const shape = queryParamSchema.shape as Record<string, z.ZodTypeAny>;\n\n for (const [key, fieldSchema] of Object.entries(shape)) {\n const rawValue = parsedParams[key];\n if (typeof rawValue !== 'string') {\n continue;\n }\n\n const unwrappedField = unwrapOptionalNullable(fieldSchema);\n const typeName = getSchemaTypeName(unwrappedField);\n const isComplex =\n typeName === 'ZodObject' ||\n typeName === 'ZodArray' ||\n typeName === 'ZodRecord' ||\n typeName === 'object' ||\n typeName === 'array' ||\n typeName === 'record';\n\n if (!isComplex) {\n continue;\n }\n\n try {\n parsedParams[key] = JSON.parse(rawValue);\n } catch {\n // Keep original string; schema validation will surface a clear error.\n }\n }\n\n return parsedParams;\n}\n\n/**\n * Property names that must never be written onto objects built from untrusted\n * input: assigning them can mutate the object's prototype chain.\n */\nconst UNSAFE_OBJECT_KEYS = new Set(['__proto__', 'prototype', 'constructor']);\n\n/**\n * Returns whether `key` is safe to use as a property name when building an\n * object from untrusted input (query strings, form fields, etc.).\n */\nexport function isSafeObjectKey(key: string): boolean {\n return !UNSAFE_OBJECT_KEYS.has(key);\n}\n\n/**\n * Normalizes query parameters from various HTTP framework formats to a consistent structure.\n * Handles both single string values and arrays (for repeated query params like ?tag=a&tag=b).\n * Reconstructs bracket-notation keys (e.g., `orderBy[field]=createdAt`) into JSON strings\n * so that z.preprocess JSON.parse can handle them.\n * Filters out non-string values that some frameworks may include.\n *\n * @param rawQuery - Raw query parameters from the HTTP framework (may contain strings, arrays, or nested objects)\n * @returns Normalized query parameters as Record<string, string | string[]>\n */\nexport function normalizeQueryParams(rawQuery: Record<string, unknown>): Record<string, QueryParamValue> {\n const queryParams: Record<string, QueryParamValue> = {};\n // Collect bracket-notation keys: e.g., \"orderBy[field]\" → parent \"orderBy\", child \"field\"\n const bracketGroups: Record<string, Record<string, string>> = {};\n\n for (const [key, value] of Object.entries(rawQuery)) {\n const bracketMatch = key.match(/^([^[]+)\\[([^\\]]+)\\]$/);\n if (bracketMatch) {\n const parent = bracketMatch[1]!;\n const child = bracketMatch[2]!;\n const strValue = Array.isArray(value)\n ? value.filter((v): v is string => typeof v === 'string')[0]\n : typeof value === 'string'\n ? value\n : undefined;\n if (strValue !== undefined && isSafeObjectKey(parent) && isSafeObjectKey(child)) {\n if (!Object.hasOwn(bracketGroups, parent)) {\n bracketGroups[parent] = {};\n }\n bracketGroups[parent]![child] = strValue;\n }\n } else if (typeof value === 'string') {\n if (isSafeObjectKey(key)) {\n queryParams[key] = value;\n }\n } else if (Array.isArray(value)) {\n if (!isSafeObjectKey(key)) {\n continue;\n }\n // Filter to only string values (some frameworks include nested objects)\n const stringValues = value.filter((v): v is string => typeof v === 'string');\n // Convert single-value arrays back to strings for compatibility\n queryParams[key] = stringValues.length === 1 ? stringValues[0]! : stringValues;\n }\n }\n\n // Merge bracket groups as JSON strings (only if the parent key wasn't already set directly)\n for (const [parent, children] of Object.entries(bracketGroups)) {\n if (!Object.hasOwn(queryParams, parent)) {\n queryParams[parent] = JSON.stringify(children);\n }\n }\n\n return queryParams;\n}\n\n/**\n * Abstract base class for server adapters that handle HTTP requests.\n *\n * This class extends `MastraServerBase` to inherit app storage functionality\n * and provides the framework for registering routes, middleware, and handling requests.\n *\n * Framework-specific adapters in @mastra/hono and @mastra/express extend this class\n * (both named `MastraServer` in their respective packages) and implement the abstract\n * methods for their specific framework.\n *\n * @template TApp - The type of the server app (e.g., Hono, Express Application)\n * @template TRequest - The type of the request object\n * @template TResponse - The type of the response object\n */\nexport abstract class MastraServer<TApp, TRequest, TResponse> extends MastraServerBase<TApp> {\n /** Request bodies cannot set agent scopes: handlers strip `scopes`, and `mastra__scopes` is a reserved key. */\n readonly reservesAgentScopes = true;\n\n protected mastra: Mastra;\n protected bodyLimitOptions?: BodyLimitOptions;\n protected tools?: ToolsInput;\n protected prefix?: string;\n protected openapiPath?: string;\n protected taskStore?: InMemoryTaskStore;\n protected customRouteAuthConfig?: Map<string, boolean>;\n protected streamOptions: StreamOptions;\n protected httpLoggingConfig?: HttpLoggingConfig;\n protected customApiRoutes?: ApiRoute[];\n protected mcpOptions?: MCPOptions;\n /** This adapter's `registerDispatchAdapter` handle, recorded on each request it serves. */\n private readonly dispatchAdapter: DispatchAdapterHandle;\n private customRouteHandler:\n | ((\n request: Request,\n env?: { requestContext?: RequestContext },\n executionCtx?: ExecutionContext,\n ) => Promise<Response>)\n | null = null;\n /** Mirrors the custom-route app's router so auth can ask which route a request runs. */\n private customRouteMatcher: CustomRouteMatcher<{\n method: string;\n path: string;\n handlerCount: number;\n route: HonoCustomApiRoute;\n }> | null = null;\n\n /**\n * Whether custom (non-schema) API routes were registered. Adapters use this\n * at request time to decide if they need to preserve a pristine copy of the\n * request body for the custom-route bridge.\n */\n protected get hasCustomRouteHandler(): boolean {\n return this.customRouteHandler !== null;\n }\n\n constructor({\n app,\n mastra,\n bodyLimitOptions,\n tools,\n prefix = '/api',\n openapiPath = '',\n taskStore,\n customRouteAuthConfig,\n streamOptions,\n customApiRoutes,\n mcpOptions,\n }: {\n app: TApp;\n mastra: Mastra;\n bodyLimitOptions?: BodyLimitOptions;\n tools?: ToolsInput;\n prefix?: string;\n openapiPath?: string;\n taskStore?: InMemoryTaskStore;\n customRouteAuthConfig?: Map<string, boolean>;\n streamOptions?: StreamOptions;\n customApiRoutes?: ApiRoute[];\n /**\n * MCP transport options applied to all MCP HTTP and SSE routes.\n * Individual routes can override these via MCPHttpTransportResult.mcpOptions.\n */\n mcpOptions?: MCPOptions;\n }) {\n super({ app, name: 'MastraServer' });\n this.mastra = mastra;\n this.bodyLimitOptions = bodyLimitOptions;\n this.tools = tools;\n this.prefix = normalizeRoutePath(prefix);\n this.dispatchAdapter = registerDispatchAdapter(mastra, {\n prefix: this.prefix,\n getCustomRouteAuthConfig: () => this.customRouteAuthConfig,\n getCustomApiRoutes: () => this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [],\n checkRouteRBAC: (route, requestContext) => this.checkRouteRBAC(route, requestContext),\n });\n this.openapiPath = openapiPath;\n this.taskStore = taskStore;\n this.customRouteAuthConfig = customRouteAuthConfig;\n this.streamOptions = { redact: true, ...streamOptions };\n this.customApiRoutes = customApiRoutes;\n this.mcpOptions = mcpOptions;\n\n // Parse HTTP logging configuration\n const serverConfig = mastra.getServer();\n this.httpLoggingConfig = this.parseLoggingConfig(serverConfig?.build?.apiReqLogs);\n\n // Automatically register this adapter with Mastra so getServerApp() works\n mastra.setMastraServer(this);\n }\n\n /**\n * Parses the apiReqLogs configuration into a normalized HttpLoggingConfig.\n * @param config - The raw config value from server.build.apiReqLogs\n * @returns Normalized HttpLoggingConfig or undefined if disabled\n */\n private parseLoggingConfig(config?: boolean | HttpLoggingConfig): HttpLoggingConfig | undefined {\n if (config === true) {\n // Default configuration when enabled with just `true`\n return {\n enabled: true,\n level: 'info',\n redactHeaders: ['authorization', 'cookie'],\n };\n }\n if (typeof config === 'object' && config.enabled) {\n // Merge user config with defaults\n return {\n enabled: true,\n level: config.level || 'info',\n excludePaths: config.excludePaths,\n includeHeaders: config.includeHeaders,\n includeQueryParams: config.includeQueryParams,\n redactHeaders: [...new Set([...['authorization', 'cookie'], ...(config.redactHeaders || [])])],\n };\n }\n return undefined;\n }\n\n /**\n * Determines if a request to the given path should be logged.\n * @param path - The request path to check\n * @returns true if the request should be logged, false otherwise\n */\n protected shouldLogRequest(path: string): boolean {\n if (!this.httpLoggingConfig?.enabled) {\n return false;\n }\n\n // Uses segment-aware matching so '/health' excludes '/health' and '/health/deep' but not '/healthcheck'\n const excludePaths = this.httpLoggingConfig.excludePaths || [];\n return !excludePaths.some((excluded: string) => path === excluded || path.startsWith(excluded + '/'));\n }\n\n /** Warn when a request looks like an agent channel webhook whose route was never registered. */\n protected warnIfUnregisteredChannelWebhook(path: string, method: string, status: number): void {\n if (status !== 404 || method.toUpperCase() !== 'POST') return;\n\n const match = AGENT_CHANNEL_WEBHOOK_PATH.exec(path);\n if (!match) return;\n\n const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes;\n if (findMatchingCustomRoute(path, method.toUpperCase(), routes)) return;\n\n const agentId = match[1]!;\n const platform = match[2]!;\n const platformLabel = /^[a-z0-9]+(?:[-_][a-z0-9]+)*$/i.test(platform)\n ? platform\n .split(/[-_]/)\n .map(segment => segment.charAt(0).toUpperCase() + segment.slice(1))\n .join(' ')\n : 'channel';\n this.mastra\n .getLogger()\n ?.warn(\n `Received a ${platformLabel} webhook, but this agent doesn't have a ${platformLabel} adapter. Add one to the agent's channels.adapters configuration and restart the server.`,\n { agentId, platform },\n );\n }\n\n protected mergeRequestContext({\n paramsRequestContext,\n bodyRequestContext,\n }: {\n paramsRequestContext?: Record<string, any>;\n bodyRequestContext?: Record<string, any>;\n }): RequestContext {\n const requestContext = new RequestContext();\n bindDispatchAdapter(requestContext, this.dispatchAdapter);\n if (bodyRequestContext) {\n for (const [key, value] of Object.entries(bodyRequestContext)) {\n if (isReservedRequestContextKey(key)) continue;\n requestContext.set(key, value);\n }\n }\n if (paramsRequestContext) {\n for (const [key, value] of Object.entries(paramsRequestContext)) {\n if (isReservedRequestContextKey(key)) continue;\n requestContext.set(key, value);\n }\n }\n return requestContext;\n }\n\n protected applyRequestMetadataToContext({\n requestContext,\n getHeader,\n }: {\n requestContext: RequestContext;\n getHeader: (name: string) => string | undefined;\n }): void {\n if (isStudioClientTypeHeader(getHeader(MASTRA_CLIENT_TYPE_HEADER))) {\n requestContext.set(MASTRA_IS_STUDIO_KEY, true);\n }\n }\n\n /**\n * Determines which auth configuration to use for the current request.\n *\n * Request routing logic:\n * 1. If `x-mastra-client-type: studio` header is present AND `studio.auth` is configured:\n * → Use studio auth (for internal team members accessing Studio UI)\n * 2. If studio header is present but `studio.auth` is NOT configured:\n * → No auth required (Studio development mode)\n * 3. Otherwise:\n * → Use server auth (for external customers calling API)\n *\n * Security note: The header is only for routing - auth validation happens\n * via session cookies/tokens. If someone spoofs the studio header but doesn't\n * have a valid studio session, they'll get a 401 (not fall back to server auth).\n */\n protected getEffectiveAuthConfig(\n getHeader: (name: string) => string | undefined,\n ): { authConfig: unknown; authMode: MastraAuthMode } | null {\n return resolveEffectiveAuthConfig(this.mastra, getHeader);\n }\n\n /**\n * Gets the effective RBAC provider for the current request based on auth mode.\n *\n * @deprecated Never consulted by route permission checks, so overriding it has no effect.\n * Override `checkRoutePermission` to change how a route's permission is decided.\n */\n protected getEffectiveRBACProvider(requestContext: RequestContext) {\n return getEffectiveRBACProvider(this.mastra, requestContext);\n }\n\n /**\n * Gets the effective FGA provider for the current request based on auth mode.\n */\n protected getEffectiveFGAProvider(requestContext: RequestContext) {\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY) as MastraAuthMode | undefined;\n\n if (authMode === 'studio') {\n return this.mastra.getStudio?.()?.fga ?? this.mastra.getServer()?.fga;\n }\n\n return this.mastra.getServer()?.fga;\n }\n\n /**\n * Check if the current request should be authenticated/authorized.\n * Returns null if auth passes, or an error response if it fails.\n *\n * This is a thin wrapper around coreAuthMiddleware that:\n * 1. Routes to the correct auth provider (studio vs server) based on request headers\n * 2. Handles route-level requiresAuth opt-out (not available in global middleware)\n * 3. Delegates all other auth logic to coreAuthMiddleware\n * 4. Translates the AuthResult into the {status, error} format adapters expect\n *\n * Security: When `x-mastra-client-type: studio` header is present and studio auth\n * is configured, we ONLY use studio auth. If authentication fails, we return 401\n * and redirect to login - we do NOT fall back to server auth. This prevents\n * external users from spoofing the studio header to access Studio UI.\n */\n protected async checkRouteAuth(\n route: ServerRoute,\n context: {\n path: string;\n method: string;\n getHeader: (name: string) => string | undefined;\n getQuery: (name: string) => string | undefined;\n requestContext: RequestContext;\n /** Raw Request object for cookie-based auth providers */\n request?: Request;\n /** Build framework-specific context for authorize() callback */\n buildAuthorizeContext?: () => unknown;\n /** Overrides the server's custom route auth map for this check. */\n customRouteAuthConfig?: Map<string, boolean>;\n },\n ): Promise<{ status: number; error: string; headers?: Record<string, string> } | null> {\n if (route.authTransport === 'bearer') {\n return this.checkBearerRouteAuth(route, context);\n }\n\n // Determine which auth config to use based on request type\n const effectiveAuth = this.getEffectiveAuthConfig(context.getHeader);\n\n // No auth config means no auth required\n if (!effectiveAuth) {\n return null;\n }\n\n const { authConfig, authMode } = effectiveAuth;\n\n // Store auth mode in request context for downstream RBAC/FGA provider selection\n context.requestContext.set(MASTRA_AUTH_MODE_KEY, authMode);\n\n // Check route-level requiresAuth flag first (explicit per-route setting)\n // This opt-out is route-specific and not available in the global middleware\n if (route.requiresAuth === false) {\n return null;\n }\n\n // Extract token from headers/query\n const authHeader = context.getHeader('authorization');\n let token: string | null = authHeader ? authHeader.replace('Bearer ', '') : null;\n if (!token) {\n token = context.getQuery('apiKey') || null;\n }\n\n const fallbackHeaders = new Headers();\n for (const headerName of ['authorization', 'cookie']) {\n const headerValue = context.getHeader(headerName);\n if (headerValue) {\n fallbackHeaders.set(headerName, headerValue);\n }\n }\n\n // Delegate to coreAuthMiddleware for all auth logic\n const result = await coreAuthMiddleware({\n path: context.path,\n method: context.method,\n getHeader: context.getHeader,\n mastra: this.mastra,\n authConfig: authConfig as any,\n customRouteAuthConfig: context.customRouteAuthConfig ?? this.customRouteAuthConfig,\n requestContext: context.requestContext,\n rawRequest:\n context.request ??\n new Request(`http://localhost${context.path}`, { method: context.method, headers: fallbackHeaders }),\n token,\n buildAuthorizeContext: context.buildAuthorizeContext ?? (() => null),\n requiresAuth: route.requiresAuth,\n });\n\n if (result.action === 'next') {\n // Pass through any refresh headers (e.g. Set-Cookie from transparent session refresh)\n if (result.headers) {\n return { status: 200, error: '', headers: result.headers };\n }\n return null;\n }\n\n // Translate AuthResult error to the {status, error} format adapters expect\n const errorBody = result.body as { error?: string } | undefined;\n return { status: result.status, error: errorBody?.error ?? 'Access denied', headers: result.headers };\n }\n\n /**\n * Auth for routes with `authTransport: 'bearer'` (the built-in MCP server): only the\n * `Authorization` header counts, always against `server.auth`. Studio client-type routing,\n * cookies, and the `apiKey` query parameter are ignored, so a browser session can't be used.\n *\n * 401s carry `WWW-Authenticate` pointing at the OAuth protected-resource metadata, and when\n * `server.mcp.oauth.resource` is set the token audience must include it.\n */\n private async checkBearerRouteAuth(\n route: ServerRoute,\n context: Parameters<MastraServer<TApp, TRequest, TResponse>['checkRouteAuth']>[1],\n ): ReturnType<MastraServer<TApp, TRequest, TResponse>['checkRouteAuth']> {\n context.requestContext.set(MASTRA_IS_STUDIO_KEY, false);\n const authorization = context.getHeader('authorization');\n const getHeader = (name: string) => {\n const lower = name.toLowerCase();\n return lower === 'cookie' || lower === MASTRA_CLIENT_TYPE_HEADER ? undefined : context.getHeader(name);\n };\n const result = await this.checkRouteAuth(\n { ...route, authTransport: undefined },\n {\n ...context,\n getHeader,\n getQuery: name => (name === 'apiKey' ? undefined : context.getQuery(name)),\n request: new Request(context.request?.url ?? `http://localhost${context.path}`, {\n method: context.method,\n headers: authorization ? { authorization } : {},\n }),\n },\n );\n\n const discovery = isMCPOAuthDiscoveryEnabled(this.mastra);\n if (!discovery && !isMCPAudienceEnforced(this.mastra)) return result;\n\n const requestUrl = context.request?.url ?? `http://localhost${context.path}`;\n const prefix = this.prefix ?? '';\n if (result?.status === 401) {\n if (!discovery) return result;\n // RFC 6750 §3: no error code when the request carried no credentials.\n const error = authorization?.trim() ? { error: 'invalid_token' } : undefined;\n const challenge = mcpWWWAuthenticate(this.mastra, prefix, requestUrl, error);\n return { ...result, headers: { ...result.headers, 'WWW-Authenticate': challenge } };\n }\n\n const user = context.requestContext.get(MASTRA_USER_KEY);\n if (user !== undefined && !(await checkMCPAudience(this.mastra, user))) {\n const challenge = mcpWWWAuthenticate(this.mastra, prefix, requestUrl, {\n error: 'invalid_token',\n error_description: 'The token audience does not include this MCP server',\n });\n return {\n status: 401,\n error: 'Invalid token audience',\n headers: { ...result?.headers, 'WWW-Authenticate': challenge },\n };\n }\n return result;\n }\n\n /**\n * Check if the user has the required permission for a route.\n *\n * Uses convention-based permission derivation:\n * 1. If route has explicit `requiresPermission`, use that\n * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)\n * 3. Routes with `requiresAuth: false` skip permission checks\n *\n * When the route specifies an array of permissions, the user needs ANY ONE\n * of them (logical OR).\n *\n * @param route - The route being accessed\n * @param userPermissions - The user's permissions from the request context\n * @returns Error response if permission denied, null if allowed\n */\n /**\n * Check if the user has the required permission for a route.\n *\n * Uses convention-based permission derivation:\n * 1. If route has explicit `requiresPermission`, use that\n * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)\n * 3. Routes with `requiresAuth: false` skip permission checks\n *\n * Permission checks use the RBAC provider that corresponds to the auth mode\n * (studio vs server) that was used for authentication.\n *\n * @param route - The route being accessed\n * @param userPermissions - The user's permissions from the request context\n * @param hasPermissionFn - Function to check if user permissions match required permission\n * @param requestContext - Request context to determine which RBAC provider to use\n * @returns Error response if permission denied, null if allowed\n */\n protected checkRoutePermission(\n route: ServerRoute,\n userPermissions: string[] | undefined,\n hasPermissionFn: (userPerms: string[], required: string) => boolean,\n requestContext: RequestContext,\n ): { status: number; error: string; message: string } | null {\n return getRoutePermissionError(this.mastra, route, userPermissions, hasPermissionFn, requestContext);\n }\n\n /**\n * RBAC check for a route this adapter serves. Skipped when no auth is configured;\n * otherwise decided by `checkRoutePermission`, so a subclass override of it still applies.\n */\n protected checkRouteRBAC(route: ServerRoute, requestContext: RequestContext): RouteAuthorizationError | null {\n if (!this.mastra.getStudio?.()?.auth && !this.mastra.getServer()?.auth) {\n return null;\n }\n const userPermissions = requestContext.get(MASTRA_USER_PERMISSIONS_KEY) as string[] | undefined;\n return this.checkRoutePermission(route, userPermissions, hasPermission, requestContext);\n }\n\n /** RBAC (`checkRouteRBAC`) then FGA on the parsed params, after authentication and validation. */\n protected async authorizeRoute(\n route: ServerRoute,\n params: Record<string, unknown>,\n requestContext: RequestContext,\n ): Promise<RouteAuthorizationError | null> {\n return (\n this.checkRouteRBAC(route, requestContext) ?? (await checkRouteFGA(this.mastra, route, requestContext, params))\n );\n }\n\n /**\n * Build a matcher that answers \"is this (path, method) a framework-public\n * route?\" — i.e. registered with `requiresAuth: false`.\n *\n * Adapters call this once at registration time and use the returned function\n * inside their context middleware to stash a boolean on the per-request\n * context under `MASTRA_FRAMEWORK_PUBLIC_KEY`. That boolean is then read by\n * per-user-middleware wrappers to short-circuit user middleware for\n * framework-public routes, guaranteeing that user middleware cannot 401\n * routes the framework declared public (e.g. Studio sign-in endpoints).\n *\n * The matcher considers:\n * - Built-in `SERVER_ROUTES` entries with `requiresAuth === false`\n * (paths joined with the adapter's configured `prefix`).\n * - Custom user API routes registered with `requiresAuth: false` via the\n * `customRouteAuthConfig` map.\n */\n getFrameworkPublicMatcher(): FrameworkPublicMatcher {\n const prefix = this.prefix ?? '';\n\n const publicRoutes = SERVER_ROUTES.filter(r => r.requiresAuth === false).map(r => ({\n method: r.method.toUpperCase(),\n pattern: `${prefix}${r.path}`,\n }));\n\n if (isMCPOAuthDiscoveryEnabled(this.mastra)) {\n for (const route of createMCPOAuthMetadataRoutes(this.mastra, prefix)) {\n publicRoutes.push({ method: route.method.toUpperCase(), pattern: route.path });\n }\n }\n\n return (path: string, method: string): boolean => {\n const upperMethod = method.toUpperCase();\n\n for (const r of publicRoutes) {\n if ((r.method === upperMethod || r.method === 'ALL') && pathMatchesPattern(path, r.pattern)) {\n return true;\n }\n }\n\n // Read `customRouteAuthConfig` at request time, not at matcher build\n // time: adapters constructed without an explicit map only populate it\n // later, in registerCustomApiRoutes(), after the context middleware has\n // already built this matcher.\n return isCustomRoutePublic(path, upperMethod, this.customRouteAuthConfig);\n };\n }\n\n abstract stream(route: ServerRoute, response: TResponse, result: unknown): Promise<unknown>;\n abstract getParams(route: ServerRoute, request: TRequest): Promise<ParsedRequestParams>;\n abstract sendResponse(route: ServerRoute, response: TResponse, result: unknown): Promise<unknown>;\n abstract registerRoute(app: TApp, route: ServerRoute, { prefix }: { prefix?: string }): Promise<void>;\n abstract registerContextMiddleware(): void;\n abstract registerAuthMiddleware(): void;\n abstract registerHttpLoggingMiddleware(): void;\n\n async init() {\n this.registerContextMiddleware();\n this.registerAuthMiddleware();\n this.validateAuthResourceScoping();\n this.registerUserMiddleware();\n this.registerHttpLoggingMiddleware();\n await this.validateEELicense();\n await this.validateAgentBuilderLicense();\n await this.validateFGAPolicyCoverage();\n await this.registerCustomApiRoutes();\n await this.registerRoutes();\n }\n\n /**\n * Validate that EE features have a valid license in production.\n * Throws if RBAC or FGA is configured without a valid license outside dev/test environments.\n */\n async validateEELicense(): Promise<void> {\n const serverConfig = this.mastra.getServer();\n const studioConfig = this.mastra.getStudio?.();\n // Check both server and studio configs for EE features\n const configuredFeatures = [\n serverConfig?.rbac || studioConfig?.rbac ? 'RBAC' : null,\n serverConfig?.fga || studioConfig?.fga ? 'FGA' : null,\n ].filter((feature): feature is string => feature !== null);\n\n if (configuredFeatures.length === 0) return;\n\n try {\n const { isEEEnabled } = await import('@mastra/core/auth/ee');\n if (!isEEEnabled()) {\n const featureList = configuredFeatures.join(' and ');\n throw new Error(\n `[mastra/auth-ee] ${featureList} ${configuredFeatures.length === 1 ? 'is' : 'are'} configured but no valid EE license was found.\\n` +\n `${featureList} ${configuredFeatures.length === 1 ? 'requires' : 'require'} a Mastra Enterprise License for production use.\\n` +\n 'Set the MASTRA_EE_LICENSE environment variable with your license key.\\n' +\n 'Learn more: https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE',\n );\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('[mastra/auth-ee]')) {\n throw err;\n }\n // @mastra/core/auth/ee module not available; EE authorization cannot function.\n throw new Error(\n `[mastra/auth-ee] ${configuredFeatures.join(' and ')} ${configuredFeatures.length === 1 ? 'is' : 'are'} configured but the EE module (@mastra/core/auth/ee) could not be loaded.\\n` +\n 'Ensure @mastra/core is updated to a version that includes EE support.',\n );\n }\n }\n\n /**\n * Validate that an Agent Builder configuration has a valid EE license.\n * Throws if the editor is configured with builder support but no valid EE license is available.\n */\n async validateAgentBuilderLicense(): Promise<void> {\n const editor = this.mastra.getEditor();\n if (!editor?.hasEnabledBuilderConfig?.()) return;\n\n try {\n const { isEEEnabled } = await import('@mastra/core/auth/ee');\n if (!isEEEnabled()) {\n throw new Error(\n '[mastra/auth-ee] Agent Builder is configured but no valid EE license was found.\\n' +\n 'Agent Builder requires a Mastra Enterprise License for production use.\\n' +\n 'Set the MASTRA_EE_LICENSE environment variable with your license key.\\n' +\n 'Learn more: https://github.com/mastra-ai/mastra/blob/main/ee/LICENSE',\n );\n }\n } catch (err) {\n if (err instanceof Error && err.message.startsWith('[mastra/auth-ee]')) {\n throw err;\n }\n // @mastra/core/auth/ee module not available — Agent Builder cannot function\n throw new Error(\n '[mastra/auth-ee] Agent Builder is configured but the EE module (@mastra/core/auth/ee) could not be loaded.\\n' +\n 'Ensure @mastra/core is updated to a version that includes EE support.',\n );\n }\n }\n\n /**\n * Warn when `server.auth` is configured without `mapUserToResourceId`.\n *\n * Without it, MASTRA_RESOURCE_ID_KEY is never set in the request context, so\n * built-in routes fall back to the client-supplied resource ID (for example\n * `memory.resource`) and ownership checks run against a caller-chosen value.\n */\n validateAuthResourceScoping(): void {\n const auth = this.mastra.getServer()?.auth as { mapUserToResourceId?: unknown } | undefined;\n if (!auth || typeof auth.mapUserToResourceId === 'function') return;\n\n this.mastra\n .getLogger()\n ?.warn(\n '[mastra/auth] server.auth is configured without mapUserToResourceId. ' +\n 'Memory, thread and workflow ownership checks will trust the resource ID supplied by the client ' +\n \"(e.g. memory.resource in the request body), so an authenticated user can read or write another user's threads. \" +\n 'Configure server.auth.mapUserToResourceId to derive the resource ID from the authenticated user.',\n );\n }\n\n /**\n * Validate route-level FGA policy coverage when an FGA provider opts into\n * startup checks.\n */\n async validateFGAPolicyCoverage(): Promise<void> {\n const serverConfig = this.mastra.getServer();\n const studioConfig = this.mastra.getStudio?.();\n // Check both server and studio FGA providers\n const fgaProvider = serverConfig?.fga ?? studioConfig?.fga;\n if (!fgaProvider) return;\n\n const customRoutes = (this.customApiRoutes ?? serverConfig?.apiRoutes ?? []).filter(\n route => !route._mastraInternal,\n );\n const routes = [...SERVER_ROUTES, ...customRoutes] as ServerRoute[];\n\n if (fgaProvider.validatePermissions) {\n const permissions = [...new Set(routes.flatMap(route => getRoutePermissions(route)))];\n await fgaProvider.validatePermissions(permissions);\n }\n\n const auditMode = fgaProvider.auditProtectedRoutes ?? (fgaProvider.requireForProtectedRoutes ? 'warn' : false);\n if (!auditMode || fgaProvider.resolveRouteFGA) return;\n\n const missingRoutes = routes.filter(\n route => isProtectedFGARoute(route) && !route.fga && !getBuiltInRouteFGAConfig(route),\n );\n\n if (missingRoutes.length === 0) return;\n\n const routeList = missingRoutes.map(route => formatRoute(route as ServerRoute));\n const message =\n `[mastra/auth-ee] FGA is configured but ${missingRoutes.length} protected route` +\n `${missingRoutes.length === 1 ? ' is' : 's are'} missing FGA metadata: ${routeList.join(', ')}`;\n\n if (auditMode === 'error') {\n throw new Error(message);\n }\n\n this.mastra.getLogger()?.warn(message, {\n routes: routeList,\n count: missingRoutes.length,\n });\n }\n\n /**\n * Register user-provided middleware from the Mastra config (`server.middleware`)\n * and from `mastra.setServerMiddleware()`. Called by init() between\n * registerAuthMiddleware() and registerHttpLoggingMiddleware().\n *\n * Mastra middleware handlers use Hono's `(c, next)` signature, so only\n * Hono-based adapters can run them. Those adapters override this method and\n * MUST wrap each handler with `skipIfFrameworkPublic` (exported by\n * `@mastra/hono`) so user middleware cannot block framework-public routes.\n * The default implementation warns when middleware is configured so the\n * config is not silently ignored on adapters that cannot honor it.\n */\n registerUserMiddleware(): void {\n const instanceMiddleware = this.mastra.getServerMiddleware?.() ?? [];\n const configMiddleware = this.mastra.getServer()?.middleware;\n const hasConfigMiddleware = Array.isArray(configMiddleware) ? configMiddleware.length > 0 : !!configMiddleware;\n if (instanceMiddleware.length === 0 && !hasConfigMiddleware) return;\n\n this.mastra\n .getLogger()\n ?.warn(\n 'Mastra server middleware (`server.middleware` or `setServerMiddleware()`) is configured, but this server adapter cannot run Hono middleware handlers. The configured middleware will not run — register middleware through your server framework instead.',\n );\n }\n\n /**\n * Override in adapters to register custom API routes defined via registerApiRoute().\n * Called by init() between registerAuthMiddleware() and registerRoutes().\n */\n async registerCustomApiRoutes(): Promise<void> {\n // Default no-op. Adapters override this to register custom routes\n // using their framework-specific middleware.\n }\n\n /** Ensures every custom route has an auth entry without overriding supplied values. */\n private initializeCustomRouteAuthConfig(routes: ApiRoute[]): void {\n this.customRouteAuthConfig ??= new Map();\n for (const route of routes) {\n const routeKey = `${route.method}:${route.path}`;\n if (!this.customRouteAuthConfig.has(routeKey)) {\n this.customRouteAuthConfig.set(routeKey, route.requiresAuth !== false);\n }\n }\n }\n\n /**\n * Registers schema-aware custom routes through the adapter's native route pipeline.\n * Returns the remaining Hono-style routes for the custom-route bridge.\n */\n protected async registerSchemaApiRoutes(): Promise<HonoCustomApiRoute[]> {\n const routes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes ?? [];\n this.validateCustomRoutePaths(routes);\n this.initializeCustomRouteAuthConfig(routes);\n\n const schemaRoutes = routes.filter(isSchemaApiRoute);\n for (const route of schemaRoutes) {\n // Opt-in built-in routes are first-party: Studio and the client SDK call them under the API prefix,\n // so they mount there like any built-in route. Other custom routes mount at the root.\n // Matched by identity: a cloned route object lands back at the root.\n const prefix = (OPT_IN_ROUTES as readonly unknown[]).includes(route) ? this.prefix : '';\n await this.registerRoute(this.app, route as unknown as ServerRoute, { prefix });\n }\n\n return routes.filter((route): route is HonoCustomApiRoute => !isSchemaApiRoute(route));\n }\n\n /**\n * Validates that no custom route path collides with the built-in route prefix.\n * Throws if any route path starts with the server's `apiPrefix`.\n */\n protected validateCustomRoutePaths(routes: ApiRoute[]): void {\n const prefix = this.prefix ?? '';\n if (!prefix) return;\n for (const route of routes) {\n if (route._mastraInternal) continue;\n if (route.path.startsWith(`${prefix}/`) || route.path === prefix) {\n throw new Error(\n `Custom API route \"${route.path}\" must not start with \"${prefix}\" — ` +\n `that path is reserved for built-in Mastra routes. ` +\n `Choose a different path (e.g. \"${route.path.replace(prefix, '/custom')}\").`,\n );\n }\n }\n }\n\n /**\n * Creates an internal Hono sub-app with all custom API routes registered.\n * Stores the handler on this instance for use by handleCustomRouteRequest().\n * Returns true if custom routes were found and registered.\n */\n protected async buildCustomRouteHandler(routes: HonoCustomApiRoute[]): Promise<boolean> {\n if (routes.length === 0) return false;\n\n const NOT_FOUND_HEADER = 'x-mastra-custom-route-not-found';\n const mastra = this.mastra;\n\n const app = new Hono<{\n Bindings: { requestContext?: RequestContext };\n Variables: { mastra: Mastra; requestContext: RequestContext };\n }>();\n\n // Internal context middleware — sets variables that custom route handlers expect\n app.use('*', async (c, next) => {\n c.set('mastra', mastra);\n c.set('requestContext', c.env?.requestContext ?? new RequestContext());\n await next();\n });\n\n // Propagate the server's onError handler so errors from custom route handlers\n // are caught here (not swallowed by Hono's default plain-text 500).\n const serverOnError = this.mastra.getServer()?.onError;\n app.onError((err, c) => {\n if (serverOnError) {\n return serverOnError(err, c as unknown as Parameters<typeof serverOnError>[1]);\n }\n const httpExceptionResponse = getCustomRouteHTTPExceptionResponse(err);\n if (httpExceptionResponse) return httpExceptionResponse;\n // Log before responding — otherwise the error is invisible on the server\n // and the client only ever sees an opaque 500.\n this.mastra.getLogger()?.error(`Custom route handler failed: ${c.req.method} ${c.req.path}`, {\n method: c.req.method,\n path: c.req.path,\n error: err instanceof Error ? (err.stack ?? err.message) : String(err),\n });\n return c.json({ error: 'Internal Server Error' }, 500);\n });\n\n // Register each custom route\n const matcherEntries: Array<{ method: string; path: string; handlerCount: number; route: HonoCustomApiRoute }> = [];\n for (const route of routes) {\n const handler =\n 'handler' in route && route.handler\n ? route.handler\n : 'createHandler' in route\n ? await route.createHandler({ mastra })\n : undefined;\n if (!handler) continue;\n\n const middlewares: any[] = [];\n if (route.middleware) {\n middlewares.push(...(Array.isArray(route.middleware) ? route.middleware : [route.middleware]));\n }\n\n const allHandlers = [...middlewares, handler];\n matcherEntries.push({ method: route.method, path: route.path, handlerCount: allHandlers.length, route });\n if (route.method === 'ALL') {\n app.all(route.path, allHandlers[0]!, ...allHandlers.slice(1));\n } else {\n app.on(route.method, route.path, allHandlers[0]!, ...allHandlers.slice(1));\n }\n }\n\n // Mark unmatched requests so the adapter bridge can fall through to next()\n app.notFound(() => new Response(null, { status: 404, headers: { [NOT_FOUND_HEADER]: 'true' } }));\n\n // Forward the platform execution context (e.g. Cloudflare Workers' `waitUntil`)\n // into the internal app so custom route handlers can keep background work\n // alive after the response is sent. Without this third arg, serverless\n // runtimes freeze the invocation on return and kill any in-flight work.\n this.customRouteHandler = async (request, env, executionCtx) => app.fetch(request, env, executionCtx);\n this.customRouteMatcher = new CustomRouteMatcher(matcherEntries);\n return true;\n }\n\n /**\n * Returns the custom route the custom-route app will run for `url` (the same URL\n * passed to `handleCustomRouteRequest`), with its decoded path params, or\n * undefined if none will.\n */\n protected matchCustomRoute(\n url: string,\n method: string,\n ): { route: HonoCustomApiRoute; params: Record<string, string> } | undefined {\n if (!this.customRouteMatcher) return undefined;\n try {\n const match = this.customRouteMatcher.matchUrl(url, method);\n return match ? { route: match.entry.route, params: match.params } : undefined;\n } catch {\n // The custom-route app can't parse or route this request either.\n return undefined;\n }\n }\n\n /**\n * Works out what auth applies to a request before it's forwarded to the\n * custom-route app. The route that decides is the one the app will dispatch\n * `dispatchUrl` to, not the route the outer framework matched, because the two\n * routers can disagree on precedence, case, trailing slashes and encoding.\n *\n * `requestPath` is the path passed to `checkRouteAuth`. When the dispatched route\n * requires auth, the returned `customRouteAuthConfig` marks that path protected so\n * the auth middleware can't skip auth on it. `fallbackRoute` is used when the app\n * won't dispatch the request (it 404s and nothing runs); pass the framework's own\n * route when there is one so its auth still applies.\n */\n protected resolveCustomRouteAuth(\n dispatchUrl: string,\n method: string,\n requestPath: string,\n fallbackRoute?: HonoCustomApiRoute,\n ): {\n match?: { route: HonoCustomApiRoute; params: Record<string, string> };\n requiresAuth: boolean;\n serverRoute: ServerRoute;\n customRouteAuthConfig?: Map<string, boolean>;\n } {\n const match = this.matchCustomRoute(dispatchUrl, method);\n const route = match?.route ?? fallbackRoute;\n\n const requiresAuth = route\n ? (this.customRouteAuthConfig?.get(`${route.method}:${route.path}`) ?? route.requiresAuth !== false)\n : isProtectedCustomRoute(requestPath, method, this.customRouteAuthConfig);\n\n const serverRoute: ServerRoute = {\n method: (route?.method ?? method) as any,\n path: route?.path ?? requestPath,\n responseType: 'json',\n handler: async () => {},\n // An explicit requiresAuth: true keeps its meaning; otherwise the auth middleware\n // decides from the path, which the map below forces to protected.\n requiresAuth: requiresAuth ? (route?.requiresAuth === true ? true : undefined) : false,\n requiresPermission: route?.requiresPermission,\n fga: route?.fga,\n };\n\n let customRouteAuthConfig: Map<string, boolean> | undefined;\n if (requiresAuth) {\n customRouteAuthConfig = new Map(this.customRouteAuthConfig ?? []);\n customRouteAuthConfig.set(`${method.toUpperCase()}:${requestPath}`, true);\n }\n\n return { match, requiresAuth, serverRoute, customRouteAuthConfig };\n }\n\n /**\n * Forwards a request to the internal custom route handler.\n * Returns the Response if a custom route matched, or null to fall through.\n */\n protected async handleCustomRouteRequest(\n url: string,\n method: string,\n headers: Record<string, string | string[] | undefined>,\n body: unknown,\n requestContext?: RequestContext,\n signal?: AbortSignal,\n executionCtx?: ExecutionContext,\n ): Promise<Response | null> {\n if (!this.customRouteHandler) return null;\n\n const fetchHeaders = new Headers();\n for (const [key, value] of Object.entries(headers)) {\n if (typeof value === 'string') fetchHeaders.set(key, value);\n else if (Array.isArray(value))\n value.forEach(v => {\n fetchHeaders.append(key, v);\n });\n }\n\n const init: RequestInit = { method, headers: fetchHeaders, signal };\n if (['POST', 'PUT', 'PATCH', 'DELETE'].includes(method) && body !== undefined) {\n if (body instanceof ArrayBuffer || body instanceof Uint8Array || body instanceof ReadableStream) {\n init.body = body as any;\n if (body instanceof ReadableStream) {\n (init as any).duplex = 'half';\n }\n } else {\n const contentType = (typeof headers['content-type'] === 'string' ? headers['content-type'] : '') || '';\n if (contentType.includes('application/json')) {\n init.body = JSON.stringify(body);\n } else if (typeof body === 'string') {\n init.body = body;\n }\n }\n }\n\n const request = new globalThis.Request(url, init);\n const response = await this.customRouteHandler(request, { requestContext }, executionCtx);\n\n if (response.headers.get('x-mastra-custom-route-not-found') === 'true') return null;\n return signal ? retainRequestWhileBodyIsOpen(response, request) : response;\n }\n\n /**\n * Pipes a custom route Response to a Node.js ServerResponse (http.ServerResponse).\n * Works with Koa (ctx.res), Express (res), and Fastify (reply.raw).\n */\n protected async writeCustomRouteResponse(\n response: Response,\n nodeRes: {\n writeHead(status: number, headers: Record<string, string | string[]>): void;\n write(chunk: unknown): void;\n end(data?: string): void;\n writableEnded?: boolean;\n destroyed?: boolean;\n } & NodeJS.WritableStream,\n signal?: AbortSignal,\n ): Promise<void> {\n const headers: Record<string, string | string[]> = {};\n response.headers.forEach((value, key) => {\n if (key.toLowerCase() !== 'set-cookie') {\n headers[key] = value;\n }\n });\n const setCookies = response.headers.getSetCookie?.();\n if (setCookies && setCookies.length > 0) {\n headers['set-cookie'] = setCookies;\n }\n if (isResponseClosed(nodeRes)) {\n await response.body?.cancel();\n return;\n }\n nodeRes.writeHead(response.status, headers);\n\n if (response.body) {\n let responseBodyError: unknown;\n let responseBodyErrorAfterResponseClosed = false;\n try {\n const responseStream = Readable.fromWeb(response.body as any);\n // This listener must run before pipeline's cleanup so source errors are\n // not mistaken for client disconnects after pipeline destroys nodeRes.\n responseStream.once('error', error => {\n responseBodyError = error;\n responseBodyErrorAfterResponseClosed = isResponseClosed(nodeRes);\n });\n if (signal) {\n await pipeline(responseStream, nodeRes, { signal });\n } else {\n await pipeline(responseStream, nodeRes);\n }\n } catch (error) {\n const expectedSignalAbort =\n signal?.aborted && isAbortSignalError(error) && (!responseBodyError || responseBodyErrorAfterResponseClosed);\n const expectedResponseClose =\n (!responseBodyError || responseBodyErrorAfterResponseClosed) &&\n isResponseClosed(nodeRes) &&\n isExpectedResponseCloseError(error);\n // Request cancellation is expected unless the response body already reported its own error.\n if (!expectedSignalAbort && !expectedResponseClose) {\n throw error;\n }\n }\n } else {\n const text = await response.text();\n if (!isResponseClosed(nodeRes)) {\n nodeRes.end(text);\n }\n }\n }\n\n /**\n * Builds the OpenAPI spec object with servers field and custom route paths.\n */\n private buildOpenAPISpec(config: { title: string; version: string; description: string }, prefix?: string): any {\n const openApiSpec = generateOpenAPIDocument(SERVER_ROUTES, config);\n\n if (prefix) {\n openApiSpec.servers = [{ url: prefix }];\n }\n\n // Custom routes are served at root (/), not under the API prefix — add per-path servers override.\n const allCustomRoutes = this.customApiRoutes ?? this.mastra.getServer()?.apiRoutes;\n if (allCustomRoutes && allCustomRoutes.length > 0) {\n const componentSchemas = openApiSpec.components?.schemas ?? Object.create(null);\n // Opt-in built-in routes are mounted under the API prefix (see registerSchemaApiRoutes), so they keep the\n // top-level server; every other custom route is served at the root.\n const isPrefixed = (route: ApiRoute) => (OPT_IN_ROUTES as readonly unknown[]).includes(route);\n const customPaths = convertCustomRoutesToOpenAPIPaths(\n allCustomRoutes.filter(route => !isPrefixed(route)),\n componentSchemas,\n );\n const prefixedPaths = convertCustomRoutesToOpenAPIPaths(allCustomRoutes.filter(isPrefixed), componentSchemas);\n if (Object.keys(componentSchemas).length > 0) {\n openApiSpec.components = { ...openApiSpec.components, schemas: componentSchemas };\n }\n if (prefix) {\n for (const pathKey of Object.keys(customPaths)) {\n if (!customPaths[pathKey].servers) {\n customPaths[pathKey].servers = [{ url: '/' }];\n }\n }\n }\n Object.assign(customPaths, prefixedPaths);\n openApiSpec.paths = { ...openApiSpec.paths, ...customPaths };\n }\n\n return openApiSpec;\n }\n\n async registerOpenAPIRoute(app: TApp, config: OpenAPIConfig = {}, { prefix }: { prefix?: string }): Promise<void> {\n const {\n title = 'Mastra API',\n version = '1.0.0',\n description = 'Mastra Server API',\n path = '/openapi.json',\n } = config;\n\n const openApiSpec = this.buildOpenAPISpec({ title, version, description }, prefix);\n\n const openApiRoute: ServerRoute = {\n method: 'GET',\n path,\n responseType: 'json',\n handler: async () => openApiSpec,\n };\n\n await this.registerRoute(app, openApiRoute, { prefix });\n }\n\n async registerRoutes(): Promise<void> {\n // Register routes sequentially to maintain order - important for routers where\n // more specific routes (e.g., /versions/compare) must be registered before\n // parameterized routes (e.g., /versions/:versionId)\n for (const route of SERVER_ROUTES) {\n await this.registerRoute(this.app, resolveServerRoute(route, this.mastra, SERVER_ROUTES), {\n prefix: this.prefix,\n });\n }\n\n // OAuth discovery for the built-in MCP endpoint lives at the server root, outside the API prefix.\n if (isMCPAudienceEnforced(this.mastra)) warnOnUnenforcedMCPAudience(this.mastra);\n if (isMCPOAuthDiscoveryEnabled(this.mastra)) {\n for (const route of createMCPOAuthMetadataRoutes(this.mastra, this.prefix ?? '')) {\n await this.registerRoute(this.app, route, { prefix: '' });\n }\n }\n\n if (this.openapiPath) {\n const specConfig = {\n title: 'Mastra API',\n version: '1.0.0',\n description: 'Mastra Server API',\n };\n\n await this.registerOpenAPIRoute(this.app, { ...specConfig, path: this.openapiPath }, { prefix: this.prefix });\n }\n }\n\n async parsePathParams(route: ServerRoute, params: Record<string, string>): Promise<Record<string, any>> {\n return parseRoutePathParams(route, params);\n }\n\n async parseQueryParams(route: ServerRoute, params: Record<string, QueryParamValue>): Promise<Record<string, any>> {\n return parseRouteQueryParams(route, params);\n }\n\n async parseBody(route: ServerRoute, body: unknown): Promise<unknown> {\n return parseRouteBody(route, body);\n }\n\n protected resolveValidationError(\n route: ServerRoute,\n error: ZodError,\n context: ValidationErrorContext,\n ): ValidationErrorResponse {\n return resolveRouteValidationError(this.mastra, route, error, context);\n }\n}\n\n/**\n * The RBAC provider for the auth mode the request was authenticated with\n * (studio vs server).\n */\nexport function getEffectiveRBACProvider(mastra: Mastra, requestContext: RequestContext) {\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY) as MastraAuthMode | undefined;\n\n if (authMode === 'studio') {\n return mastra.getStudio?.()?.rbac ?? mastra.getServer()?.rbac;\n }\n\n return mastra.getServer()?.rbac;\n}\n\n/**\n * Check if the user has the required permission for a route.\n *\n * Uses convention-based permission derivation:\n * 1. If route has explicit `requiresPermission`, use that\n * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)\n * 3. Routes with `requiresAuth: false` skip permission checks\n *\n * When the route specifies an array of permissions, the user needs ANY ONE\n * of them (logical OR). Without an RBAC provider, authenticated users get full access.\n *\n * @returns Error response if permission denied, null if allowed\n */\nexport function getRoutePermissionError(\n mastra: Mastra,\n route: ServerRoute,\n userPermissions: string[] | undefined,\n hasPermissionFn: (userPerms: string[], required: string) => boolean,\n requestContext: RequestContext,\n): { status: number; error: string; message: string } | null {\n if (!getEffectiveRBACProvider(mastra, requestContext)) {\n return null;\n }\n\n const requiredPermission = getEffectivePermission(route);\n if (!requiredPermission) {\n return null;\n }\n\n const permissions = Array.isArray(requiredPermission) ? requiredPermission : [requiredPermission];\n const hasAny = userPermissions && permissions.some(perm => hasPermissionFn(userPermissions, perm));\n\n if (!hasAny) {\n return {\n status: 403,\n error: 'Forbidden',\n message: `Missing required permission: ${permissions.join(' or ')}`,\n };\n }\n\n return null;\n}\n\nexport async function parseRoutePathParams(\n route: ServerRoute,\n params: Record<string, unknown>,\n): Promise<Record<string, any>> {\n const pathParamSchema = route.pathParamSchema;\n if (!pathParamSchema) {\n return params;\n }\n\n return pathParamSchema.parseAsync(params) as Promise<Record<string, any>>;\n}\n\nexport async function parseRouteQueryParams(\n route: ServerRoute,\n params: Record<string, unknown>,\n): Promise<Record<string, any>> {\n const queryParamSchema = route.queryParamSchema;\n if (!queryParamSchema) {\n return params;\n }\n\n const normalizedParams = parseComplexQueryParams(queryParamSchema as z.ZodTypeAny, params);\n return queryParamSchema.parseAsync(normalizedParams) as Promise<Record<string, any>>;\n}\n\nexport async function parseRouteBody(route: ServerRoute, body: unknown): Promise<unknown> {\n const bodySchema = route.bodySchema;\n if (!bodySchema) {\n return body;\n }\n\n if (body === undefined) {\n const omitted = await bodySchema.safeParseAsync(undefined);\n if (omitted.success) return omitted.data;\n // Preserve bodyless object requests with optional/defaulted fields, but keep\n // the original missing-input error if the compatibility fallback also fails.\n const schemaType = getSchemaTypeName(unwrapOptionalNullable(bodySchema));\n if (schemaType === 'object' || schemaType === 'ZodObject') {\n const emptyObject = await bodySchema.safeParseAsync({});\n if (emptyObject.success) return emptyObject.data;\n }\n throw omitted.error;\n }\n\n return bodySchema.parseAsync(body);\n}\n\nconst VALIDATION_CONTEXT_LABELS: Record<ValidationErrorContext, string> = {\n query: 'query parameters',\n body: 'request body',\n path: 'path parameters',\n};\n\nexport function resolveRouteValidationError(\n mastra: Mastra,\n route: ServerRoute,\n error: ZodError,\n context: ValidationErrorContext,\n): ValidationErrorResponse {\n const hook = route.onValidationError ?? mastra.getServer()?.onValidationError;\n\n if (hook) {\n try {\n const result = hook(error, context);\n if (result) {\n return result;\n }\n } catch (hookError) {\n mastra.getLogger()?.error('Error in custom onValidationError hook', {\n error: hookError instanceof Error ? { message: hookError.message, stack: hookError.stack } : hookError,\n });\n }\n }\n\n return {\n status: 400,\n body: formatZodError(error, VALIDATION_CONTEXT_LABELS[context]),\n };\n}\n\ntype RouteAuthorizationError = { status: number; error: string; message: string };\n\n/**\n * Check the route's RBAC permission (explicit `requiresPermission` or derived from\n * path/method) against the permissions `checkRouteAuth` stored in the request context.\n * Skipped when no auth or no RBAC provider is configured, matching what adapters enforce.\n * Uses the studio RBAC provider for studio-authenticated requests.\n * Returns null if allowed, or a 403 error object if denied.\n */\nexport function checkRouteRBAC(\n mastra: Mastra,\n route: ServerRoute,\n requestContext: RequestContext,\n): RouteAuthorizationError | null {\n if (!mastra.getStudio?.()?.auth && !mastra.getServer()?.auth) {\n return null;\n }\n\n const userPermissions = requestContext.get(MASTRA_USER_PERMISSIONS_KEY) as string[] | undefined;\n return getRoutePermissionError(mastra, route, userPermissions, hasPermission, requestContext);\n}\n\n/**\n * Run the route authorization adapters enforce after authentication and schema\n * validation: RBAC (`checkRouteRBAC`) then FGA (`checkRouteFGA`) on the parsed params.\n * Returns null if allowed, or a 403 error object if denied.\n */\nexport async function authorizeRoute(\n mastra: Mastra,\n route: ServerRoute,\n params: Record<string, unknown>,\n requestContext: RequestContext,\n): Promise<RouteAuthorizationError | null> {\n return checkRouteRBAC(mastra, route, requestContext) ?? (await checkRouteFGA(mastra, route, requestContext, params));\n}\n\nexport interface DispatchRouteInput {\n pathParams?: Record<string, unknown>;\n query?: Record<string, unknown>;\n body?: unknown;\n}\n\nexport type DispatchRouteResult = { ok: true; result: unknown } | { ok: false; status: number; body: unknown };\n\n/** What `dispatchRoute` needs to know about an adapter serving a Mastra instance's routes over HTTP. */\nexport interface DispatchAdapterInfo {\n /** The prefix built-in routes are served under, as request paths reach server auth (e.g. `/api`). */\n prefix?: string;\n getCustomRouteAuthConfig?: () => Map<string, boolean> | undefined;\n getCustomApiRoutes?: () => ApiRoute[];\n /** The adapter's own RBAC check, so its overrides also apply in-process. */\n checkRouteRBAC?: (route: ServerRoute, requestContext: RequestContext) => RouteAuthorizationError | null;\n}\n\n/**\n * Opaque handle naming one registered adapter. An adapter binds it to each request context it\n * creates (`bindDispatchAdapter`) so routes dispatched with that context get its policy.\n */\nexport type DispatchAdapterHandle = Readonly<Record<string, never>>;\n\nconst dispatchAdapters = new WeakMap<Mastra, Map<DispatchAdapterHandle, DispatchAdapterInfo>>();\n\n// Kept beside the request context rather than in it, so agent and tool code never see the handle\n// and no client input can set it.\nconst servingAdapters = new WeakMap<RequestContext, DispatchAdapterHandle>();\n\n/**\n * Record that `handle`'s adapter is serving the request `requestContext` belongs to. Adapters\n * built on `MastraServer` do this for every request; other adapters must call it.\n */\nexport function bindDispatchAdapter(requestContext: RequestContext, handle: DispatchAdapterHandle): void {\n servingAdapters.set(requestContext, handle);\n}\n\n/**\n * Tell `dispatchRoute` where an adapter serves a Mastra instance's routes. Adapters built on\n * `MastraServer` register themselves; adapters that are not must call this, and bind the returned\n * handle to each request context they create with `bindDispatchAdapter`.\n */\nexport function registerDispatchAdapter(mastra: Mastra, info: DispatchAdapterInfo): DispatchAdapterHandle {\n const adapters = dispatchAdapters.get(mastra) ?? new Map<DispatchAdapterHandle, DispatchAdapterInfo>();\n const handle: DispatchAdapterHandle = Object.freeze({});\n adapters.set(handle, info);\n dispatchAdapters.set(mastra, adapters);\n return handle;\n}\n\n/**\n * The adapter whose HTTP paths and checks a dispatched route gets. Among the adapters serving\n * `routePrefix` (all of them when it is not given), that is the one serving the current request\n * (`bindDispatchAdapter`), else the only one. `prefix` is undefined when it cannot be\n * told: several candidates and none serving this request, a `routePrefix` no registered adapter\n * serves (a custom route's own `routePrefix` is empty, for one), or nothing to go on. Guessing\n * between adapters could skip one's stricter checks, so it is never done.\n */\nfunction resolveDispatchAdapter(\n mastra: Mastra,\n routePrefix: string | undefined,\n requestContext: RequestContext,\n): { prefix: string | undefined; adapter?: DispatchAdapterInfo } {\n const adapters = [...(dispatchAdapters.get(mastra) ?? new Map<DispatchAdapterHandle, DispatchAdapterInfo>())];\n if (routePrefix !== undefined && adapters.length === 0) {\n return { prefix: normalizeRoutePath(routePrefix) };\n }\n const candidates =\n routePrefix === undefined\n ? adapters\n : adapters.filter(([, adapter]) => normalizeRoutePath(adapter.prefix ?? '') === normalizeRoutePath(routePrefix));\n const serving = servingAdapters.get(requestContext);\n const match =\n candidates.find(([handle]) => handle === serving) ?? (candidates.length === 1 ? candidates[0] : undefined);\n if (!match) {\n return { prefix: undefined };\n }\n const [, adapter] = match;\n return { prefix: normalizeRoutePath(adapter.prefix ?? ''), adapter };\n}\n\n/** Studio auth for Studio requests when `studio.auth` is configured, otherwise `server.auth`. */\nfunction resolveEffectiveAuthConfig(\n mastra: Mastra,\n getHeader: (name: string) => string | undefined,\n): { authConfig: unknown; authMode: MastraAuthMode } | null {\n const isStudioRequest = isStudioClientTypeHeader(getHeader(MASTRA_CLIENT_TYPE_HEADER));\n const studioAuth = mastra.getStudio?.()?.auth;\n const serverAuth = mastra.getServer()?.auth;\n\n // Dual auth is opt-in: if studio.auth is configured, Studio requests use it exclusively\n if (isStudioRequest && studioAuth) {\n return { authConfig: studioAuth, authMode: 'studio' };\n }\n\n // Otherwise (non-studio request, OR studio request without studio.auth configured),\n // fall back to server.auth for backward compatibility\n if (serverAuth) {\n return { authConfig: serverAuth, authMode: 'server' };\n }\n\n // No auth configured\n return null;\n}\n\nconst ROUTE_PATH_PARAM = /\\/:([A-Za-z0-9_]+)(\\?)?/g;\n\n/**\n * A URL can only carry a path param as a non-empty segment, and `.` / `..` segments are\n * resolved away before routing. Anything else names a path no HTTP request to this route\n * has, so it is rejected instead of being authorized as some other path.\n */\nfunction findInvalidPathParams(\n path: string,\n pathParams: Record<string, unknown>,\n): Array<{ field: string; message: string }> {\n const issues: Array<{ field: string; message: string }> = [];\n for (const [, name, optional] of path.matchAll(ROUTE_PATH_PARAM)) {\n const value = pathParams[name!];\n if (value === undefined && optional) continue;\n if (typeof value !== 'string' || value === '') {\n issues.push({ field: name!, message: 'Path parameter must be a non-empty string' });\n } else if (value === '.' || value === '..') {\n issues.push({ field: name!, message: 'Path parameter cannot be \".\" or \"..\"' });\n }\n }\n return issues;\n}\n\n/** Fill `:param` / `:param?` segments of a route path the way a client would put them in a URL. */\nfunction fillRoutePath(path: string, pathParams: Record<string, unknown>): string {\n return path.replace(ROUTE_PATH_PARAM, (_segment, name: string) => {\n const value = pathParams[name];\n return value === undefined ? '' : `/${encodeURIComponent(String(value))}`;\n });\n}\n\n/** Where the in-process pipeline deliberately differs between `dispatchRoute` and `invokeRoute`. */\ninterface RoutePipelinePolicy {\n /**\n * Skip auth for paths server auth declares public (and for the dev playground). When false,\n * every route that requires auth needs an authenticated user.\n */\n honorPublicPaths: boolean;\n /** Path params override same-named query/body fields, instead of the adapters' path < query < body. */\n pathParamsWin: boolean;\n /**\n * The path server auth's hooks are asked about. `adapter`: under the prefix of the adapter\n * serving the routes (custom routes unprefixed, with their auth config), refusing path params\n * no URL could carry and refusing to run when that prefix is not known. `apiPrefix`: always\n * under `server.apiPrefix`, each `:param` replaced in place.\n */\n authPath: 'adapter' | 'apiPrefix';\n /** Order inputs are validated in, which decides the error reported when several are invalid. */\n validationOrder: 'query-body-path' | 'path-query-body';\n /** A schema failing with something other than a ZodError: answer 400, or let it throw. */\n nonZodParseError: 'respond' | 'throw';\n /** Answer with the `Response` an HTTPException carries, instead of the standard error body. */\n customErrorResponses: boolean;\n /** Handlers only see the server context the caller passed, never same-named request fields. */\n reserveServerContext: boolean;\n}\n\nconst DISPATCH_ROUTE_POLICY: RoutePipelinePolicy = {\n honorPublicPaths: true,\n pathParamsWin: true,\n authPath: 'adapter',\n validationOrder: 'query-body-path',\n nonZodParseError: 'respond',\n customErrorResponses: true,\n reserveServerContext: true,\n};\n\n/** `invokeRoute`'s contract as it shipped; changing any of these changes a public API. */\nconst INVOKE_ROUTE_POLICY: RoutePipelinePolicy = {\n honorPublicPaths: false,\n pathParamsWin: false,\n authPath: 'apiPrefix',\n validationOrder: 'path-query-body',\n nonZodParseError: 'throw',\n customErrorResponses: false,\n reserveServerContext: false,\n};\n\n/**\n * The path-scoped half of `checkRouteAuth` for a route run in-process: `requiresAuth: false`,\n * protected/public path handling, then `authorizeUser` / `authorize` / `rules` / the RBAC\n * default rules, all evaluated against the route's own request path and method.\n * Uses the user Mastra server auth already put in the request context; never re-authenticates.\n */\nasync function checkDispatchedRouteAuth(\n route: ServerRoute,\n pathParams: Record<string, unknown>,\n context: ServerContext,\n policy: RoutePipelinePolicy,\n): Promise<{ status: number; body: Record<string, unknown> } | null> {\n if (route.requiresAuth === false) {\n return null;\n }\n\n const { mastra, requestContext } = context;\n const outerHeaders = context.request?.headers;\n const getHeader = (name: string) => outerHeaders?.get(name) ?? undefined;\n const studioAuth = mastra.getStudio?.()?.auth;\n const serverAuth = mastra.getServer()?.auth;\n\n // Only the user Mastra server auth resolved counts; the legacy `user` key can be\n // written by code outside it (such as an MCP server's own auth mapper).\n const user = requestContext.get(MASTRA_USER_KEY);\n if (!policy.honorPublicPaths && (studioAuth || serverAuth) && !user) {\n return { status: 401, body: { error: 'Authentication required' } };\n }\n\n // Use the auth config the caller was authenticated with (recorded by checkRouteAuth);\n // only fall back to the request's client-type header when no mode was recorded.\n const authMode = requestContext.get(MASTRA_AUTH_MODE_KEY) as MastraAuthMode | undefined;\n const recordedAuth = authMode === 'studio' ? studioAuth : authMode === 'server' ? serverAuth : undefined;\n const authConfig = (recordedAuth ?? resolveEffectiveAuthConfig(mastra, getHeader)?.authConfig) as\n | MastraAuthConfig\n | undefined;\n if (!authConfig) {\n return null;\n }\n\n // Server auth's authorization hooks see the route's own HTTP path, not the\n // path of whatever request (such as an MCP call) is running it.\n const method = route.method;\n let path: string | undefined;\n let customRouteAuthConfig: Map<string, boolean> | undefined;\n if (policy.authPath === 'adapter') {\n const { prefix, adapter } = resolveDispatchAdapter(mastra, context.routePrefix, requestContext);\n customRouteAuthConfig = adapter?.getCustomRouteAuthConfig?.();\n const customRoutes = adapter?.getCustomApiRoutes?.() ?? mastra.getServer()?.apiRoutes ?? [];\n // Opt-in built-in routes are listed as custom routes but served under the prefix.\n const isUnprefixed =\n customRoutes.includes(route as unknown as ApiRoute) && !(OPT_IN_ROUTES as readonly unknown[]).includes(route);\n if (isUnprefixed || prefix !== undefined) {\n path = `${isUnprefixed ? '' : prefix}${fillRoutePath(route.path, pathParams)}` || '/';\n }\n } else {\n const apiPrefix = normalizeRoutePath(mastra.getServer()?.apiPrefix ?? '/api');\n path = `${apiPrefix}${route.path.replace(/:(\\w+)/g, (_, name: string) =>\n encodeURIComponent(String(pathParams[name] ?? '')),\n )}`;\n }\n\n // Unlike an HTTP request, a path outside the protected patterns is not let through: the\n // path here is rebuilt, and a wrong prefix must not turn auth off. Only paths declared\n // public skip auth, plus the dev playground when no auth provider is configured.\n if (policy.honorPublicPaths && path !== undefined) {\n const isDevPlayground =\n typeof authConfig.authenticateToken !== 'function' &&\n process.env.MASTRA_DEV === 'true' &&\n getHeader('x-mastra-dev-playground') === 'true';\n const isPublic =\n !route.requiresAuth &&\n (canAccessPublicly(path, method, authConfig) || isCustomRoutePublic(path, method, customRouteAuthConfig));\n if (isDevPlayground || isPublic) {\n return null;\n }\n }\n\n if (!user) {\n return { status: 401, body: { error: 'Invalid or expired token' } };\n }\n\n if (path === undefined) {\n throw new Error(\n `dispatchRoute cannot tell which path ${method} ${route.path} is served under, so it cannot apply server auth to it. ` +\n 'Set `routePrefix` in the context to the prefix the server adapter serves its built-in routes under (such as \"/api\").',\n );\n }\n\n // Hooks get the caller's own headers when the request is forwarded, otherwise the token it authenticated with.\n const token = requestContext.get(MASTRA_AUTH_TOKEN_KEY);\n const headers =\n outerHeaders ?? (typeof token === 'string' && token ? { authorization: `Bearer ${token}` } : undefined);\n\n return authorizeAuthenticatedUser({\n path,\n method,\n user,\n mastra,\n authConfig,\n customRouteAuthConfig,\n requestContext,\n rawRequest: new Request(`http://localhost${path}`, { method, headers }),\n buildAuthorizeContext: () => null,\n });\n}\n\n/** The one in-process pipeline behind `dispatchRoute` and `invokeRoute`: path-scoped auth → validate → RBAC → FGA → handler. */\nasync function runRoutePipeline(\n route: ServerRoute,\n input: DispatchRouteInput,\n context: ServerContext,\n policy: RoutePipelinePolicy,\n): Promise<DispatchRouteResult> {\n const { mastra, requestContext } = context;\n\n if (policy.authPath === 'adapter') {\n const issues = findInvalidPathParams(route.path, input.pathParams ?? {});\n if (issues.length > 0) {\n return { ok: false, status: 400, body: { error: 'Invalid path parameters', issues } };\n }\n }\n\n const pathAuthError = await checkDispatchedRouteAuth(route, input.pathParams ?? {}, context, policy);\n if (pathAuthError) {\n return { ok: false, ...pathAuthError };\n }\n\n const validate = async <T>(\n kind: ValidationErrorContext,\n label: string,\n parse: () => Promise<T>,\n ): Promise<{ value: T } | { error: DispatchRouteResult }> => {\n try {\n return { value: await parse() };\n } catch (error) {\n if (isZodError(error)) {\n const { status, body } = resolveRouteValidationError(mastra, route, error, kind);\n return { error: { ok: false, status, body } };\n }\n if (policy.nonZodParseError === 'throw') {\n throw error;\n }\n return {\n error: {\n ok: false,\n status: 400,\n body: {\n error: `Invalid ${label}`,\n issues: [{ field: 'unknown', message: error instanceof Error ? error.message : 'Unknown error' }],\n },\n },\n };\n }\n };\n\n const parsed: { query?: Record<string, any>; body?: unknown; path?: Record<string, any> } = { body: input.body };\n const steps = {\n query: async () => {\n const result = await validate('query', 'query parameters', () => parseRouteQueryParams(route, input.query ?? {}));\n if ('error' in result) return result.error;\n parsed.query = result.value;\n },\n body: async () => {\n if (input.body === undefined && !route.bodySchema) return;\n const result = await validate('body', 'request body', () => parseRouteBody(route, input.body));\n if ('error' in result) return result.error;\n parsed.body = result.value;\n },\n path: async () => {\n const result = await validate('path', 'path parameters', () =>\n parseRoutePathParams(route, input.pathParams ?? {}),\n );\n if ('error' in result) return result.error;\n parsed.path = result.value;\n },\n };\n const order =\n policy.validationOrder === 'path-query-body'\n ? ([steps.path, steps.query, steps.body] as const)\n : ([steps.query, steps.body, steps.path] as const);\n for (const step of order) {\n const validationError = await step();\n if (validationError) return validationError;\n }\n const { body } = parsed;\n\n const params = {\n ...(policy.pathParamsWin ? {} : parsed.path),\n ...parsed.query,\n ...(typeof body === 'object' ? body : {}),\n ...(policy.pathParamsWin ? parsed.path : {}),\n };\n\n // With an adapter serving the routes, its own RBAC check runs so subclass overrides apply here too.\n const adapter =\n policy.authPath === 'adapter'\n ? resolveDispatchAdapter(mastra, context.routePrefix, requestContext).adapter\n : undefined;\n const authError = adapter?.checkRouteRBAC\n ? (adapter.checkRouteRBAC(route, requestContext) ?? (await checkRouteFGA(mastra, route, requestContext, params)))\n : await authorizeRoute(mastra, route, params, requestContext);\n if (authError) {\n return { ok: false, status: authError.status, body: { error: authError.error, message: authError.message } };\n }\n\n try {\n // HTTP adapters always set every server-context field, so request fields never stand in for them.\n const serverContext: ServerContext = policy.reserveServerContext\n ? {\n registeredTools: undefined,\n taskStore: undefined,\n routePrefix: undefined,\n request: undefined,\n ...context,\n }\n : context;\n return { ok: true, result: await route.handler({ ...params, ...serverContext }) };\n } catch (error) {\n const customResponse = policy.customErrorResponses ? getCustomHTTPExceptionResponse(error) : undefined;\n if (customResponse) {\n const text = await customResponse.text();\n let responseBody: unknown = text;\n try {\n responseBody = JSON.parse(text);\n } catch {\n // non-JSON custom response body stays as text\n }\n return { ok: false, status: customResponse.status, body: responseBody };\n }\n const { status, body: errorBody } = getHTTPErrorResponse(error);\n return { ok: false, status, body: errorBody };\n }\n}\n\n/**\n * Invoke a route in-process, enforcing what an adapter enforces for an HTTP request to it,\n * and never allowing more than that request would:\n *\n * 1. Path params must be what a URL can carry: a non-empty string for every `:param` (optional\n * `:param?` may be left out), and never `.` or `..`. Anything else is a 400.\n * 2. Path-scoped authorization from `checkRouteAuth`, evaluated against the route's own\n * path (the serving adapter's prefix + filled path params) and method: `requiresAuth: false`,\n * public paths, and `authorizeUser` / `authorize` / `rules` / the RBAC default rules.\n * Authentication is not repeated: the user (`MASTRA_USER_KEY`), permissions, and auth mode\n * must already be in `context.requestContext` from the caller's authenticated request, and\n * the auth config used is the one recorded there (`studio.auth` or `server.auth`), falling\n * back to the request's client-type header only when none was recorded. `authorizeUser`\n * receives the same `{ raw, headers, header() }` shape as over HTTP, wrapping a synthetic\n * `Request` for the route's path/method with the caller's headers (no body).\n * 3. Schema validation: query, then body, then path params.\n * 4. RBAC (the serving adapter's `checkRoutePermission`), then FGA (`checkRouteFGA`) on the\n * parsed params.\n * 5. `route.handler` with the parsed params and `context`.\n *\n * The adapter's paths and checks apply: the adapter serving the request `requestContext` came\n * from, else the only adapter serving the Mastra instance (or `context.routePrefix`, when set).\n * With none registered, `routePrefix` is required. When the adapter cannot be told (several\n * serve the prefix and none served this request), or `routePrefix` is one no registered adapter\n * serves, a caller without a user gets 401 and the call otherwise throws rather than guess.\n *\n * It is stricter than HTTP in three ways. With auth configured, a route needs a user unless\n * its path is declared public; a path merely outside the `protected` patterns is not let\n * through. Path params win over same-named query or body fields, so authorization and the\n * handler act on the resource named in the path. And request fields never stand in for\n * server context (`request`, `routePrefix`, `registeredTools`, `taskStore`) left out of `context`.\n *\n * Failures resolve to the status and JSON body an adapter would send; successful calls\n * return the raw handler result (streams are not converted).\n *\n * `invokeRoute` runs the same pipeline for JSON routes with a stricter contract: it never\n * skips auth for public paths and answers with `{ status, body }`.\n */\nexport async function dispatchRoute(\n route: ServerRoute,\n input: DispatchRouteInput,\n context: ServerContext,\n): Promise<DispatchRouteResult> {\n return runRoutePipeline(route, input, context, DISPATCH_ROUTE_POLICY);\n}\n\nexport interface InvokeRouteOptions {\n mastra: Mastra;\n /**\n * The caller's request context, already authenticated by Mastra (an HTTP route,\n * or an MCP request bridged by `applyMcpRequestAuth`). Its user, permissions and\n * auth mode decide what the caller may do.\n */\n requestContext: RequestContext;\n pathParams?: Record<string, string>;\n query?: Record<string, QueryParamValue>;\n body?: unknown;\n abortSignal?: AbortSignal;\n}\n\n/** What the route would have answered over HTTP. */\nexport interface InvokeRouteResult {\n status: number;\n body: unknown;\n}\n\n/**\n * Runs a server route in-process as the caller, with the checks its HTTP\n * endpoint applies on every adapter: authentication, auth's `authorizeUser`,\n * `authorize` and `rules` (against the route's path under `apiPrefix`), input\n * validation, RBAC permission and FGA. Lets code outside an HTTP request (such\n * as an MCP tool) reuse a route without proxying through the HTTP server.\n *\n * Authentication is not re-run: when server or studio auth is configured, the\n * request context must already carry the user Mastra server auth resolved\n * (`MASTRA_USER_KEY`), otherwise the call is refused with 401.\n *\n * Only JSON routes are supported; other response types throw. The handler gets\n * the parsed params, `mastra`, `requestContext` and `abortSignal`, but not the\n * HTTP-only `request`, `registeredTools`, `taskStore` or `routePrefix`, so\n * routes that read those are not suitable.\n *\n * Shares its pipeline with `dispatchRoute`, which follows the HTTP request more\n * closely (public paths, the adapter's prefix, custom error responses), passes a\n * full `ServerContext` and returns raw handler results.\n */\nexport async function invokeRoute(route: ServerRoute, options: InvokeRouteOptions): Promise<InvokeRouteResult> {\n if (route.responseType !== 'json') {\n throw new Error(\n `invokeRoute only runs JSON routes; ${route.method} ${route.path} answers with '${route.responseType}'`,\n );\n }\n\n const result = await runRoutePipeline(\n route,\n { pathParams: options.pathParams, query: options.query, body: options.body },\n {\n mastra: options.mastra,\n requestContext: options.requestContext,\n abortSignal: options.abortSignal ?? new AbortController().signal,\n },\n INVOKE_ROUTE_POLICY,\n );\n return result.ok ? { status: 200, body: result.result } : { status: result.status, body: result.body };\n}\n\n/**\n * Check FGA authorization for an HTTP route.\n * Returns null if authorized or FGA not configured, or an error object if denied.\n */\nexport async function checkRouteFGA(\n mastra: any,\n route: ServerRoute,\n requestContext: RequestContext,\n params: Record<string, unknown>,\n): Promise<{ status: number; error: string; message: string } | null> {\n // Use request context to determine which FGA provider to use (studio vs server)\n const fgaProvider = getFGAProvider(mastra, requestContext);\n if (!fgaProvider) return null;\n\n const fgaConfig = await resolveRouteFGAConfig(fgaProvider, route, requestContext, params);\n if (!fgaConfig) {\n if (fgaProvider.requireForProtectedRoutes && isProtectedFGARoute(route)) {\n return {\n status: 403,\n error: 'Forbidden',\n message: 'FGA authorization denied: route FGA metadata is required',\n };\n }\n return null;\n }\n\n const user = requestContext?.get('user');\n if (!user) {\n return {\n status: 403,\n error: 'Forbidden',\n message: 'FGA authorization denied: authenticated user is required',\n };\n }\n\n const resourceId =\n typeof fgaConfig.resourceId === 'function'\n ? fgaConfig.resourceId(params, { requestContext })\n : fgaConfig.resourceId || (fgaConfig.resourceIdParam ? (params[fgaConfig.resourceIdParam] as string) : undefined);\n if (!fgaConfig.resourceType || !resourceId) {\n return {\n status: 403,\n error: 'Forbidden',\n message: 'FGA authorization denied: route FGA metadata is incomplete',\n };\n }\n const effectivePermission = route.path ? getEffectivePermission(route) : null;\n const permission =\n fgaConfig.permission ||\n effectivePermission ||\n `${getFGAResourcePermissionSlug(fgaConfig.resourceType)}:${deriveFGAAction(route.method)}`;\n\n const authorized = await fgaProvider.check(user, {\n resource: { type: fgaConfig.resourceType, id: resourceId },\n permission,\n context: { resourceId, requestContext },\n });\n\n if (!authorized) {\n return {\n status: 403,\n error: 'Forbidden',\n message: `FGA authorization denied: cannot ${permission} on ${fgaConfig.resourceType}:${resourceId}`,\n };\n }\n\n return null;\n}\n\nfunction deriveFGAAction(method: string): string {\n switch (method.toUpperCase()) {\n case 'GET':\n return 'read';\n case 'DELETE':\n return 'delete';\n case 'POST':\n case 'PUT':\n case 'PATCH':\n return 'write';\n default:\n return 'read';\n }\n}\n\nfunction getFGAResourcePermissionSlug(resourceType: string): string {\n const resourcePermissionSlugs: Record<string, string> = {\n agent: 'agents',\n workflow: 'workflows',\n tool: 'tools',\n thread: 'memory',\n };\n\n return resourcePermissionSlugs[resourceType] ?? resourceType;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AAOA,MAAa,gCAAgC;AAE7C,MAAM,iCAAiB,IAAI,QAAgB;AAC3C,MAAM,mCAAmB,IAAI,QAAyB;AACtD,MAAM,iCAAiB,IAAI,IAAI;CAAC;CAAa;CAAa;AAAO,CAAC;;AAGlE,SAAS,gBAAgB,QAAiD;CACxE,MAAM,OAAO,OAAO,UAAU,CAAC,EAAE;CACjC,OAAO,QAAQ,OAAQ,KAA6B,sBAAsB,aACrE,OACD,KAAA;AACN;AAEA,SAAS,eAAe,QAAgB;CACtC,OAAO,OAAO,UAAU,CAAC,EAAE,KAAK,SAAS,CAAC;AAC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