Skip to main content
Glama
rickyb30

DataPilot MCP Server

by rickyb30

analyze_query_results

Execute database queries and analyze results using AI to extract insights, summarize findings, and identify patterns from data.

Instructions

Execute a query and analyze its results using AI

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryYes
results_limitNo
analysis_typeNosummary

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The MCP tool handler for 'analyze_query_results'. Executes the SQL query via Snowflake client, then delegates AI analysis to the OpenAI client.
    @mcp.tool()
    async def analyze_query_results(query: str, results_limit: int = 100, analysis_type: str = "summary", ctx: Context = None) -> str:
        """Execute a query and analyze its results using AI"""
        await ctx.info(f"Analyzing query results for: {query[:100]}...")
        
        try:
            # Execute the query first
            snowflake = await get_snowflake_client()
            result = await snowflake.execute_query(query, results_limit)
            
            if not result.success:
                await ctx.error(f"Query failed: {result.error}")
                return f"Query execution failed: {result.error}"
            
            # Analyze the results
            openai = await get_openai_client()
            analysis = await openai.analyze_query_results(query, result.data, analysis_type)
            
            await ctx.info("Successfully analyzed query results")
            return analysis
            
        except Exception as e:
            logger.error(f"Error analyzing query results: {str(e)}")
            await ctx.error(f"Failed to analyze query results: {str(e)}")
            raise
  • Supporting helper in OpenAIClient class that performs the AI-powered analysis of query results using OpenAI chat completions.
    async def analyze_query_results(
        self,
        query: str,
        results: List[Dict[str, Any]],
        analysis_type: str = "summary"
    ) -> str:
        """Analyze query results using AI"""
        
        # Limit data for analysis to avoid token limits
        sample_data = results[:10] if len(results) > 10 else results
        
        system_prompt = f"""
        You are a data analyst. Analyze the provided query results and provide insights.
        
        Analysis type: {analysis_type}
        
        Provide a clear, concise analysis with:
        - Key findings and patterns
        - Statistical insights if applicable
        - Recommendations or next steps
        - Any anomalies or interesting observations
        
        Format your response in a clear, professional manner.
        """
        
        user_prompt = f"""
        SQL Query: {query}
        
        Results ({len(results)} rows total, showing sample):
        {json.dumps(sample_data, indent=2, default=str)}
        
        Please analyze these results and provide insights.
        """
        
        try:
            response = await self.client.chat.completions.create(
                model=self.model,
                messages=[
                    {"role": "system", "content": system_prompt},
                    {"role": "user", "content": user_prompt}
                ],
                temperature=0.3,
                max_tokens=1000
            )
            
            analysis = response.choices[0].message.content.strip()
            logger.info("Generated data analysis")
            return analysis
            
        except Exception as e:
            logger.error(f"Error analyzing data: {str(e)}")
            raise Exception(f"Failed to analyze data: {str(e)}")
Behavior2/5

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

With no annotations provided, the description carries full burden for behavioral disclosure. It mentions AI-based analysis but doesn't specify what 'analyze' entails (e.g., statistical summaries, pattern detection, recommendations), performance characteristics, rate limits, authentication needs, or error handling. The description is too vague about the tool's actual behavior beyond the high-level concept.

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 at just 7 words, front-loading the core purpose with zero wasted words. Every element ('Execute a query', 'analyze its results', 'using AI') contributes essential information without redundancy or unnecessary elaboration.

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 has an output schema (which handles return value documentation) but no annotations and 0% schema description coverage, the description is minimally complete for understanding the high-level purpose. However, it lacks crucial details about parameter meanings, behavioral constraints, and differentiation from siblings that would make it fully adequate for a 3-parameter AI analysis tool.

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

Parameters2/5

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

With 0% schema description coverage for all 3 parameters, the description adds no semantic information about what 'query', 'results_limit', or 'analysis_type' mean. It doesn't explain query format, valid analysis types beyond the default 'summary', or how the limit applies. The description fails to compensate for the complete lack of schema documentation.

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 as 'Execute a query and analyze its results using AI', which specifies both the action (execute+analyze) and resource (query results). It distinguishes from siblings like 'execute_sql' (execution only) and 'generate_table_insights' (table-focused analysis). However, it doesn't explicitly mention what kind of query or database system is involved.

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 like 'execute_sql' (for raw execution) or 'natural_language_to_sql' (for query generation). It doesn't mention prerequisites, appropriate contexts, or exclusions, leaving the agent to infer usage from the name and purpose alone.

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/rickyb30/datapilot-mcp-server'

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