/** * FrontMcpContext - Unified context for FrontMCP * * Single point of truth for all request-related data, combining session and request state. * Flows through the entire async execution chain via AsyncLocalStorage. * * Access via DI using the FRONTMCP_CONTEXT token: * ```typescript * const ctx = this.get(FRONTMCP_CONTEXT); * console.log(ctx.requestId, ctx.sessionId, ctx.authInfo); * ``` */ import { type FrontMcpFetchInit } from '@frontmcp/auth'; import { type ZodType } from '@frontmcp/lazy-zod'; import { type AuthInfo } from '@frontmcp/protocol'; import { type FrontMcpLogger } from '../common/interfaces/logger.interface'; import { type SessionIdPayload } from '../common/types'; import { type ElicitOptions, type ElicitResult } from '../elicitation'; import { type TraceContext } from './trace-context'; /** * Request metadata extracted from HTTP headers. */ export interface RequestMetadata { /** User-Agent header */ userAgent?: string; /** Content-Type header */ contentType?: string; /** Accept header */ accept?: string; /** Client IP address (from x-forwarded-for or socket) */ clientIp?: string; /** Custom headers matching x-frontmcp-* pattern */ customHeaders: Record; } /** * Configuration for the context. */ export interface FrontMcpContextConfig { /** Auto-inject auth headers in fetch requests (default: true) */ autoInjectAuthHeaders?: boolean; /** Auto-inject tracing headers in fetch requests (default: true) */ autoInjectTracingHeaders?: boolean; /** Default fetch request timeout in milliseconds (default: 30000) */ requestTimeout?: number; } /** * Arguments for creating a FrontMcpContext. */ export interface FrontMcpContextArgs { /** Optional request ID (generated if not provided) */ requestId?: string; /** Optional trace context (generated if not provided) */ traceContext?: TraceContext; /** Session identifier (required) */ sessionId: string; /** Authentication information (can be partial, progressively populated) */ authInfo?: Partial; /** Scope identifier (required) */ scopeId: string; /** Optional timestamp (defaults to Date.now()) */ timestamp?: number; /** Optional request metadata */ metadata?: RequestMetadata; /** Optional configuration */ config?: FrontMcpContextConfig; } /** * Interface for transport access (elicit support). * Provides clean API for accessing transport capabilities. */ export interface TransportAccessor { /** * Check if transport supports elicit requests. */ readonly supportsElicit: boolean; /** * Send an elicit request to the client for interactive input. * * @param message - Message to display to the user * @param requestedSchema - Zod schema for validating the response * @param options - Elicit options (mode, ttl, elicitationId) * @returns Typed elicit result with status and validated content * @throws ElicitationNotSupportedError if client doesn't support elicitation * @throws ElicitationTimeoutError if request times out */ elicit(message: string, requestedSchema: S, options?: ElicitOptions): Promise ? O : unknown>>; } type FlowBaseRef = { readonly name: string; }; type ScopeRef = { readonly id: string; readonly logger: FrontMcpLogger; }; /** * Session ID validation constants. */ /** Maximum allowed length for session IDs */ export declare const SESSION_ID_MAX_LENGTH = 2048; /** * Valid characters for session IDs: * - Alphanumeric (a-z, A-Z, 0-9) * - Hyphen, underscore, period * - Colon (for namespaced IDs like "anon:uuid") */ export declare const SESSION_ID_VALID_PATTERN: RegExp; /** * Validate a session ID string. * * Validates: * - Not empty * - Maximum length (2048 characters) * - Valid characters only (alphanumeric, hyphen, underscore, period, colon) * * @param value - The session ID to validate * @throws InvalidInputError if validation fails (empty, too long, invalid characters) */ export declare function validateSessionId(value: string): void; /** * FrontMcpContext - Unified context for FrontMCP * * Provides a single point of truth for all request-related data: * - Identity: requestId, sessionId, scopeId * - Tracing: W3C trace context * - Auth: authentication information (progressively populated) * - References: transport, flow, scope (pointers, not copies) * - Store: key/value storage for context-scoped data * - Fetch: context-aware fetch with auto-injection */ export declare class FrontMcpContext { /** Unique request identifier (UUID v4) */ readonly requestId: string; /** Session identifier (validated) */ readonly sessionId: string; /** Scope identifier */ readonly scopeId: string; /** W3C Trace Context or generated trace ID */ readonly traceContext: TraceContext; /** Request start timestamp */ readonly timestamp: number; /** Context configuration */ readonly config: FrontMcpContextConfig; /** Request metadata (headers, user-agent, etc.) */ readonly metadata: RequestMetadata; private _authInfo; private _sessionMetadata?; private _credentialMiddleware?; private _transport?; private _flow?; private _scope?; private readonly marks; private readonly store; /** * Tokens that should be injected into the provider context. * These are registered by auth flows and made available to tools via context extensions. */ private readonly _contextTokens; constructor(args: FrontMcpContextArgs); /** * Get authentication information. * Returns Partial because auth info is progressively populated. */ get authInfo(): Partial; /** * Get session metadata (protocol, platform type, node info). * Only available after session verification. */ get sessionMetadata(): SessionIdPayload | undefined; /** * Get transport accessor for elicit support. * Returns undefined if no transport is registered. */ get transport(): TransportAccessor | undefined; /** * Get current flow reference. */ get flow(): FlowBaseRef | undefined; /** * Get scope reference. */ get scope(): ScopeRef | undefined; /** * Store context-scoped data. * * @param key - Storage key * @param value - Value to store */ set(key: string | symbol, value: T): void; /** * Retrieve context-scoped data. * * @param key - Storage key * @returns Stored value or undefined */ get(key: string | symbol): T | undefined; /** * Check if a key exists in the context store. * * @param key - Storage key * @returns True if key exists */ has(key: string | symbol): boolean; /** * Delete a key from the context store. * * @param key - Storage key * @returns True if key was deleted */ delete(key: string | symbol): boolean; /** * Mark a timing point for performance tracking. * * @param name - Name of the timing mark */ mark(name: string): void; /** * Get elapsed time in milliseconds between two marks. * * @param from - Start mark name (defaults to 'init') * @param to - End mark name (defaults to current time) * @returns Elapsed time in milliseconds */ elapsed(from?: string, to?: string): number; /** * Get all timing marks. * * @returns Read-only map of mark names to timestamps */ getMarks(): ReadonlyMap; /** * Get a child logger with context attached. * * Creates a child logger with a prefix containing the request ID and trace ID * for easy request tracing in logs. * * @param parentLogger - The parent logger to create a child from * @returns A logger with requestId and traceId in the prefix */ getLogger(parentLogger: FrontMcpLogger): FrontMcpLogger; /** * Get a summary of the context for logging. * * Note: sessionId is hashed to prevent accidental exposure of user-identifying * session identifiers in logs while still allowing correlation. * * @returns Object with key context fields */ toLogContext(): Record; /** * Perform a fetch request with automatic header injection. * * Injects: * - Authorization header (if authInfo.token is available and autoInjectAuthHeaders is true) * - W3C traceparent header (if autoInjectTracingHeaders is true) * - x-request-id header * - Custom headers from request metadata * * @param input - Request URL or Request object * @param init - Request options * @returns Fetch response */ fetch(input: RequestInfo | URL, init?: FrontMcpFetchInit | RequestInit): Promise; } /** * Alias for FrontMcpContext. * Use when you want a shorter name. */ export { FrontMcpContext as Context }; //# sourceMappingURL=frontmcp-context.d.ts.map