claude-playwright
Version:
Seamless integration between Claude Code and Playwright MCP for efficient browser automation and testing
1,719 lines (1,695 loc) • 57 kB
text/typescript
import Database from 'better-sqlite3';
import { BrowserContext, Page } from '@playwright/test';
interface SessionData {
name: string;
createdAt: number;
expiresAt: number;
storageState: any;
browserProfile?: string;
metadata?: {
url?: string;
userAgent?: string;
viewport?: {
width: number;
height: number;
};
};
}
interface SessionListItem {
name: string;
created: string;
expires: string;
expired: boolean;
browserProfile?: string;
}
declare class SessionManager {
private sessionsDir;
private profilesDir;
private configPath;
constructor(workingDir?: string);
/**
* Get session configuration
*/
getSessionConfig(): Promise<any>;
/**
* Save a browser session with 8-hour expiry
*/
saveSession(name: string, storageState: any, options?: {
browserProfile?: string;
metadata?: SessionData['metadata'];
}): Promise<string>;
/**
* Load a stored session and check expiry
*/
loadSession(name: string): Promise<any>;
/**
* Get full session data including metadata
*/
getSessionData(name: string): Promise<SessionData>;
/**
* List all sessions with their status
*/
listSessions(): Promise<SessionListItem[]>;
/**
* Clear expired sessions
*/
clearExpiredSessions(): Promise<number>;
/**
* Delete a specific session
*/
deleteSession(name: string): Promise<boolean>;
/**
* Check if session exists and is valid
*/
isSessionValid(name: string): Promise<boolean>;
/**
* Update session expiry (extend for another 8 hours)
*/
extendSession(name: string): Promise<boolean>;
/**
* Auto-extend session if it expires in less than 2 hours
*/
autoExtendSession(name: string): Promise<boolean>;
/**
* Check session health and provide recommendations
*/
checkSessionHealth(name: string): Promise<{
isValid: boolean;
hoursRemaining: number;
recommendation: string;
needsExtension: boolean;
}>;
/**
* Batch check health of all sessions
*/
checkAllSessionsHealth(): Promise<Array<{
name: string;
isValid: boolean;
hoursRemaining: number;
recommendation: string;
needsExtension: boolean;
}>>;
/**
* Find the latest valid session for auto-loading (MCP integration)
*/
findLatestValidSession(): Promise<SessionData | null>;
/**
* Get the currently active session name from active-session.json
*/
getActiveSession(): Promise<string | null>;
/**
* Switch to a different session by updating active-session.json
*/
switchSession(sessionName: string): Promise<boolean>;
/**
* Get MCP-compatible session data with environment variables
*/
getMCPSessionData(sessionName?: string): Promise<any>;
/**
* Auto-save session during MCP usage
*/
autoSaveSession(storageState: any, metadata?: any): Promise<string | null>;
/**
* Clean up old auto-backup sessions
*/
private cleanupOldAutoBackups;
}
interface BrowserProfile {
name: string;
description: string;
role: string;
createdAt: number;
lastUsed: number;
settings: {
userAgent?: string;
viewport?: {
width: number;
height: number;
};
locale?: string;
timezone?: string;
permissions?: string[];
cookies?: any[];
localStorage?: Record<string, string>;
sessionStorage?: Record<string, string>;
hasTouch?: boolean;
isMobile?: boolean;
deviceScaleFactor?: number;
};
authState?: {
storageState?: any;
authFile?: string;
};
metadata?: {
tags?: string[];
environment?: 'dev' | 'staging' | 'prod';
baseUrl?: string;
associatedSessions?: string[];
};
}
interface ProfileSummary {
name: string;
role: string;
lastUsed: string;
environment?: string;
description: string;
metadata?: {
tags?: string[];
environment?: 'dev' | 'staging' | 'prod';
baseUrl?: string;
associatedSessions?: string[];
};
configuration?: {
viewport?: {
width: number;
height: number;
};
userAgent?: string;
hasTouch?: boolean;
isMobile?: boolean;
deviceScaleFactor?: number;
locale?: string;
timezone?: string;
};
}
/**
* Browser Profile Manager for managing multiple browser profiles with different user roles
*/
declare class BrowserProfileManager {
private profilesDir;
private authStatesDir;
constructor(workingDir?: string);
/**
* Create a new browser profile for a specific role
*/
createProfile(profileData: {
name: string;
role: string;
description?: string;
settings?: BrowserProfile['settings'];
metadata?: BrowserProfile['metadata'];
silent?: boolean;
}): Promise<string>;
/**
* Load a browser profile
*/
loadProfile(profileName: string): Promise<BrowserProfile>;
/**
* Update an existing profile
*/
updateProfile(profileName: string, updates: Partial<BrowserProfile>): Promise<boolean>;
/**
* List all browser profiles
*/
listProfiles(): Promise<ProfileSummary[]>;
/**
* Delete a browser profile
*/
deleteProfile(profileName: string, silent?: boolean): Promise<boolean>;
/**
* Create predefined profiles for common roles
*/
setupDefaultProfiles(): Promise<void>;
/**
* Get profile configuration for MCP integration
*/
getProfileForSession(browserProfile?: string): Promise<BrowserProfile | null>;
/**
* Associate a session with a browser profile
*/
associateSessionWithProfile(profileName: string, sessionName: string): Promise<boolean>;
/**
* Get sessions associated with a profile
*/
getAssociatedSessions(profileName: string): Promise<string[]>;
/**
* Find the best profile for auto-loading with a session
*/
findBestProfileForAutoLoad(): Promise<string | null>;
}
interface PositionalKeyword {
word: string;
position: number;
context?: string;
}
interface InputFeatures {
hasId: boolean;
hasClass: boolean;
hasQuoted: boolean;
numbers: string[];
positions: PositionalKeyword[];
attributes: string[];
wordCount: number;
hasImperative: boolean;
casePattern: 'lower' | 'upper' | 'mixed' | 'title';
isNavigation: boolean;
isFormAction: boolean;
hasDataTestId: boolean;
}
interface NormalizationResult {
normalized: string;
tokens: string[];
positions: PositionalKeyword[];
features: InputFeatures;
hash: string;
}
declare class SmartNormalizer {
private readonly POSITION_KEYWORDS;
private readonly RELATION_KEYWORDS;
private readonly STOP_WORDS;
private readonly ACTION_SYNONYMS;
normalize(input: string): NormalizationResult;
extractFeatures(input: string): InputFeatures;
private extractPositions;
private extractAttributes;
private detectCasePattern;
/**
* Fix common Playwright CSS selector syntax errors early in the process
*/
private fixPlaywrightSyntax;
private normalizeActions;
private removeCommonPatterns;
calculateSimilarity(result1: NormalizationResult, result2: NormalizationResult): number;
damerauLevenshtein(a: string, b: string): number;
generateVariations(input: string): string[];
private generateTokenPermutations;
/**
* Calculate Jaccard similarity between two texts
* Returns similarity score between 0 (no similarity) and 1 (identical)
*/
calculateJaccardSimilarity(text1: string, text2: string): number;
/**
* Context-aware similarity calculation
* Integrates with ContextAwareSimilarity for enhanced matching
*/
calculateContextAwareSimilarity(text1: string, text2: string, context?: {
currentUrl?: string;
operationType?: 'test_search' | 'cache_lookup' | 'pattern_match' | 'cross_env' | 'default';
profile?: string;
domainMatch?: boolean;
}): number;
/**
* Enhanced similarity that automatically detects action conflicts
* Returns -1 if actions conflict (should prevent matching)
*/
calculateSimilarityWithActionDetection(text1: string, text2: string): number;
/**
* Get context-appropriate threshold for similarity matching
*/
getThresholdForOperation(operationType?: 'test_search' | 'cache_lookup' | 'pattern_match' | 'cross_env' | 'default'): number;
/**
* Check if similarity meets context-appropriate threshold
*/
meetsThresholdForOperation(similarity: number, operationType?: 'test_search' | 'cache_lookup' | 'pattern_match' | 'cross_env' | 'default'): boolean;
}
/**
* Enhanced Cache Key Schema for Phase 2.2
* Provides improved cross-environment cache matching with structured test patterns
*/
interface EnhancedCacheKey {
test_name_normalized: string;
url_pattern: string;
dom_signature: string;
steps_structure_hash: string;
profile: string;
version: number;
}
interface CacheKeyComponents {
baseKey: string;
enhancedKey: EnhancedCacheKey;
legacyKey?: string;
}
interface TestStep {
action: 'navigate' | 'click' | 'type' | 'wait' | 'assert' | 'screenshot';
target?: string;
value?: string;
selector?: string;
timeout?: number;
description: string;
}
interface StepsStructureAnalysis {
actionPattern: string[];
selectorTypes: string[];
conditionalLogic: boolean;
loopsDetected: boolean;
structureComplexity: 'simple' | 'medium' | 'complex';
}
interface URLPatternComponents {
protocol?: string;
domain?: string;
port?: string;
pathPattern: string;
queryPattern?: string;
}
/**
* Enhanced Cache Key Manager for Phase 2.2
* Manages the new enhanced cache key system with backward compatibility
*/
declare class EnhancedCacheKeyManager {
private normalizer;
private domSignatureManager;
private readonly CURRENT_VERSION;
constructor();
/**
* Generate enhanced cache key from components
*/
generateEnhancedKey(testName: string, url: string, domSignature?: string, steps?: TestStep[], profile?: string): EnhancedCacheKey;
/**
* Generate cache key components for storage and lookup
*/
generateCacheKeyComponents(testName: string, url: string, domSignature?: string, steps?: TestStep[], profile?: string): CacheKeyComponents;
/**
* Extract URL pattern from full URL - replaces IDs with wildcards
*/
extractURLPattern(url: string): string;
/**
* Analyze steps structure and generate hash
*/
analyzeStepsStructure(steps: TestStep[]): StepsStructureAnalysis;
/**
* Generate steps structure hash without sensitive values
*/
generateStepsStructureHash(steps: TestStep[]): string;
/**
* Classify selector type for pattern analysis
*/
private classifySelector;
/**
* Detect repeated action patterns in steps
*/
private detectActionLoops;
/**
* Generate fallback DOM signature when page is not available
*/
private generateFallbackDOMSignature;
/**
* Generate base storage key from enhanced key
*/
private generateBaseKey;
/**
* Generate legacy key for backward compatibility
*/
private generateLegacyKey;
/**
* Parse enhanced cache key from stored data
*/
parseEnhancedKey(keyData: string): EnhancedCacheKey | null;
/**
* Serialize enhanced cache key for storage
*/
serializeEnhancedKey(key: EnhancedCacheKey): string;
/**
* Calculate similarity between two enhanced cache keys
*/
calculateKeySimilarity(key1: EnhancedCacheKey, key2: EnhancedCacheKey): number;
/**
* Calculate URL pattern similarity
*/
private calculateURLPatternSimilarity;
/**
* Calculate DOM signature similarity
*/
private calculateDOMSimilarity;
/**
* Check if enhanced cache key is valid
*/
isValidEnhancedKey(key: EnhancedCacheKey): boolean;
}
interface CacheOptions {
maxSizeMB?: number;
selectorTTL?: number;
snapshotTTL?: number;
cleanupInterval?: number;
maxVariationsPerSelector?: number;
}
interface LookupResult {
selector: string;
confidence: number;
source: 'exact' | 'normalized' | 'reverse' | 'fuzzy';
cached: boolean;
}
declare class BidirectionalCache {
protected db: Database.Database;
protected normalizer: SmartNormalizer;
private domSignatureManager;
private enhancedKeyManager;
private migrationManager;
private cleanupTimer?;
private options;
private cacheDir;
private stats;
constructor(options?: CacheOptions);
private initializeDatabase;
/**
* Perform migration to enhanced cache key system if needed
*/
private performMigrationIfNeeded;
/**
* Enhanced cache key storage - stores using both legacy and enhanced keys
*/
setEnhanced(testName: string, input: string, url: string, selector: string, steps?: TestStep[], profile?: string, page?: any): Promise<void>;
/**
* Enhanced cache key lookup with pattern matching and cross-environment support
*/
getEnhanced(testName: string, url: string, steps?: TestStep[], profile?: string, page?: any): Promise<LookupResult | null>;
/**
* Find best matching enhanced cache entry using pattern similarity
*/
private findBestEnhancedMatch;
/**
* Update last_used timestamp for enhanced cache entry
*/
private updateLastUsed;
set(input: string, url: string, selector: string): Promise<void>;
get(input: string, url: string): Promise<LookupResult | null>;
private exactMatch;
private normalizedMatch;
private reverseLookup;
private fuzzyMatch;
/**
* Context-aware similarity calculation that integrates with the enhanced similarity system
*/
private calculateContextAwareSimilarity;
private calculateJaccardSimilarity;
private createSelectorHash;
private updateUsage;
private learnRelatedInputs;
private findCommonPattern;
private saveLearnedPattern;
private startCleanupTimer;
private cleanup;
getStats(): Promise<any>;
clear(): Promise<void>;
invalidateSelector(selector: string, url: string): Promise<void>;
getSnapshot(key: object, profile?: string, options?: {
page?: any;
url?: string;
domSignatureFallback?: boolean;
}): Promise<any | null>;
setSnapshot(key: object, value: any, options?: {
url?: string;
profile?: string;
ttl?: number;
page?: any;
}): Promise<void>;
invalidateSnapshots(options?: {
url?: string;
profile?: string;
}): Promise<void>;
getSnapshotMetrics(): Promise<any>;
private createCacheKey;
/**
* Enhanced cache key generation incorporating DOM signature
* Phase 2.1 - DOM Signature Infrastructure
*/
createDOMEnhancedCacheKey(baseKey: string, page: any, url: string, profile?: string): Promise<string>;
/**
* Enhanced selector caching with DOM signature support
* Phase 2.1 - DOM Signature Infrastructure
*/
setWithDOMSignature(input: string, url: string, selector: string, page?: any, options?: {
confidence?: number;
}): Promise<void>;
/**
* Enhanced lookup with DOM signature fallback
* Phase 2.1 - DOM Signature Infrastructure
*/
getWithDOMSignatureFallback(input: string, url: string, page?: any, options?: {
similarityThreshold?: number;
}): Promise<LookupResult | null>;
/**
* Get DOM signature statistics and health metrics
*/
getDOMSignatureMetrics(): Promise<any>;
getDOMSignatureStats(): Promise<any>;
getEnhancedKeyStats(): Promise<any>;
close(): void;
}
/**
* Command line interface types for session and profile management
*/
interface SessionCommandOptions {
dir?: string;
profile?: string;
metadata?: SessionMetadata;
extend?: boolean;
}
interface SessionMetadata {
url?: string;
userAgent?: string;
viewport?: {
width: number;
height: number;
};
description?: string;
tags?: string[];
environment?: 'dev' | 'staging' | 'prod';
}
interface SessionSaveOptions extends SessionCommandOptions {
browserProfile?: string;
metadata?: SessionMetadata;
storageState?: StorageState;
}
interface SessionLoadResult {
storageState: StorageState;
metadata?: SessionMetadata;
profile?: string;
}
interface SessionListOptions {
dir?: string;
filter?: 'all' | 'valid' | 'expired';
format?: 'table' | 'json' | 'csv';
}
interface ProfileCommandOptions {
dir?: string;
role?: string;
description?: string;
environment?: 'dev' | 'staging' | 'prod';
template?: string;
}
interface ProfileCreateOptions extends ProfileCommandOptions {
name?: string;
role?: string;
settings?: BrowserProfileSettings;
metadata?: ProfileMetadata;
}
interface BrowserProfileSettings {
userAgent?: string;
viewport?: {
width: number;
height: number;
};
locale?: string;
timezone?: string;
permissions?: string[];
cookies?: CookieData[];
localStorage?: Record<string, string>;
sessionStorage?: Record<string, string>;
}
interface ProfileMetadata {
tags?: string[];
environment?: 'dev' | 'staging' | 'prod';
baseUrl?: string;
description?: string;
team?: string;
version?: string;
associatedSessions?: string[];
}
interface ProfileListOptions {
dir?: string;
role?: string;
environment?: string;
format?: 'table' | 'json' | 'csv';
}
interface ScaffoldOptions {
path?: string;
template?: string;
overwrite?: boolean;
dryRun?: boolean;
}
interface ScaffoldPageOptions extends ScaffoldOptions {
extends?: string;
selectors?: string[];
actions?: string[];
assertions?: string[];
}
interface ScaffoldTestOptions extends ScaffoldOptions {
fixture?: string;
tags?: string[];
describe?: string;
parallel?: boolean;
}
interface ScaffoldFixtureOptions extends ScaffoldOptions {
type?: 'auth' | 'data' | 'api' | 'custom';
dependencies?: string[];
shared?: boolean;
}
interface StorageState {
cookies: CookieData[];
origins: OriginData[];
}
interface CookieData {
name: string;
value: string;
domain: string;
path: string;
expires: number;
httpOnly: boolean;
secure: boolean;
sameSite: 'Strict' | 'Lax' | 'None';
}
interface OriginData {
origin: string;
localStorage: Array<{
name: string;
value: string;
}>;
sessionStorage: Array<{
name: string;
value: string;
}>;
}
interface CommandResult<T = any> {
success: boolean;
data?: T;
error?: string;
warnings?: string[];
metadata?: {
executionTime?: number;
affectedFiles?: string[];
createdDirectories?: string[];
};
}
interface CommandContext {
workingDir: string;
verbose?: boolean;
dryRun?: boolean;
force?: boolean;
}
interface TemplateContext {
projectName: string;
templateType: string;
variables: Record<string, string>;
features: string[];
}
interface GeneratorOptions {
targetPath: string;
templatePath: string;
context: TemplateContext;
overwrite?: boolean;
backup?: boolean;
}
interface ValidationResult$1 {
isValid: boolean;
errors: ValidationError[];
warnings: ValidationWarning[];
}
interface ValidationError {
field: string;
message: string;
code: string;
severity: 'error' | 'warning';
}
interface ValidationWarning {
field: string;
message: string;
suggestion?: string;
}
type SessionAction = 'list' | 'save' | 'load' | 'delete' | 'clear' | 'extend' | 'info';
type ProfileAction = 'list' | 'create' | 'delete' | 'update' | 'setup' | 'export' | 'import';
type ScaffoldType = 'page' | 'test' | 'fixture' | 'component' | 'helper';
/**
* Session Helper for integrating Playwright with Session Management
* Provides automatic session backup, loading, and rotation
*/
declare class SessionHelper {
private sessionManager;
private currentSession?;
private context?;
private page?;
constructor(workingDir?: string);
/**
* Initialize session helper with Playwright context and page
*/
init(context: BrowserContext, page: Page): Promise<void>;
/**
* Save current browser session
*/
saveCurrentSession(sessionName: string, options?: {
browserProfile?: string;
includeMetadata?: boolean;
}): Promise<boolean>;
/**
* Create a new browser context with a saved session
*/
static createContextWithSession(browser: any, sessionName: string, workingDir?: string): Promise<BrowserContext | null>;
/**
* Create context with auto-loaded session from environment (MCP integration)
*/
static createContextWithMCPSession(browser: any): Promise<BrowserContext | null>;
/**
* Save session with MCP integration awareness
*/
saveMCPSession(sessionName: string, options?: {
browserProfile?: string;
includeMetadata?: boolean;
updateEnvironment?: boolean;
}): Promise<boolean>;
/**
* Auto-save session periodically (for MCP background operations)
*/
startAutoSave(intervalMinutes?: number): NodeJS.Timeout | null;
}
/**
* MCP Integration Utilities
* Handles coordination between Sessions and Browser Profiles for MCP server
*/
declare class MCPIntegration {
private sessionManager;
private profileManager;
constructor(workingDir?: string);
/**
* Initialize MCP with best available session and profile combination
*/
initializeMCPEnvironment(): Promise<{
sessionData: any;
profileData: any;
environmentVars: Record<string, string>;
}>;
/**
* Associate current session with a profile
*/
associateSessionWithProfile(sessionName: string, profileName: string): Promise<boolean>;
/**
* Save session with profile association
*/
saveSessionWithProfile(sessionName: string, storageState: any, profileName?: string, metadata?: any): Promise<boolean>;
/**
* Get recommended profile for a session
*/
getRecommendedProfile(sessionName: string): Promise<string | null>;
/**
* Clean up expired sessions and optimize profiles
*/
cleanupAndOptimize(): Promise<void>;
/**
* Get status report for MCP integration
*/
getStatusReport(): Promise<{
activeSessions: number;
expiredSessions: number;
availableProfiles: number;
currentSession?: string;
currentProfile?: string;
recommendations: string[];
}>;
}
/**
* Centralized project path management
* Uses project-local .claude-playwright directory instead of user home directory
*/
declare class ProjectPaths {
private static projectRoot;
private static baseDir;
/**
* Find the project root by looking for package.json, .git, or other markers
*/
static findProjectRoot(startDir?: string): string;
/**
* Get the base .claude-playwright directory (project-local)
*/
static getBaseDir(): string;
/**
* Get the cache directory
*/
static getCacheDir(): string;
/**
* Get the sessions directory
*/
static getSessionsDir(): string;
/**
* Get the profiles directory
*/
static getProfilesDir(): string;
/**
* Get the logs directory
*/
static getLogsDir(): string;
/**
* Ensure all required directories exist
*/
static ensureDirectories(): Promise<void>;
/**
* Reset cached paths (for testing)
*/
static reset(): void;
/**
* Get project-relative path for display purposes
*/
static getRelativePath(fullPath: string): string;
/**
* Check if we're in a valid project (has project markers)
*/
static isValidProject(): boolean;
}
interface ElementSignature {
tag: string;
attributes: Record<string, string>;
textContent?: string;
position?: number;
}
interface DOMSignatureResult {
criticalHash: string;
importantHash: string;
contextHash: string;
fullSignature: string;
elementCounts: {
critical: number;
important: number;
context: number;
};
}
interface DOMSignatureOptions {
cacheTTL?: number;
includeTextContent?: boolean;
includePositions?: boolean;
maxElementsPerLevel?: number;
}
/**
* DOMSignatureManager creates hierarchical page fingerprints for cache key generation.
*
* Generates 3-level DOM signatures:
* - Level 1: Critical interactive elements (buttons, inputs, forms)
* - Level 2: Important structural elements (links, navigation, containers)
* - Level 3: Page context (headings, main content areas, sections)
*
* Final signature format: criticalHash:importantHash:contextHash
*/
declare class DOMSignatureManager {
private signatureCache;
private cleanupTimer?;
private options;
constructor(options?: DOMSignatureOptions);
/**
* Generate hierarchical DOM signature for a page
* @param page Playwright Page object or DOM content string
* @param url Current page URL for caching
* @returns Promise<DOMSignatureResult> with hierarchical hashes
*/
generateSignature(page: any, url: string): Promise<DOMSignatureResult>;
/**
* Extract elements from raw HTML string
*/
private extractElementsFromHTML;
/**
* Extract attributes from HTML string
*/
private extractAttributesFromHTML;
/**
* Extract elements from live DOM (runs in browser context)
* This method would be injected into page.evaluate()
* Note: This is a placeholder - actual implementation should be converted to string
* and executed in browser context via page.evaluate()
*/
private extractElementsFromDOM;
/**
* Get the DOM extraction function as a string for page.evaluate()
*/
static getDOMExtractionScript(): string;
/**
* Create hierarchical signature from extracted elements
*/
private createHierarchicalSignature;
/**
* Generate deterministic hash for a group of elements
*/
private hashElements;
/**
* Get cached signature if valid
*/
private getCachedSignature;
/**
* Cache signature result
*/
private cacheSignature;
/**
* Start cleanup timer for expired cache entries
*/
private startCleanupTimer;
/**
* Get cache statistics
*/
getCacheStats(): {
size: number;
hits: number;
misses: number;
};
/**
* Clear signature cache
*/
clearCache(): void;
/**
* Close and cleanup
*/
close(): void;
/**
* Validate DOM signature format
*/
static isValidSignature(signature: string): boolean;
/**
* Parse DOM signature into components
*/
static parseSignature(signature: string): {
critical: string;
important: string;
context: string;
} | null;
}
/**
* Static utility functions for DOM signature operations
*/
declare const DOMSignatureUtils: {
/**
* Compare two DOM signatures for similarity
*/
calculateSimilarity(sig1: string, sig2: string): number;
/**
* Check if signature indicates significant page change
*/
hasSignificantChange(oldSignature: string, newSignature: string, threshold?: number): boolean;
/**
* Generate cache key incorporating DOM signature
*/
generateCacheKey(baseKey: string, domSignature: string, profile?: string): string;
};
/**
* MCP Protocol Validation System
*
* Ensures all MCP messages conform to JSON-RPC 2.0 specification
* and provides validation for token handling and protocol versions.
*/
interface ValidationResult {
isValid: boolean;
errors: string[];
validatedMessage?: any;
warningMessages?: string[];
}
interface SafeInput {
originalInput: any;
sanitizedInput: any;
sanitizationApplied: string[];
}
declare class ProtocolError extends Error {
type: 'VALIDATION_ERROR' | 'TOKEN_ERROR' | 'VERSION_MISMATCH';
originalMessage?: any;
constructor(message: string, type: ProtocolError['type'], originalMessage?: any);
}
interface MCPProtocolValidator {
validateMessage(message: any): ValidationResult;
validateTokenFormat(token: string): boolean;
enforceProtocolVersion(version: string): void;
sanitizeInput(input: any): SafeInput;
}
declare class DefaultMCPProtocolValidator implements MCPProtocolValidator {
private supportedVersions;
private currentVersion;
/**
* Validates MCP message against JSON-RPC 2.0 specification
*/
validateMessage(message: any): ValidationResult;
/**
* Validates token format and structure
*/
validateTokenFormat(token: string): boolean;
/**
* Enforces protocol version compatibility
*/
enforceProtocolVersion(version: string): void;
/**
* Sanitizes input to prevent injection attacks
*/
sanitizeInput(input: any): SafeInput;
private isRequest;
private isResponse;
private isNotification;
private validateRequest;
private validateResponse;
private validateNotification;
private validateMCPContent;
private isValidErrorObject;
}
/**
* Protocol Validation Layer
*
* Main integration point for protocol validation in the MCP server.
* Wraps all message processing with validation and error recovery.
*/
interface ValidatedMessage {
original: any;
validated: any;
validationResult: ValidationResult;
processingTime: number;
}
interface ProtocolValidationConfig {
enabled: boolean;
strictMode: boolean;
sanitizeInputs: boolean;
enableRecovery: boolean;
maxRecoveryAttempts: number;
}
declare class ProtocolValidationLayer {
private validator;
private errorRecovery;
private config;
private validationStats;
constructor(config?: Partial<ProtocolValidationConfig>);
/**
* Main entry point for message validation
*/
processMessage(message: any): Promise<ValidatedMessage>;
/**
* Validates and processes tool calls specifically
*/
processToolCall(toolName: string, params: any): Promise<{
toolName: string;
params: any;
}>;
/**
* Validates response before sending
*/
processResponse(response: any): Promise<any>;
/**
* Validates error response
*/
processErrorResponse(error: Error, id?: string): Promise<any>;
/**
* Get validation statistics
*/
getStats(): {
successRate: number;
recoveryRate: number;
totalMessages: number;
validMessages: number;
invalidMessages: number;
recoveredMessages: number;
averageValidationTime: number;
};
/**
* Reset validation statistics
*/
resetStats(): void;
/**
* Update configuration
*/
updateConfig(newConfig: Partial<ProtocolValidationConfig>): void;
private attemptRecovery;
private updateAverageValidationTime;
}
/**
* Protocol Error Recovery System
*
* Attempts to recover from protocol validation errors through
* intelligent message reformation and graceful degradation.
*/
interface RecoveryResult {
recovered: boolean;
recoveryMethod?: string;
recoveredMessage?: any;
error?: string;
degradationLevel?: 'none' | 'minimal' | 'significant' | 'fallback';
}
declare class ProtocolErrorRecovery {
private strategies;
constructor();
/**
* Main entry point for error recovery
*/
handleProtocolError(error: ProtocolError): Promise<RecoveryResult>;
}
/**
* Tool Naming Strategy for Phase 1: MCP Tool Recognition Revolution
*
* Maps old tool names to new mcp_ prefixed names with enhanced descriptions
* that explicitly signal preference over built-in Claude tools.
*/
interface ToolMapping {
oldName: string;
newName: string;
category: 'core' | 'testing' | 'debug';
loadPriority: number;
enhancedDescription: string;
}
declare class ToolNamingStrategy {
private static readonly TOOL_MAPPINGS;
/**
* Get all tool mappings organized by category and priority
*/
static getAllMappings(): ToolMapping[];
/**
* Get mappings by load priority for progressive loading
*/
static getMappingsByPriority(priority: number): ToolMapping[];
/**
* Get mapping for a specific old tool name
*/
static getMappingForOldName(oldName: string): ToolMapping | undefined;
/**
* Get mapping for a specific new tool name
*/
static getMappingForNewName(newName: string): ToolMapping | undefined;
/**
* Check if a tool name should be migrated
*/
static shouldMigrate(toolName: string): boolean;
/**
* Get deprecation message for old tool name
*/
static getDeprecationMessage(oldName: string): string;
/**
* Generate migration statistics
*/
static getMigrationStats(): {
totalTools: number;
coreTools: number;
testingTools: number;
debugTools: number;
immediateLoad: number;
delayedLoad: number;
};
}
/**
* Progressive Tool Loader for Phase 1: Tool Naming Revolution
*
* Implements staged tool loading to prevent Claude from being overwhelmed
* by too many tool choices at once, improving tool selection reliability.
*/
interface ProgressiveLoadingConfig {
enableProgressiveLoading: boolean;
baseDelay: number;
loadingStages: number[];
maxConcurrentLoads: number;
logLoading: boolean;
}
declare class ProgressiveToolLoader {
private config;
private loadingStages;
private totalToolsLoaded;
private startTime;
constructor(config?: Partial<ProgressiveLoadingConfig>);
/**
* Initialize loading stages based on configuration
*/
private initializeStages;
/**
* Start progressive loading process
*/
startLoading(toolRegistrationCallback: (mapping: ToolMapping, isNew: boolean) => Promise<void>): Promise<void>;
/**
* Load a specific stage
*/
private loadStage;
/**
* Fallback: Load all tools immediately if progressive loading is disabled
*/
private loadAllToolsImmediately;
/**
* Register legacy tools with deprecation warnings
*/
registerLegacyTools(registrationCallback: (mapping: ToolMapping, isNew: boolean) => Promise<void>): Promise<void>;
/**
* Get loading statistics
*/
getLoadingStats(): {
totalStages: number;
totalTools: number;
loadedStages: number;
loadedTools: number;
completionPercentage: number;
totalTime: number;
};
/**
* Get detailed stage information
*/
getStageDetails(): {
priority: number;
loaded: boolean;
toolCount: number;
loadTime?: number;
}[];
/**
* Check if loading is complete
*/
isLoadingComplete(): boolean;
/**
* Update configuration
*/
updateConfig(newConfig: Partial<ProgressiveLoadingConfig>): void;
private sleep;
private chunkArray;
}
/**
* Database Migration System for Phase 2.2 - Enhanced Cache Key System
* Handles migration from old cache format to new enhanced cache key format
* with backward compatibility and graceful fallback
*/
interface MigrationResult {
success: boolean;
migrated: number;
skipped: number;
errors: number;
duration: number;
details: string[];
}
interface MigrationOptions {
batchSize: number;
retryFailures: boolean;
preserveOldData: boolean;
validateAfterMigration: boolean;
dryRun: boolean;
}
interface EnhancedCacheEntry {
id?: number;
enhanced_key: string;
base_key_hash: string;
legacy_key_hash?: string;
test_name_normalized: string;
url_pattern: string;
dom_signature: string;
steps_structure_hash: string;
profile: string;
version: number;
selector: string;
confidence: number;
created_at: number;
last_used: number;
use_count: number;
migration_source: 'legacy' | 'enhanced' | 'manual';
}
declare class CacheMigrationManager {
private db;
private enhancedKeyManager;
private normalizer;
constructor(database: Database.Database);
/**
* Create new enhanced cache key table structure
*/
createEnhancedCacheSchema(): void;
/**
* Create optimized indexes for the enhanced cache key system
*/
private createEnhancedCacheIndexes;
/**
* Check if migration is needed
*/
isMigrationNeeded(): boolean;
/**
* Perform full migration from legacy to enhanced cache key system
*/
performMigration(options?: Partial<MigrationOptions>): Promise<MigrationResult>;
/**
* Migrate selector cache entries to enhanced format
*/
private migrateSelectorCache;
/**
* Migrate test scenarios to enhanced cache key format
*/
private migrateTestScenarios;
/**
* Convert legacy selector entry to enhanced format
*/
private convertLegacySelectorToEnhanced;
/**
* Migrate individual test scenario
*/
private migrateTestScenario;
/**
* Insert enhanced cache entry into database
*/
private insertEnhancedCacheEntry;
/**
* Extract test name from URL (fallback method)
*/
private extractTestNameFromURL;
/**
* Validate migration results
*/
private validateMigration;
/**
* Get migration status
*/
getMigrationStatus(): {
isComplete: boolean;
enhancedEntries: number;
legacyEntries: number;
unmigratedEntries: number;
};
/**
* Rollback migration (if needed for emergency)
*/
rollbackMigration(): boolean;
}
/**
* Context information for similarity calculations
*/
interface SimilarityContext {
/** Current URL for context */
currentUrl: string;
/** DOM signature for page state */
domSignature?: string;
/** Browser profile being used */
profile: string;
/** Whether domains match between contexts */
domainMatch: boolean;
/** Operation type context */
operationType?: 'test_search' | 'cache_lookup' | 'pattern_match' | 'cross_env' | 'default';
/** Additional context metadata */
metadata?: {
/** Environment type (local, staging, prod) */
environment?: string;
/** Page type (login, dashboard, settings) */
pageType?: string;
/** User intent confidence */
intentConfidence?: number;
};
}
/**
* Context-aware similarity threshold configuration
* Different use cases require different sensitivity levels
*/
declare const SIMILARITY_THRESHOLDS: {
/** Stricter for test matching to prevent false positives */
readonly test_search: 0.35;
/** Permissive for selector variation tolerance */
readonly cache_lookup: 0.15;
/** Moderate for pattern recognition */
readonly pattern_match: 0.25;
/** Very strict for cross-environment matching */
readonly cross_env: 0.4;
/** Default fallback threshold */
readonly default: 0.2;
};
/**
* Enhanced context-aware similarity calculation system
* Provides intelligent matching with action conflict detection and contextual thresholds
*/
declare class ContextAwareSimilarity {
private normalizer;
constructor();
/**
* Calculate context-aware similarity between two texts
* Returns enhanced similarity score with context considerations
*/
calculateSimilarity(query: string, candidate: string, context: SimilarityContext): number;
/**
* Check if query has exact action match with candidate
*/
hasExactActionMatch(query: string, candidate: string): boolean;
/**
* Check if query has conflicting actions with candidate
* Returns true if actions should prevent matching
*/
hasConflictingActions(query: string, candidate: string): boolean;
/**
* Get appropriate threshold for given context
*/
getThresholdForContext(context: SimilarityContext): number;
/**
* Check if similarity meets threshold for context
*/
meetsThreshold(similarity: number, context: SimilarityContext): boolean;
/**
* Calculate base Jaccard similarity using normalized results
*/
private calculateBaseSimilarity;
/**
* Apply context-aware enhancements to similarity score
*/
private applyContextEnhancements;
/**
* Apply action-specific logic (boosts and conflicts)
*/
private applyActionLogic;
/**
* Apply domain matching logic for cross-environment scenarios
*/
private applyDomainMatching;
/**
* Extract actions from normalized text
*/
private extractActions;
/**
* Calculate boost for action synonyms
*/
private calculateActionSynonymBoost;
/**
* Extract domain patterns for analysis
*/
private extractDomainPatterns;
/**
* Create similarity context from available information
*/
static createContext(currentUrl: string, operationType?: 'test_search' | 'cache_lookup' | 'pattern_match' | 'cross_env' | 'default', options?: Partial<SimilarityContext>): SimilarityContext;
/**
* Enhanced similarity with automatic context detection
*/
calculateSimilarityWithAutoContext(query: string, candidate: string, currentUrl: string, operationType?: 'test_search' | 'cache_lookup' | 'pattern_match' | 'cross_env' | 'default'): number;
/**
* Batch similarity calculation with context
*/
calculateBatchSimilarity(query: string, candidates: string[], context: SimilarityContext): Array<{
candidate: string;
similarity: number;
meetsThreshold: boolean;
}>;
/**
* Find best matches with context awareness
*/
findBestMatches(query: string, candidates: string[], context: SimilarityContext, maxResults?: number): Array<{
candidate: string;
similarity: number;
rank: number;
}>;
}
/**
* Singleton instance for global usage
*/
declare const contextAwareSimilarity: ContextAwareSimilarity;
/**
* Phase 4: Performance Monitor
*
* Comprehensive performance tracking and validation system
* for MCP reliability and Phase 1-3 implementations
*/
interface PerformanceMetrics {
tool_calling_consistency: number;
cache_hit_rate: number;
test_matching_accuracy: number;
error_recovery_time: number;
dom_signature_generation: number;
fallback_success_rate: number;
}
interface ConsistencyMetrics {
consistency_rate: number;
meets_target: boolean;
details: {
total_requests: number;
mcp_tool_usage: number;
builtin_tool_usage: number;
};
}
interface CacheMetrics {
hit_rate: number;
accuracy: number;
average_response_time: number;
meets_targets: {
hit_rate: boolean;
accuracy: boolean;
};
details: {
total_queries: number;
cache_hits: number;
cache_misses: number;
false_positives: number;
};
}
interface ErrorRecoveryMetrics {
average_recovery_time: number;
success_rate: number;
meets_targets: boolean;
error_breakdown: Record<string, number>;
recovery_strategies_used: Record<string, number>;
}
interface BenchmarkResults {
timestamp: string;
version: string;
tool_consistency: ConsistencyMetrics;
cache_performance: CacheMetrics;
error_recovery: ErrorRecoveryMetrics;
cross_environment: CrossEnvironmentMetrics;
overall_success: boolean;
}
interface CrossEnvironmentMetrics {
adaptation_success_rate: number;
environments_tested: string[];
successful_adaptations: number;
failed_adaptations: number;
meets_targets: boolean;
}
declare class PerformanceBenchmark {
private debugMode;
private readonly targets;
private performanceHistory;
constructor(debugMode?: boolean);
runBenchmarkSuite(): Promise<BenchmarkResults>;
private measureToolConsistency;
private measureCachePerformance;
private measureErrorRecovery;
private measureCrossEnvironmentPortability;
private calculateOverallSuccess;
private simulateClaudeRequest;
private generateCacheTestScenarios;
private mockCacheQuery;
private validateCacheHitRelevance;
private simulateErrorRecovery;
private simulateEnvironmentAdaptation;
private getPackageVersion;
private log;
getMetricsHistory(): BenchmarkResults[];
getTargets(): PerformanceMetrics;
generateReport(results?: BenchmarkResults): Promise<string>;
}
/**
* Phase 4: Feature Flag Management System
*
* Enables gradual rollout and A/B testing of MCP reliability improvements
* with comprehensive monitoring and configuration management
*/
interface FeatureFlagConfig {
mcp_naming_v2: {
enabled: boolean;
rollout_percentage: number;
user_groups: string[];
metric_tracking: string[];
description: string;
};
enhanced_caching: {
enabled: boolean;
rollout_percentage: number;
dom_signature_enabled: boolean;
similarity_threshold: number;
metric_tracking: string[];
description: string;
};
circuit_breaker: {
enabled: boolean;
rollout_percentage: number;
failure_threshold: number;
recovery_timeout: number;
metric_tracking: string[];
description: string;
};
intelligent_testing: {
enabled: boolean;
rollout_percentage: number;
auto_test_creation: boolean;
semantic_matching: boolean;
metric_tracking: string[];
description: string;
};
performance_monitoring: {
enabled: boolean;
rollout_percentage: number;
detailed_logging: boolean;
real_time_alerts: boolean;
metric_tracking: string[];
description: string;
};
}
interface FeatureFlagMetrics {
feature_name: string;
enabled_users: number;
total_users: number;
rollout_percentage: number;
success_metrics: Record<string, number>;
error_metrics: Record<string, number>;
performance_impact: {
average_response_time: number;
error_rate: number;
user_satisfaction: number;
};
last_updated: string;
}
interface RolloutStrategy {
type: 'percentage' | 'user_group' | 'canary' | 'blue_green';
target_percentage: number;
duration_hours: number;
success_criteria: {
min_success_rate: number;
max_error_rate: number;
min_user_satisfaction: number;
};
rollback_triggers: {
error_rate_threshold: number;
performance_degradation_threshold: number;
user_complaint_threshold: number;
};
}
declare class FeatureFlagManager {
private config;
private metricsHistory;
private rolloutStrategies;
constructor(configPath?: string);
private loadDefaultConfig;
private initializeDefaultRolloutStrategies;
/**
* Check if a feature is enabled for a specific user/context
*/
isEnabled(feature: keyof FeatureFlagConfig, userId?: string, userGroup?: string): boolean;
/**
* Get feature configuration with dynamic values
*/
getConfig<K extends keyof FeatureFlagConfig>(feature: K): FeatureFlagConfig[K];
/**
* Update feature flag configuration
*/
updateFeatureConfig<K extends keyof FeatureFlagConfig>(feature: K, updates: Partial<FeatureFlagConfig[K]>): void;
/**
* Gradual rollout with automatic percentage increases
*/
startGradualRollout(feature: keyof FeatureFlagConfig, strategyName?: string): Promise<void>;
/**
* Emergency rollback of feature
*/
rollbackFeature(feature: keyof FeatureFlagConfig, rollbackPercentage?: number): Promise<void>;
/**
* A/B test configuration for features with variants
*/
setupABTest(feature: keyof FeatureFlagConfig, variantA: any, variantB: any, splitPercentage?: number): void;
/**
* Get A/B test variant for user
*/
getABVariant(feature: keyof FeatureFlagConfig, userId: string): 'A' | 'B';
/**
* Record metrics for feature flag performance
*/
recordMetric(feature: keyof FeatureFlagConfig, metric: any): void;
/**
* Get comprehensive metrics report
*/
getMetricsReport(): Record<string, any>;
/**
* Export configuration for backup/sharing
*/
exportConfig(): string;
/**
* Import configuration from backup
*/
importConfig(configData: string): void;
private hashUserId;
private loadConfigFromFile;
private logConfigChange;
private validateRolloutStep;
private calculateTrends;
private generateRecommendations;
}
/**
* Phase 4: Test Orchestrator
*
* Coordinates comprehensive validation across all test layers:
* - Unit tests for individual components
* - Integration tests for component interactions
* - E2E tests for full system validation
* - Performance benchmarks for reliability metrics
*/
interface TestResults {
suite_name: string;
total_tests: number;
passed: number;
failed: number;
skipped: number;
duration_ms: number;
success_rate: number;
error_details: string[];
coverage_percentage?: number;
}
i