Skip to main content
Glama
sloth-wq

Prompt Auto-Optimizer MCP

by sloth-wq

gepa_reflect

Analyze AI prompt failures to generate targeted improvements, optimizing performance through evolutionary algorithms in the Prompt Auto-Optimizer MCP server.

Instructions

Analyze failures and generate prompt improvements

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
trajectoryIdsYesList of trajectory IDs to analyze for failure patterns
targetPromptIdYesPrompt ID to generate improvements for
analysisDepthNoDepth of failure analysis to performdeep
focusAreasNoSpecific areas to focus analysis on (optional)

Implementation Reference

  • The main handler function that executes the gepa_reflect tool logic. Loads execution trajectories, performs batch analysis using ReflectionEngine, processes failure patterns into prioritized improvements, and returns a comprehensive Markdown analysis report.
      private async reflect(params: ReflectParams): Promise<{
        content: { type: string; text: string; }[];
      }> {
        const { trajectoryIds, targetPromptId, analysisDepth = 'deep', focusAreas } = params;
    
        // Validate required parameters
        if (!trajectoryIds || trajectoryIds.length === 0 || !targetPromptId) {
          throw new Error('trajectoryIds and targetPromptId are required');
        }
    
        const reflectionId = `reflection_${Date.now()}_${Math.random().toString(36).substring(7)}`;
    
        try {
          // Load trajectories for analysis
          const trajectories = [];
          for (const trajectoryId of trajectoryIds) {
            try {
              const trajectory = await this.trajectoryStore.load(trajectoryId);
              if (trajectory) {
                trajectories.push(trajectory);
              }
            } catch (error) {
              // eslint-disable-next-line no-console
        console.warn(`Failed to load trajectory ${trajectoryId}:`, error);
            }
          }
    
          if (trajectories.length === 0) {
            throw new Error('No valid trajectories found for analysis');
          }
    
          // Perform failure analysis using reflection engine
          const analysisResult = await this.reflectionEngine.analyzeBatch(trajectories);
    
          // Generate improvement suggestions
          const improvements = analysisResult.commonPatterns.map(pattern => ({
            issue: pattern.description,
            frequency: pattern.frequency,
            severity: pattern.frequency,
            suggestion: `Address ${pattern.type} by improving prompt clarity and specificity`,
            priority: pattern.frequency > 0.7 ? 'High' : pattern.frequency > 0.4 ? 'Medium' : 'Low',
          }));
    
          return {
            content: [
              {
                type: 'text',
                text: `# Reflection Analysis Complete
    
    ## Analysis Details
    - **Reflection ID**: ${reflectionId}
    - **Target Prompt**: ${targetPromptId}
    - **Trajectories Analyzed**: ${trajectories.length}/${trajectoryIds.length}
    - **Analysis Depth**: ${analysisDepth}
    - **Focus Areas**: ${focusAreas?.join(', ') || 'Default'}
    
    ## Failure Pattern Analysis
    - **Patterns Detected**: ${analysisResult.commonPatterns.length}
    - **Recommendations**: ${analysisResult.recommendations.length}
    - **Confidence**: ${(analysisResult.overallConfidence * 100).toFixed(1)}%
    
    ## Key Findings
    ${analysisResult.commonPatterns.slice(0, 5).map((pattern, idx) => 
      `${idx + 1}. **${pattern.type}** (${(pattern.frequency * 100).toFixed(1)}% frequency)
       - Severity: ${(pattern.frequency * 100).toFixed(1)}%
       - Description: ${pattern.description}`
    ).join('\n')}
    
    ## Improvement Recommendations
    ${improvements.slice(0, 5).map((imp, idx) => 
      `${idx + 1}. **${imp.priority} Priority**: ${imp.suggestion}
       - Issue: ${imp.issue}
       - Frequency: ${(imp.frequency * 100).toFixed(1)}%`
    ).join('\n')}
    
    ## Summary
    The analysis identified ${analysisResult.commonPatterns.length} distinct failure patterns across ${trajectories.length} trajectories. Focus on addressing high-priority issues first to maximize improvement impact.`,
              },
            ],
          };
        } catch (error) {
          throw new Error(`Failed to perform reflection analysis: ${error instanceof Error ? error.message : 'Unknown error'}`);
        }
      }
  • MCP tool schema definition including name, description, and input validation schema for gepa_reflect, used for tool listing and validation.
    {
      name: 'gepa_reflect',
      description: 'Analyze failures and generate prompt improvements',
      inputSchema: {
        type: 'object',
        properties: {
          trajectoryIds: {
            type: 'array',
            items: { type: 'string' },
            description: 'List of trajectory IDs to analyze for failure patterns'
          },
          targetPromptId: {
            type: 'string',
            description: 'Prompt ID to generate improvements for'
          },
          analysisDepth: {
            type: 'string',
            enum: ['shallow', 'deep'],
            default: 'deep',
            description: 'Depth of failure analysis to perform'
          },
          focusAreas: {
            type: 'array',
            items: { type: 'string' },
            description: 'Specific areas to focus analysis on (optional)'
          }
        },
        required: ['trajectoryIds', 'targetPromptId']
      }
    },
  • Tool handler registration in the MCP CallToolRequestSchema switch statement, dispatching calls to the reflect method.
    case 'gepa_reflect':
      return await this.reflect(args as unknown as ReflectParams);
  • TypeScript type definition for ReflectParams, providing compile-time validation for the tool's input parameters.
    export interface ReflectParams {
      trajectoryIds: string[];
      targetPromptId: string;
      analysisDepth?: 'shallow' | 'deep';
      focusAreas?: string[];
    }
  • TOOL_NAMES constant providing the exact string identifier 'gepa_reflect' for type-safe tool name references.
    REFLECT: 'gepa_reflect',
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states the tool analyzes failures and generates improvements, implying a read-and-write operation, but doesn't specify whether it modifies data, requires specific permissions, has rate limits, or what the output format looks like. For a tool with 4 parameters and no annotations, this leaves significant behavioral gaps, such as whether it's destructive or how results are returned.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is extremely concise with just one sentence ('Analyze failures and generate prompt improvements'), which is front-loaded and wastes no words. Every part of the sentence directly contributes to understanding the tool's purpose, making it efficient and well-structured for quick comprehension.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness2/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (4 parameters, no annotations, no output schema), the description is incomplete. It lacks details on behavioral traits, output format, and usage context, which are critical for an agent to invoke it correctly. While the schema covers parameters well, the description doesn't add enough value to compensate for missing annotations and output schema, leaving gaps in overall understanding.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

Schema description coverage is 100%, so the schema already documents all parameters thoroughly. The description adds no additional meaning beyond what's in the schema, such as explaining how 'trajectoryIds' relate to failures or what 'focusAreas' might include. With high schema coverage, the baseline is 3, as the description doesn't compensate but also doesn't detract from the well-documented parameters.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose with specific verbs ('analyze failures' and 'generate prompt improvements') and identifies the resource (trajectories and prompts). It distinguishes from siblings like gepa_evaluate_prompt (which likely evaluates rather than analyzes failures) and gepa_record_trajectory (which records rather than analyzes), though not explicitly. However, it doesn't fully differentiate from all siblings like gepa_select_optimal or gepa_start_evolution, which may involve similar improvement processes.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

The description provides no guidance on when to use this tool versus alternatives. It doesn't mention prerequisites (e.g., needing existing trajectories or prompts), exclusions, or compare to siblings like gepa_evaluate_prompt for evaluation versus improvement. Usage is implied only by the purpose, with no explicit context or decision criteria provided.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/sloth-wq/prompt-auto-optimizer-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server