Skip to main content
Glama
santoshray02

CSV Editor

by santoshray02

get_correlation_matrix

Calculate correlation matrix to identify relationships between numeric columns in CSV data for statistical analysis.

Instructions

Calculate correlation matrix for numeric columns.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
session_idYes
methodNopearson
columnsNo
min_correlationNo

Output Schema

TableJSON Schema
NameRequiredDescriptionDefault

No arguments

Implementation Reference

  • Core handler function that loads the CSV session data, selects numeric columns, computes the correlation matrix using pandas.corr(), filters by min_correlation if specified, identifies high correlations, and returns formatted results.
    async def get_correlation_matrix(
        session_id: str,
        method: str = "pearson",
        columns: Optional[List[str]] = None,
        min_correlation: Optional[float] = None,
        ctx: Context = None
    ) -> Dict[str, Any]:
        """
        Calculate correlation matrix for numeric columns.
        
        Args:
            session_id: Session identifier
            method: Correlation method ('pearson', 'spearman', 'kendall')
            columns: Specific columns to include (None for all numeric)
            min_correlation: Filter to show only correlations above this threshold
            ctx: FastMCP context
            
        Returns:
            Dict with correlation matrix
        """
        try:
            manager = get_session_manager()
            session = manager.get_session(session_id)
            
            if not session or session.df is None:
                return {"success": False, "error": "Invalid session or no data loaded"}
            
            df = session.df
            
            # Select columns
            if columns:
                missing_cols = [col for col in columns if col not in df.columns]
                if missing_cols:
                    return {"success": False, "error": f"Columns not found: {missing_cols}"}
                numeric_df = df[columns].select_dtypes(include=[np.number])
            else:
                numeric_df = df.select_dtypes(include=[np.number])
            
            if numeric_df.empty:
                return {"success": False, "error": "No numeric columns found"}
            
            if len(numeric_df.columns) < 2:
                return {"success": False, "error": "Need at least 2 numeric columns for correlation"}
            
            # Calculate correlation
            if method not in ['pearson', 'spearman', 'kendall']:
                return {"success": False, "error": f"Invalid method: {method}"}
            
            corr_matrix = numeric_df.corr(method=method)
            
            # Convert to dict format
            correlations = {}
            for col1 in corr_matrix.columns:
                correlations[col1] = {}
                for col2 in corr_matrix.columns:
                    value = corr_matrix.loc[col1, col2]
                    if not pd.isna(value):
                        if min_correlation is None or abs(value) >= min_correlation or col1 == col2:
                            correlations[col1][col2] = round(float(value), 4)
            
            # Find highly correlated pairs
            high_correlations = []
            for i, col1 in enumerate(corr_matrix.columns):
                for col2 in corr_matrix.columns[i+1:]:
                    corr_value = corr_matrix.loc[col1, col2]
                    if not pd.isna(corr_value) and abs(corr_value) >= 0.7:
                        high_correlations.append({
                            "column1": col1,
                            "column2": col2,
                            "correlation": round(float(corr_value), 4)
                        })
            
            high_correlations.sort(key=lambda x: abs(x["correlation"]), reverse=True)
            
            session.record_operation(OperationType.ANALYZE, {
                "type": "correlation",
                "method": method,
                "columns": list(corr_matrix.columns)
            })
            
            return {
                "success": True,
                "method": method,
                "correlation_matrix": correlations,
                "high_correlations": high_correlations,
                "columns_analyzed": list(corr_matrix.columns)
            }
            
        except Exception as e:
            logger.error(f"Error calculating correlation: {str(e)}")
            return {"success": False, "error": str(e)}
  • MCP tool registration using @mcp.tool decorator. This wrapper function defines the tool interface and delegates to the analytics implementation.
    async def get_correlation_matrix(
        session_id: str,
        method: str = "pearson",
        columns: Optional[List[str]] = None,
        min_correlation: Optional[float] = None,
        ctx: Context = None
    ) -> Dict[str, Any]:
        """Calculate correlation matrix for numeric columns."""
        return await _get_correlation_matrix(session_id, method, columns, min_correlation, ctx)
  • Import of the get_correlation_matrix implementation from analytics module, aliased for use in the server tool wrappers.
    from .tools.analytics import (
        get_statistics as _get_statistics,
        get_column_statistics as _get_column_statistics,
        get_correlation_matrix as _get_correlation_matrix,
        group_by_aggregate as _group_by_aggregate,
        get_value_counts as _get_value_counts,
        detect_outliers as _detect_outliers,
        profile_data as _profile_data
    )
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 but offers minimal information. It states what the tool does but doesn't describe what happens during execution (e.g., whether it modifies data, requires specific data states, has performance implications, or returns specific formats). For a calculation tool with 4 parameters, 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 perfectly concise at just 6 words, front-loading the core purpose without unnecessary elaboration. Every word earns its place, and there's no wasted text or redundant information in this single, clear sentence.

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 (4 parameters, calculation operation) and the presence of an output schema (which handles return values), the description is minimally adequate but incomplete. It covers the basic purpose but lacks parameter explanations, usage context, and behavioral details that would be helpful despite the output schema handling return format documentation.

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 4 parameters, the description doesn't compensate by explaining any parameter meanings. It mentions 'numeric columns' which relates to the 'columns' parameter, but doesn't clarify 'session_id', 'method', or 'min_correlation'. The description adds minimal value beyond what's implied by the tool name, failing to address the schema coverage gap.

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 a specific verb ('calculate') and resource ('correlation matrix for numeric columns'), making it immediately understandable. However, it doesn't explicitly differentiate from sibling tools like 'get_column_statistics' or 'profile_data' that might also analyze data relationships, which prevents a perfect score.

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. With siblings like 'get_column_statistics', 'profile_data', and 'detect_outliers' that might offer overlapping statistical analysis, there's no indication of when this specific correlation matrix calculation is appropriate or what distinguishes it from other data analysis tools.

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/santoshray02/csv-editor'

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