import type { ToolsInput } from '@mastra/core/agent';
import type { Mastra } from '@mastra/core/mastra';
import { RequestContext } from '@mastra/core/request-context';
import { MastraServerBase } from '@mastra/core/server';
import type { ApiRoute, HttpLoggingConfig, ValidationErrorContext, ValidationErrorResponse } from '@mastra/core/server';
import type { ZodError } from 'zod';
import type { InMemoryTaskStore } from '../a2a/store.js';
import type { ServerRoute } from './routes/index.js';
export * from './routes/index.js';
export { redactStreamChunk } from './redact.js';
export { WorkflowRegistry, normalizeRoutePath } from '../utils.js';
export interface OpenAPIConfig {
    title?: string;
    version?: string;
    description?: string;
    path?: string;
}
export interface BodyLimitOptions {
    maxSize: number;
    onError: (error: unknown) => unknown;
}
export interface StreamOptions {
    /**
     * When true (default), redacts sensitive data from stream chunks
     * (system prompts, tool definitions, API keys) before sending to clients.
     *
     * Set to false to include full request data in stream chunks (useful for
     * debugging or internal services that need access to this data).
     *
     * @default true
     */
    redact?: boolean;
}
/**
 * MCP transport options for configuring MCP HTTP and SSE transports.
 */
export interface MCPOptions {
    /**
     * When true, runs in stateless mode without session management.
     * Ideal for serverless environments (Cloudflare Workers, Vercel Edge, etc.)
     * where you can't maintain persistent connections across requests.
     *
     * @default false
     */
    serverless?: boolean;
    /**
     * Custom session ID generator function.
     */
    sessionIdGenerator?: () => string;
}
/**
 * Query parameter values parsed from HTTP requests.
 * Supports both single values and arrays (for repeated query params like ?tag=a&tag=b).
 */
export type QueryParamValue = string | string[];
/**
 * Parsed request parameters returned by getParams().
 */
export interface ParsedRequestParams {
    urlParams: Record<string, string>;
    queryParams: Record<string, QueryParamValue>;
    body: unknown;
    /**
     * Error that occurred while parsing the request body.
     * When set, the server should return a 400 Bad Request response.
     */
    bodyParseError?: {
        message: string;
    };
}
/**
 * Normalizes query parameters from various HTTP framework formats to a consistent structure.
 * Handles both single string values and arrays (for repeated query params like ?tag=a&tag=b).
 * Reconstructs bracket-notation keys (e.g., `orderBy[field]=createdAt`) into JSON strings
 * so that z.preprocess JSON.parse can handle them.
 * Filters out non-string values that some frameworks may include.
 *
 * @param rawQuery - Raw query parameters from the HTTP framework (may contain strings, arrays, or nested objects)
 * @returns Normalized query parameters as Record<string, string | string[]>
 */
export declare function normalizeQueryParams(rawQuery: Record<string, unknown>): Record<string, QueryParamValue>;
/**
 * Abstract base class for server adapters that handle HTTP requests.
 *
 * This class extends `MastraServerBase` to inherit app storage functionality
 * and provides the framework for registering routes, middleware, and handling requests.
 *
 * Framework-specific adapters in @mastra/hono and @mastra/express extend this class
 * (both named `MastraServer` in their respective packages) and implement the abstract
 * methods for their specific framework.
 *
 * @template TApp - The type of the server app (e.g., Hono, Express Application)
 * @template TRequest - The type of the request object
 * @template TResponse - The type of the response object
 */
export declare abstract class MastraServer<TApp, TRequest, TResponse> extends MastraServerBase<TApp> {
    protected mastra: Mastra;
    protected bodyLimitOptions?: BodyLimitOptions;
    protected tools?: ToolsInput;
    protected prefix?: string;
    protected openapiPath?: string;
    protected taskStore?: InMemoryTaskStore;
    protected customRouteAuthConfig?: Map<string, boolean>;
    protected streamOptions: StreamOptions;
    protected httpLoggingConfig?: HttpLoggingConfig;
    protected customApiRoutes?: ApiRoute[];
    protected mcpOptions?: MCPOptions;
    private customRouteHandler;
    constructor({ app, mastra, bodyLimitOptions, tools, prefix, openapiPath, taskStore, customRouteAuthConfig, streamOptions, customApiRoutes, mcpOptions, }: {
        app: TApp;
        mastra: Mastra;
        bodyLimitOptions?: BodyLimitOptions;
        tools?: ToolsInput;
        prefix?: string;
        openapiPath?: string;
        taskStore?: InMemoryTaskStore;
        customRouteAuthConfig?: Map<string, boolean>;
        streamOptions?: StreamOptions;
        customApiRoutes?: ApiRoute[];
        /**
         * MCP transport options applied to all MCP HTTP and SSE routes.
         * Individual routes can override these via MCPHttpTransportResult.mcpOptions.
         */
        mcpOptions?: MCPOptions;
    });
    /**
     * Parses the apiReqLogs configuration into a normalized HttpLoggingConfig.
     * @param config - The raw config value from server.build.apiReqLogs
     * @returns Normalized HttpLoggingConfig or undefined if disabled
     */
    private parseLoggingConfig;
    /**
     * Determines if a request to the given path should be logged.
     * @param path - The request path to check
     * @returns true if the request should be logged, false otherwise
     */
    protected shouldLogRequest(path: string): boolean;
    protected mergeRequestContext({ paramsRequestContext, bodyRequestContext, }: {
        paramsRequestContext?: Record<string, any>;
        bodyRequestContext?: Record<string, any>;
    }): RequestContext;
    /**
     * Check if the current request should be authenticated/authorized.
     * Returns null if auth passes, or an error response if it fails.
     *
     * This is a thin wrapper around coreAuthMiddleware that:
     * 1. Handles route-level requiresAuth opt-out (not available in global middleware)
     * 2. Delegates all other auth logic to coreAuthMiddleware
     * 3. Translates the AuthResult into the {status, error} format adapters expect
     */
    protected checkRouteAuth(route: ServerRoute, context: {
        path: string;
        method: string;
        getHeader: (name: string) => string | undefined;
        getQuery: (name: string) => string | undefined;
        requestContext: RequestContext;
        /** Raw Request object for cookie-based auth providers */
        request?: Request;
        /** Build framework-specific context for authorize() callback */
        buildAuthorizeContext?: () => unknown;
    }): Promise<{
        status: number;
        error: string;
    } | null>;
    /**
     * Check if the user has the required permission for a route.
     *
     * Uses convention-based permission derivation:
     * 1. If route has explicit `requiresPermission`, use that
     * 2. Otherwise, derive permission from path/method (e.g., GET /agents → agents:read)
     * 3. Routes with `requiresAuth: false` skip permission checks
     *
     * @param route - The route being accessed
     * @param userPermissions - The user's permissions from the request context
     * @returns Error response if permission denied, null if allowed
     */
    protected checkRoutePermission(route: ServerRoute, userPermissions: string[] | undefined, hasPermissionFn: (userPerms: string[], required: string) => boolean): {
        status: number;
        error: string;
        message: string;
    } | null;
    abstract stream(route: ServerRoute, response: TResponse, result: unknown): Promise<unknown>;
    abstract getParams(route: ServerRoute, request: TRequest): Promise<ParsedRequestParams>;
    abstract sendResponse(route: ServerRoute, response: TResponse, result: unknown): Promise<unknown>;
    abstract registerRoute(app: TApp, route: ServerRoute, { prefix }: {
        prefix?: string;
    }): Promise<void>;
    abstract registerContextMiddleware(): void;
    abstract registerAuthMiddleware(): void;
    abstract registerHttpLoggingMiddleware(): void;
    init(): Promise<void>;
    /**
     * Validate that EE features have a valid license in production.
     * Throws if RBAC is configured without a valid license outside dev/test environments.
     */
    validateEELicense(): Promise<void>;
    /**
     * Override in adapters to register custom API routes defined via registerApiRoute().
     * Called by init() between registerAuthMiddleware() and registerRoutes().
     */
    registerCustomApiRoutes(): Promise<void>;
    /**
     * Creates an internal Hono sub-app with all custom API routes registered.
     * Stores the handler on this instance for use by handleCustomRouteRequest().
     * Returns true if custom routes were found and registered.
     */
    protected buildCustomRouteHandler(): Promise<boolean>;
    /**
     * Forwards a request to the internal custom route handler.
     * Returns the Response if a custom route matched, or null to fall through.
     * Used by non-Hono adapter bridges.
     */
    protected handleCustomRouteRequest(url: string, method: string, headers: Record<string, string | string[] | undefined>, body: unknown, requestContext?: RequestContext): Promise<Response | null>;
    /**
     * Pipes a custom route Response to a Node.js ServerResponse (http.ServerResponse).
     * Works with Koa (ctx.res), Express (res), and Fastify (reply.raw).
     */
    protected writeCustomRouteResponse(response: Response, nodeRes: {
        writeHead(status: number, headers: Record<string, string | string[]>): void;
        write(chunk: unknown): void;
        end(data?: string): void;
    }): Promise<void>;
    /**
     * Builds the OpenAPI spec object with servers field and custom route paths.
     */
    private buildOpenAPISpec;
    registerOpenAPIRoute(app: TApp, config: OpenAPIConfig | undefined, { prefix }: {
        prefix?: string;
    }): Promise<void>;
    registerRoutes(): Promise<void>;
    parsePathParams(route: ServerRoute, params: Record<string, string>): Promise<Record<string, any>>;
    parseQueryParams(route: ServerRoute, params: Record<string, QueryParamValue>): Promise<Record<string, any>>;
    parseBody(route: ServerRoute, body: unknown): Promise<unknown>;
    private static readonly CONTEXT_LABELS;
    protected resolveValidationError(route: ServerRoute, error: ZodError, context: ValidationErrorContext): ValidationErrorResponse;
}
//# sourceMappingURL=index.d.ts.map