Skip to main content
Glama
madhukarkumar

SingleStore MCP Server

optimize_sql

Analyze SQL queries with PROFILE and receive actionable optimization recommendations to enhance database performance on SingleStore MCP Server.

Instructions

Analyze a SQL query using PROFILE and provide optimization recommendations

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYesSQL query to analyze and optimize

Implementation Reference

  • The primary handler for the 'optimize_sql' tool. Validates input query, executes PROFILE on SingleStore, retrieves JSON profile data, analyzes it via analyzeProfileData helper, and returns structured optimization recommendations including summary, suggestions, and optionally an optimized query.
    case 'optimize_sql': {
      if (!request.params.arguments || typeof request.params.arguments.query !== 'string') {
        throw new McpError(
          ErrorCode.InvalidParams,
          'Query parameter must be a string'
        );
      }
    
      const query = request.params.arguments.query.trim();
      
      try {
        // Step 1: Run PROFILE on the query
        await conn.query('SET profile_for_debug = ON');
        await conn.query(`PROFILE ${query}`);
        
        // Step 2: Get the profile data in JSON format
        const [profileResult] = await conn.query('SHOW PROFILE JSON') as [mysql.RowDataPacket[], mysql.FieldPacket[]];
        
        // Step 3: Analyze the profile data and generate recommendations
        const recommendations = await this.analyzeProfileData(profileResult[0], query);
        
        // Step 4: Return the analysis and recommendations
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                original_query: query,
                profile_summary: recommendations.summary,
                recommendations: recommendations.suggestions,
                optimized_query: recommendations.optimizedQuery || query
              }, null, 2)
            }
          ]
        };
      } catch (error: unknown) {
        const err = error as Error;
        throw new McpError(
          ErrorCode.InternalError,
          `Query optimization error: ${err.message}`
        );
      }
    }
  • src/index.ts:1365-1377 (registration)
    Registration of the 'optimize_sql' tool in the MCP server's listTools response, defining its name, description, and input schema (requires 'query' string).
      name: 'optimize_sql',
      description: 'Analyze a SQL query using PROFILE and provide optimization recommendations',
      inputSchema: {
        type: 'object',
        properties: {
          query: {
            type: 'string',
            description: 'SQL query to analyze and optimize'
          }
        },
        required: ['query']
      }
    }
  • TypeScript interface defining the structure of optimization recommendations returned by the tool, including performance summary, suggestion list with impact levels, and optional optimized query.
    interface OptimizationRecommendation {
      summary: {
        total_runtime_ms: string;
        compile_time_ms: string;
        execution_time_ms: string;
        bottlenecks: string[];
      };
      suggestions: Array<{
        issue: string;
        recommendation: string;
        impact: 'high' | 'medium' | 'low';
      }>;
      optimizedQuery?: string;
    }
  • Primary helper function that processes SingleStore PROFILE JSON data, extracts timings, orchestrates specialized analysis (execution plan, memory, network, etc.), identifies bottlenecks, and builds the OptimizationRecommendation object.
    private async analyzeProfileData(profileData: any, originalQuery: string): Promise<OptimizationRecommendation> {
      const result: OptimizationRecommendation = {
        summary: {
          total_runtime_ms: '0',
          compile_time_ms: '0',
          execution_time_ms: '0',
          bottlenecks: []
        },
        suggestions: []
      };
    
      try {
        // Parse the JSON string if it's not already an object
        const profile = typeof profileData === 'string' ? JSON.parse(profileData) : profileData;
        
        // Extract query_info
        const queryInfo = profile.query_info || {};
        
        // Set basic summary information
        result.summary.total_runtime_ms = queryInfo.total_runtime_ms || '0';
        
        // Extract compile time from compile_time_stats if available
        if (queryInfo.compile_time_stats && queryInfo.compile_time_stats.total) {
          result.summary.compile_time_ms = queryInfo.compile_time_stats.total;
          
          // Calculate execution time (total - compile)
          const totalTime = parseInt(result.summary.total_runtime_ms, 10);
          const compileTime = parseInt(result.summary.compile_time_ms, 10);
          result.summary.execution_time_ms = (totalTime - compileTime).toString();
        }
    
        // Analyze execution plan and operators
        this.analyzeExecutionPlan(profile, result);
        
        // Analyze table statistics and memory usage
        this.analyzeMemoryAndStats(profile, result);
        
        // Analyze network traffic and data movement
        this.analyzeNetworkTraffic(profile, result);
        
        // Analyze compilation time
        this.analyzeCompilationTime(profile, result);
        
        // Analyze partition skew
        this.analyzePartitionSkew(profile, result);
        
        // Identify bottlenecks
        this.identifyBottlenecks(profile, result);
        
      } catch (error) {
        result.suggestions.push({
          issue: 'Error analyzing profile data',
          recommendation: 'The profile data could not be properly analyzed. Please check the query syntax.',
          impact: 'high'
        });
      }
      
      return result;
    }
  • Helper method for analyzing execution plan from profile text: detects full table scans without indexes and large hash joins, adding high/medium impact suggestions.
    private analyzeExecutionPlan(profile: any, result: OptimizationRecommendation): void {
      const textProfile = profile.query_info?.text_profile || '';
      const lines = textProfile.split('\n');
      
      // Look for full table scans
      if (textProfile.includes('TableScan') && !textProfile.includes('IndexScan')) {
        result.suggestions.push({
          issue: 'Full table scan detected',
          recommendation: 'Consider adding an index to the columns used in WHERE clauses to avoid scanning the entire table.',
          impact: 'high'
        });
      }
      
      // Check for hash joins with large tables
      if (textProfile.includes('HashJoin')) {
        const rowsMatch = textProfile.match(/actual_rows: (\d+)/);
        if (rowsMatch && parseInt(rowsMatch[1], 10) > 10000) {
          result.suggestions.push({
            issue: 'Large hash join operation',
            recommendation: 'For large tables, consider using appropriate indexes on join columns or partitioning data to reduce the size of hash tables.',
            impact: 'medium'
          });
        }
      }
    }
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions the tool uses 'PROFILE' (implying a profiling mechanism) and provides recommendations, but doesn't specify whether this is a read-only analysis, if it requires specific permissions, what the output format looks like, or any rate limits. For a tool with zero annotation coverage, this leaves significant behavioral gaps.

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 a single, efficient sentence that front-loads the core functionality ('analyze a SQL query') and adds key details ('using PROFILE and provide optimization recommendations') without any wasted words. Every part of the sentence contributes directly to understanding the tool's purpose.

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

Completeness3/5

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

Given the tool's moderate complexity (analysis with optimization recommendations), no annotations, no output schema, and a single well-documented parameter, the description is adequate but incomplete. It covers the basic purpose but lacks details on behavioral traits, output format, and usage context relative to siblings, which are needed for a more complete 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%, with the single parameter 'query' well-documented in the schema ('SQL query to analyze and optimize'). The description adds minimal value beyond this, only reiterating that it analyzes and optimizes the query. Since the schema does the heavy lifting, the baseline score of 3 is appropriate.

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' and 'provide optimization recommendations') and identifies the resource ('SQL query'). It distinguishes from siblings like 'query_table' or 'run_read_query' by focusing on analysis rather than execution. However, it doesn't explicitly differentiate from all siblings (e.g., 'describe_table' might also analyze queries).

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

Usage Guidelines3/5

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

The description implies usage context ('analyze a SQL query... and provide optimization recommendations'), suggesting it's for performance tuning rather than data retrieval or schema operations. However, it lacks explicit guidance on when to use this tool versus alternatives like 'run_read_query' for execution or 'describe_table' for schema analysis, and doesn't mention prerequisites or exclusions.

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

Related 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/madhukarkumar/singlestore-mcp-server'

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