@simonecoelhosfo/optimizely-mcp-server
Version:
Optimizely MCP Server for AI assistants with integrated CLI tools
1,269 lines (1,084 loc) β’ 87.6 kB
Markdown
# Optimizely MCP Agent Ruleset β v4.1 Enhanced β’ 2025-01-30
## π― CRITICAL: Master Tool Reference - `get_tool_reference`
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π§ PRIMARY TOOL DISCOVERY: get_tool_reference β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β β¨ THE SINGLE SOURCE OF TRUTH for all MCP tools: β
β β’ Complete parameter documentation (required vs optional) β
β β’ Exact return structures for every operation β
β β’ Real-world usage patterns and examples β
β β’ Critical safety warnings and best practices β
β β
β π― OPERATIONS: β
β β’ list - Overview of all 30 MCP tools with categories β
β β’ details - Deep dive into any specific tool β
β β’ search - Find tools by capability β
β β’ matrix - Decision guide for tool selection β
β β
β π‘ WHEN TO USE: β
β β’ BEFORE implementing any tool call β
β β’ When uncertain about parameters β
β β’ To understand response structures β
β β’ For best practices and safety guidelines β
β β
β π EXAMPLE USAGE: β
β {"operation": "details", "tool_name": "manage_entity_lifecycle"} β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### **Why `get_tool_reference` is Essential**
**Parameters First**: Shows ALL required/optional parameters with exact types and when each is needed
**Response Clarity**: Actual response structures for success, errors, and edge cases
**Safety Built-in**: Explicit warnings about operations requiring consent
**Auto-Orchestration**: Explains when template mode triggers and what gets auto-created
**USE THIS TOOL** instead of guessing parameters or relying on outdated documentation!
## π¨ CRITICAL CACHE SAFETY PROTOCOL π¨
### **β ABSOLUTE PROHIBITION: CACHE RESET WITHOUT CONSENT β**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π¨ CRITICAL RULE: NEVER RESET CACHE WITHOUT EXPLICIT CONSENT π¨ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β β FORBIDDEN OPERATIONS (without user consent): β
β β’ manage_cache(operation="refresh", options={force: true}) β
β β’ manage_cache(operation="initialize") β
β β’ manage_cache(operation="clear") β
β β
β β
ALLOWED OPERATIONS (no consent needed): β
β β’ manage_cache(operation="refresh") [incremental sync only] β
β β’ get_system_status() [with diagnostics] β
β β
β π‘οΈ CONSENT REQUIREMENT: β
β Before ANY cache reset/clear operation, you MUST: β
β 1. Explain what data will be lost β
β 2. Explain the time to rebuild (minutes/hours) β
β 3. Ask for EXPLICIT user confirmation β
β 4. Wait for clear YES/NO response β
β β
β πΎ DATA PROTECTION RATIONALE: β
β β’ Cache contains hours of synced data β
β β’ Rebuild takes 5-30 minutes depending on project size β
β β’ Loss of incremental sync history β
β β’ Potential API rate limiting during rebuild β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### **Cache Operation Decision Matrix**
| Operation | Consent Required | Explanation Required | Safe to Auto-Execute |
|-----------|------------------|---------------------|---------------------|
| `manage_cache(operation="refresh")` | β NO | β NO | β
YES - Incremental only |
| `manage_cache(operation="refresh", options={force: true})` | π¨ **YES** | π¨ **YES** | β **NO** - Full rebuild |
| `manage_cache(operation="initialize")` | π¨ **YES** | π¨ **YES** | β **NO** - Complete wipe |
| `manage_cache(operation="clear")` | π¨ **YES** | π¨ **YES** | β **NO** - Data loss |
| `get_system_status()` | β NO | β NO | β
YES - Read-only |
### **Consent Template for Cache Reset**
```
π¨ CACHE RESET CONFIRMATION REQUIRED π¨
The operation you've requested will:
β’ Delete all cached Optimizely data (X projects, Y entities)
β’ Require a complete rebuild taking 15-30 minutes
β’ Temporarily lose incremental sync capabilities
β’ May trigger API rate limits during rebuild
This will affect your ability to query data until rebuild completes.
Do you want to proceed with the cache reset?
β’ YES - Proceed with cache reset
β’ NO - Cancel operation
Please confirm your choice.
```
---
## π¨ CRITICAL PLATFORM VALIDATION RULES π¨
### **β οΈ PROJECT CREATION PLATFORM VALUES - EXACT REQUIREMENTS β οΈ**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π¨ CRITICAL: Project creation platform field validation error β
β Error: Invalid value "feature_experimentation" for 'platform' β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β β
VALID PLATFORM VALUES (for PROJECT creation): β
β β’ "web" - Web Experimentation projects β
β β’ "custom" - Feature Experimentation projects β
β β’ "ios" - iOS projects (DEPRECATED - avoid using) β
β β’ "android" - Android projects (DEPRECATED - avoid using) β
β β
β β INVALID VALUES (cause "Invalid value" validation error): β
β β’ "feature_experimentation" β MAIN ISSUE β
β β’ "feature" β WRONG β
β β’ "web_experimentation" β WRONG β
β β’ "Web" β Wrong case β
β β’ "Custom" β Wrong case β
β β
β π― PROJECT CREATION MAPPING: β
β Create Feature Experimentation Project β platform: "custom" β
β Create Web Experimentation Project β platform: "web" β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### **Project Creation Platform Decision Matrix**
| Project Type | Correct Platform Value | β Common Mistakes | Validation Error |
|--------------|----------------------|-------------------|------------------|
| **Feature Experimentation Project** | `"custom"` | `"feature_experimentation"`, `"feature"` | "Invalid value 'feature_experimentation'" |
| **Web Experimentation Project** | `"web"` | `"web_experimentation"`, `"Web"` | "Invalid value 'web_experimentation'" |
| **Mobile Projects (Legacy)** | `"ios"`, `"android"` | `"mobile"`, `"iOS"`, `"Android"` | Case-sensitive validation |
### **Template Recommendations for Project Creation**
- **ALWAYS** call `get_entity_templates(entity_type="project")` before project creation
- Project templates contain the correct platform values pre-filled
- **NEVER** guess platform values from project type descriptions
- **NEVER** use "feature_experimentation" - this WILL cause validation errors
---
## π v4.0 ENHANCEMENTS: TOOL DESCRIPTION IMPROVEMENTS
### **π― NEW: Tool Description Audit Implementation Rules**
Based on comprehensive tool analysis, critical improvements identified:
#### **Tool Accuracy Rules (NEW)**
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π¨ CRITICAL: Tool descriptions must match actual functionality β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β β DEPRECATED FUNCTIONALITY TO AVOID: β
β β’ export_data "natural language query" - NO LONGER WORKS β
β β’ analyze_data "CALL THIS THIRD" - outdated workflow β
β β’ Any reference to get_insights/get_analytics separately β
β β
β β
CORRECT CURRENT FUNCTIONALITY: β
β β’ export_data: entity_type OR structured_query only β
β β’ analyze_data: structured_query REQUIRED β
β β’ get_optimization_analysis: replaces insights+analytics β
β β
β π― ENHANCED TOOL UNDERSTANDING: β
β β’ manage_entity_lifecycle: AUTO-ORCHESTRATES dependencies β
β β’ get_entity_templates: PRIMARY educational tool β
β β’ validate_template: Direct Template format validation β
β β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
#### **Enhanced Tool Selection Matrix (v4.0)**
| Tool | Purpose | When to Use | What Changed in v4.0 |
|------|---------|-------------|---------------------|
| **export_data** | π Data export to files | Entity lists or analytics exports | β NO natural language queries |
| **analyze_data** | π Analytics queries | Structured data analysis | β NOT "third" in sequence |
| **manage_entity_lifecycle** | π― Entity operations | ANY entity create/update/delete | β
AUTO-ORCHESTRATION emphasized |
| **get_entity_templates** | π Learning & discovery | BEFORE any complex entity creation | β
EDUCATIONAL PURPOSE highlighted |
| **get_optimization_analysis** | π― Performance analysis | Project health & insights | β
REPLACES get_insights/get_analytics |
| **validate_template** | π Template validation | Before orchestration execution | β
Direct Template format only |
### **Tool Description Reading Protocol (NEW)**
```python
def READ_TOOL_DESCRIPTION_V4(tool_name):
"""Enhanced tool description interpretation for v4.0"""
# 1. LOOK FOR VISUAL MARKERS (emojis guide understanding)
if description.startswith('π―'): # Universal controller/primary tool
priority = 'HIGH'
elif description.startswith('π'): # Analytics/data tool
check_for_structured_query_requirement()
elif description.startswith('π'): # Educational tool
call_before_complex_operations()
# 2. CHECK FOR CAPS SIGNALS (unchanged from v3)
if 'DEPRECATED' in description:
DO_NOT_USE_that_feature()
if 'AUTO-ORCHESTRATION' in description:
expect_template_mode_detection()
if 'ALWAYS' in description:
mandatory_behavior()
# 3. NEW: VERIFY FUNCTIONALITY CLAIMS
if tool_name == 'export_data' and 'natural language' in args:
ERROR: functionality removed, use entity_type instead
if tool_name == 'analyze_data' and not args.structured_query:
ERROR: structured_query required, natural language not supported
return enhanced_understanding
```
---
### β‘ Quick Codes (ENHANCED FOR v4.0)
`CRQ` = Consent Required | `PLM` = Platform Mismatch | `HSE` = HardStopError
`FSH` = Fresh Call | `RSD` = Reuse Data | `SQY` = structured_query
`DOC` = get_entity_documentation | `TPL` = get_entity_templates | `FDOC` = Field Documentation
`OPT` = get_optimization_analysis | `RST` = get_results | `SEC` = security_analysis
`OAR` = get_openapi_reference (REST API) | `SDK` = get_optimizely_api_reference (SDKs)
`ORCH` = orchestration tools | `MGT` = manage_cache | `SYS` = get_system_status
**NEW v4.0 Codes:**
`AUTO` = auto-orchestration detected | `DEPR` = deprecated functionality | `EDU` = educational tool
---
## π§ LAYER 0 β PRE-FLIGHT MENTAL MODEL (~200 tokens)
### The Three Gates Every Operation Must Pass
```
βββββββββββββββ ββββββββββββββββ βββββββββββββββ
β 1. CONSENT β --> β 2. DISCOVERY β --> β 3. PLATFORM β
β GATE β β GATE β β GATE β
βββββββββββββββ ββββββββββββββββ βββββββββββββββ
β β β
Check limits Get fields/ Check entity
& triggers templates FIRST compatibility
```
### **π v4.0 ENHANCED: Four Gates System**
```
βββββββββββββββ ββββββββββββββββ βββββββββββββββ βββββββββββββββ
β 1. CONSENT β --> β 2. DISCOVERY β --> β 3. PLATFORM β --> β 4. ACCURACY β
β GATE β β GATE β β GATE β β GATE β
βββββββββββββββ ββββββββββββββββ βββββββββββββββ βββββββββββββββ
β β β β
Check limits Get fields/ Check entity Verify tool
& triggers templates FIRST compatibility descriptions
```
### π« MANDATORY PRE-OPERATION CHECKLISTS
#### Before ANY Analytics Query:
```
β‘ Call DOC: get_entity_documentation(entity_type="[view_name]")
β‘ Read returned field list β Note EXACT field names
β‘ Build SQY using ONLY documented fields
β‘ NEVER guess field names (causes FieldNotFoundError)
β‘ π v4.0: Verify structured_query is used, NOT natural language
```
#### Before ANY Entity Creation:
```
β‘ Call TPL: get_entity_templates(entity_type="[type]", complexity=2)
β‘ Receive complete JSON structure with defaults
β‘ Fill ONLY user-specified fields
β‘ VERIFY platform field: "custom" for Feature, "web" for Web
β‘ NEVER use "feature_experimentation" - always use "custom"
β‘ NEVER create from memory (causes validation errors)
β‘ π v4.0: EXPECT auto-orchestration for complex entities
```
#### π v4.0: Before ANY Export Operation:
```
β‘ Check if simple entity export β use entity_type parameter
β‘ Check if complex filtered export β use structured_query
β‘ NEVER use "query" parameter for natural language (removed)
β‘ Verify format is appropriate for data structure
```
#### Before ANY List/Get Operation:
```
β‘ Know the platform type (call list_projects if unknown)
β‘ Check entity compatibility in matrix below
β‘ Use correct entity type for platform
β‘ NEVER assume from project name
```
### π Field Discovery Pattern (MEMORIZE THIS)
```json
// β WRONG WAY (WILL FAIL):
{"structured_query": {"from": "flags_unified_view",
"select": ["flag_id", "is_enabled"]}} // Field names guessed
// β
RIGHT WAY (WILL SUCCEED):
// Step 1: ALWAYS discover first
{"name": "get_entity_documentation",
"arguments": {"entity_type": "flags_unified_view"}}
// Returns: flag_key, flag_name, enabled, environment_key, simple_status...
// Step 2: Use EXACT field names from response
{"structured_query": {"from": "flags_unified_view",
"select": ["flag_key", "enabled", "simple_status"]}}
```
---
## LAYER A β Runtime Core (~1200 tokens)
### 0 Β· Quick Codes (EXPANDED)
`CRQ` = Consent Required | `PLM` = Platform Mismatch | `HSE` = HardStopError
`FSH` = Fresh Call | `RSD` = Reuse Data | `SQY` = structured_query
`DOC` = get_entity_documentation (REQUIRED before queries)
`TPL` = get_entity_templates (REQUIRED before creation)
`OPT` = get_optimization_analysis | `RST` = get_results | `SEC` = security_analysis
### 1 Β· Absolute Prohibitions (ENHANCED v4.0)
* **NEVER**: Retry same call, guess platform from history, use plain `query`, skip `CRQ`, paraphrase OpenAPI
* **NEVER**: Skip DOC before analytics queries (causes field errors)
* **NEVER**: Skip TPL before entity creation (causes validation errors)
* **NEVER**: Guess field names from memory (they change between views)
* **NEVER**: Assume field exists without checking DOC first
* **NEVER**: Confuse API documentation tools (see section 1.5 below)
* **π¨ NEVER**: Reset cache without explicit user consent (`manage_cache` with force/initialize/clear)
* **π¨ NEVER**: Clear cached data without explaining data loss and rebuild time to user
* **π¨ NEVER**: Use "feature_experimentation" as platform value (use "custom" instead)
* **π¨ NEVER**: Guess platform values - always use templates or exact API values
* **π¨ NEVER**: Reference deprecated tools (enable_flag, get_insights, get_analytics, refresh_cache, etc.)
* **π v4.0 NEVER**: Use natural language queries with export_data (functionality removed)
* **π v4.0 NEVER**: Skip auto-orchestration when manage_entity_lifecycle suggests template mode
* **π v4.0 NEVER**: Create child entities separately when parent entity will auto-create them
## π¨ MANDATORY CONSENT CHECKPOINT π¨
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β BEFORE ANY ACTION: Check ALL conditions below β
β IF ANY = TRUE (not just present) β FULL STOP β CONSENT REQ β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β‘ pagination.total_count > 50 β
β β‘ pagination.has_more === true (NOT false) β
β β‘ pagination.consent_required === true (NOT false) β
β β‘ error_type === "HardStopError" β
β β‘ message contains "STOP:" or "Ask the user:" β
β β‘ user_consent_required === true β
β π β‘ status === "HARD_STOP_REQUIRED" (template mode) β
β π β‘ required_action.type === "GET_TEMPLATE" β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
### β CHECK FOR TRUE, NOT JUST PRESENCE β
---
## LAYER A β Runtime Core
### 1.5 Β· API DOCUMENTATION TOOLS - CRITICAL DISTINCTION β οΈ
**NEVER CONFUSE THESE TWO DIFFERENT TOOLS:**
#### `get_openapi_reference` - REST API Documentation
- **Purpose**: Optimizely REST API endpoint documentation
- **Use for**: HTTP endpoints, request/response formats, authentication
- **Example queries**:
- "What's the REST API endpoint to create an experiment?"
- "Show me the API request format for updating a flag"
- "What fields can I use in the REST API?"
#### `get_optimizely_api_reference` - SDK & Platform Documentation
- **Purpose**: SDK methods, platform guides, implementation details
- **Use for**: JavaScript SDK, Python SDK, Web Experimentation platform, Optimizely Agent
- **Enhanced Search**: Uses intelligent natural language processing
##### PRACTICAL EXAMPLES - get_optimizely_api_reference
**1. Natural Language Search (RECOMMENDED)**
```json
{
"entity_type": "search",
"search_query": "how to track custom events",
"information_type": "general"
}
// Returns methods from all SDKs that track events
```
**2. Web Experimentation - Getting Active Campaigns**
```json
{
"entity_type": "search",
"search_query": "get active campaigns visitor state",
"information_type": "general"
}
// Finds: window.optimizely.get('state').getActiveCampaigns()
```
**3. Specific Method Documentation**
```json
{
"entity_type": "method",
"product_type": "web_experimentation",
"method_name": "window.optimizely.get",
"information_type": "details"
}
// Returns full documentation with examples
```
**4. Browse All Available Methods**
```json
{
"entity_type": "overview",
"information_type": "all_methods"
}
// Lists every method across all SDKs
```
**5. SDK-Specific Information**
```json
{
"entity_type": "sdk",
"sdk_name": "javascript",
"information_type": "methods"
}
// Returns JavaScript SDK methods
// For Web Experimentation platform:
{
"entity_type": "platform",
"platform": "web_experimentation",
"information_type": "all"
}
// Returns complete Web Experimentation documentation
```
##### IMPORTANT: Entity Type Clarification
**π¨ CRITICAL**: Don't confuse `platform` vs `sdk` entity types:
- `entity_type: "sdk"` β For SDK documentation (JavaScript, Python, Java, etc.)
- `entity_type: "platform"` β ONLY for Web Experimentation or Optimizely Agent
**Common Mistake to Avoid:**
```json
// β WRONG - JavaScript is an SDK, not a platform
{
"entity_type": "platform",
"product_type": "javascript",
"information_type": "methods"
}
// β
CORRECT - Use sdk for JavaScript
{
"entity_type": "sdk",
"sdk_name": "javascript",
"information_type": "methods"
}
```
##### SEARCH TIPS FOR API REFERENCE
- **Use key terms**: "visitor id", "track event", "active", "state"
- **Web Experimentation methods**: Use full names like "window.optimizely.get"
- **Push commands**: Use format "push:event", "push:page"
- **Natural questions work**: "how to get visitor id", "activate page"
- **Related terms understood**: "user" finds "visitor", "track" finds "event"
**CRITICAL RULE**: When user mentions "API", determine WHICH API:
- REST API endpoints β use `get_openapi_reference`
- SDK/platform methods β use `get_optimizely_api_reference`
- When unclear β ask user to clarify
### 1 Β· CONSENT GATE (ABSOLUTE PRIORITY #1)
#### π The Consent Firewall (CORRECTED)
```python
def CHECK_CONSENT_FIRST(response):
"""RUN THIS BEFORE PROCESSING ANY RESPONSE"""
# Check pagination object if it exists
if hasattr(response, 'pagination'):
p = response.pagination
# EXPLICIT TRUE CHECKS
if p.total_count > 50:
return "HALT_FOR_CONSENT: Large dataset"
if p.has_more === True: # Must be explicitly True
return "HALT_FOR_CONSENT: More pages available"
if p.consent_required === True: # Must be explicitly True
return "HALT_FOR_CONSENT: Consent explicitly required"
# v4.0 NEW: Check for template mode hard stops
if response.status == "HARD_STOP_REQUIRED":
return "HALT_FOR_TEMPLATE: Template mode required"
if hasattr(response, 'required_action'):
if response.required_action.type == "GET_TEMPLATE":
return "HALT_FOR_TEMPLATE: Must get template first"
# Check error conditions
if response.error_type == "HardStopError":
return "HALT_FOR_CONSENT: HardStopError"
if "STOP:" in str(response.message) or "Ask the user:" in str(response.message):
return "HALT_FOR_CONSENT: Stop keyword found"
if hasattr(response, 'user_consent_required') and response.user_consent_required === True:
return "HALT_FOR_CONSENT: User consent required"
return "PROCEED"
```
#### Examples: Consent Check Responses
```json
// β
PROCEED - All checks pass
{
"pagination": {
"consent_required": false, // FALSE = OK
"has_more": false, // FALSE = OK
"total_count": 0 // β€50 = OK
}
}
// π HALT - Multiple triggers
{
"pagination": {
"consent_required": true, // TRUE = HALT
"has_more": true, // TRUE = HALT
"total_count": 247 // >50 = HALT
}
}
```
#### π v4.0: Template Mode Hard Stop Example
```json
{
"status": "HARD_STOP_REQUIRED",
"error": {
"code": 409,
"type": "COMPLEX_ENTITY_DEPENDENCIES",
"message": "MANDATORY: Use template mode. DO NOT create pages separately.",
"fatal": true
},
"required_action": {
"type": "GET_TEMPLATE",
"tool": "get_entity_templates",
"params": {"project_id": "12345", "entity_type": "experiment"},
"forbidden_actions": ["create_child_page", "create_child_event"]
}
}
```
**Result**: HALT FOR TEMPLATE (must follow required_action exactly)
### 1.5 Β· DISCOVERY GATE (CRITICAL - BEFORE PLATFORM CHECK)
#### π The Discovery Firewall (ENHANCED v4.0)
```python
def CHECK_DISCOVERY_FIRST(operation_type, entity_or_view):
"""RUN THIS BEFORE ANY DATA OPERATION"""
if operation_type == "ANALYTICS_QUERY":
# MUST get field documentation first
fields = get_entity_documentation(entity_type=entity_or_view)
return fields.available_fields
elif operation_type == "ENTITY_CREATION":
# MUST get template first
template = get_entity_templates(entity_type=entity_or_view, complexity=2)
return template.structure
elif operation_type == "EXPORT_DATA":
# v4.0 NEW: Check export mode
if is_simple_entity_export():
return "USE_ENTITY_TYPE_PARAMETER"
else:
return "USE_STRUCTURED_QUERY_PARAMETER"
elif operation_type == "FIELD_ERROR":
# Recovery path - get documentation
return "MUST_CALL_DOC_FIRST"
```
### 2 Β· Consent Logic Truth Table
| Field | Value | Action |
|-------|-------|--------|
| `consent_required` | `true` | π HALT |
| `consent_required` | `false` | β
Continue |
| `consent_required` | `null`/missing | β
Continue |
| `has_more` | `true` | π HALT |
| `has_more` | `false` | β
Continue |
| `has_more` | `null`/missing | β
Continue |
| `total_count` | `> 50` | π HALT |
| `total_count` | `β€ 50` | β
Continue |
| `total_count` | `0` | β
Continue |
| **π v4.0** `status` | `"HARD_STOP_REQUIRED"` | π HALT |
| **π v4.0** `required_action.type` | `"GET_TEMPLATE"` | π HALT |
### 3 Β· Decision Flow WITH Discovery & Explicit Checks (ENHANCED v4.0)
```
Response Received
β
βΌ
βββββββββββββββββββββββββββββββ
β Need to query analytics? β β NEW DISCOVERY CHECK
βββββββββββββββ¬ββββββββββββββββ
Yesβ βNo
β βΌ
β βββββββββββββββββββββββββββββββ
βΌ β Is consent_required === true?β β EXPLICIT TRUE CHECK
ββββββββββββββββ βββββββββββββββ¬ββββββββββββββββ
β CALL DOC β Yesβ βNo
β FIRST! β β βΌ
ββββββββββββββββ β ββββββββββββββββββββββββββ
β β Is has_more === true? β β EXPLICIT TRUE CHECK
β ββββββββββββ¬ββββββββββββββ
β Yesβ βNo
β β βΌ
β β βββββββββββββββββββββ
β β β Is total_count>50?β
β β βββββββββββ¬ββββββββββ
β β Yesβ βNo
β β β βΌ
β β β βββββββββββββββββββ
β β β β HARD_STOP check?β β v4.0 NEW
β β β βββββββββββ¬ββββββββ
β β β Yesβ βNo
βΌ βΌ βΌ βΌ βΌ
ββββββββββββββββββ βββββββββββ
β HALT & PROMPT β β PROCEED β
ββββββββββββββββββ βββββββββββ
```
---
## LAYER B β Complete Reference (ENHANCED)
<details><summary>π¨ Β§B.1 Consent Examples & Edge Cases π¨</summary>
### Case 1: Empty Results (No Consent Needed)
```json
{
"result": "success",
"entities": [],
"pagination": {
"consent_required": false,
"has_more": false,
"total_count": 0,
"current_page": 1,
"page_size": 25
}
}
```
**Action**: PROCEED - Display "No items found"
### Case 2: Exactly 50 Items (No Consent)
```json
{
"pagination": {
"consent_required": false,
"has_more": false,
"total_count": 50, // Exactly 50 is OK
"current_page": 1,
"page_size": 50
}
}
```
**Action**: PROCEED - 50 is the threshold, not a trigger
### Case 3: 51 Items (Consent Required)
```json
{
"pagination": {
"consent_required": false, // Even if false...
"has_more": false,
"total_count": 51, // ...this triggers consent!
"current_page": 1,
"page_size": 50
}
}
```
**Action**: HALT - total_count > 50 overrides other fields
### Case 4: Explicit Consent Flag
```json
{
"pagination": {
"consent_required": true, // Explicit flag
"has_more": false,
"total_count": 10, // Even with few items
"current_page": 1,
"page_size": 25
}
}
```
**Action**: HALT - consent_required=true is absolute
### Case 5: Has More Pages
```json
{
"pagination": {
"consent_required": false,
"has_more": true, // More data available
"total_count": 200,
"current_page": 1,
"page_size": 25
}
}
```
**Action**: HALT - has_more=true requires consent
### π v4.0 Case 6: Template Mode Hard Stop
```json
{
"status": "HARD_STOP_REQUIRED",
"error": {
"code": 409,
"type": "COMPLEX_ENTITY_DEPENDENCIES",
"message": "MANDATORY: Use template mode.",
"fatal": true
},
"required_action": {
"type": "GET_TEMPLATE",
"tool": "get_entity_templates",
"params": {"entity_type": "experiment"},
"forbidden_actions": ["create_child_page"]
}
}
```
**Action**: HALT - Must follow required_action exactly, respect forbidden_actions
</details>
<details><summary>Β§B.2 Consent Handling Pseudocode (WITH DISCOVERY)</summary>
```python
def handle_api_response(response):
# Step 0: DISCOVERY CHECK (NEW!)
if needs_field_discovery(response):
doc_response = get_entity_documentation(entity_type=view_name)
# Now we have valid fields to work with
# Step 1: ALWAYS check consent first
consent_check = CHECK_CONSENT_FIRST(response)
if consent_check != "PROCEED":
# Extract the reason
reason = consent_check.split(": ")[1]
# v4.0 NEW: Handle template mode stops differently
if consent_check.startswith("HALT_FOR_TEMPLATE"):
print(f"""
π― TEMPLATE MODE REQUIRED π―
βββββββββββββββββββββββββββββββββ
Complex entity detected! Auto-orchestration required.
Required Action: {response.required_action.tool}
Parameters: {response.required_action.params}
FORBIDDEN Actions: {response.forbidden_actions}
βββββββββββββββββββββββββββββββββ
""")
# MUST follow required_action exactly
return call_required_action(response.required_action)
# Show consent prompt
print(f"""
π CONSENT REQUIRED π
βββββββββββββββββββββ
Reason: {reason}
Total items: {response.pagination.total_count}
Current page size: {response.pagination.page_size}
Do you want to:
β’ YES - Fetch all data
β’ NO - Use current page only
βββββββββββββββββββββ
""")
# WAIT for user input
user_choice = wait_for_user_input()
if user_choice == "YES":
return fetch_all_pages()
else:
return use_current_page_only(response)
# Step 2: Only process if consent cleared
return process_response(response)
```
</details>
<details><summary>Β§B.2.1 Discovery Examples & Patterns (ENHANCED v4.0)</summary>
### Analytics Query Discovery Pattern
```yaml
User Request: "Show me all flags with custom targeting"
Agent Process:
1. Identify need: flags + custom targeting = analytics query
2. DOC FIRST: get_entity_documentation(entity_type="flags_unified_view")
3. Discover: has_audience_targeting field exists
4. Build query: {"from": "flags_unified_view", "where": {"has_audience_targeting": true}}
5. Success!
Without DOC:
- Guess field name: "custom_targeting" β FieldNotFoundError
- Retry with: "has_custom_targeting" β FieldNotFoundError
- Frustration increases!
```
### Creation Pattern with Templates
```yaml
User Request: "Create a new flag called checkout_v2"
Agent Process:
1. TPL FIRST: get_entity_templates(entity_type="flag", complexity=2)
2. Receive: Complete structure with all fields
3. Modify: Only name and key
4. Create: All other fields have valid defaults
5. Success!
Without TPL:
- Missing required fields β ValidationError
- Wrong field formats β TypeError
- Invalid defaults β CreationFailure
```
### π v4.0: Export Discovery Pattern
```yaml
User Request: "Export all flags to CSV"
Agent Process:
1. ANALYZE REQUEST: Simple entity export detected
2. CHOOSE CORRECT MODE: entity_type parameter
3. AVOID WRONG MODE: Do not use "query" parameter (deprecated)
4. Execute: {"entity_type": "flag", "format": "csv"}
5. Success!
Wrong Approach:
- Use "query": "show all flags" β Error: Natural language not supported
- Retry attempts β Confusion
- Agent learns correct pattern
```
### π v4.0: Auto-Orchestration Pattern
```yaml
User Request: "Create experiment with homepage test"
Agent Process:
1. START: manage_entity_lifecycle(create, experiment, data_with_pages)
2. RESPONSE: HARD_STOP_REQUIRED with template requirement
3. FOLLOW: required_action.tool = "get_entity_templates"
4. RESPECT: forbidden_actions = ["create_child_page"]
5. Template mode: Auto-creates experiment + pages together
6. Success!
Wrong Approach:
- Create page first β Conflicts with orchestration
- Ignore HARD_STOP β Create dependency issues
- Manual coordination β Race conditions
```
### π― CRITICAL: When to Use `orchestrate_template` vs `manage_entity_lifecycle`
```
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
β π§ TOOL SELECTION GUIDE: Orchestration vs Entity Lifecycle β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ€
β β
β π USE `manage_entity_lifecycle` WHEN: β
β β’ Creating/updating/deleting SINGLE entities β
β β’ Entity has dependencies (auto-orchestration will trigger) β
β β’ You receive a template from get_entity_templates β
β β’ System returns HARD_STOP_REQUIRED (follow guidance) β
β β
β π USE `orchestrate_template` WHEN: β
β β’ Executing SAVED orchestration templates β
β β’ Running multi-step workflows from template library β
β β’ User provides a template_id to execute β
β β’ Implementing complex patterns (e.g., Hilly Stafford) β
β β
β π¨ KEY DIFFERENCE: β
β manage_entity_lifecycle: For entity CRUD operations β
β orchestrate_template: For executing WORKFLOW templates β
β β
β π‘ TEMPLATE MODE vs ORCHESTRATION: β
β β’ Template Mode: Part of manage_entity_lifecycle β
β β’ Orchestration: Separate workflow execution system β
β β’ Both use templates, different purposes! β
βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
```
#### Decision Flow:
```
User wants to create entity?
ββ Single entity β manage_entity_lifecycle
β ββ Simple β Direct creation
β ββ Complex β Auto-triggers template mode
ββ Multi-entity workflow β orchestrate_template
ββ Has template_id β Execute it
ββ Needs template β Use manage_orchestration_templates
```
### Field Not Found Recovery
```json
// Error without DOC:
{
"result": "error",
"message": "Field not found in view",
"error_type": "FieldNotFoundError",
"available_fields": ["flag_key", "flag_name", "enabled", ...],
"next_steps": {
"option_1": "Choose a field from available_fields",
"option_2": "Use get_entity_documentation to explore other views",
"option_3": "Try these views that might have 'custom_attribute_name': audiences_flat"
},
"suggested_views": ["audiences_flat"],
"hint": "Custom attribute data is in 'audiences_flat' view, not in flags views"
}
```
</details>
<details><summary>Β§B.3 Complete EntityΓPlatformΓTools Matrix (ENHANCED v4.0)</summary>
| Entity | Icon | Web | Feature | Primary Tools | Secondary Tools | **DISCOVERY REQUIRED** | **v4.0 Notes** |
|--------|------|-----|---------|---------------|-----------------|------------------------|-----------------|
| project | π’ | β
| β
| list_entities, get_entity_details | get_project_data, get_optimization_analysis | - | Platform: "web"/"custom" |
| audience | π― | β
| β
| list_entities, get_entity_details | manage_entity_lifecycle | TPL for creation | Auto-orchestration |
| event | π | β
| β
| list_entities, get_entity_details | manage_entity_lifecycle | TPL for creation | Auto-orchestration |
| environment | π | β
| β
| list_entities, get_entity_details | compare_environments | - | - |
| variation | π² | β
| β
| list_entities, get_entity_details | get_entity_templates | TPL required | Template mode |
| experiment | π§ͺ | β
| β | list_entities, get_entity_details | get_results | TPL for creation | Complex orchestration |
| campaign | π | β
| β | list_entities, get_entity_details | get_results | TPL for creation | With pages/events |
| page | π | β
| β | list_entities, get_entity_details | get_entity_templates | TPL for creation | Auto-created |
| extension | π | β
| β | list_entities, get_entity_details | get_entity_documentation | DOC for fields | - |
| flag | π© | β | β
| list_entities, get_entity_details | manage_flag_state, get_flag_history | TPL for creation | A/B test orchestration |
| rule | π | β | β
| list_entities, get_entity_details | update_ruleset | DOC for structure | Complex dependencies |
| ruleset | π | β | β
| list_entities, get_entity_details | update_ruleset | DOC for structure | Traffic allocation |
| variable_definition | π§ | β | β
| list_entities, get_entity_details | get_entity_templates | TPL required | Flag dependencies |
**Critical**: Feature platform "experiments" β use `ruleset` with `type='a/b_test'`
**NEW v4.0**: Discovery column shows when DOC/TPL is mandatory
**NEW v4.0**: Auto-orchestration noted for complex entities
</details>
<details><summary>Β§B.4 All Analytics Views (18 required) - ENHANCED WITH DISCOVERY</summary>
| ID | View Name | Purpose | Key Use Case | **MUST CALL DOC FIRST** | **v4.0 structured_query** |
|----|-----------|---------|--------------|-------------------------|---------------------------|
| V01 | `flags_unified_view` | Flag management (27 fields) | Status, rollout%, environments | β
YES - get_entity_documentation | β
REQUIRED |
| V02 | `flag_variations_flat` | Variation configs | JSON variable storage | β
YES - get_entity_documentation | β
REQUIRED |
| V03 | `flag_variation_variables` | **Variable search** | ONE ROW per variable value | β
YES - get_entity_documentation | β
REQUIRED |
| V04 | `flag_variables_summary` | Variable usage stats | Counts/types by flag | β
YES - get_entity_documentation | β
REQUIRED |
| V05 | `flag_state_history_view` | Enable/disable timeline | Historical tracking | β
YES - get_entity_documentation | β
REQUIRED |
| V06 | `experiments_unified_view` | Cross-platform tests (29 fields) | Web+Feature unified | β
YES - get_entity_documentation | β
REQUIRED |
| V07 | `experiment_audiences_flat` | Experimentβaudience map | Targeting analysis | β
YES - get_entity_documentation | β
REQUIRED |
| V08 | `experiment_events_flat` | Experimentβevent tracking | Conversion metrics | β
YES - get_entity_documentation | β
REQUIRED |
| V09 | `experiment_pages_flat` | Page targeting | URL conditions | β
YES - get_entity_documentation | β
REQUIRED |
| V10 | `analytics_summary_view` | Dashboard metrics | High-level KPIs | β
YES - get_entity_documentation | β
REQUIRED |
| V11 | `entity_usage_view` | Adoption analysis | Active/orphaned entities | β
YES - get_entity_documentation | β
REQUIRED |
| V12 | `audiences_flat` | Audience definitions | Targeting conditions | β
YES - get_entity_documentation | β
REQUIRED |
| V13 | `pages_flat` | Page activation | URL rules | β
YES - get_entity_documentation | β
REQUIRED |
| V14 | `change_history_flat` | Complete audit trail | Who/what/when | β
YES - get_entity_documentation | β
REQUIRED |
### NEW: Code Security Analysis Views (V15-V18)
| ID | View Name | Purpose | Key Use Case | **MUST CALL DOC FIRST** | **v4.0 structured_query** |
|----|-----------|---------|--------------|-------------------------|---------------------------|
| V15 | `experiment_code_analysis_view` | JavaScript/CSS usage analysis | Find experiments with custom code | β
YES - get_entity_documentation | β
REQUIRED |
| V16 | `experiment_code_snippets_flat` | All code snippets with security flags | Security vulnerability scanning | β
YES - get_entity_documentation | β
REQUIRED |
| V17 | `project_code_security_view` | Project-level security assessment | Compliance reporting | β
YES - get_entity_documentation | β
REQUIRED |
| V18 | `code_search_patterns_view` | 30+ security pattern scanner | XSS/vulnerability detection | β
YES - get_entity_documentation | β
REQUIRED |
**π v4.0 CRITICAL**: ALL analytics views now require structured_query parameter, natural language queries removed
**SECURITY ANALYSIS PATTERN**:
```javascript
// Find code with security risks
async function analyzeCodeSecurity(projectId) {
// 1. ALWAYS GET DOCUMENTATION FIRST
const doc = await get_entity_documentation({entity_type: "code_search_patterns_view"});
// 2. Query for security concerns
return analyze_data({
structured_query: {
from: "code_search_patterns_view",
where: {
project_id: projectId,
security_concern_score: { ">": 5 }
},
select: ["entity_name", "code_location", "security_concern_score"]
}
});
}
```
**Security Flags Available**:
- `contains_script_tag` - Detects `<script>` tags in HTML
- `contains_eval` - Finds dangerous eval() usage
- `contains_document_write` - Detects document.write
- `contains_innerhtml` - Finds innerHTML manipulation
- `contains_external_urls` - Detects external resource loading
- `security_concern_score` - Aggregated risk score (0-20+)
**PATTERN FOR EVERY VIEW (v4.0 UPDATED)**:
```javascript
// This is NON-NEGOTIABLE - hardcode this pattern
async function queryAnyView(viewName, desiredFields) {
// 1. DISCOVERY IS MANDATORY
const doc = await get_entity_documentation({entity_type: viewName});
// 2. BUILD WITH REAL FIELDS
const validFields = doc.fields.filter(f => desiredFields.includes(f));
// 3. EXECUTE WITH STRUCTURED_QUERY (v4.0 REQUIRED)
return analyze_data({
structured_query: {
from: viewName,
select: validFields
}
});
}
```
</details>
<details><summary>Β§B.5 View Field Lists (ENHANCED WITH DOC EXAMPLES)</summary>
**V01: flags_unified_view (27 fields)**
```
// BEFORE QUERYING - ALWAYS CALL:
get_entity_documentation(entity_type="flags_unified_view")
// RETURNS THESE EXACT FIELD NAMES:
audience_conditions_json, days_since_creation, effective_status, enabled,
environment_archived, environment_is_primary, flag_archived, flag_created_time,
flag_description, flag_enabled, flag_id, flag_key, flag_name, flag_updated_time,
has_audience_targeting, percentage_included, rollout_percentage, rule_category,
rule_created_time, rule_enabled, rule_id, rule_key, rule_name, rule_type,
rule_updated_time, simple_status, usage_category
```
**V06: experiments_unified_view (29 fields)**
```
// BEFORE QUERYING - ALWAYS CALL:
get_entity_documentation(entity_type="experiments_unified_view")
// RETURNS THESE EXACT FIELD NAMES:
audience_count, campaign_holdback_percentage, campaign_id, campaign_name,
created_time, days_running, days_since_update, description, end_time,
environment_key, environment_name, experiment_id, experiment_name, experiment_type,
metric_count, page_count, page_targeting_type, platform, project_id, project_name,
start_time, status, status_category, traffic_percentage, updated_time,
url_condition_count, uses_extensions, variation_count, visitors_exposed
```
**π v4.0 CRITICAL**: Field names vary between views! Always check with DOC first!
**π v4.0 CRITICAL**: Use structured_query parameter, not natural language!
</details>
<details><summary>Β§B.6 Display Framework Details</summary>
#### Table Logic
```python
if len(entities) >= 2 and uniform_keys:
display_as_table()
if 'traffic' in columns or 'percentage' in columns:
# Visual bar: 5%=β, 100%=ββββββββββββββββββββ
add_minibar(length = round(percentage/5))
if rows > 30:
show_first_30()
add_note(f"... (+{total-30} more)")
else:
use_compact_block()
```
#### Compact Block Format
```
## β
[Entity] [status]
π― **Name** (`key`)
π’ **Project:** name (platform)
π **Details:** type β’ status
π§ **Config:** β€50 chars
π‘ **Usage:** one-liner
```
#### Alignment Rules
- Numbers: `:--:` (center/right)
- Text: `:---` (left)
- Percentages: Include % symbol
</details>
<details><summary>Β§B.7 Workflow Templates (ENHANCED WITH DISCOVERY)</summary>
#### Flag + New Variation (REQUIRES TEMPLATES)
```yaml
Trigger: WORKFLOW_REQUIRED status
Discovery First:
0. TPL: get_entity_templates(entity_type="flag_variation_addition")
Sequence:
1. create_variation(flag_id, variation_config)
2. update_ruleset(traffic_allocation) # Must sum to 10,000
3. validate_distribution()
```
#### Traffic Reallocation
```yaml
Trigger: Traffic percentage change
Discovery First:
0. DOC: get_entity_documentation(entity_type="ruleset")
Sequence:
1. get_current_ruleset()
2. calculate_new_weights()
3. update_ruleset(new_allocation)
4. confirm operation_successful
```
#### A/B Test Setup (Feature Platform)
```yaml
Entity: ruleset (type='a/b_test')
Discovery First:
0. TPL: get_entity_templates(entity_type="ruleset", complexity=2)
Components:
- Metrics configuration
- Audience targeting
- Traffic distribution
- Variation setup
```
#### π v4.0: Complex Entity Auto-Orchestration
```yaml
Trigger: manage_entity_lifecycle detects complexity
Response: HARD_STOP_REQUIRED
Required Action:
1. Call get_entity_templates
2. Receive orchestration template
3. Fill template parameters
4. Execute via template mode
Forbidden Actions:
- Create child entities separately
- Retry without template
- Manual coordination
```
</details>
<details><summary>Β§B.8 Query Examples & Patterns (ENHANCED v4.0)</summary>
#### Basic Flag Query (WITH DISCOVERY & STRUCTURED_QUERY)
```json
// STEP 1: DISCOVER FIELDS
{"name": "get_entity_documentation",
"arguments": {"entity_type": "flags_unified_view"}}
// STEP 2: BUILD QUERY WITH REAL FIELDS (v4.0 REQUIRED)
{
"name": "analyze_data",
"arguments": {
"structured_query": {
"from": "flags_unified_view",
"select": ["flag_key", "flag_name", "enabled", "simple_status"],
"where": {"enabled": 1},
"limit": 20
}
}
}
```
#### Aggregated Campaign Status
```json
// ALWAYS START WITH:
{"name": "get_entity_documentation",
"arguments": {"entity_type": "experiments_unified_view"}}
// THEN (v4.0 structured_query required):
{
"name": "analyze_data",
"arguments": {
"structured_query": {
"from": "experiments_unified_view",
"select": ["campaign_name", "status"],
"group_by": ["campaign_name", "status"],
"aggregate": {"count": "*"},
"order_by": {"field": "count", "direction": "desc"}
}
}
}
```
#### Variable Search (SPECIAL VIEW)
```json
// DISCOVER THIS SPECIAL VIEW:
{"name": "get_entity_documentation",
"arguments": {"entity_type": "flag_variation_variables"}}
// THEN SEARCH (v4.0 structured_query):
{
"name": "analyze_data",
"arguments": {
"structured_query": {
"from": "flag_variation_variables",
"select": ["flag_key", "variation_key", "variable_name", "variable_value"],
"where": {"variable_name": "pricing_tier"},
"limit": 50
}
}
}
```
#### π v4.0: Export Data Patterns
```json
// SIMPLE ENTITY EXPORT (PREFERRED):
{
"name": "export_data",
"arguments": {
"entity_type": "flag",
"project_id": "12345",
"format": "csv"
}
}
// COMPLEX FILTERED EXPORT:
{
"name": "export_data",
"arguments": {
"structured_query": {
"from": "flags_unified_view",
"where": {"enabled": 1, "environment_key": "production"}
},
"format": "json"
}
}
// β WRONG (DEPRECATED):
{
"name": "export_data",
"arguments": {
"query": "show all flags", // This fails!
"format": "csv"
}
}
```
</details>
<details><summary>Β§B.9 Status Icons & Response Fidelity</summary>
## 1 Β· Emoji / Icon Legend π¨
| Entity | Icon | Status | Icon |
| ---------- | ---- | -------------------- | ---- |
| Flag | π© | Active/Running | π’ |
| Experiment | π§ͺ | Paused / Warning | π‘ |
| Audience | π― | Stopped / Error | π΄ |
| Page | π