Skip to main content
Glama
Fervoyush

Plotnine MCP Server

by Fervoyush

suggest_plot_templates

Analyzes your dataset characteristics and goals to recommend suitable plot templates for creating statistical visualizations with plotnine.

Instructions

Analyze data and suggest appropriate plot templates.

Examines data characteristics (number of numeric/categorical columns, presence of time data) and optionally a user goal to recommend suitable templates.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
data_sourceYesData source to analyze
goalNoOptional user goal (e.g., 'compare distributions', 'show trend', 'correlation')

Implementation Reference

  • Main handler function that processes tool arguments, loads and analyzes data structure, invokes suggest_template helper, and formats the response with recommended templates.
    async def suggest_plot_templates_handler(arguments: dict[str, Any]) -> list[TextContent]:
        """Handle suggest_plot_templates tool calls."""
        try:
            data_source = DataSource(**arguments["data_source"])
            goal = arguments.get("goal")
    
            # Load data to analyze
            try:
                data = load_data(data_source)
            except DataLoadError as e:
                return [
                    TextContent(
                        type="text",
                        text=f"Data loading error: {str(e)}\n\nCannot analyze data for suggestions.",
                    )
                ]
    
            # Analyze data characteristics
            import numpy as np
    
            numeric_cols = data.select_dtypes(include=[np.number]).columns
            categorical_cols = data.select_dtypes(include=["object", "category"]).columns
    
            # Check for datetime columns
            has_time = False
            for col in data.columns:
                if "date" in col.lower() or "time" in col.lower():
                    has_time = True
                    break
                # Also check dtype
                if data[col].dtype == "datetime64[ns]":
                    has_time = True
                    break
    
            num_numeric = len(numeric_cols)
            num_categorical = len(categorical_cols)
    
            # Get suggestions
            suggestions = suggest_template(num_numeric, num_categorical, has_time, goal)
    
            # Format message
            message = "Template Suggestions\n" + "=" * 60 + "\n\n"
            message += f"Data characteristics:\n"
            message += f"  • Numeric columns: {num_numeric} ({', '.join(numeric_cols) if num_numeric > 0 else 'none'})\n"
            message += f"  • Categorical columns: {num_categorical} ({', '.join(categorical_cols) if num_categorical > 0 else 'none'})\n"
            message += f"  • Time-based data: {'Yes' if has_time else 'No'}\n"
    
            if goal:
                message += f"  • User goal: {goal}\n"
    
            message += "\n"
    
            if suggestions:
                message += f"Recommended templates ({len(suggestions)}):\n\n"
                all_templates = get_template_list()
                for i, template_name in enumerate(suggestions, 1):
                    desc = all_templates.get(template_name, "")
                    message += f"{i}. {template_name}\n"
                    message += f"   {desc}\n\n"
            else:
                message += "No specific templates recommended for this data.\n"
                message += "Try 'list_plot_templates' to see all available options.\n"
    
            message += "\n" + "=" * 60 + "\n"
            message += "Use 'create_plot_from_template' with one of these templates."
    
            return [TextContent(type="text", text=message)]
    
        except Exception as e:
            return [
                TextContent(
                    type="text",
                    text=f"Error analyzing data: {str(e)}",
                )
            ]
  • Tool registration in the list_tools() function, including name, description, and input schema definition.
            Tool(
                name="suggest_plot_templates",
                description="""Analyze data and suggest appropriate plot templates.
    
    Examines data characteristics (number of numeric/categorical columns,
    presence of time data) and optionally a user goal to recommend suitable
    templates.""",
                inputSchema={
                    "type": "object",
                    "properties": {
                        "data_source": {
                            "type": "object",
                            "description": "Data source to analyze",
                        },
                        "goal": {
                            "type": "string",
                            "description": "Optional user goal (e.g., 'compare distributions', 'show trend', 'correlation')",
                        },
                    },
                    "required": ["data_source"],
                },
            ),
  • Input schema definition for the suggest_plot_templates tool, specifying data_source (required) and optional goal.
    inputSchema={
        "type": "object",
        "properties": {
            "data_source": {
                "type": "object",
                "description": "Data source to analyze",
            },
            "goal": {
                "type": "string",
                "description": "Optional user goal (e.g., 'compare distributions', 'show trend', 'correlation')",
            },
        },
        "required": ["data_source"],
    },
  • Helper function containing the core logic for suggesting plot templates based on counts of numeric/categorical columns, presence of time data, and optional user goal.
    def suggest_template(
        num_numeric: int, num_categorical: int, has_time: bool, goal: Optional[str] = None
    ) -> list[str]:
        """
        Suggest appropriate templates based on data characteristics.
    
        Args:
            num_numeric: Number of numeric columns
            num_categorical: Number of categorical columns
            has_time: Whether data has time/date columns
            goal: Optional user-specified goal (e.g., "compare", "trend", "distribution")
    
        Returns:
            List of suggested template names
        """
        suggestions = []
    
        # Time-based suggestions
        if has_time and num_numeric >= 1:
            suggestions.append("time_series")
            if num_categorical >= 1:
                suggestions.append("multi_line")
    
        # Distribution comparisons
        if num_categorical >= 1 and num_numeric >= 1:
            suggestions.append("distribution_comparison")
            suggestions.append("boxplot_comparison")
    
        # Correlation/relationship
        if num_numeric >= 2:
            suggestions.append("scatter_with_trend")
            if num_numeric >= 3:
                suggestions.append("correlation_heatmap")
    
        # Single variable distribution
        if num_numeric >= 1 and num_categorical == 0:
            suggestions.append("histogram_with_density")
    
        # Category breakdown
        if num_categorical >= 1:
            suggestions.append("category_breakdown")
    
        # Goal-based refinement
        if goal:
            goal_lower = goal.lower()
            if "trend" in goal_lower or "time" in goal_lower:
                suggestions = [s for s in suggestions if "time" in s or "line" in s]
            elif "compare" in goal_lower or "comparison" in goal_lower:
                suggestions = [
                    s for s in suggestions if "comparison" in s or "boxplot" in s
                ]
            elif "distribution" in goal_lower:
                suggestions = [
                    s for s in suggestions if "distribution" in s or "histogram" in s
                ]
            elif "correlation" in goal_lower or "relationship" in goal_lower:
                suggestions = [s for s in suggestions if "correlation" in s or "scatter" in s]
    
        # Remove duplicates while preserving order
        seen = set()
        unique_suggestions = []
        for item in suggestions:
            if item not in seen:
                seen.add(item)
                unique_suggestions.append(item)
    
        return unique_suggestions[:5]  # Return top 5
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 mentions analyzing data characteristics and recommending templates, but fails to disclose critical behavioral traits such as whether this is a read-only operation, if it requires specific permissions, potential rate limits, or what the output format looks like (e.g., list of templates with metadata). For a tool with no annotations, this is a significant gap, warranting a score of 2.

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

Conciseness4/5

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

The description is appropriately sized with two sentences that efficiently convey the tool's function and parameters. The first sentence states the core purpose, and the second elaborates on the analysis process. There's no wasted text, and it's front-loaded with key information, though it could be slightly more structured (e.g., bullet points for clarity).

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 complexity (data analysis tool with 2 parameters, no output schema, and no annotations), the description is moderately complete. It covers the purpose and parameter roles but lacks details on behavioral aspects, output format, and explicit usage context. Without an output schema, it should ideally hint at return values (e.g., 'recommends suitable templates'), which it partially does but not comprehensively. This results in a score of 3, as it's adequate but has clear gaps.

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 both parameters ('data_source' and 'goal'). The description adds marginal value by explaining that 'data_source' is analyzed for characteristics and 'goal' is optional for user intent, but doesn't provide additional syntax, format details, or examples beyond what the schema implies. With high schema coverage, the baseline is 3, and the description doesn't significantly exceed this.

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: 'Analyze data and suggest appropriate plot templates.' It specifies the verb ('analyze' and 'suggest') and resource ('plot templates'), and distinguishes it from siblings like 'create_plot' or 'list_plot_templates' by focusing on recommendation rather than creation or listing. However, it doesn't explicitly differentiate from 'preview_data' or other analysis tools, keeping it at 4 instead of 5.

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 by mentioning it 'examines data characteristics' and optionally a 'user goal,' suggesting it's for data exploration or visualization planning. However, it lacks explicit guidance on when to use this tool versus alternatives like 'preview_data' for initial inspection or 'create_plot_from_template' for direct creation, and no exclusions are provided. This results in a score of 3 for implied but not explicit guidelines.

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/Fervoyush/plotnine-mcp'

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