Skip to main content
Glama

create_correlation_heatmap

Visualize correlations between numeric columns in a dataset by generating a heatmap image. Specify columns to analyze and save the visualization to a file.

Instructions

Create a correlation heatmap from numeric columns in the dataset.

Args: file_path: Path to the data file output_path: Path where to save the heatmap image columns: Optional list of specific columns to include (if None, uses all numeric columns)

Returns: Information about the created heatmap

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
file_pathYes
output_pathYes
columnsNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault
resultYes

Implementation Reference

  • The main handler function that creates a correlation heatmap from numeric columns in a dataset. It loads data using pandas, selects numeric columns (or user-specified columns), calculates the correlation matrix, and creates a visualization using seaborn with matplotlib. The function saves the heatmap to the specified output path and returns metadata about the created visualization.
    @mcp.tool()
    def create_correlation_heatmap(file_path: str, output_path: str, 
                                  columns: Optional[List[str]] = None) -> str:
        """
        Create a correlation heatmap from numeric columns in the dataset.
        
        Args:
            file_path: Path to the data file
            output_path: Path where to save the heatmap image
            columns: Optional list of specific columns to include (if None, uses all numeric columns)
        
        Returns:
            Information about the created heatmap
        """
        try:
            if not VISUALIZATION_AVAILABLE:
                return f"Error: {VISUALIZATION_ERROR}"
                
            import pandas as pd
            from pathlib import Path
            
            # Load the data
            file_extension = Path(file_path).suffix.lower()
            if file_extension == '.csv':
                df = pd.read_csv(file_path)
            elif file_extension == '.json':
                df = pd.read_json(file_path)
            elif file_extension in ['.xlsx', '.xls']:
                df = pd.read_excel(file_path)
            elif file_extension == '.tsv':
                df = pd.read_csv(file_path, sep='\t')
            else:
                df = pd.read_csv(file_path)
            
            # Select numeric columns
            if columns:
                # Validate specified columns exist
                missing_cols = [col for col in columns if col not in df.columns]
                if missing_cols:
                    return f"Error: Columns not found: {missing_cols}"
                numeric_df = df[columns].select_dtypes(include=['number'])
            else:
                numeric_df = df.select_dtypes(include=['number'])
            
            if numeric_df.empty:
                return "Error: No numeric columns found for correlation analysis"
            
            # Calculate correlation matrix
            correlation_matrix = numeric_df.corr()
            
            # Create the heatmap
            plt.figure(figsize=(10, 8))
            sns.heatmap(correlation_matrix, 
                       annot=True, 
                       cmap='coolwarm', 
                       center=0,
                       fmt='.2f',
                       square=True,
                       linewidths=0.5)
            
            plt.title('Correlation Heatmap')
            plt.tight_layout()
            
            # Save the plot
            plt.savefig(output_path, dpi=300, bbox_inches='tight')
            plt.close()
            
            result = {
                "heatmap_created": True,
                "columns_analyzed": list(correlation_matrix.columns),
                "total_correlations": len(correlation_matrix.columns) ** 2,
                "output_file": output_path,
                "file_size": Path(output_path).stat().st_size if Path(output_path).exists() else 0
            }
            
            return json.dumps(result, indent=2)
            
        except Exception as e:
            return f"Error creating correlation heatmap: {str(e)}\n{traceback.format_exc()}"
  • The tool is registered as an MCP tool using the @mcp.tool() decorator on line 687, which exposes the create_correlation_heatmap function to the MCP server.
    @mcp.tool()
    def create_correlation_heatmap(file_path: str, output_path: str, 
                                  columns: Optional[List[str]] = None) -> str:
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 that the tool creates and saves a heatmap image, implying a write operation, but doesn't disclose critical behaviors like file format requirements, error handling, performance characteristics, or whether it modifies the original dataset. For a tool that writes files and processes data, this lack of transparency is a significant gap.

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 well-structured and front-loaded with the core purpose, followed by parameter explanations in a clear 'Args' and 'Returns' format. Every sentence earns its place: the first states the action, and the subsequent lines efficiently clarify inputs and outputs without redundancy. It's appropriately sized for the tool's complexity.

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 (3 parameters, file I/O, data processing), no annotations, and an output schema present, the description is partially complete. It covers the basic what and how but misses context like error conditions, performance limits, or dependencies on other tools (e.g., 'load_data'). The output schema handles return values, so the description doesn't need to detail them, but overall it leaves gaps for safe and effective use.

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 0%, so the description must compensate. It provides basic semantics for all three parameters: 'file_path' as the data source, 'output_path' as the save location, and 'columns' as an optional filter. However, it lacks details like supported file formats, path requirements, or column selection rules. The description adds value beyond the bare schema but doesn't fully bridge the coverage gap, warranting a baseline 3.

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: 'Create a correlation heatmap from numeric columns in the dataset.' It specifies the verb ('create') and resource ('correlation heatmap'), and distinguishes it from siblings like 'create_distribution_plots' or 'create_skills_location_heatmap' by focusing on correlation analysis. However, it doesn't explicitly differentiate from all possible alternatives, keeping it at a 4 rather than a 5.

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 when to choose this over other visualization tools like 'create_distribution_plots' or 'create_skills_location_heatmap', nor does it specify prerequisites (e.g., needing numeric data). The agent must infer usage from the purpose alone, which is insufficient for clear decision-making.

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/moeloubani/visidata-mcp'

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