@simonecoelhosfo/optimizely-mcp-server
Version:
Optimizely MCP Server for AI assistants with integrated CLI tools
1,167 lines • 77.7 kB
TypeScript
/**
* Optimizely MCP Tools - Business Logic Layer
* @description Core business logic for Optimizely data operations that remains completely
* unchanged in the MCP server implementation. This module serves as the stable business
* logic layer that is consumed by the MCP protocol adapter layer.
*
* ADAPTER PATTERN IMPLEMENTATION:
* This file represents the preserved business logic layer in our MCP adapter pattern.
* The MCP protocol layer (src/mcp/) wraps these tools without modifying them, ensuring:
* - Complete separation of business logic and protocol concerns
* - Zero changes to existing business logic during MCP implementation
* - Clear adapter pattern boundary between protocol and domain logic
* - Stable API contract that can be used by other interfaces (CLI, REST, etc.)
*
* Key Principles:
* - Business logic methods remain completely unchanged
* - Error handling uses business-appropriate error types (converted by MCP layer)
* - Input/output formats optimized for business needs, not MCP protocol
* - No MCP-specific code or dependencies in this layer
* - Can be used independently of MCP protocol layer
*
* MCP Integration:
* The MCP layer (MCPToolHandlers.ts) calls these methods and:
* - Validates MCP input parameters and converts to business format
* - Maps business errors to MCP error types via MCPErrorMapper
* - Formats business results to MCP response format
* - Handles MCP protocol concerns (timeouts, validation, etc.)
*
* @author Optimizely MCP Server
* @version 1.0.0
* @since 1.0.0 - Original business logic implementation
* @pattern Adapter Pattern - Business Logic Layer
*/
import { CacheManager } from '../cache/CacheManager.js';
import { ConfigManager } from '../config/ConfigManager.js';
import type { SchemaResponse, OperationResponse, FieldResponse, DependencyResponse, ExamplesResponse, ValidationResponse, RelationshipsResponse } from './OpenAPITypes.js';
interface ProjectSummary {
id: string;
name: string;
platform: string;
is_flags_enabled: boolean;
account_id: string;
flag_count: number;
experiment_count: number;
environment_count: number;
last_modified?: string | null;
platform_type: 'Feature Experimentation' | 'Web Experimentation';
experiment_explanation: string;
}
interface ListFlagsParams {
project_id?: string;
search?: string;
environment?: string;
enabled?: boolean;
archived?: boolean;
limit?: number;
sort?: string;
}
interface FormattedFlag {
project_id: string;
key: string;
name: string;
description?: string | null;
archived: boolean;
environment_status: Record<string, boolean>;
created_time?: string | null;
updated_time?: string | null;
variations?: any;
}
interface GetFlagDetailsParams {
project_id: string;
flag_key: string;
}
interface CompareEnvironmentsParams {
project_id: string;
flag_key?: string;
environments?: string[];
}
interface ListExperimentsParams {
project_id?: string;
status?: string;
search?: string;
flag_key?: string;
archived?: boolean;
limit?: number;
}
interface FormattedExperiment {
id: string;
project_id: string;
name: string;
description?: string | null;
status: string;
flag_key?: string | null;
flag_name?: string | null;
environment?: string | null;
type: string;
archived: boolean;
created_time?: string | null;
updated_time?: string | null;
variations?: any;
metrics?: any[];
audience_conditions?: any;
}
interface GetExperimentDetailsParams {
experiment_id: string;
include_results?: boolean;
}
interface GetRecentChangesParams {
project_id?: string;
hours?: number;
limit?: number;
target_type?: string;
}
interface ChangeHistoryItem {
id: string;
project_id: string;
target_type: string;
target_id: string;
action: string;
timestamp: string;
user_id?: string | null;
details?: any;
}
interface GetAnalyticsParams {
project_id: string;
}
interface ProjectAnalytics {
project_overview: any;
environment_breakdown: any[];
top_flags_by_usage: any[];
activity_trend_last_30d: any[];
insights: Insight[];
generated_at: string;
}
interface Insight {
type: 'optimization' | 'configuration' | 'experimentation' | 'governance' | 'health';
severity: 'low' | 'medium' | 'high' | 'critical' | 'info';
title: string;
message: string;
action?: string;
affected_items?: string[];
}
/**
* Optimizely MCP Tools - Core Business Logic Implementation
* @description Provides comprehensive business logic for Optimizely data operations
* including feature flags, experiments, audiences, and analytics. This class implements
* the business domain logic independent of any protocol layer (MCP, REST, CLI, etc.).
*
* Business Capabilities:
* - Feature flag management and querying with environment status
* - Experiment lifecycle management and detailed analysis
* - Cross-environment comparison and configuration analysis
* - Full-text search across all Optimizely entities
* - Analytics and insights generation for project health
* - Change history tracking and recent activity monitoring
*
* Architecture Pattern:
* This class follows the adapter pattern where it serves as the stable business
* logic layer. The MCP protocol layer wraps these methods without modification,
* ensuring clean separation between business logic and protocol concerns.
*
* Error Handling:
* Uses business-appropriate error handling with MCPErrorMapper for protocol
* layer conversion. Errors are logged with appropriate context and converted
* to MCP errors by the protocol layer, not within these business methods.
*
* Data Dependencies:
* - CacheManager: Provides cached Optimizely data access
* - SQLiteEngine: Underlying storage for complex queries
* - Logger: Business operation logging and debugging
*/
export declare class OptimizelyMCPTools {
private configManager?;
/** Cache manager for accessing synchronized Optimizely data */
private cache;
/** Schema-aware entity creation system */
private defaultsManager;
private schemaBuilder;
/** OpenAPI reference handler */
private openAPIHandler;
/** Entity router for orchestrator to reuse */
private entityRouter;
/** Individual tool instances for modular architecture */
private individualTools;
/** Session tracking for documentation presentation (Tool Handler Optimization) */
private docsPresentedThisSession;
private docsReadForComplexity;
/**
* Creates a new Optimizely MCP Tools instance
* @param cacheManager - Initialized cache manager for data access
* @description Initializes the business logic layer with data access dependencies.
* The cache manager should be properly initialized before passing to this constructor.
*/
private syncScheduler?;
constructor(cacheManager: CacheManager, configManager?: ConfigManager | undefined);
/**
* Initializes all individual tool instances with proper dependency injection
*/
private initializeIndividualTools;
/**
* Sets the sync scheduler reference (called by the server if auto-sync is enabled)
*/
setSyncScheduler(scheduler: any): void;
/**
* TOOL HANDLER OPTIMIZATION HELPER METHODS
* These methods support the enhanced tool handler architecture that improves
* agent compliance by providing progressive documentation and complexity enforcement.
*/
/**
* Gets the count of configured projects
* @returns Number of projects configured in the cache
*/
getConfiguredProjectsCount(): number;
/**
* Checks if an entity type is complex and requires special guidance
* @param entityType - The entity type to check
* @returns True if entity type has complex creation patterns
*/
private isComplexEntityType;
/**
* Checks if entity creation data indicates complex operation requiring template mode
* @param entityType - The entity type being created
* @param entityData - The creation data provided
* @returns True if operation appears complex
*/
private isComplexCreation;
/**
* Checks if entity update data indicates complex operation requiring template mode
* @param entityType - The entity type being updated
* @param entityData - The update data provided
* @returns True if operation appears complex
*/
private isComplexUpdate;
/**
* Checks if entity update data is simple enough for direct operation (opposite of isComplexUpdate)
* @param entityType - The entity type being updated
* @param entityData - The update data provided
* @returns True if operation is simple and can bypass template orchestration
*/
private isSimpleUpdate;
/**
* Gets template mode information for an entity type
* @param entityType - The entity type
* @returns Template mode availability info
*/
private getTemplateInfo;
/**
* Gets complexity note for entity type
* @param entityType - The entity type
* @returns Complexity guidance note
*/
private getComplexityNote;
/**
* Gets complexity indicators from entity data
* @param entityType - The entity type
* @param entityData - The entity creation data
* @returns Array of detected complexity indicators
*/
private getComplexityIndicators;
/**
* Marks documentation as read for complexity enforcement
* @param entityType - The entity type documentation was read for
*/
private markDocsReadFor;
/**
* Checks if documentation has been read for an entity type
* @param entityType - The entity type to check
* @returns True if docs were read this session
*/
private hasReadDocsFor;
/**
* Lists all projects with basic statistics - simple, direct answer
* @returns Promise resolving to project summary with counts
* @description Provides immediate project overview with key metrics.
* This is the primary tool for answering "how many projects do I have?"
* and similar basic queries without complex filtering.
*/
listProjects(): Promise<{
result: string;
metadata: {
operation: string;
total_count: number;
operation_successful: boolean;
timestamp: string;
};
total_projects: number;
projects: ProjectSummary[];
summary: {
flags_enabled_projects: number;
total_flags: number;
total_experiments: number;
platforms: Record<string, number>;
platform_breakdown: {
feature_experimentation: {
count: number;
experiment_note: string;
total_experiments: number;
};
web_experimentation: {
count: number;
experiment_note: string;
total_experiments: number;
};
};
};
_platform_education: {
key_understanding: string;
feature_experimentation: string;
web_experimentation: string;
how_to_find_experiments: {
feature_experimentation: string;
web_experimentation: string;
};
};
}>;
/**
* Diagnoses sync issues and provides troubleshooting information
* @returns Promise resolving to diagnostic information
* @description Helps troubleshoot why flags might not be syncing for certain projects
*/
/**
* Get diagnostic information (wrapper for backward compatibility)
* @returns Diagnostics data
* @deprecated Use getSystemStatus({ include_diagnostics: true }) instead
*/
getDiagnostics(): Promise<{
database_status: {
projects: number;
flags: number;
experiments: number;
environments: number;
};
project_types: {
web_experimentation: number;
feature_experimentation: number;
unknown: number;
};
sync_issues: string[];
recommendations: string[];
auto_sync_status: {
isRunning: boolean;
syncInProgress?: boolean;
lastSyncTime?: Date;
consecutiveFailures?: number;
nextSyncIn?: string;
note?: string;
};
}>;
/**
* Unified cache management method that consolidates initialize_cache and refresh_cache
* @param args - Cache management arguments
* @returns Promise resolving to cache operation results
*/
manageCache(args: {
operation: 'initialize' | 'refresh' | 'clear';
project_id?: string;
options?: {
force?: boolean;
incremental?: boolean;
views_only?: boolean;
wait_for_completion?: boolean;
progress_callback?: (progress: {
phase: string;
current: number;
total: number;
message: string;
percent: number;
}) => void;
};
}): Promise<any>;
/**
* Initializes an empty cache with data from Optimizely (wrapper for backward compatibility)
* @param options - Initialization options
* @returns Promise resolving to initialization results
* @deprecated Use manageCache with operation='initialize' instead
*/
initializeCache(options?: {
wait_for_completion?: boolean;
progress_callback?: (progress: any) => void;
}): Promise<any>;
/**
* Clears all cached data
* @param options - Clear options
* @returns Promise resolving to clear results
*/
clearCache(options?: {
wait_for_completion?: boolean;
progress_callback?: (progress: any) => void;
}): Promise<any>;
/**
* Refreshes the cache by performing a full sync
* @param options - Options for the refresh operation
* @returns Promise resolving to refresh results
* @description Forces a complete refresh of all cached data from Optimizely API
* @deprecated Use manageCache with operation='refresh' instead
*/
refreshCache(options?: {
projectId?: string;
force?: boolean;
incremental?: boolean;
views_only?: boolean;
progressCallback?: (progress: {
phase: string;
current: number;
total: number;
message: string;
percent: number;
}) => void;
}): Promise<{
success: boolean;
projectsSynced: number;
duration: number;
timestamp: string;
message: string;
totalChanges?: number;
totalCreated?: number;
totalUpdated?: number;
totalDeleted?: number;
viewsRecreated?: number;
}>;
/**
* Lists feature flags with comprehensive filtering and environment status
* @param params - Filter parameters for flag listing
* @returns Promise resolving to formatted flags with environment status and metadata
* @description Core business logic for flag listing with advanced filtering capabilities.
* Provides environment status aggregation, search functionality, and comprehensive
* flag metadata. This method remains unchanged from original implementation.
*
* Business Features:
* - Project-specific filtering with validation
* - Archive status filtering (active/archived flags)
* - Full-text search across flag name, description, and key
* - Environment-specific enablement filtering
* - Configurable result limits and sorting
* - Environment status aggregation for each flag
* - Complete flag variation and configuration data
*
* @param params - Flag listing configuration
* @param params.project_id - Filter by specific project (recommended)
* @param params.search - Search term for name/description/key matching
* @param params.environment - Filter by specific environment key
* @param params.enabled - Filter by enablement status in specified environment
* @param params.archived - Include/exclude archived flags (default: false)
* @param params.limit - Maximum results to return (default: 100)
* @param params.sort - Sort specification for results
*
* @returns Business result object with formatted flags and metadata
*
* @throws {Error} When cache access fails or data parsing errors occur
*/
listFlags(params?: ListFlagsParams): Promise<{
flags: FormattedFlag[];
total: number;
filters_applied: ListFlagsParams;
}>;
/**
* Retrieves comprehensive details for a specific feature flag
* @param params - Flag identification parameters
* @returns Promise resolving to complete flag details with environment configurations
* @description Business logic for retrieving detailed flag information including
* all environment configurations, related experiments, and complete metadata.
* This method provides the comprehensive flag view needed for detailed analysis.
*
* Business Features:
* - Complete flag metadata and configuration
* - All environment-specific rulesets and enablement status
* - Related experiment discovery and summary
* - Flag variation definitions and targeting rules
* - Graceful handling of missing environment configurations
* - Complete flag lifecycle information
*
* @param params - Flag detail request configuration
* @param params.project_id - Project identifier containing the flag
* @param params.flag_key - Unique flag key identifier
*
* @returns Complete flag details with environment and experiment data
*
* @throws {Error} When flag is not found or data access fails
*/
/**
* @deprecated Use getEntityDetails with entity_type='flag' and enhanced_details=true
*/
getFlagDetails(params: GetFlagDetailsParams): Promise<any>;
private getFlagDetailsEnhanced;
/**
* Compares flag configurations across multiple environments
* @param params - Environment comparison parameters
* @returns Promise resolving to detailed comparison analysis
* @description Advanced business logic for cross-environment flag analysis.
* Identifies configuration differences, environment-specific flags, and
* provides comprehensive comparison metrics for environment management.
*
* Business Features:
* - Multi-environment configuration comparison
* - Automatic difference detection (enablement, rulesets)
* - Environment-only flag identification
* - Comprehensive comparison metrics and summaries
* - Flexible environment selection (specific or all)
* - Detailed difference categorization and reporting
*
* Comparison Analysis:
* - Enablement status differences across environments
* - Ruleset configuration variations
* - Environment-specific flag deployments
* - Missing environment configurations
*
* @param params - Environment comparison configuration
* @param params.project_id - Project for environment comparison
* @param params.flag_key - Specific flag to compare (optional, compares all if omitted)
* @param params.environments - Specific environments to compare (optional)
*
* @returns Detailed comparison results with differences and summary metrics
*
* @throws {Error} When insufficient environments or data access fails
*/
compareEnvironments(params: CompareEnvironmentsParams): Promise<{
environments: string[];
flags: Array<{
key: string;
name: string;
differences: Array<{
field: string;
values: Record<string, any>;
}>;
}>;
summary: {
total_flags: number;
flags_with_differences: number;
environment_only_flags: Record<string, number>;
};
}>;
/**
* Lists experiments with comprehensive filtering and status analysis
* @param params - Experiment listing and filtering parameters
* @returns Promise resolving to formatted experiments with summary statistics
* @description Core business logic for experiment discovery and analysis.
* Provides comprehensive experiment listing with status breakdowns, flag
* associations, and environment-specific filtering capabilities.
*
* MODE PATTERN IMPLEMENTATION:
* This method supports two modes for querying experiments:
* - all_projects: When project_id is omitted or set to "ALL"
* - single_project: When a specific numeric project_id is provided
*
* The MODE pattern addresses LLM confusion about implicit behaviors by making
* the choice explicit in the tool description. Response includes _metadata
* field indicating which mode was used and how many projects were queried.
*
* Business Features:
* - Multi-project query support (NEW: queries all configured projects)
* - Project-specific experiment filtering
* - Status-based filtering (running, paused, archived, etc.)
* - Flag-association filtering for experiment discovery
* - Full-text search across experiment names and descriptions
* - Archive status management
* - Status and environment summary statistics
* - Complete experiment metadata and configuration
*
* @param params - Experiment listing configuration
* @param params.project_id - Filter by specific project or "ALL" for all configured projects
* @param params.status - Filter by experiment status
* @param params.search - Search term for name/description matching
* @param params.flag_key - Filter by associated flag key
* @param params.archived - Include/exclude archived experiments
* @param params.limit - Maximum results to return
*
* @returns Formatted experiments with summary statistics, filter metadata, and mode information
*
* @throws {Error} When data access fails or query execution errors occur
*/
listExperiments(params?: ListExperimentsParams): Promise<{
experiments: FormattedExperiment[];
count: number;
filters: ListExperimentsParams;
summary?: Record<string, any>;
}>;
/**
* Retrieves comprehensive details for a specific experiment
* @param params - Experiment identification and options
* @returns Promise resolving to complete experiment details with optional live results
* @description Business logic for detailed experiment analysis including configuration,
* flag relationships, and optional live results from Optimizely API. Provides
* complete experiment context needed for detailed analysis and optimization.
*
* Business Features:
* - Complete experiment configuration and metadata
* - Associated flag details and relationships
* - Optional live results fetching from Optimizely API
* - Variation and audience configuration analysis
* - Experiment health and configuration summaries
* - Graceful error handling for live data access
*
* Live Results (Optional):
* When include_results=true, attempts to fetch live experiment results
* from Optimizely API. Handles rate limits and API errors gracefully.
*
* @param params - Experiment detail request configuration
* @param params.experiment_id - Unique experiment identifier
* @param params.include_results - Whether to fetch live results (default: false)
*
* @returns Complete experiment details with configuration and optional results
*
* @throws {Error} When experiment is not found or critical data access fails
*/
/**
* @deprecated Use getEntityDetails with entity_type='experiment' and enhanced_details=true
*/
getExperimentDetails(params: GetExperimentDetailsParams): Promise<any>;
private getExperimentDetailsEnhanced;
/**
* COMMENTED OUT: search_all tool is redundant with list_entities functionality
*
* Performs comprehensive search across all Optimizely entities
* @param params - Search parameters and filters
* @returns Promise resolving to ranked search results across all entity types
* @description Advanced business logic for full-text search across flags, experiments,
* and audiences. Implements relevance scoring, result ranking, and comprehensive
* search result aggregation for powerful data discovery.
*
* Business Features:
* - Cross-entity search (flags, experiments, audiences)
* - Intelligent relevance scoring based on match quality and recency
* - Project-specific or global search capabilities
* - Result ranking by relevance and update time
* - Search result categorization and summary statistics
* - Comprehensive entity metadata in results
*
* Relevance Scoring Algorithm:
* - Exact name matches: highest score
* - ID/key matches: high score
* - Partial name matches: medium score
* - Description matches: low score
* - Recent updates: bonus scoring
*
* @param params - Search configuration
* @param params.query - Search query term (required)
* @param params.project_id - Limit search to specific project (optional)
* @param params.limit - Maximum total results to return (default: 50)
*
* @returns Ranked search results with relevance scores and summary metrics
*
* @throws {Error} When search query is empty or data access fails
*/
/**
* COMMENTED OUT: search_all tool is redundant with list_entities functionality
*
* Calculates relevance score for search result ranking
* @param query - Original search query
* @param name - Entity name for scoring
* @param description - Entity description for scoring
* @param entityId - Entity ID/key for scoring
* @param updatedTime - Last update time for recency bonus
* @returns Numeric relevance score for result ranking
* @description Business logic for intelligent search result ranking based on
* match quality, entity relevance, and recency. Implements scoring algorithm
* that prioritizes exact matches, partial matches, and recent updates.
*
* Scoring Algorithm:
* - Exact name match: 100 points
* - Partial name match: 50 points
* - Exact ID match: 80 points
* - ID prefix match: 40 points
* - ID contains match: 20 points
* - Description match: 10 points
* - Recency bonus: 5-15 points based on update time
*
* @param query - Search query for matching
* @param name - Entity name (optional)
* @param description - Entity description (optional)
* @param entityId - Entity identifier (optional)
* @param updatedTime - Last update timestamp (optional)
*
* @returns Relevance score for ranking (higher = more relevant)
* @private
*/
/**
* Retrieves recent change history with filtering and analysis
* @param params - Change history filtering parameters
* @returns Promise resolving to recent changes with activity summaries
* @description Business logic for change tracking and activity analysis.
* Provides insights into recent project activity, change patterns, and
* entity modification history for operational visibility.
*
* Business Features:
* - Time-based change filtering (configurable hours)
* - Project-specific change tracking
* - Entity type filtering (flags, experiments, etc.)
* - Change action categorization
* - Activity pattern analysis and summaries
* - Complete change context and metadata
*
* @param params - Change history request configuration
* @param params.project_id - Filter by specific project (optional)
* @param params.hours - Hours back to search (default: 24)
* @param params.limit - Maximum changes to return (default: 100)
* @param params.target_type - Filter by entity type (optional)
*
* @returns Recent changes with activity summaries and metrics
*
* @throws {Error} When data access fails or query execution errors occur
*/
getRecentChanges(params?: GetRecentChangesParams): Promise<{
changes: ChangeHistoryItem[];
summary: Record<string, any>;
}>;
/**
* Generates comprehensive project analytics and health insights
* @param params - Analytics generation parameters
* @returns Promise resolving to complete project analytics with insights
* @description Advanced business logic for project health analysis and insights
* generation. Provides comprehensive metrics, utilization analysis, and
* actionable insights for project optimization and governance.
*
* Business Features:
* - Complete project overview with entity counts and health scores
* - Environment-specific utilization analysis
* - Top flags by usage and activity metrics
* - 30-day activity trend analysis
* - Intelligent insights generation with actionable recommendations
* - Flag lifecycle and experiment health analysis
*
* Analytics Categories:
* - Project Overview: Entity counts, health scores, utilization metrics
* - Environment Breakdown: Per-environment flag utilization and enablement
* - Usage Analysis: Most active flags, experiment associations
* - Activity Trends: Change patterns over time
* - Insights: Automated recommendations for optimization
*
* @param params - Analytics request configuration
* @param params.project_id - Project for analytics generation (required)
*
* @returns Complete project analytics with insights and recommendations
*
* @throws {Error} When project is not found or analytics computation fails
*/
getAnalytics(params: GetAnalyticsParams): Promise<ProjectAnalytics>;
/**
* Generates actionable insights from project analytics data
* @param analyticsData - Complete project analytics for insight generation
* @returns Array of categorized insights with severity and action recommendations
* @description Business logic for intelligent insight generation based on project
* health metrics, utilization patterns, and best practices. Provides actionable
* recommendations for project optimization, governance, and health improvement.
*
* Insight Categories:
* - Optimization: Flag lifecycle and cleanup recommendations
* - Configuration: Environment consistency and setup issues
* - Experimentation: A/B testing coverage and activity recommendations
* - Governance: Flag management and scale considerations
* - Health: Utilization and activity health indicators
*
* Severity Levels:
* - Critical: Urgent issues requiring immediate attention
* - High: Important issues that should be addressed soon
* - Medium: Recommendations for improvement
* - Low: Informational insights and optimizations
* - Info: General information and best practices
*
* @param analyticsData - Project analytics data for insight analysis
*
* @returns Array of categorized insights with actionable recommendations
* @private
*/
private generateInsights;
/**
* EXPERIMENT RESULTS AND ANALYTICS ENDPOINTS
* Advanced analytics tools for live experiment performance data
*/
/**
* Gets live results data for a specific experiment
* @param params - Parameters for experiment results request
* @returns Promise resolving to experiment results with conversion metrics and statistical analysis
* @description Fetches A/B test experiment results including conversion rates,
* statistical significance, lift metrics, winning variations, and confidence intervals.
* Shows how each variation performed against your conversion goals.
* Handles rate limiting (20 req/min for results endpoints).
*/
getExperimentResults(params: {
experiment_id: string;
start_date?: string;
end_date?: string;
stats_config?: string;
}): Promise<any>;
/**
* Gets live results for multiple experiments efficiently
* @param params - Parameters for bulk experiment results request
* @returns Promise resolving to bulk experiment results
* @description Fetches A/B test results for multiple experiments showing conversion
* metrics, statistical significance, and winning variations across experiments.
* Automatically discovers running experiments if no specific IDs provided.
* Handles rate limiting and provides aggregate A/B test analytics.
*/
getBulkExperimentResults(params: {
project_id: string;
experiment_ids?: string[];
include_paused?: boolean;
start_date?: string;
end_date?: string;
}): Promise<any>;
/**
* Gets campaign results/analytics
* @param params - Parameters for campaign results request
* @returns Promise resolving to campaign results with A/B test metrics and experiment outcomes
* @description Fetches A/B test campaign results showing how experiments within
* the campaign performed, including conversion rates, statistical significance,
* lift metrics, and winning variations across all campaign experiments.
* Handles rate limiting (20 req/min for results endpoints).
*/
getCampaignResults(params: {
campaign_id: string;
start_date?: string;
end_date?: string;
stats_config?: string;
}): Promise<any>;
/**
* Unified method to get A/B test results showing conversion metrics, statistical significance,
* lift percentages, and winning variations for experiments and campaigns.
* Consolidates get_experiment_results, get_campaign_results, and get_bulk_experiment_results.
*
* Results include:
* - Conversion rates for each variation
* - Statistical significance and confidence levels
* - Lift (improvement) over baseline/control
* - Winner/loser determination
* - Visitor counts and distribution
* - Confidence intervals
*
* @param params.result_type - Type of results to fetch: "experiment", "campaign", or "bulk_experiments"
* @param params.experiment_id - ID of experiment (for result_type: "experiment")
* @param params.campaign_id - ID of campaign (for result_type: "campaign")
* @param params.project_id - ID of project (for result_type: "bulk_experiments")
* @param params.experiment_ids - Optional array of experiment IDs to fetch (for bulk)
* @param params.include_paused - Include paused experiments in bulk fetch
* @param params.start_date - Start date for results (YYYY-MM-DD format)
* @param params.end_date - End date for results (YYYY-MM-DD format)
* @param params.stats_config - Optional stats configuration string
*/
getResults(params: {
result_type: 'experiment' | 'campaign' | 'bulk_experiments';
experiment_id?: string;
campaign_id?: string;
project_id?: string;
experiment_ids?: string[];
include_paused?: boolean;
start_date?: string;
end_date?: string;
stats_config?: string;
}): Promise<any>;
/**
* Unified method to get optimization analysis combining analytics data and AI-powered insights.
* Consolidates get_analytics and get_insights for comprehensive project analysis.
*
* Analysis includes:
* - Health scores and metrics (from analytics)
* - AI-powered insights and patterns (from insights)
* - Experiment performance and trends
* - Flag adoption and usage analysis
* - Recommendations for optimization
*
* @param params.analysis_type - Type of analysis: "analytics", "insights", or "comprehensive"
* @param params.project_id - ID of project to analyze
* @param params.include_experiment_results - Include live experiment results (for insights)
* @param params.timeframe_days - Number of days to analyze (for insights)
* @param params.entity_type - Specific entity type to focus on (for insights)
*/
getOptimizationAnalysis(params: {
analysis_type: 'analytics' | 'insights' | 'comprehensive';
project_id: string;
include_experiment_results?: boolean;
timeframe_days?: number;
entity_type?: string;
}): Promise<any>;
/**
* PARAMETRIC TOOL ARCHITECTURE METHODS
* The following methods implement the parametric tool architecture that enables
* scaling from entity-specific tools to unified parametric tools.
*/
/**
* Lists entities of any type using parametric architecture
* @param entityType - Type of entity to list (flag, experiment, audience, etc.)
* @param projectId - Optional project ID for project-scoped entities
* @param filters - Optional filters specific to the entity type
* @returns Promise resolving to array of entities
* @description Unified listing operation for all entity types. This parametric
* approach replaces entity-specific list methods and enables support for new
* entity types without creating new tools.
*/
listEntities(entityType: string, projectId?: string, filters?: Record<string, any>): Promise<any>;
/**
* Checks for platform-specific mismatches and provides educational guidance
* @param projectId - Project ID to check
* @param entityType - Entity type being requested
* @returns Educational response if platform mismatch detected, null otherwise
*/
private checkPlatformMismatch;
/**
* Gets details of a specific entity using parametric architecture
* @param entityType - Type of entity to retrieve
* @param entityId - ID or key of the entity
* @param projectId - Optional project ID for project-scoped entities
* @param options - Optional retrieval options:
* - include_results: Include live results for experiments
* - include_templates: Include model-friendly templates (default: true)
* - enhanced_details: Use specialized formatting for flags/experiments (replaces get_flag_details/get_experiment_details)
* @returns Promise resolving to entity details with optional model-friendly templates
* @description Unified get operation for all entity types. Handles both
* ID-based and key-based entity retrieval based on entity type requirements.
* Now includes model-friendly templates by default for better AI agent experience.
* With enhanced_details=true, provides the same specialized formatting as the deprecated
* get_flag_details and get_experiment_details tools.
*/
getEntityDetails(entityType: string, entityId: string, projectId?: string, options?: Record<string, any>): Promise<any>;
/**
* Manages flag state (enable/disable) in a specific environment
* @param args - Parameters for flag state management
* @returns Promise resolving to operation result
* @description Consolidated tool for enabling or disabling feature flags.
* Replaces the separate enable_flag and disable_flag tools.
*/
manageFlagState(args: {
project_id: string;
flag_key: string;
environment_key: string;
action: 'enable' | 'disable';
}): Promise<any>;
/**
* @deprecated Use manageFlagState with action='enable' instead
*/
enableFlag(args: {
project_id: string;
flag_key: string;
environment_key: string;
}): Promise<any>;
/**
* @deprecated Use manageFlagState with action='disable' instead
*/
disableFlag(args: {
project_id: string;
flag_key: string;
environment_key: string;
}): Promise<any>;
/**
* Manages entity lifecycle operations (create, update, delete, archive)
* @param operation - CRUD operation to perform
* @param entityType - Type of entity to manage
* @param entityData - Entity data for create/update operations
* @param entityId - Entity ID/key for update/delete/archive operations
* @param projectId - Optional project ID for project-scoped entities
* @returns Promise resolving to operation result
* @description Unified lifecycle management for all entity types. Supports-
* create, update, delete, and archive operations through a single interface.
*/
manageEntityLifecycle(operation: 'create' | 'update' | 'delete' | 'archive' | 'enable' | 'disable' | 'history' | 'brainstorm', entityType: string, entityData?: Record<string, any>, entityId?: string, projectId?: string, options?: Record<string, any>, mode?: 'direct' | 'template', templateData?: Record<string, any>): Promise<any>;
/**
* 🎯 **CRITICAL: Entity Relationship Documentation Matrix System**
*
* Returns comprehensive entity documentation matrix that MUST be called first
* before any entity operations. This method implements revolutionary AI-agent-first
* documentation that prevents common entity confusion mistakes.
*
* @returns Comprehensive entity relationship documentation including:
* - 🚨 MANDATORY_ENTITY_RULES_READ_FIRST: Critical checkpoints and decision tree
* - 🚫 ANTI_PATTERNS_DO_NOT_DO: Forbidden response patterns with correct alternatives
* - Variable definitions vs variables distinction documentation
* - Independence levels for all 13+ entities
* - Context requirements (none, project_scoped, flag_scoped, environment_scoped)
* - Complete CRUD operation matrices with examples
* - Usage patterns and AI guidance for each entity
*
* @description **MANDATORY FIRST STEP** - This method prevents AI agents from:
* - Treating entities like variable_definition as nested properties
* - Extracting embedded data instead of using proper entity calls
* - Confusing variable definitions (schema) with variable values (actual data)
* - Making incorrect assumptions about entity independence
*
* **Revolutionary Features:**
* - Anti-pattern detection and prevention
* - Mandatory workflow enforcement
* - Entity independence documentation
* - Critical distinction clarification (variable definitions vs variables)
* - Context-aware error prevention
*
* **Architectural Impact:**
* - Eliminates entity confusion across all AI agents
* - Enforces proper entity operations over embedded data extraction
* - Provides comprehensive entity relationship matrix
* - Prevents common mistakes through proactive guidance
*
* @example Mandatory workflow pattern:
* ```typescript
* // STEP 1: MANDATORY - Get entity rules first
* const entityRules = await getSupportedEntityTypes();
*
* // STEP 2: Follow decision tree for proper entity calls
* if (userAsksForVariableDefinitions) {
* // Use proper entity call (not embedded data extraction)
* const varDefs = await list_entities('variable_definition', projectId, {flag_key: 'flagKey'});
* }
* ```
*/
getSupportedEntityTypes(): Promise<any>;
/**
* Get concise documentation for a specific entity type
* @param entityType - The entity type to get documentation for
* @param aspect - Optional specific aspect to retrieve
* @returns Entity documentation including operations, fields, and examples
*/
getEntityDocumentation(entityType: string, aspect?: 'operations' | 'fields' | 'examples' | 'validation' | 'all'): Promise<any>;
/**
* Get documentation for UPDATE templates of a specific entity type
*/
private getUpdateTemplatesDocumentation;
/**
* Generate a usage example for a template showing the correct format
*/
private generateTemplateUsageExample;
/**
* Get template-specific usage note
*/
private getTemplateUsageNote;
/**
* Get documentation for all UPDATE templates across all entity types
*/
private getAllUpdateTemplatesDocumentation;
/**
* Get comprehensive documentation for analytics views
* @param viewType - The analytics view type requested
* @returns View documentation with field lists and usage examples
* @private
*/
private getAnalyticsViewDocumentation;
/**
* Gets comprehensive insights for a project including experiment results
* @param params - Parameters for insight generation
* @returns Promise resolving to project insights
* @description Provides unified analytics including:
* - Experiment performance metrics
* - Flag adoption and usage patterns
* - Audience targeting effectiveness
* - Recent activity and trends
* - Recommendations for optimization
*/
getInsights(params: {
project_id: string;
include_experiment_results?: boolean;
timeframe_days?: number;
entity_type?: string;
}): Promise<any>;
/**
* Gets AI-powered recommendations for optimization opportunities
* @param params - Parameters for recommendation generation
* @returns Promise resolving to recommendation results
* @description Analyzes project data and generates actionable recommendations for:
* - Experiment optimization
* - Audience targeting improvements
* - Flag configuration best practices
* - Performance enhancements
* - Testing velocity improvements
*/
getRecommendations(params: {
project_id: string;
focus_area?: 'experiments' | 'flags' | 'audiences' | 'performance' | 'all';
include_historical?: boolean;
timeframe_days?: number;
limit?: number;
}): Promise<any>;
/**
* Generates recommendations based on project insights
* @param insights - Project insights data
* @returns Array of recommendations
* @private
*/
private generateInsightRecommendations;
/**
* Gets temporary S3 credentials for exporting Optimizely data
* @param duration - Optional duration in seconds (default: 3600, max: 43200)
* @returns Promise resolving to export credentials and metadata
* @description Retrieves temporary AWS S3 credentials that can be used to
* download exported Optimizely data files directly from S3.
*/
getExportCredentials(duration?: number): Promise<{
credentials: {
access_key_id: string;
secret_access_key: string;
session_token: string;
};
export_details: {
bucket: string;
path: string;
expiration: string;
duration_seconds: number;
};
usage_instructions: string;
}>;
/**
* Gets information about the currently authenticated user
* @returns Promise resolving to current user information
* @description Retrieves details about the user associated with the API token,
* including their email, name, role, and account information.
*/
getCurrentUser(): Promise<{
user: {
id: string;
email: string;
name: string;
created: string;
};
account: {
id: string;
name: string;
created: string;
};
permissions: string[];
}>;
/**
* Lists all collaborators globally across the account
* @param params - Optional filtering and pagination parameters
* @returns Promise resolving to list of collaborators
* @description Retrieves all collaborators at the account level (not project-specific).
* This provides a global view of all users who have access to any projects in the account.
*/
listAllCollaborators(params?: {
page?: number;
per_page?: number;
email?: string;
name?: string;
}): Promise<{
collaborators: Array<{
id: string;
email: string;
name: string;
role: string;
last_seen?: string;
projects_count: number;
}>;
pagination: {
page: number;
per_page: number;
total: number;
total_pages: number;
};
}>;
/**
* Set default configuration for entity creation via chat
* @param configuration - Complete defaults configuration object
* @param saveToFile - Whether to persist to .optimizely/defaults.json
* @returns Success response with applied configuration
* @description Allows users to configure their entity defaults through chat
* without editing files directly. Solves the jQuery 1.11.3 problem by enabling
* users to set modern defaults via natural language interaction.
*/
setDefaultConfiguration(configuration: any, saveToFile?: boolean): Promise<{
success: boolean;
message: string;
file_path?: string;
applied_defaults: any;
note?: string;
}>;
/**
* Get current default configuration for entity creation
* @param entityType - Specific entity type or "all" for complete configuration
* @param includeExamples - Include example configurations
* @returns Current defaults configuration and metadata
* @description Shows users their current default configuration and provides
* examples for different team scenarios (modern, legacy, agency).
*/
getDefaultConfiguration(entityType?: string, includeExamples