/** * Audit Logger for MCP Server * * Provides comprehensive audit logging for tool invocations, * security events, and server operations. * * @packageDocumentation */ import type { Logger, ToolCallResult, ToolContext } from '../types'; /** * Audit event severity levels */ export type AuditSeverity = 'debug' | 'info' | 'warning' | 'error' | 'critical'; /** * Audit event categories */ export type AuditCategory = 'tool_invocation' | 'resource_access' | 'prompt_usage' | 'authentication' | 'authorization' | 'configuration' | 'lifecycle' | 'error'; /** * Audit event outcome */ export type AuditOutcome = 'success' | 'failure' | 'partial' | 'unknown'; /** * Base audit event structure */ export interface AuditEvent { /** Unique event identifier */ readonly id: string; /** Event timestamp */ readonly timestamp: Date; /** Event category */ readonly category: AuditCategory; /** Event severity */ readonly severity: AuditSeverity; /** Human-readable event description */ readonly message: string; /** Event outcome */ readonly outcome: AuditOutcome; /** Associated request ID */ readonly requestId?: string; /** Principal who triggered the event */ readonly principal?: AuditPrincipal; /** Resource involved in the event */ readonly resource?: AuditResource; /** Event duration in milliseconds */ readonly duration?: number; /** Additional event metadata */ readonly metadata?: Record; /** Error details if applicable */ readonly error?: AuditError; } /** * Principal information for audit events */ export interface AuditPrincipal { /** Principal type */ readonly type: 'user' | 'service' | 'anonymous' | 'system'; /** Principal identifier */ readonly id: string; /** Principal display name */ readonly name?: string; /** Client IP address */ readonly ipAddress?: string; /** User agent or client identifier */ readonly userAgent?: string; } /** * Resource information for audit events */ export interface AuditResource { /** Resource type */ readonly type: 'tool' | 'resource' | 'prompt' | 'server' | 'configuration'; /** Resource name or identifier */ readonly name: string; /** Resource URI if applicable */ readonly uri?: string; } /** * Error information for audit events */ export interface AuditError { /** Error code */ readonly code: string; /** Error message */ readonly message: string; /** Stack trace (sanitized) */ readonly stack?: string; /** Original error details */ readonly details?: Record; } /** * Tool invocation specific audit data */ export interface ToolInvocationAudit extends AuditEvent { readonly category: 'tool_invocation'; /** Tool name */ readonly toolName: string; /** Tool arguments (sanitized) */ readonly arguments?: Record; /** Tool result summary */ readonly result?: ToolResultSummary; } /** * Tool result summary for audit logging */ export interface ToolResultSummary { /** Content type returned */ readonly contentType: 'text' | 'image' | 'resource' | 'mixed'; /** Content length or count */ readonly contentLength: number; /** Whether the result was an error */ readonly isError: boolean; /** Error message if applicable */ readonly errorMessage?: string; } /** * Fields to exclude from audit logs (sensitive data) */ export interface SanitizationConfig { /** Fields to completely redact */ readonly redactFields?: readonly string[]; /** Fields to mask (show partial value) */ readonly maskFields?: readonly string[]; /** Maximum string length before truncation */ readonly maxStringLength?: number; /** Maximum object depth for logging */ readonly maxDepth?: number; } /** * Audit logger configuration */ export interface AuditLoggerConfig { /** Logger instance for output */ readonly logger?: Logger; /** Minimum severity to log */ readonly minSeverity?: AuditSeverity; /** Whether to include arguments in tool invocation logs */ readonly logArguments?: boolean; /** Whether to include results in tool invocation logs */ readonly logResults?: boolean; /** Sanitization configuration */ readonly sanitization?: SanitizationConfig; /** Custom event handler */ readonly onEvent?: (event: AuditEvent) => void; /** Whether to emit events to stdout as JSON */ readonly emitJson?: boolean; /** Server identifier for multi-instance deployments */ readonly serverId?: string; } /** * Audit Logger * * Provides comprehensive audit logging for MCP server operations. * * @example * ```typescript * const auditLogger = new AuditLogger({ * logger: serverLogger, * logArguments: true, * logResults: true, * }); * * // Log tool invocation * auditLogger.logToolInvocation({ * requestId: 'req-123', * toolName: 'drift_detection', * arguments: { path: './src' }, * principal: { type: 'user', id: 'user-123' }, * outcome: 'success', * duration: 150, * }); * ``` */ export declare class AuditLogger { private readonly config; private readonly severityOrder; /** * Create a new Audit Logger * * @param config - Logger configuration */ constructor(config?: AuditLoggerConfig); /** * Log a tool invocation event * * @param params - Tool invocation parameters */ logToolInvocation(params: { requestId?: string; toolName: string; arguments?: Record; result?: ToolCallResult; principal?: AuditPrincipal; outcome: AuditOutcome; duration?: number; error?: Error; }): void; /** * Log a resource access event * * @param params - Resource access parameters */ logResourceAccess(params: { requestId?: string; resourceUri: string; action: 'read' | 'subscribe' | 'unsubscribe'; principal?: AuditPrincipal; outcome: AuditOutcome; duration?: number; error?: Error; }): void; /** * Log a prompt usage event * * @param params - Prompt usage parameters */ logPromptUsage(params: { requestId?: string; promptName: string; arguments?: Record; principal?: AuditPrincipal; outcome: AuditOutcome; duration?: number; error?: Error; }): void; /** * Log an authorization event * * @param params - Authorization parameters */ logAuthorization(params: { requestId?: string; action: string; resource: AuditResource; principal?: AuditPrincipal; outcome: AuditOutcome; reason?: string; policy?: string; }): void; /** * Log a lifecycle event * * @param params - Lifecycle event parameters */ logLifecycle(params: { action: 'start' | 'stop' | 'restart' | 'health_check' | 'shutdown'; outcome: AuditOutcome; message?: string; metadata?: Record; error?: Error; }): void; /** * Log an error event * * @param params - Error parameters */ logError(params: { requestId?: string; error: Error; context?: string; principal?: AuditPrincipal; metadata?: Record; }): void; /** * Log a custom audit event * * @param event - Custom event to log */ logCustomEvent(event: Omit & Partial>): void; /** * Create an audit context for tool invocation tracking * * @param toolName - Tool being invoked * @param context - Tool context from MCP * @param principal - Principal making the request * @returns Audit tracking object */ createToolInvocationTracker(toolName: string, context: ToolContext, principal?: AuditPrincipal): ToolInvocationTracker; /** * Generate a unique event ID */ private generateEventId; /** * Check if an event should be logged based on severity */ private shouldLog; /** * Emit an audit event */ private emitEvent; /** * Get the appropriate log method for a severity level */ private getLogMethod; /** * Sanitize an object for logging */ private sanitize; /** * Summarize a tool result for audit logging */ private summarizeToolResult; /** * Format an error for audit logging */ private formatError; } /** * Helper class for tracking tool invocations */ export declare class ToolInvocationTracker { private readonly auditLogger; private readonly toolName; private readonly context; private readonly principal?; private readonly startTime; private arguments?; constructor(auditLogger: AuditLogger, toolName: string, context: ToolContext, principal?: AuditPrincipal); /** * Set the tool arguments */ setArguments(args: Record): void; /** * Log successful completion */ success(result: ToolCallResult): void; /** * Log failure */ failure(error: Error, result?: ToolCallResult): void; } /** * Create an audit logger with default configuration * * @param logger - Optional logger instance * @returns Configured audit logger */ export declare function createAuditLogger(logger?: Logger): AuditLogger; //# sourceMappingURL=audit-logger.d.ts.map